import { ref as b, onUnmounted as F, unref as w, nextTick as x } from "vue";
const h = 'button:not([tabindex="-1"]), [href], input, select, textarea, li, a, [tabindex]:not([tabindex="-1"])';
function T() {
  const l = b([]);
  let u = null, i = null, f = null, a = null, o = null;
  function m(e) {
    return e ? e.$el ? e.$el : e : null;
  }
  function v(e) {
    const t = m(e);
    if (!t)
      return;
    const c = t.querySelectorAll(h);
    l.value = Array.from(c), i = l.value[0] || null, f = l.value[l.value.length - 1] || null;
  }
  const s = (e) => {
    if (e.key === "Tab" && l.value.length === 0) {
      e.preventDefault();
      return;
    }
    if (e.key !== "Tab")
      return;
    const t = e.shiftKey, c = document.activeElement, n = i, r = f;
    if (!c) {
      e.preventDefault(), n == null || n.focus();
      return;
    }
    !t && c === r ? (e.preventDefault(), n == null || n.focus()) : t && c === n && (e.preventDefault(), r == null || r.focus());
  };
  async function y(e, t) {
    var r;
    if (typeof window > "u" || (d(), a = document.activeElement, o = w(e), !o))
      return;
    await x(), v(o);
    const c = (t == null ? void 0 : t.initialFocusIndex) ?? 0;
    (r = l.value[c]) == null || r.focus(), document.removeEventListener("keydown", s), u == null || u.disconnect(), document.addEventListener("keydown", s);
    const n = m(o);
    n && (u = new MutationObserver(() => v(o)), u.observe(n, { childList: !0, subtree: !0 }));
  }
  function d(e) {
    document.removeEventListener("keydown", s), u == null || u.disconnect(), u = null, e != null && e.returnFocus && a && a.focus(), o = null, l.value = [], i = null, f = null, a = null;
  }
  return F(() => {
    d({ returnFocus: !0 });
  }), {
    initFocusTrap: y,
    clearFocusTrap: d,
    focusable: l
    // expose for advanced use
  };
}
export {
  T as useFocusTrap
};
