<script lang="ts">
import * as m from '$lib/paraglide/messages.js';
import { getLocale } from '$lib/paraglide/runtime.js';
import { formatTickLabel } from '$lib/shared/utils/monthBuckets';
import Sparkline from '$lib/shared/primitives/Sparkline.svelte';
import GlyphLabel from './GlyphLabel.svelte';
import LetterCard from './LetterCard.svelte';
import { monthHistogram } from './timelineDensity';
import type { components } from '$lib/generated/api';

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

/**
 * Compact density view for a year with many letters (REQ-012): the letter count
 * plus a 12-month density sparkline, and a ≥44px keyboard-focusable toggle that
 * expands to that year's individual LetterCards. The count carries a ✉ glyph and
 * the sparkline is captioned with its month-density meaning and Jan/Dez endpoint
 * labels (REQ-010/011).
 */
let { letters, year }: { letters: TimelineEntryDTO[]; year: number } = $props();

let expanded = $state(false);

const counts = $derived(monthHistogram(letters, year).map((b) => b.count));
// Two endpoint month labels only (not one per bar). Pass the Jan/Dez anchors so
// the locale formatter returns a month (a bare "{year}" returns just the year).
const janLabel = $derived(formatTickLabel(`${year}-01`, getLocale()));
const dezLabel = $derived(formatTickLabel(`${year}-12`, getLocale()));
</script>

<div class="mx-auto max-w-md rounded-sm border border-line bg-surface p-3 shadow-sm">
	<div class="flex items-center justify-between gap-3">
		<span class="font-sans text-sm font-bold text-brand-navy">
			<GlyphLabel glyph="✉" label={m.timeline_letter_glyph_label()} />
			{m.timeline_letters_count({ count: letters.length })}
		</span>
		<button
			type="button"
			data-testid="strip-expand"
			aria-expanded={expanded}
			onclick={() => (expanded = !expanded)}
			style="display: inline-flex; align-items: center; min-height: 44px"
			class="rounded-sm px-2 font-sans text-xs text-ink-3 hover:text-brand-navy focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-navy"
		>
			{m.timeline_strip_expand()}
		</button>
	</div>

	<Sparkline
		values={counts}
		label={m.timeline_letters_count({ count: letters.length })}
		class="mt-2"
	/>

	<!-- Two endpoint month labels + the density caption, beneath the sparkline
	     (REQ-010/011). 10px is the floor for this micro-axis (the spec's 6px is
	     below this project's legibility floor for the 60+ transcriber audience). -->
	<div class="mt-1 flex items-center justify-between gap-2 font-sans text-[10px] text-ink-3">
		<span data-testid="strip-axis-label">{janLabel}</span>
		<span>{m.timeline_strip_density_caption()}</span>
		<span data-testid="strip-axis-label">{dezLabel}</span>
	</div>

	{#if expanded}
		<ul class="mt-3 space-y-2">
			{#each letters as letter (letter.documentId)}
				<li><LetterCard entry={letter} /></li>
			{/each}
		</ul>
	{/if}
</div>
