import * as a from "react";
import { useStableCallback as o } 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 f } 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 { useTransitionStatus as m } from "../useTransitionStatus.js";
import { useOpenChangeComplete as d } from "../useOpenChangeComplete.js";
function p(e, n) {
  const t = a.useRef(null), r = a.useRef(null);
  return a.useCallback((i) => {
    if (e !== void 0) {
      if (t.current !== null) {
        const c = t.current, g = r.current, u = n.context.triggerElements.getById(c);
        g && u === g && n.context.triggerElements.delete(c), t.current = null, r.current = null;
      }
      i !== null && (t.current = e, r.current = i, n.context.triggerElements.add(e, i));
    }
  }, [n, e]);
}
function C(e, n, t, r) {
  const i = t.useState("isMountedByTrigger", e), c = p(e, t), g = o((u) => {
    if (c(u), !u || !t.select("open"))
      return;
    const l = t.select("activeTriggerId");
    if (l === e) {
      t.update({
        activeTriggerElement: u,
        ...r
      });
      return;
    }
    l == null && t.update({
      activeTriggerId: e,
      activeTriggerElement: u,
      ...r
    });
  });
  return f(() => {
    i && t.update({
      activeTriggerElement: n.current,
      ...r
    });
  }, [i, t, n, ...Object.values(r)]), {
    registerTrigger: g,
    isMountedByThisTrigger: i
  };
}
function I(e) {
  const n = e.useState("open");
  f(() => {
    if (n && !e.select("activeTriggerId") && e.context.triggerElements.size === 1) {
      const t = e.context.triggerElements.entries().next();
      if (!t.done) {
        const [r, i] = t.value;
        e.update({
          activeTriggerId: r,
          activeTriggerElement: i
        });
      }
    }
  }, [n, e]);
}
function R(e, n, t) {
  const {
    mounted: r,
    setMounted: i,
    transitionStatus: c
  } = m(e);
  n.useSyncedValues({
    mounted: r,
    transitionStatus: c
  });
  const g = o(() => {
    var l, s;
    i(!1), n.update({
      activeTriggerId: null,
      activeTriggerElement: null,
      mounted: !1
    }), t == null || t(), (s = (l = n.context).onOpenChangeComplete) == null || s.call(l, !1);
  }), u = n.useState("preventUnmountingOnClose");
  return d({
    enabled: !u,
    open: e,
    ref: n.context.popupRef,
    onComplete() {
      e || g();
    }
  }), {
    forceUnmount: g,
    transitionStatus: c
  };
}
export {
  I as useImplicitActiveTrigger,
  R as useOpenStateTransitions,
  C as useTriggerDataForwarding,
  p as useTriggerRegistration
};
