<script lang="ts">
import { goto } from '$app/navigation';
import { untrack } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
import { formatLifeDateRange } from '$lib/utils/personLifeDates';
import PersonsStatsBar from './PersonsStatsBar.svelte';
import PersonsEmptyState from './PersonsEmptyState.svelte';

let { data } = $props();

let q = $state(untrack(() => data.q || ''));
let qFocused = $state(false);

$effect(() => {
	if (!qFocused) q = data.q || '';
});

let searchTimeout: ReturnType<typeof setTimeout>;

function handleSearch() {
	clearTimeout(searchTimeout);
	searchTimeout = setTimeout(() => {
		goto(`/persons?q=${q}`, { keepFocus: true });
	}, 300);
}
</script>

<svelte:head>
	<title>{m.page_title_persons()}</title>
</svelte:head>

<div class="mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8">
	<!-- Header: title+stats on left, search+CTA on right -->
	<div class="mb-10 flex flex-wrap items-end justify-between gap-4 border-b border-ink/10 pb-6">
		<div>
			<h1 class="font-serif text-3xl font-medium text-ink">{m.page_title_persons()}</h1>
			<div class="mt-2">
				<PersonsStatsBar
					totalPersons={data.stats.totalPersons ?? 0}
					totalDocuments={data.stats.totalDocuments ?? 0}
				/>
			</div>
		</div>

		<div class="flex items-center gap-3">
			<!-- Search -->
			<div class="relative">
				<label for="search" class="sr-only">Suche</label>
				<input
					id="search"
					type="text"
					placeholder={m.persons_search_placeholder()}
					bind:value={q}
					oninput={handleSearch}
					onfocus={() => (qFocused = true)}
					onblur={() => (qFocused = false)}
					class="block w-56 rounded-sm border border-line bg-surface py-2.5 pr-10 pl-4 font-sans text-sm text-ink placeholder-ink-3 shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
				/>
				<div
					class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-ink-3"
				>
					<img
						src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Mag-Glass-MD.svg"
						alt=""
						aria-hidden="true"
						class="h-4 w-4 opacity-40"
					/>
				</div>
			</div>

			<!-- New person CTA -->
			{#if data.canWrite}
				<a
					href="/persons/new"
					class="inline-flex items-center gap-1.5 rounded-sm bg-primary px-4 py-2.5 font-sans text-sm font-bold tracking-wide text-primary-fg transition-colors hover:bg-primary/80"
				>
					<img
						src="/degruyter-icons/Simple/Medium-24px/SVG/Action/Add/Add-General-MD.svg"
						alt=""
						aria-hidden="true"
						class="h-4 w-4 invert dark:invert-0"
					/>
					{m.persons_btn_new()}
				</a>
			{/if}
		</div>
	</div>

	{#if data.persons.length === 0}
		<PersonsEmptyState />
	{:else}
		<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
			{#each data.persons as person (person.id)}
				<a href="/persons/{person.id}" class="group block">
					<div
						class="flex h-full flex-col items-center gap-2 rounded border border-line bg-surface px-4 py-6 text-center shadow-sm transition-all duration-200 hover:border-l-4 hover:border-accent hover:shadow-md"
					>
						<!-- Avatar -->
						<div
							class="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-primary font-serif text-base font-bold text-primary-fg transition-colors"
						>
							{person.firstName?.[0]}{person.lastName?.[0]}
						</div>

						<!-- Name -->
						<p class="font-serif text-sm font-bold text-ink group-hover:underline">
							{person.firstName}
							{person.lastName}
						</p>

						<!-- Alias -->
						{#if person.alias}
							<p class="font-sans text-xs text-ink-2 italic">„{person.alias}"</p>
						{/if}

						<!-- Life dates -->
						{#if person.birthYear || person.deathYear}
							<p class="font-sans text-[11px] text-ink-3">
								{formatLifeDateRange(person.birthYear, person.deathYear)}
							</p>
						{/if}

						<!-- Doc count chip -->
						{#if (person.documentCount ?? 0) > 0}
							<span
								class="mt-1 inline-flex items-center rounded-full border border-line bg-muted px-2.5 py-0.5 font-sans text-[11px] font-semibold text-ink-2"
							>
								{person.documentCount === 1
									? m.person_card_doc_count_one()
									: m.person_card_doc_count_many({ count: person.documentCount ?? 0 })}
							</span>
						{/if}
					</div>
				</a>
			{/each}
		</div>
	{/if}
</div>
