import { useCallback as y, useRef as d } from "react";
import { isFocusableElement as b, FocusableMode as x } from "../utils/focus-management.js";
import { isMobile as E } from "../utils/platform.js";
import { useDocumentEvent as c } from "./use-document-event.js";
import { useIsTopLayer as g } from "./use-is-top-layer.js";
import { useLatestValue as w } from "./use-latest-value.js";
import { useWindowEvent as M } from "./use-window-event.js";
const f = 30;
function F(p, i, h) {
  let r = g(p, "outside-click"), m = w(h), a = y(function(e, n) {
    if (e.defaultPrevented) return;
    let t = n(e);
    if (t === null || !t.getRootNode().contains(t) || !t.isConnected) return;
    let v = (function l(o) {
      return typeof o == "function" ? l(o()) : Array.isArray(o) || o instanceof Set ? o : [o];
    })(i);
    for (let l of v) if (l !== null && (l.contains(t) || e.composed && e.composedPath().includes(l))) return;
    return !b(t, x.Loose) && t.tabIndex !== -1 && e.preventDefault(), m.current(e, t);
  }, [m, i]), u = d(null);
  c(r, "pointerdown", (e) => {
    var n, t;
    u.current = ((t = (n = e.composedPath) == null ? void 0 : n.call(e)) == null ? void 0 : t[0]) || e.target;
  }, !0), c(r, "mousedown", (e) => {
    var n, t;
    u.current = ((t = (n = e.composedPath) == null ? void 0 : n.call(e)) == null ? void 0 : t[0]) || e.target;
  }, !0), c(r, "click", (e) => {
    E() || u.current && (a(e, () => u.current), u.current = null);
  }, !0);
  let s = d({ x: 0, y: 0 });
  c(r, "touchstart", (e) => {
    s.current.x = e.touches[0].clientX, s.current.y = e.touches[0].clientY;
  }, !0), c(r, "touchend", (e) => {
    let n = { x: e.changedTouches[0].clientX, y: e.changedTouches[0].clientY };
    if (!(Math.abs(n.x - s.current.x) >= f || Math.abs(n.y - s.current.y) >= f)) return a(e, () => e.target instanceof HTMLElement ? e.target : null);
  }, !0), M(r, "blur", (e) => a(e, () => window.document.activeElement instanceof HTMLIFrameElement ? window.document.activeElement : null), !0);
}
export {
  F as useOutsideClick
};
