// ============================================================================
// TaxiBook Driver - App chauffeur
// Inspirée du design ch.taxibook.app.client.new (orange #FFB800)
// ============================================================================

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) || 'driving_token';
const USER_KEY = (window.API_CONFIG && window.API_CONFIG.USER_DATA_KEY) || 'driving_user';

// ============================================================================
// API
// ============================================================================
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());
}

// ============================================================================
// NOTIFICATIONS
// ============================================================================
const useNotifications = () => 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 fmtDate = (d) => d ? new Date(d).toLocaleDateString('fr-CH', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }) : '';
const fmtMoney = (cents) => (cents == null ? '—' : (cents / 100).toFixed(2) + ' CHF');
const fmtAmt = (n) => (n == null ? '—' : Number(n).toFixed(2) + ' CHF');

const statusLabel = (s) => ({
    pending: 'En attente', confirmed: 'Confirmée', searching: 'Recherche',
    accepted: 'Acceptée', driver_arriving: 'En approche', driver_arrived: 'Arrivé',
    in_progress: 'Passager à bord', onboard: 'Passager à bord',
    completed: 'Terminée', cancelled: 'Annulée'
}[s] || s);

// ============================================================================
// LOGIN
// ============================================================================
const LoginScreen = ({ onLogin }) => {
    const notifications = useNotifications();
    const [step, setStep] = useState('phone');
    const [phone, setPhone] = useState('');
    const [code, setCode] = useState('');
    const [loading, setLoading] = useState(false);

    const sendCode = async () => {
        if (!phone) { notifications.error('Numéro requis'); return; }
        setLoading(true);
        try {
            const res = await apiRequest('/auth/send-code', {
                method: 'POST',
                body: JSON.stringify({ phone_number: phone, user_type: 'driver', action: 'login' })
            });
            if (res.success) { setStep('code'); notifications.success('Code envoyé par SMS'); }
            else notifications.error(res.error || 'Erreur envoi');
        } catch { notifications.error('Erreur réseau'); }
        setLoading(false);
    };

    const verifyCode = async () => {
        if (!code) return;
        setLoading(true);
        try {
            const res = await apiRequest('/auth/verify-code', {
                method: 'POST',
                body: JSON.stringify({ phone_number: phone, code, user_type: 'driver', action: 'login' })
            });
            const token = res.data?.token || res.token;
            const user = res.data?.user || res.user;
            if (token && user) {
                localStorage.setItem(TOKEN_KEY, token);
                localStorage.setItem(USER_KEY, JSON.stringify(user));
                onLogin(user);
            } else notifications.error(res.error || res.message || 'Code invalide');
        } catch { notifications.error('Erreur réseau'); }
        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: 28, borderRadius: 20, boxShadow: '0 24px 48px -8px rgba(0,0,0,0.18)' }}>
                <div style={{ textAlign: 'center', marginBottom: 22 }}>
                    <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-taxi" style={{ color: 'white', fontSize: 22 }}></i>
                    </div>
                    <h1 style={{ fontSize: 22, fontWeight: 800, color: '#111827', margin: 0 }}>TaxiBook</h1>
                    <p style={{ color: '#6B7280', marginTop: 6, fontSize: 14 }}>Espace Chauffeur</p>
                </div>

                {step === 'phone' && (
                    <>
                        <label className="input-label">Numéro de téléphone</label>
                        <input
                            type="tel" className="input-field" placeholder="+41 79 123 45 67"
                            value={phone} onChange={e => setPhone(e.target.value)}
                            onKeyDown={e => e.key === 'Enter' && sendCode()} autoFocus
                        />
                        <button className="btn-primary" style={{ width: '100%', marginTop: 14 }} disabled={loading || !phone} onClick={sendCode}>
                            {loading ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-paper-plane"></i>Recevoir le code SMS</>}
                        </button>
                        <p style={{ fontSize: 12, color: '#9CA3AF', marginTop: 14, textAlign: 'center' }}>
                            <i className="fas fa-shield-alt" style={{ marginRight: 4 }}></i>
                            Connexion sécurisée par SMS
                        </p>
                    </>
                )}

                {step === 'code' && (
                    <>
                        <p style={{ fontSize: 13, color: '#6B7280', marginBottom: 12, textAlign: 'center' }}>
                            Code envoyé au<br /><b style={{ color: '#111827' }}>{phone}</b>
                        </p>
                        <label className="input-label">Code à 6 chiffres</label>
                        <input
                            type="tel" inputMode="numeric" maxLength="6" className="input-field"
                            placeholder="••••••" value={code}
                            onChange={e => setCode(e.target.value.replace(/\D/g, ''))}
                            onKeyDown={e => e.key === 'Enter' && verifyCode()}
                            autoFocus style={{ textAlign: 'center', fontSize: 22, letterSpacing: 6, fontWeight: 700 }}
                        />
                        <button className="btn-primary" style={{ width: '100%', marginTop: 14 }} disabled={loading || code.length < 4} onClick={verifyCode}>
                            {loading ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-sign-in-alt"></i>Se connecter</>}
                        </button>
                        <button className="btn-outline" style={{ width: '100%', marginTop: 8 }} onClick={() => { setStep('phone'); setCode(''); }}>
                            <i className="fas fa-arrow-left"></i>Modifier le numéro
                        </button>
                    </>
                )}
            </div>
        </div>
    );
};

// ============================================================================
// JOB CARD (free pool / mes courses)
// ============================================================================
const JobCard = ({ job, onClick, claimed }) => {
    const dateStr = fmtDate(job.pickup_datetime);
    const mins = job.pickup_datetime ? Math.round((new Date(job.pickup_datetime).getTime() - Date.now()) / 60000) : null;
    const isUrgent = mins != null && mins >= 0 && mins <= 30;

    return (
        <div className={`job-card ${claimed ? 'claimed' : ''} ${job.status === 'completed' ? 'completed' : ''}`} onClick={onClick}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className={`status-pill ${claimed ? (job.status === 'completed' ? 'fini' : (job.status === 'cancelled' ? 'canceled' : 'encours')) : 'dispo'}`}>
                        {claimed ? statusLabel(job.status) : 'Disponible'}
                    </span>
                    {isUrgent && <span className="job-chip urgent"><i className="fas fa-bolt"></i>{mins <= 0 ? 'Maintenant' : mins + ' min'}</span>}
                </div>
                {job.estimated_price > 0 && <span className="job-chip amount"><i className="fas fa-coins"></i>{fmtAmt(job.estimated_price)}</span>}
            </div>

            <div className="job-row">
                <div className="dot pickup"></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                    <span className="label">Départ</span>
                    <div className="value">{job.pickup_address || '—'}</div>
                </div>
            </div>
            <div className="job-row">
                <div className="dot dropoff"></div>
                <div style={{ flex: 1, minWidth: 0 }}>
                    <span className="label">Arrivée</span>
                    <div className="value">{job.dropoff_address || '—'}</div>
                </div>
            </div>

            <div className="job-meta">
                {dateStr && <span><i className="far fa-clock" style={{ marginRight: 4 }}></i>{dateStr}</span>}
                {job.display_name && <span><i className="far fa-user" style={{ marginRight: 4 }}></i>{job.display_name}</span>}
                {job.estimated_distance_km && <span><i className="fas fa-route" style={{ marginRight: 4 }}></i>{Number(job.estimated_distance_km).toFixed(1)} km</span>}
                {job.passengers && <span><i className="fas fa-users" style={{ marginRight: 4 }}></i>{job.passengers}</span>}
            </div>
        </div>
    );
};

// ============================================================================
// JOB DETAIL PANEL
// ============================================================================
const JobDetail = ({ job, onClose, onUpdated, onScanCard, claimed }) => {
    const notifications = useNotifications();
    const [busy, setBusy] = useState(false);

    const claim = async () => {
        if (busy) return;
        setBusy(true);
        const res = await apiRequest(`/free-pool/jobs/${job.job_hash}/claim`, { method: 'POST' });
        setBusy(false);
        if (res.success) { notifications.success('Course acceptée'); onUpdated(); onClose(); }
        else notifications.error(res.error || 'Échec de l\'acceptation');
    };

    const setStatus = async (status) => {
        if (busy) return;
        setBusy(true);
        const res = await apiRequest(`/free-pool/jobs/${job.job_hash}/status`, {
            method: 'POST', body: JSON.stringify({ status })
        });
        setBusy(false);
        if (res.success) { notifications.success('Statut mis à jour'); onUpdated(); }
        else notifications.error(res.error || 'Échec');
    };

    return (
        <div className="slide-panel">
            <div className="slide-header">
                <button className="slide-back" onClick={onClose}><i className="fas fa-arrow-left"></i></button>
                <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, color: '#111827' }}>Détail course</div>
                    <div style={{ fontSize: 11, color: '#94a3b8' }}>{job.job_hash}</div>
                </div>
                <span className={`status-pill ${claimed ? (job.status === 'completed' ? 'fini' : 'encours') : 'dispo'}`}>{claimed ? statusLabel(job.status) : 'Disponible'}</span>
            </div>

            <div className="page-content">
                <div className="card">
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                        <div>
                            <div style={{ fontSize: 11, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '.04em' }}>Prix estimé</div>
                            <div style={{ fontSize: 28, fontWeight: 800, color: '#111827' }}>{fmtAmt(job.estimated_price)}</div>
                        </div>
                        <div style={{ textAlign: 'right' }}>
                            <div style={{ fontSize: 11, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '.04em' }}>Distance</div>
                            <div style={{ fontSize: 18, fontWeight: 700, color: '#111827' }}>{job.estimated_distance_km ? Number(job.estimated_distance_km).toFixed(1) + ' km' : '—'}</div>
                        </div>
                    </div>
                </div>

                <div className="card">
                    <div className="job-row" style={{ paddingBottom: 12, borderBottom: '1px dashed #e5e7eb', marginBottom: 12 }}>
                        <div className="dot pickup"></div>
                        <div style={{ flex: 1 }}>
                            <span className="label">Départ</span>
                            <div className="value" style={{ fontSize: 15 }}>{job.pickup_address || '—'}</div>
                            {job.pickup_datetime && <div style={{ fontSize: 12, color: '#6b7280', marginTop: 2 }}><i className="far fa-clock" style={{ marginRight: 4 }}></i>{fmtDate(job.pickup_datetime)}</div>}
                        </div>
                    </div>
                    <div className="job-row">
                        <div className="dot dropoff"></div>
                        <div style={{ flex: 1 }}>
                            <span className="label">Arrivée</span>
                            <div className="value" style={{ fontSize: 15 }}>{job.dropoff_address || '—'}</div>
                        </div>
                    </div>
                </div>

                {(job.display_name || job.client_phone || job.client_phone_user) && (
                    <div className="card">
                        <div className="section-title">Client</div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                            <div style={{ width: 44, height: 44, borderRadius: '50%', background: '#fef3c7', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#92400e' }}>
                                <i className="fas fa-user"></i>
                            </div>
                            <div style={{ flex: 1 }}>
                                <div style={{ fontWeight: 700 }}>{job.display_name || 'Client'}</div>
                                {(job.client_phone_user || job.client_phone) && (
                                    <a href={`tel:${job.client_phone_user || job.client_phone}`} style={{ color: '#FFB800', fontSize: 13, fontWeight: 600 }}>
                                        <i className="fas fa-phone" style={{ marginRight: 4 }}></i>{job.client_phone_user || job.client_phone}
                                    </a>
                                )}
                            </div>
                        </div>
                    </div>
                )}

                {!claimed && (
                    <button className="btn-primary" style={{ width: '100%', padding: '1rem' }} disabled={busy} onClick={claim}>
                        {busy ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-check"></i>Accepter cette course</>}
                    </button>
                )}

                {claimed && job.status !== 'completed' && job.status !== 'cancelled' && (
                    <>
                        <div className="section-title">Actions</div>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                            {['accepted','driver_arriving'].includes(job.status) && (
                                <button className="btn-outline" disabled={busy} onClick={() => setStatus('driver_arrived')}>
                                    <i className="fas fa-map-marker-alt"></i>Arrivé
                                </button>
                            )}
                            {['accepted','driver_arriving','driver_arrived'].includes(job.status) && (
                                <button className="btn-primary" disabled={busy} onClick={() => setStatus('in_progress')}>
                                    <i className="fas fa-car"></i>Démarrer
                                </button>
                            )}
                            {['in_progress','onboard'].includes(job.status) && (
                                <>
                                    <button className="btn-outline" disabled={busy} onClick={() => onScanCard(job)}>
                                        <i className="fas fa-qrcode"></i>Scanner carte
                                    </button>
                                    <button className="btn-primary" disabled={busy} onClick={() => setStatus('completed')}>
                                        <i className="fas fa-flag-checkered"></i>Terminer
                                    </button>
                                </>
                            )}
                        </div>

                        <button className="btn-danger" style={{ width: '100%', marginTop: 12 }} disabled={busy} onClick={() => { if (confirm('Annuler cette course ?')) setStatus('cancelled'); }}>
                            <i className="fas fa-times"></i>Annuler la course
                        </button>
                    </>
                )}

                {claimed && job.status === 'in_progress' && (
                    <button className="btn-primary" style={{ width: '100%', padding: '1rem', background: 'linear-gradient(135deg, #10b981, #059669)', boxShadow: '0 4px 14px -2px rgba(16, 185, 129, 0.4)' }} onClick={() => onScanCard(job)}>
                        <i className="fas fa-qrcode" style={{ fontSize: 20 }}></i>
                        Encaisser via carte client
                    </button>
                )}
            </div>
        </div>
    );
};

// ============================================================================
// QR SCANNER + DEBIT PANEL
// ============================================================================
const ScanCardPanel = ({ jobContext, onClose }) => {
    const notifications = useNotifications();
    const [step, setStep] = useState('scan'); // scan | confirm | success
    const [scannedCard, setScannedCard] = useState(null);
    const [holder, setHolder] = useState(null);
    const [amount, setAmount] = useState('');
    const [busy, setBusy] = useState(false);
    const [manualMode, setManualMode] = useState(false);
    const [manualCode, setManualCode] = useState('');
    const scannerRef = useRef(null);
    const html5QrCodeRef = useRef(null);

    const initialAmount = jobContext?.estimated_price ? Number(jobContext.estimated_price).toFixed(2) : '';

    const startScanner = useCallback(() => {
        if (!window.Html5Qrcode) { notifications.error('Scanner non disponible'); return; }
        const elementId = 'qr-reader';
        const el = document.getElementById(elementId);
        if (!el) return;
        try { if (html5QrCodeRef.current) { html5QrCodeRef.current.stop().catch(() => {}); html5QrCodeRef.current.clear(); } } catch {}
        const html5QrCode = new window.Html5Qrcode(elementId);
        html5QrCodeRef.current = html5QrCode;
        html5QrCode.start(
            { facingMode: 'environment' },
            { fps: 10, qrbox: { width: 240, height: 240 } },
            async (decodedText) => {
                try { await html5QrCode.stop(); html5QrCode.clear(); } catch {}
                handleScanned(decodedText);
            },
            () => {}
        ).catch(err => {
            console.warn('[scanner]', err);
            notifications.error('Caméra inaccessible — utilisez la saisie manuelle');
            setManualMode(true);
        });
    }, []);

    useEffect(() => {
        if (step === 'scan' && !manualMode) {
            const t = setTimeout(startScanner, 300);
            return () => {
                clearTimeout(t);
                try { if (html5QrCodeRef.current) html5QrCodeRef.current.stop().catch(() => {}); } catch {}
            };
        }
    }, [step, manualMode, startScanner]);

    useEffect(() => {
        if (initialAmount && !amount) setAmount(initialAmount);
    }, [initialAmount]);

    const handleScanned = async (qrCode) => {
        setBusy(true);
        const res = await apiRequest('/cards/scan', {
            method: 'POST', body: JSON.stringify({ qr_code: qrCode })
        });
        setBusy(false);
        if (res.success && res.data) {
            setScannedCard(res.data.card);
            setHolder(res.data.holder);
            setStep('confirm');
            notifications.success('Carte détectée');
        } else {
            notifications.error(res.error || 'Carte introuvable');
            setManualMode(true);
        }
    };

    const submitDebit = async () => {
        const value = parseFloat(amount);
        if (!value || value <= 0) { notifications.error('Montant invalide'); return; }
        if (value * 100 > scannedCard.balance_cents) { notifications.error('Solde insuffisant'); return; }
        setBusy(true);
        const res = await apiRequest('/cards/debit', {
            method: 'POST',
            body: JSON.stringify({
                qr_code: scannedCard.qr_code,
                amount_cents: Math.round(value * 100),
                job_hash: jobContext?.job_hash || null,
                description: jobContext ? ('Course ' + jobContext.job_hash) : 'Paiement manuel'
            })
        });
        setBusy(false);
        if (res.success) { setStep('success'); notifications.success('Paiement confirmé'); }
        else notifications.error(res.error || 'Erreur de débit');
    };

    const numpadPress = (k) => {
        if (k === '⌫') { setAmount(a => a.slice(0, -1)); return; }
        if (k === 'C') { setAmount(''); return; }
        if (k === '.') { if (amount.includes('.')) return; setAmount(a => a + '.'); return; }
        // Limit decimals
        if (amount.includes('.') && amount.split('.')[1].length >= 2) return;
        setAmount(a => a + k);
    };

    return (
        <div className="slide-panel">
            <div className="slide-header">
                <button className="slide-back" onClick={onClose}><i className="fas fa-arrow-left"></i></button>
                <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700 }}>{step === 'scan' ? 'Scanner une carte' : step === 'confirm' ? 'Encaissement' : 'Paiement reçu'}</div>
                    {jobContext && <div style={{ fontSize: 11, color: '#94a3b8' }}>Course {jobContext.job_hash}</div>}
                </div>
            </div>

            <div className="page-content">
                {step === 'scan' && !manualMode && (
                    <>
                        <div className="scan-frame">
                            <div id="qr-reader"></div>
                            <span className="corner-bl"></span><span className="corner-br"></span>
                        </div>
                        <p style={{ textAlign: 'center', color: '#6b7280', fontSize: 13, marginTop: 8 }}>
                            Pointez l'appareil vers le QR de la carte client
                        </p>
                        <button className="btn-outline" onClick={() => setManualMode(true)}>
                            <i className="fas fa-keyboard"></i>Saisir le code manuellement
                        </button>
                    </>
                )}

                {step === 'scan' && manualMode && (
                    <>
                        <label className="input-label">Code de la carte</label>
                        <input
                            className="input-field" placeholder="TBC-XXXXX-XXXXX-XXXXX"
                            value={manualCode} onChange={e => setManualCode(e.target.value.toUpperCase())} autoFocus
                            style={{ fontFamily: 'monospace', letterSpacing: '0.05em' }}
                        />
                        <button className="btn-primary" disabled={!manualCode || busy} onClick={() => handleScanned(manualCode)}>
                            {busy ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-search"></i>Vérifier la carte</>}
                        </button>
                        <button className="btn-outline" onClick={() => setManualMode(false)}>
                            <i className="fas fa-camera"></i>Utiliser la caméra
                        </button>
                    </>
                )}

                {step === 'confirm' && scannedCard && (
                    <>
                        <div className="card-display orange">
                            <div className="card-label">Solde disponible</div>
                            <div className="card-balance">{fmtMoney(scannedCard.balance_cents)}</div>
                            <div className="card-number">{scannedCard.card_number_masked}</div>
                            {holder && (
                                <div style={{ marginTop: 8, fontSize: 13, opacity: 0.95 }}>
                                    <i className="fas fa-user" style={{ marginRight: 6 }}></i>
                                    {holder.full_name || holder.email || holder.phone_number || 'Client'}
                                </div>
                            )}
                        </div>

                        <div className="card">
                            <div className="section-title">Montant à débiter</div>
                            <div className="amount-display">
                                <span className="currency">CHF</span>
                                {amount || '0.00'}
                            </div>
                            <div className="numpad">
                                {['1','2','3','4','5','6','7','8','9','.','0','⌫'].map(k => (
                                    <button key={k} onClick={() => numpadPress(k)}>{k}</button>
                                ))}
                            </div>
                        </div>

                        <button
                            className="btn-primary"
                            style={{ width: '100%', padding: '1.125rem', fontSize: '1.0625rem', background: 'linear-gradient(135deg, #10b981, #059669)', boxShadow: '0 4px 14px -2px rgba(16, 185, 129, 0.4)' }}
                            disabled={busy || !amount || parseFloat(amount) <= 0}
                            onClick={submitDebit}
                        >
                            {busy ? <span className="spinner spinner-sm spinner-light"></span> : <><i className="fas fa-check-circle"></i>Confirmer débit {amount ? amount + ' CHF' : ''}</>}
                        </button>

                        <button className="btn-outline" onClick={() => { setScannedCard(null); setHolder(null); setStep('scan'); }}>
                            <i className="fas fa-redo"></i>Scanner une autre carte
                        </button>
                    </>
                )}

                {step === 'success' && (
                    <div style={{ textAlign: 'center', padding: '2rem 1rem' }}>
                        <div style={{ width: 88, height: 88, borderRadius: '50%', background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
                            <i className="fas fa-check" style={{ color: '#16a34a', fontSize: 38 }}></i>
                        </div>
                        <h2 style={{ fontSize: 22, fontWeight: 800, color: '#111827', margin: 0 }}>Paiement confirmé</h2>
                        <p style={{ color: '#6b7280', marginTop: 8 }}>{amount} CHF débité</p>
                        <button className="btn-primary" style={{ marginTop: 24, minWidth: 220 }} onClick={onClose}>
                            <i className="fas fa-arrow-left"></i>Retour
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
};

// ============================================================================
// PAGES
// ============================================================================

const AvailablePage = ({ onSelectJob }) => {
    const [jobs, setJobs] = useState([]);
    const [loading, setLoading] = useState(true);
    const notifications = useNotifications();

    const load = useCallback(async () => {
        const res = await apiRequest('/free-pool/available');
        if (res.success) setJobs(res.data?.jobs || []);
        setLoading(false);
    }, []);

    useEffect(() => {
        load();
        const iv = setInterval(load, 15000);
        return () => clearInterval(iv);
    }, [load]);

    return (
        <div className="page-content">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                    <h1 style={{ fontSize: 18, fontWeight: 800, margin: 0 }}>Courses disponibles</h1>
                    <p style={{ fontSize: 12, color: '#6b7280', margin: '2px 0 0' }}>Refusées par CORDIC, à prendre rapidement</p>
                </div>
                <button className="btn-outline" style={{ padding: '0.5rem 0.75rem' }} onClick={load}>
                    <i className="fas fa-sync"></i>
                </button>
            </div>

            {loading ? (
                <div style={{ textAlign: 'center', padding: 40 }}><span className="spinner"></span></div>
            ) : jobs.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-icon"><i className="fas fa-inbox"></i></div>
                    <p>Aucune course disponible pour le moment.</p>
                    <p style={{ fontSize: 12 }}>Restez connecté, le pool se met à jour automatiquement.</p>
                </div>
            ) : (
                jobs.map(j => <JobCard key={j.job_hash} job={j} onClick={() => onSelectJob(j, false)} />)
            )}
        </div>
    );
};

const MyRidesPage = ({ onSelectJob }) => {
    const [jobs, setJobs] = useState([]);
    const [loading, setLoading] = useState(true);

    const load = useCallback(async () => {
        const res = await apiRequest('/free-pool/mine');
        if (res.success) setJobs(res.data?.jobs || []);
        setLoading(false);
    }, []);

    useEffect(() => { load(); const iv = setInterval(load, 20000); return () => clearInterval(iv); }, [load]);

    const active = jobs.filter(j => !['completed','cancelled'].includes(j.status));
    const past = jobs.filter(j => ['completed','cancelled'].includes(j.status));

    return (
        <div className="page-content">
            <h1 style={{ fontSize: 18, fontWeight: 800, margin: 0 }}>Mes courses</h1>

            {loading ? (
                <div style={{ textAlign: 'center', padding: 40 }}><span className="spinner"></span></div>
            ) : (
                <>
                    {active.length > 0 && (
                        <>
                            <div className="section-title">En cours</div>
                            {active.map(j => <JobCard key={j.job_hash} job={j} claimed onClick={() => onSelectJob(j, true)} />)}
                        </>
                    )}
                    {past.length > 0 && (
                        <>
                            <div className="section-title" style={{ marginTop: 12 }}>Historique</div>
                            {past.map(j => <JobCard key={j.job_hash} job={j} claimed onClick={() => onSelectJob(j, true)} />)}
                        </>
                    )}
                    {jobs.length === 0 && (
                        <div className="empty-state">
                            <div className="empty-icon"><i className="fas fa-car"></i></div>
                            <p>Aucune course pour l'instant.</p>
                        </div>
                    )}
                </>
            )}
        </div>
    );
};

const ScanPage = ({ onScanContext }) => (
    <div className="page-content" style={{ paddingTop: 40, textAlign: 'center' }}>
        <div style={{ width: 88, height: 88, borderRadius: '50%', background: 'rgba(255,184,0,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
            <i className="fas fa-qrcode" style={{ color: '#FFB800', fontSize: 40 }}></i>
        </div>
        <h2 style={{ fontSize: 20, fontWeight: 800, margin: 0 }}>Encaisser une carte client</h2>
        <p style={{ color: '#6b7280', marginTop: 8, fontSize: 13, padding: '0 2rem' }}>
            Scannez le QR de la carte TaxiBook pour débiter le montant directement.
        </p>
        <button className="btn-primary" style={{ marginTop: 24, minWidth: 240, padding: '1rem' }} onClick={onScanContext}>
            <i className="fas fa-camera" style={{ fontSize: 20 }}></i>Lancer le scanner
        </button>
    </div>
);

const ProfilePage = ({ user, onLogout }) => (
    <div className="page-content">
        <div className="card" style={{ textAlign: 'center', padding: 24 }}>
            <div style={{ width: 76, height: 76, borderRadius: '50%', background: 'linear-gradient(135deg, #FFB800, #EAB308)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px', color: 'white', fontSize: 28, fontWeight: 800 }}>
                {((user?.first_name || user?.phone_number || 'D')[0] || 'D').toUpperCase()}
            </div>
            <h2 style={{ fontSize: 18, fontWeight: 800, margin: 0 }}>{user?.first_name || ''} {user?.last_name || ''}</h2>
            <p style={{ color: '#6b7280', margin: '4px 0 0', fontSize: 13 }}>{user?.phone_number}</p>
            {user?.email && <p style={{ color: '#94a3b8', margin: '2px 0 0', fontSize: 12 }}>{user.email}</p>}
        </div>

        <button className="btn-danger" style={{ width: '100%', marginTop: 12 }} onClick={onLogout}>
            <i className="fas fa-sign-out-alt"></i>Se déconnecter
        </button>

        <div style={{ marginTop: 18, textAlign: 'center', fontSize: 11, color: '#94a3b8' }}>
            TaxiBook Driver v1.0 — chauffeur indépendant
        </div>
    </div>
);

// ============================================================================
// MAIN APP
// ============================================================================
const App = () => {
    const [user, setUser] = useState(() => { try { return JSON.parse(localStorage.getItem(USER_KEY) || 'null'); } catch { return null; } });
    const [page, setPage] = useState('available');
    const [selectedJob, setSelectedJob] = useState(null);
    const [selectedClaimed, setSelectedClaimed] = useState(false);
    const [scanContext, setScanContext] = useState(null); // { job }
    const [refreshKey, setRefreshKey] = useState(0);

    const handleLogin = (u) => setUser(u);
    const handleLogout = () => {
        localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(USER_KEY);
        setUser(null);
    };

    if (!user) return <LoginScreen onLogin={handleLogin} />;

    return (
        <div className="app-shell">
            <div className="app-content">
                <div className="app-topbar">
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <div style={{ width: 32, height: 32, borderRadius: 8, background: 'linear-gradient(135deg, #FFB800, #EAB308)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white' }}>
                            <i className="fas fa-taxi" style={{ fontSize: 14 }}></i>
                        </div>
                        <div>
                            <div style={{ fontWeight: 800, fontSize: 14 }}>TaxiBook Driver</div>
                            <div style={{ fontSize: 11, color: '#94a3b8' }}>{user.phone_number}</div>
                        </div>
                    </div>
                    <span style={{ fontSize: 11, color: '#16a34a', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
                        <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#16a34a' }}></span>
                        En ligne
                    </span>
                </div>

                {page === 'available' && <AvailablePage key={'av-' + refreshKey} onSelectJob={(j, c) => { setSelectedJob(j); setSelectedClaimed(c); }} />}
                {page === 'mine' && <MyRidesPage key={'mi-' + refreshKey} onSelectJob={(j, c) => { setSelectedJob(j); setSelectedClaimed(c); }} />}
                {page === 'scan' && <ScanPage onScanContext={() => setScanContext({})} />}
                {page === 'profile' && <ProfilePage user={user} onLogout={handleLogout} />}
            </div>

            <div className="bottom-nav">
                <div className="bottom-nav-inner">
                    <button className={`nav-item ${page === 'available' ? 'active' : ''}`} onClick={() => setPage('available')}>
                        <span className="nav-icon"><i className="fas fa-list"></i></span>
                        <span className="nav-label">Dispo</span>
                    </button>
                    <button className={`nav-item ${page === 'mine' ? 'active' : ''}`} onClick={() => setPage('mine')}>
                        <span className="nav-icon"><i className="fas fa-car"></i></span>
                        <span className="nav-label">Mes courses</span>
                    </button>
                    <button className={`nav-item ${page === 'scan' ? 'active' : ''}`} onClick={() => setPage('scan')}>
                        <span className="nav-icon"><i className="fas fa-qrcode"></i></span>
                        <span className="nav-label">Scanner</span>
                    </button>
                    <button className={`nav-item ${page === 'profile' ? 'active' : ''}`} onClick={() => setPage('profile')}>
                        <span className="nav-icon"><i className="fas fa-user"></i></span>
                        <span className="nav-label">Profil</span>
                    </button>
                </div>
            </div>

            {selectedJob && (
                <JobDetail
                    job={selectedJob}
                    claimed={selectedClaimed}
                    onClose={() => setSelectedJob(null)}
                    onUpdated={() => setRefreshKey(k => k + 1)}
                    onScanCard={(job) => { setSelectedJob(null); setScanContext({ job }); }}
                />
            )}

            {scanContext && (
                <ScanCardPanel
                    jobContext={scanContext.job || null}
                    onClose={() => { setScanContext(null); setRefreshKey(k => k + 1); }}
                />
            )}
        </div>
    );
};

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