"use client";
import { composeRefs } from "../../utils/compose-refs.js";
import { EnvironmentProvider } from "../../providers/environment/environment-provider.js";
import { useSafeLayoutEffect } from "../../utils/use-safe-layout-effect.js";
import { FrameContent } from "./frame-content.js";
import { forwardRef, useEffect, useId, useState } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { createPortal } from "react-dom";
//#region src/components/frame/frame.tsx
var initialSrcDoc = `<html><head><style>*,*::before,*::after { margin: 0; padding: 0; box-sizing: border-box; }</style></head><body><div class="frame-root"></div></body></html>`;
function getMountNode(frame) {
	const doc = frame.contentWindow?.document;
	if (!doc) return null;
	return doc.body.querySelector(".frame-root") || doc.body;
}
var Frame = forwardRef((props, ref) => {
	const { children, head, onMount, onUnmount, srcDoc = initialSrcDoc, ...rest } = props;
	const [frameRef, setFrameRef] = useState(null);
	const [mountNode, setMountNode] = useState(null);
	useSafeLayoutEffect(() => {
		if (!frameRef) return;
		const doc = frameRef.contentWindow?.document;
		if (!doc) return;
		doc.open();
		doc.write(srcDoc);
		doc.close();
		setMountNode(getMountNode(frameRef));
	}, [frameRef, srcDoc]);
	useEffect(() => {
		if (!frameRef?.contentDocument) return;
		const win = frameRef.contentWindow;
		if (!win) return;
		const mountNode = getMountNode(frameRef);
		if (!mountNode) return;
		const exec = () => {
			win.requestAnimationFrame(() => {
				if (!frameRef.contentDocument?.documentElement) return;
				frameRef.style.setProperty("--width", `${mountNode.scrollWidth}px`);
				frameRef.style.setProperty("--height", `${mountNode.scrollHeight}px`);
			});
		};
		const resizeObserver = new win.ResizeObserver(exec);
		exec();
		if (frameRef.contentDocument) resizeObserver.observe(mountNode);
		return () => {
			resizeObserver.disconnect();
		};
	}, [frameRef]);
	return /* @__PURE__ */ jsx(EnvironmentProvider, {
		value: () => frameRef?.contentDocument ?? document,
		children: /* @__PURE__ */ jsxs("iframe", {
			title: `frame:${useId()}`,
			ref: composeRefs(ref, setFrameRef),
			...rest,
			children: [mountNode ? createPortal(/* @__PURE__ */ jsx(FrameContent, {
				onMount,
				onUnmount,
				children
			}), mountNode) : null, head && frameRef ? createPortal(head, frameRef.contentDocument.head) : null]
		})
	});
});
//#endregion
export { Frame };
