<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';

	let {
		children,
		value = $bindable(),
		...restProps
	}: WithoutChild<SelectPrimitive.RootProps> = $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>
