// PresidentValidation.tsx
// Page dédiée au rôle Président pour valider les notes de frais et générer le XML
// Ajouter dans src/pages/ ou src/components/

import { useState, useEffect, useCallback } from 'react';

// ── Types ─────────────────────────────────────────────────────────────────
interface Note {
    id: number;
    reference: string;
    libelle: string;
    montant: number;
    date: string;
    categorie: string;
    statut: string;
    collaborateur: string;
    collaborateurEmail: string;
    departement: string;
    campus: string;
    societe?: string;
    nomN1?: string;
    nomVerificateur?: string;
    dateVerification?: string;
    commentaireVerification?: string;
    lignesJson?: string;
    fichiers?: string;
}

interface HistoriqueXml {
    dateXmlJour: string;
    dateXmlExacte: string;
    nbNotes: number;
    totalMontant: number;
    noteIds: string;
    listeReferences: string;
    presidentNom?: string;
    dateValidationPresident?: string;
    commentairePresident?: string;
}

interface Props {
    apiBaseUrl: string;
    authToken: string;
    user: { prenom: string; nom: string; email: string; roles: string[] };
    onShowToast: (msg: string, type?: string) => void;
}

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

const normalizeCampus = (campus?: string): string => {
    if (!campus) return '';
    const c = campus.toUpperCase();
    if (c.includes('SQY') || c.includes('SAINT')) return 'SQY';
    if (c.includes('CGY') || c.includes('CERGY')) return 'CGY';
    if (c.includes('MRS') || c.includes('MARSEILLE')) return 'MRS';
    if (c.includes('NTE') || c.includes('NANTES')) return 'NTE';
    return campus;
};

// ── Styles ────────────────────────────────────────────────────────────────
const card: React.CSSProperties = {
    background: 'var(--bg-card)',
    borderRadius: 16,
    border: '1px solid var(--border-card)',
    boxShadow: 'var(--shadow-card)',
    overflow: 'hidden',
};

const inputStyle: React.CSSProperties = {
    width: '100%', padding: '10px 14px',
    border: '1.5px solid var(--border-input)', borderRadius: 8,
    background: 'var(--bg-input)', fontFamily: 'inherit',
    fontSize: 14, color: 'var(--text-primary)', outline: 'none',
    boxSizing: 'border-box',
};

const tagStatut = (s: string) => {
    const map: Record<string, { bg: string; color: string; label: string }> = {
        'en_attente_president': { bg: '#ede9fe', color: '#7c3aed', label: '⏳ Attente Président' },
        'paiementenattente': { bg: '#fef9c3', color: '#b45309', label: '🏦 Paiement en attente' },
        'verifie': { bg: '#ede9fe', color: '#7c3aed', label: '🔍 Vérifié' },
        'approuve': { bg: '#dcfce7', color: '#15803d', label: '✅ Approuvé' },
    };
    const k = s?.toLowerCase().trim() ?? '';
    const st = map[k] ?? { bg: '#f1f5f9', color: '#64748b', label: s };
    return (
        <span style={{
            display: 'inline-block', fontSize: 11, fontWeight: 700,
            padding: '3px 10px', borderRadius: 20, whiteSpace: 'nowrap',
            background: st.bg, color: st.color,
        }}>{st.label}</span>
    );
};

// ══════════════════════════════════════════════════════════════════════════
// COMPOSANT PRINCIPAL
// ══════════════════════════════════════════════════════════════════════════
const PresidentValidation = ({ apiBaseUrl, authToken, user, onShowToast }: Props) => {
    const [tab, setTab] = useState<'notes' | 'historique'>('notes');

    // Notes en attente
    const [notes, setNotes] = useState<Note[]>([]);
    const [notesLoading, setNotesLoading] = useState(false);

    // Sélection
    const [selectedIds, setSelectedIds] = useState<number[]>([]);
    const [commentaire, setCommentaire] = useState('');

    // Historique XML
    const [historique, setHistorique] = useState<HistoriqueXml[]>([]);
    const [historiqueLoading, setHistoriqueLoading] = useState(false);

    // XML generation
    const [xmlLoading, setXmlLoading] = useState(false);
    const [xmlFiltreAnnee, setXmlFiltreAnnee] = useState('');
    const [xmlFiltreMois, setXmlFiltreMois] = useState('');

    const hdrs = { Authorization: `Bearer ${authToken}`, 'Content-Type': 'application/json' };

    // ── Chargement des notes ───────────────────────────────────────────
    const loadNotes = useCallback(async () => {
        setNotesLoading(true);
        try {
            const res = await fetch(`${apiBaseUrl}/api/president/notes`, { headers: hdrs });
            const data = await res.json();
            if (res.ok && Array.isArray(data)) setNotes(data);
        } catch { }
        finally { setNotesLoading(false); }
    }, [apiBaseUrl, authToken]);

    // ── Chargement historique ──────────────────────────────────────────
    const loadHistorique = useCallback(async () => {
        setHistoriqueLoading(true);
        try {
            const params = new URLSearchParams();
            if (xmlFiltreAnnee) params.append('annee', xmlFiltreAnnee);
            if (xmlFiltreMois) params.append('mois', xmlFiltreMois);
            const res = await fetch(`${apiBaseUrl}/api/president/historique?${params}`, { headers: hdrs });
            const data = await res.json();
            if (res.ok && Array.isArray(data)) setHistorique(data);
        } catch { }
        finally { setHistoriqueLoading(false); }
    }, [apiBaseUrl, authToken, xmlFiltreAnnee, xmlFiltreMois]);

    useEffect(() => { loadNotes(); }, [loadNotes]);
    useEffect(() => { if (tab === 'historique') loadHistorique(); }, [tab, loadHistorique]);

    // ── Générer XML ────────────────────────────────────────────────────
    const handleGenererXml = async () => {
        if (!selectedIds.length) return;
        if (!window.confirm(`Valider et générer le virement XML pour ${selectedIds.length} note(s) ?`)) return;

        setXmlLoading(true);
        try {
            const res = await fetch(`${apiBaseUrl}/api/president/generer-xml`, {
                method: 'POST',
                headers: hdrs,
                body: JSON.stringify({ noteIds: selectedIds, commentaire: commentaire.trim() || undefined }),
            });

            if (!res.ok) {
                const e = await res.json();
                if (res.status === 422 && e.details?.length) {
                    alert(`❌ ${e.error}\n\n${e.details.map((d: string) => `• ${d}`).join('\n')}`);
                } else {
                    throw new Error(e.error);
                }
                return;
            }

            // Télécharger le fichier XML
            const blob = await res.blob();
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `virements-ndf-PRESIDENT-${new Date().toISOString().split('T')[0]}.xml`;
            a.click();
            URL.revokeObjectURL(url);

            onShowToast(`✅ XML généré et signé par ${user.prenom} ${user.nom} — ${selectedIds.length} virement(s)`, 'success');
            setSelectedIds([]);
            setCommentaire('');
            await loadNotes();
        } catch (e: any) {
            onShowToast(e.message || 'Erreur lors de la génération', 'error');
        } finally {
            setXmlLoading(false);
        }
    };

    // ── Statistiques ───────────────────────────────────────────────────
    const totalNotes = notes.length;
    const totalMontant = notes.reduce((s, n) => s + (n.montant || 0), 0);
    const totalSelectionne = notes
        .filter(n => selectedIds.includes(n.id))
        .reduce((s, n) => s + (n.montant || 0), 0);

    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

            {/* ── BANDEAU IDENTITÉ PRÉSIDENT ── */}
            <div style={{
                display: 'flex', alignItems: 'center', gap: 20,
                padding: '20px 28px',
                background: 'linear-gradient(135deg,#0f172a 0%,#1e3a5f 50%,#1d4ed8 100%)',
                borderRadius: 16, position: 'relative', overflow: 'hidden',
            }}>
                {/* Décoration fond */}
                <div style={{
                    position: 'absolute', right: -40, top: -40,
                    width: 200, height: 200, borderRadius: '50%',
                    background: 'rgba(99,102,241,0.15)', pointerEvents: 'none',
                }} />
                <div style={{
                    width: 56, height: 56, borderRadius: 16,
                    background: 'rgba(255,255,255,0.15)', backdropFilter: 'blur(8px)',
                    border: '2px solid rgba(255,255,255,0.3)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 28, flexShrink: 0,
                }}>
                    💼
                </div>
                <div>
                    <div style={{ color: 'rgba(255,255,255,0.6)', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '1px', marginBottom: 4 }}>
                        Espace Président — Validation des virements
                    </div>
                    <div style={{ color: '#fff', fontSize: 18, fontWeight: 800 }}>
                        {user.prenom} {user.nom}
                    </div>
                    <div style={{ color: 'rgba(255,255,255,0.65)', fontSize: 12, marginTop: 2 }}>
                        Votre validation est requise avant tout virement bancaire
                    </div>
                </div>
                {/* Badge compte notes en attente */}
                {totalNotes > 0 && (
                    <div style={{ marginLeft: 'auto', textAlign: 'right', flexShrink: 0 }}>
                        <div style={{
                            background: '#ef4444', color: '#fff',
                            fontSize: 22, fontWeight: 900,
                            padding: '8px 18px', borderRadius: 12,
                            display: 'inline-block',
                        }}>
                            {totalNotes}
                        </div>
                        <div style={{ color: 'rgba(255,255,255,0.6)', fontSize: 11, marginTop: 4 }}>
                            en attente
                        </div>
                    </div>
                )}
            </div>

            {/* ── ONGLETS ── */}
            <div style={{ display: 'flex', gap: 0, borderBottom: '2px solid var(--border-divider)' }}>
                {[
                    { id: 'notes', icon: '📋', label: `Notes à valider${totalNotes > 0 ? ` (${totalNotes})` : ''}` },
                    { id: 'historique', icon: '📅', label: 'Historique de mes validations' },
                ].map(t => (
                    <button
                        key={t.id}
                        onClick={() => setTab(t.id as any)}
                        style={{
                            padding: '12px 24px',
                            border: 'none', borderBottom: tab === t.id ? '2px solid #1d4ed8' : '2px solid transparent',
                            marginBottom: -2, cursor: 'pointer', fontFamily: 'inherit',
                            fontSize: 13, fontWeight: tab === t.id ? 800 : 500,
                            color: tab === t.id ? '#1d4ed8' : 'var(--text-muted)',
                            background: 'transparent', transition: 'all 0.15s',
                        }}>
                        {t.icon} {t.label}
                    </button>
                ))}
            </div>

            {/* ════════════════════════════════════════
                ONGLET 1 : NOTES À VALIDER
            ════════════════════════════════════════ */}
            {tab === 'notes' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

                    {/* ── Stat cards ── */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                        {[
                            { label: 'Notes en attente', value: totalNotes, accent: '#1d4ed8', icon: '📋' },
                            { label: 'Volume total', value: fmt(totalMontant), accent: '#7c3aed', icon: '💰' },
                            { label: 'Sélection', value: `${selectedIds.length} note(s) — ${fmt(totalSelectionne)}`, accent: '#15803d', icon: '✅' },
                        ].map((c, i) => (
                            <div key={i} style={{ ...card, padding: '16px 20px', borderLeft: `4px solid ${c.accent}` }}>
                                <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: 6 }}>
                                    {c.icon} {c.label}
                                </div>
                                <div style={{ fontSize: 18, fontWeight: 900, color: c.accent }}>{c.value}</div>
                            </div>
                        ))}
                    </div>

                    {notesLoading ? (
                        <div style={{ ...card, padding: '48px 24px', textAlign: 'center', color: 'var(--text-muted)' }}>
                            ⏳ Chargement des notes...
                        </div>
                    ) : notes.length === 0 ? (
                        <div style={{ ...card, padding: '64px 24px', textAlign: 'center' }}>
                            <div style={{ fontSize: 52, marginBottom: 16 }}>✅</div>
                            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--text-primary)', marginBottom: 8 }}>
                                Aucune note en attente
                            </div>
                            <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>
                                Les notes soumises par le ValidateurFinance apparaîtront ici.
                            </div>
                        </div>
                    ) : (
                        <>
                            {/* ── Barre d'action fixe ── */}
                            <div style={{
                                ...card,
                                padding: '14px 20px',
                                background: 'linear-gradient(90deg,#eff6ff,var(--bg-card))',
                                borderLeft: '4px solid #1d4ed8',
                            }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
                                    {/* Sélectionner tout */}
                                    <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
                                        <input
                                            type="checkbox"
                                            checked={selectedIds.length === notes.length && notes.length > 0}
                                            onChange={e => setSelectedIds(e.target.checked ? notes.map(n => n.id) : [])}
                                            style={{ width: 16, height: 16 }}
                                        />
                                        <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-secondary)' }}>
                                            Tout sélectionner
                                        </span>
                                    </label>

                                    {selectedIds.length > 0 && (
                                        <span style={{ fontSize: 12, color: '#1d4ed8', fontWeight: 600 }}>
                                            · {selectedIds.length} note(s) — {fmt(totalSelectionne)}
                                        </span>
                                    )}

                                    {/* Commentaire optionnel */}
                                    <input
                                        value={commentaire}
                                        onChange={e => setCommentaire(e.target.value)}
                                        placeholder="Commentaire de validation (optionnel)"
                                        style={{ ...inputStyle, flex: 1, minWidth: 200, fontSize: 12, padding: '8px 12px' }}
                                    />

                                    {/* Bouton générer XML */}
                                    <button
                                        disabled={selectedIds.length === 0 || xmlLoading}
                                        onClick={handleGenererXml}
                                        style={{
                                            display: 'flex', alignItems: 'center', gap: 8,
                                            padding: '11px 24px',
                                            background: (selectedIds.length === 0 || xmlLoading)
                                                ? '#e2e8f0'
                                                : 'linear-gradient(135deg,#1d4ed8,#1e40af)',
                                            color: (selectedIds.length === 0 || xmlLoading) ? '#94a3b8' : '#fff',
                                            border: 'none', borderRadius: 10,
                                            cursor: (selectedIds.length === 0 || xmlLoading) ? 'not-allowed' : 'pointer',
                                            fontFamily: 'inherit', fontSize: 13, fontWeight: 800,
                                            boxShadow: selectedIds.length > 0 && !xmlLoading
                                                ? '0 4px 14px rgba(29,78,216,.4)' : 'none',
                                            whiteSpace: 'nowrap',
                                            transition: 'all 0.15s',
                                        }}>
                                        {xmlLoading ? (
                                            <>
                                                <div style={{
                                                    width: 14, height: 14,
                                                    border: '2px solid rgba(0,0,0,0.2)',
                                                    borderTop: '2px solid #64748b',
                                                    borderRadius: '50%',
                                                    animation: 'spin 0.8s linear infinite',
                                                }} />
                                                Génération...
                                            </>
                                        ) : (
                                            <>🏦 Valider et générer XML ({selectedIds.length})</>
                                        )}
                                    </button>
                                </div>
                            </div>

                            {/* ── Tableau des notes ── */}
                            <div style={card}>
                                <div style={{ overflowX: 'auto' }}>
                                    <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 700 }}>
                                        <thead>
                                            <tr style={{ background: 'var(--bg-thead)' }}>
                                                {['', 'Référence', 'Collaborateur', 'Campus', 'Société', 'Libellé', 'Montant', 'Vérificateur', 'Statut'].map(h => (
                                                    <th key={h} style={{
                                                        padding: '11px 14px', textAlign: 'left',
                                                        fontSize: 11, fontWeight: 700,
                                                        color: 'var(--text-muted)', textTransform: 'uppercase',
                                                        letterSpacing: '0.6px', borderBottom: '1px solid var(--border-divider)',
                                                        whiteSpace: 'nowrap',
                                                    }}>{h}</th>
                                                ))}
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {notes.map(note => {
                                                const isChecked = selectedIds.includes(note.id);
                                                return (
                                                    <tr
                                                        key={note.id}
                                                        style={{
                                                            borderTop: '1px solid var(--border-divider)',
                                                            background: isChecked ? '#eff6ff' : undefined,
                                                            cursor: 'pointer', transition: 'background 0.1s',
                                                        }}
                                                        onClick={() => setSelectedIds(isChecked
                                                            ? selectedIds.filter(id => id !== note.id)
                                                            : [...selectedIds, note.id]
                                                        )}
                                                        onMouseEnter={e => { if (!isChecked) e.currentTarget.style.background = 'var(--bg-input)'; }}
                                                        onMouseLeave={e => { e.currentTarget.style.background = isChecked ? '#eff6ff' : ''; }}
                                                    >
                                                        <td style={{ padding: '12px 14px' }}>
                                                            <input
                                                                type="checkbox"
                                                                checked={isChecked}
                                                                onChange={() => { }}
                                                                style={{ width: 16, height: 16, cursor: 'pointer' }}
                                                            />
                                                        </td>
                                                        <td style={{ padding: '12px 14px', fontFamily: 'monospace', fontSize: 12, color: '#1d4ed8', fontWeight: 700, whiteSpace: 'nowrap' }}>
                                                            {note.reference}
                                                        </td>
                                                        <td style={{ padding: '12px 14px' }}>
                                                            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-primary)' }}>{note.collaborateur}</div>
                                                            <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{note.collaborateurEmail}</div>
                                                        </td>
                                                        <td style={{ padding: '12px 14px' }}>
                                                            {note.campus ? (
                                                                <span style={{ background: '#eff6ff', color: '#1d4ed8', padding: '2px 8px', borderRadius: 6, fontSize: 11, fontWeight: 700 }}>
                                                                    {normalizeCampus(note.campus)}
                                                                </span>
                                                            ) : '—'}
                                                        </td>
                                                        <td style={{ padding: '12px 14px', fontSize: 12, color: 'var(--text-muted)' }}>
                                                            {note.societe || '—'}
                                                        </td>
                                                        <td style={{ padding: '12px 14px', fontSize: 13, color: 'var(--text-secondary)', maxWidth: 180 }}>
                                                            <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                                                {note.libelle}
                                                            </div>
                                                            <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 1 }}>
                                                                {note.date ? new Date(note.date).toLocaleDateString('fr-FR') : '—'}
                                                            </div>
                                                        </td>
                                                        <td style={{ padding: '12px 14px', fontWeight: 900, fontSize: 15, color: '#1d4ed8', whiteSpace: 'nowrap' }}>
                                                            {fmt(note.montant)}
                                                        </td>
                                                        <td style={{ padding: '12px 14px' }}>
                                                            {note.nomVerificateur ? (
                                                                <div>
                                                                    <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-secondary)' }}>{note.nomVerificateur}</div>
                                                                    {note.dateVerification && (
                                                                        <div style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 1 }}>
                                                                            {new Date(note.dateVerification).toLocaleDateString('fr-FR')}
                                                                        </div>
                                                                    )}
                                                                </div>
                                                            ) : (
                                                                <span style={{ color: 'var(--text-muted)', fontSize: 12 }}>—</span>
                                                            )}
                                                        </td>
                                                        <td style={{ padding: '12px 14px' }}>
                                                            {tagStatut(note.statut)}
                                                        </td>
                                                    </tr>
                                                );
                                            })}
                                        </tbody>

                                        {/* Pied de tableau : total sélection */}
                                        {selectedIds.length > 0 && (
                                            <tfoot>
                                                <tr style={{ borderTop: '2px solid #1d4ed8', background: '#eff6ff' }}>
                                                    <td colSpan={6} style={{ padding: '10px 14px', fontSize: 12, fontWeight: 700, color: '#1d4ed8', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                                                        Total sélection ({selectedIds.length} note{selectedIds.length > 1 ? 's' : ''})
                                                    </td>
                                                    <td colSpan={3} style={{ padding: '10px 14px', fontSize: 16, fontWeight: 900, color: '#1d4ed8', whiteSpace: 'nowrap' }}>
                                                        {fmt(totalSelectionne)}
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        )}
                                    </table>
                                </div>
                            </div>

                            {/* ── Récap bouton bas ── */}
                            {selectedIds.length > 0 && (
                                <div style={{
                                    ...card,
                                    padding: '18px 24px',
                                    background: 'linear-gradient(135deg,#1e3a5f,#1d4ed8)',
                                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                                    flexWrap: 'wrap', gap: 14,
                                }}>
                                    <div style={{ color: '#fff' }}>
                                        <div style={{ fontSize: 14, fontWeight: 800 }}>
                                            💼 Prêt à valider {selectedIds.length} virement{selectedIds.length > 1 ? 's' : ''}
                                        </div>
                                        <div style={{ fontSize: 12, opacity: 0.8, marginTop: 3 }}>
                                            Montant total : <strong>{fmt(totalSelectionne)}</strong>
                                            {commentaire.trim() && ` · "${commentaire.trim()}"`}
                                        </div>
                                        <div style={{ fontSize: 11, opacity: 0.65, marginTop: 3 }}>
                                            La mention "Validé par le Président {user.prenom} {user.nom}" sera inscrite dans le fichier XML
                                        </div>
                                    </div>
                                    <button
                                        disabled={xmlLoading}
                                        onClick={handleGenererXml}
                                        style={{
                                            display: 'flex', alignItems: 'center', gap: 10,
                                            padding: '14px 32px',
                                            background: '#fff',
                                            color: '#1d4ed8',
                                            border: 'none', borderRadius: 12,
                                            cursor: xmlLoading ? 'not-allowed' : 'pointer',
                                            fontFamily: 'inherit', fontSize: 15, fontWeight: 900,
                                            boxShadow: '0 4px 20px rgba(0,0,0,0.25)',
                                            flexShrink: 0,
                                        }}>
                                        {xmlLoading ? '⏳ Génération...' : '🏦 Valider et générer XML →'}
                                    </button>
                                </div>
                            )}
                        </>
                    )}
                </div>
            )}

            {/* ════════════════════════════════════════
                ONGLET 2 : HISTORIQUE
            ════════════════════════════════════════ */}
            {tab === 'historique' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

                    {/* Filtres */}
                    <div style={{ ...card, padding: '14px 20px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                            <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                                🔍 Filtrer
                            </span>
                            <select
                                value={xmlFiltreAnnee}
                                onChange={e => setXmlFiltreAnnee(e.target.value)}
                                style={{ ...inputStyle, width: 140 }}>
                                <option value="">Toutes les années</option>
                                {[2024, 2025, 2026, 2027].map(a => (
                                    <option key={a} value={String(a)}>{a}</option>
                                ))}
                            </select>
                            <select
                                value={xmlFiltreMois}
                                onChange={e => setXmlFiltreMois(e.target.value)}
                                style={{ ...inputStyle, width: 160 }}>
                                <option value="">Tous les mois</option>
                                {[
                                    ['1', 'Janvier'], ['2', 'Février'], ['3', 'Mars'], ['4', 'Avril'],
                                    ['5', 'Mai'], ['6', 'Juin'], ['7', 'Juillet'], ['8', 'Août'],
                                    ['9', 'Septembre'], ['10', 'Octobre'], ['11', 'Novembre'], ['12', 'Décembre']
                                ].map(([v, l]) => <option key={v} value={v}>{l}</option>)}
                            </select>
                            <button
                                onClick={loadHistorique}
                                style={{
                                    padding: '9px 18px', borderRadius: 8, border: 'none',
                                    background: '#1d4ed8', color: '#fff', cursor: 'pointer',
                                    fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
                                }}>
                                🔄 Actualiser
                            </button>
                        </div>
                    </div>

                    {historiqueLoading ? (
                        <div style={{ ...card, padding: '48px 24px', textAlign: 'center', color: 'var(--text-muted)' }}>
                            ⏳ Chargement...
                        </div>
                    ) : historique.length === 0 ? (
                        <div style={{ ...card, padding: '64px 24px', textAlign: 'center' }}>
                            <div style={{ fontSize: 48, marginBottom: 16 }}>📂</div>
                            <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text-primary)' }}>
                                Aucune validation trouvée
                            </div>
                            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 8 }}>
                                Les virements que vous avez validés apparaîtront ici.
                            </div>
                        </div>
                    ) : (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                            {historique.map((batch, i) => {
                                const dateXml = new Date(batch.dateXmlExacte || batch.dateXmlJour);
                                const dateLabel = dateXml.toLocaleDateString('fr-FR', {
                                    weekday: 'long', day: '2-digit', month: 'long', year: 'numeric'
                                });
                                const heureLabel = dateXml.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });

                                return (
                                    <div key={i} style={card}>
                                        {/* En-tête batch */}
                                        <div style={{
                                            padding: '16px 22px',
                                            background: 'linear-gradient(90deg,#eff6ff,var(--bg-card))',
                                            borderBottom: '1px solid var(--border-divider)',
                                            display: 'flex', alignItems: 'center',
                                            justifyContent: 'space-between', gap: 16, flexWrap: 'wrap',
                                        }}>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                                                <div style={{
                                                    width: 44, height: 44, borderRadius: 12, flexShrink: 0,
                                                    background: 'linear-gradient(135deg,#1d4ed8,#1e40af)',
                                                    display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20,
                                                }}>🏦</div>
                                                <div>
                                                    <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--text-primary)', textTransform: 'capitalize' }}>
                                                        XML du {dateLabel}
                                                    </div>
                                                    <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>
                                                        {heureLabel} · {batch.nbNotes} virement{batch.nbNotes > 1 ? 's' : ''}
                                                    </div>
                                                    {/* Badge Président */}
                                                    <div style={{
                                                        display: 'inline-flex', alignItems: 'center', gap: 6,
                                                        marginTop: 6, padding: '4px 10px',
                                                        background: 'linear-gradient(135deg,#1e3a5f,#1d4ed8)',
                                                        borderRadius: 20, fontSize: 11, color: '#fff', fontWeight: 700,
                                                    }}>
                                                        💼 Validé par le Président {batch.presidentNom || `${user.prenom} ${user.nom}`}
                                                    </div>
                                                    {batch.commentairePresident && (
                                                        <div style={{ fontSize: 11, color: '#6366f1', marginTop: 4, fontStyle: 'italic' }}>
                                                            💬 {batch.commentairePresident}
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                            <div style={{
                                                fontSize: 20, fontWeight: 900, color: '#1d4ed8',
                                                background: '#eff6ff', border: '1.5px solid #bfdbfe',
                                                padding: '8px 18px', borderRadius: 10,
                                            }}>
                                                {fmt(parseFloat(String(batch.totalMontant)) || 0)}
                                            </div>
                                        </div>

                                        {/* Références */}
                                        <div style={{
                                            padding: '10px 22px',
                                            background: 'var(--bg-thead)',
                                            display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
                                        }}>
                                            <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', flexShrink: 0 }}>
                                                Virements :
                                            </span>
                                            {(batch.listeReferences || '').split(', ').slice(0, 8).map((ref, ri) => (
                                                <span key={ri} style={{
                                                    fontSize: 11, fontWeight: 700,
                                                    background: '#eff6ff', color: '#1d4ed8',
                                                    padding: '2px 8px', borderRadius: 6, fontFamily: 'monospace',
                                                }}>
                                                    {ref.trim()}
                                                </span>
                                            ))}
                                            {(batch.listeReferences || '').split(', ').length > 8 && (
                                                <span style={{ fontSize: 11, color: 'var(--text-muted)', fontStyle: 'italic' }}>
                                                    +{(batch.listeReferences || '').split(', ').length - 8} autres
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    )}
                </div>
            )}

            {/* Animation spinner */}
            <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
        </div>
    );
};

export default PresidentValidation;