/* mypro.ch · Partner – React app (single-file JSX) */
const { useState, useEffect, useCallback, useMemo, createContext, useContext } = React;

/* ---------- Helpers ---------- */
const fmtMoney = (v, cur = 'CHF') => {
    if (v == null || isNaN(Number(v))) return '–';
    return Number(v).toLocaleString('fr-CH', { style: 'currency', currency: cur });
};
const fmtDate = (s, opts = {}) => {
    if (!s) return '–';
    const d = new Date(s.includes('T') ? s : s.replace(' ', 'T') + 'Z');
    return d.toLocaleDateString('fr-CH', { day: '2-digit', month: 'short', year: 'numeric', ...opts });
};
const fmtDateTime = (s) => {
    if (!s) return '–';
    const d = new Date(s.includes('T') ? s : s.replace(' ', 'T') + 'Z');
    return d.toLocaleDateString('fr-CH', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
};
const initials = (name) => (name || '?').split(' ').map(s => s[0]).filter(Boolean).slice(0, 2).join('').toUpperCase();

/* ---------- Toast ---------- */
const ToastContext = createContext({ push: () => {} });
function ToastProvider({ children }) {
    const [items, setItems] = useState([]);
    const push = useCallback((msg, type = 'success') => {
        const id = Date.now() + Math.random();
        setItems((arr) => [...arr, { id, msg, type }]);
        setTimeout(() => setItems((arr) => arr.filter(i => i.id !== id)), 3500);
    }, []);
    return (
        <ToastContext.Provider value={{ push }}>
            {children}
            <div className="toast-container">
                {items.map(t => (
                    <div key={t.id} className={`toast ${t.type}`}>
                        <i className={`fas ${t.type === 'success' ? 'fa-check-circle text-emerald-500' : 'fa-circle-exclamation text-rose-500'}`}></i>
                        <span>{t.msg}</span>
                    </div>
                ))}
            </div>
        </ToastContext.Provider>
    );
}
const useToast = () => useContext(ToastContext);

/* ---------- Modal ---------- */
function Modal({ open, onClose, children, title, footer }) {
    if (!open) return null;
    return (
        <div className="modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose && onClose(); }}>
            <div className="modal">
                {title && (
                    <div style={{ padding: '18px 22px', borderBottom: '1px solid #e2e8f0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{title}</h3>
                        <button onClick={onClose} className="btn btn-ghost btn-sm"><i className="fas fa-times"></i></button>
                    </div>
                )}
                <div style={{ padding: '20px 22px' }}>{children}</div>
                {footer && (
                    <div style={{ padding: '14px 22px', borderTop: '1px solid #e2e8f0', display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                        {footer}
                    </div>
                )}
            </div>
        </div>
    );
}

/* ---------- Login Screen ---------- */
function LoginScreen() {
    const [email, setEmail] = useState('');
    const [sent, setSent] = useState(false);
    const [busy, setBusy] = useState(false);
    const [err, setErr] = useState(null);
    const submit = async (e) => {
        e.preventDefault();
        setBusy(true); setErr(null);
        try {
            await MyProAuth.requestMagic(email);
            setSent(true);
        } catch (e) { setErr(e.message); }
        setBusy(false);
    };
    return (
        <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, background: 'linear-gradient(135deg,#ede9fe,#fef3c7)' }}>
            <div className="card" style={{ maxWidth: 440, width: '100%', padding: '36px 28px' }}>
                <div style={{ textAlign: 'center', marginBottom: 24 }}>
                    <div style={{ width: 64, height: 64, borderRadius: 18, background: 'linear-gradient(135deg,#7c3aed,#6d28d9)', margin: '0 auto 14px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontSize: 28 }}>
                        <i className="fas fa-handshake"></i>
                    </div>
                    <h1 style={{ margin: 0, fontSize: 22, fontWeight: 800 }}>Espace Partenaire</h1>
                    <p style={{ color: '#64748b', fontSize: 14, marginTop: 6 }}>mypro.ch · Suivez vos courses & commissions</p>
                </div>

                {sent ? (
                    <div style={{ textAlign: 'center', padding: '20px 0' }}>
                        <div style={{ fontSize: 48, color: '#7c3aed', marginBottom: 12 }}><i className="fas fa-paper-plane"></i></div>
                        <h2 style={{ margin: '0 0 8px', fontSize: 18 }}>Lien envoyé !</h2>
                        <p style={{ color: '#64748b', fontSize: 14 }}>Consultez votre boîte mail <strong>{email}</strong> et cliquez sur le lien pour vous connecter.</p>
                        <button onClick={() => { setSent(false); setEmail(''); }} className="btn btn-ghost" style={{ marginTop: 16 }}>Recommencer</button>
                    </div>
                ) : (
                    <form onSubmit={submit}>
                        <div className="field">
                            <label>Email professionnel</label>
                            <input type="email" required placeholder="vous@hotel.ch" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus />
                        </div>
                        {err && <div className="pill pill-danger" style={{ marginBottom: 12 }}>{err}</div>}
                        <button type="submit" className="btn btn-primary" style={{ width: '100%' }} disabled={busy}>
                            {busy ? <><span className="loading-spinner" style={{ width: 16, height: 16, borderWidth: 2 }}></span> Envoi…</> : <><i className="fas fa-envelope"></i> Recevoir un lien magique</>}
                        </button>
                        <p style={{ fontSize: 12, color: '#94a3b8', marginTop: 14, textAlign: 'center' }}>
                            Pas encore partenaire ? <a href="mailto:partenaires@mypro.ch" style={{ color: '#7c3aed', fontWeight: 600 }}>Contactez-nous</a>
                        </p>
                    </form>
                )}
            </div>
        </div>
    );
}

/* ---------- App Shell ---------- */
function AppShell({ user, onLogout }) {
    const [tab, setTab] = useState('home');
    return (
        <div style={{ minHeight: '100vh' }}>
            {/* Top bar */}
            <header style={{ background: 'white', borderBottom: '1px solid #e2e8f0', padding: '12px 16px', position: 'sticky', top: 0, zIndex: 40 }}>
                <div style={{ maxWidth: 1100, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ width: 38, height: 38, borderRadius: 10, background: 'linear-gradient(135deg,#7c3aed,#6d28d9)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontWeight: 700, fontSize: 14 }}>
                        {initials(user.label)}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 700, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.label}</div>
                        <div style={{ fontSize: 12, color: '#64748b' }}>
                            {user.is_validated ? <span><i className="fas fa-check-circle text-emerald-500"></i> Compte validé</span> : <span><i className="fas fa-clock text-amber-500"></i> En attente de validation</span>}
                        </div>
                    </div>
                    <button className="btn btn-ghost btn-sm" onClick={onLogout} title="Déconnexion"><i className="fas fa-sign-out-alt"></i></button>
                </div>
            </header>

            {/* Desktop tabs */}
            <div className="hidden md:block" style={{ background: 'white', borderBottom: '1px solid #e2e8f0' }}>
                <div style={{ maxWidth: 1100, margin: '0 auto', padding: '0 16px' }} className="tab-segmented" >
                    <DesktopTab id="home" tab={tab} setTab={setTab} icon="fa-house" label="Accueil" />
                    <DesktopTab id="bookings" tab={tab} setTab={setTab} icon="fa-route" label="Courses" />
                    <DesktopTab id="commissions" tab={tab} setTab={setTab} icon="fa-coins" label="Commissions" />
                    <DesktopTab id="link" tab={tab} setTab={setTab} icon="fa-link" label="Mon lien" />
                    <DesktopTab id="profile" tab={tab} setTab={setTab} icon="fa-user" label="Profil" />
                </div>
            </div>

            {/* Content */}
            <main className="with-bottom-nav" style={{ maxWidth: 1100, margin: '0 auto', padding: 16 }}>
                {tab === 'home'        && <PageHome user={user} setTab={setTab} />}
                {tab === 'bookings'    && <PageBookings />}
                {tab === 'commissions' && <PageCommissions />}
                {tab === 'link'        && <PageLink user={user} />}
                {tab === 'profile'     && <PageProfile user={user} onLogout={onLogout} />}
            </main>

            {/* Bottom nav (mobile) */}
            <nav className="bottom-nav md:hidden">
                <NavBtn id="home"        tab={tab} setTab={setTab} icon="fa-house" label="Accueil" />
                <NavBtn id="bookings"    tab={tab} setTab={setTab} icon="fa-route" label="Courses" />
                <NavBtn id="commissions" tab={tab} setTab={setTab} icon="fa-coins" label="Gains" />
                <NavBtn id="link"        tab={tab} setTab={setTab} icon="fa-link" label="Lien" />
                <NavBtn id="profile"     tab={tab} setTab={setTab} icon="fa-user" label="Profil" />
            </nav>
        </div>
    );
}
function NavBtn({ id, tab, setTab, icon, label }) {
    return (
        <button className={tab === id ? 'active' : ''} onClick={() => setTab(id)}>
            <i className={`fas ${icon}`}></i>
            <span>{label}</span>
        </button>
    );
}
function DesktopTab({ id, tab, setTab, icon, label }) {
    return (
        <button className={tab === id ? 'active' : ''} onClick={() => setTab(id)}>
            <i className={`fas ${icon}`} style={{ marginRight: 6 }}></i>{label}
        </button>
    );
}

/* ---------- HOME ---------- */
function PageHome({ user, setTab }) {
    const [stats, setStats] = useState(null);
    const [recent, setRecent] = useState([]);
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        (async () => {
            try {
                const [s, b] = await Promise.all([
                    MyProAPI.stats(),
                    MyProAPI.bookings({ limit: 5 }),
                ]);
                setStats(s);
                setRecent(b.bookings || []);
            } catch (e) { console.error(e); }
            setLoading(false);
        })();
    }, []);

    if (loading) return <div className="empty-state"><div className="loading-spinner" style={{ margin: '0 auto' }}></div></div>;

    const k = stats?.bookings || {};
    const c = stats?.commissions || {};
    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {/* Welcome banner */}
            <div className="gradient-card">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 12 }}>
                    <div>
                        <div className="label">Commissions à recevoir</div>
                        <div className="value">{fmtMoney(c.to_pay)}</div>
                        <div style={{ fontSize: 13, opacity: .85, marginTop: 4 }}>
                            +{fmtMoney(c.pending)} en attente · {fmtMoney(c.paid)} déjà versés
                        </div>
                    </div>
                    <button className="btn" style={{ background: 'rgba(255,255,255,.2)', color: 'white', backdropFilter: 'blur(8px)' }} onClick={() => setTab('link')}>
                        <i className="fas fa-share-nodes"></i> Mon lien
                    </button>
                </div>
            </div>

            {/* KPIs */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 12 }}>
                <Kpi label="Courses envoyées" value={k.total_bookings || 0} icon="fa-paper-plane" />
                <Kpi label="Effectuées" value={k.completed || 0} icon="fa-check" />
                <Kpi label="À venir" value={k.upcoming || 0} icon="fa-calendar" />
                <Kpi label="Annulées" value={k.cancelled || 0} icon="fa-times" />
                <Kpi label="CA généré" value={fmtMoney(k.revenue_completed)} icon="fa-chart-line" />
                <Kpi label="Commissions cumulées" value={fmtMoney(c.earned)} icon="fa-coins" />
            </div>

            {/* Recent bookings */}
            <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                    <h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>Dernières courses envoyées</h2>
                    <button className="btn btn-ghost btn-sm" onClick={() => setTab('bookings')}>Voir tout <i className="fas fa-arrow-right" style={{ marginLeft: 4 }}></i></button>
                </div>
                {recent.length === 0 ? (
                    <div className="empty-state card">
                        <div className="icon"><i className="fas fa-paper-plane"></i></div>
                        <h3 style={{ margin: '0 0 6px' }}>Aucune course envoyée pour l'instant</h3>
                        <p>Partagez votre lien partenaire pour commencer à gagner des commissions.</p>
                        <button className="btn btn-primary" style={{ marginTop: 12 }} onClick={() => setTab('link')}>
                            <i className="fas fa-link"></i> Voir mon lien partenaire
                        </button>
                    </div>
                ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                        {recent.map(b => <BookingRow key={b.id} b={b} />)}
                    </div>
                )}
            </div>
        </div>
    );
}
function Kpi({ label, value, icon }) {
    return (
        <div className="kpi-card">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div className="label">{label}</div>
                <i className={`fas ${icon}`} style={{ color: '#a78bfa', fontSize: 14 }}></i>
            </div>
            <div className="value">{value}</div>
        </div>
    );
}

/* ---------- BOOKINGS ---------- */
function PageBookings() {
    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(true);
    const [filter, setFilter] = useState('all');
    const [openId, setOpenId] = useState(null);
    const load = useCallback(async () => {
        setLoading(true);
        try {
            const params = filter === 'all' ? {} : { status: filter };
            const r = await MyProAPI.bookings(params);
            setItems(r.bookings || []);
        } catch (e) { console.error(e); }
        setLoading(false);
    }, [filter]);
    useEffect(() => { load(); }, [load]);
    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>Mes courses envoyées</h2>
            <div className="tab-segmented">
                {['all','upcoming','completed','cancelled'].map(s => (
                    <button key={s} className={filter === s ? 'active' : ''} onClick={() => setFilter(s)}>
                        {s === 'all' ? 'Toutes' : s === 'upcoming' ? 'À venir' : s === 'completed' ? 'Effectuées' : 'Annulées'}
                    </button>
                ))}
            </div>
            {loading ? <div className="empty-state"><div className="loading-spinner" style={{ margin: '0 auto' }}></div></div> :
             items.length === 0 ? <div className="empty-state card"><div className="icon"><i className="fas fa-route"></i></div><p>Aucune course pour ce filtre.</p></div> : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {items.map(b => <BookingRow key={b.id} b={b} onOpen={() => setOpenId(b.id)} />)}
                </div>
             )}
            {openId && <BookingDetailModal id={openId} onClose={() => setOpenId(null)} />}
        </div>
    );
}

function BookingRow({ b, onOpen }) {
    const status = b.cancelled ? { label: 'Annulée', cls: 'pill-danger' } :
                   b.is_completed ? { label: 'Effectuée', cls: 'pill-success' } :
                   { label: b.dispatch_status === 'assigned' ? 'Assignée' : 'En recherche', cls: 'pill-info' };
    const commCls = b.commission_status === 'paid'      ? 'pill-success' :
                    b.commission_status === 'earned'    ? 'pill-info' :
                    b.commission_status === 'cancelled' ? 'pill-danger' : 'pill-warning';
    return (
        <div className={`booking-card ${b.cancelled ? 'cancelled' : ''}`} style={{ cursor: onOpen ? 'pointer' : 'default' }} onClick={onOpen}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 12, color: '#64748b', marginBottom: 4 }}>
                        <i className="fas fa-calendar" style={{ marginRight: 6 }}></i>{fmtDateTime(b.dated)}
                        {b.central_label && <span style={{ marginLeft: 10 }}><i className="fas fa-building" style={{ marginRight: 4 }}></i>{b.central_label}</span>}
                    </div>
                    <div style={{ fontWeight: 700, marginBottom: 2 }}>{b.customer_firstname} {b.customer_lastname}</div>
                    <div style={{ fontSize: 13, color: '#475569' }}>
                        <i className="fas fa-circle text-purple-500" style={{ fontSize: 6, marginRight: 6 }}></i>{b.origin_address || '—'}
                    </div>
                    <div style={{ fontSize: 13, color: '#475569' }}>
                        <i className="fas fa-circle text-amber-500" style={{ fontSize: 6, marginRight: 6 }}></i>{b.destination_address || '—'}
                    </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                    <span className={`pill ${status.cls}`}>{status.label}</span>
                    <div style={{ fontWeight: 700, fontSize: 16, marginTop: 8 }}>{fmtMoney(b.price)}</div>
                    {b.commission_amount != null && (
                        <div style={{ marginTop: 4 }}>
                            <span className={`pill ${commCls}`}>+{fmtMoney(b.commission_amount)}</span>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

function BookingDetailModal({ id, onClose }) {
    const [data, setData] = useState(null);
    useEffect(() => { (async () => { try { const r = await MyProAPI.booking(id); setData(r.booking); } catch (e) { console.error(e); } })(); }, [id]);
    if (!data) return <Modal open={true} onClose={onClose} title="Détails de la course"><div className="loading-spinner" style={{ margin: '20px auto' }}></div></Modal>;
    return (
        <Modal open={true} onClose={onClose} title={`Course ${data.reference}`} footer={<button className="btn btn-ghost" onClick={onClose}>Fermer</button>}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <DetailRow label="Date" value={fmtDateTime(data.dated)} />
                <DetailRow label="Client" value={`${data.customer_firstname || ''} ${data.customer_lastname || ''}`.trim() || '—'} />
                <DetailRow label="Téléphone" value={data.customer_mobile || '—'} />
                <DetailRow label="Email" value={data.customer_email || '—'} />
                <hr style={{ border: 0, borderTop: '1px solid #e2e8f0' }} />
                <DetailRow label="Départ" value={data.origin_address || '—'} />
                <DetailRow label="Arrivée" value={data.destination_address || '—'} />
                {data.distance_km && <DetailRow label="Distance" value={`${Number(data.distance_km).toFixed(1)} km`} />}
                {data.duration_min && <DetailRow label="Durée estimée" value={`${data.duration_min} min`} />}
                <hr style={{ border: 0, borderTop: '1px solid #e2e8f0' }} />
                <DetailRow label="Centrale" value={data.central_label || '—'} />
                {data.driver_firstname && <DetailRow label="Chauffeur" value={`${data.driver_firstname} ${data.driver_lastname || ''}`} />}
                <hr style={{ border: 0, borderTop: '1px solid #e2e8f0' }} />
                <DetailRow label="Montant course" value={fmtMoney(data.price)} />
                {data.commission_amount != null && <DetailRow label="Votre commission" value={<strong style={{ color: '#7c3aed' }}>{fmtMoney(data.commission_amount)}</strong>} />}
                {data.commission_status && <DetailRow label="Statut commission" value={<CommissionPill s={data.commission_status} />} />}
            </div>
        </Modal>
    );
}
function DetailRow({ label, value }) {
    return (
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
            <span style={{ fontSize: 13, color: '#64748b' }}>{label}</span>
            <span style={{ fontSize: 14, fontWeight: 500, textAlign: 'right' }}>{value}</span>
        </div>
    );
}
function CommissionPill({ s }) {
    const map = {
        pending:   { l: 'En attente', c: 'pill-warning' },
        earned:    { l: 'Acquise',    c: 'pill-info' },
        paid:      { l: 'Payée',      c: 'pill-success' },
        cancelled: { l: 'Annulée',    c: 'pill-danger' },
    };
    const v = map[s] || { l: s, c: 'pill-muted' };
    return <span className={`pill ${v.c}`}>{v.l}</span>;
}

/* ---------- COMMISSIONS ---------- */
function PageCommissions() {
    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(true);
    const [status, setStatus] = useState('all');
    useEffect(() => {
        (async () => {
            setLoading(true);
            try { const r = await MyProAPI.commissions({ status }); setItems(r.commissions || []); }
            catch (e) { console.error(e); }
            setLoading(false);
        })();
    }, [status]);
    const total = items.reduce((s, x) => s + (Number(x.commission_amount) || 0), 0);
    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>Mes commissions</h2>
            <div className="tab-segmented">
                {[['all','Toutes'],['pending','En attente'],['earned','Acquises'],['paid','Payées']].map(([s, l]) => (
                    <button key={s} className={status === s ? 'active' : ''} onClick={() => setStatus(s)}>{l}</button>
                ))}
            </div>
            <div className="card" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                    <div style={{ fontSize: 11, color: '#64748b', textTransform: 'uppercase', fontWeight: 600 }}>Total {status !== 'all' ? `(${status})` : ''}</div>
                    <div style={{ fontSize: 24, fontWeight: 800, color: '#7c3aed' }}>{fmtMoney(total)}</div>
                </div>
                <div style={{ fontSize: 13, color: '#64748b' }}>{items.length} ligne{items.length > 1 ? 's' : ''}</div>
            </div>
            {loading ? <div className="empty-state"><div className="loading-spinner" style={{ margin: '0 auto' }}></div></div> :
             items.length === 0 ? <div className="empty-state card"><div className="icon"><i className="fas fa-coins"></i></div><p>Aucune commission pour ce filtre.</p></div> : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {items.map(c => (
                        <div key={c.id} className="card" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
                            <div style={{ minWidth: 0, flex: 1 }}>
                                <div style={{ fontSize: 13, fontWeight: 600 }}>{c.booking_reference || `Course #${c.booking_id}`} <span style={{ color: '#64748b', fontWeight: 400 }}>· {c.central_label || '—'}</span></div>
                                <div style={{ fontSize: 12, color: '#64748b' }}>
                                    {fmtDate(c.booking_dated || c.created)}
                                    {c.origin_address && <> · {c.origin_address}</>}
                                </div>
                            </div>
                            <div style={{ textAlign: 'right' }}>
                                <div style={{ fontWeight: 700 }}>{fmtMoney(c.commission_amount)}</div>
                                <div style={{ marginTop: 4 }}><CommissionPill s={c.status} /></div>
                            </div>
                        </div>
                    ))}
                </div>
             )}
        </div>
    );
}

/* ---------- LINK PAGE ---------- */
function PageLink({ user }) {
    const [info, setInfo] = useState(null);
    const [centrals, setCentrals] = useState([]);
    const toast = useToast();
    useEffect(() => {
        (async () => {
            try { const [l, c] = await Promise.all([MyProAPI.link(), MyProAPI.centrals()]); setInfo(l); setCentrals(c.centrals || []); }
            catch (e) { console.error(e); }
        })();
    }, []);
    const copy = (s) => { navigator.clipboard.writeText(s); toast.push('Copié dans le presse-papier'); };
    if (!info) return <div className="empty-state"><div className="loading-spinner" style={{ margin: '0 auto' }}></div></div>;
    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>Mon lien partenaire</h2>

            <div className="card">
                <div style={{ fontSize: 13, color: '#64748b', marginBottom: 8, fontWeight: 600 }}>Lien à partager avec vos clients</div>
                <div className="share-box">
                    <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{info.share_url}</span>
                    <button className="btn btn-primary btn-sm" onClick={() => copy(info.share_url)}><i className="fas fa-copy"></i> Copier</button>
                </div>
                <p style={{ fontSize: 13, color: '#64748b', marginTop: 12 }}>
                    Lorsqu'un client réserve via ce lien, le système trouve automatiquement la centrale active la plus proche, et vous gagnez {' '}
                    <strong style={{ color: '#7c3aed' }}>
                        {user.commission_type === 'percent'
                            ? `${user.commission_value}% du montant de la course`
                            : `${fmtMoney(user.commission_value)} par course`}
                    </strong>.
                </p>
            </div>

            <div className="card">
                <div style={{ fontSize: 13, color: '#64748b', marginBottom: 8, fontWeight: 600 }}>QR code</div>
                <div style={{ textAlign: 'center', padding: 20, background: '#f8fafc', borderRadius: 12 }}>
                    <img alt="QR" src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&color=7c3aed&data=${encodeURIComponent(info.share_url)}`} />
                    <div style={{ fontSize: 12, color: '#64748b', marginTop: 10 }}>Imprimez et affichez ce QR à votre comptoir.</div>
                </div>
            </div>

            <div className="card">
                <div style={{ fontSize: 13, color: '#64748b', marginBottom: 8, fontWeight: 600 }}>Centrales partenaires actives</div>
                {centrals.length === 0 ? <p style={{ color: '#94a3b8', fontSize: 14 }}>Aucune centrale configurée.</p> :
                    <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
                        {centrals.filter(c => c.is_enabled !== 0).map(c => (
                            <li key={c.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid #f1f5f9' }}>
                                <span><i className="fas fa-building" style={{ color: '#7c3aed', marginRight: 8 }}></i>{c.label}</span>
                                <span style={{ fontSize: 12, color: '#64748b' }}>{c.canton || ''}</span>
                            </li>
                        ))}
                    </ul>
                }
            </div>
        </div>
    );
}

/* ---------- PROFILE ---------- */
function PageProfile({ user, onLogout }) {
    const [partner, setPartner] = useState(null);
    const [editing, setEditing] = useState(false);
    const [form, setForm] = useState({});
    const [saving, setSaving] = useState(false);
    const toast = useToast();
    const load = async () => {
        try { const r = await MyProAPI.profile(); setPartner(r.partner); setForm(r.partner || {}); }
        catch (e) { console.error(e); }
    };
    useEffect(() => { load(); }, []);
    const save = async () => {
        setSaving(true);
        try {
            await MyProAPI.updateProfile({
                label: form.label,
                description: form.description,
                contact_name: form.contact_name,
                contact_phone: form.contact_phone,
                website_url: form.website_url,
                address: form.address,
                payment_iban: form.payment_iban,
                company_type: form.company_type,
            });
            toast.push('Profil mis à jour');
            setEditing(false);
            await load();
        } catch (e) { toast.push(e.message, 'error'); }
        setSaving(false);
    };
    if (!partner) return <div className="empty-state"><div className="loading-spinner" style={{ margin: '0 auto' }}></div></div>;
    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>Profil partenaire</h2>

            <div className="card">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                    <h3 style={{ margin: 0, fontSize: 14, fontWeight: 700 }}>Informations</h3>
                    <button className="btn btn-ghost btn-sm" onClick={() => setEditing(e => !e)}>
                        <i className={`fas ${editing ? 'fa-times' : 'fa-pen'}`}></i> {editing ? 'Annuler' : 'Modifier'}
                    </button>
                </div>
                {editing ? (
                    <div>
                        <Field label="Nom de l'entreprise"><input value={form.label || ''} onChange={(e) => setForm({ ...form, label: e.target.value })} /></Field>
                        <Field label="Type">
                            <select value={form.company_type || ''} onChange={(e) => setForm({ ...form, company_type: e.target.value })}>
                                <option value="">—</option>
                                <option value="hotel">Hôtel</option>
                                <option value="concierge">Conciergerie</option>
                                <option value="restaurant">Restaurant</option>
                                <option value="event">Événementiel</option>
                                <option value="other">Autre</option>
                            </select>
                        </Field>
                        <Field label="Description"><textarea rows="3" value={form.description || ''} onChange={(e) => setForm({ ...form, description: e.target.value })} /></Field>
                        <Field label="Adresse"><input value={form.address || ''} onChange={(e) => setForm({ ...form, address: e.target.value })} /></Field>
                        <Field label="Site web"><input value={form.website_url || ''} onChange={(e) => setForm({ ...form, website_url: e.target.value })} /></Field>
                        <Field label="Personne de contact"><input value={form.contact_name || ''} onChange={(e) => setForm({ ...form, contact_name: e.target.value })} /></Field>
                        <Field label="Téléphone"><input value={form.contact_phone || ''} onChange={(e) => setForm({ ...form, contact_phone: e.target.value })} /></Field>
                        <Field label="IBAN (paiement commissions)"><input value={form.payment_iban || ''} onChange={(e) => setForm({ ...form, payment_iban: e.target.value })} /></Field>
                        <button className="btn btn-primary" onClick={save} disabled={saving}>
                            {saving ? 'Enregistrement…' : 'Enregistrer'}
                        </button>
                    </div>
                ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                        <DetailRow label="Nom" value={partner.label} />
                        <DetailRow label="Type" value={partner.company_type || '—'} />
                        <DetailRow label="Email" value={partner.contact_email} />
                        <DetailRow label="Téléphone" value={partner.contact_phone || '—'} />
                        <DetailRow label="Adresse" value={partner.address || '—'} />
                        <DetailRow label="Site web" value={partner.website_url || '—'} />
                        <DetailRow label="IBAN paiement" value={partner.payment_iban ? '••••' + String(partner.payment_iban).slice(-4) : '—'} />
                    </div>
                )}
            </div>

            <div className="card">
                <h3 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 700 }}>Conditions de commission</h3>
                <DetailRow label="Type" value={partner.commission_type === 'percent' ? 'Pourcentage' : 'Montant fixe'} />
                <DetailRow label="Valeur" value={partner.commission_type === 'percent' ? `${partner.commission_value}%` : fmtMoney(partner.commission_value)} />
                {partner.commission_min > 0 && <DetailRow label="Minimum / course" value={fmtMoney(partner.commission_min)} />}
                {partner.commission_max > 0 && <DetailRow label="Maximum / course" value={fmtMoney(partner.commission_max)} />}
                <p style={{ fontSize: 12, color: '#94a3b8', marginTop: 12 }}>
                    Pour modifier vos conditions, contactez <a href="mailto:partenaires@mypro.ch" style={{ color: '#7c3aed' }}>partenaires@mypro.ch</a>.
                </p>
            </div>

            <button className="btn btn-danger" onClick={onLogout}><i className="fas fa-sign-out-alt"></i> Déconnexion</button>
        </div>
    );
}
function Field({ label, children }) {
    return (
        <div className="field">
            <label>{label}</label>
            {children}
        </div>
    );
}

/* ---------- ROOT ---------- */
function Root() {
    const [user, setUser] = useState(MyProAuth.getUser());
    const [ready, setReady] = useState(false);
    useEffect(() => {
        (async () => {
            if (MyProAuth.isAuthenticated()) {
                const u = await MyProAuth.refreshUser();
                if (u && u.type === 'partner') setUser(u);
                else { MyProAuth.clearAuth(); setUser(null); }
            }
            setReady(true);
        })();
    }, []);
    const logout = () => MyProAuth.logout();
    if (!ready) return <div className="empty-state"><div className="loading-spinner" style={{ margin: '0 auto' }}></div></div>;
    if (!user) return <ToastProvider><LoginScreen /></ToastProvider>;
    return <ToastProvider><AppShell user={user} onLogout={logout} /></ToastProvider>;
}

ReactDOM.createRoot(document.getElementById('app')).render(<Root />);
