import Te 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/formatErrorMessage.js";
import * as r from "react";
import * as U from "react-dom";
import { useTimeout as K } 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 { ownerDocument as _ } 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/owner.js";
import { useStableCallback as I } 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 { useIsoLayoutEffect as be } 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 { EMPTY_OBJECT as Me } 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 { FloatingTreeStore as Oe } from "../../floating-ui-react/components/FloatingTreeStore.js";
import { useMenuRootContext as V } from "../root/MenuRootContext.js";
import { pressableTriggerOpenStateMapping as L } from "../../utils/popupStateMapping.js";
import { useRenderElement as Re } from "../../utils/useRenderElement.js";
import { useButton as xe } from "../../use-button/useButton.js";
import { getPseudoElementBounds as ye } from "../../utils/getPseudoElementBounds.js";
import { CompositeItem as Ee } from "../../composite/item/CompositeItem.js";
import { useCompositeRootContext as he } from "../../composite/root/CompositeRootContext.js";
import { findRootOwnerId as ve } from "../utils/findRootOwnerId.js";
import { useBaseUiId as Fe } from "../../utils/useBaseUiId.js";
import { useMixedToggleClickHandler as Ie } from "../../utils/useMixedToggleClickHandler.js";
import { useContextMenuRootContext as Ce } from "../../context-menu/root/ContextMenuRootContext.js";
import { useMenubarContext as Pe } from "../../menubar/MenubarContext.js";
import { PATIENT_CLICK_THRESHOLD as we } from "../../utils/constants.js";
import { FocusGuard as G } from "../../utils/FocusGuard.js";
import { createChangeEventDetails as Y } from "../../utils/createBaseUIEventDetails.js";
import { jsx as T, jsxs as Se } from "react/jsx-runtime";
import { useFloatingTree as ke, useFloatingNodeId as Ne, useFloatingParentNodeId as De } from "../../floating-ui-react/components/FloatingTree.js";
import { useTriggerDataForwarding as Be } from "../../utils/popups/popupStoreUtils.js";
import { useHoverReferenceInteraction as He } from "../../floating-ui-react/hooks/useHoverReferenceInteraction.js";
import { safePolygon as Ae } from "../../floating-ui-react/safePolygon.js";
import { useClick as Ue } from "../../floating-ui-react/hooks/useClick.js";
import { useFocus as _e } from "../../floating-ui-react/hooks/useFocus.js";
import { useInteractions as Le } from "../../floating-ui-react/hooks/useInteractions.js";
import { getTabbableBeforeElement as Ge, isOutsideEvent as Ye, getTabbableAfterElement as je, getNextTabbable as Ke } from "../../floating-ui-react/utils/tabbable.js";
import { triggerHover as Ve, cancelOpen as Xe, focusOut as j } from "../../utils/reason-parts.js";
import { contains as C } from "../../floating-ui-react/utils/element.js";
const R = 2, $e = /* @__PURE__ */ r.forwardRef(function(f, i) {
  const {
    render: b,
    className: d,
    disabled: X = !1,
    nativeButton: $ = !0,
    id: J,
    openOnHover: q,
    delay: z = 100,
    closeDelay: P = 0,
    handle: x,
    payload: Q,
    ...W
  } = f, y = V(!0), e = (x == null ? void 0 : x.store) ?? (y == null ? void 0 : y.store);
  if (!e)
    throw new Error(process.env.NODE_ENV !== "production" ? "Base UI: <Menu.Trigger> must be either used within a <Menu.Root> component or provided with a handle." : Te(85));
  const l = Fe(J), Z = e.useState("isTriggerActive", l), E = e.useState("floatingRootContext"), n = e.useState("isOpenedByTrigger", l), M = r.useRef(null), s = qe(), h = he(!0), w = ke(), O = r.useMemo(() => w ?? new Oe(), [w]), ee = Ne(O), te = De(), {
    registerTrigger: oe,
    isMountedByThisTrigger: S
  } = Be(l, M, e, {
    payload: Q,
    closeDelay: P,
    parent: s,
    floatingTreeRoot: O,
    floatingNodeId: ee,
    floatingParentNodeId: te,
    keyboardEventRelay: h == null ? void 0 : h.relayKeyboardEvent
  }), u = s.type === "menubar", re = e.useState("disabled"), m = X || re || u && s.context.disabled, {
    getButtonProps: ne,
    buttonRef: se
  } = xe({
    disabled: m,
    native: $
  });
  r.useEffect(() => {
    !n && s.type === void 0 && (e.context.allowMouseUpTriggerRef.current = !1);
  }, [e, n, s.type]);
  const g = r.useRef(null), k = K(), v = I((t) => {
    if (!g.current)
      return;
    k.clear(), e.context.allowMouseUpTriggerRef.current = !1;
    const o = t.target;
    if (C(g.current, o) || C(e.select("positionerElement"), o) || o === g.current || o != null && ve(o) === e.select("rootId"))
      return;
    const p = ye(g.current);
    t.clientX >= p.left - R && t.clientX <= p.right + R && t.clientY >= p.top - R && t.clientY <= p.bottom + R || O.events.emit("close", {
      domEvent: t,
      reason: Xe
    });
  });
  r.useEffect(() => {
    n && e.select("lastOpenChangeReason") === Ve && _(g.current).addEventListener("mouseup", v, {
      once: !0
    });
  }, [n, v, e]);
  const F = u && s.context.hasSubmenuOpen, ie = He(E, {
    enabled: (q ?? F) && !m && s.type !== "context-menu" && (!u || F && !S),
    handleClose: Ae({
      blockPointerEvents: !u
    }),
    mouseOnly: !0,
    move: !1,
    restMs: s.type === void 0 ? z : void 0,
    delay: {
      close: P
    },
    triggerElementRef: M,
    externalTree: O,
    isActiveTrigger: Z
  }), ue = Je(n, e.select("lastOpenChangeReason")), ce = Ue(E, {
    enabled: !m && s.type !== "context-menu",
    event: n && u ? "click" : "mousedown",
    toggle: !0,
    ignoreMouse: !1,
    stickIfOpen: s.type === void 0 ? ue : !1
  }), ae = _e(E, {
    enabled: !m && F
  }), fe = Ie({
    open: n,
    enabled: u,
    mouseDownAction: "open"
  }), le = Le([ce, ae]), N = r.useMemo(() => ({
    disabled: m,
    open: n
  }), [m, n]), pe = e.useState("triggerProps", S), D = [g, i, se, oe, M], B = [le.getReferenceProps(), ie ?? Me, pe, {
    "aria-haspopup": "menu",
    id: l,
    onMouseDown: (t) => {
      if (e.select("open"))
        return;
      k.start(200, () => {
        e.context.allowMouseUpTriggerRef.current = !0;
      }), _(t.currentTarget).addEventListener("mouseup", v, {
        once: !0
      });
    }
  }, u ? {
    role: "menuitem"
  } : {}, fe, W, ne], H = r.useRef(null), me = I((t) => {
    U.flushSync(() => {
      e.setOpen(!1, Y(j, t.nativeEvent, t.currentTarget));
    });
    const o = Ge(H.current);
    o == null || o.focus();
  }), ge = I((t) => {
    var p;
    const o = e.select("positionerElement");
    if (o && Ye(t, o))
      (p = e.context.beforeContentFocusGuardRef.current) == null || p.focus();
    else {
      U.flushSync(() => {
        e.setOpen(!1, Y(j, t.nativeEvent, t.currentTarget));
      });
      let c = je(e.context.triggerFocusTargetRef.current || M.current);
      for (; c !== null && C(o, c); ) {
        const de = c;
        if (c = Ke(c), c === de)
          break;
      }
      c == null || c.focus();
    }
  }), A = Re("button", f, {
    enabled: !u,
    stateAttributesMapping: L,
    state: N,
    ref: D,
    props: B
  });
  return u ? /* @__PURE__ */ T(Ee, {
    tag: "button",
    render: b,
    className: d,
    state: N,
    refs: D,
    props: B,
    stateAttributesMapping: L
  }) : n ? /* @__PURE__ */ Se(r.Fragment, {
    children: [/* @__PURE__ */ T(G, {
      ref: H,
      onFocus: me
    }, `${l}-pre-focus-guard`), /* @__PURE__ */ T(r.Fragment, {
      children: A
    }, l), /* @__PURE__ */ T(G, {
      ref: e.context.triggerFocusTargetRef,
      onFocus: ge
    }, `${l}-post-focus-guard`)]
  }) : /* @__PURE__ */ T(r.Fragment, {
    children: A
  }, l);
});
process.env.NODE_ENV !== "production" && ($e.displayName = "MenuTrigger");
function Je(a, f) {
  const i = K(), [b, d] = r.useState(!1);
  return be(() => {
    a && f === "trigger-hover" ? (d(!0), i.start(we, () => {
      d(!1);
    })) : a || (i.clear(), d(!1));
  }, [a, f, i]), b;
}
function qe() {
  const a = Ce(!0), f = V(!0), i = Pe();
  return r.useMemo(() => i ? {
    type: "menubar",
    context: i
  } : a && !f ? {
    type: "context-menu",
    context: a
  } : {
    type: void 0
  }, [a, f, i]);
}
export {
  $e as MenuTrigger
};
