'use client';
import Link from 'next/link';
import { t } from '@/i18n';
import { formatValue, grouped, ordinal } from '@/lib/format';
import { routes } from '@/lib/site';
import type { FormatSpec } from '@/lib/types';
import type { StoryItem, StoryResponse } from '@/lib/types-analytics';
import { LineChart } from '@/components/charts/line-chart';
import { useProvenance } from '@/components/data/provenance-context';
/**
* "How {name} changed": one small multiple per long-run indicator (full annual history), the templated sentence
* computed server-side underneath, first/last labels, peak/trough and rank change. Every chart opens provenance.
*/
export function CountryStory({ data, country }: { data: StoryResponse; country: { id: string; slug: string | null; name: string; flag?: string | null } }) {
const { open } = useProvenance();
if (!data.items.length) return
{t('country.story.none')}
;
return (
{data.items.map((it) => (
open({ indicator: { slug: it.indicator.slug, name: it.indicator.name ?? it.indicator.slug, format: it.indicator.format, unit: it.indicator.unit, unit_short: it.indicator.unit_short, precision: it.indicator.precision, frequency: it.indicator.frequency, higher_is_better: it.indicator.higher_is_better }, value: { value: it.last.value, formatted: it.last.formatted, period: `${it.last.year}-01-01`, year: it.last.year, unit: it.indicator.unit, provenance: it.provenance }, country })} />
))}
);
}
function StoryCell({ it, country, onProvenance }: { it: StoryItem; country: { slug: string | null }; onProvenance: () => void }) {
const spec: FormatSpec = { format: it.indicator.format, unit: it.indicator.unit, unit_short: it.indicator.unit_short, precision: it.indicator.precision, name: it.indicator.short_name ?? it.indicator.name, higher_is_better: it.indicator.higher_is_better };
const points = it.series.map(([year, value]) => ({ period: `${year}-01-01`, year, value }));
const up = (it.change_abs ?? 0) >= 0;
const title = it.indicator.short_name ?? it.indicator.name ?? it.indicator.slug;
return (
{title}
{it.change_pct != null && Math.abs(it.change_pct) < 10000 && ['currency', 'number', 'tonnes', 'kwh'].includes(it.indicator.format ?? '') ? `${up ? '+' : '−'}${grouped(Math.abs(it.change_pct))} %` : it.change_abs != null ? `${up ? '+' : '−'}${formatValue(Math.abs(it.change_abs), { ...spec, format: spec.format === 'percent' ? 'percent' : spec.format }).replace(/^(US\$|intl \$)/, '$1')}` : ''}
{it.first.year} · {it.first.formatted ?? formatValue(it.first.value, spec)}
{it.last.year} · {it.last.formatted ?? formatValue(it.last.value, spec)}
{it.peak && it.peak.year !== it.last.year ? `${t('country.story.peak', { value: formatValue(it.peak.value, spec), year: it.peak.year })}` : ''}
{it.rank_first && it.rank_last ? `${it.peak && it.peak.year !== it.last.year ? ' · ' : ''}${t('country.story.rank', { r0: ordinal(it.rank_first.rank), y0: it.rank_first.year, r1: ordinal(it.rank_last.rank), n: it.rank_last.n, y1: it.rank_last.year })}` : ''}
);
}