import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useAuth } from '../context/AuthContext';
import Sidebar from '../components/Sidebar';
import {
    Calendar, Clock, Check, X, Save, Lock, Unlock,
    Download, Menu, AlertCircle, ChevronLeft, ChevronRight,
    FileText, TrendingUp, RefreshCw, Info, Sun, Moon, Coffee
} from 'lucide-react';

const CompteRenduActivites = () => {
    const { user } = useAuth();
    const userId = user?.id || user?.CollaborateurADId || user?.ID;

    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [currentDate, setCurrentDate] = useState(new Date());
    const [joursActifs, setJoursActifs] = useState([]);
    const [joursAnnee, setJoursAnnee] = useState([]);
    const [statsAnnuelles, setStatsAnnuelles] = useState(null);
    const [mensuelData, setMensuelData] = useState(null);
    const [congesData, setCongesData] = useState([]);
    const [holidays, setHolidays] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [showSaisieModal, setShowSaisieModal] = useState(false);
    const [selectedJour, setSelectedJour] = useState(null);
    const [showSaisieMasse, setShowSaisieMasse] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [infoMessage, setInfoMessage] = useState(null);

    const hasAccess = () => {
        const userRole = user?.role;
        const typeContrat = user?.TypeContrat || user?.typeContrat;
        return (
            typeContrat === 'forfait-jour' ||
            typeContrat === 'forfait_jour' ||
            userRole === 'Directeur Campus' ||
            userRole === 'Directrice Campus' ||
            userRole === 'RH' ||
            userRole === 'Admin'
        );
    };

    const isRH = user?.role === 'RH' || user?.role === 'Admin';

    const annee = currentDate.getFullYear();
    const mois = currentDate.getMonth() + 1;

    const statsMensuelles = useMemo(() => {
        if (!joursActifs || joursActifs.length === 0) {
            return { totalJours: 0, journeesCompletes: 0, demiJourneesMatin: 0, demiJourneesApresMidi: 0, jpOSF: 0, equivalentJours: 0 };
        }
        let journeesCompletes = 0, demiJourneesMatin = 0, demiJourneesApresMidi = 0, jpOSF = 0;
        joursActifs.forEach(jour => {
            if (jour.JourTravaille !== true && jour.JourTravaille !== 1) return;
            const commentaire = jour.CommentaireRepos || '';
            let periode = 'Journée complète';
            const match = commentaire.match(/^\[PERIODE:(.*?)\]/);
            if (match) periode = match[1];
            let jourDateStr = jour.JourDate;
            if (jour.JourDate instanceof Date) jourDateStr = jour.JourDate.toISOString().split('T')[0];
            else if (typeof jour.JourDate === 'string') jourDateStr = jour.JourDate.split('T')[0];
            const jourDate = new Date(jourDateStr + 'T00:00:00');
            const dayOfWeek = jourDate.getDay();
            if (dayOfWeek === 0 || dayOfWeek === 6) jpOSF++;
            if (periode === 'Matin') demiJourneesMatin++;
            else if (periode === 'Après-midi') demiJourneesApresMidi++;
            else journeesCompletes++;
        });
        const equivalentJours = journeesCompletes + (demiJourneesMatin * 0.5) + (demiJourneesApresMidi * 0.5);
        return {
            totalJours: joursActifs.filter(j => j.JourTravaille === true || j.JourTravaille === 1).length,
            journeesCompletes, demiJourneesMatin, demiJourneesApresMidi, jpOSF, equivalentJours
        };
    }, [joursActifs]);

    const cumulAnnuel = useMemo(() => {
        if (!joursAnnee || joursAnnee.length === 0) return { equivalentJours: 0, jpOSF: 0 };
        let total = 0, jpOSF = 0;
        joursAnnee.forEach(jour => {
            if (jour.JourTravaille !== true && jour.JourTravaille !== 1) return;
            const commentaire = jour.CommentaireRepos || '';
            const match = commentaire.match(/^\[PERIODE:(.*?)\]/);
            const periode = match ? match[1] : 'Journée complète';
            if (periode === 'Matin' || periode === 'Après-midi') total += 0.5;
            else total += 1;
            let jourDateStr = jour.JourDate;
            if (typeof jour.JourDate === 'string') jourDateStr = jour.JourDate.split('T')[0];
            const jourDate = new Date(jourDateStr + 'T00:00:00');
            if (jourDate.getDay() === 0 || jourDate.getDay() === 6) jpOSF++;
        });
        return { equivalentJours: total, jpOSF };
    }, [joursAnnee]);

    const fetchFrenchHolidays = async (year) => {
        try {
            const response = await fetch(`https://calendrier.api.gouv.fr/jours-feries/metropole/${year}.json`);
            if (!response.ok) throw new Error(`Erreur API: ${response.status}`);
            const data = await response.json();
            return Object.keys(data).map(dateStr => {
                const [y, m, d] = dateStr.split('-').map(Number);
                return { date: new Date(y, m - 1, d), name: data[dateStr] };
            });
        } catch (error) {
            console.error('Erreur jours fériés:', error);
            return [];
        }
    };

    useEffect(() => {
        fetchFrenchHolidays(currentDate.getFullYear()).then(setHolidays);
    }, [currentDate]);

    const isHoliday = (date) => {
        if (!date) return false;
        return holidays.some(h =>
            h.date.getDate() === date.getDate() &&
            h.date.getMonth() === date.getMonth() &&
            h.date.getFullYear() === date.getFullYear()
        );
    };

    const getHolidayName = (date) => {
        const holiday = holidays.find(h =>
            h.date.getDate() === date.getDate() &&
            h.date.getMonth() === date.getMonth() &&
            h.date.getFullYear() === date.getFullYear()
        );
        return holiday?.name;
    };

    const loadMesCongesPersonnels = useCallback(async () => {
        if (!userId) return [];
        try {
            const response = await fetch(`/api/getMesCongesPersonnels?user_id=${userId}`);
            const data = await response.json();
            if (data.success) return data.conges || [];
            return [];
        } catch (error) {
            console.error('Erreur chargement congés personnels:', error);
            return [];
        }
    }, [userId]);

    const loadCompteRendu = useCallback(async () => {
        if (!userId || !hasAccess()) return;
        setIsLoading(true);
        try {
            const response = await fetch(`/api/getCompteRenduActivites?user_id=${userId}&annee=${annee}&mois=${mois}`);
            const data = await response.json();
            if (data.success) {
                setJoursActifs(data.jours || []);
                setMensuelData(data.mensuel);
            }
            const mesConges = await loadMesCongesPersonnels();
            setCongesData(mesConges);
        } catch (error) {
            console.error('Erreur chargement compte-rendu:', error);
        } finally {
            setIsLoading(false);
        }
    }, [userId, annee, mois, loadMesCongesPersonnels]);

    const loadStatsAnnuelles = useCallback(async () => {
        if (!userId || !hasAccess()) return;
        try {
            const response = await fetch(`/api/getStatsAnnuelles?user_id=${userId}&annee=${annee}`);
            const data = await response.json();
            if (data.success) setStatsAnnuelles(data.stats);
            const allJours = [];
            for (let m = 1; m <= 12; m++) {
                try {
                    const resp = await fetch(`/api/getCompteRenduActivites?user_id=${userId}&annee=${annee}&mois=${m}`);
                    const moisData = await resp.json();
                    if (moisData.success && moisData.jours) allJours.push(...moisData.jours);
                } catch (e) { }
            }
            setJoursAnnee(allJours);
        } catch (error) {
            console.error('Erreur stats annuelles:', error);
        }
    }, [userId, annee]);

    useEffect(() => {
        loadCompteRendu();
        loadStatsAnnuelles();
    }, [loadCompteRendu, loadStatsAnnuelles]);

    const isMoisAutorise = () => {
        const today = new Date();
        const currentYear = today.getFullYear();
        const currentMonth = today.getMonth() + 1;
        const selectedYear = currentDate.getFullYear();
        const selectedMonth = currentDate.getMonth() + 1;
        if (isRH) return true;
        if (selectedYear === currentYear && selectedMonth === currentMonth) return true;
        const previousMonth = currentMonth === 1 ? 12 : currentMonth - 1;
        const previousYear = currentMonth === 1 ? currentYear - 1 : currentYear;
        return selectedYear === previousYear && selectedMonth === previousMonth;
    };

    const getDaysInMonth = () => {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);
        const daysInMonth = lastDay.getDate();
        let firstDayOfWeek = firstDay.getDay();
        firstDayOfWeek = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1;
        const days = [];
        for (let i = 0; i < firstDayOfWeek; i++) days.push(null);
        for (let day = 1; day <= daysInMonth; day++) days.push(new Date(year, month, day));
        return days;
    };

    const formatDateToString = (date) => {
        if (!date) return null;
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    const getJourData = (date) => {
        const dateStr = formatDateToString(date);
        return joursActifs.find(j => {
            let jourDateStr = j.JourDate;
            if (j.JourDate instanceof Date) jourDateStr = formatDateToString(j.JourDate);
            else if (typeof j.JourDate === 'string') jourDateStr = j.JourDate.split('T')[0];
            return jourDateStr === dateStr;
        });
    };

    // ✅ CORRECTIF : getCongeInfo cherche le détail par date précise + normalisation des chaînes
    const getCongeInfo = (date) => {
        if (!date) return null;
        const checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        const checkDateStr = formatDateToString(date);

        for (const conge of congesData) {
            const startParts = conge.startdate.split('T')[0].split('-');
            const endParts = conge.enddate.split('T')[0].split('-');
            const start = new Date(parseInt(startParts[0]), parseInt(startParts[1]) - 1, parseInt(startParts[2]));
            const end = new Date(parseInt(endParts[0]), parseInt(endParts[1]) - 1, parseInt(endParts[2]));
            const isInRange = checkDate >= start && checkDate <= end;
            const isValide = conge.statut === 'Validée' || conge.statut === 'Validé' || conge.statut === 'Valide';

            if (isInRange && isValide) {
                const typeStr = (conge.type || '').toUpperCase();
                if (typeStr.includes('TÉLÉTRAVAIL') || typeStr.includes('TELETRAVAIL') || typeStr.includes('REMOTE')) {
                    continue;
                }
                const isJPOSF =
                    conge.isJPOSFOnly === 1 || conge.isJPOSFOnly === true || conge.isJPOSFOnly === '1' ||
                    typeStr === 'JPOSF' || typeStr.includes('JPOSF');

                let periodeConge = 'Journée entière', isDemiJournee = false, periodeSaisissable = null;

                try {
                    if (conge.detailsconges) {
                        const details = JSON.parse(conge.detailsconges);
                        if (details && details.length > 0) {
                            const detailDuJour = details.find(d => {
                                if (!d.date) return false;
                                return d.date.split('T')[0] === checkDateStr;
                            }) || details[0];

                            const periode = detailDuJour?.periode || 'Journée entière';
                            periodeConge = periode;

                            const p = periode.toLowerCase().replace(/[\s_]/g, '-');
                            if (
                                p.includes('matin') ||
                                p.includes('après-midi') ||
                                p.includes('apres-midi') ||
                                p === 'am' ||
                                p === 'pm'
                            ) {
                                isDemiJournee = true;
                            }

                            // ✅ AJOUT : détecter demi-journée via NombreJours si periode pas explicite
                            if (!isDemiJournee && detailDuJour?.jours === 0.5) {
                                isDemiJournee = true;
                                // On ne sait pas laquelle — on laisse periodeConge à 'Journée entière'
                                // mais isDemiJournee = true déclenchera la logique de force
                            }
                        }
                    }
                } catch (e) { }

                if (isDemiJournee) {
                    const p = periodeConge.toLowerCase().replace(/[\s_]/g, '-');
                    if (p.includes('matin') || p === 'am')
                        periodeSaisissable = 'Après-midi';
                    else if (p.includes('après-midi') || p.includes('apres-midi') || p === 'pm')
                        periodeSaisissable = 'Matin';
                    // ✅ Si on ne sait pas (jours=0.5 mais periode=Journée entière)
                    // on ne force pas — le collaborateur choisit
                }

                return { type: conge.type, isJPOSF, periodeConge, isDemiJournee, periodeSaisissable, color: conge.color };
            }
        }
        return null;
    };
    const isJPOSF = (date) => getCongeInfo(date)?.isJPOSF || false;
    const isDemiJourneeConge = (date) => getCongeInfo(date)?.isDemiJournee || false;

    const isJourComplètementBloque = (date) => {
        const info = getCongeInfo(date);
        if (!info) return false;          // ← guard null (comme dans le composant parent)
        if (info.isJPOSF) return false;
        if (info.isDemiJournee) return false;
        return true;
    };

    const isWeekend = (date) => {
        if (!date) return false;
        return date.getDay() === 0 || date.getDay() === 6;
    };

    const isPastOnly = (date) => {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const checkDate = new Date(date);
        checkDate.setHours(0, 0, 0, 0);
        return checkDate < today;
    };

    const isJourVerrouille = (date) => {
        const jourData = getJourData(date);
        return jourData?.Verrouille === true || jourData?.Verrouille === 1;
    };

    const isJourDejaSaisi = (date) => {
        const jourData = getJourData(date);
        return jourData !== undefined && jourData !== null;
    };

    const showInfo = (message, type = 'info') => {
        setInfoMessage({ message, type });
        setTimeout(() => setInfoMessage(null), 5000);
    };

    const extractPeriodeFromCommentaire = (commentaire) => {
        if (!commentaire) return { periode: 'Journée complète', commentaireClean: '' };
        const match = commentaire.match(/^\[PERIODE:(.*?)\]\s*/);
        if (match) return { periode: match[1], commentaireClean: commentaire.replace(match[0], '') };
        return { periode: 'Journée complète', commentaireClean: commentaire };
    };

    const handleJourClick = (date) => {
        if (!date) return;
        const congeInfo = getCongeInfo(date);
        // ✅ DEBUG TEMPORAIRE
        console.log('congeInfo:', JSON.stringify(congeInfo, null, 2));
        console.log('congesData JPOSF:', congesData.filter(c =>
            (c.type || '').toUpperCase().includes('JPOSF')
        ).map(c => ({
            type: c.type,
            isJPOSFOnly: c.isJPOSFOnly,
            detailsconges: c.detailsconges,
            nombrejoursouvres: c.nombrejoursouvres
        })));
        const jourJPOSF = congeInfo?.isJPOSF || false;
        const demiJourneeConge = congeInfo?.isDemiJournee && !jourJPOSF || false;

        if (!isMoisAutorise() && !isRH) {
            showInfo('Vous ne pouvez saisir que pour le mois en cours ou le mois précédent', 'warning');
            return;
        }

        if (!isPastOnly(date)) {
            showInfo('Vous ne pouvez pas saisir le jour actuel. Veuillez attendre demain.', 'warning');
            return;
        }

        if (isJourDejaSaisi(date)) {
            showInfo(
                isRH
                    ? 'Ce jour est déjà saisi. Supprimez la saisie en base avant de la modifier.'
                    : 'Ce jour est déjà saisi. Contactez les RH pour toute modification.',
                'error'
            );
            return;
        }

        if (isWeekend(date) && !jourJPOSF) {
            showInfo('Les samedis et dimanches ne peuvent pas être saisis', 'info');
            return;
        }

        if (isHoliday(date)) {
            showInfo(`Jour férié : ${getHolidayName(date)} - Saisie impossible`, 'info');
            return;
        }

        if (isJourComplètementBloque(date)) {
            showInfo('Vous êtes en congé ce jour (journée entière) - Saisie impossible', 'info');
            return;
        }

        if (isJourVerrouille(date) && !isRH) {
            showInfo('Ce jour est déjà verrouillé - Contactez les RH pour modification', 'error');
            return;
        }

        const jourData = getJourData(date);
        const { periode, commentaireClean } = extractPeriodeFromCommentaire(jourData?.CommentaireRepos);
        let periodeInitiale = periode;
        let periodesForcees = null;

        // ✅ CORRECTIF : JPOSF demi-journée ET congé demi-journée forcent la période
        const estDemiJourneeForce = demiJourneeConge || (jourJPOSF && congeInfo?.isDemiJournee);

        if (estDemiJourneeForce) {
            if (congeInfo?.periodeSaisissable) {
                // Période explicite (matin ou après-midi connu)
                periodeInitiale = congeInfo.periodeSaisissable;
                periodesForcees = [congeInfo.periodeSaisissable];
            } else {
                // 0.5j mais période non précisée → bloquer "Journée complète" seulement
                periodeInitiale = 'Matin';
                periodesForcees = ['Matin', 'Après-midi'];
            }
        }

        setSelectedJour({
            date,
            dateStr: formatDateToString(date),
            jourTravaille: true,
            reposQuotidien: true,
            reposHebdo: true,
            commentaire: '',
            periode: periodeInitiale,
            periodesForcees,
            isJPOSF: jourJPOSF,
            isDemiJourneeConge: demiJourneeConge,
            congeInfo
        });
        setShowSaisieModal(true);
        console.log('isDemiJournee:', congeInfo?.isDemiJournee);
        console.log('periodeSaisissable:', congeInfo?.periodeSaisissable);
        console.log('estDemiJourneeForce:', estDemiJourneeForce);
        console.log('periodesForcees:', periodesForcees);
    };

    const handleSaveJour = async () => {
        const isVendredi = selectedJour.date.getDay() === 5;
        if (isVendredi) {
            if (!selectedJour.reposQuotidien || !selectedJour.reposHebdo) {
                if (!selectedJour.commentaire || selectedJour.commentaire.trim() === '') {
                    showInfo('Commentaire obligatoire en cas de non-respect des repos', 'warning');
                    return;
                }
            }
        } else {
            if (!selectedJour.reposQuotidien) {
                if (!selectedJour.commentaire || selectedJour.commentaire.trim() === '') {
                    showInfo('Commentaire obligatoire en cas de non-respect du repos quotidien', 'warning');
                    return;
                }
            }
        }
        setIsSaving(true);
        try {
            const response = await fetch('/api/saveCompteRenduJour', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    user_id: userId,
                    date: selectedJour.dateStr,
                    jour_travaille: selectedJour.jourTravaille,
                    repos_quotidien: selectedJour.reposQuotidien,
                    repos_hebdo: isVendredi ? selectedJour.reposHebdo : true,
                    commentaire: selectedJour.commentaire,
                    periode: selectedJour.periode,
                    rh_override: isRH
                })
            });
            const data = await response.json();
            if (data.success) {
                await loadCompteRendu();
                await loadStatsAnnuelles();
                setShowSaisieModal(false);
                showInfo('✅ Jour enregistré', 'success');
            } else {
                showInfo(data.message || 'Erreur lors de la sauvegarde', 'error');
            }
        } catch (error) {
            console.error('Erreur sauvegarde jour:', error);
            showInfo('Erreur serveur', 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleSaisieMasse = async (joursTravailles) => {
        if (!isMoisAutorise() && !isRH) {
            showInfo('Vous ne pouvez saisir que pour le mois en cours ou le mois précédent', 'warning');
            return;
        }
        setIsSaving(true);
        try {
            const response = await fetch('/api/saveCompteRenduMasse', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    user_id: userId,
                    annee,
                    mois,
                    jours: joursTravailles,
                    rh_override: isRH
                })
            });
            const data = await response.json();
            if (data.success) {
                await loadCompteRendu();
                await loadStatsAnnuelles();
                setShowSaisieMasse(false);
                showInfo(data.message || `✅ ${data.count || 0} jours enregistrés`, 'success');
            } else {
                showInfo(data.message || 'Erreur', 'error');
            }
        } catch (error) {
            console.error('Erreur saisie masse:', error);
            showInfo('Erreur serveur', 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const navigateMonth = (direction) => {
        setCurrentDate(prev => {
            const newDate = new Date(prev);
            if (direction === 'prev') newDate.setMonth(prev.getMonth() - 1);
            else newDate.setMonth(prev.getMonth() + 1);
            return newDate;
        });
    };

    const monthNames = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
        'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
    const days = getDaysInMonth();
    const moisAutorise = isMoisAutorise();

    if (!hasAccess()) {
        return (
            <div className="min-h-screen bg-gray-50 flex">
                <Sidebar isOpen={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} />
                <div className="flex-1 lg:ml-60 p-8">
                    <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-6 text-center">
                        <AlertCircle className="w-12 h-12 text-yellow-600 mx-auto mb-4" />
                        <h2 className="text-xl font-bold text-gray-900 mb-2">Accès restreint</h2>
                        <p className="text-gray-600 mb-4">Cette fonctionnalité est réservée aux :</p>
                        <ul className="text-gray-700 space-y-2 text-left max-w-md mx-auto">
                            <li className="flex items-center gap-2"><Check className="w-4 h-4 text-green-600" />Collaborateurs en forfait jour</li>
                            <li className="flex items-center gap-2"><Check className="w-4 h-4 text-green-600" />Directeurs et directrices de campus</li>
                            <li className="flex items-center gap-2"><Check className="w-4 h-4 text-green-600" />Service RH</li>
                        </ul>
                    </div>
                </div>
            </div>
        );
    }

    if (isLoading) {
        return (
            <div className="min-h-screen bg-gray-50 flex">
                <Sidebar isOpen={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} />
                <div className="flex-1 lg:ml-60 flex items-center justify-center">
                    <div className="text-center">
                        <RefreshCw className="w-12 h-12 animate-spin text-cyan-600 mx-auto mb-4" />
                        <p className="text-gray-600">Chargement...</p>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gray-50 flex">
            <Sidebar isOpen={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} />
            <div className="flex-1 lg:ml-60 p-4 lg:p-8">

                {infoMessage && (
                    <div className={`mb-4 p-4 rounded-lg border-l-4 flex items-center gap-3 animate-slideIn ${infoMessage.type === 'success' ? 'bg-green-50 border-green-500' :
                        infoMessage.type === 'error' ? 'bg-red-50 border-red-500' :
                            infoMessage.type === 'warning' ? 'bg-orange-50 border-orange-500' :
                                'bg-blue-50 border-blue-500'
                        }`}>
                        <Info className={`w-5 h-5 flex-shrink-0 ${infoMessage.type === 'success' ? 'text-green-600' :
                            infoMessage.type === 'error' ? 'text-red-600' :
                                infoMessage.type === 'warning' ? 'text-orange-600' : 'text-blue-600'
                            }`} />
                        <p className={`text-sm font-medium ${infoMessage.type === 'success' ? 'text-green-800' :
                            infoMessage.type === 'error' ? 'text-red-800' :
                                infoMessage.type === 'warning' ? 'text-orange-800' : 'text-blue-800'
                            }`}>{infoMessage.message}</p>
                    </div>
                )}

                {/* Header */}
                <div className="mb-6">
                    <div className="flex items-center justify-between mb-4">
                        <div>
                            <h1 className="text-2xl lg:text-3xl font-bold text-gray-900">Compte-Rendu d'Activités</h1>
                            <p className="text-sm text-gray-600 mt-1">Forfait jour - Suivi des jours travaillés et repos obligatoires</p>
                        </div>
                        <button onClick={() => setSidebarOpen(true)} className="lg:hidden p-2 rounded-lg bg-white border">
                            <Menu className="w-6 h-6" />
                        </button>
                    </div>

                    {/* Stats */}
                    <div className="bg-gradient-to-r from-cyan-500 via-blue-500 to-purple-500 rounded-xl shadow-md p-6 text-white">
                        <div className="grid grid-cols-3 gap-6">
                            <div className="text-center">
                                <div className="flex items-center justify-center gap-2 mb-3">
                                    <TrendingUp className="w-5 h-5" />
                                    <h3 className="text-sm font-semibold opacity-90">Cumul annuel {annee}</h3>
                                </div>
                                <div className="bg-white bg-opacity-20 rounded-lg p-4">
                                    <p className="text-4xl font-bold">
                                        {cumulAnnuel.equivalentJours % 1 === 0 ? cumulAnnuel.equivalentJours : cumulAnnuel.equivalentJours.toFixed(1)}
                                        <span className="text-lg ml-1 opacity-75">j</span>
                                    </p>
                                </div>
                            </div>
                            <div className="text-center">
                                <div className="flex items-center justify-center gap-2 mb-3">
                                    <Calendar className="w-5 h-5" />
                                    <h3 className="text-sm font-semibold opacity-90">Cumul {monthNames[mois - 1]}</h3>
                                </div>
                                <div className="bg-white bg-opacity-20 rounded-lg p-4">
                                    <p className="text-4xl font-bold">
                                        {statsMensuelles.equivalentJours % 1 === 0 ? statsMensuelles.equivalentJours : statsMensuelles.equivalentJours.toFixed(1)}
                                        <span className="text-lg ml-1 opacity-75">j</span>
                                    </p>
                                </div>
                            </div>
                            <div className="text-center">
                                <div className="flex items-center justify-center gap-2 mb-3">
                                    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-orange-500 text-white">JPOSF</span>
                                    <h3 className="text-sm font-semibold opacity-90">{monthNames[mois - 1]}</h3>
                                </div>
                                <div className="bg-orange-400 bg-opacity-30 rounded-lg p-4">
                                    <p className="text-4xl font-bold">{statsMensuelles.jpOSF}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {!moisAutorise && !isRH && (
                    <div className="bg-yellow-50 border-l-4 border-yellow-500 p-4 mb-6 rounded">
                        <div className="flex items-center gap-3">
                            <AlertCircle className="w-6 h-6 text-yellow-600" />
                            <div>
                                <p className="font-semibold text-yellow-900">Mois non accessible</p>
                                <p className="text-sm text-yellow-700">Vous pouvez saisir uniquement le mois en cours et le mois précédent.</p>
                            </div>
                        </div>
                    </div>
                )}

                {/* Navigation */}
                <div className="bg-white rounded-lg border p-4 mb-6">
                    <div className="flex flex-col lg:flex-row items-center justify-between gap-4">
                        <div className="flex items-center gap-4">
                            <button onClick={() => navigateMonth('prev')} className="p-2 hover:bg-gray-100 rounded">
                                <ChevronLeft className="w-5 h-5 text-blue-600" />
                            </button>
                            <h2 className="text-xl font-semibold min-w-[200px] text-center">
                                {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
                            </h2>
                            <button onClick={() => navigateMonth('next')} className="p-2 hover:bg-gray-100 rounded">
                                <ChevronRight className="w-5 h-5 text-blue-600" />
                            </button>
                        </div>
                        <div className="flex items-center gap-3 flex-wrap">
                            <span className="text-sm text-gray-600">
                                {statsMensuelles.totalJours} saisie{statsMensuelles.totalJours > 1 ? 's' : ''}
                                {statsMensuelles.equivalentJours !== statsMensuelles.totalJours && (
                                    <span className="text-purple-600 ml-1">
                                        ({statsMensuelles.equivalentJours % 1 === 0 ? statsMensuelles.equivalentJours : statsMensuelles.equivalentJours.toFixed(1)} j éq.)
                                    </span>
                                )}
                            </span>
                            <button
                                onClick={() => setShowSaisieMasse(true)}
                                disabled={!moisAutorise && !isRH}
                                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                            >
                                <FileText className="w-4 h-4" />
                                <span className="hidden sm:inline">Saisie en masse</span>
                            </button>
                        </div>
                    </div>
                </div>

                {/* Calendrier */}
                <div className="bg-white rounded-lg border overflow-hidden shadow-sm">
                    <div className="grid grid-cols-7 gap-2 p-4 bg-gray-50">
                        {['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'].map(day => (
                            <div key={day} className="text-center font-semibold text-gray-700 text-sm">{day}</div>
                        ))}
                    </div>
                    <div className="grid grid-cols-7 gap-2 p-4">
                        {days.map((date, index) => {
                            if (date === null) return <div key={`empty-${index}`} className="min-h-[100px] p-3"></div>;

                            const jourData = getJourData(date);
                            const congeInfo = getCongeInfo(date);
                            const jourJPOSF = congeInfo?.isJPOSF || false;
                            const demiJourneeConge = congeInfo?.isDemiJournee || false;
                            const jourComplètementBloque = isJourComplètementBloque(date);
                            const weekend = isWeekend(date);
                            const weekendBloquant = weekend && !jourJPOSF;
                            const ferie = isHoliday(date);
                            const isPast = isPastOnly(date);
                            const isToday = date.toDateString() === new Date().toDateString();
                            const jourDejaSaisi = isJourDejaSaisi(date);

                            let bgClass = 'bg-white hover:bg-gray-50';
                            let cursorClass = 'cursor-pointer hover:shadow-md';

                            if (ferie) {
                                bgClass = 'bg-gray-700 text-white';
                                cursorClass = 'cursor-not-allowed';
                            } else if (weekendBloquant) {
                                bgClass = 'bg-gray-100';
                                cursorClass = 'cursor-not-allowed';
                            } else if (jourComplètementBloque) {
                                bgClass = 'bg-purple-100';
                                cursorClass = 'cursor-not-allowed';
                            } else if (jourDejaSaisi) {
                                bgClass = 'bg-gray-300';
                                cursorClass = 'cursor-not-allowed';
                            } else if (demiJourneeConge) {
                                bgClass = 'bg-purple-50 hover:bg-purple-100';
                                cursorClass = 'cursor-pointer hover:shadow-md';
                            } else if (jourJPOSF) {
                                bgClass = 'bg-orange-100 hover:bg-orange-200';
                                cursorClass = 'cursor-pointer hover:shadow-md';
                            }

                            return (
                                <div
                                    key={index}
                                    onClick={() => handleJourClick(date)}
                                    className={`
                                        min-h-[100px] p-3 rounded-lg border-2 transition-all
                                        ${isToday ? 'border-cyan-500' : 'border-gray-200'}
                                        ${bgClass} ${cursorClass}
                                        ${!isPast && !isRH ? 'opacity-40 cursor-not-allowed' : ''}
                                        ${!moisAutorise && !isRH ? 'opacity-60 cursor-not-allowed' : ''}
                                    `}
                                    title={
                                        ferie ? getHolidayName(date) :
                                            weekendBloquant ? 'Week-end - Non saisissable' :
                                                jourComplètementBloque ? `En congé (${congeInfo?.type})` :
                                                    jourDejaSaisi ? 'Jour saisi 🔒 - Non modifiable' :
                                                        demiJourneeConge ? `½ journée ${congeInfo?.periodeConge} - Saisir ${congeInfo?.periodeSaisissable}` :
                                                            jourJPOSF ? 'JPOSF - Cliquer pour saisir' : ''
                                    }
                                >
                                    <div className={`text-right text-sm font-semibold mb-2 flex items-center justify-end gap-1 ${ferie ? 'text-white' :
                                        weekendBloquant ? 'text-gray-500' :
                                            jourComplètementBloque ? 'text-purple-700' :
                                                demiJourneeConge ? 'text-purple-700' :
                                                    jourJPOSF ? 'text-orange-700' :
                                                        'text-gray-700'
                                        }`}>
                                        {date.getDate()}
                                        {jourDejaSaisi && !ferie && !jourComplètementBloque && !weekendBloquant && (
                                            <Lock className="w-3 h-3 text-red-600" />
                                        )}
                                    </div>

                                    {ferie ? (
                                        <div className="text-center"><div className="text-xs text-white font-bold truncate">{getHolidayName(date)}</div></div>
                                    ) : weekendBloquant ? (
                                        <div className="text-center"><div className="text-xs text-gray-500 font-semibold">Week-end</div></div>
                                    ) : jourComplètementBloque ? (
                                        <div className="text-center">
                                            <div className="text-xs text-purple-700 font-semibold">En congé</div>
                                            {congeInfo?.type && <div className="text-xs text-purple-600 mt-1">{congeInfo.type}</div>}
                                        </div>
                                    ) : demiJourneeConge ? (
                                        <div className="space-y-1">
                                                        {congeInfo?.type && !congeInfo.type.startsWith("Congé") && (
                                                            <div className="text-center">
                                                                <span className="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-bold bg-purple-500 text-white">
                                                                    ½ {congeInfo.periodeConge.toLowerCase().replace(/[\s_]/g, '-').includes('matin') ? 'Matin' : 'PM'}
                                                                </span>
                                                            </div>
                                                        )}
                                            <div className="text-xs text-purple-600 text-center">
                                                {congeInfo.periodeConge.toLowerCase().replace(/[\s_]/g, '-').includes('matin') ? 'matin' : 'après-midi'}
                                            </div>
                                            {jourData ? (
                                                <div className="text-center text-xs text-green-700 font-semibold">✓ {congeInfo.periodeSaisissable} saisi 🔒</div>
                                            ) : (
                                                <div className="text-center text-xs text-purple-700 mt-1">Saisir {congeInfo.periodeSaisissable}</div>
                                            )}
                                        </div>
                                    ) : jourJPOSF ? (
                                    <div className="space-y-1">
                                        <div className="text-center">
                                            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-orange-500 text-white">JPOSF</span>
                                            {congeInfo?.isDemiJournee && (
                                                <span className="ml-1 text-xs text-orange-700 font-semibold">½ j</span>
                                            )}
                                        </div>
                                        {jourData ? (
                                            <div className="text-center text-xs text-green-700 font-semibold">✓ Saisi 🔒</div>
                                        ) : (
                                            <div className="text-center text-xs text-orange-600 mt-1">Cliquer si travaillé</div>
                                        )}
                                    </div>
                                       ) : demiJourneeConge?(
                                        <div className="space-y-1">
                                            <div className="flex items-center gap-1 text-xs">
                                                {jourData.JourTravaille ? <Check className="w-3 h-3 text-gray-700" /> : <X className="w-3 h-3 text-gray-700" />}
                                                <span className="text-gray-700 truncate">{jourData.JourTravaille ? 'Travaillé' : 'Non travaillé'}</span>
                                            </div>
                                            {jourData.CommentaireRepos?.includes('[PERIODE:') && (
                                                <div className="flex items-center gap-1 text-xs text-blue-600">
                                                    {jourData.CommentaireRepos.includes('Matin') ? (
                                                        <><Sun className="w-3 h-3" /><span>Matin</span></>
                                                    ) : jourData.CommentaireRepos.includes('Après-midi') ? (
                                                        <><Moon className="w-3 h-3" /><span>Après-midi</span></>
                                                    ) : null}
                                                </div>
                                            )}
                                            {!jourData.ReposQuotidienRespect && (
                                                <div className="flex items-center gap-1 text-xs text-gray-700">
                                                    <AlertCircle className="w-3 h-3" /><span className="truncate">Repos quotidien</span>
                                                </div>
                                            )}
                                            {!jourData.ReposHebdomadaireRespect && (
                                                <div className="flex items-center gap-1 text-xs text-gray-700">
                                                    <AlertCircle className="w-3 h-3" /><span className="truncate">Repos hebdo</span>
                                                </div>
                                            )}
                                            <div className="text-center text-xs font-semibold mt-2 text-gray-600">Saisi 🔒</div>
                                        </div>
                                    ) : (
                                        <div className="text-center text-xs text-gray-400">
                                            {(isPast || isRH) && moisAutorise ? 'Cliquer pour saisir' : 'Non disponible'}
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* Légende */}
                <div className="mt-4 flex flex-wrap items-center gap-4 text-sm text-gray-600">
                    <div className="flex items-center gap-2"><div className="w-4 h-4 bg-cyan-50 border-2 border-cyan-500 rounded"></div><span>Aujourd'hui</span></div>
                    <div className="flex items-center gap-2"><div className="w-4 h-4 bg-gray-300 border-2 border-gray-200 rounded"></div><Lock className="w-3 h-3 text-red-600" /><span>Saisi (non modifiable)</span></div>
                    <div className="flex items-center gap-2"><div className="w-4 h-4 bg-gray-100 border-2 border-gray-200 rounded"></div><span>Week-end</span></div>
                    <div className="flex items-center gap-2"><div className="w-4 h-4 bg-purple-100 border-2 border-gray-200 rounded"></div><span>Congé (journée)</span></div>
                    <div className="flex items-center gap-2"><div className="w-4 h-4 bg-purple-50 border-2 border-purple-300 rounded"></div><span>½ congé (saisissable)</span></div>
                    <div className="flex items-center gap-2"><div className="w-4 h-4 bg-orange-100 border-2 border-orange-300 rounded"></div><span>JPOSF (saisissable)</span></div>
                    <div className="flex items-center gap-2"><div className="w-4 h-4 bg-gray-700 rounded"></div><span>Jour férié</span></div>
                </div>
            </div>

            {/* Modal saisie unitaire */}
            {showSaisieModal && selectedJour && (
                <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
                    <div className="bg-white rounded-xl shadow-xl max-w-lg w-full p-6 max-h-[90vh] overflow-y-auto">
                        <h3 className="text-xl font-bold text-gray-900 mb-4">
                            Saisie du {selectedJour.date.toLocaleDateString('fr-FR', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
                        </h3>

                        {selectedJour.isJPOSF && !selectedJour.periodesForcees && (
                            <div className="bg-orange-50 border border-orange-200 rounded-lg p-3 mb-4">
                                <div className="flex items-center gap-2">
                                    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-orange-500 text-white">JPOSF</span>
                                    <span className="text-sm text-orange-800">Ce jour est un JPOSF (travail week-end).</span>
                                </div>
                            </div>
                        )}

                        {selectedJour.isJPOSF && selectedJour.periodesForcees && (
                            <div className="bg-orange-50 border border-orange-200 rounded-lg p-3 mb-4">
                                <div className="flex items-center gap-2">
                                    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-orange-500 text-white">JPOSF</span>
                                    <span className="text-sm text-orange-800">
                                        JPOSF ½ journée —{' '}
                                        <strong>{selectedJour.periodesForcees[0]}</strong> uniquement.
                                    </span>
                                </div>
                            </div>
                        )}

                       

                        <div className="space-y-4">
                            {/* Période */}
                            <div className="border rounded-lg p-4 bg-blue-50">
                                <label className="block text-sm font-medium text-gray-700 mb-3">Période travaillée</label>
                                <div className="grid grid-cols-3 gap-2">
                                    {[
                                        { value: 'Journée complète', icon: <Coffee className="w-5 h-5 mb-1 text-blue-600" />, label: 'Journée', sub: 'complète', activeClass: 'border-blue-500 bg-blue-100' },
                                        { value: 'Matin', icon: <Sun className="w-5 h-5 mb-1 text-yellow-600" />, label: 'Matin', sub: '½ journée', activeClass: 'border-yellow-500 bg-yellow-100' },
                                        { value: 'Après-midi', icon: <Moon className="w-5 h-5 mb-1 text-indigo-600" />, label: 'Après-midi', sub: '½ journée', activeClass: 'border-indigo-500 bg-indigo-100' },
                                    ].map(({ value, icon, label, sub, activeClass }) => {
                                        const isForced = selectedJour.periodesForcees && !selectedJour.periodesForcees.includes(value);
                                        return (
                                            <button
                                                key={value}
                                                type="button"
                                                onClick={() => !isForced && setSelectedJour({ ...selectedJour, periode: value })}
                                                disabled={isForced}
                                                className={`flex flex-col items-center p-3 rounded-lg border-2 transition-all ${selectedJour.periode === value ? activeClass :
                                                    isForced ? 'border-gray-200 bg-gray-100 opacity-50 cursor-not-allowed' :
                                                        'border-gray-200 bg-white hover:bg-gray-50'
                                                    }`}
                                            >
                                                {icon}
                                                <span className="text-xs font-medium">{label}</span>
                                                <span className="text-xs text-gray-500">{sub}</span>
                                            </button>
                                        );
                                    })}
                                </div>
                            </div>

                            {/* Repos quotidien */}
                            <div className="border-t pt-4">
                                <label className="flex items-start gap-3 cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={selectedJour.reposQuotidien}
                                        onChange={(e) => setSelectedJour({ ...selectedJour, reposQuotidien: e.target.checked })}
                                        className="w-5 h-5 text-blue-600 rounded mt-0.5"
                                    />
                                    <div>
                                        <span className="text-gray-700 font-medium block">Respect du repos quotidien</span>
                                        <span className="text-xs text-gray-500">11 heures consécutives minimum</span>
                                    </div>
                                </label>
                            </div>

                            {selectedJour.date.getDay() === 5 && (
                                <div>
                                    <label className="flex items-start gap-3 cursor-pointer">
                                        <input
                                            type="checkbox"
                                            checked={selectedJour.reposHebdo}
                                            onChange={(e) => setSelectedJour({ ...selectedJour, reposHebdo: e.target.checked })}
                                            className="w-5 h-5 text-blue-600 rounded mt-0.5"
                                        />
                                        <div>
                                            <span className="text-gray-700 font-medium block">Respect du repos hebdomadaire</span>
                                            <span className="text-xs text-gray-500">35 heures consécutives minimum</span>
                                        </div>
                                    </label>
                                </div>
                            )}

                            {(!selectedJour.reposQuotidien || (selectedJour.date.getDay() === 5 && !selectedJour.reposHebdo)) && (
                                <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
                                    <label className="block text-sm font-medium text-gray-700 mb-2">Commentaire obligatoire</label>
                                    <textarea
                                        value={selectedJour.commentaire}
                                        onChange={(e) => setSelectedJour({ ...selectedJour, commentaire: e.target.value })}
                                        placeholder="Précisez les circonstances du non-respect des repos obligatoires..."
                                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                        rows={4}
                                    />
                                    <p className="text-xs text-orange-700 mt-2">Veuillez préciser les circonstances du non-respect des repos obligatoires</p>
                                </div>
                            )}
                        </div>

                        <div className="flex gap-3 mt-6">
                            <button
                                onClick={() => setShowSaisieModal(false)}
                                className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                                disabled={isSaving}
                            >
                                Annuler
                            </button>
                            <button
                                onClick={handleSaveJour}
                                disabled={isSaving}
                                className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center gap-2 disabled:opacity-50"
                            >
                                {isSaving ? <><RefreshCw className="w-4 h-4 animate-spin" />Enregistrement...</> : <><Save className="w-4 h-4" />Enregistrer</>}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {showSaisieMasse && (
                <SaisieMasseModal
                    mois={mois}
                    annee={annee}
                    days={days.filter(d => d !== null)}
                    congesData={congesData}
                    holidays={holidays}
                    joursActifs={joursActifs}
                    onClose={() => setShowSaisieMasse(false)}
                    onSave={handleSaisieMasse}
                    isSaving={isSaving}
                />
            )}
        </div>
    );
};

// ✅ SaisieMasseModal — jours déjà saisis bloqués pour TOUT LE MONDE
const SaisieMasseModal = ({ mois, annee, days, congesData, holidays, joursActifs, onClose, onSave, isSaving }) => {
    const [selectedDays, setSelectedDays] = useState([]);
    const [defaultPeriode, setDefaultPeriode] = useState('Journée complète');

    const monthNames = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
        'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];

    const formatDateToString = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    const isJourDejaSaisi = (date) => {
        const dateStr = formatDateToString(date);
        return joursActifs?.some(j => {
            const jourDateStr = typeof j.JourDate === 'string'
                ? j.JourDate.split('T')[0]
                : formatDateToString(new Date(j.JourDate));
            return jourDateStr === dateStr;
        }) || false;
    };

    // ✅ CORRECTIF également appliqué dans SaisieMasseModal
    const getCongeInfo = (date) => {
        if (!date) return null;
        const checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        const checkDateStr = formatDateToString(date);

        for (const conge of congesData) {
            const startParts = conge.startdate.split('T')[0].split('-');
            const endParts = conge.enddate.split('T')[0].split('-');
            const start = new Date(parseInt(startParts[0]), parseInt(startParts[1]) - 1, parseInt(startParts[2]));
            const end = new Date(parseInt(endParts[0]), parseInt(endParts[1]) - 1, parseInt(endParts[2]));
            const isInRange = checkDate >= start && checkDate <= end;
            const isValide = conge.statut === 'Validée' || conge.statut === 'Validé' || conge.statut === 'Valide';

            if (isInRange && isValide) {
                const typeStr = (conge.type || '').toUpperCase();
                if (typeStr.includes('TÉLÉTRAVAIL') || typeStr.includes('TELETRAVAIL') || typeStr.includes('REMOTE')) {
                    continue;
                }
                const isJPOSF =
                    conge.isJPOSFOnly === 1 || conge.isJPOSFOnly === true || conge.isJPOSFOnly === '1' ||
                    typeStr === 'JPOSF' || typeStr.includes('JPOSF');

                let periodeConge = 'Journée entière', isDemiJournee = false, periodeSaisissable = null;

                try {
                    if (conge.detailsconges) {
                        const details = JSON.parse(conge.detailsconges);
                        if (details && details.length > 0) {
                            const detailDuJour = details.find(d => {
                                if (!d.date) return false;
                                return d.date.split('T')[0] === checkDateStr;
                            }) || details[0];

                            const periode = detailDuJour?.periode || 'Journée entière';
                            periodeConge = periode;

                            const p = periode.toLowerCase().replace(/[\s_]/g, '-');
                            if (
                                p.includes('matin') ||
                                p.includes('après-midi') ||
                                p.includes('apres-midi') ||
                                p === 'am' ||
                                p === 'pm'
                            ) {
                                isDemiJournee = true;
                                periodeSaisissable = p.includes('matin') ? 'Après-midi' : 'Matin';
                            }

                            // ✅ AJOUT : jours=0.5 mais periode="Journée entière"
                            // Le RH n'a pas précisé matin/après-midi → on bloque quand même "Journée complète"
                            if (!isDemiJournee && detailDuJour?.jours === 0.5) {
                                isDemiJournee = true;
                                periodeSaisissable = null; // les deux demi-journées restent disponibles
                            }
                        }
                    }

                    // ✅ Fallback via nombrejoursouvres si detailsconges absent ou mal formé
                    if (!isDemiJournee && parseFloat(conge.nombrejoursouvres) === 0.5) {
                        isDemiJournee = true;
                        periodeSaisissable = null;
                    }

                } catch (e) { }

                return { type: conge.type, isJPOSF, periodeConge, isDemiJournee, periodeSaisissable, color: conge.color };
            }
        }
        return null;
    };

    const isJourComplètementBloque = (date) => {
        const info = getCongeInfo(date);
        if (!info) return false;
        if (info.isJPOSF) return false;
        if (info.isDemiJournee) return false;
        return true;
    };
    const isJPOSF = (date) => getCongeInfo(date)?.isJPOSF || false;
    const isDemiJourneeConge = (date) => getCongeInfo(date)?.isDemiJournee || false;

    const isHoliday = (date) => holidays.some(h =>
        h.date.getDate() === date.getDate() &&
        h.date.getMonth() === date.getMonth() &&
        h.date.getFullYear() === date.getFullYear()
    );

    const isWeekend = (date) => date.getDay() === 0 || date.getDay() === 6;

    const isPastOnly = (date) => {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const checkDate = new Date(date);
        checkDate.setHours(0, 0, 0, 0);
        return checkDate < today;
    };

    const toggleDay = (date) => {
        const jourJPOSF = isJPOSF(date);
        const weekendBloquant = isWeekend(date) && !jourJPOSF;
        const jourBloque = isJourComplètementBloque(date);
        const ferie = isHoliday(date);
        const past = isPastOnly(date);
        const dejaSaisi = isJourDejaSaisi(date);

        if (weekendBloquant || jourBloque || ferie || !past || dejaSaisi) return;

        const dateStr = formatDateToString(date);
        setSelectedDays(prev =>
            prev.includes(dateStr) ? prev.filter(d => d !== dateStr) : [...prev, dateStr]
        );
    };

    const selectAllWorkingDays = () => {
        const workingDays = days
            .filter(date => {
                const jourJPOSF = isJPOSF(date);
                const weekendBloquant = isWeekend(date) && !jourJPOSF;
                const jourBloque = isJourComplètementBloque(date);
                const ferie = isHoliday(date);
                const past = isPastOnly(date);
                const dejaSaisi = isJourDejaSaisi(date);
                return past && !weekendBloquant && !jourBloque && !ferie && !dejaSaisi;
            })
            .map(date => formatDateToString(date));
        setSelectedDays(workingDays);
    };

    const handleSave = () => {
        const joursTravailles = selectedDays.map(dateStr => {
            const date = new Date(dateStr + 'T00:00:00');
            const congeInfo = getCongeInfo(date);
            let periode = defaultPeriode;
            if (congeInfo?.isDemiJournee && congeInfo?.periodeSaisissable) periode = congeInfo.periodeSaisissable;
            return { date: dateStr, jour_travaille: true, repos_quotidien: true, repos_hebdo: true, commentaire: '', periode };
        });
        onSave(joursTravailles);
    };

    const getDaysWithOffset = () => {
        const month = mois - 1;
        const firstDay = new Date(annee, month, 1);
        let firstDayOfWeek = firstDay.getDay();
        firstDayOfWeek = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1;
        const result = [];
        for (let i = 0; i < firstDayOfWeek; i++) result.push(null);
        result.push(...days);
        return result;
    };

    const daysWithOffset = getDaysWithOffset();

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
            <div className="bg-white rounded-xl shadow-xl max-w-4xl w-full p-6 max-h-[90vh] overflow-y-auto">
                <h3 className="text-xl font-bold text-gray-900 mb-4">
                    Saisie en masse — {monthNames[mois - 1]} {annee}
                </h3>

                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
                    <p className="text-sm text-blue-800">
                        Sélectionnez tous les jours travaillés. Les week-ends, congés journée entière et jours déjà saisis sont exclus.
                        <br />
                        <strong className="text-orange-600">JPOSF</strong> et <strong className="text-purple-600">demi-journées</strong> peuvent être sélectionnés.
                    </p>
                </div>

                {/* Période par défaut */}
                <div className="bg-gray-50 border rounded-lg p-4 mb-4">
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        Période par défaut (ignorée pour les demi-journées de congé)
                    </label>
                    <div className="flex gap-2">
                        {[
                            { value: 'Journée complète', icon: <Coffee className="w-4 h-4" />, label: 'Journée complète', activeClass: 'border-blue-500 bg-blue-100' },
                            { value: 'Matin', icon: <Sun className="w-4 h-4" />, label: 'Matin', activeClass: 'border-yellow-500 bg-yellow-100' },
                            { value: 'Après-midi', icon: <Moon className="w-4 h-4" />, label: 'Après-midi', activeClass: 'border-indigo-500 bg-indigo-100' },
                        ].map(({ value, icon, label, activeClass }) => (
                            <button
                                key={value}
                                type="button"
                                onClick={() => setDefaultPeriode(value)}
                                className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${defaultPeriode === value ? activeClass : 'border-gray-200 bg-white hover:bg-gray-50'
                                    }`}
                            >
                                {icon}
                                <span className="text-sm">{label}</span>
                            </button>
                        ))}
                    </div>
                </div>

                <button
                    onClick={selectAllWorkingDays}
                    className="mb-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                    Sélectionner tous les jours disponibles
                </button>

                {/* Grille du calendrier */}
                <div className="grid grid-cols-7 gap-1 mb-2 text-center">
                    {['L', 'M', 'M', 'J', 'V', 'S', 'D'].map((d, i) => (
                        <div key={i} className="text-xs font-semibold text-gray-500 py-1">{d}</div>
                    ))}
                </div>
                <div className="grid grid-cols-7 gap-1 p-2 mb-4">
                    {daysWithOffset.map((date, index) => {
                        if (date === null) return <div key={`empty-${index}`} className="p-2"></div>;

                        const dateStr = formatDateToString(date);
                        const congeInfo = getCongeInfo(date);
                        const jourJPOSF = isJPOSF(date);
                        const demiJournee = isDemiJourneeConge(date);
                        const weekend = isWeekend(date);
                        const weekendBloquant = weekend && !jourJPOSF;
                        const jourBloque = isJourComplètementBloque(date);
                        const ferie = isHoliday(date);
                        const isPast = isPastOnly(date);
                        const isSelected = selectedDays.includes(dateStr);
                        const isToday = date.toDateString() === new Date().toDateString();
                        const dejaSaisi = isJourDejaSaisi(date);
                        const isDisabled = !isPast || weekendBloquant || jourBloque || ferie || dejaSaisi;

                        return (
                            <div
                                key={index}
                                onClick={() => toggleDay(date)}
                                className={`
                                    p-2 rounded-lg border-2 text-center transition-all min-h-[60px] flex flex-col items-center justify-center
                                    ${isToday ? 'border-cyan-500' : 'border-transparent'}
                                    ${isSelected ? 'bg-green-500 border-green-600 text-white cursor-pointer' : ''}
                                    ${!isSelected && ferie ? 'bg-gray-700 text-white cursor-not-allowed' : ''}
                                    ${!isSelected && weekendBloquant ? 'bg-gray-100 cursor-not-allowed' : ''}
                                    ${!isSelected && jourBloque ? 'bg-purple-100 cursor-not-allowed' : ''}
                                    ${!isSelected && dejaSaisi ? 'bg-gray-300 border-gray-400 cursor-not-allowed opacity-70' : ''}
                                    ${!isSelected && demiJournee && !jourBloque && !dejaSaisi ? 'bg-purple-50 border-purple-300 cursor-pointer hover:bg-purple-100' : ''}
                                    ${!isSelected && jourJPOSF && !jourBloque && !dejaSaisi ? 'bg-orange-100 border-orange-300 cursor-pointer hover:bg-orange-200' : ''}
                                    ${!isSelected && !isDisabled && !jourJPOSF && !demiJournee ? 'bg-white border-gray-200 hover:bg-gray-50 cursor-pointer hover:border-blue-300' : ''}
                                    ${!isPast && !ferie && !weekendBloquant && !jourBloque && !dejaSaisi ? 'opacity-30 cursor-not-allowed' : ''}
                                `}
                            >
                                <div className="font-semibold text-sm">{date.getDate()}</div>
                                {isToday && <div className="text-xs">Auj.</div>}
                                {ferie && <div className="text-xs">Férié</div>}
                                {weekendBloquant && <div className="text-xs text-gray-500">WE</div>}
                                {jourBloque && <div className="text-xs text-purple-700">Congé</div>}
                                {demiJournee && !isSelected && !dejaSaisi && (
                                    <div className="text-xs text-purple-700 font-bold">½ {congeInfo.periodeSaisissable}</div>
                                )}
                                {jourJPOSF && !isSelected && !dejaSaisi && (
                                    <div className="text-xs text-orange-700 font-bold">JPOSF</div>
                                )}
                                {dejaSaisi && !jourBloque && (
                                    <div className="text-xs text-gray-600 font-bold">🔒 Saisi</div>
                                )}
                            </div>
                        );
                    })}
                </div>

                <div className="text-sm text-gray-600 mb-4">
                    {selectedDays.length} jour{selectedDays.length > 1 ? 's' : ''} sélectionné{selectedDays.length > 1 ? 's' : ''}
                </div>

                <div className="flex gap-3">
                    <button
                        onClick={onClose}
                        className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                        disabled={isSaving}
                    >
                        Annuler
                    </button>
                    <button
                        onClick={handleSave}
                        disabled={isSaving || selectedDays.length === 0}
                        className="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        {isSaving
                            ? <><RefreshCw className="w-4 h-4 animate-spin" />Enregistrement...</>
                            : <><Save className="w-4 h-4" />Enregistrer {selectedDays.length} jour{selectedDays.length > 1 ? 's' : ''}</>
                        }
                    </button>
                </div>
            </div>
        </div>
    );
};

export default CompteRenduActivites;
