import { useCallbackRef } from "../utils/react.js";
import { cs, ellipsisOverflow } from "../utils/styles.js";
import { useStyleConfig } from "../core/theme.js";
import vui from "../core/vui.js";
import ListItem from "../list/listItem.js";
import List from "../list/list.js";
import Checkbox from "../checkbox/checkbox.js";
import { usePopoverContext } from "../popover/context.js";
import { useSelectContext } from "./context.js";
import { useEffect } from "react";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";

//#region src/select/selectOption.tsx
/**
* Displays a select option as a list item. By default, closes popover when option is selected.
* In multi-select mode, displays a checkbox and doesn't close popover.
* 'onChange' is triggered with a modified click event, which adds 'value' and 'name' properties.
*/
const SelectOption = vui((props, ref) => {
	const { children, closeOnScroll, className, disabled, title, onClick: onClickProp, value: valueProp, ...rest } = props;
	const { close } = usePopoverContext() ?? {};
	const { isMultiple, name, onChange, value } = useSelectContext() ?? {};
	const styles = useStyleConfig("Select", useSelectContext());
	const isSelected = Array.isArray(value) && valueProp ? value.includes(valueProp) : value === valueProp;
	const hide = () => close?.();
	const onClick = useCallbackRef((e) => {
		const nativeEvent = e.nativeEvent || e;
		const clonedEvent = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
		Object.defineProperty(clonedEvent, "target", {
			writable: true,
			value: {
				value: valueProp,
				name
			}
		});
		onClickProp?.(e);
		onChange?.(clonedEvent);
		!isMultiple && hide();
	});
	const onKeyDown = useCallbackRef((e) => e.key === "Enter" && onClick(e));
	const onScroll = (e) => !e.target?.className?.includes("vui-allowScroll") && hide();
	useEffect(() => {
		if (closeOnScroll) document.addEventListener("scroll", onScroll, true);
		return () => {
			if (closeOnScroll) document.removeEventListener("scroll", onScroll, true);
		};
	}, [closeOnScroll]);
	return /* @__PURE__ */ jsx(ListItem, {
		activeBg: "skyBlue.active",
		className: cs("vui-selectOption", className),
		disabled,
		hoverBg: "skyBlue.hover",
		isInteractive: true,
		isSelected,
		onClick,
		onKeyDown,
		ref,
		selectedBg: "skyBlue.selected",
		tabIndex: 0,
		title,
		value: valueProp,
		...styles.option,
		...rest,
		...ellipsisOverflow,
		children: children ?? (isMultiple && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Checkbox, {
			checked: isSelected,
			disabled,
			mr: 1,
			...styles.option
		}), /* @__PURE__ */ jsx(List.Text, { children: props.text })] }))
	});
});
SelectOption.displayName = "SelectOption";

//#endregion
export { SelectOption as default };
globalThis.__vuiVersion__ = "4.0.1"
//# sourceMappingURL=selectOption.js.map