import { t as e } from "../chunks/ui.module-BisoTevy.js";
import { useEffect as t, useId as n, useLayoutEffect as r, useMemo as i, useRef as a, useState as o } from "react";
import { cn as s, findFirstEnabledIndex as c, findLastEnabledIndex as l, findNextEnabledIndex as u, handleKeyboardActivation as d } from "@ryuzaki13/react-foundation-lib/utils";
import { CheckIcon as f } from "lucide-react";
import { jsx as p, jsxs as m } from "react/jsx-runtime";
//#region src/listbox/Listbox.tsx
var h = (e) => e.disabled === !0;
function g(e, t, n) {
	if (n) {
		if (Array.isArray(t) && t.length > 0) {
			let n = e.findIndex((e) => t.includes(e.value) && !e.disabled);
			if (n >= 0) return n;
		}
		return c(e, h);
	}
	if (t !== void 0) {
		let n = e.findIndex((e) => e.value === t && !e.disabled);
		if (n >= 0) return n;
	}
	return c(e, h);
}
function _(_) {
	let { value: v, defaultValue: y, multiple: b, focusOnMount: x, renderItem: S, getKey: C, options: w, onChange: T, id: E, ...D } = _, O = v !== void 0, k = n(), A = E ?? `${k}-listbox`, [j, M] = o(y), N = a(null), [P, F] = o(() => g(w, v ?? y, b)), I = i(() => (O ? v : j) ?? (b ? [] : null), [
		j,
		O,
		b,
		v
	]), L = P, R = (e) => {
		if (e.disabled) return;
		let t;
		if (_.multiple) {
			let n = Array.isArray(I) ? I : [];
			t = n.includes(e.value) ? n.filter((t) => t !== e.value) : [...n, e.value], _.onChange?.(t, e);
		} else t = e.value, _.onChange?.(t, e);
		O || M(t);
	};
	return t(() => {
		let e = N.current?.querySelectorAll("[role=\"option\"]")[L];
		e && e.scrollIntoView({ block: "nearest" });
	}, [L]), r(() => {
		x && N.current?.focus();
	}, [x]), /* @__PURE__ */ p("ul", {
		ref: N,
		id: A,
		role: "listbox",
		"aria-multiselectable": b || void 0,
		"aria-activedescendant": L >= 0 ? `${A}-option-${L}` : void 0,
		tabIndex: 0,
		onKeyDown: (e) => {
			if (e.key === "ArrowDown") e.preventDefault(), F((e) => u(w, e, 1, h));
			else if (e.key === "ArrowUp") e.preventDefault(), F((e) => u(w, e, -1, h));
			else if (e.key === "Home") e.preventDefault(), F(c(w, h));
			else if (e.key === "End") e.preventDefault(), F(l(w, h));
			else if (d(e, () => {
				let e = w[L];
				e && R(e);
			})) return;
		},
		...D,
		className: s(e.uiPanel, "scrollable"),
		children: w.map((t, n) => {
			let r = b ? Array.isArray(I) && I.includes(t.value) : I === t.value, i = n === L;
			return /* @__PURE__ */ m("li", {
				id: `${A}-option-${n}`,
				role: "option",
				"aria-selected": r,
				"aria-disabled": t.disabled || void 0,
				onMouseDown: (e) => {
					e.preventDefault(), !t.disabled && (F(n), R(t));
				},
				tabIndex: -1,
				className: s(e.uiPopupOption, t.disabled && e.disabled, i && e.uiPopupOptionActive, r && e.selected),
				children: [p(r ? f : "span", { className: e.uiPopupOptionIcon }), /* @__PURE__ */ p("div", { children: S ? S(t, r, i) : t.label ?? String(t.value) })]
			}, C ? C(t, n) : n);
		})
	});
}
//#endregion
export { _ as Listbox };

//# sourceMappingURL=index.js.map