/**
 * Formats d'affichage et libellés pré-traduits pour les îlots React.
 * Les îlots n'importent pas @notariat-ci/i18n (tout le dictionnaire serait livré au navigateur) :
 * ils reçoivent leurs textes déjà traduits, avec des modèles « {x} » remplis par `remplir`.
 */
import type { Statut } from '@notariat-ci/annuaire';
import type { Langue } from '@notariat-ci/i18n';

const LOCALES: Readonly<Partial<Record<string, string>>> = { fr: 'fr-CI', en: 'en-GB' };

export function locale(langue: Langue): string {
  return LOCALES[langue] ?? langue;
}

/** « 2 mars 2009 » pour une date ISO AAAA-MM-JJ (sans fuseau). */
export function dateLongue(localeOuLangue: string, iso: string): string {
  const [annee, mois, jour] = iso.split('-').map(Number);
  const date = new Date(Date.UTC(annee ?? 1970, (mois ?? 1) - 1, jour ?? 1));
  return new Intl.DateTimeFormat(LOCALES[localeOuLangue] ?? localeOuLangue, {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
    timeZone: 'UTC',
  }).format(date);
}

/** « 26 novembre 2026 à 08:00 », heure d'Abidjan (UTC+0, sans heure d'été). */
export function dateHeure(localeOuLangue: string, date: Date | string): string {
  return new Intl.DateTimeFormat(LOCALES[localeOuLangue] ?? localeOuLangue, {
    dateStyle: 'long',
    timeStyle: 'short',
    timeZone: 'Africa/Abidjan',
  }).format(typeof date === 'string' ? new Date(date) : date);
}

/** Remplit un modèle déjà traduit : `remplir('Résultats : {n}', { n: 3 })`. */
export function remplir(modele: string, parametres: Record<string, string | number>): string {
  return modele.replace(/\{(\w+)\}/g, (brut, nom: string) =>
    nom in parametres ? String(parametres[nom]) : brut,
  );
}

/** Libellés d'un statut, aux deux genres. */
export interface LibellesStatut {
  masculin: string;
  feminin: string;
}
export type LibellesStatuts = Readonly<Record<Statut, LibellesStatut>>;

/** « 25 000 000 F CFA » (francs CFA, sans décimales). */
export function montantFcfa(localeOuLangue: string, montant: number): string {
  return new Intl.NumberFormat(LOCALES[localeOuLangue] ?? localeOuLangue, {
    style: 'currency',
    currency: 'XOF',
    maximumFractionDigits: 0,
  }).format(montant);
}

/** Taux en parties par million -> « 2,5 » (pour « 2,5 % »). */
export function pourcentage(localeOuLangue: string, tauxPpm: number): string {
  return new Intl.NumberFormat(LOCALES[localeOuLangue] ?? localeOuLangue, {
    maximumFractionDigits: 4,
  }).format(tauxPpm / 10_000);
}
