/* ── DASHBOARD VIEW ─────────────────────────────────────────────────────── */

function DashboardView({ month, months, activeMonthKey, onMonthSelect, onSelectCarteira, onMonthChange }) {
  const [filter, setFilter] = React.useState('Todos');
  const [search, setSearch] = React.useState('');
  const [sortCol, setSortCol] = React.useState('plAtual');
  const [sortDir, setSortDir] = React.useState(-1);
  const [toDelete, setToDelete] = React.useState(null); // { nome }
  const [deleteScope, setDeleteScope] = React.useState('month'); // 'month' or 'all'

  const [fxRate, setFxRate] = React.useState(null);

  React.useEffect(() => {
    window.fetchBenchmarks?.();
    window.fetchFX?.().then(r => setFxRate(r));
  }, [month?.key]);

  if (!month) return (
    <div className="empty-state">
      <Icon.import />
      <p>Nenhum mês carregado. Importe PDFs em <strong>Importar PDFs</strong>.</p>
    </div>
  );

  const cList = Object.values(month.carteiras);
  const hasCorrigir = cList.some(c => c.status === 'CORRIGIR');
  const corrigirList = cList.filter(c => c.status === 'CORRIGIR');

  const filtered = cList
    .filter(c => {
      if (filter === 'LIBERAR')            return c.status === 'LIBERAR';
      if (filter === 'COM ALERTA')         return c.status === 'LIBERAR COM ALERTA';
      if (filter === 'CORRIGIR')           return c.status === 'CORRIGIR';
      return true;
    })
    .filter(c => !search || c.nome.toLowerCase().includes(search.toLowerCase()))
    .sort((a, b) => {
      const av = a[sortCol] ?? 0, bv = b[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>
    );
  }

  return (
    <div>
      {/* CORRIGIR banner */}
      {hasCorrigir && (
        <div className="alert-banner">
          <Icon.alert />
          <span>
            <strong>{corrigirList.length} carteira{corrigirList.length > 1 ? 's' : ''} bloqueada{corrigirList.length > 1 ? 's' : ''} — </strong>
            {corrigirList.map(c => (
              <a key={c.nome} onClick={() => onSelectCarteira(c.nome)} style={{ marginRight: 8 }}>{c.nome}</a>
            ))}
            aguarda revisão do gestor.
          </span>
        </div>
      )}

      {/* KPI strip */}
      <div className="kpi-strip">
        <div className="kpi-tile">
          <div className="kpi-tile-label">Carteiras</div>
          <div className="kpi-tile-value">{month.totals.total}</div>
          <div className="kpi-tile-sub">{month.label}</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">Liberar</div>
          <div className="kpi-tile-value green">{month.totals.liberar}</div>
          <div className="kpi-tile-sub">{Math.round(100*month.totals.liberar/month.totals.total)}% sem ressalvas</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">Com alerta</div>
          <div className="kpi-tile-value amber">{month.totals.alerta}</div>
          <div className="kpi-tile-sub">monitorar antes do fechamento</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">Corrigir</div>
          <div className="kpi-tile-value red">{month.totals.corrigir}</div>
          <div className="kpi-tile-sub">bloqueia liberação</div>
        </div>
        <div className="kpi-tile">
          <div className="kpi-tile-label">PL {month.label}</div>
          <div className="kpi-tile-value" style={{ fontSize: '1.35rem' }}>{fmtBRL(month.plTotal, true)}</div>
          <div className="kpi-tile-sub" style={{ fontFamily: 'JetBrains Mono', fontSize: '0.68rem' }}>
            {fmtPct((month.plTotal - month.plBaseline) / (month.plBaseline||1))} vs {month.baselineLabel || 'mês anterior'}
          </div>
        </div>
          <div className="kpi-tile">
            <div className="kpi-tile-label">USD/BRL</div>
            <div className="kpi-tile-value" style={{ fontSize:'1.35rem' }}>{fxRate ? `R$ ${fxRate.toFixed(2)}` : '—'}</div>
            <div className="kpi-tile-sub">câmbio spot · Brapi</div>
          </div>
      </div>

      {/* Table */}
      <div className="card">
        <div className="filter-bar">
          {['Todos','LIBERAR','COM ALERTA','CORRIGIR'].map(f => (
            <button key={f} className={`filter-tab${filter===f?' active':''}`} onClick={() => setFilter(f)}>{f}</button>
          ))}
          {months && months.length > 0 && onMonthSelect && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginLeft: 4 }}>
              <span style={{ fontSize: '0.65rem', color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Mês</span>
              <select
                value={activeMonthKey || ''}
                onChange={e => onMonthSelect(e.target.value)}
                className="filter-month-select"
                style={{
                  padding: '5px 28px 5px 12px',
                  fontSize: '0.72rem',
                  fontWeight: 500,
                  letterSpacing: '0.04em',
                  border: '1px solid var(--rule)',
                  borderRadius: 2,
                  background: 'var(--white)',
                  color: 'var(--body)',
                  cursor: 'pointer',
                  appearance: 'none',
                  WebkitAppearance: 'none',
                  MozAppearance: 'none',
                  backgroundImage: "url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%239A9188' stroke-width='1.4' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E\")",
                  backgroundRepeat: 'no-repeat',
                  backgroundPosition: 'right 10px center',
                }}
                title="Selecione o mês"
              >
                {months.map(m => (
                  <option key={m.key} value={m.key}>{m.label}</option>
                ))}
              </select>
            </div>
          )}
          <input className="search-input" placeholder="Buscar carteira…" value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table className="tbl">
            <thead>
              <tr>
                <Th col="nome" cls="">Carteira</Th>
                <th>Status</th>
                <Th col="plAnterior" cls="r">PL Anterior</Th>
                <Th col="plAtual" cls="r">PL Atual</Th>
                <Th col="varRS" cls="r">Variação R$</Th>
                <Th col="varPct" cls="r">Var %</Th>
                <Th col="rentMes" cls="r">Rent. Mês</Th>
                <th className="r" style={{ whiteSpace:'nowrap' }}>% CDI</th>
                <th className="r">Ativos</th>
                <th>Achados</th>
                <th style={{ width: 40 }}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(c => {
                const rowCls = c.status === 'CORRIGIR' ? 'tbl-row-corrigir' : c.status === 'LIBERAR COM ALERTA' ? 'tbl-row-alert' : '';
                return (
                  <tr key={c.nome} className={rowCls}>
                    <td className="nome" onClick={() => onSelectCarteira(c.nome)}>{c.nome}</td>
                    <td><span className={`badge ${statusBadge(c.status)}`}>{c.status}</span></td>
                    <td className="num">{fmtBRL(c.plAnterior)}</td>
                    <td className="num">{fmtBRL(c.plAtual)}</td>
                    <td className={`num ${colorClass(c.varRS)}`}>{fmtBRL(c.varRS)}</td>
                    <td className={`num ${colorClass(c.varPct)}`}>{fmtPct(c.varPct)}</td>
                    <td className={`num ${colorClass(c.rentMes)}`}>{fmtPct(c.rentMes)}</td>
                    <td className="num" style={{ whiteSpace:'nowrap' }}>
                      {(() => {
                        const pct = window.calcPctCDI?.(c.rentMes, month.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, fontFamily:'JetBrains Mono', fontSize:'0.76rem', fontWeight:600 }}>{Math.round(pct)}%</span>;
                      })()}
                    </td>
                    <td className="num">{c.nAtivosMar||c.nAtivosAbr ? `${c.nAtivosMar||'?'}→${c.nAtivosAbr||'?'}` : '—'}</td>
                    <td style={{ fontSize: '0.72rem', maxWidth: 200, color: 'var(--muted)' }}>
                      {c.erros !== '-' ? <span style={{ color: 'var(--red)' }}>● </span> : null}
                      {c.alertas !== '-' ? <span style={{ color: 'var(--amber)' }}>● </span> : null}
                      {c.erros === '-' && c.alertas === '-' ? '—' : (c.erros !== '-' ? c.erros.split(' | ')[0].slice(0,60) : c.alertas.split(' | ')[0].slice(0,60))}
                    </td>
                    <td style={{ textAlign: 'center' }}>
                      <button
                        title="Excluir carteira"
                        onClick={e => { e.stopPropagation(); setToDelete({ nome: c.nome }); setDeleteScope('month'); }}
                        style={{
                          width: 24, height: 24, borderRadius: 4, padding: 0,
                          color: 'var(--muted)', background: 'transparent',
                          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                          transition: 'all 0.12s',
                        }}
                        onMouseEnter={e => { e.currentTarget.style.background = 'var(--red-bg)'; e.currentTarget.style.color = 'var(--red)'; }}
                        onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--muted)'; }}
                      >
                        <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
                          <path d="M3 4h7M5 2h3M5 4v6M8 4v6M4 4l.5 7a1 1 0 001 1h2a1 1 0 001-1L9 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </button>
                    </td>
                  </tr>
                );
              })}
              {filtered.length === 0 && (
                <tr><td colSpan={10} style={{ textAlign: 'center', padding: 32, color: 'var(--muted)' }}>Nenhuma carteira encontrada.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Delete confirmation modal */}
      <Modal
        open={!!toDelete}
        onClose={() => setToDelete(null)}
        title="Excluir Carteira"
        footer={<>
          <button className="btn btn-secondary" onClick={() => setToDelete(null)}>Cancelar</button>
          <button
            className="btn btn-danger"
            onClick={() => {
              if (deleteScope === 'all') Store.deleteCarteiraAllMonths(toDelete.nome);
              else Store.deleteCarteira(month.key, toDelete.nome);
              setToDelete(null);
              if (onMonthChange) onMonthChange(month.key);
            }}
          >Excluir</button>
        </>}
      >
        {toDelete && (
          <div>
            <p style={{ fontSize: '0.88rem', marginBottom: 16 }}>
              Confirma a exclusão da carteira <strong style={{ color: 'var(--heading)' }}>{toDelete.nome}</strong>?
            </p>
            <div style={{ marginBottom: 8 }}>
              <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px', border: `1px solid ${deleteScope === 'month' ? 'var(--navy)' : 'var(--rule)'}`, cursor: 'pointer', marginBottom: 8 }}>
                <input type="radio" name="scope" checked={deleteScope === 'month'} onChange={() => setDeleteScope('month')} style={{ marginTop: 2 }} />
                <div>
                  <div style={{ fontSize: '0.82rem', fontWeight: 500, color: 'var(--heading)' }}>Apenas deste mês</div>
                  <div style={{ fontSize: '0.7rem', color: 'var(--muted)', marginTop: 2 }}>Remove só de <strong>{month.label}</strong>; histórico em outros meses permanece.</div>
                </div>
              </label>
              <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px', border: `1px solid ${deleteScope === 'all' ? 'var(--red)' : 'var(--rule)'}`, cursor: 'pointer' }}>
                <input type="radio" name="scope" checked={deleteScope === 'all'} onChange={() => setDeleteScope('all')} style={{ marginTop: 2 }} />
                <div>
                  <div style={{ fontSize: '0.82rem', fontWeight: 500, color: 'var(--red)' }}>De todos os meses</div>
                  <div style={{ fontSize: '0.7rem', color: 'var(--muted)', marginTop: 2 }}>Remove a carteira de Jan, Fev, Mar, Abr — todo o histórico. Esta ação não pode ser desfeita.</div>
                </div>
              </label>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

Object.assign(window, { DashboardView });
