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

	export const textareaField = tv({
		slots: {
			root: "relative flex max-h-64 items-start gap-1 rounded border bg-background-default px-2.5 py-2 transition-colors",
			textarea:
				"min-h-24 flex-1 bg-transparent text-sm leading-6 outline-none placeholder:text-foreground-placeholder read-only:resize-none disabled:cursor-not-allowed disabled:resize-none"
		},
		variants: {
			error: {
				false: {
					root: "border-border-default focus-within:border-border-strong focus-within:ring-1 focus-within:ring-border-strong"
				},
				true: {
					root: "border-border-danger bg-background-danger-subtle text-foreground-danger focus-within:border-border-focus-danger focus-within:ring-1 focus-within:ring-border-focus-danger",
					textarea: "placeholder:text-foreground-danger"
				}
			},
			disabled: {
				false: "",
				true: {
					root: "cursor-not-allowed border-border-disabled bg-background-subtle text-foreground-muted"
				}
			},
			readonly: {
				false: "",
				true: {
					root: "cursor-default border-border-disabled bg-background-subtle text-foreground-muted"
				}
			},
			resizeable: {
				false: { textarea: "resize-none" },
				true: { textarea: "resize-y" }
			}
		},
		defaultVariants: {
			error: false,
			disabled: false,
			readonly: false
		}
	});

	export type TextareaFieldVariants = VariantProps<typeof textareaField>;
</script>

<script lang="ts">
	import type { Component } from "svelte";
	import type { HTMLTextareaAttributes, SvelteHTMLElements } from "svelte/elements";
	import Spinner from "./Spinner.svelte";

	interface Props extends Omit<HTMLTextareaAttributes, "class" | "value"> {
		value?: string;
		error?: boolean;
		disabled?: boolean;
		loading?: boolean;
		readonly?: boolean;
		resizeable?: boolean;
		iconLeft?: Component<SvelteHTMLElements["svg"]>;
		iconRight?: Component<SvelteHTMLElements["svg"]>;
		class?: string;
	}

	let {
		value = $bindable(""),
		error = false,
		disabled = false,
		loading = false,
		readonly = false,
		resizeable = false,
		iconLeft,
		iconRight,
		class: className,
		...rest
	}: Props = $props();

	const { root, textarea } = $derived(textareaField({ error, disabled, readonly, resizeable }));
</script>

<div class={root({ class: className })}>
	{#if iconLeft}
		{@const IconLeft = iconLeft}
		<IconLeft class="size-4 mt-0.5 mr-1 shrink-0 text-foreground-subtle" aria-hidden="true" />
	{/if}
	<textarea
		bind:value
		{disabled}
		{readonly}
		aria-invalid={error}
		aria-busy={loading}
		class={textarea({ class: loading ? "pr-5" : undefined })}
		{...rest}></textarea>
	{#if loading}
		<Spinner class="absolute right-2.5 top-2 size-4" />
	{:else if iconRight}
		{@const IconRight = iconRight}
		<IconRight class="size-4 mt-0.5 ml-1 shrink-0 text-foreground-subtle" aria-hidden="true" />
	{/if}
</div>
