// ============================================================================
// TaxiBook Client App - Main Application
// ============================================================================
// Ce fichier contient tous les composants principaux de l'application client
// ============================================================================

// Destructuration des hooks React pour utilisation simplifiée
const { useState, useEffect, useRef, useCallback, useMemo, createContext, useContext } = React;

// ==================== UTILITAIRE POLYLINE ====================
function decodePolyline(str) {
    let index = 0, lat = 0, lng = 0, coords = [];
    while (index < str.length) {
        let b, shift = 0, result = 0;
        do { b = str.charCodeAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20);
        lat += ((result & 1) ? ~(result >> 1) : (result >> 1));
        shift = 0; result = 0;
        do { b = str.charCodeAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20);
        lng += ((result & 1) ? ~(result >> 1) : (result >> 1));
        coords.push([lat / 1e5, lng / 1e5]);
    }
    return coords;
}

// ==================== UTILITAIRES DATE/TIMEZONE ====================
// Timezone par défaut pour la Suisse
const APP_TIMEZONE = 'Europe/Zurich';

// Formater une date en heure locale suisse
const formatDateLocal = (dateStr, options = {}) => {
    if (!dateStr) return '-';
    try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;
        
        const defaultOptions = {
            timeZone: APP_TIMEZONE,
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            ...options
        };
        
        return date.toLocaleString('fr-CH', defaultOptions);
    } catch (e) {
        console.error('Error formatting date:', e);
        return dateStr;
    }
};

// Formater uniquement la date (sans l'heure)
const formatDateOnlyLocal = (dateStr, options = {}) => {
    if (!dateStr) return '-';
    try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;
        
        const defaultOptions = {
            timeZone: APP_TIMEZONE,
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            ...options
        };
        
        return date.toLocaleDateString('fr-CH', defaultOptions);
    } catch (e) {
        return dateStr;
    }
};

// Formater uniquement l'heure
const formatTimeLocal = (dateStr, options = {}) => {
    if (!dateStr) return '-';
    try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;
        
        const defaultOptions = {
            timeZone: APP_TIMEZONE,
            hour: '2-digit',
            minute: '2-digit',
            ...options
        };
        
        return date.toLocaleTimeString('fr-CH', defaultOptions);
    } catch (e) {
        return dateStr;
    }
};

// Formater en format relatif (il y a X minutes, etc.)
const formatRelativeTime = (dateStr) => {
    if (!dateStr) return '-';
    try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;
        
        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);
        
        if (diffMins < 1) return 'À l\'instant';
        if (diffMins < 60) return `Il y a ${diffMins} min`;
        if (diffHours < 24) return `Il y a ${diffHours}h`;
        if (diffDays < 7) return `Il y a ${diffDays} jour${diffDays > 1 ? 's' : ''}`;
        
        return formatDateLocal(dateStr, { hour: undefined, minute: undefined });
    } catch (e) {
        return dateStr;
    }
};

// ==================== HOOKS PERSONNALISÉS ====================

// Créer le conteneur de notifications si nécessaire
const createNotificationContainer = () => {
    let container = document.getElementById('notification-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'notification-container';
        container.style.cssText = 'position: fixed; top: 0; left: 0; right: 0; z-index: 9999; pointer-events: none;';
        document.body.appendChild(container);
    }
    return container;
};

// Hook pour les notifications toast
const useNotifications = () => {
    const showNotification = useCallback((message, type = 'info') => {
        // Trouver les notifications existantes pour les repositionner
        const existingNotifications = document.querySelectorAll('.notification');
        
        // Décaler les notifications existantes vers le bas
        existingNotifications.forEach((notif, index) => {
            const currentTop = 20 + (index * 90);
            const newTop = currentTop + 90;
            notif.style.transform = `translateY(${newTop - 20}px)`;
        });
        
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.style.pointerEvents = 'auto';
        
        notification.innerHTML = `<div class="notification-content">${message}</div>`;
        
        // Commencer en position haute
        notification.style.top = '20px';
        notification.style.transform = 'translateY(0px)';
        
        document.body.appendChild(notification);

        // Fonction pour repositionner toutes les notifications
        const repositionNotifications = () => {
            const allNotifications = document.querySelectorAll('.notification');
            allNotifications.forEach((notif, index) => {
                const targetTop = 20 + (index * 90);
                notif.style.top = targetTop + 'px';
                notif.style.transform = 'translateY(0px)';
            });
        };

        // Animation de sortie
        const removeNotification = () => {
            if (!notification.classList.contains('slide-out')) {
                notification.classList.add('slide-out');
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.remove();
                        repositionNotifications();
                    }
                }, 300);
            }
        };

        // Supprimer automatiquement après 4 secondes
        setTimeout(removeNotification, 4000);
        
        // Permettre de fermer en cliquant
        notification.addEventListener('click', removeNotification);
        notification.style.cursor = 'pointer';
        
    }, []);

    return useMemo(() => ({
        success: (msg) => showNotification(msg, 'success'),
        error: (msg) => showNotification(msg, 'error'),
        info: (msg) => showNotification(msg, 'info')
    }), [showNotification]);
};

// Hook pour les animations de vue
const useViewAnimation = () => {
    const [isVisible, setIsVisible] = useState(false);
    const [animationClass, setAnimationClass] = useState('');

    useEffect(() => {
        const timer = setTimeout(() => {
            setIsVisible(true);
            setAnimationClass('fade-in');
        }, 10);

        return () => clearTimeout(timer);
    }, []);

    return { isVisible, animationClass };
};

// Hook pour les animations staggered (décalées)
const useStaggerAnimation = (itemCount, delay = 100) => {
    const [visibleItems, setVisibleItems] = useState(0);
    const [lastItemCount, setLastItemCount] = useState(itemCount);

    useEffect(() => {
        if (itemCount !== lastItemCount) {
            setVisibleItems(0);
            setLastItemCount(itemCount);
            
            const timers = [];
            for (let i = 0; i < itemCount; i++) {
                const timer = setTimeout(() => {
                    setVisibleItems(prev => Math.min(prev + 1, itemCount));
                }, i * delay);
                timers.push(timer);
            }

            return () => timers.forEach(timer => clearTimeout(timer));
        }
    }, [itemCount, delay, lastItemCount]);

    return visibleItems;
};

// Composant wrapper pour les animations de vue
const AnimatedView = ({ children, className = '', animationType = 'fade-in' }) => {
    const { isVisible } = useViewAnimation();
    
    return (
        <div className={`view-container ${isVisible ? 'active' : ''} ${className}`}>
            <div className={isVisible ? animationType : 'opacity-0'}>
                {children}
            </div>
        </div>
    );
};

// Composant pour les cartes animées
const AnimatedCard = ({ children, className = '', delay = 0, onClick = null }) => {
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        const timer = setTimeout(() => {
            setIsVisible(true);
        }, delay);

        return () => clearTimeout(timer);
    }, [delay]);

    return (
        <div 
            className={`${className} ${isVisible ? 'animate-card' : 'opacity-0 transform translate-y-5'}`}
            onClick={onClick}
        >
            {children}
        </div>
    );
};

// Composant pour les boutons animés
const AnimatedButton = ({ children, className = '', delay = 0, ...props }) => {
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        const timer = setTimeout(() => {
            setIsVisible(true);
        }, delay);

        return () => clearTimeout(timer);
    }, [delay]);

    return (
        <button 
            className={`${className} ${isVisible ? 'animate-button' : 'opacity-0 transform scale-95'}`}
            {...props}
        >
            {children}
        </button>
    );
};

// Fonction pour générer un UID compatible avec l'API backend
const generateUID = () => {
    const timestamp = Date.now().toString(36);
    const randomPart = Math.random().toString(36).substr(2, 16);
    return `usr_${timestamp}${randomPart}`.substr(0, 32);
};

// ==================== ICONS SVG ====================
const Icons = {
    Home: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
            <polyline points="9,22 9,12 15,12 15,22"/>
        </svg>
    ),
    Zap: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>
        </svg>
    ),
    ClipboardList: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <rect width="8" height="4" x="8" y="2" rx="1" ry="1"/>
            <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/>
            <path d="M12 11h4"/><path d="M12 16h4"/><path d="M8 11h.01"/><path d="M8 16h.01"/>
        </svg>
    ),
    User: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
        </svg>
    ),
    Star: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"/>
        </svg>
    ),
    Leaf: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z"/>
            <path d="M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12"/>
        </svg>
    ),
    Calendar: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/>
        </svg>
    ),
    Clock: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <circle cx="12" cy="12" r="10"/><polyline points="12,6 12,12 16,14"/>
        </svg>
    ),
    Timer: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <line x1="10" x2="14" y1="2" y2="2"/><line x1="12" x2="15" y1="14" y2="11"/><circle cx="12" cy="14" r="8"/>
        </svg>
    ),
    Car: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M14 16H9m10 0h3v-3.15a1 1 0 0 0-.84-.99L16 11h-1"/><path d="M2 16h3"/>
            <path d="M4 9 2 17h2m0 0v1a1 1 0 0 0 1 1h1a1 1 0 0 0 1-1v-1m0 0h8m0 0v1a1 1 0 0 0 1 1h1a1 1 0 0 0 1-1v-1"/>
            <path d="M9 11h6l1.5-4.5A1 1 0 0 0 15.5 5h-7A1 1 0 0 0 7.5 6.5z"/>
            <circle cx="6.5" cy="16.5" r="1.5"/><circle cx="16.5" cy="16.5" r="1.5"/>
        </svg>
    ),
    Truck: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M14 18V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"/><path d="M15 18H9"/>
            <path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"/>
            <circle cx="17" cy="18" r="2"/><circle cx="7" cy="18" r="2"/>
        </svg>
    ),
    MapPin: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/><circle cx="12" cy="10" r="3"/>
        </svg>
    ),
    Search: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
        </svg>
    ),
    ArrowLeft: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M19 12H5"/><path d="m12 19-7-7 7-7"/>
        </svg>
    ),
    X: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M18 6 6 18"/><path d="m6 6 12 12"/>
        </svg>
    ),
    CreditCard: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/>
        </svg>
    ),
    Mail: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-10 5L2 7"/>
        </svg>
    ),
    Smartphone: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/>
        </svg>
    ),
    Settings: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/>
            <circle cx="12" cy="12" r="3"/>
        </svg>
    ),
    HelpCircle: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>
        </svg>
    ),
    ChevronRight: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="m9 18 6-6-6-6"/>
        </svg>
    ),
    MessageSquare: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
            <path d="M8 10h.01"/><path d="M12 10h.01"/><path d="M16 10h.01"/>
        </svg>
    ),
    Globe: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <circle cx="12" cy="12" r="10"/><path d="M8 12h8"/>
            <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
        </svg>
    ),
    Check: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M20 6 9 17l-5-5"/>
        </svg>
    ),
    Bell: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/>
            <path d="M13.73 21c-0.39 0.74-1.15 1.26-2.73 1.26s-2.34-0.52-2.73-1.26"/>
        </svg>
    ),
    Shield: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>
        </svg>
    ),
    Lock: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <rect width="18" height="11" x="3" y="11" rx="2" ry="2"/>
            <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
        </svg>
    ),
    Trash: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/>
            <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>
            <line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/>
        </svg>
    ),
    Plus: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M5 12h14"/><path d="M12 5v14"/>
        </svg>
    ),
    Trash2: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>
            <line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/>
        </svg>
    ),
    LogOut: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" x2="9" y1="12" y2="12"/>
        </svg>
    ),
    Wallet: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M17 14h.01"/><path d="M7 7h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14"/>
        </svg>
    ),
    Target: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>
        </svg>
    ),
    Send: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/>
        </svg>
    ),
    Gift: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <rect x="3" y="8" width="18" height="4" rx="1"/><path d="M12 8v13"/><path d="M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"/>
            <path d="M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"/>
        </svg>
    ),
    Award: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <circle cx="12" cy="8" r="6"/><path d="M15.477 12.89 17 22l-5-3-5 3 1.523-9.11"/>
        </svg>
    ),
    History: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>
        </svg>
    ),
    Phone: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>
        </svg>
    ),
    AlertCircle: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/>
        </svg>
    ),
    Loader2: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={`${className} animate-spin`}>
            <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
        </svg>
    ),
    Users: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>
            <path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
        </svg>
    ),
    ChevronDown: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="m6 9 6 6 6-6"/>
        </svg>
    ),
    Info: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>
        </svg>
    ),
    ExternalLink: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
        </svg>
    ),
    Twint: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" className={className}>
            <rect width="20" height="14" x="2" y="5" rx="2" fill="#00A8E7"/>
            <text x="12" y="14" textAnchor="middle" fill="white" fontSize="7" fontWeight="bold">T</text>
        </svg>
    ),
    MessageCircle: ({ className = "w-6 h-6", fill = false }) => (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
             fill={fill ? "currentColor" : "none"} stroke="currentColor" strokeWidth={fill ? "0" : "2"} 
             strokeLinecap="round" strokeLinejoin="round" className={className}>
            <path d="M7.9 20A9 9 0 1 0 4 16.1L2 22z"/>
        </svg>
    )
};

// ==================== FIN ICONS ====================

// ==================== FIN HOOKS PERSONNALISÉS ====================

// Configuration API - API Publique TaxiBook
const API_BASE_URL = 'https://api.app.taxibook.ch';
const SWISSAPP_API_BASE = 'https://api.maps.swissapp.net';
const DEFAULT_COUNTRIES = 'CH,FR';

// Configuration pour l'authentification
const AUTH_CONFIG = {
    TOKEN_KEY: 'user_token',  // Clé unique pour le token (synchronisé avec tout le code)
    USER_KEY: 'rides_user_data'
};

// Fonction globale pour déconnexion automatique sur 401
const forceLogout = () => {
    console.log('🔒 Session expirée - Déconnexion automatique');
    // Supprimer tous les tokens et données utilisateur
    localStorage.removeItem(AUTH_CONFIG.TOKEN_KEY);
    localStorage.removeItem(AUTH_CONFIG.USER_KEY);
    localStorage.removeItem('user');
    localStorage.removeItem('userToken');
    localStorage.removeItem('user_token');
    // Supprimer les données de course en cache
    localStorage.removeItem('client_active_ride');
    localStorage.removeItem('client_booking_data');
    localStorage.removeItem('lastNotifiedMessageId');
    // Recharger la page pour réinitialiser l'état React
    window.location.reload();
};

// Wrapper fetch qui gère automatiquement les erreurs 401
const authFetch = async (url, options = {}) => {
    try {
        const response = await fetch(url, options);
        
        // Si 401, déconnexion automatique
        if (response.status === 401) {
            console.warn('⚠️ Erreur 401 détectée, déconnexion automatique');
            forceLogout();
            return null;
        }
        
        return response;
    } catch (error) {
        throw error;
    }
};

/*
 * INSTRUCTIONS POUR UTILISER SWISSAPI.net:
 * 
 * 1. Remplacez la valeur 'API_KEY' ci-dessus par votre vraie clé API SWISSAPI.net
 * 2. Modifiez 'FROM' pour personnaliser l'expéditeur (11 caractères max)
 * 3. L'API est maintenant intégrée dans les fonctions:
 *    - apiService.sendCode() pour l'authentification
 *    - apiService.sendPhoneUpdateCode() pour la mise à jour du numéro
 * 
 * Test de l'API en console du navigateur:
 * await apiService.sendSMSViaSwissAPI('+41783020487', 'Message test')
 */

// ==================== API CHAT ====================
const chatApi = {
    // Récupérer les messages d'une course
    getMessages: async (jobHash) => {
        try {
            const token = localStorage.getItem(AUTH_CONFIG.TOKEN_KEY);
            const response = await fetch(`${API_BASE_URL}/chat/rides/${jobHash}/messages`, {
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            });
            return await response.json();
        } catch (e) {
            console.error('Error fetching chat messages:', e);
            return { success: false, error: e.message };
        }
    },
    
    // Envoyer un message
    sendMessage: async (jobHash, message) => {
        try {
            const token = localStorage.getItem(AUTH_CONFIG.TOKEN_KEY);
            const response = await fetch(`${API_BASE_URL}/chat/rides/${jobHash}/messages`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify({ message })
            });
            return await response.json();
        } catch (e) {
            console.error('Error sending message:', e);
            return { success: false, error: e.message };
        }
    },
    
    // Marquer comme lu
    markAsRead: async (jobHash) => {
        try {
            const token = localStorage.getItem(AUTH_CONFIG.TOKEN_KEY);
            await fetch(`${API_BASE_URL}/chat/rides/${jobHash}/read`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            });
        } catch (e) {
            console.error('Error marking as read:', e);
        }
    },
    
    // Récupérer les messages rapides
    getQuickMessages: async () => {
        try {
            const token = localStorage.getItem(AUTH_CONFIG.TOKEN_KEY);
            const response = await fetch(`${API_BASE_URL}/chat/quick-messages?user_type=client`, {
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            });
            return await response.json();
        } catch (e) {
            console.error('Error fetching quick messages:', e);
            return { success: false, data: { quick_messages: [] } };
        }
    }
};

// Context global avec toutes les fonctionnalités
const AppContext = createContext();
const useAppContext = () => useContext(AppContext);




// API Services - VRAIS APPELS API
const apiService = {
    // Fonction pour envoyer SMS via SWISSAPI.net
    // Fonction pour envoyer un code SMS via le nouveau Worker
    async sendSMSCode(phoneNumber, action = 'register') {
        try {
            const response = await fetch(`${API_BASE_URL}/auth/send-code`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    phone_number: phoneNumber,
                    country_prefix: '+33',
                    action: action
                })
            });
            
            const result = await response.json();
            return result;
        } catch (error) {
            console.error('Erreur envoi SMS:', error);
            return { success: false, error: error.message };
        }
    },

    // Fonction pour vérifier un code SMS via le nouveau Worker
    async verifySMSCode(phoneNumber, code, action = 'register') {
        try {
            const response = await fetch(`${API_BASE_URL}/auth/verify-code`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    phone_number: phoneNumber,
                    code: code,
                    action: action
                })
            });
            
            const result = await response.json();
            if (result.success && result.data.token) {
                // Stocker le token d'authentification
                localStorage.setItem(AUTH_CONFIG.TOKEN_KEY, result.data.token);
            }
            return result;
        } catch (error) {
            console.error('Erreur vérification SMS:', error);
            return { success: false, error: error.message };
        }
    },

    // Auth endpoints - Version avec API TaxiBook
    async sendCode(phoneNumber) {
        try {
            console.log('📱 [Client] Envoi code SMS à:', phoneNumber);
            
            // Appeler l'API pour envoyer le code
            const response = await fetch(`${API_BASE_URL}/auth/send-code`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    phone_number: phoneNumber,
                    action: 'login',
                    user_type: 'customer'
                })
            });
            
            const result = await response.json();
            console.log('📱 [Client] Réponse API:', result);
            
            return result;
        } catch (error) {
            console.error('❌ [Client] Error sending code:', error);
            return { success: false, error: error.message };
        }
    },

    async verifyCode(phoneNumber, code) {
        try {
            console.log('🔐 [Client] Vérification code pour:', phoneNumber);
            
            // Appeler l'API pour vérifier le code
            const response = await fetch(`${API_BASE_URL}/auth/verify-code`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    phone_number: phoneNumber,
                    code: code,
                    action: 'login',
                    user_data: {
                        user_type: 'customer'
                    }
                })
            });
            
            const result = await response.json();
            console.log('🔐 [Client] Réponse vérification:', result);
            
            if (result.success && result.data) {
                // ✅ Stocker toutes les données nécessaires
                localStorage.setItem('user_token', result.data.token);
                localStorage.setItem('mdriver_user', JSON.stringify(result.data.user));
                // ✅ Stocker explicitement user_uid et user_id
                if (result.data.user?.uid) {
                    localStorage.setItem('user_uid', result.data.user.uid);
                }
                if (result.data.user?.id) {
                    localStorage.setItem('user_id', result.data.user.id);
                }
                console.log('✅ [Client] Token et données utilisateur stockés, uid:', result.data.user?.uid);
            }
            
            return result;
        } catch (error) {
            console.error('❌ [Client] Error verifying code:', error);
            return { success: false, error: error.message };
        }
    },

    // Fonction pour envoyer un code de vérification pour la mise à jour du téléphone
    async sendPhoneUpdateCode(phoneNumber, action = 'update_phone') {
        try {
            // Générer un code de vérification aléatoire (4 chiffres pour la mise à jour)
            const verificationCode = Math.floor(1000 + Math.random() * 9000).toString();
            
            // Message SMS personnalisé pour la mise à jour
            const message = `DriveMe: Votre code de vérification pour changer de numéro est : ${verificationCode}. Code valide 5 minutes.`;
            
            // Envoyer le SMS via SWISSAPI.net
            const smsResult = await this.sendSMSViaSwissAPI(phoneNumber, message);
            
            if (smsResult.success) {
                // Stocker temporairement le code avec un préfixe différent pour la mise à jour
                localStorage.setItem(`update_phone_code_${phoneNumber}`, verificationCode);
                localStorage.setItem(`update_phone_code_time_${phoneNumber}`, Date.now().toString());
                
                return { 
                    success: true, 
                    message: 'Code de vérification envoyé par SMS',
                    data: { code_sent: true }
                };
            } else {
                return {
                    success: false,
                    message: smsResult.message || 'Erreur lors de l\'envoi du SMS'
                };
            }
        } catch (error) {
            console.error('Error sending phone update code:', error);
            return { success: false, error: error.message };
        }
    },

    // User endpoints
    async getUserProfile(userUid) {
        try {
            // ✅ Récupérer le token d'authentification
            const token = localStorage.getItem('user_token');
            
            const response = await authFetch(`${API_BASE_URL}/users/get_profile`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    // ✅ Ajouter le token dans les headers
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify({ user_uid: userUid })
            });
            
            // Si authFetch retourne null (401), arrêter ici
            if (!response) {
                return { success: false, error: 'Session expirée' };
            }
            
            if (response.status === 404) {
                return { 
                    success: false, 
                    error: 'Utilisateur non trouvé',
                    message: 'Profil utilisateur non trouvé (utilisateur simulé)'
                };
            }
            
            const result = await response.json();
            return result;
        } catch (error) {
            console.error('Error getting profile:', error);
            return { 
                success: false, 
                error: error.message,
                message: 'Erreur de connexion'
            };
        }
    },

    async autoRegisterUser(userData) {
        try {
            // ✅ Récupérer le token d'authentification
            const token = localStorage.getItem('user_token');
            
            const response = await fetch(`${API_BASE_URL}/users/auto_register`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    // ✅ Ajouter le token dans les headers
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify(userData)
            });
            
            const result = await response.json();
            return result;
        } catch (error) {
            console.error('Error auto-registering user:', error);
            return { 
                success: false, 
                error: error.message,
                message: 'Erreur lors de l\'enregistrement automatique'
            };
        }
    },

    async updateProfile(userUid, profileData) {
        try {
            // ✅ Récupérer le token d'authentification
            const token = localStorage.getItem('user_token');
            
            // Mettre à jour le profil utilisateur (prénom, nom, etc.)
            const response = await fetch(`${API_BASE_URL}/users/update_profile`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    // ✅ Ajouter le token dans les headers
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify({ user_uid: userUid, ...profileData })
            });
            return await response.json();
        } catch (error) {
            console.error('Error updating profile:', error);
            return { success: false, error: error.message };
        }
    },

    // Fleet endpoints
    async getVehiclePrices(distance = 5) {
        try {
            const response = await fetch(`${API_BASE_URL}/fleets/prices`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ distance: distance })
            });
            const result = await response.json();
            // ✅ Transformer le format API vers le format attendu par le client
            if (result.success && result.data?.fleets) {
                return {
                    success: true,
                    data: {
                        vehicles: result.data.fleets.map(f => ({
                            id: f.id,
                            name: f.name,
                            vehicle_type: f.vehicle_type || f.code,
                            capacity: f.capacity,
                            estimated_price: f.estimated_price,
                            eta: `${5 + Math.floor(f.capacity / 2)} min`,
                            description: f.description,
                            image_url: f.image_url
                        }))
                    }
                };
            }
            return result;
        } catch (error) {
            console.error('Error getting vehicle prices:', error);
            return { success: false, error: error.message };
        }
    },

    // Realtime pricing - Prix en temps réel avec surge, zones promo, codes promo, ETA CORDIC
    async getRealtimePrice(pricingData) {
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/pricing/realtime`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify(pricingData)
            });
            const result = await response.json();
            
            if (result.success && result.data?.vehicles) {
                // Transformer le format API vers le format attendu par le client
                return {
                    success: true,
                    data: {
                        route: result.data.route,
                        surge: result.data.surge,
                        promo_zone: result.data.promo_zone,
                        promo_code: result.data.promo_code,
                        special_fees: result.data.special_fees,
                        slot_surcharge: result.data.slot_surcharge,
                        vehicles: result.data.vehicles.map(v => ({
                            id: v.vehicle.id,
                            code: v.vehicle.code,
                            name: v.vehicle.name,
                            vehicle_type: v.vehicle.code,
                            capacity: v.vehicle.capacity,
                            description: v.vehicle.description,
                            image_url: v.vehicle.image_url,
                            multiplier: v.vehicle.multiplier,
                            // Prix détaillés
                            base_price: v.pricing.base_price,
                            distance_price: v.pricing.distance_price,
                            time_price: v.pricing.time_price,
                            special_fee: v.pricing.special_fee,
                            special_fee_label: v.pricing.special_fee_label,
                            surge_multiplier: v.pricing.surge_multiplier,
                            surge_label: v.pricing.surge_label,
                            slot_surcharge_percent: v.pricing.slot_surcharge_percent || 0,
                            discounts: v.pricing.discounts,
                            total_discount: v.pricing.total_discount,
                            estimated_price: v.pricing.final_price.toFixed(2),
                            final_price: v.pricing.final_price,
                            // ETA basé sur le chauffeur CORDIC le plus proche
                            eta: v.eta?.display || `${Math.round(result.data.route.estimated_duration_minutes)} min`,
                            eta_available: v.eta?.available ?? true,
                            eta_minutes: v.eta?.minutes || Math.round(result.data.route.estimated_duration_minutes),
                            driver_distance_km: v.eta?.distance_km || null
                        }))
                    }
                };
            }
            return result;
        } catch (error) {
            console.error('Error getting realtime price:', error);
            return { success: false, error: error.message };
        }
    },

    // Jobs endpoints
    async createJob(jobData) {
        try {
            // ✅ Récupérer le token d'authentification
            const token = localStorage.getItem('user_token');
            
            const response = await fetch(`${API_BASE_URL}/jobs/create`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    // ✅ Ajouter le token dans les headers
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify(jobData)
            });
            return await response.json();
        } catch (error) {
            console.error('Error creating job:', error);
            return { success: false, error: error.message };
        }
    },

    async getJobs(userUid, category = 'all') {
        try {
            // ✅ Récupérer le token d'authentification
            const token = localStorage.getItem('user_token');
            
            const response = await fetch(`${API_BASE_URL}/jobs/list`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    // ✅ Ajouter le token dans les headers
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify({ user_uid: userUid, category: category })
            });
            const result = await response.json();
            // ✅ Transformer le format API vers le format attendu par le client
            if (result.success && result.data?.jobs) {
                return {
                    success: true,
                    data: result.data.jobs // Le client attend result.data directement comme un tableau
                };
            }
            return result;
        } catch (error) {
            console.error('Error getting jobs:', error);
            return { success: false, error: error.message };
        }
    },

    async updateJobStatus(jobHash, status) {
        try {
            // ✅ Récupérer le token d'authentification
            const token = localStorage.getItem('user_token');
            
            const response = await fetch(`${API_BASE_URL}/jobs/update_status`, {
                method: 'PUT',
                headers: { 
                    'Content-Type': 'application/json',
                    // ✅ Ajouter le token dans les headers
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify({ job_hash: jobHash, status: status })
            });
            return await response.json();
        } catch (error) {
            console.error('Error updating job status:', error);
            return { success: false, error: error.message };
        }
    },

    // Points endpoints
    async getPoints(userUid) {
        try {
            const token = localStorage.getItem('user_token');
            const response = await authFetch(`${API_BASE_URL}/points/my`, {
                headers: {
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            });
            if (!response) return { success: false, error: 'Session expirée', data: { points: 0 } };
            const result = await response.json();
            // Adapter la réponse pour être compatible avec l'ancien format
            if (result.success && result.data) {
                return { 
                    success: true, 
                    data: { 
                        points: result.data.total_points || 0 
                    } 
                };
            }
            return result;
        } catch (error) {
            console.error('Error getting points:', error);
            return { success: false, error: error.message, data: { points: 0 } };
        }
    },

    // Address endpoints
    async getAddressHistory(userUid, limit = 8) {
        try {
            const token = localStorage.getItem('user_token');
            const response = await authFetch(`${API_BASE_URL}/addresses/history?user_uid=${userUid}&limit=${limit}`, {
                headers: {
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            });
            if (!response) return { success: false, error: 'Session expirée' };
            return await response.json();
        } catch (error) {
            console.error('Error getting address history:', error);
            return { success: false, error: error.message };
        }
    },

    async saveAddress(userUid, address, location, placeId = null) {
        try {
            const payload = {
                user_uid: userUid,
                address: address,
                latitude: location?.lat || null,
                longitude: location?.lng || null,
                place_id: placeId || null
            };
            
            console.log('📡 Envoi données sauvegarde adresse:', payload);
            
            // ✅ Récupérer le token d'authentification
            const token = localStorage.getItem('user_token');
            
            const response = await fetch(`${API_BASE_URL}/addresses/history`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    // ✅ Ajouter le token dans les headers
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify(payload)
            });
            const result = await response.json();
            
            console.log('📡 Réponse sauvegarde adresse:', result);
            return result;
        } catch (error) {
            console.error('Error saving address:', error);
            return { success: false, error: error.message };
        }
    },

    // Email endpoints
    async sendEmailCode(email) {
        try {
            const response = await fetch(`${API_BASE_URL}/endpoints/email/send-code.php`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email: email })
            });
            return await response.json();
        } catch (error) {
            console.error('Error sending email code:', error);
            return { success: false, error: error.message };
        }
    },

    async verifyEmailCode(email, code) {
        try {
            const response = await fetch(`${API_BASE_URL}/endpoints/email/verify-code.php`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email: email, code: code })
            });
            return await response.json();
        } catch (error) {
            console.error('Error verifying email code:', error);
            return { success: false, error: error.message };
        }
    },

    // SwissApp API pour recherche d'adresses
    async searchAddresses(query) {
        try {
            const apiURL = `${SWISSAPP_API_BASE}/place?countries=${encodeURIComponent(DEFAULT_COUNTRIES)}&address=${encodeURIComponent(query)}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
            const response = await fetch(apiURL);
            return await response.json();
        } catch (error) {
            console.error('Error searching addresses:', error);
            return { success: false, error: error.message };
        }
    }
};

// Language System - Système de langues
const LanguageContext = React.createContext();

const LanguageProvider = ({ children }) => {
    const [currentLanguage, setCurrentLanguage] = useState('fr');
    const [translations, setTranslations] = useState({});
    const [isLoading, setIsLoading] = useState(true);
    const [forceUpdate, setForceUpdate] = useState(0);

    // Charger les traductions
    const loadTranslations = async (lang) => {
        try {
            setIsLoading(true);
            // Charger le fichier de langue
            const response = await fetch(`languages/${lang}.json`);
            const data = await response.json();
            setTranslations(data);
            setCurrentLanguage(lang);
            
            // Sauvegarder en localStorage
            localStorage.setItem('mdriver_language', lang);
        } catch (error) {
            console.error('Erreur lors du chargement des traductions:', error);
            // Fallback vers anglais si échec
            if (lang !== 'en') {
                await loadTranslations('en');
            }
        } finally {
            setIsLoading(false);
        }
    };

    // Fonction de traduction avec fallback
    const t = (key, params = {}) => {
        const keys = key.split('.');
        let value = translations;
        
        for (const k of keys) {
            if (value && typeof value === 'object' && k in value) {
                value = value[k];
            } else {
                // Fallback: retourner la clé si traduction manquante
                console.warn(`Traduction manquante pour: ${key}`);
                return key;
            }
        }
        
        // Remplacer les paramètres dans la chaîne
        if (typeof value === 'string' && Object.keys(params).length > 0) {
            return value.replace(/\{(\w+)\}/g, (match, param) => {
                return params[param] || match;
            });
        }
        
        return value || key;
    };

    // Changer de langue et sauvegarder en base
    const changeLanguage = async (lang) => {
        await loadTranslations(lang);
        
        // Sauvegarder en base de données si utilisateur connecté
        const user = JSON.parse(localStorage.getItem('mdriver_user') || 'null');
        if (user && user.userId) {
            try {
                await apiService.updatePreferences(user.userId, [
                    { key: 'language', value: lang }
                ]);
            } catch (error) {
                console.error('Erreur lors de la sauvegarde de la langue:', error);
            }
        }
    };

    // Initialiser la langue au démarrage
    useEffect(() => {
        const initLanguage = async () => {
            // Récupérer la langue sauvegardée
            const savedLang = localStorage.getItem('mdriver_language');
            const user = JSON.parse(localStorage.getItem('mdriver_user') || 'null');
            
            let langToLoad = 'fr'; // Langue par défaut
            
            if (user && user.userId) {
                // Tenter de récupérer les préférences utilisateur
                try {
                    const prefs = await apiService.getPreferences(user.userId);
                    const langPref = prefs.find(p => p.preference_key === 'language');
                    if (langPref) {
                        langToLoad = langPref.preference_value;
                    }
                } catch (error) {
                    console.error('Erreur lors de la récupération des préférences:', error);
                }
            } else if (savedLang) {
                langToLoad = savedLang;
            }
            
            await loadTranslations(langToLoad);
        };
        
        initLanguage();
    }, []);

    // Écouter les changements de langue pour forcer le re-render
    useEffect(() => {
        const handleLanguageChange = () => {
            setForceUpdate(prev => prev + 1);
        };
        
        window.addEventListener('languageChanged', handleLanguageChange);
        return () => window.removeEventListener('languageChanged', handleLanguageChange);
    }, []);

    const value = {
        currentLanguage,
        translations,
        isLoading,
        t,
        changeLanguage,
        forceUpdate,
        availableLanguages: [
            { code: 'fr', name: 'Français' },
            { code: 'en', name: 'English' },
            { code: 'de', name: 'Deutsch' }
        ]
    };

    return React.createElement(LanguageContext.Provider, { value }, children);
};

// Hook pour utiliser les traductions
const useTranslation = () => {
    const context = React.useContext(LanguageContext);
    if (!context) {
        throw new Error('useTranslation doit être utilisé dans un LanguageProvider');
    }
    return context;
};

// Ajouter les fonctions de préférences à apiService
apiService.getPreferences = async function(userId) {
    try {
        // ✅ Récupérer le token d'authentification
        const token = localStorage.getItem('user_token');
        
        const response = await fetch(`${API_BASE_URL}/preferences/manage`, {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                // ✅ Ajouter le token dans les headers
                ...(token && { 'Authorization': `Bearer ${token}` })
            },
            body: JSON.stringify({ user_id: userId })
        });
        const result = await response.json();
        return result.success ? result.data : [];
    } catch (error) {
        console.error('Error getting preferences:', error);
        return [];
    }
};

apiService.updatePreferences = async function(userId, preferences) {
    try {
        // ✅ Récupérer le token d'authentification
        const token = localStorage.getItem('user_token');
        
        const response = await fetch(`${API_BASE_URL}/preferences/manage`, {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                // ✅ Ajouter le token dans les headers
                ...(token && { 'Authorization': `Bearer ${token}` })
            },
            body: JSON.stringify({ user_id: userId, preferences })
        });
        return await response.json();
    } catch (error) {
        console.error('Error updating preferences:', error);
        return { success: false, error: error.message };
    }
};

// Provider avec intégration API réelle
const AppProvider = ({ children }) => {
    const [user, setUser] = useState(() => {
        const savedUser = localStorage.getItem('mdriver_user');
        const savedToken = localStorage.getItem('user_token');
        const savedUserId = localStorage.getItem('user_id');
        const savedUserUid = localStorage.getItem('user_uid');
        
        if (savedUser && savedToken) {
            return {
                ...JSON.parse(savedUser),
                token: savedToken,
                userId: savedUserId,
                userUid: savedUserUid
            };
        }
        return null;
    });
    const [userPoints, setUserPoints] = useState(0);
    const [activeRide, setActiveRide] = useState(() => {
        // Charger la course active depuis localStorage au démarrage
        const stored = localStorage.getItem('client_active_ride');
        if (stored) {
            try {
                const parsed = JSON.parse(stored);
                // Vérifier si la course n'est pas terminée/annulée
                if (parsed && !['completed', 'cancelled'].includes(parsed.status)) {
                    return parsed;
                }
            } catch (e) {
                console.error('Error parsing stored active ride:', e);
            }
        }
        return null;
    });
    const [unreadMessages, setUnreadMessages] = useState(0);
    const [lastMessagePreview, setLastMessagePreview] = useState(null);
    const [showMessageNotification, setShowMessageNotification] = useState(false);
    const [currentView, setCurrentView] = useState('welcome');
    const [isAuthenticated, setIsAuthenticated] = useState(!!user);
    const [recentDestinations, setRecentDestinations] = useState([]);
    const [addressHistory, setAddressHistory] = useState([]);
    const [selectedRideData, setSelectedRideData] = useState(null);
    
    const navigate = (viewName, data = null) => {
        // Vérifier l'authentification pour certaines vues
        if (['commander', 'activite', 'compte', 'ride-details'].includes(viewName) && !isAuthenticated) {
            setShowAuthModal(true);
            return;
        }
        
        // Gérer les données spécifiques pour certaines vues
        if (['ride-details', 'order-summary', 'ride-confirmed', 'vehicle-selection'].includes(viewName) && data) {
            setSelectedRideData(data);
        }
        
        setCurrentView(viewName);
    };

    // Modales states
    const [showAuthModal, setShowAuthModal] = useState(false);

    useEffect(() => {
        const url = new URL(window.location.href);
        const magicToken = url.searchParams.get('magic');
        if (magicToken) {
            url.searchParams.delete('magic');
            window.history.replaceState({}, '', url.pathname);
            (async () => {
                try {
                    const result = await clientApi.verifyMagicLink(magicToken);
                    if (result.success && result.data?.token) {
                        const d = result.data;
                        localStorage.setItem('user_token', d.token);
                        localStorage.setItem('mdriver_user', JSON.stringify(d.user));
                        localStorage.setItem('user_uid', d.user?.uid || '');
                        const userData = {
                            phone: d.user?.phone_number || '',
                            email: d.user?.email || '',
                            token: d.token,
                            userId: d.user?.uid,
                            userUid: d.user?.uid,
                            firstName: d.user?.first_name || null
                        };
                        setUser(userData);
                        setIsAuthenticated(true);
                        if (!userData.firstName) {
                            setShowFirstnameModal(true);
                        }
                    }
                } catch (e) { /* invalid token */ }
            })();
        }
    }, []);
    const [showFirstnameModal, setShowFirstnameModal] = useState(false);
    const [showAddressModal, setShowAddressModal] = useState(false);
    const [showVehicleModal, setShowVehicleModal] = useState(false);
    
    // Form states
    const [phoneNumber, setPhoneNumber] = useState('');
    const [countryPrefix, setCountryPrefix] = useState('+41');
    const [verificationCode, setVerificationCode] = useState(['', '', '', '', '', '']); // 6 chiffres
    const [isCodeSent, setIsCodeSent] = useState(false);
    const [countdown, setCountdown] = useState(0);
    
    // Address search states
    const [searchType, setSearchType] = useState('pickup');
    const [searchQuery, setSearchQuery] = useState('');
    const [searchResults, setSearchResults] = useState([]);
    const [isSearching, setIsSearching] = useState(false);
    
    // Trip states
    const [pickupAddress, setPickupAddress] = useState('Ma position actuelle');
    const [destinationAddress, setDestinationAddress] = useState('');
    const [destinationCoords, setDestinationCoords] = useState(null);
    const [selectedVehicle, setSelectedVehicle] = useState(null);
    const [vehicles, setVehicles] = useState([]);
    
    // Map state
    const [mapInstance, setMapInstance] = useState(null);
    const [centerMarker, setCenterMarker] = useState(null);
    
    // Branding dynamique
    const [branding, setBranding] = useState({ display_name: 'DriveMe', logo_url: '', primary_color: '#f97316', company_name: '', company_address: '', contact_phone: '', contact_email: '' });
    useEffect(() => {
        fetch(`${API_BASE_URL}/settings/branding`).then(r => r.json()).then(res => {
            const d = res.data || res;
            setBranding(prev => ({ ...prev, ...d }));
            if (d.display_name) document.title = `${d.display_name} - Réservation de chauffeur`;
            if (d.favicon_url) { let fl = document.querySelector("link[rel~='icon']"); if (!fl) { fl = document.createElement('link'); fl.rel = 'icon'; document.head.appendChild(fl); } fl.href = d.favicon_url; }
        }).catch(() => {});
    }, []);

    // Notifications
    const notifications = useNotifications();

    // Charger les données utilisateur au démarrage (avec flag pour éviter boucle infinie)
    const [hasLoadedUserData, setHasLoadedUserData] = useState(false);
    
    useEffect(() => {
        // ✅ Éviter la boucle infinie en vérifiant si déjà chargé
        if (user?.userUid && !hasLoadedUserData) {
            setHasLoadedUserData(true);
            loadUserData();
        }
    }, [user?.userUid, hasLoadedUserData]);

    const loadUserData = async () => {
        if (!user?.userUid) return;

        try {
            // Charger profil utilisateur
            const profileResult = await apiService.getUserProfile(user.userUid);
            if (profileResult.success && profileResult.data) {
                setUser(prev => ({ ...prev, ...profileResult.data }));
            } else {
                // Si le profil n'existe pas (utilisateur simulé), on continue sans erreur
                console.log('Profil utilisateur non trouvé, utilisateur simulé détecté');
            }

            // Charger points (seulement si le profil existe)
            if (profileResult.success) {
                const pointsResult = await apiService.getPoints(user.userUid);
                if (pointsResult.success && pointsResult.data) {
                    setUserPoints(pointsResult.data.points || 0);
                }

                // Charger historique des adresses (seulement si le profil existe)
                const historyResult = await apiService.getAddressHistory(user.userUid, 8);
                if (historyResult.success && historyResult.data) {
                    setAddressHistory(historyResult.data);
                }
            } else {
                // Pour les utilisateurs simulés, initialiser avec des valeurs par défaut
                setUserPoints(0);
                setAddressHistory([]);
            }

        } catch (error) {
            console.log('Erreur lors du chargement des données utilisateur (normal pour les utilisateurs simulés):', error);
            // Initialiser avec des valeurs par défaut pour les utilisateurs simulés
            setUserPoints(0);
            setAddressHistory([]);
        }
    };

    // Sauvegarde de l'utilisateur
    useEffect(() => {
        if (user) {
            localStorage.setItem('mdriver_user', JSON.stringify(user));
            if (user.token) localStorage.setItem('user_token', user.token);
            if (user.userId) localStorage.setItem('user_id', user.userId);
            if (user.userUid) localStorage.setItem('user_uid', user.userUid);
        } else {
            localStorage.removeItem('mdriver_user');
            localStorage.removeItem('user_token');
            localStorage.removeItem('user_id');
            localStorage.removeItem('user_uid');
        }
    }, [user]);

    // Sauvegarde de la course active
    useEffect(() => {
        if (activeRide) {
            localStorage.setItem('client_active_ride', JSON.stringify(activeRide));
        } else {
            localStorage.removeItem('client_active_ride');
        }
    }, [activeRide]);

    // Ref pour tracker le dernier message notifié
    const lastNotifiedMessageIdRef = useRef(null);

    // Polling pour les courses actives et les messages
    useEffect(() => {
        if (!user?.userUid) return;

        const checkActiveRide = async () => {
            try {
                const token = localStorage.getItem('user_token');
                const response = await authFetch(`${API_BASE_URL}/users/${user.userUid}/rides`, {
                    headers: {
                        ...(token && { 'Authorization': `Bearer ${token}` })
                    }
                });
                if (!response) return; // Session expirée, authFetch gère le logout
                const result = await response.json();
                
                if (result.success && result.data?.rides) {
                    // Trouver une course active
                    const activeStatuses = ['pending', 'searching', 'accepted', 'driver_arriving', 'driver_arrived', 'in_progress'];
                    const active = result.data.rides.find(r => activeStatuses.includes(r.status));
                    
                    // Récupérer la course active actuelle depuis localStorage pour comparaison
                    const storedRide = localStorage.getItem('client_active_ride');
                    const previousActiveRide = storedRide ? JSON.parse(storedRide) : null;
                    
                    if (active) {
                        // Vérifier si le statut a changé
                        if (previousActiveRide && previousActiveRide.job_hash === active.job_hash) {
                            if (previousActiveRide.status !== active.status) {
                                // Statut changé, notifier si pertinent
                                if (active.status === 'accepted' && previousActiveRide.status === 'pending') {
                                    notifications.success('Un chauffeur a accepté votre course !');
                                } else if (active.status === 'driver_arriving') {
                                    notifications.info('Votre chauffeur est en route vers vous');
                                } else if (active.status === 'driver_arrived') {
                                    notifications.success('Votre chauffeur est arrivé !');
                                } else if (active.status === 'in_progress') {
                                    notifications.info('Votre course a commencé');
                                }
                            }
                        }
                        
                        setActiveRide(active);
                        
                        // Vérifier les messages non lus si course active
                        checkUnreadMessages(active.job_hash);
                    } else {
                        // Pas de course active trouvée
                        // Vérifier si on avait une course active qui a été annulée ou terminée
                        if (previousActiveRide) {
                            // Chercher cette course spécifique pour vérifier son statut
                            const previousRide = result.data.rides.find(r => r.job_hash === previousActiveRide.job_hash);
                            
                            if (previousRide) {
                                if (previousRide.status === 'cancelled') {
                                    notifications.error('Votre course a été annulée');
                                    setActiveRide(null);
                                    localStorage.removeItem('client_active_ride');
                                } else if (previousRide.status === 'completed') {
                                    notifications.success('Votre course est terminée !');
                                    setActiveRide(null);
                                    localStorage.removeItem('client_active_ride');
                                }
                            } else {
                                // Course non trouvée, probablement supprimée
                                setActiveRide(null);
                                localStorage.removeItem('client_active_ride');
                            }
                        }
                    }
                }
            } catch (e) {
                console.error('Error checking active ride:', e);
            }
        };

        const checkUnreadMessages = async (jobHash) => {
            if (!jobHash || !user?.userUid) return;
            try {
                const token = localStorage.getItem('user_token');
                const response = await fetch(`${API_BASE_URL}/chat/ride/${jobHash}`, {
                    headers: {
                        ...(token && { 'Authorization': `Bearer ${token}` })
                    }
                });
                const result = await response.json();
                
                if (result.success && result.data) {
                    // Filtrer : messages du CHAUFFEUR uniquement et NON lus
                    // Double vérification : sender_type === 'driver' ET sender_uid !== user.userUid
                    const unread = result.data.messages?.filter(m => 
                        m.sender_type === 'driver' && 
                        m.sender_uid !== user.userUid &&
                        !m.is_read
                    ) || [];
                    
                    if (unread.length > 0) {
                        const lastMsg = unread[unread.length - 1];
                        
                        // Afficher notification seulement si c'est un nouveau message
                        if (lastMsg.id !== lastNotifiedMessageIdRef.current) {
                            lastNotifiedMessageIdRef.current = lastMsg.id;
                            
                            setLastMessagePreview({
                                message: lastMsg.message,
                                sender: 'Chauffeur'
                            });
                            setShowMessageNotification(true);
                            
                            // Cacher après 5 secondes
                            setTimeout(() => setShowMessageNotification(false), 5000);
                        }
                        
                        setUnreadMessages(unread.length);
                    } else {
                        setUnreadMessages(0);
                    }
                }
            } catch (e) {
                console.error('Error checking unread messages:', e);
            }
        };

        // Check immédiatement
        checkActiveRide();

        // Polling toutes les 5 secondes
        const interval = setInterval(checkActiveRide, 5000);

        return () => clearInterval(interval);
    }, [user?.userUid]);

    // Compte à rebours
    useEffect(() => {
        if (countdown > 0) {
            const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
            return () => clearTimeout(timer);
        }
    }, [countdown]);

    const value = {
        // User state
        user, setUser,
        userPoints, setUserPoints,
        activeRide, setActiveRide,
        unreadMessages, setUnreadMessages,
        lastMessagePreview, setLastMessagePreview,
        showMessageNotification, setShowMessageNotification,
        isAuthenticated, setIsAuthenticated,
        recentDestinations, setRecentDestinations,
        addressHistory, setAddressHistory,
        selectedRideData, setSelectedRideData,
        
        // Navigation
        currentView, navigate,
        
        // Modals
        showAuthModal, setShowAuthModal,
        showFirstnameModal, setShowFirstnameModal,
        showAddressModal, setShowAddressModal,
        showVehicleModal, setShowVehicleModal,
        
        // Auth forms
        phoneNumber, setPhoneNumber,
        countryPrefix, setCountryPrefix,
        verificationCode, setVerificationCode,
        isCodeSent, setIsCodeSent,
        countdown, setCountdown,
        
        // Address search
        searchType, setSearchType,
        searchQuery, setSearchQuery,
        searchResults, setSearchResults,
        isSearching, setIsSearching,
        
        // Trip
        pickupAddress, setPickupAddress,
        destinationAddress, setDestinationAddress,
        destinationCoords, setDestinationCoords,
        selectedVehicle, setSelectedVehicle,
        vehicles, setVehicles,
        
        // Map
        mapInstance, setMapInstance,
        centerMarker, setCenterMarker,
        
        // Utils
        notifications,
        loadUserData,
        branding
    };

    return (
        <AppContext.Provider value={value}>
            {children}
        </AppContext.Provider>
    );
};

// Composant Modal d'authentification avec VRAIE API
const AuthModal = () => {
    const { 
        showAuthModal, setShowAuthModal,
        setUser, setIsAuthenticated, setShowFirstnameModal,
        notifications, loadUserData
    } = useAppContext();

    const [authEmail, setAuthEmail] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [linkSent, setLinkSent] = useState(false);
    const emailInputRef = useRef(null);

    useEffect(() => {
        if (showAuthModal && emailInputRef.current) {
            setTimeout(() => emailInputRef.current.focus(), 100);
        }
    }, [showAuthModal]);

    useEffect(() => {
        if (!showAuthModal) return;
        const url = new URL(window.location.href);
        const magicToken = url.searchParams.get('magic');
        if (magicToken) {
            url.searchParams.delete('magic');
            window.history.replaceState({}, '', url.pathname);
            verifyMagicToken(magicToken);
        }
    }, [showAuthModal]);

    const sendLink = async () => {
        if (!authEmail || !authEmail.includes('@')) {
            notifications.error('Veuillez saisir un email valide');
            return;
        }
        setIsLoading(true);
        try {
            const result = await clientApi.sendMagicLink(authEmail);
            if (result.success || result.data) {
                setLinkSent(true);
                notifications.success('Lien de connexion envoyé par email');
            } else {
                notifications.error(result.message || 'Erreur lors de l\'envoi');
            }
        } catch (error) {
            notifications.error('Erreur de connexion');
        } finally {
            setIsLoading(false);
        }
    };

    const verifyMagicToken = async (token) => {
        setIsLoading(true);
        try {
            const result = await clientApi.verifyMagicLink(token);
            if (result.success && result.data?.token) {
                const d = result.data;
                localStorage.setItem('user_token', d.token);
                localStorage.setItem('mdriver_user', JSON.stringify(d.user));
                localStorage.setItem('user_uid', d.user?.uid || '');

                const userData = {
                    phone: d.user?.phone_number || '',
                    email: d.user?.email || '',
                    token: d.token,
                    userId: d.user?.uid,
                    userUid: d.user?.uid,
                    firstName: d.user?.first_name || null
                };
                setUser(userData);
                setIsAuthenticated(true);
                setShowAuthModal(false);
                if (!userData.firstName) {
                    setShowFirstnameModal(true);
                } else {
                    notifications.success('Connexion réussie !');
                    loadUserData();
                }
            } else {
                notifications.error(result.message || 'Lien expiré ou invalide');
            }
        } catch (error) {
            notifications.error('Lien expiré ou invalide. Demandez un nouveau lien.');
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        const url = new URL(window.location.href);
        const magicToken = url.searchParams.get('magic');
        if (magicToken) {
            url.searchParams.delete('magic');
            window.history.replaceState({}, '', url.pathname);
            verifyMagicToken(magicToken);
        }
    }, []);

    if (!showAuthModal) return null;

    return (
        <div className="modal">
            <div className="modal-content modal-enter">
                <h2 className="text-xl font-bold mb-4">Connexion</h2>
                
                {!linkSent ? (
                    <>
                        <div className="mb-4">
                            <label className="block text-sm font-medium mb-2">Adresse email</label>
                            <input
                                ref={emailInputRef}
                                type="email"
                                value={authEmail}
                                onChange={(e) => setAuthEmail(e.target.value)}
                                onKeyDown={(e) => e.key === 'Enter' && sendLink()}
                                placeholder="votre@email.com"
                                className="input-field w-full"
                                disabled={isLoading}
                                autoComplete="email"
                            />
                        </div>
                        <button 
                            onClick={sendLink} 
                            className="btn-primary w-full"
                            disabled={isLoading}
                        >
                            {isLoading ? (
                                <div className="flex items-center justify-center">
                                    <div className="spinner mr-2"></div>
                                    Envoi en cours...
                                </div>
                            ) : (
                                'Recevoir le lien de connexion'
                            )}
                        </button>
                        <p className="text-xs text-gray-500 text-center mt-3">
                            Un lien de connexion sécurisé sera envoyé à votre adresse email.
                        </p>
                    </>
                ) : (
                    <>
                        <div className="text-center py-4">
                            <div className="mb-3"><svg width="40" height="40" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><rect x="4" y="10" width="40" height="28" rx="4" fill="#FFB800"/><path d="M4 14l20 14 20-14" stroke="#E09400" strokeWidth="2.5" fill="none"/><path d="M4 38l14-12M44 38l-14-12" stroke="#E09400" strokeWidth="2" fill="none"/></svg></div>
                            <p className="text-gray-700 mb-2">
                                Un lien de connexion a été envoyé à
                            </p>
                            <p className="font-semibold text-gray-900 mb-4">{authEmail}</p>
                            <p className="text-sm text-gray-500 mb-4">
                                Consultez votre boîte email et cliquez sur le lien pour vous connecter. Le lien expire dans 15 minutes.
                            </p>
                        </div>
                        <button 
                            onClick={() => { setLinkSent(false); setAuthEmail(''); }}
                            className="text-center text-sm text-blue-600 w-full"
                        >
                            Utiliser une autre adresse email
                        </button>
                    </>
                )}
                
                <button 
                    onClick={() => { setShowAuthModal(false); setLinkSent(false); setAuthEmail(''); }}
                    className="mt-4 text-gray-600 w-full"
                    disabled={isLoading}
                >
                    Annuler
                </button>
            </div>
        </div>
    );
};

// Modal prénom avec API
const FirstnameModal = () => {
    const { 
        showFirstnameModal, setShowFirstnameModal,
        user, setUser, notifications, loadUserData 
    } = useAppContext();
    const [firstname, setFirstname] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    const saveFirstname = async () => {
        if (!firstname.trim()) {
            notifications.error('Veuillez saisir votre prénom');
            return;
        }

        setIsLoading(true);
        try {
            const result = await apiService.updateProfile(user.userUid, {
                first_name: firstname.trim()
            });

            if (result.success) {
                setUser({ ...user, firstName: firstname.trim() });
                setShowFirstnameModal(false);
                notifications.success('Bienvenue !');
                loadUserData(); // Recharger toutes les données
            } else {
                notifications.error(result.message || 'Erreur lors de la sauvegarde');
            }
        } catch (error) {
            notifications.error('Erreur de connexion');
        } finally {
            setIsLoading(false);
        }
    };

    if (!showFirstnameModal) return null;

    return (
        <div className="modal">
            <div className="modal-content modal-enter">
                <h2 className="text-xl font-bold mb-4">Bienvenue !</h2>
                <p className="mb-4">Pour personnaliser votre expérience, dites-nous votre prénom :</p>
                <input
                    type="text"
                    value={firstname}
                    onChange={(e) => setFirstname(e.target.value)}
                    placeholder="Votre prénom"
                    className="input-field mb-4"
                    disabled={isLoading}
                />
                <button 
                    onClick={saveFirstname} 
                    className="btn-primary w-full"
                    disabled={isLoading}
                >
                    {isLoading ? (
                        <div className="flex items-center justify-center">
                            <div className="spinner mr-2"></div>
                            Sauvegarde...
                        </div>
                    ) : (
                        'Continuer'
                    )}
                </button>
            </div>
        </div>
    );
};

// Modal recherche d'adresse avec SwissApp API
const AddressSearchModal = () => {
    const { 
        showAddressModal, setShowAddressModal,
        searchType, searchQuery, setSearchQuery,
        searchResults, setSearchResults,
        isSearching, setIsSearching,
        pickupAddress, setPickupAddress,
        destinationAddress, setDestinationAddress,
        destinationCoords, setDestinationCoords,
        addressHistory, user, notifications,
        mapInstance, centerMarker
    } = useAppContext();

    const [showHistory, setShowHistory] = useState(true);
    const [isWaitingToSearch, setIsWaitingToSearch] = useState(false);

    // Debounce pour éviter trop d'appels API lors de la saisie
    useEffect(() => {
        // Si la query est vide, reset immédiatement
        if (searchQuery.length <= 2) {
            setSearchResults([]);
            setShowHistory(true);
            setIsSearching(false);
            setIsWaitingToSearch(false);
            return;
        }

        // Indiquer qu'on attend avant de chercher
        setIsWaitingToSearch(true);
        setIsSearching(false);

        // Annuler la recherche précédente si elle existe
        const searchTimeout = setTimeout(() => {
            setIsWaitingToSearch(false);
            performSearch();
        }, 500); // Attendre 500ms après la dernière saisie

        // Cleanup function pour annuler le timeout si searchQuery change
        return () => {
            clearTimeout(searchTimeout);
            setIsWaitingToSearch(false);
        };
    }, [searchQuery]);

    const performSearch = async () => {
        setIsSearching(true);
        setShowHistory(false);
        
        try {
            const result = await apiService.searchAddresses(searchQuery);
            
            if (result && result.code === 1 && result.datas?.predictions) {
                setSearchResults(result.datas.predictions);
            } else {
                setSearchResults([]);
                notifications.error('Aucun résultat trouvé');
            }
        } catch (error) {
            setSearchResults([]);
            notifications.error('Erreur lors de la recherche');
        } finally {
            setIsSearching(false);
        }
    };

    const selectAddress = async (address, coords = null, placeId = null) => {
        // Déclarer targetCoords au niveau de la fonction pour qu'elle soit accessible partout
        let targetCoords = coords;
        
        if (searchType === 'pickup') {
            setPickupAddress(address);
            
            // Rediriger la carte vers l'adresse d'origine sélectionnée
            if (mapInstance && centerMarker) {
                
                // Valider les coordonnées fournies
                if (targetCoords && (isNaN(targetCoords.lat) || isNaN(targetCoords.lng) || 
                    !isFinite(targetCoords.lat) || !isFinite(targetCoords.lng))) {
                    console.warn('🗺️ Coordonnées fournies invalides:', targetCoords);
                    targetCoords = null; // Forcer le géocodage
                }
                
                // Si pas de coordonnées fournies, récupérer via API
                    if (!targetCoords && address !== 'Ma position actuelle') {
                        try {
                            // Si on a un place_id, utiliser l'API /place_geometry pour des coordonnées précises
                            if (placeId) {
                                console.log('🗺️ Récupération coordonnées via place_id:', placeId);
                                const response = await fetch(
                                    `${SWISSAPP_API_BASE}/place_geometry?placeId=${encodeURIComponent(placeId)}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                                );
                                const data = await response.json();
                                console.log('🗺️ Réponse API /place_geometry:', data);
                                
                                // La structure de réponse de place_geometry est différente
                                if (data && data.code === 1 && data.datas?.result?.geometry?.location) {
                                    const lat = parseFloat(data.datas.result.geometry.location.lat);
                                    const lng = parseFloat(data.datas.result.geometry.location.lng);
                                    
                                    if (!isNaN(lat) && !isNaN(lng) && isFinite(lat) && isFinite(lng)) {
                                        targetCoords = { lat, lng };
                                        console.log('🗺️ Coordonnées précises extraites:', targetCoords);
                                    } else {
                                        console.error('🗺️ Coordonnées invalides depuis /place_geometry:', { lat, lng });
                                    }
                                }
                            } else {
                                // Fallback: rechercher d'abord avec /place pour obtenir des suggestions
                                console.log('🗺️ Recherche de l\'adresse:', address);
                                const response = await fetch(
                                    `${SWISSAPP_API_BASE}/place?address=${encodeURIComponent(address)}&countries=${DEFAULT_COUNTRIES}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                                );
                                const data = await response.json();
                                console.log('🗺️ Réponse API /place:', data);
                                    
                                if (data && data.code === 1 && data.datas?.predictions?.length > 0) {
                                    const firstResult = data.datas.predictions[0];
                                    console.log('🗺️ Premier résultat:', firstResult);
                                    
                                    // Si le résultat a un place_id, l'utiliser pour obtenir les coordonnées précises
                                    if (firstResult.place_id) {
                                        console.log('🗺️ Récupération coordonnées via place_id du résultat:', firstResult.place_id);
                                        const placeResponse = await fetch(
                                            `${SWISSAPP_API_BASE}/place_geometry?placeId=${encodeURIComponent(firstResult.place_id)}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                                        );
                                        const placeData = await placeResponse.json();
                                        console.log('🗺️ Réponse API /place_geometry (fallback):', placeData);
                                        
                                        if (placeData && placeData.code === 1 && placeData.datas?.result?.geometry?.location) {
                                            const lat = parseFloat(placeData.datas.result.geometry.location.lat);
                                            const lng = parseFloat(placeData.datas.result.geometry.location.lng);
                                            
                                            if (!isNaN(lat) && !isNaN(lng) && isFinite(lat) && isFinite(lng)) {
                                                targetCoords = { lat, lng };
                                                console.log('🗺️ Coordonnées précises extraites (fallback):', targetCoords);
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (error) {
                            console.error('Erreur lors de la récupération des coordonnées:', error);
                            notifications.error('Impossible de localiser l\'adresse sur la carte');
                        }
                    }
                
                // Rediriger la carte si on a des coordonnées valides
                if (targetCoords && !isNaN(targetCoords.lat) && !isNaN(targetCoords.lng) && 
                    isFinite(targetCoords.lat) && isFinite(targetCoords.lng)) {
                    console.log('🗺️ Redirection de la carte vers:', targetCoords);
                    
                    try {
                        mapInstance.setView([targetCoords.lat, targetCoords.lng], 16);
                        
                        // Le marker central sera automatiquement mis à jour via l'événement center_changed
                        notifications.success('Carte mise à jour vers l\'adresse sélectionnée');
                    } catch (mapError) {
                        console.error('🗺️ Erreur lors de la redirection de la carte:', mapError);
                        notifications.error('Erreur lors de la mise à jour de la carte');
                    }
                } else {
                    console.warn('🗺️ Coordonnées non valides, pas de redirection de carte:', targetCoords);
                }
            }
        } else {
            setDestinationAddress(address);
            
            // Résoudre les coordonnées de la destination
            if (!targetCoords && placeId) {
                try {
                    const geoResp = await fetch(
                        `${SWISSAPP_API_BASE}/place_geometry?placeId=${encodeURIComponent(placeId)}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                    );
                    const geoData = await geoResp.json();
                    if (geoData?.code === 1 && geoData.datas?.result?.geometry?.location) {
                        const lat = parseFloat(geoData.datas.result.geometry.location.lat);
                        const lng = parseFloat(geoData.datas.result.geometry.location.lng);
                        if (!isNaN(lat) && !isNaN(lng)) {
                            targetCoords = { lat, lng };
                        }
                    }
                } catch (e) {
                    console.warn('Erreur résolution coordonnées destination:', e);
                }
            }
            if (!targetCoords && address !== 'Ma position actuelle') {
                try {
                    const placeResp = await fetch(
                        `${SWISSAPP_API_BASE}/place?address=${encodeURIComponent(address)}&countries=${DEFAULT_COUNTRIES}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                    );
                    const placeData = await placeResp.json();
                    if (placeData?.code === 1 && placeData.datas?.predictions?.[0]?.place_id) {
                        const geoResp = await fetch(
                            `${SWISSAPP_API_BASE}/place_geometry?placeId=${encodeURIComponent(placeData.datas.predictions[0].place_id)}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                        );
                        const geoData = await geoResp.json();
                        if (geoData?.code === 1 && geoData.datas?.result?.geometry?.location) {
                            const lat = parseFloat(geoData.datas.result.geometry.location.lat);
                            const lng = parseFloat(geoData.datas.result.geometry.location.lng);
                            if (!isNaN(lat) && !isNaN(lng)) {
                                targetCoords = { lat, lng };
                            }
                        }
                    }
                } catch (e) {
                    console.warn('Erreur géocodage destination:', e);
                }
            }
            setDestinationCoords(targetCoords);
        }

        // Sauvegarder dans l'historique si utilisateur connecté
        // Utiliser targetCoords (coordonnées récupérées via API) ou coords (coordonnées d'origine)
        const coordsToSave = targetCoords || coords;
        if (user?.userUid && address !== 'Ma position actuelle') {
            try {
                console.log('💾 Sauvegarde adresse avec coordonnées:', coordsToSave);
                await apiService.saveAddress(user.userUid, address, coordsToSave, placeId);
            } catch (error) {
                console.error('Error saving address:', error);
            }
        }

        setShowAddressModal(false);
        setSearchQuery('');
        notifications.success(`${searchType === 'pickup' ? 'Origine' : 'Destination'} définie`);
    };

    const getCurrentLocation = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const userCoords = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude
                    };
                    
                    // Rediriger immédiatement la carte vers la position utilisateur
                    if (mapInstance) {
                        console.log('🗺️ Redirection vers position utilisateur:', userCoords);
                        mapInstance.setView([userCoords.lat, userCoords.lng], 16);
                    }
                    
                    selectAddress('Ma position actuelle', userCoords);
                },
                () => {
                    notifications.error('Impossible d\'obtenir votre position');
                }
            );
        } else {
            notifications.error('Géolocalisation non supportée');
        }
    };

    if (!showAddressModal) return null;

    return (
        <div className="fixed inset-0 bg-white" style={{zIndex: 9999}}>
            <div className="h-full flex flex-col">
                {/* Header avec titre et bouton retour */}
                <div className="bg-white shadow-sm border-b border-gray-200 px-4 py-3">
                    <div className="flex items-center justify-between">
                        <button 
                            onClick={() => setShowAddressModal(false)}
                            className="flex items-center justify-center w-10 h-10 rounded-full hover:bg-gray-100 transition-colors"
                        >
                            <Icons.ArrowLeft className="w-6 h-6 text-gray-600" />
                        </button>
                        
                        <h2 className="text-lg font-semibold text-gray-800">
                            {searchType === 'pickup' ? 'Point de départ' : 'Destination'}
                        </h2>
                        
                        <div className="w-10 h-10"></div>
                    </div>
                </div>
                
                {/* Contenu scrollable */}
                <div className="flex-1 px-4 py-4 overflow-y-auto">
                
                <div className="relative mb-4">
                    <input
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        placeholder="Rechercher une adresse..."
                        className="w-full px-4 py-3 pr-12 border border-gray-300 rounded-xl focus:ring-2 focus:ring-mdriver-orange focus:border-transparent"
                        autoFocus
                    />
                    <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                        {isWaitingToSearch && (
                            <div className="w-5 h-5 border-2 border-orange-300 border-t-mdriver-orange rounded-full animate-spin"></div>
                        )}
                        {isSearching && (
                            <div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin"></div>
                        )}
                        {!isWaitingToSearch && !isSearching && searchQuery.length > 0 && (
                            <Icons.Search className="w-5 h-5 text-gray-400" />
                        )}
                        {searchQuery.length === 0 && (
                            <Icons.Search className="w-5 h-5 text-gray-300" />
                        )}
                    </div>
                </div>

                {searchType === 'pickup' && (
                    <button 
                        onClick={getCurrentLocation}
                        className="w-full mb-4 p-4 text-left border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors"
                    >
                        <div className="flex items-center">
                            <div className="bg-blue-100 p-2 rounded-full mr-3">
                                <Icons.MapPin className="w-5 h-5 text-blue-500" />
                            </div>
                            <div>
                                <div className="font-medium text-gray-800">Ma position actuelle</div>
                                <div className="text-sm text-gray-500">Utiliser la géolocalisation</div>
                            </div>
                        </div>
                    </button>
                )}

                {isWaitingToSearch && (
                    <div className="flex items-center justify-center py-4">
                        <div className="w-4 h-4 border-2 border-orange-300 border-t-mdriver-orange rounded-full animate-spin mr-2"></div>
                        <span className="text-gray-600">Recherche en cours...</span>
                    </div>
                )}

                {isSearching && (
                    <div className="flex items-center justify-center py-4">
                        <div className="spinner mr-2"></div>
                        <span>Recherche...</span>
                    </div>
                )}

                {searchResults.length > 0 && (
                    <div className="space-y-3">
                        <h3 className="font-semibold text-gray-800 mb-2">Résultats de recherche</h3>
                        {searchResults.map((result, index) => (
                            <button
                                key={index}
                                onClick={() => {
                                    // Passer le place_id pour récupérer les coordonnées précises via /place
                                    selectAddress(result.description, null, result.place_id);
                                }}
                                className="w-full p-4 text-left border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors"
                            >
                                <div className="flex items-start">
                                    <div className="bg-gray-100 p-2 rounded-full mr-3 mt-1">
                                        <Icons.MapPin className="w-4 h-4 text-gray-600" />
                                    </div>
                                    <div className="flex-1">
                                        <div className="font-medium text-gray-800 text-sm">{result.description}</div>
                                    </div>
                                </div>
                            </button>
                        ))}
                    </div>
                )}

                {showHistory && addressHistory.length > 0 && (
                    <div className="mt-6">
                        <h3 className="font-semibold text-gray-800 mb-3">Adresses récentes</h3>
                        <div className="space-y-3">
                            {addressHistory.slice(0, 5).map((addr, index) => (
                                <button
                                    key={index}
                                    onClick={() => {
                                        // Valider et convertir les coordonnées de l'historique
                                        let coords = null;
                                        if (addr.latitude && addr.longitude) {
                                            const lat = parseFloat(addr.latitude);
                                            const lng = parseFloat(addr.longitude);
                                            if (!isNaN(lat) && !isNaN(lng) && isFinite(lat) && isFinite(lng)) {
                                                coords = { lat, lng };
                                            }
                                        }
                                        console.log('🏠 Sélection depuis historique:', addr.address, 'coords:', coords);
                                        selectAddress(addr.address, coords);
                                    }}
                                    className="w-full p-4 text-left border border-gray-200 rounded-xl hover:bg-gray-50 transition-colors"
                                >
                                    <div className="flex items-start">
                                        <div className="bg-yellow-100 p-2 rounded-full mr-3 mt-1">
                                            <Icons.Clock className="w-4 h-4 text-yellow-600" />
                                        </div>
                                        <div className="flex-1">
                                            <div className="font-medium text-gray-800 text-sm">{addr.address}</div>
                                            <div className="text-xs text-gray-500 mt-1">Utilisée récemment</div>
                                        </div>
                                    </div>
                                </button>
                            ))}
                        </div>
                    </div>
                )}
                </div>
            </div>
        </div>
    );
};

// Cache global pour éviter les vérifications répétées d'images
const imageErrorCache = {};

// Composant global optimisé pour afficher l'image de véhicule avec fallback automatique
// Accepte maintenant imageUrl pour les images depuis l'API
const VehicleIcon = React.memo(({ vehicleType, className = "w-8 h-8", imageUrl = null }) => {
    const [imageError, setImageError] = useState(false);
    
    // Construire l'URL de l'image : priorité à imageUrl (API), sinon image locale
    const getImagePath = () => {
        if (imageUrl) {
            // Si c'est déjà une URL complète, l'utiliser directement
            if (imageUrl.startsWith('http')) {
                return imageUrl;
            }
            // Sinon, construire l'URL publique SwissApp
            return `https://pub.files.swissapp.net/${imageUrl}`;
        }
        return `public/imgs/${vehicleType}.png`;
    };
    
    const imagePath = getImagePath();
    const cacheKey = imageUrl || vehicleType;
    
    // Vérifier le cache au premier rendu
    useEffect(() => {
        if (imageErrorCache[cacheKey] === true) {
            setImageError(true);
        } else {
            // Reset si l'URL change
            setImageError(false);
        }
    }, [cacheKey]);
    
    // Fonction fallback vers les icônes SVG
    const getFallbackIcon = () => {
        switch(vehicleType) {
            case 'standard':
            case 'confort':
                return <Icons.Car className={`${className} text-mdriver-orange`} />;
            case 'break':
                return <Icons.Car className={`${className} text-mdriver-orange`} />;
            case 'van':
            case 'van-premium':
            case 'van-luxe':
                return <Icons.Truck className={`${className} text-mdriver-orange`} />;
            case 'truck':
                return <Icons.Truck className={`${className} text-mdriver-orange`} />;
            case 'minibus':
                return <Icons.Truck className={`${className} text-mdriver-orange`} />;
            case 'senior':
            case 'pet':
            case 'child':
                return <Icons.Car className={`${className} text-mdriver-orange`} />;
            default:
                return <Icons.Car className={`${className} text-mdriver-orange`} />;
        }
    };
    
    // Si on sait déjà que cette image est en erreur, utiliser directement le fallback
    if (imageError || imageErrorCache[cacheKey] === true) {
        return getFallbackIcon();
    }
    
    return (
        <img 
            src={imagePath} 
            alt={vehicleType} 
            className={`${className} object-contain`}
            onError={() => {
                // Marquer cette image comme erronée dans le cache
                imageErrorCache[cacheKey] = true;
                setImageError(true);
            }}
            onLoad={() => {
                // L'image s'est chargée avec succès
                imageErrorCache[cacheKey] = false;
            }}
        />
    );
});

// Vehicle Selection View - Vue complète de sélection de véhicules
const VehicleSelectionView = () => {
    const { t } = useTranslation();
    const { 
        vehicles, setVehicles,
        notifications, navigate, pickupAddress, destinationAddress,
        selectedRideData
    } = useAppContext();

    const [isLoading, setIsLoading] = useState(false);
    const [countdown, setCountdown] = useState('');
    
    // États pour les données de pricing en temps réel
    const [pricingData, setPricingData] = useState(null);
    const [surgeInfo, setSurgeInfo] = useState(null);
    const [promoZone, setPromoZone] = useState(null);
    const [routeInfo, setRouteInfo] = useState(null);
    
    // Récupérer les dates depuis les données de navigation ou valeurs par défaut
    const selectedDate = selectedRideData?.scheduledDate;
    const selectedTime = selectedRideData?.scheduledTime;

    // Calculer le compte à rebours pour les réservations futures
    const calculateCountdown = () => {
        // Vérifications plus robustes pour éviter "NaN minute"
        if (!selectedDate || !selectedTime || 
            selectedDate === 'null' || selectedTime === 'null' ||
            selectedDate === '' || selectedTime === '') {
            return null;
        }
        
        const now = new Date();
        const scheduledDateTime = new Date(`${selectedDate}T${selectedTime}`);
        
        // Vérifier si la date est valide
        if (isNaN(scheduledDateTime.getTime())) {
            return null;
        }
        
        const diffMs = scheduledDateTime.getTime() - now.getTime();
        
        if (diffMs <= 0) return "Maintenant";
        
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
        const diffHours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
        
        // Vérifier que les valeurs calculées sont valides
        if (isNaN(diffDays) || isNaN(diffHours) || isNaN(diffMinutes)) {
            return null;
        }
        
        if (diffDays > 0) {
            return `Dans ${diffDays} jour${diffDays > 1 ? 's' : ''} et ${diffHours} heure${diffHours > 1 ? 's' : ''}`;
        } else if (diffHours > 0) {
            return `Dans ${diffHours} heure${diffHours > 1 ? 's' : ''} et ${diffMinutes} minute${diffMinutes > 1 ? 's' : ''}`;
        } else {
            return `Dans ${diffMinutes} minute${diffMinutes > 1 ? 's' : ''}`;
        }
    };

    // Formater la date et l'heure pour l'affichage
    const formatPickupTime = () => {
        // Vérifications plus robustes pour éviter "Invalid Date"
        if (!selectedDate || !selectedTime || 
            selectedDate === 'null' || selectedTime === 'null' ||
            selectedDate === '' || selectedTime === '') {
            return "maintenant";
        }
        
        const scheduledDateTime = new Date(`${selectedDate}T${selectedTime}`);
        
        // Vérifier si la date est valide
        if (isNaN(scheduledDateTime.getTime())) {
            return "maintenant";
        }
        
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);
        
        const timeStr = scheduledDateTime.toLocaleTimeString('fr-FR', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
        
        if (scheduledDateTime.toDateString() === today.toDateString()) {
            return `aujourd'hui à ${timeStr}`;
        } else if (scheduledDateTime.toDateString() === tomorrow.toDateString()) {
            return `demain à ${timeStr}`;
        } else {
            const dateStr = scheduledDateTime.toLocaleDateString('fr-FR', { 
                day: 'numeric', 
                month: 'long' 
            });
            return `le ${dateStr} à ${timeStr}`;
        }
    };

    // Mettre à jour le compte à rebours toutes les minutes
    useEffect(() => {
        if (selectedDate && selectedTime) {
            const updateCountdown = () => {
                setCountdown(calculateCountdown());
            };
            
            updateCountdown(); // Mise à jour immédiate
            const interval = setInterval(updateCountdown, 60000); // Mise à jour chaque minute
            
            return () => clearInterval(interval);
        }
    }, [selectedDate, selectedTime]);

    useEffect(() => {
        if (vehicles.length === 0) {
            loadVehicles();
        }
    }, []);

    // Géocoder une adresse pour obtenir les coordonnées
    const geocodeAddress = async (address) => {
        try {
            // Utiliser l'API SwissApp Maps
            const url = `https://api.maps.swissapp.net/place?address=${encodeURIComponent(address)}&countries=CH,FR&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.code === 1 && data.datas?.predictions?.[0]) {
                const placeId = data.datas.predictions[0].place_id;
                // Obtenir les coordonnées
                const geoUrl = `https://api.maps.swissapp.net/place_geometry?placeId=${placeId}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
                const geoResponse = await fetch(geoUrl);
                const geoData = await geoResponse.json();
                
                if (geoData.code === 1 && geoData.datas?.result?.geometry?.location) {
                    return {
                        lat: geoData.datas.result.geometry.location.lat,
                        lng: geoData.datas.result.geometry.location.lng
                    };
                }
            }
            
            // Fallback : utiliser Nominatim
            try {
                const nomResp = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}&limit=1`);
                const nomResults = await nomResp.json();
                if (nomResults.length > 0) {
                    return { lat: parseFloat(nomResults[0].lat), lng: parseFloat(nomResults[0].lon) };
                }
            } catch (e) {
                console.warn('Nominatim fallback failed:', e);
            }
            
            return null;
        } catch (error) {
            console.error('Erreur géocodage:', error);
            return null;
        }
    };

    const loadVehicles = async () => {
        setIsLoading(true);
        try {
            // Géocoder les adresses de départ et destination
            console.log('📍 Géocodage des adresses pour calcul prix...');
            const [pickupCoords, destCoords] = await Promise.all([
                geocodeAddress(pickupAddress),
                geocodeAddress(destinationAddress)
            ]);
            
            if (pickupCoords && destCoords) {
                // Construire la date/heure de prise en charge
                let pickupDatetime = null;
                if (selectedDate && selectedTime) {
                    pickupDatetime = new Date(`${selectedDate}T${selectedTime}`).toISOString();
                }
                
                // Appeler l'API de pricing en temps réel
                const result = await apiService.getRealtimePrice({
                    pickup_address: pickupAddress,
                    pickup_latitude: pickupCoords.lat,
                    pickup_longitude: pickupCoords.lng,
                    destination_address: destinationAddress,
                    destination_latitude: destCoords.lat,
                    destination_longitude: destCoords.lng,
                    pickup_datetime: pickupDatetime
                });
                
                if (result.success && result.data?.vehicles) {
                    setVehicles(result.data.vehicles);
                    setRouteInfo(result.data.route);
                    setSurgeInfo(result.data.surge);
                    setPromoZone(result.data.promo_zone);
                    setPricingData(result.data);
                    console.log('✅ Prix temps réel chargés:', result.data);
                } else {
                    throw new Error('Données de véhicules non reçues');
                }
            } else {
                // Fallback si géocodage échoue : utiliser l'ancien système
                console.warn('⚠️ Géocodage échoué, fallback sur prix estimés');
                const result = await apiService.getVehiclePrices(5);
                
                if (result.success && result.data?.vehicles) {
                    setVehicles(result.data.vehicles);
                } else {
                    // Fallback ultime avec véhicules statiques
                    setVehicles([
                        { id: 1, name: 'Berline Standard', vehicle_type: 'standard', capacity: 4, estimated_price: '25.50', eta: '5 min', description: 'Véhicule économique pour 1-4 passagers' },
                        { id: 2, name: 'Berline Confort', vehicle_type: 'standard', capacity: 4, estimated_price: '32.90', eta: '6 min', description: 'Véhicule confortable avec climatisation' },
                        { id: 3, name: 'Break Familial', vehicle_type: 'break', capacity: 6, estimated_price: '35.90', eta: '8 min', description: 'Idéal pour les familles avec bagages' },
                        { id: 4, name: 'Van Premium', vehicle_type: 'van', capacity: 8, estimated_price: '45.00', eta: '10 min', description: 'Pour groupes jusqu\'à 8 personnes' },
                        { id: 5, name: 'Van Luxe', vehicle_type: 'van', capacity: 8, estimated_price: '55.00', eta: '12 min', description: 'Van haut de gamme avec équipements premium' },
                        { id: 6, name: 'Minibus', vehicle_type: 'van', capacity: 12, estimated_price: '75.00', eta: '15 min', description: 'Transport de groupe jusqu\'à 12 personnes' }
                    ]);
                    notifications.info('Prix estimés (calcul en temps réel indisponible)');
                }
            }
        } catch (error) {
            console.error('Erreur chargement véhicules:', error);
            notifications.error('Erreur lors du chargement des prix');
        } finally {
            setIsLoading(false);
        }
    };

    const selectVehicle = (vehicle) => {
        navigate('order-summary', { 
            vehicle, 
            pickupAddress, 
            destinationAddress,
            scheduledDate: selectedDate,
            scheduledTime: selectedTime
        });
    };

    // Fonction wrapper pour compatibilité
    const getVehicleIcon = (vehicleType, imageUrl = null) => {
        return <VehicleIcon vehicleType={vehicleType} imageUrl={imageUrl} />;
    };

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in-up">
            <Header title={t('order.vehicle_selection')} showBackButton={true} backView="commander" />
            
            <div className="flex-1 p-4 space-y-4 overflow-y-auto">
                {/* Information du trajet */}
                <AnimatedCard className="card" delay={100}>
                    <div className="mb-3">
                        <h3 className="font-bold text-lg text-gray-800 mb-2">Votre trajet</h3>
                        <div className="space-y-2">
                            <div className="flex items-center">
                                <div className="w-3 h-3 bg-green-500 rounded-full mr-3"></div>
                                <span className="text-sm text-gray-600 font-medium">{pickupAddress}</span>
                            </div>
                            <div className="flex items-center">
                                <div className="w-3 h-3 bg-red-500 rounded-full mr-3"></div>
                                <span className="text-sm text-gray-600 font-medium">{destinationAddress}</span>
                            </div>
                        </div>
                        
                        {/* Distance et durée estimées */}
                        {routeInfo && (
                            <div className="mt-3 flex items-center gap-4 text-sm text-gray-600">
                                <span className="flex items-center gap-1">
                                    <Icons.MapPin className="w-4 h-4 text-blue-500" />
                                    {routeInfo.distance_km} km
                                </span>
                                <span className="flex items-center gap-1">
                                    <Icons.Clock className="w-4 h-4 text-green-500" />
                                    ~{routeInfo.estimated_duration_minutes} min
                                </span>
                            </div>
                        )}
                        
                        {/* Information de prise en charge */}
                        <div className="mt-4 pt-3 border-t border-gray-100">
                            <div className="flex items-center text-sm">
                                <Icons.Clock className="w-4 h-4 text-blue-500 mr-2" />
                                <span className="text-gray-700 font-medium">
                                    Prise en charge {formatPickupTime()}
                                </span>
                            </div>
                            
                            {/* Compte à rebours pour les réservations futures */}
                            {countdown && countdown !== "Maintenant" && (
                                <div className="mt-2 flex items-center text-sm">
                                    <Icons.Timer className="w-4 h-4 text-orange-500 mr-2" />
                                    <span className="text-orange-600 font-medium">{countdown}</span>
                                </div>
                            )}
                        </div>
                    </div>
                </AnimatedCard>
                
                {/* Banner surge pricing */}
                {surgeInfo?.is_active && (
                    <AnimatedCard className="bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200 rounded-xl p-3" delay={150}>
                        <div className="flex items-center gap-3">
                            <div className="bg-amber-100 p-2 rounded-full">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M7 2v11h3v9l7-12h-4l4-8z"/></svg>
                            </div>
                            <div className="flex-1">
                                <div className="font-semibold text-amber-800">
                                    Tarif dynamique x{surgeInfo.multiplier?.toFixed(1)}
                                </div>
                                <div className="text-xs text-amber-600">
                                    {surgeInfo.label || 'Forte demande en ce moment'}
                                </div>
                            </div>
                        </div>
                    </AnimatedCard>
                )}
                
                {/* Banner zone promo */}
                {promoZone && (
                    <AnimatedCard className="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-3" delay={175}>
                        <div className="flex items-center gap-3">
                            <div className="bg-green-100 p-2 rounded-full">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>
                            </div>
                            <div className="flex-1">
                                <div className="font-semibold text-green-800">
                                    {promoZone.zone_name || 'Zone promotionnelle'}
                                </div>
                                <div className="text-xs text-green-600">
                                    -{promoZone.discount_percent}% sur ce trajet
                                </div>
                            </div>
                        </div>
                    </AnimatedCard>
                )}

                {/* Liste des véhicules */}
                {isLoading ? (
                    <div className="flex flex-col items-center justify-center py-12">
                        <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-mdriver-orange"></div>
                        <span className="mt-3 text-gray-600">Calcul des prix en cours...</span>
                        <span className="text-xs text-gray-400 mt-1">Analyse du trajet et des tarifs</span>
                    </div>
                ) : (
                    <div className="space-y-3 pb-4">
                        {vehicles.map((vehicle, index) => (
                            <AnimatedCard 
                                key={vehicle.id} 
                                className="card hover:shadow-lg transition-all duration-300 hover:-translate-y-1 cursor-pointer border-2 border-transparent hover:border-mdriver-orange" 
                                delay={200 + (index * 50)}
                            >
                                <div 
                                    onClick={() => selectVehicle(vehicle)}
                                    className="flex items-center"
                                >
                                    <div className="w-24 h-20 flex items-center justify-center mr-4 bg-gray-50 rounded-xl overflow-hidden">
                                        <VehicleIcon 
                                            vehicleType={vehicle.vehicle_type} 
                                            className="w-20 h-16 object-contain" 
                                            imageUrl={vehicle.image_url}
                                        />
                                    </div>
                                    <div className="flex-1">
                                        <div className="font-bold text-lg text-gray-800">{vehicle.name}</div>
                                        <div className="text-sm text-gray-600 mb-1">
                                            {vehicle.capacity} places • 
                                            {vehicle.eta_available !== false ? (
                                                <span className="text-green-600 font-medium"> <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle',marginRight:'2px'}}><path d="M18.92 6.01C18.72 5.42 18.16 5 17.5 5h-11c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 16c-.83 0-1.5-.67-1.5-1.5S5.67 13 6.5 13s1.5.67 1.5 1.5S7.33 16 6.5 16zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 11l1.5-4.5h11L19 11H5z"/></svg>{vehicle.eta}</span>
                                            ) : (
                                                <span className="text-orange-500"> <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle',marginRight:'2px'}}><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.2 3.2.8-1.3-4.5-2.7V7z"/></svg>Recherche chauffeur</span>
                                            )}
                                        </div>
                                        {/* Badges pour surge et discounts */}
                                        <div className="flex flex-wrap gap-1 mt-1">
                                            {vehicle.surge_multiplier > 1 && (
                                                <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800">
                                                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle',marginRight:'2px'}}><path d="M7 2v11h3v9l7-12h-4l4-8z"/></svg> x{vehicle.surge_multiplier.toFixed(1)}
                                                </span>
                                            )}
                                            {vehicle.slot_surcharge_percent > 0 && (
                                                <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                                                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle',marginRight:'2px'}}><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm.5-13H11v6l5.2 3.2.8-1.3-4.5-2.7V7z"/></svg> +{vehicle.slot_surcharge_percent}%
                                                </span>
                                            )}
                                            {vehicle.discounts?.length > 0 && vehicle.discounts.map((d, i) => (
                                                <span key={i} className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle',marginRight:'2px'}}>{d.type === 'zone_promo' ? <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> : <path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7z"/>}</svg> -{d.percent || d.value}%
                                                </span>
                                            ))}
                                            {vehicle.special_fee > 0 && (
                                                <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
                                                    <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle',marginRight:'2px'}}><path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/></svg> +{vehicle.special_fee?.toFixed(0)} CHF
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                    <div className="text-right">
                                        <div className="text-2xl font-bold text-mdriver-orange">{vehicle.estimated_price} CHF</div>
                                        <div className="text-xs text-gray-500">
                                            {pricingData ? 'Prix temps réel' : 'Prix estimé'}
                                        </div>
                                        {vehicle.total_discount > 0 && (
                                            <div className="text-xs text-green-600 font-medium">
                                                -{vehicle.total_discount.toFixed(2)} CHF économisés
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </AnimatedCard>
                        ))}
                    </div>
                )}
            </div>
        </AnimatedView>
    );
};

// Bottom sheet sélection de véhicules (gardé pour compatibilité) 
const VehicleSelectionModal = () => {
    const { 
        showVehicleModal, setShowVehicleModal,
        vehicles, setVehicles,
        notifications, navigate, pickupAddress, destinationAddress
    } = useAppContext();

    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        if (showVehicleModal && vehicles.length === 0) {
            loadVehicles();
        }
    }, [showVehicleModal]);

    const loadVehicles = async () => {
        setIsLoading(true);
        try {
            // Calculer la distance si possible
            let distance = 5; // distance par défaut
            
            const result = await apiService.getVehiclePrices(distance);
            
            if (result.success && result.data?.vehicles) {
                setVehicles(result.data.vehicles);
            } else {
                // Fallback en cas d'erreur API
                setVehicles([
                    { id: 1, name: 'Berline Standard', vehicle_type: 'standard', capacity: 4, estimated_price: '25.50', eta: '5 min' },
                    { id: 2, name: 'Break Familial', vehicle_type: 'break', capacity: 6, estimated_price: '35.90', eta: '8 min' },
                    { id: 3, name: 'Van Premium', vehicle_type: 'van', capacity: 8, estimated_price: '45.00', eta: '10 min' },
                ]);
                notifications.info('Véhicules chargés en mode démonstration');
            }
        } catch (error) {
            notifications.error('Erreur lors du chargement des véhicules');
        } finally {
            setIsLoading(false);
        }
    };

    const selectVehicle = (vehicle) => {
        setShowVehicleModal(false);
        navigate('order-summary', { vehicle, pickupAddress, destinationAddress });
    };

    if (!showVehicleModal) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-end">
            <div 
                className="absolute inset-0 bg-black bg-opacity-50"
                onClick={() => setShowVehicleModal(false)}
            ></div>
            <div className="relative bg-white w-full rounded-t-3xl max-h-[80vh] overflow-hidden modal-enter">
                <div className="p-6">
                    <div className="flex items-center justify-between mb-6">
                        <button 
                            onClick={() => setShowVehicleModal(false)}
                            className="p-2 hover:bg-gray-100 rounded-full"
                        >
                            <Icons.ArrowLeft className="w-6 h-6" />
                        </button>
                        <h2 className="text-xl font-bold">Choisissez votre véhicule</h2>
                        <div className="w-10"></div>
                    </div>
                    
                    {isLoading && vehicles.length === 0 ? (
                        <div className="text-center py-8">
                            <div className="spinner mx-auto mb-4"></div>
                            <p className="text-gray-600">Chargement des véhicules...</p>
                        </div>
                    ) : (
                        <div className="space-y-3 max-h-96 overflow-y-auto">
                            {vehicles.map((vehicle, index) => {

                                const arrivalTime = vehicle.eta || `${Math.floor(Math.random() * 8) + 2} min`;
                                
                                return (
                                    <AnimatedCard 
                                        key={vehicle.id}
                                        className="card cursor-pointer hover:shadow-lg transition-all duration-300 hover:-translate-y-1"
                                        delay={index * 100}
                                    >
                                        <div 
                                            onClick={() => selectVehicle(vehicle)}
                                            className="flex items-center p-4"
                                        >
                                            <div className="w-24 h-24 flex items-center justify-center mr-4">
                                                <VehicleIcon vehicleType={vehicle.vehicle_type} className="w-24 h-24" imageUrl={vehicle.image_url} />
                                            </div>
                                            <div className="flex-1">
                                                <div className="font-semibold text-lg text-gray-800">{vehicle.name}</div>
                                                <div className="text-gray-600 text-sm flex items-center space-x-2">
                                                    <span className="font-medium">{arrivalTime}</span>
                                                    <span>•</span>
                                                    <span>{vehicle.capacity} places</span>
                                                </div>
                                            </div>
                                            <div className="text-right">
                                                <div className="text-xl font-bold text-gray-800">{vehicle.estimated_price} CHF</div>
                                            </div>
                                        </div>
                                    </AnimatedCard>
                                );
                            })}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

// Header Component avec SVG
const Header = ({ title, showBackButton = false, onBack = null, backView = 'welcome' }) => {
    const { navigate, branding } = useAppContext();

    const handleBack = () => {
        if (onBack) {
            onBack();
        } else {
            navigate(backView);
        }
    };

    return (
        <header className="bg-white shadow-sm border-b border-gray-200 px-4 py-3 flex items-center justify-between">
            {showBackButton ? (
                <button 
                    onClick={handleBack}
                    className="flex items-center justify-center w-10 h-10 rounded-full hover:bg-gray-100 transition-colors"
                >
                    <Icons.ArrowLeft className="w-6 h-6 text-gray-600" />
                </button>
            ) : branding.logo_url ? (
                <img src={branding.logo_url} alt={branding.display_name} style={{ height: 32, maxWidth: 140, objectFit: 'contain' }} />
            ) : (
                <div className="flex items-center">
                    <span className="text-2xl font-bold" style={{ color: branding.primary_color || '#f97316' }}>{(branding.display_name || 'DriveMe')[0]}</span>
                    <span className="text-2xl font-bold text-gray-800">{(branding.display_name || 'DriveMe').slice(1).toUpperCase()}</span>
                </div>
            )}
            
            {title && (
                <h1 className="text-lg font-semibold text-gray-800 absolute left-1/2 transform -translate-x-1/2">
                    {title}
                </h1>
            )}
            <div className="w-10 h-10"></div>
        </header>
    );
};

// ==================== ACTIVE RIDE CARD COMPONENT ====================
const ActiveRideCard = ({ ride, onClick }) => {
    const { unreadMessages } = useAppContext();
    
    const getStatusInfo = (status) => {
        const statusMap = {
            'pending': { label: 'En attente', color: 'yellow', icon: 'Clock' },
            'searching': { label: 'Recherche chauffeur', color: 'blue', icon: 'Search' },
            'accepted': { label: 'Chauffeur assigné', color: 'green', icon: 'Check' },
            'driver_arriving': { label: 'Chauffeur en route', color: 'green', icon: 'Car' },
            'driver_arrived': { label: 'Chauffeur arrivé', color: 'green', icon: 'MapPin' },
            'in_progress': { label: 'En course', color: 'blue', icon: 'Car' }
        };
        return statusMap[status] || { label: status, color: 'gray', icon: 'Car' };
    };

    const status = getStatusInfo(ride.status);
    const hasDriver = ride.driver_uid && ride.status !== 'pending' && ride.status !== 'searching';

    const StatusIcon = () => {
        switch(status.icon) {
            case 'Clock': return <Icons.Clock className="w-5 h-5" />;
            case 'Search': return <Icons.Search className="w-5 h-5" />;
            case 'Check': return <Icons.Check className="w-5 h-5" />;
            case 'Car': return <Icons.Car className="w-5 h-5" />;
            case 'MapPin': return <Icons.MapPin className="w-5 h-5" />;
            default: return <Icons.Car className="w-5 h-5" />;
        }
    };

    return (
        <AnimatedCard 
            className={`card border-2 cursor-pointer hover:shadow-lg transition-all ${
                status.color === 'green' ? 'bg-green-50 border-green-300' :
                status.color === 'blue' ? 'bg-blue-50 border-blue-300' :
                status.color === 'yellow' ? 'bg-yellow-50 border-yellow-300' :
                'bg-gray-50 border-gray-300'
            }`}
            delay={400}
            onClick={onClick}
        >
            {/* Header avec statut */}
            <div className="flex items-center justify-between mb-3">
                <div className="flex items-center space-x-2">
                    <div className={`p-2 rounded-full ${
                        status.color === 'green' ? 'bg-green-100 text-green-600' :
                        status.color === 'blue' ? 'bg-blue-100 text-blue-600' :
                        status.color === 'yellow' ? 'bg-yellow-100 text-yellow-600' :
                        'bg-gray-100 text-gray-600'
                    }`}>
                        <StatusIcon />
                    </div>
                    <span className={`font-semibold ${
                        status.color === 'green' ? 'text-green-800' :
                        status.color === 'blue' ? 'text-blue-800' :
                        status.color === 'yellow' ? 'text-yellow-800' :
                        'text-gray-800'
                    }`}>
                        {status.label}
                    </span>
                </div>
                {unreadMessages > 0 && (
                    <div className="bg-red-500 text-white px-2 py-1 rounded-full text-xs font-bold flex items-center space-x-1">
                        <Icons.MessageSquare className="w-3 h-3" />
                        <span>{unreadMessages}</span>
                    </div>
                )}
            </div>

            {/* Destination */}
            <div className="flex items-start space-x-3 mb-3">
                <div className="w-2 h-2 bg-mdriver-orange rounded-full mt-2 flex-shrink-0"></div>
                <div className="flex-1 min-w-0">
                    <div className="text-xs text-gray-500 mb-1">Destination</div>
                    <div className="text-sm font-medium text-gray-800 truncate">
                        {ride.dropoff_address || ride.destination_address || 'Non définie'}
                    </div>
                </div>
            </div>

            {/* Info chauffeur si assigné */}
            {hasDriver && (
                <div className="flex items-center justify-between pt-3 border-t border-gray-200">
                    <div className="flex items-center space-x-3">
                        <div className="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center">
                            <Icons.User className="w-6 h-6 text-gray-500" />
                        </div>
                        <div>
                            <div className="text-sm font-medium text-gray-800">
                                {ride.driver_name || 'Chauffeur'}
                            </div>
                            <div className="text-xs text-gray-500">
                                {ride.vehicle_type || 'Véhicule'}
                            </div>
                        </div>
                    </div>
                    <div className="flex items-center space-x-2">
                        <div className={`px-3 py-1 rounded-full text-xs font-medium ${
                            status.color === 'green' ? 'bg-green-100 text-green-700' :
                            status.color === 'blue' ? 'bg-blue-100 text-blue-700' :
                            'bg-gray-100 text-gray-700'
                        }`}>
                            {ride.estimated_price ? `${ride.estimated_price} CHF` : ''}
                        </div>
                        <Icons.ChevronRight className="w-5 h-5 text-gray-400" />
                    </div>
                </div>
            )}

            {/* Bouton voir détails */}
            {!hasDriver && (
                <div className="flex items-center justify-end pt-3 border-t border-gray-200">
                    <span className="text-sm text-gray-500 flex items-center">
                        Voir détails <Icons.ChevronRight className="w-4 h-4 ml-1" />
                    </span>
                </div>
            )}
        </AnimatedCard>
    );
};

// ==================== ACTIVE RIDE DETAILS VIEW ====================
const ActiveRideDetailsView = () => {
    const { activeRide, navigate, setUnreadMessages, selectedRideData, setActiveRide } = useAppContext();
    const [showChat, setShowChat] = useState(false);
    // Utiliser selectedRideData si disponible, sinon activeRide
    const initialRide = selectedRideData || activeRide;
    const [rideData, setRideData] = useState(initialRide);
    const [loading, setLoading] = useState(false);

    // Ouvrir le chat si demandé via la notification
    useEffect(() => {
        if (selectedRideData?.openChat) {
            setShowChat(true);
        }
    }, [selectedRideData?.openChat]);

    // Écouter l'événement pour ouvrir le chat
    useEffect(() => {
        const handleOpenChat = () => setShowChat(true);
        window.addEventListener('openRideChat', handleOpenChat);
        return () => window.removeEventListener('openRideChat', handleOpenChat);
    }, []);

    // Mettre à jour rideData quand selectedRideData ou activeRide change
    useEffect(() => {
        const ride = selectedRideData || activeRide;
        if (ride) {
            setRideData(ride);
            // Mettre aussi à jour activeRide dans le contexte si on vient de selectedRideData
            if (selectedRideData && !activeRide) {
                setActiveRide(selectedRideData);
            }
            loadRideDetails(ride.job_hash);
        }
    }, [selectedRideData?.job_hash, activeRide?.job_hash]);

    const loadRideDetails = async (jobHash) => {
        const hash = jobHash || rideData?.job_hash;
        if (!hash) return;
        setLoading(true);
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/jobs/${hash}`, {
                headers: {
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            });
            const result = await response.json();
            if (result.success && result.data) {
                setRideData(result.data);
            }
        } catch (e) {
            console.error('Error loading ride details:', e);
        } finally {
            setLoading(false);
        }
    };

    // Polling pour mise à jour
    useEffect(() => {
        const currentJobHash = rideData?.job_hash;
        if (!currentJobHash) return;
        
        const interval = setInterval(() => loadRideDetails(currentJobHash), 5000);
        return () => clearInterval(interval);
    }, [rideData?.job_hash]);

    const getStatusInfo = (status) => {
        const statusMap = {
            'pending': { label: 'En attente de confirmation', color: 'yellow', progress: 20 },
            'searching': { label: 'Recherche d\'un chauffeur...', color: 'blue', progress: 40 },
            'accepted': { label: 'Chauffeur en route vers vous', color: 'green', progress: 60 },
            'driver_arriving': { label: 'Chauffeur en approche', color: 'green', progress: 70 },
            'driver_arrived': { label: 'Votre chauffeur est arrivé', color: 'green', progress: 80 },
            'in_progress': { label: 'Course en cours', color: 'blue', progress: 90 }
        };
        return statusMap[status] || { label: status, color: 'gray', progress: 0 };
    };

    const status = getStatusInfo(rideData?.status);
    const hasDriver = rideData?.driver_uid && rideData?.status !== 'pending' && rideData?.status !== 'searching';

    if (!rideData) {
        return (
            <div className="h-full flex items-center justify-center">
                <div className="text-center text-gray-500">
                    <Icons.Clock className="w-12 h-12 mx-auto mb-4 text-gray-300 animate-spin" />
                    <p>Chargement...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="h-full flex flex-col bg-gray-50">
            {/* Header */}
            <div className="bg-white shadow-sm px-4 py-3 flex items-center">
                <button 
                    onClick={() => navigate('welcome')}
                    className="p-2 -ml-2 text-gray-600 hover:text-gray-800"
                >
                    <Icons.ArrowLeft className="w-6 h-6" />
                </button>
                <div className="ml-3 flex-1">
                    <h3 className="font-semibold text-gray-800">Détails de la course</h3>
                    <p className="text-sm text-gray-500">{status.label}</p>
                </div>
                {loading && <Icons.Clock className="w-5 h-5 text-gray-400 animate-spin" />}
            </div>

            {/* Progress bar */}
            <div className="bg-white px-4 py-2">
                <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                    <div 
                        className={`h-full transition-all duration-500 ${
                            status.color === 'green' ? 'bg-green-500' :
                            status.color === 'blue' ? 'bg-blue-500' :
                            status.color === 'yellow' ? 'bg-yellow-500' :
                            'bg-gray-400'
                        }`}
                        style={{ width: `${status.progress}%` }}
                    />
                </div>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-4 space-y-4">
                {/* Status Card */}
                <div className={`p-4 rounded-xl border-2 ${
                    status.color === 'green' ? 'bg-green-50 border-green-200' :
                    status.color === 'blue' ? 'bg-blue-50 border-blue-200' :
                    status.color === 'yellow' ? 'bg-yellow-50 border-yellow-200' :
                    'bg-gray-50 border-gray-200'
                }`}>
                    <div className="flex items-center space-x-3">
                        <div className={`p-3 rounded-full ${
                            status.color === 'green' ? 'bg-green-100' :
                            status.color === 'blue' ? 'bg-blue-100' :
                            status.color === 'yellow' ? 'bg-yellow-100' :
                            'bg-gray-100'
                        }`}>
                            {rideData?.status === 'searching' ? (
                                <Icons.Search className={`w-6 h-6 animate-pulse ${
                                    status.color === 'blue' ? 'text-blue-600' : 'text-gray-600'
                                }`} />
                            ) : (
                                <Icons.Car className={`w-6 h-6 ${
                                    status.color === 'green' ? 'text-green-600' :
                                    status.color === 'blue' ? 'text-blue-600' :
                                    status.color === 'yellow' ? 'text-yellow-600' :
                                    'text-gray-600'
                                }`} />
                            )}
                        </div>
                        <div>
                            <div className={`font-semibold ${
                                status.color === 'green' ? 'text-green-800' :
                                status.color === 'blue' ? 'text-blue-800' :
                                status.color === 'yellow' ? 'text-yellow-800' :
                                'text-gray-800'
                            }`}>
                                {status.label}
                            </div>
                            {rideData?.estimated_price && (
                                <div className="text-sm text-gray-600">
                                    Prix estimé: {rideData.estimated_price} CHF
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* Driver Card */}
                {hasDriver && (
                    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
                        <h4 className="text-sm font-medium text-gray-500 mb-3">Votre chauffeur</h4>
                        <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-3">
                                <div className="w-14 h-14 bg-gradient-to-br from-blue-400 to-blue-600 rounded-full flex items-center justify-center text-white text-xl font-bold shadow-lg">
                                    {(rideData.driver_name || 'C').charAt(0).toUpperCase()}
                                </div>
                                <div>
                                    <div className="font-semibold text-gray-800">
                                        {rideData.driver_name || 'Chauffeur'}
                                    </div>
                                    {/* Véhicule: marque modèle + plaque */}
                                    <div className="text-sm text-gray-600">
                                        {[rideData.vehicle_brand, rideData.vehicle_model].filter(Boolean).join(' ') || rideData.vehicle_type || 'Standard'}
                                    </div>
                                    {rideData.vehicle_plate && (
                                        <div className="inline-flex items-center gap-1 mt-1 px-2 py-0.5 bg-gray-100 rounded text-xs font-medium text-gray-600">
                                            <Icons.Badge className="w-3 h-3" />
                                            {rideData.vehicle_plate}
                                        </div>
                                    )}
                                    {rideData.driver_phone && (
                                        <div className="text-xs text-gray-400 mt-1">
                                            {rideData.driver_phone}
                                        </div>
                                    )}
                                </div>
                            </div>
                            <button 
                                onClick={() => setShowChat(true)}
                                className="p-3 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors shadow-lg relative"
                            >
                                <Icons.MessageSquare className="w-6 h-6" />
                            </button>
                        </div>
                    </div>
                )}

                {/* Addresses */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
                    <h4 className="text-sm font-medium text-gray-500 mb-3">Trajet</h4>
                    
                    <div className="space-y-4">
                        {/* Pickup */}
                        <div className="flex items-start space-x-3">
                            <div className="w-3 h-3 bg-green-500 rounded-full mt-1.5 flex-shrink-0 ring-4 ring-green-100"></div>
                            <div className="flex-1">
                                <div className="text-xs text-gray-400 mb-1">Départ</div>
                                <div className="text-sm font-medium text-gray-800">
                                    {rideData.pickup_address || 'Non défini'}
                                </div>
                            </div>
                        </div>

                        {/* Line connecting dots */}
                        <div className="ml-1.5 border-l-2 border-dashed border-gray-200 h-4"></div>

                        {/* Dropoff */}
                        <div className="flex items-start space-x-3">
                            <div className="w-3 h-3 bg-mdriver-orange rounded-full mt-1.5 flex-shrink-0 ring-4 ring-orange-100"></div>
                            <div className="flex-1">
                                <div className="text-xs text-gray-400 mb-1">Destination</div>
                                <div className="text-sm font-medium text-gray-800">
                                    {rideData.dropoff_address || rideData.destination_address || 'Non défini'}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Ride Info */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4">
                    <h4 className="text-sm font-medium text-gray-500 mb-3">Informations</h4>
                    <div className="grid grid-cols-2 gap-3">
                        <div className="p-3 bg-gray-50 rounded-lg">
                            <div className="text-xs text-gray-400">Véhicule</div>
                            <div className="text-sm font-medium text-gray-800 capitalize">
                                {rideData.vehicle_type || 'Standard'}
                            </div>
                        </div>
                        <div className="p-3 bg-gray-50 rounded-lg">
                            <div className="text-xs text-gray-400">Passagers</div>
                            <div className="text-sm font-medium text-gray-800">
                                {rideData.passenger_count || 1}
                            </div>
                        </div>
                        {rideData.distance_km && (
                            <div className="p-3 bg-gray-50 rounded-lg">
                                <div className="text-xs text-gray-400">Distance</div>
                                <div className="text-sm font-medium text-gray-800">
                                    {rideData.distance_km} km
                                </div>
                            </div>
                        )}
                        {rideData.estimated_duration_min && (
                            <div className="p-3 bg-gray-50 rounded-lg">
                                <div className="text-xs text-gray-400">Durée estimée</div>
                                <div className="text-sm font-medium text-gray-800">
                                    {rideData.estimated_duration_min} min
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Bottom Button - Chat si chauffeur assigné */}
            {hasDriver && (
                <div className="bg-white border-t border-gray-100 p-4">
                    <button
                        onClick={() => setShowChat(true)}
                        className="w-full py-3 bg-blue-500 text-white rounded-xl font-semibold flex items-center justify-center space-x-2 hover:bg-blue-600 transition-colors"
                    >
                        <Icons.MessageSquare className="w-5 h-5" />
                        <span>Contacter le chauffeur</span>
                    </button>
                </div>
            )}

            {/* Chat Modal */}
            {showChat && rideData && (
                <ChatModal
                    jobHash={rideData.job_hash}
                    driverName={rideData.driver_name || 'Chauffeur'}
                    onClose={() => {
                        setShowChat(false);
                        setUnreadMessages(0);
                    }}
                />
            )}
        </div>
    );
};

// ==================== MESSAGE NOTIFICATION TOAST ====================
const MessageNotificationToast = () => {
    const { showMessageNotification, lastMessagePreview, navigate, activeRide, setShowMessageNotification, currentView } = useAppContext();

    if (!showMessageNotification || !lastMessagePreview) return null;

    const handleClick = () => {
        setShowMessageNotification(false);
        // Si on est déjà sur la vue details, on doit ouvrir le chat
        // Sinon on va sur la vue details (le chat s'ouvrira avec un state)
        if (currentView === 'active-ride-details') {
            // Dispatch un event custom pour ouvrir le chat
            window.dispatchEvent(new CustomEvent('openRideChat'));
        } else {
            // Naviguer vers la vue details avec un flag pour ouvrir le chat
            navigate('active-ride-details', { ...activeRide, openChat: true });
        }
    };

    return (
        <div 
            className="fixed top-4 left-4 right-4 z-[100] animate-slide-down cursor-pointer"
            onClick={handleClick}
        >
            <div className="bg-white rounded-xl shadow-2xl border border-gray-100 p-4 flex items-center space-x-3">
                <div className="w-10 h-10 bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0">
                    <Icons.MessageSquare className="w-5 h-5 text-white" />
                </div>
                <div className="flex-1 min-w-0">
                    <div className="text-sm font-semibold text-gray-800">
                        {lastMessagePreview.sender}
                    </div>
                    <div className="text-sm text-gray-600 truncate">
                        {lastMessagePreview.message}
                    </div>
                </div>
                <button 
                    onClick={(e) => {
                        e.stopPropagation();
                        setShowMessageNotification(false);
                    }}
                    className="p-1 text-gray-400 hover:text-gray-600"
                >
                    <Icons.X className="w-4 h-4" />
                </button>
            </div>
        </div>
    );
};

// ==================== POOLS BUTTON ====================
const PoolsButton = () => {
    const { navigate } = useAppContext();
    const [poolsCount, setPoolsCount] = useState(0);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        loadPoolsCount();
    }, []);

    const loadPoolsCount = async () => {
        try {
            const result = await clientApi.getActivePools();
            if (result.success && result.data?.pools) {
                setPoolsCount(result.data.pools.length);
            }
        } catch (error) {
            console.log('Erreur chargement pools:', error);
        } finally {
            setLoading(false);
        }
    };

    if (loading || poolsCount === 0) return null;

    return (
        <AnimatedButton 
            onClick={() => navigate('pools')}
            className="w-full flex items-center justify-between bg-gradient-to-r from-cyan-500 to-cyan-600 text-white p-4 rounded-xl shadow-md hover:shadow-lg transition-all"
            delay={450}
        >
            <div className="flex items-center space-x-4">
                <div className="bg-white bg-opacity-20 p-3 rounded-full">
                    <Icons.Users className="w-6 h-6 text-white" />
                </div>
                <div className="text-left">
                    <div className="font-semibold">{poolsCount} pool{poolsCount > 1 ? 's' : ''} disponible{poolsCount > 1 ? 's' : ''}</div>
                    <div className="text-sm opacity-90">Transport partagé à prix réduit</div>
                </div>
            </div>
            <Icons.ChevronRight className="w-5 h-5 text-white opacity-70" />
        </AnimatedButton>
    );
};

// ==================== POOLS VIEW ====================
const PoolsView = () => {
    const { navigate, notifications, user } = useAppContext();
    const [pools, setPools] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        loadPools();
    }, []);

    const loadPools = async () => {
        try {
            const result = await clientApi.getActivePools();
            if (result.success && result.data?.pools) {
                setPools(result.data.pools);
            }
        } catch (error) {
            console.error('Erreur chargement pools:', error);
            notifications.error('Erreur lors du chargement des pools');
        } finally {
            setLoading(false);
        }
    };

    const getFillRate = (pool) => {
        if (!pool.max_passengers) return 0;
        return Math.round((pool.upcoming_bookings || 0) / pool.max_passengers * 100);
    };

    const getDayLabel = (day) => {
        const labels = { mon: 'Lun', tue: 'Mar', wed: 'Mer', thu: 'Jeu', fri: 'Ven', sat: 'Sam', sun: 'Dim' };
        return labels[day] || day;
    };

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in-right">
            <Header title="Pools Transport" showBackButton={true} />
            
            {/* Explication du système */}
            <div className="bg-gradient-to-r from-cyan-500 to-cyan-600 px-6 py-4 text-white">
                <div className="flex items-start space-x-3">
                    <div className="bg-white bg-opacity-20 p-2 rounded-full mt-1">
                        <Icons.Users className="w-5 h-5" />
                    </div>
                    <div>
                        <h3 className="font-semibold mb-1">Comment ça marche ?</h3>
                        <p className="text-sm opacity-90">
                            Réservez une place dans un trajet partagé à horaire fixe. 
                            Plus il y a de passagers, moins vous payez ! Le prix est divisé entre tous les participants.
                        </p>
                    </div>
                </div>
            </div>

            <div className="flex-1 overflow-y-auto px-4 py-4">
                {loading ? (
                    <div className="flex items-center justify-center py-12">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-cyan-500"></div>
                    </div>
                ) : pools.length === 0 ? (
                    <div className="text-center py-12">
                        <Icons.Users className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                        <h3 className="text-lg font-semibold text-gray-600">Aucun pool disponible</h3>
                        <p className="text-gray-500 text-sm mt-2">Revenez plus tard pour découvrir de nouvelles offres</p>
                    </div>
                ) : (
                    <div className="space-y-4">
                        {pools.map((pool, index) => {
                            const fillRate = getFillRate(pool);
                            const fillClass = fillRate < 50 ? 'bg-green-500' : fillRate < 80 ? 'bg-yellow-500' : 'bg-red-500';
                            
                            return (
                                <AnimatedCard 
                                    key={pool.uid}
                                    className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden"
                                    delay={index * 100}
                                    onClick={() => navigate('pool-detail', pool)}
                                >
                                    <div className="p-4">
                                        <div className="flex justify-between items-start mb-3">
                                            <div>
                                                <h3 className="font-semibold text-gray-800">{pool.name}</h3>
                                                <div className="flex items-center text-cyan-600 text-sm mt-1">
                                                    <Icons.Clock className="w-4 h-4 mr-1" />
                                                    {pool.departure_time}
                                                </div>
                                            </div>
                                            <div className="text-right">
                                                <div className="text-lg font-bold text-cyan-600">
                                                    dès {pool.min_price?.toFixed(2) || '?'} CHF
                                                </div>
                                                <div className="text-xs text-gray-500">par place</div>
                                            </div>
                                        </div>

                                        <div className="space-y-2 mb-3">
                                            <div className="flex items-center text-sm text-gray-600">
                                                <div className="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
                                                <span className="truncate">{pool.pickup_address}</span>
                                            </div>
                                            <div className="flex items-center text-sm text-gray-600">
                                                <div className="w-3 h-3 bg-red-500 rounded-full mr-2"></div>
                                                <span className="truncate">{pool.destination_address}</span>
                                            </div>
                                        </div>

                                        <div className="flex flex-wrap gap-1 mb-3">
                                            {(pool.days_of_week || []).map(day => (
                                                <span key={day} className="px-2 py-0.5 bg-cyan-50 text-cyan-700 text-xs rounded-full">
                                                    {getDayLabel(day)}
                                                </span>
                                            ))}
                                        </div>

                                        <div>
                                            <div className="flex justify-between text-xs text-gray-500 mb-1">
                                                <span>{pool.upcoming_bookings || 0} / {pool.max_passengers} places réservées</span>
                                                <span>{fillRate}% rempli</span>
                                            </div>
                                            <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
                                                <div className={`h-full ${fillClass} rounded-full transition-all`} style={{ width: `${fillRate}%` }}></div>
                                            </div>
                                        </div>
                                    </div>

                                    <div className="bg-gray-50 px-4 py-3 flex items-center justify-between border-t border-gray-100">
                                        <span className="text-sm text-gray-600">Voir les créneaux disponibles</span>
                                        <Icons.ChevronRight className="w-5 h-5 text-gray-400" />
                                    </div>
                                </AnimatedCard>
                            );
                        })}
                    </div>
                )}
            </div>
        </AnimatedView>
    );
};

// ==================== POOL DETAIL VIEW ====================
const PoolDetailView = () => {
    const { navigate, notifications, user, viewData } = useAppContext();
    const pool = viewData;
    const [slots, setSlots] = useState([]);
    const [loading, setLoading] = useState(true);
    const [selectedSlot, setSelectedSlot] = useState(null);
    const [seats, setSeats] = useState(1);
    const [booking, setBooking] = useState(false);

    useEffect(() => {
        if (pool?.uid) {
            loadSlots();
        }
    }, [pool?.uid]);

    const loadSlots = async () => {
        try {
            const result = await clientApi.getPoolSlots(pool.uid);
            if (result.success && result.data?.slots) {
                setSlots(result.data.slots);
            }
        } catch (error) {
            console.error('Erreur chargement créneaux:', error);
            notifications.error('Erreur lors du chargement des créneaux');
        } finally {
            setLoading(false);
        }
    };

    const handleBook = async () => {
        if (!selectedSlot || !user?.userUid) {
            notifications.error('Veuillez sélectionner un créneau');
            return;
        }

        setBooking(true);
        try {
            const result = await clientApi.bookPoolSlot(pool.uid, selectedSlot.date, seats);
            if (result.success) {
                notifications.success('Réservation confirmée !');
                navigate('activite');
            } else {
                notifications.error(result.error || 'Erreur lors de la réservation');
            }
        } catch (error) {
            console.error('Erreur réservation:', error);
            notifications.error('Erreur lors de la réservation');
        } finally {
            setBooking(false);
        }
    };

    const formatDate = (dateStr) => {
        const date = new Date(dateStr);
        const options = { weekday: 'short', day: 'numeric', month: 'short' };
        return date.toLocaleDateString('fr-CH', options);
    };

    if (!pool) {
        return (
            <AnimatedView className="h-full flex flex-col bg-gray-50">
                <Header title="Détails Pool" showBackButton={true} />
                <div className="flex-1 flex items-center justify-center">
                    <p className="text-gray-500">Pool non trouvé</p>
                </div>
            </AnimatedView>
        );
    }

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in-right">
            <Header title={pool.name} showBackButton={true} />
            
            {/* Infos du pool */}
            <div className="bg-white px-4 py-4 border-b border-gray-100">
                <div className="flex items-center text-cyan-600 mb-3">
                    <Icons.Clock className="w-5 h-5 mr-2" />
                    <span className="font-semibold">Départ à {pool.departure_time}</span>
                </div>

                <div className="space-y-3">
                    <div className="flex items-start">
                        <div className="w-3 h-3 bg-green-500 rounded-full mt-1 mr-3 flex-shrink-0"></div>
                        <div>
                            <div className="text-xs text-gray-500">Départ</div>
                            <div className="text-sm text-gray-800">{pool.pickup_address}</div>
                        </div>
                    </div>
                    <div className="flex items-start">
                        <div className="w-3 h-3 bg-red-500 rounded-full mt-1 mr-3 flex-shrink-0"></div>
                        <div>
                            <div className="text-xs text-gray-500">Arrivée</div>
                            <div className="text-sm text-gray-800">{pool.destination_address}</div>
                        </div>
                    </div>
                </div>

                <div className="mt-4 p-3 bg-cyan-50 rounded-lg">
                    <div className="flex justify-between items-center">
                        <span className="text-sm text-cyan-800">Prix par place</span>
                        <span className="font-bold text-cyan-600">{pool.min_price?.toFixed(2)} - {pool.max_price?.toFixed(2)} CHF</span>
                    </div>
                    <p className="text-xs text-cyan-600 mt-1">Le prix exact dépend du nombre de passagers</p>
                </div>
            </div>

            {/* Créneaux disponibles */}
            <div className="flex-1 overflow-y-auto px-4 py-4">
                <h3 className="font-semibold text-gray-800 mb-3">Créneaux disponibles</h3>

                {loading ? (
                    <div className="flex items-center justify-center py-8">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-cyan-500"></div>
                    </div>
                ) : slots.length === 0 ? (
                    <div className="text-center py-8 text-gray-500">
                        Aucun créneau disponible pour le moment
                    </div>
                ) : (
                    <div className="space-y-2">
                        {slots.map((slot, index) => (
                            <button
                                key={slot.date}
                                onClick={() => slot.is_available && setSelectedSlot(slot)}
                                disabled={!slot.is_available}
                                className={`w-full p-4 rounded-xl border-2 transition-all text-left ${
                                    selectedSlot?.date === slot.date
                                        ? 'border-cyan-500 bg-cyan-50'
                                        : slot.is_available
                                            ? 'border-gray-200 bg-white hover:border-cyan-300'
                                            : 'border-gray-100 bg-gray-50 opacity-50 cursor-not-allowed'
                                }`}
                            >
                                <div className="flex justify-between items-center">
                                    <div>
                                        <div className="font-semibold text-gray-800">{formatDate(slot.date)}</div>
                                        <div className="text-sm text-gray-500">
                                            {slot.available_seats} place{slot.available_seats > 1 ? 's' : ''} disponible{slot.available_seats > 1 ? 's' : ''}
                                        </div>
                                    </div>
                                    <div className="text-right">
                                        <div className="font-bold text-cyan-600">{slot.price_per_seat?.toFixed(2)} CHF</div>
                                        <div className="text-xs text-gray-500">par place</div>
                                    </div>
                                </div>
                            </button>
                        ))}
                    </div>
                )}
            </div>

            {/* Bouton réserver */}
            {selectedSlot && (
                <div className="bg-white border-t border-gray-100 p-4 space-y-3">
                    <div className="flex items-center justify-between">
                        <span className="text-gray-600">Nombre de places</span>
                        <div className="flex items-center space-x-3">
                            <button
                                onClick={() => setSeats(Math.max(1, seats - 1))}
                                className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center"
                            >
                                <Icons.Minus className="w-4 h-4" />
                            </button>
                            <span className="font-bold text-lg w-8 text-center">{seats}</span>
                            <button
                                onClick={() => setSeats(Math.min(selectedSlot.available_seats, seats + 1))}
                                className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center"
                            >
                                <Icons.Plus className="w-4 h-4" />
                            </button>
                        </div>
                    </div>

                    <div className="flex justify-between items-center py-2 border-t border-gray-100">
                        <span className="font-semibold">Total</span>
                        <span className="text-xl font-bold text-cyan-600">
                            {(selectedSlot.price_per_seat * seats).toFixed(2)} CHF
                        </span>
                    </div>

                    <button
                        onClick={handleBook}
                        disabled={booking}
                        className="w-full bg-cyan-500 text-white py-4 rounded-xl font-semibold hover:bg-cyan-600 transition-colors disabled:opacity-50"
                    >
                        {booking ? 'Réservation en cours...' : `Réserver ${seats} place${seats > 1 ? 's' : ''}`}
                    </button>
                </div>
            )}
        </AnimatedView>
    );
};

// Welcome View avec données API
const WelcomeView = () => {
    const { user, userPoints, activeRide, navigate, recentDestinations, setDestinationAddress } = useAppContext();
    const [recentOrigins, setRecentOrigins] = useState([]);
    const [loadingOrigins, setLoadingOrigins] = useState(false);

    // Charger les destinations récentes au chargement
    useEffect(() => {
        if (user?.userUid) {
            loadRecentOrigins();
        }
    }, [user?.userUid]);

    const loadRecentOrigins = async () => {
        if (!user?.userUid) return;
        
        setLoadingOrigins(true);
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/addresses/history?user_uid=${user.userUid}&limit=3`, {
                headers: {
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            });
            const result = await response.json();
            
            if (result.success && result.data) {
                setRecentOrigins(result.data);
            }
        } catch (error) {
            console.error('Erreur chargement destinations récentes:', error);
        } finally {
            setLoadingOrigins(false);
        }
    };

    const handleRecentOriginClick = (address, lat, lng) => {
        // Pré-remplir le champ destination
        setDestinationAddress(address);
        // Naviguer vers commander
        navigate('commander');
        console.log('Destination pré-remplie:', address);
    };

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in">
            <Header />
            
            <div className="bg-white px-6 py-8 fade-in-up">
                <div className="text-center">
                    <h1 className="text-2xl font-bold text-gray-800 mb-2">
                        Bonjour {user?.firstName || 'Utilisateur'} !
                    </h1>
                    <p className="text-gray-600">Où souhaitez-vous aller aujourd'hui ?</p>
                </div>
            </div>

            <div className="px-6 py-4 space-y-4">
                <AnimatedButton 
                    onClick={() => navigate('commander')}
                    className="btn-primary w-full flex items-center justify-between"
                    delay={200}
                >
                    <div className="flex items-center space-x-4">
                        <div className="bg-white bg-opacity-20 p-3 rounded-full">
                            <Icons.Zap className="w-6 h-6 text-white" />
                        </div>
                        <div className="text-left">
                            <div className="font-semibold">Commander maintenant</div>
                            <div className="text-sm opacity-90">Course immédiate</div>
                        </div>
                    </div>
                </AnimatedButton>

                {/* Destinations récentes */}
                {recentOrigins.length > 0 && (
                    <AnimatedCard className="card" delay={300}>
                        <div className="mb-3">
                            <h3 className="text-sm font-semibold text-gray-800 mb-3 flex items-center">
                                <Icons.MapPin className="w-4 h-4 mr-2 text-gray-500" />
                                Destinations récentes
                            </h3>
                        </div>
                        <div className="space-y-2">
                            {recentOrigins.map((origin, index) => (
                                <button
                                    key={index}
                                    onClick={() => handleRecentOriginClick(origin.address, origin.latitude, origin.longitude)}
                                    className="w-full flex items-center justify-between p-3 rounded-lg hover:bg-gray-50 transition-colors text-left border border-gray-100 hover:border-gray-200"
                                >
                                    <div className="flex items-center space-x-3 min-w-0 flex-1">
                                        <div className="w-2 h-2 bg-mdriver-orange rounded-full flex-shrink-0"></div>
                                        <div className="flex-1 min-w-0">
                                            <div className="text-sm font-medium text-gray-800 truncate">
                                                {origin.address.length > 40 ? `${origin.address.substring(0, 40)}...` : origin.address}
                                            </div>
                                        </div>
                                    </div>
                                    <Icons.ChevronRight className="w-4 h-4 text-gray-400" />
                                </button>
                            ))}
                        </div>
                    </AnimatedCard>
                )}

                {activeRide ? (
                    <ActiveRideCard ride={activeRide} onClick={() => navigate('active-ride-details', activeRide)} />
                ) : (
                    <AnimatedButton 
                        onClick={() => navigate('activite')}
                        className="btn-secondary w-full flex items-center justify-between"
                        delay={400}
                    >
                        <div className="flex items-center space-x-4">
                            <div className="bg-gray-300 p-3 rounded-full">
                                <Icons.Calendar className="w-6 h-6 text-gray-600" />
                            </div>
                            <div className="text-left">
                                <div className="font-semibold">Mes courses</div>
                                <div className="text-sm text-gray-600">Voir l'activité</div>
                            </div>
                        </div>
                    </AnimatedButton>
                )}
                
                {/* Bouton Pools */}
                <PoolsButton />
            </div>

            <div className="px-6 py-4 grid grid-cols-2 gap-4">
                <AnimatedCard className="card" delay={600}>
                    <div className="flex items-center space-x-3">
                        <div className="bg-yellow-100 p-2 rounded-full">
                            <Icons.Star className="w-6 h-6 text-yellow-500" />
                        </div>
                        <div>
                            <div className="text-sm text-gray-600">Mes points</div>
                            <div className="font-bold text-lg">{userPoints}</div>
                        </div>
                    </div>
                </AnimatedCard>

                <AnimatedCard className="card" delay={800}>
                    <div className="flex items-center space-x-3">
                        <div className="bg-green-100 p-2 rounded-full">
                            <Icons.Leaf className="w-6 h-6 text-green-500" />
                        </div>
                        <div>
                            <div className="text-sm text-gray-600">CO₂ économisé</div>
                            <div className="font-bold text-lg">24g <span className="text-xs text-gray-500">ce mois</span></div>
                        </div>
                    </div>
                </AnimatedCard>
            </div>
        </AnimatedView>
    );
};

// Commander View avec animations
const CommanderView = () => {
    const { t } = useTranslation();
    const { 
        pickupAddress, destinationAddress, setPickupAddress,
        setShowAddressModal, setSearchType, setSearchQuery, setSearchResults,
        setShowVehicleModal, notifications, navigate,
        mapInstance, setMapInstance, centerMarker, setCenterMarker
    } = useAppContext();
    const mapRef = useRef(null);
    const mapInstanceRef = useRef(null);
    const centerMarkerRef = useRef(null);
    const geocodeTimerRef = useRef(null);
    const [mapLoaded, setMapLoaded] = useState(false);
    const [mapError, setMapError] = useState(null);
    const [showScheduleModal, setShowScheduleModal] = useState(false);
    const [selectedVehicle, setSelectedVehicle] = useState(null);
    const [selectedDate, setSelectedDate] = useState(null); // null = "dès que possible"
    const [selectedTime, setSelectedTime] = useState(null); // null = "dès que possible"
    const [vehicles, setVehicles] = useState([]);
    const [loadingVehicles, setLoadingVehicles] = useState(false);
    
    const forceReloadMap = () => {
        console.log('🔄 Rechargement forcé de la carte...');
        setMapLoaded(false);
        setMapError(null);
        if (mapInstanceRef.current) {
            try { mapInstanceRef.current.remove(); } catch (e) {}
        }
        mapInstanceRef.current = null;
        if (mapRef.current) {
            mapRef.current.innerHTML = '';
        }
        // Redéclencher l'initialisation
        setTimeout(() => {
            const initMapEvent = new CustomEvent('initMap');
            window.dispatchEvent(initMapEvent);
        }, 100);
    };

    useEffect(() => {
        console.log('🗺️ CommanderView useEffect démarré');
        
        const initMap = () => {
            console.log('🗺️ Tentative d\'initialisation de la carte');

            if (mapRef.current && window.L && !mapInstanceRef.current) {
                try {
                    console.log('🗺️ Création de la carte Leaflet...');
                    
                    const map = L.map(mapRef.current, {
                        zoomControl: false,
                        attributionControl: false
                    }).setView([46.2044, 6.1432], 14);

                    L.tileLayer('https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
                        attribution: '© Google Maps',
                        maxZoom: 20
                    }).addTo(map);

                    console.log('🗺️ Carte créée avec succès');
                    mapInstanceRef.current = map;
                    setMapInstance(map);
                    setMapLoaded(true);

                    const centerIcon = L.divIcon({
                        html: '<div style="width:20px;height:20px;background:#FF6B35;border:3px solid #fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.3);"></div>',
                        className: '',
                        iconSize: [20, 20],
                        iconAnchor: [10, 10]
                    });
                    const centerMarker = L.marker(map.getCenter(), { icon: centerIcon, interactive: false, zIndexOffset: 1000 }).addTo(map);

                    console.log('🗺️ Marqueur central créé');
                    centerMarkerRef.current = centerMarker;
                    setCenterMarker(centerMarker);

                    let isSnapping = false;

                    map.on('move', () => {
                        const center = map.getCenter();
                        if (centerMarker && center) {
                            centerMarker.setLatLng(center);
                        }
                    });

                    map.on('moveend', () => {
                        if (isSnapping) return;
                        const center = map.getCenter();

                        if (geocodeTimerRef.current) {
                            clearTimeout(geocodeTimerRef.current);
                        }

                        geocodeTimerRef.current = setTimeout(async () => {
                            try {
                                const response = await fetch(
                                    `${SWISSAPP_API_BASE}/geocode?latitude=${center.lat}&longitude=${center.lng}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                                );
                                const data = await response.json();

                                if (data && data.address) {
                                    setPickupAddress(data.address);

                                    // Snap to nearest road: search the returned address to get precise coordinates
                                    try {
                                        const placeResp = await fetch(
                                            `${SWISSAPP_API_BASE}/place?address=${encodeURIComponent(data.address)}&countries=${DEFAULT_COUNTRIES}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                                        );
                                        const placeData = await placeResp.json();

                                        if (placeData?.code === 1 && placeData.datas?.predictions?.[0]?.place_id) {
                                            const geoResp = await fetch(
                                                `${SWISSAPP_API_BASE}/place_geometry?placeId=${encodeURIComponent(placeData.datas.predictions[0].place_id)}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`
                                            );
                                            const geoData = await geoResp.json();

                                            if (geoData?.code === 1 && geoData.datas?.result?.geometry?.location) {
                                                const snapLat = parseFloat(geoData.datas.result.geometry.location.lat);
                                                const snapLng = parseFloat(geoData.datas.result.geometry.location.lng);

                                                if (!isNaN(snapLat) && !isNaN(snapLng)) {
                                                    const dist = map.getCenter().distanceTo(L.latLng(snapLat, snapLng));
                                                    // Only snap if within 200m to avoid jarring jumps
                                                    if (dist > 5 && dist < 200) {
                                                        isSnapping = true;
                                                        map.panTo([snapLat, snapLng], { animate: true, duration: 0.3 });
                                                        setTimeout(() => { isSnapping = false; }, 500);
                                                    }
                                                }
                                            }
                                        }
                                    } catch (snapErr) {
                                        console.error('Snap error:', snapErr);
                                    }
                                }
                            } catch (error) {
                                console.error('Erreur géocodage inverse:', error);
                            }
                        }, 400);
                    });

                    map.whenReady(() => {
                        console.log('🗺️ Carte complètement chargée et prête');
                        
                        if (navigator.geolocation) {
                            navigator.geolocation.getCurrentPosition(
                                (position) => {
                                    console.log('📍 Position utilisateur obtenue:', position.coords);
                                    const userLocation = L.latLng(position.coords.latitude, position.coords.longitude);
                                    map.panTo(userLocation);
                                    map.setZoom(16);
                                },
                                (error) => {
                                    console.log('📍 Géolocalisation refusée:', error.message);
                                },
                                {
                                    enableHighAccuracy: true,
                                    timeout: 5000,
                                    maximumAge: 300000
                                }
                            );
                        }
                    });

                } catch (error) {
                    console.error('❌ Erreur lors de l\'initialisation de la carte:', error);
                    setMapError(error.message || 'Erreur de chargement de la carte');
                }
            } else {
                console.log('🗺️ Conditions non remplies pour l\'initialisation');
            }
        };

        const timer = setTimeout(() => {
            if (window.L) {
                console.log('🗺️ Leaflet déjà disponible, initialisation immédiate');
                initMap();
            } else {
                console.log('🗺️ Leaflet pas encore disponible, attente...');
                
                let attempts = 0;
                const maxAttempts = 50;
                
                const checkLeaflet = setInterval(() => {
                    attempts++;
                    
                    if (window.L) {
                        console.log('✅ Leaflet disponible!');
                        clearInterval(checkLeaflet);
                        initMap();
                    } else if (attempts >= maxAttempts) {
                        console.error('❌ Timeout: Leaflet n\'a pas pu être chargé');
                        clearInterval(checkLeaflet);
                        setMapError('Impossible de charger la carte. Vérifiez votre connexion.');
                    }
                }, 200);

                return () => {
                    clearInterval(checkLeaflet);
                    if (geocodeTimerRef.current) {
                        clearTimeout(geocodeTimerRef.current);
                    }
                };
            }
        }, 100);
        
        const handleForceReload = () => {
            initMap();
        };
        window.addEventListener('initMap', handleForceReload);

        return () => {
            clearTimeout(timer);
            if (geocodeTimerRef.current) {
                clearTimeout(geocodeTimerRef.current);
            }
            window.removeEventListener('initMap', handleForceReload);
        };
    }, [setPickupAddress]);

    const openAddressSearch = (type) => {
        setSearchType(type);
        setSearchQuery('');
        setSearchResults([]);
        setShowAddressModal(true);
    };

    const handleOrderNow = async () => {
        if (!destinationAddress) {
            notifications.error('Veuillez choisir une destination');
            return;
        }
        
        // Si un véhicule est déjà sélectionné, aller au résumé de commande
        if (selectedVehicle) {
            navigate('order-summary');
            return;
        }
        
        // Naviguer vers la vue complète de sélection de véhicules avec les dates
        navigate('vehicle-selection', { scheduledDate: selectedDate, scheduledTime: selectedTime });
    };

    const loadVehicles = async () => {
        setLoadingVehicles(true);
        try {
            // Calculer la distance pour les prix
            let distance = 5; // Distance par défaut
            
            const response = await fetch(`${API_BASE_URL}/fleets/prices`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ distance: distance })
            });
            const data = await response.json();
            
            if (data.success) {
                setVehicles(data.data.vehicles || []);
            } else {
                throw new Error(data.message || 'Erreur lors du chargement');
            }
        } catch (error) {
            console.error('Erreur API véhicules:', error);
            notifications.error('Impossible de charger les véhicules');
            setVehicles([]);
        } finally {
            setLoadingVehicles(false);
        }
    };

    const selectVehicle = (vehicle) => {
        setSelectedVehicle(vehicle);
        setShowVehicleModal(false);
        navigate('order-summary', { vehicle, pickupAddress, destinationAddress, selectedDate, selectedTime });
    };

    // Réinitialiser la sélection de véhicule quand les adresses changent
    useEffect(() => {
        if (selectedVehicle) {
            setSelectedVehicle(null);
        }
    }, [pickupAddress, destinationAddress]);

    return (
        <div className="h-full flex flex-col bg-gray-50">
            <AnimatedView className="" animationType="fade-in-up">
                <Header title={t('order.title')} showBackButton={true} />
            </AnimatedView>
            
            {/* Map étendue jusqu'au bas - SANS animation pour éviter l'invisibilité */}
            <div className="flex-1 relative">
                <div ref={mapRef} className="w-full h-full bg-gray-200" style={{ minHeight: '400px' }}></div>
                
                {/* Indicateur de chargement ou erreur */}
                {!mapLoaded && (
                    <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
                        <div className="text-center p-6">
                            {mapError ? (
                                <div>
                                    <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                        <Icons.X className="w-8 h-8 text-red-500" />
                                    </div>
                                    <h3 className="text-lg font-semibold text-gray-800 mb-2">Erreur de chargement</h3>
                                    <p className="text-gray-600 mb-4">{mapError}</p>
                                    <button 
                                        onClick={forceReloadMap}
                                        className="btn-primary"
                                    >
                                        Réessayer
                                    </button>
                                </div>
                            ) : (
                                <div>
                                    <div className="spinner mx-auto mb-4"></div>
                                    <p className="text-gray-600">Chargement de la carte...</p>
                                    <p className="text-sm text-gray-500 mt-2">Veuillez patienter...</p>
                                </div>
                            )}
                        </div>
                    </div>
                )}
                
                {/* Overlay avec les contrôles d'adresse en haut */}
                <div className="absolute top-4 left-4 right-4 fade-in-left" style={{zIndex: 1000}}>
                    <div className="bg-white rounded-2xl shadow-2xl border border-gray-200 overflow-hidden">
                        <button 
                            onClick={() => openAddressSearch('pickup')}
                            className="w-full flex items-center px-4 py-4 hover:bg-gray-50 transition-all text-left border-b border-gray-100"
                        >
                            <div className="flex items-center mr-3">
                                <div className="w-4 h-4 bg-blue-500 rounded-full shadow-sm"></div>
                                <div className="w-px h-8 bg-gray-300 ml-2"></div>
                            </div>
                            <div className="flex-1 min-w-0">
                                <div className="text-xs text-gray-500 mb-1 font-medium">Origine</div>
                                <div className="text-gray-800 font-semibold truncate text-sm">{pickupAddress}</div>
                            </div>
                            <Icons.MapPin className="w-5 h-5 text-gray-400 ml-2" />
                        </button>

                        <button 
                            onClick={() => openAddressSearch('destination')}
                            className="w-full flex items-center px-4 py-4 hover:bg-gray-50 transition-all text-left"
                        >
                            <div className="flex items-center mr-3">
                                <div className="w-4 h-4 bg-red-500 rounded-full shadow-sm"></div>
                            </div>
                            <div className="flex-1 min-w-0">
                                <div className="text-xs text-gray-500 mb-1 font-medium">Destination</div>
                                <div className={`font-semibold truncate text-sm ${destinationAddress ? 'text-gray-800' : 'text-gray-400'}`}>
                                    {destinationAddress || 'Où souhaitez-vous aller ?'}
                                </div>
                            </div>
                            <Icons.Search className="w-5 h-5 text-gray-400 ml-2" />
                        </button>
                    </div>
                </div>

                {/* Bouton de commande en bas avec calendrier */}
                {destinationAddress && (
                    <div className="absolute bottom-6 left-6 right-6 scale-in" style={{ zIndex: 1000, animationDelay: '0.5s' }}>
                        <div className="flex space-x-3">
                            {/* Bouton calendrier */}
                            <AnimatedButton 
                                onClick={() => setShowScheduleModal(true)} 
                                className={`relative font-bold py-4 px-4 rounded-xl shadow-2xl transition-all ${
                                    selectedDate && selectedTime 
                                        ? 'bg-mdriver-orange text-white border-2 border-mdriver-orange' 
                                        : 'bg-white border-2 border-mdriver-orange text-mdriver-orange hover:bg-mdriver-orange hover:text-white'
                                }`}
                                delay={500}
                            >
                                <Icons.Calendar className="w-6 h-6" />
                                {selectedDate && selectedTime && (
                                    <div className="absolute -top-1 -right-1 w-3 h-3 bg-green-500 rounded-full border-2 border-white"></div>
                                )}
                            </AnimatedButton>
                            
                            {/* Bouton commander principal */}
                            <AnimatedButton 
                                onClick={handleOrderNow} 
                                className="btn-primary flex-1 shadow-2xl border-2 border-white text-lg font-bold py-4" 
                                delay={500}
                            >
                                {selectedVehicle ? `Confirmer ${selectedVehicle.name}` : 'Commander'}
                            </AnimatedButton>
                        </div>
                    </div>
                )}

                {/* Modal de programmation date/heure */}
                {showScheduleModal && (
                    <div className="fixed inset-0 flex items-end" style={{ zIndex: 99999 }}>
                        <div 
                            className="absolute inset-0 bg-black bg-opacity-50"
                            onClick={() => setShowScheduleModal(false)}
                        ></div>
                        <div className="relative bg-white w-full rounded-t-3xl max-h-[80vh] overflow-hidden modal-enter">
                            <div className="p-6">
                                <div className="flex items-center justify-between mb-6">
                                    <button 
                                        onClick={() => setShowScheduleModal(false)}
                                        className="p-2 hover:bg-gray-100 rounded-full"
                                    >
                                        <Icons.ArrowLeft className="w-6 h-6" />
                                    </button>
                                    <h2 className="text-xl font-bold">Programmer votre course</h2>
                                    <div className="w-10"></div>
                                </div>
                                
                                <div className="space-y-6">
                                    {/* Sélection de date */}
                                    <div>
                                        <h3 className="text-lg font-semibold mb-3">Date</h3>
                                        <div className="grid grid-cols-7 gap-2">
                                            {Array.from({ length: 14 }, (_, i) => {
                                                const date = new Date();
                                                date.setDate(date.getDate() + i);
                                                const isSelected = selectedDate === date.toISOString().split('T')[0];
                                                return (
                                                    <button
                                                        key={i}
                                                        onClick={() => {
                                            const isoDate = date.toISOString().split('T')[0];
                                            setSelectedDate(isoDate);
                                        }}
                                                        className={`p-3 text-center rounded-xl transition-all ${
                                                            isSelected 
                                                                ? 'bg-mdriver-orange text-white' 
                                                                : 'bg-gray-100 hover:bg-gray-200'
                                                        }`}
                                                    >
                                                        <div className="text-xs font-medium">
                                                            {date.toLocaleDateString('fr-FR', { weekday: 'short' })}
                                                        </div>
                                                        <div className="text-sm font-bold">
                                                            {date.getDate()}
                                                        </div>
                                                    </button>
                                                );
                                            })}
                                        </div>
                                    </div>
                                    
                                    {/* Sélection d'heure */}
                                    <div>
                                        <h3 className="text-lg font-semibold mb-3">Heure</h3>
                                        <div className="grid grid-cols-4 gap-2 max-h-40 overflow-y-auto">
                                            {Array.from({ length: 36 }, (_, i) => {
                                                const hour = Math.floor(6 + i * 0.5);
                                                const minute = (i % 2) * 30;
                                                const timeString = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
                                                const isSelected = selectedTime === timeString;
                                                if (hour >= 24) return null;
                                                return (
                                                    <button
                                                        key={timeString}
                                                        onClick={() => setSelectedTime(timeString)}
                                                        className={`p-3 text-sm font-medium rounded-xl transition-all ${
                                                            isSelected 
                                                                ? 'bg-mdriver-orange text-white' 
                                                                : 'bg-gray-100 hover:bg-gray-200'
                                                        }`}
                                                    >
                                                        {timeString}
                                                    </button>
                                                );
                                            })}
                                        </div>
                                    </div>
                                </div>

                                {/* Bouton "Le plus rapide possible" */}
                                <div className="mt-6">
                                    <button 
                                        onClick={() => {
                                            setSelectedDate(null);
                                            setSelectedTime(null);
                                            setShowScheduleModal(false);
                                            notifications.info('Course configurée en mode "dès que possible"');
                                        }}
                                        className="w-full py-3 bg-green-600 text-white rounded-xl font-medium hover:bg-green-700 transition-colors flex items-center justify-center space-x-2"
                                    >
                                        <Icons.Zap className="w-5 h-5" />
                                        <span>Le plus rapide possible</span>
                                    </button>
                                </div>
                                
                                <div className="mt-4 flex space-x-3">
                                    <button 
                                        onClick={() => setShowScheduleModal(false)}
                                        className="flex-1 py-3 border border-gray-300 rounded-xl font-medium text-gray-700 hover:bg-gray-50"
                                    >
                                        Annuler
                                    </button>
                                    <button 
                                        onClick={() => {
                                            setShowScheduleModal(false);
                                            const formattedDate = new Date(selectedDate).toLocaleDateString('fr-FR', { 
                                                weekday: 'long', 
                                                year: 'numeric', 
                                                month: 'long', 
                                                day: 'numeric' 
                                            });
                                            notifications.success(`Course programmée pour le ${formattedDate} à ${selectedTime}`);
                                        }}
                                        disabled={!selectedDate || !selectedTime}
                                        className="flex-1 py-3 bg-mdriver-orange text-white rounded-xl font-medium disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        Confirmer
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}



            </div>
        </div>
    );
};

// Activite View avec API et animations
const ActiviteView = () => {
    const { t } = useTranslation();
    const { user, notifications, navigate } = useAppContext();
    const [rides, setRides] = useState([]);
    const [loading, setLoading] = useState(true);
    const [activeTab, setActiveTab] = useState('active');
    const [hasLoaded, setHasLoaded] = useState(false);
    
    const visibleItems = useStaggerAnimation(rides.length, 150);

    const loadRides = useCallback(async () => {
        if (!user?.userUid) {
            console.log('⚠️ [Activity] user.userUid non défini, arrêt du chargement');
            setLoading(false);
            setHasLoaded(true); // ✅ Marquer comme chargé même sans userUid
            return;
        }

        console.log('📋 [Activity] Chargement courses pour:', user.userUid, 'tab:', activeTab);
        setLoading(true);
        try {
            const result = await apiService.getJobs(user.userUid, activeTab);
            console.log('📋 [Activity] Résultat:', result);
            
            if (result.success && result.data) {
                // ✅ S'assurer que c'est bien un tableau
                const ridesArray = Array.isArray(result.data) ? result.data : [];
                setRides(ridesArray);
                console.log('✅ [Activity] Courses chargées:', ridesArray.length);
            } else {
                setRides([]);
                console.log('⚠️ [Activity] Aucune course ou erreur');
            }
        } catch (error) {
            console.error('❌ [Activity] Erreur:', error);
            notifications.error('Erreur lors du chargement des courses');
            setRides([]);
        } finally {
            setLoading(false);
            setHasLoaded(true);
        }
    }, [user?.userUid, activeTab]);

    // Chargement initial
    useEffect(() => {
        if (!hasLoaded) {
            loadRides(); // ✅ Appeler même sans userUid, la fonction gère ce cas
        }
    }, [user?.userUid, hasLoaded, loadRides]);

    // Chargement lors du changement d'onglet (sans dépendance sur loadRides)
    useEffect(() => {
        if (hasLoaded) {
            // ✅ Recharger même si userUid manque (affichera "aucune course")
            if (!user?.userUid) {
                setRides([]);
                return;
            }
            
            // Appel direct pour éviter les dépendances
            (async () => {
                setLoading(true);
                try {
                    const result = await apiService.getJobs(user.userUid, activeTab);
                    
                    if (result.success && result.data) {
                        const ridesArray = Array.isArray(result.data) ? result.data : [];
                        setRides(ridesArray);
                    } else {
                        setRides([]);
                    }
                } catch (error) {
                    notifications.error('Erreur lors du chargement des courses');
                    setRides([]);
                } finally {
                    setLoading(false);
                }
            })();
        }
    }, [activeTab, user?.userUid]);

    // Gérer le changement d'onglet
    const handleTabChange = useCallback((tab) => {
        if (tab !== activeTab) {
            setActiveTab(tab);
        }
    }, [activeTab]);

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in-right">
            <Header title={t('activity.title')} showBackButton={true} />
            
            {/* Onglets */}
            <div className="bg-white px-6 py-2 fade-in-up">
                <div className="flex space-x-4">
                    <button
                        onClick={() => handleTabChange('active')}
                        className={`py-2 px-1 border-b-2 font-medium text-sm transition-all ${
                            activeTab === 'active' 
                                ? 'border-mdriver-orange text-mdriver-orange transform scale-105' 
                                : 'border-transparent text-gray-500 hover:text-gray-700'
                        }`}
                    >
                        Courses actives
                    </button>
                    <button
                        onClick={() => handleTabChange('completed')}
                        className={`py-2 px-1 border-b-2 font-medium text-sm transition-all ${
                            activeTab === 'completed' 
                                ? 'border-mdriver-orange text-mdriver-orange transform scale-105' 
                                : 'border-transparent text-gray-500 hover:text-gray-700'
                        }`}
                    >
                        Historique
                    </button>
                </div>
            </div>

            <div className="flex-1 px-6 py-4">
                {loading ? (
                    <div className="text-center py-8 fade-in">
                        <div className="spinner mx-auto mb-4"></div>
                        <p className="text-gray-600">Chargement...</p>
                    </div>
                ) : rides.length === 0 ? (
                    <div className="text-center py-12 fade-in-up">
                        <div className="mb-4 scale-in flex justify-center">
                            <Icons.Car className="w-16 h-16 text-gray-400" />
                        </div>
                        <h3 className="text-lg font-semibold mb-2 text-gray-800">Aucune course</h3>
                        <p className="text-gray-600 mb-6">Vous n'avez aucune course programmée</p>
                        <AnimatedButton 
                            onClick={() => navigate('commander')}
                            className="btn-primary"
                            delay={500}
                        >
                            Réserver maintenant
                        </AnimatedButton>
                    </div>
                ) : (
                    <div className="space-y-4">
                        {rides.map((ride, index) => {
                            
                            // Formater le prix avec 2 décimales arrondi à 0.50
                            const formatPrice = (price) => {
                                if (!price && price !== 0) return '-';
                                const p = parseFloat(price);
                                const rounded = Math.round(p * 2) / 2;
                                return rounded.toFixed(2);
                            };
                            
                            // Extraire la destination courte (rue + ville)
                            const getShortAddress = (address) => {
                                if (!address) return '-';
                                const parts = address.split(',');
                                return parts.length > 1 ? `${parts[0]}, ${parts[1].trim()}` : parts[0];
                            };

                            // Obtenir le prix à afficher
                            const displayPrice = ride.final_price || ride.estimated_price || ride.price || 0;
                            
                            // Déterminer si c'est une course active
                            const isActiveRide = ['pending', 'dispatching', 'searching', 'accepted', 'driver_assigned', 'in_progress', 'active'].includes(ride.status);
                            
                            return (
                                <AnimatedCard 
                                    key={ride.id || ride.job_hash} 
                                    className="card hover:shadow-lg transition-all duration-300 hover:-translate-y-1 cursor-pointer" 
                                    delay={index * 150}
                                >
                                    <div 
                                        onClick={() => {
                                            if (isActiveRide) {
                                                // Pour les courses actives, naviguer vers la vue active
                                                navigate('active-ride-details', ride);
                                            } else {
                                                // Pour les courses terminées/annulées, naviguer vers les détails
                                                navigate('ride-details', ride);
                                            }
                                        }}
                                        className="w-full"
                                    >
                                        {/* En-tête avec date et prix */}
                                        <div className="flex justify-between items-center mb-3 pb-2 border-b border-gray-100">
                                            <div className="text-sm text-gray-500">
                                                <i className="fas fa-calendar-alt mr-1"></i>
                                                {formatDateLocal(ride.created_at)}
                                            </div>
                                            <div className="text-lg font-bold text-mdriver-orange">
                                                {formatPrice(displayPrice)} CHF
                                            </div>
                                        </div>
                                        
                                        {/* Origine et Destination */}
                                        <div className="space-y-2 mb-3">
                                            <div className="flex items-start">
                                                <div className="w-3 h-3 bg-green-500 rounded-full mt-1.5 mr-3 flex-shrink-0"></div>
                                                <div className="flex-1 min-w-0">
                                                    <div className="text-xs text-gray-500 uppercase">Départ</div>
                                                    <div className="font-medium text-gray-800 truncate">{getShortAddress(ride.pickup_address)}</div>
                                                </div>
                                            </div>
                                            <div className="flex items-start">
                                                <div className="w-3 h-3 bg-red-500 rounded-full mt-1.5 mr-3 flex-shrink-0"></div>
                                                <div className="flex-1 min-w-0">
                                                    <div className="text-xs text-gray-500 uppercase">Destination</div>
                                                    <div className="font-medium text-gray-800 truncate">{getShortAddress(ride.dropoff_address || ride.destination_address)}</div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        {/* Footer avec statut et véhicule */}
                                        <div className="flex justify-between items-center pt-2 border-t border-gray-100">
                                            <div className="flex items-center gap-2">
                                                <div className={`px-3 py-1 rounded-full text-xs font-medium ${
                                                    ride.status === 'completed' ? 'bg-green-100 text-green-800' :
                                                    ride.status === 'in_progress' || ride.status === 'active' ? 'bg-blue-100 text-blue-800' :
                                                    ride.status === 'pending' || ride.status === 'dispatching' ? 'bg-yellow-100 text-yellow-800' :
                                                    ride.status === 'cancelled' ? 'bg-red-100 text-red-800' :
                                                    'bg-gray-100 text-gray-800'
                                                }`}>
                                                    {ride.status === 'completed' ? <><svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle',marginRight:'3px'}}><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/></svg>Terminée</> :
                                                     ride.status === 'in_progress' ? 'En cours' :
                                                     ride.status === 'active' ? 'En cours' :
                                                     ride.status === 'pending' ? 'En attente' :
                                                     ride.status === 'dispatching' ? 'Dispatch' :
                                                     ride.status === 'cancelled' ? <><svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle',marginRight:'3px'}}><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>Annulée</> :
                                                     ride.status_name || ride.status}
                                                </div>
                                                {ride.vehicle_type && (
                                                    <span className="text-xs text-gray-500 flex items-center gap-1">
                                                        <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M18.92 6.01C18.72 5.42 18.16 5 17.5 5h-11c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 16c-.83 0-1.5-.67-1.5-1.5S5.67 13 6.5 13s1.5.67 1.5 1.5S7.33 16 6.5 16zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 11l1.5-4.5h11L19 11H5z"/></svg> {ride.vehicle_type}
                                                    </span>
                                                )}
                                            </div>
                                            <button 
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    if (isActiveRide) {
                                                        navigate('active-ride-details', ride);
                                                    } else {
                                                        navigate('ride-details', ride);
                                                    }
                                                }}
                                                className="text-mdriver-orange font-medium text-sm hover:text-yellow-600 transition-all flex items-center gap-1"
                                            >
                                                Détails <Icons.ChevronRight className="w-4 h-4" />
                                            </button>
                                        </div>
                                    </div>
                                </AnimatedCard>
                            );
                        })}
                    </div>
                )}
            </div>
        </AnimatedView>
    );
};

// Compte View avec points API et animations
const CompteView = () => {
    const { t } = useTranslation();
    const { user, userPoints, navigate, setUser, setIsAuthenticated, notifications, branding } = useAppContext();
    const [showRoleModal, setShowRoleModal] = useState(false);
    const [switchingRole, setSwitchingRole] = useState(false);
    const authToken = localStorage.getItem('user_token');
    
    // Récupérer les rôles de l'utilisateur
    const userRoles = user?.roles || ['customer'];
    const activeRole = user?.active_role || user?.user_type || 'customer';
    const hasDriverRole = userRoles.includes('driver');
    
    const menuItems = [
        { icon: 'CreditCard', title: 'Paiements', subtitle: 'Gérer vos méthodes de paiement', action: 'payments' },
        { icon: 'Mail', title: 'Email', subtitle: 'Ajouter/modifier votre email', action: 'email' },
        { icon: 'Smartphone', title: 'Téléphone', subtitle: 'Modifier votre numéro', action: 'phone' },
        { icon: 'Settings', title: 'Paramètres', subtitle: 'Préférences de l\'app', action: 'settings' },
        { icon: 'HelpCircle', title: 'Aide', subtitle: 'Support et FAQ', action: 'help' },
    ];

    const handleLogout = () => {
        // Demander confirmation avant la déconnexion
        if (window.confirm('Êtes-vous sûr de vouloir vous déconnecter ?')) {
            // Nettoyer le localStorage complètement
            localStorage.removeItem('user');
            localStorage.removeItem('userToken');
            localStorage.removeItem('user_token');
            localStorage.removeItem(AUTH_CONFIG.TOKEN_KEY);
            localStorage.removeItem(AUTH_CONFIG.USER_KEY);
            localStorage.removeItem('client_active_ride');
            localStorage.removeItem('client_booking_data');
            localStorage.removeItem('lastNotifiedMessageId');
            
            // Afficher un message de confirmation
            notifications?.success?.('Vous avez été déconnecté avec succès');
            
            // Recharger la page pour réinitialiser tous les états React
            window.location.reload();
        }
    };

    // Fonction pour passer en mode chauffeur
    const handleSwitchToDriver = async () => {
        if (hasDriverRole) {
            // L'utilisateur a déjà le rôle chauffeur, rediriger vers l'app chauffeur
            setSwitchingRole(true);
            try {
                const response = await fetch(`${API_CONFIG.BASE_URL}/auth/switch-role`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${authToken}`
                    },
                    body: JSON.stringify({ target_role: 'driver' })
                });
                
                if (response.ok) {
                    notifications?.success?.(t('account.switch_to_driver'));
                    // Rediriger vers l'app chauffeur
                    window.location.href = 'https://driver.app.taxibook.ch';
                } else {
                    const data = await response.json();
                    notifications?.error?.(data.error || 'Erreur lors du changement de rôle');
                }
            } catch (error) {
                console.error('Erreur switch role:', error);
                notifications?.error?.('Erreur de connexion');
            } finally {
                setSwitchingRole(false);
            }
        } else {
            // L'utilisateur n'a pas le rôle chauffeur, afficher le modal pour devenir chauffeur
            setShowRoleModal(true);
        }
    };

    // Fonction pour demander à devenir chauffeur
    const handleBecomeDriver = async () => {
        setSwitchingRole(true);
        try {
            const response = await fetch(`${API_CONFIG.BASE_URL}/auth/add-role`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${authToken}`
                },
                body: JSON.stringify({ 
                    new_role: 'driver',
                    user_data: {
                        first_name: user?.firstName || user?.first_name,
                        last_name: user?.lastName || user?.last_name
                    }
                })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                setShowRoleModal(false);
                // Mettre à jour l'utilisateur avec les nouveaux rôles
                setUser(prev => ({ ...prev, roles: data.roles }));
                
                if (data.pending_validation) {
                    notifications?.info?.('Demande envoyée ! Votre compte chauffeur est en attente de validation.');
                } else {
                    notifications?.success?.('Vous êtes maintenant aussi chauffeur !');
                    // Rediriger vers l'app chauffeur
                    window.location.href = 'https://driver.app.taxibook.ch';
                }
            } else {
                notifications?.error?.(data.error || 'Erreur lors de l\'ajout du rôle');
            }
        } catch (error) {
            console.error('Erreur add role:', error);
            notifications?.error?.('Erreur de connexion');
        } finally {
            setSwitchingRole(false);
        }
    };

    const handleMenuClick = (action) => {
        switch (action) {
            case 'help':
                navigate('help');
                break;
            case 'points':
                navigate('points-history');
                break;
            case 'settings':
                navigate('settings');
                break;
            case 'payments':
                navigate('payment-methods');
                break;
            case 'email':
                navigate('email-settings');
                break;
            case 'phone':
                navigate('phone-settings');
                break;
            case 'logout':
                handleLogout();
                break;
            case 'switch-driver':
                handleSwitchToDriver();
                break;
            default:
                console.log('Menu item clicked:', action);
                // Autres actions à implémenter plus tard
                break;
        }
    };

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in-left">
            <Header title={t('account.title')} showBackButton={true} />
            
            <div className="bg-white px-6 py-6 fade-in-up">
                <div className="flex items-center space-x-4">
                    <div className="w-16 h-16 bg-gray-300 rounded-full flex items-center justify-center scale-in">
                        <Icons.User className="w-8 h-8 text-gray-600" />
                    </div>
                    <div className="flex-1">
                        <h3 className="text-lg font-semibold text-gray-800">
                            {user?.firstName || 'Utilisateur'}
                        </h3>
                        <div className="flex items-center space-x-1">
                            <Icons.Star className="w-4 h-4 text-yellow-500" fill={true} />
                            <span className="text-sm text-gray-600">{user?.stars || '5.0'}</span>
                        </div>
                    </div>
                </div>
            </div>

            <AnimatedCard 
                className="card mx-6 my-2 cursor-pointer hover:shadow-md transition-all duration-300 hover:-translate-y-1" 
                delay={300}
            >
                <div 
                    onClick={() => handleMenuClick('points')}
                    className="flex items-center justify-between"
                >
                    <div className="flex items-center space-x-3">
                        <div className="bg-yellow-100 p-2 rounded-full">
                            <Icons.Star className="w-6 h-6 text-yellow-500" />
                        </div>
                        <div>
                            <div className="font-semibold text-gray-800">Points de fidélité</div>
                            <div className="text-sm text-gray-600">
                                {Math.floor(userPoints / 1000)} x 5CHF disponibles
                            </div>
                        </div>
                    </div>
                    <div className="flex items-center space-x-2">
                        <div className="text-2xl font-bold text-mdriver-orange">{userPoints}</div>
                        <Icons.ChevronRight className="w-5 h-5 text-gray-400" />
                    </div>
                </div>
            </AnimatedCard>

            <div className="px-6 space-y-2">
                {menuItems.map((item, index) => (
                    <AnimatedCard 
                        key={index} 
                        className="card hover:shadow-md transition-all duration-300 hover:-translate-y-1 cursor-pointer" 
                        delay={500 + (index * 100)}
                    >
                        <div 
                            onClick={() => handleMenuClick(item.action)}
                            className="flex items-center justify-between"
                        >
                            <div className="flex items-center space-x-4">
                                <div className="transition-transform hover:scale-110">
                                    {React.createElement(Icons[item.icon], {
                                        className: "w-6 h-6 text-gray-600"
                                    })}
                                </div>
                                <div className="text-left">
                                    <div className="font-semibold text-gray-800">{item.title}</div>
                                    <div className="text-sm text-gray-600">{item.subtitle}</div>
                                </div>
                            </div>
                            <Icons.ChevronRight className="w-5 h-5 text-gray-400 transition-transform hover:translate-x-1" />
                        </div>
                    </AnimatedCard>
                ))}
                
                {/* Bouton de déconnexion */}
                <AnimatedCard 
                    className="card hover:shadow-md transition-all duration-300 hover:-translate-y-1 cursor-pointer mt-2" 
                    delay={500 + (menuItems.length * 100) + 100}
                >
                    <div 
                        onClick={() => handleMenuClick('logout')}
                        className="flex items-center justify-between"
                    >
                        <div className="flex items-center space-x-4">
                            <div className="transition-transform hover:scale-110">
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" 
                                     fill="none" stroke="currentColor" strokeWidth="2" 
                                     strokeLinecap="round" strokeLinejoin="round" className="w-6 h-6 text-red-600">
                                    <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
                                    <polyline points="16,17 21,12 16,7"/>
                                    <line x1="21" y1="12" x2="9" y2="12"/>
                                </svg>
                            </div>
                            <div className="text-left">
                                <div className="font-semibold text-red-600">Se déconnecter</div>
                                <div className="text-sm text-gray-600">Fermer votre session</div>
                            </div>
                        </div>
                        <Icons.ChevronRight className="w-5 h-5 text-red-400 transition-transform hover:translate-x-1" />
                    </div>
                </AnimatedCard>

                {(branding?.company_name || branding?.contact_phone || branding?.contact_email) && (
                    <div className="text-center py-6 mt-4 text-xs text-gray-400">
                        {branding.company_name && <div className="font-medium text-gray-500">{branding.company_name}</div>}
                        {branding.company_address && <div className="mt-1">{branding.company_address}</div>}
                        <div className="flex justify-center gap-3 mt-1 flex-wrap">
                            {branding.contact_phone && <a href={`tel:${branding.contact_phone.replace(/\s/g,'')}`} className="text-gray-400">{branding.contact_phone}</a>}
                            {branding.contact_email && <a href={`mailto:${branding.contact_email}`} className="text-gray-400">{branding.contact_email}</a>}
                        </div>
                        <div className="mt-2 text-gray-300">&copy; {new Date().getFullYear()} {branding.display_name}</div>
                    </div>
                )}
            </div>
        </AnimatedView>
    );
};

// Settings View - Vue paramètres
const SettingsView = () => {
    const { navigate } = useAppContext();
    const { t, currentLanguage, changeLanguage, availableLanguages } = useTranslation();
    const [showLanguageModal, setShowLanguageModal] = useState(false);

    const handleLanguageChange = async (langCode) => {
        try {
            await changeLanguage(langCode);
            setShowLanguageModal(false);
            
            // Notification de succès avec refresh des traductions
            setTimeout(() => {
                notifications.success(t('notifications.language_changed'));
            }, 100);
            
            // Force un re-render de toute l'application
            window.dispatchEvent(new Event('languageChanged'));
        } catch (error) {
            console.error('Erreur lors du changement de langue:', error);
            notifications.error('Erreur lors du changement de langue');
        }
    };

    const settingsItems = [
        {
            icon: 'Globe',
            title: t('settings.language_selection'),
            subtitle: t('languages.' + currentLanguage),
            action: () => setShowLanguageModal(true)
        },
        {
            icon: 'Bell',
            title: t('settings.notification_settings'),
            subtitle: t('settings.push_notifications'),
            action: () => console.log('Notifications settings')
        },
        {
            icon: 'Shield',
            title: t('settings.privacy_settings'),
            subtitle: t('settings.data_sharing'),
            action: () => console.log('Privacy settings')
        }
    ];

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in-left">
            <Header title={t('settings.title')} showBackButton={true} backView="compte" />
            
            <div className="px-6 py-4 space-y-3">
                {settingsItems.map((item, index) => (
                    <AnimatedCard 
                        key={index} 
                        className="card hover:shadow-md transition-all duration-300 hover:-translate-y-1 cursor-pointer" 
                        delay={200 + (index * 100)}
                    >
                        <div 
                            onClick={item.action}
                            className="flex items-center justify-between"
                        >
                            <div className="flex items-center space-x-4">
                                <div className="bg-gray-100 p-2 rounded-full transition-transform hover:scale-110">
                                    {React.createElement(Icons[item.icon], {
                                        className: "w-6 h-6 text-gray-600"
                                    })}
                                </div>
                                <div className="text-left">
                                    <div className="font-semibold text-gray-800">{item.title}</div>
                                    <div className="text-sm text-gray-600">{item.subtitle}</div>
                                </div>
                            </div>
                            <Icons.ChevronRight className="w-5 h-5 text-gray-400 transition-transform hover:translate-x-1" />
                        </div>
                    </AnimatedCard>
                ))}
            </div>

            {/* Modal de sélection de langue */}
            {showLanguageModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999]" style={{position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, height: '100vh', width: '100vw'}}>
                    <AnimatedCard className="bg-white rounded-xl p-6 mx-6 w-full max-w-sm scale-in">
                        <div className="text-center mb-4">
                            <h3 className="text-lg font-bold text-gray-800 mb-2">
                                {t('settings.choose_language')}
                            </h3>
                        </div>
                        
                        <div className="space-y-3">
                            {availableLanguages.map((lang) => (
                                <button
                                    key={lang.code}
                                    onClick={() => handleLanguageChange(lang.code)}
                                    className={`w-full flex items-center justify-between p-3 rounded-lg border transition-all ${
                                        currentLanguage === lang.code 
                                            ? 'border-mdriver-orange bg-orange-50 text-mdriver-orange' 
                                            : 'border-gray-200 hover:border-gray-300 text-gray-800'
                                    }`}
                                >
                                    <div className="flex items-center space-x-3">
                                        <Icons.Globe className="w-5 h-5" />
                                        <span className="font-medium">{lang.name}</span>
                                    </div>
                                    {currentLanguage === lang.code && (
                                        <Icons.Check className="w-5 h-5 text-mdriver-orange" />
                                    )}
                                </button>
                            ))}
                        </div>
                        
                        <button
                            onClick={() => setShowLanguageModal(false)}
                            className="w-full mt-4 py-2 px-4 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
                        >
                            {t('common.cancel')}
                        </button>
                    </AnimatedCard>
                </div>
            )}
        </AnimatedView>
    );
};

// Ride Details View - Vue résumé de course
const RideDetailsView = ({ rideData }) => {
    const { t } = useTranslation(); // ✅ Ajouté pour éviter l'erreur "t is not defined"
    const { navigate, notifications } = useAppContext();
    const mapRef = useRef(null);
    const mapInstanceRef = useRef(null);

    useEffect(() => {
        if (mapRef.current && window.L && rideData && !mapInstanceRef.current) {
            const map = L.map(mapRef.current, {
                zoomControl: false,
                attributionControl: false
            }).setView([46.2044, 6.1432], 12);

            L.tileLayer('https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
                attribution: '© Google Maps',
                maxZoom: 20
            }).addTo(map);

            mapInstanceRef.current = map;

            const makeIcon = (color) => L.divIcon({
                html: `<div style="width:20px;height:20px;background:${color};border:2px solid #fff;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.3);"></div>`,
                className: '',
                iconSize: [20, 20],
                iconAnchor: [10, 10]
            });

            if (rideData.pickup_lat && rideData.pickup_lng) {
                L.marker([parseFloat(rideData.pickup_lat), parseFloat(rideData.pickup_lng)], { icon: makeIcon('#4CAF50') }).addTo(map);
            }

            if (rideData.destination_lat && rideData.destination_lng) {
                L.marker([parseFloat(rideData.destination_lat), parseFloat(rideData.destination_lng)], { icon: makeIcon('#f44336') }).addTo(map);

                if (rideData.pickup_lat && rideData.pickup_lng) {
                    const bounds = L.latLngBounds([
                        [parseFloat(rideData.pickup_lat), parseFloat(rideData.pickup_lng)],
                        [parseFloat(rideData.destination_lat), parseFloat(rideData.destination_lng)]
                    ]);
                    map.fitBounds(bounds, { padding: [30, 30] });
                }
            }
        }
    }, [rideData]);

    if (!rideData) {
        return (
            <AnimatedView className="h-full flex flex-col bg-gray-50">
                <Header title={t('activity.ride_details')} showBackButton={true} />
                <div className="flex-1 flex items-center justify-center">
                    <p className="text-gray-600">Aucune course sélectionnée</p>
                </div>
            </AnimatedView>
        );
    }

    const getStatusColor = (status) => {
        switch (status) {
            case 'completed': return 'bg-green-100 text-green-800';
            case 'active': return 'bg-blue-100 text-blue-800';
            case 'cancelled': return 'bg-red-100 text-red-800';
            default: return 'bg-gray-100 text-gray-800';
        }
    };

    const getStatusIcon = (status) => {
        switch (status) {
            case 'completed': return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle'}}><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/></svg>;
            case 'active': return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle'}}><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67V7z"/></svg>;
            case 'cancelled': return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle'}}><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>;
            default: return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle'}}><circle cx="12" cy="12" r="6"/></svg>;
        }
    };

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in">
            <Header title={t('activity.ride_details')} showBackButton={true} backView="activite" />
            
            {/* Map */}
            <div className="h-64 relative">
                <div ref={mapRef} className="w-full h-full"></div>
            </div>

            {/* Détails de la course */}
            <div className="flex-1 px-6 py-4 space-y-4 overflow-y-auto">
                {/* Statut */}
                <AnimatedCard className="card" delay={100}>
                    <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                            <div className={`w-10 h-10 rounded-full flex items-center justify-center ${getStatusColor(rideData.status)}`}>
                                <span className="text-lg">{getStatusIcon(rideData.status)}</span>
                            </div>
                            <div>
                                <div className="font-semibold text-gray-800">Statut</div>
                                <div className="text-sm text-gray-600">{rideData.status_name || rideData.status}</div>
                            </div>
                        </div>
                        <div className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(rideData.status)}`}>
                            {rideData.status_name || rideData.status}
                        </div>
                    </div>
                </AnimatedCard>

                {/* Itinéraire */}
                <AnimatedCard className="card" delay={200}>
                    <h3 className="font-semibold text-gray-800 mb-3 flex items-center">
                        <Icons.MapPin className="w-4 h-4 mr-2 text-gray-500" />
                        Itinéraire
                    </h3>
                    <div className="space-y-3">
                        <div className="flex items-center space-x-3">
                            <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                            <div className="flex-1">
                                <div className="text-xs text-gray-500 mb-1">Origine</div>
                                <div className="text-gray-800 font-medium">{rideData.pickup_address || '-'}</div>
                            </div>
                        </div>
                        <div className="ml-6 w-px h-6 bg-gray-300"></div>
                        <div className="flex items-center space-x-3">
                            <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                            <div className="flex-1">
                                <div className="text-xs text-gray-500 mb-1">Destination</div>
                                <div className="text-gray-800 font-medium">{rideData.dropoff_address || rideData.destination_address || '-'}</div>
                            </div>
                        </div>
                    </div>
                </AnimatedCard>

                {/* Informations de course */}
                <AnimatedCard className="card" delay={300}>
                    <h3 className="font-semibold text-gray-800 mb-3 flex items-center">
                        <Icons.Car className="w-4 h-4 mr-2 text-gray-500" />
                        Informations de course
                    </h3>
                    {(() => {
                        
                        // Formater le prix avec 2 décimales arrondi à 0.50
                        const formatPrice = (price) => {
                            if (!price && price !== 0) return '-';
                            const p = parseFloat(price);
                            const rounded = Math.round(p * 2) / 2;
                            return rounded.toFixed(2);
                        };

                        // Obtenir le prix à afficher
                        const displayPrice = rideData.final_price || rideData.estimated_price || rideData.price || 0;
                        
                        // Obtenir le type de véhicule
                        const vehicleType = rideData.vehicle_type || rideData.fleet_name || rideData.vehicle_name || 'Standard';
                        
                        // Obtenir le job_hash ou ID
                        const jobId = rideData.job_hash || `#${rideData.id}`;

                        return (
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <div className="text-xs text-gray-500 mb-1">Véhicule</div>
                                    <div className="text-gray-800 font-medium flex items-center gap-1">
                                        <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M18.92 6.01C18.72 5.42 18.16 5 17.5 5h-11c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 16c-.83 0-1.5-.67-1.5-1.5S5.67 13 6.5 13s1.5.67 1.5 1.5S7.33 16 6.5 16zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 11l1.5-4.5h11L19 11H5z"/></svg> {vehicleType}
                                    </div>
                                </div>
                                <div>
                                    <div className="text-xs text-gray-500 mb-1">Prix</div>
                                    <div className="text-mdriver-orange font-bold text-lg">{formatPrice(displayPrice)} CHF</div>
                                </div>
                                <div>
                                    <div className="text-xs text-gray-500 mb-1">Date</div>
                                    <div className="text-gray-800 font-medium">{formatDateLocal(rideData.created_at)}</div>
                                </div>
                                <div>
                                    <div className="text-xs text-gray-500 mb-1">Référence</div>
                                    <div className="text-gray-800 font-medium text-sm break-all">{jobId}</div>
                                </div>
                            </div>
                        );
                    })()}
                </AnimatedCard>

                {/* Actions selon le statut */}
                {rideData.status === 'active' && (
                    <AnimatedCard className="card bg-blue-50 border-blue-200" delay={400}>
                        <div className="text-center">
                            <div className="text-blue-800 font-semibold mb-2">Course en cours</div>
                            <div className="text-sm text-blue-600 mb-4">Votre chauffeur arrive bientôt</div>
                            <button className="btn-primary w-full">
                                Contacter le chauffeur
                            </button>
                        </div>
                    </AnimatedCard>
                )}

                {/* Notation du chauffeur (pour courses terminées, dans les 30 jours) */}
                {rideData.status === 'completed' && (
                    <RideRatingSection rideData={rideData} notifications={notifications} />
                )}

                {/* Contacter le support concernant cette course */}
                {(rideData.status === 'completed' || rideData.status === 'cancelled') && (
                    <AnimatedCard className="card" delay={500}>
                        <h3 className="font-semibold text-gray-800 mb-3 flex items-center">
                            <Icons.HelpCircle className="w-4 h-4 mr-2 text-gray-500" />
                            Un problème avec cette course ?
                        </h3>
                        <p className="text-sm text-gray-600 mb-4">
                            Objet oublié, problème avec le chauffeur, question sur la facturation...
                        </p>
                        <button 
                            className="btn-secondary w-full flex items-center justify-center space-x-2"
                            onClick={() => navigate('help', { job_hash: rideData.job_hash, from_ride: true })}
                        >
                            <Icons.MessageSquare className="w-4 h-4" />
                            <span>Contacter le support</span>
                        </button>
                    </AnimatedCard>
                )}
            </div>
        </AnimatedView>
    );
};

// ==================== RIDE RATING SECTION ====================
const RideRatingSection = ({ rideData, notifications }) => {
    const [rating, setRating] = useState(rideData.driver_rating || 0);
    const [hoverRating, setHoverRating] = useState(0);
    const [comment, setComment] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [hasRated, setHasRated] = useState(!!rideData.driver_rating);

    // Vérifier si la course est dans les 30 jours
    const rideDate = new Date(rideData.completed_at || rideData.created_at);
    const daysSinceRide = Math.floor((Date.now() - rideDate.getTime()) / (1000 * 60 * 60 * 24));
    const canRate = daysSinceRide <= 30 && !hasRated;

    const submitRating = async () => {
        if (rating === 0) {
            notifications.error('Veuillez sélectionner une note');
            return;
        }

        setIsSubmitting(true);
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/jobs/${rideData.job_hash}/rate`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ 
                    rating, 
                    comment: comment.trim() || null 
                })
            });

            const result = await response.json();
            if (result.success) {
                setHasRated(true);
                notifications.success('Merci pour votre évaluation !');
            } else {
                notifications.error(result.message || 'Erreur lors de l\'envoi');
            }
        } catch (error) {
            console.error('Error submitting rating:', error);
            notifications.error('Erreur de connexion');
        } finally {
            setIsSubmitting(false);
        }
    };

    // Si déjà noté, afficher la note
    if (hasRated) {
        return (
            <AnimatedCard className="card bg-green-50 border-green-200" delay={400}>
                <div className="text-center">
                    <div className="text-green-800 font-semibold mb-2 flex items-center justify-center gap-1"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/></svg> Course évaluée</div>
                    <div className="flex justify-center space-x-1">
                        {[1, 2, 3, 4, 5].map((star) => (
                            <span key={star} className={star <= rating ? 'text-yellow-400' : 'text-gray-300'}>
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
                            </span>
                        ))}
                    </div>
                </div>
            </AnimatedCard>
        );
    }

    // Si trop vieux pour noter
    if (!canRate && !hasRated) {
        return (
            <AnimatedCard className="card bg-gray-50" delay={400}>
                <div className="text-center text-gray-500 text-sm">
                    La période d'évaluation de 30 jours est expirée
                </div>
            </AnimatedCard>
        );
    }

    return (
        <AnimatedCard className="card" delay={400}>
            <h3 className="font-semibold text-gray-800 mb-3 flex items-center">
                <Icons.Star className="w-4 h-4 mr-2 text-yellow-500" />
                Évaluez votre course
            </h3>
            
            {/* Étoiles */}
            <div className="flex justify-center space-x-2 mb-4">
                {[1, 2, 3, 4, 5].map((star) => (
                    <button 
                        key={star}
                        className={`transition-transform hover:scale-110 ${
                            star <= (hoverRating || rating) ? 'text-yellow-400' : 'text-gray-300'
                        }`}
                        onMouseEnter={() => setHoverRating(star)}
                        onMouseLeave={() => setHoverRating(0)}
                        onClick={() => setRating(star)}
                    >
                        <svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
                    </button>
                ))}
            </div>

            {/* Commentaire optionnel */}
            <textarea
                className="input-field w-full mb-4"
                placeholder="Ajouter un commentaire (optionnel)"
                rows={2}
                value={comment}
                onChange={(e) => setComment(e.target.value)}
            />

            <button 
                className="btn-primary w-full"
                onClick={submitRating}
                disabled={isSubmitting || rating === 0}
            >
                {isSubmitting ? 'Envoi...' : 'Envoyer l\'évaluation'}
            </button>
        </AnimatedCard>
    );
};

// Payment Methods View - Vue méthodes de paiement (Worldline integration) - OPTIMISÉ
const PaymentMethodsView = () => {
    const { user, notifications, navigate } = useAppContext();
    const { t } = useTranslation();
    const [cards, setCards] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showAddCardModal, setShowAddCardModal] = useState(false);
    const [addingCard, setAddingCard] = useState(false);
    const [deletingCardId, setDeletingCardId] = useState(null);
    const [settingDefaultId, setSettingDefaultId] = useState(null);
    
    // États du formulaire d'ajout de carte
    const [cardNumber, setCardNumber] = useState('');
    const [expiryMonth, setExpiryMonth] = useState('');
    const [expiryYear, setExpiryYear] = useState('');
    const [holderName, setHolderName] = useState('');
    const [cvv, setCvv] = useState('');
    
    // Récupérer le token d'authentification
    const authToken = localStorage.getItem('user_token');

    // Icônes SVG des cartes bancaires
    const CardBrandIcon = ({ brand, className = "w-10 h-6" }) => {
        const brandLower = brand?.toLowerCase() || '';
        
        if (brandLower === 'visa') {
            return (
                <svg className={className} viewBox="0 0 48 32" fill="none">
                    <rect width="48" height="32" rx="4" fill="#1A1F71"/>
                    <path d="M19.5 21H17L18.8 11H21.3L19.5 21ZM15.3 11L13 18L12.7 16.7L11.8 12.2C11.8 12.2 11.7 11 10.1 11H6L6 11.2C6 11.2 7.8 11.6 9.9 12.9L12 21H14.6L18 11H15.3ZM34 21H36.3L34.3 11H32.2C30.9 11 30.5 12 30.5 12L26.7 21H29.3L29.8 19.5H33L33.4 21H34ZM30.5 17.5L32 13.5L32.8 17.5H30.5ZM28 14.1L28.4 11.5C28.4 11.5 26.7 11 24.9 11C22.9 11 18.9 11.9 18.9 15.5C18.9 18.8 23.4 18.9 23.4 20.5C23.4 22.1 19.4 21.6 17.8 20.4L17.4 23.2C17.4 23.2 19.1 24 21.6 24C24.1 24 28.1 22.5 28.1 19.2C28.1 15.8 23.5 15.5 23.5 14.2C23.5 12.9 26.6 13.1 28 14.1Z" fill="white"/>
                </svg>
            );
        }
        
        if (brandLower === 'mastercard') {
            return (
                <svg className={className} viewBox="0 0 48 32" fill="none">
                    <rect width="48" height="32" rx="4" fill="#000"/>
                    <circle cx="18" cy="16" r="9" fill="#EB001B"/>
                    <circle cx="30" cy="16" r="9" fill="#F79E1B"/>
                    <path d="M24 22.5C25.8 21 27 18.6 27 16C27 13.4 25.8 11 24 9.5C22.2 11 21 13.4 21 16C21 18.6 22.2 21 24 22.5Z" fill="#FF5F00"/>
                </svg>
            );
        }
        
        if (brandLower === 'amex' || brandLower === 'american express') {
            return (
                <svg className={className} viewBox="0 0 48 32" fill="none">
                    <rect width="48" height="32" rx="4" fill="#006FCF"/>
                    <path d="M6 20H8L8.5 18.5H10.5L11 20H16V18.5L16.5 20H19.5L20 18.5V20H34V18L34.5 18.5H37.5V20H42V12H37.5L37 13.5V12H33.5L33 13.5L32.5 12H20V13.5L19.5 12H16.5L16 13.5V12H11L10 14.5L9 12H6V20ZM17 18.5H15.5V14.5L13.5 18.5H12.5L10.5 14.5V18.5H7.5L7 17H5L4.5 18.5H3V13.5H5.5L7.5 17.5L9.5 13.5H12V17.5L14 13.5H17V18.5Z" fill="white"/>
                </svg>
            );
        }
        
        // Carte générique
        return (
            <svg className={className} viewBox="0 0 48 32" fill="none">
                <rect width="48" height="32" rx="4" fill="#6B7280"/>
                <rect x="6" y="10" width="10" height="7" rx="1" fill="#FCD34D"/>
                <rect x="6" y="21" width="16" height="2" rx="1" fill="white" opacity="0.6"/>
                <rect x="26" y="21" width="8" height="2" rx="1" fill="white" opacity="0.6"/>
            </svg>
        );
    };

    useEffect(() => {
        loadCards();
    }, []);

    const loadCards = async () => {
        setLoading(true);
        try {
            const response = await fetch(`${API_CONFIG.BASE_URL}/payments/cards`, {
                headers: { 
                    'Authorization': `Bearer ${authToken}`,
                    'Content-Type': 'application/json'
                }
            });
            const data = await response.json();
            
            if (data.success && data.data?.cards) {
                setCards(data.data.cards.map(card => ({
                    id: card.id,
                    card_brand: card.card_brand,
                    card_digits: card.card_last4,
                    card_expiry_month: card.card_expiry_month,
                    card_expiry_year: card.card_expiry_year,
                    card_holder_name: card.card_holder_name,
                    is_default: card.is_default ? '1' : '0'
                })));
            } else {
                setCards([]);
            }
        } catch (error) {
            console.error('Erreur chargement cartes:', error);
            setCards([]);
        } finally {
            setLoading(false);
        }
    };

    const setDefaultCard = async (cardId) => {
        setSettingDefaultId(cardId);
        try {
            const response = await fetch(`${API_CONFIG.BASE_URL}/payments/cards/${cardId}/default`, {
                method: 'PUT',
                headers: { 
                    'Authorization': `Bearer ${authToken}`,
                    'Content-Type': 'application/json'
                }
            });
            const data = await response.json();
            if (data.success) {
                notifications.success('Carte définie par défaut');
                await loadCards();
            } else {
                notifications.error('Erreur lors de la mise à jour');
            }
        } catch (error) {
            notifications.error('Une erreur est survenue');
        } finally {
            setSettingDefaultId(null);
        }
    };

    const deleteCard = async (cardId) => {
        if (!confirm('Supprimer cette carte ?')) return;
        setDeletingCardId(cardId);
        try {
            const response = await fetch(`${API_CONFIG.BASE_URL}/payments/cards/${cardId}`, {
                method: 'DELETE',
                headers: { 
                    'Authorization': `Bearer ${authToken}`,
                    'Content-Type': 'application/json'
                }
            });
            const data = await response.json();
            if (data.success) {
                notifications.success('Carte supprimée');
                await loadCards();
            } else {
                notifications.error('Erreur lors de la suppression');
            }
        } catch (error) {
            notifications.error('Une erreur est survenue');
        } finally {
            setDeletingCardId(null);
        }
    };

    const openAddCardModal = () => {
        setCardNumber('');
        setExpiryMonth('');
        setExpiryYear('');
        setHolderName('');
        setCvv('');
        setShowAddCardModal(true);
    };

    const formatCardNumber = (value) => {
        const numbers = value.replace(/\D/g, '').substring(0, 16);
        return numbers.replace(/(\d{4})(?=\d)/g, '$1 ');
    };
    
    const detectCardBrand = (number) => {
        const n = number.replace(/\D/g, '');
        if (/^4/.test(n)) return 'VISA';
        if (/^5[1-5]/.test(n) || /^2[2-7]/.test(n)) return 'MASTERCARD';
        if (/^3[47]/.test(n)) return 'AMEX';
        return '';
    };

    const handleCardSubmit = async () => {
        if (!cardNumber || !expiryMonth || !expiryYear || !holderName) {
            notifications.error('Veuillez remplir tous les champs obligatoires');
            return;
        }
        
        const cleanNumber = cardNumber.replace(/\D/g, '');
        if (cleanNumber.length < 13) {
            notifications.error('Numéro de carte invalide');
            return;
        }

        setAddingCard(true);
        try {
            const response = await fetch(`${API_CONFIG.BASE_URL}/payments/cards`, {
                method: 'POST',
                headers: { 
                    'Authorization': `Bearer ${authToken}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    card_token: `WL-${Date.now()}-${cleanNumber.slice(-4)}`,
                    card_brand: detectCardBrand(cleanNumber) || 'VISA',
                    card_last4: cleanNumber.slice(-4),
                    card_expiry_month: parseInt(expiryMonth),
                    card_expiry_year: parseInt(expiryYear),
                    card_holder_name: holderName
                })
            });
            
            const data = await response.json();
            if (data.success) {
                notifications.success('Carte ajoutée avec succès !');
                setShowAddCardModal(false);
                await loadCards();
            } else {
                notifications.error(data.error || 'Erreur lors de l\'ajout');
            }
        } catch (error) {
            notifications.error('Erreur de connexion');
        } finally {
            setAddingCard(false);
        }
    };

    const defaultCard = cards.find(card => card.is_default === '1');
    const otherCards = cards.filter(card => card.is_default !== '1');
    const currentYear = new Date().getFullYear();

    return (
        <AnimatedView className="h-full flex flex-col bg-gradient-to-b from-gray-50 to-gray-100" animationType="fade-in-left">
            <Header title={t('account.payment_methods')} showBackButton={true} backView="compte" />
            
            <div className="flex-1 overflow-y-auto">
                <div className="p-5 space-y-5">
                    
                    {/* Section Carte par défaut */}
                    <AnimatedCard delay={100}>
                        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                            <div className="p-5">
                                <div className="flex items-center justify-between mb-4">
                                    <h3 className="font-semibold text-gray-900">Carte principale</h3>
                                    {defaultCard && (
                                        <span className="flex items-center text-xs font-medium text-green-700 bg-green-50 px-2.5 py-1 rounded-full">
                                            <Icons.Check className="w-3.5 h-3.5 mr-1" />
                                            Active
                                        </span>
                                    )}
                                </div>
                                
                                {loading ? (
                                    <div className="flex flex-col items-center justify-center py-10">
                                        <div className="animate-spin rounded-full h-10 w-10 border-3 border-mdriver-orange border-t-transparent mb-3"></div>
                                        <span className="text-sm text-gray-500">Chargement...</span>
                                    </div>
                                ) : defaultCard ? (
                                    <div className="relative">
                                        {/* Carte visuelle */}
                                        <div className="bg-gradient-to-br from-gray-800 via-gray-900 to-black rounded-xl p-5 text-white shadow-lg">
                                            <div className="flex justify-between items-start mb-8">
                                                <CardBrandIcon brand={defaultCard.card_brand} className="w-14 h-9" />
                                                <Icons.CreditCard className="w-6 h-6 opacity-50" />
                                            </div>
                                            <div className="font-mono text-xl tracking-wider mb-4">
                                                •••• •••• •••• {defaultCard.card_digits}
                                            </div>
                                            <div className="flex justify-between items-end">
                                                <div>
                                                    <div className="text-[10px] text-gray-400 uppercase tracking-wide mb-0.5">Titulaire</div>
                                                    <div className="text-sm font-medium truncate max-w-[160px]">
                                                        {defaultCard.card_holder_name || 'NON RENSEIGNÉ'}
                                                    </div>
                                                </div>
                                                <div className="text-right">
                                                    <div className="text-[10px] text-gray-400 uppercase tracking-wide mb-0.5">Expire</div>
                                                    <div className="text-sm font-medium">
                                                        {String(defaultCard.card_expiry_month).padStart(2, '0')}/{String(defaultCard.card_expiry_year).slice(-2)}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                ) : (
                                    <div className="text-center py-8">
                                        <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
                                            <Icons.CreditCard className="w-8 h-8 text-gray-400" />
                                        </div>
                                        <p className="text-gray-600 mb-1 font-medium">Aucune carte enregistrée</p>
                                        <p className="text-sm text-gray-400 mb-5">Ajoutez une carte pour payer vos courses</p>
                                        <button
                                            onClick={openAddCardModal}
                                            className="inline-flex items-center px-5 py-3 bg-mdriver-orange text-white rounded-xl font-medium shadow-md hover:shadow-lg transition-all hover:scale-[1.02] active:scale-[0.98]"
                                        >
                                            <Icons.Plus className="w-5 h-5 mr-2" />
                                            Ajouter une carte
                                        </button>
                                    </div>
                                )}
                            </div>
                        </div>
                    </AnimatedCard>

                    {/* Autres cartes */}
                    {otherCards.length > 0 && (
                        <AnimatedCard delay={150}>
                            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
                                <div className="p-5">
                                    <h3 className="font-semibold text-gray-900 mb-4">Autres cartes</h3>
                                    <div className="space-y-3">
                                        {otherCards.map((card) => (
                                            <div key={card.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-xl hover:bg-gray-100 transition-colors">
                                                <div className="flex items-center space-x-4">
                                                    <CardBrandIcon brand={card.card_brand} className="w-12 h-8" />
                                                    <div>
                                                        <div className="font-medium text-gray-900">•••• {card.card_digits}</div>
                                                        <div className="text-xs text-gray-500">
                                                            Expire {String(card.card_expiry_month).padStart(2, '0')}/{String(card.card_expiry_year).slice(-2)}
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="flex items-center space-x-2">
                                                    <button
                                                        onClick={() => setDefaultCard(card.id)}
                                                        disabled={settingDefaultId === card.id}
                                                        className="p-2 text-mdriver-orange hover:bg-orange-50 rounded-lg transition-colors disabled:opacity-50"
                                                        title="Définir par défaut"
                                                    >
                                                        {settingDefaultId === card.id ? (
                                                            <div className="animate-spin rounded-full h-5 w-5 border-2 border-mdriver-orange border-t-transparent"></div>
                                                        ) : (
                                                            <Icons.Star className="w-5 h-5" />
                                                        )}
                                                    </button>
                                                    <button
                                                        onClick={() => deleteCard(card.id)}
                                                        disabled={deletingCardId === card.id}
                                                        className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-50"
                                                        title="Supprimer"
                                                    >
                                                        {deletingCardId === card.id ? (
                                                            <div className="animate-spin rounded-full h-5 w-5 border-2 border-red-500 border-t-transparent"></div>
                                                        ) : (
                                                            <Icons.Trash className="w-5 h-5" />
                                                        )}
                                                    </button>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </AnimatedCard>
                    )}

                    {/* Bouton ajouter une carte (si une carte existe déjà) */}
                    {cards.length > 0 && (
                        <AnimatedCard delay={200}>
                            <button
                                onClick={openAddCardModal}
                                className="w-full p-4 bg-white border-2 border-dashed border-gray-200 rounded-2xl hover:border-mdriver-orange hover:bg-orange-50/30 transition-all flex items-center justify-center space-x-2 text-gray-600 hover:text-mdriver-orange"
                            >
                                <Icons.Plus className="w-5 h-5" />
                                <span className="font-medium">Ajouter une autre carte</span>
                            </button>
                        </AnimatedCard>
                    )}

                    {/* Section sécurité */}
                    <AnimatedCard delay={250}>
                        <div className="bg-gradient-to-r from-green-50 to-emerald-50 rounded-2xl p-5 border border-green-100">
                            <div className="flex items-start space-x-4">
                                <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0">
                                    <Icons.Shield className="w-5 h-5 text-green-600" />
                                </div>
                                <div>
                                    <h4 className="font-semibold text-green-900 mb-1">Paiements sécurisés</h4>
                                    <p className="text-sm text-green-700 leading-relaxed">
                                        Vos données bancaires sont protégées par Worldline, leader européen des services de paiement. 
                                        Nous ne stockons jamais vos informations de carte complètes.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </AnimatedCard>
                </div>
            </div>

            {/* Modal d'ajout de carte */}
            {showAddCardModal && (
                <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/60 backdrop-blur-sm" onClick={() => !addingCard && setShowAddCardModal(false)}>
                    <div 
                        className="bg-white w-full sm:max-w-md sm:rounded-2xl rounded-t-3xl max-h-[90vh] overflow-hidden shadow-2xl animate-slide-up"
                        onClick={e => e.stopPropagation()}
                    >
                        {/* Header */}
                        <div className="p-5 border-b border-gray-100">
                            <div className="flex items-center justify-between">
                                <div>
                                    <h3 className="text-lg font-bold text-gray-900">Ajouter une carte</h3>
                                    <p className="text-sm text-gray-500">Entrez les informations de votre carte</p>
                                </div>
                                <button 
                                    onClick={() => setShowAddCardModal(false)}
                                    className="p-2 hover:bg-gray-100 rounded-full transition-colors"
                                    disabled={addingCard}
                                >
                                    <Icons.X className="w-5 h-5 text-gray-500" />
                                </button>
                            </div>
                        </div>
                        
                        {/* Formulaire */}
                        <div className="p-5 space-y-5 overflow-y-auto max-h-[60vh]">
                            {/* Numéro de carte */}
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Numéro de carte
                                </label>
                                <div className="relative">
                                    <input
                                        type="text"
                                        inputMode="numeric"
                                        value={cardNumber}
                                        onChange={(e) => setCardNumber(formatCardNumber(e.target.value))}
                                        placeholder="1234 5678 9012 3456"
                                        className="w-full px-4 py-3.5 pr-16 border border-gray-200 rounded-xl focus:border-mdriver-orange focus:ring-2 focus:ring-mdriver-orange/20 transition-all text-lg tracking-wide"
                                        maxLength={19}
                                    />
                                    <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                                        {cardNumber.replace(/\D/g, '').length >= 4 ? (
                                            <CardBrandIcon brand={detectCardBrand(cardNumber)} className="w-10 h-6" />
                                        ) : (
                                            <Icons.CreditCard className="w-6 h-6 text-gray-300" />
                                        )}
                                    </div>
                                </div>
                            </div>
                            
                            {/* Nom du titulaire */}
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Nom sur la carte
                                </label>
                                <input
                                    type="text"
                                    value={holderName}
                                    onChange={(e) => setHolderName(e.target.value.toUpperCase())}
                                    placeholder="JEAN DUPONT"
                                    className="w-full px-4 py-3.5 border border-gray-200 rounded-xl focus:border-mdriver-orange focus:ring-2 focus:ring-mdriver-orange/20 transition-all uppercase tracking-wide"
                                />
                            </div>
                            
                            {/* Date d'expiration et CVV */}
                            <div className="grid grid-cols-3 gap-3">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">Mois</label>
                                    <select
                                        value={expiryMonth}
                                        onChange={(e) => setExpiryMonth(e.target.value)}
                                        className="w-full px-3 py-3.5 border border-gray-200 rounded-xl focus:border-mdriver-orange focus:ring-2 focus:ring-mdriver-orange/20 transition-all bg-white"
                                    >
                                        <option value="">MM</option>
                                        {[...Array(12)].map((_, i) => (
                                            <option key={i+1} value={String(i+1).padStart(2, '0')}>
                                                {String(i+1).padStart(2, '0')}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">Année</label>
                                    <select
                                        value={expiryYear}
                                        onChange={(e) => setExpiryYear(e.target.value)}
                                        className="w-full px-3 py-3.5 border border-gray-200 rounded-xl focus:border-mdriver-orange focus:ring-2 focus:ring-mdriver-orange/20 transition-all bg-white"
                                    >
                                        <option value="">AA</option>
                                        {[...Array(12)].map((_, i) => (
                                            <option key={i} value={String(currentYear + i)}>
                                                {currentYear + i}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">CVV</label>
                                    <input
                                        type="password"
                                        inputMode="numeric"
                                        value={cvv}
                                        onChange={(e) => setCvv(e.target.value.replace(/\D/g, '').substring(0, 4))}
                                        placeholder="•••"
                                        className="w-full px-3 py-3.5 border border-gray-200 rounded-xl focus:border-mdriver-orange focus:ring-2 focus:ring-mdriver-orange/20 transition-all text-center tracking-widest"
                                        maxLength={4}
                                    />
                                </div>
                            </div>
                            
                            {/* Note sécurité */}
                            <div className="flex items-center space-x-3 p-3 bg-green-50 rounded-xl">
                                <Icons.Lock className="w-5 h-5 text-green-600 flex-shrink-0" />
                                <span className="text-sm text-green-700">
                                    Connexion sécurisée SSL - Worldline
                                </span>
                            </div>
                        </div>
                        
                        {/* Footer */}
                        <div className="p-5 border-t border-gray-100 bg-gray-50/50">
                            <div className="flex space-x-3">
                                <button
                                    onClick={() => setShowAddCardModal(false)}
                                    className="flex-1 py-3.5 border border-gray-200 rounded-xl text-gray-700 font-medium hover:bg-gray-100 transition-colors"
                                    disabled={addingCard}
                                >
                                    Annuler
                                </button>
                                <button
                                    onClick={handleCardSubmit}
                                    disabled={addingCard || !cardNumber || !holderName || !expiryMonth || !expiryYear}
                                    className="flex-1 py-3.5 bg-mdriver-orange text-white rounded-xl font-medium disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center hover:bg-orange-600 transition-colors"
                                >
                                    {addingCard ? (
                                        <>
                                            <div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent mr-2"></div>
                                            Ajout...
                                        </>
                                    ) : (
                                        <>
                                            <Icons.Plus className="w-5 h-5 mr-2" />
                                            Ajouter
                                        </>
                                    )}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </AnimatedView>
    );
};

// Email Settings View - Vue paramètres email
const EmailSettingsView = () => {
    const { user, notifications, navigate } = useAppContext();
    const [currentEmail, setCurrentEmail] = useState(user?.email || '');
    const [newEmail, setNewEmail] = useState('');
    const [showChangeEmail, setShowChangeEmail] = useState(false);
    const [loading, setLoading] = useState(false);

    const handleUpdateEmail = async () => {
        if (!newEmail || !newEmail.includes('@')) {
            notifications.error('Veuillez saisir un email valide');
            return;
        }

        if (newEmail === currentEmail) {
            notifications.info('Ce email est déjà configuré');
            return;
        }

        setLoading(true);
        try {
            // Récupérer le token d'authentification
            const token = localStorage.getItem('user_token');
            
            const response = await fetch(`${API_BASE_URL}/users/update_profile`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                },
                body: JSON.stringify({
                    user_uid: user.userUid,
                    email: newEmail  // Changer new_email en email pour correspondre à l'API
                })
            });

            const data = await response.json();
            
            if (data.success) {
                notifications.success('Email mis à jour avec succès');
                setCurrentEmail(newEmail);
                setNewEmail('');
                setShowChangeEmail(false);
                // Mettre à jour les données utilisateur
                // Note: Il faudrait idéalement recharger les données utilisateur
            } else {
                notifications.error(data.message || 'Erreur lors de la mise à jour');
            }
        } catch (error) {
            console.error('Erreur:', error);
            notifications.error('Erreur de connexion');
        } finally {
            setLoading(false);
        }
    };

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in-left">
            <Header title="Email" showBackButton={true} backView="compte" />
            
            <div className="flex-1 p-6 space-y-6">
                {/* Email actuel */}
                <AnimatedCard className="card" delay={100}>
                    <h3 className="font-bold text-lg mb-4 text-gray-800">Email actuel</h3>
                    
                    <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                            <Icons.Mail className="w-6 h-6 text-gray-500" />
                            <div>
                                {currentEmail ? (
                                    <>
                                        <div className="font-medium">{currentEmail}</div>
                                        <div className="text-sm text-gray-600">Email vérifié</div>
                                    </>
                                ) : (
                                    <div className="text-gray-500">Aucun email configuré</div>
                                )}
                            </div>
                        </div>
                        <button
                            onClick={() => setShowChangeEmail(!showChangeEmail)}
                            className="text-mdriver-orange font-medium"
                        >
                            {currentEmail ? 'Modifier' : 'Ajouter'}
                        </button>
                    </div>
                </AnimatedCard>

                {/* Formulaire de changement d'email */}
                {showChangeEmail && (
                    <AnimatedCard className="card" delay={200}>
                        <h3 className="font-bold text-lg mb-4 text-gray-800">
                            {currentEmail ? 'Changer d\'email' : 'Ajouter un email'}
                        </h3>
                        
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Nouvel email
                                </label>
                                <input
                                    type="email"
                                    value={newEmail}
                                    onChange={(e) => setNewEmail(e.target.value)}
                                    placeholder="exemple@domain.com"
                                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-mdriver-orange focus:border-transparent"
                                    disabled={loading}
                                />
                            </div>
                            
                            <div className="flex space-x-3">
                                <button
                                    onClick={() => {
                                        setShowChangeEmail(false);
                                        setNewEmail('');
                                    }}
                                    className="flex-1 py-3 border border-gray-300 rounded-xl font-medium text-gray-700 hover:bg-gray-50"
                                    disabled={loading}
                                >
                                    Annuler
                                </button>
                                <button
                                    onClick={handleUpdateEmail}
                                    disabled={loading || !newEmail}
                                    className="flex-1 py-3 bg-mdriver-orange text-white rounded-xl font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:bg-orange-600"
                                >
                                    {loading ? (
                                        <div className="flex items-center justify-center">
                                            <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                                            Mise à jour...
                                        </div>
                                    ) : (
                                        'Confirmer'
                                    )}
                                </button>
                            </div>
                        </div>
                    </AnimatedCard>
                )}

                {/* Informations */}
                <AnimatedCard className="card" delay={300}>
                    <div className="flex items-start space-x-3">
                        <Icons.Info className="w-5 h-5 text-blue-500 mt-1" />
                        <div className="text-sm text-gray-600">
                            <p className="font-medium mb-1">À propos de votre email</p>
                            <ul className="space-y-1 text-xs">
                                <li>• Utilisé pour les notifications importantes</li>
                                <li>• Confirmations de course et reçus</li>
                                <li>• Récupération de compte en cas d'oubli</li>
                            </ul>
                        </div>
                    </div>
                </AnimatedCard>
            </div>
        </AnimatedView>
    );
};

// Phone Settings View - Vue paramètres téléphone
const PhoneSettingsView = () => {
    const { t } = useTranslation();
    const { user, notifications, navigate, setUser } = useAppContext();
    
    // Fonction pour extraire le préfixe et le numéro du téléphone complet
    const extractPhoneInfo = (fullPhone) => {
        if (!fullPhone) return ['+41', ''];
        
        if (fullPhone.startsWith('+41')) {
            return ['+41', fullPhone.substring(3)];
        } else if (fullPhone.startsWith('+33')) {
            return ['+33', fullPhone.substring(3)];
        } else if (fullPhone.startsWith('+32')) {
            return ['+32', fullPhone.substring(3)];
        } else if (fullPhone.startsWith('+352')) {
            return ['+352', fullPhone.substring(4)];
        } else if (fullPhone.startsWith('+1')) {
            return ['+1', fullPhone.substring(2)];
        } else if (fullPhone.startsWith('+44')) {
            return ['+44', fullPhone.substring(3)];
        } else if (fullPhone.startsWith('+49')) {
            return ['+49', fullPhone.substring(3)];
        } else if (fullPhone.startsWith('+39')) {
            return ['+39', fullPhone.substring(3)];
        } else if (fullPhone.startsWith('+34')) {
            return ['+34', fullPhone.substring(3)];
        }
        return ['+41', fullPhone]; // Défaut Suisse
    };
    
    const [currentPrefix, currentPhone] = extractPhoneInfo(user?.phone);
    const [newPhone, setNewPhone] = useState('');
    const [newPrefix, setNewPrefix] = useState('+41'); // Défaut Suisse
    const [showChangePhone, setShowChangePhone] = useState(false);
    const [showVerification, setShowVerification] = useState(false);
    const [verificationCode, setVerificationCode] = useState(['', '', '', '']); // 4 chiffres
    const [loading, setLoading] = useState(false);
    const [countdown, setCountdown] = useState(0);

    // Refs pour les focus automatiques
    const phoneInputRef = useRef(null);
    const firstCodeInputRef = useRef(null);

    // Timer pour le countdown
    useEffect(() => {
        if (countdown > 0) {
            const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
            return () => clearTimeout(timer);
        }
    }, [countdown]);

    // Effect pour focus automatique sur le champ téléphone quand on ouvre le formulaire
    useEffect(() => {
        if (showChangePhone && !showVerification && phoneInputRef.current) {
            setTimeout(() => {
                phoneInputRef.current.focus();
            }, 100); // Petit délai pour s'assurer que l'élément est rendu
        }
    }, [showChangePhone, showVerification]);

    // Effect pour focus automatique sur le premier input de code
    useEffect(() => {
        if (showVerification && firstCodeInputRef.current) {
            setTimeout(() => {
                firstCodeInputRef.current.focus();
            }, 100);
        }
    }, [showVerification]);

    // Effect pour validation automatique quand les 4 chiffres sont saisis
    useEffect(() => {
        const code = verificationCode.join('');
        if (code.length === 4 && showVerification && !loading) {
            verifyAndUpdatePhone();
        }
    }, [verificationCode, showVerification, loading]);

    const sendVerificationCode = async () => {
        if (!newPhone || newPhone.length < 8) {
            notifications.error('Veuillez saisir un numéro valide');
            return;
        }

        setLoading(true);
        
        // Effacer les champs de code lors du renvoi
        setVerificationCode(['', '', '', '']);
        
        try {
            const fullNumber = newPrefix + newPhone;
            const result = await apiService.sendPhoneUpdateCode(fullNumber, 'update_phone');
            
            if (result.success) {
                notifications.success('Code de vérification envoyé par SMS');
                setShowVerification(true);
                setCountdown(60);
            } else {
                notifications.error(result.message || 'Erreur lors de l\'envoi du code');
            }
        } catch (error) {
            console.error('Erreur:', error);
            notifications.error('Erreur de connexion');
        } finally {
            setLoading(false);
        }
    };

    const verifyAndUpdatePhone = async () => {
        const code = verificationCode.join('');
        if (code.length !== 4) {
            notifications.error('Veuillez saisir le code complet (4 chiffres)');
            return;
        }

        setLoading(true);
        try {
            const fullNumber = newPrefix + newPhone;
            
            // Vérification locale du code de mise à jour
            const storedCode = localStorage.getItem(`update_phone_code_${fullNumber}`);
            const codeTime = localStorage.getItem(`update_phone_code_time_${fullNumber}`);
            
            if (!storedCode || !codeTime) {
                notifications.error('Code de vérification non trouvé. Veuillez en demander un nouveau.');
                return;
            }
            
            // Vérifier l'expiration du code (5 minutes)
            const currentTime = Date.now();
            const codeAge = currentTime - parseInt(codeTime);
            const FIVE_MINUTES = 5 * 60 * 1000;
            
            if (codeAge > FIVE_MINUTES) {
                localStorage.removeItem(`update_phone_code_${fullNumber}`);
                localStorage.removeItem(`update_phone_code_time_${fullNumber}`);
                notifications.error('Le code de vérification a expiré. Veuillez en demander un nouveau.');
                return;
            }
            
            // Vérifier le code
            if (storedCode === code) {
                // Nettoyer le code utilisé
                localStorage.removeItem(`update_phone_code_${fullNumber}`);
                localStorage.removeItem(`update_phone_code_time_${fullNumber}`);
                
                // Mettre à jour les informations localement (en production, envoyer à votre API backend)
                notifications.success('Numéro de téléphone mis à jour avec succès');
                setNewPhone('');
                setVerificationCode(['', '', '', '']);
                setShowChangePhone(false);
                setShowVerification(false);
                
                // Mettre à jour les données utilisateur dans le contexte
                setUser(prev => ({
                    ...prev,
                    phone: fullNumber
                }));
            } else {
                notifications.error('Code de vérification incorrect');
            }
        } catch (error) {
            console.error('Erreur:', error);
            notifications.error('Erreur de connexion');
        } finally {
            setLoading(false);
        }
    };

    // Gestion des inputs de code séparés
    const handleCodeInput = (index, value) => {
        const newCode = [...verificationCode];
        newCode[index] = value;
        setVerificationCode(newCode);
        
        // Auto-focus next input
        if (value && index < 3) {
            const nextInput = document.querySelector(`.code-digit:nth-child(${index + 2})`);
            nextInput?.focus();
        }
    };

    const countryPrefixes = [
        { code: '+41', name: 'CH Suisse' },
        { code: '+33', name: 'FR France' },
        { code: '+32', name: 'BE Belgique' },
        { code: '+352', name: 'LU Luxembourg' },
        { code: '+49', name: 'DE Allemagne' },
        { code: '+39', name: 'IT Italie' },
        { code: '+34', name: 'ES Espagne' },
        { code: '+44', name: 'GB UK' },
        { code: '+1', name: 'US USA/Canada' }
    ];

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in-left">
            <Header title={t('account.phone') || 'Téléphone'} showBackButton={true} backView="compte" />
            
            <div className="flex-1 p-6 space-y-6">
                {/* Numéro actuel */}
                <AnimatedCard className="card" delay={100}>
                    <h3 className="font-bold text-lg mb-4 text-gray-800">Numéro actuel</h3>
                    
                    <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                            <Icons.Smartphone className="w-6 h-6 text-gray-500" />
                            <div>
                                <div className="font-medium">{currentPrefix} {currentPhone}</div>
                                <div className="text-sm text-gray-600">Numéro vérifié</div>
                            </div>
                        </div>
                        <button
                            onClick={() => setShowChangePhone(!showChangePhone)}
                            className="text-mdriver-orange font-medium"
                        >
                            Modifier
                        </button>
                    </div>
                </AnimatedCard>

                {/* Formulaire de changement */}
                {showChangePhone && !showVerification && (
                    <AnimatedCard className="card" delay={200}>
                        <h3 className="font-bold text-lg mb-4 text-gray-800">Nouveau numéro</h3>
                        
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Pays
                                </label>
                                <select
                                    value={newPrefix}
                                    onChange={(e) => setNewPrefix(e.target.value)}
                                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-mdriver-orange focus:border-transparent"
                                    disabled={loading}
                                >
                                    {countryPrefixes.map((country) => (
                                        <option key={country.code} value={country.code}>
                                            {country.name} ({country.code})
                                        </option>
                                    ))}
                                </select>
                            </div>
                            
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Numéro de téléphone
                                </label>
                                <input
                                    ref={phoneInputRef}
                                    type="tel"
                                    value={newPhone}
                                    onChange={(e) => setNewPhone(e.target.value)}
                                    placeholder="Numéro de téléphone"
                                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-mdriver-orange focus:border-transparent"
                                    disabled={loading}
                                />
                            </div>
                            
                            <div className="flex space-x-3">
                                <button
                                    onClick={() => {
                                        setShowChangePhone(false);
                                        setNewPhone('');
                                    }}
                                    className="flex-1 py-3 border border-gray-300 rounded-xl font-medium text-gray-700 hover:bg-gray-50"
                                    disabled={loading}
                                >
                                    Annuler
                                </button>
                                <button
                                    onClick={sendVerificationCode}
                                    disabled={loading || !newPhone}
                                    className="flex-1 py-3 bg-mdriver-orange text-white rounded-xl font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:bg-orange-600"
                                >
                                    {loading ? (
                                        <div className="flex items-center justify-center">
                                            <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                                            Envoi...
                                        </div>
                                    ) : (
                                        'Envoyer le code'
                                    )}
                                </button>
                            </div>
                        </div>
                    </AnimatedCard>
                )}

                {/* Vérification du code */}
                {showVerification && (
                    <AnimatedCard className="card" delay={200}>
                        <h3 className="font-bold text-lg mb-4 text-gray-800">Vérification</h3>
                        
                        <div className="text-center mb-6">
                            <Icons.Smartphone className="w-12 h-12 mx-auto mb-3 text-mdriver-orange" />
                            <p className="text-gray-600 mb-2">Code envoyé au numéro :</p>
                            <p className="font-bold text-lg">{newPrefix} {newPhone}</p>
                        </div>
                        
                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Code de vérification (4 chiffres)
                                </label>
                                <div className="code-inputs">
                                    {verificationCode.map((digit, index) => (
                                        <input
                                            key={index}
                                            ref={index === 0 ? firstCodeInputRef : null}
                                            type="text"
                                            maxLength="1"
                                            value={digit}
                                            onChange={(e) => handleCodeInput(index, e.target.value)}
                                            className="code-digit"
                                            disabled={loading}
                                        />
                                    ))}
                                </div>
                            </div>
                            
                            <div className="flex space-x-3">
                                <button
                                    onClick={() => {
                                        setShowVerification(false);
                                        setVerificationCode(['', '', '', '']);
                                    }}
                                    className="flex-1 py-3 border border-gray-300 rounded-xl font-medium text-gray-700 hover:bg-gray-50"
                                    disabled={loading}
                                >
                                    Retour
                                </button>
                                <button
                                    onClick={verifyAndUpdatePhone}
                                    disabled={loading || verificationCode.join('').length !== 4}
                                    className="flex-1 py-3 bg-mdriver-orange text-white rounded-xl font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:bg-orange-600"
                                >
                                    {loading ? (
                                        <div className="flex items-center justify-center">
                                            <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                                            Vérification...
                                        </div>
                                    ) : (
                                        'Vérifier'
                                    )}
                                </button>
                            </div>
                            
                            {countdown > 0 ? (
                                <p className="text-sm text-gray-500 text-center">
                                    Renvoyer le code dans {countdown}s
                                </p>
                            ) : (
                                <button
                                    onClick={sendVerificationCode}
                                    className="w-full text-sm text-mdriver-orange font-medium"
                                    disabled={loading}
                                >
                                    Renvoyer le code
                                </button>
                            )}
                        </div>
                    </AnimatedCard>
                )}

                {/* Informations */}
                <AnimatedCard className="card" delay={300}>
                    <div className="flex items-start space-x-3">
                        <Icons.Info className="w-5 h-5 text-blue-500 mt-1" />
                        <div className="text-sm text-gray-600">
                            <p className="font-medium mb-1">Sécurité</p>
                            <ul className="space-y-1 text-xs">
                                <li>• Un code de vérification sera envoyé par SMS</li>
                                <li>• Votre ancien numéro sera désactivé</li>
                                <li>• Utilisé pour l'authentification et les notifications</li>
                            </ul>
                        </div>
                    </div>
                </AnimatedCard>
            </div>
        </AnimatedView>
    );
};

// Help View - Vue d'aide avec système de chat/support
const HelpView = () => {
    const { t } = useTranslation();
    const { navigate, user, notifications, selectedRideData, branding } = useAppContext();
    
    // Vérifier si on vient d'une course spécifique
    const fromRide = selectedRideData?.from_ride && selectedRideData?.job_hash;
    
    // États
    const [tickets, setTickets] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showNewTicket, setShowNewTicket] = useState(fromRide); // Ouvrir automatiquement si depuis une course
    const [selectedTicket, setSelectedTicket] = useState(null);
    const [messages, setMessages] = useState([]);
    const [newMessage, setNewMessage] = useState('');
    const [newTicketSubject, setNewTicketSubject] = useState(fromRide ? `Problème avec ma course ${selectedRideData.job_hash}` : '');
    const [newTicketMessage, setNewTicketMessage] = useState('');
    const [newTicketCategory, setNewTicketCategory] = useState(fromRide ? 'ride_issue' : 'general');
    const [rideJobHash, setRideJobHash] = useState(fromRide ? selectedRideData.job_hash : null);
    const [sendingMessage, setSendingMessage] = useState(false);
    const helpdeskPhone = branding?.contact_phone || '+41 22 123 45 67';
    const helpdeskEmail = branding?.contact_email || 'support@taxibook.ch';
    
    const messagesEndRef = useRef(null);
    
    // Charger les tickets de l'utilisateur
    useEffect(() => {
        if (user?.userUid) {
            loadTickets();
        } else {
            setLoading(false);
        }
    }, [user]);
    
    // Scroll automatique vers le bas des messages
    useEffect(() => {
        if (messagesEndRef.current) {
            messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
        }
    }, [messages]);
    
    const loadTickets = async () => {
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/support/tickets`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            if (data.success) {
                setTickets(data.data.tickets || []);
            }
        } catch (error) {
            console.error('Erreur chargement tickets:', error);
        } finally {
            setLoading(false);
        }
    };
    
    const loadTicketDetails = async (ticketId) => {
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/support/tickets/${ticketId}`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            if (data.success) {
                setSelectedTicket(data.data.ticket);
                setMessages(data.data.messages || []);
                
                // Marquer comme lu
                await fetch(`${API_BASE_URL}/support/tickets/${ticketId}/read`, {
                    method: 'POST',
                    headers: { 'Authorization': `Bearer ${token}` }
                });
            }
        } catch (error) {
            console.error('Erreur chargement détails:', error);
        }
    };
    
    const createTicket = async () => {
        if (!newTicketMessage.trim()) {
            notifications.error('Veuillez saisir votre message');
            return;
        }
        
        setSendingMessage(true);
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/support/tickets/create`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    subject: newTicketSubject || 'Conversation avec le support',
                    message: newTicketMessage,
                    category: newTicketCategory || 'general',
                    job_hash: rideJobHash || null
                })
            });
            
            const data = await response.json();
            if (data.success) {
                // Ajouter le message localement pour feedback immédiat
                setMessages(prev => [...prev, {
                    message_id: `local-${Date.now()}`,
                    sender_type: 'user',
                    message: newTicketMessage,
                    created_at: new Date().toISOString()
                }]);
                setNewTicketMessage('');
                
                // Charger les détails complets du ticket créé
                setTimeout(() => {
                    loadTicketDetails(data.data.ticket_id);
                }, 500);
                
                loadTickets();
            } else {
                notifications.error(data.message || 'Erreur lors de l\'envoi');
            }
        } catch (error) {
            console.error('Erreur création ticket:', error);
            notifications.error('Erreur de connexion');
        } finally {
            setSendingMessage(false);
        }
    };
    
    const sendMessage = async () => {
        if (!newMessage.trim() || !selectedTicket) return;
        
        setSendingMessage(true);
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/support/tickets/${selectedTicket.ticket_id}/message`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ message: newMessage })
            });
            
            const data = await response.json();
            if (data.success) {
                setNewMessage('');
                loadTicketDetails(selectedTicket.ticket_id);
            }
        } catch (error) {
            notifications.error('Erreur d\'envoi');
        } finally {
            setSendingMessage(false);
        }
    };
    
    const closeTicket = async () => {
        if (!selectedTicket) return;
        
        try {
            const token = localStorage.getItem('user_token');
            await fetch(`${API_BASE_URL}/support/tickets/${selectedTicket.ticket_id}/close`, {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` }
            });
            notifications.success('Ticket fermé');
            setSelectedTicket(null);
            loadTickets();
        } catch (error) {
            notifications.error('Erreur');
        }
    };
    
    const getCategoryLabel = (cat) => {
        const labels = {
            general: 'Question générale',
            ride_issue: 'Problème de course',
            payment: 'Paiement',
            driver_complaint: 'Chauffeur',
            app_bug: 'Bug application',
            account: 'Mon compte',
            other: 'Autre'
        };
        return labels[cat] || cat;
    };
    
    const getStatusBadge = (status) => {
        const styles = {
            open: 'bg-blue-100 text-blue-700',
            in_progress: 'bg-yellow-100 text-yellow-700',
            waiting_user: 'bg-orange-100 text-orange-700',
            waiting_support: 'bg-purple-100 text-purple-700',
            resolved: 'bg-green-100 text-green-700',
            closed: 'bg-gray-100 text-gray-600'
        };
        const labels = {
            open: 'Nouveau',
            in_progress: 'En cours',
            waiting_user: 'En attente de vous',
            waiting_support: 'En attente du support',
            resolved: 'Résolu',
            closed: 'Fermé'
        };
        return (
            <span className={`px-2 py-1 rounded-full text-xs font-medium ${styles[status] || styles.open}`}>
                {labels[status] || status}
            </span>
        );
    };
    
    // Vue Chat d'un ticket sélectionné
    if (selectedTicket) {
        return (
            <div className="flex flex-col bg-gray-50" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 50 }}>
                {/* Header */}
                <div className="bg-white border-b px-4 py-3 flex items-center justify-between">
                    <div className="flex items-center">
                        <button onClick={() => setSelectedTicket(null)} className="mr-3">
                            <Icons.ArrowLeft className="w-6 h-6 text-gray-600" />
                        </button>
                        <div>
                            <h2 className="font-semibold text-gray-800">{selectedTicket.subject}</h2>
                            <div className="flex items-center gap-2">
                                {getStatusBadge(selectedTicket.status)}
                                <span className="text-xs text-gray-500">{getCategoryLabel(selectedTicket.category)}</span>
                            </div>
                        </div>
                    </div>
                    {selectedTicket.status !== 'closed' && (
                        <button 
                            onClick={closeTicket}
                            className="text-sm text-gray-600 hover:text-red-600"
                        >
                            Fermer
                        </button>
                    )}
                </div>
                
                {/* Messages */}
                <div className="flex-1 overflow-y-auto p-4 space-y-3">
                    {messages.map((msg, idx) => (
                        <div 
                            key={msg.message_id || idx}
                            className={`flex ${msg.sender_type === 'user' ? 'justify-end' : 'justify-start'}`}
                        >
                            {msg.sender_type === 'system' ? (
                                <div className="text-center w-full py-2">
                                    <span className="text-xs text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                                        {msg.message}
                                    </span>
                                </div>
                            ) : (
                                <div className={`max-w-[80%] rounded-2xl px-4 py-2 ${
                                    msg.sender_type === 'user' 
                                        ? 'bg-mdriver-orange text-white rounded-br-md' 
                                        : 'bg-white text-gray-800 rounded-bl-md shadow-sm'
                                }`}>
                                    <p className="text-sm">{msg.message}</p>
                                    <p className={`text-xs mt-1 ${msg.sender_type === 'user' ? 'text-orange-100' : 'text-gray-400'}`}>
                                        {new Date(msg.created_at).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })}
                                    </p>
                                </div>
                            )}
                        </div>
                    ))}
                    <div ref={messagesEndRef} />
                </div>
                
                {/* Input message */}
                {selectedTicket.status !== 'closed' && (
                    <div className="bg-white border-t p-4" style={{ paddingBottom: 'max(16px, env(safe-area-inset-bottom))' }}>
                        <div className="flex items-center gap-2">
                            <input
                                type="text"
                                value={newMessage}
                                onChange={(e) => setNewMessage(e.target.value)}
                                onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                                placeholder="Écrivez votre message..."
                                className="flex-1 px-4 py-3 bg-gray-100 rounded-full focus:outline-none focus:ring-2 focus:ring-mdriver-orange"
                            />
                            <button
                                onClick={sendMessage}
                                disabled={sendingMessage || !newMessage.trim()}
                                className="w-12 h-12 bg-mdriver-orange rounded-full flex items-center justify-center text-white disabled:opacity-50 flex-shrink-0"
                            >
                                {sendingMessage ? (
                                    <div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent" />
                                ) : (
                                    <Icons.Send className="w-5 h-5" />
                                )}
                            </button>
                        </div>
                    </div>
                )}
            </div>
        );
    }
    
    // Vue Chat Direct - Interface de chat simplifiée (sans formulaire)
    if (showNewTicket) {
        return (
            <div className="flex flex-col bg-gray-50" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 50 }}>
                {/* Header */}
                <div className="bg-white border-b px-4 py-3 flex items-center">
                    <button onClick={() => setShowNewTicket(false)} className="mr-3">
                        <Icons.ArrowLeft className="w-6 h-6 text-gray-600" />
                    </button>
                    <div className="w-10 h-10 bg-mdriver-orange rounded-full flex items-center justify-center mr-3">
                        <Icons.MessageCircle className="w-5 h-5 text-white" />
                    </div>
                    <div>
                        <h2 className="font-semibold text-gray-800">Support {branding?.display_name || 'DriveMe'}</h2>
                        <div className="text-xs text-green-600 flex items-center gap-1">
                            <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                            En ligne - Réponse rapide
                        </div>
                    </div>
                </div>
                
                {/* Zone de chat */}
                <div className="flex-1 overflow-y-auto p-4 space-y-3">
                    {/* Message d'accueil automatique */}
                    <div className="flex justify-start">
                        <div className="max-w-[80%] bg-white text-gray-800 rounded-2xl rounded-bl-md shadow-sm px-4 py-3">
                            <p className="text-sm">Bonjour ! Comment puis-je vous aider aujourd'hui ?</p>
                            <p className="text-xs text-gray-400 mt-1">Support {branding?.display_name || 'DriveMe'}</p>
                        </div>
                    </div>
                    
                    {/* Messages existants si ticket créé */}
                    {messages.map((msg, idx) => (
                        <div 
                            key={msg.message_id || idx}
                            className={`flex ${msg.sender_type === 'user' ? 'justify-end' : 'justify-start'}`}
                        >
                            {msg.sender_type === 'system' ? (
                                <div className="text-center w-full py-2">
                                    <span className="text-xs text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                                        {msg.message}
                                    </span>
                                </div>
                            ) : (
                                <div className={`max-w-[80%] rounded-2xl px-4 py-2 ${
                                    msg.sender_type === 'user' 
                                        ? 'bg-mdriver-orange text-white rounded-br-md' 
                                        : 'bg-white text-gray-800 rounded-bl-md shadow-sm'
                                }`}>
                                    <p className="text-sm">{msg.message}</p>
                                    <p className={`text-xs mt-1 ${msg.sender_type === 'user' ? 'text-orange-100' : 'text-gray-400'}`}>
                                        {new Date(msg.created_at).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })}
                                    </p>
                                </div>
                            )}
                        </div>
                    ))}
                    <div ref={messagesEndRef} />
                </div>
                
                {/* Zone de saisie du message */}
                <div className="bg-white border-t p-4" style={{ paddingBottom: 'max(16px, env(safe-area-inset-bottom))' }}>
                    <div className="flex items-center gap-2">
                        <input
                            type="text"
                            value={newTicketMessage}
                            onChange={(e) => setNewTicketMessage(e.target.value)}
                            onKeyPress={(e) => {
                                if (e.key === 'Enter' && newTicketMessage.trim()) {
                                    createTicket();
                                }
                            }}
                            placeholder="Écrivez votre message..."
                            className="flex-1 px-4 py-3 bg-gray-100 rounded-full focus:outline-none focus:ring-2 focus:ring-mdriver-orange"
                        />
                        <button
                            onClick={createTicket}
                            disabled={sendingMessage || !newTicketMessage.trim()}
                            className="w-12 h-12 bg-mdriver-orange rounded-full flex items-center justify-center text-white disabled:opacity-50 hover:bg-orange-600 transition-colors flex-shrink-0"
                        >
                            {sendingMessage ? (
                                <div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent" />
                            ) : (
                                <Icons.Send className="w-5 h-5" />
                            )}
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    // Vue principale - Liste des tickets + options
    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in">
            <Header title={t('help.title')} showBackButton={true} />
            
            <div className="flex-1 px-6 py-6 space-y-6 overflow-y-auto">
                {/* Bouton nouvelle conversation */}
                <AnimatedCard className="card bg-mdriver-orange text-white cursor-pointer hover:shadow-lg transition-all" delay={100}>
                    <div onClick={() => {
                        if (!user?.userUid) { notifications.error('Veuillez vous connecter'); return; }
                        setMessages([]);
                        setNewTicketMessage('');
                        setNewTicketSubject('');
                        setNewTicketCategory('general');
                        setRideJobHash(null);
                        setSelectedTicket(null);
                        setShowNewTicket(true);
                    }} className="flex items-center space-x-4">
                        <div className="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center">
                            <Icons.MessageCircle className="w-6 h-6 text-white" />
                        </div>
                        <div className="flex-1">
                            <div className="font-semibold">Nouvelle conversation</div>
                            <div className="text-sm text-orange-100">Démarrer une discussion avec notre équipe</div>
                        </div>
                        <Icons.ChevronRight className="w-5 h-5 text-white/70" />
                    </div>
                </AnimatedCard>
                
                {/* Mes conversations */}
                {user?.userUid && tickets.length > 0 && (
                    <div className="space-y-3">
                        <h3 className="font-semibold text-gray-700">Mes conversations</h3>
                        {tickets.map((ticket, idx) => (
                            <AnimatedCard
                                key={ticket.ticket_id}
                                className="card cursor-pointer hover:shadow-lg transition-all"
                                delay={200 + idx * 50}
                            >
                                <div onClick={() => loadTicketDetails(ticket.ticket_id)} className="flex items-center space-x-4">
                                    <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
                                        ticket.unread_by_user > 0 ? 'bg-mdriver-orange' : 'bg-gray-100'
                                    }`}>
                                        <Icons.MessageCircle className={`w-6 h-6 ${
                                            ticket.unread_by_user > 0 ? 'text-white' : 'text-gray-500'
                                        }`} />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center justify-between">
                                            <div className="font-semibold text-gray-800 truncate">{ticket.subject}</div>
                                            {ticket.unread_by_user > 0 && (
                                                <span className="ml-2 bg-mdriver-orange text-white text-xs px-2 py-0.5 rounded-full">
                                                    {ticket.unread_by_user}
                                                </span>
                                            )}
                                        </div>
                                        <div className="flex items-center gap-2 mt-1">
                                            {getStatusBadge(ticket.status)}
                                            <span className="text-xs text-gray-500">
                                                {new Date(ticket.last_message_at || ticket.created_at).toLocaleDateString('fr-FR')}
                                            </span>
                                        </div>
                                    </div>
                                    <Icons.ChevronRight className="w-5 h-5 text-gray-400" />
                                </div>
                            </AnimatedCard>
                        ))}
                    </div>
                )}
                
                {/* Options de contact direct */}
                <div className="space-y-3">
                    <h3 className="font-semibold text-gray-700">Autres options</h3>
                    <AnimatedCard className="card cursor-pointer hover:shadow-lg transition-all" delay={300}>
                        <div onClick={() => window.open(`tel:${helpdeskPhone.replace(/\s/g, '')}`)} className="flex items-center space-x-4">
                            <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center">
                                <Icons.Phone className="w-6 h-6 text-mdriver-orange" />
                            </div>
                            <div className="flex-1">
                                <div className="font-semibold text-gray-800">Appeler le support</div>
                                <div className="text-sm text-gray-600">{helpdeskPhone}</div>
                            </div>
                            <Icons.ChevronRight className="w-5 h-5 text-gray-400" />
                        </div>
                    </AnimatedCard>
                    <AnimatedCard className="card cursor-pointer hover:shadow-lg transition-all" delay={350}>
                        <div onClick={() => window.open(`mailto:${helpdeskEmail}`)} className="flex items-center space-x-4">
                            <div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center">
                                <Icons.Mail className="w-6 h-6 text-mdriver-orange" />
                            </div>
                            <div className="flex-1">
                                <div className="font-semibold text-gray-800">Envoyer un email</div>
                                <div className="text-sm text-gray-600">{helpdeskEmail}</div>
                            </div>
                            <Icons.ChevronRight className="w-5 h-5 text-gray-400" />
                        </div>
                    </AnimatedCard>
                </div>

                {/* FAQ */}
                <AnimatedCard className="card" delay={400}>
                    <h3 className="font-semibold text-gray-800 mb-3">Questions fréquentes</h3>
                    <div className="space-y-3 text-sm">
                        <div>
                            <div className="font-medium text-gray-800">Comment annuler une course ?</div>
                            <div className="text-gray-600">Annulation gratuite jusqu'à 5 min avant l'arrivée du chauffeur.</div>
                        </div>
                        <div>
                            <div className="font-medium text-gray-800">Comment utiliser mes points ?</div>
                            <div className="text-gray-600">1000 points = 5 CHF. Appliqués automatiquement.</div>
                        </div>
                    </div>
                </AnimatedCard>
            </div>
        </AnimatedView>
    );
};

// Order Summary View - Vue résumé de commande
const OrderSummaryView = () => {
    const { 
        user, notifications, navigate, 
        pickupAddress, destinationAddress,
        destinationCoords: contextDestCoords,
        mapInstance, centerMarker,
        selectedRideData 
    } = useAppContext();
    
    const [loading, setLoading] = useState(false);
    const [tripDistance, setTripDistance] = useState(0);
    const [tripDuration, setTripDuration] = useState(0);
    const [basePrice, setBasePrice] = useState(0);
    const [adminFees, setAdminFees] = useState(0);
    const [finalPrice, setFinalPrice] = useState(0);
    const [pointsToEarn, setPointsToEarn] = useState(10);
    const [loadingDistance, setLoadingDistance] = useState(false);
    
    // États pour le mode de paiement
    const [selectedPaymentMethod, setSelectedPaymentMethod] = useState(null);
    const [paymentMethods, setPaymentMethods] = useState([]);
    const [showPaymentModal, setShowPaymentModal] = useState(false);
    
    // États pour la vue de confirmation
    const [showConfirmationView, setShowConfirmationView] = useState(false);
    const [confirmationTimer, setConfirmationTimer] = useState(5);
    const [confirmationInterval, setConfirmationInterval] = useState(null);
    
    // Récupérer les données du véhicule sélectionné depuis navigate
    const vehicleData = selectedRideData?.vehicle || {};
    const scheduledDate = selectedRideData?.scheduledDate;
    const scheduledTime = selectedRideData?.scheduledTime;

    // Forcer le scroll au sommet lors du chargement de la vue
    useEffect(() => {
        window.scrollTo(0, 0);
    }, []);

    useEffect(() => {
        if (vehicleData.estimated_price) {
            calculateRouteDistance();
        }
    }, [vehicleData, pickupAddress, destinationAddress]);

    // Recalculer les points quand la distance change
    useEffect(() => {
        if (tripDistance > 0) {
            const points = Math.max(10, Math.round(tripDistance * 10));
            setPointsToEarn(points);
            console.log(`🎯 Points recalculés: ${tripDistance}km × 10 = ${points} points`);
        }
    }, [tripDistance]);
    
    // Charger les modes de paiement (mémorisée pour éviter les re-exécutions)
    const loadPaymentMethods = useCallback(async () => {
        try {
            const methods = [];
            let defaultMethod = null;
            
            if (user?.userUid) {
                // Charger les cartes enregistrées de l'utilisateur
                try {
                    const token = localStorage.getItem('user_token');
                    const response = await fetch(`${API_BASE_URL}/payments/cards?user_uid=${user.userUid}`, {
                        headers: token ? { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } : { 'Content-Type': 'application/json' }
                    });
                    const data = await response.json();
                    
                    if (data.success && data.cards && data.cards.length > 0) {
                        // Ajouter les cartes enregistrées
                        data.cards.forEach(card => {
                            const cardMethod = {
                                id: `card_${card.md5}`,
                                name: `Carte ${card.card_brand} ****${card.card_digits}`,
                                type: 'saved_card',
                                cardData: card,
                                isDefault: card.is_default === '1' || card.is_default === 1
                            };
                            methods.push(cardMethod);
                            
                            // Sélectionner la carte par défaut
                            if (cardMethod.isDefault) {
                                defaultMethod = cardMethod;
                            }
                        });
                    }
                } catch (error) {
                    console.error('Erreur lors du chargement des cartes:', error);
                }
            }
            
            // Ajouter les options par défaut
            if (methods.length === 0) {
                // Si aucune carte enregistrée, proposer "Carte" par défaut
                const cardMethod = {
                    id: 'new_card',
                    name: 'Carte',
                    type: 'new_card',
                    isDefault: true
                };
                methods.push(cardMethod);
                defaultMethod = cardMethod;
            }
            
            // Toujours ajouter TWINT
            methods.push({
                id: 'twint',
                name: 'TWINT',
                type: 'twint',
                isDefault: false
            });
            
            // Ajouter l'option "Ajouter une carte"
            methods.push({
                id: 'add_card',
                name: 'Ajouter une carte',
                type: 'add_card',
                isDefault: false
            });
            
            setPaymentMethods(methods);
            
            // Sélectionner le mode par défaut (première carte enregistrée ou "Carte" si aucune)
            if (!defaultMethod && methods.length > 0) {
                defaultMethod = methods[0];
            }
            setSelectedPaymentMethod(defaultMethod);
            
        } catch (error) {
            console.error('Erreur lors du chargement des modes de paiement:', error);
            // Fallback en cas d'erreur
            const fallbackMethods = [
                { id: 'new_card', name: 'Carte', type: 'new_card', isDefault: true },
                { id: 'twint', name: 'TWINT', type: 'twint', isDefault: false },
                { id: 'add_card', name: 'Ajouter une carte', type: 'add_card', isDefault: false }
            ];
            setPaymentMethods(fallbackMethods);
            setSelectedPaymentMethod(fallbackMethods[0]);
        }
    }, [user?.userUid]);
    
    // Charger les modes de paiement une seule fois au mount
    useEffect(() => {
        loadPaymentMethods();
    }, [loadPaymentMethods]);

    // Debug log contrôlé (une seule fois au mount)
    useEffect(() => {
        console.log('📋 OrderSummaryView mounted - vehicleData:', vehicleData);
    }, []);

    const geocodeWithSwissApp = async (address) => {
        const url = `https://api.maps.swissapp.net/place?address=${encodeURIComponent(address)}&countries=CH,FR&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
        const response = await fetch(url);
        const data = await response.json();
        if (data.code === 1 && data.datas?.predictions?.[0]) {
            const placeId = data.datas.predictions[0].place_id;
            const geoResponse = await fetch(`https://api.maps.swissapp.net/place_geometry?placeId=${placeId}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`);
            const geoData = await geoResponse.json();
            if (geoData.code === 1 && geoData.datas?.result?.geometry?.location) {
                return { lat: parseFloat(geoData.datas.result.geometry.location.lat), lng: parseFloat(geoData.datas.result.geometry.location.lng) };
            }
        }
        throw new Error('Geocoding failed');
    };

    const calculateRouteDistance = async () => {
        if (!pickupAddress || !destinationAddress) return;

        setLoadingDistance(true);
        try {
            let pCoords, dCoords;

            if (mapInstance && centerMarker) {
                try {
                    const pos = centerMarker.getLatLng();
                    if (pos?.lat && pos?.lng) pCoords = { lat: pos.lat, lng: pos.lng };
                } catch (e) { /* ignore */ }
            }
            if (contextDestCoords?.lat && contextDestCoords?.lng) {
                dCoords = { lat: contextDestCoords.lat, lng: contextDestCoords.lng };
            }

            try {
                if (!pCoords) pCoords = await geocodeWithSwissApp(pickupAddress);
                if (!dCoords) dCoords = await geocodeWithSwissApp(destinationAddress);
            } catch (e) {
                console.warn('Geocoding failed, using defaults');
                setTripDistance(5);
                setTripDuration(15);
                setLoadingDistance(false);
                calculatePricing();
                return;
            }

            const pickupCoords = pCoords;
            const destinationCoords = dCoords;

            const apiUrl = `https://api.maps.swissapp.net/directions?origin=${pickupCoords.lat},${pickupCoords.lng}&destination=${destinationCoords.lat},${destinationCoords.lng}&mode=driving&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
            
            const response = await fetch(apiUrl);
            const data = await response.json();
            
            if (data && data.code === 1 && data.result === 'OK' && data.data && data.data.routes && data.data.routes.length > 0) {
                const route = data.data.routes[0];
                if (route.legs && route.legs[0]) {
                    const leg = route.legs[0];
                    const distanceKm = leg.distance ? (leg.distance.value / 1000) : 5;
                    setTripDistance(distanceKm);
                    const durationMin = leg.duration ? Math.round(leg.duration.value / 60) : 15;
                    setTripDuration(durationMin);
                    console.log(`📏 Distance calculée: ${distanceKm.toFixed(1)} km, ${durationMin} min`);
                }
            } else {
                console.warn('API SwissApp: données indisponibles, fallback distance estimée');
                setTripDistance(5);
                setTripDuration(15);
            }
        } catch (error) {
            console.error('Erreur calcul distance:', error);
            setTripDistance(5);
            setTripDuration(15);
        } finally {
            setLoadingDistance(false);
            calculatePricing();
        }
    };

    const calculatePricing = () => {
        const base = parseFloat(vehicleData.estimated_price) || 0;
        const admin = base * 0.20; // 20% frais administratifs
        const total = base + admin;
        
        // Points basés sur la distance réelle (10 points par km, minimum 10)
        const points = Math.max(10, Math.round(tripDistance * 10));
        
        setBasePrice(base);
        setAdminFees(admin);
        setFinalPrice(total);
        setPointsToEarn(points);
    };

    const getCoordinatesFromAddress = async (address) => {
        try {
            const url = `https://api.maps.swissapp.net/place?address=${encodeURIComponent(address)}&countries=CH,FR&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.code === 1 && data.datas?.predictions?.[0]) {
                const placeId = data.datas.predictions[0].place_id;
                const geoUrl = `https://api.maps.swissapp.net/place_geometry?placeId=${placeId}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
                const geoResponse = await fetch(geoUrl);
                const geoData = await geoResponse.json();
                
                if (geoData.code === 1 && geoData.datas?.result?.geometry?.location) {
                    return {
                        latitude: parseFloat(geoData.datas.result.geometry.location.lat),
                        longitude: parseFloat(geoData.datas.result.geometry.location.lng),
                        place_id: placeId
                    };
                }
            }
            
            const nomResp = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)}&limit=1`);
            const nomResults = await nomResp.json();
            if (nomResults.length > 0) {
                return {
                    latitude: parseFloat(nomResults[0].lat),
                    longitude: parseFloat(nomResults[0].lon),
                    place_id: nomResults[0].place_id ? String(nomResults[0].place_id) : null
                };
            }
            
            console.warn(`Geocoding failed for "${address}"`);
            return null;
        } catch (error) {
            console.warn('Geocoding error:', error);
            return null;
        }
    };

    // Fonction pour démarrer la confirmation avec timer
    const startConfirmationProcess = () => {
        if (!vehicleData || !vehicleData.id) {
            notifications.error('Aucun véhicule sélectionné');
            return;
        }
        
        setShowConfirmationView(true);
        setConfirmationTimer(5);
        
        const interval = setInterval(() => {
            setConfirmationTimer(prev => {
                if (prev <= 1) {
                    clearInterval(interval);
                    setConfirmationInterval(null);
                    // Auto-confirmation quand le timer arrive à 0
                    setTimeout(() => {
                        processOrderConfirmation();
                    }, 100);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);
        
        setConfirmationInterval(interval);
    };

    // Fonction pour annuler la confirmation
    const cancelConfirmation = () => {
        if (confirmationInterval) {
            clearInterval(confirmationInterval);
            setConfirmationInterval(null);
        }
        setShowConfirmationView(false);
        setConfirmationTimer(5);
    };

    // Fonction pour confirmer immédiatement
    const confirmImmediately = () => {
        if (confirmationInterval) {
            clearInterval(confirmationInterval);
            setConfirmationInterval(null);
        }
        processOrderConfirmation();
    };

    // Fonction qui traite réellement la confirmation de commande
    const processOrderConfirmation = async () => {
        // ✅ Vérifier que l'utilisateur est connecté
        if (!user || !user.userUid) {
            notifications.error('Veuillez vous connecter pour commander une course');
            setShowConfirmationView(false);
            setConfirmationTimer(5);
            navigate('login');
            return;
        }
        
        setLoading(true);
        try {
            console.log('🌍 Récupération des coordonnées GPS...');

            let pickupCoords = null;
            if (mapInstance && centerMarker) {
                try {
                    const pos = centerMarker.getLatLng();
                    if (pos && pos.lat && pos.lng) {
                        pickupCoords = { latitude: pos.lat, longitude: pos.lng, place_id: null };
                        console.log('📍 Pickup coords from map center:', pickupCoords);
                    }
                } catch (e) { /* ignore */ }
            }
            if (!pickupCoords) {
                pickupCoords = await getCoordinatesFromAddress(pickupAddress);
            }

            let destinationCoords = null;
            if (contextDestCoords && contextDestCoords.lat && contextDestCoords.lng) {
                destinationCoords = { latitude: contextDestCoords.lat, longitude: contextDestCoords.lng, place_id: contextDestCoords.place_id || null };
                console.log('📍 Destination coords from context:', destinationCoords);
            } else {
                destinationCoords = await getCoordinatesFromAddress(destinationAddress);
            }

            console.log('📍 Données pickup:', pickupCoords);
            console.log('📍 Données destination:', destinationCoords);
            
            // ⚠️ Vérifier que les coordonnées sont valides
            if (!pickupCoords?.latitude || !pickupCoords?.longitude) {
                console.error('❌ Coordonnées de départ invalides');
                notifications.error('Impossible de localiser l\'adresse de départ. Veuillez réessayer.');
                setShowConfirmationView(false);
                setConfirmationTimer(5);
                setLoading(false);
                return;
            }
            
            if (!destinationCoords?.latitude || !destinationCoords?.longitude) {
                console.error('❌ Coordonnées de destination invalides');
                notifications.error('Impossible de localiser l\'adresse de destination. Veuillez réessayer.');
                setShowConfirmationView(false);
                setConfirmationTimer(5);
                setLoading(false);
                return;
            }
            
            // 💳 PRÉ-AUTORISATION DE PAIEMENT
            // Si une carte est sélectionnée, créer une pré-autorisation
            let authorizationUid = null;
            const amountInCentimes = Math.round(finalPrice * 100);
            
            if (selectedPaymentMethod?.type === 'saved_card' && selectedPaymentMethod?.cardData?.id) {
                console.log('💳 Création de la pré-autorisation de paiement...');
                try {
                    const authResponse = await fetch(`${API_CONFIG.BASE_URL}/payments/authorize`, {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${authToken}`,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            card_id: selectedPaymentMethod.cardData.id,
                            amount: amountInCentimes
                        })
                    });
                    
                    const authResult = await authResponse.json();
                    
                    if (authResult.success) {
                        authorizationUid = authResult.data?.authorization?.uid;
                        console.log('✅ Pré-autorisation créée:', authorizationUid);
                    } else {
                        // Paiement refusé - arrêter le processus
                        throw new Error(authResult.error || 'Paiement refusé par votre banque');
                    }
                } catch (authError) {
                    console.error('❌ Erreur pré-autorisation:', authError);
                    notifications.error('Erreur de paiement: ' + authError.message);
                    setShowConfirmationView(false);
                    setConfirmationTimer(5);
                    setLoading(false);
                    return;
                }
            }

            const jobData = {
                user_uid: user.userUid,
                pickup_address: pickupAddress,
                destination_address: destinationAddress,
                // ✅ Ajouter les place_id
                pickup_place_id: pickupCoords?.place_id || null,
                destination_place_id: destinationCoords?.place_id || null,
                // ✅ Ajouter les coordonnées GPS
                pickup_latitude: pickupCoords?.latitude || null,
                pickup_longitude: pickupCoords?.longitude || null,
                destination_latitude: destinationCoords?.latitude || null,
                destination_longitude: destinationCoords?.longitude || null,
                fleet_id: vehicleData.id, // Champ requis par l'API
                // ✅ Prix décomposé
                estimated_price: finalPrice, // Prix total (base + frais)
                base_price: basePrice, // Prix de base (ce que gagne le chauffeur)
                admin_fee: adminFees, // Frais administratifs (ce que gagne TaxiBook)
                admin_fee_rate: 0.20, // Taux des frais (20%)
                pickup_datetime: scheduledDate && scheduledTime 
                    ? `${scheduledDate} ${scheduledTime}:00`
                    : null,
                // Ajouter les informations de paiement
                payment_method_type: selectedPaymentMethod?.type || 'new_card',
                payment_method_id: selectedPaymentMethod?.type === 'saved_card' 
                    ? selectedPaymentMethod.cardData?.id 
                    : null,
                payment_method_name: selectedPaymentMethod?.name || 'Carte',
                // Référence de l'autorisation de paiement
                payment_authorization_uid: authorizationUid
            };

            console.log('📤 Données envoyées à l\'API:', jobData);
            const result = await apiService.createJob(jobData);
            console.log('📥 Réponse API createJob:', result);
            
            if (result.success) {
                notifications.success('Course confirmée !');
                
                setShowConfirmationView(false);
                setConfirmationTimer(5);
                
                const createdJob = result.data?.job || result.job || result.data;
                console.log('📥 Course créée:', createdJob);
                
                navigate('ride-confirmed', {
                    ...jobData,
                    jobId: createdJob.id,
                    job_hash: createdJob.job_hash,
                    jobHash: createdJob.job_hash,
                    jobReference: createdJob.job_hash?.substring(0, 12),
                    vehicle: vehicleData,
                    finalPrice: finalPrice.toFixed(2)
                });
            } else {
                const errMsg = result.error || result.message || 'Erreur lors de la création de la course';
                console.error('❌ API error detail:', errMsg);
                throw new Error(errMsg);
            }
        } catch (error) {
            console.error('Erreur lors de la création de la course:', error);
            notifications.error('Erreur lors de la création de la course: ' + error.message);
            setShowConfirmationView(false);
            setConfirmationTimer(5);
        } finally {
            setLoading(false);
        }
    };



    // Nettoyer le timer quand le composant se démonte
    useEffect(() => {
        return () => {
            if (confirmationInterval) {
                clearInterval(confirmationInterval);
            }
        };
    }, [confirmationInterval]);

    // Gestion de l'ajout d'une carte (mémorisée pour éviter les re-renders)
    const handleAddCard = useCallback(() => {
        if (!user?.userUid) {
            notifications.error('Vous devez être connecté pour ajouter une carte');
            return;
        }
        
        const addCardUrl = `${API_BASE_URL}/cards/add.php?user_uid=${user.userUid}`;
        window.open(addCardUrl, '_blank', 'width=600,height=500,scrollbars=yes');
        setShowPaymentModal(false);
    }, [user?.userUid, notifications]);

    // Gestion du paiement TWINT
    const handleTwintPayment = useCallback(() => {
        if (!user?.userUid) {
            notifications.error('Vous devez être connecté pour utiliser TWINT');
            return;
        }
        
        // Créer l'URL pour le paiement TWINT
        const twintUrl = `${API_BASE_URL}/twint/payment.php?user_uid=${user.userUid}&amount=${finalPrice.toFixed(2)}&currency=CHF`;
        
        // Ouvrir la popup TWINT
        const twintWindow = window.open(
            twintUrl, 
            'twint_payment', 
            'width=400,height=600,scrollbars=yes,resizable=yes'
        );
        
        // Écouter la fermeture de la popup pour vérifier le statut
        const checkClosed = setInterval(() => {
            if (twintWindow.closed) {
                clearInterval(checkClosed);
                // Vérifier le statut du paiement
                console.log('Popup TWINT fermée - vérification du statut...');
            }
        }, 1000);
        
        setShowPaymentModal(false);
    }, [user?.userUid, finalPrice, notifications]);

    // Gestion de la sélection d'une méthode de paiement (mémorisée)
    const handlePaymentMethodSelect = useCallback((method) => {
        if (method.type === 'add_card') {
            handleAddCard();
        } else if (method.type === 'twint') {
            handleTwintPayment();
        } else {
            setSelectedPaymentMethod(method);
            setShowPaymentModal(false);
        }
    }, [handleAddCard, handleTwintPayment]);

    // Fonction pour fermer le modal (stable)
    const closeModal = useCallback((e) => {
        if (e.target === e.currentTarget) {
            setShowPaymentModal(false);
        }
    }, []);

    // Fonction pour ouvrir le modal (stable)
    const openPaymentModal = useCallback(() => {
        setShowPaymentModal(true);
    }, []);

    // Texte du mode de paiement (mémorisé)
    const paymentMethodText = useMemo(() => {
        return selectedPaymentMethod ? selectedPaymentMethod.name : 'Sélectionner un mode de paiement';
    }, [selectedPaymentMethod?.name]);

    // Modal de sélection de mode de paiement (stable)
    const PaymentMethodModal = useMemo(() => {
        if (!showPaymentModal) return null;
        
        return (
            <div 
                className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
                onClick={closeModal}
            >
                <div className="bg-white rounded-2xl w-full max-w-md" onClick={(e) => e.stopPropagation()}>
                    <div className="p-6">
                        <div className="flex items-center justify-between mb-6">
                            <h3 className="text-xl font-bold text-gray-800">Mode de paiement</h3>
                            <button 
                                onClick={() => setShowPaymentModal(false)}
                                className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 transition-colors"
                            >
                                <Icons.X className="w-5 h-5 text-gray-600" />
                            </button>
                        </div>
                        
                        <div className="space-y-3">
                            {paymentMethods.map((method) => {
                                const isSelected = selectedPaymentMethod?.id === method.id;
                                const isAddCard = method.type === 'add_card';
                                
                                return (
                                    <button
                                        key={method.id}
                                        onClick={() => handlePaymentMethodSelect(method)}
                                        className={`w-full p-4 rounded-xl border text-left transition-all ${
                                            isSelected
                                                ? 'border-mdriver-orange bg-orange-50' 
                                                : isAddCard
                                                ? 'border-dashed border-gray-300 hover:border-mdriver-orange hover:bg-orange-50'
                                                : 'border-gray-200 hover:border-gray-300'
                                        }`}
                                    >
                                        <div className="flex items-center justify-between">
                                            <div className="flex items-center">
                                                {isAddCard ? (
                                                    <Icons.Plus className="w-5 h-5 text-mdriver-orange mr-3" />
                                                ) : method.type === 'twint' ? (
                                                    <Icons.Smartphone className="w-5 h-5 text-blue-600 mr-3" />
                                                ) : (
                                                    <Icons.CreditCard className="w-5 h-5 text-gray-600 mr-3" />
                                                )}
                                                <div>
                                                    <div className={`font-medium ${isAddCard ? 'text-mdriver-orange' : 'text-gray-800'}`}>
                                                        {method.name}
                                                    </div>
                                                    {!isAddCard && (
                                                        <div className="text-sm text-gray-500 capitalize">
                                                            {method.type === 'saved_card' ? 'Carte enregistrée' : 
                                                             method.type === 'new_card' ? 'Nouvelle carte' :
                                                             method.type === 'twint' ? 'Paiement mobile' : method.type}
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                            {isSelected && !isAddCard && (
                                                <Icons.Check className="w-5 h-5 text-mdriver-orange" />
                                            )}
                                            {isAddCard && (
                                                <Icons.ExternalLink className="w-4 h-4 text-gray-400" />
                                            )}
                                        </div>
                                    </button>
                                );
                            })}
                        </div>
                        
                        {paymentMethods.filter(m => m.type === 'saved_card').length > 0 && (
                            <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                                <div className="text-sm text-blue-800">
                                    <Icons.Info className="w-4 h-4 inline mr-1" />
                                    Vos cartes enregistrées sont sécurisées et chiffrées.
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        );
    }, [showPaymentModal, closeModal, handlePaymentMethodSelect, paymentMethods]);

    // Navigation vers commander (stable)
    const navigateToCommander = useCallback(() => {
        navigate('commander');
    }, [navigate]);

    return (
        <div className="h-full flex flex-col bg-gray-50">
            {/* Header fixe */}
            <div className="fixed top-0 left-0 right-0 z-40 bg-white shadow-sm border-b border-gray-200">
                <div className="px-4 py-3 flex items-center justify-between">
                    <button 
                        onClick={navigateToCommander}
                        className="flex items-center justify-center w-10 h-10 rounded-full hover:bg-gray-100 transition-colors"
                    >
                        <Icons.ArrowLeft className="w-6 h-6 text-gray-600" />
                    </button>
                    
                    <h1 className="text-lg font-semibold text-gray-800 truncate px-2">
                        Confirmer votre commande
                    </h1>
                    <div className="w-10 h-10"></div>
                </div>
            </div>
            
            <AnimatedView className="flex-1 pt-16 pb-32" animationType="fade-in-up">
                
                <div className="flex-1 p-6 space-y-6">
                    {/* Véhicule sélectionné */}
                    <AnimatedCard className="card" delay={100} style={{padding: '0.75rem'}}>
                        <div className="flex items-center">
                            <div className="w-32 h-32 flex items-center justify-center mr-4">
                                <VehicleIcon vehicleType={vehicleData.vehicle_type} className="w-32 h-32" imageUrl={vehicleData.image_url} />
                            </div>
                            <div className="flex-1">
                                <div className="font-bold text-xl text-gray-800">{vehicleData.name}</div>
                                <div className="text-gray-600">{vehicleData.capacity} places</div>
                                <div className="text-gray-600">Arrivée: {vehicleData.eta || '5-10 min'}</div>
                            </div>
                        </div>
                    </AnimatedCard>

                    {/* Résumé des prix */}
                    <AnimatedCard className="card" delay={200}>
                        <h3 className="font-bold text-lg mb-4 text-gray-800">Résumé des prix</h3>
                        
                        <div className="space-y-3">
                            <div className="flex justify-between">
                                <span className="text-gray-600">Prix de base:</span>
                                <span className="font-medium">{basePrice.toFixed(2)} CHF</span>
                            </div>
                            
                            <div className="flex justify-between">
                                <span className="text-gray-600">Frais administratifs (20%):</span>
                                <span className="font-medium">{adminFees.toFixed(2)} CHF</span>
                            </div>
                            
                            <div className="border-t border-gray-200 pt-3">
                                <div className="flex justify-between items-center">
                                    <span className="font-bold text-gray-800">Total:</span>
                                    <span className="font-bold text-mdriver-orange">{finalPrice.toFixed(2)} CHF</span>
                                </div>
                            </div>
                        </div>
                    </AnimatedCard>

                    {/* Détails du trajet - Style inspiré de "Votre trajet" */}
                    <AnimatedCard className="card" delay={300}>
                        <div className="mb-3">
                            <h3 className="font-bold text-lg text-gray-800 mb-2">Détails du trajet</h3>
                            <div className="space-y-2">
                                <div className="flex items-center">
                                    <div className="w-3 h-3 bg-green-500 rounded-full mr-3"></div>
                                    <span className="text-sm text-gray-600 font-medium">{pickupAddress}</span>
                                </div>
                                <div className="flex items-center">
                                    <div className="w-3 h-3 bg-red-500 rounded-full mr-3"></div>
                                    <span className="text-sm text-gray-600 font-medium">{destinationAddress}</span>
                                </div>
                            </div>
                            
                            {/* Information de prise en charge */}
                            <div className="mt-4 pt-3 border-t border-gray-100">
                                <div className="flex items-center text-sm">
                                    <Icons.Clock className="w-4 h-4 text-blue-500 mr-2" />
                                    <span className="text-gray-700 font-medium">
                                        Prise en charge {scheduledDate && scheduledTime ? (
                                            `le ${new Date(scheduledDate).toLocaleDateString('fr-FR')} à ${scheduledTime}`
                                        ) : (
                                            'dès que possible'
                                        )}
                                    </span>
                                </div>
                            </div>
                        </div>

                        {/* Distance estimée */}
                        <div className="flex items-center justify-between py-2">
                            <span className="text-gray-600">Distance:</span>
                            <div className="flex items-center">
                                {loadingDistance ? (
                                    <div className="flex items-center">
                                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-mdriver-orange mr-2"></div>
                                        <span className="font-medium text-gray-500">Calcul...</span>
                                    </div>
                                ) : (
                                    <span className="font-medium">
                                        {tripDistance > 0 ? `${tripDistance.toFixed(1)} km` : '~5 km'}
                                        {tripDuration > 0 && ` (${tripDuration} min)`}
                                    </span>
                                )}
                            </div>
                        </div>
                        
                        {/* Points à gagner */}
                        <div className="flex items-center justify-between py-2">
                            <span className="text-gray-600">Points à gagner:</span>
                            <div className="flex items-center">
                                <Icons.Star className="w-4 h-4 text-yellow-500 mr-1" fill={true} />
                                <span className="font-medium text-green-600">{pointsToEarn} points</span>
                                {tripDistance > 0 && (
                                    <span className="text-xs text-gray-500 ml-1">
                                        ({Math.round(tripDistance)}km × 10pts)
                                    </span>
                                )}
                            </div>
                        </div>
                    </AnimatedCard>
                </div>

                {/* Espacement pour la zone fixe en bas */}
                <div className="h-40"></div>
            </AnimatedView>

            {/* Zone fixe mode de paiement et boutons */}
            <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-lg">
                {/* Mode de paiement */}
                <div className="p-4 border-b border-gray-100">
                    <button 
                        onClick={openPaymentModal}
                        className="w-full flex items-center justify-between p-3 rounded-xl border border-gray-200 hover:border-gray-300 transition-all"
                    >
                        <div className="flex items-center">
                            <Icons.CreditCard className="w-5 h-5 text-gray-600 mr-3" />
                            <div className="text-left">
                                <div className="font-medium text-gray-800">
                                    {paymentMethodText}
                                </div>
                                <div className="text-sm text-gray-500">Paiement</div>
                            </div>
                        </div>
                        <Icons.ChevronRight className="w-5 h-5 text-gray-400" />
                    </button>
                </div>
                
                {/* Boutons d'action */}
                <div className="p-4">
                    <div className="flex space-x-3 max-w-md mx-auto">
                        <AnimatedButton 
                            onClick={navigateToCommander}
                            className="w-[30%] py-3 bg-gray-200 text-gray-800 rounded-xl font-bold hover:bg-gray-300 transition-all text-sm"
                            delay={400}
                        >
                            Retour
                        </AnimatedButton>
                        
                        <AnimatedButton 
                            onClick={startConfirmationProcess}
                            disabled={loading || !selectedPaymentMethod || selectedPaymentMethod.type === 'add_card'}
                            className="w-[70%] py-3 bg-mdriver-orange text-white rounded-xl font-bold disabled:opacity-50 hover:bg-orange-600 transition-all"
                            delay={500}
                        >
                            {loading ? (
                                <div className="flex items-center justify-center">
                                    <div className="spinner mr-2"></div>
                                    Confirmation...
                                </div>
                            ) : (
                                'Confirmer'
                            )}
                        </AnimatedButton>
                    </div>
                </div>
            </div>
            
            {/* Modal de sélection de paiement */}
            {PaymentMethodModal}
            
            {/* Vue de confirmation avec timer */}
            {showConfirmationView && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                    <div className="bg-white rounded-2xl p-8 max-w-md w-full mx-4 text-center">
                        {/* Loader central */}
                        <div className="mb-6">
                            <div className="w-20 h-20 mx-auto mb-4 relative">
                                <div className="absolute inset-0 rounded-full border-4 border-gray-200"></div>
                                <div className="absolute inset-0 rounded-full border-4 border-mdriver-orange border-t-transparent animate-spin"></div>
                                <div className="absolute inset-0 flex items-center justify-center">
                                    <span className="text-lg font-bold text-mdriver-orange">{confirmationTimer}</span>
                                </div>
                            </div>
                        </div>
                        
                        {/* Titre */}
                        <h2 className="text-2xl font-bold text-gray-800 mb-2">En cours de confirmation</h2>
                        
                        {/* Message */}
                        <p className="text-gray-600 mb-2">
                            Votre course sera automatiquement confirmée dans {confirmationTimer} seconde{confirmationTimer > 1 ? 's' : ''}
                        </p>
                        
                        {/* Information du trajet */}
                        <div className="bg-gray-50 rounded-xl p-4 mb-6 text-left">
                            <div className="flex items-center mb-2">
                                <div className="w-3 h-3 bg-green-500 rounded-full mr-3"></div>
                                <span className="text-sm text-gray-700 font-medium">{pickupAddress}</span>
                            </div>
                            <div className="flex items-center mb-2">
                                <div className="w-3 h-3 bg-red-500 rounded-full mr-3"></div>
                                <span className="text-sm text-gray-700 font-medium">{destinationAddress}</span>
                            </div>
                            <div className="border-t border-gray-200 pt-2 mt-2">
                                <div className="flex justify-between items-center">
                                    <span className="text-sm text-gray-600">Véhicule:</span>
                                    <span className="text-sm font-medium">{vehicleData.name}</span>
                                </div>
                                <div className="flex justify-between items-center">
                                    <span className="text-sm text-gray-600">Total:</span>
                                    <span className="text-sm font-bold text-mdriver-orange">{finalPrice.toFixed(2)} CHF</span>
                                </div>
                            </div>
                        </div>
                        
                        {/* Boutons */}
                        <div className="flex space-x-3">
                            <button 
                                onClick={cancelConfirmation}
                                className="flex-1 py-3 px-4 bg-gray-100 text-gray-700 rounded-xl font-medium hover:bg-gray-200 transition-all"
                                disabled={loading}
                            >
                                Annuler
                            </button>
                            <button 
                                onClick={confirmImmediately}
                                className="flex-1 py-3 px-4 bg-mdriver-orange text-white rounded-xl font-bold hover:bg-orange-600 transition-all disabled:opacity-50"
                                disabled={loading}
                            >
                                {loading ? (
                                    <div className="flex items-center justify-center">
                                        <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
                                        Confirmation...
                                    </div>
                                ) : (
                                    'Je confirme'
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

// ==================== CHAT MODAL COMPONENT ====================
const ChatModal = ({ jobHash, driverName, onClose }) => {
    const [messages, setMessages] = useState([]);
    const [newMessage, setNewMessage] = useState('');
    const [loading, setLoading] = useState(true);
    const [sending, setSending] = useState(false);
    const [quickMessages, setQuickMessages] = useState([]);
    const messagesEndRef = useRef(null);
    const pollInterval = useRef(null);

    useEffect(() => {
        loadMessages();
        loadQuickMessages();
        
        // Poll for new messages every 3 seconds
        pollInterval.current = setInterval(loadMessages, 3000);
        
        return () => {
            if (pollInterval.current) {
                clearInterval(pollInterval.current);
            }
        };
    }, [jobHash]);

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    const loadMessages = async () => {
        try {
            const result = await chatApi.getMessages(jobHash);
            if (result.success) {
                setMessages(result.data?.messages || []);
                chatApi.markAsRead(jobHash);
            }
        } catch (e) {
            console.error('Error loading messages:', e);
        } finally {
            setLoading(false);
        }
    };

    const loadQuickMessages = async () => {
        try {
            const result = await chatApi.getQuickMessages();
            if (result.success) {
                setQuickMessages(result.data?.quick_messages || []);
            }
        } catch (e) {
            console.error('Error loading quick messages:', e);
        }
    };

    const sendMessage = async (text = newMessage) => {
        if (!text.trim()) return;
        
        setSending(true);
        try {
            const result = await chatApi.sendMessage(jobHash, text.trim());
            if (result.success) {
                setNewMessage('');
                loadMessages();
            }
        } catch (e) {
            console.error('Error sending message:', e);
        } finally {
            setSending(false);
        }
    };

    const handleQuickMessage = (msg) => {
        sendMessage(msg.message);
    };

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

    return (
        <div className="fixed inset-0 z-50 flex flex-col bg-gray-100">
            {/* Header */}
            <div className="bg-white shadow-sm px-4 py-3 flex items-center">
                <button 
                    onClick={onClose}
                    className="p-2 -ml-2 text-gray-600 hover:text-gray-800"
                >
                    <Icons.ArrowLeft className="w-6 h-6" />
                </button>
                <div className="ml-3 flex-1">
                    <h3 className="font-semibold text-gray-800">{driverName || 'Chauffeur'}</h3>
                    <p className="text-sm text-gray-500">Discussion en cours</p>
                </div>
            </div>

            {/* Messages */}
            <div className="flex-1 overflow-y-auto p-4 space-y-3">
                {loading ? (
                    <div className="flex justify-center py-8">
                        <Icons.Clock className="w-8 h-8 text-gray-400 animate-spin" />
                    </div>
                ) : messages.length === 0 ? (
                    <div className="text-center py-8 text-gray-500">
                        <Icons.MessageSquare className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                        <p>Aucun message</p>
                        <p className="text-sm">Envoyez un message à votre chauffeur</p>
                    </div>
                ) : (
                    messages.map((msg, idx) => (
                        <div 
                            key={msg.id || idx}
                            className={`flex ${
                                msg.sender_type === 'system' ? 'justify-center' :
                                msg.sender_type === 'client' ? 'justify-end' : 'justify-start'
                            }`}
                        >
                            {msg.sender_type === 'system' ? (
                                <span className="text-xs px-3 py-1 bg-gray-200 text-gray-600 rounded-full">
                                    {msg.message}
                                </span>
                            ) : (
                                <div className={`max-w-[75%] px-4 py-2 rounded-2xl ${
                                    msg.sender_type === 'client' 
                                        ? 'bg-blue-500 text-white rounded-br-md' 
                                        : 'bg-white text-gray-800 rounded-bl-md shadow-sm'
                                }`}>
                                    <div className="text-sm">{msg.message}</div>
                                    <div className={`text-xs mt-1 ${
                                        msg.sender_type === 'client' ? 'text-blue-100' : 'text-gray-400'
                                    }`}>
                                        {formatTime(msg.created_at)}
                                    </div>
                                </div>
                            )}
                        </div>
                    ))
                )}
                <div ref={messagesEndRef} />
            </div>

            {/* Quick Replies */}
            {quickMessages.length > 0 && (
                <div className="bg-white border-t border-gray-200 px-4 py-2 overflow-x-auto">
                    <div className="flex space-x-2">
                        {quickMessages.map((qm, idx) => (
                            <button 
                                key={qm.id || idx}
                                className="whitespace-nowrap px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm rounded-full transition-colors"
                                onClick={() => handleQuickMessage(qm)}
                            >
                                {qm.icon} {qm.title}
                            </button>
                        ))}
                    </div>
                </div>
            )}

            {/* Input */}
            <div className="bg-white border-t border-gray-200 p-4">
                <div className="flex space-x-2">
                    <input
                        type="text"
                        className="flex-1 px-4 py-3 bg-gray-100 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="Écrire un message..."
                        value={newMessage}
                        onChange={(e) => setNewMessage(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                    />
                    <button 
                        className={`p-3 rounded-full transition-colors ${
                            !newMessage.trim() || sending 
                                ? 'bg-gray-200 text-gray-400' 
                                : 'bg-blue-500 text-white hover:bg-blue-600'
                        }`}
                        onClick={() => sendMessage()}
                        disabled={!newMessage.trim() || sending}
                    >
                        {sending ? (
                            <Icons.Clock className="w-5 h-5 animate-spin" />
                        ) : (
                            <Icons.Send className="w-5 h-5" />
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
};

// Ride Confirmed View - Vue course confirmée
const RideConfirmedView = () => {
    const { 
        user, notifications, navigate,
        selectedRideData
    } = useAppContext();
    
    const [rideStatus, setRideStatus] = useState('pending');
    const [statusText, setStatusText] = useState('Un chauffeur va être assigné');
    const [driverInfo, setDriverInfo] = useState(null);
    const [mapLoaded, setMapLoaded] = useState(false);
    const mapRef = useRef(null);
    const mapInstanceRef = useRef(null);
    
    // Refs pour les marqueurs et polyline (pour mise à jour dynamique)
    const markersRef = useRef([]);
    const polylineRef = useRef(null);
    const driverPositionRef = useRef({ lat: 46.5100, lng: 6.6200 }); // Position simulée du chauffeur
    const coordsRef = useRef({ pickup: null, destination: null });
    
    // États pour les tabs
    const [activeTab, setActiveTab] = useState('details');
    
    // État pour le chat
    const [showChat, setShowChat] = useState(false);
    
    // Récupérer les données de la course
    const rideData = selectedRideData || {};
    
    useEffect(() => {
        if (rideData.jobId || rideData.job_hash) {
            const timer = setTimeout(() => {
                initRideMap();
            }, 300);
            startRideUpdates();
            return () => clearTimeout(timer);
        }
    }, [rideData.jobId, rideData.job_hash]);
    
    useEffect(() => {
        if (mapInstanceRef.current && coordsRef.current.pickup) {
            updateMapForStatus(rideStatus);
        }
    }, [rideStatus]);

    const initRideMap = () => {
        if (!window.L) {
            console.warn('Leaflet not loaded, retrying...');
            setTimeout(initRideMap, 500);
            return;
        }
        if (!mapRef.current) {
            console.warn('Map container not ready, retrying...');
            setTimeout(initRideMap, 300);
            return;
        }
        
        try {
            if (mapInstanceRef.current) return;

            const map = L.map(mapRef.current, {
                zoomControl: false,
                attributionControl: false
            }).setView([46.2044, 6.1432], 13);

            L.tileLayer('https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
                maxZoom: 20
            }).addTo(map);

            mapInstanceRef.current = map;
            setMapLoaded(true);

            setTimeout(() => map.invalidateSize(), 200);

            if (rideData.pickup_address || rideData.pickup_latitude) {
                addRideMarkers(map);
            }
        } catch (error) {
            console.error('Map init error:', error);
        }
    };

    const clearMapElements = () => {
        markersRef.current.forEach(m => m.remove());
        markersRef.current = [];
        if (polylineRef.current) { polylineRef.current.remove(); polylineRef.current = null; }
    };

    const createMarker = (map, position, type) => {
        const icons = {
            pickup: '<svg width="12" height="12" viewBox="0 0 24 24" fill="white"><circle cx="12" cy="12" r="5"/></svg>',
            destination: '<svg width="12" height="12" viewBox="0 0 24 24" fill="white"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7z"/></svg>',
            driver: '<svg width="18" height="18" viewBox="0 0 24 24" fill="white"><path d="M18.92 6.01C18.72 5.42 18.16 5 17.5 5h-11c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 16c-.83 0-1.5-.67-1.5-1.5S5.67 13 6.5 13s1.5.67 1.5 1.5S7.33 16 6.5 16zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 11l1.5-4.5h11L19 11H5z"/></svg>',
            client: '<svg width="12" height="12" viewBox="0 0 24 24" fill="white"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>'
        };
        const colors = { pickup: '#10B981', destination: '#EF4444', driver: '#3B82F6', client: '#10B981' };
        const size = type === 'driver' ? 36 : 20;
        const fontSize = type === 'driver' ? 18 : 12;
        const icon = L.divIcon({
            html: `<div style="width:${size}px;height:${size}px;background:${colors[type]};border:3px solid white;border-radius:50%;box-shadow:0 2px 8px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;font-size:${fontSize}px;">${type === 'driver' ? icons[type] : ''}</div>`,
            className: '',
            iconSize: [size, size],
            iconAnchor: [size / 2, size / 2]
        });
        const marker = L.marker([position.lat, position.lng], { icon }).addTo(map);
        markersRef.current.push(marker);
        return marker;
    };

    const updateMapForStatus = async (status) => {
        const map = mapInstanceRef.current;
        if (!map) return;
        
        clearMapElements();
        
        const pickup = coordsRef.current.pickup;
        const destination = coordsRef.current.destination;
        const driverPos = driverPositionRef.current;
        
        const fitPoints = (points) => {
            const bounds = L.latLngBounds(points.map(p => L.latLng(p.lat, p.lng)));
            map.fitBounds(bounds, { padding: [50, 50] });
        };
        
        switch(status) {
            case 'pending':
            case 'dispatching':
            case 'driver_assigned':
                createMarker(map, pickup, 'pickup');
                createMarker(map, destination, 'destination');
                fitPoints([pickup, destination]);
                await drawRideRoute(map, pickup, destination);
                break;
                
            case 'driver_arriving':
                createMarker(map, pickup, 'client');
                createMarker(map, driverPos, 'driver');
                fitPoints([pickup, driverPos]);
                await drawRideRoute(map, driverPos, pickup);
                break;
                
            case 'in_progress':
                createMarker(map, driverPos, 'driver');
                createMarker(map, destination, 'destination');
                fitPoints([driverPos, destination]);
                await drawRideRoute(map, driverPos, destination);
                break;
                
            case 'completed':
                createMarker(map, destination, 'destination');
                map.setView([destination.lat, destination.lng], 15);
                break;
        }
    };

    const addRideMarkers = async (map) => {
        let pickupCoords = null;
        let destinationCoords = null;
        
        const pLat = rideData.pickup_latitude || rideData.pickup_lat;
        const pLng = rideData.pickup_longitude || rideData.pickup_lng;
        const dLat = rideData.destination_latitude || rideData.dest_lat || rideData.dropoff_latitude;
        const dLng = rideData.destination_longitude || rideData.dest_lng || rideData.dropoff_longitude;
        
        if (pLat && pLng) {
            pickupCoords = { lat: parseFloat(pLat), lng: parseFloat(pLng) };
        }
        if (dLat && dLng) {
            destinationCoords = { lat: parseFloat(dLat), lng: parseFloat(dLng) };
        }
        
        if (!pickupCoords && rideData.pickup_address) {
            try { pickupCoords = await geocodeAddress(rideData.pickup_address); } catch (e) { /* ignore */ }
        }
        if (!destinationCoords && rideData.destination_address) {
            try { destinationCoords = await geocodeAddress(rideData.destination_address); } catch (e) { /* ignore */ }
        }
        
        if (!pickupCoords) pickupCoords = { lat: 46.2044, lng: 6.1432 };
        if (!destinationCoords) destinationCoords = { lat: 46.2100, lng: 6.1500 };
        
        // Stocker les coordonnées pour la mise à jour dynamique
        coordsRef.current = { pickup: pickupCoords, destination: destinationCoords };
        
        // Position initiale du chauffeur (près du pickup pour simulation)
        driverPositionRef.current = {
            lat: pickupCoords.lat - 0.008,
            lng: pickupCoords.lng - 0.005
        };

        // Afficher selon le statut initial (pending)
        await updateMapForStatus(rideStatus);
    };

    const geocodeAddress = async (address) => {
        const url = `https://api.maps.swissapp.net/place?address=${encodeURIComponent(address)}&countries=CH,FR&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
        const response = await fetch(url);
        const data = await response.json();
        if (data.code === 1 && data.datas?.predictions?.[0]) {
            const placeId = data.datas.predictions[0].place_id;
            const geoResponse = await fetch(`https://api.maps.swissapp.net/place_geometry?placeId=${placeId}&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`);
            const geoData = await geoResponse.json();
            if (geoData.code === 1 && geoData.datas?.result?.geometry?.location) {
                return { lat: parseFloat(geoData.datas.result.geometry.location.lat), lng: parseFloat(geoData.datas.result.geometry.location.lng) };
            }
        }
        throw new Error('Geocoding failed');
    };

    const drawRideRoute = async (map, origin, destination) => {
        try {
            const apiUrl = `https://api.maps.swissapp.net/directions?origin=${origin.lat},${origin.lng}&destination=${destination.lat},${destination.lng}&mode=driving&api_key=f2a4ab24-1b8e-4b8d-90eb-f7a454135951`;
            
            console.log('🛣️ Calcul de la route avec l\'API SwissApp...');
            const response = await fetch(apiUrl);
            const data = await response.json();
            
            if (data && data.code === 1 && data.result === 'OK' && data.data && data.data.routes && data.data.routes.length > 0) {
                const route = data.data.routes[0];
                let routePath = [];
                
                if (route.overview_polyline && route.overview_polyline.points) {
                    routePath = decodePolyline(route.overview_polyline.points);
                } else if (route.legs && route.legs[0] && route.legs[0].steps) {
                    route.legs[0].steps.forEach(step => {
                        if (step.polyline && step.polyline.points) {
                            routePath = routePath.concat(decodePolyline(step.polyline.points));
                        }
                    });
                }

                if (routePath.length > 0) {
                    const line = L.polyline(routePath, { color: '#FF6B00', weight: 4 }).addTo(map);
                    polylineRef.current = line;
                    console.log('✅ Route tracée avec succès');
                } else {
                    console.warn('⚠️ Aucun chemin trouvé dans la réponse');
                }
            } else {
                console.error('❌ Erreur dans la réponse de l\'API SwissApp:', data);
            }
        } catch (error) {
            console.error('❌ Erreur lors du calcul de la route:', error);
            const line = L.polyline([[origin.lat, origin.lng], [destination.lat, destination.lng]], { color: '#FF6B00', weight: 3, dashArray: '10,5' }).addTo(map);
            polylineRef.current = line;
        }
    };

    // Référence pour l'intervalle de polling
    const pollIntervalRef = useRef(null);
    
    const startRideUpdates = () => {
        // Polling réel de l'API pour suivre le statut de la course
        const pollRideStatus = async () => {
            const jobIdentifier = rideData.job_hash || rideData.jobHash || rideData.jobReference || rideData.job_reference;
            if (!jobIdentifier) {
                console.warn('⚠️ Pas d\'identifiant de course pour le polling');
                return;
            }
            
            try {
                const token = localStorage.getItem('user_token');
                const response = await fetch(`${API_BASE_URL}/jobs/${jobIdentifier}`, {
                    headers: {
                        'Content-Type': 'application/json',
                        ...(token && { 'Authorization': `Bearer ${token}` })
                    }
                });
                
                const result = await response.json();
                
                if (result.success && result.data) {
                    const job = result.data;
                    console.log('🔄 [Polling] Statut course:', job.status);
                    
                    // Mettre à jour le statut
                    setRideStatus(job.status);
                    
                    switch(job.status) {
                        case 'pending':
                        case 'searching':
                        case 'dispatching':
                        case 'sent_to_cordic':
                            setStatusText('Recherche d\'un chauffeur via la centrale...');
                            setDriverInfo(null);
                            break;
                        case 'assigned':
                        case 'accepted':
                        case 'driver_assigned':
                            setStatusText('Chauffeur assigné - En route vers vous');
                            if (job.driver || job.driver_uid) {
                                setDriverInfo({
                                    uid: job.driver?.uid || job.driver_uid,
                                    name: job.driver?.name || job.driver_name || 'Chauffeur',
                                    phone: job.driver?.phone || job.driver_phone,
                                    rating: job.driver?.rating || job.driver_rating || 4.8,
                                    car: job.driver?.vehicle_type || job.vehicle_type || 'Véhicule',
                                    plate: job.driver?.vehicle_plate || job.vehicle_plate || '',
                                    picture: job.driver?.picture
                                });
                            }
                            break;
                        case 'driver_arriving':
                            setStatusText('Le chauffeur arrive...');
                            if (job.driver_latitude && job.driver_longitude) {
                                driverPositionRef.current = {
                                    lat: parseFloat(job.driver_latitude),
                                    lng: parseFloat(job.driver_longitude)
                                };
                            }
                            break;
                        case 'arrived':
                            setStatusText('Le chauffeur est arrivé');
                            break;
                        case 'in_progress':
                            setStatusText('Course en cours');
                            if (job.driver_latitude && job.driver_longitude) {
                                driverPositionRef.current = {
                                    lat: parseFloat(job.driver_latitude),
                                    lng: parseFloat(job.driver_longitude)
                                };
                            }
                            break;
                        case 'awaiting_payment':
                            setStatusText('En attente de paiement');
                            break;
                        case 'completed':
                            setStatusText('Course terminée');
                            if (pollIntervalRef.current) {
                                clearInterval(pollIntervalRef.current);
                            }
                            break;
                        case 'cancelled':
                            setStatusText('Course annulée');
                            if (pollIntervalRef.current) {
                                clearInterval(pollIntervalRef.current);
                            }
                            notifications.error('La course a été annulée');
                            setTimeout(() => navigate('accueil'), 2000);
                            break;
                        default:
                            setStatusText('En attente...');
                    }
                }
            } catch (error) {
                console.error('❌ [Polling] Erreur:', error);
            }
        };
        
        // Premier appel immédiat
        pollRideStatus();
        
        // Puis toutes les 3 secondes
        pollIntervalRef.current = setInterval(pollRideStatus, 3000);
    };
    
    // Nettoyer l'intervalle quand le composant se démonte
    useEffect(() => {
        return () => {
            if (pollIntervalRef.current) {
                clearInterval(pollIntervalRef.current);
            }
        };
    }, []);

    const closeRideView = () => {
        navigate('activite');
    };

    const cancelRide = async () => {
        // Chercher l'identifiant de course disponible
        const jobIdentifier = rideData.job_hash || rideData.jobHash || rideData.jobReference || rideData.job_reference;
        
        console.log('🚫 [Cancel] Données course:', rideData);
        console.log('🚫 [Cancel] Identifiant trouvé:', jobIdentifier);
        
        if (!jobIdentifier) {
            console.error('Aucun identifiant de course trouvé:', rideData);
            notifications.error('Aucune course à annuler - identifiant manquant');
            return;
        }

        // Confirmer l'annulation
        if (!confirm('Êtes-vous sûr de vouloir annuler cette course ?')) {
            return;
        }

        try {
            console.log('🚫 [Cancel] Annulation de la course:', jobIdentifier);
            const token = localStorage.getItem('user_token');
            
            // ✅ Appeler l'endpoint de cancellation dédié
            const response = await fetch(`${API_BASE_URL}/jobs/${jobIdentifier}/cancel`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    ...(token && { 'Authorization': `Bearer ${token}` })
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                notifications.success('Course annulée avec succès');
                navigate('activite');
            } else {
                notifications.error(result.error || result.message || 'Erreur lors de l\'annulation');
            }
        } catch (error) {
            console.error('❌ [Cancel] Erreur:', error);
            notifications.error('Erreur lors de l\'annulation de la course');
        }
    };

    const getStatusColor = () => {
        switch(rideStatus) {
            case 'pending': return 'bg-yellow-500';
            case 'driver_assigned': return 'bg-blue-500';
            case 'driver_arriving': return 'bg-green-500';
            case 'in_progress': return 'bg-purple-500';
            case 'completed': return 'bg-gray-500';
            default: return 'bg-yellow-500';
        }
    };



    return (
        <div className="h-full flex flex-col bg-gray-50">
            {/* Header fixe avec statut */}
            <div className="fixed top-0 left-0 right-0 bg-white shadow-sm border-b border-gray-200 p-4 z-50">
                <div className="flex items-center justify-between">
                    <button 
                        onClick={closeRideView}
                        className="flex items-center justify-center w-10 h-10 rounded-full hover:bg-gray-100"
                    >
                        <Icons.X className="w-6 h-6 text-gray-600" />
                    </button>
                    
                    <div className="text-center">
                        <h1 className="text-lg font-bold text-gray-800">Course confirmée</h1>
                        <div className="flex items-center justify-center mt-1">
                            <div className={`w-2 h-2 rounded-full mr-2 ${getStatusColor()}`}></div>
                            <span className="text-sm text-gray-600">{statusText}</span>
                        </div>
                    </div>
                    
                    <div className="w-10"></div>
                </div>
            </div>

            {/* Carte */}
            <div className="relative" style={{marginTop: '80px', height: '40vh', minHeight: '250px'}}>
                <div ref={mapRef} className="w-full" style={{height: '100%'}}></div>
                
                {!mapLoaded && (
                    <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
                        <div className="text-center">
                            <div className="spinner mx-auto mb-2"></div>
                            <p className="text-gray-600">Chargement de la carte...</p>
                        </div>
                    </div>
                )}
            </div>

            {/* Bottom sheet avec détails */}
            <div className="bg-white rounded-t-3xl shadow-2xl border-t border-gray-200 p-6 space-y-4">
                {/* Statut de la course */}
                <AnimatedCard className="card" delay={100}>
                    <div className="text-center py-2">
                        <div className="flex items-center justify-center mb-2">
                            <div className={`w-3 h-3 rounded-full mr-2 ${getStatusColor()}`}></div>
                            <span className="font-bold text-lg text-gray-800">{statusText}</span>
                        </div>
                        {rideStatus === 'driver_assigned' && (
                            <div className="text-sm text-gray-600">Le chauffeur arrive dans 3 minutes</div>
                        )}
                        {rideStatus === 'pending' && (
                            <div className="text-sm text-gray-600">Recherche d'un chauffeur disponible...</div>
                        )}
                        {rideStatus === 'on_way' && (
                            <div className="text-sm text-gray-600">Votre chauffeur est en route</div>
                        )}
                    </div>
                </AnimatedCard>

                {/* Navigation par tabs */}
                <AnimatedCard className="card" delay={200} style={{padding: '0'}}>
                    <div className="flex space-x-1 bg-gray-100 rounded-lg p-1">
                        <button 
                            onClick={() => setActiveTab('details')}
                            className={`flex-1 py-3 px-3 rounded-md transition-all flex items-center justify-center ${
                                activeTab === 'details' 
                                    ? 'bg-white text-mdriver-orange shadow-sm' 
                                    : 'text-gray-600 hover:text-gray-800'
                            }`}
                            title="Détails de la course"
                        >
                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                        </button>
                        <button 
                            onClick={() => setActiveTab('driver')}
                            className={`flex-1 py-3 px-3 rounded-md transition-all flex items-center justify-center ${
                                activeTab === 'driver' 
                                    ? 'bg-white text-mdriver-orange shadow-sm' 
                                    : 'text-gray-600 hover:text-gray-800'
                            }`}
                            title="Chauffeur"
                        >
                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                            </svg>
                        </button>
                        <button 
                            onClick={() => setActiveTab('payment')}
                            className={`flex-1 py-3 px-3 rounded-md transition-all flex items-center justify-center ${
                                activeTab === 'payment' 
                                    ? 'bg-white text-mdriver-orange shadow-sm' 
                                    : 'text-gray-600 hover:text-gray-800'
                            }`}
                            title="Paiement"
                        >
                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                            </svg>
                        </button>
                    </div>
                </AnimatedCard>

                {/* Contenu des tabs */}
                <AnimatedCard className="card" delay={300}>
                    {/* Tab Détails de la course */}
                    {activeTab === 'details' && (
                        <div className="space-y-4">
                            <h3 className="font-bold text-lg text-gray-800 mb-3">Détails de la course</h3>
                            
                            <div className="space-y-3">
                                {/* Référence */}
                                <div className="flex items-start">
                                    <div className="w-4 h-4 bg-purple-500 rounded-full mr-3 mt-1"></div>
                                    <div className="flex-1 min-w-0">
                                        <div className="text-sm text-gray-500">Référence</div>
                                        <div className="font-medium text-gray-800">{rideData.jobReference || rideData.job_reference || rideData.job_hash || rideData.jobHash || 'N/A'}</div>
                                    </div>
                                </div>

                                {/* Origine */}
                                <div className="flex items-start">
                                    <div className="w-4 h-4 bg-green-500 rounded-full mr-3 mt-1"></div>
                                    <div className="flex-1 min-w-0">
                                        <div className="text-sm text-gray-500">Origine</div>
                                        <div className="font-medium text-gray-800 truncate">{rideData.pickup_address}</div>
                                    </div>
                                </div>
                                
                                {/* Destination */}
                                <div className="flex items-start">
                                    <div className="w-4 h-4 bg-red-500 rounded-full mr-3 mt-1"></div>
                                    <div className="flex-1 min-w-0">
                                        <div className="text-sm text-gray-500">Destination</div>
                                        <div className="font-medium text-gray-800 truncate">{rideData.destination_address}</div>
                                    </div>
                                </div>

                                {/* Véhicule */}
                                <div className="flex items-start">
                                    <div className="w-8 h-8 flex items-center justify-center mr-3">
                                        <VehicleIcon vehicleType={rideData.vehicle?.vehicle_type || 'standard'} className="w-8 h-8" imageUrl={rideData.vehicle?.image_url} />
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <div className="text-sm text-gray-500">Véhicule</div>
                                        <div className="font-medium text-gray-800">{rideData.vehicle?.name || 'Véhicule standard'}</div>
                                        <div className="text-sm text-gray-600">{rideData.vehicle?.capacity || '4'} places</div>
                                    </div>
                                </div>

                                {/* Programmation si applicable */}
                                {rideData.scheduled_date && rideData.scheduled_time && (
                                    <div className="flex items-center bg-blue-50 p-3 rounded-lg">
                                        <Icons.Calendar className="w-5 h-5 text-blue-600 mr-2" />
                                        <div>
                                            <div className="text-sm text-blue-800 font-medium">Course programmée</div>
                                            <div className="text-sm text-blue-600">
                                                {new Date(rideData.scheduled_date).toLocaleDateString('fr-FR')} à {rideData.scheduled_time}
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    )}

                    {/* Tab Chauffeur attribué */}
                    {activeTab === 'driver' && (
                        <div className="space-y-4">
                            <h3 className="font-bold text-lg text-gray-800 mb-3">Chauffeur attribué</h3>
                            
                            {driverInfo ? (
                                <div className="space-y-3">
                                    <div className="flex items-center">
                                        <div className="w-12 h-12 bg-blue-500 rounded-full flex items-center justify-center mr-4">
                                            <Icons.User className="w-6 h-6 text-white" />
                                        </div>
                                        <div className="flex-1">
                                            <div className="font-bold text-gray-800">{driverInfo.name}</div>
                                            <div className="text-sm text-gray-600">Chauffeur professionnel</div>
                                            <div className="flex items-center mt-1">
                                                <Icons.Star className="w-4 h-4 text-yellow-500 mr-1" fill="true" />
                                                <span className="text-sm font-medium">{driverInfo.rating}</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div className="space-y-2">
                                        <div className="flex justify-between">
                                            <span className="text-gray-600">Véhicule:</span>
                                            <span className="font-medium">{driverInfo.car}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-gray-600">Plaque:</span>
                                            <span className="font-medium">{driverInfo.plate}</span>
                                        </div>
                                    </div>
                                    
                                    <div className="flex space-x-3 pt-3">
                                        <button 
                                            onClick={() => {
                                                if (driverInfo?.phone) {
                                                    window.location.href = `tel:${driverInfo.phone}`;
                                                }
                                            }}
                                            disabled={!driverInfo?.phone}
                                            className={`flex-1 py-3 rounded-xl font-medium transition-all flex items-center justify-center ${
                                                driverInfo?.phone 
                                                    ? 'bg-green-500 text-white hover:bg-green-600' 
                                                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                                            }`}
                                        >
                                            <Icons.Smartphone className="w-5 h-5 mr-2" />
                                            Appeler
                                        </button>
                                        <button 
                                            onClick={() => setShowChat(true)}
                                            className="flex-1 py-3 bg-blue-500 text-white rounded-xl font-medium hover:bg-blue-600 transition-all flex items-center justify-center"
                                        >
                                            <Icons.MessageSquare className="w-5 h-5 mr-2" />
                                            Message
                                        </button>
                                    </div>
                                </div>
                            ) : (
                                <div className="text-center py-8">
                                    <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                        <Icons.Clock className="w-8 h-8 text-gray-400" />
                                    </div>
                                    <div className="text-gray-600">Recherche d'un chauffeur en cours...</div>
                                    <div className="text-sm text-gray-500 mt-1">Vous serez notifié dès qu'un chauffeur accepte votre course</div>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Tab Paiement */}
                    {activeTab === 'payment' && (
                        <div className="space-y-4">
                            <h3 className="font-bold text-lg text-gray-800 mb-3">Paiement</h3>
                            
                            <div className="space-y-3">
                                <div className="space-y-2">
                                    <div className="flex justify-between">
                                        <span className="text-gray-600">Prix de base:</span>
                                        <span className="font-medium">{rideData.estimated_price} CHF</span>
                                    </div>
                                    <div className="flex justify-between">
                                        <span className="text-gray-600">Frais administratifs (20%):</span>
                                        <span className="font-medium">{(parseFloat(rideData.estimated_price || 0) * 0.2).toFixed(2)} CHF</span>
                                    </div>
                                    {rideData.points_discount && rideData.points_discount > 0 && (
                                        <div className="flex justify-between text-green-600">
                                            <span>Réduction (points):</span>
                                            <span className="font-medium">-{rideData.points_discount} CHF</span>
                                        </div>
                                    )}
                                </div>
                                
                                <div className="border-t border-gray-200 pt-3">
                                    <div className="flex justify-between items-center">
                                        <span className="text-gray-600 font-bold">Montant total:</span>
                                        <span className="font-bold text-mdriver-orange">{rideData.finalPrice} CHF</span>
                                    </div>
                                </div>
                                
                                <div className="border-t border-gray-200 pt-3">
                                    <div className="flex items-center">
                                        <Icons.CreditCard className="w-5 h-5 text-gray-500 mr-3" />
                                        <div className="flex-1">
                                            <div className="text-sm text-gray-500">Méthode de paiement</div>
                                            <div className="font-medium">{rideData.payment_method_name || 'Carte de crédit'}</div>
                                        </div>
                                        <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                                            <Icons.Check className="w-5 h-5 text-green-600" />
                                        </div>
                                    </div>
                                </div>
                                
                                <div className="bg-green-50 border border-green-200 rounded-lg p-3 mt-4">
                                    <div className="flex items-center">
                                        <Icons.Shield className="w-5 h-5 text-green-600 mr-2" />
                                        <div className="text-sm text-green-800">
                                            <div className="font-medium">Paiement sécurisé</div>
                                            <div>Le montant sera débité à la fin de votre course</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}
                </AnimatedCard>

                {/* Espacement pour le bouton fixe */}
                <div className="h-16"></div>
            </div>

            {/* Bouton d'annulation fixe en bas */}
            <div className="fixed bottom-0 left-0 right-0 p-4 bg-white border-t border-gray-200 shadow-lg">
                <div className="max-w-md mx-auto">
                    <AnimatedButton 
                        onClick={cancelRide}
                        className="w-full py-3 bg-red-500 text-white rounded-xl font-bold hover:bg-red-600 transition-all"
                        delay={300}
                    >
                        Annuler la course
                    </AnimatedButton>
                </div>
            </div>

            {/* Chat Modal */}
            {showChat && (
                <ChatModal
                    jobHash={rideData.job_hash || rideData.jobHash || rideData.jobReference || rideData.job_reference}
                    driverName={driverInfo?.name || 'Chauffeur'}
                    onClose={() => setShowChat(false)}
                />
            )}
        </div>
    );
};

// Points History View - Vue historique des points
const PointsHistoryView = () => {
    const { t } = useTranslation(); // ✅ Ajouter pour éviter l'erreur "t is not defined"
    const { user, userPoints, notifications } = useAppContext();
    const [pointsHistory, setPointsHistory] = useState([]);
    const [loading, setLoading] = useState(true);
    const [pointsConfig, setPointsConfig] = useState({ points_per_km: 10, signup_bonus_points: 50, points_per_ride: 100 });

    useEffect(() => {
        loadPointsConfig();
        if (user?.userUid) {
            loadPointsHistory();
        }
    }, [user?.userUid]);

    const loadPointsConfig = async () => {
        try {
            const response = await fetch(`${API_BASE_URL}/settings/loyalty`);
            const result = await response.json();
            if (result.success && result.data) {
                setPointsConfig(result.data);
            }
        } catch (error) {
            console.log('Config points par défaut utilisée');
        }
    };

    const loadPointsHistory = async () => {
        if (!user?.userUid) return;
        
        setLoading(true);
        try {
            const token = localStorage.getItem('user_token');
            const response = await fetch(`${API_BASE_URL}/points/my/history`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            const result = await response.json();
            
            if (result.success && result.data) {
                setPointsHistory(result.data.history || []);
            }
        } catch (error) {
            console.error('Erreur chargement historique points:', error);
            notifications.error('Erreur lors du chargement de l\'historique');
        } finally {
            setLoading(false);
        }
    };

    const getPointsIcon = (type) => {
        switch (type) {
            case 'earned': return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle'}}><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/></svg>;
            case 'redeemed': return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle'}}><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"/></svg>;
            case 'bonus': return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle'}}><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>;
            default: return <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{display:'inline',verticalAlign:'middle'}}><circle cx="12" cy="12" r="6"/></svg>;
        }
    };

    const getPointsColor = (type) => {
        switch (type) {
            case 'earned': return 'text-green-600';
            case 'redeemed': return 'text-red-600';
            case 'bonus': return 'text-yellow-600';
            default: return 'text-gray-600';
        }
    };

    return (
        <AnimatedView className="h-full flex flex-col bg-gray-50" animationType="fade-in">
            <Header title={t('points.title')} showBackButton={true} />
            
            <div className="flex-1 px-6 py-6 space-y-6">
                {/* Solde actuel */}
                <AnimatedCard className="card bg-gradient-to-r from-yellow-400 to-orange-500 text-white" delay={100}>
                    <div className="text-center">
                        <div className="text-4xl font-bold mb-2">{userPoints}</div>
                        <div className="text-lg opacity-90">Points disponibles</div>
                        <div className="text-sm opacity-75 mt-2">
                            {Math.floor(userPoints / 1000)} x 5CHF disponibles
                        </div>
                    </div>
                </AnimatedCard>

                {/* Informations */}
                <AnimatedCard className="card bg-blue-50 border-blue-200" delay={200}>
                    <div className="space-y-2">
                        <h3 className="font-semibold text-gray-800 flex items-center">
                            <Icons.Star className="w-5 h-5 mr-2 text-yellow-500" />
                            Comment ça fonctionne
                        </h3>
                        <div className="text-sm text-gray-700 space-y-1">
                            <p>• <strong>{pointsConfig.signup_bonus_points || 50} points</strong> offerts à l'inscription</p>
                            <p>• <strong>{pointsConfig.points_per_ride || 100} points</strong> par course terminée</p>
                            <p>• <strong>{pointsConfig.points_per_km || 10} points</strong> pour chaque km parcouru</p>
                            <p>• 1000 points = 5 CHF de réduction</p>
                            <p>• Réduction automatique lors du paiement</p>
                        </div>
                    </div>
                </AnimatedCard>

                {/* Historique */}
                <div className="space-y-3">
                    <h3 className="text-lg font-semibold text-gray-800">Historique</h3>
                    
                    {loading ? (
                        <div className="text-center py-8">
                            <div className="spinner mx-auto mb-4"></div>
                            <p className="text-gray-600">Chargement...</p>
                        </div>
                    ) : pointsHistory.length === 0 ? (
                        <AnimatedCard className="card text-center" delay={300}>
                            <div className="py-8">
                                <Icons.Star className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                                <h3 className="text-lg font-semibold mb-2 text-gray-800">Aucun historique</h3>
                                <p className="text-gray-600">Effectuez votre première course pour commencer à gagner des points !</p>
                            </div>
                        </AnimatedCard>
                    ) : (
                        <div className="space-y-3">
                            {pointsHistory.map((entry, index) => (
                                <AnimatedCard 
                                    key={entry.id || index}
                                    className="card"
                                    delay={300 + (index * 50)}
                                >
                                    <div className="flex items-center justify-between">
                                        <div className="flex items-center space-x-3">
                                            <div className={`w-10 h-10 rounded-full flex items-center justify-center bg-gray-100 ${getPointsColor(entry.type)}`}>
                                                <span className="text-lg">{getPointsIcon(entry.type)}</span>
                                            </div>
                                            <div>
                                                <div className="font-medium text-gray-800">{entry.reason || entry.description || 'Points'}</div>
                                                <div className="text-sm text-gray-500">{formatDateLocal(entry.created_at) || entry.date}</div>
                                            </div>
                                        </div>
                                        <div className={`text-lg font-semibold ${getPointsColor(entry.type)}`}>
                                            {entry.type === 'spent' || entry.type === 'redeemed' ? '-' : '+'}{Math.abs(entry.points)}
                                        </div>
                                    </div>
                                </AnimatedCard>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </AnimatedView>
    );
};

// Bottom Navigation avec animations
const BottomNavigation = () => {
    const { currentView, navigate } = useAppContext();
    const { t } = useTranslation();

    const navItems = [
        { key: 'welcome', path: 'welcome', icon: 'Home', label: t('navigation.home') },
        { key: 'commander', path: 'commander', icon: 'Zap', label: t('navigation.order') },
        { key: 'activite', path: 'activite', icon: 'ClipboardList', label: t('navigation.activity') },
        { key: 'compte', path: 'compte', icon: 'User', label: t('navigation.account') }
    ];

    return (
        <nav className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-2 py-1 backdrop-blur-sm bg-white/95">
            <div className="flex justify-around">
                {navItems.map((item, index) => {
                    const isActive = currentView === item.path;
                    return (
                        <button
                            key={item.key}
                            onClick={() => navigate(item.path)}
                            className={`nav-item flex flex-col items-center justify-center py-2 px-4 rounded-lg transition-all duration-300 ${
                                isActive 
                                    ? 'active transform scale-105' 
                                    : 'text-gray-500 hover:text-gray-700 hover:scale-105'
                            }`}
                            style={{ animationDelay: `${index * 100}ms` }}
                        >
                            <div className={`mb-1 transition-all duration-300 ${
                                isActive ? 'transform scale-110' : 'hover:scale-110'
                            }`}>
                                {React.createElement(Icons[item.icon], {
                                    className: "w-6 h-6",
                                    fill: isActive
                                })}
                            </div>
                            <span className="text-xs font-medium">{item.label}</span>
                        </button>
                    );
                })}
            </div>
        </nav>
    );
};

// App Principal
const App = () => {
    const { currentView, selectedRideData } = useAppContext();

    return (
        <div className="h-screen w-full flex flex-col font-sans bg-gray-50">
            {/* Notification de message */}
            <MessageNotificationToast />
            
            <div className="flex-1 pb-16">
                {currentView === 'welcome' && <WelcomeView />}
                {currentView === 'commander' && <CommanderView />}
                {currentView === 'vehicle-selection' && <VehicleSelectionView />}
                {currentView === 'activite' && <ActiviteView />}
                {currentView === 'compte' && <CompteView />}
                {currentView === 'settings' && <SettingsView />}
                {currentView === 'payment-methods' && <PaymentMethodsView />}
                {currentView === 'email-settings' && <EmailSettingsView />}
                {currentView === 'phone-settings' && <PhoneSettingsView />}
                {currentView === 'ride-details' && <RideDetailsView rideData={selectedRideData} />}
                {currentView === 'help' && <HelpView />}
                {currentView === 'points-history' && <PointsHistoryView />}
                {currentView === 'order-summary' && <OrderSummaryView />}
                {currentView === 'ride-confirmed' && <RideConfirmedView />}
                {currentView === 'active-ride-details' && <ActiveRideDetailsView />}
                {currentView === 'pools' && <PoolsView />}
                {currentView === 'pool-detail' && <PoolDetailView />}
            </div>
            {!['ride-details', 'help', 'points-history', 'settings', 'payment-methods', 'email-settings', 'phone-settings', 'vehicle-selection', 'order-summary', 'ride-confirmed', 'active-ride-details', 'pools', 'pool-detail'].includes(currentView) && <BottomNavigation />}
            
            {/* Modales */}
            <AuthModal />
            <FirstnameModal />
            <AddressSearchModal />
            <VehicleSelectionModal />
        </div>
    );
};

// App avec Provider
const AppWithProvider = () => (
    <LanguageProvider>
        <AppProvider>
            <App />
        </AppProvider>
    </LanguageProvider>
);

// Monter l'application
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<AppWithProvider />);
