<script lang="ts">
import { onMount, tick } from 'svelte';
import PersonTypeahead from '$lib/person/PersonTypeahead.svelte';
import { m } from '$lib/paraglide/messages.js';

interface RecentPerson {
	id: string;
	name: string;
}

interface Props {
	onSelectPerson: (id: string) => void;
	recentPersons?: RecentPerson[];
}

const { onSelectPerson, recentPersons = [] }: Props = $props();

let senderId = $state('');
let typeaheadEl: HTMLDivElement | undefined = $state();

onMount(async () => {
	await tick();
	typeaheadEl?.querySelector<HTMLInputElement>('input[type="text"]')?.focus();
});

function handlePersonChange(id: string) {
	if (id) {
		onSelectPerson(id);
	}
}
</script>

<div
	data-testid="conv-hero"
	class="mx-auto flex max-w-lg flex-col items-center gap-6 py-12 text-center sm:py-20"
>
	<!-- Discovery headline -->
	<h1 class="font-serif text-2xl font-black text-ink">
		{m.conv_empty_heading()}
	</h1>

	<!-- Cross-link to document search -->
	<a href="/" class="text-sm text-ink-3 transition-colors hover:text-primary">
		{m.conv_hero_crosslink()}
	</a>

	<!-- Person typeahead (large, hero-sized) -->
	<div class="w-full max-w-sm" bind:this={typeaheadEl}>
		<PersonTypeahead
			name="senderId"
			label="Person"
			large={true}
			bind:value={senderId}
			onchange={handlePersonChange}
		/>
	</div>

	<!-- Recent persons -->
	{#if recentPersons.length > 0}
		<div class="flex w-full max-w-sm items-center gap-2">
			<div class="flex-1 border-t border-line"></div>
			<span class="text-xs font-bold tracking-wider text-ink-3 uppercase"
				>{m.conv_hero_divider()}</span
			>
			<div class="flex-1 border-t border-line"></div>
		</div>

		<div class="flex w-full max-w-sm flex-col items-center gap-3">
			<span class="text-xs font-bold tracking-widest text-ink-3 uppercase">
				{m.conv_empty_recent_label()}
			</span>
			<div class="flex flex-wrap justify-center gap-2">
				{#each recentPersons as person (person.id)}
					<button
						type="button"
						data-testid="recent-person-{person.id}"
						onclick={() => onSelectPerson(person.id)}
						class="flex items-center gap-2 rounded-full border border-line bg-surface px-4 py-2 text-sm font-bold text-ink transition-colors hover:border-primary hover:text-primary"
					>
						<span
							class="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-xs text-primary-fg"
							aria-hidden="true"
						>
							{person.name.charAt(0).toUpperCase()}
						</span>
						{person.name}
					</button>
				{/each}
			</div>
		</div>
	{/if}
</div>
