import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2007-2026 GoodData Corporation
import { Fragment, useCallback, useMemo, useRef, useState } from "react";
import { RenderChildrenInPortal } from "../utils/RenderChildrenInPortal.js";
import { PositionedMenuContent } from "./PositionedMenuContent.js";
function Wrapper({ children }) {
    return _jsx("div", { className: "gd-menuPosition-wrapper", children: children });
}
function PortalIfTopLevelMenu({ topLevelMenu, children, portalTarget, }) {
    return topLevelMenu ? (_jsx(RenderChildrenInPortal, { targetElement: portalTarget, children: children })) : (_jsx(Fragment, { children: children }));
}
export function MenuPosition({ portalTarget, topLevelMenu, contentWrapper: ContentWrapper = Fragment, toggler, opened, alignment, spacing, offset, togglerWrapperClassName, children, }) {
    const [togglerElInitialized, setTogglerElInitialized] = useState(false);
    const togglerEl = useRef(null);
    // React Measure is not used because it cannot detect the left/top coordinate
    // changes of absolute positioned blocks. This caused problems where left/top
    // positions from React Measure were outdated. To solve this we do the
    // measurements manually in PositionedMenuContent at the correct time.
    const setTogglerEl = useCallback((el) => {
        togglerEl.current = el;
        setTogglerElInitialized(true);
    }, []);
    // Top level menu uses React portals to be rendered in body element (or
    // any element specified in targetElement prop). Any submenus are rendered
    // inside of previous menu, so they do not need any portals.
    const MaybeWrapper = useMemo(() => (topLevelMenu ? Fragment : Wrapper), [topLevelMenu]);
    return (_jsxs(MaybeWrapper, { children: [
            _jsx("div", { className: topLevelMenu ? togglerWrapperClassName : undefined, ref: setTogglerEl, children: toggler }), _jsx(PortalIfTopLevelMenu, { portalTarget: portalTarget, topLevelMenu: topLevelMenu, children: opened && togglerElInitialized ? (_jsx(ContentWrapper, { children: _jsx(PositionedMenuContent, { alignment: alignment, spacing: spacing, offset: offset, topLevelMenu: topLevelMenu, togglerEl: togglerEl.current, children: children }) })) : null })
        ] }));
}
