import { useRef as R, useCallback as u, useEffect as v } from "../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { popoverUtil as a } from "../../components/internal/Popover/utils/popoverUtil.js";
import L from "../useReflex.js";
const p = /* @__PURE__ */ Symbol("__control.Elem.");
var w = /* @__PURE__ */ ((r) => (r.POPOVER = "POPOVER", r.DEFAULT = "DEFAULT", r))(w || {});
const O = (r) => r.stopImmediatePropagation(), T = (r, s, c, f) => {
  const o = R(null), i = R(!1), E = u(
    (n) => {
      if (!(o && o.current)) return;
      const t = n.composedPath();
      if (f === "POPOVER")
        a.closePopoversOutsideOfClick(t);
      else {
        let d = 0, P = !1, e = t[d];
        for (; (e instanceof Element || e instanceof ShadowRoot) && (e instanceof ShadowRoot && (e = e.host), !(P ||= e.isSameNode(o.current))); ) {
          if (e?.[p] instanceof Element) {
            e = e[p], t.length = 0;
            continue;
          }
          const h = t[++d];
          h ? e = h : e.parentElement ? e = e.parentElement : e.parentNode instanceof ShadowRoot ? e = e.parentNode : e = null;
        }
        s && !P && s(!0);
      }
    },
    [o, s, f]
  ), l = u((n) => {
    o.current && (i.current = n.composedPath().includes(o.current));
  }, []), m = u(
    (n) => {
      i.current ? i.current = !1 : E(n);
    },
    [E]
  );
  return v(() => {
    if (c || !o.current) return;
    const n = o.current, t = n.getRootNode();
    if (t instanceof ShadowRoot || t instanceof Document)
      return t.addEventListener("mousedown", l, !0), t.addEventListener("click", m, !0), f === "POPOVER" && a.add(n, s), () => {
        t.removeEventListener("mousedown", l, !0), t.removeEventListener("click", m, !0), f === "POPOVER" && a.remove(n);
      };
  }, [c, f, l, m, s]), L(
    u(
      (n, t) => {
        t instanceof Element && t.removeEventListener("focusout", O, !1), n instanceof Element ? c || (n.addEventListener("focusout", O, !1), o.current = n) : o.current = null;
      },
      [c]
    ),
    r
  );
};
export {
  p as CONTROL_ELEMENT_PROPERTY,
  w as ClickOutsideVariant,
  T as useClickOutside
};
