<script lang="ts">
import * as m from '$lib/paraglide/messages.js';

export type FilterValue = 'alle' | 'fuer-dich' | 'hochgeladen' | 'transkription' | 'kommentare';

interface Props {
	value: FilterValue;
	onChange: (v: FilterValue) => void;
}

const { value, onChange }: Props = $props();

type Pill = { value: FilterValue; label: () => string };

const pills: Pill[] = [
	{ value: 'alle', label: () => m.chronik_filter_all() },
	{ value: 'fuer-dich', label: () => m.chronik_filter_for_you() },
	{ value: 'hochgeladen', label: () => m.chronik_filter_uploaded() },
	{ value: 'transkription', label: () => m.chronik_filter_transcription() },
	{ value: 'kommentare', label: () => m.chronik_filter_comments() }
];

let container: HTMLDivElement | undefined = $state();

function moveFocus(direction: 1 | -1, fromValue: FilterValue): void {
	if (!container) return;
	const idx = pills.findIndex((p) => p.value === fromValue);
	if (idx === -1) return;
	const nextIdx = (idx + direction + pills.length) % pills.length;
	const nextValue = pills[nextIdx].value;
	const target = container.querySelector<HTMLButtonElement>(`[data-filter-value="${nextValue}"]`);
	target?.focus();
}

function handleKeydown(e: KeyboardEvent, v: FilterValue): void {
	if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
		e.preventDefault();
		moveFocus(1, v);
	} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
		e.preventDefault();
		moveFocus(-1, v);
	}
}
</script>

<div
	bind:this={container}
	role="radiogroup"
	aria-label={m.chronik_filter_label()}
	class="flex flex-wrap gap-2"
>
	{#each pills as p (p.value)}
		{@const active = p.value === value}
		<button
			type="button"
			role="radio"
			aria-checked={active}
			tabindex={active ? 0 : -1}
			data-filter-value={p.value}
			onclick={() => onChange(p.value)}
			onkeydown={(e) => handleKeydown(e, p.value)}
			class="inline-flex min-h-[44px] items-center rounded-sm px-4 py-2 font-sans text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:ring-focus-ring focus-visible:outline-none
				{active ? 'bg-primary text-primary-fg' : 'bg-muted text-ink hover:bg-muted/80'}"
		>
			{p.label()}
		</button>
	{/each}
</div>
