import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
import ReactDOM from "react-dom";
import { forwardRef, useMemo, } from "react";
import { useEffect } from "react";
import { useState } from "react";
import Styles from "./Portal.module.scss";
/**
 * A react portal implementation with current page fallback
 *
 * Usage
 * <PortalReceiver name="receive"/>
 *
 * <Portal to="receive">CHILD</Portal>
 *
 * This component renders its children inside a different part of the DOM tree
 * than where it was originally placed, allowing content to appear outside its
 * parent containers (useful for modals, tooltips, and dropdowns).
 **/
export default function Portal({ to, children, }) {
    const [target, setTarget] = useState();
    useEffect(() => {
        const els = document.querySelectorAll(`[data-one-portal="${to}"]`);
        let latestEl;
        els.forEach((el) => {
            latestEl =
                Number(el.getAttribute("data-timestamp")) >
                    Number(latestEl?.timestamp || 0)
                    ? el
                    : latestEl;
        });
        setTarget(latestEl || null);
    }, []);
    return target === undefined ? null : (_jsx(_Fragment, { children: target === null ? children : ReactDOM.createPortal(children, target) }));
}
function _PortalReceiver({ name, className = "", ...props }, _ref) {
    const timestamp = useMemo(() => Date.now(), []);
    return (_jsx("div", { className: `${Styles.portal} ${className}`, "data-one-portal": name, ref: _ref, "data-timestamp": timestamp, ...props }));
}
export const PortalReceiver = forwardRef(_PortalReceiver);
//# sourceMappingURL=Portal.js.map