import React, { useState, useEffect } from 'react';
import { X, AlertCircle, CheckCircle, Calendar, TrendingDown } from 'lucide-react';

const NewLeaveRequestModal = ({
    onClose,
    userId,
    userEmail,
    userName,
    onRequestSubmitted,
    preselectedStartDate = null,
    preselectedEndDate = null,
    preselectedType = null,
    userRole,
}) => {
    const [formData, setFormData] = useState({
        types: preselectedType ? [preselectedType] : ['CP'],
        startDate: preselectedStartDate || '',
        endDate: preselectedEndDate || '',
        periodeDebut: 'Journée entière',
        periodeFin: 'Journée entière',
        reason: ''
    });

    const [repartitionDetails, setRepartitionDetails] = useState({});
    const [countersData, setCountersData] = useState(null);
    const [isLoadingCounters, setIsLoadingCounters] = useState(true);
    const [totalDays, setTotalDays] = useState(0);
    const [saturdayCount, setSaturdayCount] = useState(0);
    const [holidayCount, setHolidayCount] = useState(0);
    const [error, setError] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [publicHolidays, setPublicHolidays] = useState({});
    const [previsionnel, setPrevisionnel] = useState(null);
    const [isLoadingPrev, setIsLoadingPrev] = useState(false);

    const [simulationDate, setSimulationDate] = useState(null);
    const [isLoadingSimul, setIsLoadingSimul] = useState(false);

    const [simulationRTT, setSimulationRTT] = useState(null);
    const [isLoadingSimulRTT, setIsLoadingSimulRTT] = useState(false);

    // ── Jours fériés ─────────────────────────────────────────────────────
    useEffect(() => {
        const fetchPublicHolidays = async () => {
            try {
                const y = new Date().getFullYear();
                const [cur, nxt] = await Promise.all([
                    fetch(`https://calendrier.api.gouv.fr/jours-feries/metropole/${y}.json`).then(r => r.json()),
                    fetch(`https://calendrier.api.gouv.fr/jours-feries/metropole/${y + 1}.json`).then(r => r.json()),
                ]);
                setPublicHolidays({ ...cur, ...nxt });
            } catch (e) { console.error('❌ Erreur jours fériés:', e); }
        };
        fetchPublicHolidays();
    }, []);

    const isPublicHoliday = (date) => date.toISOString().split('T')[0] in publicHolidays;

    const isWeekend = (dateString) => {
        if (!dateString) return false;
        const d = new Date(dateString).getDay();
        return d === 0 || d === 6;
    };

    const getNextWorkingDay = (dateString) => {
        const d = new Date(dateString);
        const day = d.getDay();
        if (day === 5) d.setDate(d.getDate() + 3);
        else if (day === 6) d.setDate(d.getDate() + 2);
        else if (day === 0) d.setDate(d.getDate() + 1);
        return d.toISOString().split('T')[0];
    };

    // ── Compteurs ─────────────────────────────────────────────────────────
    useEffect(() => {
        if (!userId) return;
        setIsLoadingCounters(true);
        fetch(`/api/getDetailedLeaveCounters?user_id=${userId}`)
            .then(r => r.json())
            .then(data => { if (data.success && data.data) setCountersData(data); })
            .catch(e => console.error('❌ Erreur compteurs:', e))
            .finally(() => setIsLoadingCounters(false));
    }, [userId]);

    // ── Simulation CP ─────────────────────────────────────────────────────
    useEffect(() => {
        const fetchSimulation = async () => {
            if (!formData.startDate || !userId || !formData.types.includes('CP')) {
                setSimulationDate(null);
                return;
            }
            setIsLoadingSimul(true);
            try {
                const res = await fetch(`/api/simulation-solde-cp?userid=${userId}&date=${formData.startDate}`);
                if (!res.ok) { setSimulationDate(null); return; }
                const data = await res.json();
                if (data.success) {
                    setSimulationDate(data);
                } else {
                    setSimulationDate(null);
                }
            } catch (e) {
                console.error('❌ Erreur simulation CP:', e);
                setSimulationDate(null);
            } finally {
                setIsLoadingSimul(false);
            }
        };
        fetchSimulation();
    }, [formData.startDate, userId]);

    // ── Simulation RTT ────────────────────────────────────────────────────
    useEffect(() => {
        const fetchSimulationRTT = async () => {
            if (!formData.startDate || !userId || !formData.types.includes('RTT')) {
                setSimulationRTT(null);
                return;
            }
            setIsLoadingSimulRTT(true);
            try {
                const res = await fetch(`/api/simulation-solde-rtt?userid=${userId}&date=${formData.startDate}`);
                if (!res.ok) { setSimulationRTT(null); return; }
                const data = await res.json();
                if (data.success) {
                    setSimulationRTT(data);
                } else {
                    setSimulationRTT(null);
                }
            } catch (e) {
                console.error('❌ Erreur simulation RTT:', e);
                setSimulationRTT(null);
            } finally {
                setIsLoadingSimulRTT(false);
            }
        };
        fetchSimulationRTT();
    }, [formData.startDate, userId, formData.types]);

    // ── Calcul jours ouvrés (brut, sans demi-journées) ───────────────────
    useEffect(() => {
        if (!formData.startDate || !formData.endDate) return;
        const start = new Date(formData.startDate);
        const end = new Date(formData.endDate);
        let working = 0, sats = 0, hols = 0;
        const cur = new Date(start);
        while (cur <= end) {
            const day = cur.getDay();
            if (isPublicHoliday(cur)) hols++;
            else if (day === 6) sats++;
            else if (day !== 0) working++;
            cur.setDate(cur.getDate() + 1);
        }
        setTotalDays(working);
        setSaturdayCount(sats);
        setHolidayCount(hols);
    }, [formData.startDate, formData.endDate, publicHolidays]);

    // ── Reset répartition si les types changent ───────────────────────────
    useEffect(() => {
        setRepartitionDetails(prev => {
            const next = {};
            formData.types.forEach((t, idx) => {
                const seg = prev[t] || {};
                if (seg.dateDebut && seg.dateFin) {
                    const isFirst = idx === 0;
                    const isLast = idx === formData.types.length - 1;
                    const prevSegType = idx > 0 ? formData.types[idx - 1] : null;
                    const prevSegPeriodeFin = prevSegType ? (next[prevSegType]?.periodeFin || 'Journée entière') : 'Journée entière';
                    const prevSegDateFin = prevSegType ? next[prevSegType]?.dateFin : null;
                    const curSegDateDebut = seg.dateDebut;
                    const startsOnSameDay = prevSegDateFin && curSegDateDebut && prevSegDateFin === curSegDateDebut;
                    const debut = isFirst
                        ? formData.periodeDebut
                        : (startsOnSameDay && prevSegPeriodeFin === 'Matin')
                            ? 'Après-midi'
                            : 'Journée entière';

                    const nextType = formData.types[idx + 1];
                    const nextDateDebut = next[nextType]?.dateDebut;
                    const nextStartsSameDay = nextDateDebut && next[t]?.dateFin && nextDateDebut === next[t]?.dateFin;
                    const fin = isLast
                        ? formData.periodeFin
                        : (seg.periodeFin || (nextStartsSameDay ? 'Matin' : 'Journée entière'));

                    const jours = calcWorkingDays(seg.dateDebut, seg.dateFin, debut, fin);
                    next[t] = { ...seg, jours: jours.toString() };
                }
            });
            return next;
        });
    }, [formData.types, formData.startDate, formData.endDate]);

    // ── Auto-remplissage des segments suivants ────────────────────────────
    useEffect(() => {
        const sameDayMixte = formData.startDate && formData.endDate && formData.startDate === formData.endDate;
        if (!isMixte || sameDayMixte) return;
        setRepartitionDetails(prev => {
            const next = { ...prev };
            formData.types.forEach((t, idx) => {
                if (idx === 0) return;
                const prevType = formData.types[idx - 1];
                const prevDateFin = next[prevType]?.dateFin;
                if (!prevDateFin) return;
                const prevPeriodeFin = next[prevType]?.periodeFin || 'Journée entière';
                let suggestedDebut;
                let suggestedDebutPeriode;
                if (prevPeriodeFin === 'Matin') {
                    suggestedDebut = prevDateFin;
                    suggestedDebutPeriode = 'Après-midi';
                } else {
                    const d = new Date(prevDateFin);
                    d.setDate(d.getDate() + 1);
                    while (d.getDay() === 0 || d.getDay() === 6 || d.toISOString().split('T')[0] in publicHolidays) {
                        d.setDate(d.getDate() + 1);
                    }
                    suggestedDebut = d.toISOString().split('T')[0];
                    suggestedDebutPeriode = 'Journée entière';
                }
                const suggestedFin = formData.endDate;
                if (!next[t]?.dateDebut && !next[t]?.dateFin) {
                    const isLast = idx === formData.types.length - 1;
                    const fin = isLast ? formData.periodeFin : 'Journée entière';
                    const jours = calcWorkingDays(suggestedDebut, suggestedFin, suggestedDebutPeriode, fin);
                    next[t] = { ...next[t], dateDebut: suggestedDebut, dateFin: suggestedFin, jours: jours.toString() };
                }
            });
            return next;
        });
    }, [
        formData.types.length > 1 ? repartitionDetails[formData.types[0]]?.dateFin : null,
        formData.endDate,
        publicHolidays
    ]);

    // ── Recalcul automatique des jours par segment (avec demi-journées) ───
    useEffect(() => {
        const sameDayMixte = formData.startDate && formData.endDate && formData.startDate === formData.endDate && isMixte;
        if (!isMixte || Object.keys(publicHolidays).length === 0 || sameDayMixte) return;
        setRepartitionDetails(prev => {
            const next = { ...prev };
            formData.types.forEach((t, idx) => {
                const seg = next[t] || {};
                if (seg.dateDebut && seg.dateFin) {
                    const isFirst = idx === 0;
                    const isLast = idx === formData.types.length - 1;
                    let debutAuto = 'Journée entière';
                    if (!isFirst) {
                        const prevType = formData.types[idx - 1];
                        const prevSeg = next[prevType] || {};
                        const prevEndsAtMatin = (prevSeg.periodeFin || 'Journée entière') === 'Matin';
                        const startsOnSameDay = prevSeg.dateFin && seg.dateDebut && prevSeg.dateFin === seg.dateDebut;
                        if (prevEndsAtMatin && startsOnSameDay) {
                            debutAuto = 'Après-midi';
                        }
                    }
                    const debut = isFirst ? formData.periodeDebut : (seg.periodeDebut || debutAuto);
                    const fin = isLast
                        ? formData.periodeFin
                        : (seg.periodeFin || 'Journée entière');
                    const jours = calcWorkingDays(seg.dateDebut, seg.dateFin, debut, fin);
                    next[t] = { ...seg, jours: jours.toString() };
                }
            });
            return next;
        });
    }, [
        ...formData.types.flatMap(t => [
            repartitionDetails[t]?.dateDebut,
            repartitionDetails[t]?.dateFin,
            repartitionDetails[t]?.periodeFin,
            repartitionDetails[t]?.periodeDebut,
        ]),
        publicHolidays,
        formData.periodeDebut,
        formData.periodeFin,
    ]);

    // ── Prévisionnel CP + RTT ─────────────────────────────────────────────
    useEffect(() => {
        const fetchPrevisionnel = async () => {
            const hasCP = formData.types.includes('CP');
            const hasRTT = formData.types.includes('RTT');
            if (!formData.startDate || !userId || (!hasCP && !hasRTT)) {
                setPrevisionnel(null);
                return;
            }
            const isMixteLocal = formData.types.length > 1;
            const joursCP = hasCP
                ? (isMixteLocal ? parseFloat(repartitionDetails['CP']?.jours || 0) : getJoursEffectifs())
                : 0;
            const joursRTT = hasRTT
                ? (isMixteLocal ? parseFloat(repartitionDetails['RTT']?.jours || 0) : getJoursEffectifs())
                : 0;
            if (joursCP <= 0 && joursRTT <= 0) { setPrevisionnel(null); return; }

            setIsLoadingPrev(true);
            try {
                const dateDebut = isMixteLocal
                    ? (hasCP
                        ? (repartitionDetails['CP']?.dateDebut || formData.startDate)
                        : (repartitionDetails['RTT']?.dateDebut || formData.startDate))
                    : formData.startDate;

                const res = await fetch(`/api/soldes-previsionnel?userid=${userId}&dateDebut=${dateDebut}&joursCP=${joursCP}&joursRTT=${joursRTT}`);
                if (!res.ok) { setPrevisionnel(null); return; }
                const data = await res.json();

                if (data.success && data.previsionnel) {
                    const p = data.previsionnel;
                    setPrevisionnel({
                        ...p,
                        cpNSolde: parseFloat(p.cpNSolde ?? 0),
                        cpN1Reporte: parseFloat(p.cpN1Reporte ?? 0),
                        cpNSoldeALaDate: parseFloat(p.cpNSoldeALaDate ?? p.cpNSolde ?? 0),
                        cpNAnticipeAutorise: parseFloat(p.cpNAnticipeAutorise ?? 0),
                        totalDisponible: parseFloat(p.totalDisponible ?? 0),
                        deficit: parseFloat(p.deficit ?? 0),
                        joursNecessaires: parseFloat(p.joursNecessaires ?? 0),
                        simulation: {
                            n1Utilise: parseFloat(p.simulation?.n1Utilise ?? 0),
                            nAcquisUtilise: parseFloat(p.simulation?.nAcquisUtilise ?? 0),
                            nAnticipeUtilise: parseFloat(p.simulation?.nAnticipeUtilise ?? 0),
                        },
                        rttDispo: parseFloat(p.rttDispo ?? 0),
                        suffisantRTT: p.suffisantRTT ?? true,
                        deficitRTT: parseFloat(p.deficitRTT ?? 0),
                        isAnticipeRTT: p.isAnticipeRTT ?? false,
                        anneeRTT: p.anneeRTT ?? new Date().getFullYear(),
                        rttNAcquisAujourdHui: parseFloat(p.rttNAcquisAujourdHui ?? 0),
                        rttAnticipeDispo: parseFloat(p.rttAnticipeDispo ?? 0),
                        joursNecessairesRTT: parseFloat(p.joursNecessairesRTT ?? 0),
                    });
                } else { setPrevisionnel(null); }
            } catch { setPrevisionnel(null); }
            finally { setIsLoadingPrev(false); }
        };
        const debounceTimer = setTimeout(fetchPrevisionnel, 300);
        return () => clearTimeout(debounceTimer);
    }, [formData.startDate, formData.endDate, formData.periodeDebut, formData.periodeFin, formData.types, totalDays, userId, repartitionDetails]);

    // ── Helpers ───────────────────────────────────────────────────────────
    const safeCounters = countersData?.success && countersData?.data ? {
        availableCP: parseFloat(countersData.data.totalDisponible?.cp || 0),
        availableRTT: parseFloat(countersData.data.totalDisponible?.rtt || 0),
        availableRecup: parseFloat(countersData.data.totalDisponible?.recup || 0),
    } : { availableCP: 0, availableRTT: 0, availableRecup: 0 };

    const calcWorkingDays = (startStr, endStr, debutPeriode = 'Journée entière', finPeriode = 'Journée entière') => {
        if (!startStr || !endStr) return 0;
        const start = new Date(startStr);
        const end = new Date(endStr);
        if (end < start) return 0;
        let count = 0;
        const cur = new Date(start);
        while (cur <= end) {
            const day = cur.getDay();
            if (day !== 0 && day !== 6 && !isPublicHoliday(cur)) count++;
            cur.setDate(cur.getDate() + 1);
        }
        if (debutPeriode === 'Matin' || debutPeriode === 'Après-midi') count -= 0.5;
        if (finPeriode === 'Matin' || finPeriode === 'Après-midi') count -= 0.5;
        return Math.max(0, count);
    };

    const getJoursEffectifs = () => {
        if (!formData.startDate) return totalDays;
        if (formData.startDate === formData.endDate) {
            if (isMixte) return 1;
            if (formData.periodeDebut === 'Matin' || formData.periodeDebut === 'Après-midi') return 0.5;
            return totalDays;
        }
        let days = totalDays;
        if (formData.periodeDebut === 'Matin' || formData.periodeDebut === 'Après-midi') days -= 0.5;
        if (formData.periodeFin === 'Matin' || formData.periodeFin === 'Après-midi') days -= 0.5;
        return Math.max(0, days);
    };

    const getTotalReparti = () =>
        formData.types.reduce((sum, t) => sum + parseFloat(repartitionDetails[t]?.jours || 0), 0);

    const getMinDate = () => {
        const d = new Date();
        d.setDate(d.getDate() + 1);
        return d.toISOString().split('T')[0];
    };

    const getMinDateFormation = () => {
        const d = new Date();
        d.setDate(d.getDate() + 7);
        return d.toISOString().split('T')[0];
    };

    const isMixte = formData.types.length > 1;
    const safeNum = (v) => parseFloat(v ?? 0);
    const recupDispo = parseFloat(countersData?.data?.recupN?.solde ?? 0);

    // ── Seuil d'affichage N+1 : 0.1j minimum pour éviter "0.00j" ─────────
    const NP1_DISPLAY_THRESHOLD = 0.1;

    // ════════════════════════════════════════════════════════════════════
    // ReportCard
    // ════════════════════════════════════════════════════════════════════
    const ReportCard = ({ data }) => {
        if (!data || parseFloat(data.solde || 0) === 0) return null;
        const solde = parseFloat(data.solde || 0);
        return (
            <div className="bg-amber-50 border-2 border-amber-200 rounded-lg p-3">
                <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                        <span className="text-lg">📦</span>
                        <span className="text-sm font-semibold text-amber-900">CP N-1</span>
                    </div>
                </div>
                <div className="bg-white border border-amber-200 rounded p-2 text-center">
                    <div className="text-xs text-amber-700 mb-1">Solde disponible</div>
                    <div className="text-xl font-bold text-amber-800">{solde.toFixed(2)}j</div>
                </div>
            </div>
        );
    };

    // ════════════════════════════════════════════════════════════════════
    // CompactCounterCard
    // ════════════════════════════════════════════════════════════════════
    const CompactCounterCard = ({ type, data, isExpanded, previsionnel: prev }) => {
        if (!data) return null;

        const solde = parseFloat(data.solde || 0);
        const anticipe = type === 'CP' ? parseFloat(data.soldeAnticipe || 0) : 0;
        const icons = { CP: '💼', RTT: '🌴', Récup: '🔄' };

        const soldeSimuleN = type === 'CP' && simulationDate ? safeNum(simulationDate.cpN?.disponible) : null;
        const soldeSimuleNp1 = type === 'CP' && simulationDate ? safeNum(simulationDate.cpNp1?.disponible) : null;
        const soldeSimuleTotal = type === 'CP'
            ? (simulationDate
                ? safeNum(simulationDate.totalDisponible)
                : (prev ? safeNum(prev.totalCPDisponible) : null))
            : null;

        const soldeSimuleRTTN = type === 'RTT' && simulationRTT ? safeNum(simulationRTT.rttN?.disponible) : null;
        const soldeSimuleRTTNp1 = type === 'RTT' && simulationRTT ? safeNum(simulationRTT.rttNp1?.disponible) : null;
        const soldeSimuleRTTTotal = type === 'RTT' && simulationRTT ? safeNum(simulationRTT.totalDisponible) : null;
        const rttApresBasculement = type === 'RTT' && simulationRTT ? simulationRTT.apresBasculement : false;

        const soldeReel = type === 'CP'
            ? Math.max(0, solde - anticipe)
            : type === 'RTT' && simulationRTT
                ? safeNum(simulationRTT.rttN?.soldeActuel ?? solde)
                : Math.max(0, solde - anticipe);

        // ✅ FIX : N+1 s'affiche seulement si >= seuil (évite "0.00j")
        const showNp1 = (soldeSimuleNp1 ?? 0) >= NP1_DISPLAY_THRESHOLD;

        if (!isExpanded) return (
            <div className="bg-white border border-gray-200 rounded-lg p-3">
                <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-semibold text-gray-900">
                        {icons[type]} {type === 'CP' ? 'CP N' : type}
                    </span>
                    <span className="text-sm text-gray-600">{solde.toFixed(2)}j disponible</span>
                </div>
            </div>
        );

        return (
            <div className="bg-white border-2 border-blue-200 rounded-lg p-4">
                <div className="flex items-center justify-between mb-3">
                    <span className="text-sm font-semibold text-gray-900">
                        {icons[type]} {type === 'CP' ? 'CP N' : type}
                    </span>
                </div>

                {type === 'CP' ? (
                    <>
                        <div className="grid grid-cols-2 gap-2 mb-3">
                            <div className="bg-gray-50 border rounded p-2 text-center">
                                <div className="text-xs text-gray-500 mb-1">💰 Solde actuel</div>
                                <div className="text-lg font-bold text-green-600">{soldeReel.toFixed(2)}j</div>
                            </div>
                            <div className="bg-blue-50 border border-blue-200 rounded p-2 text-center">
                                <div className="text-xs text-blue-600 mb-1">📅 Solde prévisionnel</div>
                                {isLoadingSimul ? (
                                    <div className="animate-pulse text-sm text-blue-400">...</div>
                                ) : (simulationDate || prev) ? (
                                    <>
                                        <div className="text-lg font-bold text-blue-700">{(soldeSimuleTotal ?? 0).toFixed(2)}j</div>
                                        {/* ✅ FIX : afficher N + N+1 seulement si N+1 >= 0.1j */}
                                        {simulationDate && showNp1 ? (
                                            <div className="text-xs text-blue-500 mt-0.5">
                                                N: {(soldeSimuleN ?? 0).toFixed(2)}j + N+1: {(soldeSimuleNp1 ?? 0).toFixed(2)}j
                                            </div>
                                        ) : (
                                            <div className="text-xs text-blue-500 mt-0.5">
                                                au {new Date(formData.startDate).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' })}
                                            </div>
                                        )}
                                    </>
                                ) : (
                                    <div className="text-lg font-bold text-gray-400">—</div>
                                )}
                            </div>
                        </div>
                        {anticipe > 0 && (
                            <div className="bg-orange-50 border border-orange-200 rounded p-2 mb-3">
                                <div className="text-xs text-orange-800">⚠️ {anticipe.toFixed(2)}j déjà anticipé (~{Math.ceil(anticipe / 2.08)}m)</div>
                            </div>
                        )}
                    </>
                ) : type === 'RTT' ? (
                    <>
                        <div className="grid grid-cols-2 gap-2 mb-3">
                            <div className="bg-gray-50 border rounded p-2 text-center">
                                <div className="text-xs text-gray-500 mb-1">💰 Solde actuel</div>
                                <div className="text-lg font-bold text-green-600">{Math.max(0, solde).toFixed(2)}j</div>
                            </div>
                            <div className="bg-blue-50 border border-blue-200 rounded p-2 text-center">
                                <div className="text-xs text-blue-600 mb-1">📅 Solde prévisionnel</div>
                                {isLoadingSimulRTT ? (
                                    <div className="animate-pulse text-sm text-blue-400">...</div>
                                ) : simulationRTT ? (
                                    <>
                                        <div className="text-lg font-bold text-blue-700">{(soldeSimuleRTTTotal ?? 0).toFixed(2)}j</div>
                                        {rttApresBasculement ? (
                                            <div className="text-xs text-blue-500 mt-0.5">N: {(soldeSimuleRTTN ?? 0).toFixed(2)}j + N+1: {(soldeSimuleRTTNp1 ?? 0).toFixed(2)}j</div>
                                        ) : (
                                            <div className="text-xs text-blue-500 mt-0.5">au {new Date(formData.startDate).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' })}</div>
                                        )}
                                    </>
                                ) : (
                                    <div className="text-lg font-bold text-gray-400">—</div>
                                )}
                            </div>
                        </div>
                        {simulationRTT?.apresBasculement && (
                            <div className="bg-purple-50 border border-purple-200 rounded p-2 mb-2 text-xs">
                                <div className="font-medium text-purple-800 mb-1">📊 Détail au {new Date(formData.startDate).toLocaleDateString('fr-FR')}</div>
                                <div className="flex justify-between text-purple-700"><span>RTT {simulationRTT.anneeRTTN} (solde final 31/12)</span><span className="font-semibold">{(soldeSimuleRTTN ?? 0).toFixed(2)}j</span></div>
                                <div className="flex justify-between text-purple-700"><span>RTT {simulationRTT.anneeRTTNp1} (prorata depuis 01/01)</span><span className="font-semibold">{(soldeSimuleRTTNp1 ?? 0).toFixed(2)}j</span></div>
                            </div>
                        )}
                    </>
                ) : (
                    <div className="bg-gray-50 border rounded p-2 text-center mb-3">
                        <div className="text-xs text-gray-500">Solde disponible</div>
                        <div className="text-lg font-bold text-green-600">{solde.toFixed(2)}j</div>
                    </div>
                )}
            </div>
        );
    };

    // ════════════════════════════════════════════════════════════════════
    // ImpactPreview
    // ════════════════════════════════════════════════════════════════════
    const ImpactPreview = () => {
        const joursEffectifs = isMixte ? getTotalReparti() : getJoursEffectifs();
        if (!formData.types.length || joursEffectifs === 0) return null;

        if (isMixte) {
            const cpN1SoldeReel = safeNum(countersData?.data?.cpN1?.solde ?? 0);
            const cpNDispo = simulationDate ? safeNum(simulationDate.cpN?.disponible) : 0;
            const cpNp1Dispo = simulationDate ? safeNum(simulationDate.cpNp1?.disponible) : 0;
            const apresBasculement = simulationDate?.apresBasculement ?? false;

            const joursDemandesCP = safeNum(repartitionDetails['CP']?.jours);
            const totalCPAffiche = simulationDate
                ? safeNum(simulationDate.totalDisponible)
                : previsionnel ? safeNum(previsionnel.totalDisponible) : safeCounters.availableCP;
            const soldeApresCP = totalCPAffiche - joursDemandesCP;
            const anticipeUtilise = safeNum(previsionnel?.simulation?.nAnticipeUtilise);

            const joursDemandesRTT = safeNum(repartitionDetails['RTT']?.jours);
            const rttDispoAffiche = simulationRTT
                ? safeNum(simulationRTT.totalDisponible)
                : previsionnel ? safeNum(previsionnel.rttDispo) : safeCounters.availableRTT;
            const rttN = simulationRTT ? safeNum(simulationRTT.rttN?.disponible) : 0;
            const rttNp1 = simulationRTT ? safeNum(simulationRTT.rttNp1?.disponible) : 0;
            const rttApresBasculement = simulationRTT?.apresBasculement ?? false;
            const soldeApresRTT = rttDispoAffiche - joursDemandesRTT;
            const rttSuffisant = previsionnel ? previsionnel.suffisantRTT : soldeApresRTT >= 0;

            const joursDemandesRecup = safeNum(repartitionDetails['Récup']?.jours);
            const recupSolde = safeNum(countersData?.data?.recupN?.solde ?? 0);
            const soldeApresRecup = recupSolde - joursDemandesRecup;

            const joursEffectifsTotal = getJoursEffectifs();

            return (
                <div className="bg-white border border-gray-200 rounded-lg p-4 space-y-4">
                    <h3 className="text-sm font-semibold text-gray-900 flex items-center gap-2">
                        <TrendingDown className="w-4 h-4" />IMPACT PAR TYPE
                    </h3>

                    {formData.types.includes('CP') && (
                        <div className="space-y-1">
                            {cpN1SoldeReel > 0 && !apresBasculement && (
                                <div className="flex justify-between text-xs bg-amber-50 border border-amber-200 rounded px-3 py-1.5">
                                    <span className="text-amber-700 font-medium">📦 CP N-1</span>
                                    <span className="font-semibold text-amber-800">{cpN1SoldeReel.toFixed(2)}j</span>
                                </div>
                            )}
                            {/* ✅ FIX : CP N — sans condition apresBasculement */}
                            {simulationDate && cpNDispo > 0 && (
                                <div className="flex justify-between text-xs bg-blue-50 border border-blue-100 rounded px-3 py-1.5">
                                    <span className="text-blue-700 font-medium">🏖️ CP N — au {new Date(formData.startDate).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' })}</span>
                                    <span className="font-semibold text-blue-800">{cpNDispo.toFixed(2)}j</span>
                                </div>
                            )}
                            {/* ✅ FIX : CP N+1 — seulement si >= seuil */}
                            {simulationDate && cpNp1Dispo >= NP1_DISPLAY_THRESHOLD && (
                                <div className="flex justify-between text-xs bg-purple-50 border border-purple-100 rounded px-3 py-1.5">
                                    <span className="text-purple-700 font-medium">✨ CP N+1 (01/06 → {new Date(formData.startDate).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' })})</span>
                                    <span className="font-semibold text-purple-800">{cpNp1Dispo.toFixed(2)}j</span>
                                </div>
                            )}
                            <div className="flex justify-between text-sm px-1 pt-0.5">
                                <span className="text-gray-600">CP demandés</span>
                                <span className="font-medium text-red-600">-{joursDemandesCP.toFixed(2)}j{isLoadingSimul && <span className="text-gray-400 ml-1 animate-pulse text-xs">...</span>}</span>
                            </div>
                            <div className="border-t border-gray-200 pt-1.5 flex justify-between text-sm font-semibold px-1">
                                <span>Solde après</span>
                                <span className={soldeApresCP >= 0 ? 'text-green-600' : 'text-orange-500'}>
                                    {soldeApresCP.toFixed(2)}j
                                    {soldeApresCP < 0 && anticipeUtilise > 0 && <span className="text-xs font-normal text-orange-400 ml-1">couvert par anticipation</span>}
                                </span>
                            </div>
                            {(() => {
                                const totalDispoCP = simulationDate
                                    ? safeNum(simulationDate.totalDisponible)
                                    : safeNum(previsionnel?.totalDisponible ?? 0);
                                const deficit = joursEffectifs - totalDispoCP;
                                return deficit > 0 ? (
                                    <div className="flex items-center gap-1.5 text-xs text-red-700 bg-red-50 border border-red-200 rounded px-2 py-1">
                                        <AlertCircle className="w-3.5 h-3.5 flex-shrink-0" />
                                        <span>Solde insuffisant — Déficit : {deficit.toFixed(2)}j</span>
                                    </div>
                                ) : null;
                            })()}
                        </div>
                    )}

                    {formData.types.includes('RTT') && (
                        <div className="space-y-1">
                            {simulationRTT && !rttApresBasculement && rttN > 0 && (
                                <div className="flex justify-between text-xs bg-green-50 border border-green-100 rounded px-3 py-1.5">
                                    <span className="text-green-700 font-medium">🌴 RTT {simulationRTT.anneeRTTN} — au {new Date(formData.startDate).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' })}</span>
                                    <span className="font-semibold text-green-800">{rttN.toFixed(2)}j</span>
                                </div>
                            )}
                            {simulationRTT?.apresBasculement && (
                                <>
                                    {rttN > 0 && <div className="flex justify-between text-xs bg-green-50 border border-green-100 rounded px-3 py-1.5"><span className="text-green-700 font-medium">🌴 RTT {simulationRTT.anneeRTTN} (31/12)</span><span className="font-semibold text-green-800">{rttN.toFixed(2)}j</span></div>}
                                    {rttNp1 > 0 && <div className="flex justify-between text-xs bg-purple-50 border border-purple-100 rounded px-3 py-1.5"><span className="text-purple-700 font-medium">✨ RTT {simulationRTT.anneeRTTNp1} (01/01)</span><span className="font-semibold text-purple-800">{rttNp1.toFixed(2)}j</span></div>}
                                </>
                            )}
                            {!simulationRTT && (
                                <div className="flex justify-between text-xs bg-green-50 border border-green-100 rounded px-3 py-1.5">
                                    <span className="text-green-700 font-medium">🌴 RTT disponible</span>
                                    <span className="font-semibold text-green-800">{rttDispoAffiche.toFixed(2)}j{isLoadingPrev && <span className="text-green-400 ml-1 animate-pulse">...</span>}</span>
                                </div>
                            )}
                            <div className="flex justify-between text-sm px-1 pt-0.5">
                                <span className="text-gray-600">RTT demandés</span>
                                <span className="font-medium text-red-600">-{joursDemandesRTT.toFixed(2)}j</span>
                            </div>
                            <div className="border-t border-gray-200 pt-1.5 flex justify-between text-sm font-semibold px-1">
                                <span>Solde après</span>
                                <span className={soldeApresRTT >= 0 ? 'text-green-600' : 'text-orange-500'}>{soldeApresRTT.toFixed(2)}j</span>
                            </div>
                            {!rttSuffisant && (
                                <div className="flex items-center gap-1.5 text-xs text-red-700 bg-red-50 border border-red-200 rounded px-2 py-1">
                                    <AlertCircle className="w-3.5 h-3.5 flex-shrink-0" />
                                    <span>Déficit : {safeNum(previsionnel?.deficitRTT || Math.abs(soldeApresRTT)).toFixed(2)}j</span>
                                </div>
                            )}
                            {previsionnel?.isAnticipeRTT && (
                                <div className="text-xs text-purple-700 bg-purple-50 rounded px-2 py-1">⏩ Anticipé — RTT {previsionnel.anneeRTT} projeté au 31/12</div>
                            )}
                        </div>
                    )}

                    {formData.types.includes('Récup') && (
                        <div className="space-y-1">
                            <div className="flex justify-between text-xs bg-purple-50 border border-purple-100 rounded px-3 py-1.5">
                                <span className="text-purple-700 font-medium">🔄 Récup disponible</span>
                                <span className="font-semibold text-purple-800">{recupSolde.toFixed(2)}j</span>
                            </div>
                            <div className="flex justify-between text-sm px-1 pt-0.5">
                                <span className="text-gray-600">Récup demandés</span>
                                <span className="font-medium text-red-600">-{joursDemandesRecup.toFixed(2)}j</span>
                            </div>
                            <div className="border-t border-gray-200 pt-1.5 flex justify-between text-sm font-semibold px-1">
                                <span>Solde après</span>
                                <span className={soldeApresRecup >= 0 ? 'text-green-600' : 'text-red-600'}>{soldeApresRecup.toFixed(2)}j</span>
                            </div>
                        </div>
                    )}

                    <div className="border-t pt-2 flex justify-between text-sm font-semibold">
                        <span>Total réparti :</span>
                        <span className={getTotalReparti() === joursEffectifsTotal ? 'text-green-600' : 'text-orange-600'}>
                            {getTotalReparti()}j / {joursEffectifsTotal}j
                        </span>
                    </div>
                </div>
            );
        }

        const type = formData.types[0];
        if (type === 'CP') {
            const cpN1SoldeReel = safeNum(countersData?.data?.cpN1?.solde ?? 0);
            const totalAffiche = simulationDate
                ? safeNum(simulationDate.totalDisponible)
                : previsionnel ? safeNum(previsionnel.totalDisponible) : safeCounters.availableCP;
            const soldeApres = totalAffiche - joursEffectifs;
            const apresBasculement = simulationDate?.apresBasculement ?? false;

            const n1Utilise = apresBasculement ? 0 : (previsionnel ? safeNum(previsionnel.simulation?.n1Utilise) : Math.min(cpN1SoldeReel, joursEffectifs));
            const nAcquisUtilise = apresBasculement
                ? joursEffectifs
                : (previsionnel ? safeNum(previsionnel.simulation?.nAcquisUtilise) : Math.max(0, joursEffectifs - n1Utilise));
            const anticipeUtilise = previsionnel ? safeNum(previsionnel.simulation?.nAnticipeUtilise) : 0;

            const cpNDispo = simulationDate ? safeNum(simulationDate.cpN?.disponible) : 0;
            const cpNp1Dispo = simulationDate ? safeNum(simulationDate.cpNp1?.disponible) : 0;

            return (
                <div className="bg-white border border-gray-200 rounded-lg p-4 space-y-3">
                    <h3 className="text-sm font-semibold text-gray-900 flex items-center gap-2"><TrendingDown className="w-4 h-4" /> IMPACT DE VOTRE DEMANDE</h3>
                    <div className="space-y-1">
                        {cpN1SoldeReel > 0 && !apresBasculement && (
                            <div className="flex justify-between text-xs bg-amber-50 border border-amber-200 rounded px-3 py-1.5">
                                <span className="text-amber-700 font-medium">📦 CP N-1</span>
                                <span className="font-semibold text-amber-800">{cpN1SoldeReel.toFixed(2)}j</span>
                            </div>
                        )}
                        {/* ✅ FIX : CP N — sans condition apresBasculement */}
                        {simulationDate && cpNDispo > 0 && (
                            <div className="flex justify-between text-xs bg-blue-50 border border-blue-100 rounded px-3 py-1.5">
                                <span className="text-blue-700 font-medium">🏖️ CP N — au {new Date(formData.startDate).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' })}</span>
                                <span className="font-semibold text-blue-800">{cpNDispo.toFixed(2)}j</span>
                            </div>
                        )}
                        {/* ✅ FIX : CP N+1 — seulement si >= seuil */}
                        {simulationDate && cpNp1Dispo >= NP1_DISPLAY_THRESHOLD && (
                            <div className="flex justify-between text-xs bg-purple-50 border border-purple-100 rounded px-3 py-1.5">
                                <span className="text-purple-700 font-medium">✨ CP N+1 (01/06 → {new Date(formData.startDate).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' })})</span>
                                <span className="font-semibold text-purple-800">{cpNp1Dispo.toFixed(2)}j</span>
                            </div>
                        )}
                        {!simulationDate && safeNum(previsionnel?.cpN1Reporte) > 0 && (
                            <div className="flex justify-between text-xs bg-amber-50 border border-amber-200 rounded px-3 py-1.5">
                                <span className="text-amber-700 font-medium">📦 CP N-1 disponible</span>
                                <span className="font-semibold text-amber-800">{safeNum(previsionnel?.cpN1Reporte).toFixed(2)}j</span>
                            </div>
                        )}
                        <div className="flex justify-between text-sm px-1"><span className="text-gray-600">CP demandés</span><span className="font-medium text-red-600">-{joursEffectifs.toFixed(2)}j</span></div>
                        {previsionnel && (n1Utilise > 0 || nAcquisUtilise > 0 || anticipeUtilise > 0) && (
                            <div className="bg-gray-50 border border-gray-100 rounded px-3 py-2 space-y-1">
                                <div className="text-xs text-gray-500 font-medium mb-1">Ordre de déduction :</div>
                                {n1Utilise > 0 && !apresBasculement && (
                                    <div className="flex justify-between text-xs text-amber-700">
                                        <span>↳ Prélevé sur CP N-1</span>
                                        <span className="font-semibold">-{n1Utilise.toFixed(2)}j</span>
                                    </div>
                                )}
                                {nAcquisUtilise > 0 && (
                                    <div className="flex justify-between text-xs text-blue-700">
                                        <span>↳ Prélevé sur CP N</span>
                                        <span className="font-semibold">-{nAcquisUtilise.toFixed(2)}j</span>
                                    </div>
                                )}
                                {anticipeUtilise > 0 && (
                                    <div className="flex justify-between text-xs text-orange-600">
                                        <span>↳ Anticipé sur CP N</span>
                                        <span className="font-semibold">-{anticipeUtilise.toFixed(2)}j</span>
                                    </div>
                                )}
                            </div>
                        )}
                        <div className="border-t border-gray-200 pt-2 flex justify-between text-sm font-semibold px-1">
                            <span>Solde après la demande</span>
                            <span className={soldeApres >= 0 ? 'text-green-600' : 'text-orange-500'}>{soldeApres.toFixed(2)}j</span>
                        </div>
                    </div>
                    {previsionnel && (previsionnel.suffisant ? (
                        <div className="bg-green-50 border border-green-200 rounded p-2 flex items-center gap-2"><CheckCircle className="w-4 h-4 text-green-600" /><span className="text-xs text-green-800 font-medium">Solde suffisant</span></div>
                    ) : (
                        <div className="bg-red-50 border border-red-200 rounded p-2 flex items-start gap-2"><AlertCircle className="w-4 h-4 text-red-600 flex-shrink-0 mt-0.5" /><span className="text-xs text-red-800"><strong>Solde insuffisant — Déficit {safeNum(previsionnel.deficit).toFixed(2)}j</strong></span></div>
                    ))}
                </div>
            );
        }

        if (type === 'RTT') {
            const rttDispoTotal = simulationRTT ? safeNum(simulationRTT.totalDisponible) : previsionnel ? safeNum(previsionnel.rttDispo) : safeCounters.availableRTT;
            const rttSoldeApres = rttDispoTotal - joursEffectifs;
            const rttN = simulationRTT ? safeNum(simulationRTT.rttN?.disponible) : 0;
            const rttNp1 = simulationRTT ? safeNum(simulationRTT.rttNp1?.disponible) : 0;
            const isAnticipeRTT = previsionnel?.isAnticipeRTT ?? simulationRTT?.apresBasculement ?? false;
            return (
                <div className="bg-white border border-gray-200 rounded-lg p-4 space-y-3">
                    <h3 className="text-sm font-semibold text-gray-900 flex items-center gap-2">
                        <TrendingDown className="w-4 h-4" /> IMPACT DE VOTRE DEMANDE
                        {isAnticipeRTT && <span className="ml-auto text-xs px-2 py-0.5 rounded-full font-medium bg-purple-100 text-purple-700">Anticipé</span>}
                    </h3>
                    <div className="space-y-1">
                        {simulationRTT && !simulationRTT.apresBasculement && rttN > 0 && (
                            <div className="flex justify-between text-xs bg-green-50 border border-green-100 rounded px-3 py-1.5">
                                <span className="text-green-700 font-medium">🌴 RTT {simulationRTT.anneeRTTN} — solde au {new Date(formData.startDate).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' })}</span>
                                <span className="font-semibold text-green-800">{rttN.toFixed(2)}j</span>
                            </div>
                        )}
                        {simulationRTT?.apresBasculement && (
                            <>
                                {rttN > 0 && <div className="flex justify-between text-xs bg-green-50 border border-green-100 rounded px-3 py-1.5"><span className="text-green-700 font-medium">🌴 RTT {simulationRTT.anneeRTTN} (solde final 31/12)</span><span className="font-semibold text-green-800">{rttN.toFixed(2)}j</span></div>}
                                {rttNp1 > 0 && <div className="flex justify-between text-xs bg-purple-50 border border-purple-100 rounded px-3 py-1.5"><span className="text-purple-700 font-medium">✨ RTT {simulationRTT.anneeRTTNp1} (prorata depuis 01/01)</span><span className="font-semibold text-purple-800">{rttNp1.toFixed(2)}j</span></div>}
                            </>
                        )}
                        <div className="flex justify-between text-xs bg-gray-50 border border-gray-200 rounded px-3 py-1.5">
                            <span className="text-gray-600 font-medium">📊 Total disponible{isLoadingPrev && <span className="text-gray-400 ml-1 animate-pulse">...</span>}</span>
                            <span className="font-bold text-gray-800">{rttDispoTotal.toFixed(2)}j</span>
                        </div>
                        <div className="flex justify-between text-sm px-1"><span className="text-gray-600">RTT demandés</span><span className="font-medium text-red-600">-{joursEffectifs.toFixed(2)}j</span></div>
                        <div className="border-t border-gray-200 pt-2 flex justify-between text-sm font-semibold px-1">
                            <span>Solde après la demande</span>
                            <span className={rttSoldeApres >= 0 ? 'text-green-600' : 'text-orange-500'}>{rttSoldeApres.toFixed(2)}j{rttSoldeApres < 0 && isAnticipeRTT && <span className="text-xs font-normal text-orange-400 ml-1">couvert par anticipation</span>}</span>
                        </div>
                    </div>
                </div>
            );
        }

        const data = countersData?.data?.recupN;
        if (!data) return null;
        const soldeActuel = parseFloat(data.solde || 0);
        const soldeApres = soldeActuel - joursEffectifs;
        return (
            <div className="bg-white border border-gray-200 rounded-lg p-4 space-y-3">
                <h3 className="text-sm font-semibold text-gray-900 flex items-center gap-2"><TrendingDown className="w-4 h-4" />📊 IMPACT DE VOTRE DEMANDE</h3>
                <div className="space-y-2">
                    <div className="flex justify-between text-sm"><span className="text-gray-600">{type} disponible :</span><span className="font-medium">{soldeActuel.toFixed(2)}j</span></div>
                    <div className="flex justify-between text-sm"><span className="text-gray-600">{type} demandé :</span><span className="font-medium text-red-600">-{joursEffectifs.toFixed(2)}j</span></div>
                    <div className="border-t border-gray-300 pt-2 flex justify-between text-sm font-semibold">
                        <span>{soldeApres >= 0 ? '✅' : '⚠️'} Solde après :</span>
                        <span className={soldeApres >= 0 ? 'text-green-600' : 'text-red-600'}>{soldeApres.toFixed(2)}j</span>
                    </div>
                </div>
            </div>
        );
    };

    // ── Validation ────────────────────────────────────────────────────────
    const validateForm = () => {
        if (!formData.types.length) { setError('Veuillez sélectionner au moins un type de congé'); return false; }
        if (!formData.startDate || !formData.endDate) { setError('Veuillez sélectionner les dates'); return false; }
        const today = new Date(); today.setHours(0, 0, 0, 0);
        const start = new Date(formData.startDate);
        const end = new Date(formData.endDate);
        if (formData.types.includes('Formation')) {
            const min = new Date(today); min.setDate(min.getDate() + 7);
            if (start < min) { setError("La formation doit être posée au moins 7 jours à l'avance."); return false; }
        }
        if (start <= today || end <= today) { setError("Vous ne pouvez pas poser un congé pour aujourd'hui ou une date passée."); return false; }
        if (end < start) { setError("La date de fin doit être après la date de début."); return false; }
        if (!countersData?.success || !countersData?.data) { setError("Erreur : Les compteurs ne sont pas chargés. Veuillez réessayer."); return false; }

        const joursEffectifs = getJoursEffectifs();

        if (isMixte) {
            const totalReparti = getTotalReparti();
            if (totalReparti !== joursEffectifs) { setError(`La répartition doit totaliser ${joursEffectifs}j ouvrés (actuellement ${totalReparti}j)`); return false; }
            for (const t of formData.types) {
                const seg = repartitionDetails[t];
                if (!seg?.dateDebut || !seg?.dateFin) { setError(`Veuillez renseigner les dates pour le type "${t}"`); return false; }
                if (!seg?.jours || parseFloat(seg.jours) <= 0) { setError(`Veuillez renseigner le nombre de jours pour "${t}"`); return false; }
            }
            if (formData.types.includes('CP')) {
                const joursCP = parseFloat(repartitionDetails['CP']?.jours || 0);
                if (joursCP > 0) {
                    const totalDispoCP = simulationDate
                        ? safeNum(simulationDate.totalDisponible)
                        : previsionnel
                            ? parseFloat(previsionnel.totalDisponible)
                            : safeCounters.availableCP;
                    if (joursCP > totalDispoCP) {
                        setError(`Solde CP insuffisant — Maximum disponible : ${totalDispoCP.toFixed(2)}j — Demandé : ${joursCP.toFixed(2)}j — Déficit : ${(joursCP - totalDispoCP).toFixed(2)}j`);
                        return false;
                    }
                }
            }
            if (formData.types.includes('RTT') && previsionnel && !previsionnel.suffisantRTT) { setError(`Solde RTT insuffisant — Déficit : ${parseFloat(previsionnel.deficitRTT).toFixed(2)}j`); return false; }
            if (formData.types.includes('RTT') && !previsionnel && parseFloat(repartitionDetails['RTT']?.jours || 0) > safeCounters.availableRTT) { setError(`Solde RTT insuffisant (${safeCounters.availableRTT.toFixed(2)}j disponibles)`); return false; }
            if (formData.types.includes('Récup') && parseFloat(repartitionDetails['Récup']?.jours || 0) > safeCounters.availableRecup) { setError(`Solde Récup insuffisant (${safeCounters.availableRecup.toFixed(2)}j disponibles)`); return false; }
            return true;
        }

        const type = formData.types[0];
        if (type === 'CP' && joursEffectifs > 0) {
            if (previsionnel) {
                if (!previsionnel.suffisant) {
                    setError(`Solde CP insuffisant\nMaximum disponible : ${parseFloat(previsionnel.totalDisponible).toFixed(2)}j — Demandé : ${joursEffectifs.toFixed(2)}j — Déficit : ${parseFloat(previsionnel.deficitCP).toFixed(2)}j`);
                    return false;
                }
            } else {
                const totalDispoCP = simulationDate ? safeNum(simulationDate.totalDisponible) : safeCounters.availableCP;
                if (joursEffectifs > totalDispoCP) {
                    setError(`Solde CP insuffisant\nMaximum disponible : ${totalDispoCP.toFixed(2)}j — Demandé : ${joursEffectifs.toFixed(2)}j`);
                    return false;
                }
            }
        }
        if (type === 'RTT' && joursEffectifs > 0) {
            if (previsionnel && !previsionnel.suffisantRTT) { setError(`Solde RTT insuffisant${previsionnel.isAnticipeRTT ? ' (⏩ Anticipé)' : ''}\nMaximum disponible : ${parseFloat(previsionnel.rttDispo).toFixed(2)}j — Demandé : ${joursEffectifs.toFixed(2)}j — Déficit : ${parseFloat(previsionnel.deficitRTT).toFixed(2)}j`); return false; }
            else if (!previsionnel && joursEffectifs > safeCounters.availableRTT) { setError(`Solde RTT insuffisant (${safeCounters.availableRTT.toFixed(2)}j disponibles)`); return false; }
        }
        if (type === 'Récup' && joursEffectifs > safeCounters.availableRecup) { setError(`Solde Récup insuffisant (${safeCounters.availableRecup.toFixed(2)}j disponibles)`); return false; }
        return true;
    };

    // ── Submit ────────────────────────────────────────────────────────────
    const handleSubmit = async () => {
        setError('');
        if (!validateForm()) return;
        setIsSubmitting(true);
        try {
            const joursEffectifs = getJoursEffectifs();
            const formDataToSend = new FormData();
            formDataToSend.append('DateDebut', formData.startDate);
            formDataToSend.append('DateFin', formData.endDate);
            formDataToSend.append('Email', userEmail);
            formDataToSend.append('Nom', userName);
            formDataToSend.append('Commentaire', formData.reason || '');
            formDataToSend.append('NombreJours', isMixte ? getTotalReparti() : joursEffectifs);

            const sameDayMixte = isMixte && formData.startDate === formData.endDate;
            const repartition = isMixte
                ? formData.types.map((t, idx) => {
                    const isFirst = idx === 0;
                    const isLast = idx === formData.types.length - 1;
                    const segPeriodeFin = isLast
                        ? formData.periodeFin
                        : (repartitionDetails[t]?.periodeFin || 'Journée entière');
                    return {
                        TypeConge: t,
                        NombreJours: parseFloat(repartitionDetails[t]?.jours || 0),
                        PeriodeJourneeDebut: sameDayMixte
                            ? (repartitionDetails[t]?.periode || 'Journée entière')
                            : (isFirst ? formData.periodeDebut : 'Journée entière'),
                        PeriodeJourneeFin: sameDayMixte
                            ? (repartitionDetails[t]?.periode || 'Journée entière')
                            : segPeriodeFin,
                        DateDebut: repartitionDetails[t]?.dateDebut || formData.startDate,
                        DateFin: repartitionDetails[t]?.dateFin || formData.endDate,
                    };
                })
                : [{
                    TypeConge: formData.types[0],
                    NombreJours: joursEffectifs,
                    PeriodeJourneeDebut: formData.periodeDebut,
                    PeriodeJourneeFin: formData.periodeFin,
                    DateDebut: formData.startDate,
                    DateFin: formData.endDate,
                }];

            formDataToSend.append('Repartition', JSON.stringify(repartition));

            if (formData.types.includes('CP') && previsionnel) {
                formDataToSend.append('IsAnticipe', previsionnel.isAnticipe ? '1' : '0');
                formDataToSend.append('ExerciceConges', previsionnel.exerciceConges);
                formDataToSend.append('ExerciceDemande', previsionnel.exerciceDemande);
                const sim = previsionnel.simulation || {};
                formDataToSend.append('JoursN1Utilises', sim.n1Utilise || 0);
                formDataToSend.append('JoursNAcquisUtilises', sim.nAcquisUtilise || 0);
                formDataToSend.append('JoursNAnticipeUtilises', sim.nAnticipeUtilise || 0);
            }

            const response = await fetch('/api/submitLeaveRequest', { method: 'POST', body: formDataToSend });
            const result = await response.json();
            if (result.success) {
                onClose();
                if (onRequestSubmitted) onRequestSubmitted(result);
            } else {
                setError(result.message || 'Erreur lors de la soumission');
            }
        } catch (err) {
            setError(err.message || 'Une erreur est survenue');
        } finally {
            setIsSubmitting(false);
        }
    };

    const availableTypesOptions = userRole === 'Apprenti'
        ? [
            { key: 'CP', label: '💼 Congés Payés (CP)', disabled: false },
            { key: 'Formation', label: '📚 Formation', disabled: false },
            { key: 'Récup', label: '🔄 Récupération', disabled: recupDispo <= 0 && !isLoadingCounters },
        ]
        : [
            { key: 'CP', label: '💼 Congés Payés (CP)', disabled: false },
            { key: 'RTT', label: '🌴 RTT', disabled: false },
            { key: 'Récup', label: '🔄 Récupération', disabled: recupDispo <= 0 && !isLoadingCounters },
        ];

    const getDureeAffichee = () => {
        const j = getJoursEffectifs();
        if (j === 0) return null;
        return j;
    };

    const isSameDay = formData.startDate && formData.endDate && formData.startDate === formData.endDate;

    // ── Render ────────────────────────────────────────────────────────────
    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] overflow-hidden flex flex-col">

                {/* Header */}
                <div className="flex justify-between items-center p-6 border-b bg-white">
                    <h2 className="text-xl font-semibold text-gray-900">🏖️ Nouvelle demande de congés</h2>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><X className="w-6 h-6" /></button>
                </div>

                {/* Body 2 colonnes */}
                <div className="flex-1 overflow-y-auto">
                    <div className="grid grid-cols-5 gap-6 p-6">

                        {/* ══ COLONNE GAUCHE (60%) ══ */}
                        <div className="col-span-3 space-y-6">

                            {/* Dates */}
                            <div>
                                <h3 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
                                    <Calendar className="w-4 h-4" />📅 PÉRIODE D'ABSENCE
                                </h3>
                                <div className="space-y-4">

                                    {/* Date début */}
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-2">
                                            Date début <span className="text-red-500">*</span>
                                        </label>
                                        <input type="date"
                                            value={formData.startDate}
                                            min={formData.types.includes('Formation') ? getMinDateFormation() : getMinDate()}
                                            onChange={(e) => {
                                                const v = e.target.value;
                                                const adj = isWeekend(v) ? getNextWorkingDay(v) : v;
                                                setFormData(prev => ({
                                                    ...prev,
                                                    startDate: adj,
                                                    endDate: !prev.endDate || new Date(prev.endDate) < new Date(adj) ? adj : prev.endDate
                                                }));
                                            }}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                                        />
                                        {formData.startDate && !formData.types.includes('Formation') && !isSameDay && (
                                            <div className="mt-2">
                                                <label className="block text-xs text-gray-500 mb-1.5">⏰ Début de la période</label>
                                                <div className="grid grid-cols-3 gap-2">
                                                    {['Journée entière', 'Matin', 'Après-midi'].map(p => (
                                                        <button key={p} type="button"
                                                            onClick={() => setFormData(prev => ({ ...prev, periodeDebut: p }))}
                                                            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${formData.periodeDebut === p ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                                                            {p === 'Matin' ? '🌅 Matin' : p === 'Après-midi' ? '☀️ Après-midi' : '🌞 Journée entière'}
                                                        </button>
                                                    ))}
                                                </div>
                                                {formData.periodeDebut === 'Après-midi' && <p className="mt-1 text-xs text-blue-600">↪ Le congé commence l'après-midi du {new Date(formData.startDate).toLocaleDateString('fr-FR', { weekday: 'short', day: '2-digit', month: 'short' })}</p>}
                                                {formData.periodeDebut === 'Matin' && <p className="mt-1 text-xs text-blue-600">↪ Le congé commence le matin du {new Date(formData.startDate).toLocaleDateString('fr-FR', { weekday: 'short', day: '2-digit', month: 'short' })}</p>}
                                            </div>
                                        )}
                                    </div>

                                    {/* Date fin */}
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-2">
                                            Date fin <span className="text-red-500">*</span>
                                        </label>
                                        <input type="date"
                                            value={formData.endDate}
                                            min={formData.startDate || (formData.types.includes('Formation') ? getMinDateFormation() : getMinDate())}
                                            onChange={(e) => {
                                                const v = e.target.value;
                                                const adj = isWeekend(v) ? getNextWorkingDay(v) : v;
                                                setFormData(prev => ({ ...prev, endDate: adj }));
                                            }}
                                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                                        />
                                        {formData.endDate && !formData.types.includes('Formation') && !isSameDay && (
                                            <div className="mt-2">
                                                <label className="block text-xs text-gray-500 mb-1.5">⏰ Fin de la période</label>
                                                <div className="grid grid-cols-3 gap-2">
                                                    {['Journée entière', 'Matin', 'Après-midi'].map(p => (
                                                        <button key={p} type="button"
                                                            onClick={() => setFormData(prev => ({ ...prev, periodeFin: p }))}
                                                            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${formData.periodeFin === p ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                                                            {p === 'Matin' ? '🌅 Matin' : p === 'Après-midi' ? '☀️ Après-midi' : '🌞 Journée entière'}
                                                        </button>
                                                    ))}
                                                </div>
                                                {formData.periodeFin === 'Matin' && <p className="mt-1 text-xs text-blue-600">↪ Le congé se termine le matin du {new Date(formData.endDate).toLocaleDateString('fr-FR', { weekday: 'short', day: '2-digit', month: 'short' })}</p>}
                                                {formData.periodeFin === 'Après-midi' && <p className="mt-1 text-xs text-blue-600">↪ Le congé se termine l'après-midi du {new Date(formData.endDate).toLocaleDateString('fr-FR', { weekday: 'short', day: '2-digit', month: 'short' })}</p>}
                                            </div>
                                        )}
                                        {isSameDay && !isMixte && !formData.types.includes('Formation') && (
                                            <div className="mt-2">
                                                <label className="block text-xs text-gray-500 mb-1.5">⏰ Période de la journée</label>
                                                <div className="grid grid-cols-3 gap-2">
                                                    {['Matin', 'Après-midi', 'Journée entière'].map(p => (
                                                        <button key={p} type="button"
                                                            onClick={() => setFormData(prev => ({ ...prev, periodeDebut: p, periodeFin: p }))}
                                                            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${formData.periodeDebut === p ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                                                            {p === 'Matin' ? '🌅 Matin' : p === 'Après-midi' ? '☀️ Après-midi' : '🌞 Journée entière'}
                                                        </button>
                                                    ))}
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Récapitulatif jours */}
                                {totalDays > 0 && (
                                    <div className="mt-3 bg-blue-50 border border-blue-200 rounded-lg p-3">
                                        <p className="text-sm font-medium text-blue-900">
                                            Durée : <span className="text-lg font-bold">{getDureeAffichee() ?? totalDays}</span>
                                            <span className="text-sm ml-1">jour{(getDureeAffichee() ?? totalDays) > 1 ? 's' : ''} ouvré{(getDureeAffichee() ?? totalDays) > 1 ? 's' : ''}</span>
                                        </p>
                                        {(formData.periodeDebut === 'Après-midi' || (formData.periodeFin === 'Matin' && !isSameDay)) && (
                                            <p className="text-xs text-blue-700 mt-1">ℹ️ {totalDays} jour{totalDays > 1 ? 's' : ''} calendaire{totalDays > 1 ? 's' : ''} → {getDureeAffichee()}j après déduction des demi-journées</p>
                                        )}
                                        {holidayCount > 0 && <p className="text-xs text-blue-700 mt-1">🎉 {holidayCount} jour{holidayCount > 1 ? 's' : ''} férié{holidayCount > 1 ? 's' : ''} exclu{holidayCount > 1 ? 's' : ''}</p>}
                                        {saturdayCount > 0 && <p className="text-xs text-blue-700">📅 {saturdayCount} samedi{saturdayCount > 1 ? 's' : ''} exclu{saturdayCount > 1 ? 's' : ''}</p>}
                                    </div>
                                )}
                            </div>

                            {/* Type de congé */}
                            <div>
                                <h3 className="text-sm font-semibold text-gray-900 mb-3">📋 TYPE DE CONGÉ</h3>
                                <div className="space-y-2">
                                    {availableTypesOptions.map(type => (
                                        <label key={type.key}
                                            className={`flex items-center gap-3 p-3 border rounded-lg transition-colors ${type.disabled ? 'opacity-50 bg-gray-50 border-gray-200 cursor-not-allowed' : 'cursor-pointer border-gray-200 hover:bg-gray-50'}`}>
                                            <input type="checkbox"
                                                checked={formData.types.includes(type.key)}
                                                disabled={type.disabled}
                                                onChange={() => {
                                                    if (type.disabled) return;
                                                    setFormData(prev => ({
                                                        ...prev,
                                                        types: prev.types.includes(type.key)
                                                            ? prev.types.filter(t => t !== type.key)
                                                            : type.key === 'Formation'
                                                                ? [type.key]
                                                                : [...prev.types.filter(t => t !== 'Formation'), type.key],
                                                        periodeDebut: 'Journée entière',
                                                        periodeFin: 'Journée entière',
                                                    }));
                                                }}
                                                className="w-5 h-5 rounded border-gray-300"
                                            />
                                            <span className="text-sm font-medium text-gray-900">{type.label}</span>
                                            {type.disabled && <span className="ml-auto text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded-full">Solde épuisé</span>}
                                        </label>
                                    ))}
                                </div>
                                {formData.types.includes('Formation') && (
                                    <div className="mt-3 flex items-start gap-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                                        <AlertCircle className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                                        <p className="text-blue-700 text-xs">⚠️ La formation doit être posée au moins <strong>7 jours à l'avance</strong>.</p>
                                    </div>
                                )}
                            </div>

                            {/* Répartition mode mixte */}
                            {isMixte && totalDays > 0 && (
                                <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
                                    <h3 className="text-sm font-semibold text-gray-900 mb-3">
                                        🗓️ RÉPARTITION PAR TYPE
                                        <span className="ml-2 text-xs font-normal text-gray-500">Total à répartir : {getJoursEffectifs()}j ouvrés</span>
                                    </h3>
                                    <div className="space-y-4">
                                        {formData.types.map((t, idx) => {
                                            const isFirst = idx === 0;
                                            const isLast = idx === formData.types.length - 1;

                                            if (isSameDay) {
                                                const segPeriode = repartitionDetails[t]?.periode || (idx === 0 ? 'Matin' : 'Après-midi');
                                                const periodeLabel = { Matin: '🌅 Matin', 'Après-midi': '☀️ Après-midi' };
                                                const autreType = formData.types.find(x => x !== t);
                                                return (
                                                    <div key={t} className="bg-white border border-gray-200 rounded-lg p-3">
                                                        <div className="text-sm font-semibold text-gray-800 mb-3">
                                                            {t === 'CP' && '💼'}{t === 'RTT' && '🌴'}{t === 'Récup' && '🔄'} {t === 'CP' ? 'Congé(s) payé(s)' : t}
                                                        </div>
                                                        <div className="mb-3">
                                                            <label className="text-xs text-gray-500 mb-1.5 block">⏰ Période de la journée</label>
                                                            <div className="grid grid-cols-2 gap-2">
                                                                {['Matin', 'Après-midi'].map(p => {
                                                                    const takenByOther = repartitionDetails[autreType]?.periode === p;
                                                                    return (
                                                                        <button key={p} type="button"
                                                                            disabled={takenByOther}
                                                                            onClick={() => {
                                                                                setRepartitionDetails(prev => {
                                                                                    const next = { ...prev };
                                                                                    next[t] = { ...next[t], periode: p, jours: '0.5', dateDebut: formData.startDate, dateFin: formData.endDate };
                                                                                    if (autreType) {
                                                                                        next[autreType] = { ...next[autreType], periode: p === 'Matin' ? 'Après-midi' : 'Matin', jours: '0.5', dateDebut: formData.startDate, dateFin: formData.endDate };
                                                                                    }
                                                                                    return next;
                                                                                });
                                                                            }}
                                                                            className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${segPeriode === p ? 'bg-blue-600 text-white' : takenByOther ? 'opacity-40 bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                                                                            {periodeLabel[p]}
                                                                        </button>
                                                                    );
                                                                })}
                                                            </div>
                                                        </div>
                                                        <div className="w-full px-2 py-1.5 border border-blue-200 bg-blue-50 rounded text-sm flex items-center justify-between">
                                                            <span className="font-semibold text-blue-800">0.5 jour</span>
                                                            <span className="text-xs font-normal text-blue-500">demi-journée</span>
                                                        </div>
                                                    </div>
                                                );
                                            }

                                            const joursDejaAffectes = formData.types.slice(0, idx).reduce((sum, prevType) => sum + parseFloat(repartitionDetails[prevType]?.jours || 0), 0);
                                            const joursRestants = getJoursEffectifs() - joursDejaAffectes;
                                            const prevType = idx > 0 ? formData.types[idx - 1] : null;
                                            const prevDateFin = prevType ? repartitionDetails[prevType]?.dateFin : null;

                                            const getNextWorkingDayAfter = (dateStr) => {
                                                if (!dateStr) return formData.startDate;
                                                const d = new Date(dateStr);
                                                d.setDate(d.getDate() + 1);
                                                while (d.getDay() === 0 || d.getDay() === 6 || isPublicHoliday(d)) d.setDate(d.getDate() + 1);
                                                return d.toISOString().split('T')[0];
                                            };

                                            const prevSegEndsAtMorning = prevType && (repartitionDetails[prevType]?.periodeFin || 'Journée entière') === 'Matin';
                                            const minDateForType = prevDateFin ? (prevSegEndsAtMorning ? prevDateFin : getNextWorkingDayAfter(prevDateFin)) : formData.startDate;
                                            const defaultNextDateDebut = prevDateFin ? (prevSegEndsAtMorning ? prevDateFin : getNextWorkingDayAfter(prevDateFin)) : '';
                                            const prevSegPeriodeFin = prevType ? (repartitionDetails[prevType]?.periodeFin || 'Journée entière') : 'Journée entière';
                                            const segDateDebut = repartitionDetails[t]?.dateDebut;
                                            const startsOnSameDayAsPrev = prevDateFin && segDateDebut && prevDateFin === segDateDebut;
                                            const segDebutPeriodeAuto = isFirst ? formData.periodeDebut : (startsOnSameDayAsPrev && prevSegPeriodeFin === 'Matin') ? 'Après-midi' : 'Journée entière';
                                            const segDebutPeriode = isFirst ? formData.periodeDebut : (repartitionDetails[t]?.periodeDebut || segDebutPeriodeAuto);
                                            const segFinPeriode = isLast ? formData.periodeFin : (repartitionDetails[t]?.periodeFin || 'Journée entière');

                                            return (
                                                <div key={t} className="bg-white border border-gray-200 rounded-lg p-3">
                                                    <div className="flex items-center justify-between mb-3">
                                                        <div className="text-sm font-semibold text-gray-800">
                                                            {t === 'CP' && '💼'}{t === 'RTT' && '🌴'}{t === 'Récup' && '🔄'} {t === 'CP' ? 'Congé(s) payé(s)' : t}
                                                            {isFirst && formData.periodeDebut !== 'Journée entière' && <span className="ml-2 text-xs font-normal text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded">Début {formData.periodeDebut === 'Après-midi' ? '½ journée' : 'Matin'}</span>}
                                                            {isLast && formData.periodeFin !== 'Journée entière' && <span className="ml-2 text-xs font-normal text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded">Fin {formData.periodeFin === 'Matin' ? '½ journée' : 'Après-midi'}</span>}
                                                        </div>
                                                        {idx > 0 && joursRestants > 0 && !repartitionDetails[t]?.jours && (
                                                            <span className="text-xs px-2 py-0.5 rounded-full bg-orange-100 text-orange-700 font-medium">{joursRestants}j restant{joursRestants > 1 ? 's' : ''} à affecter</span>
                                                        )}
                                                    </div>
                                                    <div className="grid grid-cols-2 gap-2 mb-3">
                                                        <div>
                                                            <label className="text-xs text-gray-500 mb-1 block">Date début</label>
                                                            <input type="date"
                                                                value={repartitionDetails[t]?.dateDebut || (idx > 0 ? defaultNextDateDebut : '')}
                                                                min={minDateForType} max={formData.endDate}
                                                                onChange={e => {
                                                                    const newDateDebut = e.target.value;
                                                                    setRepartitionDetails(prev => {
                                                                        const seg = { ...prev[t], dateDebut: newDateDebut };
                                                                        if (seg.dateFin) seg.jours = calcWorkingDays(newDateDebut, seg.dateFin, segDebutPeriode, segFinPeriode).toString();
                                                                        return { ...prev, [t]: seg };
                                                                    });
                                                                }}
                                                                className="w-full px-2 py-1.5 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500"
                                                            />
                                                        </div>
                                                        <div>
                                                            <label className="text-xs text-gray-500 mb-1 block">Date fin</label>
                                                            <input type="date"
                                                                value={repartitionDetails[t]?.dateFin || (idx > 0 ? formData.endDate : '')}
                                                                min={repartitionDetails[t]?.dateDebut || minDateForType} max={formData.endDate}
                                                                onChange={e => {
                                                                    const newDateFin = e.target.value;
                                                                    setRepartitionDetails(prev => {
                                                                        const seg = { ...prev[t], dateFin: newDateFin };
                                                                        if (seg.dateDebut) seg.jours = calcWorkingDays(seg.dateDebut, newDateFin, segDebutPeriode, segFinPeriode).toString();
                                                                        return { ...prev, [t]: seg };
                                                                    });
                                                                }}
                                                                className="w-full px-2 py-1.5 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500"
                                                            />
                                                        </div>
                                                    </div>
                                                    {!isFirst && (
                                                        <div className="mb-3">
                                                            <label className="text-xs text-gray-500 mb-1.5 block">⏰ Début de ce segment</label>
                                                            <div className="grid grid-cols-2 gap-2">
                                                                {['Journée entière', 'Après-midi'].map(p => (
                                                                    <button key={p} type="button"
                                                                        onClick={() => {
                                                                            setRepartitionDetails(prev => {
                                                                                const seg = { ...prev[t], periodeDebut: p };
                                                                                if (seg.dateDebut && seg.dateFin) seg.jours = calcWorkingDays(seg.dateDebut, seg.dateFin, p, segFinPeriode).toString();
                                                                                return { ...prev, [t]: seg };
                                                                            });
                                                                        }}
                                                                        className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${segDebutPeriode === p ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                                                                        {p === 'Après-midi' ? '☀️ Début après-midi (½j)' : '🌞 Journée entière'}
                                                                    </button>
                                                                ))}
                                                            </div>
                                                            {segDebutPeriode === 'Après-midi' && repartitionDetails[t]?.dateDebut && (
                                                                <p className="mt-1 text-xs text-blue-600">↪ Ce segment commence l'après-midi du {new Date(repartitionDetails[t].dateDebut).toLocaleDateString('fr-FR', { weekday: 'short', day: '2-digit', month: 'short' })}</p>
                                                            )}
                                                        </div>
                                                    )}
                                                    {!isLast && (
                                                        <div className="mb-3">
                                                            <label className="text-xs text-gray-500 mb-1.5 block">⏰ Fin de ce segment</label>
                                                            <div className="grid grid-cols-2 gap-2">
                                                                {['Journée entière', 'Matin'].map(p => (
                                                                    <button key={p} type="button"
                                                                        onClick={() => {
                                                                            setRepartitionDetails(prev => {
                                                                                const seg = { ...prev[t], periodeFin: p };
                                                                                if (seg.dateDebut && seg.dateFin) seg.jours = calcWorkingDays(seg.dateDebut, seg.dateFin, segDebutPeriode, p).toString();
                                                                                return { ...prev, [t]: seg };
                                                                            });
                                                                        }}
                                                                        className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${(repartitionDetails[t]?.periodeFin || 'Journée entière') === p ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                                                                        {p === 'Matin' ? '🌅 Fin le matin (½j)' : '🌞 Journée entière'}
                                                                    </button>
                                                                ))}
                                                            </div>
                                                            {(repartitionDetails[t]?.periodeFin || 'Journée entière') === 'Matin' && repartitionDetails[t]?.dateFin && (
                                                                <p className="mt-1 text-xs text-blue-600">↪ Ce segment se termine le matin du {new Date(repartitionDetails[t].dateFin).toLocaleDateString('fr-FR', { weekday: 'short', day: '2-digit', month: 'short' })}</p>
                                                            )}
                                                        </div>
                                                    )}
                                                    <div>
                                                        <label className="text-xs text-gray-500 mb-1 block">Nb jours ouvrés</label>
                                                        <div className={`w-full px-2 py-1.5 border rounded text-sm flex items-center justify-between ${repartitionDetails[t]?.jours ? 'border-blue-200 bg-blue-50 text-blue-800 font-semibold' : 'border-gray-200 bg-gray-50 text-gray-400'}`}>
                                                            <span>{repartitionDetails[t]?.jours ? `${repartitionDetails[t].jours} jour${parseFloat(repartitionDetails[t].jours) > 1 ? 's' : ''}` : 'Sélectionnez les dates'}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                    <div className={`mt-3 text-center text-xs font-medium px-3 py-1.5 rounded-full ${getTotalReparti() === getJoursEffectifs() ? 'bg-green-100 text-green-700' : 'bg-orange-100 text-orange-700'}`}>
                                        {getTotalReparti() === getJoursEffectifs()
                                            ? `✅ Répartition complète (${getJoursEffectifs()}j)`
                                            : `⚠️ ${getTotalReparti()}j répartis sur ${getJoursEffectifs()}j — il reste ${(getJoursEffectifs() - getTotalReparti()).toFixed(1)}j à affecter`}
                                    </div>
                                </div>
                            )}

                            {/* Motif */}
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-2">💬 MOTIF (optionnel)</label>
                                <textarea
                                    value={formData.reason}
                                    onChange={(e) => setFormData(prev => ({ ...prev, reason: e.target.value }))}
                                    rows={4}
                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 text-sm"
                                    placeholder="Précisez le motif de votre demande..."
                                />
                            </div>

                            {error && (
                                <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                                    <div className="flex items-start gap-2">
                                        <AlertCircle className="w-5 h-5 text-red-600 flex-shrink-0" />
                                        <p className="text-sm text-red-700 whitespace-pre-line">{error}</p>
                                    </div>
                                </div>
                            )}

                            <div className="flex gap-3 pt-4">
                                <button type="button" onClick={onClose}
                                    className="flex-1 px-4 py-2.5 border border-gray-300 rounded-lg hover:bg-gray-50 font-medium text-gray-700">
                                    Annuler
                                </button>
                                <button type="button" onClick={handleSubmit}
                                    disabled={isSubmitting || isLoadingCounters || isLoadingPrev}
                                    className="flex-1 px-4 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium">
                                    {isLoadingPrev ? '⏳ Calcul en cours...' : isSubmitting ? 'Envoi...' : '✓ Soumettre'}
                                </button>
                            </div>
                        </div>

                        {/* ══ COLONNE DROITE (40%) ══ */}
                        <div className="col-span-2 space-y-4">
                            <h3 className="text-sm font-semibold text-gray-900">📊 VOS SOLDES</h3>

                            {isLoadingCounters ? (
                                <div className="bg-gray-50 border border-gray-200 rounded-lg p-6 text-center">
                                    <div className="animate-spin h-6 w-6 border-2 border-blue-600 border-t-transparent rounded-full mx-auto mb-2" />
                                    <p className="text-xs text-gray-600">Chargement...</p>
                                </div>
                            ) : (
                                <>
                                    <ReportCard data={countersData?.data?.cpN1} />
                                    <CompactCounterCard
                                        type="CP"
                                        data={countersData?.data?.cpN}
                                        isExpanded={formData.types.includes('CP')}
                                        previsionnel={formData.types.includes('CP') && formData.startDate ? previsionnel : null}
                                    />
                                    {userRole !== 'Apprenti' && (
                                        <CompactCounterCard
                                            type="RTT"
                                            data={countersData?.data?.rttN}
                                            isExpanded={formData.types.includes('RTT')}
                                        />
                                    )}
                                    <CompactCounterCard
                                        type="Récup"
                                        data={countersData?.data?.recupN}
                                        isExpanded={formData.types.includes('Récup')}
                                    />
                                </>
                            )}

                            <div className="border-t border-gray-200 my-4" />
                            <ImpactPreview />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default NewLeaveRequestModal;