<script lang="ts">
	import { Select as SelectPrimitive } from 'bits-ui';
	import { writable } from 'svelte/store';
	import { setContext } from 'svelte';
	import { selectSearchContextKey, type SelectSearchContext } from './select-search-context';
	import { type WithoutChild } from '$lib/utils.js';

	// SelectPrimitive.RootProps is a discriminated union (single | multiple).
	// Spreading a discriminated union collapses conflicting members (e.g. onValueChange) to `never`.
	// We widen the props type so callers can pass either variant without hitting `never`.
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	type SelectRootProps = Omit<WithoutChild<SelectPrimitive.RootProps>, 'value' | 'onValueChange'> & {
		type?: 'single' | 'multiple';
		value?: string | string[];
		onValueChange?: (value: any) => void;
	};

	let {
		children,
		value = $bindable(),
		...restProps
	}: SelectRootProps = $props();

	let open = $state(false);
	const query = writable('');
	const openStore = writable(false);
	const context: SelectSearchContext = {
		query,
		open: openStore,
		setOpen: (next) => {
			open = next;
		}
	};

	setContext(selectSearchContextKey, context);

	$effect(() => {
		openStore.set(open);
		if (!open) {
			query.set('');
		}
	});
</script>

<SelectPrimitive.Root bind:open bind:value={value as any} {...restProps}>
	{@render children?.()}
</SelectPrimitive.Root>
