
// Financeiro Module

function Financeiro({ onNavigate }) {
  const [loading, setLoading]         = React.useState(true);
  const [activeTab, setActiveTab]     = React.useState('geral');
  const [budgets, setBudgets]         = React.useState([]);
  const [budgetItems, setBudgetItems] = React.useState([]);
  const [freelancers, setFreelancers] = React.useState([]);
  const [periodType, setPeriodType]   = React.useState('mensal');
  const [periodOffset, setPeriodOffset] = React.useState(0);

  React.useEffect(() => {
    Promise.all([
      sb.from('budgets').select('*').order('created_at', { ascending: false }),
      sb.from('budget_items').select('*'),
      sb.from('freelancers').select('id, name, role, rate, payments, status').order('name'),
    ]).then(([{ data: b }, { data: bi }, { data: f }]) => {
      setBudgets(b || []);
      setBudgetItems(bi || []);
      setFreelancers(f || []);
      setLoading(false);
    });
  }, []);

  // ── Período ──────────────────────────────────────────────
  const getRange = (type, offset) => {
    const now = new Date();
    let start, end, label;

    if (type === 'todos') {
      return { start: new Date(2000, 0, 1), end: new Date(2099, 11, 31), label: 'Todo o período' };
    }

    if (type === 'diario') {
      const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() + offset);
      start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0);
      end   = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59);
      label = d.toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
      label = label.charAt(0).toUpperCase() + label.slice(1);
    } else if (type === 'semanal') {
      const d = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const dow = d.getDay();
      d.setDate(d.getDate() - dow + offset * 7);
      start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0);
      end   = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 6, 23, 59, 59);
      const fmt = { day: 'numeric', month: 'short' };
      label = `${start.toLocaleDateString('pt-BR', fmt)} – ${end.toLocaleDateString('pt-BR', { ...fmt, year: 'numeric' })}`;
    } else {
      const d = new Date(now.getFullYear(), now.getMonth() + offset, 1);
      start = new Date(d.getFullYear(), d.getMonth(), 1, 0, 0, 0);
      end   = new Date(d.getFullYear(), d.getMonth() + 1, 0, 23, 59, 59);
      label = d.toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
      label = label.charAt(0).toUpperCase() + label.slice(1);
    }
    return { start, end, label };
  };

  const { start: rangeStart, end: rangeEnd, label: rangeLabel } = getRange(periodType, periodOffset);

  // Parseia "dd/mm/yyyy" → Date
  const parsePayDate = (str) => {
    if (!str) return null;
    const p = str.split('/');
    if (p.length !== 3) return null;
    return new Date(+p[2], +p[1] - 1, +p[0]);
  };

  const inRange = (d) => d && d >= rangeStart && d <= rangeEnd;

  // ── Dados filtrados ───────────────────────────────────────
  const budgetTotals = React.useMemo(() => {
    const map = {};
    (budgetItems || []).forEach(item => {
      if (!map[item.budget_id]) map[item.budget_id] = 0;
      map[item.budget_id] += (item.qty || 1) * (item.unit_price || 0);
    });
    return map;
  }, [budgetItems]);

  const allPayments = freelancers.flatMap(f =>
    (f.payments || []).map(p => ({ ...p, freelancer: f.name, freelancerRole: f.role }))
  );

  // Filtrar pagamentos pelo período
  const filteredPayments = allPayments.filter(p => inRange(parsePayDate(p.data)));

  // Filtrar orçamentos pelo período (usa event_date ou created_at)
  const filteredBudgets = budgets.filter(b => {
    if (periodType === 'todos') return true;
    const d = b.event_date ? new Date(b.event_date) : (b.created_at ? new Date(b.created_at) : null);
    return inRange(d);
  });

  const totalAprovado         = filteredBudgets.filter(b => ['Aprovado','Concluído'].includes(b.status)).reduce((s,b) => s + (budgetTotals[b.id]||0), 0);
  const totalPendente         = filteredBudgets.filter(b => ['Pendente','Aguardando'].includes(b.status)).reduce((s,b) => s + (budgetTotals[b.id]||0), 0);
  const totalPagoFreelancers  = filteredPayments.reduce((s,p) => s + (p.valor||0), 0);
  const saldoLiquido          = totalAprovado - totalPagoFreelancers;

  const recentPayments = [...filteredPayments].sort((a,b) => b.id - a.id);

  const OG = DS.colors.primary;
  const metodoColor = { PIX: '#10B981', Cartão: '#3B82F6', Dinheiro: '#F59E0B' };
  const metodoEmoji = { PIX: '⚡', Cartão: '💳', Dinheiro: '💵' };
  const statusColor  = { Aprovado:'success', Concluído:'success', Pendente:'warning', Aguardando:'warning', Rascunho:'default', Cancelado:'danger' };
  const statusFColor = { Disponível:'success', Escalado:'primary', Indisponível:'danger' };

  const Tab = ({ id, label, icon }) => (
    <button onClick={() => setActiveTab(id)}
      style={{ padding:'8px 16px', borderRadius:DS.radius.sm, border:'none', background: activeTab===id ? OG : 'transparent', color: activeTab===id ? '#fff' : DS.colors.textSec, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', transition:'all 0.15s', display:'flex', alignItems:'center', gap:6 }}>
      <Icon name={icon} size={14} color={activeTab===id ? '#fff' : DS.colors.textSec} />
      {label}
    </button>
  );

  if (loading) return <div style={{ display:'flex', justifyContent:'center', paddingTop:80 }}><Spinner /></div>;

  return (
    <div>
      {/* ── Header ── */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:24 }}>
        <div>
          <h1 style={{ fontSize:24, fontWeight:700, color:DS.colors.text, margin:0, letterSpacing:'-0.02em' }}>Financeiro</h1>
          <p style={{ fontSize:13, color:DS.colors.textSec, margin:'4px 0 0' }}>Controle de receitas, orçamentos e pagamentos</p>
        </div>
      </div>

      {/* ── Seletor de período ── */}
      <Card style={{ padding:'14px 20px', marginBottom:20 }}>
        <div style={{ display:'flex', alignItems:'center', gap:16, flexWrap:'wrap' }}>

          {/* Toggle tipo */}
          <div style={{ display:'flex', gap:4, background:'#F1F5F9', borderRadius:DS.radius.sm, padding:4 }}>
            {[
              { id:'diario',  label:'Diário'  },
              { id:'semanal', label:'Semanal' },
              { id:'mensal',  label:'Mensal'  },
              { id:'todos',   label:'Todos'   },
            ].map(t => (
              <button key={t.id} onClick={() => { setPeriodType(t.id); setPeriodOffset(0); }}
                style={{ padding:'7px 16px', borderRadius:DS.radius.sm, border:'none', background: periodType===t.id ? OG : 'transparent', color: periodType===t.id ? '#fff' : DS.colors.textSec, fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit', transition:'all 0.15s' }}>
                {t.label}
              </button>
            ))}
          </div>

          {/* Navegação ◀ label ▶ */}
          {periodType !== 'todos' && (
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <button onClick={() => setPeriodOffset(o => o - 1)}
                style={{ width:30, height:30, borderRadius:DS.radius.sm, border:`1px solid ${DS.colors.border}`, background:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="arrow" size={14} color={DS.colors.textSec} style={{ transform:'rotate(180deg)' }} />
              </button>
              <div style={{ fontSize:13, fontWeight:700, color:DS.colors.text, minWidth:220, textAlign:'center' }}>{rangeLabel}</div>
              <button onClick={() => setPeriodOffset(o => o + 1)}
                style={{ width:30, height:30, borderRadius:DS.radius.sm, border:`1px solid ${DS.colors.border}`, background:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="arrow" size={14} color={DS.colors.textSec} />
              </button>
              {periodOffset !== 0 && (
                <button onClick={() => setPeriodOffset(0)}
                  style={{ padding:'5px 12px', borderRadius:DS.radius.sm, border:`1px solid ${DS.colors.border}`, background:'#fff', fontSize:11, fontWeight:700, color:DS.colors.textSec, cursor:'pointer', fontFamily:'inherit' }}>
                  Hoje
                </button>
              )}
            </div>
          )}

          {/* Resumo rápido do período */}
          <div style={{ marginLeft:'auto', fontSize:12, color:DS.colors.textMuted }}>
            <span style={{ fontWeight:700, color:DS.colors.text }}>{filteredPayments.length}</span> pgto{filteredPayments.length!==1?'s':''} ·{' '}
            <span style={{ fontWeight:700, color:DS.colors.text }}>{filteredBudgets.length}</span> orçamento{filteredBudgets.length!==1?'s':''}
          </div>
        </div>
      </Card>

      {/* ── Cards resumo ── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16, marginBottom:24 }}>
        {[
          { label:'Receita aprovada',   value:totalAprovado,        color:'#10B981', icon:'budget',  desc:'Orçamentos aprovados / concluídos' },
          { label:'Em negociação',      value:totalPendente,        color:'#F59E0B', icon:'clock',   desc:'Orçamentos pendentes de aprovação' },
          { label:'Pago a freelancers', value:totalPagoFreelancers, color:'#EF4444', icon:'users',   desc:`${filteredPayments.length} pagamento${filteredPayments.length!==1?'s':''} no período` },
          { label:'Saldo líquido',      value:saldoLiquido,         color:saldoLiquido>=0?'#10B981':'#EF4444', icon:'reports', desc:'Receita aprovada − cachês pagos' },
        ].map(c => (
          <Card key={c.label} style={{ padding:20 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:12 }}>
              <div style={{ fontSize:11, fontWeight:700, color:DS.colors.textMuted, textTransform:'uppercase', letterSpacing:'0.06em', lineHeight:1.4 }}>{c.label}</div>
              <div style={{ width:34, height:34, borderRadius:DS.radius.sm, background:c.color+'18', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, marginLeft:8 }}>
                <Icon name={c.icon} size={16} color={c.color} />
              </div>
            </div>
            <div style={{ fontSize:22, fontWeight:800, color:c.color, letterSpacing:'-0.02em' }}>
              {c.value<0&&'−'} R$ {Math.abs(c.value).toLocaleString('pt-BR',{minimumFractionDigits:2})}
            </div>
            <div style={{ fontSize:11, color:DS.colors.textMuted, marginTop:5 }}>{c.desc}</div>
          </Card>
        ))}
      </div>

      {/* ── Tabs ── */}
      <div style={{ display:'flex', gap:4, marginBottom:20, background:'#F1F5F9', borderRadius:DS.radius.sm, padding:4, width:'fit-content' }}>
        <Tab id="geral"       label="Visão Geral"  icon="dashboard" />
        <Tab id="orcamentos"  label="Orçamentos"   icon="budget"    />
        <Tab id="freelancers" label="Freelancers"  icon="users"     />
      </div>

      {/* ── VISÃO GERAL ── */}
      {activeTab==='geral' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 340px', gap:20 }}>
          <Card style={{ padding:24 }}>
            <div style={{ fontSize:14, fontWeight:700, color:DS.colors.text, marginBottom:16 }}>
              Pagamentos no período ({recentPayments.length})
            </div>
            {recentPayments.length===0 ? (
              <EmptyState icon="budget" title="Nenhum pagamento neste período" desc="Navegue entre os períodos ou selecione 'Todos' para ver o histórico completo." />
            ) : (
              <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
                {recentPayments.map((p,i) => (
                  <div key={p.id||i} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 12px', borderRadius:DS.radius.sm, background:i%2===0?'#F8FAFC':'#fff' }}>
                    <div style={{ width:36, height:36, borderRadius:'50%', background:(metodoColor[p.metodo]||OG)+'18', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontSize:16 }}>
                      {metodoEmoji[p.metodo]||'💰'}
                    </div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:13, fontWeight:600, color:DS.colors.text }}>{p.freelancer}</div>
                      <div style={{ fontSize:11, color:DS.colors.textSec }}>{p.descricao||p.freelancerRole} · {p.data}</div>
                    </div>
                    <div style={{ textAlign:'right' }}>
                      <div style={{ fontSize:14, fontWeight:700, color:'#EF4444' }}>
                        − R$ {(p.valor||0).toLocaleString('pt-BR',{minimumFractionDigits:2})}
                      </div>
                      <div style={{ display:'flex', gap:4, justifyContent:'flex-end', marginTop:3 }}>
                        <span style={{ fontSize:10, fontWeight:600, color:metodoColor[p.metodo], background:(metodoColor[p.metodo]||OG)+'18', padding:'1px 7px', borderRadius:8 }}>{p.metodo}</span>
                        {p.tipo==='parcial'&&<span style={{ fontSize:10, fontWeight:600, color:'#F59E0B', background:'#FEF9C3', padding:'1px 7px', borderRadius:8 }}>Parcial</span>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </Card>

          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            {/* Orçamentos por status */}
            <Card style={{ padding:20 }}>
              <div style={{ fontSize:13, fontWeight:700, color:DS.colors.text, marginBottom:14 }}>Orçamentos no período</div>
              {filteredBudgets.length===0 ? (
                <div style={{ fontSize:12, color:DS.colors.textMuted }}>Nenhum orçamento neste período.</div>
              ) : (
                ['Aprovado','Concluído','Pendente','Rascunho','Cancelado'].map(st => {
                  const list  = filteredBudgets.filter(b => b.status===st);
                  if(list.length===0) return null;
                  const total = list.reduce((s,b) => s+(budgetTotals[b.id]||0), 0);
                  const col   = { Aprovado:'#10B981', Concluído:'#3B82F6', Pendente:'#F59E0B', Rascunho:'#94A3B8', Cancelado:'#EF4444' };
                  return (
                    <div key={st} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'9px 0', borderBottom:'1px solid #F1F5F9' }}>
                      <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                        <div style={{ width:8, height:8, borderRadius:'50%', background:col[st] }} />
                        <span style={{ fontSize:13, color:DS.colors.textSec }}>{st}</span>
                        <span style={{ fontSize:11, background:'#F1F5F9', borderRadius:8, padding:'1px 7px', fontWeight:700, color:DS.colors.textMuted }}>{list.length}</span>
                      </div>
                      <div style={{ fontSize:13, fontWeight:700, color:col[st] }}>
                        R$ {total.toLocaleString('pt-BR',{minimumFractionDigits:0})}
                      </div>
                    </div>
                  );
                })
              )}
            </Card>

            {/* Método de pagamento */}
            <Card style={{ padding:20 }}>
              <div style={{ fontSize:13, fontWeight:700, color:DS.colors.text, marginBottom:14 }}>Método de pagamento</div>
              {filteredPayments.length===0 ? (
                <div style={{ fontSize:12, color:DS.colors.textMuted }}>Nenhum pagamento neste período.</div>
              ) : (
                ['PIX','Cartão','Dinheiro'].map(m => {
                  const pags  = filteredPayments.filter(p => p.metodo===m);
                  const total = pags.reduce((s,p) => s+(p.valor||0), 0);
                  if(total===0) return null;
                  return (
                    <div key={m} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'9px 0', borderBottom:'1px solid #F1F5F9' }}>
                      <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                        <span style={{ fontSize:18 }}>{metodoEmoji[m]}</span>
                        <span style={{ fontSize:13, color:DS.colors.textSec }}>{m}</span>
                        <span style={{ fontSize:11, background:'#F1F5F9', borderRadius:8, padding:'1px 7px', fontWeight:700, color:DS.colors.textMuted }}>{pags.length}</span>
                      </div>
                      <div style={{ fontSize:13, fontWeight:700, color:metodoColor[m] }}>
                        R$ {total.toLocaleString('pt-BR',{minimumFractionDigits:2})}
                      </div>
                    </div>
                  );
                })
              )}
            </Card>

            {/* Atalhos */}
            <Card style={{ padding:20 }}>
              <div style={{ fontSize:13, fontWeight:700, color:DS.colors.text, marginBottom:12 }}>Atalhos</div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                <Btn variant="secondary" icon="budget" style={{ justifyContent:'flex-start', width:'100%' }} onClick={() => onNavigate&&onNavigate('budgets')}>Ir para Orçamentos</Btn>
                <Btn variant="secondary" icon="users"  style={{ justifyContent:'flex-start', width:'100%' }} onClick={() => onNavigate&&onNavigate('freelancers')}>Ir para Freelancers</Btn>
              </div>
            </Card>
          </div>
        </div>
      )}

      {/* ── ORÇAMENTOS ── */}
      {activeTab==='orcamentos' && (
        <Card style={{ padding:0 }}>
          <div style={{ padding:'14px 20px', borderBottom:`1px solid ${DS.colors.border}`, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <span style={{ fontSize:14, fontWeight:700, color:DS.colors.text }}>Orçamentos · {rangeLabel}</span>
            <span style={{ fontSize:12, color:DS.colors.textMuted }}>{filteredBudgets.length} orçamento{filteredBudgets.length!==1?'s':''} · Aprovados: <strong style={{ color:'#10B981' }}>R$ {totalAprovado.toLocaleString('pt-BR',{minimumFractionDigits:2})}</strong></span>
          </div>
          {filteredBudgets.length===0 ? (
            <div style={{ padding:40 }}><EmptyState icon="budget" title="Nenhum orçamento neste período" desc="Tente mudar o período ou selecione 'Todos'." /></div>
          ) : (
            <div>
              <div style={{ display:'grid', gridTemplateColumns:'90px 1fr 130px 120px 110px', gap:16, padding:'10px 20px', background:'#F8FAFC', fontSize:11, fontWeight:700, color:DS.colors.textMuted, textTransform:'uppercase', letterSpacing:'0.06em', borderBottom:`1px solid ${DS.colors.border}` }}>
                <div>Código</div><div>Cliente</div><div>Data</div><div>Valor</div><div>Status</div>
              </div>
              {filteredBudgets.map((b,i) => (
                <div key={b.id}
                  style={{ display:'grid', gridTemplateColumns:'90px 1fr 130px 120px 110px', gap:16, padding:'13px 20px', borderBottom:i<filteredBudgets.length-1?`1px solid ${DS.colors.border}`:'none', alignItems:'center', transition:'background 0.1s' }}
                  onMouseEnter={e => e.currentTarget.style.background='#F8FAFC'}
                  onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                  <div style={{ fontSize:12, fontWeight:800, color:OG }}>{b.code}</div>
                  <div>
                    <div style={{ fontSize:13, fontWeight:600, color:DS.colors.text }}>{b.client_name}</div>
                    {b.notes&&<div style={{ fontSize:11, color:DS.colors.textMuted, marginTop:2 }}>{String(b.notes).slice(0,55)}{String(b.notes).length>55?'…':''}</div>}
                  </div>
                  <div style={{ fontSize:12, color:DS.colors.textSec }}>{b.event_date?new Date(b.event_date).toLocaleDateString('pt-BR'):'—'}</div>
                  <div style={{ fontSize:14, fontWeight:800, color:DS.colors.text }}>R$ {(budgetTotals[b.id]||0).toLocaleString('pt-BR',{minimumFractionDigits:2})}</div>
                  <div><Badge variant={statusColor[b.status]||'default'}>{b.status}</Badge></div>
                </div>
              ))}
              <div style={{ display:'grid', gridTemplateColumns:'90px 1fr 130px 120px 110px', gap:16, padding:'12px 20px', background:'#F8FAFC', borderTop:`2px solid ${DS.colors.border}` }}>
                <div /><div style={{ fontSize:12, fontWeight:700, color:DS.colors.textSec }}>Total</div><div />
                <div style={{ fontSize:14, fontWeight:800, color:DS.colors.text }}>R$ {filteredBudgets.reduce((s,b)=>s+(budgetTotals[b.id]||0),0).toLocaleString('pt-BR',{minimumFractionDigits:2})}</div>
                <div />
              </div>
            </div>
          )}
        </Card>
      )}

      {/* ── FREELANCERS ── */}
      {activeTab==='freelancers' && (
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          <Card style={{ padding:0 }}>
            <div style={{ padding:'14px 20px', borderBottom:`1px solid ${DS.colors.border}`, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <span style={{ fontSize:14, fontWeight:700, color:DS.colors.text }}>Freelancers · {rangeLabel}</span>
              <span style={{ fontSize:12, color:DS.colors.textMuted }}>Total pago: <strong style={{ color:'#EF4444' }}>R$ {totalPagoFreelancers.toLocaleString('pt-BR',{minimumFractionDigits:2})}</strong></span>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 110px 130px 70px 110px', gap:16, padding:'10px 20px', background:'#F8FAFC', fontSize:11, fontWeight:700, color:DS.colors.textMuted, textTransform:'uppercase', letterSpacing:'0.06em', borderBottom:`1px solid ${DS.colors.border}` }}>
              <div>Freelancer</div><div>Cachê/dia</div><div>Pago no período</div><div>Pgtos</div><div>Status</div>
            </div>
            {freelancers.map((f,i) => {
              const pags      = filteredPayments.filter(p => p.freelancer===f.name);
              const totalPago = pags.reduce((s,p)=>s+(p.valor||0),0);
              return (
                <div key={f.id}
                  style={{ display:'grid', gridTemplateColumns:'1fr 110px 130px 70px 110px', gap:16, padding:'13px 20px', borderBottom:i<freelancers.length-1?`1px solid ${DS.colors.border}`:'none', alignItems:'center', transition:'background 0.1s' }}
                  onMouseEnter={e=>e.currentTarget.style.background='#F8FAFC'}
                  onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                  <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                    <Avatar name={f.name} size={34} />
                    <div>
                      <div style={{ fontSize:13, fontWeight:600, color:DS.colors.text }}>{f.name}</div>
                      <div style={{ fontSize:11, color:DS.colors.textSec }}>{f.role}</div>
                    </div>
                  </div>
                  <div style={{ fontSize:13, fontWeight:600, color:DS.colors.text }}>R$ {(f.rate||0).toLocaleString('pt-BR')}</div>
                  <div style={{ fontSize:14, fontWeight:800, color:totalPago>0?'#10B981':DS.colors.textMuted }}>
                    {totalPago>0?`R$ ${totalPago.toLocaleString('pt-BR',{minimumFractionDigits:2})}`:'—'}
                  </div>
                  <div style={{ fontSize:13, color:DS.colors.textSec, textAlign:'center' }}>{pags.length}</div>
                  <div><Badge variant={statusFColor[f.status]||'default'}>{f.status}</Badge></div>
                </div>
              );
            })}
            <div style={{ display:'grid', gridTemplateColumns:'1fr 110px 130px 70px 110px', gap:16, padding:'12px 20px', background:'#F8FAFC', borderTop:`2px solid ${DS.colors.border}` }}>
              <div style={{ fontSize:12, fontWeight:700, color:DS.colors.textSec }}>{freelancers.length} freelancer{freelancers.length!==1?'s':''}</div>
              <div /><div style={{ fontSize:14, fontWeight:800, color:'#EF4444' }}>R$ {totalPagoFreelancers.toLocaleString('pt-BR',{minimumFractionDigits:2})}</div>
              <div style={{ fontSize:13, fontWeight:700, color:DS.colors.textSec }}>{filteredPayments.length}</div>
              <div />
            </div>
          </Card>

          {recentPayments.length>0&&(
            <Card style={{ padding:24 }}>
              <div style={{ fontSize:14, fontWeight:700, color:DS.colors.text, marginBottom:16 }}>Detalhamento · {rangeLabel}</div>
              <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
                {recentPayments.map((p,i)=>(
                  <div key={p.id||i} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 12px', borderRadius:DS.radius.sm, background:i%2===0?'#F8FAFC':'#fff' }}>
                    <div style={{ width:34, height:34, borderRadius:'50%', background:(metodoColor[p.metodo]||OG)+'18', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontSize:16 }}>
                      {metodoEmoji[p.metodo]||'💰'}
                    </div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:13, fontWeight:600, color:DS.colors.text }}>{p.freelancer} <span style={{ fontWeight:400, color:DS.colors.textSec }}>· {p.freelancerRole}</span></div>
                      <div style={{ fontSize:11, color:DS.colors.textSec }}>{p.descricao||'—'} · {p.data}</div>
                    </div>
                    <div style={{ textAlign:'right' }}>
                      <div style={{ fontSize:14, fontWeight:700, color:'#EF4444' }}>R$ {(p.valor||0).toLocaleString('pt-BR',{minimumFractionDigits:2})}</div>
                      <div style={{ display:'flex', gap:4, justifyContent:'flex-end', marginTop:3 }}>
                        <span style={{ fontSize:10, fontWeight:600, color:metodoColor[p.metodo], background:(metodoColor[p.metodo]||OG)+'18', padding:'1px 7px', borderRadius:8 }}>{p.metodo}</span>
                        {p.tipo==='parcial'&&<span style={{ fontSize:10, fontWeight:600, color:'#F59E0B', background:'#FEF9C3', padding:'1px 7px', borderRadius:8 }}>Parcial</span>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </Card>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Financeiro });
