/* eslint-disable jsx-a11y/iframe-has-title */
import { useRef, useEffect } from 'react';
const Iframe = function Iframe(props) {
  const {
    code,
    active,
    className
  } = props;
  const ref = useRef();
  useEffect(() => {
    const iframe = ref.current;
    const html = `
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
      </head>
      <body>
        <div>${active ? code : ''}</div>
      </body>
    `;
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write(html);
    iframe.contentWindow.document.close();
    const dom = iframe.contentWindow.document.body;
    const observer = new window.ResizeObserver(() => {
      iframe.style.height = `${dom.offsetHeight}px`;
    });
    observer.observe(dom);
    return () => observer.disconnect();
  }, [code, active]);
  return <div className={className}>
      <iframe ref={ref} frameBorder="0" marginWidth="0px" marginHeight="0px" style={{
      height: 0
    }} />
    </div>;
};
Iframe.nodeToProps = (node, context) => ({
  code: node.data.code,
  active: context.active
});
export default Iframe;