import x, { useRef as E, useContext as D, useMemo as j, useEffect as L, useState as P, useCallback as A } from "react";
import { useLayoutEffect as F, runAfterTransition as q, focusWithoutScrolling as R, mergeProps as I, useSyncRef as z } from "../../utils/dist/module.es.js";
import { isFocusVisible as H, useFocusVisibleListener as U, useFocus as _, useFocusWithin as G, getInteractionModality as J, useKeyboard as Y } from "../../interactions/dist/module.es.js";
function W(e) {
  if (J() === "virtual") {
    let t = document.activeElement;
    q(() => {
      document.activeElement === t && document.contains(e) && R(e);
    });
  } else
    R(e);
}
function Q(e) {
  if (!(e instanceof HTMLElement) && !(e instanceof SVGElement))
    return !1;
  let { display: t, visibility: r } = e.style, o = t !== "none" && r !== "hidden" && r !== "collapse";
  if (o) {
    const { getComputedStyle: i } = e.ownerDocument.defaultView;
    let { display: n, visibility: u } = i(e);
    o = n !== "none" && u !== "hidden" && u !== "collapse";
  }
  return o;
}
function X(e, t) {
  return !e.hasAttribute("hidden") && (e.nodeName === "DETAILS" && t && t.nodeName !== "SUMMARY" ? e.hasAttribute("open") : !0);
}
function O(e, t) {
  return e.nodeName !== "#comment" && Q(e) && X(e, t) && (!e.parentElement || O(e.parentElement, e));
}
const K = /* @__PURE__ */ x.createContext(null);
let d = null;
function fe(e) {
  let { children: t, contain: r, restoreFocus: o, autoFocus: i } = e, n = E(), u = E(), a = E([]), c = D(K);
  var l;
  let s = (l = c == null ? void 0 : c.scopeRef) !== null && l !== void 0 ? l : null, b = j(
    () => d && f.getTreeNode(d) && !S(d, s) ? d : s,
    [
      s
    ]
  );
  F(() => {
    let v = n.current.nextSibling, M = [];
    for (; v && v !== u.current; )
      M.push(v), v = v.nextSibling;
    a.current = M;
  }, [
    t,
    b
  ]), f.getTreeNode(b) && !f.getTreeNode(a) && f.addTreeNode(a, b);
  let p = f.getTreeNode(a);
  p.contain = r, oe(a, o, r), re(a, r), ie(a, o, r), ne(a, i), F(() => {
    if (a)
      return () => {
        let v = f.getTreeNode(a).parent.scopeRef;
        (a === d || S(a, d)) && (!v || f.getTreeNode(v)) && (d = v), f.removeTreeNode(a);
      };
  }, [
    a,
    b
  ]);
  let T = Z(a);
  return /* @__PURE__ */ x.createElement(K.Provider, {
    value: {
      scopeRef: a,
      focusManager: T
    }
  }, /* @__PURE__ */ x.createElement("span", {
    "data-focus-scope-start": !0,
    hidden: !0,
    ref: n
  }), t, /* @__PURE__ */ x.createElement("span", {
    "data-focus-scope-end": !0,
    hidden: !0,
    ref: u
  }));
}
function Z(e) {
  return {
    focusNext(t = {}) {
      let r = e.current, { from: o, tabbable: i, wrap: n, accept: u } = t, a = o || document.activeElement, c = r[0].previousElementSibling, l = h(N(r), {
        tabbable: i,
        accept: u
      }, r);
      l.currentNode = $(a, r) ? a : c;
      let s = l.nextNode();
      return !s && n && (l.currentNode = c, s = l.nextNode()), s && m(s, !0), s;
    },
    focusPrevious(t = {}) {
      let r = e.current, { from: o, tabbable: i, wrap: n, accept: u } = t, a = o || document.activeElement, c = r[r.length - 1].nextElementSibling, l = h(N(r), {
        tabbable: i,
        accept: u
      }, r);
      l.currentNode = $(a, r) ? a : c;
      let s = l.previousNode();
      return !s && n && (l.currentNode = c, s = l.previousNode()), s && m(s, !0), s;
    },
    focusFirst(t = {}) {
      let r = e.current, { tabbable: o, accept: i } = t, n = h(N(r), {
        tabbable: o,
        accept: i
      }, r);
      n.currentNode = r[0].previousElementSibling;
      let u = n.nextNode();
      return u && m(u, !0), u;
    },
    focusLast(t = {}) {
      let r = e.current, { tabbable: o, accept: i } = t, n = h(N(r), {
        tabbable: o,
        accept: i
      }, r);
      n.currentNode = r[r.length - 1].nextElementSibling;
      let u = n.previousNode();
      return u && m(u, !0), u;
    }
  };
}
const C = [
  "input:not([disabled]):not([type=hidden])",
  "select:not([disabled])",
  "textarea:not([disabled])",
  "button:not([disabled])",
  "a[href]",
  "area[href]",
  "summary",
  "iframe",
  "object",
  "embed",
  "audio[controls]",
  "video[controls]",
  "[contenteditable]"
], ee = C.join(":not([hidden]),") + ",[tabindex]:not([disabled]):not([hidden])";
C.push('[tabindex]:not([tabindex="-1"]):not([disabled])');
const te = C.join(':not([hidden]):not([tabindex="-1"]),');
function N(e) {
  return e[0].parentElement;
}
function g(e) {
  let t = f.getTreeNode(d);
  for (; t && t.scopeRef !== e; ) {
    if (t.contain)
      return !1;
    t = t.parent;
  }
  return !0;
}
function re(e, t) {
  let r = E(), o = E(null);
  F(() => {
    let i = e.current;
    if (!t) {
      o.current && (cancelAnimationFrame(o.current), o.current = null);
      return;
    }
    let n = (c) => {
      if (c.key !== "Tab" || c.altKey || c.ctrlKey || c.metaKey || !g(e))
        return;
      let l = document.activeElement, s = e.current;
      if (!$(l, s))
        return;
      let b = h(N(s), {
        tabbable: !0
      }, s);
      b.currentNode = l;
      let p = c.shiftKey ? b.previousNode() : b.nextNode();
      p || (b.currentNode = c.shiftKey ? s[s.length - 1].nextElementSibling : s[0].previousElementSibling, p = c.shiftKey ? b.previousNode() : b.nextNode()), c.preventDefault(), p && m(p, !0);
    }, u = (c) => {
      (!d || S(d, e)) && $(c.target, e.current) ? (d = e, r.current = c.target) : g(e) && !y(c.target, e) ? r.current ? r.current.focus() : d && w(d.current) : g(e) && (r.current = c.target);
    }, a = (c) => {
      o.current = requestAnimationFrame(() => {
        g(e) && !y(document.activeElement, e) && (d = e, document.body.contains(c.target) ? (r.current = c.target, r.current.focus()) : d && w(d.current));
      });
    };
    return document.addEventListener("keydown", n, !1), document.addEventListener("focusin", u, !1), i.forEach(
      (c) => c.addEventListener("focusin", u, !1)
    ), i.forEach(
      (c) => c.addEventListener("focusout", a, !1)
    ), () => {
      document.removeEventListener("keydown", n, !1), document.removeEventListener("focusin", u, !1), i.forEach(
        (c) => c.removeEventListener("focusin", u, !1)
      ), i.forEach(
        (c) => c.removeEventListener("focusout", a, !1)
      );
    };
  }, [
    e,
    t
  ]), L(() => () => {
    o.current && cancelAnimationFrame(o.current);
  }, [
    o
  ]);
}
function B(e) {
  return y(e);
}
function $(e, t) {
  return t.some(
    (r) => r.contains(e)
  );
}
function y(e, t = null) {
  for (let { scopeRef: r } of f.traverse(f.getTreeNode(t)))
    if ($(e, r.current))
      return !0;
  return !1;
}
function be(e) {
  return y(e, d);
}
function S(e, t) {
  var r;
  let o = (r = f.getTreeNode(t)) === null || r === void 0 ? void 0 : r.parent;
  for (; o; ) {
    if (o.scopeRef === e)
      return !0;
    o = o.parent;
  }
  return !1;
}
function m(e, t = !1) {
  if (e != null && !t)
    try {
      W(e);
    } catch {
    }
  else if (e != null)
    try {
      e.focus();
    } catch {
    }
}
function w(e, t = !0) {
  let r = e[0].previousElementSibling, o = h(N(e), {
    tabbable: t
  }, e);
  o.currentNode = r;
  let i = o.nextNode();
  t && !i && (o = h(N(e), {
    tabbable: !1
  }, e), o.currentNode = r, i = o.nextNode()), m(i);
}
function ne(e, t) {
  const r = x.useRef(t);
  L(() => {
    r.current && (d = e, $(document.activeElement, d.current) || w(e.current)), r.current = !1;
  }, [
    e
  ]);
}
function oe(e, t, r) {
  F(() => {
    if (t || r)
      return;
    let o = e.current, i = (n) => {
      let u = n.target;
      $(u, e.current) ? d = e : B(u) || (d = null);
    };
    return document.addEventListener("focusin", i, !1), o.forEach(
      (n) => n.addEventListener("focusin", i, !1)
    ), () => {
      document.removeEventListener("focusin", i, !1), o.forEach(
        (n) => n.removeEventListener("focusin", i, !1)
      );
    };
  }, [
    e,
    t,
    r
  ]);
}
function ae(e) {
  let t = f.getTreeNode(d);
  for (; t && t.scopeRef !== e; ) {
    if (t.nodeToRestore)
      return !1;
    t = t.parent;
  }
  return (t == null ? void 0 : t.scopeRef) === e;
}
function ie(e, t, r) {
  const o = E(typeof document < "u" ? document.activeElement : null);
  F(() => {
    let i = e.current;
    if (!t || r)
      return;
    let n = () => {
      (!d || S(d, e)) && (d = e);
    };
    return document.addEventListener("focusin", n, !1), i.forEach(
      (u) => u.addEventListener("focusin", n, !1)
    ), () => {
      document.removeEventListener("focusin", n, !1), i.forEach(
        (u) => u.removeEventListener("focusin", n, !1)
      );
    };
  }, [
    e,
    r
  ]), F(() => {
    if (!t)
      return;
    f.getTreeNode(e).nodeToRestore = o.current;
    let i = (n) => {
      if (n.key !== "Tab" || n.altKey || n.ctrlKey || n.metaKey)
        return;
      let u = document.activeElement;
      if (!$(u, e.current))
        return;
      let a = f.getTreeNode(e).nodeToRestore, c = h(document.body, {
        tabbable: !0
      });
      c.currentNode = u;
      let l = n.shiftKey ? c.previousNode() : c.nextNode();
      if ((!document.body.contains(a) || a === document.body) && (a = null, f.getTreeNode(e).nodeToRestore = null), (!l || !$(l, e.current)) && a) {
        c.currentNode = a;
        do
          l = n.shiftKey ? c.previousNode() : c.nextNode();
        while ($(l, e.current));
        n.preventDefault(), n.stopPropagation(), l ? m(l, !0) : B(a) ? m(a, !0) : u.blur();
      }
    };
    return r || document.addEventListener("keydown", i, !0), () => {
      r || document.removeEventListener("keydown", i, !0);
      let n = f.getTreeNode(e).nodeToRestore;
      if (t && n && ($(document.activeElement, e.current) || document.activeElement === document.body && ae(e))) {
        let u = f.clone();
        requestAnimationFrame(() => {
          if (document.activeElement === document.body) {
            let a = u.getTreeNode(e);
            for (; a; ) {
              if (a.nodeToRestore && document.body.contains(a.nodeToRestore)) {
                m(a.nodeToRestore);
                return;
              }
              a = a.parent;
            }
            for (a = u.getTreeNode(e); a; ) {
              if (a.scopeRef && f.getTreeNode(a.scopeRef)) {
                w(a.scopeRef.current, !0);
                return;
              }
              a = a.parent;
            }
          }
        });
      }
    };
  }, [
    e,
    t,
    r
  ]);
}
function h(e, t, r) {
  let o = t != null && t.tabbable ? te : ee, i = document.createTreeWalker(e, NodeFilter.SHOW_ELEMENT, {
    acceptNode(n) {
      var u;
      return !(t == null || (u = t.from) === null || u === void 0) && u.contains(n) ? NodeFilter.FILTER_REJECT : n.matches(o) && O(n) && (!r || $(n, r)) && (!(t != null && t.accept) || t.accept(n)) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    }
  });
  return t != null && t.from && (i.currentNode = t.from), i;
}
class k {
  get size() {
    return this.fastMap.size;
  }
  getTreeNode(t) {
    return this.fastMap.get(t);
  }
  addTreeNode(t, r, o) {
    let i = this.fastMap.get(r != null ? r : null), n = new V({
      scopeRef: t
    });
    i.addChild(n), n.parent = i, this.fastMap.set(t, n), o && (n.nodeToRestore = o);
  }
  removeTreeNode(t) {
    if (t === null)
      return;
    let r = this.fastMap.get(t), o = r.parent;
    for (let n of this.traverse())
      n !== r && r.nodeToRestore && n.nodeToRestore && r.scopeRef.current && $(n.nodeToRestore, r.scopeRef.current) && (n.nodeToRestore = r.nodeToRestore);
    let i = r.children;
    o.removeChild(r), i.length > 0 && i.forEach(
      (n) => o.addChild(n)
    ), this.fastMap.delete(r.scopeRef);
  }
  *traverse(t = this.root) {
    if (t.scopeRef != null && (yield t), t.children.length > 0)
      for (let r of t.children)
        yield* this.traverse(r);
  }
  clone() {
    let t = new k();
    for (let r of this.traverse())
      t.addTreeNode(r.scopeRef, r.parent.scopeRef, r.nodeToRestore);
    return t;
  }
  constructor() {
    this.fastMap = /* @__PURE__ */ new Map(), this.root = new V({
      scopeRef: null
    }), this.fastMap.set(null, this.root);
  }
}
class V {
  addChild(t) {
    this.children.push(t), t.parent = this;
  }
  removeChild(t) {
    this.children.splice(this.children.indexOf(t), 1), t.parent = void 0;
  }
  constructor(t) {
    this.children = [], this.contain = !1, this.scopeRef = t.scopeRef;
  }
}
let f = new k();
function $e(e = {}) {
  let { autoFocus: t = !1, isTextInput: r, within: o } = e, i = E({
    isFocused: !1,
    isFocusVisible: t || H()
  }), [n, u] = P(!1), [a, c] = P(
    () => i.current.isFocused && i.current.isFocusVisible
  ), l = A(
    () => c(i.current.isFocused && i.current.isFocusVisible),
    []
  ), s = A((T) => {
    i.current.isFocused = T, u(T), l();
  }, [
    l
  ]);
  U((T) => {
    i.current.isFocusVisible = T, l();
  }, [], {
    isTextInput: r
  });
  let { focusProps: b } = _({
    isDisabled: o,
    onFocusChange: s
  }), { focusWithinProps: p } = G({
    isDisabled: !o,
    onFocusWithinChange: s
  });
  return {
    isFocused: n,
    isFocusVisible: i.current.isFocused && a,
    focusProps: o ? p : b
  };
}
let ue = /* @__PURE__ */ x.createContext(null);
function ce(e) {
  let t = D(ue) || {};
  z(t, e);
  let { ref: r, ...o } = t;
  return o;
}
function ve(e, t) {
  let { focusProps: r } = _(e), { keyboardProps: o } = Y(e), i = I(r, o), n = ce(t), u = e.isDisabled ? {} : n, a = E(e.autoFocus);
  return L(() => {
    a.current && t.current && W(t.current), a.current = !1;
  }, [
    t
  ]), {
    focusableProps: I({
      ...i,
      tabIndex: e.excludeFromTabOrder && !e.isDisabled ? -1 : void 0
    }, u)
  };
}
export {
  fe as FocusScope,
  W as focusSafely,
  h as getFocusableTreeWalker,
  be as isElementInChildOfActiveScope,
  $e as useFocusRing,
  ve as useFocusable
};
//# sourceMappingURL=module.es.js.map
