<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import CommentThread from './CommentThread.svelte';

type SaveState = 'idle' | 'saving' | 'saved' | 'fading' | 'error';

type Props = {
	blockId: string;
	documentId: string;
	blockNumber: number;
	text: string;
	label: string | null;
	active: boolean;
	saveState: SaveState;
	canComment: boolean;
	currentUserId: string | null;
	onTextChange: (text: string) => void;
	onFocus: () => void;
	onDeleteClick: () => void;
	onRetry: () => void;
};

let {
	blockId,
	documentId,
	blockNumber,
	text,
	label = null,
	active,
	saveState,
	canComment,
	currentUserId,
	onTextChange,
	onFocus,
	onDeleteClick,
	onRetry
}: Props = $props();

let localText = $state(text);
let commentOpen = $state(false);
let selectedQuote = $state<string | null>(null);
let textareaEl = $state<HTMLTextAreaElement | null>(null);

// Sync from prop only when switching to a different block (not on save responses)
let prevBlockId = $state(blockId);
$effect(() => {
	if (blockId !== prevBlockId) {
		localText = text;
		prevBlockId = blockId;
	}
});

let leftBorderClass = $derived(
	saveState === 'error' ? 'border-l-2 border-error' : active ? 'border-l-2 border-turquoise' : ''
);

function autoresize(node: HTMLTextAreaElement) {
	textareaEl = node;
	function resize() {
		node.style.height = 'auto';
		node.style.height = `${node.scrollHeight}px`;
	}

	resize();

	return {
		update() {
			resize();
		},
		destroy() {
			textareaEl = null;
		}
	};
}

function handleInput(event: Event) {
	const target = event.target as HTMLTextAreaElement;
	localText = target.value;
	onTextChange(target.value);
}

function handleDelete() {
	if (confirm(m.transcription_block_delete_confirm())) {
		onDeleteClick();
	}
}

function captureSelectionAndOpenComments() {
	if (textareaEl) {
		const start = textareaEl.selectionStart;
		const end = textareaEl.selectionEnd;
		if (start !== end) {
			selectedQuote = localText.substring(start, end);
		} else {
			selectedQuote = null;
		}
	}
	commentOpen = true;
}
</script>

<div
	class="relative overflow-visible rounded border border-line {leftBorderClass}"
	data-block-id={blockId}
>
	<!-- Turquoise numbered badge — overlaps top-left of card -->
	<span
		class="absolute -top-2 -left-2 z-10 flex h-6 w-6 items-center justify-center rounded-full bg-turquoise text-xs font-bold text-turquoise-fg shadow-sm"
	>
		{blockNumber}
	</span>
	<div class="p-4 pl-6">
		<!-- Header -->
		<div class="mb-2 flex items-center gap-2">
			{#if label}
				<span class="text-xs font-medium tracking-wide text-ink-2 uppercase">
					{label}
				</span>
			{/if}
		</div>

		<!-- Textarea -->
		<textarea
			use:autoresize={localText}
			class="w-full resize-none border-none bg-transparent font-serif text-base leading-relaxed text-ink outline-none placeholder:text-ink-3"
			placeholder={m.transcription_block_placeholder()}
			rows={1}
			value={localText}
			oninput={handleInput}
			onfocus={onFocus}
		></textarea>

		<!-- Footer -->
		<div class="flex items-center justify-between border-t border-line pt-2">
			<div class="flex flex-col gap-1">
				<button
					type="button"
					class="text-xs font-medium text-ink-2 transition-colors hover:text-ink"
					onclick={captureSelectionAndOpenComments}
				>
					{m.transcription_block_comment_btn()}
				</button>
				{#if active}
					<span class="text-xs text-ink-3">
						{m.transcription_block_quote_hint()}
					</span>
				{/if}
			</div>

			<div class="flex items-center gap-2">
				<!-- Save state indicator -->
				{#if saveState === 'saving'}
					<span class="animate-pulse text-xs text-ink-3">
						{m.transcription_block_save_saving()}
					</span>
				{:else if saveState === 'saved' || saveState === 'fading'}
					<span
						class="text-xs text-green-600 transition-opacity duration-300 {saveState === 'fading' ? 'opacity-0' : 'opacity-100'}"
					>
						{m.transcription_block_save_saved()} <span class="inline-block">&#10003;</span>
					</span>
				{:else if saveState === 'error'}
					<span class="text-error text-xs">
						{m.transcription_block_save_error()}
						<span class="mx-1">&mdash;</span>
						<button
							type="button"
							class="underline transition-colors hover:text-ink"
							onclick={onRetry}
						>
							{m.transcription_block_save_retry()}
						</button>
					</span>
				{/if}

				<!-- Delete button -->
				<button
					type="button"
					class="hover:text-error text-ink-3 transition-colors"
					aria-label={m.btn_delete()}
					onclick={handleDelete}
				>
					<svg
						class="h-4 w-4"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						stroke-width="1.5"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
						/>
					</svg>
				</button>
			</div>
		</div>

		<!-- Comment thread (expandable) -->
		{#if commentOpen}
			<div class="mt-3 border-t border-line pt-3">
				<div class="mb-2 flex items-center justify-between">
					<span class="font-sans text-xs font-semibold text-ink-2">
						{m.comment_section_title()}
					</span>
					<button
						type="button"
						class="font-sans text-xs text-ink-3 transition-colors hover:text-ink"
						onclick={() => {
							commentOpen = false;
							selectedQuote = null;
						}}
					>
						{m.comment_panel_close()}
					</button>
				</div>
				<CommentThread
					documentId={documentId}
					blockId={blockId}
					loadOnMount={true}
					canComment={canComment}
					currentUserId={currentUserId}
					canAdmin={false}
					quotedText={selectedQuote}
				/>
			</div>
		{/if}
	</div>
</div>
