// ── HELPERS & UTILITAIRES NDF ──────────────────────────────────────────────
import type { LigneNote } from './types';

export const fmt = (n: number) =>
    new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(n || 0);

export function getHT(ttc: number, taux: number): number {
    if (!taux) return ttc;
    return parseFloat((ttc / (1 + taux / 100)).toFixed(2));
}

export function getMontantTVA(ttc: number, taux: number): number {
    return parseFloat((ttc - getHT(ttc, taux)).toFixed(2));
}

export const normalizeStatut = (s?: string): string =>
    s?.trim().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '') ?? '';

export const BAREME_KM: Record<number, { t1: number; t2_a: number; t2_b: number; t3: number; label: string }> = {
    3: { t1: 0.529, t2_a: 0.316, t2_b: 1061, t3: 0.369, label: '3 CV et moins' },
    4: { t1: 0.606, t2_a: 0.340, t2_b: 1330, t3: 0.408, label: '4 CV' },
    5: { t1: 0.636, t2_a: 0.356, t2_b: 1391, t3: 0.427, label: '5 CV' },
    6: { t1: 0.665, t2_a: 0.374, t2_b: 1457, t3: 0.448, label: '6 CV' },
    7: { t1: 0.697, t2_a: 0.394, t2_b: 1512, t3: 0.470, label: '7 CV et plus' },
};

export function getIndemniteKm(kmTotal: number, chevaux: number | string): number {
    const cv = Math.min(Math.max(parseInt(String(chevaux)) || 7, 3), 7) as keyof typeof BAREME_KM;
    const b = BAREME_KM[cv];
    if (kmTotal <= 0) return 0;
    if (kmTotal <= 5000) return parseFloat((kmTotal * b.t1).toFixed(2));
    if (kmTotal <= 20000) return parseFloat((kmTotal * b.t2_a + b.t2_b).toFixed(2));
    return parseFloat((kmTotal * b.t3).toFixed(2));
}

export function getTarifUnitaireKm(kmTotal: number, chevaux: number | string): number {
    if (kmTotal <= 0) return 0;
    return parseFloat((getIndemniteKm(kmTotal, chevaux) / kmTotal).toFixed(4));
}

export function newLigne(date: string): LigneNote {
    return {
        idTemp: crypto.randomUUID(),
        date,
        categorie: '',
        libelle: '',
        montant: '',
        tvaItems: [{ taux: '', montantTTC: '' }],
        tauxTVA: '',
        km: '',
        chevaux: '7',
        description: '',
        files: [],
        participants: [{ nom: '', prenom: '', societe: '' }],
        nombreParticipants: '',
        qrLink: null,
        qrUploaded: false,
        qrNoteRef: '',
    };
}
