import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { PopupController } from "./PopupController";
const PopupContext = createContext(undefined);
export function usePopupController() {
    const ctrl = useContext(PopupContext);
    if (!ctrl)
        throw new Error("usePopupController must be used inside a Popup component");
    return ctrl;
}
export function DOMPopup({ ctrlRef, id, constraints, isOpen, children, className, onClose, zIndex, position, ...props }) {
    const popupRef = useRef(null);
    const [ctrl, setCtrl] = useState();
    useEffect(() => {
        if (!props.anchor)
            throw new Error("Anchor element is required");
        const _ctrl = new PopupController({
            ...props,
            onClose
        });
        setCtrl(_ctrl);
        return () => {
            _ctrl.tryClose();
        };
    }, []);
    useEffect(() => {
        if (ctrlRef) {
            ctrlRef.current = ctrl;
        }
    }, [ctrl]);
    // effect to open / close the popup
    useEffect(() => {
        if (ctrl && popupRef.current) {
            if (ctrl.isOpen !== isOpen) {
                if (isOpen) {
                    ctrl.open(popupRef.current, constraints);
                }
                else {
                    ctrl.close();
                }
            }
        }
        else if (ctrl?.isOpen && !isOpen) {
            // close the popup - happens when isOpen becomes false but the ctrl is still open
            // and the popupRef was destroyed by the isOpen && below
            ctrl.close();
        }
    }, [isOpen, ctrl, popupRef.current]);
    return (_jsx(PopupContext.Provider, { value: ctrl, children: isOpen && createPortal(_jsx("div", { id: id, style: {
                //display: isOpen ? 'block' : 'none',
                visibility: 'hidden',
                position: position || 'absolute',
                zIndex: zIndex || 100,
            }, ref: popupRef, className: className, children: children }), document.body) }));
}
export function Popup({ anchor, root, children, ...others }) {
    return anchor.current && (!root || root.current) ? (_jsx(DOMPopup, { anchor: anchor.current, root: root?.current || undefined, ...others, children: children })) : null;
}
//# sourceMappingURL=Popup.js.map