
// ============================================================
// JuFlow — Financeiro
// ============================================================
const { useState: useStFN, useMemo: useMemoFN } = React;
const UFN = window.JFUtils;

// ─── Native SVG Cash Flow Chart (no CDN dependency) ──────
const CashFlowChart = ({ data }) => {
  const [hover, setHover] = useStFN(null);
  const W = 760, H = 240;
  const padL = 56, padR = 16, padT = 24, padB = 32;
  const innerW = W - padL - padR;
  const innerH = H - padT - padB;

  const maxV = Math.max(1, ...data.flatMap(d => [d.entradas, d.saidas]));
  const niceMax = Math.ceil(maxV / 5000) * 5000 || 5000;
  const yScale = v => padT + innerH - (v / niceMax) * innerH;
  const groupW = innerW / data.length;
  const barW = Math.min(28, groupW / 3);
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => Math.round(niceMax * t));

  const fmtBR = v => 'R$ ' + (v >= 1000 ? (v/1000).toFixed(v % 1000 === 0 ? 0 : 1) + 'k' : v.toFixed(0));

  // Saldo line points
  const linePoints = data.map((d, i) => {
    const cx = padL + groupW * i + groupW / 2;
    const saldo = Math.max(0, d.entradas - d.saidas);
    return { x: cx, y: yScale(saldo), saldo };
  });
  const lineD = linePoints.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x},${p.y}`).join(' ');

  return (
    <div style={{ position:'relative' }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} style={{ display:'block' }}>
        <defs>
          <linearGradient id="gIncome" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#10B981" />
            <stop offset="100%" stopColor="#059669" />
          </linearGradient>
          <linearGradient id="gExpense" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#FCA5A5" />
            <stop offset="100%" stopColor="#EF4444" />
          </linearGradient>
        </defs>

        {/* Y grid + labels */}
        {yTicks.map(v => (
          <g key={v}>
            <line x1={padL} y1={yScale(v)} x2={W - padR} y2={yScale(v)} stroke="#F3F4F6" strokeDasharray="3 3" />
            <text x={padL - 8} y={yScale(v) + 4} fontSize="10" fill="#9CA3AF" textAnchor="end">{fmtBR(v)}</text>
          </g>
        ))}

        {/* Bars */}
        {data.map((d, i) => {
          const cx = padL + groupW * i + groupW / 2;
          const inH = innerH - (yScale(d.entradas) - padT);
          const exH = innerH - (yScale(d.saidas) - padT);
          const isHover = hover === i;
          return (
            <g key={i}
              onMouseEnter={() => setHover(i)}
              onMouseLeave={() => setHover(null)}
              style={{ cursor:'pointer' }}
            >
              <rect x={cx - barW - 1} y={yScale(d.entradas)} width={barW} height={Math.max(2, inH)} fill="url(#gIncome)" rx="4" opacity={isHover ? 1 : .92} />
              <rect x={cx + 1}        y={yScale(d.saidas)}   width={barW} height={Math.max(2, exH)} fill="url(#gExpense)" rx="4" opacity={isHover ? 1 : .92} />

              {/* Value labels on hover */}
              {isHover && (
                <>
                  <text x={cx - barW/2 - 1} y={yScale(d.entradas) - 6} fontSize="10" fontWeight="700" fill="#059669" textAnchor="middle">{fmtBR(d.entradas)}</text>
                  <text x={cx + barW/2 + 1} y={yScale(d.saidas) - 6}   fontSize="10" fontWeight="700" fill="#EF4444" textAnchor="middle">{fmtBR(d.saidas)}</text>
                </>
              )}

              {/* X label */}
              <text x={cx} y={H - 12} fontSize="11" fontWeight={isHover ? 700 : 500} fill={isHover ? '#0A1F44' : '#6B7280'} textAnchor="middle">{d.month}</text>
            </g>
          );
        })}

        {/* Saldo line */}
        <path d={lineD} fill="none" stroke="#0891B2" strokeWidth="2" strokeDasharray="5 4" opacity=".55" />
        {linePoints.map((p, i) => (
          <circle key={i} cx={p.x} cy={p.y} r="3" fill="#0891B2" stroke="#fff" strokeWidth="1.5" />
        ))}
      </svg>

      {/* Tooltip */}
      {hover !== null && (() => {
        const d = data[hover];
        const saldo = d.entradas - d.saidas;
        const groupW = innerW / data.length;
        const cx = padL + groupW * hover + groupW / 2;
        const leftPct = (cx / W) * 100;
        return (
          <div style={{
            position:'absolute', top:0, left:`${leftPct}%`, transform:'translate(-50%, -8px)',
            background:'#fff', border:'1px solid #E2E8F0', borderRadius:10,
            padding:'8px 12px', fontSize:11, boxShadow:'0 6px 16px rgba(10,31,68,.12)',
            pointerEvents:'none', whiteSpace:'nowrap', zIndex:5,
          }}>
            <div style={{ fontWeight:700, color:'#0A1F44', marginBottom:4 }}>{d.month}</div>
            <div style={{ color:'#059669' }}>● Entradas: <strong>{UFN.formatCurrency(d.entradas)}</strong></div>
            <div style={{ color:'#EF4444' }}>● Saídas: <strong>{UFN.formatCurrency(d.saidas)}</strong></div>
            <div style={{ color: saldo >= 0 ? '#0891B2' : '#EF4444', borderTop:'1px solid #F0F4F8', marginTop:4, paddingTop:4 }}>
              Saldo: <strong>{UFN.formatCurrency(saldo)}</strong>
            </div>
          </div>
        );
      })()}
    </div>
  );
};

const FN_INCOME_CATS  = ['Atendimento','Pacote vendido','Produto','Outros'];
const FN_EXPENSE_CATS = ['Aluguel','Material','Marketing','Manutenção','Utilities','Software','Pró-labore','Impostos','Outros'];
const EMPTY_TXN = (today) => ({
  id:null, date: today.toISOString().split('T')[0],
  description:'', category:'Atendimento', type:'income',
  amount:0, status:'completed',
});

const Financeiro = ({ appointments, addToast }) => {
  const [tab, setTab] = useStFN('movimentacoes');
  const [period, setPeriod] = useStFN('30');
  const [typeFilter, setTypeFilter] = useStFN('all');
  const [extraTxns, setExtraTxns] = useStFN([]);
  const [modal, setModal] = useStFN({ open:false, form: EMPTY_TXN(window.JF.TODAY) });

  const allTxns = useMemoFN(() =>
    [...window.JF.FINANCIALS, ...extraTxns].sort((a,b) => b.date.localeCompare(a.date))
  , [extraTxns]);

  const txns = useMemoFN(() => {
    const cutoff = UFN.addDays(window.JF.TODAY, -Number(period));
    let list = allTxns.filter(t => new Date(t.date) >= cutoff);
    if (typeFilter !== 'all') list = list.filter(t => t.type === typeFilter);
    return list;
  }, [allTxns, period, typeFilter]);

  const income   = txns.filter(t=>t.type==='income').reduce((s,t)=>s+t.amount,0);
  const expenses = txns.filter(t=>t.type==='expense').reduce((s,t)=>s+t.amount,0);
  const balance  = income - expenses;

  // Monthly bar chart data (last 6 months)
  const barData = useMemoFN(() => {
    const months = ['Dez','Jan','Fev','Mar','Abr','Mai'];
    return months.map((m, i) => {
      const monthIdx = (window.JF.TODAY.getMonth() - 5 + i + 12) % 12;
      const year = monthIdx > window.JF.TODAY.getMonth() ? window.JF.TODAY.getFullYear()-1 : window.JF.TODAY.getFullYear();
      const monthTxns = allTxns.filter(t => {
        const d = new Date(t.date);
        return d.getMonth() === monthIdx && d.getFullYear() === year;
      });
      return {
        month: m,
        entradas: monthTxns.filter(t=>t.type==='income').reduce((s,t)=>s+t.amount,0),
        saidas: monthTxns.filter(t=>t.type==='expense').reduce((s,t)=>s+t.amount,0),
      };
    });
  }, [allTxns]);

  const openCreate = () => setModal({ open:true, form: { ...EMPTY_TXN(window.JF.TODAY), category: FN_INCOME_CATS[0] } });
  const closeModal = () => setModal(m => ({ ...m, open:false }));
  const setForm = (k, v) => setModal(m => {
    const next = { ...m.form, [k]: v };
    if (k === 'type') {
      const cats = v === 'income' ? FN_INCOME_CATS : FN_EXPENSE_CATS;
      if (!cats.includes(next.category)) next.category = cats[0];
    }
    return { ...m, form: next };
  });
  const saveTxn = () => {
    const f = modal.form;
    if (!f.description.trim()) { addToast('Informe uma descrição.', 'warning'); return; }
    if (!f.amount || f.amount <= 0) { addToast('Informe um valor válido.', 'warning'); return; }
    const id = Math.max(0, ...allTxns.map(t=>t.id||0)) + 1;
    setExtraTxns(arr => [...arr, { ...f, id }]);
    addToast(`${f.type==='income'?'Entrada':'Saída'} de ${UFN.formatCurrency(f.amount)} registrada!`, 'success');
    closeModal();
  };

  // Commission tab data
  const commissions = useMemoFN(() =>
    window.JF.PROFESSIONALS.map(prof => {
      const cutoff = UFN.addDays(window.JF.TODAY, -Number(period));
      const profAppts = appointments.filter(a =>
        a.professionalId === prof.id &&
        a.status === 'completed' &&
        new Date(a.datetime) >= cutoff
      );
      const revenue = profAppts.reduce((s,a)=>s+a.price,0);
      const commission = revenue * (prof.commission/100);
      return { prof, sessions: profAppts.length, revenue, commission };
    }).filter(c => c.sessions > 0)
  , [appointments, period]);

  // Pending receivables
  const pendingAppts = useMemoFN(() =>
    appointments
      .filter(a => a.status==='confirmed' && !a.paymentMethod)
      .sort((a,b) => new Date(b.datetime)-new Date(a.datetime))
      .slice(0,10)
  , [appointments]);

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      {/* Top metrics */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14 }}>
        <div style={{ background:'#fff', borderRadius:14, padding:'20px 22px', boxShadow:'0 2px 8px rgba(10,31,68,.06)', borderLeft:'4px solid #059669' }}>
          <div style={{ fontSize:12, fontWeight:600, color:'#6B7280', marginBottom:8 }}>Entradas do Mês</div>
          <div style={{ fontSize:28, fontWeight:800, color:'#059669' }}>{UFN.formatCurrency(income)}</div>
        </div>
        <div style={{ background:'#fff', borderRadius:14, padding:'20px 22px', boxShadow:'0 2px 8px rgba(10,31,68,.06)', borderLeft:'4px solid #EF4444' }}>
          <div style={{ fontSize:12, fontWeight:600, color:'#6B7280', marginBottom:8 }}>Saídas do Mês</div>
          <div style={{ fontSize:28, fontWeight:800, color:'#EF4444' }}>{UFN.formatCurrency(expenses)}</div>
        </div>
        <div style={{ background:'#fff', borderRadius:14, padding:'20px 22px', boxShadow:'0 2px 8px rgba(10,31,68,.06)', borderLeft:`4px solid ${balance>=0?'#0891B2':'#EF4444'}` }}>
          <div style={{ fontSize:12, fontWeight:600, color:'#6B7280', marginBottom:8 }}>Saldo</div>
          <div style={{ fontSize:28, fontWeight:800, color:balance>=0?'#0891B2':'#EF4444' }}>{UFN.formatCurrency(balance)}</div>
        </div>
      </div>

      {/* Bar chart */}
      {(() => {
        const totalIn  = barData.reduce((s,d)=>s+d.entradas,0);
        const totalEx  = barData.reduce((s,d)=>s+d.saidas,0);
        const totalSal = totalIn - totalEx;
        const prevIn   = barData.slice(0,3).reduce((s,d)=>s+d.entradas,0);
        const recIn    = barData.slice(3).reduce((s,d)=>s+d.entradas,0);
        const trend    = prevIn > 0 ? ((recIn - prevIn) / prevIn) * 100 : 0;
        return (
          <div style={{ background:'#fff', borderRadius:16, padding:'22px 24px', boxShadow:'0 2px 8px rgba(10,31,68,.06)' }}>
            <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', flexWrap:'wrap', gap:14, marginBottom:18 }}>
              <div>
                <h3 style={{ fontSize:15, fontWeight:700, color:'#0A1F44', margin:'0 0 4px' }}>Fluxo de Caixa — Últimos 6 meses</h3>
                <div style={{ fontSize:12, color:'#6B7280' }}>
                  Saldo acumulado: <strong style={{ color: totalSal>=0 ? '#0891B2' : '#EF4444' }}>{UFN.formatCurrency(totalSal)}</strong>
                  <span style={{ display:'inline-flex', alignItems:'center', gap:3, marginLeft:10, padding:'2px 8px', borderRadius:20, fontSize:11, fontWeight:700, background: trend>=0 ? '#F0FDF4' : '#FEF2F2', color: trend>=0 ? '#15803D' : '#B91C1C' }}>
                    <Icon name={trend>=0 ? 'TrendingUp' : 'TrendingDown'} size={11} />
                    {trend>=0?'+':''}{trend.toFixed(1)}% vs trimestre anterior
                  </span>
                </div>
              </div>
              <div style={{ display:'flex', gap:14, alignItems:'center', flexWrap:'wrap' }}>
                <div style={{ display:'flex', alignItems:'center', gap:6, fontSize:12, color:'#6B7280' }}>
                  <span style={{ width:10, height:10, borderRadius:3, background:'linear-gradient(180deg,#10B981,#059669)' }} />
                  Entradas <strong style={{ color:'#059669' }}>{UFN.formatCurrency(totalIn)}</strong>
                </div>
                <div style={{ display:'flex', alignItems:'center', gap:6, fontSize:12, color:'#6B7280' }}>
                  <span style={{ width:10, height:10, borderRadius:3, background:'linear-gradient(180deg,#FCA5A5,#EF4444)' }} />
                  Saídas <strong style={{ color:'#EF4444' }}>{UFN.formatCurrency(totalEx)}</strong>
                </div>
                <div style={{ display:'flex', alignItems:'center', gap:6, fontSize:12, color:'#6B7280' }}>
                  <span style={{ width:14, height:2, background:'#0891B2', borderRadius:2, opacity:.7 }} />
                  Saldo mensal
                </div>
              </div>
            </div>
            <CashFlowChart data={barData} />
          </div>
        );
      })()}

      {/* Tabs */}
      <Tabs
        tabs={[
          { id:'movimentacoes', label:'Movimentações', icon:'ArrowLeftRight' },
          { id:'comissoes', label:'Comissões', icon:'Percent' },
          { id:'receber', label:'Contas a Receber', icon:'Clock', count:pendingAppts.length },
        ]}
        activeTab={tab} onTabChange={setTab}
      />

      {tab === 'movimentacoes' && (
        <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(10,31,68,.06)', overflow:'hidden' }}>
          {/* Sub-filters */}
          <div style={{ padding:'14px 18px', borderBottom:'1px solid #E2E8F0', display:'flex', gap:12, alignItems:'center' }}>
            <select value={period} onChange={e=>setPeriod(e.target.value)} style={{ padding:'7px 10px', borderRadius:8, fontSize:12, border:'1px solid #E2E8F0', outline:'none', background:'#fff', color:'#0A1F44', cursor:'pointer' }}>
              <option value="7">Últimos 7 dias</option>
              <option value="30">Últimos 30 dias</option>
              <option value="60">Últimos 60 dias</option>
              <option value="90">Últimos 90 dias</option>
            </select>
            <div style={{ display:'flex', background:'#F3F4F6', borderRadius:8, padding:3 }}>
              {[['all','Todos'],['income','Entradas'],['expense','Saídas']].map(([v,l]) => (
                <button key={v} onClick={()=>setTypeFilter(v)} style={{ padding:'5px 12px', borderRadius:6, fontSize:12, fontWeight:600, cursor:'pointer', background:typeFilter===v?'#fff':'transparent', color:typeFilter===v?'#0A1F44':'#6B7280', border:'none', boxShadow:typeFilter===v?'0 1px 3px rgba(0,0,0,.08)':'none', transition:'all .15s' }}>{l}</button>
              ))}
            </div>
            <span style={{ fontSize:12, color:'#9CA3AF', marginLeft:'auto' }}>{txns.length} registros</span>
            <Button size="sm" variant="primary" icon="Plus" onClick={openCreate}>Nova Movimentação</Button>
          </div>
          <div style={{ overflowX:'auto' }}>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr style={{ background:'#F9FAFB' }}>
                  {['Data','Descrição','Categoria','Tipo','Valor','Status'].map(h => (
                    <th key={h} style={{ padding:'11px 14px', fontSize:11, fontWeight:700, color:'#6B7280', textAlign:'left', textTransform:'uppercase', letterSpacing:.5 }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {txns.slice(0,30).map((t, i) => (
                  <tr key={t.id} style={{ borderTop:'1px solid #F0F4F8' }}
                    onMouseEnter={e=>e.currentTarget.style.background='#F9FAFB'}
                    onMouseLeave={e=>e.currentTarget.style.background='#fff'}
                  >
                    <td style={{ padding:'11px 14px', fontSize:12, color:'#374151' }}>{UFN.formatDate(t.date)}</td>
                    <td style={{ padding:'11px 14px', fontSize:13, fontWeight:600, color:'#0A1F44', maxWidth:200 }}>{t.description}</td>
                    <td style={{ padding:'11px 14px', fontSize:12, color:'#6B7280' }}>{t.category}</td>
                    <td style={{ padding:'11px 14px' }}>
                      <div style={{ display:'flex', alignItems:'center', gap:5 }}>
                        <Icon name={t.type==='income'?'ArrowDownLeft':'ArrowUpRight'} size={13} color={t.type==='income'?'#059669':'#EF4444'} />
                        <span style={{ fontSize:12, fontWeight:600, color:t.type==='income'?'#059669':'#EF4444' }}>{t.type==='income'?'Entrada':'Saída'}</span>
                      </div>
                    </td>
                    <td style={{ padding:'11px 14px', fontSize:13, fontWeight:700, color:t.type==='income'?'#059669':'#EF4444' }}>
                      {t.type==='income'?'+':'-'} {UFN.formatCurrency(t.amount)}
                    </td>
                    <td style={{ padding:'11px 14px' }}><Badge status={t.status} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'comissoes' && (
        <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(10,31,68,.06)', overflow:'hidden' }}>
          <div style={{ padding:'14px 18px', borderBottom:'1px solid #E2E8F0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <h3 style={{ margin:0, fontSize:14, fontWeight:700, color:'#0A1F44' }}>Comissões por Profissional</h3>
            <Button size="sm" variant="secondary" icon="Download" onClick={()=>addToast('Relatório exportado!','success')}>Exportar</Button>
          </div>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead>
              <tr style={{ background:'#F9FAFB' }}>
                {['Profissional','Especialidade','Sessões','Faturado','% Comissão','A Receber'].map(h => (
                  <th key={h} style={{ padding:'11px 14px', fontSize:11, fontWeight:700, color:'#6B7280', textAlign:'left', textTransform:'uppercase', letterSpacing:.5 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {commissions.map(({ prof, sessions, revenue, commission }) => (
                <tr key={prof.id} style={{ borderTop:'1px solid #F0F4F8' }}
                  onMouseEnter={e=>e.currentTarget.style.background='#F9FAFB'}
                  onMouseLeave={e=>e.currentTarget.style.background='#fff'}
                >
                  <td style={{ padding:'13px 14px' }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <Avatar name={prof.name} color={prof.color} size={30} />
                      <span style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>{prof.name}</span>
                    </div>
                  </td>
                  <td style={{ padding:'13px 14px', fontSize:12, color:'#6B7280' }}>{prof.role}</td>
                  <td style={{ padding:'13px 14px', fontSize:14, fontWeight:700, color:'#0A1F44' }}>{sessions}</td>
                  <td style={{ padding:'13px 14px', fontSize:13, fontWeight:600, color:'#059669' }}>{UFN.formatCurrency(revenue)}</td>
                  <td style={{ padding:'13px 14px' }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <ProgressBar value={prof.commission} max={100} color={prof.color} style={{ width:60 }} />
                      <span style={{ fontSize:12, fontWeight:700, color:prof.color }}>{prof.commission}%</span>
                    </div>
                  </td>
                  <td style={{ padding:'13px 14px', fontSize:15, fontWeight:800, color:'#0891B2' }}>{UFN.formatCurrency(commission)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'receber' && (
        <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(10,31,68,.06)', overflow:'hidden' }}>
          <div style={{ padding:'14px 18px', borderBottom:'1px solid #E2E8F0' }}>
            <h3 style={{ margin:0, fontSize:14, fontWeight:700, color:'#0A1F44' }}>Contas a Receber</h3>
          </div>
          {pendingAppts.length === 0 ? (
            <EmptyState icon="CheckCircle" title="Tudo em dia!" message="Não há contas pendentes no momento." />
          ) : (
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr style={{ background:'#F9FAFB' }}>
                  {['Cliente','Serviço','Data','Valor','Ação'].map(h=>(
                    <th key={h} style={{ padding:'11px 14px', fontSize:11, fontWeight:700, color:'#6B7280', textAlign:'left', textTransform:'uppercase', letterSpacing:.5 }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {pendingAppts.map(a => {
                  const c = UFN.getClient(a.clientId), s = UFN.getService(a.serviceId);
                  return (
                    <tr key={a.id} style={{ borderTop:'1px solid #F0F4F8' }}>
                      <td style={{ padding:'11px 14px' }}><div style={{ display:'flex', alignItems:'center', gap:8 }}><Avatar name={c?.name} color="#0A1F44" size={28} /><span style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{c?.name}</span></div></td>
                      <td style={{ padding:'11px 14px', fontSize:12, color:'#374151' }}>{s?.name}</td>
                      <td style={{ padding:'11px 14px', fontSize:12, color:'#374151' }}>{UFN.formatDate(a.datetime)}</td>
                      <td style={{ padding:'11px 14px', fontSize:14, fontWeight:700, color:'#D97706' }}>{UFN.formatCurrency(a.price)}</td>
                      <td style={{ padding:'11px 14px' }}>
                        <Button size="sm" variant="primary" icon="Check" onClick={()=>addToast('Pagamento registrado!','success')}>Receber</Button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
      )}

      {/* Nova Movimentação modal */}
      <Modal
        open={modal.open}
        onClose={closeModal}
        title="Nova Movimentação"
        width={560}
        footer={<>
          <Button variant="secondary" onClick={closeModal}>Cancelar</Button>
          <Button variant="primary" icon="Save" onClick={saveTxn}>Salvar</Button>
        </>}
      >
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          {/* Type toggle */}
          <div>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:8 }}>Tipo de movimentação</label>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
              {[
                { v:'income',  label:'Entrada', icon:'ArrowDownLeft', color:'#059669', desc:'Recebimento' },
                { v:'expense', label:'Saída',   icon:'ArrowUpRight',  color:'#EF4444', desc:'Despesa' },
              ].map(opt => {
                const active = modal.form.type === opt.v;
                return (
                  <button key={opt.v} type="button" onClick={() => setForm('type', opt.v)} style={{
                    padding:'14px 16px', borderRadius:12, cursor:'pointer',
                    background: active ? UFN.hexToRgba(opt.color,.10) : '#F9FAFB',
                    border: active ? `2px solid ${opt.color}` : '2px solid #E2E8F0',
                    display:'flex', alignItems:'center', gap:12, transition:'all .15s', textAlign:'left',
                  }}>
                    <div style={{ width:36, height:36, borderRadius:10, background: UFN.hexToRgba(opt.color,.15), display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                      <Icon name={opt.icon} size={18} color={opt.color} />
                    </div>
                    <div>
                      <div style={{ fontSize:14, fontWeight:700, color: active ? opt.color : '#0A1F44' }}>{opt.label}</div>
                      <div style={{ fontSize:11, color:'#9CA3AF' }}>{opt.desc}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          <Input label="Descrição" value={modal.form.description} onChange={v=>setForm('description',v)} icon="FileText" required autoFocus placeholder="Ex: Atendimentos do dia, Pagamento aluguel..." />

          {/* Amount + Date */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
              <label style={{ fontSize:13, fontWeight:600, color:'#374151' }}>Valor (R$) <span style={{ color:'#EF4444' }}>*</span></label>
              <input type="number" min="0" step="0.01" value={modal.form.amount} onChange={e=>setForm('amount', Number(e.target.value))}
                style={{ padding:'9px 12px', borderRadius:8, fontSize:13, border:'1.5px solid #E2E8F0', outline:'none', color:'#0A1F44', background:'#fff' }} />
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
              <label style={{ fontSize:13, fontWeight:600, color:'#374151' }}>Data</label>
              <input type="date" value={modal.form.date} onChange={e=>setForm('date', e.target.value)}
                style={{ padding:'9px 12px', borderRadius:8, fontSize:13, border:'1.5px solid #E2E8F0', outline:'none', color:'#0A1F44', background:'#fff' }} />
            </div>
          </div>

          {/* Category */}
          <div>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:8 }}>Categoria</label>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
              {(modal.form.type === 'income' ? FN_INCOME_CATS : FN_EXPENSE_CATS).map(c => (
                <button key={c} type="button" onClick={() => setForm('category', c)} style={{
                  padding:'6px 12px', borderRadius:20, fontSize:12, fontWeight:600, cursor:'pointer',
                  background: modal.form.category === c ? '#0A1F44' : '#F3F4F6',
                  color: modal.form.category === c ? '#fff' : '#6B7280',
                  border:'none', transition:'all .15s',
                }}>{c}</button>
              ))}
            </div>
          </div>

          {/* Status */}
          <div>
            <label style={{ fontSize:13, fontWeight:600, color:'#374151', display:'block', marginBottom:8 }}>Status</label>
            <div style={{ display:'flex', gap:8 }}>
              {[
                { v:'completed', label:'Realizado', color:'#059669' },
                { v:'pending',   label:'Pendente',  color:'#D97706' },
              ].map(opt => {
                const active = modal.form.status === opt.v;
                return (
                  <button key={opt.v} type="button" onClick={() => setForm('status', opt.v)} style={{
                    flex:1, padding:'10px 12px', borderRadius:10, cursor:'pointer', fontSize:13, fontWeight:700,
                    background: active ? UFN.hexToRgba(opt.color,.10) : '#fff',
                    border: active ? `2px solid ${opt.color}` : '2px solid #E2E8F0',
                    color: active ? opt.color : '#6B7280', transition:'all .15s',
                  }}>{opt.label}</button>
                );
              })}
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};

Object.assign(window, { Financeiro });
