// InstantDevis — Vue Web (tableau de bord bureau)
// Affichage côté "Web" avec tableau complet des devis

// Mêmes TTC / acompte que `AfDashboard` (documentOutput, puis repli montants, acompte arrondi affichage)
function _afWebQuoteDisplay(q) {
  const o = (typeof AF_DEVIS !== 'undefined' && AF_DEVIS.documentOutput)
    ? AF_DEVIS.documentOutput(q)
    : null;
  const ttcR = o ? o.totalTTC : (q.totalTTC != null ? q.totalTTC : q.amount);
  const _webAcomptePct = typeof AF_PROFILE_STORE !== 'undefined' ? (AF_PROFILE_STORE.get().acomptePercent ?? 30) : 30;
  const acR = o
    ? o.acompte
    : (q.acompte != null
        ? q.acompte
        : Math.round((Number(ttcR) || 0) * (_webAcomptePct / 100) * 100) / 100);
  return { totalTTC: Number(ttcR) || 0, acompte: Math.round(acR) };
}

// Même tri et limite que `AfDashboard` (devis `source: voice` en tête, puis date, 4 entrées)
function _afWebRecentQuotes(allQuotes) {
  if (!allQuotes || !allQuotes.length) return [];
  return allQuotes
    .slice()
    .sort((a, b) => {
      const aIsNew = a.source === 'voice' ? 1 : 0;
      const bIsNew = b.source === 'voice' ? 1 : 0;
      if (aIsNew !== bIsNew) return bIsNew - aIsNew;
      return new Date(b.createdAt) - new Date(a.createdAt);
    })
    .slice(0, 4);
}

function AfWebView({ t, currency, userName, dark, offline, networkOnline = true }) {
  const [activeTab, setActiveTab] = React.useState('dashboard');
  const [filterStatus, setFilterStatus] = React.useState('all');
  const [searchQ, setSearchQ] = React.useState('');
  const [storeQuotes, setStoreQuotes] = React.useState(() => AF_STORE.getAll());
  const [cloudMsg, setCloudMsg] = React.useState(() => (AF_STORE.getLastFirestoreError && AF_STORE.getLastFirestoreError()) || '');

  React.useEffect(() => {
    const tick = () => {
      if (AF_STORE.getLastFirestoreError) {
        setCloudMsg(AF_STORE.getLastFirestoreError() || '');
      }
    };
    const u = AF_STORE.subscribe(() => {
      setStoreQuotes(AF_STORE.getAll());
      tick();
    });
    const unsubFirestore = AF_STORE.initFirestoreSync();
    const t0 = setTimeout(tick, 900);
    return () => {
      clearTimeout(t0);
      u();
      if (unsubFirestore) unsubFirestore();
    };
  }, []);

  const stats = AF_STORE.computeStats(storeQuotes);
  const monthPct = stats.monthTarget > 0
    ? Math.min(100, Math.round((stats.monthRevenue / stats.monthTarget) * 100))
    : 0;
  const recentDevis = _afWebRecentQuotes(storeQuotes);
  const webClientList = (typeof afGetClientsListForUI === 'function')
    ? afGetClientsListForUI(storeQuotes)
    : (typeof AF_CLIENTS !== 'undefined' ? AF_CLIENTS : []);
  const nEnvoye = storeQuotes.filter((q) => {
    const st = String(q.status || '').toLowerCase();
    return st === 'sent' || st === 'envoye';
  }).length;
  const nSigne = storeQuotes.filter((q) => q.status === 'signe').length;
  const denomTaux = nEnvoye + nSigne;
  const tauxTransfoPct = denomTaux > 0 ? Math.round((100 * nSigne) / denomTaux) : null;

  const filteredQ = storeQuotes.filter(q => {
    const st = String(q.status || '').toLowerCase();
    const matchStatus = filterStatus === 'all'
      || st === filterStatus
      || (filterStatus === 'envoye' && st === 'sent')
      || (filterStatus === 'sent' && st === 'envoye');
    const matchSearch = q.title.toLowerCase().includes(searchQ.toLowerCase()) ||
                        q.clientName.toLowerCase().includes(searchQ.toLowerCase()) ||
                        q.id.toLowerCase().includes(searchQ.toLowerCase());
    return matchStatus && matchSearch;
  });

  const navItems = [
    { id: 'dashboard', label: 'Accueil', Icon: lucide.LayoutDashboard },
    { id: 'devis', label: 'Devis', Icon: lucide.FileText },
    { id: 'clients', label: 'Clients', Icon: lucide.Users },
    { id: 'catalogue', label: 'Catalogue', Icon: lucide.Package },
    { id: 'stats', label: 'Statistiques', Icon: lucide.BarChart3 },
  ];

  return (
    <div style={{
      display: 'flex', height: '100%',
      background: t.bg, color: t.text,
      fontFamily: 'Inter Tight, system-ui, sans-serif',
    }}>
      {/* Sidebar */}
      <div style={{
        width: 220, height: '100%',
        background: t.primary,
        display: 'flex', flexDirection: 'column',
        flexShrink: 0,
      }}>
        {/* Logo sidebar */}
        <div style={{
          padding: '20px 16px 16px',
          borderBottom: '1px solid rgba(255,255,255,0.1)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
              width: 34, height: 34, borderRadius: 8,
              background: t.safety,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <lucide.Zap size={18} color="#0D1520" strokeWidth={2.5} />
            </div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 800, color: '#fff', letterSpacing: -0.4 }}>
                InstantDevis
              </div>
              <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.55)', fontWeight: 600 }}>
                {userName}
              </div>
            </div>
          </div>
        </div>

        {/* Nav items */}
        <nav style={{ padding: '10px 8px', flex: 1 }}>
          {navItems.map(({ id, label, Icon }) => (
            <button
              key={id}
              onClick={() => setActiveTab(id)}
              style={{
                width: '100%', padding: '10px 12px', borderRadius: 8,
                display: 'flex', alignItems: 'center', gap: 10,
                background: activeTab === id ? 'rgba(255,255,255,0.15)' : 'transparent',
                color: activeTab === id ? '#fff' : 'rgba(255,255,255,0.6)',
                fontSize: 13, fontWeight: activeTab === id ? 700 : 500,
                cursor: 'pointer', marginBottom: 2,
                border: 'none', textAlign: 'left',
                transition: 'background 0.15s, color 0.15s',
                borderLeft: activeTab === id ? `3px solid ${t.safety}` : '3px solid transparent',
              }}
            >
              <Icon size={17} strokeWidth={activeTab === id ? 2.5 : 2} />
              {label}
            </button>
          ))}
        </nav>

        {(!networkOnline || offline) && (
          <div style={{
            margin: '0 8px 12px',
            padding: '8px 10px', borderRadius: 8,
            background: !networkOnline ? 'rgba(13,21,32,0.45)' : 'rgba(255,107,0,0.2)',
            border: !networkOnline ? '1px solid rgba(128,128,128,0.4)' : '1px solid rgba(255,107,0,0.4)',
            display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 2,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <lucide.WifiOff size={13} color={!networkOnline ? t.textMuted : t.safety} />
              <span style={{ fontSize: 11, color: !networkOnline ? t.text : t.safety, fontWeight: 700 }}>
                {!networkOnline ? 'Réseau indisponible' : 'Mode hors-ligne (aperçu)'}
              </span>
            </div>
            {!networkOnline && (
              <span style={{ fontSize: 9, color: 'rgba(255,255,255,0.55)', fontWeight: 600, lineHeight: 1.3 }}>
                Devis, PDF, signature : en local. Firestore, auth, Workers, envoi mail : besoin d’Internet. Import catalogue XLSX : uniquement si la lib SheetJS est déjà en cache.
              </span>
            )}
          </div>
        )}
      </div>

      {/* Contenu principal */}
      <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
        {/* Topbar */}
        <div style={{
          height: 56, padding: '0 24px',
          background: t.bgElevated,
          borderBottom: `1px solid ${t.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexShrink: 0,
        }}>
          <div style={{ fontSize: 16, fontWeight: 800, color: t.text }}>
            {navItems.find(n => n.id === activeTab)?.label}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <button style={{
              padding: '7px 14px', borderRadius: 6,
              background: t.safety, border: 'none', cursor: 'pointer',
              fontSize: 12, fontWeight: 700, color: '#0D1520',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <lucide.Plus size={14} />
              Nouveau devis
            </button>
          </div>
        </div>

        {cloudMsg && (
          <div style={{
            margin: '0 24px 0', padding: '10px 12px',
            borderRadius: 10,
            background: 'rgba(234, 179, 8, 0.12)',
            border: '1px solid rgba(180, 83, 9, 0.35)',
            fontSize: 12, fontWeight: 600, color: '#92400E', lineHeight: 1.45,
            flexShrink: 0,
          }}>
            {cloudMsg}
          </div>
        )}

        {/* DASHBOARD TAB */}
        {activeTab === 'dashboard' && (
          <div style={{ padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            {/* Objectif du mois — même lecture que le dashboard mobile */}
            <div style={{
              background: t.primary, borderRadius: 10, padding: '14px 18px',
              color: '#fff',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                <span style={{ fontSize: 12, fontWeight: 600, opacity: 0.9 }}>Objectif du mois</span>
                <span style={{ fontSize: 12, fontWeight: 800, color: t.safety }}>{monthPct}%</span>
              </div>
              <div style={{ height: 6, borderRadius: 3, background: 'rgba(255,255,255,0.2)', overflow: 'hidden' }}>
                <div style={{
                  height: '100%', borderRadius: 3, width: `${monthPct}%`,
                  background: t.safety, transition: 'width 0.6s cubic-bezier(0.2,0.8,0.2,1)',
                }} />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
                <span className="af-mono" style={{ fontSize: 13, fontWeight: 700, color: t.safety }}>
                  {stats.monthRevenue.toLocaleString('fr-FR')} €
                </span>
                <span className="af-mono" style={{ fontSize: 12, opacity: 0.75 }}>
                  / {stats.monthTarget.toLocaleString('fr-FR')} €
                </span>
              </div>
            </div>

            {/* KPI row */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
              {[
                { label: 'CA Encaissé', value: `${stats.monthRevenue.toLocaleString('fr-FR')} €`, sub: 'ce mois', color: '#10B981', icon: lucide.TrendingUp },
                { label: 'En attente', value: `${stats.pendingAmount.toLocaleString('fr-FR')} €`, sub: 'devis envoyés', color: '#3B82F6', icon: lucide.Clock },
                { label: 'En retard', value: `${stats.overdueAmount.toLocaleString('fr-FR')} €`, sub: `${stats.overdueCount} devis`, color: '#FF6B00', icon: lucide.AlertTriangle },
                { label: 'Devis signés (mois)', value: stats.signedThisMonth, sub: `Date sign. ou créa. · ${stats.notesThisWeek} notes/sem`, color: t.primary, icon: lucide.CheckCircle2 },
              ].map((kpi, i) => (
                <div key={i} style={{
                  background: t.bgElevated, borderRadius: 10,
                  border: `1px solid ${t.border}`, padding: '16px',
                  boxShadow: t.shadowSm,
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>
                        {kpi.label}
                      </div>
                      <div className="af-mono" style={{ fontSize: 24, fontWeight: 800, color: kpi.color, letterSpacing: -0.5 }}>
                        {kpi.value}
                      </div>
                      <div style={{ fontSize: 11, color: t.textMuted, marginTop: 3 }}>{kpi.sub}</div>
                    </div>
                    <div style={{
                      width: 36, height: 36, borderRadius: 8,
                      background: kpi.color + '18',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <kpi.icon size={18} color={kpi.color} />
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {/* Tableau devis récents */}
            <div style={{
              background: t.bgElevated, borderRadius: 10,
              border: `1px solid ${t.border}`, overflow: 'hidden',
            }}>
              <div style={{
                padding: '14px 20px',
                borderBottom: `1px solid ${t.border}`,
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              }}>
                <span style={{ fontSize: 14, fontWeight: 800, color: t.text }}>Devis récents</span>
                <button
                  onClick={() => setActiveTab('devis')}
                  style={{
                    fontSize: 12, fontWeight: 700, color: t.primary,
                    background: 'none', border: 'none', cursor: 'pointer',
                  }}
                >
                  Voir tous →
                </button>
              </div>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                <thead>
                  <tr style={{ background: t.bgSunken }}>
                    {['Réf.', 'Client', 'Prestation', 'Montant TTC', 'Acompte', 'Statut', 'Échéance'].map(h => (
                      <th key={h} style={{
                        padding: '8px 16px', textAlign: 'left',
                        fontWeight: 700, color: t.textMuted,
                        fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.6,
                        borderBottom: `1px solid ${t.border}`,
                      }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {recentDevis.length === 0 && (
                    <tr>
                      <td colSpan={7} style={{ padding: 28, textAlign: 'center', color: t.textMuted, fontSize: 13, fontWeight: 600, lineHeight: 1.5 }}>
                        Aucun devis pour le moment. Utilisez Instant Note (mobile) pour créer un devis.
                      </td>
                    </tr>
                  )}
                  {recentDevis.map((q, i) => {
                    const o = _afWebQuoteDisplay(q);
                    const qttc = o.totalTTC;
                    const acompte = o.acompte;
                    return (
                      <tr key={q.id} style={{
                        borderBottom: `1px solid ${t.border}`,
                        background: i % 2 === 0 ? 'transparent' : t.bg + '40',
                        transition: 'background 0.1s',
                        cursor: 'pointer',
                      }}
                        onMouseEnter={e => e.currentTarget.style.background = t.primaryTint}
                        onMouseLeave={e => e.currentTarget.style.background = i % 2 === 0 ? 'transparent' : t.bg + '40'}
                      >
                        <td style={{ padding: '10px 16px' }}>
                          <span className="af-mono" style={{ fontSize: 11, fontWeight: 700, color: t.primary }}>{q.id}</span>
                        </td>
                        <td style={{ padding: '10px 16px', fontWeight: 600, color: t.text }}>{q.clientName}</td>
                        <td style={{ padding: '10px 16px', color: t.textMuted, maxWidth: 160 }}>
                          <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                            {q.title}
                          </div>
                        </td>
                        <td style={{ padding: '10px 16px' }}>
                          <span className="af-mono" style={{ fontWeight: 800, color: t.text }}>{qttc.toLocaleString('fr-FR')} €</span>
                        </td>
                        <td style={{ padding: '10px 16px' }}>
                          <span className="af-mono" style={{ fontWeight: 700, color: t.safety }}>{acompte.toLocaleString('fr-FR')} €</span>
                        </td>
                        <td style={{ padding: '10px 16px' }}>
                          <AfBadge status={q.status} t={t} />
                        </td>
                        <td style={{ padding: '10px 16px', color: t.textMuted }}>
                          {q.dueDate || '—'}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* DEVIS TAB */}
        {activeTab === 'devis' && (
          <div style={{ padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
            {/* Barre de filtres */}
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <div style={{ position: 'relative', flex: 1, maxWidth: 280 }}>
                <lucide.Search size={14} color={t.textMuted}
                  style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)' }} />
                <input
                  value={searchQ}
                  onChange={e => setSearchQ(e.target.value)}
                  placeholder="Rechercher…"
                  style={{
                    width: '100%', padding: '8px 10px 8px 32px', borderRadius: 6,
                    background: t.bgElevated, border: `1px solid ${t.border}`,
                    fontSize: 13, color: t.text, outline: 'none',
                  }}
                />
              </div>
              <div style={{ display: 'flex', gap: 4 }}>
                {['all', 'envoye', 'signe', 'retard', 'paye', 'brouillon'].map(s => (
                  <button key={s} onClick={() => setFilterStatus(s)} style={{
                    padding: '6px 10px', borderRadius: 5,
                    background: filterStatus === s ? t.primary : t.bgElevated,
                    color: filterStatus === s ? '#fff' : t.textMuted,
                    border: `1px solid ${filterStatus === s ? t.primary : t.border}`,
                    fontSize: 11, fontWeight: 700, cursor: 'pointer',
                  }}>
                    {s === 'all' ? 'Tous' : AF_STATUS[s]?.label}
                  </button>
                ))}
              </div>
            </div>
            {/* Tableau filtré */}
            <div style={{ background: t.bgElevated, borderRadius: 10, border: `1px solid ${t.border}`, overflow: 'hidden' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                <thead>
                  <tr style={{ background: t.bgSunken }}>
                    {['Réf.', 'Client', 'Prestation', 'Montant TTC', 'Acompte', 'Statut', 'Métier'].map(h => (
                      <th key={h} style={{
                        padding: '9px 14px', textAlign: 'left',
                        fontWeight: 700, color: t.textMuted,
                        fontSize: 10, textTransform: 'uppercase', letterSpacing: 0.6,
                        borderBottom: `1px solid ${t.border}`,
                      }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {filteredQ.map((q, i) => {
                    const trade = AF_TRADE_META[q.trade] || AF_TRADE_META.multi;
                    const o = _afWebQuoteDisplay(q);
                    const qttc = o.totalTTC;
                    const acompte = o.acompte;
                    return (
                      <tr key={q.id} style={{
                        borderBottom: `1px solid ${t.border}`,
                        cursor: 'pointer', transition: 'background 0.1s',
                      }}
                        onMouseEnter={e => e.currentTarget.style.background = t.primaryTint}
                        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                      >
                        <td style={{ padding: '10px 14px' }}>
                          <span className="af-mono" style={{ fontSize: 11, fontWeight: 700, color: t.primary }}>{q.id}</span>
                        </td>
                        <td style={{ padding: '10px 14px', fontWeight: 600, color: t.text }}>{q.clientName}</td>
                        <td style={{ padding: '10px 14px', color: t.textMuted, maxWidth: 180 }}>
                          <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{q.title}</div>
                        </td>
                        <td style={{ padding: '10px 14px' }}>
                          <span className="af-mono" style={{ fontWeight: 800, color: t.text }}>{qttc.toLocaleString('fr-FR')} €</span>
                        </td>
                        <td style={{ padding: '10px 14px' }}>
                          <span className="af-mono" style={{ fontWeight: 700, color: t.safety }}>{acompte.toLocaleString('fr-FR')} €</span>
                        </td>
                        <td style={{ padding: '10px 14px' }}><AfBadge status={q.status} t={t} /></td>
                        <td style={{ padding: '10px 14px' }}>
                          <span style={{
                            fontSize: 10, padding: '2px 6px', borderRadius: 4,
                            background: trade.color + '22', color: trade.color, fontWeight: 700,
                          }}>{trade.label}</span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              {filteredQ.length === 0 && (
                <div style={{ padding: 32, textAlign: 'center', color: t.textMuted, fontSize: 13 }}>
                  Aucun devis correspondant
                </div>
              )}
            </div>
          </div>
        )}

        {/* CLIENTS TAB */}
        {activeTab === 'clients' && (
          <div style={{ padding: '16px 24px' }}>
            {webClientList.length === 0 && (
              <div style={{
                background: t.bgElevated,
                borderRadius: 10,
                border: `1px dashed ${t.border}`,
                padding: 32,
                textAlign: 'center',
                color: t.textMuted,
                fontSize: 14,
                fontWeight: 600,
                lineHeight: 1.5,
              }}>
                Aucun client enregistré. Créez un devis (Instant Note) pour voir des clients ici.
              </div>
            )}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
              {webClientList.map(c => {
                const trade = AF_TRADE_META[c.trade] || AF_TRADE_META.multi;
                const clientQ = storeQuotes.filter(q => (q.client || q.clientId) === c.id);
                const totalCA = clientQ.reduce((s, q) => s + _afWebQuoteDisplay(q).totalTTC, 0);
                return (
                  <div key={c.id} style={{
                    background: t.bgElevated, borderRadius: 10,
                    border: `1px solid ${t.border}`, padding: '16px',
                    boxShadow: t.shadowSm, cursor: 'pointer',
                    transition: 'transform 0.1s',
                  }}
                    onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
                    onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
                  >
                    <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 10 }}>
                      <div style={{
                        width: 40, height: 40, borderRadius: 10,
                        background: trade.color + '20', border: `1px solid ${trade.color}44`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                      }}>
                        <lucide.User size={18} color={trade.color} />
                      </div>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 800, color: t.text }}>{c.name}</div>
                        <span style={{
                          fontSize: 10, padding: '1px 5px', borderRadius: 3,
                          background: trade.color + '22', color: trade.color, fontWeight: 700,
                        }}>{trade.label}</span>
                      </div>
                    </div>
                    <div style={{ fontSize: 11, color: t.textMuted, marginBottom: 6 }}>{c.address}</div>
                    <div style={{ fontSize: 11, color: t.textMuted, marginBottom: 10 }}>{c.phone}</div>
                    <div style={{
                      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                      paddingTop: 10, borderTop: `1px solid ${t.border}`,
                    }}>
                      <span style={{ fontSize: 11, color: t.textMuted }}>{c.projects} devis</span>
                      <span className="af-mono" style={{ fontSize: 14, fontWeight: 800, color: t.text }}>
                        {totalCA.toLocaleString('fr-FR')} €
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* CATALOGUE TAB */}
        {activeTab === 'catalogue' && (
          <div style={{ padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 12 }}>
            {['plomberie', 'electricite', 'peinture', 'multi'].map(trade => {
              const catalogItems = (typeof AF_CATALOG_STORE !== 'undefined' ? AF_CATALOG_STORE.getAll() : AF_CATALOG_DEFAULTS || [])
                .filter(i => i.trade === trade);
              if (catalogItems.length === 0) return null;
              const meta = AF_TRADE_META[trade] || AF_TRADE_META.multi;
              return (
                <div key={trade}>
                  <div style={{ fontSize: 12, fontWeight: 800, color: meta.color, textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8 }}>
                    {meta.label}
                  </div>
                  <div style={{ background: t.bgElevated, borderRadius: 10, border: `1px solid ${t.border}`, overflow: 'hidden' }}>
                    {catalogItems.map((item, i) => (
                      <div key={item.id} style={{
                        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                        padding: '10px 16px',
                        borderBottom: i < catalogItems.length - 1 ? `1px solid ${t.border}` : 'none',
                      }}>
                        <div>
                          <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{item.label}</div>
                          <div style={{ fontSize: 11, color: t.textMuted }}>Unité: {item.unit}</div>
                        </div>
                        <div className="af-mono" style={{ fontSize: 15, fontWeight: 800, color: t.text }}>
                          {(item.pu ?? item.price ?? 0).toLocaleString('fr-FR')} €
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* STATS TAB */}
        {activeTab === 'stats' && (
          <div style={{ padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {/* Répartition métiers */}
              <div style={{ background: t.bgElevated, borderRadius: 10, border: `1px solid ${t.border}`, padding: '16px' }}>
                <div style={{ fontSize: 13, fontWeight: 800, color: t.text, marginBottom: 14 }}>CA par métier</div>
                {Object.entries(AF_TRADE_META).filter(([k]) => k !== 'multi').map(([key, meta]) => {
                  const total = storeQuotes.filter(q => q.trade === key).reduce((s, q) => s + _afWebQuoteDisplay(q).totalTTC, 0);
                  const allTotal = storeQuotes.reduce((s, q) => s + _afWebQuoteDisplay(q).totalTTC, 0) || 1;
                  const pct = Math.round((total / allTotal) * 100);
                  return (
                    <div key={key} style={{ marginBottom: 10 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                        <span style={{ fontSize: 12, fontWeight: 600, color: meta.color }}>{meta.label}</span>
                        <span className="af-mono" style={{ fontSize: 12, fontWeight: 700, color: t.text }}>{total.toLocaleString('fr-FR')} € ({pct}%)</span>
                      </div>
                      <div style={{ height: 6, borderRadius: 3, background: t.bgSunken, overflow: 'hidden' }}>
                        <div style={{ height: '100%', borderRadius: 3, background: meta.color, width: `${pct}%`, transition: 'width 0.6s' }} />
                      </div>
                    </div>
                  );
                })}
              </div>
              {/* Taux de transformation */}
              <div style={{ background: t.bgElevated, borderRadius: 10, border: `1px solid ${t.border}`, padding: '16px' }}>
                <div style={{ fontSize: 13, fontWeight: 800, color: t.text, marginBottom: 14 }}>Statistiques clés</div>
                {[
                  { label: 'Objectif (mois)', value: `${stats.monthTarget.toLocaleString('fr-FR')} €`, sub: 'cible' },
                  { label: 'CA encaissé (mois)', value: `${stats.monthRevenue.toLocaleString('fr-FR')} €`, sub: 'payé' },
                  { label: 'En attente (€)', value: `${stats.pendingAmount.toLocaleString('fr-FR')} €`, sub: 'devis envoyés' },
                  { label: 'Taux transfo. (est.)', value: tauxTransfoPct != null ? `${tauxTransfoPct} %` : '—', sub: nEnvoye + nSigne > 0 ? 'signé / (envoyé + signé)' : 'aucun devis envoyé+signé' },
                  { label: 'Devis signés (mois en cours)', value: `${stats.signedThisMonth}`, sub: 'statut signé, date de réf. dans le mois' },
                  { label: 'Notes vocales (7 j)', value: `${stats.notesThisWeek}`, sub: 'source voice' },
                ].map((s, i) => (
                  <div key={i} style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    padding: '8px 0', borderBottom: i < 5 ? `1px solid ${t.border}` : 'none',
                  }}>
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: t.text }}>{s.label}</div>
                      <div style={{ fontSize: 10, color: t.textMuted }}>{s.sub}</div>
                    </div>
                    <span className="af-mono" style={{ fontSize: 20, fontWeight: 800, color: t.primary }}>{s.value}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AfWebView });
