/* global React, Card, Badge, Button, Avatar, Icon, ICONS, Field, sb */
const { useState, useEffect } = React;

// ── constants ─────────────────────────────────────────────────────────────────
const MONTH_LABELS = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
const CAT_COLORS = {
  'Receita':'#22C55E','Adiantamento':'#3B82F6','Bônus':'#F59E0B','Reembolso':'#10B981',
  'Software':'#36CFC9','Estrutura':'#FA541C','Marketing':'#FADB14','Pró-labore':'#7C3AED',
  'Produção':'#22C55E','Pessoal':'#1D39C4','Outros':'#94A3B8',
};
const FALLBACK_COLORS = ['#1D39C4','#36CFC9','#FA541C','#FADB14','#7C3AED','#22C55E','#94A3B8'];

// ── helpers ───────────────────────────────────────────────────────────────────
const fmtDate = d => { if (!d) return '—'; const [y,m,dd]=d.split('-'); return `${dd}/${m}/${y}`; };
const fmtK = v => {
  const n = Number(v || 0);
  return n >= 1000 ? 'R$ ' + (Math.round(n/100)/10).toLocaleString('pt-BR') + 'k' : 'R$ ' + Math.round(n).toLocaleString('pt-BR');
};

function rowToTx(row) {
  const isReceita = row.type === 'receita';
  return {
    id:      row.id,
    d:       fmtDate(row.date),
    t:       row.description || '',
    cat:     row.category || (isReceita ? 'Receita' : 'Outros'),
    v:       (isReceita ? '+ R$ ' : '- R$ ') + Number(row.amount||0).toLocaleString('pt-BR'),
    status:  row.status || 'pendente',
    who:     row.who || '—',
    type:    row.type,
    amount:  Number(row.amount || 0),
    rawDate: row.date,
  };
}

function vencStatus(tx) {
  if (tx.status === 'pago') return 'pago';
  if (!tx.rawDate) return 'pendente';
  const today = new Date(); today.setHours(0,0,0,0);
  const due   = new Date(tx.rawDate + 'T00:00:00');
  const diff  = Math.floor((due - today) / 86400000);
  if (diff < 0)  return 'vencido';
  if (diff === 0) return 'hoje';
  if (diff <= 7)  return 'em_breve';
  return 'futuro';
}

function VencBadge({ tx }) {
  const vs = vencStatus(tx);
  const today = new Date(); today.setHours(0,0,0,0);
  const due  = tx.rawDate ? new Date(tx.rawDate + 'T00:00:00') : null;
  const diff = due ? Math.floor((due - today) / 86400000) : null;
  const badgeBase = { borderRadius:999, padding:'3px 10px', fontSize:11, fontWeight:700, display:'inline-block' };
  if (vs === 'pago')     return <span style={{ ...badgeBase, background:'rgba(34,197,94,0.15)', color:'#22C55E' }}>Recebido</span>;
  if (vs === 'vencido')  return <span style={{ ...badgeBase, background:'rgba(239,68,68,0.15)', color:'#EF4444' }}>Vencido há {Math.abs(diff)}d</span>;
  if (vs === 'hoje')     return <span style={{ ...badgeBase, background:'rgba(245,158,11,0.15)', color:'#F59E0B' }}>Vence hoje</span>;
  if (vs === 'em_breve') return <span style={{ ...badgeBase, background:'rgba(250,219,20,0.12)', color:'#CA8A04' }}>Em {diff}d</span>;
  return <span style={{ ...badgeBase, background:'var(--bg-elevated)', color:'var(--fg-muted)' }}>Pendente</span>;
}

function buildMonthlyData(txs) {
  const now = new Date();
  const slots = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(now.getFullYear(), now.getMonth() - (6-i), 1);
    return { key:`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`, label:MONTH_LABELS[d.getMonth()], rev:0, exp:0, pending:0 };
  });
  const byKey = Object.fromEntries(slots.map(s => [s.key, s]));
  txs.forEach(t => {
    if (!t.rawDate) return;
    const k = t.rawDate.slice(0,7);
    if (!byKey[k]) return;
    if (t.type==='receita') { byKey[k].rev += t.amount; if (t.status==='pendente') byKey[k].pending += t.amount; }
    else byKey[k].exp += t.amount;
  });
  return {
    labels:  slots.map(s=>s.label),
    revenue: slots.map(s=>s.rev),
    expense: slots.map(s=>s.exp),
    pending: slots.map(s=>s.pending),
    lucro:   slots.map(s=>s.rev - s.exp),
  };
}

function buildDonutData(txs) {
  const despesas = txs.filter(t => t.type==='despesa');
  const total = despesas.reduce((s,t) => s+t.amount, 0);
  if (!total) return [];
  const bycat = {};
  despesas.forEach(t => { bycat[t.cat] = (bycat[t.cat]||0) + t.amount; });
  return Object.entries(bycat).sort((a,b)=>b[1]-a[1]).map(([cat,val],i) => ({
    l:cat, v:val, pct:Math.round(val/total*100)+'%',
    c: CAT_COLORS[cat] || FALLBACK_COLORS[i % FALLBACK_COLORS.length],
  }));
}

// ── chart primitives ──────────────────────────────────────────────────────────
function Sparkline({ data, color='var(--primary)', height=60 }) {
  const max = Math.max(...data), min = Math.min(...data);
  const w = 280;
  const pts = data.map((v,i) => `${(i/(data.length-1))*w},${height-((v-min)/(max-min||1))*(height-8)-4}`).join(' ');
  const uid = color.replace(/[^a-z0-9]/gi,'');
  return (
    <svg viewBox={`0 0 ${w} ${height}`} width="100%" height={height} preserveAspectRatio="none">
      <defs><linearGradient id={`slg${uid}`} x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={color} stopOpacity="0.4"/><stop offset="100%" stopColor={color} stopOpacity="0"/></linearGradient></defs>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="2"/>
      <polygon points={`0,${height} ${pts} ${w},${height}`} fill={`url(#slg${uid})`}/>
    </svg>
  );
}

function BarChart({ data, labels, color='var(--primary)' }) {
  const max = Math.max(...data) || 1;
  return (
    <div style={{ display:'grid', gridTemplateColumns:`repeat(${data.length},1fr)`, gap:6, alignItems:'end', height:180 }}>
      {data.map((v,i) => (
        <div key={i} style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:6, height:'100%' }}>
          <div style={{ flex:1, width:'100%', display:'flex', alignItems:'flex-end' }}>
            <div style={{ width:'100%', height:(v/max*100)+'%', background:`linear-gradient(180deg,${color},${color}55)`, borderRadius:'6px 6px 0 0', minHeight:4 }}/>
          </div>
          <span style={{ fontSize:10, color:'var(--fg-muted)', fontFamily:'var(--font-mono)' }}>{labels[i]}</span>
        </div>
      ))}
    </div>
  );
}

function Donut({ segments, size=160, label='', year='' }) {
  const total = segments.reduce((s,x) => s+x.v, 0) || 1;
  const r=size/2-14, cx=size/2, cy=size/2, C=2*Math.PI*r;
  let off=0;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--bg-elevated)" strokeWidth="14"/>
      {segments.map((s,i) => { const len=(s.v/total)*C; const el=<circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={s.c} strokeWidth="14" strokeDasharray={`${len} ${C-len}`} strokeDashoffset={-off} transform={`rotate(-90 ${cx} ${cy})`} strokeLinecap="butt"/>; off+=len; return el; })}
      <text x={cx} y={cy-4} textAnchor="middle" fontFamily="var(--font-display)" fontSize="22" fontWeight="700" fill="var(--fg-primary)">{label}</text>
      <text x={cx} y={cy+14} textAnchor="middle" fontSize="10" fill="var(--fg-muted)">{year}</text>
    </svg>
  );
}

// ── modals ────────────────────────────────────────────────────────────────────
function ExportModal({ onClose }) {
  const [fmt, setFmt]       = useState('csv');
  const [period, setPeriod] = useState('mes');
  const chip = active => ({ padding:'8px 14px', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:active?'var(--primary-soft)':'var(--bg-elevated)', color:active?'var(--geek-blue-200)':'var(--fg-secondary)', border:`1px solid ${active?'var(--geek-blue-a40)':'var(--border-subtle)'}` });
  const lbl  = { fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--fg-muted)', display:'block', marginBottom:8 };
  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(7,11,28,0.72)', backdropFilter:'blur(6px)', display:'grid', placeItems:'center', zIndex:200, padding:24 }}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'min(420px,100%)', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:18, boxShadow:'0 30px 80px rgba(0,0,0,0.55)', overflow:'hidden' }}>
        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div><div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>Financeiro</div><h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Exportar dados</h2></div>
          <button onClick={onClose} style={{ background:'transparent', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', width:34, height:34, borderRadius:8, cursor:'pointer', fontSize:18 }}>×</button>
        </div>
        <div style={{ padding:'22px 24px', display:'flex', flexDirection:'column', gap:18 }}>
          <div><span style={lbl}>Período</span><div style={{ display:'flex', gap:8 }}>{[['mes','Este mês'],['trimestre','Trimestre'],['ano','Este ano']].map(([id,l])=><button key={id} onClick={()=>setPeriod(id)} style={chip(period===id)}>{l}</button>)}</div></div>
          <div><span style={lbl}>Formato</span><div style={{ display:'flex', gap:8 }}>{[['csv','CSV'],['xlsx','Excel'],['pdf','PDF']].map(([id,l])=><button key={id} onClick={()=>setFmt(id)} style={chip(fmt===id)}>{l}</button>)}</div></div>
          <div style={{ background:'var(--bg-elevated)', borderRadius:10, padding:'12px 14px', fontSize:12, color:'var(--fg-muted)' }}>{fmt==='csv'?'Arquivo .csv compatível com planilhas':fmt==='xlsx'?'Planilha Excel formatada com gráficos e totais':'Relatório PDF pronto para impressão'}</div>
        </div>
        <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10, background:'var(--bg-elevated)' }}>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button icon="check" onClick={()=>{ window.__toast?.(`Exportando ${fmt.toUpperCase()}…`,{tone:'success'}); onClose(); }}>Exportar</Button>
        </div>
      </div>
    </div>
  );
}

function NovaTransacaoModal({ onClose, onSave, defaultTipo='receita' }) {
  const [tipo,   setTipo]   = useState(defaultTipo);
  const [desc,   setDesc]   = useState('');
  const [valor,  setValor]  = useState('');
  const [data,   setData]   = useState('');
  const [quem,   setQuem]   = useState('');
  const [status, setStatus] = useState('pago');
  const [cat,    setCat]    = useState('');
  const [recorr, setRecorr] = useState(false);
  const [freq,   setFreq]   = useState('mensal');

  const catsR = ['Receita','Adiantamento','Bônus','Reembolso'];
  const catsD = ['Software','Estrutura','Pró-labore','Marketing','Produção','Pessoal','Outros'];
  const cats  = tipo === 'receita' ? catsR : catsD;
  const valido = desc.trim().length > 1 && valor.trim().length > 0 && data.trim().length > 0;

  function salvar() {
    if (!valido) return;
    const rawAmount = parseFloat(valor.replace(/[^\d,]/g,'').replace(',','.')) || 0;
    onSave({ type:tipo, amount:rawAmount, description:desc.trim(), category:cat||cats[0], status, date:data, who:quem.trim()||'—' });
    onClose();
  }

  const inp   = { width:'100%', background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', borderRadius:8, padding:'9px 12px', color:'var(--fg-primary)', fontSize:13, fontFamily:'inherit', outline:'none', boxSizing:'border-box' };
  const lbl   = { fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--fg-muted)', display:'block', marginBottom:8 };
  const chip  = active => ({ padding:'6px 12px', borderRadius:999, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:active?'var(--primary-soft)':'var(--bg-elevated)', color:active?'var(--geek-blue-200)':'var(--fg-secondary)', border:`1px solid ${active?'var(--geek-blue-a40)':'var(--border-subtle)'}` });

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(7,11,28,0.72)', backdropFilter:'blur(6px)', display:'grid', placeItems:'center', zIndex:200, padding:24 }}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'min(560px,100%)', display:'flex', flexDirection:'column', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:18, boxShadow:'0 30px 80px rgba(0,0,0,0.55)', overflow:'hidden' }}>
        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div><div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>Financeiro</div><h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Nova transação</h2></div>
          <button onClick={onClose} style={{ background:'transparent', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', width:34, height:34, borderRadius:8, cursor:'pointer', fontSize:18 }}>×</button>
        </div>
        <div style={{ padding:'22px 24px', display:'flex', flexDirection:'column', gap:16, overflowY:'auto', maxHeight:'70vh' }}>
          <div>
            <span style={lbl}>Tipo</span>
            <div style={{ display:'flex', gap:8 }}>
              {[['receita','Entrada','#22C55E'],['despesa','Saída','#FF6A6A']].map(([id,l,cor])=>(
                <button key={id} onClick={()=>{setTipo(id);setCat('');}} style={{ flex:1, padding:'10px 0', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:tipo===id?cor+'22':'var(--bg-elevated)', color:tipo===id?cor:'var(--fg-secondary)', border:`1px solid ${tipo===id?cor+'66':'var(--border-subtle)'}` }}>{l}</button>
              ))}
            </div>
          </div>
          <div><span style={lbl}>Descrição</span><input style={inp} placeholder={tipo==='receita'?'Ex.: NF #1285 · Cliente XYZ':'Ex.: Adobe Creative Cloud'} value={desc} onChange={e=>setDesc(e.target.value)}/></div>
          <div><span style={lbl}>Cliente / Fornecedor</span><input style={inp} placeholder="Nome" value={quem} onChange={e=>setQuem(e.target.value)}/></div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <div><span style={lbl}>Valor (R$)</span><input style={inp} placeholder="0,00" value={valor} onChange={e=>setValor(e.target.value)}/></div>
            <div><span style={lbl}>{tipo==='receita'?'Data / Vencimento':'Data / Vencimento'}</span><input type="date" style={inp} value={data} onChange={e=>setData(e.target.value)}/></div>
          </div>
          <div>
            <span style={lbl}>Status</span>
            <div style={{ display:'flex', gap:8 }}>
              {[['pago',tipo==='receita'?'Recebido':'Pago'],['pendente',tipo==='receita'?'A receber':'A pagar']].map(([id,l])=>(
                <button key={id} onClick={()=>setStatus(id)} style={{ flex:1, padding:'9px 0', borderRadius:8, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:status===id?'var(--primary-soft)':'var(--bg-elevated)', color:status===id?'var(--geek-blue-200)':'var(--fg-secondary)', border:`1px solid ${status===id?'var(--geek-blue-a40)':'var(--border-subtle)'}` }}>{l}</button>
              ))}
            </div>
          </div>
          <div>
            <span style={lbl}>Categoria</span>
            <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
              {cats.map(c=><button key={c} onClick={()=>setCat(c)} style={chip(cat===c)}>{c}</button>)}
            </div>
          </div>
          <div style={{ borderRadius:10, border:'1px solid var(--border-subtle)', padding:14, display:'flex', alignItems:'center', gap:12 }}>
            <button onClick={()=>setRecorr(!recorr)} style={{ width:36, height:20, borderRadius:999, background:recorr?'var(--primary)':'var(--bg-elevated)', border:'1px solid', borderColor:recorr?'var(--primary)':'var(--border-strong)', position:'relative', cursor:'pointer', padding:0, flexShrink:0 }}>
              <span style={{ position:'absolute', top:1, left:recorr?17:1, width:16, height:16, borderRadius:'50%', background:'#fff', transition:'left 160ms' }}/>
            </button>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13, fontWeight:600 }}>Recorrente</div>
              <div style={{ fontSize:11, color:'var(--fg-muted)' }}>Lança automaticamente todo período</div>
            </div>
            {recorr && (
              <div style={{ display:'flex', gap:6 }}>
                {['mensal','trimestral','anual'].map(f=><button key={f} onClick={()=>setFreq(f)} style={chip(freq===f)}>{f}</button>)}
              </div>
            )}
          </div>
        </div>
        <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10, background:'var(--bg-elevated)' }}>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button icon="check" onClick={salvar} style={{ opacity:valido?1:0.45, pointerEvents:valido?'auto':'none' }}>Salvar</Button>
        </div>
      </div>
    </div>
  );
}

// ── A Receber Tab ─────────────────────────────────────────────────────────────
function AReceberTab({ txs, loading, onAdd, onMarkPaid, onDelete }) {
  const now = new Date();
  const curMonthKey = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`;
  const receitas   = txs.filter(t => t.type === 'receita');
  const pendentes  = receitas.filter(t => t.status === 'pendente');
  const pagas      = receitas.filter(t => t.status === 'pago');
  const vencidos   = pendentes.filter(t => vencStatus(t) === 'vencido');
  const totalPend  = pendentes.reduce((s,t) => s+t.amount, 0);
  const totalVenc  = vencidos.reduce((s,t) => s+t.amount, 0);
  const recebidoM  = pagas.filter(t => t.rawDate?.startsWith(curMonthKey)).reduce((s,t) => s+t.amount, 0);

  const GROUPS = [
    { key:'vencido',  label:'Vencidas',          color:'#EF4444', toneStyle:{ background:'rgba(239,68,68,0.08)', borderColor:'rgba(239,68,68,0.2)' } },
    { key:'hoje',     label:'Vencem hoje',        color:'#F59E0B', toneStyle:{} },
    { key:'em_breve', label:'Próximos 7 dias',    color:'#CA8A04', toneStyle:{} },
    { key:'futuro',   label:'Futuras',            color:'var(--fg-muted)', toneStyle:{} },
  ];

  const grouped = GROUPS.map(g => ({
    ...g,
    txs: pendentes.filter(t => vencStatus(t) === g.key).sort((a,b) => (a.rawDate||'') > (b.rawDate||'') ? 1 : -1),
  })).filter(g => g.txs.length > 0);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14 }}>
        {[
          { l:'Total a receber', v:fmtK(totalPend), c:'#22C55E', sub: pendentes.length + ' cobranças pendentes' },
          { l:'Vencido', v:fmtK(totalVenc), c:'#EF4444', sub: vencidos.length + ' em atraso' },
          { l:`Recebido em ${MONTH_LABELS[now.getMonth()]}`, v:fmtK(recebidoM), c:'var(--geek-blue-300)', sub:'confirmado este mês' },
        ].map(card => (
          <Card key={card.l} padding={18}>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)' }}>{card.l}</div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:26, fontWeight:700, marginTop:6, letterSpacing:'-0.02em', color:card.c }}>{card.v}</div>
            <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:4 }}>{card.sub}</div>
          </Card>
        ))}
      </div>

      {loading && <div style={{ padding:'32px', textAlign:'center', color:'var(--fg-muted)' }}>Carregando…</div>}

      {!loading && pendentes.length === 0 && (
        <Card padding={40}>
          <div style={{ textAlign:'center', color:'var(--fg-muted)' }}>
            <div style={{ fontSize:36, marginBottom:10 }}>✓</div>
            <div style={{ fontSize:15, fontWeight:700, color:'var(--fg-primary)' }}>Tudo recebido!</div>
            <div style={{ fontSize:13, marginTop:6 }}>Nenhuma cobrança pendente no momento.</div>
            <div style={{ marginTop:18 }}><Button onClick={()=>onAdd('receita')}>Nova cobrança</Button></div>
          </div>
        </Card>
      )}

      {grouped.map(group => (
        <Card key={group.key} padding={0} style={group.toneStyle}>
          <div style={{ padding:'14px 20px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:10 }}>
            <span style={{ width:8, height:8, borderRadius:'50%', background:group.color, flexShrink:0 }}/>
            <span style={{ fontFamily:'var(--font-display)', fontSize:12, fontWeight:700, letterSpacing:'0.04em', color:group.color }}>{group.label}</span>
            <span style={{ fontSize:11, color:'var(--fg-muted)' }}>· {group.txs.length} cobrança{group.txs.length!==1?'s':''} · {fmtK(group.txs.reduce((s,t)=>s+t.amount,0))}</span>
          </div>
          {group.txs.map((t,i) => (
            <div key={t.id||i} style={{ padding:'14px 20px', borderBottom:i<group.txs.length-1?'1px solid var(--border-subtle)':'none', display:'flex', alignItems:'center', gap:14 }}>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:14, fontWeight:600 }}>{t.t}</div>
                <div style={{ display:'flex', gap:10, marginTop:3, fontSize:12, color:'var(--fg-muted)', flexWrap:'wrap' }}>
                  <span>{t.who}</span>
                  <span>·</span>
                  <span>Vence {fmtDate(t.rawDate)}</span>
                  <span>·</span>
                  <span style={{ background:(CAT_COLORS[t.cat]||'#94A3B8')+'22', color:CAT_COLORS[t.cat]||'var(--fg-muted)', borderRadius:999, padding:'0 8px' }}>{t.cat}</span>
                </div>
              </div>
              <VencBadge tx={t}/>
              <span style={{ fontFamily:'var(--font-display)', fontWeight:700, color:'#22C55E', fontSize:15, minWidth:80, textAlign:'right' }}>{fmtK(t.amount)}</span>
              <Button variant="secondary" size="sm" onClick={()=>onMarkPaid(t.id)}>Marcar pago</Button>
              <button onClick={()=>onDelete(t.id)} title="Excluir" style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', fontSize:15, padding:'4px 6px', lineHeight:1 }}>🗑</button>
            </div>
          ))}
        </Card>
      ))}

      {!loading && pagas.length > 0 && (
        <Card padding={0}>
          <div style={{ padding:'14px 20px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:10 }}>
            <span style={{ width:8, height:8, borderRadius:'50%', background:'#22C55E', flexShrink:0 }}/>
            <span style={{ fontFamily:'var(--font-display)', fontSize:12, fontWeight:700, letterSpacing:'0.04em', color:'#22C55E' }}>Recebidas</span>
            <span style={{ fontSize:11, color:'var(--fg-muted)' }}>· {pagas.length} pagamento{pagas.length!==1?'s':''}</span>
          </div>
          {pagas.slice(0,6).map((t,i) => (
            <div key={t.id||i} style={{ padding:'12px 20px', borderBottom:i<Math.min(pagas.length,6)-1?'1px solid var(--border-subtle)':'none', display:'flex', alignItems:'center', gap:14 }}>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13, fontWeight:600 }}>{t.t}</div>
                <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2 }}>{t.who} · {fmtDate(t.rawDate)}</div>
              </div>
              <span style={{ background:'rgba(34,197,94,0.12)', color:'#22C55E', borderRadius:999, padding:'3px 10px', fontSize:11, fontWeight:700 }}>Recebido</span>
              <span style={{ fontFamily:'var(--font-display)', fontWeight:700, color:'#22C55E', fontSize:14 }}>{fmtK(t.amount)}</span>
            </div>
          ))}
        </Card>
      )}

      <div style={{ display:'flex', justifyContent:'flex-end' }}>
        <Button icon="plus" onClick={()=>onAdd('receita')}>Nova cobrança</Button>
      </div>
    </div>
  );
}

// ── A Pagar Tab ───────────────────────────────────────────────────────────────
function APagarTab({ txs, loading, onAdd, onMarkPaid, onDelete }) {
  const now = new Date();
  const curMonthKey = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`;
  const despesas  = txs.filter(t => t.type === 'despesa');
  const pendentes = despesas.filter(t => t.status === 'pendente');
  const pagas     = despesas.filter(t => t.status === 'pago');
  const vencidos  = pendentes.filter(t => vencStatus(t) === 'vencido');
  const totalPend = pendentes.reduce((s,t) => s+t.amount, 0);
  const totalVenc = vencidos.reduce((s,t) => s+t.amount, 0);
  const pagoM     = pagas.filter(t => t.rawDate?.startsWith(curMonthKey)).reduce((s,t) => s+t.amount, 0);

  const GROUPS = [
    { key:'vencido',  label:'Vencidas',       color:'#EF4444', toneStyle:{ background:'rgba(239,68,68,0.06)', borderColor:'rgba(239,68,68,0.18)' } },
    { key:'hoje',     label:'Vencem hoje',     color:'#F59E0B', toneStyle:{} },
    { key:'em_breve', label:'Próximos 7 dias', color:'#CA8A04', toneStyle:{} },
    { key:'futuro',   label:'Futuras',         color:'var(--fg-muted)', toneStyle:{} },
  ];

  const grouped = GROUPS.map(g => ({
    ...g,
    txs: pendentes.filter(t => vencStatus(t) === g.key).sort((a,b) => (a.rawDate||'') > (b.rawDate||'') ? 1 : -1),
  })).filter(g => g.txs.length > 0);

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14 }}>
        {[
          { l:'Total a pagar', v:fmtK(totalPend), c:'#FF6A6A', sub: pendentes.length + ' despesas pendentes' },
          { l:'Vencido', v:fmtK(totalVenc), c:'#EF4444', sub: vencidos.length + ' despesa' + (vencidos.length!==1?'s':'') + ' em atraso' },
          { l:`Pago em ${MONTH_LABELS[now.getMonth()]}`, v:fmtK(pagoM), c:'var(--fg-secondary)', sub:'despesas quitadas' },
        ].map(card => (
          <Card key={card.l} padding={18}>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)' }}>{card.l}</div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:26, fontWeight:700, marginTop:6, letterSpacing:'-0.02em', color:card.c }}>{card.v}</div>
            <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:4 }}>{card.sub}</div>
          </Card>
        ))}
      </div>

      {loading && <div style={{ padding:'32px', textAlign:'center', color:'var(--fg-muted)' }}>Carregando…</div>}

      {!loading && pendentes.length === 0 && (
        <Card padding={40}>
          <div style={{ textAlign:'center', color:'var(--fg-muted)' }}>
            <div style={{ fontSize:36, marginBottom:10 }}>✓</div>
            <div style={{ fontSize:15, fontWeight:700, color:'var(--fg-primary)' }}>Tudo em dia!</div>
            <div style={{ fontSize:13, marginTop:6 }}>Nenhuma despesa pendente.</div>
            <div style={{ marginTop:18 }}><Button onClick={()=>onAdd('despesa')}>Nova despesa</Button></div>
          </div>
        </Card>
      )}

      {grouped.map(group => (
        <Card key={group.key} padding={0} style={group.toneStyle}>
          <div style={{ padding:'14px 20px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:10 }}>
            <span style={{ width:8, height:8, borderRadius:'50%', background:group.color, flexShrink:0 }}/>
            <span style={{ fontFamily:'var(--font-display)', fontSize:12, fontWeight:700, letterSpacing:'0.04em', color:group.color }}>{group.label}</span>
            <span style={{ fontSize:11, color:'var(--fg-muted)' }}>· {group.txs.length} despesa{group.txs.length!==1?'s':''} · {fmtK(group.txs.reduce((s,t)=>s+t.amount,0))}</span>
          </div>
          {group.txs.map((t,i) => (
            <div key={t.id||i} style={{ padding:'14px 20px', borderBottom:i<group.txs.length-1?'1px solid var(--border-subtle)':'none', display:'flex', alignItems:'center', gap:14 }}>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:14, fontWeight:600 }}>{t.t}</div>
                <div style={{ display:'flex', gap:10, marginTop:3, fontSize:12, color:'var(--fg-muted)', flexWrap:'wrap' }}>
                  <span>{t.who}</span>
                  <span>·</span>
                  <span>{fmtDate(t.rawDate)}</span>
                  <span>·</span>
                  <span style={{ background:(CAT_COLORS[t.cat]||'#94A3B8')+'22', color:CAT_COLORS[t.cat]||'var(--fg-muted)', borderRadius:999, padding:'0 8px' }}>{t.cat}</span>
                </div>
              </div>
              <VencBadge tx={t}/>
              <span style={{ fontFamily:'var(--font-display)', fontWeight:700, color:'#FF6A6A', fontSize:15, minWidth:80, textAlign:'right' }}>{fmtK(t.amount)}</span>
              <Button variant="secondary" size="sm" onClick={()=>onMarkPaid(t.id)}>Marcar pago</Button>
              <button onClick={()=>onDelete(t.id)} title="Excluir" style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', fontSize:15, padding:'4px 6px', lineHeight:1 }}>🗑</button>
            </div>
          ))}
        </Card>
      ))}

      {!loading && pagas.length > 0 && (
        <Card padding={0}>
          <div style={{ padding:'14px 20px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:10 }}>
            <span style={{ width:8, height:8, borderRadius:'50%', background:'#94A3B8', flexShrink:0 }}/>
            <span style={{ fontFamily:'var(--font-display)', fontSize:12, fontWeight:700, letterSpacing:'0.04em', color:'var(--fg-secondary)' }}>Pagas</span>
            <span style={{ fontSize:11, color:'var(--fg-muted)' }}>· {pagas.length} despesa{pagas.length!==1?'s':''}</span>
          </div>
          {pagas.slice(0,6).map((t,i) => (
            <div key={t.id||i} style={{ padding:'12px 20px', borderBottom:i<Math.min(pagas.length,6)-1?'1px solid var(--border-subtle)':'none', display:'flex', alignItems:'center', gap:14 }}>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13, fontWeight:600 }}>{t.t}</div>
                <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2 }}>{t.who} · {fmtDate(t.rawDate)}</div>
              </div>
              <Badge tone="success">Pago</Badge>
              <span style={{ fontFamily:'var(--font-display)', fontWeight:700, color:'#FF6A6A', fontSize:14 }}>{fmtK(t.amount)}</span>
            </div>
          ))}
        </Card>
      )}

      <div style={{ display:'flex', justifyContent:'flex-end' }}>
        <Button icon="plus" onClick={()=>onAdd('despesa')}>Nova despesa</Button>
      </div>
    </div>
  );
}

// ── Relatórios Tab ────────────────────────────────────────────────────────────
function RelatoriosTab({ txs }) {
  const [period, setPeriod] = useState('mes');
  const now = new Date();

  function filterByPeriod(arr) {
    const today = new Date(now); today.setHours(23,59,59,999);
    let from;
    if (period==='mes')       from = new Date(now.getFullYear(), now.getMonth(), 1);
    else if (period==='trim') from = new Date(now.getFullYear(), now.getMonth()-2, 1);
    else                      from = new Date(now.getFullYear(), 0, 1);
    return arr.filter(t => { if (!t.rawDate) return false; const d=new Date(t.rawDate+'T00:00:00'); return d>=from&&d<=today; });
  }

  const filtered  = filterByPeriod(txs);
  const receitas  = filtered.filter(t => t.type==='receita');
  const despesas  = filtered.filter(t => t.type==='despesa');
  const totalRec  = receitas.reduce((s,t)=>s+t.amount,0);
  const totalDesp = despesas.reduce((s,t)=>s+t.amount,0);
  const lucro     = totalRec - totalDesp;
  const margem    = totalRec > 0 ? Math.round(lucro/totalRec*100) : 0;

  const byCatDesp = {};
  despesas.forEach(t => { byCatDesp[t.cat] = (byCatDesp[t.cat]||0) + t.amount; });
  const catRows = Object.entries(byCatDesp).sort((a,b)=>b[1]-a[1]);

  const byClient = {};
  receitas.forEach(t => { if (t.who && t.who!=='—') byClient[t.who] = (byClient[t.who]||0) + t.amount; });
  const clientRows = Object.entries(byClient).sort((a,b)=>b[1]-a[1]).slice(0,6);

  const periodLabel = period==='mes' ? MONTH_LABELS[now.getMonth()] : period==='trim' ? 'Últimos 3 meses' : String(now.getFullYear());
  const chip = active => ({ padding:'7px 14px', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:active?'var(--primary-soft)':'var(--bg-elevated)', color:active?'var(--geek-blue-200)':'var(--fg-secondary)', border:`1px solid ${active?'var(--geek-blue-a40)':'var(--border-subtle)'}` });

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'flex', alignItems:'center', gap:8 }}>
        <span style={{ fontSize:13, color:'var(--fg-muted)', fontWeight:600, marginRight:4 }}>Período:</span>
        {[['mes','Este mês'],['trim','Trimestre'],['ano','Este ano']].map(([id,l])=><button key={id} onClick={()=>setPeriod(id)} style={chip(period===id)}>{l}</button>)}
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        {[
          { l:'Faturamento', v:fmtK(totalRec),  c:'#22C55E' },
          { l:'Despesas',    v:fmtK(totalDesp), c:'#FF6A6A' },
          { l:'Lucro',       v:fmtK(lucro),     c:lucro>=0?'var(--geek-blue-300)':'#EF4444' },
          { l:'Margem',      v:margem+'%',       c:margem>=30?'#22C55E':margem>=10?'#CA8A04':'#EF4444' },
        ].map(card=>(
          <Card key={card.l} padding={18}>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)' }}>{card.l}</div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:24, fontWeight:700, marginTop:6, letterSpacing:'-0.02em', color:card.c }}>{card.v}</div>
            <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:4 }}>{periodLabel}</div>
          </Card>
        ))}
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:18 }}>
        <Card padding={20}>
          <h3 style={{ margin:'0 0 16px', fontSize:15, fontWeight:700 }}>Despesas por categoria</h3>
          {catRows.length === 0
            ? <div style={{ color:'var(--fg-muted)', fontSize:13 }}>Nenhuma despesa no período.</div>
            : catRows.map(([cat,val],i) => {
                const pct = Math.round(val/totalDesp*100);
                const cor = CAT_COLORS[cat] || FALLBACK_COLORS[i%FALLBACK_COLORS.length];
                return (
                  <div key={cat} style={{ marginBottom:14 }}>
                    <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, marginBottom:5 }}>
                      <span style={{ display:'flex', alignItems:'center', gap:8 }}>
                        <span style={{ width:10, height:10, borderRadius:3, background:cor, flexShrink:0 }}/>
                        {cat}
                      </span>
                      <span style={{ fontFamily:'var(--font-mono)', color:'var(--fg-secondary)' }}>{fmtK(val)} <span style={{ color:'var(--fg-muted)' }}>({pct}%)</span></span>
                    </div>
                    <div style={{ height:4, borderRadius:999, background:'var(--bg-elevated)' }}>
                      <div style={{ height:'100%', width:pct+'%', background:cor, borderRadius:999 }}/>
                    </div>
                  </div>
                );
              })
          }
        </Card>

        <Card padding={20}>
          <h3 style={{ margin:'0 0 16px', fontSize:15, fontWeight:700 }}>Receita por cliente</h3>
          {clientRows.length === 0
            ? <div style={{ color:'var(--fg-muted)', fontSize:13 }}>Nenhuma receita com cliente registrado no período.</div>
            : clientRows.map(([client,val],i)=>(
                <div key={client} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 0', borderBottom:'1px solid var(--border-subtle)' }}>
                  <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                    <Avatar name={client} size={28} idx={i}/>
                    <span style={{ fontSize:13, fontWeight:600 }}>{client}</span>
                  </div>
                  <span style={{ fontFamily:'var(--font-display)', fontWeight:700, color:'#22C55E', fontSize:14 }}>{fmtK(val)}</span>
                </div>
              ))
          }
        </Card>
      </div>

      <Card padding={20}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:20 }}>
          <div>
            <h3 style={{ margin:0, fontSize:15, fontWeight:700 }}>Receita vs Despesas — {periodLabel}</h3>
            <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2 }}>Comparativo do período</div>
          </div>
        </div>
        <div style={{ display:'flex', alignItems:'flex-end', gap:24 }}>
          <div style={{ display:'flex', gap:16, height:140, alignItems:'flex-end', flex:1 }}>
            {[['Faturamento',totalRec,'#22C55E'],['Despesas',totalDesp,'#FF6A6A'],['Lucro',Math.max(lucro,0),'#1D39C4']].map(([l,v,c])=>{
              const maxV = Math.max(totalRec, totalDesp, 1);
              const h = Math.max(v/maxV*100, v>0?4:0);
              return (
                <div key={l} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:8, height:'100%' }}>
                  <div style={{ flex:1, width:'100%', display:'flex', alignItems:'flex-end' }}>
                    <div style={{ width:'100%', height:h+'%', background:`linear-gradient(180deg,${c},${c}55)`, borderRadius:'8px 8px 0 0', minHeight:v>0?4:0 }}/>
                  </div>
                  <div style={{ fontSize:12, fontWeight:700, fontFamily:'var(--font-mono)', color:c }}>{fmtK(v)}</div>
                  <div style={{ fontSize:11, color:'var(--fg-muted)' }}>{l}</div>
                </div>
              );
            })}
          </div>
          <div style={{ width:1, height:140, background:'var(--border-subtle)', flexShrink:0 }}/>
          <div style={{ width:200, display:'flex', flexDirection:'column', gap:10, flexShrink:0 }}>
            <div style={{ fontSize:12, color:'var(--fg-muted)', fontWeight:700, letterSpacing:'0.04em', textTransform:'uppercase' }}>Resumo</div>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize:13 }}><span style={{ color:'var(--fg-secondary)' }}>Faturamento</span><span style={{ fontWeight:700, color:'#22C55E' }}>{fmtK(totalRec)}</span></div>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize:13 }}><span style={{ color:'var(--fg-secondary)' }}>Despesas</span><span style={{ fontWeight:700, color:'#FF6A6A' }}>{fmtK(totalDesp)}</span></div>
            <div style={{ height:1, background:'var(--border-subtle)' }}/>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize:14 }}><span style={{ fontWeight:700 }}>Lucro</span><span style={{ fontWeight:700, color:lucro>=0?'var(--geek-blue-300)':'#EF4444' }}>{fmtK(lucro)}</span></div>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize:12 }}><span style={{ color:'var(--fg-muted)' }}>Margem</span><span style={{ fontWeight:700, color:margem>=30?'#22C55E':margem>=10?'#CA8A04':'#EF4444' }}>{margem}%</span></div>
          </div>
        </div>
      </Card>
    </div>
  );
}

// ── Finance (main) ────────────────────────────────────────────────────────────
function Finance() {
  const [tab,          setTab]          = useState('geral');
  const [txs,          setTxs]          = useState([]);
  const [loading,      setLoading]      = useState(true);
  const [modalAberto,  setModalAberto]  = useState(false);
  const [modalTipo,    setModalTipo]    = useState('receita');
  const [exportOpen,   setExportOpen]   = useState(false);
  const [cardFilter,   setCardFilter]   = useState(null);
  const [filterOpen,   setFilterOpen]   = useState(false);
  const [filterTipo,   setFilterTipo]   = useState('todos');
  const [filterStatus, setFilterStatus] = useState('todos');
  const [filterCat,    setFilterCat]    = useState('');

  useEffect(() => {
    (async () => {
      const { data, error } = await sb.from('finances').select('*').order('date', { ascending:false });
      if (error) window.__toast?.(error.message, { tone:'danger' });
      setTxs((data||[]).map(rowToTx));
      setLoading(false);
    })();
  }, []);

  async function adicionarTx(nova) {
    const { data:{ user } } = await sb.auth.getUser();
    const { data, error } = await sb.from('finances').insert({
      user_id:user.id, type:nova.type, amount:nova.amount,
      description:nova.description, category:nova.category,
      status:nova.status, date:nova.date, who:nova.who,
    }).select().single();
    if (error) { window.__toast?.(error.message, { tone:'danger' }); return; }
    setTxs(prev => [rowToTx(data), ...prev]);
    window.__toast?.('Transação registrada', { tone:'success' });
  }

  async function deleteTx(id) {
    setTxs(prev => prev.filter(t => t.id !== id));
    const { error } = await sb.from('finances').delete().eq('id', id);
    if (error) window.__toast?.(error.message, { tone:'danger' });
    else window.__toast?.('Transação excluída', { tone:'success' });
  }

  async function markPaid(id) {
    const { error } = await sb.from('finances').update({ status:'pago' }).eq('id', id);
    if (error) { window.__toast?.(error.message, { tone:'danger' }); return; }
    setTxs(prev => prev.map(t => t.id===id ? { ...t, status:'pago' } : t));
    window.__toast?.('Marcado como pago!', { tone:'success' });
  }

  function openAdd(tipo) { setModalTipo(tipo||'receita'); setModalAberto(true); }
  function toggleCF(id)  { setCardFilter(p=>p===id?null:id); setFilterTipo('todos'); setFilterStatus('todos'); setFilterCat(''); setFilterOpen(false); }
  function clearFil()    { setCardFilter(null); setFilterTipo('todos'); setFilterStatus('todos'); setFilterCat(''); }

  const now = new Date();
  const totalReceita  = txs.filter(t=>t.type==='receita').reduce((s,t)=>s+t.amount,0);
  const totalAReceber = txs.filter(t=>t.type==='receita'&&t.status==='pendente').reduce((s,t)=>s+t.amount,0);
  const totalDespesa  = txs.filter(t=>t.type==='despesa').reduce((s,t)=>s+t.amount,0);
  const lucro         = totalReceita - totalDespesa;
  const vencidosAReceberCount = txs.filter(t=>t.type==='receita'&&t.status==='pendente'&&vencStatus(t)==='vencido').length;
  const vencidosAPagarCount   = txs.filter(t=>t.type==='despesa'&&t.status==='pendente'&&vencStatus(t)==='vencido').length;

  const monthly   = buildMonthlyData(txs);
  const donutData = buildDonutData(txs);
  const sl0 = arr => arr.map(v=>v===0?0:v);

  const allCats = [...new Set(txs.map(t=>t.cat))];
  const filteredTxs = txs.filter(t => {
    const isR = t.v.startsWith('+');
    if (cardFilter==='receita'  && !isR) return false;
    if (cardFilter==='areceber' && !(t.status==='pendente'&&isR)) return false;
    if (cardFilter==='despesa'  && isR) return false;
    if (filterTipo==='receita'  && !isR) return false;
    if (filterTipo==='despesa'  && isR) return false;
    if (filterStatus!=='todos'  && t.status!==filterStatus) return false;
    if (filterCat               && t.cat!==filterCat) return false;
    return true;
  });
  const hasActive = cardFilter!==null||filterTipo!=='todos'||filterStatus!=='todos'||filterCat!=='';

  const cards = [
    { id:'receita',  l:`Receita · ${MONTH_LABELS[now.getMonth()]}`, v:fmtK(totalReceita),  c:'#22C55E',             sl:sl0(monthly.revenue), color:'#22C55E' },
    { id:'areceber', l:'A receber',                                  v:fmtK(totalAReceber), c:'#FADB14',             sl:sl0(monthly.pending), color:'#FADB14' },
    { id:'despesa',  l:'Despesas',                                   v:fmtK(totalDespesa),  c:'#FF6A6A',             sl:sl0(monthly.expense), color:'#FF6A6A' },
    { id:'lucro',    l:'Lucro líquido',                              v:fmtK(lucro),         c:'var(--geek-blue-300)',sl:sl0(monthly.lucro),   color:'#1D39C4' },
  ];

  const chip = active => ({ padding:'5px 12px', borderRadius:999, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:active?'var(--primary-soft)':'var(--bg-elevated)', color:active?'var(--geek-blue-200)':'var(--fg-secondary)', border:`1px solid ${active?'var(--geek-blue-a40)':'var(--border-subtle)'}` });
  const filterLabel = cardFilter==='receita'?'Receitas':cardFilter==='areceber'?'A receber':cardFilter==='despesa'?'Despesas':null;

  const TABS = [
    { id:'geral',      label:'Visão Geral' },
    { id:'areceber',   label:'A Receber',  badge: vencidosAReceberCount > 0 ? vencidosAReceberCount : null },
    { id:'apagar',     label:'A Pagar',    badge: vencidosAPagarCount   > 0 ? vencidosAPagarCount   : null },
    { id:'relatorios', label:'Relatórios' },
  ];

  return (
    <>
    <div style={{ padding:'24px 28px', display:'flex', flexDirection:'column', gap:18 }}>

      {/* ── Tab nav ── */}
      <div style={{ display:'flex', alignItems:'center', gap:2, borderBottom:'1px solid var(--border-subtle)' }}>
        {TABS.map(t => (
          <button key={t.id} onClick={()=>setTab(t.id)} style={{
            padding:'10px 18px', borderRadius:'10px 10px 0 0', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
            background: tab===t.id ? 'var(--bg-surface)' : 'transparent',
            color: tab===t.id ? 'var(--fg-primary)' : 'var(--fg-secondary)',
            border: tab===t.id ? '1px solid var(--border-subtle)' : '1px solid transparent',
            borderBottom: tab===t.id ? '1px solid var(--bg-surface)' : '1px solid transparent',
            marginBottom: tab===t.id ? -1 : 0,
            display:'flex', alignItems:'center', gap:8,
          }}>
            {t.label}
            {t.badge && <span style={{ background:'#EF4444', color:'#fff', borderRadius:999, padding:'1px 7px', fontSize:11, fontWeight:700 }}>{t.badge}</span>}
          </button>
        ))}
        <div style={{ flex:1 }}/>
        <div style={{ display:'flex', gap:8, marginBottom:4 }}>
          <Button variant="secondary" size="sm" onClick={()=>setExportOpen(true)}>Exportar</Button>
          <Button icon="plus" size="sm" onClick={()=>openAdd('receita')}>Nova transação</Button>
        </div>
      </div>

      {/* ── Geral Tab ── */}
      {tab === 'geral' && (<>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
          {cards.map(s => {
            const isActive = cardFilter===s.id;
            return (
              <div key={s.id} onClick={()=>toggleCF(s.id)} style={{ cursor:'pointer', borderRadius:14, border:isActive?`2px solid ${s.color}`:'2px solid transparent', boxShadow:isActive?`0 0 0 3px ${s.color}22`:'none', transition:'all 160ms ease' }}>
                <Card padding={18}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
                    <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)' }}>{s.l}</div>
                    {isActive && <span style={{ fontSize:10, background:s.color+'22', color:s.color, border:`1px solid ${s.color}44`, borderRadius:999, padding:'2px 7px', fontWeight:700 }}>Filtro ativo</span>}
                  </div>
                  <div style={{ fontFamily:'var(--font-display)', fontSize:26, fontWeight:700, marginTop:6, letterSpacing:'-0.02em' }}>{s.v}</div>
                  <div style={{ marginTop:6 }}><Sparkline data={s.sl} color={s.color} height={42}/></div>
                </Card>
              </div>
            );
          })}
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:18 }}>
          <Card padding={20}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:18 }}>
              <div><h3 style={{ margin:0, fontSize:16, fontWeight:700 }}>Receita mensal</h3><div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2 }}>Últimos 7 meses · em R$</div></div>
              <div style={{ display:'flex', gap:8 }}>
                <Button variant="ghost" size="sm" onClick={()=>openAdd('receita')}>+ Receita</Button>
                <Button variant="ghost" size="sm" onClick={()=>openAdd('despesa')}>+ Despesa</Button>
              </div>
            </div>
            <BarChart data={monthly.revenue} labels={monthly.labels} color="#1D39C4"/>
          </Card>
          <Card padding={20}>
            <h3 style={{ margin:0, fontSize:16, fontWeight:700 }}>Despesas por categoria</h3>
            <div style={{ display:'flex', alignItems:'center', gap:18, marginTop:14 }}>
              {donutData.length === 0
                ? <div style={{ width:160, height:160, display:'flex', alignItems:'center', justifyContent:'center' }}><svg width="160" height="160" viewBox="0 0 160 160"><circle cx="80" cy="80" r="66" fill="none" stroke="var(--bg-elevated)" strokeWidth="14"/><text x="80" y="80" textAnchor="middle" fontSize="12" fill="var(--fg-muted)">Sem despesas</text></svg></div>
                : <Donut segments={donutData} label={MONTH_LABELS[now.getMonth()]} year={String(now.getFullYear())}/>
              }
              <div style={{ display:'flex', flexDirection:'column', gap:8, fontSize:12 }}>
                {donutData.length === 0
                  ? <span style={{ color:'var(--fg-muted)' }}>Nenhuma despesa registrada.</span>
                  : donutData.map(r=>(
                      <div key={r.l} style={{ display:'flex', alignItems:'center', gap:10 }}>
                        <span style={{ width:10, height:10, borderRadius:3, background:r.c }}/>
                        <span style={{ flex:1, color:'var(--fg-secondary)' }}>{r.l}</span>
                        <span style={{ fontFamily:'var(--font-mono)', color:'var(--fg-muted)' }}>{r.pct}</span>
                      </div>
                    ))
                }
              </div>
            </div>
          </Card>
        </div>

        <Card padding={0}>
          <div style={{ padding:'18px 22px', borderBottom:'1px solid var(--border-subtle)' }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <div>
                <h3 style={{ margin:0, fontSize:16, fontWeight:700 }}>
                  Movimentações{filterLabel && <span style={{ marginLeft:10, fontSize:12, background:'var(--primary-soft)', color:'var(--geek-blue-200)', border:'1px solid var(--geek-blue-a40)', borderRadius:999, padding:'2px 10px', fontWeight:600 }}>{filterLabel}</span>}
                </h3>
                <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2 }}>
                  {loading ? 'Carregando…' : `${filteredTxs.length} transaç${filteredTxs.length===1?'ão':'ões'}`}
                  {hasActive && <span style={{ marginLeft:6, color:'var(--geek-blue-300)', cursor:'pointer', textDecoration:'underline' }} onClick={clearFil}>· Limpar filtros</span>}
                </div>
              </div>
              <button onClick={()=>{ setFilterOpen(o=>!o); setCardFilter(null); }} style={{ display:'flex', alignItems:'center', gap:6, padding:'7px 12px', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', border:'1px solid var(--border-subtle)', background:filterOpen?'var(--primary-soft)':'var(--bg-elevated)', color:filterOpen?'var(--geek-blue-200)':'var(--fg-secondary)' }}>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1.5 3.5h11M3.5 7h7M5.5 10.5h3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
                Filtros
              </button>
            </div>
            {filterOpen && (
              <div style={{ marginTop:14, paddingTop:14, borderTop:'1px solid var(--border-subtle)', display:'flex', flexDirection:'column', gap:12 }}>
                <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                  <span style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--fg-muted)', minWidth:56 }}>Tipo</span>
                  {[['todos','Todos'],['receita','Receitas'],['despesa','Despesas']].map(([id,l])=><button key={id} onClick={()=>setFilterTipo(id)} style={chip(filterTipo===id)}>{l}</button>)}
                </div>
                <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                  <span style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--fg-muted)', minWidth:56 }}>Status</span>
                  {[['todos','Todos'],['pago','Pago'],['pendente','Pendente']].map(([id,l])=><button key={id} onClick={()=>setFilterStatus(id)} style={chip(filterStatus===id)}>{l}</button>)}
                </div>
                <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                  <span style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--fg-muted)', minWidth:56 }}>Categoria</span>
                  <button onClick={()=>setFilterCat('')} style={chip(filterCat==='')}>Todas</button>
                  {allCats.map(c=><button key={c} onClick={()=>setFilterCat(c)} style={chip(filterCat===c)}>{c}</button>)}
                </div>
              </div>
            )}
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'80px 1fr 140px 130px 110px 80px 42px', padding:'12px 22px', borderBottom:'1px solid var(--border-subtle)', fontSize:11, fontFamily:'var(--font-display)', fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--fg-muted)' }}>
            <span>Data</span><span>Descrição</span><span>Categoria</span><span>Cliente</span><span>Status</span><span style={{ textAlign:'right' }}>Valor</span><span/>
          </div>
          {loading ? (
            <div style={{ padding:'32px 22px', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Carregando transações…</div>
          ) : filteredTxs.length === 0 ? (
            <div style={{ padding:'40px 22px', textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>
              Nenhuma transação encontrada. {!hasActive && <span onClick={()=>openAdd('receita')} style={{ color:'var(--geek-blue-300)', cursor:'pointer', textDecoration:'underline' }}>Adicione a primeira.</span>}
            </div>
          ) : filteredTxs.map((t,i) => (
            <div key={t.id||i} style={{ display:'grid', gridTemplateColumns:'80px 1fr 140px 130px 110px 80px 42px', padding:'14px 22px', borderBottom:'1px solid var(--border-subtle)', fontSize:13, alignItems:'center' }}>
              <span style={{ color:'var(--fg-muted)', fontFamily:'var(--font-mono)' }}>{t.d}</span>
              <span style={{ fontWeight:600 }}>{t.t}</span>
              <span style={{ color:'var(--fg-secondary)' }}>{t.cat}</span>
              <span style={{ color:'var(--fg-secondary)' }}>{t.who}</span>
              <Badge tone={t.status==='pago'?'success':'warning'}>{t.status}</Badge>
              <span style={{ textAlign:'right', fontFamily:'var(--font-display)', fontWeight:700, color:t.v.startsWith('+')?'#22C55E':'#FF6A6A' }}>{t.v}</span>
              <button onClick={()=>deleteTx(t.id)} title="Excluir" style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', fontSize:14, display:'flex', alignItems:'center', justifyContent:'center', padding:0 }}>🗑</button>
            </div>
          ))}
        </Card>
      </>)}

      {tab === 'areceber'   && <AReceberTab   txs={txs} loading={loading} onAdd={openAdd} onMarkPaid={markPaid} onDelete={deleteTx}/>}
      {tab === 'apagar'     && <APagarTab     txs={txs} loading={loading} onAdd={openAdd} onMarkPaid={markPaid} onDelete={deleteTx}/>}
      {tab === 'relatorios' && <RelatoriosTab txs={txs}/>}
    </div>

    {modalAberto && <NovaTransacaoModal onClose={()=>setModalAberto(false)} onSave={adicionarTx} defaultTipo={modalTipo}/>}
    {exportOpen  && <ExportModal onClose={()=>setExportOpen(false)}/>}
    </>
  );
}
window.Finance = Finance;
