<script lang="ts">
import { onMount, untrack } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
import type { Comment } from '$lib/types';
import MentionEditor from '$lib/components/MentionEditor.svelte';
import { renderBody, extractContent } from '$lib/utils/mention';
import type { MentionDTO } from '$lib/types';

type Props = {
	documentId: string;
	annotationId?: string | null;
	blockId?: string | null;
	initialComments?: Comment[];
	loadOnMount?: boolean;
	canComment: boolean;
	currentUserId: string | null;
	quotedText?: string | null;
	showCompose?: boolean;
	onCountChange?: (count: number) => void;
};

let {
	documentId,
	annotationId = null,
	blockId = null,
	initialComments = [],
	loadOnMount = false,
	canComment,
	currentUserId = null,
	quotedText = null,
	showCompose = true,
	onCountChange
}: Props = $props();

type FlatMessage = {
	id: string;
	authorId: string | null;
	authorName: string;
	content: string;
	createdAt: string;
	updatedAt: string;
	mentionDTOs?: MentionDTO[];
};

let comments: Comment[] = $state(untrack(() => [...initialComments]));
let newText: string = $state('');
let posting: boolean = $state(false);
let newMentionCandidates: MentionDTO[] = $state([]);
let editingId: string | null = $state(null);
let editText: string = $state('');

const commentsBase = $derived(
	blockId
		? `/api/documents/${documentId}/transcription-blocks/${blockId}/comments`
		: annotationId
			? `/api/documents/${documentId}/annotations/${annotationId}/comments`
			: `/api/documents/${documentId}/comments`
);

const flatMessages = $derived(
	comments.flatMap((thread) => [thread as FlatMessage, ...(thread.replies as FlatMessage[])])
);

$effect(() => {
	if (quotedText && quotedText.trim()) {
		newText = `> "${quotedText}"\n\n`;
	}
});

function timeAgo(iso: string): string {
	const diff = Date.now() - new Date(iso).getTime();
	const minutes = Math.floor(diff / 60000);
	if (minutes < 1) return m.comment_time_just_now();
	if (minutes < 60) return m.comment_time_minutes({ count: minutes });
	const hours = Math.floor(minutes / 60);
	if (hours < 24) return m.comment_time_hours({ count: hours });
	const days = Math.floor(hours / 24);
	return m.comment_time_days({ count: days });
}

function wasEdited(c: { createdAt: string; updatedAt: string }): boolean {
	return c.updatedAt > c.createdAt;
}

function isOwn(c: { authorId: string | null }): boolean {
	return currentUserId !== null && c.authorId === currentUserId;
}

function getInitials(name: string): string {
	return name
		.split(/\s+/)
		.slice(0, 2)
		.map((w) => w.charAt(0).toUpperCase())
		.join('');
}

function extractQuote(content: string): { quote: string | null; body: string } {
	const match = content.match(/^>\s*"(.+?)"\s*\n\n?([\s\S]*)$/);
	if (match) return { quote: match[1], body: match[2] };
	return { quote: null, body: content };
}

async function reload() {
	try {
		const res = await fetch(commentsBase);
		if (res.ok) {
			comments = await res.json();
			const total = comments.reduce((s, c) => s + 1 + c.replies.length, 0);
			onCountChange?.(total);
		}
	} catch {
		/* ignore */
	}
}

async function postComment() {
	const text = newText.trim();
	if (!text || posting) return;
	posting = true;
	try {
		const { content, mentionedUserIds } = extractContent(text, newMentionCandidates);
		const res = await fetch(commentsBase, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ content, mentionedUserIds })
		});
		if (res.ok) {
			newText = '';
			newMentionCandidates = [];
			await reload();
		}
	} finally {
		posting = false;
	}
}

function startEdit(msg: FlatMessage) {
	editingId = msg.id;
	editText = msg.content;
}

async function saveEdit(commentId: string) {
	const text = editText.trim();
	if (!text || posting) return;
	posting = true;
	try {
		const res = await fetch(`/api/documents/${documentId}/comments/${commentId}`, {
			method: 'PATCH',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ content: text })
		});
		if (res.ok) {
			editingId = null;
			editText = '';
			await reload();
		}
	} finally {
		posting = false;
	}
}

function cancelEdit() {
	editingId = null;
	editText = '';
}

function handleEditKeydown(e: KeyboardEvent, commentId: string) {
	if (e.key === 'Enter' && !e.shiftKey) {
		e.preventDefault();
		saveEdit(commentId);
	} else if (e.key === 'Escape') {
		e.stopPropagation();
		cancelEdit();
	}
}

async function deleteComment(commentId: string) {
	if (posting) return;
	posting = true;
	try {
		const res = await fetch(`/api/documents/${documentId}/comments/${commentId}`, {
			method: 'DELETE'
		});
		if (res.ok) {
			await reload();
		}
	} finally {
		posting = false;
	}
}

onMount(() => {
	if (loadOnMount) {
		reload();
	} else {
		const total = initialComments.reduce((s, c) => s + 1 + c.replies.length, 0);
		onCountChange?.(total);
	}
});
</script>

{#if flatMessages.length > 0}
	<div class="rounded border-l-2 border-accent bg-muted p-2">
		<div class="mb-2 flex items-center gap-1.5 font-sans text-sm font-semibold text-ink-2">
			<svg
				class="h-3.5 w-3.5"
				viewBox="0 0 24 24"
				fill="none"
				stroke="currentColor"
				stroke-width="2"
			>
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					d="M2.25 12.76c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.076-4.076a1.526 1.526 0 011.037-.443 48.282 48.282 0 005.68-.494c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"
				/>
			</svg>
			{flatMessages.length}
			{flatMessages.length === 1 ? 'Kommentar' : 'Kommentare'}
		</div>

		<div class="space-y-2">
			{#each flatMessages as msg (msg.id)}
				{@const parsed = extractQuote(msg.content)}
				<div class="flex gap-2">
					<div
						class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-bold text-primary-fg"
					>
						{getInitials(msg.authorName)}
					</div>
					<div class="min-w-0 flex-1">
						<div class="flex items-center gap-1.5">
							<span class="font-sans text-sm font-semibold text-ink">{msg.authorName}</span>
							{#if wasEdited(msg)}
								<span class="font-sans text-xs text-ink-3"
									>{timeAgo(msg.updatedAt)} {m.comment_edited_label()}</span
								>
							{:else}
								<span class="font-sans text-xs text-ink-3">{timeAgo(msg.createdAt)}</span>
							{/if}
						</div>
						{#if parsed.quote}
							<div class="my-1 border-l-2 border-line pl-2 font-serif text-base text-ink-3 italic">
								&ldquo;{parsed.quote}&rdquo;
							</div>
						{/if}

						{#if editingId === msg.id}
							<textarea
								class="mt-1 w-full resize-none rounded border border-line bg-surface px-2 py-1 font-serif text-sm leading-relaxed text-ink outline-none focus:border-primary"
								rows={2}
								bind:value={editText}
								onkeydown={(e) => handleEditKeydown(e, msg.id)}
							></textarea>
							<div class="mt-1 font-sans text-xs text-ink-3">Enter speichern · Esc abbrechen</div>
						{:else}
							<!-- svelte-ignore a11y_click_events_have_key_events -->
							<!-- svelte-ignore a11y_no_static_element_interactions -->
							<div class="relative" onclick={() => { if (isOwn(msg)) startEdit(msg); }}>
								<p
									class="font-serif text-base leading-relaxed text-ink-2 {isOwn(msg) ? '-mx-1 cursor-text rounded px-1 transition-colors hover:bg-surface' : ''}"
								>
									<!-- eslint-disable-next-line svelte/no-at-html-tags -- renderBody escapes all HTML before injecting mention links -->
									{@html renderBody(parsed.body, msg.mentionDTOs ?? [])}
								</p>
								{#if isOwn(msg)}
									<button
										type="button"
										class="hover:text-error absolute -right-1 -bottom-1 cursor-pointer rounded p-0.5 text-ink-3 transition-colors"
										title={m.btn_delete()}
										aria-label={m.btn_delete()}
										onclick={(e) => { e.stopPropagation(); deleteComment(msg.id); }}
									>
										<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>
								{/if}
							</div>
						{/if}
					</div>
				</div>
			{/each}
		</div>
	</div>
{/if}

{#if canComment && (showCompose || flatMessages.length > 0)}
	<div class="mt-2">
		<MentionEditor
			bind:value={newText}
			bind:mentionCandidates={newMentionCandidates}
			rows={1}
			placeholder={m.comment_placeholder()}
			disabled={posting}
			onsubmit={postComment}
		/>
	</div>
{/if}
