<script lang="ts">
	import VoiceRecorder from './VoiceRecorder.svelte';

	interface Props {
		onsubmit: (content: string) => Promise<void>;
		disabled?: boolean;
		accessToken?: string;
		/** Context node for voice memo attachment (e.g. communication node) */
		contextId?: string;
	}

	let { onsubmit, disabled = false, accessToken, contextId }: Props = $props();

	let content = $state('');
	let submitting = $state(false);
	let error = $state('');
	let textareaEl: HTMLTextAreaElement | undefined = $state();

	const isEmpty = $derived(!content.trim());

	async function handleSubmit() {
		if (isEmpty || submitting || disabled) return;

		submitting = true;
		error = '';

		try {
			await onsubmit(content.trim());
			content = '';
			// Reset textarea height
			if (textareaEl) textareaEl.style.height = 'auto';
		} catch (e) {
			error = e instanceof Error ? e.message : 'Noe gikk galt';
		} finally {
			submitting = false;
			textareaEl?.focus();
		}
	}

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

	function autoResize(e: Event) {
		const el = e.target as HTMLTextAreaElement;
		el.style.height = 'auto';
		el.style.height = Math.min(el.scrollHeight, 160) + 'px';
	}
</script>

<div class="flex items-end gap-2">
	<div class="relative flex-1">
		<textarea
			bind:this={textareaEl}
			bind:value={content}
			onkeydown={handleKeydown}
			oninput={autoResize}
			placeholder="Skriv en melding…"
			disabled={disabled || submitting}
			rows={1}
			class="w-full resize-none rounded-xl border border-gray-200 bg-gray-50 px-4 py-2.5 text-sm text-gray-900 placeholder:text-gray-400 focus:border-blue-300 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-300"
		></textarea>
		{#if error}
			<p class="absolute -top-6 left-0 text-xs text-red-600">{error}</p>
		{/if}
	</div>
	<VoiceRecorder
		{accessToken}
		sourceId={contextId}
		disabled={disabled || submitting}
		onerror={(msg) => { error = msg; }}
	/>
	<button
		onclick={handleSubmit}
		disabled={isEmpty || submitting || disabled}
		class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-blue-600 text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-40"
		aria-label="Send melding"
	>
		{#if submitting}
			<svg class="h-4 w-4 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-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
				<path stroke-linecap="round" stroke-linejoin="round" d="M5 12h14M12 5l7 7-7 7" />
			</svg>
		{/if}
	</button>
</div>
