<script lang="ts">
	import { chat } from '$lib/stores/chat.svelte';

	let inputValue = $state('');
	let textareaEl: HTMLTextAreaElement;

	function handleSubmit(e: Event) {
		e.preventDefault();
		if (!inputValue.trim() || chat.isStreaming) return;

		chat.sendMessage(inputValue);
		inputValue = '';

		// Reset textarea height
		if (textareaEl) {
			textareaEl.style.height = 'auto';
		}
	}

	function handleKeydown(e: KeyboardEvent) {
		// Submit on Enter (without Shift)
		if (e.key === 'Enter' && !e.shiftKey) {
			e.preventDefault();
			handleSubmit(e);
		}
	}

	function autoResize() {
		if (textareaEl) {
			textareaEl.style.height = 'auto';
			textareaEl.style.height = Math.min(textareaEl.scrollHeight, 150) + 'px';
		}
	}

	let isDisabled = $derived(chat.connectionStatus !== 'connected' || chat.isStreaming);
</script>

<form onsubmit={handleSubmit} class="border-t border-gray-200 p-4 dark:border-gray-700">
	<div class="flex items-end gap-2">
		<textarea
			bind:this={textareaEl}
			bind:value={inputValue}
			onkeydown={handleKeydown}
			oninput={autoResize}
			placeholder={chat.connectionStatus === 'connected'
				? 'Type a message...'
				: 'Connecting...'}
			disabled={isDisabled}
			rows="1"
			class="max-h-36 min-h-[42px] flex-1 resize-none rounded-xl border border-gray-300 bg-white px-4 py-2.5 text-sm focus:border-primary-500 focus:ring-1 focus:ring-primary-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:bg-gray-800 dark:text-white dark:focus:border-primary-400"
		></textarea>

		<button
			type="submit"
			disabled={isDisabled || !inputValue.trim()}
			class="flex h-[42px] w-[42px] shrink-0 items-center justify-center rounded-xl bg-primary-600 text-white transition-colors hover:bg-primary-700 focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
			aria-label="Send message"
		>
			{#if chat.isStreaming}
				<svg class="h-5 w-5 animate-spin" fill="none" viewBox="0 0 24 24">
					<circle
						class="opacity-25"
						cx="12"
						cy="12"
						r="10"
						stroke="currentColor"
						stroke-width="4"
					></circle>
					<path
						class="opacity-75"
						fill="currentColor"
						d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
					></path>
				</svg>
			{:else}
				<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
					/>
				</svg>
			{/if}
		</button>
	</div>

	{#if chat.connectionStatus === 'error'}
		<p class="mt-2 text-xs text-red-500">
			Connection error.
			<button
				type="button"
				onclick={() => chat.connect()}
				class="underline hover:no-underline"
			>
				Retry
			</button>
		</p>
	{/if}
</form>
