/**
 * TaxiBook Partner - Dashboard View
 * ==================================
 * Vue d'ensemble du portail Partenaire.
 *  - Liste des outils disponibles (Smart, Agent, IVR, Tablet, ...)
 *  - Stats des réservations par jour, par source et par agent.
 */

const SOURCE_LABELS = {
    partner_app: 'App Partenaire',
    minisite: 'Mini-site',
    site: 'Site web',
    smart: 'Smart',
    agent: 'Agent',
    tablet: 'Tablet',
    ivr: 'IVR',
    gateway: 'Gateway (API)',
    manager: 'Manager',
    app_client: 'App Client',
    app_my: 'App MY',
    partner: 'Partenaire',
    unknown: 'Autre'
};

const SOURCE_COLORS = {
    partner_app: '#8b5cf6',
    minisite: '#10b981',
    site: '#0ea5e9',
    smart: '#22c55e',
    agent: '#3b82f6',
    tablet: '#6366f1',
    ivr: '#f43f5e',
    gateway: '#0f172a',
    manager: '#f59e0b',
    app_client: '#06b6d4',
    app_my: '#14b8a6',
    partner: '#a855f7',
    unknown: '#94a3b8'
};

const TOOL_COLOR_CLASSES = {
    amber: { bg: 'bg-amber-50', text: 'text-amber-600', icon: 'bg-amber-100 text-amber-600', ring: 'ring-amber-200' },
    emerald: { bg: 'bg-emerald-50', text: 'text-emerald-600', icon: 'bg-emerald-100 text-emerald-600', ring: 'ring-emerald-200' },
    blue: { bg: 'bg-blue-50', text: 'text-blue-600', icon: 'bg-blue-100 text-blue-600', ring: 'ring-blue-200' },
    indigo: { bg: 'bg-indigo-50', text: 'text-indigo-600', icon: 'bg-indigo-100 text-indigo-600', ring: 'ring-indigo-200' },
    sky: { bg: 'bg-sky-50', text: 'text-sky-600', icon: 'bg-sky-100 text-sky-600', ring: 'ring-sky-200' },
    purple: { bg: 'bg-purple-50', text: 'text-purple-600', icon: 'bg-purple-100 text-purple-600', ring: 'ring-purple-200' },
    rose: { bg: 'bg-rose-50', text: 'text-rose-600', icon: 'bg-rose-100 text-rose-600', ring: 'ring-rose-200' },
    teal: { bg: 'bg-teal-50', text: 'text-teal-600', icon: 'bg-teal-100 text-teal-600', ring: 'ring-teal-200' },
    orange: { bg: 'bg-orange-50', text: 'text-orange-600', icon: 'bg-orange-100 text-orange-600', ring: 'ring-orange-200' },
    slate: { bg: 'bg-slate-50', text: 'text-slate-700', icon: 'bg-slate-200 text-slate-800', ring: 'ring-slate-300' }
};

const sourceLabel = (s) => SOURCE_LABELS[s] || (s || 'Autre');
const sourceColor = (s) => SOURCE_COLORS[s] || SOURCE_COLORS.unknown;
const fmtNumber = (n) => (n || 0).toLocaleString('fr-CH');
const fmtMoney = (n) => `${(parseFloat(n) || 0).toLocaleString('fr-CH', { minimumFractionDigits: 0, maximumFractionDigits: 0 })} CHF`;

// ============================================================================
// STAT CARD
// ============================================================================

const DashStatCard = ({ icon, label, value, sublabel, color = 'primary' }) => (
    <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
        <div className="flex items-start justify-between mb-3">
            <div className={`w-12 h-12 bg-${color}-100 text-${color}-600 rounded-xl flex items-center justify-center`}>
                <i className={`fas ${icon} text-xl`}></i>
            </div>
        </div>
        <p className="text-3xl font-bold text-dark-900 mb-1">{value}</p>
        <p className="text-dark-500 text-sm font-medium">{label}</p>
        {sublabel && <p className="text-dark-400 text-xs mt-1">{sublabel}</p>}
    </div>
);

// ============================================================================
// TOOL CARD
// ============================================================================

const ToolCard = ({ tool }) => {
    const c = TOOL_COLOR_CLASSES[tool.color] || TOOL_COLOR_CLASSES.amber;
    const enabled = tool.enabled !== false;
    return (
        <div className={`relative rounded-2xl border ${enabled ? 'border-dark-100 bg-white' : 'border-dark-100 bg-dark-50 opacity-70'} p-5 shadow-sm flex flex-col`}>
            <div className="flex items-start gap-4 mb-3">
                <div className={`w-12 h-12 ${c.icon} rounded-xl flex items-center justify-center flex-shrink-0`}>
                    <i className={`fas ${tool.icon} text-xl`}></i>
                </div>
                <div className="min-w-0">
                    <h3 className="text-lg font-bold text-dark-900 truncate">{tool.name}</h3>
                    <p className="text-sm text-dark-500 leading-snug">{tool.description}</p>
                </div>
            </div>
            <div className="mt-auto pt-3 flex items-center justify-between gap-2">
                <div className="flex items-center gap-2 flex-wrap">
                    {enabled ? (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-700">
                            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
                            Actif
                        </span>
                    ) : (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold bg-dark-200 text-dark-600">
                            Indisponible
                        </span>
                    )}
                    {typeof tool.accounts_count === 'number' && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-dark-100 text-dark-700">
                            <i className="fas fa-user text-[10px]"></i>
                            {tool.accounts_count} compte{tool.accounts_count > 1 ? 's' : ''}
                        </span>
                    )}
                    {typeof tool.count === 'number' && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-dark-100 text-dark-700">
                            {tool.count}
                        </span>
                    )}
                    {tool.accounts === 'main' && (
                        <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium bg-amber-50 text-amber-700">
                            <i className="fas fa-crown text-[10px]"></i>
                            Compte principal
                        </span>
                    )}
                </div>
                {enabled && tool.url && (
                    <a
                        href={tool.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm font-semibold text-primary-600 hover:text-primary-700 inline-flex items-center gap-1.5"
                    >
                        Ouvrir
                        <i className="fas fa-arrow-up-right-from-square text-xs"></i>
                    </a>
                )}
            </div>
        </div>
    );
};

// ============================================================================
// STACKED BAR CHART (par jour, par source)
// ============================================================================

const DailyChart = ({ dayList, perDay, sources }) => {
    const map = {};
    dayList.forEach(d => { map[d] = { day: d, total: 0, sources: {} }; });
    perDay.forEach(row => {
        if (!map[row.day]) map[row.day] = { day: row.day, total: 0, sources: {} };
        map[row.day].sources[row.source] = (map[row.day].sources[row.source] || 0) + (row.total || 0);
        map[row.day].total += (row.total || 0);
    });
    const days = dayList.map(d => map[d]);
    const max = Math.max(1, ...days.map(d => d.total));

    const sourceKeys = Array.from(new Set(perDay.map(r => r.source))).sort();
    if (sourceKeys.length === 0) sourceKeys.push('unknown');

    return (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
            <div className="flex items-center justify-between mb-4">
                <div>
                    <h3 className="text-lg font-bold text-dark-900">Réservations par jour</h3>
                    <p className="text-sm text-dark-500">Empilées par source</p>
                </div>
            </div>

            {/* Légende */}
            <div className="flex flex-wrap gap-3 mb-5">
                {sourceKeys.map(s => (
                    <div key={s} className="flex items-center gap-1.5 text-xs text-dark-600">
                        <span className="w-2.5 h-2.5 rounded-sm" style={{ backgroundColor: sourceColor(s) }}></span>
                        {sourceLabel(s)}
                    </div>
                ))}
            </div>

            {/* Graphique */}
            <div className="flex items-end gap-1 h-48 overflow-x-auto pb-1">
                {days.map((d, idx) => {
                    const totalH = max > 0 ? Math.max(2, (d.total / max) * 100) : 2;
                    const dt = new Date(d.day + 'T00:00:00');
                    const showLabel = idx % Math.ceil(days.length / 10) === 0 || idx === days.length - 1;
                    return (
                        <div key={d.day} className="flex-1 min-w-[12px] flex flex-col items-center group relative">
                            <div className="w-full flex flex-col-reverse" style={{ height: `${totalH}%`, minHeight: '2px' }}>
                                {sourceKeys.map((s) => {
                                    const cnt = d.sources[s] || 0;
                                    if (!cnt) return null;
                                    const pct = (cnt / d.total) * 100;
                                    return (
                                        <div
                                            key={s}
                                            style={{ height: `${pct}%`, backgroundColor: sourceColor(s) }}
                                            className="w-full first:rounded-t-md transition-all"
                                        />
                                    );
                                })}
                                {d.total === 0 && (
                                    <div className="w-full bg-dark-100 rounded-md h-full"></div>
                                )}
                            </div>
                            <span className={`text-[10px] mt-1 text-dark-500 ${showLabel ? '' : 'invisible'}`}>
                                {dt.toLocaleDateString('fr-CH', { day: '2-digit', month: '2-digit' })}
                            </span>
                            {/* Tooltip on hover */}
                            <div className="hidden group-hover:block absolute bottom-full mb-2 z-10 bg-dark-900 text-white text-xs rounded-lg px-3 py-2 whitespace-nowrap shadow-xl">
                                <div className="font-semibold mb-1">
                                    {dt.toLocaleDateString('fr-CH', { weekday: 'short', day: '2-digit', month: 'short' })}
                                </div>
                                <div className="text-dark-300">{d.total} réservation{d.total > 1 ? 's' : ''}</div>
                                {Object.entries(d.sources).map(([s, c]) => (
                                    <div key={s} className="flex items-center gap-2 mt-1">
                                        <span className="w-2 h-2 rounded-sm" style={{ backgroundColor: sourceColor(s) }}></span>
                                        <span>{sourceLabel(s)}: {c}</span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

// ============================================================================
// COURSES PAR OUTIL (SMART, TABLET, AGENT, MINI-SITE, IVR)
// ============================================================================

const TOOL_LIST = [
    { source: 'smart', label: 'Smart', icon: 'fa-mobile-screen', color: 'emerald' },
    { source: 'tablet', label: 'Tablet', icon: 'fa-tablet-screen-button', color: 'indigo' },
    { source: 'agent', label: 'Agent', icon: 'fa-headset', color: 'blue' },
    { source: 'minisite', label: 'Mini-site', icon: 'fa-globe', color: 'teal' },
    { source: 'ivr', label: 'IVR', icon: 'fa-phone-volume', color: 'rose' },
    { source: 'gateway', label: 'Gateway (API)', icon: 'fa-code', color: 'slate' }
];

const RidesByToolBreakdown = ({ bySource }) => {
    const map = {};
    (bySource || []).forEach(row => {
        map[row.source] = row;
    });

    const rows = TOOL_LIST.map(t => {
        const r = map[t.source] || {};
        return {
            ...t,
            total: r.total || 0,
            completed: r.completed || 0,
            cancelled: r.cancelled || 0
        };
    });

    const grandTotal = rows.reduce((s, r) => s + r.total, 0);
    const maxTotal = Math.max(1, ...rows.map(r => r.total));

    return (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
            <div className="flex items-center justify-between mb-5">
                <div>
                    <h3 className="text-lg font-bold text-dark-900">Courses par outil</h3>
                    <p className="text-sm text-dark-500">Nombre de courses par canal de réservation</p>
                </div>
                <div className="text-right">
                    <p className="text-xs text-dark-400 uppercase tracking-wider">Total</p>
                    <p className="text-xl font-bold text-dark-900">{fmtNumber(grandTotal)}</p>
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-5 gap-3 mb-5">
                {rows.map(r => {
                    const c = TOOL_COLOR_CLASSES[r.color] || TOOL_COLOR_CLASSES.amber;
                    return (
                        <div key={r.source} className={`rounded-xl border border-dark-100 p-4 ${r.total > 0 ? 'bg-white' : 'bg-dark-50'}`}>
                            <div className="flex items-center gap-2 mb-3">
                                <div className={`w-9 h-9 ${c.icon} rounded-lg flex items-center justify-center`}>
                                    <i className={`fas ${r.icon}`}></i>
                                </div>
                                <div className="min-w-0">
                                    <p className="text-sm font-semibold text-dark-900 truncate">{r.label}</p>
                                    <p className="text-[11px] text-dark-500">{r.completed} terminée{r.completed > 1 ? 's' : ''}</p>
                                </div>
                            </div>
                            <p className={`text-xl font-bold ${r.total > 0 ? 'text-dark-900' : 'text-dark-400'}`}>
                                {fmtNumber(r.total)} <span className="text-sm font-normal text-dark-500">course{r.total > 1 ? 's' : ''}</span>
                            </p>
                        </div>
                    );
                })}
            </div>

            <div className="space-y-2">
                {rows.map(r => {
                    const pct = maxTotal > 0 ? (r.total / maxTotal) * 100 : 0;
                    return (
                        <div key={r.source} className="flex items-center gap-3">
                            <div className="w-20 text-xs font-medium text-dark-600 flex items-center gap-1.5">
                                <i className={`fas ${r.icon} text-[10px]`} style={{ color: sourceColor(r.source) }}></i>
                                {r.label}
                            </div>
                            <div className="flex-1 h-2 bg-dark-100 rounded-full overflow-hidden">
                                <div
                                    className="h-full rounded-full transition-all"
                                    style={{ width: `${pct}%`, backgroundColor: sourceColor(r.source) }}
                                ></div>
                            </div>
                            <div className="w-24 text-right text-xs font-semibold text-dark-700">
                                {fmtNumber(r.total)}
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

// ============================================================================
// SOURCE BREAKDOWN
// ============================================================================

const SourceBreakdown = ({ bySource, total }) => {
    const sorted = [...(bySource || [])].sort((a, b) => (b.total || 0) - (a.total || 0));
    return (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
            <h3 className="text-lg font-bold text-dark-900 mb-4">Répartition par source</h3>
            {sorted.length === 0 ? (
                <p className="text-dark-400 text-sm text-center py-8">Aucune réservation sur la période</p>
            ) : (
                <div className="space-y-3">
                    {sorted.map(row => {
                        const pct = total > 0 ? Math.round((row.total / total) * 100) : 0;
                        return (
                            <div key={row.source}>
                                <div className="flex items-center justify-between mb-1">
                                    <div className="flex items-center gap-2">
                                        <span className="w-2.5 h-2.5 rounded-sm" style={{ backgroundColor: sourceColor(row.source) }}></span>
                                        <span className="text-sm font-medium text-dark-700">{sourceLabel(row.source)}</span>
                                    </div>
                                    <div className="text-sm text-dark-600">
                                        <span className="font-semibold text-dark-900">{fmtNumber(row.total)}</span>
                                        <span className="text-dark-400 ml-1">({pct}%)</span>
                                    </div>
                                </div>
                                <div className="h-2 bg-dark-100 rounded-full overflow-hidden">
                                    <div
                                        className="h-full rounded-full transition-all"
                                        style={{ width: `${pct}%`, backgroundColor: sourceColor(row.source) }}
                                    ></div>
                                </div>
                                <div className="flex justify-between text-xs text-dark-400 mt-1">
                                    <span>{row.completed || 0} terminée{(row.completed || 0) > 1 ? 's' : ''} · {row.cancelled || 0} annulée{(row.cancelled || 0) > 1 ? 's' : ''}</span>
                                    {row.source !== 'minisite' && <span>{fmtMoney(row.revenue)}</span>}
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
};

// ============================================================================
// AGENT BREAKDOWN
// ============================================================================

const AgentBreakdown = ({ byAgent, subAccounts }) => {
    const sorted = [...(byAgent || [])].sort((a, b) => (b.total || 0) - (a.total || 0));
    const subByLabel = {};
    (subAccounts || []).forEach(s => {
        if (s.label) subByLabel[s.label.toLowerCase()] = s;
        if (s.username) subByLabel[s.username.toLowerCase()] = s;
    });
    return (
        <div className="bg-white rounded-2xl p-6 shadow-sm border border-dark-100">
            <div className="flex items-center justify-between mb-4">
                <div>
                    <h3 className="text-lg font-bold text-dark-900">Réservations par agent / compte</h3>
                    <p className="text-sm text-dark-500">Basé sur le nom déclaré au moment de la réservation</p>
                </div>
            </div>
            {sorted.length === 0 ? (
                <p className="text-dark-400 text-sm text-center py-8">Aucun agent identifié sur la période</p>
            ) : (
                <div className="space-y-2">
                    {sorted.slice(0, 10).map((row, i) => {
                        const linked = subByLabel[(row.agent_name || '').toLowerCase()];
                        return (
                            <div key={i} className="flex items-center justify-between p-3 bg-dark-50 rounded-xl hover:bg-dark-100 transition">
                                <div className="flex items-center gap-3 min-w-0">
                                    <div className="w-9 h-9 rounded-full bg-primary-100 text-primary-700 flex items-center justify-center text-sm font-bold flex-shrink-0">
                                        {(row.agent_name || '?').slice(0, 1).toUpperCase()}
                                    </div>
                                    <div className="min-w-0">
                                        <p className="font-semibold text-dark-900 truncate">{row.agent_name || 'Inconnu'}</p>
                                        <p className="text-xs text-dark-500 flex items-center gap-2">
                                            {linked ? (
                                                <>
                                                    <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-semibold ${linked.access_type === 'unlimited' ? 'bg-amber-100 text-amber-700' : 'bg-blue-100 text-blue-700'}`}>
                                                        {linked.access_type === 'unlimited' ? 'Illimité' : 'Limité'}
                                                    </span>
                                                    @{linked.username}
                                                </>
                                            ) : (
                                                <span className="text-dark-400">Compte non lié</span>
                                            )}
                                        </p>
                                    </div>
                                </div>
                                <div className="text-right flex-shrink-0">
                                    <p className="font-bold text-dark-900">{fmtNumber(row.total)}</p>
                                    <p className="text-xs text-dark-500">{row.completed || 0} terminée{(row.completed || 0) > 1 ? 's' : ''}</p>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
};

// ============================================================================
// UPCOMING RIDES
// Liste compacte des courses à venir (statut actif, pickup futur).
// Affiché en haut du dashboard pour visibilité immédiate.
// ============================================================================

const UPCOMING_STATUS_LABELS = {
    pending: 'En attente',
    confirmed: 'Confirmée',
    driver_assigned: 'Chauffeur assigné',
    in_progress: 'En cours',
    booked: 'Confirmée',
    creating: 'En attente',
    searching: 'Recherche'
};

const UPCOMING_STATUS_COLORS = {
    pending: 'bg-amber-100 text-amber-700 border-amber-200',
    creating: 'bg-amber-100 text-amber-700 border-amber-200',
    searching: 'bg-amber-100 text-amber-700 border-amber-200',
    confirmed: 'bg-blue-100 text-blue-700 border-blue-200',
    booked: 'bg-blue-100 text-blue-700 border-blue-200',
    driver_assigned: 'bg-indigo-100 text-indigo-700 border-indigo-200',
    in_progress: 'bg-emerald-100 text-emerald-700 border-emerald-200'
};

const formatUpcomingRelative = (date) => {
    const now = new Date();
    const diffMs = date - now;
    if (diffMs <= 0) return 'maintenant';
    const mins = Math.floor(diffMs / 60000);
    if (mins < 60) return `dans ${mins} min`;
    const hours = Math.floor(mins / 60);
    if (hours < 24) {
        const remainingMins = mins % 60;
        return remainingMins > 0 ? `dans ${hours}h${String(remainingMins).padStart(2, '0')}` : `dans ${hours}h`;
    }
    const days = Math.floor(hours / 24);
    if (days < 7) return `dans ${days}j`;
    return date.toLocaleDateString('fr-CH', { day: '2-digit', month: '2-digit' });
};

const UpcomingRides = ({ bookings = [], onCancelBooking, onNavigate }) => {
    const [showAll, setShowAll] = useState(false);
    const visible = showAll ? bookings : bookings.slice(0, 5);

    return (
        <div className="bg-white rounded-2xl border border-dark-100 shadow-sm overflow-hidden">
            <div className="px-6 py-4 border-b border-dark-100 flex items-center justify-between gap-4">
                <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-xl bg-primary-100 text-primary-600 flex items-center justify-center">
                        <i className="fas fa-clock"></i>
                    </div>
                    <div>
                        <h2 className="text-lg font-bold text-dark-900">Courses à venir</h2>
                        <p className="text-xs text-dark-500">
                            {bookings.length === 0
                                ? 'Aucune course planifiée'
                                : `${bookings.length} course${bookings.length > 1 ? 's' : ''} planifiée${bookings.length > 1 ? 's' : ''}`}
                        </p>
                    </div>
                </div>
                {onNavigate && bookings.length > 0 && (
                    <button
                        onClick={() => onNavigate('rides')}
                        className="text-sm font-semibold text-primary-600 hover:text-primary-700 flex items-center gap-1"
                    >
                        Voir tout
                        <i className="fas fa-arrow-right text-xs"></i>
                    </button>
                )}
            </div>

            {bookings.length === 0 ? (
                <div className="p-8 text-center text-dark-400">
                    <i className="fas fa-calendar-check text-3xl mb-3"></i>
                    <p className="text-sm">Aucune course n'est prévue pour le moment.</p>
                </div>
            ) : (
                <div className="divide-y divide-dark-100">
                    {visible.map(booking => {
                        const dt = new Date(booking.pickup_datetime);
                        const statusLabel = UPCOMING_STATUS_LABELS[booking.status] || booking.status;
                        const statusColor = UPCOMING_STATUS_COLORS[booking.status] || 'bg-dark-100 text-dark-600 border-dark-200';
                        return (
                            <div key={booking.id || booking.uid} className="px-6 py-4 hover:bg-dark-50 transition">
                                <div className="flex items-start justify-between gap-4">
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 flex-wrap mb-2">
                                            <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold border ${statusColor}`}>
                                                {statusLabel}
                                            </span>
                                            <span className="text-sm font-semibold text-primary-600">
                                                <i className="fas fa-clock mr-1 text-xs"></i>
                                                {formatUpcomingRelative(dt)}
                                            </span>
                                            <span className="text-xs text-dark-400">
                                                {dt.toLocaleString('fr-CH', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
                                            </span>
                                            <span className="text-xs text-dark-400">#{booking.confirmation_code || (booking.uid || '').slice(-8)}</span>
                                        </div>

                                        <div className="flex items-start gap-3 mb-2">
                                            <div className="flex flex-col items-center pt-1">
                                                <div className="w-2.5 h-2.5 rounded-full bg-emerald-500"></div>
                                                <div className="w-0.5 h-5 bg-dark-200"></div>
                                                <div className="w-2.5 h-2.5 rounded-full bg-primary-500"></div>
                                            </div>
                                            <div className="flex-1 min-w-0 text-sm">
                                                <p className="font-medium text-dark-800 truncate">
                                                    {booking.pickup_address || booking.package_name || 'Départ'}
                                                </p>
                                                <p className="text-dark-500 truncate mt-1">
                                                    {booking.destination_address || 'Destination selon forfait'}
                                                </p>
                                            </div>
                                        </div>

                                        {(booking.guest_name || booking.guest_phone || booking.driver_name) && (
                                            <div className="flex items-center gap-x-4 gap-y-1 text-xs text-dark-500 flex-wrap">
                                                {booking.guest_name && <span className="text-dark-700 font-medium"><i className="fas fa-user mr-1 text-primary-500"></i>{booking.guest_name}</span>}
                                                {booking.guest_phone && (
                                                    <a href={`tel:${booking.guest_phone}`} onClick={e => e.stopPropagation()} className="hover:text-primary-600">
                                                        <i className="fas fa-phone mr-1"></i>{booking.guest_phone}
                                                    </a>
                                                )}
                                                {booking.driver_name && <span className="text-emerald-600"><i className="fas fa-id-badge mr-1"></i>{booking.driver_name}</span>}
                                            </div>
                                        )}
                                    </div>

                                    <div className="text-right flex flex-col items-end shrink-0">
                                        {booking.source !== 'minisite' && (
                                            <p className="text-lg font-bold text-dark-900">{booking.price || 0} CHF</p>
                                        )}
                                        <p className="text-xs text-dark-400 capitalize">{booking.vehicle_type || 'Standard'}</p>
                                        {['pending', 'confirmed', 'creating', 'searching', 'booked'].includes(booking.status) && onCancelBooking && (
                                            <button
                                                onClick={(e) => { e.stopPropagation(); onCancelBooking(booking.uid); }}
                                                className="mt-2 px-2.5 py-1 text-xs bg-red-50 text-red-600 rounded-md hover:bg-red-100 transition"
                                            >
                                                <i className="fas fa-times mr-1"></i>Annuler
                                            </button>
                                        )}
                                    </div>
                                </div>
                            </div>
                        );
                    })}

                    {bookings.length > 5 && !showAll && (
                        <button
                            onClick={() => setShowAll(true)}
                            className="w-full py-3 text-sm font-semibold text-primary-600 hover:bg-dark-50 transition border-t border-dark-100"
                        >
                            Afficher {bookings.length - 5} course{bookings.length - 5 > 1 ? 's' : ''} supplémentaire{bookings.length - 5 > 1 ? 's' : ''}
                            <i className="fas fa-chevron-down ml-2 text-xs"></i>
                        </button>
                    )}
                </div>
            )}
        </div>
    );
};

// ============================================================================
// DASHBOARD VIEW
// ============================================================================

const DashboardView = ({ partner, setToast, bookings = [], onCancelBooking, onNavigate }) => {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [days, setDays] = useState(30);

    const load = async (d = days) => {
        setLoading(true);
        try {
            const res = await window.partnerAPI.getDashboard(d);
            if (res.success) {
                setData(res.data);
            } else {
                setToast && setToast({ message: res.error || 'Erreur de chargement', type: 'error' });
            }
        } catch (e) {
            setToast && setToast({ message: 'Erreur de connexion', type: 'error' });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { load(days); }, [days]);

    if (loading && !data) {
        return (
            <div className="flex items-center justify-center py-20">
                <Spinner size="lg" />
            </div>
        );
    }

    if (!data) return null;

    const { tools = [], stats = {}, totals = {}, period = {}, sub_accounts = [] } = data;
    const dayList = period.day_list || [];
    const enabledToolsCount = tools.filter(t => t.enabled !== false).length;

    // Courses à venir : statuts non terminaux, date de pickup >= maintenant.
    // Tri du plus proche au plus lointain.
    const now = new Date();
    const upcomingBookings = (bookings || [])
        .filter(b => {
            if (!b.pickup_datetime) return false;
            if (['cancelled', 'completed', 'no_show'].includes(b.status)) return false;
            const dt = new Date(b.pickup_datetime);
            return !isNaN(dt) && dt >= now;
        })
        .sort((a, b) => new Date(a.pickup_datetime) - new Date(b.pickup_datetime));

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between gap-4 flex-wrap">
                <div>
                    <h1 className="text-3xl font-bold text-dark-900">Tableau de bord</h1>
                    <p className="text-dark-500 mt-1">Vue d'ensemble de l'activité de {partner?.name || 'votre établissement'}</p>
                </div>
                <div className="flex items-center gap-2 bg-white rounded-xl p-1 border border-dark-100">
                    {[7, 30, 90].map(d => (
                        <button
                            key={d}
                            onClick={() => setDays(d)}
                            className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${
                                days === d ? 'bg-primary-500 text-white' : 'text-dark-600 hover:bg-dark-100'
                            }`}
                        >
                            {d} jours
                        </button>
                    ))}
                </div>
            </div>

            {/* Stat cards */}
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <DashStatCard icon="fa-list-check" label="Réservations" value={fmtNumber(totals.total)} sublabel={`Sur ${days} jours`} color="primary" />
                <DashStatCard icon="fa-circle-check" label="Terminées" value={fmtNumber(totals.completed)} color="emerald" />
                <DashStatCard icon="fa-circle-xmark" label="Annulées" value={fmtNumber(totals.cancelled)} color="rose" />
            </div>

            {/* Courses à venir */}
            <UpcomingRides bookings={upcomingBookings} onCancelBooking={onCancelBooking} onNavigate={onNavigate} />

            {/* Courses par outil */}
            <RidesByToolBreakdown bySource={stats.by_source || []} />

            {/* Chart + repartition */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <div className="lg:col-span-2">
                    <DailyChart dayList={dayList} perDay={stats.per_day || []} sources={stats.by_source || []} />
                </div>
                <div>
                    <SourceBreakdown bySource={stats.by_source || []} total={totals.total || 0} />
                </div>
            </div>

            {/* Agent breakdown */}
            <AgentBreakdown byAgent={stats.by_agent || []} subAccounts={sub_accounts} />

            {/* Tools */}
            <div>
                <div className="flex items-center justify-between mb-4">
                    <div>
                        <h2 className="text-2xl font-bold text-dark-900">Outils Partenaire</h2>
                        <p className="text-dark-500 text-sm mt-1">{enabledToolsCount} outil{enabledToolsCount > 1 ? 's' : ''} disponible{enabledToolsCount > 1 ? 's' : ''}</p>
                    </div>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                    {tools.map(t => <ToolCard key={t.id} tool={t} />)}
                </div>
            </div>
        </div>
    );
};
