// Caririaçu Guincho — Financeiro Screen

const { useState: useStateFin, useEffect: useEffectFin } = React;

const FinanceiroScreen = () => {
  const [transacoes, setTransacoes] = useStateFin([]);
  const [categorias, setCategorias] = useStateFin([]);
  const [motoristas, setMotoristas] = useStateFin([]);
  const [loading, setLoading] = useStateFin(true);
  const [modal, setModal] = useStateFin(false);
  const [holModal, setHolModal] = useStateFin(false);
  const [filtroTipo, setFiltroTipo] = useStateFin('');
  const [busca, setBusca] = useStateFin('');
  const [page, setPage] = useStateFin(1);
  const PER = 6;

  const [form, setForm] = useStateFin({ tipo: 'entrada', descricao: '', categoria: 'Serviço Prestado', valor: '', data: new Date().toISOString().slice(0,10), assistencia_numero: '', obs: '' });
  const set = (k,v) => setForm(f => ({...f,[k]:v}));

  const fmtBRL = v => Number(v || 0).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});

  const refresh = async () => {
    setLoading(true);
    const [t, c, m] = await Promise.all([
      db.list('transacoes', { order: 'data' }),
      db.list('categorias_financeiras', { order: 'nome', asc: true }),
      db.list('motoristas', { order: 'nome', asc: true })
    ]);
    setTransacoes(t);
    setCategorias(c);
    setMotoristas(m);
    setLoading(false);
  };
  useEffectFin(() => { refresh(); }, []);

  const entradas = transacoes.filter(t=>t.tipo==='entrada').reduce((s,t)=>s+Number(t.valor||0),0);
  const saidas   = transacoes.filter(t=>t.tipo==='saida').reduce((s,t)=>s+Number(t.valor||0),0);
  const saldo    = entradas - saidas;
  const hoje = new Date().toISOString().slice(0,10);
  const caixaDia = transacoes.filter(t => t.data === hoje).reduce((s,t)=>s+(t.tipo==='entrada'?Number(t.valor||0):-Number(t.valor||0)),0);

  const filtered = transacoes.filter(t => {
    const q = busca.toLowerCase();
    const mQ = !q || t.descricao.toLowerCase().includes(q) || (t.categoria || '').toLowerCase().includes(q);
    const mT = !filtroTipo || t.tipo === filtroTipo;
    return mQ && mT;
  });
  const paged = filtered.slice((page-1)*PER, page*PER);

  const handleSave = async () => {
    if (!form.descricao || !form.valor) { showToast('Preencha descrição e valor', 'warning'); return; }
    const created = await db.insert('transacoes', {
      tipo: form.tipo, descricao: form.descricao, categoria: form.categoria,
      valor: parseFloat(form.valor) || 0, data: form.data, obs: form.obs,
      assistencia_numero: form.assistencia_numero || null,
    });
    if (created) {
      showToast('Transação registrada!','success');
      setModal(false);
      setForm({ tipo:'entrada', descricao:'', categoria:'Serviço Prestado', valor:'', data:new Date().toISOString().slice(0,10), assistencia_numero:'', obs:'' });
      refresh();
    }
  };

  const handleDelete = async (id) => {
    const ok = await db.remove('transacoes', id);
    if (ok) { showToast('Transação removida','warning'); refresh(); }
  };

  // Holerite
  const [holForm, setHolForm] = useStateFin({
    motoristaId: '',
    periodo: new Date().toISOString().slice(0,7),
    salarioBase: '',
    adicionais: '',
    descontos: '',
  });
  useEffectFin(() => {
    if (motoristas.length > 0 && !holForm.motoristaId) setHolForm(f => ({ ...f, motoristaId: motoristas[0].id }));
  }, [motoristas]);
  const setHol = (k,v) => setHolForm(f => ({...f,[k]:v}));
  const holLiquido = (parseFloat(holForm.salarioBase) || 0) + (parseFloat(holForm.adicionais) || 0) - (parseFloat(holForm.descontos) || 0);
  const holMotorista = motoristas.find(m => m.id === parseInt(holForm.motoristaId)) || motoristas[0] || {};

  const gerarHoleritePDF = () => {
    if (!holMotorista.id) { showToast('Cadastre um motorista antes', 'warning'); return; }
    const fmt = v => (parseFloat(v) || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    const [ano, mes] = (holForm.periodo || '').split('-');
    const meses = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
    const periodoLabel = mes ? `${meses[parseInt(mes)-1]} de ${ano}` : holForm.periodo;
    const numHolerite = `HOL-${Date.now().toString().slice(-6)}`;
    const dataEmissao = new Date().toLocaleDateString('pt-BR');

    const html = `<!DOCTYPE html><html lang="pt-BR"><head><meta charset="UTF-8"><title>Holerite ${holMotorista.nome} — ${periodoLabel}</title>
<link rel="icon" type="image/png" href="${window.location.origin}/logo.png" />
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: 'Segoe UI', Arial, sans-serif; color: #0F172A; padding: 40px; background: #fff; }
  .holerite { max-width: 720px; margin: 0 auto; border: 2px solid #0F172A; }
  .header { background: linear-gradient(135deg,#1E293B,#0F172A); color: #fff; padding: 24px 28px; display: flex; justify-content: space-between; align-items: center; }
  .header h1 { font-size: 22px; font-weight: 700; letter-spacing: 0.5px; }
  .header .logo { display: flex; align-items: center; gap: 12px; }
  .header .logo-text { font-size: 11px; opacity: 0.8; letter-spacing: 1px; text-transform: uppercase; }
  .meta { padding: 16px 28px; background: #F8FAFC; border-bottom: 1px solid #E2E8F0; display: grid; grid-template-columns: repeat(3,1fr); gap: 12px; font-size: 12px; }
  .meta-label { color: #64748B; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; font-size: 10px; }
  .meta-value { color: #0F172A; font-weight: 600; margin-top: 2px; }
  .section { padding: 20px 28px; border-bottom: 1px solid #E2E8F0; }
  .section h2 { font-size: 13px; color: #64748B; text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 12px; font-weight: 700; border-bottom: 2px solid #F59E0B; padding-bottom: 6px; display: inline-block; }
  .info-grid { display: grid; grid-template-columns: repeat(2,1fr); gap: 14px; }
  .info-label { font-size: 10px; color: #94A3B8; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
  .info-value { font-size: 14px; color: #0F172A; font-weight: 600; margin-top: 2px; }
  table { width: 100%; border-collapse: collapse; margin-top: 8px; }
  th { background: #F8FAFC; padding: 10px 14px; text-align: left; font-size: 11px; color: #64748B; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid #E2E8F0; }
  th.r { text-align: right; }
  td { padding: 12px 14px; font-size: 13px; border-bottom: 1px solid #F1F5F9; }
  td.r { text-align: right; font-family: 'Courier New', monospace; font-weight: 600; }
  td.green { color: #10B981; }
  td.red { color: #EF4444; }
  .totals { padding: 20px 28px; background: #F8FAFC; }
  .totals-row { display: flex; justify-content: space-between; padding: 6px 0; font-size: 14px; }
  .totals-row.green { color: #10B981; }
  .totals-row.red { color: #EF4444; }
  .totals-row.liquido { border-top: 2px solid #0F172A; margin-top: 10px; padding-top: 14px; font-size: 18px; font-weight: 800; }
  .liquido-value { font-family: 'Courier New', monospace; color: #10B981; }
  .footer { padding: 24px 28px; text-align: center; font-size: 11px; color: #94A3B8; }
  .signatures { display: grid; grid-template-columns: 1fr 1fr; gap: 60px; margin-top: 50px; padding: 0 28px 30px; }
  .sig { text-align: center; border-top: 1px solid #0F172A; padding-top: 8px; font-size: 12px; color: #374151; }
  .print-btn { position: fixed; top: 20px; right: 20px; background: #F59E0B; color: #0F172A; border: none; padding: 12px 22px; border-radius: 8px; font-size: 14px; font-weight: 700; cursor: pointer; box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
  @media print { body { padding: 0; } .print-btn { display: none; } .holerite { border: 1px solid #0F172A; } }
</style></head><body>
<button class="print-btn" onclick="window.print()">📥 Salvar como PDF / Imprimir</button>
<div class="holerite">
  <div class="header">
    <div class="logo">
      <img src="${window.location.origin}/logo.png" alt="Caririaçu Guincho" style="width:56px;height:56px;border-radius:50%;object-fit:cover;transform:scale(1.08);box-shadow:0 0 0 2px rgba(245,158,11,0.6);" />
      <div><h1>Caririaçu Guincho</h1><div class="logo-text">Recibo de Pagamento de Salário</div></div>
    </div>
    <div style="text-align:right; font-size:12px;"><div style="opacity:0.8;">Nº ${numHolerite}</div><div style="margin-top:4px; font-weight:600;">${dataEmissao}</div></div>
  </div>
  <div class="meta">
    <div><div class="meta-label">Período</div><div class="meta-value">${periodoLabel}</div></div>
    <div><div class="meta-label">Funcionário</div><div class="meta-value">${holMotorista.nome}</div></div>
    <div><div class="meta-label">Cargo</div><div class="meta-value">Motorista de Guincho</div></div>
  </div>
  <div class="section">
    <h2>Dados do Funcionário</h2>
    <div class="info-grid">
      <div><div class="info-label">Nome Completo</div><div class="info-value">${holMotorista.nome}</div></div>
      <div><div class="info-label">CNH</div><div class="info-value">${holMotorista.cnh || '—'} · Cat. ${holMotorista.categoria || '—'}</div></div>
      <div><div class="info-label">Telefone</div><div class="info-value">${holMotorista.telefone || '—'}</div></div>
      <div><div class="info-label">Guincho</div><div class="info-value">${holMotorista.guincho_code || '—'}</div></div>
    </div>
  </div>
  <div class="section">
    <h2>Composição do Salário</h2>
    <table>
      <thead><tr><th>Descrição</th><th>Referência</th><th class="r">Valor</th></tr></thead>
      <tbody>
        <tr><td>Salário Base</td><td style="color:#64748B; font-size:12px;">30 dias</td><td class="r">R$ ${fmt(holForm.salarioBase)}</td></tr>
        <tr><td>Adicionais (HE / Bonificação)</td><td style="color:#64748B; font-size:12px;">—</td><td class="r green">+ R$ ${fmt(holForm.adicionais)}</td></tr>
        <tr><td>Descontos (INSS / IRRF / Outros)</td><td style="color:#64748B; font-size:12px;">—</td><td class="r red">− R$ ${fmt(holForm.descontos)}</td></tr>
      </tbody>
    </table>
  </div>
  <div class="totals">
    <div class="totals-row"><span>Total de Vencimentos</span><span style="font-family:'Courier New',monospace; font-weight:600;">R$ ${fmt((parseFloat(holForm.salarioBase)||0) + (parseFloat(holForm.adicionais)||0))}</span></div>
    <div class="totals-row red"><span>Total de Descontos</span><span style="font-family:'Courier New',monospace; font-weight:600;">R$ ${fmt(holForm.descontos)}</span></div>
    <div class="totals-row liquido"><span>VALOR LÍQUIDO A RECEBER</span><span class="liquido-value">R$ ${fmt(holLiquido)}</span></div>
  </div>
  <div class="signatures"><div class="sig">Assinatura do Funcionário</div><div class="sig">Assinatura da Empresa</div></div>
  <div class="footer">Recibo gerado em ${dataEmissao} · Caririaçu Guincho · Rapidez · Segurança · Confiança · ${numHolerite}</div>
</div>
<script>setTimeout(() => window.print(), 400);</script>
</body></html>`;

    const win = window.open('', '_blank', 'width=860,height=900');
    if (!win) { showToast('Habilite popups para gerar o PDF','warning'); return; }
    win.document.write(html); win.document.close();
    showToast('Holerite gerado','success');
    setHolModal(false);
  };

  const CATS_ENT = ['Serviço Prestado','Reembolso Seguradora','Outros'];
  const CATS_SAI = ['Combustível','Manutenção','Salários','Seguros','Impostos','Outros'];
  const opcoesCat = form.tipo === 'entrada' ? CATS_ENT : CATS_SAI;

  return (
    <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif' }}>Financeiro</h1>
          <span style={{ fontSize:13, color:'#64748B' }}>Controle de entradas, saídas e holerites</span>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <Btn variant="secondary" icon="fileText" onClick={() => setHolModal(true)}>Gerar Holerite</Btn>
          <Btn variant="primary" icon="plus" onClick={() => setModal(true)}>Nova Transação</Btn>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(180px,1fr))', gap: 16 }}>
        <Card style={{ padding: 20 }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
            <div style={{ width:36, height:36, borderRadius:9, background:'#ECFDF5', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon name="trendUp" size={18} color="#10B981"/>
            </div>
            <span style={{ fontSize:13, color:'#64748B', fontWeight:500 }}>Total Entradas</span>
          </div>
          <div style={{ fontSize: 24, fontWeight: 700, color: '#10B981', fontFamily: 'DM Mono, monospace' }}>{fmtBRL(entradas)}</div>
        </Card>
        <Card style={{ padding: 20 }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
            <div style={{ width:36, height:36, borderRadius:9, background:'#FEF2F2', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon name="trendDown" size={18} color="#EF4444"/>
            </div>
            <span style={{ fontSize:13, color:'#64748B', fontWeight:500 }}>Total Saídas</span>
          </div>
          <div style={{ fontSize: 24, fontWeight: 700, color: '#EF4444', fontFamily: 'DM Mono, monospace' }}>{fmtBRL(saidas)}</div>
        </Card>
        <Card style={{ padding: 20 }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
            <div style={{ width:36, height:36, borderRadius:9, background:'#EFF6FF', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon name="dollar" size={18} color="#3B82F6"/>
            </div>
            <span style={{ fontSize:13, color:'#64748B', fontWeight:500 }}>Saldo</span>
          </div>
          <div style={{ fontSize: 24, fontWeight: 700, color: saldo >= 0 ? '#10B981' : '#EF4444', fontFamily: 'DM Mono, monospace' }}>{fmtBRL(saldo)}</div>
        </Card>
        <Card style={{ padding: 20 }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
            <div style={{ width:36, height:36, borderRadius:9, background:'#FFF7ED', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon name="calendar" size={18} color="#F59E0B"/>
            </div>
            <span style={{ fontSize:13, color:'#64748B', fontWeight:500 }}>Hoje</span>
          </div>
          <div style={{ fontSize: 24, fontWeight: 700, color: caixaDia >= 0 ? '#10B981' : '#EF4444', fontFamily: 'DM Mono, monospace' }}>{fmtBRL(caixaDia)}</div>
        </Card>
      </div>

      <Card style={{ padding: 16 }}>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <div style={{ position: 'relative', flex: 1, minWidth: 200 }}>
            <Icon name="search" size={15} color="#94A3B8" style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)' }} />
            <input value={busca} onChange={e => { setBusca(e.target.value); setPage(1); }} placeholder="Buscar transação..."
              style={{ width: '100%', paddingLeft: 34, paddingRight: 12, paddingTop: 9, paddingBottom: 9, borderRadius: 8, border: '1px solid #E2E8F0', fontSize: 13, color: '#0F172A', fontFamily: 'Inter, sans-serif', outline: 'none', boxSizing: 'border-box' }} />
          </div>
          <select value={filtroTipo} onChange={e => { setFiltroTipo(e.target.value); setPage(1); }} style={{ padding: '9px 12px', borderRadius: 8, border: '1px solid #E2E8F0', fontSize: 13, color: '#374151', outline: 'none', background: '#fff', cursor: 'pointer' }}>
            <option value="">Todos os tipos</option>
            <option value="entrada">Apenas Entradas</option>
            <option value="saida">Apenas Saídas</option>
          </select>
        </div>
      </Card>

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>Carregando...</div>
        ) : paged.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center' }}>
            <Icon name="dollar" size={48} color="#CBD5E1" />
            <div style={{ fontSize: 16, color: '#64748B', marginTop: 14, fontWeight: 600 }}>{transacoes.length === 0 ? 'Nenhuma transação registrada' : 'Nenhum resultado'}</div>
            <div style={{ fontSize: 13, color: '#94A3B8', marginTop: 4 }}>{transacoes.length === 0 ? 'Comece registrando entradas e saídas' : 'Tente ajustar os filtros'}</div>
          </div>
        ) : (
          <table style={{ width:'100%', borderCollapse: 'collapse', fontSize:13, fontFamily:'Inter, sans-serif' }}>
            <thead>
              <tr style={{ background: '#F8FAFC' }}>
                {['Data','Descrição','Categoria','Tipo','Valor','Ações'].map(h=>(
                  <th key={h} style={{ padding:'11px 16px', textAlign:'left', fontSize:12, fontWeight:600, color:'#64748B', borderBottom:'1px solid #E2E8F0', whiteSpace:'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {paged.map((t,i)=>(
                <tr key={t.id} style={{ background:i%2?'#F8FAFC':'#fff' }}>
                  <td style={{ padding:'12px 16px', color:'#64748B' }}>{new Date(t.data).toLocaleDateString('pt-BR')}</td>
                  <td style={{ padding:'12px 16px', color:'#0F172A', fontWeight:500 }}>{t.descricao}</td>
                  <td style={{ padding:'12px 16px' }}><span style={{ background:'#F1F5F9', borderRadius:6, padding:'2px 9px', fontSize:12, color:'#64748B', fontWeight:500 }}>{t.categoria || '—'}</span></td>
                  <td style={{ padding:'12px 16px' }}><StatusBadge status={t.tipo}/></td>
                  <td style={{ padding:'12px 16px', textAlign:'right', fontFamily:'DM Mono, monospace', fontWeight:700, color: t.tipo==='entrada'?'#10B981':'#EF4444' }}>
                    {t.tipo==='entrada'?'+ ':'− '}R$ {Number(t.valor).toFixed(2)}
                  </td>
                  <td style={{ padding:'12px 16px' }}>
                    <button onClick={() => handleDelete(t.id)} style={{ background:'none',border:'none',cursor:'pointer',color:'#EF4444',padding:4,borderRadius:6 }} onMouseEnter={e=>e.currentTarget.style.background='#FEF2F2'} onMouseLeave={e=>e.currentTarget.style.background='none'}>
                      <Icon name="trash" size={15}/>
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        <div style={{ padding: '14px 20px', borderTop: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
          <span style={{ fontSize: 13, color: '#64748B' }}>Mostrando {Math.min(filtered.length, PER)} de {filtered.length} registros</span>
          <Pagination page={page} total={filtered.length} perPage={PER} onChange={setPage} />
        </div>
      </Card>

      <Modal open={modal} onClose={()=>setModal(false)} title="Nova Transação" width={520}>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <Select label="Tipo" value={form.tipo} onChange={e=>{set('tipo',e.target.value); set('categoria', e.target.value === 'entrada' ? CATS_ENT[0] : CATS_SAI[0]);}}
              options={[{value:'entrada',label:'Entrada'},{value:'saida',label:'Saída'}]}/>
            <Input label="Data" type="date" value={form.data} onChange={e=>set('data',e.target.value)}/>
          </div>
          <Input label="Descrição" placeholder="Ex: Serviço prestado para Porto Seguro" value={form.descricao} onChange={e=>set('descricao',e.target.value)}/>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <Select label="Categoria" value={form.categoria} onChange={e=>set('categoria',e.target.value)}
              options={opcoesCat.map(v=>({value:v,label:v}))}/>
            <Input label="Valor (R$)" type="number" placeholder="0.00" value={form.valor} onChange={e=>set('valor',e.target.value)}/>
          </div>
          <Input label="Nº Assistência (opcional)" placeholder="#ASS-0001" value={form.assistencia_numero} onChange={e=>set('assistencia_numero',e.target.value)}/>
          <Input label="Observações" value={form.obs} onChange={e=>set('obs',e.target.value)}/>
          <div style={{ display:'flex', gap:10, justifyContent:'flex-end', paddingTop:8, borderTop:'1px solid #F1F5F9' }}>
            <Btn variant="secondary" onClick={()=>setModal(false)}>Cancelar</Btn>
            <Btn variant="primary" onClick={handleSave}>Registrar</Btn>
          </div>
        </div>
      </Modal>

      <Modal open={holModal} onClose={()=>setHolModal(false)} title="Gerar Holerite" width={460}>
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          {motoristas.length === 0 ? (
            <div style={{ padding: 20, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>
              <Icon name="users" size={32} color="#CBD5E1" />
              <div style={{ marginTop: 8 }}>Cadastre um motorista antes de gerar holerite.</div>
            </div>
          ) : (
            <>
              <Select label="Motorista" value={holForm.motoristaId} onChange={e=>setHol('motoristaId', e.target.value)} options={motoristas.map(m=>({value:m.id,label:m.nome}))}/>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
                <Input label="Período" type="month" value={holForm.periodo} onChange={e=>setHol('periodo', e.target.value)}/>
                <Input label="Salário Base (R$)" type="number" placeholder="3200.00" value={holForm.salarioBase} onChange={e=>setHol('salarioBase', e.target.value)}/>
                <Input label="Adicionais (R$)" type="number" placeholder="0.00" value={holForm.adicionais} onChange={e=>setHol('adicionais', e.target.value)}/>
                <Input label="Descontos (R$)" type="number" placeholder="0.00" value={holForm.descontos} onChange={e=>setHol('descontos', e.target.value)}/>
              </div>
              <div style={{ background:'#F8FAFC', borderRadius:10, padding:16, display:'flex', flexDirection:'column', gap:8 }}>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, color:'#374151' }}><span>Salário Base</span><span style={{ fontFamily:'DM Mono, monospace', fontWeight:600 }}>{fmtBRL(parseFloat(holForm.salarioBase) || 0)}</span></div>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, color:'#10B981' }}><span>+ Adicionais</span><span style={{ fontFamily:'DM Mono, monospace', fontWeight:600 }}>{fmtBRL(parseFloat(holForm.adicionais) || 0)}</span></div>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, color:'#EF4444' }}><span>- Descontos</span><span style={{ fontFamily:'DM Mono, monospace', fontWeight:600 }}>{fmtBRL(parseFloat(holForm.descontos) || 0)}</span></div>
                <div style={{ borderTop:'1px solid #E2E8F0', paddingTop:8, display:'flex', justifyContent:'space-between', fontSize:15, fontWeight:700, color:'#0F172A' }}><span>Líquido</span><span style={{ fontFamily:'DM Mono, monospace', color:'#10B981' }}>{fmtBRL(holLiquido)}</span></div>
              </div>
              <div style={{ display:'flex', gap:10, justifyContent:'flex-end', paddingTop:8, borderTop:'1px solid #F1F5F9' }}>
                <Btn variant="secondary" onClick={()=>setHolModal(false)}>Cancelar</Btn>
                <Btn variant="primary" icon="download" onClick={gerarHoleritePDF}>Gerar PDF</Btn>
              </div>
            </>
          )}
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { FinanceiroScreen });
