import { useState as g, useRef as x, useMemo as m, useCallback as h, useEffect as R } from "../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import { InteractionKeyCode as l } from "../components/types.js";
import q from "./useUniqueId.js";
const O = (t) => t?.disabled === !0, a = (t, c, u) => {
  const s = t.length;
  if (s) {
    let n = c, i = s;
    for (; i--; ) {
      for (; n < 0; ) n += s;
      if (n >= s && (n %= s), !O(t[n])) return n;
      n += u;
    }
  }
  return 0;
}, A = (t, c, u = 0) => {
  if (!c) return u;
  const s = t.findIndex((f) => f.id === c), n = s === -1 ? u : s, i = a(
    t,
    n,
    1
    /* FORWARD */
  );
  return n === i ? n : u;
}, H = ({
  options: t,
  activeOption: c,
  onChange: u
}) => {
  const [s, n] = g(!1), [i, f] = g(A(t, c)), o = t[i], y = x(o), E = x(c), d = x([]), D = q(), T = m(() => {
    const r = [];
    for (let e = 0; e < t.length; e++)
      r[e] = (I) => d.current[e] = I;
    return r;
  }, [t]), b = h((r) => {
    const e = d.current.findIndex((I) => I === r.currentTarget);
    O(d.current[e]) || (r.preventDefault(), f(e));
  }, []), k = m(() => {
    const r = {
      [l.ARROW_LEFT]: () => f((e) => a(
        d.current,
        e - 1,
        -1
        /* BACKWARD */
      )),
      [l.ARROW_RIGHT]: () => f((e) => a(
        d.current,
        e + 1,
        1
        /* FORWARD */
      )),
      [l.HOME]: () => f(a(
        d.current,
        0,
        1
        /* FORWARD */
      )),
      [l.END]: () => f(a(
        d.current,
        -1,
        -1
        /* BACKWARD */
      ))
    };
    return (e) => {
      r[e.key] && (e.preventDefault(), r[e.key]?.(), n(!0));
    };
  }, []);
  return R(() => {
    f((r) => A(t, c, r));
  }, [t, c]), R(() => {
    if (s) {
      const r = d.current[i];
      O(r) || r?.focus(), n(!1);
    }
  }, [i, s]), R(() => {
    if (E.current !== c) {
      E.current = c;
      return;
    }
    y.current !== o && (y.current = o, u?.(o));
  }, [o, c, u]), { activeIndex: i, onClick: b, onKeyDown: k, refs: T, uniqueId: D };
};
export {
  H as default,
  H as useTabbedControl
};
