import { toggleItem } from "../utils/array.js";
import { useCallbackRef } from "../utils/react.js";
import { Children, isValidElement, useState } from "react";

//#region src/select/useSelect.tsx
const getOptionText = (value, options) => {
	return (options?.find((o) => o?.value === value))?.text || value;
};
/** Handles controlled/uncontrolled value state. Supports single and multiple values. */
function useSelect(props) {
	const { defaultValue, isMultiple, onChange: onChangeProp, value: valueProp, options = [], selectedText, children } = props;
	const [stateValue, setStateValue] = useState(defaultValue);
	const isControlled = valueProp !== void 0;
	const value = isControlled ? valueProp : stateValue;
	const dynamicOptions = [];
	Children.forEach(children, (element) => {
		if (!isValidElement(element)) return;
		const option = element.props;
		if (option.text && option.value) dynamicOptions.push(option);
	});
	return {
		onChange: useCallbackRef((e) => {
			onChangeProp?.(e);
			if (!isControlled) setStateValue((value) => Array.isArray(value) ? toggleItem(value, e.target.value).sort() : e.target.value);
		}),
		value,
		valueText: isMultiple && Array.isArray(value) ? value[0] ? selectedText && value.length > 1 ? selectedText : `${getOptionText(value[0], [...options, ...dynamicOptions])}${value.length > 1 ? ` (+${value.length - 1})` : ""}` : void 0 : getOptionText(value, [...options, ...dynamicOptions])
	};
}

//#endregion
export { useSelect as default, getOptionText };
globalThis.__vuiVersion__ = "4.0.1"
//# sourceMappingURL=useSelect.js.map