import * as r from "react";
import * as Ae from "react-dom";
import { useTimeout as X } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useTimeout.js";
import { useStableCallback as He } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useStableCallback.js";
import { useId as Ue } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useId.js";
import { useIsoLayoutEffect as Z } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useIsoLayoutEffect.js";
import { useAnimationFrame as Ke } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useAnimationFrame.js";
import { useScrollLock as Le } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useScrollLock.js";
import { EMPTY_ARRAY as _e } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/empty.js";
import { useMenuRootContext as Ve, MenuRootContext as Ye } from "./MenuRootContext.js";
import { useMenubarContext as qe } from "../../menubar/MenubarContext.js";
import { TYPEAHEAD_RESET_MS as De } from "../../utils/constants.js";
import { useDirection as je } from "../../direction-provider/DirectionContext.js";
import { useOpenInteractionType as Be } from "../../utils/useOpenInteractionType.js";
import { createChangeEventDetails as $e } from "../../utils/createBaseUIEventDetails.js";
import { useContextMenuRootContext as ze } from "../../context-menu/root/ContextMenuRootContext.js";
import { MenuStore as Ge } from "../store/MenuStore.js";
import { useMenuSubmenuRootContext as Je } from "../submenu-root/MenuSubmenuRootContext.js";
import { jsx as ee } from "react/jsx-runtime";
import { useFloatingNodeId as Qe, useFloatingParentNodeId as We, FloatingTree as Xe } from "../../floating-ui-react/components/FloatingTree.js";
import { useImplicitActiveTrigger as Ze, useOpenStateTransitions as et } from "../../utils/popups/popupStoreUtils.js";
import { useSyncedFloatingRootContext as tt } from "../../floating-ui-react/hooks/useSyncedFloatingRootContext.js";
import { useDismiss as ot } from "../../floating-ui-react/hooks/useDismiss.js";
import { useRole as nt } from "../../floating-ui-react/hooks/useRole.js";
import { useListNavigation as rt } from "../../floating-ui-react/hooks/useListNavigation.js";
import { useTypeahead as st } from "../../floating-ui-react/hooks/useTypeahead.js";
import { useInteractions as it } from "../../floating-ui-react/hooks/useInteractions.js";
import { imperativeAction as ut, triggerFocus as te, triggerPress as at, itemPress as ct, triggerHover as k, focusOut as lt, listNavigation as pt, siblingOpen as dt, escapeKey as mt } from "../../utils/reason-parts.js";
import { mergeProps as oe } from "../../merge-props/mergeProps.js";
function Yt(ne) {
  const {
    children: T,
    open: re,
    onOpenChange: b,
    onOpenChangeComplete: se,
    defaultOpen: ie = !1,
    disabled: ue = !1,
    modal: w,
    loopFocus: ae = !0,
    orientation: ce = "vertical",
    actionsRef: le,
    closeParentOnEsc: pe = !1,
    handle: P,
    triggerId: de,
    defaultTriggerId: me = null,
    highlightItemOnHover: fe = !0
  } = ne, d = ze(!0), c = Ve(!0), x = qe(), F = Je(), h = r.useMemo(() => F && c ? {
    type: "menu",
    store: c.store
  } : x ? {
    type: "menubar",
    context: x
  } : d && !c ? {
    type: "context-menu",
    context: d
  } : {
    type: void 0
  }, [d, c, x, F]), e = Ge.useStore(P == null ? void 0 : P.store, {
    parent: h
  }), y = e.useState("floatingTreeRoot"), R = Qe(y), v = We();
  Z(() => {
    d && !c ? e.update({
      parent: {
        type: "context-menu",
        context: d
      },
      floatingNodeId: R,
      floatingParentNodeId: v
    }) : c && e.update({
      floatingNodeId: R,
      floatingParentNodeId: v
    });
  }, [d, c, R, v, e]), e.useControlledProp("open", re, ie), e.useControlledProp("activeTriggerId", de, me), e.useContextCallback("onOpenChangeComplete", se);
  const i = e.useState("open"), A = e.useState("activeTriggerElement"), M = e.useState("positionerElement"), H = e.useState("hoverEnabled"), ge = e.useState("modal"), U = e.useState("disabled"), K = e.useState("lastOpenChangeReason"), n = e.useState("parent"), f = e.useState("activeIndex"), ye = e.useState("payload"), Ce = e.useState("floatingParentNodeId"), E = r.useRef(null), S = Ce != null;
  let u;
  process.env.NODE_ENV !== "production" && n.type !== void 0 && w !== void 0 && console.warn("Base UI: The `modal` prop is not supported on nested menus. It will be ignored."), e.useSyncedValues({
    disabled: ue,
    modal: n.type === void 0 ? w : void 0,
    rootId: Ue()
  });
  const {
    openMethod: Ie,
    triggerProps: C,
    reset: Te
  } = Be(i);
  Ze(e);
  const {
    forceUnmount: L
  } = et(i, e, () => {
    e.update({
      allowMouseEnter: !1,
      stickIfOpen: !0
    }), Te();
  }), O = r.useRef(n.type !== "context-menu"), N = X();
  r.useEffect(() => {
    if (i || (E.current = null), n.type === "context-menu") {
      if (!i) {
        N.clear(), O.current = !1;
        return;
      }
      N.start(500, () => {
        O.current = !0;
      });
    }
  }, [N, i, n.type]), Le(i && ge && K !== k && Ie !== "touch", M), Z(() => {
    !i && !H && e.set("hoverEnabled", !0);
  }, [i, H, e]);
  const I = r.useRef(!0), _ = X(), g = He((t, o) => {
    const s = o.reason;
    if (i === t && o.trigger === A && K === s || (o.preventUnmountOnClose = () => {
      e.set("preventUnmountingOnClose", !0);
    }, !t && o.trigger == null && (o.trigger = A ?? void 0), b == null || b(t, o), o.isCanceled))
      return;
    const we = {
      open: t,
      nativeEvent: o.event,
      reason: o.reason,
      nested: S
    };
    u == null || u.emit("openchange", we);
    const a = o.event;
    if (t === !1 && (a == null ? void 0 : a.type) === "click" && a.pointerType === "touch" && !I.current)
      return;
    if (!t && f !== null) {
      const p = e.context.itemDomElements.current[f];
      queueMicrotask(() => {
        p == null || p.setAttribute("tabindex", "-1");
      });
    }
    t && s === te ? (I.current = !1, _.start(300, () => {
      I.current = !0;
    })) : (I.current = !0, _.clear());
    const G = (s === at || s === ct) && a.detail === 0 && (a == null ? void 0 : a.isTrusted), Fe = !t && (s === mt || s == null);
    function J() {
      var W;
      const p = {
        open: t,
        openChangeReason: s
      };
      E.current = o.event ?? null;
      const Q = ((W = o.trigger) == null ? void 0 : W.id) ?? null;
      (Q || t) && (p.activeTriggerId = Q, p.activeTriggerElement = o.trigger ?? null), e.update(p);
    }
    s === k ? Ae.flushSync(J) : J(), n.type === "menubar" && (s === te || s === lt || s === k || s === pt || s === dt) ? e.set("instantType", "group") : G || Fe ? e.set("instantType", G ? "click" : "dismiss") : e.set("instantType", void 0);
  }), V = r.useCallback((t) => {
    const o = $e(t);
    return o.preventUnmountOnClose = () => {
      e.set("preventUnmountingOnClose", !0);
    }, o;
  }, [e]), Y = r.useCallback(() => {
    e.setOpen(!1, V(ut));
  }, [e, V]);
  r.useImperativeHandle(le, () => ({
    unmount: L,
    close: Y
  }), [L, Y]);
  let l;
  n.type === "context-menu" && (l = n.context), r.useImperativeHandle(l == null ? void 0 : l.positionerRef, () => M, [M]), r.useImperativeHandle(l == null ? void 0 : l.actionsRef, () => ({
    setOpen: g
  }), [g]);
  const m = tt({
    popupStore: e,
    onOpenChange: g
  });
  u = m.context.events, r.useEffect(() => {
    const t = ({
      open: o,
      eventDetails: s
    }) => g(o, s);
    return u.on("setOpen", t), () => {
      u == null || u.off("setOpen", t);
    };
  }, [u, g]);
  const be = ot(m, {
    enabled: !U,
    bubbles: {
      escapeKey: pe && n.type === "menu"
    },
    outsidePress() {
      var t;
      return n.type !== "context-menu" || ((t = E.current) == null ? void 0 : t.type) === "contextmenu" ? !0 : O.current;
    },
    externalTree: S ? y : void 0
  }), Pe = nt(m, {
    role: "menu"
  }), xe = je(), he = r.useCallback((t) => {
    e.select("activeIndex") !== t && e.set("activeIndex", t);
  }, [e]), Re = rt(m, {
    enabled: !U,
    listRef: e.context.itemDomElements,
    activeIndex: f,
    nested: n.type !== void 0,
    loopFocus: ae,
    orientation: ce,
    parentOrientation: n.type === "menubar" ? n.context.orientation : void 0,
    rtl: xe === "rtl",
    disabledIndices: _e,
    onNavigate: he,
    openOnArrowKeyDown: n.type !== "context-menu",
    externalTree: S ? y : void 0,
    focusItemOnHover: fe
  }), ve = r.useCallback((t) => {
    e.context.typingRef.current = t;
  }, [e]), Me = st(m, {
    listRef: e.context.itemLabels,
    activeIndex: f,
    resetMs: De,
    onMatch: (t) => {
      i && t !== f && e.set("activeIndex", t);
    },
    onTypingChange: ve
  }), {
    getReferenceProps: q,
    getFloatingProps: D,
    getItemProps: j,
    getTriggerProps: B
  } = it([be, Pe, Re, Me]), Ee = r.useMemo(() => {
    const t = oe(q(), {
      onMouseEnter() {
        e.set("hoverEnabled", !0);
      },
      onMouseMove() {
        e.set("allowMouseEnter", !0);
      }
    }, C);
    return delete t.role, t;
  }, [q, e, C]), Se = r.useMemo(() => {
    const t = B();
    if (!t)
      return t;
    const o = oe(t, C);
    return delete o.role, delete o["aria-controls"], o;
  }, [B, C]), $ = Ke(), Oe = r.useMemo(() => D({
    onMouseEnter() {
      n.type === "menu" && $.request(() => e.set("hoverEnabled", !1));
    },
    onMouseMove() {
      e.set("allowMouseEnter", !0);
    },
    onClick() {
      e.select("hoverEnabled") && e.set("hoverEnabled", !1);
    },
    onKeyDown(t) {
      const o = e.select("keyboardEventRelay");
      o && !t.isPropagationStopped() && o(t);
    }
  }), [D, n.type, $, e]), Ne = r.useMemo(() => j(), [j]);
  e.useSyncedValues({
    floatingRootContext: m,
    activeTriggerProps: Ee,
    inactiveTriggerProps: Se,
    popupProps: Oe,
    itemProps: Ne
  });
  const ke = r.useMemo(() => ({
    store: e,
    parent: h
  }), [e, h]), z = /* @__PURE__ */ ee(Ye.Provider, {
    value: ke,
    children: typeof T == "function" ? T({
      payload: ye
    }) : T
  });
  return n.type === void 0 || n.type === "context-menu" ? /* @__PURE__ */ ee(Xe, {
    externalTree: y,
    children: z
  }) : z;
}
export {
  Yt as MenuRoot
};
