import { jsx as _jsx } from "react/jsx-runtime";
import React from "react";
const PortalContainerContext = React.createContext(undefined);
function findOrCreatePortalContainer(root, id = "plugin-portal-container") {
    // look only at direct children
    for (const child of Array.from(root.children)) {
        if (child instanceof HTMLElement && child.id === id) {
            return child;
        }
    }
    // not found → create
    const container = document.createElement("div");
    container.id = id;
    root.appendChild(container);
    return container;
}
export function PortalContainerProvider({ children, id = "plugin-portal-container", }) {
    const ref = React.useRef(null);
    const [container, setContainer] = React.useState(undefined);
    React.useEffect(() => {
        if (ref.current) {
            const root = ref.current.getRootNode();
            if (root instanceof ShadowRoot || root instanceof Document) {
                const container = findOrCreatePortalContainer(root, id);
                setContainer(container);
            }
            else {
                setContainer(null);
            }
        }
    }, [id]);
    // If container not discovered yet → render hidden marker only
    if (container === undefined) {
        return _jsx("div", { ref: ref, style: { display: "none" } });
    }
    // Once container is resolved (null or HTMLElement) → provide it
    return (_jsx(PortalContainerContext.Provider, { value: container || undefined, children: children }));
}
export function usePortalContainer() {
    return React.useContext(PortalContainerContext);
}
//# sourceMappingURL=PortalContainerProvider.js.map