/* ── RECEITAS & ROA VIEW ─────────────────────────────────────────────────
   Revenue + ROA analysis from ROA_2025_01.2026.xlsx
   ──────────────────────────────────────────────────────────────────────── */

/* ── Bar + Line Chart (Receita mensal por mês + ROA line) ── */
function ReceitaChart({ data, height = 260 }) {
  const [hoverIdx, setHoverIdx] = React.useState(null);
  const svgRef = React.useRef(null);
  if (!data || data.length < 2) return null;

  const W = 800, H = height;
  const pad = { t: 28, r: 40, b: 48, l: 80 };
  const iW = W - pad.l - pad.r, iH = H - pad.t - pad.b;
  const n = data.length;

  const maxRec = Math.max(...data.map(d => d.receita)) * 1.1;
  const minROA = Math.min(...data.map(d => d.roa)) * 0.95;
  const maxROA = Math.max(...data.map(d => d.roa)) * 1.05;
  const rangeROA = maxROA - minROA || 0.001;

  const barW = (iW / n) * 0.6;
  const xi = i => pad.l + (i + 0.5) * (iW / n);
  const yRec = v => pad.t + iH - (v / maxRec) * iH;
  const yROA = v => pad.t + iH - ((v - minROA) / rangeROA) * iH;

  const roaPath = data.map((d,i) => `${i===0?'M':'L'} ${xi(i)},${yROA(d.roa)}`).join(' ');

  const gridLines = Array.from({length: 5}, (_, i) => {
    const v = (maxRec * i / 4);
    return { y: yRec(v), v };
  });

  function handleMouseMove(e) {
    const rect = svgRef.current?.getBoundingClientRect();
    if (!rect) return;
    const mx = (e.clientX - rect.left) / rect.width * W;
    const idx = Math.floor((mx - pad.l) / (iW / n));
    setHoverIdx(Math.max(0, Math.min(n-1, idx)));
  }

  const fmtK = v => v >= 1e6 ? (v/1e6).toFixed(2)+'M' : v >= 1e3 ? (v/1e3).toFixed(0)+'k' : v.toFixed(0);
  const fmtPct = v => (v*100).toFixed(3)+'%';
  const GOLD = '#C4A228', BLUE = '#5B8DEF';

  return (
    <div style={{ background: '#0D1520', borderRadius: 'var(--r-sm)' }}>
      <div style={{ display:'flex', alignItems:'center', padding:'12px 16px 0', gap:16 }}>
        <span style={{ fontSize:'0.68rem', fontWeight:600, letterSpacing:'0.06em', color:'rgba(255,255,255,0.4)', textTransform:'uppercase' }}>
          Receita Mensal · Jan/2025 — Jan/2026
        </span>
        <div style={{ marginLeft:'auto', display:'flex', gap:16 }}>
          <div style={{ display:'flex', alignItems:'center', gap:6 }}>
            <div style={{ width:14, height:10, background:GOLD, borderRadius:2, opacity:0.85 }} />
            <span style={{ fontSize:'0.65rem', color:'rgba(255,255,255,0.5)' }}>Receita</span>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:6 }}>
            <svg width="20" height="10"><line x1="0" y1="5" x2="20" y2="5" stroke={BLUE} strokeWidth="1.5" strokeDasharray="4,3"/></svg>
            <span style={{ fontSize:'0.65rem', color:'rgba(255,255,255,0.5)' }}>ROA (eixo dir.)</span>
          </div>
        </div>
      </div>
      <svg ref={svgRef} viewBox={`0 0 ${W} ${H}`}
        style={{ width:'100%', height, display:'block', cursor:'crosshair' }}
        onMouseMove={handleMouseMove} onMouseLeave={() => setHoverIdx(null)}
        preserveAspectRatio="none">

        {/* Grid + Y labels (receita) */}
        {gridLines.map((g,i) => (
          <g key={i}>
            <line x1={pad.l} x2={pad.l+iW} y1={g.y} y2={g.y} stroke="rgba(255,255,255,0.05)" strokeWidth="1"/>
            <text x={pad.l-8} y={g.y+4} textAnchor="end" fontSize="8.5" fill="rgba(255,255,255,0.3)" fontFamily="JetBrains Mono,monospace">
              {fmtK(g.v)}
            </text>
          </g>
        ))}

        {/* ROA Y labels (right axis) */}
        {Array.from({length:5},(_,i) => {
          const v = minROA + (rangeROA * i / 4);
          return <text key={i} x={pad.l+iW+8} y={yROA(v)+4} fontSize="8.5" fill={`${BLUE}aa`} fontFamily="JetBrains Mono,monospace">{fmtPct(v)}</text>;
        })}

        {/* Bars */}
        {data.map((d, i) => (
          <g key={i}>
            <rect
              x={xi(i) - barW/2} y={yRec(d.receita)}
              width={barW} height={iH - (yRec(d.receita) - pad.t)}
              fill={hoverIdx === i ? '#E8C540' : GOLD}
              opacity={hoverIdx !== null && hoverIdx !== i ? 0.5 : 0.85}
              rx="2"
            />
          </g>
        ))}

        {/* ROA line */}
        <path d={roaPath} fill="none" stroke={BLUE} strokeWidth="1.8" strokeDasharray="5,3" opacity="0.85"/>
        {data.map((d,i) => (
          <circle key={i} cx={xi(i)} cy={yROA(d.roa)} r={hoverIdx===i?4:2.5}
            fill={hoverIdx===i?BLUE:'#0D1520'} stroke={BLUE} strokeWidth="1.5"/>
        ))}

        {/* X labels */}
        {data.map((d,i) => (
          <text key={i} x={xi(i)} y={H-10}
            textAnchor="middle" fontSize="9" fill="rgba(255,255,255,0.38)" fontFamily="Inter,sans-serif">
            {d.mes.split('/')[0]}
          </text>
        ))}

        {/* Hover tooltip */}
        {hoverIdx !== null && (() => {
          const d = data[hoverIdx];
          const tx = Math.min(xi(hoverIdx)+10, W-160), ty = pad.t+4;
          return <g>
            <line x1={xi(hoverIdx)} x2={xi(hoverIdx)} y1={pad.t} y2={pad.t+iH}
              stroke="rgba(255,255,255,0.15)" strokeWidth="1" strokeDasharray="3,3"/>
            <rect x={tx} y={ty} width={152} height={72} rx="4" fill="#1A2840" stroke="rgba(255,255,255,0.1)" strokeWidth="1"/>
            <text x={tx+10} y={ty+16} fontSize="9" fill="rgba(255,255,255,0.55)" fontFamily="Inter,sans-serif">{d.mes}</text>
            <text x={tx+10} y={ty+34} fontSize="10" fill={GOLD} fontFamily="JetBrains Mono,monospace" fontWeight="600">
              R$ {fmtK(d.receita)}
            </text>
            <text x={tx+10} y={ty+52} fontSize="10" fill={BLUE} fontFamily="JetBrains Mono,monospace">
              ROA {fmtPct(d.roa)}
            </text>
            <text x={tx+10} y={ty+68} fontSize="9" fill="rgba(255,255,255,0.4)" fontFamily="JetBrains Mono,monospace">
              AUM {(d.aum/1e9).toFixed(2)}B
            </text>
          </g>;
        })()}
      </svg>
    </div>
  );
}

/* ── ROA Status badge ── */
function ROAStatus({ ratio }) {
  if (ratio >= 1)    return <span className="badge badge-liberar">✓ Acima</span>;
  if (ratio >= 0.8)  return <span className="badge badge-alerta">⚠ Próx.</span>;
  return <span className="badge badge-corrigir">✗ Abaixo</span>;
}

/* ── Tab Por Cliente ───────────────────────────────────────────────
   Tabela filtravel + buscavel + ordenavel dos 99 clientes da base.
   Dois modos de visao: "essencial" e "alertas" (foco em meta). */
function ClientesTab({ clientes, totals }) {
  const [modo, setModo] = React.useState('essencial'); // essencial | alertas
  const [filtroGerente, setFiltroGerente] = React.useState('Todos');
  const [filtroSegmento, setFiltroSegmento] = React.useState('Todos');
  const [filtroStatus, setFiltroStatus] = React.useState('Todos');
  const [busca, setBusca] = React.useState('');
  const [sortBy, setSortBy] = React.useState('receitaYTD');
  const [sortDir, setSortDir] = React.useState('desc');

  const gerentesUnicos = React.useMemo(
    () => ['Todos', ...Array.from(new Set(clientes.map(c => c.gerente))).sort()],
    [clientes]
  );
  const segmentosUnicos = React.useMemo(
    () => ['Todos', ...Array.from(new Set(clientes.map(c => c.segmento))).sort()],
    [clientes]
  );
  const statusUnicos = React.useMemo(
    () => ['Todos', ...Array.from(new Set(clientes.map(c => c.status))).sort()],
    [clientes]
  );

  const filtrados = React.useMemo(() => {
    let arr = clientes;
    if (filtroGerente !== 'Todos')  arr = arr.filter(c => c.gerente === filtroGerente);
    if (filtroSegmento !== 'Todos') arr = arr.filter(c => c.segmento === filtroSegmento);
    if (filtroStatus !== 'Todos')   arr = arr.filter(c => c.status === filtroStatus);
    if (busca.trim()) {
      const q = busca.trim().toLowerCase();
      arr = arr.filter(c => c.cliente.toLowerCase().includes(q) || c.gerente.toLowerCase().includes(q));
    }
    arr = arr.slice().sort((a, b) => {
      const va = a[sortBy], vb = b[sortBy];
      if (typeof va === 'string') return sortDir === 'asc' ? va.localeCompare(vb) : vb.localeCompare(va);
      return sortDir === 'asc' ? (va - vb) : (vb - va);
    });
    return arr;
  }, [clientes, filtroGerente, filtroSegmento, filtroStatus, busca, sortBy, sortDir]);

  function toggleSort(col) {
    if (sortBy === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortBy(col); setSortDir('desc'); }
  }
  function SortableTh({ col, label, align = 'left' }) {
    const active = sortBy === col;
    const arrow = active ? (sortDir === 'asc' ? '▲' : '▼') : '';
    return (
      <th className={align === 'right' ? 'r' : align === 'center' ? 'c' : ''}
          onClick={() => toggleSort(col)}
          style={{ cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap' }}>
        {label} <span style={{ color: 'var(--gold)', fontSize: '0.6rem' }}>{arrow}</span>
      </th>
    );
  }

  const fmtBRL = v => (v || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
  const fmtPct = v => ((v || 0) * 100).toFixed(3) + '%';
  const aumFiltrado = filtrados.reduce((s, c) => s + c.aum, 0);
  const receitaFiltrada = filtrados.reduce((s, c) => s + c.receitaYTD, 0);

  return (
    <div>
      {/* Toggle de modo */}
      <div style={{ display: 'flex', gap: 0, marginBottom: 12, background: 'var(--paper-mid)', padding: 3, borderRadius: 'var(--r-sm)', width: 'fit-content' }}>
        {[['essencial', 'Visão essencial'], ['alertas', 'Foco em meta e alertas']].map(([id, label]) => (
          <button key={id} onClick={() => setModo(id)} style={{
            padding: '6px 14px', fontSize: '0.7rem', fontWeight: 500,
            background: modo === id ? 'var(--white)' : 'transparent',
            color: modo === id ? 'var(--heading)' : 'var(--muted)',
            border: 'none', borderRadius: 'var(--r-sm)',
            boxShadow: modo === id ? '0 1px 2px rgba(0,0,0,0.08)' : 'none',
            transition: 'all 0.12s',
          }}>{label}</button>
        ))}
      </div>

      {/* Filtros */}
      <div className="filter-bar" style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: '0.65rem', color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Gestor</span>
          <select value={filtroGerente} onChange={e => setFiltroGerente(e.target.value)}
            style={{ padding: '4px 8px', fontSize: '0.75rem', border: '1px solid var(--rule)', background: 'var(--white)' }}>
            {gerentesUnicos.map(g => <option key={g} value={g}>{g}</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: '0.65rem', color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Segmento</span>
          <select value={filtroSegmento} onChange={e => setFiltroSegmento(e.target.value)}
            style={{ padding: '4px 8px', fontSize: '0.75rem', border: '1px solid var(--rule)', background: 'var(--white)' }}>
            {segmentosUnicos.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: '0.65rem', color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Status</span>
          <select value={filtroStatus} onChange={e => setFiltroStatus(e.target.value)}
            style={{ padding: '4px 8px', fontSize: '0.75rem', border: '1px solid var(--rule)', background: 'var(--white)' }}>
            {statusUnicos.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
        <input
          className="search-input"
          type="text"
          placeholder="Buscar cliente ou gestor..."
          value={busca}
          onChange={e => setBusca(e.target.value)}
        />
      </div>

      {/* Resumo da seleção */}
      <div style={{ display: 'flex', gap: 24, marginBottom: 12, padding: '8px 16px', background: 'var(--paper)', border: '1px solid var(--rule)', fontSize: '0.72rem' }}>
        <span><strong style={{ color: 'var(--heading)' }}>{filtrados.length}</strong> <span style={{ color: 'var(--muted)' }}>clientes filtrados</span></span>
        <span><strong style={{ color: 'var(--heading)', fontFamily: 'JetBrains Mono, monospace' }}>{(aumFiltrado/1e9).toFixed(3)} bi</strong> <span style={{ color: 'var(--muted)' }}>AUM</span></span>
        <span><strong style={{ color: 'var(--gold)', fontFamily: 'JetBrains Mono, monospace' }}>{fmtBRL(receitaFiltrada)}</strong> <span style={{ color: 'var(--muted)' }}>receita YTD</span></span>
        <span style={{ marginLeft: 'auto', color: 'var(--muted)' }}>{(aumFiltrado/totals.aum*100).toFixed(1)}% do AUM total</span>
      </div>

      {/* Tabela */}
      <div className="card">
        <div style={{ overflowX: 'auto', WebkitOverflowScrolling: 'touch' }}>
          <table className="tbl">
            <thead>
              <tr>
                <SortableTh col="cliente"    label="Cliente" />
                <SortableTh col="gerente"    label="Gestor" />
                <SortableTh col="segmento"   label="Segmento" />
                <SortableTh col="aum"        label="AUM" align="right" />
                {modo === 'essencial' && <SortableTh col="nnm" label="NNM YTD" align="right" />}
                <SortableTh col="roa"        label="ROA" align="right" />
                {modo === 'alertas' && <SortableTh col="fee" label="Fee %" align="right" />}
                {modo === 'alertas' && <SortableTh col="faixaROA" label="Faixa" align="center" />}
                <SortableTh col="receitaYTD" label="Receita YTD" align="right" />
                <SortableTh col="status"     label="Status" align="center" />
                {modo === 'alertas' && <SortableTh col="alerta" label="Alerta" />}
              </tr>
            </thead>
            <tbody>
              {filtrados.map(c => {
                const statusClass = c.status === 'OK' ? 'badge-liberar'
                  : c.status === 'Free of Charging' ? 'badge-alerta'
                  : 'badge';
                return (
                  <tr key={c.id}>
                    <td style={{ fontWeight: 600, color: 'var(--heading)', fontSize: '0.82rem' }}>{c.cliente}</td>
                    <td style={{ fontSize: '0.78rem' }}>{c.gerente}</td>
                    <td style={{ fontSize: '0.72rem', color: 'var(--muted)' }}>{c.segmento}</td>
                    <td className="num">{(c.aum/1e6).toFixed(2)} M</td>
                    {modo === 'essencial' && (
                      <td className={`num ${c.nnm >= 0 ? 'tbl-pos' : 'tbl-neg'}`}>
                        {c.nnm >= 0 ? '+' : ''}{(c.nnm/1e6).toFixed(2)} M
                      </td>
                    )}
                    <td className="num" style={{ color: c.roa >= 0.004 ? 'var(--green)' : 'var(--amber)', fontWeight: 600 }}>
                      {fmtPct(c.roa)}
                    </td>
                    {modo === 'alertas' && <td className="num">{fmtPct(c.fee)}</td>}
                    {modo === 'alertas' && (
                      <td className="c" style={{ fontSize: '0.68rem' }}>
                        <span className={`badge ${c.faixaROA === 'Alto' ? 'badge-liberar' : c.faixaROA === 'Médio' ? 'badge-alerta' : c.faixaROA === 'Baixo' ? 'badge-corrigir' : 'badge'}`}>
                          {c.faixaROA || '—'}
                        </span>
                      </td>
                    )}
                    <td className="num" style={{ color: 'var(--gold)', fontWeight: 500 }}>{fmtBRL(c.receitaYTD)}</td>
                    <td className="c"><span className={`badge ${statusClass}`} style={{ fontSize: '0.6rem' }}>{c.status}</span></td>
                    {modo === 'alertas' && (
                      <td style={{ fontSize: '0.72rem', color: c.alerta ? 'var(--red)' : 'var(--muted)' }}>
                        {c.alerta || '—'}
                      </td>
                    )}
                  </tr>
                );
              })}
              {filtrados.length === 0 && (
                <tr><td colSpan={modo === 'alertas' ? 10 : 9} style={{ padding: '32px', textAlign: 'center', color: 'var(--muted)' }}>
                  Nenhum cliente corresponde aos filtros aplicados.
                </td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

/* ── Main View ── */
function ReceitasView() {
  const data = window.ROA_DATA;
  const [expandedGerente, setExpandedGerente] = React.useState(null);
  const [tab, setTab] = React.useState('mensal'); // mensal | gerentes | clientes

  if (!data) return (
    <div className="empty-state">
      <p>Dados de receita não carregados. Verifique o arquivo roa-seed.js.</p>
    </div>
  );

  const { totals, snapshot, mensal, gerentes, clientes } = data;

  // % CDI comparison: ROA médio vs CDI médio (from BENCHMARKS)
  const cdiMedio = Object.values(window.BENCHMARKS?.monthly_cdi || {}).reduce((s,v,_,a) => s + v/a.length, 0);

  return (
    <div>
      {/* KPI Strip */}
      <div className="kpi-strip" style={{ marginBottom: 20 }}>
        <div className="kpi-tile">
          <div className="kpi-tile-label">AUM Dez/2025</div>
          <div className="kpi-tile-value" style={{ fontSize:'1.3rem' }}>
            {(totals.aum/1e9).toFixed(2)} <span style={{ fontSize:'0.9rem', color:'var(--muted)' }}>bi</span>
          </div>
          <div className="kpi-tile-sub">{totals.clientes} clientes</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">Receita Jan/2026</div>
          <div className="kpi-tile-value" style={{ fontSize:'1.3rem' }}>
            {(snapshot.receita/1e3).toFixed(0)} <span style={{ fontSize:'0.9rem', color:'var(--muted)' }}>k</span>
          </div>
          <div className="kpi-tile-sub">mês corrente</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">Receita Acum. 2025</div>
          <div className="kpi-tile-value" style={{ fontSize:'1.3rem' }}>
            {(totals.receitaAcum/1e6).toFixed(2)} <span style={{ fontSize:'0.9rem', color:'var(--muted)' }}>M</span>
          </div>
          <div className="kpi-tile-sub">Jan→Dez/2025</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">ROA Médio 2025</div>
          <div className="kpi-tile-value" style={{ fontSize:'1.5rem', color:'var(--gold)' }}>
            {(totals.roaMedio*100).toFixed(3)}%
          </div>
          <div className="kpi-tile-sub">a.m. ponderado</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">NNM Acumulado</div>
          <div className="kpi-tile-value" style={{ fontSize:'1.3rem', color: totals.nnmAcum >= 0 ? 'var(--green)' : 'var(--red)' }}>
            {totals.nnmAcum >= 0 ? '+' : ''}{(totals.nnmAcum/1e6).toFixed(1)} <span style={{ fontSize:'0.9rem' }}>M</span>
          </div>
          <div className="kpi-tile-sub">captação líquida 2025</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">ROA Jan/2026</div>
          <div className="kpi-tile-value" style={{ fontSize:'1.5rem', color:'var(--gold)' }}>
            {(snapshot.roa*100).toFixed(3)}%
          </div>
          <div className="kpi-tile-sub">snapshot atual</div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display:'flex', borderBottom:'1px solid var(--rule)', marginBottom:16, background:'var(--white)' }}>
        {[['mensal','Série Mensal'],['gerentes','Por Gerente'],['clientes','Por Cliente']].map(([id,label]) => (
          <button key={id} onClick={() => setTab(id)} style={{
            padding:'10px 20px', fontSize:'0.72rem', fontWeight:500, letterSpacing:'0.04em',
            borderBottom: tab===id ? '2px solid var(--navy)' : '2px solid transparent',
            color: tab===id ? 'var(--navy)' : 'var(--muted)',
            background:'transparent', transition:'all 0.12s',
          }}>{label}</button>
        ))}
      </div>

      {/* ── TAB: MENSAL ── */}
      {tab === 'mensal' && (
        <div>
          <div className="card" style={{ overflow:'hidden', marginBottom:16 }}>
            <div className="card-header" style={{ background:'#0D1520', border:'none' }}>
              <h3 style={{ color:'rgba(255,255,255,0.6)', fontFamily:'Inter,sans-serif', fontSize:'0.78rem', fontWeight:500 }}>
                Receita Mensal · Jan/2025 — Jan/2026
              </h3>
            </div>
            <ReceitaChart data={mensal} height={260} />
          </div>

          <div className="card">
            <div className="card-header"><h3>Série Histórica Completa</h3></div>
            <div className="tbl-wrap">
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Mês</th>
                    <th className="r">AUM</th>
                    <th className="r">Receita Mês</th>
                    <th className="r">ROA</th>
                    <th className="r">NNM</th>
                    <th className="r">Clientes</th>
                  </tr>
                </thead>
                <tbody>
                  {mensal.slice().reverse().map((m, i) => (
                    <tr key={i}>
                      <td style={{ fontWeight:500 }}>{m.mes}</td>
                      <td className="num">{(m.aum/1e9).toFixed(3)} bi</td>
                      <td className="num" style={{ color:'var(--gold)', fontWeight:500 }}>
                        {m.receita.toLocaleString('pt-BR',{style:'currency',currency:'BRL'})}
                      </td>
                      <td className="num" style={{ color: m.roa >= totals.roaMedio ? 'var(--green)' : 'var(--amber)' }}>
                        {(m.roa*100).toFixed(4)}%
                      </td>
                      <td className={`num ${m.nnm >= 0 ? 'tbl-pos' : 'tbl-neg'}`}>
                        {m.nnm >= 0 ? '+' : ''}{(m.nnm/1e6).toFixed(2)} M
                      </td>
                      <td className="num">{m.clientes}</td>
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr style={{ borderTop:'2px solid var(--heading)', fontWeight:700 }}>
                    <td style={{ fontWeight:700, fontFamily:'Cormorant Garamond,serif', fontSize:'0.95rem' }}>2025 Total</td>
                    <td className="num">—</td>
                    <td className="num" style={{ color:'var(--gold)', fontWeight:700 }}>
                      {totals.receitaAcum.toLocaleString('pt-BR',{style:'currency',currency:'BRL'})}
                    </td>
                    <td className="num" style={{ fontWeight:700 }}>{(totals.roaMedio*100).toFixed(4)}%</td>
                    <td className={`num ${totals.nnmAcum >= 0 ? 'tbl-pos' : 'tbl-neg'}`} style={{ fontWeight:700 }}>
                      {totals.nnmAcum >= 0 ? '+' : ''}{(totals.nnmAcum/1e6).toFixed(2)} M
                    </td>
                    <td className="num">{totals.clientes}</td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ── TAB: GERENTES ── */}
      {tab === 'gerentes' && (
        <div>
          <div className="card">
            <div className="card-header">
              <h3>Ranking por Gestor · Jan/2026</h3>
              <span style={{ fontSize:'0.7rem', color:'var(--muted)' }}>{gerentes.length} gestores</span>
            </div>
            <div className="tbl-wrap">
              <table className="tbl">
                <thead>
                  <tr>
                    <th className="c">Rank</th>
                    <th>Gestor</th>
                    <th className="r">Carteiras</th>
                    <th className="r">AUM</th>
                    <th className="r">Receita Mês</th>
                    <th className="r">Receita Acum.</th>
                    <th className="r">ROA Real</th>
                    <th className="r">Meta ROA</th>
                    <th className="c">vs Meta</th>
                  </tr>
                </thead>
                <tbody>
                  {gerentes.map((g, i) => (
                    <React.Fragment key={g.nome}>
                      <tr
                        onClick={() => setExpandedGerente(expandedGerente === g.nome ? null : g.nome)}
                        style={{ cursor:'pointer' }}
                        className={expandedGerente === g.nome ? 'tbl-row-alert' : ''}
                      >
                        <td className="c" style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'1.1rem', fontWeight:500, color:'var(--muted)' }}>
                          {g.rank}
                        </td>
                        <td style={{ fontWeight:600, color:'var(--heading)', fontSize:'0.88rem' }}>
                          {g.nome}
                          <span style={{ fontSize:'0.62rem', color:'var(--muted)', marginLeft:6, fontWeight:400 }}>
                            {expandedGerente === g.nome ? '▲' : '▼'}
                          </span>
                        </td>
                        <td className="num">{g.carteiras}</td>
                        <td className="num">{(g.aum/1e9).toFixed(3)} bi</td>
                        <td className="num" style={{ color:'var(--gold)', fontWeight:500 }}>
                          {g.receitaMes > 0 ? g.receitaMes.toLocaleString('pt-BR',{style:'currency',currency:'BRL'}) : '—'}
                        </td>
                        <td className="num">
                          {g.receitaAcum.toLocaleString('pt-BR',{style:'currency',currency:'BRL'})}
                        </td>
                        <td className="num" style={{ color: g.roa >= g.meta ? 'var(--green)' : 'var(--amber)', fontWeight:600 }}>
                          {(g.roa*100).toFixed(4)}%
                        </td>
                        <td className="num" style={{ color:'var(--muted)' }}>{(g.meta*100).toFixed(3)}%</td>
                        <td className="c"><ROAStatus ratio={g.vsMetaRatio} /></td>
                      </tr>
                      {expandedGerente === g.nome && (
                        <tr>
                          <td colSpan={9} style={{ padding:0, background:'var(--paper)' }}>
                            <div style={{ padding:'12px 20px 16px' }}>
                              <div style={{ fontSize:'0.68rem', fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--muted)', marginBottom:10 }}>
                                Detalhes do Gestor · {g.nome}
                              </div>
                              <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:1, background:'var(--rule)', marginBottom:12 }}>
                                {[
                                  { label:'AUM', value:(g.aum/1e9).toFixed(3)+' bi' },
                                  { label:'ROA Real', value:(g.roa*100).toFixed(4)+'%', color: g.roa>=g.meta?'var(--green)':'var(--amber)' },
                                  { label:'Meta ROA', value:(g.meta*100).toFixed(3)+'%' },
                                  { label:'NNM', value:(g.nnm>=0?'+':'')+(g.nnm/1e6).toFixed(2)+' M', color: g.nnm>=0?'var(--green)':'var(--red)' },
                                ].map((k,j) => (
                                  <div key={j} style={{ background:'var(--white)', padding:'12px 16px' }}>
                                    <div style={{ fontSize:'0.6rem', fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'var(--muted)', marginBottom:4 }}>{k.label}</div>
                                    <div style={{ fontFamily:'JetBrains Mono', fontSize:'0.88rem', fontWeight:600, color: k.color || 'var(--heading)' }}>{k.value}</div>
                                  </div>
                                ))}
                              </div>
                              <div style={{ fontSize:'0.72rem', color:'var(--muted)', fontStyle:'italic' }}>
                                {g.carteiras} carteiras · Receita acumulada {g.receitaAcum.toLocaleString('pt-BR',{style:'currency',currency:'BRL'})} · Proporção do AUM total: {(g.aum/totals.aum*100).toFixed(1)}%
                              </div>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  ))}
                </tbody>
                <tfoot>
                  <tr style={{ borderTop:'2px solid var(--heading)' }}>
                    <td colSpan={2} style={{ fontWeight:700, fontFamily:'Cormorant Garamond,serif', fontSize:'0.95rem' }}>TOTAL</td>
                    <td className="num" style={{ fontWeight:700 }}>{gerentes.reduce((s,g)=>s+g.carteiras,0)}</td>
                    <td className="num" style={{ fontWeight:700 }}>{(totals.aum/1e9).toFixed(3)} bi</td>
                    <td className="num" style={{ color:'var(--gold)', fontWeight:700 }}>
                      {gerentes.reduce((s,g)=>s+g.receitaMes,0).toLocaleString('pt-BR',{style:'currency',currency:'BRL'})}
                    </td>
                    <td className="num" style={{ fontWeight:700 }}>
                      {totals.receitaAcum.toLocaleString('pt-BR',{style:'currency',currency:'BRL'})}
                    </td>
                    <td className="num" style={{ fontWeight:700, color:'var(--gold)' }}>{(totals.roaMedio*100).toFixed(4)}%</td>
                    <td colSpan={2} />
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ── TAB: CLIENTES ── */}
      {tab === 'clientes' && clientes && (
        <ClientesTab clientes={clientes} totals={totals} />
      )}
      {tab === 'clientes' && !clientes && (
        <div className="empty-state">
          <p>Lista de clientes não carregada. Verifique o campo "clientes" em roa-seed.js.</p>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ReceitasView });
