<script lang="ts">
import type { components } from '$lib/generated/api';
import * as m from '$lib/paraglide/messages.js';

const AVATAR_PALETTE = ['#012851', '#5A3080', '#005F74', '#2A6040', '#803020'] as const;
function djb2(str: string): number {
	let hash = 5381;
	for (let i = 0; i < str.length; i++) hash = (hash * 33) ^ str.charCodeAt(i);
	return Math.abs(hash);
}
function personAvatarColor(id: string): string {
	return AVATAR_PALETTE[djb2(id) % AVATAR_PALETTE.length];
}
function getInitials(name: string): string {
	const words = name.trim().split(/\s+/).filter(Boolean);
	if (words.length === 0) return '';
	if (words.length === 1) return words[0].charAt(0).toUpperCase();
	return (words[0].charAt(0) + words[words.length - 1].charAt(0)).toUpperCase();
}

type PersonSummaryDTO = components['schemas']['PersonSummaryDTO'];

interface Props {
	persons: PersonSummaryDTO[];
}

const { persons }: Props = $props();
</script>

<section aria-label={m.dashboard_reader_person_chips_heading()}>
	{#if persons.length === 0}
		<p class="font-sans text-sm text-ink-3">{m.dashboard_reader_no_persons()}</p>
	{/if}
	<div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
		{#each persons as p (p.id)}
			<a
				href="/persons/{p.id}"
				class="group flex min-h-[44px] flex-col items-center gap-2 rounded border border-line bg-surface px-4 py-6 text-center no-underline shadow-sm transition-all duration-200 hover:border-l-4 hover:border-accent hover:shadow-md focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:outline-none"
			>
				<span
					class="flex h-12 w-12 shrink-0 items-center justify-center rounded-full text-base font-bold text-white shadow-sm dark:shadow-none dark:ring-1 dark:ring-white/10"
					style="background-color: {personAvatarColor(p.id ?? '')}"
				>
					{getInitials(p.displayName ?? p.lastName ?? '')}
				</span>
				<span class="truncate font-serif text-sm font-bold text-ink group-hover:underline"
					>{p.displayName ?? p.lastName}</span
				>
				{#if (p.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"
					>
						{p.documentCount}
					</span>
				{/if}
			</a>
		{/each}
	</div>
	<a
		href="/persons"
		class="mt-1 flex min-h-[44px] items-center justify-end text-right text-xs font-semibold text-ink-2 no-underline focus-visible:ring-2 focus-visible:ring-brand-navy focus-visible:outline-none"
		>{m.dashboard_reader_all_persons()}</a
	>
</section>
