"use client";
let react = require("react");
//#region packages/@mantine/core/src/components/Menu/use-menu-type-ahead.ts
const RESET_DELAY = 500;
function getItemText(item) {
	return ((item.querySelector("[data-menu-item-label]") ?? item).textContent ?? "").trim().toLowerCase();
}
function isRepeatedChar(buffer) {
	return buffer.length > 1 && buffer.split("").every((char) => char === buffer[0]);
}
function useMenuTypeAhead({ enabled, opened, getDropdown }) {
	const stateRef = (0, react.useRef)({
		buffer: "",
		timeoutId: null
	});
	(0, react.useEffect)(() => {
		if (opened && enabled) return;
		const state = stateRef.current;
		if (state.timeoutId !== null) {
			window.clearTimeout(state.timeoutId);
			state.timeoutId = null;
		}
		state.buffer = "";
	}, [opened, enabled]);
	(0, react.useEffect)(() => () => {
		const { timeoutId } = stateRef.current;
		if (timeoutId !== null) window.clearTimeout(timeoutId);
	}, []);
	return (event) => {
		if (!enabled || event.defaultPrevented) return;
		if (event.ctrlKey || event.metaKey || event.altKey) return;
		if (event.key.length !== 1 || event.key === " ") return;
		const target = event.target;
		if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT" || target.isContentEditable)) return;
		const dropdown = getDropdown();
		if (!dropdown) return;
		const items = Array.from(dropdown.querySelectorAll("[data-menu-item]:not([data-disabled])")).filter((item) => item.closest("[data-menu-dropdown]") === dropdown);
		if (items.length === 0) return;
		const state = stateRef.current;
		state.buffer = (state.buffer + event.key).toLowerCase();
		if (state.timeoutId !== null) window.clearTimeout(state.timeoutId);
		state.timeoutId = window.setTimeout(() => {
			state.buffer = "";
			state.timeoutId = null;
		}, RESET_DELAY);
		const activeElement = document.activeElement;
		const currentIndex = activeElement ? items.indexOf(activeElement) : -1;
		let match = null;
		if (state.buffer.length === 1 || isRepeatedChar(state.buffer)) {
			const char = state.buffer[0];
			const startIndex = currentIndex + 1;
			for (let i = 0; i < items.length; i += 1) {
				const idx = (startIndex + i) % items.length;
				if (getItemText(items[idx]).startsWith(char)) {
					match = items[idx];
					break;
				}
			}
		} else for (let i = 0; i < items.length; i += 1) if (getItemText(items[i]).startsWith(state.buffer)) {
			match = items[i];
			break;
		}
		if (match) {
			event.preventDefault();
			match.focus();
		}
	};
}
//#endregion
exports.useMenuTypeAhead = useMenuTypeAhead;

//# sourceMappingURL=use-menu-type-ahead.cjs.map