// ============================================================================
// TaxiBook Mon Compte - Application principale
// Style mdriver / orange (#FFB800), basée sur app.my
// ============================================================================

const { useState, useEffect, useRef, useCallback, useMemo, createContext, useContext } = React;

const API_URL = (window.API_CONFIG && window.API_CONFIG.BASE_URL) || 'https://api.app.taxibook.ch';
const TOKEN_KEY = (window.API_CONFIG && window.API_CONFIG.AUTH_TOKEN_KEY) || 'my_token';
const USER_KEY = (window.API_CONFIG && window.API_CONFIG.USER_DATA_KEY) || 'my_user';

// ============================================================================
// API HELPER
// ============================================================================
function apiRequest(endpoint, options = {}) {
    const token = localStorage.getItem(TOKEN_KEY);
    const headers = { 'Content-Type': 'application/json', ...options.headers };
    if (token) headers['Authorization'] = `Bearer ${token}`;
    return fetch(`${API_URL}${endpoint}`, { ...options, headers }).then(r => r.json());
}

// ============================================================================
// CONTEXT
// ============================================================================
const BrandingContext = createContext({
    display_name: 'TaxiBook', logo_url: '', display_url: '', primary_color: '#FFB800',
    company_name: '', company_address: '', contact_phone: '', contact_email: ''
});
const useBranding = () => useContext(BrandingContext);

// ============================================================================
// NOTIFICATIONS (toasts plein-écran style mdriver)
// ============================================================================
const useNotifications = () => {
    return useMemo(() => {
        const show = (message, type = 'info') => {
            const existing = document.querySelectorAll('.notification');
            existing.forEach((notif, i) => { notif.style.transform = `translateY(${(i + 1) * 80}px)`; });
            const n = document.createElement('div');
            n.className = `notification ${type}`;
            n.innerHTML = `<div class="notification-content">${message}</div>`;
            document.body.appendChild(n);
            const remove = () => {
                if (n.classList.contains('slide-out')) return;
                n.classList.add('slide-out');
                setTimeout(() => { n.remove(); document.querySelectorAll('.notification').forEach((x, i) => { x.style.transform = `translateY(${i * 80}px)`; }); }, 280);
            };
            setTimeout(remove, 4000);
            n.addEventListener('click', remove);
        };
        return {
            success: (msg) => show(msg, 'success'),
            error: (msg) => show(msg, 'error'),
            info: (msg) => show(msg, 'info')
        };
    }, []);
};

// ============================================================================
// HELPERS
// ============================================================================
const statusLabel = (s) => ({
    completed: 'Terminée', cancelled: 'Annulée', cancelled_central: 'Annulée centrale',
    pending: 'En attente', confirmed: 'Confirmée', booked: 'Réservée',
    searching: 'Recherche de taxi', accepted: 'Taxi en approche',
    driver_arriving: 'Taxi en approche', driver_arrived: 'Attente prise en charge',
    onboard: 'Passager à bord', in_progress: 'Passager à bord',
    awaiting_payment: 'Attente paiement', processing_payment: 'Paiement en cours',
    no_driver: 'Aucun taxi disponible'
}[s] || s);

const canCancel = (s) => ['pending', 'confirmed', 'searching', 'assigned', 'accepted', 'driver_arriving'].includes(s);

const fmtDate = (d) => d ? new Date(d).toLocaleDateString('fr-CH', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : '';
const fmtDateShort = (d) => d ? new Date(d).toLocaleDateString('fr-CH', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }) : '';

// ============================================================================
// COUNTDOWN
// ============================================================================
const useCountdown = (targetDate) => {
    const [now, setNow] = useState(Date.now());
    useEffect(() => {
        if (!targetDate) return;
        const iv = setInterval(() => setNow(Date.now()), 1000);
        return () => clearInterval(iv);
    }, [targetDate]);
    if (!targetDate) return null;
    const diff = new Date(targetDate).getTime() - now;
    if (diff <= 0) return null;
    const h = Math.floor(diff / 3600000), m = Math.floor((diff % 3600000) / 60000), s = Math.floor((diff % 60000) / 1000);
    return h > 0 ? `${h}h ${String(m).padStart(2, '0')}min` : `${m}min ${String(s).padStart(2, '0')}s`;
};

const CountdownBadge = ({ datetime }) => {
    const cd = useCountdown(datetime);
    if (!cd) return null;
    return (
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 8px', borderRadius: 6, background: 'rgba(255,184,0,0.15)', color: '#b45309', fontSize: 11, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
            <i className="fas fa-clock" style={{ fontSize: 9 }}></i>{cd}
        </span>
    );
};

// ============================================================================
// LOGIN SCREEN (Magic Link)
// ============================================================================
const LoginScreen = () => {
    const branding = useBranding();
    const notifications = useNotifications();
    const [email, setEmail] = useState('');
    const [loading, setLoading] = useState(false);
    const [sent, setSent] = useState(false);

    const sendLink = async () => {
        if (!email || !email.includes('@')) {
            notifications.error('Veuillez saisir un email valide');
            return;
        }
        setLoading(true);
        try {
            const res = await apiRequest('/auth/client/magic-link', { method: 'POST', body: JSON.stringify({ email: email.trim(), app_origin: 'my' }) });
            if (res.success || res.data) {
                setSent(true);
                notifications.success('Lien envoyé par email');
            } else {
                notifications.error(res.message || 'Erreur lors de l\'envoi');
            }
        } catch {
            notifications.error('Erreur de connexion');
        }
        setLoading(false);
    };

    return (
        <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'linear-gradient(135deg, #FFB800 0%, #EAB308 100%)', padding: 20 }}>
            <div className="card scale-in" style={{ width: '100%', maxWidth: 420, padding: 32, borderRadius: 20, boxShadow: '0 24px 48px -8px rgba(0,0,0,0.18)' }}>
                <div style={{ textAlign: 'center', marginBottom: 24 }}>
                    {branding.logo_url ? (
                        <img src={branding.logo_url} alt={branding.display_name} style={{ height: 56, maxWidth: 200, objectFit: 'contain', margin: '0 auto 12px', display: 'block' }} />
                    ) : (
                        <div style={{ width: 56, height: 56, borderRadius: 16, background: 'linear-gradient(135deg, #FFB800, #EAB308)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px', boxShadow: '0 6px 16px rgba(255,184,0,0.4)' }}>
                            <i className="fas fa-user" style={{ color: 'white', fontSize: 22 }}></i>
                        </div>
                    )}
                    <h1 style={{ fontSize: 22, fontWeight: 800, color: '#111827', margin: 0 }}>{branding.display_name}</h1>
                    <p style={{ color: '#6B7280', marginTop: 6, fontSize: 14 }}>Mon Compte</p>
                </div>

                {!sent ? (
                    <>
                        <div style={{ marginBottom: 16 }}>
                            <label className="input-label">Adresse email</label>
                            <input
                                type="email"
                                className="input-field"
                                placeholder="votre@email.com"
                                value={email}
                                onChange={e => setEmail(e.target.value)}
                                onKeyDown={e => e.key === 'Enter' && sendLink()}
                                autoComplete="email"
                            />
                        </div>
                        <button className="btn-primary" style={{ width: '100%' }} onClick={sendLink} disabled={loading || !email.includes('@')}>
                            {loading ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-envelope"></i>Recevoir le lien de connexion</>}
                        </button>
                        <p style={{ fontSize: 12, color: '#9CA3AF', marginTop: 14, textAlign: 'center' }}>
                            <i className="fas fa-shield-alt" style={{ marginRight: 4 }}></i>
                            Un lien sécurisé sera envoyé à votre email
                        </p>
                    </>
                ) : (
                    <div style={{ textAlign: 'center' }}>
                        <div style={{ width: 56, height: 56, borderRadius: 16, background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
                            <i className="fas fa-envelope-circle-check" style={{ color: '#16a34a', fontSize: 22 }}></i>
                        </div>
                        <p style={{ color: '#374151', marginBottom: 4, fontWeight: 500 }}>Lien envoyé à</p>
                        <p style={{ fontWeight: 700, color: '#111827', marginBottom: 16, fontSize: 15 }}>{email}</p>
                        <p style={{ fontSize: 13, color: '#6B7280', marginBottom: 22 }}>Consultez votre boîte email et cliquez sur le lien. Expire dans 15 minutes.</p>
                        <button className="btn-outline" style={{ width: '100%' }} onClick={() => { setSent(false); setEmail(''); }}>
                            <i className="fas fa-arrow-left"></i>Utiliser une autre adresse
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
};

// ============================================================================
// USER DROPDOWN
// ============================================================================
const UserDropdown = ({ user, activePage, onNavigate, onLogout }) => {
    const [open, setOpen] = useState(false);
    const ref = useRef(null);
    useEffect(() => {
        const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', h);
        return () => document.removeEventListener('mousedown', h);
    }, []);

    const items = [
        { id: 'home', icon: 'fa-home', label: 'Accueil' },
        { id: 'booking', icon: 'fa-taxi', label: 'Réserver' },
        { id: 'rides', icon: 'fa-car', label: 'Mes courses' },
        { id: 'requests', icon: 'fa-headset', label: 'Mes demandes' },
        { id: 'payments', icon: 'fa-credit-card', label: 'Mes cartes' },
        { id: 'invoices', icon: 'fa-file-invoice', label: 'Mes factures' },
        { id: 'profile', icon: 'fa-user', label: 'Mon profil' }
    ];

    const initial = (user.first_name || user.email || 'U')[0].toUpperCase();

    return (
        <div ref={ref} style={{ position: 'relative' }}>
            <button onClick={() => setOpen(!open)} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px 6px 6px', borderRadius: 999, border: '1px solid #E5E7EB', background: open ? '#fafbfc' : 'white', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, color: '#374151', transition: 'all 0.15s' }}>
                <div style={{ width: 30, height: 30, borderRadius: '50%', background: 'linear-gradient(135deg, #FFB800, #EAB308)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, color: 'white', fontWeight: 700, boxShadow: '0 2px 6px rgba(255,184,0,0.35)' }}>{initial}</div>
                <span style={{ maxWidth: 110, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 500 }}>{user.first_name || (user.email || '').split('@')[0]}</span>
                <i className="fas fa-chevron-down" style={{ fontSize: 10, color: '#94a3b8', transition: 'transform 0.2s', transform: open ? 'rotate(180deg)' : 'none' }}></i>
            </button>
            {open && (
                <div className="dropdown-menu">
                    {items.map(it => (
                        <button key={it.id} className={`dropdown-item ${activePage === it.id ? 'active' : ''}`} onClick={() => { onNavigate(it.id); setOpen(false); }}>
                            <i className={`fas ${it.icon}`} style={{ width: 18, textAlign: 'center', fontSize: 14 }}></i>
                            {it.label}
                        </button>
                    ))}
                    <div className="dropdown-sep"></div>
                    <button className="dropdown-item danger" onClick={() => { onLogout(); setOpen(false); }}>
                        <i className="fas fa-sign-out-alt" style={{ width: 18, textAlign: 'center', fontSize: 14 }}></i>
                        Déconnexion
                    </button>
                </div>
            )}
        </div>
    );
};

// ============================================================================
// RIDE DETAIL (Slide Panel)
// ============================================================================
const RideDetail = ({ ride, onBack, onCancelled, onNavigate }) => {
    const branding = useBranding();
    const notifications = useNotifications();
    const [cancelling, setCancelling] = useState(false);
    const [closing, setClosing] = useState(false);
    const [actionSending, setActionSending] = useState(null);
    const domain = (branding.display_url || 'taxis.ch').replace(/^https?:\/\//, '').replace(/\/+$/, '');

    const close = () => { setClosing(true); setTimeout(onBack, 200); };

    const handleCancel = async () => {
        if (!confirm('Voulez-vous vraiment annuler cette course ?')) return;
        setCancelling(true);
        try {
            const res = await apiRequest(`/jobs/${ride.job_hash}/cancel`, { method: 'POST', body: JSON.stringify({ reason: 'Annulé par le client' }) });
            if (res.success) { notifications.success('Course annulée'); onCancelled && onCancelled(); }
            else notifications.error(res.error || 'Impossible d\'annuler');
        } catch { notifications.error('Erreur de connexion'); }
        setCancelling(false);
    };

    const openTicket = async (category, subject) => {
        setActionSending(category);
        try {
            const ref = ride.job_hash || '';
            const res = await apiRequest('/support/tickets/create', { method: 'POST', body: JSON.stringify({ category, subject: `${subject} - #${ref}`, message: `${subject} - #${ref}` }) });
            if (res.success) { notifications.success('Demande créée'); onNavigate && onNavigate('requests'); }
        } catch { notifications.error('Erreur'); }
        setActionSending(null);
    };

    const actionBtns = [
        { id: 'lost_item', icon: 'fa-box-open', label: 'Objet perdu', subject: 'Objet perdu', color: '#f59e0b', bg: '#fffbeb', border: '#fef3c7' },
        { id: 'complaint', icon: 'fa-exclamation-triangle', label: 'Réclamation', subject: 'Réclamation', color: '#ef4444', bg: '#fef2f2', border: '#fecaca' },
        { id: 'other', icon: 'fa-headset', label: 'Assistance', subject: 'Demande d\'assistance', color: '#3b82f6', bg: '#eff6ff', border: '#dbeafe' },
        { id: 'receipt', icon: 'fa-file-invoice', label: 'Quittance', subject: 'Demande de quittance', color: '#8b5cf6', bg: '#f5f3ff', border: '#ede9fe' }
    ];

    const payLabels = { paid: 'Payé', authorized: 'Autorisé', awaiting_payment: 'Attente paiement', pending: 'En attente', processing_payment: 'En cours', captured: 'Capturé' };

    return (
        <div className={`slide-panel ${closing ? 'closing' : ''}`}>
            <div className="slide-header">
                <button className="slide-back" onClick={close}><i className="fas fa-arrow-left"></i></button>
                <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 15, color: '#111827' }}>Course</div>
                    <div style={{ fontSize: 12, color: '#94a3b8' }}>#{ride.job_hash?.substring(0, 12)}</div>
                </div>
            </div>

            <div className="page-content">
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className={`status-badge ${ride.status}`} style={{ fontSize: 12, padding: '4px 12px' }}>{statusLabel(ride.status)}</span>
                    <CountdownBadge datetime={ride.pickup_datetime} />
                </div>

                <div className="card-flat">
                    {ride.pickup_address && (
                        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', borderBottom: '1px solid #f1f5f9' }}>
                            <div style={{ width: 10, height: 10, borderRadius: '50%', background: '#22c55e', marginTop: 4, flexShrink: 0 }}></div>
                            <div>
                                <div style={{ fontSize: 11, color: '#94a3b8', fontWeight: 600, marginBottom: 2, textTransform: 'uppercase', letterSpacing: 0.05 }}>Prise en charge</div>
                                <div style={{ fontSize: 14, color: '#1e293b', fontWeight: 500 }}>{ride.pickup_address}</div>
                            </div>
                        </div>
                    )}
                    {ride.dropoff_address && (
                        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px' }}>
                            <div style={{ width: 10, height: 10, borderRadius: '50%', background: '#ef4444', marginTop: 4, flexShrink: 0 }}></div>
                            <div>
                                <div style={{ fontSize: 11, color: '#94a3b8', fontWeight: 600, marginBottom: 2, textTransform: 'uppercase', letterSpacing: 0.05 }}>Destination</div>
                                <div style={{ fontSize: 14, color: '#1e293b', fontWeight: 500 }}>{ride.dropoff_address}</div>
                            </div>
                        </div>
                    )}
                </div>

                <div className="card-flat">
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
                        <div style={{ padding: '12px 16px', borderBottom: '1px solid #f1f5f9', borderRight: '1px solid #f1f5f9' }}>
                            <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 2 }}>Date</div>
                            <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b' }}>{fmtDate(ride.pickup_datetime)}</div>
                        </div>
                        <div style={{ padding: '12px 16px', borderBottom: '1px solid #f1f5f9' }}>
                            <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 2 }}>Véhicule</div>
                            <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b' }}>{ride.vehicle_type || 'Standard'}</div>
                        </div>
                        <div style={{ padding: '12px 16px', borderRight: '1px solid #f1f5f9' }}>
                            <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 2 }}>Prix</div>
                            <div style={{ fontSize: 13, fontWeight: 700, color: '#FFB800' }}>{ride.final_price ? `CHF ${parseFloat(ride.final_price).toFixed(2)}` : ride.estimated_price ? `CHF ${parseFloat(ride.estimated_price).toFixed(2)}` : '-'}</div>
                        </div>
                        <div style={{ padding: '12px 16px' }}>
                            <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 2 }}>Paiement</div>
                            <div style={{ fontSize: 13, fontWeight: 600, color: ride.payment_status === 'awaiting_payment' ? '#ea580c' : (['authorized', 'paid', 'captured'].includes(ride.payment_status)) ? '#16a34a' : '#1e293b' }}>{payLabels[ride.payment_status] || ride.payment_status || '-'}</div>
                        </div>
                    </div>
                </div>

                {ride.driver_name && (
                    <div className="card-flat">
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }}>
                            <div style={{ width: 44, height: 44, borderRadius: '50%', background: '#fef3c7', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                <i className="fas fa-user" style={{ color: '#FFB800', fontSize: 18 }}></i>
                            </div>
                            <div>
                                <div style={{ fontSize: 14, fontWeight: 600, color: '#1e293b' }}>{ride.driver_name}</div>
                                {ride.vehicle_plate && <div style={{ fontSize: 12, color: '#94a3b8' }}>{ride.vehicle_plate}</div>}
                            </div>
                        </div>
                    </div>
                )}

                {ride.notes && (
                    <div className="card-flat" style={{ padding: '12px 16px' }}>
                        <div style={{ fontSize: 11, color: '#94a3b8', marginBottom: 4, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.05 }}>Notes</div>
                        <div style={{ fontSize: 13, color: '#475569' }}>{ride.notes}</div>
                    </div>
                )}

                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {ride.payment_status === 'awaiting_payment' && ride.job_hash && (
                        <a href={`https://payment.${domain}/?ride_id=${ride.job_hash}`} target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '12px 16px', borderRadius: 12, background: 'linear-gradient(135deg, #ea580c, #dc2626)', color: 'white', fontSize: 14, fontWeight: 700, textDecoration: 'none', boxShadow: '0 4px 14px -2px rgba(220,38,38,0.4)' }}>
                            <i className="fas fa-credit-card"></i>Procéder au paiement
                        </a>
                    )}
                    {ride.job_hash && !['cancelled', 'completed', 'no_show'].includes(ride.status) && (
                        <a href={`https://tracking.${domain}/${ride.job_hash}`} target="_blank" rel="noopener" className="btn-outline" style={{ textDecoration: 'none' }}>
                            <i className="fas fa-location-dot"></i>Suivre la course
                        </a>
                    )}
                    {canCancel(ride.status) && (
                        <button className="btn-danger" onClick={handleCancel} disabled={cancelling}>
                            {cancelling ? <span className="spinner spinner-sm" style={{ borderTopColor: '#dc2626' }}></span> : <><i className="fas fa-times"></i>Annuler la course</>}
                        </button>
                    )}
                </div>

                <div>
                    <div className="section-title">Actions</div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                        {actionBtns.map(a => (
                            <button key={a.id} onClick={() => openTicket(a.id, a.subject)} disabled={!!actionSending}
                                style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px 14px', borderRadius: 12, border: `1px solid ${a.border}`, background: a.bg, cursor: 'pointer', fontSize: 13, fontWeight: 600, color: a.color, fontFamily: 'inherit' }}>
                                {actionSending === a.id ? <span className="spinner spinner-sm" style={{ borderTopColor: a.color }}></span> : <i className={`fas ${a.icon}`} style={{ fontSize: 14 }}></i>}
                                {a.label}
                            </button>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
};

// ============================================================================
// RIDES PAGE
// ============================================================================
const RidesPage = ({ user, onNavigate }) => {
    const [rides, setRides] = useState([]);
    const [loading, setLoading] = useState(true);
    const [filter, setFilter] = useState('upcoming');
    const [selectedRide, setSelectedRide] = useState(null);

    const load = useCallback(() => {
        setLoading(true);
        apiRequest(`/users/${user.uid}/rides?page=1&limit=100`).then(r => { setRides(r.data?.rides || []); setLoading(false); }).catch(() => setLoading(false));
    }, [user.uid]);

    useEffect(load, [load]);

    const now = new Date();
    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterdayStart = new Date(todayStart.getTime() - 86400000);
    const filtered = rides.filter(r => {
        const d = r.pickup_datetime ? new Date(r.pickup_datetime) : null;
        if (!d) return filter === 'past';
        if (filter === 'upcoming') return d >= todayStart && !['cancelled', 'completed', 'no_show'].includes(r.status);
        if (filter === 'yesterday') return d >= yesterdayStart && d < todayStart;
        return d < todayStart || ['cancelled', 'completed', 'no_show'].includes(r.status);
    });

    const filters = [
        { id: 'upcoming', label: 'À venir', icon: 'fa-clock' },
        { id: 'yesterday', label: 'Hier', icon: 'fa-calendar-day' },
        { id: 'past', label: 'Passées', icon: 'fa-history' }
    ];

    if (loading) return <div style={{ textAlign: 'center', padding: 48 }}><div className="spinner"></div></div>;

    return (
        <div className="page-content fade-in">
            <div className="filter-tab">
                {filters.map(f => (
                    <button key={f.id} className={`filter-tab-item ${filter === f.id ? 'active' : ''}`} onClick={() => setFilter(f.id)}>
                        <i className={`fas ${f.icon}`} style={{ marginRight: 4, fontSize: 10 }}></i>{f.label}
                    </button>
                ))}
            </div>

            {filtered.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-icon"><i className="fas fa-car"></i></div>
                    <p style={{ fontSize: 15, fontWeight: 600, color: '#64748b' }}>Aucune course</p>
                    <p style={{ fontSize: 13 }}>{filter === 'upcoming' ? 'Pas de course à venir' : filter === 'yesterday' ? 'Aucune course hier' : 'Aucune course passée'}</p>
                </div>
            ) : (
                <div className="card-flat">
                    {filtered.map((ride, i) => (
                        <div key={i} className="item-row" style={{ flexDirection: 'column', alignItems: 'stretch', gap: 8 }} onClick={() => setSelectedRide(ride)}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                    <span style={{ fontWeight: 700, fontSize: 13, color: '#374151' }}>#{ride.job_hash?.substring(0, 12) || ride.id}</span>
                                    {filter === 'upcoming' && <CountdownBadge datetime={ride.pickup_datetime} />}
                                </div>
                                <span className={`status-badge ${ride.status}`}>{statusLabel(ride.status)}</span>
                            </div>
                            {ride.pickup_address && (
                                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                                    <i className="fas fa-circle" style={{ color: '#22c55e', fontSize: 7, marginTop: 5 }}></i>
                                    <span style={{ fontSize: 13, color: '#475569' }}>{ride.pickup_address}</span>
                                </div>
                            )}
                            {ride.dropoff_address && (
                                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                                    <i className="fas fa-circle" style={{ color: '#ef4444', fontSize: 7, marginTop: 5 }}></i>
                                    <span style={{ fontSize: 13, color: '#475569' }}>{ride.dropoff_address}</span>
                                </div>
                            )}
                            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#94a3b8' }}>
                                <span>{fmtDate(ride.pickup_datetime)}</span>
                                {(ride.final_price || ride.estimated_price) && <span style={{ fontWeight: 700, color: '#FFB800' }}>CHF {parseFloat(ride.final_price || ride.estimated_price).toFixed(2)}</span>}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {selectedRide && <RideDetail ride={selectedRide} onBack={() => setSelectedRide(null)} onCancelled={() => { setSelectedRide(null); load(); }} onNavigate={onNavigate} />}
        </div>
    );
};

// ============================================================================
// TICKET CHAT (Slide Panel)
// ============================================================================
const TicketChat = ({ ticket, onBack }) => {
    const [messages, setMessages] = useState([]);
    const [loading, setLoading] = useState(true);
    const [msg, setMsg] = useState('');
    const [sending, setSending] = useState(false);
    const [closing, setClosing] = useState(false);
    const chatEndRef = useRef(null);
    const isClosed = ticket.status === 'closed' || ticket.status === 'resolved';

    const loadMessages = useCallback(async () => {
        try {
            const res = await apiRequest(`/support/tickets/${ticket.ticket_id}`);
            if (res.success) setMessages(res.data?.messages || []);
        } catch {}
        setLoading(false);
    }, [ticket.ticket_id]);

    useEffect(() => {
        loadMessages();
        apiRequest(`/support/tickets/${ticket.ticket_id}/read`, { method: 'POST' }).catch(() => {});
    }, [loadMessages]);

    useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]);

    const send = async () => {
        if (!msg.trim() || sending) return;
        setSending(true);
        try {
            const res = await apiRequest(`/support/tickets/${ticket.ticket_id}/message`, { method: 'POST', body: JSON.stringify({ message: msg.trim() }) });
            if (res.success) { setMsg(''); loadMessages(); }
        } catch {}
        setSending(false);
    };

    const close = () => { setClosing(true); setTimeout(onBack, 200); };

    const catLabels = { lost_item: 'Objet perdu', claim: 'Réclamation', complaint: 'Réclamation', general: 'Autre', other: 'Autre', receipt: 'Quittance' };
    const statusLabels = { open: 'Ouvert', in_progress: 'En cours', waiting_user: 'En attente de réponse', waiting_support: 'En traitement', resolved: 'Résolu', closed: 'Fermé' };

    return (
        <div className={`slide-panel ${closing ? 'closing' : ''}`}>
            <div className="slide-header">
                <button className="slide-back" onClick={close}><i className="fas fa-arrow-left"></i></button>
                <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14, color: '#111827', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{ticket.subject}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
                        <span style={{ fontSize: 11, color: '#94a3b8' }}>{catLabels[ticket.category] || ticket.category}</span>
                        <span style={{ background: isClosed ? '#f1f5f9' : '#dbeafe', color: isClosed ? '#64748b' : '#1e40af', fontSize: 10, padding: '2px 8px', borderRadius: 999, fontWeight: 600 }}>{statusLabels[ticket.status] || ticket.status}</span>
                    </div>
                </div>
            </div>

            <div className="chat-area scrollbar-thin">
                {loading ? (
                    <div style={{ textAlign: 'center', padding: 32 }}><div className="spinner"></div></div>
                ) : messages.map((m, i) => (
                    <div key={i}>
                        <div className={`chat-bubble ${m.sender_type === 'user' ? 'user' : m.sender_type === 'system' ? 'system' : 'support'}`}>
                            {m.sender_type === 'support' && <div style={{ fontSize: 11, fontWeight: 700, color: '#FFB800', marginBottom: 2 }}>{m.sender_first_name || 'Support'}</div>}
                            {m.message}
                        </div>
                        <div style={{ fontSize: 10, color: '#94a3b8', textAlign: m.sender_type === 'user' ? 'right' : m.sender_type === 'system' ? 'center' : 'left', padding: '2px 8px' }}>{fmtDateShort(m.created_at)}</div>
                    </div>
                ))}
                <div ref={chatEndRef}></div>
            </div>

            {!isClosed && (
                <div className="chat-input-bar">
                    <input
                        className="chat-input"
                        placeholder="Votre message..."
                        value={msg}
                        onChange={e => setMsg(e.target.value)}
                        onKeyDown={e => e.key === 'Enter' && !e.shiftKey && (e.preventDefault(), send())}
                    />
                    <button className="chat-send" onClick={send} disabled={!msg.trim() || sending}>
                        <i className="fas fa-paper-plane" style={{ fontSize: 13 }}></i>
                    </button>
                </div>
            )}
        </div>
    );
};

// ============================================================================
// NEW TICKET FORM (Slide Panel)
// ============================================================================
const NewTicketForm = ({ onBack, onCreated }) => {
    const notifications = useNotifications();
    const [category, setCategory] = useState('general');
    const [message, setMessage] = useState('');
    const [sending, setSending] = useState(false);
    const [closing, setClosing] = useState(false);

    const cats = [
        { id: 'lost_item', icon: 'fa-box-open', label: 'Objet perdu', color: '#f59e0b' },
        { id: 'claim', icon: 'fa-exclamation-triangle', label: 'Réclamation', color: '#ef4444' },
        { id: 'general', icon: 'fa-comment-dots', label: 'Autre', color: '#FFB800' }
    ];

    const close = () => { setClosing(true); setTimeout(onBack, 200); };

    const submit = async () => {
        if (!message.trim()) return;
        setSending(true);
        try {
            const res = await apiRequest('/support/tickets/create', { method: 'POST', body: JSON.stringify({ category, subject: cats.find(c => c.id === category)?.label || 'Demande', message: message.trim() }) });
            if (res.success) { notifications.success('Demande créée'); onCreated && onCreated(); }
            else notifications.error(res.error || 'Erreur');
        } catch { notifications.error('Erreur de connexion'); }
        setSending(false);
    };

    return (
        <div className={`slide-panel ${closing ? 'closing' : ''}`}>
            <div className="slide-header">
                <button className="slide-back" onClick={close}><i className="fas fa-arrow-left"></i></button>
                <span style={{ fontWeight: 700, fontSize: 15, color: '#111827' }}>Nouvelle demande</span>
            </div>
            <div className="page-content">
                <div>
                    <label className="input-label">Type de demande</label>
                    <div style={{ display: 'flex', gap: 8 }}>
                        {cats.map(c => (
                            <button key={c.id} onClick={() => setCategory(c.id)}
                                style={{
                                    flex: 1, padding: '14px 8px', borderRadius: 12,
                                    border: category === c.id ? `2px solid ${c.color}` : '2px solid #E5E7EB',
                                    background: category === c.id ? `${c.color}10` : 'white',
                                    cursor: 'pointer', textAlign: 'center', transition: 'all 0.2s', fontFamily: 'inherit'
                                }}>
                                <i className={`fas ${c.icon}`} style={{ color: c.color, fontSize: 20, display: 'block', marginBottom: 6 }}></i>
                                <span style={{ fontSize: 12, fontWeight: 600, color: category === c.id ? c.color : '#64748b' }}>{c.label}</span>
                            </button>
                        ))}
                    </div>
                </div>
                <div>
                    <label className="input-label">Message</label>
                    <textarea className="input-field" rows="5" placeholder="Décrivez votre demande en détail..." value={message} onChange={e => setMessage(e.target.value)}></textarea>
                </div>
                <button className="btn-primary" style={{ width: '100%' }} onClick={submit} disabled={!message.trim() || sending}>
                    {sending ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-paper-plane"></i>Envoyer la demande</>}
                </button>
            </div>
        </div>
    );
};

// ============================================================================
// REQUESTS PAGE
// ============================================================================
const RequestsPage = ({ user }) => {
    const [tickets, setTickets] = useState([]);
    const [loading, setLoading] = useState(true);
    const [filter, setFilter] = useState('all');
    const [selectedTicket, setSelectedTicket] = useState(null);
    const [showNew, setShowNew] = useState(false);

    const load = () => { setLoading(true); apiRequest('/support/tickets').then(r => { setTickets(r.data?.tickets || []); setLoading(false); }).catch(() => setLoading(false)); };
    useEffect(load, []);

    const filters = [
        { id: 'all', label: 'Tous', icon: 'fa-list' },
        { id: 'lost_item', label: 'Objets', icon: 'fa-box-open' },
        { id: 'claim', label: 'Réclam.', icon: 'fa-exclamation-triangle' },
        { id: 'general', label: 'Autres', icon: 'fa-comment-dots' }
    ];
    const filtered = filter === 'all' ? tickets : tickets.filter(t => t.category === filter);
    const catLabels = { lost_item: 'Objet perdu', claim: 'Réclamation', complaint: 'Réclamation', general: 'Autre', other: 'Autre', receipt: 'Quittance' };
    const catColors = { lost_item: { bg: '#fef3c7', color: '#92400e' }, claim: { bg: '#fee2e2', color: '#991b1b' }, complaint: { bg: '#fee2e2', color: '#991b1b' }, general: { bg: '#fef3c7', color: '#b45309' }, other: { bg: '#dbeafe', color: '#1e40af' }, receipt: { bg: '#ede9fe', color: '#6d28d9' } };
    const statusLabels = { open: 'Ouvert', in_progress: 'En cours', waiting_user: 'Réponse reçue', waiting_support: 'En traitement', resolved: 'Résolu', closed: 'Fermé' };

    if (loading) return <div style={{ textAlign: 'center', padding: 48 }}><div className="spinner"></div></div>;

    return (
        <div className="page-content fade-in">
            <button onClick={() => setShowNew(true)} style={{ width: '100%', padding: '14px 16px', borderRadius: 12, border: '2px dashed #FFB800', background: 'rgba(255,184,0,0.04)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: '#b45309', fontWeight: 600, fontSize: 14, fontFamily: 'inherit', transition: 'all 0.2s' }}>
                <i className="fas fa-plus"></i>Nouvelle demande
            </button>
            <div className="filter-tab">
                {filters.map(f => (
                    <button key={f.id} className={`filter-tab-item ${filter === f.id ? 'active' : ''}`} onClick={() => setFilter(f.id)}>
                        <i className={`fas ${f.icon}`} style={{ marginRight: 4, fontSize: 10 }}></i>{f.label}
                    </button>
                ))}
            </div>

            {filtered.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-icon"><i className="fas fa-headset"></i></div>
                    <p style={{ fontSize: 15, fontWeight: 600, color: '#64748b' }}>Aucune demande</p>
                    <p style={{ fontSize: 13 }}>Vos demandes d'assistance apparaîtront ici</p>
                </div>
            ) : (
                <div className="card-flat">
                    {filtered.map((t, i) => {
                        const cc = catColors[t.category] || catColors.general;
                        const isOpen = !['closed', 'resolved'].includes(t.status);
                        return (
                            <div key={i} className="item-row" style={{ flexDirection: 'column', alignItems: 'stretch', gap: 6 }} onClick={() => setSelectedTicket(t)}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                        <span style={{ background: cc.bg, color: cc.color, fontSize: 11, padding: '3px 9px', borderRadius: 999, fontWeight: 600 }}>{catLabels[t.category] || t.category}</span>
                                        {t.unread_by_user > 0 && <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#FFB800', display: 'inline-block' }}></span>}
                                    </div>
                                    <span style={{ fontSize: 11, color: isOpen ? '#16a34a' : '#94a3b8', fontWeight: 600 }}>{statusLabels[t.status] || t.status}</span>
                                </div>
                                <div style={{ fontWeight: 600, fontSize: 14, color: '#1e293b' }}>{t.subject}</div>
                                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#94a3b8' }}>
                                    <span>{fmtDateShort(t.last_message_at || t.created_at)}</span>
                                    <span>{t.message_count || 0} message{(t.message_count || 0) > 1 ? 's' : ''}</span>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}

            {selectedTicket && <TicketChat ticket={selectedTicket} onBack={() => { setSelectedTicket(null); load(); }} />}
            {showNew && <NewTicketForm onBack={() => setShowNew(false)} onCreated={() => { setShowNew(false); load(); }} />}
        </div>
    );
};

// ============================================================================
// PICKERS (Number, Time, Date)
// ============================================================================
const NumberPicker = ({ value, onChange, min = 0, max = 16, icon, label }) => {
    const [open, setOpen] = useState(false);
    const wrapRef = useRef(null);
    const listRef = useRef(null);
    useEffect(() => {
        const h = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', h);
        return () => document.removeEventListener('mousedown', h);
    }, []);
    useEffect(() => {
        if (open && listRef.current) {
            const idx = value - min;
            if (idx >= 0) listRef.current.scrollTop = Math.max(0, idx * 40 - 80);
        }
    }, [open, value, min]);
    const items = Array.from({ length: max - min + 1 }, (_, i) => min + i);
    return (
        <div ref={wrapRef} style={{ position: 'relative' }}>
            <button type="button" onClick={() => setOpen(!open)}
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '12px 14px', borderRadius: 10, border: open ? '2px solid #FFB800' : '2px solid #E5E7EB', background: 'white', cursor: 'pointer', fontSize: 15, fontWeight: 600, color: '#1e293b', fontFamily: 'inherit' }}>
                <span><i className={`fas ${icon}`} style={{ color: '#FFB800', fontSize: 13, marginRight: 8 }}></i>{value} {label}{value > 1 ? 's' : ''}</span>
                <i className={`fas fa-chevron-${open ? 'up' : 'down'}`} style={{ fontSize: 11, color: '#94a3b8' }}></i>
            </button>
            {open && (
                <div ref={listRef} style={{ position: 'absolute', left: 0, right: 0, top: '100%', marginTop: 4, maxHeight: 200, overflowY: 'auto', borderRadius: 10, border: '1px solid #E5E7EB', background: 'white', boxShadow: '0 8px 24px rgba(0,0,0,0.1)', zIndex: 20 }}>
                    {items.map(n => (
                        <div key={n} onClick={() => { onChange(n); setOpen(false); }}
                            style={{ padding: '10px 16px', cursor: 'pointer', fontSize: 14, fontWeight: value === n ? 700 : 400, color: value === n ? 'white' : '#374151', background: value === n ? '#FFB800' : 'transparent', borderBottom: '1px solid #f1f5f9' }}>
                            {n} {label}{n > 1 ? 's' : ''}
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

const TIME_SLOTS = (() => {
    const arr = [];
    for (let h = 0; h < 24; h++) for (let m = 0; m < 60; m += 15) arr.push(`${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`);
    return arr;
})();

const TimePicker = ({ value, onChange }) => {
    const [open, setOpen] = useState(false);
    const wrapRef = useRef(null);
    const listRef = useRef(null);
    useEffect(() => {
        const h = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
        document.addEventListener('mousedown', h);
        return () => document.removeEventListener('mousedown', h);
    }, []);
    useEffect(() => {
        if (open && listRef.current && value) {
            const idx = TIME_SLOTS.indexOf(value);
            if (idx >= 0) listRef.current.scrollTop = Math.max(0, idx * 40 - 80);
        }
    }, [open, value]);
    return (
        <div ref={wrapRef} style={{ position: 'relative' }}>
            <button type="button" onClick={() => setOpen(!open)}
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '12px 14px', borderRadius: 10, border: open ? '2px solid #FFB800' : '2px solid #E5E7EB', background: 'white', cursor: 'pointer', fontSize: 15, fontWeight: 600, color: '#1e293b', fontFamily: 'inherit' }}>
                <span><i className="fas fa-clock" style={{ color: '#FFB800', fontSize: 13, marginRight: 8 }}></i>{value || '--:--'}</span>
                <i className={`fas fa-chevron-${open ? 'up' : 'down'}`} style={{ fontSize: 11, color: '#94a3b8' }}></i>
            </button>
            {open && (
                <div ref={listRef} style={{ position: 'absolute', left: 0, right: 0, top: '100%', marginTop: 4, maxHeight: 200, overflowY: 'auto', borderRadius: 10, border: '1px solid #E5E7EB', background: 'white', boxShadow: '0 8px 24px rgba(0,0,0,0.1)', zIndex: 20 }}>
                    {TIME_SLOTS.map(slot => (
                        <div key={slot} onClick={() => { onChange(slot); setOpen(false); }}
                            style={{ padding: '10px 16px', cursor: 'pointer', fontSize: 14, fontWeight: value === slot ? 700 : 400, color: value === slot ? 'white' : '#374151', background: value === slot ? '#FFB800' : 'transparent', borderBottom: '1px solid #f1f5f9' }}>
                            {slot}
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

const MONTHS_FR = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
const DAYS_FR = ['Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa', 'Di'];

const DatePicker = ({ value, onChange }) => {
    const [open, setOpen] = useState(false);
    const wrapRef = useRef(null);
    const parsed = value ? new Date(value + 'T00:00:00') : new Date();
    const [viewYear, setViewYear] = useState(parsed.getFullYear());
    const [viewMonth, setViewMonth] = useState(parsed.getMonth());

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

    const today = new Date(); today.setHours(0, 0, 0, 0);
    const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
    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 '--/--/----'; const p = v.split('-'); return `${p[2]}/${p[1]}/${p[0]}`; };

    return (
        <div ref={wrapRef} style={{ position: 'relative' }}>
            <button type="button" onClick={() => setOpen(!open)}
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '12px 14px', borderRadius: 10, border: open ? '2px solid #FFB800' : '2px solid #E5E7EB', background: 'white', cursor: 'pointer', fontSize: 15, fontWeight: 600, color: '#1e293b', fontFamily: 'inherit' }}>
                <span><i className="fas fa-calendar-alt" style={{ color: '#FFB800', fontSize: 13, marginRight: 8 }}></i>{formatDisplay(value)}</span>
                <i className={`fas fa-chevron-${open ? 'up' : 'down'}`} style={{ fontSize: 11, color: '#94a3b8' }}></i>
            </button>
            {open && (
                <div style={{ position: 'absolute', left: 0, right: 0, top: '100%', marginTop: 4, borderRadius: 12, border: '1px solid #E5E7EB', background: 'white', boxShadow: '0 8px 24px rgba(0,0,0,0.12)', zIndex: 20, padding: 12 }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                        <button type="button" onClick={prevMonth} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '4px 8px', fontSize: 14, color: '#64748b' }}><i className="fas fa-chevron-left"></i></button>
                        <span style={{ fontWeight: 700, fontSize: 14, color: '#1e293b' }}>{MONTHS_FR[viewMonth]} {viewYear}</span>
                        <button type="button" onClick={nextMonth} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '4px 8px', fontSize: 14, color: '#64748b' }}><i className="fas fa-chevron-right"></i></button>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2, textAlign: 'center' }}>
                        {DAYS_FR.map(d => <div key={d} style={{ fontSize: 11, fontWeight: 600, color: '#94a3b8', padding: '4px 0' }}>{d}</div>)}
                        {cells.map((d, i) => {
                            if (!d) return <div key={`e${i}`}></div>;
                            const dateStr = `${viewYear}-${String(viewMonth + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
                            const isSelected = dateStr === value;
                            const isToday = dateStr === todayStr;
                            const isPast = new Date(dateStr) < today;
                            return (
                                <div key={d} onClick={() => !isPast && selectDay(d)}
                                    style={{ padding: '8px 0', borderRadius: 8, cursor: isPast ? 'not-allowed' : 'pointer', fontSize: 13, fontWeight: isSelected ? 700 : isToday ? 600 : 400, color: isPast ? '#d1d5db' : isSelected ? 'white' : isToday ? '#FFB800' : '#374151', background: isSelected ? '#FFB800' : isToday ? 'rgba(255,184,0,0.1)' : 'transparent' }}>
                                    {d}
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}
        </div>
    );
};

// ============================================================================
// BOOKING PAGE (multi-step: form → vehicles → summary → success)
// ============================================================================
const BookingPage = ({ user, onBooked }) => {
    const branding = useBranding();
    const notifications = useNotifications();
    const [step, setStep] = useState('form');
    const [pickup, setPickup] = useState('');
    const [pickupCoords, setPickupCoords] = useState(null);
    const [dropoff, setDropoff] = useState('');
    const [dropoffCoords, setDropoffCoords] = useState(null);
    const [timeMode, setTimeMode] = useState('now');
    const getTomorrow = () => { const d = new Date(); d.setDate(d.getDate() + 2); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
    const [pickDate, setPickDate] = useState(getTomorrow);
    const getNextSlot = () => {
        const now = new Date();
        let m = Math.ceil(now.getMinutes() / 15) * 15;
        let h = now.getHours();
        if (m >= 60) { m = 0; h = (h + 1) % 24; }
        return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
    };
    const [pickTime, setPickTime] = useState(getNextSlot);
    const [passengers, setPassengers] = useState(1);
    const [luggage, setLuggage] = useState(0);
    const [notes, setNotes] = useState('');
    const [flightNumber, setFlightNumber] = useState('');
    const [sending, setSending] = useState(false);
    const [createdJob, setCreatedJob] = useState(null);
    const [pickupSuggestions, setPickupSuggestions] = useState([]);
    const [dropoffSuggestions, setDropoffSuggestions] = useState([]);
    const [focusField, setFocusField] = useState(null);
    const searchTimer = useRef(null);
    const dropoffInputRef = useRef(null);

    const [fleets, setFleets] = useState([]);
    const [fleetsLoading, setFleetsLoading] = useState(false);
    const [selectedFleet, setSelectedFleet] = useState(null);
    const [routeInfo, setRouteInfo] = useState(null);

    const [cards, setCards] = useState([]);
    const [selectedCard, setSelectedCard] = useState(null);
    const [paymentMode, setPaymentMode] = useState('card');
    const [paymentResultStatus, setPaymentResultStatus] = useState(null);

    const searchAddress = (query, setter) => {
        if (searchTimer.current) clearTimeout(searchTimer.current);
        if (query.length < 3) { setter([]); return; }
        searchTimer.current = setTimeout(() => {
            fetch(`${API_URL}/maps/place?address=${encodeURIComponent(query)}&countries=CH,FR`)
                .then(r => r.json()).then(res => {
                    const d = res.data || res;
                    const preds = d.datas?.predictions || d.predictions || [];
                    setter(preds.map(p => ({ label: p.description, place_id: p.place_id })));
                }).catch(() => setter([]));
        }, 350);
    };

    const selectAddress = (item, type) => {
        const setVal = type === 'pickup' ? setPickup : setDropoff;
        const setCoords = type === 'pickup' ? setPickupCoords : setDropoffCoords;
        const setSugg = type === 'pickup' ? setPickupSuggestions : setDropoffSuggestions;
        setVal(item.label); setSugg([]);
        if (item.place_id) {
            fetch(`${API_URL}/maps/place_geometry?placeId=${encodeURIComponent(item.place_id)}`)
                .then(r => r.json()).then(res => {
                    const d = res.data || res;
                    const geo = d.datas?.result?.geometry || d.geometry;
                    if (geo?.location) setCoords({ lat: parseFloat(geo.location.lat), lng: parseFloat(geo.location.lng) });
                }).catch(() => {});
        }
        if (type === 'pickup' && dropoffInputRef.current) {
            setTimeout(() => { dropoffInputRef.current.focus(); }, 50);
        }
    };

    const getPickupDatetime = () => {
        const now = new Date();
        if (timeMode === 'now') return new Date(now.getTime() + 5 * 60000).toISOString();
        const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
        const tomorrow = new Date(now.getTime() + 86400000);
        const tomStr = `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')}`;
        if (timeMode === 'today') return new Date(`${today}T${pickTime || '12:00'}`).toISOString();
        if (timeMode === 'tomorrow') return new Date(`${tomStr}T${pickTime || '12:00'}`).toISOString();
        return new Date(`${pickDate}T${pickTime || '12:00'}`).toISOString();
    };

    const getPickupLabel = () => {
        if (timeMode === 'now') return 'Maintenant (~5 min)';
        if (timeMode === 'today') return `Aujourd'hui à ${pickTime || '12:00'}`;
        if (timeMode === 'tomorrow') return `Demain à ${pickTime || '12:00'}`;
        return `${pickDate} à ${pickTime || '12:00'}`;
    };

    const fleetImgUrl = (f) => {
        if (!f.image_url) return null;
        return f.image_url.startsWith('http') ? f.image_url : 'https://pub.files.swissapp.net/' + f.image_url;
    };

    const fetchFleets = async () => {
        if (!pickupCoords || !dropoffCoords) {
            notifications.error('Sélectionnez les adresses depuis les suggestions');
            return;
        }
        setFleetsLoading(true);
        try {
            const osrmUrl = `https://router.project-osrm.org/route/v1/driving/${pickupCoords.lng},${pickupCoords.lat};${dropoffCoords.lng},${dropoffCoords.lat}?overview=false`;
            const osrm = await fetch(osrmUrl).then(r => r.json());
            let dist = 5, dur = 10;
            if (osrm.routes?.[0]) {
                dist = Math.round(osrm.routes[0].distance / 100) / 10;
                dur = Math.round(osrm.routes[0].duration / 60);
            }
            setRouteInfo({ distance_km: dist, duration_minutes: dur });

            const res = await fetch(`${API_URL}/fleets/prices`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ distance: dist, duration: dur, pickup_address: pickup, destination_address: dropoff })
            }).then(r => r.json());

            if (res.success && res.data?.fleets) {
                setFleets(res.data.fleets);
                setStep('vehicles');
            } else {
                notifications.error('Aucun véhicule disponible');
            }
        } catch {
            notifications.error('Erreur lors du chargement des véhicules');
        }
        setFleetsLoading(false);
    };

    const goToSummary = () => {
        if (!selectedFleet) return;
        apiRequest('/payments/cards').then(r => {
            const c = r.data?.cards || [];
            setCards(c);
            const def = c.find(x => x.is_default);
            if (def) { setSelectedCard(def.id); setPaymentMode('saved_card'); }
            else if (c.length > 0) { setSelectedCard(c[0].id); setPaymentMode('saved_card'); }
            else setPaymentMode('card');
            setStep('summary');
        }).catch(() => setStep('summary'));
    };

    const brandIcon = (brand) => {
        const b = (brand || '').toLowerCase();
        if (b.includes('visa')) return 'fa-brands fa-cc-visa';
        if (b.includes('master')) return 'fa-brands fa-cc-mastercard';
        if (b.includes('amex')) return 'fa-brands fa-cc-amex';
        return 'fas fa-credit-card';
    };

    const submit = async () => {
        if (!pickup.trim() || !selectedFleet) return;
        setSending(true);
        try {
            const payload = {
                pickup_address: pickup, pickup_latitude: pickupCoords?.lat, pickup_longitude: pickupCoords?.lng,
                dropoff_address: dropoff || undefined, dropoff_latitude: dropoffCoords?.lat, dropoff_longitude: dropoffCoords?.lng,
                pickup_datetime: getPickupDatetime(),
                passenger_count: passengers, luggage_count: luggage,
                vehicle_type: selectedFleet.vehicle_type, fleet_id: selectedFleet.id,
                notes: notes || undefined, flight_number: flightNumber || undefined,
                customer_name: [user.first_name, user.last_name].filter(Boolean).join(' ') || undefined,
                customer_phone: user.phone_number || undefined, customer_email: user.email || undefined,
                source: 'app_client',
                estimated_price: selectedFleet.estimated_price,
                payment_method: paymentMode
            };
            if (paymentMode === 'saved_card' && selectedCard) payload.payment_card_id = selectedCard;
            const res = await apiRequest('/jobs/create', { method: 'POST', body: JSON.stringify(payload) });
            if (res.success) {
                if (paymentMode === 'card' && !selectedCard) {
                    const job = res.data?.job || res.data;
                    window.location.href = `https://payment.taxis.ch/?job_hash=${job.job_hash}&amount=${selectedFleet.estimated_price || 0}&return_url=${encodeURIComponent(window.location.origin + window.location.pathname)}`;
                    return;
                }
                setCreatedJob(res.data?.job || res.data);
                setPaymentResultStatus(res.data?.payment_status || null);
                setStep('success');
            } else {
                notifications.error(res.error || 'Erreur lors de la création');
            }
        } catch {
            notifications.error('Erreur de connexion');
        }
        setSending(false);
    };

    useEffect(() => {
        const url = new URL(window.location.href);
        const cardStatus = url.searchParams.get('card_status');
        if (cardStatus === 'success') {
            const pending = localStorage.getItem('pending_card_reg');
            let regId = url.searchParams.get('reg_id');
            let tok = url.searchParams.get('token');
            if (!regId && !tok && pending) {
                try { const p = JSON.parse(pending); regId = p.reg_id; tok = p.token; } catch {}
            }
            localStorage.removeItem('pending_card_reg');
            if (regId || tok) {
                apiRequest('/payments/cards/assert', { method: 'POST', body: JSON.stringify({ registration_id: regId, token: tok }) })
                    .then(res => { if (res.success) { apiRequest('/payments/cards').then(r => { const c = r.data?.cards || []; setCards(c); if (c.length > 0) { setSelectedCard(c[c.length - 1].id); setPaymentMode('saved_card'); } }); } })
                    .catch(() => {});
            }
            url.searchParams.delete('card_status'); url.searchParams.delete('reg_id'); url.searchParams.delete('token');
            window.history.replaceState({}, '', url.pathname + (url.search || ''));
        }
    }, []);

    const timeModes = [
        { id: 'now', label: 'Maintenant' },
        { id: 'today', label: "Aujourd'hui" },
        { id: 'tomorrow', label: 'Demain' },
        { id: 'custom', label: 'Autre' }
    ];

    const SuggestionList = ({ items, type }) => items.length === 0 ? null : (
        <div className="suggestion-list">
            {items.map((it, i) => (
                <div key={i} className="suggestion-item" onClick={() => selectAddress(it, type)}>
                    <i className="fas fa-map-marker-alt" style={{ color: '#FFB800', fontSize: 12 }}></i>
                    <span style={{ flex: 1 }}>{it.label}</span>
                </div>
            ))}
        </div>
    );

    const resetAll = () => {
        setStep('form'); setPickup(''); setPickupCoords(null); setDropoff(''); setDropoffCoords(null);
        setNotes(''); setFlightNumber(''); setTimeMode('now'); setSelectedFleet(null); setFleets([]);
        setRouteInfo(null); setSelectedCard(null); setPaymentMode('card'); setPaymentResultStatus(null);
        setPassengers(1); setLuggage(0);
        if (onBooked) onBooked();
    };

    // ===== STEP: SUCCESS =====
    if (step === 'success') {
        const domain = (branding.display_url || 'taxis.ch').replace(/^https?:\/\//, '').replace(/\/+$/, '');
        const job = createdJob;
        const isAwaitingPayment = paymentResultStatus === 'awaiting_payment';
        const jobHash = job?.job_hash || createdJob?.job?.job_hash;
        return (
            <div className="page-content fade-in" style={{ textAlign: 'center' }}>
                {isAwaitingPayment ? (
                    <>
                        <div style={{ width: 72, height: 72, borderRadius: '50%', background: '#fef3c7', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '24px auto 0' }}>
                            <i className="fas fa-clock" style={{ color: '#f59e0b', fontSize: 30 }}></i>
                        </div>
                        <h3 style={{ fontSize: 18, fontWeight: 700, color: '#111827' }}>Course pré-enregistrée</h3>
                        <div style={{ background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 12, padding: '12px 16px' }}>
                            <p style={{ fontSize: 14, fontWeight: 600, color: '#dc2626', margin: 0 }}>En attente de paiement</p>
                            <p style={{ fontSize: 12, color: '#991b1b', margin: '4px 0 0' }}>Veuillez procéder au paiement pour confirmer votre réservation.</p>
                        </div>
                    </>
                ) : (
                    <>
                        <div style={{ width: 72, height: 72, borderRadius: '50%', background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '24px auto 0' }}>
                            <i className="fas fa-check" style={{ color: '#16a34a', fontSize: 30 }}></i>
                        </div>
                        <h3 style={{ fontSize: 18, fontWeight: 700, color: '#111827' }}>{createdJob?.status === 'booked' ? 'Course réservée' : 'Recherche de chauffeur'}</h3>
                        <p style={{ fontSize: 14, color: '#6B7280' }}>{createdJob?.status === 'booked' ? 'Votre course a été réservée avec succès.' : 'Nous recherchons un chauffeur pour vous.'}</p>
                    </>
                )}

                <div className="card-flat" style={{ textAlign: 'left' }}>
                    <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <i className="fas fa-circle" style={{ color: '#22c55e', fontSize: 8 }}></i>
                            <span style={{ fontSize: 13, color: '#374151' }}>{pickup}</span>
                        </div>
                        {dropoff && (
                            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                                <i className="fas fa-circle" style={{ color: '#ef4444', fontSize: 8 }}></i>
                                <span style={{ fontSize: 13, color: '#374151' }}>{dropoff}</span>
                            </div>
                        )}
                        <div style={{ borderTop: '1px solid #f1f5f9', paddingTop: 10, display: 'flex', flexWrap: 'wrap', gap: 16, fontSize: 13, color: '#6B7280' }}>
                            <span><i className="fas fa-clock" style={{ marginRight: 4 }}></i>{getPickupLabel()}</span>
                            <span><i className="fas fa-car" style={{ marginRight: 4 }}></i>{selectedFleet?.name}</span>
                            <span style={{ fontWeight: 700, color: '#FFB800' }}>{selectedFleet?.estimated_price?.toFixed(2)} CHF</span>
                        </div>
                    </div>
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {jobHash && (
                        <a href={`https://tracking.${domain}/${jobHash}`} target="_blank" rel="noopener" className="btn-outline" style={{ textDecoration: 'none' }}>
                            <i className="fas fa-location-dot"></i>Suivre ma course
                        </a>
                    )}
                    {isAwaitingPayment && jobHash && (
                        <a href={`https://payment.${domain}/?ride_id=${jobHash}`} target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '12px 16px', borderRadius: 12, background: 'linear-gradient(135deg, #dc2626, #b91c1c)', color: 'white', fontSize: 14, fontWeight: 700, textDecoration: 'none' }}>
                            <i className="fas fa-credit-card"></i>Effectuer le paiement
                        </a>
                    )}
                </div>
                <button className="btn-primary" style={{ width: '100%' }} onClick={resetAll}>
                    <i className="fas fa-plus"></i>Nouvelle réservation
                </button>
            </div>
        );
    }

    // ===== STEP: SUMMARY =====
    if (step === 'summary') {
        const isAirport = /a[ée]roport|airport|gva|genève.cointrin|zürich.kloten|zrh|bsl|bern.belp/i.test(pickup);
        return (
            <div className="page-content fade-in">
                <button onClick={() => setStep('vehicles')} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#FFB800', fontSize: 14, fontWeight: 700, padding: 0, alignSelf: 'flex-start', display: 'flex', alignItems: 'center', gap: 6 }}>
                    <i className="fas fa-arrow-left"></i>Modifier le véhicule
                </button>

                <h3 style={{ fontSize: 17, fontWeight: 700, color: '#1e293b', margin: 0 }}>Récapitulatif</h3>

                <div className="card-flat">
                    <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <i className="fas fa-circle" style={{ color: '#22c55e', fontSize: 8, flexShrink: 0 }}></i>
                            <span style={{ fontSize: 13, color: '#374151' }}>{pickup}</span>
                        </div>
                        {dropoff && (
                            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                                <i className="fas fa-circle" style={{ color: '#ef4444', fontSize: 8, flexShrink: 0 }}></i>
                                <span style={{ fontSize: 13, color: '#374151' }}>{dropoff}</span>
                            </div>
                        )}
                        <div style={{ borderTop: '1px solid #f1f5f9', paddingTop: 10, display: 'flex', flexWrap: 'wrap', gap: 12, fontSize: 13, color: '#6B7280' }}>
                            <span><i className="fas fa-clock" style={{ marginRight: 4 }}></i>{getPickupLabel()}</span>
                            <span><i className="fas fa-user" style={{ marginRight: 4 }}></i>{passengers} passager{passengers > 1 ? 's' : ''}</span>
                            {luggage > 0 && <span><i className="fas fa-suitcase" style={{ marginRight: 4 }}></i>{luggage} bagage{luggage > 1 ? 's' : ''}</span>}
                            {routeInfo && <span><i className="fas fa-road" style={{ marginRight: 4 }}></i>{routeInfo.distance_km} km</span>}
                            {routeInfo && <span><i className="fas fa-clock" style={{ marginRight: 4 }}></i>~{routeInfo.duration_minutes} min</span>}
                        </div>
                    </div>
                </div>

                {selectedFleet && (
                    <div className="card-flat">
                        <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14 }}>
                            {fleetImgUrl(selectedFleet) ? (
                                <img src={fleetImgUrl(selectedFleet)} alt={selectedFleet.name} style={{ width: 60, height: 42, objectFit: 'contain' }} />
                            ) : (
                                <div style={{ width: 60, height: 42, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f1f5f9', borderRadius: 8 }}>
                                    <i className="fas fa-car" style={{ color: '#cbd5e1', fontSize: 22 }}></i>
                                </div>
                            )}
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 700, fontSize: 14, color: '#1e293b' }}>{selectedFleet.name}</div>
                                <div style={{ fontSize: 12, color: '#94a3b8' }}>{selectedFleet.capacity} places</div>
                            </div>
                            <div style={{ fontWeight: 800, fontSize: 18, color: '#FFB800' }}>{selectedFleet.estimated_price?.toFixed(2)} <span style={{ fontSize: 12, fontWeight: 500 }}>CHF</span></div>
                        </div>
                    </div>
                )}

                <div>
                    <label className="input-label"><i className="fas fa-comment" style={{ color: '#94a3b8', fontSize: 12, marginRight: 6 }}></i>Notes (optionnel)</label>
                    <textarea className="input-field" rows="2" placeholder="Instructions pour le chauffeur..." value={notes} onChange={e => setNotes(e.target.value)}></textarea>
                </div>

                {isAirport && (
                    <div>
                        <label className="input-label"><i className="fas fa-plane" style={{ color: '#94a3b8', fontSize: 12, marginRight: 6 }}></i>N° de vol (optionnel)</label>
                        <input className="input-field" placeholder="Ex: LX 1234" value={flightNumber} onChange={e => setFlightNumber(e.target.value)} />
                    </div>
                )}

                <div>
                    <label className="input-label"><i className="fas fa-credit-card" style={{ color: '#94a3b8', fontSize: 12, marginRight: 6 }}></i>Moyen de paiement</label>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                        {[
                            { id: 'card', icon: 'fa-credit-card', label: 'Nouvelle carte', desc: 'Visa / Mastercard via Worldline', color: '#3b82f6' },
                            { id: 'twint', icon: 'fa-mobile-alt', label: 'TWINT', desc: 'Paiement via l\'app TWINT', color: '#000' },
                            { id: 'apple_google', icon: 'fa-wallet', label: 'Apple Pay / Google Pay', desc: 'Paiement sans contact', color: '#1e293b' }
                        ].map(pm => (
                            <div key={pm.id} className={`pm-card ${paymentMode === pm.id && !selectedCard ? 'selected' : ''}`} onClick={() => { setPaymentMode(pm.id); setSelectedCard(null); }}>
                                <div style={{ width: 42, height: 42, borderRadius: 10, background: pm.color + '15', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                                    <i className={`fas ${pm.icon}`} style={{ color: pm.color, fontSize: 17 }}></i>
                                </div>
                                <div style={{ flex: 1 }}>
                                    <div style={{ fontWeight: 600, fontSize: 14, color: '#1e293b' }}>{pm.label}</div>
                                    <div style={{ fontSize: 12, color: '#94a3b8' }}>{pm.desc}</div>
                                </div>
                                <div className="pm-radio"></div>
                            </div>
                        ))}

                        {cards.length > 0 && (
                            <>
                                <div className="section-title" style={{ marginTop: 8 }}>Mes cartes enregistrées</div>
                                {cards.map(card => (
                                    <div key={card.id} className={`pm-card ${paymentMode === 'saved_card' && selectedCard === card.id ? 'selected' : ''}`} onClick={() => { setSelectedCard(card.id); setPaymentMode('saved_card'); }}>
                                        <i className={brandIcon(card.card_brand)} style={{ color: '#475569', fontSize: 22, width: 32, textAlign: 'center' }}></i>
                                        <div style={{ flex: 1 }}>
                                            <span style={{ fontWeight: 600, fontSize: 14, color: '#1e293b', fontFamily: 'monospace' }}>•••• {card.card_last4}</span>
                                            <div style={{ fontSize: 12, color: '#94a3b8' }}>{card.card_brand ? card.card_brand.toUpperCase() : 'Carte'}</div>
                                        </div>
                                        {card.is_default && <span style={{ fontSize: 10, fontWeight: 600, padding: '2px 6px', borderRadius: 4, background: '#dcfce7', color: '#166534' }}>Défaut</span>}
                                        <div className="pm-radio"></div>
                                    </div>
                                ))}
                            </>
                        )}
                    </div>
                </div>

                <button className="btn-primary" style={{ width: '100%' }} onClick={submit} disabled={sending}>
                    {sending ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-check"></i>Confirmer la réservation</>}
                </button>
            </div>
        );
    }

    // ===== STEP: VEHICLES =====
    if (step === 'vehicles') {
        return (
            <div className="page-content fade-in">
                <button onClick={() => { setStep('form'); setFleets([]); setSelectedFleet(null); }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#FFB800', fontSize: 14, fontWeight: 700, padding: 0, alignSelf: 'flex-start', display: 'flex', alignItems: 'center', gap: 6 }}>
                    <i className="fas fa-arrow-left"></i>Modifier l'itinéraire
                </button>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <h3 style={{ fontSize: 17, fontWeight: 700, color: '#1e293b', margin: 0 }}>Choisir un véhicule</h3>
                    {routeInfo && (
                        <span style={{ fontSize: 12, color: '#6B7280', display: 'flex', alignItems: 'center', gap: 8 }}>
                            <span><i className="fas fa-road" style={{ marginRight: 3 }}></i>{routeInfo.distance_km} km</span>
                            <span><i className="fas fa-clock" style={{ marginRight: 3 }}></i>{routeInfo.duration_minutes} min</span>
                        </span>
                    )}
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {fleets.map(fleet => {
                        const img = fleetImgUrl(fleet);
                        const isSelected = selectedFleet?.id === fleet.id;
                        return (
                            <div key={fleet.id} className={`vehicle-item ${isSelected ? 'selected' : ''}`} onClick={() => setSelectedFleet(fleet)}>
                                {img ? (
                                    <img src={img} alt={fleet.name} style={{ width: 64, height: 44, objectFit: 'contain' }} />
                                ) : (
                                    <div style={{ width: 64, height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f1f5f9', borderRadius: 8 }}>
                                        <i className="fas fa-car" style={{ color: '#cbd5e1', fontSize: 22 }}></i>
                                    </div>
                                )}
                                <div style={{ flex: 1 }}>
                                    <div style={{ fontWeight: 700, fontSize: 14, color: '#1e293b' }}>{fleet.name}</div>
                                    <div style={{ fontSize: 12, color: '#94a3b8' }}>
                                        <i className="fas fa-user" style={{ marginRight: 3, fontSize: 10 }}></i>{fleet.capacity} places
                                        {fleet.description ? ` · ${fleet.description}` : ''}
                                    </div>
                                </div>
                                <div style={{ textAlign: 'right' }}>
                                    <div style={{ fontWeight: 800, fontSize: 16, color: '#FFB800' }}>{fleet.estimated_price?.toFixed(2)}</div>
                                    <div style={{ fontSize: 11, color: '#94a3b8', fontWeight: 600 }}>CHF</div>
                                </div>
                                {isSelected && <i className="fas fa-check-circle" style={{ color: '#FFB800', fontSize: 20, marginLeft: 6 }}></i>}
                            </div>
                        );
                    })}
                </div>

                {fleets.length === 0 && (
                    <div className="empty-state">
                        <div className="empty-icon"><i className="fas fa-car"></i></div>
                        <p style={{ fontSize: 15, fontWeight: 600, color: '#64748b' }}>Aucun véhicule disponible</p>
                    </div>
                )}

                <button className="btn-primary" style={{ width: '100%' }} onClick={goToSummary} disabled={!selectedFleet}>
                    <i className="fas fa-arrow-right"></i>Continuer
                </button>
            </div>
        );
    }

    // ===== STEP: FORM =====
    return (
        <div className="page-content fade-in">
            <div style={{ position: 'relative' }}>
                <label className="input-label"><i className="fas fa-circle" style={{ color: '#22c55e', fontSize: 8, marginRight: 6 }}></i>Prise en charge</label>
                <input className="input-field" placeholder="Adresse de départ" value={pickup}
                    onChange={e => { setPickup(e.target.value); setPickupCoords(null); searchAddress(e.target.value, setPickupSuggestions); }}
                    onFocus={() => setFocusField('pickup')}
                    onBlur={() => setTimeout(() => setFocusField(null), 200)} />
                {focusField === 'pickup' && <SuggestionList items={pickupSuggestions} type="pickup" />}
            </div>

            <div style={{ position: 'relative' }}>
                <label className="input-label"><i className="fas fa-circle" style={{ color: '#ef4444', fontSize: 8, marginRight: 6 }}></i>Destination</label>
                <input ref={dropoffInputRef} className="input-field" placeholder="Adresse d'arrivée" value={dropoff}
                    onChange={e => { setDropoff(e.target.value); setDropoffCoords(null); searchAddress(e.target.value, setDropoffSuggestions); }}
                    onFocus={() => setFocusField('dropoff')}
                    onBlur={() => setTimeout(() => setFocusField(null), 200)} />
                {focusField === 'dropoff' && <SuggestionList items={dropoffSuggestions} type="dropoff" />}
            </div>

            <div>
                <label className="input-label"><i className="fas fa-clock" style={{ color: '#94a3b8', fontSize: 12, marginRight: 6 }}></i>Quand ?</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
                    {timeModes.map(t => (
                        <button key={t.id} onClick={() => setTimeMode(t.id)}
                            style={{ padding: '10px 4px', borderRadius: 10, border: timeMode === t.id ? '2px solid #FFB800' : '2px solid #E5E7EB', background: timeMode === t.id ? 'rgba(255,184,0,0.06)' : 'white', cursor: 'pointer', fontSize: 12, fontWeight: 600, color: timeMode === t.id ? '#b45309' : '#64748b', fontFamily: 'inherit' }}>
                            {t.label}
                        </button>
                    ))}
                </div>
                {timeMode === 'now' && <p style={{ fontSize: 12, color: '#94a3b8', marginTop: 8 }}><i className="fas fa-info-circle" style={{ marginRight: 4 }}></i>Prise en charge dans ~5 minutes</p>}
                {(timeMode === 'today' || timeMode === 'tomorrow') && (
                    <div style={{ marginTop: 10 }}>
                        <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: '#64748b', marginBottom: 6 }}>Heure</label>
                        <TimePicker value={pickTime} onChange={setPickTime} />
                    </div>
                )}
                {timeMode === 'custom' && (
                    <div style={{ marginTop: 10 }}>
                        <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: '#64748b', marginBottom: 6 }}>Date</label>
                        <DatePicker value={pickDate} onChange={setPickDate} />
                        <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: '#64748b', marginBottom: 6, marginTop: 10 }}>Heure</label>
                        <TimePicker value={pickTime} onChange={setPickTime} />
                    </div>
                )}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div>
                    <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: '#64748b', marginBottom: 6 }}>Passagers</label>
                    <NumberPicker value={passengers} onChange={setPassengers} min={1} max={16} icon="fa-user" label="passager" />
                </div>
                <div>
                    <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: '#64748b', marginBottom: 6 }}>Bagages</label>
                    <NumberPicker value={luggage} onChange={setLuggage} min={0} max={16} icon="fa-suitcase" label="bagage" />
                </div>
            </div>

            <button className="btn-primary" style={{ width: '100%' }} onClick={fetchFleets} disabled={fleetsLoading || !pickup.trim() || !dropoff.trim()}>
                {fleetsLoading ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-car"></i>Choisir un véhicule</>}
            </button>
        </div>
    );
};

// ============================================================================
// PAYMENT METHODS PAGE
// ============================================================================
const PaymentMethodsPage = ({ user }) => {
    const notifications = useNotifications();
    const [cards, setCards] = useState([]);
    const [loading, setLoading] = useState(true);
    const [adding, setAdding] = useState(false);
    const [deleting, setDeleting] = useState(null);

    const load = () => {
        setLoading(true);
        apiRequest('/payments/cards').then(r => { setCards(r.data?.cards || []); setLoading(false); }).catch(() => setLoading(false));
    };

    useEffect(() => {
        load();
        const url = new URL(window.location.href);
        const cardStatus = url.searchParams.get('card_status');
        if (cardStatus === 'success') {
            const pending = localStorage.getItem('pending_card_reg');
            let regId = url.searchParams.get('reg_id');
            let tok = url.searchParams.get('token');
            if (!regId && !tok && pending) {
                try { const p = JSON.parse(pending); regId = p.reg_id; tok = p.token; } catch {}
            }
            localStorage.removeItem('pending_card_reg');
            if (regId || tok) {
                apiRequest('/payments/cards/assert', { method: 'POST', body: JSON.stringify({ registration_id: regId, token: tok }) })
                    .then(res => { if (res.success) { notifications.success('Carte ajoutée'); load(); } })
                    .catch(() => {});
            }
            url.searchParams.delete('card_status'); url.searchParams.delete('reg_id'); url.searchParams.delete('token');
            window.history.replaceState({}, '', url.pathname + (url.search || ''));
        }
    }, []);

    const brandIcon = (brand) => {
        const b = (brand || '').toLowerCase();
        if (b.includes('visa')) return 'fa-brands fa-cc-visa';
        if (b.includes('master')) return 'fa-brands fa-cc-mastercard';
        if (b.includes('amex')) return 'fa-brands fa-cc-amex';
        return 'fas fa-credit-card';
    };
    const brandColor = (brand) => {
        const b = (brand || '').toLowerCase();
        if (b.includes('visa')) return { bg: '#dbeafe', color: '#1e40af' };
        if (b.includes('master')) return { bg: '#fef3c7', color: '#d97706' };
        if (b.includes('amex')) return { bg: '#dbeafe', color: '#2563eb' };
        return { bg: '#ede9fe', color: '#7c3aed' };
    };

    const addCard = async () => {
        setAdding(true);
        try {
            const base = `${window.location.origin}${window.location.pathname}`;
            const res = await apiRequest('/payments/cards/init', { method: 'POST', body: JSON.stringify({ return_url: `${base}?card_status=success`, fail_url: `${base}?card_status=failed` }) });
            if (res.success && res.data?.redirect_url) {
                localStorage.setItem('pending_card_reg', JSON.stringify({ reg_id: res.data.registration_id, token: res.data.token }));
                window.location.href = res.data.redirect_url;
            } else { setAdding(false); notifications.error('Erreur'); }
        } catch { setAdding(false); notifications.error('Erreur de connexion'); }
    };

    const removeCard = async (id) => {
        if (!confirm('Supprimer cette carte ?')) return;
        setDeleting(id);
        try { await apiRequest(`/payments/cards/${id}`, { method: 'DELETE' }); notifications.success('Carte supprimée'); load(); } catch {}
        setDeleting(null);
    };

    const setDefault = async (id) => {
        try { await apiRequest(`/payments/cards/${id}/default`, { method: 'PUT' }); notifications.success('Carte définie par défaut'); load(); } catch {}
    };

    if (loading) return <div style={{ textAlign: 'center', padding: 48 }}><div className="spinner"></div></div>;

    return (
        <div className="page-content fade-in">
            <button onClick={addCard} disabled={adding}
                style={{ width: '100%', padding: '14px 16px', borderRadius: 12, border: '2px dashed #FFB800', background: 'rgba(255,184,0,0.04)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: '#b45309', fontWeight: 600, fontSize: 14, fontFamily: 'inherit' }}>
                {adding ? <span className="spinner spinner-sm" style={{ borderTopColor: '#FFB800' }}></span> : <><i className="fas fa-plus"></i>Ajouter une carte</>}
            </button>

            {cards.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-icon"><i className="fas fa-credit-card"></i></div>
                    <p style={{ fontSize: 15, fontWeight: 600, color: '#64748b' }}>Aucune carte enregistrée</p>
                    <p style={{ fontSize: 13 }}>Ajoutez une carte pour faciliter vos paiements</p>
                </div>
            ) : (
                <div className="card-flat">
                    {cards.map((card, i) => {
                        const bc = brandColor(card.card_brand);
                        return (
                            <div key={i} className="item-row" style={{ cursor: 'default' }}>
                                <div className="icon-circle" style={{ background: bc.bg, color: bc.color, fontSize: 22 }}>
                                    <i className={brandIcon(card.card_brand)}></i>
                                </div>
                                <div style={{ flex: 1 }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                        <span style={{ fontWeight: 600, fontSize: 14, color: '#1e293b' }}>{card.card_brand || 'Carte'} •••• {card.card_last4}</span>
                                        {card.is_default && <span style={{ fontSize: 10, fontWeight: 600, padding: '2px 6px', borderRadius: 4, background: '#dcfce7', color: '#166534' }}>Par défaut</span>}
                                    </div>
                                    <div style={{ fontSize: 12, color: '#94a3b8' }}>Expire {card.card_expiry_month}/{card.card_expiry_year}</div>
                                </div>
                                <div style={{ display: 'flex', gap: 4 }}>
                                    {!card.is_default && (
                                        <button onClick={() => setDefault(card.id)} title="Définir par défaut"
                                            style={{ width: 32, height: 32, borderRadius: 8, border: '1px solid #E5E7EB', background: 'white', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#94a3b8', fontSize: 12 }}>
                                            <i className="fas fa-star"></i>
                                        </button>
                                    )}
                                    <button onClick={() => removeCard(card.id)} disabled={deleting === card.id} title="Supprimer"
                                        style={{ width: 32, height: 32, borderRadius: 8, border: '1px solid #fecaca', background: '#fef2f2', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#dc2626', fontSize: 12 }}>
                                        {deleting === card.id ? <span className="spinner spinner-sm" style={{ borderTopColor: '#dc2626' }}></span> : <i className="fas fa-trash"></i>}
                                    </button>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
};

// ============================================================================
// INVOICES PAGE
// ============================================================================
const InvoicesPage = ({ user }) => {
    const [invoices, setInvoices] = useState([]);
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        apiRequest(`/users/${user.uid}/invoices?page=1&limit=50`).then(r => { setInvoices(r.data?.invoices || r.data || []); setLoading(false); }).catch(() => setLoading(false));
    }, [user.uid]);

    if (loading) return <div style={{ textAlign: 'center', padding: 48 }}><div className="spinner"></div></div>;

    return (
        <div className="page-content fade-in">
            {(!invoices || invoices.length === 0) ? (
                <div className="empty-state">
                    <div className="empty-icon"><i className="fas fa-file-invoice"></i></div>
                    <p style={{ fontSize: 15, fontWeight: 600, color: '#64748b' }}>Aucune facture</p>
                    <p style={{ fontSize: 13 }}>Vos factures apparaîtront ici</p>
                </div>
            ) : (
                <div className="card-flat">
                    {invoices.map((inv, i) => (
                        <div key={i} className="item-row">
                            <div className="icon-circle" style={{ background: '#ede9fe', color: '#7c3aed' }}>
                                <i className="fas fa-file-invoice"></i>
                            </div>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 600, fontSize: 14, color: '#1e293b' }}>{inv.reference || `Facture #${inv.id}`}</div>
                                <div style={{ fontSize: 12, color: '#94a3b8' }}>{fmtDate(inv.created_at)}</div>
                            </div>
                            {inv.total && <span style={{ fontWeight: 700, fontSize: 14, color: '#FFB800' }}>CHF {parseFloat(inv.total).toFixed(2)}</span>}
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

// ============================================================================
// PROFILE PAGE
// ============================================================================
const ProfilePage = ({ user, onLogout }) => {
    const branding = useBranding();
    return (
        <div className="page-content fade-in">
            <div className="card" style={{ padding: 22, textAlign: 'center' }}>
                <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'linear-gradient(135deg, #FFB800, #EAB308)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px', fontSize: 28, color: 'white', fontWeight: 800, boxShadow: '0 6px 16px rgba(255,184,0,0.4)' }}>
                    {(user.first_name || user.email || 'U')[0].toUpperCase()}
                </div>
                <h2 style={{ fontSize: 18, fontWeight: 700, color: '#111827', margin: 0 }}>{[user.first_name, user.last_name].filter(Boolean).join(' ') || 'Utilisateur'}</h2>
                <p style={{ color: '#6B7280', fontSize: 13, marginTop: 4 }}>{user.email}</p>
            </div>

            <div className="card-flat">
                <div className="item-row" style={{ cursor: 'default' }}>
                    <div className="icon-circle" style={{ background: '#ede9fe', color: '#7c3aed' }}><i className="fas fa-phone"></i></div>
                    <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 12, color: '#94a3b8' }}>Téléphone</div>
                        <div style={{ fontWeight: 500, fontSize: 14, color: '#1e293b' }}>{user.phone_number || 'Non renseigné'}</div>
                    </div>
                </div>
                <div className="item-row" style={{ cursor: 'default' }}>
                    <div className="icon-circle" style={{ background: '#dbeafe', color: '#2563eb' }}><i className="fas fa-envelope"></i></div>
                    <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 12, color: '#94a3b8' }}>Email</div>
                        <div style={{ fontWeight: 500, fontSize: 14, color: '#1e293b' }}>{user.email || 'Non renseigné'}</div>
                    </div>
                </div>
                <div className="item-row" style={{ cursor: 'default' }}>
                    <div className="icon-circle" style={{ background: '#fef3c7', color: '#d97706' }}><i className="fas fa-id-badge"></i></div>
                    <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 12, color: '#94a3b8' }}>Type de compte</div>
                        <div style={{ fontWeight: 500, fontSize: 14, color: '#1e293b' }}>{user.user_type === 'customer' ? 'Client' : user.user_type}</div>
                    </div>
                </div>
            </div>

            {(branding.contact_phone || branding.contact_email) && (
                <div className="card-flat">
                    <div style={{ padding: '12px 16px', borderBottom: '1px solid #f1f5f9' }}>
                        <span style={{ fontSize: 13, fontWeight: 700, color: '#374151' }}>Besoin d'aide ?</span>
                    </div>
                    {branding.contact_phone && (
                        <a href={`tel:${branding.contact_phone.replace(/\s/g, '')}`} className="item-row" style={{ textDecoration: 'none', color: 'inherit' }}>
                            <div className="icon-circle" style={{ background: '#dcfce7', color: '#16a34a' }}><i className="fas fa-phone"></i></div>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 500, fontSize: 14, color: '#1e293b' }}>{branding.contact_phone}</div>
                                <div style={{ fontSize: 12, color: '#94a3b8' }}>Appeler</div>
                            </div>
                            <i className="fas fa-chevron-right" style={{ color: '#d1d5db', fontSize: 12 }}></i>
                        </a>
                    )}
                    {branding.contact_email && (
                        <a href={`mailto:${branding.contact_email}`} className="item-row" style={{ textDecoration: 'none', color: 'inherit' }}>
                            <div className="icon-circle" style={{ background: '#dbeafe', color: '#2563eb' }}><i className="fas fa-envelope"></i></div>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 500, fontSize: 14, color: '#1e293b' }}>{branding.contact_email}</div>
                                <div style={{ fontSize: 12, color: '#94a3b8' }}>Envoyer un email</div>
                            </div>
                            <i className="fas fa-chevron-right" style={{ color: '#d1d5db', fontSize: 12 }}></i>
                        </a>
                    )}
                </div>
            )}

            <button onClick={onLogout} style={{ background: 'none', border: 'none', color: '#ef4444', fontWeight: 600, cursor: 'pointer', fontSize: 14, padding: '14px', width: '100%', fontFamily: 'inherit' }}>
                <i className="fas fa-sign-out-alt" style={{ marginRight: 8 }}></i>Déconnexion
            </button>
        </div>
    );
};

// ============================================================================
// HOME PAGE
// ============================================================================
const HomePage = ({ user, onNavigate }) => {
    const branding = useBranding();
    const [stats, setStats] = useState({ upcoming: 0, past: 0, cards: 0, tickets: 0 });
    const [upcomingRides, setUpcomingRides] = useState([]);
    const [loadingStats, setLoadingStats] = useState(true);

    useEffect(() => {
        const load = async () => {
            try {
                const [ridesRes, cardsRes, ticketsRes] = await Promise.all([
                    apiRequest('/jobs/my').catch(() => ({ data: [] })),
                    apiRequest('/payments/cards').catch(() => ({ data: [] })),
                    apiRequest('/support/tickets').catch(() => ({ data: [] }))
                ]);
                const rides = ridesRes.data || [];
                const upcoming = rides.filter(r => !['completed', 'cancelled', 'cancelled_central'].includes(r.status));
                const past = rides.filter(r => ['completed', 'cancelled', 'cancelled_central'].includes(r.status));
                setStats({
                    upcoming: upcoming.length,
                    past: past.length,
                    cards: (cardsRes.data?.cards || cardsRes.data || []).length,
                    tickets: ((ticketsRes.data?.tickets || ticketsRes.data || []).filter(t => t.status !== 'closed')).length
                });
                setUpcomingRides(upcoming.slice(0, 3));
            } catch {}
            setLoadingStats(false);
        };
        load();
    }, []);

    const sections = [
        { id: 'rides', icon: 'fa-car', label: 'Mes courses', desc: `${stats.upcoming} en cours · ${stats.past} terminées`, iconBg: '#dbeafe', iconColor: '#3b82f6' },
        { id: 'requests', icon: 'fa-headset', label: 'Mes demandes', desc: stats.tickets > 0 ? `${stats.tickets} demande${stats.tickets > 1 ? 's' : ''} en cours` : 'Aucune demande en cours', iconBg: '#fef3c7', iconColor: '#d97706' },
        { id: 'payments', icon: 'fa-credit-card', label: 'Mes cartes', desc: stats.cards > 0 ? `${stats.cards} carte${stats.cards > 1 ? 's' : ''} enregistrée${stats.cards > 1 ? 's' : ''}` : 'Aucune carte enregistrée', iconBg: '#dcfce7', iconColor: '#16a34a' },
        { id: 'invoices', icon: 'fa-file-invoice', label: 'Mes factures', desc: 'Historique de facturation', iconBg: '#ede9fe', iconColor: '#7c3aed' },
        { id: 'profile', icon: 'fa-user', label: 'Mon profil', desc: user.email || '', iconBg: '#fce7f3', iconColor: '#ec4899' }
    ];

    return (
        <div className="page-content fade-in">
            <div style={{ textAlign: 'center', padding: '20px 8px 4px' }}>
                <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'linear-gradient(135deg, #FFB800, #EAB308)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px', fontSize: 24, color: 'white', fontWeight: 800, boxShadow: '0 6px 16px rgba(255,184,0,0.4)' }}>
                    {(user.first_name || user.email || 'U')[0].toUpperCase()}
                </div>
                <div style={{ fontSize: 20, fontWeight: 800, color: '#111827' }}>Bonjour {user.first_name || 'Utilisateur'} !</div>
                <div style={{ fontSize: 14, color: '#6B7280', marginTop: 4 }}>Où souhaitez-vous aller aujourd'hui ?</div>
            </div>

            <button onClick={() => onNavigate('booking')} className="active-ride-card" style={{ display: 'flex', alignItems: 'center', gap: 14, border: 'none', textAlign: 'left', width: '100%', fontFamily: 'inherit' }}>
                <div style={{ width: 48, height: 48, borderRadius: 14, background: 'rgba(255,255,255,0.22)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <i className="fas fa-bolt" style={{ color: 'white', fontSize: 20 }}></i>
                </div>
                <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 16 }}>Commander maintenant</div>
                    <div style={{ fontSize: 13, opacity: 0.92 }}>Réserver une nouvelle course</div>
                </div>
                <i className="fas fa-chevron-right" style={{ fontSize: 16, opacity: 0.85 }}></i>
            </button>

            {upcomingRides.length > 0 && (
                <div className="card-flat">
                    <div style={{ padding: '12px 16px', borderBottom: '1px solid #f1f5f9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                        <span style={{ fontSize: 13, fontWeight: 700, color: '#374151' }}>Courses en cours</span>
                        <button onClick={() => onNavigate('rides')} style={{ fontSize: 12, color: '#FFB800', fontWeight: 700, background: 'none', border: 'none', cursor: 'pointer' }}>Voir tout</button>
                    </div>
                    {upcomingRides.map(ride => (
                        <div key={ride.job_hash || ride.id} className="item-row" onClick={() => onNavigate('rides')}>
                            <div className="icon-circle" style={{ background: 'rgba(255,184,0,0.15)', color: '#FFB800' }}>
                                <i className="fas fa-car"></i>
                            </div>
                            <div style={{ flex: 1, minWidth: 0 }}>
                                <div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                                    {ride.pickup_address?.split(',')[0] || 'Course'}
                                </div>
                                <div style={{ fontSize: 11, color: '#94a3b8' }}>{fmtDateShort(ride.pickup_datetime)}</div>
                            </div>
                            <span className={`status-badge ${ride.status}`}>{statusLabel(ride.status)}</span>
                        </div>
                    ))}
                </div>
            )}

            <div style={{ display: 'grid', gap: 8 }}>
                {sections.map(s => (
                    <button key={s.id} onClick={() => onNavigate(s.id)}
                        style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 16px', borderRadius: 14, background: 'white', color: '#1e293b', border: '1px solid #f1f5f9', cursor: 'pointer', textAlign: 'left', width: '100%', boxShadow: '0 1px 3px rgba(0,0,0,0.04)', transition: 'all 0.15s', fontFamily: 'inherit' }}
                        onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'; e.currentTarget.style.borderColor = '#FFB800'; }}
                        onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '0 1px 3px rgba(0,0,0,0.04)'; e.currentTarget.style.borderColor = '#f1f5f9'; }}>
                        <div style={{ width: 42, height: 42, borderRadius: 12, background: s.iconBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                            <i className={`fas ${s.icon}`} style={{ fontSize: 16, color: s.iconColor }}></i>
                        </div>
                        <div style={{ flex: 1 }}>
                            <div style={{ fontWeight: 700, fontSize: 14 }}>{s.label}</div>
                            <div style={{ fontSize: 12, color: '#6B7280', marginTop: 1 }}>{loadingStats ? '...' : s.desc}</div>
                        </div>
                        <i className="fas fa-chevron-right" style={{ fontSize: 12, color: '#cbd5e1' }}></i>
                    </button>
                ))}
            </div>

            {(branding.contact_phone || branding.contact_email) && (
                <div className="card-flat">
                    <div style={{ padding: '12px 16px', borderBottom: '1px solid #f1f5f9' }}>
                        <span style={{ fontSize: 13, fontWeight: 700, color: '#374151' }}>Besoin d'aide ?</span>
                    </div>
                    {branding.contact_phone && (
                        <a href={`tel:${branding.contact_phone.replace(/\s/g, '')}`} className="item-row" style={{ textDecoration: 'none', color: 'inherit' }}>
                            <div className="icon-circle" style={{ background: '#dcfce7', color: '#16a34a' }}><i className="fas fa-phone"></i></div>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 600, fontSize: 14, color: '#1e293b' }}>{branding.contact_phone}</div>
                                <div style={{ fontSize: 12, color: '#94a3b8' }}>Appeler</div>
                            </div>
                            <i className="fas fa-chevron-right" style={{ color: '#d1d5db', fontSize: 12 }}></i>
                        </a>
                    )}
                    {branding.contact_email && (
                        <a href={`mailto:${branding.contact_email}`} className="item-row" style={{ textDecoration: 'none', color: 'inherit' }}>
                            <div className="icon-circle" style={{ background: '#dbeafe', color: '#2563eb' }}><i className="fas fa-envelope"></i></div>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 600, fontSize: 14, color: '#1e293b' }}>{branding.contact_email}</div>
                                <div style={{ fontSize: 12, color: '#94a3b8' }}>Envoyer un email</div>
                            </div>
                            <i className="fas fa-chevron-right" style={{ color: '#d1d5db', fontSize: 12 }}></i>
                        </a>
                    )}
                </div>
            )}
        </div>
    );
};

// ============================================================================
// BOTTOM NAVIGATION
// ============================================================================
const BottomNavigation = ({ activePage, onNavigate }) => {
    const items = [
        { id: 'home', icon: 'fa-home', label: 'Accueil' },
        { id: 'booking', icon: 'fa-bolt', label: 'Commander' },
        { id: 'rides', icon: 'fa-car', label: 'Courses' },
        { id: 'profile', icon: 'fa-user', label: 'Compte' }
    ];
    return (
        <nav className="bottom-nav">
            <div className="bottom-nav-inner">
                {items.map(it => (
                    <button key={it.id} className={`nav-item ${activePage === it.id ? 'active' : ''}`} onClick={() => onNavigate(it.id)}>
                        <i className={`fas ${it.icon} nav-icon`}></i>
                        <span className="nav-label">{it.label}</span>
                    </button>
                ))}
            </div>
        </nav>
    );
};

// ============================================================================
// MAIN APP
// ============================================================================
const App = () => {
    const [user, setUser] = useState(null);
    const [activePage, setActivePage] = useState('home');
    const [loading, setLoading] = useState(true);
    const [branding, setBranding] = useState({
        display_name: 'TaxiBook', logo_url: '', display_url: '',
        primary_color: '#FFB800', company_name: '', company_address: '',
        contact_phone: '', contact_email: ''
    });

    const verifyMagicLink = async (token) => {
        try {
            const result = await apiRequest('/auth/client/magic-verify', { method: 'POST', body: JSON.stringify({ token }) });
            if (result.success && result.data?.token) {
                localStorage.setItem(TOKEN_KEY, result.data.token);
                localStorage.setItem(USER_KEY, JSON.stringify(result.data.user));
                setUser(result.data.user);
            }
        } catch {}
        setLoading(false);
    };

    const loadProfile = async () => {
        try {
            const result = await apiRequest('/users/profile');
            if (result.success && result.data) {
                setUser(result.data.user || result.data);
                localStorage.setItem(USER_KEY, JSON.stringify(result.data.user || result.data));
            } else {
                localStorage.removeItem(TOKEN_KEY);
                localStorage.removeItem(USER_KEY);
            }
        } catch {
            localStorage.removeItem(TOKEN_KEY);
            localStorage.removeItem(USER_KEY);
        }
        setLoading(false);
    };

    useEffect(() => {
        fetch(`${API_URL}/settings/branding`).then(r => r.json()).then(res => {
            const d = res.data || res;
            setBranding(prev => ({ ...prev, ...d }));
            if (d.display_name) document.title = `${d.display_name} - Mon Compte`;
            if (d.favicon_url) {
                let fl = document.querySelector("link[rel~='icon']");
                if (!fl) { fl = document.createElement('link'); fl.rel = 'icon'; document.head.appendChild(fl); }
                fl.href = d.favicon_url;
            }
        }).catch(() => {});

        const url = new URL(window.location.href);
        const magicToken = url.searchParams.get('magic');
        if (magicToken) {
            url.searchParams.delete('magic');
            window.history.replaceState({}, '', url.pathname);
            verifyMagicLink(magicToken);
            return;
        }
        if (url.searchParams.get('card_status')) {
            if (localStorage.getItem('booking_in_progress')) {
                setActivePage('booking');
                localStorage.removeItem('booking_in_progress');
            } else {
                setActivePage('payments');
            }
        }
        const token = localStorage.getItem(TOKEN_KEY);
        if (token) loadProfile();
        else setLoading(false);
    }, []);

    const handleLogout = () => {
        localStorage.removeItem(TOKEN_KEY);
        localStorage.removeItem(USER_KEY);
        setUser(null);
        setActivePage('home');
    };

    if (loading) {
        return (
            <BrandingContext.Provider value={branding}>
                <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'linear-gradient(135deg, #FFB800 0%, #EAB308 100%)' }}>
                    <div className="spinner spinner-light" style={{ width: 40, height: 40, borderWidth: 4 }}></div>
                </div>
            </BrandingContext.Provider>
        );
    }

    if (!user) {
        return <BrandingContext.Provider value={branding}><LoginScreen /></BrandingContext.Provider>;
    }

    const pageTitles = {
        home: 'Accueil', booking: 'Réserver', rides: 'Mes courses',
        requests: 'Mes demandes', payments: 'Mes cartes',
        invoices: 'Mes factures', profile: 'Mon profil'
    };

    return (
        <BrandingContext.Provider value={branding}>
            <div className="app-shell">
                <div className="app-content scrollbar-thin">
                    {/* Top bar with logo + user dropdown */}
                    <div className="app-topbar">
                        <a href="#" onClick={(e) => { e.preventDefault(); setActivePage('home'); }} style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
                            {branding.logo_url ? (
                                <img src={branding.logo_url} alt={branding.display_name} style={{ height: 28, maxWidth: 130, objectFit: 'contain' }} />
                            ) : (
                                <>
                                    <div style={{ width: 32, height: 32, borderRadius: 9, background: 'linear-gradient(135deg, #FFB800, #EAB308)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 3px 8px rgba(255,184,0,0.35)' }}>
                                        <i className="fas fa-taxi" style={{ color: 'white', fontSize: 14 }}></i>
                                    </div>
                                    <span style={{ fontWeight: 800, color: '#111827', fontSize: 16 }}>{branding.display_name}</span>
                                </>
                            )}
                        </a>
                        <UserDropdown user={user} activePage={activePage} onNavigate={setActivePage} onLogout={handleLogout} />
                    </div>

                    {/* Page header */}
                    <div className="page-header">
                        <h1>{pageTitles[activePage]}</h1>
                    </div>

                    {/* Page content */}
                    {activePage === 'home' && <HomePage user={user} onNavigate={setActivePage} />}
                    {activePage === 'booking' && <BookingPage user={user} onBooked={() => {}} />}
                    {activePage === 'rides' && <RidesPage user={user} onNavigate={setActivePage} />}
                    {activePage === 'requests' && <RequestsPage user={user} />}
                    {activePage === 'payments' && <PaymentMethodsPage user={user} />}
                    {activePage === 'invoices' && <InvoicesPage user={user} />}
                    {activePage === 'profile' && <ProfilePage user={user} onLogout={handleLogout} />}

                    {/* Footer (company info) */}
                    {(branding.company_name || branding.contact_phone) && (
                        <div style={{ background: 'linear-gradient(135deg, #1e293b 0%, #334155 100%)', padding: '14px 20px', textAlign: 'center', marginTop: 20 }}>
                            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.7)', display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'center', gap: 4 }}>
                                {branding.company_name && <span style={{ fontWeight: 600, color: 'white' }}>{branding.company_name}</span>}
                                {branding.company_name && branding.company_address && <span style={{ color: 'rgba(255,255,255,0.35)' }}>•</span>}
                                {branding.company_address && <span>{branding.company_address}</span>}
                                {(branding.company_name || branding.company_address) && branding.contact_phone && <span style={{ color: 'rgba(255,255,255,0.35)' }}>•</span>}
                                {branding.contact_phone && <a href={`tel:${branding.contact_phone.replace(/\s/g, '')}`} style={{ color: 'rgba(255,255,255,0.85)', textDecoration: 'none' }}>{branding.contact_phone}</a>}
                                {branding.contact_phone && branding.contact_email && <span style={{ color: 'rgba(255,255,255,0.35)' }}>•</span>}
                                {branding.contact_email && <a href={`mailto:${branding.contact_email}`} style={{ color: 'rgba(255,255,255,0.85)', textDecoration: 'none' }}>{branding.contact_email}</a>}
                            </div>
                        </div>
                    )}
                </div>

                <BottomNavigation activePage={activePage} onNavigate={setActivePage} />
            </div>
        </BrandingContext.Provider>
    );
};

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