import { useEffect } from 'react';
import PropTypes from 'prop-types';
import cx from "../../../utils/css/cx.js";
import classes from './styles.module.scss';
const cls = cx.merge(classes);
const DWIframe = ({
  id
}) => {
  if (!id) return null;
  return <iframe title={`Datawrapper chart ${id}`} id={`datawrapper-chart-${id}`} src={`https://datawrapper.dwcdn.net/${id}/1/`} scrolling="no" frameBorder="0" style={{
    width: 0,
    minWidth: '100%',
    border: 'none'
  }} data-external="1" />;
};
const Datawrapper = function Datawrapper(props) {
  const {
    datawrapperId,
    maxWidth
  } = props;
  useEffect(() => {
    const handler = event => {
      const dataWrapperHeight = event.data['datawrapper-height'];

      // Check if the message contains a 'datawrapper-height' property
      if (dataWrapperHeight !== undefined) {
        // Select all iframe elements on the page
        const iframes = Array.from(window.document.querySelectorAll('iframe'));
        Object.keys(dataWrapperHeight).forEach(key => {
          const newHeight = `${dataWrapperHeight[key]}px`;
          iframes.forEach(frame => {
            if (frame.contentWindow === event.source) {
              frame.style.height = newHeight; // eslint-disable-line
            }
          });
        });
      }
    };

    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);
  return <div className={cls('datawrapper')} style={{
    maxWidth
  }}>
      <DWIframe id={datawrapperId} />
    </div>;
};
Datawrapper.defaultProps = {
  datawrapperId: undefined,
  maxWidth: undefined
};
Datawrapper.propTypes = {
  /**
   * The Datawrapper viz ID
   */
  datawrapperId: PropTypes.string,
  /**
   * A value to set as the inline max-width style for the viz's container.
   */
  maxWidth: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};
export default Datawrapper;