/**
 * TaxiBook - Site Principal
 * Application React pour la réservation de taxi
 */

const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;
const { LANGUAGES, LOCALE_FOR_LANG, detectBrowserLanguage, t: i18nTranslate } = window.TBSi18n;

function applyWidgetBranding(cfg) {
    if (!cfg) return;
    const style = document.createElement('style');
    style.id = 'widget-branding';
    const rules = [];

    if (cfg.primary_color) {
        rules.push(`.btn-primary, .booking-form button[type="submit"] { background: ${cfg.button_bg || cfg.primary_color} !important; color: ${cfg.button_text || '#fff'} !important; }`);
        rules.push(`.booking-title span { color: ${cfg.accent_color || cfg.primary_color} !important; }`);
    }
    if (cfg.accent_color) {
        rules.push(`.navbar { border-bottom-color: ${cfg.accent_color} !important; }`);
    }
    if (cfg.button_bg) {
        rules.push(`.btn-success, .modal-footer .btn-primary { background: ${cfg.button_bg} !important; color: ${cfg.button_text || '#fff'} !important; }`);
    }
    if (cfg.font_family) {
        rules.push(`* { font-family: '${cfg.font_family}', sans-serif !important; }`);
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(cfg.font_family)}:wght@400;500;600;700&display=swap`;
        document.head.appendChild(link);
    }
    if (cfg.custom_css) {
        rules.push(cfg.custom_css);
    }

    if (rules.length > 0) {
        style.textContent = rules.join('\n');
        document.head.appendChild(style);
    }
}

// ============================================================
// CONTEXTES
// ============================================================

const AuthContext = createContext(null);
const ToastContext = createContext(null);
const WidgetContext = createContext(null);
const LanguageContext = createContext({ lang: 'en', setLang: () => {}, t: (k) => k });

const useAuth = () => useContext(AuthContext);
const useToast = () => useContext(ToastContext);
const useWidget = () => useContext(WidgetContext);
const useTranslation = () => useContext(LanguageContext);

function LanguageProvider({ children }) {
    const [lang, setLangState] = useState(() => detectBrowserLanguage());

    useEffect(() => {
        document.documentElement.lang = lang;
        document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
        try {
            const meta = document.querySelector('meta[name="description"]');
            if (meta) meta.setAttribute('content', i18nTranslate(lang, 'doc_meta_description'));
        } catch (e) {}
    }, [lang]);

    const setLang = (newLang) => {
        if (!window.TBSi18n.TRANSLATIONS[newLang]) return;
        setLangState(newLang);
        try {
            localStorage.setItem('site_language', newLang);
            localStorage.setItem('partner_language', newLang);
        } catch (e) {}
    };

    const t = (key, vars) => i18nTranslate(lang, key, vars);
    return <LanguageContext.Provider value={{ lang, setLang, t }}>{children}</LanguageContext.Provider>;
}

// ============================================================
// COMPOSANTS UTILITAIRES
// ============================================================

const Spinner = ({ size = 'md', className = '' }) => (
    <div className={`spinner ${size === 'lg' ? 'spinner-lg' : ''} ${className}`}></div>
);

const Toast = ({ message, type = 'info', onClose }) => {
    useEffect(() => {
        const timer = setTimeout(onClose, 4000);
        return () => clearTimeout(timer);
    }, [onClose]);
    
    return (
        <div className={`toast ${type}`}>
            <i className={`fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'}`}></i>
            <span>{message}</span>
        </div>
    );
};

const ToastContainer = ({ toasts, removeToast }) => (
    <div className="toast-container">
        {toasts.map((toast) => (
            <Toast key={toast.id} {...toast} onClose={() => removeToast(toast.id)} />
        ))}
    </div>
);

// ============================================================
// COMPOSANT NAVBAR
// ============================================================

const LEGAL_LINKS = [
    {
        href: 'https://silgeneve.ch/legis/index.aspx',
        labelKey: 'nav_legal_sil',
        icon: 'fa-gavel'
    },
    {
        href: 'https://www.ge.ch/pratiquer-transport-personnes-taxi-vtc/obtenir-diplome-chauffeur-taxi-vtc',
        labelKey: 'nav_legal_diploma',
        icon: 'fa-id-card'
    }
];

const Navbar = ({ user, onLogin, onLogout, onNavigate, branding }) => {
    const { t, lang, setLang } = useTranslation();
    const [showDropdown, setShowDropdown] = useState(false);
    const [showLegal, setShowLegal] = useState(false);
    const [showMobile, setShowMobile] = useState(false);
    const dropdownRef = useRef(null);
    const legalRef = useRef(null);
    
    useEffect(() => {
        const handleClickOutside = (e) => {
            if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
                setShowDropdown(false);
            }
            if (legalRef.current && !legalRef.current.contains(e.target)) {
                setShowLegal(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);
    
    const nav = (page) => {
        onNavigate(page);
        setShowDropdown(false);
        setShowLegal(false);
        setShowMobile(false);
    };
    
    return (
        <>
            <nav className="navbar">
                <a href="#" className="navbar-logo" onClick={(e) => { e.preventDefault(); nav('home'); }}>
                    {branding?.logo_url ? (
                        <img src={branding.logo_url} alt={branding?.display_name || t('nav_brand_fallback')} style={{ height: 36, maxWidth: 180, objectFit: 'contain' }} />
                    ) : (
                        <span>{branding?.display_name || t('nav_brand_fallback')}</span>
                    )}
                </a>
                
                <div className="navbar-links">
                    <a href="#" onClick={(e) => { e.preventDefault(); nav('home'); }}>{t('nav_home')}</a>
                    <a href="#" onClick={(e) => { e.preventDefault(); nav('services'); }}>{t('nav_services')}</a>
                    <a href="#" onClick={(e) => { e.preventDefault(); nav('driver'); }}>{t('nav_driver')}</a>
                    <a href="#" onClick={(e) => { e.preventDefault(); nav('contact'); }}>{t('nav_contact')}</a>
                    <div className="navbar-dropdown" ref={legalRef}>
                        <button
                            type="button"
                            className="navbar-dropdown-trigger"
                            onClick={() => setShowLegal(!showLegal)}
                            aria-expanded={showLegal}
                        >
                            {t('nav_legal')} <i className={`fas fa-chevron-${showLegal ? 'up' : 'down'}`} style={{ fontSize: '0.7rem' }}></i>
                        </button>
                        {showLegal && (
                            <div className="navbar-dropdown-menu">
                                {LEGAL_LINKS.map((link) => (
                                    <a key={link.href} href={link.href} target="_blank" rel="noopener noreferrer" onClick={() => setShowLegal(false)}>
                                        <i className={`fas ${link.icon}`}></i>
                                        <span>{t(link.labelKey)}</span>
                                    </a>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
                
                <div className="navbar-actions">
                    <select className="navbar-lang-select" value={lang} onChange={e=>setLang(e.target.value)} aria-label={t('language')}>
                        {LANGUAGES.map(l => <option key={l.code} value={l.code}>{l.native}</option>)}
                    </select>
                    <button
                        type="button"
                        className="navbar-burger"
                        aria-label={t('nav_menu_aria')}
                        onClick={() => setShowMobile(!showMobile)}
                    >
                        <i className={`fas fa-${showMobile ? 'times' : 'bars'}`}></i>
                    </button>
                    {user ? (
                        <div className="user-menu-trigger" onClick={() => setShowDropdown(!showDropdown)} ref={dropdownRef}>
                            <div className="user-avatar">
                                {(user.first_name || user.phone_number || 'U')[0].toUpperCase()}
                            </div>
                            <span className="user-name">{user.first_name || t('nav_account_fallback')}</span>
                            <i className="fas fa-chevron-down" style={{ color: 'var(--text-muted)', fontSize: '0.8rem' }}></i>
                            
                            {showDropdown && (
                                <div className="user-dropdown">
                                    <div className="user-dropdown-item" onClick={(e) => { e.stopPropagation(); nav('bookings'); }}>
                                        <i className="fas fa-history"></i>
                                        <span>{t('nav_my_bookings')}</span>
                                    </div>
                                    <div className="user-dropdown-item" onClick={(e) => { e.stopPropagation(); nav('payments'); }}>
                                        <i className="fas fa-credit-card"></i>
                                        <span>{t('nav_payment_methods')}</span>
                                    </div>
                                    <div className="user-dropdown-item" onClick={(e) => { e.stopPropagation(); nav('profile'); }}>
                                        <i className="fas fa-user"></i>
                                        <span>{t('nav_my_profile')}</span>
                                    </div>
                                    <div className="user-dropdown-divider"></div>
                                    <div className="user-dropdown-item danger" onClick={(e) => { e.stopPropagation(); onLogout(); setShowDropdown(false); }}>
                                        <i className="fas fa-sign-out-alt"></i>
                                        <span>{t('nav_logout')}</span>
                                    </div>
                                </div>
                            )}
                        </div>
                    ) : (
                        <>
                            <button className="btn btn-ghost" onClick={onLogin}>
                                {t('nav_login')}
                            </button>
                            <button className="btn btn-primary" onClick={onLogin}>
                                {t('nav_signup')}
                            </button>
                        </>
                    )}
                </div>
            </nav>
            <div className={`navbar-mobile${showMobile ? ' open' : ''}`}>
                <a href="#" onClick={(e) => { e.preventDefault(); nav('home'); }}>{t('nav_home')}</a>
                <a href="#" onClick={(e) => { e.preventDefault(); nav('services'); }}>{t('nav_services')}</a>
                <a href="#" onClick={(e) => { e.preventDefault(); nav('driver'); }}>{t('nav_driver')}</a>
                <a href="#" onClick={(e) => { e.preventDefault(); nav('contact'); }}>{t('nav_contact')}</a>
                <div className="nav-mobile-group">
                    <div className="nav-mobile-label">{t('nav_legal')}</div>
                    {LEGAL_LINKS.map((link) => (
                        <a key={link.href} href={link.href} target="_blank" rel="noopener noreferrer" onClick={() => setShowMobile(false)}>
                            <i className={`fas ${link.icon}`}></i>
                            <span>{t(link.labelKey)}</span>
                        </a>
                    ))}
                </div>
            </div>
        </>
    );
};

// ============================================================
// COMPOSANT ADDRESS AUTOCOMPLETE
// ============================================================

const AddressAutocomplete = React.forwardRef(({ value, onChange, onSelect, placeholder, type, disabled, onPlaceSelected }, ref) => {
    const [query, setQuery] = useState(value?.address || '');
    const [suggestions, setSuggestions] = useState([]);
    const [showSuggestions, setShowSuggestions] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const inputRef = useRef(null);
    const wrapperRef = useRef(null);
    const debounceRef = useRef(null);
    
    useEffect(() => {
        setQuery(value?.address || '');
    }, [value?.address]);
    
    useEffect(() => {
        const handleClickOutside = (e) => {
            if (wrapperRef.current && !wrapperRef.current.contains(e.target)) {
                setShowSuggestions(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);
    
    const searchAddress = async (q) => {
        if (q.length < 3) {
            setSuggestions([]);
            setShowSuggestions(false);
            return;
        }
        
        setIsLoading(true);
        try {
            console.log('🔎 Searching for:', q);
            const result = await window.taxiBookAPI.autocomplete(q);
            console.log('📦 Autocomplete result:', result);
            
            if (result.success && result.predictions && result.predictions.length > 0) {
                const mappedSuggestions = result.predictions.map(p => ({
                    id: p.place_id,
                    placeId: p.place_id,
                    name: p.structured_formatting?.main_text || p.description,
                    address: p.description,
                    secondary: p.structured_formatting?.secondary_text || ''
                }));
                console.log('✅ Mapped suggestions:', mappedSuggestions);
                setSuggestions(mappedSuggestions);
                setShowSuggestions(true);
            } else {
                console.log('⚠️ No suggestions to display');
                setSuggestions([]);
                setShowSuggestions(false);
            }
        } catch (error) {
            console.error('❌ Autocomplete error:', error);
            setSuggestions([]);
            setShowSuggestions(false);
        } finally {
            setIsLoading(false);
        }
    };
    
    const handleChange = (e) => {
        const val = e.target.value;
        setQuery(val);
        onChange({ address: val, latitude: null, longitude: null, postcode: null });
        
        if (debounceRef.current) clearTimeout(debounceRef.current);
        
        debounceRef.current = setTimeout(() => {
            searchAddress(val);
        }, 400);
    };
    
    const handleSelect = async (suggestion) => {
        setQuery(suggestion.address);
        setShowSuggestions(false);
        setIsLoading(true);
        
        const details = await window.taxiBookAPI.getPlaceDetails(suggestion.placeId, suggestion.address);
        setIsLoading(false);
        
        if (details.success) {
            onSelect({
                address: details.address,
                latitude: details.lat,
                longitude: details.lng,
                postcode: details.postcode || null
            });
        } else {
            onSelect({ address: suggestion.address, latitude: null, longitude: null, postcode: null });
        }
        if (onPlaceSelected) onPlaceSelected();
    };

    React.useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus() }));

    const postcode = value?.postcode || null;
    
    return (
        <div className="form-group" ref={wrapperRef}>
            <div className={`input-wrapper ${type}`}>
                <i className={`input-icon fas ${type === 'origin' ? 'fa-circle' : 'fa-map-marker-alt'}`}></i>
                <input
                    ref={inputRef}
                    type="text"
                    className={postcode ? 'has-postcode' : ''}
                    value={query}
                    onChange={handleChange}
                    onFocus={() => suggestions.length > 0 && setShowSuggestions(true)}
                    placeholder={placeholder}
                    disabled={disabled}
                    autoComplete="off"
                />
                {postcode && (
                    <span className="postcode-badge">
                        <i className="fas fa-map-pin" style={{ fontSize: 9 }}></i>
                        {postcode}
                    </span>
                )}
                {isLoading && <Spinner size="sm" />}
            </div>
            
            {showSuggestions && suggestions.length > 0 && (
                <div className="suggestions-dropdown">
                    {suggestions.map((s) => (
                        <div key={s.id} className="suggestion-item" onClick={() => handleSelect(s)}>
                            <div className="suggestion-main">{s.name}</div>
                            <div className="suggestion-secondary">{s.secondary}</div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
});

// ============================================================
// COMPOSANT MAP (Leaflet + Google Tiles)
// ============================================================

const MapComponent = ({ origin, destination, route }) => {
    const { t } = useTranslation();
    const mapRef = useRef(null);
    const mapInstanceRef = useRef(null);
    const markersRef = useRef([]);
    const routeLayerRef = useRef(null);
    const routeBadgeRef = useRef(null);
    const routeCacheRef = useRef(null);
    const tRef = useRef(t);
    tRef.current = t;
    
    useEffect(() => {
        if (!mapInstanceRef.current && mapRef.current) {
            mapInstanceRef.current = L.map(mapRef.current, { zoomControl: true }).setView([46.2044, 6.1432], 12);
            
            L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
                attribution: '© OpenStreetMap © CARTO',
                maxZoom: 20,
                subdomains: 'abcd'
            }).addTo(mapInstanceRef.current);
        }
        
        return () => {
            if (mapInstanceRef.current) {
                mapInstanceRef.current.remove();
                mapInstanceRef.current = null;
            }
        };
    }, []);
    
    useEffect(() => {
        if (!mapInstanceRef.current) return;
        const map = mapInstanceRef.current;
        
        markersRef.current.forEach(m => m.remove());
        markersRef.current = [];
        
        const newCacheKey = (origin?.latitude && origin?.longitude && destination?.latitude && destination?.longitude)
            ? `${origin.latitude},${origin.longitude}-${destination.latitude},${destination.longitude}`
            : null;
        
        const coordsChanged = routeCacheRef.current !== newCacheKey;
        if (coordsChanged) {
            if (routeLayerRef.current) { map.removeLayer(routeLayerRef.current); routeLayerRef.current = null; }
            if (routeBadgeRef.current) { map.removeLayer(routeBadgeRef.current); routeBadgeRef.current = null; }
        }
        
        const bounds = [];
        
        if (origin?.latitude && origin?.longitude) {
            const originIcon = L.divIcon({
                className: 'custom-marker',
                html: '<div style="background: #22c55e; width: 16px; height: 16px; border-radius: 50%; border: 3px solid white; box-shadow: 0 2px 8px rgba(0,0,0,0.3);"></div>',
                iconSize: [16, 16],
                iconAnchor: [8, 8]
            });
            
            const originMarker = L.marker([origin.latitude, origin.longitude], { icon: originIcon })
                .addTo(map);
            markersRef.current.push(originMarker);
            bounds.push([origin.latitude, origin.longitude]);
        }
        
        if (destination?.latitude && destination?.longitude) {
            const destIcon = L.divIcon({
                className: 'custom-marker',
                html: '<div style="background: #ef4444; width: 16px; height: 16px; border-radius: 50%; border: 3px solid white; box-shadow: 0 2px 8px rgba(0,0,0,0.3);"></div>',
                iconSize: [16, 16],
                iconAnchor: [8, 8]
            });
            
            const destMarker = L.marker([destination.latitude, destination.longitude], { icon: destIcon })
                .addTo(map);
            markersRef.current.push(destMarker);
            bounds.push([destination.latitude, destination.longitude]);
        }
        
        if (newCacheKey && coordsChanged) {
            routeCacheRef.current = newCacheKey;
            fetch(`https://router.project-osrm.org/route/v1/driving/${origin.longitude},${origin.latitude};${destination.longitude},${destination.latitude}?overview=full&geometries=geojson`)
                .then(r => r.json())
                .then(data => {
                    if (!data.routes || !data.routes[0]) return;
                    const osrmRoute = data.routes[0];
                    const coords = osrmRoute.geometry.coordinates.map(c => [c[1], c[0]]);
                    const distKm = (osrmRoute.distance / 1000).toFixed(1);
                    const durMin = Math.round(osrmRoute.duration / 60);

                    if (routeLayerRef.current) map.removeLayer(routeLayerRef.current);
                    if (routeBadgeRef.current) map.removeLayer(routeBadgeRef.current);

                    routeLayerRef.current = L.polyline(coords, {
                        color: '#1e293b', weight: 4, opacity: 0.8,
                        dashArray: '8, 6', lineCap: 'round'
                    }).addTo(map);

                    const mid = coords[Math.floor(coords.length / 2)];
                    routeBadgeRef.current = L.marker(mid, {
                        icon: L.divIcon({
                            className: '',
                            html: `<div style="
                                background:#1e293b;color:#fff;padding:5px 12px;border-radius:20px;
                                font-size:11px;font-weight:600;font-family:'Space Grotesk',sans-serif;
                                white-space:nowrap;display:inline-flex;align-items:center;gap:6px;
                                box-shadow:0 2px 8px rgba(0,0,0,0.25);border:2px solid #fff;
                                transform:translate(-50%,-50%);
                            "><i class="fas fa-route" style="font-size:10px"></i>${tRef.current('map_route_badge', { distKm, durMin })}</div>`,
                            iconSize: [0, 0],
                            iconAnchor: [0, 0]
                        }),
                        interactive: false
                    }).addTo(map);
                })
                .catch(() => {});
        } else if (!newCacheKey) {
            routeCacheRef.current = null;
        }
        
        if (bounds.length > 0) {
            if (bounds.length === 1) {
                map.setView(bounds[0], 14);
            } else {
                map.fitBounds(bounds, { padding: [50, 50] });
            }
        }
    }, [origin, destination, route]);
    
    return <div id="map" ref={mapRef}></div>;
};

function decodePolyline(encoded) {
    const points = [];
    let index = 0, lat = 0, lng = 0;
    while (index < encoded.length) {
        let b, shift = 0, result = 0;
        do { b = encoded.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 = encoded.charCodeAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20);
        lng += ((result & 1) ? ~(result >> 1) : (result >> 1));
        points.push([lat / 1e5, lng / 1e5]);
    }
    return points;
}

// ============================================================
// DATE / TIME PICKERS (ULTIME_DESIGN_ELEMENTS)
// ============================================================

function todayStr() {
    const t = new Date();
    return t.getFullYear() + '-' + String(t.getMonth() + 1).padStart(2, '0') + '-' + String(t.getDate()).padStart(2, '0');
}

function getDefaultTime() {
    const now = new Date();
    const m = now.getMinutes();
    let nextQ = Math.ceil((m + 1) / 15) * 15;
    let h = now.getHours();
    if (nextQ >= 60) { h++; nextQ = 0; }
    if (h >= 24) { h = 0; }
    return String(h).padStart(2, '0') + ':' + String(nextQ).padStart(2, '0');
}

function localizedMonthName(lang, monthIndex) {
    try {
        const d = new Date(2000, monthIndex, 1);
        const name = new Intl.DateTimeFormat(lang, { month: 'long' }).format(d);
        return name.charAt(0).toUpperCase() + name.slice(1);
    } catch (e) {
        return ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sep', 'Oct', 'Nov', 'Déc'][monthIndex];
    }
}

function localizedDayShort(lang, dayIndex) {
    try {
        const d = new Date(2024, 0, 1 + dayIndex);
        const name = new Intl.DateTimeFormat(lang, { weekday: 'short' }).format(d).replace(/\.$/, '');
        return name.charAt(0).toUpperCase() + name.slice(1);
    } catch (e) {
        return ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'][dayIndex];
    }
}

const DatePicker = ({ value, onChange, minDate }) => {
    const { lang, t } = useTranslation();
    const locale = LOCALE_FOR_LANG[lang] || lang;
    const [open, setOpen] = useState(false);
    const today = new Date(); today.setHours(0, 0, 0, 0);
    const [viewYear, setViewYear] = useState((value ? new Date(value + 'T00:00:00') : today).getFullYear());
    const [viewMonth, setViewMonth] = useState((value ? new Date(value + 'T00:00:00') : today).getMonth());
    const ref = useRef(null);
    const localMonthNames = Array.from({ length: 12 }, (_, i) => localizedMonthName(locale, i));
    const localDayNames = Array.from({ length: 7 }, (_, i) => localizedDayShort(locale, i));

    useEffect(() => {
        const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, []);

    const minStr = minDate || todayStr();
    const firstDay = new Date(viewYear, viewMonth, 1);
    let startDay = firstDay.getDay() - 1; if (startDay < 0) startDay = 6;
    const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate();
    const cells = [];
    for (let i = 0; i < startDay; i++) cells.push(null);
    for (let d = 1; d <= daysInMonth; d++) cells.push(d);

    const selectDay = (d) => {
        const v = viewYear + '-' + String(viewMonth + 1).padStart(2, '0') + '-' + String(d).padStart(2, '0');
        onChange(v);
        setOpen(false);
    };
    const prevMonth = () => { if (viewMonth === 0) { setViewMonth(11); setViewYear(viewYear - 1); } else setViewMonth(viewMonth - 1); };
    const nextMonth = () => { if (viewMonth === 11) { setViewMonth(0); setViewYear(viewYear + 1); } else setViewMonth(viewMonth + 1); };
    const formatDisplay = (v) => {
        if (!v) return t('datepicker_placeholder');
        const p = v.split('-');
        return p[2] + '/' + p[1] + '/' + p[0];
    };

    const accent = 'var(--color-primary, #FDB813)';
    const accentDark = 'var(--color-primary-dark, #E09400)';
    const todayIso = todayStr();

    return (
        <div ref={ref} style={{ position: 'relative' }}>
            <button type="button" onClick={() => setOpen(!open)}
                style={{ width: '100%', padding: '14px', background: '#fff', border: '2px solid ' + (open ? accent : '#e5e7eb'), borderRadius: 12, textAlign: 'left', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, cursor: 'pointer', fontSize: 14, fontWeight: 600, fontFamily: 'inherit', color: '#1e293b', transition: 'border-color 0.2s' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <i className="fas fa-calendar-alt" style={{ color: accent, fontSize: 14 }}></i>
                    <span style={{ color: value ? '#1e293b' : '#94a3b8', fontWeight: 600 }}>{formatDisplay(value)}</span>
                </span>
                <i className={'fas fa-chevron-' + (open ? 'up' : 'down')} style={{ color: '#cbd5e1', fontSize: 10 }}></i>
            </button>
            {open && (
                <div style={{ position: 'absolute', bottom: '100%', left: 0, marginBottom: 8, width: 360, maxWidth: 'calc(100vw - 32px)', background: '#fff', borderRadius: 16, boxShadow: '0 -10px 40px rgba(0,0,0,0.15)', border: '2px solid #f1f5f9', padding: 16, zIndex: 80 }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                        <button type="button" onClick={prevMonth} style={{ width: 36, height: 36, borderRadius: '50%', border: 'none', background: '#f8fafc', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><i className="fas fa-chevron-left" style={{ color: '#64748b', fontSize: 12 }}></i></button>
                        <span style={{ fontWeight: 700, fontSize: 15, color: '#1e293b' }}>{localMonthNames[viewMonth]} {viewYear}</span>
                        <button type="button" onClick={nextMonth} style={{ width: 36, height: 36, borderRadius: '50%', border: 'none', background: '#f8fafc', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><i className="fas fa-chevron-right" style={{ color: '#64748b', fontSize: 12 }}></i></button>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4, marginBottom: 6 }}>
                        {localDayNames.map((dn, i) => (
                            <div key={i} style={{ height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.5 }}>{dn}</div>
                        ))}
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
                        {cells.map((d, i) => {
                            if (!d) return <div key={'e' + i} style={{ height: 40 }}></div>;
                            const dateStr = viewYear + '-' + String(viewMonth + 1).padStart(2, '0') + '-' + String(d).padStart(2, '0');
                            const isSelected = dateStr === value;
                            const isToday = dateStr === todayIso;
                            const isPast = dateStr < minStr;
                            return (
                                <button key={d} type="button" disabled={isPast} onClick={() => { if (!isPast) selectDay(d); }}
                                    style={{ width: 40, height: 40, borderRadius: 12, border: isToday && !isSelected ? '2px solid ' + accent : '2px solid transparent', background: isSelected ? `linear-gradient(135deg, ${accent}, ${accentDark})` : (isToday ? 'rgba(253,184,19,0.12)' : 'transparent'), color: isSelected ? '#fff' : (isPast ? '#cbd5e1' : '#1e293b'), fontSize: 14, fontWeight: isSelected || isToday ? 700 : 500, cursor: isPast ? 'not-allowed' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto', transition: 'all 0.15s' }}>
                                    {d}
                                </button>
                            );
                        })}
                    </div>
                </div>
            )}
        </div>
    );
};

const TimePicker = ({ value, onChange, minTime }) => {
    const { t } = useTranslation();
    const [open, setOpen] = useState(false);
    const ref = useRef(null);
    const listRef = useRef(null);

    useEffect(() => {
        if (!value) onChange(getDefaultTime());
    }, []);

    useEffect(() => {
        const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, []);

    useEffect(() => {
        if (open && listRef.current && value) {
            const container = listRef.current;
            const slotsEl = container.children;
            for (let i = 0; i < slotsEl.length; i++) {
                if (slotsEl[i].dataset.slot === value) {
                    const target = slotsEl[i];
                    container.scrollTop = target.offsetTop - (container.clientHeight / 2) + (target.clientHeight / 2);
                    break;
                }
            }
        }
    }, [open]);

    const slots = [];
    for (let hh = 0; hh < 24; hh++) {
        for (let mm = 0; mm < 60; mm += 15) {
            const slot = String(hh).padStart(2, '0') + ':' + String(mm).padStart(2, '0');
            if (minTime && slot < minTime) continue;
            slots.push(slot);
        }
    }

    const accent = 'var(--color-primary, #FDB813)';
    const accentDark = 'var(--color-primary-dark, #E09400)';

    return (
        <div ref={ref} style={{ position: 'relative' }}>
            <button type="button" onClick={() => setOpen(!open)}
                style={{ width: '100%', padding: '14px', background: '#fff', border: '2px solid ' + (open ? accent : '#e5e7eb'), borderRadius: 12, textAlign: 'left', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, cursor: 'pointer', fontSize: 14, fontWeight: 600, fontFamily: 'inherit', color: '#1e293b', transition: 'border-color 0.2s' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <i className="fas fa-clock" style={{ color: accent, fontSize: 14 }}></i>
                    <span style={{ color: value ? '#1e293b' : '#94a3b8', fontWeight: 600 }}>{value || t('timepicker_placeholder')}</span>
                </span>
                <i className={'fas fa-chevron-' + (open ? 'up' : 'down')} style={{ color: '#cbd5e1', fontSize: 10 }}></i>
            </button>
            {open && (
                <div ref={listRef} style={{ position: 'absolute', bottom: '100%', left: 0, right: 0, marginBottom: 8, background: '#fff', borderRadius: 16, boxShadow: '0 -10px 40px rgba(0,0,0,0.15)', border: '2px solid #f1f5f9', zIndex: 80, maxHeight: 240, overflowY: 'auto' }}>
                    {slots.map((slot) => {
                        const isSelected = slot === value;
                        return (
                            <button key={slot} data-slot={slot} type="button" onClick={() => { onChange(slot); setOpen(false); }}
                                style={{ display: 'block', width: '100%', padding: '10px 16px', fontSize: 14, fontWeight: isSelected ? 700 : 400, fontFamily: 'monospace', border: 'none', borderBottom: '1px solid #f1f5f9', background: isSelected ? `linear-gradient(135deg, ${accent}, ${accentDark})` : 'transparent', color: isSelected ? '#fff' : '#1e293b', cursor: 'pointer', textAlign: 'left' }}>
                                {slot}
                            </button>
                        );
                    })}
                </div>
            )}
        </div>
    );
};

// ============================================================
// COMPOSANT BOOKING FORM
// ============================================================

const BookingForm = ({ onSearch, onAddressChange }) => {
    const { t } = useTranslation();
    const [origin, setOrigin] = useState({ address: '', latitude: null, longitude: null });
    const [destination, setDestination] = useState({ address: '', latitude: null, longitude: null });
    const [whenMode, setWhenMode] = useState('now');
    const [selectedDate, setSelectedDate] = useState('');
    const [selectedTime, setSelectedTime] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const destRef = useRef(null);
    
    useEffect(() => {
        if (onAddressChange) {
            onAddressChange(origin, destination);
        }
    }, [origin, destination]);

    const combineDateTime = (d, t) => {
        if (!d || !t) return null;
        return new Date(d + 'T' + t + ':00').toISOString();
    };

    const handleSearch = async () => {
        if (!origin.latitude || !destination.latitude) {
            return;
        }
        
        setIsLoading(true);
        
        try {
            const datetime = whenMode === 'now'
                ? new Date().toISOString()
                : (combineDateTime(selectedDate || todayStr(), selectedTime || getDefaultTime()) || new Date().toISOString());
            await onSearch({
                origin,
                destination,
                datetime
            });
        } finally {
            setIsLoading(false);
        }
    };
    
    return (
        <div className="booking-form">
            <AddressAutocomplete
                value={origin}
                onChange={setOrigin}
                onSelect={setOrigin}
                placeholder={t('booking_placeholder_origin')}
                type="origin"
                onPlaceSelected={() => setTimeout(() => destRef.current?.focus(), 100)}
            />
            
            <AddressAutocomplete
                ref={destRef}
                value={destination}
                onChange={setDestination}
                onSelect={setDestination}
                placeholder={t('booking_placeholder_destination')}
                type="destination"
            />
            
            <div className="date-time-section">
                <label className="section-label">
                    <i className="fas fa-clock"></i>
                    {t('booking_when_label')}
                </label>
                
                <div className="quick-time-buttons" style={{gridTemplateColumns: '1fr 1fr'}}>
                    <button 
                        type="button"
                        className={`quick-time-btn ${whenMode === 'now' ? 'active' : ''}`}
                        onClick={() => setWhenMode('now')}
                    >
                        <i className="fas fa-bolt"></i>
                        {t('booking_when_now')}
                    </button>
                    <button 
                        type="button"
                        className={`quick-time-btn ${whenMode === 'later' ? 'active' : ''}`}
                        onClick={() => {
                            setWhenMode('later');
                            if (!selectedDate) setSelectedDate(todayStr());
                            if (!selectedTime) setSelectedTime(getDefaultTime());
                        }}
                    >
                        <i className="fas fa-calendar-alt"></i>
                        {t('booking_when_later')}
                    </button>
                </div>
                
                {whenMode === 'later' && (
                    <div style={{ marginTop: '0.75rem', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                        <div>
                            <label style={{ fontSize: '0.8rem', fontWeight: 600, color: '#64748b', display: 'block', marginBottom: 6 }}>{t('booking_label_date')}</label>
                            <DatePicker value={selectedDate || todayStr()} onChange={setSelectedDate} minDate={todayStr()} />
                        </div>
                        <div>
                            <label style={{ fontSize: '0.8rem', fontWeight: 600, color: '#64748b', display: 'block', marginBottom: 6 }}>{t('booking_label_time')}</label>
                            <TimePicker
                                value={selectedTime || getDefaultTime()}
                                onChange={setSelectedTime}
                                minTime={selectedDate === todayStr() ? getDefaultTime() : null}
                            />
                        </div>
                    </div>
                )}
            </div>
            
            <button 
                className="btn btn-primary btn-lg search-button"
                onClick={handleSearch}
                disabled={!origin.latitude || !destination.latitude || isLoading}
            >
                {isLoading ? <Spinner /> : (
                    <>
                        <i className="fas fa-search"></i>
                        {t('booking_see_prices')}
                    </>
                )}
            </button>
        </div>
    );
};

// ============================================================
// COMPOSANT BOOKING MODAL (Multi-étapes)
// ============================================================

const getBookingOptions = (t) => [
    { id: 'babyseat', name: t('option_babyseat_name'), desc: t('option_babyseat_desc'), icon: 'fa-baby', price: 30 },
    { id: 'booster', name: t('option_booster_name'), desc: t('option_booster_desc'), icon: 'fa-child', price: 0 },
    { id: 'wheelchair', name: t('option_wheelchair_name'), desc: t('option_wheelchair_desc'), icon: 'fa-wheelchair', price: 0 },
    { id: 'pet', name: t('option_pet_name'), desc: t('option_pet_desc'), icon: 'fa-paw', price: 0 },
    { id: 'extra_luggage', name: t('option_luggage_name'), desc: t('option_luggage_desc'), icon: 'fa-suitcase-rolling', price: 0 }
];

const isAirportAddress = (addr) => {
    if (!addr) return false;
    const lower = addr.toLowerCase();
    return lower.includes('aroport') || lower.includes('gva') || lower.includes('airport') || lower.includes('cointrin');
};

const isVanVehicle = (v) => {
    const code = String(v?.code || v?.slug || v?.type || v?.vehicle_type || '').toLowerCase();
    const name = String(v?.name || '').toLowerCase();
    return code.includes('van') || name.includes('van');
};
const getVehicleCapacity = (v) => {
    if (isVanVehicle(v)) return 6;
    const raw = Number(v?.capacity);
    return raw > 0 ? raw : 4;
};
const filterVehiclesForPassengers = (list, pax) => {
    if (!list || !list.length) return [];
    if (Number(pax) >= 5) return list.filter(isVanVehicle);
    return list;
};

const InlineBookingFlow = ({ searchData, onBook, onModify }) => {
    const { user } = useAuth();
    const toast = useToast();
    const { t } = useTranslation();
    const bookingOptions = getBookingOptions(t);

    const [step, setStep] = useState(1);
    const [passengers, setPassengers] = useState(1);
    const [vehicles, setVehicles] = useState([]);
    const [selectedVehicle, setSelectedVehicle] = useState(null);
    const [routeInfo, setRouteInfo] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [isBooking, setIsBooking] = useState(false);
    const [surgeInfo, setSurgeInfo] = useState(null);
    const [slotInfo, setSlotInfo] = useState(null);

    const [contact, setContact] = useState({
        first_name: user?.first_name || '',
        last_name: user?.last_name || '',
        phone: user?.phone_number || '',
        email: user?.email || '',
        flight_number: '',
        comment: ''
    });
    const [selectedOptions, setSelectedOptions] = useState([]);
    const [cgvAccepted, setCgvAccepted] = useState(false);
    const [paymentMethod, setPaymentMethod] = useState('card');
    const [savedCards, setSavedCards] = useState([]);
    const [selectedCard, setSelectedCard] = useState(null);

    useEffect(() => {
        if (searchData) {
            setStep(1);
            setSelectedOptions([]);
            setCgvAccepted(false);
            setPaymentMethod('card');
            setSelectedCard(null);
            loadPricing();
            loadSavedCards();
        }
    }, [searchData]);

    const loadSavedCards = async () => {
        try {
            const res = await window.taxiBookAPI.getCards();
            if (res.success && res.data) setSavedCards(res.data.cards || []);
        } catch (e) {}
    };

    useEffect(() => {
        if (user) {
            setContact(c => ({
                ...c,
                first_name: c.first_name || user.first_name || '',
                last_name: c.last_name || user.last_name || '',
                phone: c.phone || user.phone_number || '',
                email: c.email || user.email || ''
            }));
        }
    }, [user]);

    const loadPricing = async () => {
        setIsLoading(true);
        try {
            const result = await window.taxiBookAPI.getRealtimePrice({
                pickup_address: searchData.origin.address,
                pickup_latitude: searchData.origin.latitude,
                pickup_longitude: searchData.origin.longitude,
                destination_address: searchData.destination.address,
                destination_latitude: searchData.destination.latitude,
                destination_longitude: searchData.destination.longitude,
                pickup_datetime: searchData.datetime || null
            });
            if (result.success && result.data) {
                const vehicleList = result.data.vehicles.map(v => ({
                    id: v.vehicle.id || v.vehicle.code,
                    code: v.vehicle.code,
                    name: v.vehicle.name,
                    capacity: v.vehicle.capacity,
                    description: v.vehicle.description,
                    image_url: v.vehicle.image_url,
                    price: v.pricing.final_price,
                    eta: v.eta?.minutes || 5,
                    surge_multiplier: v.pricing.surge_multiplier || 1,
                    slot_surcharge: v.pricing.slot_surcharge_percent || 0,
                    special_fee: v.pricing.special_fee || 0,
                    special_fee_label: v.pricing.special_fee_label,
                    total_discount: v.pricing.total_discount || 0,
                    base_before_vehicle: v.pricing.base_before_vehicle
                }));
                setVehicles(vehicleList);
                const filtered = filterVehiclesForPassengers(vehicleList, passengers);
                setSelectedVehicle(filtered[0] || null);
                setSurgeInfo(result.data.surge);
                setSlotInfo(result.data.slot_surcharge);
                setRouteInfo({
                    distance: result.data.route?.distance_km,
                    duration: result.data.route?.estimated_duration_minutes,
                    polyline: result.data.route?.polyline
                });
            }
        } catch (error) {
            toast.show(t('toast_prices_load_error'), 'error');
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        const filtered = filterVehiclesForPassengers(vehicles, passengers);
        if (!filtered.length) { setSelectedVehicle(null); return; }
        const stillOk = selectedVehicle && filtered.some(v => v.id === selectedVehicle.id);
        if (!stillOk) setSelectedVehicle(filtered[0]);
    }, [passengers, vehicles]);

    const availableVehicles = filterVehiclesForPassengers(vehicles, passengers);

    const optionsTotal = selectedOptions.reduce((sum, id) => {
        const opt = bookingOptions.find(o => o.id === id);
        return sum + (opt?.price || 0);
    }, 0);
    const totalPrice = (selectedVehicle?.price || 0) + optionsTotal;

    const showFlightField = isAirportAddress(searchData?.origin?.address) || isAirportAddress(searchData?.destination?.address);

    const toggleOption = (id) => {
        setSelectedOptions(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
    };

    const canProceedStep2 = contact.first_name && contact.phone && contact.email;

    const handleBook = async () => {
        if (!selectedVehicle || !cgvAccepted) return;
        setIsBooking(true);
        try {
            await onBook({
                ...searchData,
                vehicle: selectedVehicle,
                price: totalPrice,
                passengers,
                contact,
                options: selectedOptions,
                options_total: optionsTotal,
                payment_method: paymentMethod,
                saved_card_id: selectedCard?.id || null
            });
        } finally {
            setIsBooking(false);
        }
    };

    const stepTitles = [t('booking_step_vehicle'), t('booking_step_contact'), t('booking_step_payment'), t('booking_step_confirmation')];

    return (
        <div className="inline-booking-flow animate-fade-in">
            {/* Route summary */}
            <div style={{background:'#f6f6f6',borderRadius:12,padding:'1rem 1.25rem',marginBottom:'1.25rem'}}>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:8}}>
                    <span style={{fontWeight:600,fontSize:'0.9rem',color:'#000'}}>{t('booking_your_trip')}</span>
                    <button onClick={onModify} style={{background:'none',border:'none',cursor:'pointer',color:'#666',fontSize:'0.85rem',fontWeight:500,display:'flex',alignItems:'center',gap:4}}>
                        <i className="fas fa-pen" style={{fontSize:'0.7rem'}}></i> {t('booking_modify')}
                    </button>
                </div>
                <div style={{display:'flex',flexDirection:'column',gap:6}}>
                    <div style={{display:'flex',alignItems:'center',gap:8,fontSize:'0.85rem'}}>
                        <i className="fas fa-circle" style={{color:'#22c55e',fontSize:'0.5rem'}}></i>
                        <span style={{color:'#333',flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{searchData?.origin?.address}</span>
                    </div>
                    <div style={{display:'flex',alignItems:'center',gap:8,fontSize:'0.85rem'}}>
                        <i className="fas fa-map-marker-alt" style={{color:'#ef4444',fontSize:'0.65rem'}}></i>
                        <span style={{color:'#333',flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{searchData?.destination?.address}</span>
                    </div>
                </div>
            </div>

            {/* Stepper */}
            <div className="stepper" style={{padding:'0 0 1.25rem',borderBottom:'1px solid #eee',marginBottom:'1.25rem'}}>
                {stepTitles.map((title, i) => (
                    <div key={i} className={`stepper-step ${step === i + 1 ? 'active' : ''} ${step > i + 1 ? 'done' : ''}`}>
                        <div className="stepper-number">
                            {step > i + 1 ? <i className="fas fa-check" style={{fontSize:'0.7rem'}}></i> : i + 1}
                        </div>
                        <span className="stepper-label">{title}</span>
                    </div>
                ))}
            </div>

            {/* Step content */}
            {isLoading ? (
                <div style={{ display: 'flex', justifyContent: 'center', padding: '3rem' }}>
                    <Spinner size="lg" />
                </div>
            ) : step === 1 ? (
                <>
                    {routeInfo && (
                        <div className="route-info">
                            <div className="route-info-item">
                                <i className="fas fa-road"></i>
                                <div>
                                    <div className="label">{t('booking_distance')}</div>
                                    <div className="value">{t('booking_distance_value', { n: routeInfo.distance?.toFixed(1) })}</div>
                                </div>
                            </div>
                            <div className="route-info-item">
                                <i className="fas fa-clock"></i>
                                <div>
                                    <div className="label">{t('booking_duration')}</div>
                                    <div className="value">{t('booking_duration_value', { n: Math.round(routeInfo.duration) })}</div>
                                </div>
                            </div>
                        </div>
                    )}
                    {surgeInfo?.is_active && (
                        <div style={{display:'flex',alignItems:'center',gap:'10px',padding:'10px 14px',background:'linear-gradient(135deg,#fef3c7,#fed7aa)',borderRadius:'10px',marginBottom:'12px'}}>
                            <span style={{fontSize:'20px'}}>⚡</span>
                            <div style={{flex:1}}>
                                <div style={{fontWeight:600,color:'#92400e',fontSize:'13px'}}>{t('booking_surge_title', { multiplier: surgeInfo.multiplier?.toFixed(1) })}</div>
                                <div style={{fontSize:'11px',color:'#b45309'}}>{surgeInfo.label || t('booking_surge_fallback')}</div>
                            </div>
                        </div>
                    )}
                    {slotInfo?.percent > 0 && (
                        <div style={{display:'flex',alignItems:'center',gap:'10px',padding:'10px 14px',background:'linear-gradient(135deg,#fed7aa,#fecaca)',borderRadius:'10px',marginBottom:'12px'}}>
                            <span style={{fontSize:'20px'}}>🕐</span>
                            <div style={{flex:1}}>
                                <div style={{fontWeight:600,color:'#c2410c',fontSize:'13px'}}>{t('booking_slot_title', { percent: slotInfo.percent })}</div>
                                <div style={{fontSize:'11px',color:'#ea580c'}}>{t('booking_slot_desc')}</div>
                            </div>
                        </div>
                    )}
                    <div style={{marginBottom:'1rem'}}>
                        <div style={{fontWeight:600,fontSize:'0.9rem',color:'#333',marginBottom:8}}>
                            <i className="fas fa-users" style={{marginRight:6}}></i>{t('booking_passengers')}
                        </div>
                        <div className="pax-grid">
                            {[1, 2, 3, 4, 5, 6].map(n => (
                                <button
                                    key={n}
                                    type="button"
                                    className={`pax-btn ${passengers === n ? 'active' : ''}`}
                                    onClick={() => setPassengers(n)}
                                >{n}</button>
                            ))}
                        </div>
                    </div>
                    <div className="vehicles-grid">
                        {availableVehicles.map(vehicle => {
                            const cap = getVehicleCapacity(vehicle);
                            return (
                            <div key={vehicle.id} className={`vehicle-card ${selectedVehicle?.id === vehicle.id ? 'selected' : ''}`} onClick={() => setSelectedVehicle(vehicle)}>
                                {vehicle.image_url ? (
                                    <img src={vehicle.image_url} alt={vehicle.name} className="vehicle-image" />
                                ) : (
                                    <div className="vehicle-image-placeholder"><i className="fas fa-car"></i></div>
                                )}
                                <div className="vehicle-info">
                                    <div className="vehicle-name">{vehicle.name}</div>
                                    <div className="vehicle-capacity">
                                        <span className="vehicle-capacity-icons" aria-hidden="true">
                                            {Array.from({ length: cap }, (_, i) => (
                                                <i key={i} className="fas fa-user"></i>
                                            ))}
                                        </span>
                                        <span>{t('capacity_label', { n: cap })}</span>
                                    </div>
                                    <div className="vehicle-description">{vehicle.description}</div>
                                    <div style={{display:'flex',flexWrap:'wrap',gap:'4px',marginTop:'4px'}}>
                                        {vehicle.special_fee > 0 && <span style={{fontSize:'10px',padding:'2px 6px',borderRadius:'4px',background:'#ede9fe',color:'#7c3aed',fontWeight:600}}>✈ +{vehicle.special_fee.toFixed(0)}</span>}
                                        {vehicle.total_discount > 0 && <span style={{fontSize:'10px',padding:'2px 6px',borderRadius:'4px',background:'#d1fae5',color:'#059669',fontWeight:600}}>{t('booking_discount_badge', { amount: vehicle.total_discount.toFixed(2) })}</span>}
                                    </div>
                                </div>
                                <div className="vehicle-price">
                                    <div className="vehicle-price-value">{t('booking_price_chf', { price: vehicle.price?.toFixed(2) })}</div>
                                    <div className="vehicle-price-eta">{t('booking_eta_min', { eta: vehicle.eta })}</div>
                                </div>
                            </div>
                            );
                        })}
                    </div>
                    <button className="btn btn-success btn-lg" style={{width:'100%',marginTop:'1.25rem'}} onClick={() => setStep(2)} disabled={!selectedVehicle}>
                        {selectedVehicle ? t('booking_continue_with_price', { price: selectedVehicle.price?.toFixed(2) }) : t('booking_continue')}
                    </button>
                </>
            ) : step === 2 ? (
                <>
                    <p style={{fontWeight:600,marginBottom:'12px',color:'#333',fontSize:'0.95rem'}}>{t('booking_your_details')}</p>
                    <div className="contact-form">
                        <div className="form-row">
                            <div className="form-field">
                                <label>{t('booking_label_firstname')} <span className="required">*</span></label>
                                <input type="text" value={contact.first_name} onChange={e => setContact({...contact, first_name: e.target.value})} placeholder={t('booking_ph_firstname')} />
                            </div>
                            <div className="form-field">
                                <label>{t('booking_label_lastname')}</label>
                                <input type="text" value={contact.last_name} onChange={e => setContact({...contact, last_name: e.target.value})} placeholder={t('booking_ph_lastname')} />
                            </div>
                        </div>
                        <div className="form-row">
                            <div className="form-field">
                                <label>{t('booking_label_phone')} <span className="required">*</span></label>
                                <input type="tel" value={contact.phone} onChange={e => setContact({...contact, phone: e.target.value})} placeholder={t('booking_ph_phone')} />
                            </div>
                            <div className="form-field">
                                <label>{t('booking_label_email')} <span className="required">*</span></label>
                                <input type="email" value={contact.email} onChange={e => setContact({...contact, email: e.target.value})} placeholder={t('booking_ph_email')} />
                            </div>
                        </div>
                        {showFlightField && (
                            <div className="form-field">
                                <label><i className="fas fa-plane" style={{marginRight:'6px',color:'#3b82f6'}}></i>{t('booking_label_flight')}</label>
                                <input type="text" value={contact.flight_number} onChange={e => setContact({...contact, flight_number: e.target.value})} placeholder={t('booking_ph_flight')} />
                                <span className="field-hint">{t('booking_flight_hint')}</span>
                            </div>
                        )}
                        <div className="form-field">
                            <label>{t('booking_label_comment')}</label>
                            <textarea value={contact.comment} onChange={e => setContact({...contact, comment: e.target.value})} placeholder={t('booking_ph_comment')} />
                        </div>
                    </div>
                    <div style={{display:'flex',gap:'0.75rem',marginTop:'1.25rem'}}>
                        <button className="btn btn-outline" onClick={() => setStep(1)} style={{flex:'0 0 auto'}}>
                            <i className="fas fa-arrow-left"></i> {t('booking_back')}
                        </button>
                        <button className="btn btn-success btn-lg" style={{flex:1}} onClick={() => setStep(3)} disabled={!canProceedStep2}>
                            {t('booking_continue')}
                        </button>
                    </div>
                </>
            ) : step === 3 ? (
                <>
                    <p style={{fontWeight:600, marginBottom:'16px', color:'#333', fontSize:'0.95rem'}}>{t('booking_payment_title')}</p>
                    <div style={{display:'flex',flexDirection:'column',gap:'10px'}}>
                        {[
                            { id: 'card', icon: 'fa-credit-card', label: t('payment_card_label'), desc: t('payment_card_desc'), color: '#3b82f6' },
                            { id: 'twint', icon: 'fa-mobile-alt', label: t('payment_twint_label'), desc: t('payment_twint_desc'), color: '#000' },
                            { id: 'apple_google', icon: 'fa-wallet', label: t('payment_wallet_label'), desc: t('payment_wallet_desc'), color: '#1e293b' }
                        ].map(pm => (
                            <div key={pm.id}
                                onClick={() => { setPaymentMethod(pm.id); setSelectedCard(null); }}
                                style={{
                                    display:'flex', alignItems:'center', gap:'14px', padding:'16px 18px',
                                    borderRadius:'14px', cursor:'pointer', transition:'all 0.2s',
                                    border: paymentMethod === pm.id && !selectedCard ? '2px solid #000' : '2px solid #e5e7eb',
                                    background: paymentMethod === pm.id && !selectedCard ? '#f8fafc' : '#fff'
                                }}
                            >
                                <div style={{width:44, height:44, borderRadius:12, background: pm.color + '15', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
                                    <i className={`fas ${pm.icon}`} style={{color: pm.color, fontSize:'18px'}}></i>
                                </div>
                                <div style={{flex:1}}>
                                    <div style={{fontWeight:600, fontSize:'0.9rem', color:'#1e293b'}}>{pm.label}</div>
                                    <div style={{fontSize:'0.78rem', color:'#94a3b8'}}>{pm.desc}</div>
                                </div>
                                <div style={{width:22, height:22, borderRadius:'50%', border: paymentMethod === pm.id && !selectedCard ? '6px solid #000' : '2px solid #d1d5db', flexShrink:0}}></div>
                            </div>
                        ))}
                    </div>

                    {savedCards.length > 0 && (
                        <>
                            <p style={{fontWeight:600, marginTop:'20px', marginBottom:'10px', color:'#333', fontSize:'0.9rem'}}>
                                <i className="fas fa-credit-card" style={{marginRight:8, color:'#6b7280'}}></i>{t('payment_saved_cards')}
                            </p>
                            <div style={{display:'flex',flexDirection:'column',gap:'8px'}}>
                                {savedCards.map(card => (
                                    <div key={card.id}
                                        onClick={() => { setSelectedCard(card); setPaymentMethod('saved_card'); }}
                                        style={{
                                            display:'flex', alignItems:'center', gap:'12px', padding:'14px 16px',
                                            borderRadius:'12px', cursor:'pointer', transition:'all 0.2s',
                                            border: selectedCard?.id === card.id ? '2px solid #000' : '2px solid #e5e7eb',
                                            background: selectedCard?.id === card.id ? '#f8fafc' : '#fff'
                                        }}
                                    >
                                        <i className={`fab ${card.brand === 'visa' ? 'fa-cc-visa' : card.brand === 'mastercard' ? 'fa-cc-mastercard' : 'fa-credit-card'}`} style={{fontSize:'24px', color:'#475569'}}></i>
                                        <div style={{flex:1}}>
                                            <div style={{fontWeight:600, fontSize:'0.85rem', color:'#1e293b', fontFamily:'monospace'}}>•••• •••• •••• {card.last4 || card.masked_number?.slice(-4) || '****'}</div>
                                            <div style={{fontSize:'0.75rem', color:'#94a3b8'}}>{t('payment_card_exp', { brand: card.brand ? card.brand.toUpperCase() : t('payment_card_fallback'), month: card.exp_month, year: card.exp_year })}</div>
                                        </div>
                                        <div style={{width:22, height:22, borderRadius:'50%', border: selectedCard?.id === card.id ? '6px solid #000' : '2px solid #d1d5db', flexShrink:0}}></div>
                                    </div>
                                ))}
                            </div>
                        </>
                    )}

                    <div style={{display:'flex',gap:'0.75rem',marginTop:'1.25rem'}}>
                        <button className="btn btn-outline" onClick={() => setStep(2)} style={{flex:'0 0 auto'}}>
                            <i className="fas fa-arrow-left"></i> {t('booking_back')}
                        </button>
                        <button className="btn btn-success btn-lg" style={{flex:1}} onClick={() => setStep(4)}>
                            {t('booking_continue')}
                        </button>
                    </div>
                </>
            ) : (
                <>
                    <p style={{fontWeight:600, marginBottom:'12px', color:'#333'}}>{t('booking_extra_options')}</p>
                    <div className="options-grid">
                        {bookingOptions.map(opt => (
                            <div key={opt.id} className={`option-card ${selectedOptions.includes(opt.id) ? 'selected' : ''}`} onClick={() => toggleOption(opt.id)}>
                                <div className="option-icon"><i className={`fas ${opt.icon}`}></i></div>
                                <div className="option-info">
                                    <div className="option-name">{opt.name}</div>
                                    <div className="option-desc">{opt.desc}</div>
                                </div>
                                {opt.price > 0 && <div className="option-price">{t('option_price_plus', { price: opt.price })}</div>}
                                <div className="option-check"><i className="fas fa-check" style={{fontSize:'0.7rem'}}></i></div>
                            </div>
                        ))}
                    </div>

                    <div style={{marginTop:'1.5rem'}}>
                        <p style={{fontWeight:600, marginBottom:'12px', color:'#333'}}>{t('booking_summary')}</p>
                        <div className="booking-summary">
                            <div className="summary-row">
                                <span className="summary-label"><i className="fas fa-map-marker-alt" style={{color:'#22c55e'}}></i> {t('summary_departure')}</span>
                                <span className="summary-value" style={{fontSize:'0.85rem',maxWidth:'60%',textAlign:'right'}}>{searchData?.origin?.address}</span>
                            </div>
                            <div className="summary-row">
                                <span className="summary-label"><i className="fas fa-flag-checkered" style={{color:'#ef4444'}}></i> {t('summary_arrival')}</span>
                                <span className="summary-value" style={{fontSize:'0.85rem',maxWidth:'60%',textAlign:'right'}}>{searchData?.destination?.address}</span>
                            </div>
                            <div className="summary-row">
                                <span className="summary-label"><i className="fas fa-car"></i> {t('summary_vehicle')}</span>
                                <span className="summary-value">{selectedVehicle?.name}</span>
                            </div>
                            <div className="summary-row">
                                <span className="summary-label"><i className="fas fa-user"></i> {t('summary_contact')}</span>
                                <span className="summary-value">{contact.first_name} {contact.last_name}</span>
                            </div>
                            <div className="summary-row">
                                <span className="summary-label"><i className="fas fa-credit-card"></i> {t('summary_payment')}</span>
                                <span className="summary-value">{
                                    selectedCard ? `•••• ${selectedCard.last4 || '****'}` :
                                    paymentMethod === 'card' ? t('summary_pay_card') :
                                    paymentMethod === 'twint' ? t('summary_pay_twint') :
                                    paymentMethod === 'apple_google' ? t('summary_pay_wallet') : t('summary_pay_card_short')
                                }</span>
                            </div>
                            <div className="summary-row">
                                <span className="summary-label">{t('summary_ride')}</span>
                                <span className="summary-value">{t('booking_price_chf', { price: selectedVehicle?.price?.toFixed(2) })}</span>
                            </div>
                            {optionsTotal > 0 && (
                                <div className="summary-row">
                                    <span className="summary-label">{t('summary_options')}</span>
                                    <span className="summary-value">{t('summary_options_plus', { amount: optionsTotal.toFixed(2) })}</span>
                                </div>
                            )}
                            <div className="summary-row">
                                <span className="summary-label" style={{fontWeight:600,color:'#000'}}>{t('summary_total')}</span>
                                <span className="summary-value summary-total">{t('booking_price_chf', { price: totalPrice.toFixed(2) })}</span>
                            </div>
                        </div>
                    </div>

                    <div className="cgv-section">
                        <div className="cgv-checkbox">
                            <input type="checkbox" id="cgv" checked={cgvAccepted} onChange={e => setCgvAccepted(e.target.checked)} />
                            <label htmlFor="cgv">
                                {t('cgv_accept_before')}<a href="#" onClick={e => {e.preventDefault(); window.open('https://taxibook.ch/cgv','_blank');}}>{t('cgv_link_text')}</a>{t('cgv_accept_mid')}<a href="#" onClick={e => {e.preventDefault(); window.open('https://taxibook.ch/privacy','_blank');}}>{t('privacy_link_text')}</a>{t('cgv_accept_after')}
                            </label>
                        </div>
                    </div>

                    <div style={{display:'flex',gap:'0.75rem',marginTop:'1.25rem'}}>
                        <button className="btn btn-outline" onClick={() => setStep(3)} style={{flex:'0 0 auto'}}>
                            <i className="fas fa-arrow-left"></i> {t('booking_back')}
                        </button>
                        <button className="btn btn-success btn-lg" style={{flex:1}} onClick={handleBook} disabled={!cgvAccepted || isBooking}>
                            {isBooking ? <Spinner /> : t('booking_confirm', { price: totalPrice.toFixed(2) })}
                        </button>
                    </div>
                </>
            )}
        </div>
    );
};

// ============================================================
// COMPOSANT AUTH MODAL
// ============================================================

const AuthModal = ({ isOpen, onClose, onSuccess }) => {
    const toast = useToast();
    const { t } = useTranslation();
    const [step, setStep] = useState('email'); // email, sent
    const [email, setEmail] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    
    const handleSendLink = async () => {
        if (!email || !email.includes('@')) {
            toast.show(t('toast_invalid_email'), 'error');
            return;
        }
        
        setIsLoading(true);
        try {
            const result = await window.taxiBookAPI.sendMagicLink(email.trim());
            
            if (result.success || result.data) {
                setStep('sent');
                toast.show(t('toast_magic_link_sent'), 'success');
            } else {
                toast.show(result.error || t('toast_send_error'), 'error');
            }
        } catch (error) {
            toast.show(t('toast_connection_error'), 'error');
        } 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 + url.search);
            handleVerifyMagicLink(magicToken);
        }
    }, []);

    const handleVerifyMagicLink = async (token) => {
        setIsLoading(true);
        try {
            const result = await window.taxiBookAPI.verifyMagicLink(token);
            if (result.success) {
                toast.show(t('toast_login_success'), 'success');
                onSuccess(result.data);
                onClose();
            } else {
                toast.show(result.error || t('toast_link_invalid'), 'error');
            }
        } catch (error) {
            toast.show(t('toast_link_invalid'), 'error');
        } finally {
            setIsLoading(false);
        }
    };

    const handleClose = () => {
        setStep('email');
        setEmail('');
        onClose();
    };
    
    if (!isOpen) return null;
    
    return (
        <div className="modal-overlay" onClick={handleClose}>
            <div className="modal-content auth-modal" onClick={e => e.stopPropagation()}>
                <button className="modal-close" onClick={handleClose}>
                    <i className="fas fa-times"></i>
                </button>
                
                <div className="modal-body">
                    <div className="auth-header">
                        <div className="auth-icon">
                            <i className="fas fa-envelope"></i>
                        </div>
                        <h2 className="auth-title">
                            {step === 'email' ? t('auth_title_login') : t('auth_title_sent')}
                        </h2>
                        <p className="auth-subtitle">
                            {step === 'email' 
                                ? t('auth_subtitle_email') 
                                : t('auth_subtitle_sent', { email })}
                        </p>
                    </div>
                    
                    {step === 'email' ? (
                        <>
                            <div style={{ marginBottom: '1rem' }}>
                                <input
                                    type="email"
                                    className="phone-input"
                                    style={{ width: '100%', padding: '14px 16px', borderRadius: '12px', border: '1px solid #e5e7eb', fontSize: '16px' }}
                                    placeholder={t('auth_ph_email')}
                                    value={email}
                                    onChange={e => setEmail(e.target.value)}
                                    onKeyDown={e => e.key === 'Enter' && handleSendLink()}
                                    autoComplete="email"
                                />
                            </div>
                            
                            <button 
                                className="btn btn-primary btn-lg" 
                                style={{ width: '100%' }}
                                onClick={handleSendLink}
                                disabled={!email.includes('@') || isLoading}
                            >
                                {isLoading ? <Spinner /> : t('auth_send_link')}
                            </button>
                            
                            <p style={{ textAlign: 'center', fontSize: '13px', color: '#9ca3af', marginTop: '12px' }}>
                                {t('auth_hint_secure')}
                            </p>
                        </>
                    ) : (
                        <>
                            <div style={{ textAlign: 'center', padding: '1rem 0' }}>
                                <div style={{ fontSize: '48px', marginBottom: '16px' }}>✉️</div>
                                <p style={{ color: '#6b7280', fontSize: '14px', marginBottom: '16px' }}>
                                    {t('auth_check_inbox')}
                                </p>
                            </div>
                            
                            <button 
                                className="btn btn-ghost" 
                                style={{ width: '100%', marginTop: '0.5rem' }}
                                onClick={() => setStep('email')}
                            >
                                <i className="fas fa-arrow-left"></i>
                                {t('auth_use_other')}
                            </button>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
};

// ============================================================
// COMPOSANT SUCCESS MODAL
// ============================================================

const BookingSuccessScreen = ({ booking, onClose }) => {
    const { t } = useTranslation();
    if (!booking) return null;

    const jobHash = booking.job_hash || booking.confirmation_code || booking.uid;
    const firstName = (booking.contact_name || '').trim().split(/\s+/)[0] || '';
    const contactEmail = booking.contact_email || '';
    const trackUrl = booking.tracking_url
        || (jobHash ? `https://tracking.taxis.ch/${jobHash}` : null);
    const payUrl = booking.payment_url
        || (jobHash ? `https://payment.taxis.ch/?ride_id=${encodeURIComponent(jobHash)}` : null);
    const needsPay = booking.requires_prepayment
        || booking.payment_status === 'awaiting_prepayment'
        || booking.payment_status === 'awaiting_payment';

    return (
        <div className="site-success animate-fade-in">
            <div className="site-success-icon"><i className="fas fa-check"></i></div>
            <h2>{t('success_title')}</h2>
            <p>
                {t('success_thanks', { name: firstName ? ` ${firstName}` : '' })}
            </p>
            {jobHash && (
                <div className="site-success-ref">{t('success_reference', { jobHash })}</div>
            )}
            {needsPay && (
                <div className="site-success-alert">
                    <i className="fas fa-exclamation-triangle"></i>
                    <span>{t('success_pay_alert')}</span>
                </div>
            )}
            {contactEmail && (
                <div className="site-success-note">
                    <i className="fas fa-envelope"></i>
                    <span>
                        {t('success_email_note_prefix')} <strong>{contactEmail}</strong>
                        {needsPay ? t('success_email_pay_suffix') : t('success_email_dot')}
                    </span>
                </div>
            )}
            {trackUrl && (
                <div className="site-success-link">
                    <div className="site-success-link-label">{t('success_track_label')}</div>
                    <a href={trackUrl} target="_blank" rel="noopener noreferrer">{trackUrl}</a>
                </div>
            )}
            <div className="site-success-actions">
                {needsPay && payUrl && (
                    <a className="btn btn-lg" style={{ background: '#ea580c', color: '#fff', textDecoration: 'none' }} href={payUrl} target="_blank" rel="noopener noreferrer">
                        <i className="fas fa-credit-card"></i> {t('success_pay_cta')}
                    </a>
                )}
                {trackUrl && (
                    <a className="btn btn-primary btn-lg" style={{ textDecoration: 'none' }} href={trackUrl} target="_blank" rel="noopener noreferrer">
                        <i className="fas fa-map-marker-alt"></i> {t('success_open_tracking')}
                    </a>
                )}
                {onClose && (
                    <button className="btn btn-outline" onClick={onClose}>{t('success_new_booking')}</button>
                )}
            </div>
        </div>
    );
};

const buildConfirmedBooking = (result, bookingData) => {
    const job = result.data?.job || result.data || {};
    const jobHash = job.job_hash || result.data?.job_hash;
    const contactName = bookingData.contact
        ? `${bookingData.contact.first_name || ''} ${bookingData.contact.last_name || ''}`.trim()
        : (bookingData.contact_name || null);
    return {
        ...job,
        job_hash: jobHash,
        payment_status: job.payment_status || result.data?.payment_status,
        requires_prepayment: job.requires_prepayment
            || job.payment_status === 'awaiting_prepayment'
            || result.data?.payment_status === 'awaiting_prepayment',
        payment_url: job.payment_url
            || (jobHash ? `https://payment.taxis.ch/?ride_id=${encodeURIComponent(jobHash)}` : null),
        tracking_url: job.tracking_url
            || (jobHash ? `https://tracking.taxis.ch/${jobHash}` : null),
        contact_name: contactName,
        contact_email: bookingData.contact?.email || bookingData.contact_email || null,
        estimated_price: bookingData.price ?? job.estimated_price
    };
};

// ============================================================
// COMPOSANT MY BOOKINGS MODAL
// ============================================================

const MyBookingsModal = ({ isOpen, onClose }) => {
    const toast = useToast();
    const { t, lang } = useTranslation();
    const [bookings, setBookings] = useState([]);
    const [cancellationDelay, setCancellationDelay] = useState(3);
    const [isLoading, setIsLoading] = useState(true);
    const [cancellingId, setCancellingId] = useState(null);
    
    useEffect(() => {
        if (isOpen) {
            loadBookings();
            // Rafraîchir toutes les 30 secondes pour mettre à jour le temps restant
            const interval = setInterval(loadBookings, 30000);
            return () => clearInterval(interval);
        }
    }, [isOpen]);
    
    const loadBookings = async () => {
        setIsLoading(true);
        try {
            const result = await window.taxiBookAPI.getUserBookings();
            if (result.success) {
                setBookings(result.data?.bookings || []);
                setCancellationDelay(result.data?.cancellation_delay_minutes || 3);
            }
        } catch (error) {
            console.error('Error loading bookings:', error);
        } finally {
            setIsLoading(false);
        }
    };
    
    const handleCancel = async (uid) => {
        if (!confirm(t('confirm_cancel_booking'))) return;
        
        setCancellingId(uid);
        try {
            const result = await window.taxiBookAPI.cancelBooking(uid);
            if (result.success) {
                toast.show(t('toast_booking_cancelled'), 'success');
                loadBookings();
            } else {
                toast.show(result.error || t('toast_cancel_error'), 'error');
            }
        } catch (error) {
            toast.show(t('toast_connection_error'), 'error');
        } finally {
            setCancellingId(null);
        }
    };
    
    const formatDate = (dateStr) => {
        const d = new Date(dateStr);
        return d.toLocaleDateString(LOCALE_FOR_LANG[lang] || lang, { 
            day: 'numeric', 
            month: 'short',
            hour: '2-digit',
            minute: '2-digit'
        });
    };
    
    const getStatusLabel = (status) => {
        const key = `status_${status}`;
        const translated = t(key);
        return translated === key ? status : translated;
    };
    
    if (!isOpen) return null;
    
    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" style={{ maxWidth: '600px' }} onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                    <h2 className="modal-title">{t('bookings_modal_title')}</h2>
                    <button className="modal-close" onClick={onClose}>
                        <i className="fas fa-times"></i>
                    </button>
                </div>
                
                <div className="modal-body">
                    {isLoading ? (
                        <div style={{ display: 'flex', justifyContent: 'center', padding: '3rem' }}>
                            <Spinner size="lg" />
                        </div>
                    ) : bookings.length === 0 ? (
                        <div className="empty-state">
                            <div className="empty-state-icon">
                                <i className="fas fa-car"></i>
                            </div>
                            <h3 className="empty-state-title">{t('bookings_empty_title')}</h3>
                            <p className="empty-state-text">{t('bookings_empty_text')}</p>
                        </div>
                    ) : (
                        <div className="bookings-list">
                            {bookings.map(booking => (
                                <div key={booking.id || booking.uid} className="booking-card">
                                    <div className="booking-card-header">
                                        <span className="booking-date">
                                            {formatDate(booking.pickup_datetime || booking.created_at)}
                                        </span>
                                        <span className={`booking-status ${booking.status}`}>
                                            {getStatusLabel(booking.status)}
                                        </span>
                                    </div>
                                    
                                    <div className="booking-route">
                                        <div className="booking-location origin">
                                            <i className="fas fa-circle"></i>
                                            <span>{booking.pickup_address}</span>
                                        </div>
                                        <div className="booking-location destination">
                                            <i className="fas fa-map-marker-alt"></i>
                                            <span>{booking.dropoff_address || booking.destination_address}</span>
                                        </div>
                                    </div>
                                    
                                    <div className="booking-card-footer">
                                        <span className="booking-vehicle">
                                            <i className="fas fa-car"></i> {booking.vehicle_type || t('vehicle_standard_fallback')}
                                        </span>
                                        <span className="booking-price">
                                            {(booking.estimated_price || booking.price)?.toFixed(2)} CHF
                                        </span>
                                    </div>
                                    
                                    {/* Infos chauffeur si assigné */}
                                    {booking.driver && (
                                        <div className="booking-driver">
                                            <i className="fas fa-user"></i>
                                            <span>{booking.driver.name}</span>
                                        </div>
                                    )}
                                    
                                    {/* Bouton d'annulation avec temps restant */}
                                    {booking.can_cancel && (
                                        <div className="booking-cancel-section">
                                            <div className="cancel-timer">
                                                <i className="fas fa-clock"></i>
                                                <span>
                                                    {booking.cancel_minutes_remaining > 0 
                                                        ? t('cancel_minutes_left', { n: booking.cancel_minutes_remaining })
                                                        : t('cancel_available')
                                                    }
                                                </span>
                                            </div>
                                            <button 
                                                className="btn btn-cancel"
                                                onClick={() => handleCancel(booking.uid || booking.job_hash)}
                                                disabled={cancellingId === (booking.uid || booking.job_hash)}
                                            >
                                                {cancellingId === (booking.uid || booking.job_hash) ? (
                                                    <Spinner size="sm" />
                                                ) : (
                                                    <>
                                                        <i className="fas fa-times"></i>
                                                        {t('cancel_this_ride')}
                                                    </>
                                                )}
                                            </button>
                                        </div>
                                    )}
                                    
                                    {/* Message si l'annulation n'est plus possible */}
                                    {!booking.can_cancel && !['completed', 'cancelled'].includes(booking.status) && (
                                        <div className="cancel-expired">
                                            <i className="fas fa-info-circle"></i>
                                            {t('cancel_deadline_expired')}
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

// ============================================================
// PAGE: NOS SERVICES
// ============================================================

const ServicesPage = ({ onBack, onNavigate }) => {
    const { t } = useTranslation();
    const services = [
        { icon: 'fa-car', title: t('service_private_title'), desc: t('service_private_desc'), color: '#3b82f6' },
        { icon: 'fa-plane-departure', title: t('service_airport_title'), desc: t('service_airport_desc'), color: '#8b5cf6' },
        { icon: 'fa-briefcase', title: t('service_business_title'), desc: t('service_business_desc'), color: '#f59e0b' },
        { icon: 'fa-clock', title: t('service_advance_title'), desc: t('service_advance_desc'), color: '#10b981' },
        { icon: 'fa-star', title: t('service_premium_title'), desc: t('service_premium_desc'), color: '#ec4899' },
        { icon: 'fa-box', title: t('service_delivery_title'), desc: t('service_delivery_desc'), color: '#f97316' },
    ];

    return (
        <div className="page-container">
            <div className="page-header">
                <div className="page-header-inner">
                    <button className="page-back" onClick={onBack}><i className="fas fa-arrow-left"></i></button>
                    <h1 className="page-title">{t('services_title')}</h1>
                </div>
            </div>
            <div className="page-content">
                <div style={{textAlign:'center', marginBottom:'2.5rem'}}>
                    <p style={{fontSize:'1.1rem', color:'#555', lineHeight:1.7, maxWidth:600, margin:'0 auto'}}>
                        {t('services_intro')}
                    </p>
                </div>
                <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))', gap:'1.25rem'}}>
                    {services.map((s, i) => (
                        <div key={i} className="page-card" style={{padding:'1.75rem', cursor:'default'}}>
                            <div style={{width:48, height:48, borderRadius:12, background:`${s.color}15`, display:'flex', alignItems:'center', justifyContent:'center', marginBottom:'1rem'}}>
                                <i className={`fas ${s.icon}`} style={{fontSize:'1.25rem', color:s.color}}></i>
                            </div>
                            <h3 style={{fontWeight:700, fontSize:'1.05rem', marginBottom:'0.5rem', color:'#111'}}>{s.title}</h3>
                            <p style={{color:'#666', fontSize:'0.9rem', lineHeight:1.6}}>{s.desc}</p>
                        </div>
                    ))}
                </div>
                <div className="page-card" style={{marginTop:'2rem', textAlign:'center', padding:'2.5rem 2rem', background:'linear-gradient(135deg, #f0fdf4, #ecfdf5)'}}>
                    <h3 style={{fontWeight:700, fontSize:'1.15rem', marginBottom:'0.75rem', color:'#111'}}>{t('services_cta_title')}</h3>
                    <p style={{color:'#555', marginBottom:'1.25rem'}}>{t('services_cta_text')}</p>
                    <button className="btn btn-primary" onClick={onBack} style={{background:'#22c55e', border:'none'}}>
                        <i className="fas fa-calculator" style={{marginRight:6}}></i> {t('services_cta_button')}
                    </button>
                </div>
                <div style={{marginTop:'1.5rem', textAlign:'center', fontSize:'0.85rem', color:'#888'}}>
                    <a href="https://silgeneve.ch/legis/index.aspx" target="_blank" rel="noopener noreferrer" style={{color:'#6b7280', textDecoration:'underline'}}>
                        <i className="fas fa-gavel" style={{marginRight:4}}></i> {t('services_legal_link')}
                    </a>
                </div>
            </div>
        </div>
    );
};

// ============================================================
// PAGE: DEVENIR CHAUFFEUR
// ============================================================

const DriverPage = ({ onBack }) => {
    const { t } = useTranslation();
    const steps = [
        { num: '1', title: t('driver_step1_title'), desc: t('driver_step1_desc') },
        { num: '2', title: t('driver_step2_title'), desc: t('driver_step2_desc') },
        { num: '3', title: t('driver_step3_title'), desc: t('driver_step3_desc') },
        { num: '4', title: t('driver_step4_title'), desc: t('driver_step4_desc') },
    ];

    return (
        <div className="page-container">
            <div className="page-header">
                <div className="page-header-inner">
                    <button className="page-back" onClick={onBack}><i className="fas fa-arrow-left"></i></button>
                    <h1 className="page-title">{t('driver_page_title')}</h1>
                </div>
            </div>
            <div className="page-content">
                <div className="page-card" style={{padding:'2rem', textAlign:'center', background:'linear-gradient(135deg, #eff6ff, #eef2ff)'}}>
                    <div style={{width:64, height:64, borderRadius:'50%', background:'#3b82f620', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 1rem'}}>
                        <i className="fas fa-id-card" style={{fontSize:'1.5rem', color:'#3b82f6'}}></i>
                    </div>
                    <h2 style={{fontWeight:700, fontSize:'1.3rem', marginBottom:'0.75rem', color:'#111'}}>{t('driver_hero_title')}</h2>
                    <p style={{color:'#555', lineHeight:1.7, maxWidth:550, margin:'0 auto'}}>
                        {t('driver_hero_text')}
                    </p>
                </div>

                <h3 style={{fontWeight:700, fontSize:'1.1rem', margin:'2rem 0 1rem', color:'#111'}}>{t('driver_steps_heading')}</h3>
                {steps.map((s, i) => (
                    <div key={i} className="page-card" style={{padding:'1.25rem 1.5rem', display:'flex', gap:'1rem', alignItems:'flex-start'}}>
                        <div style={{width:36, height:36, borderRadius:'50%', background:'#3b82f6', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:'0.95rem', flexShrink:0}}>
                            {s.num}
                        </div>
                        <div>
                            <h4 style={{fontWeight:700, marginBottom:'0.25rem', color:'#111'}}>{s.title}</h4>
                            <p style={{color:'#666', fontSize:'0.9rem', lineHeight:1.6}}>{s.desc}</p>
                        </div>
                    </div>
                ))}

                <div className="page-card" style={{marginTop:'1.5rem', padding:'2rem', textAlign:'center', background:'linear-gradient(135deg, #fefce8, #fef9c3)'}}>
                    <h3 style={{fontWeight:700, fontSize:'1.05rem', marginBottom:'0.5rem', color:'#111'}}>
                        <i className="fas fa-calendar-alt" style={{color:'#f59e0b', marginRight:6}}></i>
                        {t('driver_exam_session_title')}
                    </h3>
                    <p style={{color:'#555', marginBottom:'0.25rem'}}>{t('driver_exam_date')}</p>
                    <p style={{color:'#888', fontSize:'0.85rem'}}>{t('driver_exam_note')}</p>
                </div>

                <div className="page-card" style={{marginTop:'1rem', padding:'1.75rem', textAlign:'center'}}>
                    <p style={{color:'#555', marginBottom:'1rem'}}>{t('driver_official_info')}</p>
                    <a href="https://www.ge.ch/pratiquer-transport-personnes-taxi-vtc/obtenir-diplome-chauffeur-taxi-vtc"
                       target="_blank" rel="noopener noreferrer"
                       className="btn btn-primary" style={{background:'#3b82f6', border:'none', display:'inline-flex', alignItems:'center', gap:8}}>
                        <i className="fas fa-external-link-alt"></i> {t('driver_official_cta')}
                    </a>
                </div>
                <div style={{marginTop:'1rem', textAlign:'center', fontSize:'0.85rem'}}>
                    <a href="https://silgeneve.ch/legis/index.aspx" target="_blank" rel="noopener noreferrer" style={{color:'#6b7280', textDecoration:'underline'}}>
                        <i className="fas fa-gavel" style={{marginRight:4}}></i> {t('driver_legal_link')}
                    </a>
                </div>
            </div>
        </div>
    );
};

// ============================================================
// PAGE: CONTACT
// ============================================================

const ContactPage = ({ onBack, branding }) => {
    const { t } = useTranslation();
    const [form, setForm] = useState({ name:'', email:'', phone:'', subject:'general', message:'' });
    const [sent, setSent] = useState(false);
    const [sending, setSending] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setSending(true);
        await new Promise(r => setTimeout(r, 800));
        setSent(true);
        setSending(false);
    };

    const subjects = [
        { value: 'general', label: t('contact_subject_general') },
        { value: 'booking', label: t('contact_subject_booking') },
        { value: 'driver', label: t('contact_subject_driver') },
        { value: 'partner', label: t('contact_subject_partner') },
        { value: 'complaint', label: t('contact_subject_complaint') },
    ];

    if (sent) {
        return (
            <div className="page-container">
                <div className="page-header">
                    <div className="page-header-inner">
                        <button className="page-back" onClick={onBack}><i className="fas fa-arrow-left"></i></button>
                        <h1 className="page-title">{t('contact_title')}</h1>
                    </div>
                </div>
                <div className="page-content">
                    <div className="page-card" style={{textAlign:'center', padding:'3rem 2rem'}}>
                        <div style={{width:64, height:64, borderRadius:'50%', background:'#22c55e20', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 1rem'}}>
                            <i className="fas fa-check" style={{fontSize:'1.5rem', color:'#22c55e'}}></i>
                        </div>
                        <h2 style={{fontWeight:700, fontSize:'1.3rem', marginBottom:'0.5rem'}}>{t('contact_sent_title')}</h2>
                        <p style={{color:'#666', marginBottom:'1.5rem'}}>{t('contact_sent_text')}</p>
                        <button className="btn btn-primary" onClick={onBack} style={{background:'#22c55e', border:'none'}}>
                            <i className="fas fa-home" style={{marginRight:6}}></i> {t('contact_back_home')}
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    const inputStyle = { width:'100%', padding:'0.75rem 1rem', border:'1px solid #e5e7eb', borderRadius:10, fontSize:'0.95rem', fontFamily:'inherit', outline:'none', transition:'border 0.2s' };

    return (
        <div className="page-container">
            <div className="page-header">
                <div className="page-header-inner">
                    <button className="page-back" onClick={onBack}><i className="fas fa-arrow-left"></i></button>
                    <h1 className="page-title">{t('contact_title')}</h1>
                </div>
            </div>
            <div className="page-content">
                <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(200px, 1fr))', gap:'1rem', marginBottom:'2rem'}}>
                    {[
                        { icon:'fa-phone', label: t('contact_info_phone'), value: branding?.contact_phone || '+41 22 320 21 20', href: `tel:${(branding?.contact_phone || '+41 22 320 21 20').replace(/\s/g,'')}`, color:'#22c55e' },
                        { icon:'fa-envelope', label: t('contact_info_email'), value: branding?.contact_email || 'info@taxibook.ch', href: `mailto:${branding?.contact_email || 'info@taxibook.ch'}`, color:'#3b82f6' },
                        { icon:'fa-map-marker-alt', label: t('contact_info_address'), value: branding?.company_address || t('contact_address_fallback'), href:null, color:'#f59e0b' },
                        { icon:'fa-clock', label: t('contact_info_availability'), value: t('contact_availability_value'), href:null, color:'#8b5cf6' },
                    ].map((c, i) => (
                        <div key={i} className="page-card" style={{padding:'1.25rem', textAlign:'center', cursor:'default'}}>
                            <div style={{width:40, height:40, borderRadius:10, background:`${c.color}15`, display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 0.75rem'}}>
                                <i className={`fas ${c.icon}`} style={{color:c.color}}></i>
                            </div>
                            <div style={{fontSize:'0.8rem', color:'#888', marginBottom:'0.25rem'}}>{c.label}</div>
                            {c.href ? (
                                <a href={c.href} style={{fontWeight:600, color:'#111', textDecoration:'none', fontSize:'0.9rem'}}>{c.value}</a>
                            ) : (
                                <div style={{fontWeight:600, color:'#111', fontSize:'0.9rem'}}>{c.value}</div>
                            )}
                        </div>
                    ))}
                </div>

                <div className="page-card" style={{padding:'2rem'}}>
                    <h3 style={{fontWeight:700, fontSize:'1.1rem', marginBottom:'1.25rem', color:'#111'}}>
                        <i className="fas fa-paper-plane" style={{color:'#3b82f6', marginRight:8}}></i>
                        {t('contact_form_title')}
                    </h3>
                    <form onSubmit={handleSubmit}>
                        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:'1rem', marginBottom:'1rem'}}>
                            <div>
                                <label style={{display:'block', fontSize:'0.85rem', fontWeight:600, color:'#333', marginBottom:4}}>{t('contact_label_name')}</label>
                                <input required style={inputStyle} value={form.name} onChange={e => setForm({...form, name:e.target.value})} placeholder={t('contact_ph_name')} />
                            </div>
                            <div>
                                <label style={{display:'block', fontSize:'0.85rem', fontWeight:600, color:'#333', marginBottom:4}}>{t('contact_label_email')}</label>
                                <input required type="email" style={inputStyle} value={form.email} onChange={e => setForm({...form, email:e.target.value})} placeholder={t('contact_ph_email')} />
                            </div>
                        </div>
                        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:'1rem', marginBottom:'1rem'}}>
                            <div>
                                <label style={{display:'block', fontSize:'0.85rem', fontWeight:600, color:'#333', marginBottom:4}}>{t('contact_label_phone')}</label>
                                <input style={inputStyle} value={form.phone} onChange={e => setForm({...form, phone:e.target.value})} placeholder={t('contact_ph_phone')} />
                            </div>
                            <div>
                                <label style={{display:'block', fontSize:'0.85rem', fontWeight:600, color:'#333', marginBottom:4}}>{t('contact_label_subject')}</label>
                                <select style={{...inputStyle, background:'#fff'}} value={form.subject} onChange={e => setForm({...form, subject:e.target.value})}>
                                    {subjects.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
                                </select>
                            </div>
                        </div>
                        <div style={{marginBottom:'1.25rem'}}>
                            <label style={{display:'block', fontSize:'0.85rem', fontWeight:600, color:'#333', marginBottom:4}}>{t('contact_label_message')}</label>
                            <textarea required rows={5} style={{...inputStyle, resize:'vertical'}} value={form.message} onChange={e => setForm({...form, message:e.target.value})} placeholder={t('contact_ph_message')}></textarea>
                        </div>
                        <button type="submit" className="btn btn-primary" disabled={sending} style={{width:'100%', padding:'0.85rem', background:'#22c55e', border:'none'}}>
                            {sending ? t('contact_sending') : <><i className="fas fa-paper-plane" style={{marginRight:6}}></i> {t('contact_send')}</>}
                        </button>
                    </form>
                </div>
            </div>
        </div>
    );
};

// ============================================================
// PAGE: MES RÉSERVATIONS
// ============================================================

const BookingsPage = ({ onBack }) => {
    const toast = useToast();
    const { t, lang } = useTranslation();
    const [bookings, setBookings] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [cancellingId, setCancellingId] = useState(null);
    
    useEffect(() => { loadBookings(); }, []);
    
    const loadBookings = async () => {
        setIsLoading(true);
        try {
            const result = await window.taxiBookAPI.getUserBookings();
            if (result.success) setBookings(result.data?.bookings || []);
        } catch (e) { console.error(e); }
        finally { setIsLoading(false); }
    };
    
    const handleCancel = async (uid) => {
        if (!confirm(t('confirm_cancel_booking'))) return;
        setCancellingId(uid);
        try {
            const r = await window.taxiBookAPI.cancelBooking(uid);
            if (r.success) { toast.show(t('toast_booking_cancelled'), 'success'); loadBookings(); }
            else toast.show(r.error || t('toast_generic_error'), 'error');
        } catch (e) { toast.show(t('toast_connection_error'), 'error'); }
        finally { setCancellingId(null); }
    };
    
    const fmt = (d) => new Date(d).toLocaleDateString(LOCALE_FOR_LANG[lang] || lang, { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
    const getStatusLabel = (status) => {
        const key = `status_${status}`;
        const translated = t(key);
        return translated === key ? status : translated;
    };
    const canCancel = (b) => ['pending','searching','accepted'].includes(b.status);
    
    return (
        <div className="page-container">
            <div className="page-header">
                <div className="page-header-inner">
                    <button className="page-back" onClick={onBack}><i className="fas fa-arrow-left"></i></button>
                    <h1 className="page-title">{t('bookings_page_title')}</h1>
                </div>
            </div>
            <div className="page-content">
                {isLoading ? (
                    <div style={{display:'flex',justifyContent:'center',padding:'4rem'}}><Spinner size="lg" /></div>
                ) : bookings.length === 0 ? (
                    <div className="page-card" style={{textAlign:'center',padding:'4rem 2rem'}}>
                        <i className="fas fa-car" style={{fontSize:'3rem',color:'#ccc',marginBottom:'1rem',display:'block'}}></i>
                        <h3 style={{fontWeight:600,marginBottom:'0.5rem'}}>{t('bookings_empty_title')}</h3>
                        <p style={{color:'#666'}}>{t('bookings_empty_text')}</p>
                        <button className="btn btn-primary" style={{marginTop:'1.5rem'}} onClick={onBack}><i className="fas fa-plus"></i> {t('bookings_empty_cta')}</button>
                    </div>
                ) : bookings.map(b => (
                    <div key={b.id || b.uid} className="page-card">
                        <div className="page-card-header">
                            <span style={{fontWeight:600}}>{fmt(b.pickup_datetime || b.created_at)}</span>
                            <span className={`status-badge ${b.status}`}>{getStatusLabel(b.status)}</span>
                        </div>
                        <div className="page-card-route">
                            <div className="page-card-location origin"><i className="fas fa-circle"></i><span>{b.pickup_address}</span></div>
                            <div className="page-card-location dest"><i className="fas fa-map-marker-alt"></i><span>{b.dropoff_address || b.destination_address}</span></div>
                        </div>
                        {b.driver_name && (
                            <div style={{display:'flex',alignItems:'center',gap:'8px',marginTop:'0.75rem',padding:'0.5rem 0.75rem',background:'#f0fdf4',borderRadius:'8px',fontSize:'0.9rem',color:'#166534'}}>
                                <i className="fas fa-user" style={{color:'#22c55e'}}></i>
                                <span>{b.driver_name} {b.driver_plate ? `• ${b.driver_plate}` : ''}</span>
                            </div>
                        )}
                        <div className="page-card-footer">
                            <span style={{color:'#666',fontSize:'0.9rem'}}><i className="fas fa-car" style={{marginRight:'6px'}}></i>{b.vehicle_type || t('vehicle_standard_fallback')}</span>
                            <span style={{fontWeight:700,fontSize:'1.1rem'}}>{(b.estimated_price || b.price)?.toFixed(2)} CHF</span>
                        </div>
                        <div className="page-card-actions">
                            {b.job_hash && (
                                <a href={`https://tracking.taxis.ch/${b.job_hash}`} target="_blank" rel="noopener" className="btn btn-sm btn-track">
                                    <i className="fas fa-map-marked-alt"></i> {t('bookings_track')}
                                </a>
                            )}
                            {canCancel(b) && (
                                <button className="btn btn-sm btn-danger" onClick={() => handleCancel(b.job_hash || b.uid)} disabled={cancellingId === (b.job_hash || b.uid)}>
                                    {cancellingId === (b.job_hash || b.uid) ? <Spinner /> : <><i className="fas fa-times"></i> {t('bookings_cancel')}</>}
                                </button>
                            )}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};

// ============================================================
// PAGE: MOYENS DE PAIEMENT
// ============================================================

const PaymentsPage = ({ onBack }) => {
    const toast = useToast();
    const { t } = useTranslation();
    const [cards, setCards] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isAdding, setIsAdding] = useState(false);
    
    useEffect(() => { loadCards(); }, []);
    
    const loadCards = async () => {
        setIsLoading(true);
        try {
            const r = await window.taxiBookAPI.getCards();
            if (r.success) setCards(r.data?.cards || []);
        } catch (e) { console.error(e); }
        finally { setIsLoading(false); }
    };
    
    const handleAddCard = async () => {
        setIsAdding(true);
        try {
            const r = await window.taxiBookAPI.initAddCard({ return_url: window.location.href });
            if (r.success && r.data?.redirect_url) {
                window.location.href = r.data.redirect_url;
            } else {
                toast.show(r.error || t('toast_card_add_error'), 'error');
            }
        } catch (e) { toast.show(t('toast_connection_error'), 'error'); }
        finally { setIsAdding(false); }
    };
    
    const handleDelete = async (cardId) => {
        if (!confirm(t('confirm_delete_card'))) return;
        try {
            const r = await window.taxiBookAPI.deleteCard(cardId);
            if (r.success) { toast.show(t('toast_card_deleted'), 'success'); loadCards(); }
            else toast.show(r.error || t('toast_generic_error'), 'error');
        } catch (e) { toast.show(t('toast_generic_error'), 'error'); }
    };
    
    const handleSetDefault = async (cardId) => {
        try {
            const r = await window.taxiBookAPI.setDefaultCard(cardId);
            if (r.success) { toast.show(t('toast_card_default_updated'), 'success'); loadCards(); }
        } catch (e) { toast.show(t('toast_generic_error'), 'error'); }
    };
    
    const cardIcon = (brand) => {
        const b = (brand || '').toLowerCase();
        if (b.includes('visa')) return 'fa-cc-visa';
        if (b.includes('master')) return 'fa-cc-mastercard';
        if (b.includes('amex')) return 'fa-cc-amex';
        return 'fa-credit-card';
    };
    
    return (
        <div className="page-container">
            <div className="page-header">
                <div className="page-header-inner">
                    <button className="page-back" onClick={onBack}><i className="fas fa-arrow-left"></i></button>
                    <h1 className="page-title">{t('payments_title')}</h1>
                </div>
            </div>
            <div className="page-content">
                <div className="profile-section">
                    <div className="profile-section-title"><i className="fas fa-credit-card"></i> {t('payments_saved_title')}</div>
                    
                    {isLoading ? (
                        <div style={{display:'flex',justifyContent:'center',padding:'2rem'}}><Spinner size="lg" /></div>
                    ) : cards.length === 0 ? (
                        <div style={{textAlign:'center',padding:'2rem',color:'#666'}}>
                            <i className="far fa-credit-card" style={{fontSize:'2.5rem',color:'#ccc',marginBottom:'1rem',display:'block'}}></i>
                            <p>{t('payments_empty')}</p>
                        </div>
                    ) : cards.map(card => (
                        <div key={card.id} className="payment-card-item">
                            <div className="payment-card-icon"><i className={`fab ${cardIcon(card.brand)}`}></i></div>
                            <div className="payment-card-info">
                                <div className="payment-card-number">•••• •••• •••• {card.last4 || '****'}</div>
                                <div className="payment-card-exp">{card.brand || t('payment_card_fallback')} {card.exp_month && card.exp_year ? `• ${String(card.exp_month).padStart(2,'0')}/${card.exp_year}` : ''}</div>
                            </div>
                            {card.is_default ? (
                                <span className="payment-card-default">{t('payments_default')}</span>
                            ) : (
                                <button className="btn btn-sm btn-outline" onClick={() => handleSetDefault(card.id)} style={{fontSize:'0.75rem',padding:'4px 10px'}}>{t('payments_set_default')}</button>
                            )}
                            <button className="payment-card-delete" onClick={() => handleDelete(card.id)}><i className="fas fa-trash"></i></button>
                        </div>
                    ))}
                    
                    <button className="btn btn-primary" onClick={handleAddCard} disabled={isAdding} style={{width:'100%',marginTop:'1rem',justifyContent:'center'}}>
                        {isAdding ? <Spinner /> : <><i className="fas fa-plus"></i> {t('payments_add_card')}</>}
                    </button>
                </div>
                
                <div className="profile-section">
                    <div className="profile-section-title"><i className="fas fa-shield-alt"></i> {t('payments_security_title')}</div>
                    <p style={{fontSize:'0.9rem',color:'#666',lineHeight:1.6}}>
                        {t('payments_security_text')}
                    </p>
                </div>
            </div>
        </div>
    );
};

// ============================================================
// PAGE: MON PROFIL
// ============================================================

const ProfilePage = ({ onBack }) => {
    const { user, setUser } = useAuth();
    const toast = useToast();
    const { t } = useTranslation();
    const [profile, setProfile] = useState({
        first_name: user?.first_name || '',
        last_name: user?.last_name || '',
        email: user?.email || '',
        phone_number: user?.phone_number || ''
    });
    const [isSaving, setIsSaving] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    
    useEffect(() => {
        (async () => {
            try {
                const r = await window.taxiBookAPI.getProfile();
                if (r.success && r.data) {
                    const p = r.data.user || r.data;
                    setProfile({
                        first_name: p.first_name || '',
                        last_name: p.last_name || '',
                        email: p.email || '',
                        phone_number: p.phone_number || user?.phone_number || ''
                    });
                }
            } catch (e) { console.error(e); }
            finally { setIsLoading(false); }
        })();
    }, []);
    
    const handleSave = async () => {
        setIsSaving(true);
        try {
            const r = await window.taxiBookAPI.updateProfile({
                first_name: profile.first_name,
                last_name: profile.last_name,
                email: profile.email
            });
            if (r.success) {
                toast.show(t('toast_profile_updated'), 'success');
                const updated = { ...user, ...profile };
                setUser(updated);
                localStorage.setItem('taxibook_user', JSON.stringify(updated));
            } else {
                toast.show(r.error || t('toast_generic_error'), 'error');
            }
        } catch (e) { toast.show(t('toast_connection_error'), 'error'); }
        finally { setIsSaving(false); }
    };
    
    return (
        <div className="page-container">
            <div className="page-header">
                <div className="page-header-inner">
                    <button className="page-back" onClick={onBack}><i className="fas fa-arrow-left"></i></button>
                    <h1 className="page-title">{t('profile_title')}</h1>
                </div>
            </div>
            <div className="page-content">
                {isLoading ? (
                    <div style={{display:'flex',justifyContent:'center',padding:'4rem'}}><Spinner size="lg" /></div>
                ) : (
                    <>
                        <div className="profile-section">
                            <div className="profile-section-title"><i className="fas fa-user"></i> {t('profile_personal_title')}</div>
                            <div className="contact-form">
                                <div className="form-row">
                                    <div className="form-field">
                                        <label>{t('booking_label_firstname')}</label>
                                        <input type="text" value={profile.first_name} onChange={e => setProfile({...profile, first_name: e.target.value})} placeholder={t('booking_ph_firstname')} />
                                    </div>
                                    <div className="form-field">
                                        <label>{t('booking_label_lastname')}</label>
                                        <input type="text" value={profile.last_name} onChange={e => setProfile({...profile, last_name: e.target.value})} placeholder={t('booking_ph_lastname')} />
                                    </div>
                                </div>
                                <div className="form-field">
                                    <label>{t('booking_label_email')}</label>
                                    <input type="email" value={profile.email} onChange={e => setProfile({...profile, email: e.target.value})} placeholder={t('booking_ph_email')} />
                                </div>
                                <div className="form-field">
                                    <label>{t('booking_label_phone')}</label>
                                    <input type="tel" value={profile.phone_number} disabled style={{opacity:0.6,cursor:'not-allowed'}} />
                                    <span className="field-hint">{t('profile_phone_readonly_hint')}</span>
                                </div>
                                <button className="btn btn-primary" onClick={handleSave} disabled={isSaving} style={{width:'100%',justifyContent:'center',marginTop:'0.5rem'}}>
                                    {isSaving ? <Spinner /> : <><i className="fas fa-check"></i> {t('profile_save')}</>}
                                </button>
                            </div>
                        </div>
                        
                        <div className="profile-section">
                            <div className="profile-section-title"><i className="fas fa-bell"></i> {t('profile_notifications_title')}</div>
                            <p style={{fontSize:'0.9rem',color:'#666',lineHeight:1.6}}>
                                {t('profile_notifications_text')}
                            </p>
                        </div>
                    </>
                )}
            </div>
        </div>
    );
};

// ============================================================
// COMPOSANT PRINCIPAL APP
// ============================================================

const App = () => {
    const { t, lang, setLang } = useTranslation();
    // Widget state
    const [widgetConfig, setWidgetConfig] = useState(null);
    const [widgetLoading, setWidgetLoading] = useState(false);

    useEffect(() => {
        const params = new URLSearchParams(window.location.search);
        const wId = params.get('w');
        if (!wId) return;

        setWidgetLoading(true);
        fetch(`${API_CONFIG.BASE_URL}/widgets/public/${wId}`)
            .then(r => r.json())
            .then(data => {
                if (data.success && data.data) {
                    const cfg = data.data;
                    setWidgetConfig(cfg);
                    applyWidgetBranding(cfg);
                    // Track click
                    fetch(`${API_CONFIG.BASE_URL}/widgets/public/${wId}/click`, { method: 'POST' }).catch(() => {});
                }
            })
            .catch(err => console.error('Widget load error:', err))
            .finally(() => setWidgetLoading(false));
    }, []);

    // Branding dynamique
    const [branding, setBranding] = useState({ display_name: 'TaxiBook', logo_url: '', primary_color: '#f97316', company_name: '', company_address: '', contact_phone: '', contact_email: '' });
    useEffect(() => {
        fetch(`${API_CONFIG.BASE_URL}/settings/branding`).then(r => r.json()).then(res => {
            const d = res.data || res;
            setBranding(prev => ({ ...prev, ...d }));
            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; }
            if (d.primary_color) {
                document.documentElement.style.setProperty('--color-primary', d.primary_color);
                // Assombrir légèrement pour le gradient du picker
                document.documentElement.style.setProperty('--color-primary-dark', d.primary_color);
            }
        }).catch(() => {});
    }, []);

    useEffect(() => {
        if (widgetConfig?.source_title) {
            document.title = t('doc_title_widget', { source_title: widgetConfig.source_title });
        } else if (branding.display_name && branding.display_name !== 'TaxiBook') {
            document.title = t('doc_title_branding', { display_name: branding.display_name });
        } else {
            document.title = t('doc_title_default');
        }
    }, [lang, t, widgetConfig, branding.display_name]);

    // Auth state
    const [user, setUser] = useState(() => {
        const saved = localStorage.getItem('taxibook_user');
        return saved ? JSON.parse(saved) : null;
    });
    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 + url.search);
            (async () => {
                try {
                    const result = await window.taxiBookAPI.verifyMagicLink(magicToken);
                    if (result.success && result.data) {
                        const userData = result.data.user || result.data;
                        setUser(userData);
                        localStorage.setItem('taxibook_user', JSON.stringify(userData));
                    }
                } catch (e) { /* invalid token */ }
            })();
        }
    }, []);
    
    // Booking state
    const [searchData, setSearchData] = useState(null);
    const [liveOrigin, setLiveOrigin] = useState(null);
    const [liveDestination, setLiveDestination] = useState(null);
    const [routeData, setRouteData] = useState(null);
    const [currentPage, setCurrentPage] = useState('home');
    const [bookingStep, setBookingStep] = useState(null);
    const [confirmedBooking, setConfirmedBooking] = useState(null);
    const [pendingBooking, setPendingBooking] = useState(null);
    
    // Toast state
    const [toasts, setToasts] = useState([]);
    
    const showToast = useCallback((message, type = 'info') => {
        const id = Date.now();
        setToasts(prev => [...prev, { id, message, type }]);
    }, []);
    
    const removeToast = useCallback((id) => {
        setToasts(prev => prev.filter(t => t.id !== id));
    }, []);
    
    // Listen for auth logout events
    useEffect(() => {
        const handleLogout = () => {
            setUser(null);
        };
        window.addEventListener('auth:logout', handleLogout);
        return () => window.removeEventListener('auth:logout', handleLogout);
    }, []);
    
    // Handle pending booking after successful auth
    // This useEffect triggers when user changes and there's a pending booking
    useEffect(() => {
        if (user && pendingBooking) {
            const bookingToProcess = pendingBooking;
            setPendingBooking(null);
            setBookingStep('processing');
            
            // Process the booking with the now-authenticated user
            (async () => {
                try {
                    const result = await window.taxiBookAPI.createBooking({
                        pickup_address: bookingToProcess.origin.address,
                        pickup_latitude: bookingToProcess.origin.latitude,
                        pickup_longitude: bookingToProcess.origin.longitude,
                        dropoff_address: bookingToProcess.destination.address,
                        dropoff_latitude: bookingToProcess.destination.latitude,
                        dropoff_longitude: bookingToProcess.destination.longitude,
                        vehicle_type: bookingToProcess.vehicle.code,
                        estimated_price: bookingToProcess.price,
                        pickup_datetime: bookingToProcess.datetime,
                        passengers: bookingToProcess.passengers || 1,
                        customer_name: bookingToProcess.contact ? `${bookingToProcess.contact.first_name} ${bookingToProcess.contact.last_name}`.trim() : undefined,
                        customer_phone: bookingToProcess.contact?.phone,
                        customer_email: bookingToProcess.contact?.email,
                        flight_number: bookingToProcess.contact?.flight_number || undefined,
                        notes: bookingToProcess.contact?.comment || undefined,
                        options: bookingToProcess.options || [],
                        options_total: bookingToProcess.options_total || 0,
                        source: 'site'
                    });
                    
                    if (result.success) {
                        const confirmed = buildConfirmedBooking(result, bookingToProcess);
                        if (!confirmed.job_hash) {
                            showToast(t('toast_booking_no_ref'), 'error');
                            setBookingStep(null);
                            return;
                        }
                        setConfirmedBooking(confirmed);
                        setBookingStep('success');
                    } else {
                        showToast(result.error || t('toast_booking_error'), 'error');
                        setBookingStep(null);
                    }
                } catch (error) {
                    showToast(t('toast_connection_error'), 'error');
                    setBookingStep(null);
                }
            })();
        }
    }, [user, pendingBooking]);
    
    const handleAddressChange = useCallback(async (origin, destination) => {
        setLiveOrigin(origin?.latitude ? origin : null);
        setLiveDestination(destination?.latitude ? destination : null);
        
        if (origin?.latitude && destination?.latitude) {
            try {
                const dirResult = await window.taxiBookAPI.getDirections(
                    `${origin.latitude},${origin.longitude}`,
                    `${destination.latitude},${destination.longitude}`
                );
                
                let polyline = null;
                if (dirResult?.code === 1 && dirResult?.datas?.routes?.[0]) {
                    polyline = dirResult.datas.routes[0].overview_polyline?.points;
                } else if (dirResult?.routes?.[0]) {
                    polyline = dirResult.routes[0].overview_polyline?.points;
                } else if (dirResult?.data?.routes?.[0]) {
                    polyline = dirResult.data.routes[0].overview_polyline?.points;
                }
                
                if (polyline) {
                    setRouteData({ polyline });
                } else {
                    setRouteData(null);
                }
            } catch (e) {
                console.log('Could not fetch directions for map');
                setRouteData(null);
            }
        } else {
            setRouteData(null);
        }
    }, []);
    
    const handleSearch = async (data) => {
        setSearchData(data);
        setBookingStep('inline');
    };
    
    const handleBook = async (bookingData) => {
        try {
            const result = await window.taxiBookAPI.createBooking({
                pickup_address: bookingData.origin.address,
                pickup_latitude: bookingData.origin.latitude,
                pickup_longitude: bookingData.origin.longitude,
                dropoff_address: bookingData.destination.address,
                dropoff_latitude: bookingData.destination.latitude,
                dropoff_longitude: bookingData.destination.longitude,
                vehicle_type: bookingData.vehicle.code,
                estimated_price: bookingData.price,
                pickup_datetime: bookingData.datetime,
                passengers: bookingData.passengers || 1,
                customer_name: bookingData.contact ? `${bookingData.contact.first_name} ${bookingData.contact.last_name}`.trim() : undefined,
                customer_phone: bookingData.contact?.phone,
                customer_email: bookingData.contact?.email,
                flight_number: bookingData.contact?.flight_number || undefined,
                notes: bookingData.contact?.comment || undefined,
                options: bookingData.options || [],
                options_total: bookingData.options_total || 0,
                payment_method: bookingData.payment_method || 'card',
                saved_card_id: bookingData.saved_card_id || null,
                source: 'site'
            });
            
            if (result.success) {
                const confirmed = buildConfirmedBooking(result, bookingData);
                if (!confirmed.job_hash) {
                    showToast(t('toast_booking_no_ref'), 'error');
                    return;
                }
                setConfirmedBooking(confirmed);
                setBookingStep('success');
            } else {
                showToast(result.error || t('toast_booking_error'), 'error');
            }
        } catch (error) {
            showToast(t('toast_connection_error'), 'error');
        }
    };
    
    const handleAuthSuccess = (authData) => {
        const userData = authData.user || authData;
        setUser(userData);
        localStorage.setItem('taxibook_user', JSON.stringify(userData));
        setShowAuthModal(false);
        // pendingBooking will be processed by the useEffect above
    };
    
    const handleLogout = () => {
        window.taxiBookAPI.logout();
        setUser(null);
        showToast(t('toast_logout_success'), 'success');
    };
    
    const toastContext = {
        show: showToast
    };
    
    const handleNavigate = (page) => {
        setCurrentPage(page);
        window.scrollTo(0, 0);
    };
    
    const wc = widgetConfig;
    const navbarTitle = wc?.source_title || branding.display_name || t('nav_brand_fallback');
    const navbarLogo = wc?.logo_url || branding.logo_url || null;
    const heroSubtitle = wc?.source_title
        ? t('hero_subtitle_widget', { source_title: wc.source_title })
        : t('hero_subtitle_default');

    return (
        <AuthContext.Provider value={{ user, setUser }}>
            <ToastContext.Provider value={toastContext}>
                <WidgetContext.Provider value={widgetConfig}>

                {/* Widget branded navbar */}
                {wc ? (
                    <nav className="navbar" style={{ borderBottom: `3px solid ${wc.accent_color || wc.primary_color || '#000'}` }}>
                        <a href={wc.source_url || '#'} className="navbar-logo" target={wc.source_url ? '_blank' : undefined} rel="noopener noreferrer">
                            {navbarLogo ? (
                                <img src={navbarLogo} alt={navbarTitle} style={{ height: 36, maxWidth: 180, objectFit: 'contain' }} />
                            ) : (
                                <span>{navbarTitle}</span>
                            )}
                        </a>
                        <div className="navbar-links">
                            {wc.source_phone && (
                                <a href={`tel:${wc.source_phone}`}><i className="fas fa-phone" style={{ marginRight: 4 }}></i> {wc.source_phone}</a>
                            )}
                            {wc.source_url && (
                                <a href={wc.source_url} target="_blank" rel="noopener noreferrer">{wc.source_title || t('nav_website_fallback')}</a>
                            )}
                        </div>
                        <div className="navbar-actions">
                            <select className="navbar-lang-select" value={lang} onChange={e=>setLang(e.target.value)} aria-label={t('language')}>
                                {LANGUAGES.map(l => <option key={l.code} value={l.code}>{l.native}</option>)}
                            </select>
                            {user ? (
                                <button className="btn btn-outline" onClick={() => { handleLogout(); setCurrentPage('home'); }}>
                                    <i className="fas fa-sign-out-alt"></i>
                                </button>
                            ) : (
                                <button className="btn btn-primary" onClick={() => setShowAuthModal(true)} style={{ background: wc.button_bg, color: wc.button_text }}>
                                    <i className="fas fa-user"></i> {t('nav_login')}
                                </button>
                            )}
                        </div>
                    </nav>
                ) : (
                    <Navbar 
                        user={user} 
                        onLogin={() => setShowAuthModal(true)}
                        onLogout={() => { handleLogout(); setCurrentPage('home'); }}
                        onNavigate={handleNavigate}
                        branding={branding}
                    />
                )}
                
                {currentPage === 'home' && (
                    <>
                        <div className="main-container">
                            <div className="booking-section">
                                {/* Widget branding banner */}
                                {wc && wc.show_logo !== 0 && wc.logo_url && (
                                    <div className="animate-fade-in" style={{ textAlign: 'center', padding: '16px 0 8px', background: wc.banner_bg || '#eee', borderRadius: 12, marginBottom: 16 }}>
                                        <img src={wc.logo_url} alt={wc.source_title || ''} style={{ maxHeight: 48, maxWidth: '80%', objectFit: 'contain' }} />
                                    </div>
                                )}

                                {bookingStep === 'success' && confirmedBooking ? (
                                    <BookingSuccessScreen
                                        booking={confirmedBooking}
                                        onClose={() => {
                                            setConfirmedBooking(null);
                                            setSearchData(null);
                                            setBookingStep(null);
                                            setLiveOrigin(null);
                                            setLiveDestination(null);
                                            setRouteData(null);
                                        }}
                                    />
                                ) : bookingStep === 'inline' && searchData ? (
                                    <InlineBookingFlow
                                        searchData={searchData}
                                        onBook={handleBook}
                                        onModify={() => { setBookingStep(null); }}
                                    />
                                ) : (
                                    <>
                                        <div className="booking-header animate-fade-in">
                                            <h1 className="booking-title">
                                                {wc?.source_title ? t('hero_title_widget', {source_title: wc.source_title}) : <>{t('hero_title_before')} <span>{t('hero_title_highlight')}</span></>}
                                            </h1>
                                            <p className="booking-subtitle">{heroSubtitle}</p>
                                        </div>
                                        
                                        <BookingForm onSearch={handleSearch} onAddressChange={handleAddressChange} />
                                    </>
                                )}
                            </div>
                            
                            <div className="map-section">
                                <MapComponent 
                                    origin={liveOrigin || searchData?.origin} 
                                    destination={liveDestination || searchData?.destination}
                                    route={routeData}
                                />
                            </div>
                        </div>
                    </>
                )}
                
                {currentPage === 'services' && <ServicesPage onBack={() => handleNavigate('home')} onNavigate={handleNavigate} />}
                {currentPage === 'driver' && <DriverPage onBack={() => handleNavigate('home')} />}
                {currentPage === 'contact' && <ContactPage onBack={() => handleNavigate('home')} branding={branding} />}
                {currentPage === 'bookings' && <BookingsPage onBack={() => handleNavigate('home')} />}
                {currentPage === 'payments' && <PaymentsPage onBack={() => handleNavigate('home')} />}
                {currentPage === 'profile' && <ProfilePage onBack={() => handleNavigate('home')} />}
                
                <AuthModal
                    isOpen={showAuthModal}
                    onClose={() => setShowAuthModal(false)}
                    onSuccess={handleAuthSuccess}
                />
                
                <ToastContainer toasts={toasts} removeToast={removeToast} />

                </WidgetContext.Provider>
            </ToastContext.Provider>
        </AuthContext.Provider>
    );
};

// ============================================================
// RENDER
// ============================================================

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<LanguageProvider><App /></LanguageProvider>);
