'use client'; import { X } from 'lucide-react'; import { usePathname, useRouter, useSearchParams } from 'next/navigation'; import { useEffect, useMemo, useState } from 'react'; import { t } from '@/i18n'; import { clientCompare } from '@/lib/client-api-compare'; import type { CountryLite, RankHistoryResponse } from '@/lib/types-compare'; import { seriesVar } from '@/components/charts/palette'; import { CountryTypeahead } from '@/components/compare/country-picker'; import { RankHistoryChart, type RankSeries } from './rank-history-chart'; export const MAX_HISTORY = 5; /** * "Rank over time" panel: up to 5 countries (default top 3 + highlighted), rank-by-year chart. The selection is * written to `?history=ISO3,ISO3` (router.replace); new selections fetch `/rankings/{slug}/history` client-side. */ export function RankHistoryPanel({ slug, countries, initialIds, initial }: { slug: string; countries: CountryLite[]; initialIds: string[]; initial: RankHistoryResponse | null }) { const router = useRouter(); const pathname = usePathname(); const params = useSearchParams(); const [ids, setIds] = useState(initialIds); const [data, setData] = useState(initial); const [loading, setLoading] = useState(false); const byId = useMemo(() => new Map(countries.map((c) => [c.id, c])), [countries]); const exclude = useMemo(() => new Set(ids.map((id) => byId.get(id)?.slug ?? id.toLowerCase())), [ids, byId]); useEffect(() => { const key = ids.join(','); const have = data ? data.countries.map((c) => c.id).join(',') : ''; if (!ids.length || key === have) return; const ctrl = new AbortController(); setLoading(true); clientCompare .rankHistory(slug, ids, ctrl.signal) .then((r) => setData(r)) .catch((e) => { if ((e as Error).name !== 'AbortError') setData(null); }) .finally(() => setLoading(false)); return () => ctrl.abort(); }, [ids, slug, data]); const apply = (next: string[]) => { setIds(next); const p = new URLSearchParams(params.toString()); if (next.length) p.set('history', next.join(',')); else p.delete('history'); const s = p.toString(); router.replace(`${pathname}${s ? `?${s}` : ''}`, { scroll: false }); }; const series: RankSeries[] = ids.map((id, i) => { const c = byId.get(id) ?? data?.countries.find((x) => x.id === id); const pts = (data?.series[id] ?? []).filter((p) => p.rank != null).map((p) => ({ year: p.year, rank: p.rank!, n: p.n })); return { id, name: c?.name ?? id, flag: c?.flag ?? null, colorIndex: i, points: pts }; }); return (
{ids.map((id, i) => { const c = byId.get(id); return ( {c?.flag} {c?.name ?? id} ); })} {ids.length < MAX_HISTORY ? apply([...ids, c.id])} placeholder={t('ranking.history.pick')} className="w-full sm:w-64" /> : {t('ranking.history.full', { max: MAX_HISTORY })}}
{ids.length === 0 ?

{t('ranking.history.empty')}

: }
); }