/** @license MIT | @cube-dev/ui-kit v0.147.0 | Cube Dev Team */
import { extractStyles } from "../../../utils/styles.js";
import { mergeProps as mergeProps$1 } from "../../../utils/react/mergeProps.js";
import { useCombinedRefs } from "../../../utils/react/useCombinedRefs.js";
import { modAttrs } from "../../../utils/react/index.js";
import { useFocus as useFocus$1 } from "../../../utils/react/interactions.js";
import { LoadingIcon } from "../../../icons/LoadingIcon.js";
import { useProviderProps } from "../../../provider.js";
import { useI18n } from "../../../i18n/useI18n.js";
import { StyledHeader } from "../../actions/Menu/styled.js";
import { useFormProps } from "../../form/Form/Form.js";
import { useFieldProps } from "../../form/Form/use-field/use-field-props.js";
import { wrapWithField } from "../../form/wrapper.js";
import { ListBox } from "../ListBox/ListBox.js";
import { DEFAULT_INPUT_STYLES, INPUT_WRAPPER_STYLES } from "../TextInput/TextInputBase.js";
import { BASE_STYLES, COLOR_STYLES, OUTER_STYLES, tasty } from "@tenphi/tasty";
import { cloneElement, forwardRef, isValidElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { useFilter, useKeyboard } from "react-aria";
import { Item, Section, useListState } from "react-stately";

//#region src/components/fields/FilterListBox/FilterListBox.tsx
const FilterListBoxWrapperElement = tasty({ styles: {
	display: "grid",
	flow: "column",
	gridColumns: "1sf",
	gridRows: "max-content max-content 1sf",
	gap: 0,
	position: "relative",
	radius: true,
	color: "#dark-02",
	transition: "theme",
	outline: {
		"": "#purple-03.0",
		"invalid & focused": "#danger.50",
		focused: "#purple-03"
	},
	border: {
		"": true,
		focused: "#primary-text",
		valid: "#success-text.50",
		invalid: "#danger-text.50",
		disabled: true,
		popover: false
	}
} });
const SearchWrapperElement = tasty({
	qa: "FilterListBoxSearchWrapper",
	styles: {
		...INPUT_WRAPPER_STYLES,
		border: "bottom",
		radius: "1r top",
		fill: "#clear",
		height: "($size + 1x)",
		$size: {
			"": "$size-md",
			"size=small": "$size-sm",
			"size=medium": "$size-md",
			"size=large": "$size-lg"
		}
	}
});
const SearchInputElement = tasty({
	as: "input",
	styles: {
		...DEFAULT_INPUT_STYLES,
		fill: "#clear",
		padding: {
			"": ".5x 1.5x",
			prefix: "0 1.5x 0 .5x",
			suffix: ".5x .5x .5x 1.5x",
			"prefix & suffix": "0 .5x 0 .5x"
		}
	}
});
const StyledHeaderWithoutBorder = tasty(StyledHeader, { styles: { border: false } });
const PROP_STYLES = [
	...BASE_STYLES,
	...OUTER_STYLES,
	...COLOR_STYLES
];
const FilterListBox = forwardRef(function FilterListBox(props, ref) {
	props = useProviderProps(props);
	props = useFormProps(props);
	props = useFieldProps(props, { valuePropsMapper: ({ value, onChange }) => {
		const fieldProps = {};
		if (props.selectionMode === "multiple") fieldProps.selectedKeys = value || [];
		else fieldProps.selectedKey = value ?? null;
		fieldProps.onSelectionChange = (key) => {
			if (props.selectionMode === "multiple") if (key === "all") onChange("all");
			else onChange(key ? Array.isArray(key) ? key : [key] : []);
			else onChange(Array.isArray(key) ? key[0] : key);
		};
		return fieldProps;
	} });
	const { t } = useI18n();
	let { qa, label, extra, id, labelStyles, isRequired, necessityIndicator, validationState, isDisabled, isLoading, isLoadingItems, searchPlaceholder = t("filterListBox.searchPlaceholder", "Search..."), autoFocus, filter, mods: externalMods, emptyLabel, searchInputStyles, listStyles, optionStyles, sectionStyles, headingStyles, searchInputRef, listRef, message, description, styles, focusOnHover, shouldFocusWrap, labelSuffix, selectedKey, defaultSelectedKey, selectedKeys, defaultSelectedKeys, onSelectionChange: externalOnSelectionChange, allowsCustomValue = false, showSelectAll, selectAllLabel, header, footer, size = "medium", headerStyles, footerStyles, listBoxStyles, items, children: renderChildren, onEscape, isCheckable, onOptionClick, selectionMode = "single", allValueProps, customValueProps, newCustomValueProps, searchValue: controlledSearchValue, onSearchChange, _internalCollection, isReorderable = false, onReorder, form, ...otherProps } = props;
	let children = renderChildren;
	const renderFn = renderChildren;
	if (items && typeof renderFn === "function") try {
		children = Array.from(items).map((item, idx) => {
			const rendered = renderFn(item);
			if (isValidElement(rendered) && rendered.key == null) return cloneElement(rendered, { key: rendered?.key ?? item?.key ?? idx });
			return rendered;
		});
	} catch {}
	const localCollectionState = _internalCollection ? { collection: _internalCollection } : useListState({
		children,
		items,
		selectionMode: "none"
	});
	const originalKeys = useMemo(() => {
		const keys = /* @__PURE__ */ new Set();
		for (const item of localCollectionState.collection) if (item.type === "item") keys.add(String(item.key));
		return keys;
	}, [localCollectionState.collection]);
	const [customKeys, setCustomKeys] = useState(/* @__PURE__ */ new Set());
	const [internalSearchValue, setInternalSearchValue] = useState("");
	const isSearchControlled = controlledSearchValue !== void 0;
	const searchValue = isSearchControlled ? controlledSearchValue : internalSearchValue;
	const { contains } = useFilter({ sensitivity: "base" });
	useEffect(() => {
		if (!allowsCustomValue) return;
		const currentSelectedKeys = selectedKeys ? selectedKeys === "all" ? [] : Array.from(selectedKeys).map(String) : selectedKey != null ? [String(selectedKey)] : [];
		if (currentSelectedKeys.length === 0) return;
		const keysToAdd = currentSelectedKeys.filter((k) => !originalKeys.has(k));
		if (keysToAdd.length) setCustomKeys((prev) => new Set([...Array.from(prev), ...keysToAdd]));
	}, [
		allowsCustomValue,
		selectedKeys,
		selectedKey,
		originalKeys
	]);
	const mergedChildren = useMemo(() => {
		if (!children && customKeys.size === 0) return children;
		const term = searchValue.trim();
		const localFilter = typeof filter === "function" ? filter : contains;
		const customArray = Array.from(customKeys).filter((key) => !term || localFilter(key, term)).map((key) => /* @__PURE__ */ jsx(Item, {
			textValue: key,
			...customValueProps,
			children: key
		}, key));
		const selectedKeysSet = /* @__PURE__ */ new Set();
		if (selectionMode === "multiple") if (selectedKeys === "all") {} else Array.from(selectedKeys ?? []).forEach((k) => selectedKeysSet.add(String(k)));
		else if (selectedKey != null) selectedKeysSet.add(String(selectedKey));
		const selectedCustom = [];
		const unselectedCustom = [];
		customArray.forEach((item) => {
			if (selectedKeysSet.has(String(item.key))) selectedCustom.push(item);
			else unselectedCustom.push(item);
		});
		if (!children) return [...selectedCustom, ...unselectedCustom];
		const originalArray = Array.isArray(children) ? children : [children];
		return [
			...selectedCustom,
			...originalArray,
			...unselectedCustom
		];
	}, [
		children,
		customKeys,
		selectionMode,
		selectedKey,
		selectedKeys,
		searchValue,
		filter,
		contains,
		customValueProps
	]);
	const innerAriaLabel = props["aria-label"] || (typeof label === "string" ? label : void 0);
	const handleSearchChange = useCallback((value) => {
		if (!isSearchControlled) setInternalSearchValue(value);
		onSearchChange?.(value);
	}, [isSearchControlled, onSearchChange]);
	const textFilterFn = useMemo(() => {
		if (filter === false) return isLoadingItems ? contains : () => true;
		return filter || contains;
	}, [
		filter,
		contains,
		isLoadingItems
	]);
	const filterFn = useCallback((nodes) => {
		if (filter === false && !isLoadingItems) return nodes;
		const term = searchValue.trim();
		if (!term) return nodes;
		return [...nodes].map((node) => {
			if (node.type === "section" && node.childNodes) {
				const filteredNodes = [...node.childNodes].filter((child) => textFilterFn(child.textValue || "", term));
				if (filteredNodes.length === 0) return null;
				return {
					...node,
					childNodes: filteredNodes,
					hasChildNodes: true
				};
			}
			return textFilterFn(node.textValue || "", term) ? node : null;
		}).filter(Boolean);
	}, [
		filter,
		searchValue,
		textFilterFn,
		isLoadingItems
	]);
	const enhancedChildren = useMemo(() => {
		let childrenToProcess = mergedChildren;
		if (!allowsCustomValue) return childrenToProcess;
		const term = searchValue.trim();
		if (!term) return childrenToProcess;
		const doesTermExist = (term) => {
			if (customKeys.has(term)) return true;
			for (const item of localCollectionState.collection) if (item.type === "item") {
				if (term === (item.textValue || String(item.rendered || "")) || String(item.key) === term) return true;
			}
			return false;
		};
		if (doesTermExist(term)) return childrenToProcess;
		const localFilter = typeof filter === "function" ? filter : contains;
		const hasVisibleFilteredItems = (() => {
			for (const item of localCollectionState.collection) if (item.type === "item") {
				if (textFilterFn(item.textValue || String(item.rendered || ""), term)) return true;
			} else if (item.type === "section" && item.childNodes) {
				for (const child of item.childNodes) if (textFilterFn(child.textValue || String(child.rendered || ""), term)) return true;
			}
			for (const customKey of customKeys) if (localFilter(customKey, term)) return true;
			return false;
		})();
		const customOption = /* @__PURE__ */ jsx(Item, {
			textValue: term,
			...mergeProps$1(customValueProps, newCustomValueProps),
			children: term
		}, term);
		if (hasVisibleFilteredItems && childrenToProcess) {
			const hasSections = [...localCollectionState.collection].some((item) => item.type === "section");
			const customValueSection = /* @__PURE__ */ jsx(Section, {
				"aria-label": t("filterListBox.customValue", "Custom value"),
				children: customOption
			}, "__custom_value__");
			if (hasSections) {
				if (Array.isArray(childrenToProcess)) return [...childrenToProcess, customValueSection];
				return [childrenToProcess, customValueSection];
			}
			return [/* @__PURE__ */ jsx(Section, {
				"aria-label": t("filterListBox.filteredItems", "Filtered items"),
				children: childrenToProcess
			}, "__filtered_items__"), customValueSection];
		}
		if (Array.isArray(childrenToProcess)) return [...childrenToProcess, customOption];
		if (childrenToProcess) return [childrenToProcess, customOption];
		return customOption;
	}, [
		allowsCustomValue,
		mergedChildren,
		searchValue,
		customKeys,
		localCollectionState.collection,
		customValueProps,
		newCustomValueProps,
		textFilterFn,
		filter,
		contains,
		t
	]);
	styles = extractStyles(otherProps, PROP_STYLES, styles);
	ref = useCombinedRefs(ref);
	searchInputRef = useCombinedRefs(searchInputRef);
	listRef = useCombinedRefs(listRef);
	const { isFocused, focusProps } = useFocus$1({ isDisabled });
	const isInvalid = validationState === "invalid";
	const listBoxRef = useRef(null);
	const listStateRef = useRef(null);
	useLayoutEffect(() => {
		const listState = listStateRef.current;
		if (!listState) return;
		const { selectionManager, collection } = listState;
		const term = searchValue.trim();
		let newCustomValueKey = null;
		let customValueHasMatches = false;
		const collectVisibleKeys = (nodes, out, inCustomSection = false) => {
			for (const node of nodes) if (node.type === "item") {
				out.push(node.key);
				if (inCustomSection) {
					newCustomValueKey = node.key;
					customValueHasMatches = true;
				}
			} else if (node.childNodes) {
				const isCustomSection = inCustomSection || node.key === "__custom_value__";
				collectVisibleKeys(node.childNodes, out, isCustomSection);
			}
		};
		const visibleKeys = [];
		collectVisibleKeys(collection, visibleKeys);
		if (newCustomValueKey == null && allowsCustomValue && term) {
			for (const node of collection) if (node.type === "item" && String(node.key) === term) {
				newCustomValueKey = node.key;
				customValueHasMatches = false;
				break;
			}
		}
		if (visibleKeys.length === 0) {
			selectionManager.setFocusedKey(null);
			return;
		}
		const customValueShouldBeFocused = newCustomValueKey != null && !customValueHasMatches;
		const currentFocused = selectionManager.focusedKey;
		if (currentFocused != null && visibleKeys.includes(currentFocused)) {
			const currentIsNewCustomValue = newCustomValueKey != null && currentFocused === newCustomValueKey;
			if (customValueShouldBeFocused) {
				if (currentIsNewCustomValue) return;
			} else if (newCustomValueKey != null) {
				if (!currentIsNewCustomValue) return;
			} else return;
		}
		const findFirstVisibleSelectedKey = () => {
			if (selectionMode === "single") {
				if (selectedKey != null) {
					const selectedKeyStr = String(selectedKey);
					if (visibleKeys.some((k) => String(k) === selectedKeyStr)) return selectedKey;
				}
			} else if (selectionMode === "multiple") {
				if (selectedKeys && selectedKeys !== "all") for (const key of selectedKeys) {
					const keyStr = String(key);
					if (visibleKeys.some((k) => String(k) === keyStr)) return key;
				}
			}
			return null;
		};
		let keyToFocus = null;
		if (customValueShouldBeFocused) keyToFocus = newCustomValueKey;
		else {
			keyToFocus = findFirstVisibleSelectedKey();
			if (keyToFocus == null) keyToFocus = visibleKeys.find((k) => k !== newCustomValueKey) ?? visibleKeys[0];
		}
		if (listState.lastFocusSourceRef) listState.lastFocusSourceRef.current = "keyboard";
		selectionManager.setFocusedKey(keyToFocus);
	}, [
		searchValue,
		enhancedChildren,
		selectionMode,
		selectedKey,
		selectedKeys,
		allowsCustomValue
	]);
	const { keyboardProps } = useKeyboard({ onKeyDown: (e) => {
		if (e.key === "ArrowDown" || e.key === "ArrowUp") {
			e.preventDefault();
			const listState = listStateRef.current;
			if (!listState) return;
			const { selectionManager, collection } = listState;
			const collectVisibleKeys = (nodes, out) => {
				for (const node of nodes) if (node.type === "item") out.push(node.key);
				else if (node.childNodes) collectVisibleKeys(node.childNodes, out);
			};
			const visibleKeys = [];
			collectVisibleKeys(collection, visibleKeys);
			if (visibleKeys.length === 0) return;
			const isArrowDown = e.key === "ArrowDown";
			const direction = isArrowDown ? 1 : -1;
			const currentKey = selectionManager.focusedKey;
			let nextKey = null;
			if (currentKey == null) nextKey = isArrowDown ? visibleKeys[0] : visibleKeys[visibleKeys.length - 1];
			else {
				const currentIndex = visibleKeys.indexOf(currentKey);
				if (currentIndex !== -1) {
					const newIndex = currentIndex + direction;
					if (newIndex >= 0 && newIndex < visibleKeys.length) nextKey = visibleKeys[newIndex];
					else if (shouldFocusWrap) nextKey = isArrowDown ? visibleKeys[0] : visibleKeys[visibleKeys.length - 1];
				} else nextKey = isArrowDown ? visibleKeys[0] : visibleKeys[visibleKeys.length - 1];
			}
			if (nextKey != null) {
				if (listState.lastFocusSourceRef) listState.lastFocusSourceRef.current = "keyboard";
				selectionManager.setFocusedKey(nextKey);
			}
		} else if (e.key === "Home" || e.key === "End" || e.key === "PageUp" || e.key === "PageDown") {
			e.preventDefault();
			const listState = listStateRef.current;
			if (!listState) return;
			const { selectionManager, collection } = listState;
			const collectVisibleKeys = (nodes, out) => {
				for (const node of nodes) if (node.type === "item") out.push(node.key);
				else if (node.childNodes) collectVisibleKeys(node.childNodes, out);
			};
			const visibleKeys = [];
			collectVisibleKeys(collection, visibleKeys);
			if (visibleKeys.length === 0) return;
			const targetKey = e.key === "Home" || e.key === "PageUp" ? visibleKeys[0] : visibleKeys[visibleKeys.length - 1];
			if (listState.lastFocusSourceRef) listState.lastFocusSourceRef.current = "keyboard";
			selectionManager.setFocusedKey(targetKey);
		} else if (e.key === "Enter" || e.key === " " && !searchValue) {
			const listState = listStateRef.current;
			if (!listState) return;
			const keyToSelect = listState.selectionManager.focusedKey;
			if (keyToSelect != null) {
				e.preventDefault();
				listState.selectionManager.select(keyToSelect, e);
				if (e.key === "Enter" && isCheckable && onEscape && selectionMode === "multiple") onEscape();
			}
		} else if (e.key === "Escape") {
			if (searchValue) {
				e.preventDefault();
				handleSearchChange("");
			} else if (onEscape) {
				e.preventDefault();
				onEscape();
			}
		}
	} });
	const mods = useMemo(() => ({
		invalid: isInvalid,
		valid: validationState === "valid",
		disabled: !!isDisabled,
		focused: isFocused,
		loading: !!isLoading,
		"loading-items": !!isLoadingItems,
		searchable: true,
		prefix: !!isLoading,
		suffix: !!isLoadingItems,
		...externalMods
	}), [
		isInvalid,
		validationState,
		isDisabled,
		isFocused,
		isLoading,
		isLoadingItems,
		externalMods
	]);
	const handleSelectionChange = (selection) => {
		if (allowsCustomValue) {
			let selectedValues = [];
			if (selection != null) if (Array.isArray(selection)) selectedValues = selection.map(String);
			else selectedValues = [String(selection)];
			const nextSet = /* @__PURE__ */ new Set();
			selectedValues.forEach((val) => {
				if (!originalKeys.has(val)) nextSet.add(val);
			});
			setCustomKeys(nextSet);
		}
		if (externalOnSelectionChange) externalOnSelectionChange(selection);
	};
	const handleOptionClick = (key) => {
		setTimeout(() => {
			if (searchInputRef.current) searchInputRef.current.focus();
		}, 0);
		if (onOptionClick) onOptionClick(key);
	};
	const searchInput = /* @__PURE__ */ jsxs(SearchWrapperElement, {
		mods,
		"data-size": size,
		children: [
			isLoading && /* @__PURE__ */ jsx("div", {
				"data-element": "Prefix",
				children: /* @__PURE__ */ jsx("div", {
					"data-element": "InputIcon",
					children: isLoading ? /* @__PURE__ */ jsx(LoadingIcon, {}) : null
				})
			}),
			/* @__PURE__ */ jsx(SearchInputElement, {
				ref: searchInputRef,
				qa: qa || "FilterListBox",
				id,
				"data-prefix": isLoading ? "" : void 0,
				"data-suffix": isLoadingItems ? "" : void 0,
				type: "search",
				placeholder: searchPlaceholder,
				value: searchValue,
				disabled: isDisabled,
				autoFocus,
				"data-autofocus": autoFocus ? "" : void 0,
				styles: searchInputStyles,
				"data-size": size,
				"data-input-type": "filterlistbox",
				role: "combobox",
				"aria-expanded": "true",
				"aria-haspopup": "listbox",
				"aria-activedescendant": listStateRef.current?.selectionManager.focusedKey != null ? `ListBoxItem-${listStateRef.current?.selectionManager.focusedKey}` : void 0,
				onChange: (e) => {
					handleSearchChange(e.target.value);
				},
				...keyboardProps,
				...modAttrs(mods)
			}),
			isLoadingItems && /* @__PURE__ */ jsx("div", {
				"data-element": "Suffix",
				children: /* @__PURE__ */ jsx(LoadingIcon, { "data-element": "InputIcon" })
			})
		]
	});
	return wrapWithField(/* @__PURE__ */ jsxs(FilterListBoxWrapperElement, {
		ref,
		qa: "FilterListBoxWrapper",
		...modAttrs(mods),
		styles,
		...focusProps,
		children: [
			header ? /* @__PURE__ */ jsx(StyledHeaderWithoutBorder, {
				"data-size": size,
				styles: headerStyles,
				children: header
			}) : /* @__PURE__ */ jsx("div", { role: "presentation" }),
			searchInput,
			/* @__PURE__ */ jsx(ListBox, {
				ref: listBoxRef,
				"aria-label": innerAriaLabel,
				selectedKey,
				defaultSelectedKey,
				selectedKeys,
				defaultSelectedKeys,
				selectionMode,
				isDisabled,
				listRef,
				stateRef: listStateRef,
				listStyles,
				shouldFocusWrap,
				optionStyles,
				sectionStyles,
				headingStyles,
				validationState,
				disallowEmptySelection: props.disallowEmptySelection,
				disabledKeys: props.disabledKeys,
				focusOnHover,
				shouldUseVirtualFocus: !(isReorderable && !searchValue.trim()),
				showSelectAll,
				selectAllLabel,
				footer,
				footerStyles,
				mods,
				size: "medium",
				styles: listBoxStyles,
				isCheckable,
				items,
				allValueProps,
				filter: filterFn,
				emptyLabel: emptyLabel !== void 0 ? emptyLabel : searchValue.trim() ? t("filterListBox.noResults", "No results found") : t("filterListBox.noItems", "No items"),
				isReorderable: isReorderable && !searchValue.trim(),
				onReorder,
				onSelectionChange: handleSelectionChange,
				onEscape,
				onOptionClick: handleOptionClick,
				children: enhancedChildren
			})
		]
	}), ref, props);
});
FilterListBox.Item = ListBox.Item;
FilterListBox.Section = Section;
Object.defineProperty(FilterListBox, "cubeInputType", {
	value: "FilterListBox",
	enumerable: false,
	configurable: false
});

//#endregion
export { FilterListBox };
//# sourceMappingURL=FilterListBox.js.map