<script module lang="ts">
	import { tv, type VariantProps } from "$lib/tv";

	export const select = tv({
		base: "w-full appearance-none rounded border bg-background-default px-3 py-2 pr-9 text-sm transition-colors outline-none 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: "text-foreground-disabled"
			}
		},
		compoundVariants: [
			{
				error: true,
				disabled: true,
				class:
					"border-border-danger-subtle bg-background-danger-subtle text-foreground-danger-subtle"
			}
		],
		defaultVariants: {
			error: false,
			disabled: false
		}
	});

	export type SelectVariants = VariantProps<typeof select>;

	const chevron = tv({
		base: "pointer-events-none absolute top-1/2 right-3 size-3.5 -translate-y-1/2 text-foreground-subtle",
		variants: {
			error: {
				true: "text-foreground-danger"
			},
			disabled: {
				true: "text-foreground-disabled"
			}
		},
		compoundVariants: [
			{
				error: true,
				disabled: true,
				class: "text-foreground-danger-subtle"
			}
		]
	});
</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={chevron({ error, disabled })} aria-hidden="true" />
</div>
