// Wave 2a — Financeiro (5 telas): Fluxo, Lançamentos, Bancos, Conciliação, Contratos
// Uses shared atoms from pages_dashboards.jsx: PageContainer, Tile, Spark, Donut, Bars.

// =============================================================
// 1. Fluxo de Caixa
// =============================================================
const PageFluxo = ({ onNavigate }) => {
  const [range, setRange] = React.useState('6m');
  const labels = ['Nov', 'Dez', 'Jan', 'Fev', 'Mar', 'Abr'];
  const entradas = [68400, 74200, 71800, 82300, 85900, 91200];
  const saidas   = [41200, 44100, 46700, 48900, 51200, 52900];

  return (
    <AppShell current="fluxo" onNavigate={onNavigate}>
      <PageContainer
        title="Fluxo de Caixa"
        subtitle="Entradas × saídas com projeção automática para os próximos 30 dias."
        actions={<>
          <select style={selectStyle}>
            <option>Todas as contas (5)</option>
            <option>Itaú Empresarial</option>
            <option>Banco do Brasil</option>
            <option>Nubank PJ</option>
          </select>
          <div style={{ display: 'inline-flex', background: 'var(--bg-2)', border: '1px solid var(--line-2)', borderRadius: 8, padding: 3 }}>
            {['30d', '3m', '6m', '12m'].map(r => (
              <button key={r} onClick={() => setRange(r)} style={{
                padding: '6px 12px', fontSize: 12, borderRadius: 6, fontWeight: 500,
                background: range === r ? 'var(--bg-3)' : 'transparent',
                color: range === r ? 'var(--text-0)' : 'var(--text-3)',
              }}>{r}</button>
            ))}
          </div>
          <button className="btn btn-outline btn-sm"><Icon name="download" size={13}/> Exportar</button>
          <button className="btn btn-primary btn-sm"><Icon name="plus" size={13}/> Novo lançamento</button>
        </>}
      >
        <div className="row-4" style={{ marginBottom: 18 }}>
          <Tile icon="wallet" label="Saldo consolidado hoje" value={BRL(284720.40)} delta="+R$ 12.340" sub="5 contas"/>
          <Tile icon="trending-up" label="Entradas abril" value={BRL(91200)} delta="+6,2%" sub="vs. março"/>
          <Tile icon="minus-circle" label="Saídas abril" value={BRL(52900)} delta="+3,3%" deltaDir="up"/>
          <Tile icon="sparkle" label="Projeção +30d" value={BRL(324800)} sub="Com base em recorrentes" accent="rgba(139,92,246,.2)"/>
        </div>

        <div className="tile" style={{ marginBottom: 18 }}>
          <div className="tile-head">
            <div className="sect-title">Entradas × Saídas · últimos 6 meses</div>
            <span className="grow"/>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--text-2)' }}>
              <span className="dot" style={{ background: '#22c55e' }}/>Entradas
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--text-2)' }}>
              <span className="dot" style={{ background: '#ef4444' }}/>Saídas
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--text-2)' }}>
              <span className="dot" style={{ background: 'var(--accent-1)' }}/>Saldo
            </span>
          </div>
          <CashflowChart labels={labels} entradas={entradas} saidas={saidas}/>
        </div>

        <div className="row-2">
          <div className="tile">
            <div className="tile-head">
              <Icon name="arrowDown" size={14} color="#22c55e"/>
              <div className="sect-title">Contas a receber · próximos 30d</div>
              <span className="grow"/>
              <button className="btn btn-outline btn-sm" onClick={() => onNavigate('faturas')}>Ver tudo</button>
            </div>
            <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--text-0)', fontVariantNumeric: 'tabular-nums', marginBottom: 2 }}>{BRL(48290)}</div>
            <div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 14 }}>16 faturas em aberto · 2 em atraso</div>
            {[
              { name: 'Supermercado Vila Rica', date: '22/abr', val: 8400, overdue: false },
              { name: 'Distribuidora RC', date: '25/abr', val: 3200, overdue: false },
              { name: 'Hamburgueria 22', date: '18/abr', val: 1240, overdue: true },
              { name: 'Farmácia Bem Estar', date: '28/abr', val: 960, overdue: false },
            ].map((r, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < 3 ? '1px solid var(--line-1)' : 'none' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: 'var(--text-0)', fontWeight: 500 }}>{r.name}</div>
                  <div style={{ fontSize: 11.5, color: r.overdue ? '#fca5a5' : 'var(--text-3)' }}>
                    {r.overdue ? '⚠ ' : ''}Vence {r.date}
                  </div>
                </div>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#86efac', fontVariantNumeric: 'tabular-nums' }}>{BRL(r.val)}</div>
              </div>
            ))}
          </div>
          <div className="tile">
            <div className="tile-head">
              <Icon name="arrowUp" size={14} color="#ef4444"/>
              <div className="sect-title">Contas a pagar · próximos 30d</div>
              <span className="grow"/>
              <button className="btn btn-outline btn-sm" onClick={() => onNavigate('despesas')}>Ver tudo</button>
            </div>
            <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--text-0)', fontVariantNumeric: 'tabular-nums', marginBottom: 2 }}>{BRL(31840)}</div>
            <div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 14 }}>22 despesas · 4 agendadas para hoje</div>
            {[
              { name: 'Folha CLT · Abril/26', date: '25/abr', val: 14820, cat: 'RH' },
              { name: 'Aluguel sede', date: '10/mai', val: 4200, cat: 'Imóvel' },
              { name: 'Fornecedor Farinha SP', date: '22/abr', val: 3680, cat: 'Insumos' },
              { name: 'Energia CEMIG', date: '19/abr', val: 1240, cat: 'Utilidades' },
            ].map((r, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < 3 ? '1px solid var(--line-1)' : 'none' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: 'var(--text-0)', fontWeight: 500 }}>{r.name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{r.cat} · Vence {r.date}</div>
                </div>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#fca5a5', fontVariantNumeric: 'tabular-nums' }}>-{BRL(r.val)}</div>
              </div>
            ))}
          </div>
        </div>
      </PageContainer>
    </AppShell>
  );
};

const CashflowChart = ({ labels, entradas, saidas }) => {
  const saldo = entradas.map((e, i) => e - saidas[i]);
  const all = [...entradas, ...saidas];
  const max = Math.max(...all) * 1.1, min = 0;
  const w = 1000, h = 280, pad = 40;
  const line = (data, color) => {
    const pts = data.map((v, i) => [pad + i * ((w - pad * 2) / (data.length - 1)), h - pad - ((v - min) / (max - min)) * (h - pad * 2)]);
    const path = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
    return { path, pts };
  };
  const ent = line(entradas, '#22c55e');
  const sai = line(saidas, '#ef4444');
  const sal = line(saldo, 'var(--accent-1)');
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: 280 }} preserveAspectRatio="none">
      <defs>
        <linearGradient id="entGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#22c55e" stopOpacity=".2"/>
          <stop offset="1" stopColor="#22c55e" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {[0,1,2,3,4].map(i => {
        const y = pad + i * ((h - pad*2) / 4);
        return (
          <g key={i}>
            <line x1={pad} x2={w-pad} y1={y} y2={y} stroke="rgba(255,255,255,.06)"/>
            <text x={pad-8} y={y+4} fill="rgba(255,255,255,.35)" fontSize="10" textAnchor="end">{BRLShort(max - i * ((max-min)/4))}</text>
          </g>
        );
      })}
      <path d={`${ent.path} L${ent.pts[ent.pts.length-1][0]},${h-pad} L${ent.pts[0][0]},${h-pad} Z`} fill="url(#entGrad)"/>
      <path d={ent.path} fill="none" stroke="#22c55e" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
      <path d={sai.path} fill="none" stroke="#ef4444" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
      <path d={sal.path} fill="none" stroke="var(--accent-1)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="0"/>
      {ent.pts.map((p, i) => <circle key={'e'+i} cx={p[0]} cy={p[1]} r="4" fill="#0c0b1a" stroke="#22c55e" strokeWidth="2"/>)}
      {sai.pts.map((p, i) => <circle key={'s'+i} cx={p[0]} cy={p[1]} r="4" fill="#0c0b1a" stroke="#ef4444" strokeWidth="2"/>)}
      {sal.pts.map((p, i) => <circle key={'sal'+i} cx={p[0]} cy={p[1]} r="3.5" fill="var(--accent-1)"/>)}
      {labels.map((l, i) => (
        <text key={i} x={pad + i * ((w-pad*2)/(labels.length-1))} y={h-8} fill="rgba(255,255,255,.5)" fontSize="11" textAnchor="middle">{l}</text>
      ))}
    </svg>
  );
};

// =============================================================
// 2. Lançamentos
// =============================================================
const PageLancamentos = ({ onNavigate }) => {
  const [drawer, setDrawer] = React.useState(false);
  const [selected, setSelected] = React.useState(new Set());
  const [filter, setFilter] = React.useState('todos');

  const rows = [
    { id: 101, data: '17/04', desc: 'Venda #2847 · Cliente PF', cat: 'Receita Venda', conta: 'Itaú Emp', tipo: 'entrada', valor: 1249.90, status: 'conciliado' },
    { id: 102, data: '17/04', desc: 'Fornecedor Farinha SP · NF 5892', cat: 'Insumos', conta: 'BB PJ', tipo: 'saida', valor: -3680.00, status: 'pago' },
    { id: 103, data: '16/04', desc: 'Mensalidade Automatiza', cat: 'Software', conta: 'Nubank PJ', tipo: 'saida', valor: -499.00, status: 'pago' },
    { id: 104, data: '16/04', desc: 'Recebimento boleto #18291', cat: 'Receita Venda', conta: 'Itaú Emp', tipo: 'entrada', valor: 3200.00, status: 'conciliado' },
    { id: 105, data: '15/04', desc: 'Supermercado Vila Rica · NF 1204', cat: 'Receita Venda', conta: 'Itaú Emp', tipo: 'entrada', valor: 8400.00, status: 'pendente' },
    { id: 106, data: '15/04', desc: 'Energia Elétrica CEMIG · abril', cat: 'Utilidades', conta: 'BB PJ', tipo: 'saida', valor: -1240.55, status: 'pendente' },
    { id: 107, data: '14/04', desc: 'Comissão Bruno Tavares · mar', cat: 'Folha CLT', conta: 'Itaú Emp', tipo: 'saida', valor: -2480.00, status: 'pago' },
    { id: 108, data: '14/04', desc: 'Tarifa bancária Itaú', cat: 'Taxas', conta: 'Itaú Emp', tipo: 'saida', valor: -89.90, status: 'conciliado' },
    { id: 109, data: '12/04', desc: 'Aporte sócio · Rafael', cat: 'Movimentação', conta: 'Itaú Emp', tipo: 'entrada', valor: 15000.00, status: 'conciliado' },
    { id: 110, data: '10/04', desc: 'Aluguel sede · abril', cat: 'Imóvel', conta: 'BB PJ', tipo: 'saida', valor: -4200.00, status: 'pago' },
    { id: 111, data: '08/04', desc: 'Assinatura NetShoes · devolução', cat: 'Receita Venda', conta: 'Itaú Emp', tipo: 'entrada', valor: 680.00, status: 'conciliado' },
    { id: 112, data: '05/04', desc: 'Folha CLT · março/26', cat: 'Folha CLT', conta: 'Itaú Emp', tipo: 'saida', valor: -14820.00, status: 'pago' },
  ];
  const filtered = filter === 'todos' ? rows : rows.filter(r => r.tipo === filter);
  const toggle = (id) => {
    const s = new Set(selected);
    s.has(id) ? s.delete(id) : s.add(id);
    setSelected(s);
  };
  const statusChip = (s) => ({
    conciliado: { bg: 'rgba(34,197,94,.14)', color: '#86efac', label: 'Conciliado' },
    pago: { bg: 'rgba(59,130,246,.14)', color: '#93c5fd', label: 'Pago' },
    pendente: { bg: 'rgba(245,158,11,.14)', color: '#fcd34d', label: 'Pendente' },
  })[s];

  return (
    <AppShell current="lancamentos" onNavigate={onNavigate}>
      <PageContainer
        title="Lançamentos"
        subtitle="Todas as movimentações financeiras em uma única tabela filtrável."
        actions={<>
          <button className="btn btn-outline btn-sm"><Icon name="download" size={13}/> Exportar CSV</button>
          <button className="btn btn-primary btn-sm" onClick={() => setDrawer(true)}><Icon name="plus" size={13}/> Novo lançamento</button>
        </>}
      >
        <div className="row-4" style={{ marginBottom: 18 }}>
          <Tile icon="arrowDown" label="Entradas mês" value={BRL(28329.90)} delta="+14%" accent="rgba(34,197,94,.2)"/>
          <Tile icon="arrowUp" label="Saídas mês" value={BRL(27009.45)} delta="-3%" deltaDir="down" accent="rgba(239,68,68,.2)"/>
          <Tile icon="circleCheck" label="Conciliados" value="86%" sub="24 pendentes" accent="rgba(59,130,246,.2)"/>
          <Tile icon="cpu" label="Categorizados por IA" value="92%" sub="Auto + confirmação" accent="rgba(139,92,246,.2)"/>
        </div>

        {/* Filter chips + search */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap', alignItems: 'center' }}>
          {[
            { id: 'todos', l: 'Todos', c: rows.length },
            { id: 'entrada', l: 'Entradas', c: rows.filter(r => r.tipo === 'entrada').length },
            { id: 'saida', l: 'Saídas', c: rows.filter(r => r.tipo === 'saida').length },
          ].map(c => (
            <button key={c.id} onClick={() => setFilter(c.id)} style={{
              padding: '7px 12px', fontSize: 12.5, borderRadius: 8, fontWeight: 500,
              background: filter === c.id ? 'var(--accent-soft-14)' : 'var(--bg-2)',
              border: `1px solid ${filter === c.id ? 'var(--accent-soft-55)' : 'var(--line-2)'}`,
              color: filter === c.id ? 'var(--accent-text)' : 'var(--text-2)',
            }}>{c.l} <span style={{ opacity: .6, fontSize: 11 }}>({c.c})</span></button>
          ))}
          <span style={{ flex: 1 }}/>
          <div style={{ position: 'relative' }}>
            <Icon name="search" size={13} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }}/>
            <input placeholder="Buscar por descrição, valor, NF..." style={{
              padding: '8px 12px 8px 32px', borderRadius: 8, fontSize: 12.5, width: 280,
              background: 'var(--bg-2)', border: '1px solid var(--line-2)', color: 'var(--text-1)',
            }}/>
          </div>
          <button className="btn btn-outline btn-sm"><Icon name="filter" size={13}/> Filtros</button>
        </div>

        {/* Bulk actions bar */}
        {selected.size > 0 && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px', marginBottom: 12,
            background: 'var(--accent-soft-14)', border: '1px solid var(--accent-soft-55)', borderRadius: 10,
          }}>
            <Icon name="check" size={14} color="var(--accent-text)"/>
            <span style={{ fontSize: 13, color: 'var(--text-0)' }}>{selected.size} selecionado{selected.size > 1 ? 's' : ''}</span>
            <span style={{ flex: 1 }}/>
            <button className="btn btn-outline btn-sm"><Icon name="tag" size={12}/> Alterar categoria</button>
            <button className="btn btn-outline btn-sm"><Icon name="check" size={12}/> Marcar conciliado</button>
            <button className="btn btn-outline btn-sm" style={{ color: '#fca5a5' }}><Icon name="trash" size={12}/> Excluir</button>
          </div>
        )}

        <div className="table-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 36 }}><input type="checkbox" onChange={(e) => setSelected(e.target.checked ? new Set(filtered.map(r => r.id)) : new Set())}/></th>
                <th>Data</th>
                <th>Descrição</th>
                <th>Categoria</th>
                <th>Conta</th>
                <th style={{ textAlign: 'right' }}>Valor</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(r => {
                const st = statusChip(r.status);
                return (
                  <tr key={r.id} style={{ background: selected.has(r.id) ? 'var(--accent-soft-08)' : 'transparent' }}>
                    <td><input type="checkbox" checked={selected.has(r.id)} onChange={() => toggle(r.id)}/></td>
                    <td style={{ color: 'var(--text-2)', fontVariantNumeric: 'tabular-nums' }}>{r.data}</td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <span style={{
                          width: 28, height: 28, borderRadius: 7, display: 'grid', placeItems: 'center',
                          background: r.tipo === 'entrada' ? 'rgba(34,197,94,.14)' : 'rgba(239,68,68,.14)',
                          color: r.tipo === 'entrada' ? '#86efac' : '#fca5a5',
                        }}>
                          <Icon name={r.tipo === 'entrada' ? 'arrowDown' : 'arrowUp'} size={13}/>
                        </span>
                        <b style={{ color: 'var(--text-0)', fontWeight: 500 }}>{r.desc}</b>
                      </div>
                    </td>
                    <td><span className="chip" style={{ fontSize: 11 }}>{r.cat}</span></td>
                    <td style={{ color: 'var(--text-2)' }}>{r.conta}</td>
                    <td style={{ textAlign: 'right', color: r.valor > 0 ? '#86efac' : '#fca5a5', fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
                      {r.valor > 0 ? '+' : ''}{BRL(Math.abs(r.valor))}
                    </td>
                    <td><span className="chip" style={{ background: st.bg, color: st.color, fontSize: 10.5, fontWeight: 600 }}>{st.label}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div style={{ padding: '12px 18px', display: 'flex', alignItems: 'center', gap: 10, color: 'var(--text-3)', fontSize: 12, borderTop: '1px solid var(--line-1)' }}>
            <span>{filtered.length} de 247 lançamentos</span>
            <span style={{ flex: 1 }}/>
            <button className="btn btn-outline btn-sm" style={{ padding: '4px 10px' }}>Anterior</button>
            <span style={{ fontSize: 12 }}>Página 1 de 21</span>
            <button className="btn btn-outline btn-sm" style={{ padding: '4px 10px' }}>Próximo</button>
          </div>
        </div>

        {drawer && <LancDrawer onClose={() => setDrawer(false)}/>}
      </PageContainer>
    </AppShell>
  );
};

const LancDrawer = ({ onClose }) => {
  const [tipo, setTipo] = React.useState('saida');
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.6)', zIndex: 100, backdropFilter: 'blur(4px)' }}/>
      <div style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 480, zIndex: 101,
        background: 'var(--bg-1)', borderLeft: '1px solid var(--line-2)',
        boxShadow: '-24px 0 60px rgba(0,0,0,.6)', overflowY: 'auto',
        animation: 'slideLeft .25s ease',
      }}>
        <style>{`@keyframes slideLeft { from { transform: translateX(100%); } to { transform: translateX(0); } }`}</style>
        <div style={{ padding: '22px 26px', borderBottom: '1px solid var(--line-1)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: 'var(--text-0)', letterSpacing: '-.01em' }}>Novo lançamento</h2>
          <span style={{ flex: 1 }}/>
          <button onClick={onClose} className="shell-top-btn" style={{ width: 32, height: 32 }}><Icon name="x" size={14}/></button>
        </div>
        <div style={{ padding: 26, display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* Tipo toggle */}
          <div>
            <label style={drawerLabel}>Tipo</label>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {[
                { id: 'entrada', l: 'Entrada', icon: 'arrowDown', color: '#22c55e' },
                { id: 'saida', l: 'Saída', icon: 'arrowUp', color: '#ef4444' },
              ].map(t => (
                <button key={t.id} onClick={() => setTipo(t.id)} style={{
                  padding: '14px', borderRadius: 10, fontSize: 13, fontWeight: 500,
                  background: tipo === t.id ? t.color + '22' : 'var(--bg-2)',
                  border: `1px solid ${tipo === t.id ? t.color : 'var(--line-2)'}`,
                  color: tipo === t.id ? t.color : 'var(--text-2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                }}>
                  <Icon name={t.icon} size={15}/> {t.l}
                </button>
              ))}
            </div>
          </div>

          <DField label="Descrição" placeholder="Ex: Pagamento fornecedor NF 1234"/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <DField label="Valor" placeholder="R$ 0,00" prefix="R$"/>
            <DField label="Data" type="date" defaultValue="2026-04-17"/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <DField label="Categoria" select options={['Insumos', 'Software', 'Folha CLT', 'Utilidades', 'Receita Venda', 'Movimentação', 'Taxas']}/>
            <DField label="Conta" select options={['Itaú Empresarial', 'BB PJ', 'Nubank PJ', 'Caixa']}/>
          </div>
          <DField label="Observações" textarea placeholder="Notas internas, comprovante..."/>

          <div style={{ padding: 14, background: 'var(--accent-soft-10)', border: '1px solid var(--accent-soft-30)', borderRadius: 10, display: 'flex', gap: 10 }}>
            <Icon name="sparkle" size={16} color="var(--accent-text)"/>
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-0)', marginBottom: 2 }}>IA sugere: "Insumos"</div>
              <div style={{ fontSize: 11.5, color: 'var(--text-2)', lineHeight: 1.4 }}>Com base em padrões anteriores de "Farinha SP" (92% de confiança).</div>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
            <button onClick={onClose} className="btn btn-outline" style={{ flex: 1 }}>Cancelar</button>
            <button className="btn btn-primary" style={{ flex: 1 }}><Icon name="check" size={14}/> Salvar</button>
          </div>
        </div>
      </div>
    </>
  );
};

const drawerLabel = { fontSize: 12, fontWeight: 500, color: 'var(--text-2)', display: 'block', marginBottom: 6 };
const DField = ({ label, placeholder, prefix, type = 'text', defaultValue, select, options = [], textarea }) => (
  <div>
    <label style={drawerLabel}>{label}</label>
    {select ? (
      <select style={drawerInput}><option>Selecionar...</option>{options.map(o => <option key={o}>{o}</option>)}</select>
    ) : textarea ? (
      <textarea placeholder={placeholder} style={{ ...drawerInput, minHeight: 80, resize: 'vertical', fontFamily: 'inherit' }}/>
    ) : (
      <div style={{ position: 'relative' }}>
        {prefix && <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)', fontSize: 13 }}>{prefix}</span>}
        <input type={type} placeholder={placeholder} defaultValue={defaultValue} style={{ ...drawerInput, paddingLeft: prefix ? 38 : 12 }}/>
      </div>
    )}
  </div>
);
const drawerInput = {
  width: '100%', padding: '10px 12px', borderRadius: 8, fontSize: 13,
  background: 'var(--bg-2)', border: '1px solid var(--line-2)', color: 'var(--text-0)',
};
const selectStyle = {
  padding: '7px 12px', borderRadius: 8, fontSize: 12.5,
  background: 'var(--bg-2)', border: '1px solid var(--line-2)', color: 'var(--text-1)',
};

// =============================================================
// 3. Contas Bancárias
// =============================================================
const PageBancos = ({ onNavigate }) => {
  const bancos = [
    { id: 1, nome: 'Itaú Empresarial', agencia: '0412', conta: '18293-4', saldo: 187420.40, sync: 'há 12 min', status: 'sync', color: '#ec7000', bg: '#ec7000', short: 'ITÚ' },
    { id: 2, nome: 'Banco do Brasil PJ', agencia: '1847', conta: '29-018428-3', saldo: 62840.00, sync: 'há 1h', status: 'sync', color: '#fcc200', bg: '#003469', short: 'BB' },
    { id: 3, nome: 'Nubank PJ', agencia: '0001', conta: '82947-1', saldo: 24180.00, sync: 'há 34 min', status: 'sync', color: '#8a05be', bg: '#8a05be', short: 'NU' },
    { id: 4, nome: 'Caixa Tesouraria', agencia: '3215', conta: '0093-4', saldo: 8420.00, sync: 'há 3 dias', status: 'stale', color: '#0070af', bg: '#0070af', short: 'CEF' },
    { id: 5, nome: 'Inter PJ', agencia: '0001', conta: '10293-8', saldo: 1860.00, sync: 'erro', status: 'error', color: '#ff7a00', bg: '#ff7a00', short: 'INT' },
  ];
  const total = bancos.reduce((s, b) => s + b.saldo, 0);
  return (
    <AppShell current="bancos" onNavigate={onNavigate}>
      <PageContainer
        title="Contas Bancárias"
        subtitle="Saldos consolidados em tempo real via Open Finance · 5 instituições conectadas."
        actions={<>
          <button className="btn btn-outline btn-sm"><Icon name="sync" size={13}/> Sincronizar tudo</button>
          <button className="btn btn-primary btn-sm"><Icon name="plus" size={13}/> Conectar conta</button>
        </>}
      >
        <div className="row-4" style={{ marginBottom: 22 }}>
          <Tile icon="wallet" label="Saldo consolidado" value={BRL(total)} sub="5 contas ativas"/>
          <Tile icon="trending-up" label="Variação 30d" value="+R$ 24.180" delta="+9,3%"/>
          <Tile icon="sync" label="Última sincronia" value="há 12 min" sub="Itaú Emp"/>
          <Tile icon="alert" label="Contas com erro" value="1" sub="Inter PJ · reconectar" accent="rgba(239,68,68,.18)"/>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 16 }}>
          {bancos.map(b => (
            <div key={b.id} className="tile" style={{ padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
              <div style={{
                padding: '18px 20px', background: `linear-gradient(135deg, ${b.bg} 0%, ${b.bg}cc 100%)`,
                display: 'flex', alignItems: 'center', gap: 14,
              }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 12,
                  background: 'rgba(255,255,255,.18)',
                  display: 'grid', placeItems: 'center', color: 'white',
                  fontWeight: 800, fontSize: 14, letterSpacing: '-.02em',
                  backdropFilter: 'blur(8px)', border: '1px solid rgba(255,255,255,.25)',
                }}>{b.short}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ color: 'white', fontWeight: 700, fontSize: 15 }}>{b.nome}</div>
                  <div style={{ color: 'rgba(255,255,255,.8)', fontSize: 11, fontVariantNumeric: 'tabular-nums' }}>Ag {b.agencia} · CC {b.conta}</div>
                </div>
                <button style={{ width: 32, height: 32, borderRadius: 8, background: 'rgba(255,255,255,.15)', color: 'white', display: 'grid', placeItems: 'center', border: '1px solid rgba(255,255,255,.2)' }}>
                  <Icon name="dots" size={14}/>
                </button>
              </div>
              <div style={{ padding: 20, flex: 1 }}>
                <div style={{ fontSize: 11.5, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 4 }}>Saldo atual</div>
                <div style={{ fontSize: 26, fontWeight: 700, color: 'var(--text-0)', fontVariantNumeric: 'tabular-nums', letterSpacing: '-.02em', marginBottom: 14 }}>{BRL(b.saldo)}</div>
                <Spark data={Array.from({ length: 20 }, (_, i) => b.saldo * (0.9 + Math.sin(i) * 0.05 + i * 0.006))} stroke="var(--accent-text-2)" fill="var(--accent-soft-14)" height={36}/>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--line-1)' }}>
                  {b.status === 'sync' && <><span className="dot" style={{ background: '#22c55e' }}/><span style={{ fontSize: 12, color: 'var(--text-2)' }}>Sincronizado {b.sync}</span></>}
                  {b.status === 'stale' && <><span className="dot" style={{ background: '#f59e0b' }}/><span style={{ fontSize: 12, color: '#fcd34d' }}>Desatualizado · {b.sync}</span></>}
                  {b.status === 'error' && <><span className="dot" style={{ background: '#ef4444' }}/><span style={{ fontSize: 12, color: '#fca5a5' }}>Erro na conexão</span></>}
                  <span style={{ flex: 1 }}/>
                  {b.status === 'error' ? (
                    <button className="btn btn-outline btn-sm" style={{ padding: '5px 10px', color: '#fca5a5', borderColor: 'rgba(239,68,68,.3)' }}>Reconectar</button>
                  ) : (
                    <button className="btn btn-outline btn-sm" style={{ padding: '5px 10px' }}>Extrato</button>
                  )}
                </div>
              </div>
            </div>
          ))}

          {/* Connect new card */}
          <button className="tile" style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            minHeight: 260, gap: 14, border: '2px dashed var(--line-3)', background: 'transparent', cursor: 'pointer',
          }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: 'var(--brand-gradient)', display: 'grid', placeItems: 'center' }}>
              <Icon name="plus" size={26} color="white"/>
            </div>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-0)' }}>Conectar nova conta</div>
            <div style={{ fontSize: 12, color: 'var(--text-3)', textAlign: 'center', maxWidth: 260, lineHeight: 1.5 }}>
              Via Open Finance — conecte qualquer banco regulado pelo BACEN em 2 minutos.
            </div>
          </button>
        </div>

        {/* Open finance partners */}
        <div className="tile" style={{ marginTop: 20 }}>
          <div className="tile-head">
            <span style={{ width: 28, height: 28, borderRadius: 7, background: 'rgba(34,197,94,.14)', color: '#86efac', display: 'grid', placeItems: 'center' }}><Icon name="shield" size={13}/></span>
            <div className="sect-title">Bancos suportados · certificados BACEN</div>
            <span className="grow"/>
            <span className="chip chip-green">Open Finance v3.0</span>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
            {['Itaú', 'Bradesco', 'Santander', 'Banco do Brasil', 'Caixa', 'Nubank', 'Inter', 'Sicoob', 'Sicredi', 'BTG Pactual', 'C6 Bank', 'Banrisul', 'XP', 'Original'].map(b => (
              <span key={b} style={{
                padding: '8px 14px', background: 'var(--bg-1)', border: '1px solid var(--line-2)',
                borderRadius: 8, fontSize: 12.5, color: 'var(--text-1)', fontWeight: 500,
              }}>{b}</span>
            ))}
            <span style={{ padding: '8px 14px', fontSize: 12, color: 'var(--text-3)' }}>+ 35 outros</span>
          </div>
        </div>
      </PageContainer>
    </AppShell>
  );
};

// =============================================================
// 4. Conciliação OFX (split view)
// =============================================================
const PageConciliacao = ({ onNavigate }) => {
  const [matches, setMatches] = React.useState({ m1: true, m2: true, m3: false, m4: true });
  const toggle = (k) => setMatches({ ...matches, [k]: !matches[k] });
  const confidence = (score) => {
    if (score >= 95) return { c: '#22c55e', l: 'Alta' };
    if (score >= 80) return { c: '#f59e0b', l: 'Média' };
    return { c: '#ef4444', l: 'Baixa' };
  };
  const suggestions = [
    { id: 'm1', score: 98, ofx: { date: '17/04', desc: 'TED RECEBIDA SUPERMERCADO VILA RICA ME', val: 8400 }, sys: { date: '15/04', desc: 'Supermercado Vila Rica · NF 1204', val: 8400 }},
    { id: 'm2', score: 95, ofx: { date: '17/04', desc: 'PAG FORNECEDOR FARINHA SP NF5892', val: -3680 }, sys: { date: '17/04', desc: 'Fornecedor Farinha SP · NF 5892', val: -3680 }},
    { id: 'm3', score: 82, ofx: { date: '16/04', desc: 'PIX CPF ***.458.291-**', val: 1249.90 }, sys: { date: '17/04', desc: 'Venda #2847 · Cliente PF', val: 1249.90 }},
    { id: 'm4', score: 99, ofx: { date: '16/04', desc: 'DEB AUTOMATIZA TECH MENSALIDADE', val: -499 }, sys: { date: '16/04', desc: 'Mensalidade Automatiza', val: -499 }},
  ];
  return (
    <AppShell current="conciliacao" onNavigate={onNavigate}>
      <PageContainer
        title="Conciliação Bancária"
        subtitle="A IA sugere correspondências entre o extrato OFX e os lançamentos do sistema. Confirme ou arraste para reconciliar."
        maxWidth={1680}
        actions={<>
          <select style={selectStyle}>
            <option>Itaú Empresarial</option>
            <option>Banco do Brasil PJ</option>
          </select>
          <button className="btn btn-outline btn-sm"><Icon name="upload" size={13}/> Importar OFX</button>
          <button className="btn btn-primary btn-sm"><Icon name="check" size={13}/> Confirmar todos (3)</button>
        </>}
      >
        <div className="row-4" style={{ marginBottom: 18 }}>
          <Tile icon="file" label="Transações no extrato" value="47"/>
          <Tile icon="sparkle" label="Sugestões da IA" value="38" delta="95% confiança" accent="rgba(139,92,246,.2)"/>
          <Tile icon="circleCheck" label="Já conciliadas" value="34" sub="72%" accent="rgba(34,197,94,.2)"/>
          <Tile icon="alert" label="Não identificadas" value="5" sub="Requer atenção" accent="rgba(245,158,11,.2)"/>
        </div>

        {/* Suggestions matching IA */}
        <div className="tile" style={{ marginBottom: 18, padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--line-1)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--brand-gradient)', display: 'grid', placeItems: 'center' }}>
              <Icon name="sparkle" size={15} color="white"/>
            </span>
            <div>
              <div className="sect-title">Correspondências sugeridas pela IA</div>
              <div className="sect-sub">Matches automáticos por valor, data e texto · 4 de 38 exibidos</div>
            </div>
          </div>
          {suggestions.map((s, i) => {
            const conf = confidence(s.score);
            const checked = matches[s.id];
            return (
              <div key={s.id} style={{
                display: 'grid', gridTemplateColumns: '1fr 64px 1fr 150px', gap: 16,
                padding: '16px 20px', borderBottom: i < 3 ? '1px solid var(--line-1)' : 'none',
                alignItems: 'center', background: checked ? 'rgba(34,197,94,.04)' : 'transparent',
                transition: 'background 180ms',
              }}>
                {/* OFX side */}
                <div style={{ padding: 14, background: 'var(--bg-1)', borderRadius: 10, border: '1px solid var(--line-1)' }}>
                  <div style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 4 }}>
                    <Icon name="file" size={10}/> Extrato OFX · {s.ofx.date}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--text-0)', fontWeight: 500, marginBottom: 2, fontFamily: 'var(--font-mono)' }}>{s.ofx.desc}</div>
                  <div style={{ fontSize: 15, fontWeight: 700, color: s.ofx.val > 0 ? '#86efac' : '#fca5a5', fontVariantNumeric: 'tabular-nums' }}>
                    {s.ofx.val > 0 ? '+' : ''}{BRL(Math.abs(s.ofx.val))}
                  </div>
                </div>
                {/* Match indicator */}
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                  <div style={{
                    width: 40, height: 40, borderRadius: 10,
                    background: `conic-gradient(${conf.c} ${s.score * 3.6}deg, var(--bg-3) 0)`,
                    display: 'grid', placeItems: 'center', position: 'relative',
                  }}>
                    <div style={{ position: 'absolute', inset: 4, background: 'var(--bg-2)', borderRadius: 8, display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700, color: conf.c }}>
                      {s.score}%
                    </div>
                  </div>
                  <div style={{ fontSize: 10, color: conf.c, fontWeight: 600 }}>{conf.l}</div>
                </div>
                {/* System side */}
                <div style={{ padding: 14, background: 'var(--bg-1)', borderRadius: 10, border: '1px solid var(--line-1)' }}>
                  <div style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 4 }}>
                    <Icon name="receipt" size={10}/> Sistema · {s.sys.date}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--text-0)', fontWeight: 500, marginBottom: 2 }}>{s.sys.desc}</div>
                  <div style={{ fontSize: 15, fontWeight: 700, color: s.sys.val > 0 ? '#86efac' : '#fca5a5', fontVariantNumeric: 'tabular-nums' }}>
                    {s.sys.val > 0 ? '+' : ''}{BRL(Math.abs(s.sys.val))}
                  </div>
                </div>
                {/* Actions */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <button onClick={() => toggle(s.id)} className={checked ? 'btn btn-primary btn-sm' : 'btn btn-outline btn-sm'} style={{ padding: '6px 10px', fontSize: 11.5 }}>
                    <Icon name={checked ? 'check' : 'link'} size={12}/> {checked ? 'Confirmado' : 'Confirmar'}
                  </button>
                  <button className="btn btn-outline btn-sm" style={{ padding: '6px 10px', fontSize: 11.5 }}>
                    <Icon name="x" size={12}/> Rejeitar
                  </button>
                </div>
              </div>
            );
          })}
        </div>

        {/* Unmatched */}
        <div className="row-2">
          <div className="tile">
            <div className="tile-head">
              <Icon name="file" size={14} color="var(--text-3)"/>
              <div className="sect-title">Extrato sem correspondência</div>
              <span className="grow"/>
              <span className="chip" style={{ fontSize: 11 }}>3</span>
            </div>
            {[
              { date: '15/04', desc: 'TED ENVIADA PJ BCO FITNESS LTDA', val: -1800 },
              { date: '13/04', desc: 'TARIFA PACOTE SERVIÇOS', val: -49.90 },
              { date: '12/04', desc: 'RENDIMENTO CDB 103%', val: 182.40 },
            ].map((r, i) => (
              <div key={i} style={{ padding: '12px 0', display: 'flex', alignItems: 'center', gap: 10, borderBottom: i < 2 ? '1px solid var(--line-1)' : 'none', cursor: 'grab' }}>
                <Icon name="menu" size={14} color="var(--text-4)"/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text-0)' }}>{r.desc}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-3)' }}>OFX · {r.date}</div>
                </div>
                <div style={{ fontSize: 13, fontWeight: 600, color: r.val > 0 ? '#86efac' : '#fca5a5', fontVariantNumeric: 'tabular-nums' }}>
                  {r.val > 0 ? '+' : ''}{BRL(Math.abs(r.val))}
                </div>
                <button className="btn btn-outline btn-sm" style={{ padding: '5px 8px' }}><Icon name="plus" size={11}/></button>
              </div>
            ))}
          </div>
          <div className="tile">
            <div className="tile-head">
              <Icon name="receipt" size={14} color="var(--text-3)"/>
              <div className="sect-title">Lançamentos sem extrato</div>
              <span className="grow"/>
              <span className="chip" style={{ fontSize: 11 }}>2</span>
            </div>
            {[
              { date: '14/04', desc: 'Comissão Bruno Tavares · mar', val: -2480 },
              { date: '12/04', desc: 'Aporte sócio · Rafael', val: 15000 },
            ].map((r, i) => (
              <div key={i} style={{ padding: '12px 0', display: 'flex', alignItems: 'center', gap: 10, borderBottom: i < 1 ? '1px solid var(--line-1)' : 'none', cursor: 'grab' }}>
                <Icon name="menu" size={14} color="var(--text-4)"/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: 'var(--text-0)' }}>{r.desc}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-3)' }}>Sistema · {r.date}</div>
                </div>
                <div style={{ fontSize: 13, fontWeight: 600, color: r.val > 0 ? '#86efac' : '#fca5a5', fontVariantNumeric: 'tabular-nums' }}>
                  {r.val > 0 ? '+' : ''}{BRL(Math.abs(r.val))}
                </div>
              </div>
            ))}
          </div>
        </div>
      </PageContainer>
    </AppShell>
  );
};

// =============================================================
// 5. Contratos
// =============================================================
const PageContratos = ({ onNavigate }) => {
  const [selected, setSelected] = React.useState(1);
  const contracts = [
    { id: 1, num: 'CT-2026-014', parte: 'Supermercado Vila Rica ME', cnpj: '18.293.472/0001-82', tipo: 'Fornecimento recorrente', valor: 8400, freq: 'mensal', vigencia: '01/04/26 → 31/03/27', dias: 348, status: 'ativo', assinado: true },
    { id: 2, num: 'CT-2026-013', parte: 'Distribuidora RC Ltda', cnpj: '82.471.029/0001-34', tipo: 'Fornecimento recorrente', valor: 3200, freq: 'mensal', vigencia: '15/03/26 → 14/03/27', dias: 331, status: 'ativo', assinado: true },
    { id: 3, num: 'CT-2026-012', parte: 'Construtora AV SA', cnpj: '20.194.028/0001-91', tipo: 'Prestação de serviços', valor: 24000, freq: 'único', vigencia: '01/02/26 → 31/07/26', dias: 105, status: 'expirando', assinado: true },
    { id: 4, num: 'CT-2026-011', parte: 'Mecânica Rápida Eireli', cnpj: '40.201.837/0001-20', tipo: 'Locação equipamento', valor: 1200, freq: 'mensal', vigencia: '10/01/26 → 09/01/27', dias: 267, status: 'ativo', assinado: true },
    { id: 5, num: 'CT-2026-010', parte: 'Hamburgueria 22', cnpj: '31.804.728/0001-01', tipo: 'Fornecimento recorrente', valor: 1240, freq: 'mensal', vigencia: '01/01/26 → 31/12/26', dias: 258, status: 'ativo', assinado: false },
  ];
  const sel = contracts.find(c => c.id === selected);
  const statusStyle = (s) => ({
    ativo: { bg: 'rgba(34,197,94,.14)', c: '#86efac', l: 'Ativo' },
    expirando: { bg: 'rgba(245,158,11,.14)', c: '#fcd34d', l: 'Expira em 105d' },
    encerrado: { bg: 'rgba(239,68,68,.14)', c: '#fca5a5', l: 'Encerrado' },
  })[s];

  return (
    <AppShell current="contratos" onNavigate={onNavigate}>
      <PageContainer
        title="Contratos"
        subtitle="Gestão de contratos ativos, vigências, assinaturas digitais e aditivos."
        maxWidth={1680}
        actions={<>
          <button className="btn btn-outline btn-sm"><Icon name="upload" size={13}/> Importar</button>
          <button className="btn btn-primary btn-sm"><Icon name="plus" size={13}/> Novo contrato</button>
        </>}
      >
        <div className="row-4" style={{ marginBottom: 18 }}>
          <Tile icon="doc" label="Contratos ativos" value="42" sub={`${BRL(186800)} em valor total`}/>
          <Tile icon="clock" label="Expirando em 90d" value="7" sub="Renovar ou encerrar" accent="rgba(245,158,11,.18)"/>
          <Tile icon="check" label="Aguardando assinatura" value="3" accent="rgba(59,130,246,.18)"/>
          <Tile icon="trending-up" label="MRR contratualizado" value={BRL(18480)} delta="+R$ 2.400"/>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 16 }} className="gridC">
          <style>{`@media (max-width: 1280px) { .gridC { grid-template-columns: 1fr !important; } }`}</style>
          {/* List */}
          <div className="table-wrap">
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--line-1)', display: 'flex', gap: 8, alignItems: 'center' }}>
              <input placeholder="Buscar contratos..." style={{
                flex: 1, padding: '7px 10px', borderRadius: 8, fontSize: 12.5,
                background: 'var(--bg-1)', border: '1px solid var(--line-2)', color: 'var(--text-1)',
              }}/>
              <select style={selectStyle}><option>Todos os tipos</option></select>
            </div>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Contrato</th>
                  <th>Parte</th>
                  <th style={{ textAlign: 'right' }}>Valor</th>
                  <th>Vigência</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {contracts.map(c => {
                  const st = statusStyle(c.status);
                  return (
                    <tr key={c.id} onClick={() => setSelected(c.id)} style={{
                      cursor: 'pointer',
                      background: selected === c.id ? 'var(--accent-soft-10)' : 'transparent',
                    }}>
                      <td>
                        <div style={{ fontSize: 12, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>{c.num}</div>
                        <div style={{ fontSize: 12, color: 'var(--text-1)' }}>{c.tipo}</div>
                      </td>
                      <td>
                        <b style={{ color: 'var(--text-0)' }}>{c.parte}</b>
                        <div style={{ fontSize: 11, color: 'var(--text-3)', fontVariantNumeric: 'tabular-nums' }}>{c.cnpj}</div>
                      </td>
                      <td style={{ textAlign: 'right', color: 'var(--text-0)', fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>
                        {BRL(c.valor)}
                        <div style={{ fontSize: 10.5, color: 'var(--text-3)', fontWeight: 400 }}>/{c.freq}</div>
                      </td>
                      <td style={{ fontSize: 11.5, color: 'var(--text-2)' }}>{c.dias} dias restantes</td>
                      <td><span className="chip" style={{ background: st.bg, color: st.c, fontSize: 10.5, fontWeight: 600 }}>{st.l}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Detail */}
          <div className="tile" style={{ padding: 0 }}>
            <div style={{ padding: 20, borderBottom: '1px solid var(--line-1)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <span className="chip chip-brand" style={{ fontSize: 11 }}>{sel.num}</span>
                {(() => { const st = statusStyle(sel.status); return <span className="chip" style={{ background: st.bg, color: st.c, fontSize: 10.5, fontWeight: 600 }}>{st.l}</span>; })()}
                {sel.assinado ? <span className="chip chip-green" style={{ fontSize: 10.5 }}><Icon name="check" size={10}/> Assinado</span> : <span className="chip" style={{ fontSize: 10.5, background: 'rgba(59,130,246,.14)', color: '#93c5fd' }}><Icon name="clock" size={10}/> Aguardando</span>}
              </div>
              <h2 style={{ margin: '2px 0 2px', fontSize: 19, fontWeight: 700, color: 'var(--text-0)', letterSpacing: '-.01em' }}>{sel.parte}</h2>
              <div style={{ fontSize: 13, color: 'var(--text-3)' }}>{sel.tipo} · CNPJ {sel.cnpj}</div>
            </div>

            <div style={{ padding: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, borderBottom: '1px solid var(--line-1)' }}>
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 3 }}>Valor</div>
                <div style={{ fontSize: 20, fontWeight: 700, color: 'var(--text-0)', fontVariantNumeric: 'tabular-nums' }}>{BRL(sel.valor)}</div>
                <div style={{ fontSize: 11, color: 'var(--text-3)' }}>recorrência {sel.freq}</div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 3 }}>Vigência</div>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-0)' }}>{sel.vigencia}</div>
                <div style={{ marginTop: 6, height: 6, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ width: `${Math.min(100, (365 - sel.dias) / 365 * 100)}%`, height: '100%', background: sel.status === 'expirando' ? '#f59e0b' : 'var(--brand-gradient)' }}/>
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 4 }}>{sel.dias} dias restantes</div>
              </div>
            </div>

            <div style={{ padding: 20, borderBottom: '1px solid var(--line-1)' }}>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--text-0)', marginBottom: 10 }}>Cláusulas principais</div>
              {[
                { t: 'Reajuste', v: 'IPCA anual, janela de 30 dias' },
                { t: 'Multa rescisória', v: '3 mensalidades no caso de rescisão antecipada' },
                { t: 'Garantia', v: 'Avalista solidário identificado · CPF ***.472.18**' },
                { t: 'Foro', v: 'Comarca de Belo Horizonte / MG' },
              ].map((c, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 10, padding: '6px 0', fontSize: 12.5 }}>
                  <span style={{ color: 'var(--text-3)' }}>{c.t}</span>
                  <span style={{ color: 'var(--text-1)' }}>{c.v}</span>
                </div>
              ))}
            </div>

            <div style={{ padding: 20, borderBottom: '1px solid var(--line-1)' }}>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--text-0)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon name="file" size={13}/> Anexos (3)
              </div>
              {[
                { n: 'Contrato original.pdf', sz: '284 KB' },
                { n: 'Aditivo 1 · reajuste.pdf', sz: '92 KB' },
                { n: 'Certificado digital ICP-Brasil.p7s', sz: '18 KB' },
              ].map((a, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: i < 2 ? '1px solid var(--line-1)' : 'none' }}>
                  <Icon name="file" size={14} color="var(--accent-text)"/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12.5, color: 'var(--text-0)' }}>{a.n}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-3)' }}>{a.sz}</div>
                  </div>
                  <button style={{ width: 28, height: 28, borderRadius: 7, background: 'var(--bg-3)', color: 'var(--text-2)', display: 'grid', placeItems: 'center' }}><Icon name="download" size={12}/></button>
                </div>
              ))}
            </div>

            <div style={{ padding: 20, display: 'flex', gap: 8 }}>
              <button className="btn btn-outline" style={{ flex: 1 }}><Icon name="download" size={13}/> Baixar</button>
              <button className="btn btn-outline" style={{ flex: 1 }}><Icon name="edit" size={13}/> Aditivar</button>
              <button className="btn btn-primary" style={{ flex: 1 }}><Icon name="check" size={13}/> Renovar</button>
            </div>
          </div>
        </div>
      </PageContainer>
    </AppShell>
  );
};

Object.assign(window, { PageFluxo, PageLancamentos, PageBancos, PageConciliacao, PageContratos });
