<script lang="ts">
import { untrack } from 'svelte';
import { radioGroupNav } from '$lib/shared/actions/radioGroupNav';
import { m } from '$lib/paraglide/messages.js';
import { PERSON_TYPES as TYPES, type PersonType } from '$lib/person/person-validation';

let {
	value = 'PERSON',
	name = 'personType',
	onchange
}: { value?: string; name?: string; onchange?: (type: PersonType) => void } = $props();

let selected = $state<PersonType>(
	untrack(() => (TYPES.includes(value as PersonType) ? (value as PersonType) : 'PERSON'))
);

let announcement = $state('');

const labels: Record<PersonType, () => string> = {
	PERSON: m.person_type_PERSON,
	INSTITUTION: m.person_type_INSTITUTION,
	GROUP: m.person_type_GROUP,
	UNKNOWN: m.person_type_UNKNOWN
};

function select(type: PersonType) {
	selected = type;
	announcement = m.a11y_type_changed({ type: labels[type]() });
	onchange?.(type);
}
</script>

<div
	role="radiogroup"
	aria-label={m.form_label_person_type()}
	class="grid grid-cols-2 gap-2 sm:grid-cols-4"
	use:radioGroupNav={(v) => { if (TYPES.includes(v as PersonType)) select(v as PersonType); }}
>
	{#each TYPES as type (type)}
		<button
			type="button"
			role="radio"
			value={type}
			aria-checked={selected === type}
			tabindex={selected === type ? 0 : -1}
			onclick={() => select(type)}
			class="min-h-[48px] cursor-pointer rounded-sm border px-3 py-2 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:ring-focus-ring focus-visible:outline-none {selected === type
				? 'border-primary bg-primary text-primary-fg'
				: 'border-line bg-surface text-ink hover:border-primary/50'}"
		>
			{labels[type]()}
		</button>
	{/each}
</div>

<input type="hidden" name={name} value={selected} />

<div class="sr-only" aria-live="polite" aria-atomic="true">{announcement}</div>
