<script lang="ts">
import { enhance } from '$app/forms';
import { m } from '$lib/paraglide/messages.js';
import TagParentPicker from '$lib/tag/TagParentPicker.svelte';

type FlatTag = {
	id: string;
	name: string;
	color?: string;
	parentId?: string;
	documentCount: number;
};

interface Props {
	tag: { id: string; name: string; documentCount: number };
	allTags: FlatTag[];
	form: { error?: string } | null;
}

let { tag, allTags, form }: Props = $props();

let targetId = $state('');

$effect(() => {
	void tag.id;
	targetId = '';
});

const step = $derived(targetId ? 2 : 1);

// All descendants of tag.id (to exclude from picker)
const descendantIds = $derived.by(() => {
	const ids: string[] = [];
	const queue = [tag.id];
	while (queue.length) {
		const cur = queue.shift()!;
		for (const t of allTags) {
			if (t.parentId === cur) {
				ids.push(t.id);
				queue.push(t.id);
			}
		}
	}
	return ids;
});

const excludeIds = $derived([tag.id, ...descendantIds]);

// Find target tag for step 2 preview
const targetTag = $derived(allTags.find((t) => t.id === targetId));
</script>

<div class="mb-5 rounded-sm border border-line bg-surface p-5 shadow-sm">
	<h3 class="mb-1 text-xs font-bold tracking-widest text-ink-3 uppercase">
		{m.admin_tag_merge_heading()}
	</h3>
	<p class="mb-4 text-xs text-ink-3">{m.admin_tag_merge_description()}</p>

	<!-- Step indicator (aria-live announces step changes to screen reader users) -->
	<p class="mb-3 text-xs font-medium text-ink-3" aria-live="polite" role="status">
		{step === 1 ? m.admin_tag_merge_step1() : m.admin_tag_merge_step2()}
	</p>

	<!-- Step 1: pick target -->
	<div>
		<label for="mergePickerTarget-search" class="mb-1 block text-xs font-medium text-ink-2">
			{m.admin_tag_merge_target_label()}
		</label>
		<TagParentPicker
			name="mergePickerTarget"
			bind:value={targetId}
			excludeIds={excludeIds}
			placeholder={m.admin_tag_merge_target_placeholder()}
		/>
	</div>

	<!-- Step 2: confirm -->
	{#if step === 2}
		<div data-testid="merge-step2" class="mt-4">
			<!-- From/to summary -->
			<div
				class="mb-4 flex items-center gap-3 rounded border border-line bg-surface/50 p-3 text-sm"
			>
				<div class="flex-1">
					<div class="font-medium text-ink">{tag.name}</div>
					<div class="text-xs text-ink-3">
						{m.admin_tag_merge_preview_docs({ count: tag.documentCount })}
					</div>
				</div>
				<svg
					class="h-4 w-4 flex-shrink-0 text-ink-3"
					fill="none"
					stroke="currentColor"
					viewBox="0 0 24 24"
					aria-hidden="true"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M13 7l5 5m0 0l-5 5m5-5H6"
					/>
				</svg>
				<div class="flex-1">
					<div class="font-medium text-ink">{targetTag?.name ?? ''}</div>
				</div>
			</div>
			<p class="mb-3 text-xs text-ink-3">{m.admin_tag_merge_deleted_after()}</p>

			<form method="POST" action="?/merge" use:enhance>
				<input type="hidden" name="targetId" value={targetId} />
				<button
					type="submit"
					class="rounded-sm bg-amber-600 px-4 py-2 font-sans text-xs font-bold tracking-widest text-white uppercase transition-opacity hover:opacity-80"
				>
					{m.admin_tag_merge_confirm_btn()}
				</button>
			</form>
		</div>
	{/if}

	{#if form?.error}
		<p class="mt-3 text-xs text-red-600">{form.error}</p>
	{/if}
</div>
