import { cache } from "react"; import { api } from "@/lib/api"; import { routes } from "@/lib/routes"; /** iso2 → canonical country slug (from /countries?all=1), memoised per request. */ export const countrySlugMap = cache(async (): Promise> => { const r = await api.countries({ all: 1 }); const m = new Map(); for (const c of r.items) m.set(c.iso2.toUpperCase(), c.slug); return m; }); /** Fallback slug when the registry is unreachable: ASCII-folded, hyphenated name (matches the API's slugs for most countries). */ export function slugifyCountryName(name: string | null | undefined, iso2: string): string { if (!name) return iso2.toLowerCase(); const folded = name .normalize("NFD") .replace(/[̀-ͯ]/g, "") .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/(^-|-$)/g, ""); return folded || iso2.toLowerCase(); } /** Href of the country page for an iso2 (canonical slug when known). */ export async function countryHref(iso2: string | null | undefined, name?: string | null): Promise { if (!iso2) return null; const m = await countrySlugMap(); return routes.country(m.get(iso2.toUpperCase()) ?? slugifyCountryName(name, iso2)); }