// =============================================================================
// mypro · widget de réservation (go.<key>.mypro.ch)
// =============================================================================
const { useState, useEffect, useRef, useMemo } = React;
const CFG = window.MyProConfig;

// =============================================================================
// HELPERS
// =============================================================================
const cls = (...x) => x.filter(Boolean).join(' ');

const formatMoney = (n, cur = 'CHF') => {
    if (n == null) return '';
    return new Intl.NumberFormat('fr-CH', { style: 'currency', currency: cur }).format(n);
};

const formatDateTime = (date, time) => {
    if (!date) return '';
    try {
        const d = new Date(date + 'T' + (time || '00:00'));
        return d.toLocaleDateString('fr-CH', { weekday: 'long', day: 'numeric', month: 'long' }) + ' à ' + (time || '');
    } catch (_) { return date + ' ' + (time || ''); }
};

// Applique les couleurs/branding de la centrale en CSS variables
function applyTheme(central, website) {
    const color = (central && central.color) || (website && website.color) || '#e74c3c';
    const root = document.documentElement;
    root.style.setProperty('--brand', color);
    root.style.setProperty('--brand-dark', shade(color, -0.18));
    root.style.setProperty('--brand-light', shade(color, 0.85));
}

function shade(hex, lum) {
    hex = String(hex || '').replace('#', '');
    if (hex.length === 3) hex = hex.split('').map(c => c + c).join('');
    const num = parseInt(hex, 16);
    const r = clamp(((num >> 16) & 0xff) + Math.round(255 * lum));
    const g = clamp(((num >>  8) & 0xff) + Math.round(255 * lum));
    const b = clamp((num & 0xff) + Math.round(255 * lum));
    return '#' + ((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1);
}
function clamp(v) { return Math.max(0, Math.min(255, v)); }

// =============================================================================
// ROOT
// =============================================================================
function App() {
    const [loading, setLoading] = useState(true);
    const [error, setError]     = useState(null);
    const [config, setConfig]   = useState(null);

    useEffect(() => {
        const key = CFG.PARTNER_KEY;
        if (!key) { setLoading(false); setError('NO_KEY'); return; }
        CentralAPI.widgetConfig(key)
            .then(r => {
                setConfig(r);
                applyTheme(r.central, r.website);
                document.title = (r.website && r.website.company) || (r.central && r.central.label) || 'Réservation';
            })
            .catch(e => setError(e.message || 'CONFIG_ERROR'))
            .finally(() => setLoading(false));
    }, []);

    if (loading) return <Loading />;
    if (error === 'NO_KEY') return <NotConfigured />;
    if (error)  return <ErrorScreen msg={error} />;
    if (!config) return <ErrorScreen msg="Configuration introuvable" />;

    return <BookingFlow config={config} />;
}

function Loading() {
    return (
        <div className="min-h-screen flex items-center justify-center bg-pattern">
            <div className="loading-spinner" />
        </div>
    );
}

function NotConfigured() {
    return (
        <div className="min-h-screen flex items-center justify-center px-4">
            <div className="glass rounded-2xl p-8 max-w-md text-center">
                <i className="fas fa-key text-4xl text-gray-300 mb-4" />
                <h1 className="text-xl font-bold mb-2">Aucune centrale spécifiée</h1>
                <p className="text-sm text-gray-600">
                    Pour accéder à un widget de réservation, utilisez l'URL de votre centrale au format
                    <span className="font-mono text-xs block mt-2 text-brand">&lt;votre-cle&gt;.go.mypro.ch</span>
                </p>
            </div>
        </div>
    );
}

function ErrorScreen({ msg }) {
    return (
        <div className="min-h-screen flex items-center justify-center px-4">
            <div className="glass rounded-2xl p-8 max-w-md text-center">
                <i className="fas fa-triangle-exclamation text-4xl text-red-400 mb-4" />
                <h1 className="text-xl font-bold mb-2">Erreur</h1>
                <p className="text-sm text-gray-600">{msg}</p>
            </div>
        </div>
    );
}

// =============================================================================
// BOOKING FLOW
// =============================================================================
function BookingFlow({ config }) {
    const { central, website, vehicles = [] } = config;
    const [step, setStep] = useState(1);
    const [data, setData] = useState({
        origin: null, destination: null, route: null,
        date: '', time: '',
        seats: 1, luggage: 0,
        vehicle: vehicles[0] || null,
        firstname: '', lastname: '', email: '', mobile: '', notes: '',
        payment: pickDefaultPayment(central),
    });
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState('');
    const [booking, setBooking] = useState(null);

    const update = (patch) => setData(d => ({ ...d, ...patch }));

    const submit = async () => {
        setErr(''); setBusy(true);
        try {
            const dated = data.date && data.time ? `${data.date} ${data.time}:00` : null;
            const payload = {
                customer_firstname: data.firstname,
                customer_lastname:  data.lastname,
                customer_email:     data.email,
                customer_mobile:    data.mobile,
                origin_address:      data.origin?.address,
                origin_latitude:     data.origin?.lat,
                origin_longitude:    data.origin?.lng,
                destination_address:  data.destination?.address,
                destination_latitude: data.destination?.lat,
                destination_longitude:data.destination?.lng,
                distance_km:  data.route?.distance_km || 0,
                duration_min: data.route?.duration_min || 0,
                dated,
                seats: data.seats,
                luggage: data.luggage,
                payment_method: data.payment,
                vehicle_id: data.vehicle?.id || null,
                notes: data.notes || null,
            };
            const r = await CentralAPI.createBooking(website.partnerkey, payload);
            setBooking(r.booking || r);
            setStep(6);
        } catch (e) {
            setErr(e.message);
        } finally { setBusy(false); }
    };

    if (step === 6 && booking) {
        return <BookingSuccess booking={booking} central={central} website={website} onNew={() => { setBooking(null); setStep(1); setData({ origin: null, destination: null, route: null, date: '', time: '', seats: 1, luggage: 0, vehicle: vehicles[0] || null, firstname: '', lastname: '', email: '', mobile: '', notes: '', payment: pickDefaultPayment(central) }); }} />;
    }

    return (
        <div className="min-h-screen flex flex-col bg-pattern">
            <Header central={central} website={website} />
            <StepBar current={step} onGo={(s) => s < step && setStep(s)} hasVehicles={vehicles.length > 0} />
            <main className="flex-1 max-w-2xl mx-auto w-full px-4 pb-10">
                {step === 1 && <Step1Trip data={data} update={update} onNext={() => setStep(vehicles.length ? 2 : 3)} central={central} />}
                {step === 2 && vehicles.length > 0 && (
                    <Step2Vehicle data={data} update={update} vehicles={vehicles} central={central}
                        onBack={() => setStep(1)} onNext={() => setStep(3)} />
                )}
                {step === 3 && <Step3DateTime data={data} update={update} onBack={() => setStep(vehicles.length ? 2 : 1)} onNext={() => setStep(4)} />}
                {step === 4 && <Step4Contact data={data} update={update} onBack={() => setStep(3)} onNext={() => setStep(5)} />}
                {step === 5 && (
                    <Step5Recap data={data} central={central} website={website}
                        err={err} busy={busy}
                        onBack={() => setStep(4)} onConfirm={submit}
                        onSelectPayment={(id) => update({ payment: id })} />
                )}
            </main>
            <footer className="border-t border-gray-100 bg-white py-3 text-center text-xs text-gray-400">
                <i className="fas fa-shield-halved mr-1" /> Propulsé par <a href="https://mypro.ch" target="_blank" rel="noopener" className="font-semibold text-brand hover:underline">mypro.ch</a>
            </footer>
        </div>
    );
}

function pickDefaultPayment(c) {
    if (!c) return 'card';
    if (c.is_method_card) return 'card';
    if (c.is_method_cash) return 'cash';
    if (c.is_method_bill) return 'bill';
    return 'card';
}

// =============================================================================
// HEADER
// =============================================================================
function Header({ central, website }) {
    const name = (website && website.company) || (central && central.label) || 'Réservation VTC';
    const phone = (website && website.phone_booking) || (central && central.phone_booking) || (website && website.phone);
    const logo = website && website.img;
    return (
        <header className="glass-header text-white">
            <div className="max-w-2xl mx-auto px-4 py-4 flex items-center gap-3">
                <div className="w-12 h-12 rounded-xl flex items-center justify-center bg-white/10 overflow-hidden">
                    {logo
                        ? <img src={logo} alt="" className="w-full h-full object-contain" />
                        : <i className="fas fa-taxi text-xl" />}
                </div>
                <div className="flex-1 min-w-0">
                    <div className="font-bold text-base truncate">{name}</div>
                    <div className="text-xs text-white/70">Réserver un trajet</div>
                </div>
                {phone && (
                    <a href={'tel:' + phone} className="hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 hover:bg-white/20 text-sm">
                        <i className="fas fa-phone" /> {phone}
                    </a>
                )}
            </div>
        </header>
    );
}

// =============================================================================
// STEP BAR
// =============================================================================
function StepBar({ current, onGo, hasVehicles }) {
    const steps = hasVehicles
        ? [{ id: 1, label: 'Trajet' }, { id: 2, label: 'Véhicule' }, { id: 3, label: 'Date' }, { id: 4, label: 'Vous' }, { id: 5, label: 'Confirmer' }]
        : [{ id: 1, label: 'Trajet' }, { id: 3, label: 'Date' }, { id: 4, label: 'Vous' }, { id: 5, label: 'Confirmer' }];
    return (
        <div className="bg-white border-b border-gray-100">
            <div className="max-w-2xl mx-auto px-4 py-3 flex items-center gap-1">
                {steps.map((s, i) => {
                    const done   = current > s.id;
                    const active = current === s.id;
                    return (
                        <React.Fragment key={s.id}>
                            <button onClick={() => onGo(s.id)} disabled={!done}
                                className={cls('flex items-center gap-2 px-2 py-1 rounded-lg text-xs font-semibold transition-all',
                                    active ? 'text-brand' : done ? 'text-gray-700 cursor-pointer hover:bg-gray-50' : 'text-gray-400')}>
                                <span className={cls('w-6 h-6 rounded-full flex items-center justify-center text-[10px]',
                                    done ? 'bg-green-500 text-white' : active ? 'bg-brand text-white' : 'bg-gray-200 text-gray-500')}
                                    style={active ? { background: 'var(--brand)' } : {}}>
                                    {done ? <i className="fas fa-check" /> : (i + 1)}
                                </span>
                                <span className="hidden sm:inline">{s.label}</span>
                            </button>
                            {i < steps.length - 1 && <div className="flex-1 h-px bg-gray-200" />}
                        </React.Fragment>
                    );
                })}
            </div>
        </div>
    );
}

// =============================================================================
// STEP 1 — TRAJET
// =============================================================================
function Step1Trip({ data, update, onNext, central }) {
    useEffect(() => {
        if (data.origin && data.destination && !data.route) {
            Maps.route(`${data.origin.lat},${data.origin.lng}`, `${data.destination.lat},${data.destination.lng}`)
                .then(d => {
                    if (d?.routes?.[0]?.legs?.[0]) {
                        const leg = d.routes[0].legs[0];
                        update({ route: {
                            distance_km: Math.round(leg.distance.value / 100) / 10,
                            duration_min: Math.round(leg.duration.value / 60),
                        }});
                    }
                }).catch(() => {});
        }
    }, [data.origin, data.destination]);

    return (
        <div className="space-y-4 py-6 fade-in">
            <div className="glass rounded-2xl p-5 space-y-3">
                <h2 className="font-bold text-lg">Votre trajet</h2>
                <AddressInput
                    label="Lieu de prise en charge"
                    iconColor="text-green-600"
                    value={data.origin}
                    onChange={(v) => update({ origin: v, route: null })}
                    placeholder="Adresse, gare, aéroport..." />
                <AddressInput
                    label="Destination"
                    iconColor="text-red-600"
                    value={data.destination}
                    onChange={(v) => update({ destination: v, route: null })}
                    placeholder="Où allez-vous ?" />
                {data.route && (
                    <div className="bg-brand-light/40 rounded-xl p-3 flex items-center justify-around text-sm font-semibold"
                        style={{ background: 'var(--brand-light)' }}>
                        <span><i className="fas fa-road mr-1" /> {data.route.distance_km} km</span>
                        <span><i className="fas fa-clock mr-1" /> {data.route.duration_min} min</span>
                        {central?.base_price != null && (
                            <span><i className="fas fa-coins mr-1" /> ≈ {formatMoney((Number(central.base_price) || 0) + (Number(central.price_per_km) || 0) * data.route.distance_km)}</span>
                        )}
                    </div>
                )}
            </div>
            <button onClick={onNext} disabled={!data.origin || !data.destination}
                className="btn-primary w-full">
                Continuer <i className="fas fa-arrow-right ml-2" />
            </button>
        </div>
    );
}

// =============================================================================
// STEP 2 — VÉHICULE
// =============================================================================
function Step2Vehicle({ data, update, vehicles, central, onBack, onNext }) {
    const km = data.route?.distance_km || 0;
    const basePrice = (v) => (Number(central?.base_price) || 0) + (Number(central?.price_per_km) || 0) * km;

    return (
        <div className="space-y-3 py-6 fade-in">
            <h2 className="font-bold text-lg px-1">Choisissez votre véhicule</h2>
            <div className="space-y-2">
                {vehicles.map(v => {
                    const selected = data.vehicle?.id === v.id;
                    return (
                        <button key={v.id} onClick={() => update({ vehicle: v })}
                            className={cls('glass rounded-2xl p-4 w-full text-left flex items-center gap-3 transition-all',
                                selected ? 'ring-2 ring-brand shadow-md' : 'hover:shadow-md')}
                            style={selected ? { boxShadow: '0 0 0 2px var(--brand)' } : {}}>
                            <div className="w-14 h-14 rounded-xl bg-gray-100 flex items-center justify-center text-2xl text-gray-400 flex-shrink-0">
                                <i className="fas fa-car" />
                            </div>
                            <div className="flex-1 min-w-0">
                                <div className="font-bold truncate">{v.brand} {v.model}</div>
                                <div className="text-xs text-gray-500 truncate">
                                    <i className="fas fa-user mr-1" /> {v.seats || 4} places
                                    {v.color ? ' · ' + v.color : ''}
                                </div>
                            </div>
                            {km > 0 && (
                                <div className="text-right">
                                    <div className="font-bold text-sm" style={{ color: 'var(--brand)' }}>{formatMoney(basePrice(v))}</div>
                                    <div className="text-[10px] text-gray-400">estimation</div>
                                </div>
                            )}
                        </button>
                    );
                })}
            </div>
            <div className="flex gap-2 pt-2">
                <button onClick={onBack} className="btn-secondary flex-1"><i className="fas fa-arrow-left mr-2" /> Retour</button>
                <button onClick={onNext} disabled={!data.vehicle} className="btn-primary flex-[2]">
                    Continuer <i className="fas fa-arrow-right ml-2" />
                </button>
            </div>
        </div>
    );
}

// =============================================================================
// STEP 3 — DATE / HEURE
// =============================================================================
function Step3DateTime({ data, update, onBack, onNext }) {
    const today = new Date().toISOString().split('T')[0];
    const setNow = () => {
        const d = new Date(Date.now() + 30 * 60000);
        const day = d.toISOString().split('T')[0];
        const h = String(d.getHours()).padStart(2, '0');
        const m = String(Math.floor(d.getMinutes() / 5) * 5).padStart(2, '0');
        update({ date: day, time: `${h}:${m}` });
    };

    return (
        <div className="space-y-3 py-6 fade-in">
            <div className="glass rounded-2xl p-5 space-y-4">
                <h2 className="font-bold text-lg">Quand ?</h2>
                <button type="button" onClick={setNow}
                    className="w-full py-2 rounded-lg border border-dashed border-brand text-brand text-sm font-semibold hover:bg-brand-light/30"
                    style={{ borderColor: 'var(--brand)', color: 'var(--brand)' }}>
                    <i className="fas fa-bolt mr-1" /> Dès que possible (30 min)
                </button>
                <div className="grid grid-cols-2 gap-3">
                    <div>
                        <label className="block text-xs font-semibold text-gray-600 mb-1">Date</label>
                        <input type="date" min={today} className="input-field"
                            value={data.date} onChange={e => update({ date: e.target.value })} />
                    </div>
                    <div>
                        <label className="block text-xs font-semibold text-gray-600 mb-1">Heure</label>
                        <input type="time" className="input-field"
                            value={data.time} onChange={e => update({ time: e.target.value })} />
                    </div>
                </div>
                <div className="grid grid-cols-2 gap-3">
                    <div>
                        <label className="block text-xs font-semibold text-gray-600 mb-1">Passagers</label>
                        <select className="input-field" value={data.seats} onChange={e => update({ seats: parseInt(e.target.value) })}>
                            {[1,2,3,4,5,6,7,8].map(n => <option key={n} value={n}>{n} passager{n > 1 ? 's' : ''}</option>)}
                        </select>
                    </div>
                    <div>
                        <label className="block text-xs font-semibold text-gray-600 mb-1">Bagages</label>
                        <select className="input-field" value={data.luggage} onChange={e => update({ luggage: parseInt(e.target.value) })}>
                            {[0,1,2,3,4,5,6].map(n => <option key={n} value={n}>{n} bagage{n > 1 ? 's' : ''}</option>)}
                        </select>
                    </div>
                </div>
            </div>
            <div className="flex gap-2">
                <button onClick={onBack} className="btn-secondary flex-1"><i className="fas fa-arrow-left mr-2" /> Retour</button>
                <button onClick={onNext} disabled={!data.date || !data.time} className="btn-primary flex-[2]">
                    Continuer <i className="fas fa-arrow-right ml-2" />
                </button>
            </div>
        </div>
    );
}

// =============================================================================
// STEP 4 — CONTACT
// =============================================================================
function Step4Contact({ data, update, onBack, onNext }) {
    const ok = data.firstname && data.lastname && data.email && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email) && data.mobile;
    return (
        <div className="space-y-3 py-6 fade-in">
            <div className="glass rounded-2xl p-5 space-y-3">
                <h2 className="font-bold text-lg">Vos coordonnées</h2>
                <div className="grid grid-cols-2 gap-3">
                    <input className="input-field" placeholder="Prénom" value={data.firstname} onChange={e => update({ firstname: e.target.value })} />
                    <input className="input-field" placeholder="Nom" value={data.lastname} onChange={e => update({ lastname: e.target.value })} />
                </div>
                <input type="email" className="input-field" placeholder="Email" value={data.email} onChange={e => update({ email: e.target.value })} />
                <input type="tel" className="input-field" placeholder="Téléphone (mobile)" value={data.mobile} onChange={e => update({ mobile: e.target.value })} />
                <textarea className="input-field" rows="3" placeholder="Notes (optionnel : nº de vol, instructions...)"
                    value={data.notes} onChange={e => update({ notes: e.target.value })} />
            </div>
            <div className="flex gap-2">
                <button onClick={onBack} className="btn-secondary flex-1"><i className="fas fa-arrow-left mr-2" /> Retour</button>
                <button onClick={onNext} disabled={!ok} className="btn-primary flex-[2]">
                    Continuer <i className="fas fa-arrow-right ml-2" />
                </button>
            </div>
        </div>
    );
}

// =============================================================================
// STEP 5 — RECAP / PAYMENT / CONFIRM
// =============================================================================
function Step5Recap({ data, central, website, err, busy, onBack, onConfirm, onSelectPayment }) {
    const km = data.route?.distance_km || 0;
    const price = (Number(central?.base_price) || 0) + (Number(central?.price_per_km) || 0) * km;

    const methods = [
        { id: 'card', enabled: !!central?.is_method_card, label: 'Carte (en ligne)', icon: 'fa-credit-card' },
        { id: 'cash', enabled: !!central?.is_method_cash, label: 'Cash au chauffeur', icon: 'fa-money-bill' },
        { id: 'bill', enabled: !!central?.is_method_bill, label: 'Sur facture', icon: 'fa-file-invoice' },
        { id: 'card_to_driver', enabled: !!central?.is_method_card_to_driver, label: 'Carte au chauffeur', icon: 'fa-mobile' },
    ].filter(m => m.enabled);

    return (
        <div className="space-y-3 py-6 fade-in">
            <div className="glass rounded-2xl p-5">
                <h2 className="font-bold text-lg mb-3">Récapitulatif</h2>
                <RecapRow icon="fa-circle text-green-500" text={data.origin?.address} />
                <RecapRow icon="fa-map-marker-alt text-red-500" text={data.destination?.address} />
                <RecapRow icon="fa-calendar text-blue-500" text={formatDateTime(data.date, data.time)} />
                <RecapRow icon="fa-user text-purple-500" text={`${data.seats} passager${data.seats > 1 ? 's' : ''} · ${data.luggage} bagage${data.luggage > 1 ? 's' : ''}`} />
                {data.vehicle && (
                    <RecapRow icon="fa-car text-gray-700" text={`${data.vehicle.brand} ${data.vehicle.model}`} />
                )}
                {km > 0 && (
                    <RecapRow icon="fa-road text-gray-700" text={`${km} km · ${data.route.duration_min} min`} />
                )}
                <RecapRow icon="fa-user text-gray-700" text={`${data.firstname} ${data.lastname} · ${data.email} · ${data.mobile}`} last />
                {price > 0 && (
                    <div className="mt-3 p-3 rounded-xl flex items-center justify-between"
                        style={{ background: 'var(--brand-light)' }}>
                        <span className="text-sm font-semibold">Prix estimé</span>
                        <span className="text-xl font-bold" style={{ color: 'var(--brand)' }}>{formatMoney(price)}</span>
                    </div>
                )}
            </div>

            {methods.length > 0 && (
                <div className="glass rounded-2xl p-5">
                    <h3 className="font-bold mb-3">Mode de paiement</h3>
                    <div className="grid grid-cols-2 gap-2">
                        {methods.map(m => {
                            const sel = data.payment === m.id;
                            return (
                                <button key={m.id} type="button"
                                    onClick={() => onSelectPayment && onSelectPayment(m.id)}
                                    className={cls('rounded-xl border-2 p-3 text-left text-sm flex items-center gap-2 transition-all',
                                        sel ? 'shadow-sm' : 'border-gray-200 hover:border-gray-300')}
                                    style={sel ? { borderColor: 'var(--brand)', background: 'var(--brand-light)' } : {}}>
                                    <i className={'fas ' + m.icon + ' text-lg'} style={sel ? { color: 'var(--brand)' } : {}} />
                                    <span className="flex-1 font-semibold">{m.label}</span>
                                    {sel && <i className="fas fa-check text-green-600" />}
                                </button>
                            );
                        })}
                    </div>
                </div>
            )}

            {err && <div className="text-sm text-red-600 px-4">{err}</div>}

            <div className="flex gap-2">
                <button onClick={onBack} className="btn-secondary flex-1" disabled={busy}>
                    <i className="fas fa-arrow-left mr-2" /> Retour
                </button>
                <button onClick={onConfirm} className="btn-primary flex-[2]" disabled={busy}>
                    {busy ? <span className="spinner-dot" /> : <><i className="fas fa-check mr-2" /> Confirmer</>}
                </button>
            </div>
        </div>
    );
}

function RecapRow({ icon, text, last }) {
    if (!text) return null;
    return (
        <div className={cls('flex items-start gap-3 py-2', !last && 'border-b border-gray-100')}>
            <i className={'fas ' + icon + ' text-xs mt-1.5 w-4 text-center'} />
            <div className="text-sm flex-1">{text}</div>
        </div>
    );
}

// =============================================================================
// SUCCESS
// =============================================================================
function BookingSuccess({ booking, central, website, onNew }) {
    const phone = (website && website.phone_booking) || (central && central.phone_booking) || (website && website.phone);
    return (
        <div className="min-h-screen flex items-center justify-center px-4 bg-pattern">
            <div className="glass rounded-2xl p-8 max-w-md w-full text-center fade-in">
                <div className="w-20 h-20 mx-auto mb-4 rounded-full flex items-center justify-center bg-green-500 success-pop">
                    <i className="fas fa-check text-white text-3xl" />
                </div>
                <h1 className="text-2xl font-bold mb-1">Réservation confirmée !</h1>
                <p className="text-gray-500 text-sm mb-4">
                    Votre numéro : <span className="font-mono font-bold" style={{ color: 'var(--brand)' }}>
                        {booking.reference || booking.id || '—'}
                    </span>
                </p>
                <div className="text-sm text-gray-600 mb-6">
                    Vous allez recevoir un email de confirmation. Un chauffeur vous sera assigné très bientôt.
                </div>
                {phone && (
                    <a href={'tel:' + phone} className="block btn-secondary w-full mb-2">
                        <i className="fas fa-phone mr-2" /> {phone}
                    </a>
                )}
                <button onClick={onNew} className="btn-primary w-full">
                    Nouvelle réservation
                </button>
            </div>
        </div>
    );
}

// =============================================================================
// ADDRESS INPUT (Maps autocomplete)
// =============================================================================
function AddressInput({ label, value, onChange, placeholder, iconColor }) {
    const [q, setQ] = useState(value?.address || '');
    const [items, setItems] = useState([]);
    const [open, setOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const tRef = useRef(null);
    useEffect(() => { setQ(value?.address || ''); }, [value]);

    const handle = (e) => {
        const v = e.target.value; setQ(v); setOpen(true);
        clearTimeout(tRef.current);
        tRef.current = setTimeout(async () => {
            if (v.length < 3) { setItems([]); return; }
            setLoading(true);
            const r = await Maps.search(v).catch(() => []);
            setItems(r); setLoading(false);
        }, 280);
    };

    const pick = async (s) => {
        setItems([]); setOpen(false);
        const det = await Maps.details(s.place_id);
        if (det?.geometry?.location) {
            const addr = det.formatted_address || s.description;
            onChange({ address: addr, lat: det.geometry.location.lat, lng: det.geometry.location.lng, place_id: s.place_id });
            setQ(addr);
        } else {
            onChange({ address: s.description, place_id: s.place_id });
            setQ(s.description);
        }
    };

    return (
        <div className="relative">
            <label className="block text-xs font-semibold text-gray-600 mb-1">{label}</label>
            <div className="relative">
                <i className={'fas fa-map-marker-alt absolute left-3 top-1/2 -translate-y-1/2 ' + (iconColor || 'text-gray-400')} />
                <input className="input-field pl-9" placeholder={placeholder}
                    value={q} onChange={handle}
                    onFocus={() => items.length && setOpen(true)} />
                {loading && <div className="absolute right-3 top-1/2 -translate-y-1/2 loading-spinner" style={{ width: 16, height: 16, borderWidth: 2 }} />}
            </div>
            {open && items.length > 0 && (
                <div className="absolute z-20 mt-1 w-full bg-white border border-gray-200 rounded-xl shadow-xl max-h-72 overflow-auto">
                    {items.map(s => (
                        <button key={s.place_id} onClick={() => pick(s)}
                            className="w-full text-left px-4 py-3 hover:bg-gray-50 text-sm border-b border-gray-100 last:border-b-0">
                            <i className="fas fa-map-marker-alt text-gray-400 mr-2" />
                            <span className="font-medium">{s.structured_formatting?.main_text || s.description}</span>
                            {s.structured_formatting?.secondary_text && (
                                <div className="text-xs text-gray-500 ml-6 mt-0.5">{s.structured_formatting.secondary_text}</div>
                            )}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
}

// =============================================================================
// MOUNT
// =============================================================================
ReactDOM.createRoot(document.getElementById('app')).render(<App />);
