import React, { useState, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { useAuth } from '../context/AuthContext';
import Sidebar from '../components/Sidebar';
import { Calendar, Clock, Plus, RefreshCw, Menu, Info, Briefcase, AlertCircle, Wifi, WifiOff, TrendingUp, HelpCircle, FileText, ChevronRight, Users } from 'lucide-react';
import NewLeaveRequestModal from '../components/NewLeaveRequestModal';
import { useMsal } from "@azure/msal-react";
import { loginRequest } from "../authConfig";
import { useNavigate } from 'react-router-dom';

// 🌸 COMPOSANT PRINTEMPS
const PrintempsDecor = () => {
    return (
        <div className="printemps-container">
            {[...Array(15)].map((_, i) => (
                <div key={i} className="petale" style={{
                    left: `${Math.random() * 100}%`,
                    animationDelay: `${Math.random() * 8}s`,
                    animationDuration: `${12 + Math.random() * 8}s`,
                    opacity: Math.random() * 0.4 + 0.3,
                    fontSize: `${Math.random() * 15 + 20}px`
                }}>🌸</div>
            ))}
            {[...Array(20)].map((_, i) => (
                <div key={`papillon-${i}`} className="papillon" style={{
                    left: `${Math.random() * 100}%`,
                    animationDelay: `${Math.random() * 10}s`,
                    animationDuration: `${15 + Math.random() * 10}s`,
                    opacity: Math.random() * 0.3 + 0.2,
                    fontSize: `${Math.random() * 10 + 15}px`
                }}>🦋</div>
            ))}
        </div>
    );
};

    // ✅ HELPER : extrait une année INT depuis n'importe quel format (INT, STRING, OBJET)
    // ✅ HELPER : extrait une année INT depuis n'importe quel format (INT, STRING, OBJET)
    const toAnnee = (val) => {
        if (!val) return null;
        if (typeof val === 'object') {
            if (val.annee) return parseInt(val.annee);
            if (val.debut) return parseInt(val.debut);
            return null;
        }
        const str = String(val);
        // Format "2026-2027" → on prend le premier nombre
        if (str.includes('-') && !str.startsWith('{')) return parseInt(str.split('-')[0]);
        const n = parseInt(str);
        return isNaN(n) ? null : n;
    };

    // ✅ CP N-1 : exercice = "2025-2026" → debut=2025, fin=2026
    const getDebutN1 = (val) => {
        const str = String(val || '');
        if (str.includes('-')) {
            const parts = str.split('-');
            return parseInt(parts[0]) || '?';
        }
        const a = toAnnee(val);
        return a ? a - 1 : '?';
    };
    const getFinN1 = (val) => {
        const str = String(val || '');
        if (str.includes('-')) {
            const parts = str.split('-');
            return parseInt(parts[1]) || '?';
        }
        const a = toAnnee(val);
        return a ? a : '?';
    };

    // ✅ CP N : exercice = "2026-2027" → debut=2026, fin=2027
    const getDebutN = (val) => {
        const str = String(val || '');
        if (str.includes('-')) {
            const parts = str.split('-');
            return parseInt(parts[0]) || '?';
        }
        const a = toAnnee(val);
        return a ? a : '?';
    };
    const getFinN = (val) => {
        const str = String(val || '');
        if (str.includes('-')) {
            const parts = str.split('-');
            return parseInt(parts[1]) || '?';
        }
        const a = toAnnee(val);
        return a ? a + 1 : '?';
    };
const Dashboard = () => {
    const { user } = useAuth();
    const [graphToken, setGraphToken] = useState(null);
    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [detailedCounters, setDetailedCounters] = useState(null);
    const [showNewRequestModal, setShowNewRequestModal] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const { instance, accounts } = useMsal();
    const [notifications, setNotifications] = useState([]);
    const [showNotifications, setShowNotifications] = useState(false);
    const [lastRefresh, setLastRefresh] = useState(new Date());
    const [sseConnected, setSseConnected] = useState(false);
    const [toasts, setToasts] = useState([]);
    const [congesAnticipes, setCongesAnticipes] = useState(null);
    const [showAnticipes, setShowAnticipes] = useState(false);
    const [recentRequests, setRecentRequests] = useState([]);
    const [teamLeaves, setTeamLeaves] = useState([]);
    const [isUpdatingCounters, setIsUpdatingCounters] = useState(false);
    const navigate = useNavigate();
    const userId = user?.id || user?.CollaborateurADId || user?.ID;

    const handleRestartTutorial = () => {
        localStorage.removeItem(`global-tutorial-completed-${userId}`);
        window.location.reload();
    };

    useEffect(() => {
        if (accounts.length > 0) {
            const request = { ...loginRequest, account: accounts[0] };
            instance.acquireTokenSilent(request)
                .then((response) => { setGraphToken(response.accessToken); })
                .catch(async (err) => {
                    try {
                        const tokenResponse = await instance.acquireTokenPopup(request);
                        setGraphToken(tokenResponse.accessToken);
                    } catch (popupErr) {
                        console.error("❌ Impossible d'obtenir un token:", popupErr);
                    }
                });
        }
    }, [accounts, instance]);

    const fetchNotifications = async () => {
        try {
            const response = await fetch(`/api/getNotifications?user_id=${userId}`);
            if (!response.ok) throw new Error(`Erreur HTTP: ${response.status}`);
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                const text = await response.text();
                throw new Error('Réponse non JSON: ' + text);
            }
            const data = await response.json();
            if (data.success) {
                setNotifications(data.notifications || []);
            } else {
                console.warn("Erreur récupération notifications:", data.message);
            }
        } catch (error) {
            console.error("Erreur fetchNotifications:", error);
            setNotifications([]);
        }
    };

    const fetchDetailedCounters = async () => {
        try {
            if (!isLoading) {
                setIsRefreshing(true);
                setIsUpdatingCounters(true);
            }
            const response = await fetch(`/api/getDetailedLeaveCounters?user_id=${userId}`);
            const data = await response.json();
            if (data.success) {
                setDetailedCounters(data.data);
            } else {
                console.error("❌ Erreur compteurs:", data.message);
            }
        } catch (error) {
            console.error("💥 Erreur compteurs:", error);
        } finally {
            setIsLoading(false);
            setIsRefreshing(false);
            setIsUpdatingCounters(false);
        }
    };

    const fetchCongesAnticipes = async () => {
        try {
            const response = await fetch(`/api/getCongesAnticipes?user_id=${userId}`);
            const data = await response.json();
            if (data.success) {
                setCongesAnticipes(data);
            } else {
                console.error("Erreur congés anticipés:", data.message);
            }
        } catch (error) {
            console.error("💥 Erreur congés anticipés:", error);
        }
    };

    const fetchRecentRequests = async () => {
        try {
            const url = `/api/getRequests?user_id=${userId}`;
            const response = await fetch(url);
            const text = await response.text();
            let data;
            try {
                data = JSON.parse(text);
            } catch (parseError) {
                setRecentRequests([]);
                return;
            }
            if (data.success && data.requests) {
                const sortedRequests = data.requests
                    .sort((a, b) => {
                        const dateA = new Date(a.submittedAt || a.DateCreation || a.created_at);
                        const dateB = new Date(b.submittedAt || b.DateCreation || b.created_at);
                        return dateB - dateA;
                    })
                    .slice(0, 5);
                setRecentRequests(sortedRequests);
            } else {
                setRecentRequests([]);
            }
        } catch (error) {
            console.error("💥 Erreur demandes récentes:", error);
            setRecentRequests([]);
        }
    };

    const fetchTeamLeaves = async () => {
        try {
            const currentMonth = new Date().getMonth();
            const currentYear = new Date().getFullYear();
            const response = await fetch(`/api/getTeamLeaves?user_id=${userId}&role=${user.role}`);
            const data = await response.json();
            if (data.success) {
                let filteredLeaves = (data.leaves || []).filter(leave => {
                    const startDate = new Date(leave.startdate);
                    const endDate = new Date(leave.enddate);
                    return (startDate.getFullYear() === currentYear && startDate.getMonth() === currentMonth) ||
                        (endDate.getFullYear() === currentYear && endDate.getMonth() === currentMonth) ||
                        (startDate <= new Date(currentYear, currentMonth, 1) &&
                            endDate >= new Date(currentYear, currentMonth + 1, 0));
                });
                if (user.role === 'RH' && user.service) {
                    filteredLeaves = filteredLeaves.filter(leave => leave.servicenom === user.service);
                }
                setTeamLeaves(filteredLeaves);
            }
        } catch (error) {
            console.error("💥 Erreur congés équipe:", error);
        }
    };

    const refreshAllData = useCallback(async () => {
        if (!userId) return;
        setIsRefreshing(true);
        try {
            await Promise.all([
                fetchDetailedCounters(),
                fetchNotifications(),
                fetchCongesAnticipes(),
                fetchRecentRequests(),
                fetchTeamLeaves()
            ]);
            setLastRefresh(new Date());
        } catch (error) {
            console.error('❌ Erreur lors du rafraîchissement:', error);
        } finally {
            setIsRefreshing(false);
        }
    }, [userId]);

    const showToast = useCallback((message, type = 'info') => {
        const id = Date.now();
        setToasts(prev => [...prev, { id, message, type }]);
        setTimeout(() => {
            setToasts(prev => prev.filter(t => t.id !== id));
        }, 5000);
    }, []);

    useEffect(() => {
        if (!userId) return;
        const eventSource = new EventSource(`/api/events/collaborateur?user_id=${userId}`);

        eventSource.onopen = () => { setSseConnected(true); };

        eventSource.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                switch (data.type) {
                    case 'connected': break;
                    case 'heartbeat': break;
                    case 'demande-validated-rh':
                        if (data.statut === 'Validée') showToast('✅ Votre demande a été VALIDÉE !', 'success');
                        else if (data.statut === 'Refusée') showToast('❌ Votre demande a été REFUSÉE', 'error');
                        refreshAllData();
                        break;
                    case 'compteur-updated':
                        const collabIdNum = parseInt(data.collaborateurId);
                        const userIdNum = parseInt(userId);
                        if (collabIdNum === userIdNum) {
                            if (data.typeUpdate === 'reinitialisation') showToast(`📊 Compteur ${data.typeConge} ${data.annee} réinitialisé`, 'info');
                            else if (data.typeUpdate === 'actualisation_manuel') showToast(`🔄 Compteur ${data.typeConge} actualisé`, 'success');
                            else if (data.typeUpdate === 'actualisation_globale') showToast('✅ Mise à jour automatique des compteurs', 'info');
                            else if (data.typeUpdate === 'modification_manuelle') showToast(`✏️ Compteur ${data.typeConge} ${data.annee} modifié par RH`, 'info');
                            fetchDetailedCounters().then(() => fetchCongesAnticipes());
                        }
                        break;
                    case 'demande-list-updated':
                        refreshAllData();
                        break;
                    case 'demande-updated-rh':
                        showToast('✏️ Votre demande a été modifiée', 'info');
                        refreshAllData();
                        break;
                    case 'demande-deleted-rh':
                        showToast('🗑️ Votre demande a été supprimée', 'warning');
                        refreshAllData();
                        break;
                    default: break;
                }
            } catch (error) {
                console.error('❌ Erreur parsing SSE:', error);
            }
        };

        eventSource.onerror = () => { setSseConnected(false); };

        return () => { eventSource.close(); };
    }, [userId, refreshAllData, showToast]);

    useEffect(() => {
        if (userId) { refreshAllData(); }
    }, [userId, refreshAllData]);

    useEffect(() => {
        if (!userId) return;
        const interval = setInterval(() => { refreshAllData(); }, 120000);
        return () => clearInterval(interval);
    }, [userId, refreshAllData]);

    useEffect(() => {
        const handleVisibilityChange = () => {
            if (document.visibilityState === 'visible' && userId) { refreshAllData(); }
        };
        document.addEventListener('visibilitychange', handleVisibilityChange);
        return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
    }, [userId, refreshAllData]);

    useEffect(() => {
        const handleFocus = () => { if (userId) { refreshAllData(); } };
        window.addEventListener('focus', handleFocus);
        return () => window.removeEventListener('focus', handleFocus);
    }, [userId, refreshAllData]);

    const markNotificationRead = async (id) => {
        try {
            const res = await fetch(`/api/markNotificationRead`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ notificationId: id }),
            });
            const data = await res.json();
            if (data.success) {
                setNotifications((prev) =>
                    prev.map((notif) => notif.Id === id ? { ...notif, lu: true } : notif)
                );
                refreshAllData();
            }
        } catch (error) {
            console.error("Erreur markNotificationRead:", error);
        }
    };

    const unreadCount = notifications.filter(n => !n.lu).length;
    const handleManualRefresh = async () => { await refreshAllData(); };

    const formatDate = (dateStr) => {
        if (!dateStr) return 'N/A';
        return new Date(dateStr).toLocaleDateString('fr-FR', { day: '2-digit', month: 'long', year: 'numeric' });
    };

    const formatTime = (date) => {
        return new Date(date).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
    };

    const getTypeContratLabel = (type) => {
        switch (type) {
            case '37h': return '37h hebdomadaires';
            case 'forfait_jour': return 'Forfait jour';
            case 'temps_partiel': return 'Temps partiel';
            default: return type || '37h hebdomadaires';
        }
    };

    if (isLoading) {
        return (
            <div className="min-h-screen bg-gray-50">
                <Sidebar isOpen={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} />
                <div className="lg:ml-60 flex items-center justify-center min-h-screen">
                    <div className="text-center">
                        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-pink-400 mx-auto mb-4"></div>
                        <p className="text-gray-600">Chargement des données...</p>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gray-50 flex printemps-theme">
            <PrintempsDecor />

            <div className="floral-garland">
                <div className="floral-piece rose"></div>
                <div className="floral-piece vert"></div>
                <div className="floral-piece lavande"></div>
                <div className="floral-piece rose"></div>
                <div className="floral-piece vert"></div>
                <div className="floral-piece lavande"></div>
                <div className="floral-piece rose"></div>
                <div className="floral-piece vert"></div>
                <div className="floral-piece lavande"></div>
                <div className="floral-piece rose"></div>
                <div className="floral-piece vert"></div>
                <div className="floral-piece lavande"></div>
            </div>

            <Sidebar isOpen={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} />
            <div className="flex-1 lg:ml-60">
                <div className="p-4 lg:p-8 w-full">

                    {/* INDICATEUR SSE */}
                    <div className="fixed bottom-4 right-4 z-50">
                        {sseConnected ? (
                            <div className="bg-green-500 text-white px-3 py-2 rounded-lg shadow-lg flex items-center gap-2 text-sm">
                                <Wifi className="w-4 h-4" />
                                <span>Connecté en temps réel</span>
                            </div>
                        ) : (
                            <div className="bg-red-500 text-white px-3 py-2 rounded-lg shadow-lg flex items-center gap-2 text-sm animate-pulse">
                                <WifiOff className="w-4 h-4" />
                                <span>Déconnecté - Reconnexion...</span>
                            </div>
                        )}
                    </div>

                    {/* TOASTS */}
                    <div className="fixed top-20 right-4 z-50 space-y-2">
                        {toasts.map(toast => (
                            <div
                                key={toast.id}
                                className={`px-4 py-3 rounded-lg shadow-lg flex items-center gap-3 min-w-[300px] transform transition-all duration-300 ease-in-out
                                    ${toast.type === 'success' ? 'bg-green-500 text-white' : ''}
                                    ${toast.type === 'error' ? 'bg-red-500 text-white' : ''}
                                    ${toast.type === 'info' ? 'bg-blue-500 text-white' : ''}
                                    ${toast.type === 'warning' ? 'bg-orange-500 text-white' : ''}`}
                                style={{ animation: 'slideInRight 0.3s ease-out' }}
                            >
                                <span className="text-2xl flex-shrink-0">
                                    {toast.type === 'success' && '✅'}
                                    {toast.type === 'error' && '❌'}
                                    {toast.type === 'info' && 'ℹ️'}
                                    {toast.type === 'warning' && '⚠️'}
                                </span>
                                <span className="font-medium">{toast.message}</span>
                            </div>
                        ))}
                    </div>

                    <div className="lg:hidden mb-4">
                        <button onClick={() => setSidebarOpen(true)} className="p-2 rounded-lg bg-white shadow-sm border border-gray-200">
                            <Menu className="w-6 h-6" />
                        </button>
                    </div>

                    {isRefreshing && (
                        <div className="fixed top-4 right-4 bg-blue-500 text-white px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 z-40 animate-pulse">
                            <RefreshCw className="w-4 h-4 animate-spin" />
                            <span className="text-sm">Mise à jour...</span>
                        </div>
                    )}

                    {/* HEADER */}
                    <div className="flex justify-between items-center mb-8">
                        <div>
                            <h1 className="text-2xl lg:text-3xl font-bold text-gray-900 mb-2 galette-title">
                                Bonjour, {user?.name || user?.prenom || 'Utilisateur'} 👋🌸
                            </h1>
                            <p className="text-sm lg:text-base text-gray-600">
                                Vos soldes de congés au {detailedCounters ? formatDate(detailedCounters.dateReference) : '...'}
                            </p>
                            <p className="text-xs text-gray-400 mt-1">
                                Dernière mise à jour : {formatTime(lastRefresh)}
                            </p>
                        </div>
                        <div className="flex gap-2 lg:gap-3">
                            <button
                                data-tour="refresh"
                                onClick={handleManualRefresh}
                                disabled={isRefreshing}
                                className="bg-gray-200 text-gray-700 px-3 lg:px-4 py-2 lg:py-3 rounded-lg font-medium hover:bg-gray-300 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                                title="Rafraîchir les données"
                            >
                                <RefreshCw className={`w-5 h-5 ${isRefreshing ? 'animate-spin' : ''}`} />
                                <span className="hidden lg:inline">Rafraîchir</span>
                            </button>

                            <div className="relative">
                                <button
                                    data-tour="notifications"
                                    onClick={() => setShowNotifications(!showNotifications)}
                                    className="relative bg-white border border-gray-200 px-3 lg:px-4 py-2 lg:py-3 rounded-lg font-medium hover:bg-gray-50 transition-colors flex items-center gap-2 shadow-sm"
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-700" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6 6 0 10-12 0v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                                    </svg>
                                    <span className="hidden sm:inline">Notifications</span>
                                    {unreadCount > 0 && (
                                        <span className="absolute -top-1 -right-1 inline-flex items-center justify-center px-1.5 py-0.5 text-xs font-bold leading-none text-white bg-red-600 rounded-full animate-pulse">
                                            {unreadCount}
                                        </span>
                                    )}
                                </button>

                                {showNotifications && (
                                    <div className="absolute right-0 mt-2 w-80 max-h-96 overflow-y-auto bg-white rounded-xl shadow-lg border border-gray-200 z-50">
                                        <div className="p-3 border-b border-gray-100 font-semibold text-gray-700">Notifications</div>
                                        {notifications.length === 0 ? (
                                            <div className="p-4 text-center text-gray-500">Aucune notification</div>
                                        ) : (
                                            <ul>
                                                {notifications.map((notif) => (
                                                    <li
                                                        key={notif.Id}
                                                        onClick={() => { if (!notif.lu) markNotificationRead(notif.Id); }}
                                                        className={`cursor-pointer p-3 border-b border-gray-100 hover:bg-blue-50 ${notif.lu ? "text-gray-600" : "font-semibold bg-blue-50"}`}
                                                    >
                                                        <div className="flex items-start gap-2">
                                                            {!notif.lu && <span className="w-2 h-2 bg-blue-600 rounded-full mt-2 flex-shrink-0"></span>}
                                                            <div className="flex-1">
                                                                <div>{notif.Titre}</div>
                                                                <div className="text-xs text-gray-400">{new Date(notif.DateCreation).toLocaleString()}</div>
                                                            </div>
                                                        </div>
                                                    </li>
                                                ))}
                                            </ul>
                                        )}
                                    </div>
                                )}
                            </div>

                            <button
                                data-tour="nouvelle-demande"
                                onClick={() => setShowNewRequestModal(true)}
                                className="bg-cyan-600 text-white px-3 lg:px-6 py-2 lg:py-3 rounded-lg font-medium hover:bg-cyan-700 transition-colors flex items-center gap-2"
                            >
                                <Plus className="w-5 h-5" />
                                <span className="hidden sm:inline">Nouvelle demande</span>
                                <span className="sm:hidden">Nouveau</span>
                            </button>
                        </div>
                    </div>

                    {/* INFO TEMPS RÉEL */}
                    <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-6 flex items-start gap-2">
                        <Info className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                        <div className="text-sm text-blue-800">
                            <strong>Actualisation en temps réel :</strong> Vos compteurs se mettent à jour automatiquement dès qu'une action est effectuée sur vos demandes.
                            {sseConnected && <span className="text-green-600 font-semibold ml-1">✓ Connecté</span>}
                        </div>
                    </div>
                  

                    {/* CARTE UTILISATEUR */}
                    {detailedCounters && detailedCounters.user && (
                        <div className="bg-gradient-to-r from-cyan-500 to-blue-500 rounded-xl shadow-md p-6 mb-6 text-white">
                            <div className="flex items-start justify-between">
                                <div className="flex-1">
                                    <div className="flex flex-wrap gap-3 text-sm mb-3">
                                        <div className="flex items-center gap-2">
                                            <Briefcase className="w-4 h-4" />
                                            <span className="font-medium">{detailedCounters.user.role}</span>
                                        </div>
                                        {detailedCounters.user.service && (
                                            <div className="flex items-center gap-2">
                                                <span>•</span>
                                                <span>{detailedCounters.user.service}</span>
                                            </div>
                                        )}
                                        {detailedCounters.user.typeContrat && (
                                            <div className="flex items-center gap-2">
                                                <span>•</span>
                                                <span className="px-2 py-1 bg-white bg-opacity-20 rounded-md font-medium">
                                                    {getTypeContratLabel(detailedCounters.user.typeContrat)}
                                                </span>
                                            </div>
                                        )}
                                    </div>
                                    <div className="mt-3 pt-3 border-t border-white border-opacity-20">
                                        <div className="flex items-start gap-2">
                                            <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                            </svg>
                                            <div className="flex-1">
                                                <p className="text-xs font-semibold uppercase tracking-wide opacity-90 mb-1">Fonction</p>
                                                <p className="text-sm font-medium">{detailedCounters.user.description || '(Non renseignée)'}</p>
                                            </div>
                                        </div>
                                    </div>
                                    {detailedCounters.user.dateEntree && (
                                        <p className="text-sm mt-3 opacity-90">
                                            📅 Ancienneté : {detailedCounters.user.ancienneteAnnees} an{detailedCounters.user.ancienneteAnnees > 1 ? 's' : ''} et {detailedCounters.user.ancienneteMoisRestants} mois
                                            {' '}(depuis le {formatDate(detailedCounters.user.dateEntree)})
                                        </p>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}

                    {detailedCounters && (
                        <div className="space-y-6 mb-8">

                            {/* SECTION CÔTE À CÔTE */}
                            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

                                {/* DEMANDES RÉCENTES */}
                                <div data-tour="demandes-recentes" className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 lg:col-span-1">
                                    <div className="flex items-center justify-between mb-4">
                                        <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                                            <FileText className="w-5 h-5 text-cyan-600" />
                                            Mon activité
                                        </h3>
                                        <button onClick={() => navigate('/demandes')} className="text-sm text-cyan-600 hover:text-cyan-700 flex items-center gap-1">
                                            Voir tout <ChevronRight className="w-4 h-4" />
                                        </button>
                                    </div>
                                    {recentRequests.length === 0 ? (
                                        <p className="text-gray-500 text-sm text-center py-4">Aucune demande récente</p>
                                    ) : (
                                        <div className="space-y-2">
                                            {recentRequests.map((request, idx) => {
                                                const type = request.type || 'Congé';
                                                const statut = request.status || 'En attente';
                                                const dateDebut = request.startDate;
                                                const dateFin = request.endDate;
                                                const nbJours = request.days || 0;
                                                return (
                                                    <div key={request.id || idx} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer" onClick={() => navigate('/demandes')}>
                                                        <div className="flex-1">
                                                            <div className="flex items-center gap-2">
                                                                <span className="font-medium text-gray-900">{type}</span>
                                                                <span className={`text-xs px-2 py-0.5 rounded-full ${statut === 'Validée' ? 'bg-green-100 text-green-700' :
                                                                    statut === 'En attente' ? 'bg-orange-100 text-orange-700' :
                                                                        statut === 'Refusée' ? 'bg-red-100 text-red-700' :
                                                                            'bg-gray-100 text-gray-700'
                                                                    }`}>{statut}</span>
                                                            </div>
                                                            <p className="text-sm text-gray-600 mt-1">
                                                                {dateDebut && dateFin ? (
                                                                    <>Du {new Date(dateDebut).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })} au {new Date(dateFin).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' })}</>
                                                                ) : request.dateDisplay || <span className="text-gray-400">Dates non disponibles</span>}
                                                            </p>
                                                        </div>
                                                        <div className="text-right">
                                                            <span className="text-lg font-bold text-cyan-600">{nbJours}j</span>
                                                        </div>
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    )}
                                </div>

                                {/* CONGÉS DU SERVICE */}
                                <div data-tour="conges-service" className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 lg:col-span-2">
                                    <div className="flex items-center justify-between mb-4">
                                        <h3 className="text-lg font-semibold text-gray-900 flex items-center gap-2">
                                            <Users className="w-5 h-5 text-cyan-600" />
                                            Activités du service - {new Date().toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' })}
                                        </h3>
                                        <button onClick={() => navigate('/calendrier')} className="text-sm text-cyan-600 hover:text-cyan-700 flex items-center gap-1">
                                            Voir tout <ChevronRight className="w-4 h-4" />
                                        </button>
                                    </div>
                                    {teamLeaves.length === 0 ? (
                                        <p className="text-gray-500 text-sm text-center py-4">Aucun congé prévu ce mois-ci</p>
                                    ) : (
                                        <div className="space-y-2 overflow-y-auto" style={{ maxHeight: '400px' }}>
                                            {teamLeaves.map((leave, idx) => (
                                                <div key={idx} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                                                    <div className={`w-3 h-3 rounded-full flex-shrink-0 ${leave.type === 'Formation' ? 'bg-blue-400' :
                                                        leave.statut === 'Validée' ? 'bg-green-400' :
                                                            leave.statut === 'En attente' ? 'bg-orange-400' : 'bg-gray-400'
                                                        }`}></div>
                                                    <div className="flex-1 min-w-0">
                                                        <p className="font-medium text-gray-900 truncate">{leave.employeename}</p>
                                                        <p className="text-xs text-gray-600">
                                                            {new Date(leave.startdate).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })}
                                                            {' '}-{' '}
                                                            {new Date(leave.enddate).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })}
                                                        </p>
                                                    </div>
                                                    {leave.type === 'Formation' && (
                                                        <span className="text-xs text-blue-600 font-medium whitespace-nowrap bg-blue-50 px-2 py-1 rounded">
                                                            📚 Formation
                                                        </span>
                                                    )}
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            </div>

                            {/* RACCOURCI FORFAIT JOUR */}
                            {(user?.TypeContrat === 'forfait_jour' || user?.typeContrat === 'forfait_jour') && (
                                <div onClick={() => navigate('/compte-rendu-activites')} className="bg-gradient-to-r from-purple-500 to-purple-600 rounded-xl shadow-md p-6 text-white cursor-pointer hover:shadow-lg transition-all">
                                    <div className="flex items-center justify-between">
                                        <div>
                                            <h3 className="text-lg font-bold mb-2 flex items-center gap-2">
                                                <FileText className="w-6 h-6" />
                                                Compte-Rendu d'Activités
                                            </h3>
                                            <p className="text-sm opacity-90">Suivez vos jours travaillés et repos obligatoires</p>
                                        </div>
                                        <ChevronRight className="w-8 h-8" />
                                    </div>
                                </div>
                            )}

                            {/* GRILLE DES COMPTEURS */}
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">

                                {/* ── CP N-1 ─────────────────────────────────────────────────── */}
                                {detailedCounters.cpN1 && (
                                    <div data-tour="cp-n-1" className="bg-white rounded-xl shadow-md border border-gray-200 overflow-hidden relative">
                                        {isUpdatingCounters && (
                                            <div className="absolute top-2 right-2 bg-yellow-500 text-white text-xs px-2 py-1 rounded-full animate-pulse z-10">
                                                🔄 Mise à jour...
                                            </div>
                                        )}
                                        <div className="bg-gradient-to-r from-blue-500 to-blue-600 p-4 text-white">
                                            <div className="flex items-center justify-between">
                                                <div>
                                                    <h3 className="text-lg font-bold">CP N-1</h3>
                                                    <p className="text-sm opacity-90">
                                                        Congés acquis du 1er juin {getDebutN1(detailedCounters.cpN1.exercice)} au 31 mai {getFinN1(detailedCounters.cpN1.exercice)}
                                                    </p>
                                                </div>
                                                <Calendar className="w-8 h-8 opacity-80" />
                                            </div>
                                        </div>
                                        <div className="p-5 space-y-3">
                                            <div className="flex justify-between items-center py-3 bg-blue-50 rounded-lg px-3 mt-3">
                                                <span className="text-base font-semibold text-gray-700">Solde disponible</span>
                                                <span className="text-2xl font-bold text-blue-600">{detailedCounters.cpN1.solde.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex justify-between items-center py-2 border-b border-gray-100">
                                                <span className="text-sm font-medium text-gray-600">Acquis</span>
                                                <span className="text-lg font-bold text-gray-900">{detailedCounters.cpN1.reporte.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex justify-between items-center py-2 border-b border-gray-100">
                                                <span className="text-sm font-medium text-gray-600">Consommé(s)</span>
                                                <span className="text-lg font-bold text-red-600">-{detailedCounters.cpN1.pris.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg mt-2">
                                                <AlertCircle className="w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5" />
                                                <p className="text-xs text-amber-800">
                                                   <strong>À solder avant le 31/05/{getFinN1(detailedCounters.cpN1.exercice)}</strong>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* ── CP N ───────────────────────────────────────────────────── */}
                                {detailedCounters.cpN && (
                                    <div data-tour="cp-n" className="bg-white rounded-xl shadow-md border border-gray-200 overflow-hidden relative">
                                        {isUpdatingCounters && (
                                            <div className="absolute top-2 right-2 bg-yellow-500 text-white text-xs px-2 py-1 rounded-full animate-pulse z-10">
                                                🔄 Mise à jour...
                                            </div>
                                        )}
                                        <div className="bg-gradient-to-r from-cyan-500 to-cyan-600 p-4 text-white">
                                            <div className="flex items-center justify-between">
                                                <div>
                                                    <h3 className="text-lg font-bold">CP N</h3>
                                                    <p className="text-sm opacity-90">
                                                        Congés acquis du 1er juin {getDebutN(detailedCounters.cpN.exercice)} au 31 mai {getFinN(detailedCounters.cpN.exercice)}
                                                    </p>
                                                </div>
                                                <Calendar className="w-8 h-8 opacity-80" />
                                            </div>
                                        </div>
                                        <div className="p-5 space-y-3">
                                            <div className="flex justify-between items-center py-3 bg-cyan-50 rounded-lg px-3 mt-3">
                                                <span className="text-base font-semibold text-gray-700">Solde disponible</span>
                                                <span className="text-2xl font-bold text-cyan-600">{detailedCounters.cpN.solde.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex justify-between items-center py-2 border-b border-gray-100">
                                                <span className="text-sm font-medium text-gray-600">Acquis</span>
                                                <span className="text-lg font-bold text-green-600">+{detailedCounters.cpN.acquis.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex justify-between items-center py-2 border-b border-gray-100">
                                                <span className="text-sm font-medium text-gray-600">Consommé(s)</span>
                                                <span className="text-lg font-bold text-red-600">-{detailedCounters.cpN.pris.toFixed(2)}j</span>
                                            </div>
                                            {detailedCounters.cpN.solde > 0 && (
                                                <div className="flex items-start gap-2 p-3 bg-blue-50 border border-blue-200 rounded-lg mt-2">
                                                    <Info className="w-4 h-4 text-blue-600 flex-shrink-0 mt-0.5" />
                                                    <p className="text-xs text-blue-800">
                                                       <strong>À solder avant le 31/05/{getFinN(detailedCounters.cpN.exercice)}</strong>
                                                    </p>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                )}

                                {/* ── RTT ────────────────────────────────────────────────────── */}
                                {detailedCounters.rttN && detailedCounters.user.role !== 'Apprenti' && (
                                    <div data-tour="rtt" className="bg-white rounded-xl shadow-md border border-gray-200 overflow-hidden relative">
                                        {isUpdatingCounters && (
                                            <div className="absolute top-2 right-2 bg-yellow-500 text-white text-xs px-2 py-1 rounded-full animate-pulse z-10">
                                                🔄 Mise à jour...
                                            </div>
                                        )}
                                        <div className="bg-gradient-to-r from-green-500 to-green-600 p-4 text-white">
                                            <div className="flex items-center justify-between">
                                                <div>
                                                    <h3 className="text-lg font-bold">RTT {detailedCounters.rttN.annee}</h3>
                                                    <p className="text-sm opacity-90">
                                                        {getTypeContratLabel(detailedCounters.rttN.typeContrat)} • {detailedCounters.rttN.totalAnnuel}j/an
                                                    </p>
                                                </div>
                                                <Clock className="w-8 h-8 opacity-80" />
                                            </div>
                                        </div>
                                        <div className="p-5 space-y-3">
                                            <div className="flex justify-between items-center py-3 bg-green-50 rounded-lg px-3 mt-3">
                                                <span className="text-base font-semibold text-gray-700">Solde disponible</span>
                                                <span className="text-2xl font-bold text-green-600">{detailedCounters.rttN.solde.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex justify-between items-center py-2 border-b border-gray-100">
                                                <span className="text-sm font-medium text-gray-600">Acquis</span>
                                                <span className="text-lg font-bold text-green-600">+{detailedCounters.rttN.acquis.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex justify-between items-center py-2 border-b border-gray-100">
                                                <span className="text-sm font-medium text-gray-600">Consommé(s)</span>
                                                <span className="text-lg font-bold text-red-600">-{detailedCounters.rttN.pris.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex items-start gap-2 p-3 bg-green-50 border border-green-200 rounded-lg mt-2">
                                                <Info className="w-4 h-4 text-green-600 flex-shrink-0 mt-0.5" />
                                                <p className="text-xs text-green-800">
                                                    <strong>À consommer avant le 31/12/{detailedCounters.rttN.annee}</strong>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* ── RÉCUPÉRATIONS ──────────────────────────────────────────── */}
                                {detailedCounters.recupN && (
                                    <div data-tour="recup" className="bg-white rounded-xl shadow-md border border-gray-200 overflow-hidden relative">
                                        {isUpdatingCounters && (
                                            <div className="absolute top-2 right-2 bg-yellow-500 text-white text-xs px-2 py-1 rounded-full animate-pulse z-10">
                                                🔄 Mise à jour...
                                            </div>
                                        )}
                                        <div className="bg-gradient-to-r from-purple-500 to-purple-600 p-4 text-white">
                                            <div className="flex items-center justify-between">
                                                <div><h3 className="text-lg font-bold">Récupérations</h3></div>
                                                <Calendar className="w-8 h-8 opacity-80" />
                                            </div>
                                        </div>
                                        <div className="p-5 space-y-3">
                                            <div className="flex justify-between items-center py-3 bg-purple-50 rounded-lg px-3 mt-3">
                                                <span className="text-base font-semibold text-gray-700">Solde disponible</span>
                                                <span className="text-2xl font-bold text-purple-600">{detailedCounters.recupN.solde.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex justify-between items-center py-2 border-b border-gray-100">
                                                <span className="text-sm font-medium text-gray-600">Jours acquis</span>
                                                <span className="text-lg font-bold text-green-600">+{detailedCounters.recupN.acquis.toFixed(2)}j</span>
                                            </div>
                                            <div className="flex justify-between items-center py-2 border-b border-gray-100">
                                                <span className="text-sm font-medium text-gray-600">Consommé(s)</span>
                                                <span className="text-lg font-bold text-red-600">-{detailedCounters.recupN.pris.toFixed(2)}j</span>
                                            </div>
                                            <div className="text-xs text-gray-500 pt-2">
                                                {detailedCounters.recupN.message}
                                            </div>
                                        </div>
                                    </div>
                                )}

                            </div>
                        </div>
                    )}

                    {/* BOUTON AIDE TUTORIEL */}
                    <button
                        onClick={handleRestartTutorial}
                        className="fixed bottom-20 right-4 bg-cyan-600 text-white shadow-lg hover:bg-cyan-700 transition-all flex items-center gap-2 z-40 group overflow-hidden rounded-full hover:rounded-lg hover:px-4 px-3 py-3"
                        title="Relancer le tutoriel"
                    >
                        <HelpCircle className="w-5 h-5 flex-shrink-0" />
                        <span className="max-w-0 group-hover:max-w-xs overflow-hidden transition-all duration-300 text-sm font-medium whitespace-nowrap">
                            Aide
                        </span>
                    </button>

                </div>
            </div>

            {/* ✅ FIX : MODAL RENDUE VIA PORTAL DIRECTEMENT SUR document.body
                Cela évite que le `position: fixed` de la modale soit cassé par
                les styles du Dashboard (overflow-x:hidden, position:relative, flex, etc.)
            */}
            {showNewRequestModal && detailedCounters && createPortal(
                <NewLeaveRequestModal
                    onClose={() => setShowNewRequestModal(false)}
                    availableLeaveCounters={{
                        availableCP_N: detailedCounters.cpN?.solde || 0,
                        totalCP_N: detailedCounters.cpN?.acquis || 0,
                        availableCP_N1: detailedCounters.cpN1?.solde || 0,
                        availableRTT_N: detailedCounters.rttN?.solde || 0,
                        totalRTT_N: detailedCounters.rttN?.acquis || 0,
                        availableRTT_N1: 0,
                        availableABS: 0,
                        availableCP: (detailedCounters.cpN1?.solde || 0) + (detailedCounters.cpN?.solde || 0),
                        availableRTT: detailedCounters.rttN?.solde || 0,
                        availableRecup: detailedCounters?.recupN?.solde || 0,
                        availableRecup_N: detailedCounters?.recupN?.solde || 0
                    }}
                    congesAnticipes={congesAnticipes}
                    accessToken={graphToken}
                    userId={userId}
                    userRole={user.role}
                    userEmail={user.email}
                    userName={`${user.prenom} ${user.nom}`}
                    onRequestSubmitted={() => { refreshAllData(); }}
                />,
                document.body
            )}

            {/* STYLES */}
            <style>{`
                .printemps-theme {
                    position: relative;
                    overflow-x: hidden;
                    background: linear-gradient(180deg, #f0fdf4 0%, #fdf2f8 50%, #f0fdf4 100%);
                }
                .printemps-container {
                    position: fixed;
                    top: 0; left: 0;
                    width: 100%; height: 100%;
                    pointer-events: none;
                    z-index: 1;
                    overflow: hidden;
                }
                .petale {
                    position: absolute;
                    top: -30px;
                    animation: fallPetale linear infinite;
                    user-select: none;
                    filter: drop-shadow(0 0 3px rgba(255, 182, 193, 0.5));
                }
                .papillon {
                    position: absolute;
                    top: -20px;
                    animation: volerPapillon linear infinite;
                    user-select: none;
                }
                @keyframes fallPetale {
                    0% { top: -10%; transform: translateX(0) rotate(0deg); }
                    50% { transform: translateX(40px) rotate(180deg); }
                    100% { top: 110%; transform: translateX(-20px) rotate(360deg); }
                }
                @keyframes volerPapillon {
                    0% { top: -10%; transform: translateX(0) rotate(0deg) scale(1); }
                    25% { transform: translateX(60px) rotate(15deg) scale(1.1); }
                    50% { transform: translateX(-40px) rotate(-15deg) scale(0.9); }
                    75% { transform: translateX(50px) rotate(10deg) scale(1.1); }
                    100% { top: 110%; transform: translateX(0) rotate(0deg) scale(1); }
                }
                .floral-garland {
                    position: fixed;
                    top: 0; left: 0;
                    width: 100%; height: 25px;
                    display: flex;
                    justify-content: space-around;
                    z-index: 49;
                    pointer-events: none;
                    background: linear-gradient(to bottom, rgba(236, 72, 153, 0.08), transparent);
                }
                .floral-piece {
                    width: 18px; height: 18px;
                    border-radius: 50%;
                    margin: 3px;
                    animation: blinkFloral 2s infinite;
                    box-shadow: 0 0 12px currentColor;
                }
                .floral-piece.rose { background: #f472b6; animation-delay: 0s; }
                .floral-piece.vert { background: #4ade80; animation-delay: 0.4s; }
                .floral-piece.lavande { background: #c084fc; animation-delay: 0.8s; }
                @keyframes blinkFloral {
                    0%, 49%, 100% { opacity: 1; transform: scale(1); }
                    50% { opacity: 0.4; transform: scale(0.85); }
                }
                .galette-title:hover { animation: sparklePrintemps 0.6s ease-in-out; }
                @keyframes sparklePrintemps {
                    0%, 100% { text-shadow: none; }
                    50% { text-shadow: 0 0 10px rgba(244,114,182,0.8), 0 0 20px rgba(167,243,208,0.6), 0 0 30px rgba(192,132,252,0.4); }
                }
                [data-tour]:hover::before {
                    content: '🌸';
                    position: absolute;
                    top: -15px; right: -15px;
                    font-size: 28px;
                    animation: bouncePrintemps 0.6s ease-in-out;
                    z-index: 10;
                    filter: drop-shadow(0 2px 4px rgba(244, 114, 182, 0.5));
                }
                @keyframes bouncePrintemps {
                    0%, 100% { transform: translateY(0) rotate(0deg); }
                    25% { transform: translateY(-12px) rotate(-10deg); }
                    75% { transform: translateY(-12px) rotate(10deg); }
                }
                @keyframes slideInRight {
                    from { transform: translateX(400px); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
            `}</style>
        </div>
    );
};

export default Dashboard;