<script lang="ts">
import { goto } from '$app/navigation';
import { untrack } from 'svelte';
import { m } from '$lib/paraglide/messages.js';
import { formatLifeDateRange } from '$lib/person/personLifeDates';
import PersonTypeBadge from '$lib/person/PersonTypeBadge.svelte';
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"
						>
							{#if person.personType && person.personType !== 'PERSON'}
								<svg
									class="h-5 w-5"
									fill="none"
									viewBox="0 0 24 24"
									stroke="currentColor"
									stroke-width="2"
								>
									{#if person.personType === 'INSTITUTION'}
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0H5m14 0h2m-2 0v-2M5 21H3m2 0v-2m4-12h2m-2 4h2m4-4h2m-2 4h2"
										/>
									{:else if person.personType === 'GROUP'}
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
										/>
									{:else}
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01"
										/>
									{/if}
								</svg>
							{:else}
								{person.firstName ? person.firstName[0] : person.lastName[0]}{person.lastName[0]}
							{/if}
						</div>

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

						{#if person.personType && person.personType !== 'PERSON'}
							<PersonTypeBadge personType={person.personType} />
						{/if}

						<!-- 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>
