import { useRef as M, useMemo as z, useEffect as I } from "react";
import { focusSafely as C, getFocusableTreeWalker as R } from "../../focus/dist/module.es.js";
import { useEvent as H, scrollIntoView as L, mergeProps as N, isAppleDevice as q, isMac as Y, focusWithoutScrolling as V } from "../../utils/dist/module.es.js";
import { usePress as G, useLongPress as Z } from "../../interactions/dist/module.es.js";
import { useCollator as _, useLocale as j } from "../../i18n/dist/real-module.es.js";
function W(a) {
  return q() ? a.altKey : a.ctrlKey;
}
function B(a) {
  return Y() ? a.metaKey : a.ctrlKey;
}
const J = 1e3;
function Q(a) {
  let { keyboardDelegate: e, selectionManager: t, onTypeSelect: s } = a, r = M({
    search: "",
    timeout: null
  }).current, d = (u) => {
    let K = X(u.key);
    if (!K || u.ctrlKey || u.metaKey)
      return;
    K === " " && r.search.trim().length > 0 && (u.preventDefault(), "continuePropagation" in u || u.stopPropagation()), r.search += K;
    let c = e.getKeyForSearch(r.search, t.focusedKey);
    c == null && (c = e.getKeyForSearch(r.search)), c != null && (t.setFocusedKey(c), s && s(c)), clearTimeout(r.timeout), r.timeout = setTimeout(() => {
      r.search = "";
    }, J);
  };
  return {
    typeSelectProps: {
      onKeyDownCapture: e.getKeyForSearch ? d : null
    }
  };
}
function X(a) {
  return a.length === 1 || !/^[A-Z]/i.test(a) ? a : "";
}
function ee(a) {
  let { selectionManager: e, keyboardDelegate: t, ref: s, autoFocus: r = !1, shouldFocusWrap: d = !1, disallowEmptySelection: u = !1, disallowSelectAll: K = !1, selectOnFocus: c = e.selectionBehavior === "replace", disallowTypeAhead: b = !1, shouldUseVirtualFocus: D, allowsTabNavigation: m = !1, isVirtualized: y, scrollRef: n = s } = a, { direction: F } = j(), g = (o) => {
    if (o.altKey && o.key === "Tab" && o.preventDefault(), !s.current.contains(o.target))
      return;
    const f = (i, A) => {
      i != null && (e.setFocusedKey(i, A), o.shiftKey && e.selectionMode === "multiple" ? e.extendSelection(i) : c && !W(o) && e.replaceSelection(i));
    };
    switch (o.key) {
      case "ArrowDown":
        if (t.getKeyBelow) {
          var S, p;
          o.preventDefault();
          let i = e.focusedKey != null ? t.getKeyBelow(e.focusedKey) : (S = t.getFirstKey) === null || S === void 0 ? void 0 : S.call(t);
          i == null && d && (i = (p = t.getFirstKey) === null || p === void 0 ? void 0 : p.call(t, e.focusedKey)), f(i);
        }
        break;
      case "ArrowUp":
        if (t.getKeyAbove) {
          var T, l;
          o.preventDefault();
          let i = e.focusedKey != null ? t.getKeyAbove(e.focusedKey) : (T = t.getLastKey) === null || T === void 0 ? void 0 : T.call(t);
          i == null && d && (i = (l = t.getLastKey) === null || l === void 0 ? void 0 : l.call(t, e.focusedKey)), f(i);
        }
        break;
      case "ArrowLeft":
        if (t.getKeyLeftOf) {
          o.preventDefault();
          let i = t.getKeyLeftOf(e.focusedKey);
          f(i, F === "rtl" ? "first" : "last");
        }
        break;
      case "ArrowRight":
        if (t.getKeyRightOf) {
          o.preventDefault();
          let i = t.getKeyRightOf(e.focusedKey);
          f(i, F === "rtl" ? "last" : "first");
        }
        break;
      case "Home":
        if (t.getFirstKey) {
          o.preventDefault();
          let i = t.getFirstKey(e.focusedKey, B(o));
          e.setFocusedKey(i), B(o) && o.shiftKey && e.selectionMode === "multiple" ? e.extendSelection(i) : c && e.replaceSelection(i);
        }
        break;
      case "End":
        if (t.getLastKey) {
          o.preventDefault();
          let i = t.getLastKey(e.focusedKey, B(o));
          e.setFocusedKey(i), B(o) && o.shiftKey && e.selectionMode === "multiple" ? e.extendSelection(i) : c && e.replaceSelection(i);
        }
        break;
      case "PageDown":
        if (t.getKeyPageBelow) {
          o.preventDefault();
          let i = t.getKeyPageBelow(e.focusedKey);
          f(i);
        }
        break;
      case "PageUp":
        if (t.getKeyPageAbove) {
          o.preventDefault();
          let i = t.getKeyPageAbove(e.focusedKey);
          f(i);
        }
        break;
      case "a":
        B(o) && e.selectionMode === "multiple" && K !== !0 && (o.preventDefault(), e.selectAll());
        break;
      case "Escape":
        o.preventDefault(), u || e.clearSelection();
        break;
      case "Tab":
        if (!m) {
          if (o.shiftKey)
            s.current.focus();
          else {
            let i = R(s.current, {
              tabbable: !0
            }), A, E;
            do
              E = i.lastChild(), E && (A = E);
            while (E);
            A && !A.contains(document.activeElement) && V(A);
          }
          break;
        }
    }
  }, v = M({
    top: 0,
    left: 0
  });
  H(n, "scroll", y ? null : () => {
    v.current = {
      top: n.current.scrollTop,
      left: n.current.scrollLeft
    };
  });
  let $ = (o) => {
    if (e.isFocused) {
      o.currentTarget.contains(o.target) || e.setFocused(!1);
      return;
    }
    if (!!o.currentTarget.contains(o.target)) {
      if (e.setFocused(!0), e.focusedKey == null) {
        let p = (l) => {
          l != null && (e.setFocusedKey(l), c && e.replaceSelection(l));
        }, T = o.relatedTarget;
        var f, S;
        T && o.currentTarget.compareDocumentPosition(T) & Node.DOCUMENT_POSITION_FOLLOWING ? p((f = e.lastSelectedKey) !== null && f !== void 0 ? f : t.getLastKey()) : p((S = e.firstSelectedKey) !== null && S !== void 0 ? S : t.getFirstKey());
      } else if (!y) {
        n.current.scrollTop = v.current.top, n.current.scrollLeft = v.current.left;
        let p = n.current.querySelector(`[data-key="${e.focusedKey}"]`);
        p && (V(p), L(n.current, p));
      }
    }
  }, x = (o) => {
    o.currentTarget.contains(o.relatedTarget) || e.setFocused(!1);
  };
  const w = M(r);
  I(() => {
    if (w.current) {
      let o = null;
      r === "first" && (o = t.getFirstKey()), r === "last" && (o = t.getLastKey());
      let f = e.selectedKeys;
      f.size && (o = f.values().next().value), e.setFocused(!0), e.setFocusedKey(o), o == null && !D && C(s.current);
    }
    w.current = !1;
  }, []), I(() => {
    if (!y && e.focusedKey && (n == null ? void 0 : n.current)) {
      let o = n.current.querySelector(`[data-key="${e.focusedKey}"]`);
      o && L(n.current, o);
    }
  }, [
    y,
    n,
    e.focusedKey
  ]);
  let P = {
    onKeyDown: g,
    onFocus: $,
    onBlur: x,
    onMouseDown(o) {
      n.current === o.target && o.preventDefault();
    }
  }, { typeSelectProps: O } = Q({
    keyboardDelegate: t,
    selectionManager: e
  });
  b || (P = N(O, P));
  let h;
  return D || (h = e.focusedKey == null ? 0 : -1), {
    collectionProps: {
      ...P,
      tabIndex: h
    }
  };
}
function ae(a) {
  let { selectionManager: e, key: t, ref: s, shouldSelectOnPressUp: r, isVirtualized: d, shouldUseVirtualFocus: u, focus: K, isDisabled: c, onAction: b, allowsDifferentPressOrigin: D } = a, m = (l) => {
    if (l.pointerType === "keyboard" && W(l))
      e.toggleSelection(t);
    else {
      if (e.selectionMode === "none")
        return;
      e.selectionMode === "single" ? e.isSelected(t) && !e.disallowEmptySelection ? e.toggleSelection(t) : e.replaceSelection(t) : l && l.shiftKey ? e.extendSelection(t) : e.selectionBehavior === "toggle" || l && (B(l) || l.pointerType === "touch" || l.pointerType === "virtual") ? e.toggleSelection(t) : e.replaceSelection(t);
    }
  };
  I(() => {
    t === e.focusedKey && e.isFocused && !u && document.activeElement !== s.current && (K ? K() : C(s.current));
  }, [
    s,
    t,
    e.focusedKey,
    e.childFocusStrategy,
    e.isFocused,
    u
  ]), c = c || e.isDisabled(t);
  let y = {};
  !u && !c ? y = {
    tabIndex: t === e.focusedKey ? 0 : -1,
    onFocus(l) {
      l.target === s.current && e.setFocusedKey(t);
    }
  } : c && (y.onMouseDown = (l) => {
    l.preventDefault();
  });
  let n = !c && e.canSelectItem(t), F = b && !c, g = F && (e.selectionBehavior === "replace" ? !n : e.isEmpty), v = F && n && e.selectionBehavior === "replace", $ = g || v, x = M(null), w = $ && n, P = M(!1), O = M(!1), h = {};
  r ? (h.onPressStart = (l) => {
    x.current = l.pointerType, P.current = w, l.pointerType === "keyboard" && (!$ || U()) && m(l);
  }, D ? (h.onPressUp = (l) => {
    l.pointerType !== "keyboard" && m(l);
  }, h.onPress = g ? () => b() : null) : h.onPress = (l) => {
    if (g || v && l.pointerType !== "mouse") {
      if (l.pointerType === "keyboard" && !k())
        return;
      b();
    } else
      l.pointerType !== "keyboard" && m(l);
  }) : (h.onPressStart = (l) => {
    x.current = l.pointerType, P.current = w, O.current = g, (l.pointerType === "mouse" && !g || l.pointerType === "keyboard" && (!b || U())) && m(l);
  }, h.onPress = (l) => {
    (l.pointerType === "touch" || l.pointerType === "pen" || l.pointerType === "virtual" || l.pointerType === "keyboard" && $ && k() || l.pointerType === "mouse" && O.current) && ($ ? b() : m(l));
  }), d || (y["data-key"] = t), h.preventFocusOnPress = u;
  let { pressProps: o, isPressed: f } = G(h), S = v ? (l) => {
    x.current === "mouse" && (l.stopPropagation(), l.preventDefault(), b());
  } : void 0, { longPressProps: p } = Z({
    isDisabled: !w,
    onLongPress(l) {
      l.pointerType === "touch" && (m(l), e.setSelectionBehavior("toggle"));
    }
  });
  return {
    itemProps: N(y, n || g ? o : {}, w ? p : {}, {
      onDoubleClick: S,
      onDragStartCapture: (l) => {
        x.current === "touch" && P.current && l.preventDefault();
      }
    }),
    isPressed: f,
    isSelected: e.isSelected(t),
    isDisabled: c,
    allowsSelection: n,
    hasAction: $
  };
}
function k() {
  let a = window.event;
  return (a == null ? void 0 : a.key) === "Enter";
}
function U() {
  let a = window.event;
  return (a == null ? void 0 : a.key) === " " || (a == null ? void 0 : a.code) === "Space";
}
class te {
  getKeyBelow(e) {
    for (e = this.collection.getKeyAfter(e); e != null; ) {
      if (this.collection.getItem(e).type === "item" && !this.disabledKeys.has(e))
        return e;
      e = this.collection.getKeyAfter(e);
    }
  }
  getKeyAbove(e) {
    for (e = this.collection.getKeyBefore(e); e != null; ) {
      if (this.collection.getItem(e).type === "item" && !this.disabledKeys.has(e))
        return e;
      e = this.collection.getKeyBefore(e);
    }
  }
  getFirstKey() {
    let e = this.collection.getFirstKey();
    for (; e != null; ) {
      if (this.collection.getItem(e).type === "item" && !this.disabledKeys.has(e))
        return e;
      e = this.collection.getKeyAfter(e);
    }
  }
  getLastKey() {
    let e = this.collection.getLastKey();
    for (; e != null; ) {
      if (this.collection.getItem(e).type === "item" && !this.disabledKeys.has(e))
        return e;
      e = this.collection.getKeyBefore(e);
    }
  }
  getItem(e) {
    return this.ref.current.querySelector(`[data-key="${e}"]`);
  }
  getKeyPageAbove(e) {
    let t = this.ref.current, s = this.getItem(e);
    if (!s)
      return null;
    let r = Math.max(0, s.offsetTop + s.offsetHeight - t.offsetHeight);
    for (; s && s.offsetTop > r; )
      e = this.getKeyAbove(e), s = this.getItem(e);
    return e;
  }
  getKeyPageBelow(e) {
    let t = this.ref.current, s = this.getItem(e);
    if (!s)
      return null;
    let r = Math.min(t.scrollHeight, s.offsetTop - s.offsetHeight + t.offsetHeight);
    for (; s && s.offsetTop < r; )
      e = this.getKeyBelow(e), s = this.getItem(e);
    return e;
  }
  getKeyForSearch(e, t) {
    if (!this.collator)
      return null;
    let s = this.collection, r = t || this.getFirstKey();
    for (; r != null; ) {
      let d = s.getItem(r), u = d.textValue.slice(0, e.length);
      if (d.textValue && this.collator.compare(u, e) === 0)
        return r;
      r = this.getKeyBelow(r);
    }
    return null;
  }
  constructor(e, t, s, r) {
    this.collection = e, this.disabledKeys = t, this.ref = s, this.collator = r;
  }
}
function ne(a) {
  let { selectionManager: e, collection: t, disabledKeys: s, ref: r, keyboardDelegate: d, autoFocus: u, shouldFocusWrap: K, isVirtualized: c, disallowEmptySelection: b, selectOnFocus: D = e.selectionBehavior === "replace", disallowTypeAhead: m, shouldUseVirtualFocus: y, allowsTabNavigation: n } = a, F = _({
    usage: "search",
    sensitivity: "base"
  }), g = e.disabledBehavior, v = z(
    () => d || new te(t, g === "selection" ? /* @__PURE__ */ new Set() : s, r, F),
    [
      d,
      t,
      s,
      r,
      F,
      g
    ]
  ), { collectionProps: $ } = ee({
    ref: r,
    selectionManager: e,
    keyboardDelegate: v,
    autoFocus: u,
    shouldFocusWrap: K,
    disallowEmptySelection: b,
    selectOnFocus: D,
    disallowTypeAhead: m,
    shouldUseVirtualFocus: y,
    allowsTabNavigation: n,
    isVirtualized: c,
    scrollRef: r
  });
  return {
    listProps: $
  };
}
export {
  te as ListKeyboardDelegate,
  ee as useSelectableCollection,
  ae as useSelectableItem,
  ne as useSelectableList,
  Q as useTypeSelect
};
//# sourceMappingURL=module.es.js.map
