<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { untrack } from 'svelte';
import { SvelteURLSearchParams } from 'svelte/reactivity';
import { m } from '$lib/paraglide/messages.js';
import PersonCard from '$lib/person/PersonCard.svelte';
import PersonFilterBar from '$lib/person/PersonFilterBar.svelte';
import Pagination from '$lib/shared/primitives/Pagination.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>;

// Debounced search must preserve the active filters/review flag — compose over the live URL,
// never a bare `?q=` that would wipe page/type/review.
function handleSearch() {
	clearTimeout(searchTimeout);
	searchTimeout = setTimeout(() => {
		const params = new SvelteURLSearchParams(page.url.searchParams);
		params.delete('page');
		if (q) params.set('q', q);
		else params.delete('q');
		const qs = params.toString();
		goto(qs ? `/persons?${qs}` : '/persons', { keepFocus: true });
	}, 300);
}

// Pagination links preserve every active param and only change the page index.
function buildPageHref(targetPage: number): string {
	const params = new SvelteURLSearchParams(page.url.searchParams);
	params.set('page', String(targetPage));
	return `/persons?${params.toString()}`;
}

const hasResults = $derived(data.persons.length > 0);
const noFiltersActive = $derived(
	!data.q && !data.filters.type && !data.filters.familyOnly && !data.filters.hasDocuments
);
</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-6 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">{m.persons_search_placeholder()}</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>

			<!-- Triage link (transcriber only) -->
			{#if data.canWrite}
				<a
					href="/persons/review"
					class="inline-flex min-h-[44px] items-center gap-1.5 rounded-sm border border-line bg-surface px-4 py-2 font-sans text-sm font-semibold text-ink transition-colors hover:bg-muted"
				>
					{m.persons_toggle_needs_review({ count: data.needsReviewCount })}
				</a>
			{/if}

			<!-- New person CTA -->
			{#if data.canWrite}
				<a
					href="/persons/new"
					class="inline-flex min-h-[44px] 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>

	<!-- Filter chips + show-all toggle -->
	<div class="mb-8">
		<PersonFilterBar
			type={data.filters.type}
			familyOnly={data.filters.familyOnly}
			hasDocuments={data.filters.hasDocuments}
			review={data.filters.review}
			needsReviewCount={data.needsReviewCount}
			canWrite={data.canWrite}
		/>
	</div>

	{#if !hasResults}
		{#if noFiltersActive}
			<PersonsEmptyState />
		{:else}
			<div
				class="flex flex-col items-center justify-center rounded-lg border border-dashed border-line bg-surface py-16 text-center"
			>
				<p class="font-serif text-lg text-ink">{m.persons_empty_filtered()}</p>
			</div>
		{/if}
	{:else}
		<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
			{#each data.persons as person (person.id)}
				<PersonCard person={person} />
			{/each}
		</div>

		<Pagination page={data.pageNumber} totalPages={data.totalPages} makeHref={buildPageHref} />
	{/if}
</div>
