import React, { useCallback, useEffect, useState } from "react";
import { Iframe } from "./iframe.js";
const isSSR = typeof window === "undefined";
const HtmlSrcPath = "/html/2b2e4b_d767b483cae16e027c4ea8ac7906fbf4.html";
const IframeHtml = ({
  html,
  onHeightChange,
  iframeSandboxDomain,
  isViewer
}) => {
  const [shouldRender, setShouldRender] = useState(false);
  const [isIFrameLoaded, setIsIFrameLoaded] = useState(false);
  const [currId] = useState(Math.random().toString(36).substr(2, 9));
  const strippedUrl = iframeSandboxDomain.replace(/\/$/, "");
  const [iframeRef, setIframeRef] = useState(null);
  const observerRef = React.useRef(null);
  const handleIframeMessage = ({
    data
  }) => {
    const { type, id, height } = data;
    if (type === "htmlPlugin:heightResize" && id === currId) {
      onHeightChange(height);
      if (!window?.ricosHtmlPlugins) {
        window.ricosHtmlPlugins = /* @__PURE__ */ new Set();
      }
      window.ricosHtmlPlugins.add(id);
    }
  };
  useEffect(() => {
    setShouldRender(true);
    !isSSR && window.addEventListener("message", handleIframeMessage);
    return () => {
      !isSSR && window.removeEventListener("message", handleIframeMessage);
    };
  }, []);
  useEffect(() => {
    if (!isSSR && iframeRef) {
      observerRef.current = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          if (mutation.type === "childList") {
            mutation.removedNodes.forEach((node) => {
              if (node === iframeRef || node.contains(iframeRef)) {
                setIsIFrameLoaded(false);
              }
            });
          }
        });
      });
      observerRef.current.observe(document.body, {
        childList: true,
        subtree: true
      });
    }
    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [iframeRef]);
  const updateIframeContent = (content) => {
    iframeRef?.contentWindow?.postMessage(
      { type: "htmlPlugin:updateContent", id: currId, content },
      "*"
    );
  };
  useEffect(() => {
    if (!isIFrameLoaded) {
      return;
    }
    updateIframeContent(html);
  }, [html, isIFrameLoaded]);
  const handleIframeLoad = useCallback(() => {
    setIsIFrameLoaded(true);
  }, []);
  return shouldRender ? /* @__PURE__ */ React.createElement(
    Iframe,
    {
      style: { backgroundColor: "transparent" },
      onLoad: handleIframeLoad,
      iframeRef: setIframeRef,
      isViewer,
      src: strippedUrl + HtmlSrcPath
    }
  ) : null;
};
export {
  IframeHtml
};
//# sourceMappingURL=iframe-html.js.map
