import { useState as A, useId as h, useRef as H, useCallback as n, useMemo as P } from "react";
function T({
  items: i,
  isOpen: D,
  onOpenChange: f,
  onSelect: l,
  activeDescendantId: g
}) {
  const [x, y] = A(!1), [s, p] = A(-1), d = D !== void 0, e = d ? D : x, w = h(), $ = `listbox-${w}`, b = `option-${w}`, v = H(/* @__PURE__ */ new Map()), o = n(
    (t) => {
      d || y(t), f == null || f(t), t || p(-1);
    },
    [d, f]
  ), I = n(() => o(!0), [o]), k = n(() => o(!1), [o]), u = n(
    (t) => {
      l == null || l(t, i[t]), o(!1);
    },
    [i, l, o]
  ), c = n((t) => {
    var a;
    p(t);
    const r = v.current.get(t);
    (a = r == null ? void 0 : r.scrollIntoView) == null || a.call(r, { block: "nearest" });
  }, []), m = n(
    (t) => {
      const r = i.length;
      switch (t.key) {
        case "ArrowDown": {
          t.preventDefault(), e ? c(Math.min(s + 1, r - 1)) : (o(!0), p(0));
          break;
        }
        case "ArrowUp": {
          t.preventDefault(), e && c(Math.max(s - 1, 0));
          break;
        }
        case "Enter":
        case " ": {
          t.preventDefault(), e && s >= 0 ? u(s) : e || (o(!0), p(0));
          break;
        }
        case "Escape": {
          t.preventDefault(), e && o(!1);
          break;
        }
        case "Home": {
          e && (t.preventDefault(), c(0));
          break;
        }
        case "End": {
          e && (t.preventDefault(), c(r - 1));
          break;
        }
      }
    },
    [e, s, i.length, o, c, u]
  ), M = g ?? (s >= 0 ? `${b}-${s}` : void 0), E = P(
    () => ({
      "aria-expanded": e,
      "aria-haspopup": "listbox",
      "aria-activedescendant": M,
      onClick: () => {
        e ? k() : I();
      },
      onKeyDown: m
    }),
    [e, M, I, k, m]
  ), K = P(
    () => ({
      role: "listbox",
      id: $
    }),
    [$]
  ), R = n(
    (t) => ({
      role: "option",
      id: `${b}-${t}`,
      "aria-selected": t === s,
      onClick: () => u(t),
      ref: (a) => {
        a ? v.current.set(t, a) : v.current.delete(t);
      }
    }),
    [b, s, u]
  );
  return {
    isOpen: e,
    activeIndex: s,
    open: I,
    close: k,
    triggerProps: E,
    listboxProps: K,
    getOptionProps: R
  };
}
export {
  T as useMenuDropdown
};
//# sourceMappingURL=useMenuDropdown.js.map
