import { onUnmounted as y, unref as p, nextTick as x } from "vue";
const m = 'button:not([tabindex="-1"]), [href], input, select, textarea, li, a, [tabindex]:not([tabindex="-1"])';
function w() {
  let n = [], u = null, s = null, r = null;
  async function b(e) {
    e = p(e), e && (await x(), f(e), s && s.focus(), document.addEventListener("keydown", d), u = new MutationObserver(() => f(e)), e.$el ? u.observe(e.$el, { childList: !0, subtree: !0 }) : u.observe(e, { childList: !0, subtree: !0 }));
  }
  function f(e) {
    if (e === null)
      return;
    let c;
    e.$el ? c = e == null ? void 0 : e.$el.querySelectorAll(m) : e.querySelectorAll(m), n = Array.from(c || []), s = n[0] || null, r = n[n.length - 1] || null;
  }
  const d = (e) => {
    var c;
    if (e.key === "Tab") {
      const t = e.shiftKey, o = document.activeElement;
      if (!o) {
        e.preventDefault(), (c = n[0]) == null || c.focus();
        return;
      }
      const l = n[0], i = n[n.length - 1];
      !t && o === i ? (e.preventDefault(), l == null || l.focus()) : t && o === l && (e.preventDefault(), i == null || i.focus());
    } else if (e.key === "ArrowUp" || e.key === "ArrowLeft") {
      e.preventDefault();
      const t = document.activeElement, o = n.indexOf(t), l = n[o - 1];
      l ? l.focus() : r && r.focus();
    } else if (e.key === "ArrowDown" || e.key === "ArrowRight") {
      e.preventDefault();
      const t = document.activeElement, o = n.indexOf(t), l = n[o + 1];
      l ? l.focus() : s && s.focus();
    }
  }, a = () => {
    document.removeEventListener("keydown", d), u == null || u.disconnect();
  };
  return y(() => {
    a();
  }), {
    initFocusTrap: b,
    clearFocusTrap: a
  };
}
export {
  w as useFocusTrap
};
