import { useSyntheticBlurEvent as W, setEventTarget as v, createSyntheticEvent as x } from "./utils.js";
import { useRef as E, useCallback as b } from "react";
import { nodeContains as i, getActiveElement as T, getEventTarget as B } from "../../../../../@react-aria_utils@3.33.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@react-aria/utils/dist/DOMFunctions.js";
import { getOwnerDocument as G } from "../../../../../@react-aria_utils@3.33.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@react-aria/utils/dist/domHelpers.js";
import { useGlobalListeners as L } from "../../../../../@react-aria_utils@3.33.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@react-aria/utils/dist/useGlobalListeners.js";
function S(h) {
  let { isDisabled: g, onBlurWithin: o, onFocusWithin: a, onFocusWithinChange: t } = h, r = E({
    isFocusWithin: !1
  }), { addGlobalListener: s, removeAllGlobalListeners: u } = L(), n = b((e) => {
    i(e.currentTarget, e.target) && r.current.isFocusWithin && !i(e.currentTarget, e.relatedTarget) && (r.current.isFocusWithin = !1, u(), o && o(e), t && t(!1));
  }, [
    o,
    t,
    r,
    u
  ]), f = W(n), p = b((e) => {
    if (!i(e.currentTarget, e.target)) return;
    const c = G(e.target), m = T(c);
    if (!r.current.isFocusWithin && m === B(e.nativeEvent)) {
      a && a(e), t && t(!0), r.current.isFocusWithin = !0, f(e);
      let l = e.currentTarget;
      s(c, "focus", (d) => {
        if (r.current.isFocusWithin && !i(l, d.target)) {
          let $ = new c.defaultView.FocusEvent("blur", {
            relatedTarget: d.target
          });
          v($, l);
          let F = x($);
          n(F);
        }
      }, {
        capture: !0
      });
    }
  }, [
    a,
    t,
    f,
    s,
    n
  ]);
  return g ? {
    focusWithinProps: {
      // These cannot be null, that would conflict in mergeProps
      onFocus: void 0,
      onBlur: void 0
    }
  } : {
    focusWithinProps: {
      onFocus: p,
      onBlur: n
    }
  };
}
export {
  S as useFocusWithin
};
