/* ── COMPARATIVE VIEW ────────────────────────────────────────────────────── */

function ComparativeView({ months, onSelectCarteira }) {
  const [keyA, setKeyA] = React.useState('');
  const [keyB, setKeyB] = React.useState('');
  const [sortCol, setSortCol] = React.useState('varPct');
  const [sortDir, setSortDir] = React.useState(-1);

  React.useEffect(() => {
    if (months.length >= 2 && !keyA) {
      setKeyA(months[0].key);
      setKeyB(months[1].key);
    } else if (months.length === 1 && !keyA) {
      setKeyA(months[0].key);
    }
  }, [months]);

  const mA = months.find(m => m.key === keyA);
  const mB = months.find(m => m.key === keyB);

  if (!mA) return (
    <div className="empty-state"><Icon.comp /><p>Importe ao menos um mês para ver o comparativo.</p></div>
  );

  // Build comparison rows
  const namesA = Object.keys(mA.carteiras);
  const namesB = mB ? Object.keys(mB.carteiras) : [];
  const allNames = [...new Set([...namesA, ...namesB])];

  const rows = allNames.map(nome => {
    const a = mA.carteiras[nome];
    const b = mB ? mB.carteiras[nome] : null;
    // varPct = PL variation (includes aportes/resgates) — used for flow monitoring
    const varPct = a && b ? (a.plAtual - b.plAtual) / (b.plAtual || 1) : (a ? 0 : null);
    const varRS  = a && b ? a.plAtual - b.plAtual : null;
    // rentDiff = actual investment return diff between months (no aportes/resgates)
    const rentA = a?.rentMes || 0;
    const rentB = b?.rentMes || 0;
    return { nome, a, b, varPct, varRS, rentA, rentB };
  }).filter(r => r.a);

  const sorted = rows.slice().sort((x, y) => {
    const av = x[sortCol] ?? 0, bv = y[sortCol] ?? 0;
    if (typeof av === 'string') return sortDir * av.localeCompare(bv);
    return sortDir * (av - bv);
  });

  function toggleSort(col) {
    if (sortCol === col) setSortDir(d => -d);
    else { setSortCol(col); setSortDir(-1); }
  }
  function Th({ col, children, cls }) {
    const active = sortCol === col;
    return <th className={cls} onClick={() => toggleSort(col)} style={{ cursor: 'pointer', userSelect: 'none' }}>{children}{active ? (sortDir === -1 ? ' ↓' : ' ↑') : ''}</th>;
  }

  // Top movers by RENT (pure investment performance, no aportes)
  const withVar = rows.filter(r => r.a?.rentMes != null);
  const topUp   = withVar.slice().sort((a,b) => (b.a?.rentMes||0) - (a.a?.rentMes||0)).slice(0, 5);
  const topDown = withVar.slice().sort((a,b) => (a.a?.rentMes||0) - (b.a?.rentMes||0)).slice(0, 5);

  const plA = Object.values(mA.carteiras).reduce((s,c) => s+c.plAtual, 0);
  const plB = mB ? Object.values(mB.carteiras).reduce((s,c) => s+c.plAtual, 0) : 0;

  return (
    <div>
      {/* Month selectors + export */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 20, alignItems: 'flex-end', flexWrap: 'wrap' }}>
        <div>
          <div className="label" style={{ marginBottom: 6 }}>Mês de referência</div>
          <select value={keyA} onChange={e => setKeyA(e.target.value)} style={{ padding: '7px 12px', border: '1px solid var(--rule)', background: 'var(--white)', fontSize: '0.82rem', color: 'var(--body)', outline: 'none' }}>
            {months.map(m => <option key={m.key} value={m.key}>{m.label}</option>)}
          </select>
        </div>
        {months.length > 1 && (
          <>
            <div style={{ color: 'var(--muted)', paddingBottom: 8, fontSize: '0.9rem' }}>vs</div>
            <div>
              <div className="label" style={{ marginBottom: 6 }}>Baseline</div>
              <select value={keyB} onChange={e => setKeyB(e.target.value)} style={{ padding: '7px 12px', border: '1px solid var(--rule)', background: 'var(--white)', fontSize: '0.82rem', color: 'var(--body)', outline: 'none' }}>
                <option value="">— nenhum —</option>
                {months.filter(m => m.key !== keyA).map(m => <option key={m.key} value={m.key}>{m.label}</option>)}
              </select>
            </div>
          </>
        )}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <button className="btn btn-secondary btn-sm" onClick={() => exportComparativeExcel(mA, mB, sorted)}>
            <Icon.export /> Excel
          </button>
          <button className="btn btn-secondary btn-sm" onClick={() => exportComparativePDF(mA, mB, sorted, topUp, topDown)}>
            <Icon.export /> PDF
          </button>
        </div>
      </div>

      {/* PL panels */}
      <div className="comp-panels" style={{ marginBottom: 16 }}>
        <div className="comp-panel">
          <div className="comp-panel-label">PL · {mA.label}</div>
          <div className="comp-panel-val">{fmtBRL(plA, true)}</div>
          <div className="comp-panel-delta" style={{ color: 'var(--muted)' }}>{mA.totals.total} carteiras</div>
        </div>
        {mB ? (
          <div className="comp-panel">
            <div className="comp-panel-label">PL · {mB.label}</div>
            <div className="comp-panel-val">{fmtBRL(plB, true)}</div>
            <div className={`comp-panel-delta ${colorClass(plA - plB)}`}>
              {fmtPct((plA - plB) / (plB || 1))} &nbsp;{fmtBRL(plA - plB, true)}
            </div>
          </div>
        ) : (
          <div className="comp-panel" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--muted)', fontSize: '0.8rem' }}>
            Selecione um segundo mês para comparar
          </div>
        )}
      </div>

      {/* KPI strip */}
      <div className="kpi-strip" style={{ marginBottom: 20 }}>
        <div className="kpi-tile">
          <div className="kpi-tile-label">Rent. Positiva</div>
          <div className="kpi-tile-value green">{withVar.filter(r => (r.a?.rentMes||0) > 0).length}</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">Rent. Nula</div>
          <div className="kpi-tile-value">{withVar.filter(r => (r.a?.rentMes||0) === 0).length}</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">Rent. Negativa</div>
          <div className="kpi-tile-value red">{withVar.filter(r => (r.a?.rentMes||0) < 0).length}</div>
        </div>
      </div>

      {/* Movers */}
      {mB && (
        <div className="movers-grid" style={{ marginBottom: 20 }}>
          <div className="movers-panel">
            <div className="movers-header">▲ Maiores Altas</div>
            {topUp.map((r, i) => {
              const barW = Math.min(100, Math.abs(r.a?.rentMes||0) * 2000);
              return (
                <div className="mover-row" key={i}>
                  <span className="mover-nome" style={{ cursor: 'pointer' }} onClick={() => onSelectCarteira(r.nome)}>{r.nome}</span>
                  <div className="mover-bar-wrap"><div className="mover-bar" style={{ width: `${barW}%`, background: 'var(--green)' }} /></div>
                  <span className="num tbl-pos" style={{ minWidth: 60, textAlign: 'right', fontSize: '0.75rem' }}>{fmtPct(r.a?.rentMes)}</span>
                  <span className="num tbl-nt" style={{ minWidth: 80, textAlign: 'right', fontSize: '0.72rem' }}>{fmtBRL(r.a?.plAtual, true)}</span>
                </div>
              );
            })}
          </div>
          <div className="movers-panel">
            <div className="movers-header">▼ Maiores Quedas</div>
            {topDown.map((r, i) => {
              const barW = Math.min(100, Math.abs(r.a?.rentMes||0) * 2000);
              return (
                <div className="mover-row" key={i}>
                  <span className="mover-nome" style={{ cursor: 'pointer' }} onClick={() => onSelectCarteira(r.nome)}>{r.nome}</span>
                  <div className="mover-bar-wrap"><div className="mover-bar" style={{ width: `${barW}%`, background: 'var(--red)' }} /></div>
                  <span className="num tbl-neg" style={{ minWidth: 60, textAlign: 'right', fontSize: '0.75rem' }}>{fmtPct(r.a?.rentMes)}</span>
                  <span className="num tbl-nt" style={{ minWidth: 80, textAlign: 'right', fontSize: '0.72rem' }}>{fmtBRL(r.a?.plAtual, true)}</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Full table */}
      <div className="card">
        <div className="card-header">
          <h3>Diferenças por Carteira</h3>
          <span style={{ fontSize: '0.7rem', color: 'var(--muted)' }}>{rows.length} carteiras</span>
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead>
              <tr>
                <Th col="nome" cls="">Carteira</Th>
                <th>Status</th>
                <th className="r">PL {mA.label}</th>
                {mB && <th className="r">PL {mB.label}</th>}
                <Th col="varRS"   cls="r">Δ PL R$</Th>
                <Th col="varPct"  cls="r" style={{ fontSize:'0.58rem', color:'var(--muted)' }}>Δ PL % ¹</Th>
                <Th col="a.rentMes" cls="r">Rent. Real</Th>
                <th className="r" style={{ whiteSpace:'nowrap' }}>% CDI</th>
                <th className="r">Ativos</th>
              </tr>
            </thead>
            <tbody>
              {sorted.map(r => (
                <tr key={r.nome} className={r.a?.status === 'CORRIGIR' ? 'tbl-row-corrigir' : r.a?.status === 'LIBERAR COM ALERTA' ? 'tbl-row-alert' : ''}>
                  <td className="nome" onClick={() => onSelectCarteira(r.nome)}>{r.nome}</td>
                  <td><span className={`badge ${statusBadge(r.a?.status)}`}>{r.a?.status || '—'}</span></td>
                  <td className="num">{fmtBRL(r.a?.plAtual)}</td>
                  {mB && <td className="num">{r.b ? fmtBRL(r.b.plAtual) : '—'}</td>}
                  <td className={`num ${colorClass(r.varRS)}`}>{r.varRS != null ? fmtBRL(r.varRS, true) : '—'}</td>
                  <td className="num tbl-nt" style={{ fontSize:'0.72rem' }}>{r.varPct != null ? fmtPct(r.varPct) : '—'}</td>
                  <td className={`num ${colorClass(r.a?.rentMes)}`}>{fmtPct(r.a?.rentMes)}</td>
                  <td className="num">
                    {(() => {
                      const pct = window.calcPctCDI?.(r.a?.rentMes, mA.key);
                      if (pct == null) return <span className="tbl-nt">—</span>;
                      const color = pct >= 100 ? 'var(--green)' : pct >= 80 ? 'var(--amber)' : 'var(--red)';
                      return <span style={{ color, fontWeight:600, fontFamily:'JetBrains Mono', fontSize:'0.75rem' }}>{Math.round(pct)}%</span>;
                    })()}
                  </td>
                  <td className="num">{r.a?.nAtivosAbr || '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      {/* Footnote */}
      <div style={{ padding: '10px 16px', fontSize: '0.65rem', color: 'var(--muted)', borderTop: '1px solid var(--rule)', marginTop: 4 }}>
        ¹ Δ PL % inclui aportes e resgates — não representa rentabilidade. Use a coluna <strong>Rent. Real</strong> para comparar performance de investimento.
      </div>
    </div>
  );
}

Object.assign(window, { ComparativeView });

/* ── EXPORT FUNCTIONS ────────────────────────────────────────────────── */

function exportComparativePDF(mA, mB, rows, topUp, topDown) {
  const plA = Object.values(mA.carteiras).reduce((s,c) => s+c.plAtual, 0);
  const plB = mB ? Object.values(mB.carteiras).reduce((s,c) => s+c.plAtual, 0) : 0;

  const html = `<!DOCTYPE html><html><head><meta charset="utf-8">
<title>Comparativo · ${mA.label}${mB ? ' × ' + mB.label : ''}</title>
<style>
@page { size: A4 landscape; margin: 14mm; }
body { font-family: Georgia, serif; color: #1a1814; line-height: 1.5; }
.brand { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
.brand-name { font-size: 0.85rem; font-weight: 600; letter-spacing: 0.18em; color: #05305F; text-transform: uppercase; }
.brand-sub { font-size: 0.65rem; color: #C4A228; letter-spacing: 0.1em; text-transform: uppercase; }
h1 { font-size: 1.4rem; margin: 6px 0 4px; }
.subtitle { font-size: 0.75rem; color: #9a9188; margin-bottom: 16px; }
.panels { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: #e3ddd5; margin-bottom: 16px; }
.panel { background: #fff; padding: 12px 16px; border: 1px solid #e3ddd5; }
.panel-l { font-size: 0.55rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: #9a9188; margin-bottom: 4px; }
.panel-v { font-size: 1.2rem; font-weight: 500; }
.panel-d { font-size: 0.7rem; margin-top: 2px; font-family: monospace; }
.pos { color: #1a5c36; } .neg { color: #7a1e1e; }
.movers { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: #e3ddd5; margin-bottom: 16px; }
.movers > div { background: #fff; padding: 10px 14px; border: 1px solid #e3ddd5; }
.movers h3 { font-size: 0.65rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: #9a9188; margin-bottom: 6px; }
.mv-row { display: flex; padding: 4px 0; border-bottom: 1px solid #f0ede7; font-size: 0.78rem; }
.mv-row span:first-child { flex: 1; font-weight: 500; }
.mv-row span:last-child { font-family: monospace; min-width: 70px; text-align: right; }
table { width: 100%; border-collapse: collapse; font-size: 0.72rem; margin-top: 12px; }
th { font-size: 0.55rem; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; color: #9a9188; padding: 6px 8px; border-bottom: 2px solid #b8b2a6; text-align: left; }
th.r { text-align: right; }
td { padding: 5px 8px; border-bottom: 1px solid #e3ddd5; }
td.r { text-align: right; }
td.num { font-family: monospace; font-size: 0.7rem; }
.badge { display: inline-block; font-size: 0.55rem; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; padding: 1px 5px; border-radius: 2px; }
.b-l { background: #eaf4ee; color: #1a5c36; }
.b-a { background: #fbf0dc; color: #7a5318; }
.b-c { background: #fae8e8; color: #7a1e1e; border: 1px solid #7a1e1e; }
.foot { margin-top: 18px; font-size: 0.62rem; color: #9a9188; border-top: 1px solid #e3ddd5; padding-top: 10px; }
</style></head><body>
<div class="brand"><span class="brand-name">Mirabaud</span><span class="brand-sub">Family Office</span></div>
<h1>Comparativo Mensal · ${mA.label}${mB ? ' × ' + mB.label : ''}</h1>
<div class="subtitle">Variação de Patrimônio Líquido e diferenças por carteira</div>

<div class="panels">
  <div class="panel">
    <div class="panel-l">PL · ${mA.label}</div>
    <div class="panel-v">${fmtBRL(plA, true)}</div>
    <div class="panel-d">${mA.totals.total} carteiras</div>
  </div>
  ${mB ? `<div class="panel">
    <div class="panel-l">PL · ${mB.label}</div>
    <div class="panel-v">${fmtBRL(plB, true)}</div>
    <div class="panel-d ${plA-plB>=0?'pos':'neg'}">${fmtPct((plA-plB)/(plB||1))} · ${fmtBRL(plA-plB, true)}</div>
  </div>` : ''}
</div>

${mB && topUp.length ? `<div class="movers">
  <div>
    <h3>▲ Maiores Altas</h3>
    ${topUp.map(r => `<div class="mv-row"><span>${r.nome}</span><span class="pos">${fmtPct(r.varPct)}</span><span class="pos">${fmtBRL(r.varRS, true)}</span></div>`).join('')}
  </div>
  <div>
    <h3>▼ Maiores Quedas</h3>
    ${topDown.map(r => `<div class="mv-row"><span>${r.nome}</span><span class="neg">${fmtPct(r.varPct)}</span><span class="neg">${fmtBRL(r.varRS, true)}</span></div>`).join('')}
  </div>
</div>` : ''}

<table>
<thead>
  <tr>
    <th>Carteira</th><th>Status</th>
    <th class="r">PL ${mA.label}</th>
    ${mB ? `<th class="r">PL ${mB.label}</th>` : ''}
    <th class="r">Δ R$</th><th class="r">Δ %</th><th class="r">Rent. Mês</th>
  </tr>
</thead>
<tbody>
  ${rows.map(r => {
    const cls = r.a?.status === 'CORRIGIR' ? 'b-c' : r.a?.status === 'LIBERAR COM ALERTA' ? 'b-a' : 'b-l';
    return `<tr>
      <td><strong>${r.nome}</strong></td>
      <td><span class="badge ${cls}">${r.a?.status || '—'}</span></td>
      <td class="num r">${fmtBRL(r.a?.plAtual)}</td>
      ${mB ? `<td class="num r">${r.b ? fmtBRL(r.b.plAtual) : '—'}</td>` : ''}
      <td class="num r ${r.varRS>=0?'pos':'neg'}">${r.varRS != null ? fmtBRL(r.varRS, true) : '—'}</td>
      <td class="num r ${r.varPct>=0?'pos':'neg'}">${r.varPct != null ? fmtPct(r.varPct) : '—'}</td>
      <td class="num r ${r.a?.rentMes>=0?'pos':'neg'}">${fmtPct(r.a?.rentMes)}</td>
    </tr>`;
  }).join('')}
</tbody>
</table>

<div class="foot">Mirabaud Family Office · Comparativo gerado em ${new Date().toLocaleDateString('pt-BR', { dateStyle: 'long' })} · ${new Date().toLocaleTimeString('pt-BR', { timeStyle: 'short' })}</div>
</body></html>`;
  const w = window.open('','_blank');
  w.document.write(html);
  w.document.close();
  setTimeout(() => w.print(), 600);
}

function exportComparativeExcel(mA, mB, rows) {
  // CSV with BOM for Excel UTF-8
  const sep = ';';
  const esc = v => {
    if (v == null) return '';
    const s = String(v).replace(/"/g, '""');
    return /[";\n]/.test(s) ? `"${s}"` : s;
  };
  const num = v => v == null ? '' : String(v).replace('.', ',');
  const pct = v => v == null ? '' : (v * 100).toFixed(4).replace('.', ',') + '%';

  const headers = ['Carteira','Status'];
  headers.push(`PL ${mA.label}`);
  if (mB) headers.push(`PL ${mB.label}`);
  headers.push('Variação R$','Variação %','Rent. Mês','Ativos');

  const lines = [headers.map(esc).join(sep)];
  for (const r of rows) {
    const cells = [
      r.nome,
      r.a?.status || '',
      num(r.a?.plAtual),
    ];
    if (mB) cells.push(num(r.b?.plAtual));
    cells.push(num(r.varRS), pct(r.varPct), pct(r.a?.rentMes), r.a?.nAtivosAbr ?? '');
    lines.push(cells.map(esc).join(sep));
  }

  const BOM = '\uFEFF';
  const csv = BOM + lines.join('\r\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `Comparativo_${mA.key}${mB ? '_vs_' + mB.key : ''}.csv`;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 100);
}

Object.assign(window, { exportComparativePDF, exportComparativeExcel });
