import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { Fragment as external_react_Fragment } from "react";
import { Observer, observable } from "@tachybase/schema";
import { createPortal } from "react-dom";
import { render as external_render_mjs_render, unmount as external_render_mjs_unmount } from "./render.mjs";
const PortalMap = observable(new Map());
const createPortalProvider = (id)=>{
    const Portal = (props)=>{
        if (props.id && !PortalMap.has(props.id)) PortalMap.set(props.id, null);
        return /*#__PURE__*/ jsxs(external_react_Fragment, {
            children: [
                props.children,
                /*#__PURE__*/ jsx(Observer, {
                    children: ()=>{
                        if (!props.id) return /*#__PURE__*/ jsx(Fragment, {});
                        const portal = PortalMap.get(props.id);
                        if (portal) return /*#__PURE__*/ createPortal(portal, document.body);
                        return /*#__PURE__*/ jsx(Fragment, {});
                    }
                })
            ]
        });
    };
    Portal.defaultProps = {
        id
    };
    return Portal;
};
function createPortalRoot(host, id) {
    function render(renderer) {
        if (PortalMap.has(id)) PortalMap.set(id, null == renderer ? void 0 : renderer());
        else if (host) external_render_mjs_render(/*#__PURE__*/ jsx(external_react_Fragment, {
            children: null == renderer ? void 0 : renderer()
        }), host);
    }
    function unmount() {
        if (PortalMap.has(id)) PortalMap.set(id, null);
        if (host) {
            const unmountResult = external_render_mjs_unmount(host);
            if (unmountResult && host.parentNode) {
                var _host_parentNode;
                null == (_host_parentNode = host.parentNode) || _host_parentNode.removeChild(host);
            }
        }
    }
    return {
        render,
        unmount
    };
}
export { createPortalProvider, createPortalRoot };
