<script lang="ts">
	import { Select } from 'bits-ui';
	import Icon from './Icon.svelte';

	export type SelectItem = { label: string; value: string; disabled?: boolean };

	let {
		items,
		value = $bindable(''),
		class: className = '',
		disabled = false,
		placeholder = '请选择…',
		onchange,
	}: {
		items: SelectItem[];
		value?: string;
		class?: string;
		disabled?: boolean;
		placeholder?: string;
		onchange?: (value: string) => void;
	} = $props();
</script>

<Select.Root
	type="single"
	{items}
	{disabled}
	{value}
	onValueChange={(next) => {
		value = next;
		onchange?.(next);
	}}
>
	<Select.Trigger class="saas-select-trigger {className}" {disabled}>
		<span class="min-w-0 flex-1 truncate text-left">
			<Select.Value {placeholder} />
		</span>
		<svg
			class="ml-2 h-4 w-4 shrink-0 text-surface-600"
			viewBox="0 0 24 24"
			fill="none"
			stroke="currentColor"
			stroke-width="1.75"
			aria-hidden="true"
		>
			<path stroke-linecap="round" stroke-linejoin="round" d="M8.25 15l3.75 3.75L15.75 15" />
			<path stroke-linecap="round" stroke-linejoin="round" d="M8.25 9l3.75-3.75L15.75 9" />
		</svg>
	</Select.Trigger>
	<Select.Portal>
		<Select.Content class="saas-select-content" sideOffset={6} collisionPadding={8}>
			<Select.Viewport class="p-1">
				{#each items as item (item.value)}
					<Select.Item class="saas-select-item" value={item.value} label={item.label} disabled={item.disabled}>
						{#snippet children({ selected })}
							<span class="min-w-0 flex-1 truncate">{item.label}</span>
							{#if selected}
								<Icon name="check" class="ml-2 h-4 w-4 shrink-0 text-primary-600" />
							{/if}
						{/snippet}
					</Select.Item>
				{/each}
			</Select.Viewport>
		</Select.Content>
	</Select.Portal>
</Select.Root>
