<script module lang="ts">
	import { tv, type VariantProps } from "tailwind-variants";

	export const select = tv({
		base: "w-full appearance-none rounded border bg-background-default px-3 py-2 pr-9 text-sm outline-none transition-colors disabled:cursor-not-allowed",
		variants: {
			error: {
				false:
					"border-border-default focus:border-border-strong focus:ring-1 focus:ring-border-strong",
				true: "border-border-danger bg-background-danger-subtle text-foreground-danger focus:border-border-focus-danger focus:ring-1 focus:ring-border-focus-danger"
			},
			disabled: {
				false: "",
				true: "bg-background-inset text-foreground-disabled"
			}
		},
		defaultVariants: {
			error: false,
			disabled: false
		}
	});

	export type SelectVariants = VariantProps<typeof select>;
</script>

<script lang="ts">
	import ChevronDown from "$icon/chevron-down";
	import type { HTMLSelectAttributes } from "svelte/elements";
	import type { Snippet } from "svelte";

	interface Props extends Omit<HTMLSelectAttributes, "class" | "value"> {
		value?: string;
		error?: boolean;
		disabled?: boolean;
		class?: string;
		children?: Snippet;
	}

	let {
		value = $bindable(""),
		error = false,
		disabled = false,
		class: className,
		children,
		...rest
	}: Props = $props();

	const classes = $derived(select({ error, disabled, class: className }));
</script>

<div class="relative">
	<select bind:value {disabled} aria-invalid={error} class={classes} {...rest}>
		{#if children}
			{@render children()}
		{/if}
	</select>
	<ChevronDown
		class="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-foreground-subtle"
		aria-hidden="true"
	/>
</div>
