import * as c from "react";
import { useStableCallback as x } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useStableCallback.js";
import { useIsoLayoutEffect as E } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useIsoLayoutEffect.js";
import { useTimeout as U } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/useTimeout.js";
import { EMPTY_ARRAY as _ } from "../../../../../../../@base-ui_utils@0.2.4_@types_react@18.3.27_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@base-ui/utils/esm/empty.js";
import { stopEvent as A } from "../utils/event.js";
function J(d, F) {
  const M = "rootStore" in d ? d.rootStore : d, s = M.useState("open"), l = M.context.dataRef, {
    listRef: Y,
    activeIndex: p,
    onMatch: R,
    onTypingChange: n,
    enabled: g = !0,
    findMatch: K = null,
    resetMs: D = 750,
    ignoreKeys: T = _,
    selectedIndex: L = null
  } = F, k = U(), r = c.useRef(""), a = c.useRef(L ?? p ?? -1), m = c.useRef(null);
  E(() => {
    s && (k.clear(), m.current = null, r.current = "");
  }, [s, k]), E(() => {
    s && r.current === "" && (a.current = L ?? p ?? -1);
  }, [s, L, p]);
  const o = x((e) => {
    e ? l.current.typing || (l.current.typing = e, n == null || n(e)) : l.current.typing && (l.current.typing = e, n == null || n(e));
  }), y = x((e) => {
    function C(u, i, f) {
      const b = K ? K(i, f) : i.find((I) => (I == null ? void 0 : I.toLocaleLowerCase().indexOf(f.toLocaleLowerCase())) === 0);
      return b ? u.indexOf(b) : -1;
    }
    const t = Y.current;
    if (r.current.length > 0 && r.current[0] !== " " && (C(t, t, r.current) === -1 ? o(!1) : e.key === " " && A(e)), t == null || T.includes(e.key) || // Character key.
    e.key.length !== 1 || // Modifier key.
    e.ctrlKey || e.metaKey || e.altKey)
      return;
    s && e.key !== " " && (A(e), o(!0)), t.every((u) => {
      var i, f;
      return u ? ((i = u[0]) == null ? void 0 : i.toLocaleLowerCase()) !== ((f = u[1]) == null ? void 0 : f.toLocaleLowerCase()) : !0;
    }) && r.current === e.key && (r.current = "", a.current = m.current), r.current += e.key, k.start(D, () => {
      r.current = "", a.current = m.current, o(!1);
    });
    const O = a.current, w = C(t, [...t.slice((O || 0) + 1), ...t.slice(0, (O || 0) + 1)], r.current);
    w !== -1 ? (R == null || R(w), m.current = w) : e.key !== " " && (r.current = "", o(!1));
  }), S = c.useMemo(() => ({
    onKeyDown: y
  }), [y]), h = c.useMemo(() => ({
    onKeyDown: y,
    onKeyUp(e) {
      e.key === " " && o(!1);
    }
  }), [y, o]);
  return c.useMemo(() => g ? {
    reference: S,
    floating: h
  } : {}, [g, S, h]);
}
export {
  J as useTypeahead
};
