// Financial.jsx
'use strict';
const { useState, useMemo, useEffect } = React;

const TRX_CATS  = ['Serviço','Peças','Operacional','Pessoal','Equipamentos','Outros'];
const PAY_METHODS = ['PIX','Cartão Crédito','Cartão Débito','Dinheiro','Boleto','Transferência'];
const PAY_ICON  = { 'PIX':'Zap', 'Cartão Crédito':'CreditCard', 'Cartão Débito':'CreditCard', 'Dinheiro':'DollarSign', 'Boleto':'FileText', 'Transferência':'RefreshCw' };
const PAY_COLOR = { 'PIX':'#10B981', 'Cartão Crédito':'#6366F1', 'Cartão Débito':'#3B82F6', 'Dinheiro':'#F59E0B', 'Boleto':'#94A3B8', 'Transferência':'#8B5CF6' };
const CAT_COLOR = { 'Serviço':'#3B82F6', 'Peças':'#F59E0B', 'Operacional':'#8B5CF6', 'Pessoal':'#EC4899', 'Equipamentos':'#10B981', 'Outros':'#94A3B8' };

// Dias entre 2 datas YYYY-MM-DD
const daysBetween = (a, b) => Math.floor((new Date(b) - new Date(a)) / 86400000);

function PaymentBadge({ method }) {
  if (!method) return <span className="text-xs text-slate-300">—</span>;
  const c = PAY_COLOR[method] || '#94A3B8';
  return (
    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-semibold"
      style={{ background:c+'18', color:c }}>
      <Icon name={PAY_ICON[method]||'CreditCard'} size={11} color={c}/>{method}
    </span>
  );
}

function DeltaChip({ delta }) {
  if (delta === null || delta === undefined || !isFinite(delta)) return null;
  const positive = delta >= 0;
  const color = positive ? '#059669' : '#DC2626';
  const bg    = positive ? '#D1FAE5' : '#FEE2E2';
  return (
    <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-md text-[10px] font-bold"
      style={{ background:bg, color }}>
      <Icon name={positive?'TrendingUp':'TrendingDown'} size={10} color={color}/>
      {positive?'+':''}{delta.toFixed(0)}%
    </span>
  );
}

function TrxModal({ open, onClose, onSave, onDelete, editTrx }) {
  const today = new Date().toISOString().split('T')[0];
  const empty = { date: today, desc:'', category:'Serviço', type:'entrada', amount:0, status:'pago', paymentMethod:'PIX', recurring:false };
  const [form, setForm] = useState(empty);
  const [errors, setErrors] = useState({});
  useEffect(()=>{ if(open){ setForm(editTrx?{...empty,...editTrx}:{...empty}); setErrors({}); } },[open,editTrx]);
  const set=(k,v)=>setForm(f=>({...f,[k]:v}));
  const validate=()=>{ const e={}; if(!form.desc.trim())e.desc='Descrição obrigatória'; if(!form.amount||form.amount<=0)e.amount='Valor inválido'; setErrors(e); return Object.keys(e).length===0; };
  const handleSave=()=>{ if(!validate())return; onSave(form); onClose(); };
  return (
    <Modal open={open} onClose={onClose} title={editTrx?'Editar Movimentação':'Nova Movimentação'} width="max-w-md">
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-3 p-1">
          {['entrada','saída'].map(t=>(
            <button key={t} onClick={()=>set('type',t)}
              className="py-3 rounded-xl border-2 font-semibold text-sm flex items-center justify-center gap-2 transition-all"
              style={{ borderColor:form.type===t?(t==='entrada'?'#10B981':'#EF4444'):'#E2E8F0', background:form.type===t?(t==='entrada'?'#F0FDF4':'#FEF2F2'):'white', color:form.type===t?(t==='entrada'?'#059669':'#DC2626'):'#94A3B8' }}>
              <Icon name={t==='entrada'?'ArrowUp':'ArrowDown'} size={15}/>{t==='entrada'?'Entrada':'Saída'}
            </button>
          ))}
        </div>
        <FormField label="Descrição" required error={errors.desc}>
          <Input value={form.desc} onChange={e=>set('desc',e.target.value)} placeholder="Ex: OS #001 — João Silva" error={!!errors.desc}/>
        </FormField>
        <div className="grid grid-cols-2 gap-4">
          <FormField label="Categoria">
            <Select value={form.category} onChange={e=>set('category',e.target.value)}>
              {TRX_CATS.map(c=><option key={c}>{c}</option>)}
            </Select>
          </FormField>
          <FormField label="Forma de Pagamento">
            <Select value={form.paymentMethod} onChange={e=>set('paymentMethod',e.target.value)}>
              {PAY_METHODS.map(p=><option key={p}>{p}</option>)}
            </Select>
          </FormField>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <FormField label="Data"><Input type="date" value={form.date} onChange={e=>set('date',e.target.value)}/></FormField>
          <FormField label="Valor (R$)" required error={errors.amount}>
            <Input type="number" min="0" step="0.01" value={form.amount} onChange={e=>set('amount',+e.target.value)} error={!!errors.amount}/>
          </FormField>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <FormField label="Status">
            <Select value={form.status} onChange={e=>set('status',e.target.value)}>
              <option value="pago">Pago</option>
              <option value="pendente">Pendente</option>
            </Select>
          </FormField>
          <FormField label=" ">
            <label className="flex items-center gap-2 px-3 py-2.5 rounded-xl border border-slate-200 cursor-pointer hover:bg-slate-50 text-sm">
              <input type="checkbox" checked={!!form.recurring} onChange={e=>set('recurring',e.target.checked)} className="rounded"/>
              <Icon name="RefreshCw" size={13} color="#8B5CF6"/>
              <span className="text-slate-600">Despesa recorrente</span>
            </label>
          </FormField>
        </div>
        <div className="flex flex-wrap gap-2 pt-3 border-t border-slate-100">
          <Btn variant="outline" onClick={onClose} className="sm:mr-auto">Cancelar</Btn>
          {editTrx && onDelete && (
            <Btn variant="ghost" icon="Trash2" onClick={()=>{ onDelete(editTrx.id); onClose(); }} className="text-red-500 hover:bg-red-50">Excluir</Btn>
          )}
          <Btn icon="Check" onClick={handleSave}>{editTrx?'Salvar':'Registrar'}</Btn>
        </div>
      </div>
    </Modal>
  );
}

// ── Card de breakdown por categoria ─────────────────────────────────────────
function CategoryBreakdown({ title, icon, color, items, total }) {
  return (
    <Card className="p-5">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <div className="w-7 h-7 rounded-lg flex items-center justify-center" style={{ background:color+'18' }}>
            <Icon name={icon} size={14} color={color}/>
          </div>
          <h3 className="font-bold text-sm" style={{ color:'#0A1F44' }}>{title}</h3>
        </div>
        <span className="text-xs font-bold" style={{ color }}>{fmtCurrency(total)}</span>
      </div>
      {items.length === 0 ? (
        <div className="text-center text-xs text-slate-400 py-6">Sem dados no mês corrente.</div>
      ) : (
        <div className="space-y-3">
          {items.map(({ cat, val, pct }) => {
            const c = CAT_COLOR[cat] || '#94A3B8';
            return (
              <div key={cat}>
                <div className="flex items-center justify-between text-xs mb-1.5">
                  <span className="font-semibold text-slate-700">{cat}</span>
                  <span className="text-slate-500 font-mono">{fmtCurrency(val)} <span className="text-slate-300 ml-1">({pct.toFixed(0)}%)</span></span>
                </div>
                <div className="h-1.5 rounded-full overflow-hidden" style={{ background:'#F1F5F9' }}>
                  <div className="h-full rounded-full transition-all" style={{ width:pct+'%', background:`linear-gradient(90deg, ${c}, ${c}cc)` }} />
                </div>
              </div>
            );
          })}
        </div>
      )}
    </Card>
  );
}

function Financial({ transactions, workOrders, onAdd, onUpdate, onDelete, onUpdateWO, addToast }) {
  const [tab, setTab] = useState('movimentacoes');
  const [search, setSearch] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [catFilter, setCatFilter] = useState('');
  const [periodFilter, setPeriodFilter] = useState('6m');
  const [showModal, setShowModal] = useState(false);
  const [editTrx, setEditTrx] = useState(null);
  const [confirm, setConfirm] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(()=>{ const t=setTimeout(()=>setLoading(false),500); return()=>clearTimeout(t); },[]);

  const today = new Date();
  const todayStr = today.toISOString().split('T')[0];
  const ymCurrent = todayStr.slice(0,7);
  const ymPrev = (() => { const d=new Date(today); d.setMonth(d.getMonth()-1); return d.toISOString().slice(0,7); })();

  const cutoff = useMemo(()=>{
    const d=new Date(today);
    if(periodFilter==='1m') d.setMonth(d.getMonth()-1);
    else if(periodFilter==='3m') d.setMonth(d.getMonth()-3);
    else if(periodFilter==='12m') d.setMonth(d.getMonth()-12);
    else d.setMonth(d.getMonth()-6);
    return d.toISOString().split('T')[0];
  },[periodFilter]);

  const filtered = transactions.filter(t=>{
    const mP = t.date>=cutoff;
    const mQ = !search || t.desc?.toLowerCase().includes(search.toLowerCase());
    const mT = !typeFilter || t.type===typeFilter;
    const mS = !statusFilter || t.status===statusFilter;
    const mC = !catFilter || t.category===catFilter;
    return mP&&mQ&&mT&&mS&&mC;
  }).sort((a,b)=>b.date.localeCompare(a.date));

  // ─── KPIs com delta vs mês anterior ─────────────────────────────────────
  const stats = useMemo(()=>{
    const sum = (predicate) => transactions.filter(predicate).reduce((s,t)=>s+t.amount,0);
    const inMes   = sum(t=>t.type==='entrada'&&t.date?.startsWith(ymCurrent)&&t.status==='pago');
    const outMes  = sum(t=>t.type==='saída' &&t.date?.startsWith(ymCurrent)&&t.status==='pago');
    const inPrev  = sum(t=>t.type==='entrada'&&t.date?.startsWith(ymPrev)   &&t.status==='pago');
    const outPrev = sum(t=>t.type==='saída' &&t.date?.startsWith(ymPrev)   &&t.status==='pago');
    const pendente= sum(t=>t.status==='pendente'&&t.type==='entrada');
    const overdue = transactions.filter(t=>t.status==='pendente'&&t.type==='entrada'&&daysBetween(t.date, todayStr)>30);
    const overdueAmount = overdue.reduce((s,t)=>s+t.amount,0);
    const saldo = inMes - outMes;
    const margem = inMes>0 ? (saldo/inMes)*100 : 0;
    const deltaIn  = inPrev  ? ((inMes-inPrev)/inPrev)*100 : null;
    const deltaOut = outPrev ? ((outMes-outPrev)/outPrev)*100 : null;
    return { inMes, outMes, saldo, margem, pendente, overdue:overdue.length, overdueAmount, deltaIn, deltaOut };
  },[transactions, ymCurrent, ymPrev, todayStr]);

  // ─── Breakdown por categoria (mês corrente) ─────────────────────────────
  const breakdownCats = (type) => {
    const byCat = {};
    transactions
      .filter(t=>t.type===type&&t.status==='pago'&&t.date?.startsWith(ymCurrent))
      .forEach(t=>{ byCat[t.category]=(byCat[t.category]||0)+t.amount; });
    const total = Object.values(byCat).reduce((s,v)=>s+v,0);
    const items = Object.entries(byCat)
      .map(([cat,val])=>({cat,val,pct: total?(val/total)*100:0}))
      .sort((a,b)=>b.val-a.val);
    return { items, total };
  };
  const incomeBreakdown  = useMemo(()=>breakdownCats('entrada'), [transactions, ymCurrent]);
  const expenseBreakdown = useMemo(()=>breakdownCats('saída'),   [transactions, ymCurrent]);

  // ─── Receivables (OSs concluídas/entregues e não marcadas como pagas) ───
  const receivables = workOrders.filter(o=>o.total>0 && (o.status==='Concluída'||o.status==='Entregue') && !o.paid);
  const receivablesAged = receivables.map(o=>({ ...o, _days: daysBetween(o.entryDate, todayStr) }))
    .sort((a,b)=>b._days-a._days);
  const totalReceivable = receivables.reduce((s,o)=>s+(o.total||0),0);

  const handleSave=form=>{
    if(editTrx){ onUpdate(editTrx.id,form); addToast({type:'success',msg:'Movimentação atualizada!'}); }
    else{ onAdd({...form,id:'TRN'+String(transactions.length+1).padStart(3,'0')}); addToast({type:'success',msg:'Movimentação registrada!'}); }
  };

  const handleMarkPaid = t => {
    onUpdate(t.id, { ...t, status:'pago' });
    addToast({ type:'success', msg:`Movimentação marcada como paga.` });
  };

  const handleReceiveOS = os => {
    const id = 'TRN'+String(transactions.length+1).padStart(3,'0');
    onAdd({ id, date:todayStr, desc:`OS #${os.num} — ${os.clientName}`, category:'Serviço',
      type:'entrada', amount:os.total||0, status:'pago', paymentMethod:'PIX', recurring:false });
    if (onUpdateWO) onUpdateWO(os.id, { paid:true });
    addToast({ type:'success', title:'Recebimento registrado', msg:`${fmtCurrency(os.total||0)} de ${os.clientName}` });
  };

  const exportCSV = () => {
    const esc = v => `"${String(v ?? '').replace(/"/g,'""')}"`;
    const header = ['Data','Descrição','Categoria','Tipo','Valor (R$)','Status','Forma Pagamento','Recorrente'];
    const rows = filtered.map(t=>[t.date, t.desc, t.category, t.type, (t.amount||0).toFixed(2).replace('.',','), t.status, t.paymentMethod||'', t.recurring?'Sim':'Não'].map(esc).join(';'));
    const csv = '﻿' + [header.map(esc).join(';'), ...rows].join('\r\n');
    const blob = new Blob([csv], { type:'text/csv;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `movimentacoes-${todayStr}.csv`; a.click();
    URL.revokeObjectURL(url);
    addToast({ type:'info', msg:'CSV exportado.' });
  };

  // Group by month for sparklines
  const byMonth = useMemo(()=>{
    const m={};
    transactions.filter(t=>t.status==='pago').forEach(t=>{
      const mo=t.date?.slice(0,7)||'';
      if(!m[mo])m[mo]={month:mo,entrada:0,saída:0};
      m[mo][t.type]+=t.amount;
    });
    return Object.values(m).sort((a,b)=>a.month.localeCompare(b.month)).slice(-6).map(x=>({
      ...x, label: x.month ? `${x.month.slice(5,7)}/${x.month.slice(2,4)}` : ''
    }));
  },[transactions]);

  const isOverdue = t => t.status==='pendente' && t.type==='entrada' && daysBetween(t.date, todayStr) > 30;

  return (
    <div className="anim-fade">
      <PageHeader title="Financeiro" subtitle="Controle de entradas, saídas e contas a receber"
        action={<Btn icon="Plus" onClick={()=>{setEditTrx(null);setShowModal(true);}}>Nova Movimentação</Btn>}/>

      {/* Alerta de inadimplência */}
      {stats.overdue > 0 && (
        <div className="mb-5 p-3 rounded-xl flex items-center gap-3 border" style={{ background:'#FEF2F2', borderColor:'#FECACA' }}>
          <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background:'#FEE2E2' }}>
            <Icon name="AlertCircle" size={18} color="#DC2626"/>
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-sm font-bold text-red-700">Atenção: {stats.overdue} movimentação(ões) vencida(s) há mais de 30 dias</div>
            <div className="text-xs text-red-600">Total em atraso: <b>{fmtCurrency(stats.overdueAmount)}</b></div>
          </div>
          <button onClick={()=>{setStatusFilter('pendente');setTypeFilter('entrada');setTab('movimentacoes');}}
            className="text-xs font-bold text-red-600 hover:bg-red-100 px-3 py-1.5 rounded-lg transition-colors">
            Ver todas →
          </button>
        </div>
      )}

      {/* KPI cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {[
          { label:'Receita do Mês',  value:fmtCurrency(stats.inMes),   icon:'ArrowUp',   bg:'#10B981', light:'#F0FDF4', text:'#065F46', delta:stats.deltaIn },
          { label:'Despesa do Mês',  value:fmtCurrency(stats.outMes),  icon:'ArrowDown', bg:'#EF4444', light:'#FEF2F2', text:'#991B1B', delta:stats.deltaOut, deltaInverse:true },
          { label:'Lucro Líquido',   value:fmtCurrency(stats.saldo),   icon:'Activity',  bg:stats.saldo>=0?'#10B981':'#EF4444', light:stats.saldo>=0?'#F0FDF4':'#FEF2F2', text:stats.saldo>=0?'#065F46':'#991B1B', sub:`Margem ${stats.margem.toFixed(0)}%` },
          { label:'A Receber',       value:fmtCurrency(stats.pendente),icon:'Clock',     bg:'#F59E0B', light:'#FFFBEB', text:'#92400E', sub:stats.overdue>0?`${stats.overdue} vencida(s)`:'Em dia' },
        ].map((c,i)=>(
          <Card key={i} className="p-5">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-8 h-8 rounded-xl flex items-center justify-center" style={{background:c.light}}>
                <Icon name={c.icon} size={16} color={c.bg}/>
              </div>
              <span className="text-xs font-semibold text-slate-400">{c.label}</span>
            </div>
            <div className="flex items-end gap-2">
              <div className="text-xl font-bold leading-tight" style={{color:c.text}}>{c.value}</div>
            </div>
            <div className="mt-1.5 flex items-center gap-2">
              {c.delta !== undefined && c.delta !== null && (
                <DeltaChip delta={c.deltaInverse ? -c.delta : c.delta}/>
              )}
              {c.sub && <span className="text-[10px] text-slate-400 font-semibold">{c.sub}</span>}
              {c.delta !== null && c.delta !== undefined && <span className="text-[10px] text-slate-300">vs mês ant.</span>}
            </div>
          </Card>
        ))}
      </div>

      {/* Mini bar chart */}
      {byMonth.length>0 && (
        <Card className="p-5 mb-6">
          <h3 className="font-bold text-sm mb-4" style={{color:'#0A1F44'}}>Fluxo de Caixa — Últimos 6 Meses</h3>
          <SimpleBarChart data={byMonth} xKey="label" height={150}
            bars={[{key:'entrada',label:'Entradas',color:'#10B981'},{key:'saída',label:'Saídas',color:'#FCA5A5'}]}
            formatY={v=>`R$${(v/1000).toFixed(0)}k`} formatTooltip={fmtCurrency}/>
        </Card>
      )}

      {/* Breakdown por categoria — mês corrente */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
        <CategoryBreakdown title="Receitas por Categoria" icon="ArrowUp" color="#10B981"
          items={incomeBreakdown.items} total={incomeBreakdown.total}/>
        <CategoryBreakdown title="Despesas por Categoria" icon="ArrowDown" color="#EF4444"
          items={expenseBreakdown.items} total={expenseBreakdown.total}/>
      </div>

      {/* Tabs */}
      <Tabs tabs={[{id:'movimentacoes',label:'Movimentações'},{id:'receber',label:`Contas a Receber (${receivables.length})`}]}
        active={tab} onChange={setTab}/>

      <Card className="mt-4">
        {tab==='movimentacoes' && <>
          <div className="flex flex-wrap gap-3 p-4 border-b border-slate-50">
            <SearchInput value={search} onChange={setSearch} placeholder="Buscar movimentação..." className="flex-1 min-w-48"/>
            <Select className="w-32" value={typeFilter} onChange={e=>setTypeFilter(e.target.value)}>
              <option value="">Tipo</option>
              <option value="entrada">Entradas</option>
              <option value="saída">Saídas</option>
            </Select>
            <Select className="w-32" value={catFilter} onChange={e=>setCatFilter(e.target.value)}>
              <option value="">Categoria</option>
              {TRX_CATS.map(c=><option key={c} value={c}>{c}</option>)}
            </Select>
            <Select className="w-32" value={statusFilter} onChange={e=>setStatusFilter(e.target.value)}>
              <option value="">Status</option>
              <option value="pago">Pago</option>
              <option value="pendente">Pendente</option>
            </Select>
            <Select className="w-28" value={periodFilter} onChange={e=>setPeriodFilter(e.target.value)}>
              <option value="1m">1 mês</option>
              <option value="3m">3 meses</option>
              <option value="6m">6 meses</option>
              <option value="12m">12 meses</option>
            </Select>
            <Btn variant="outline" size="sm" icon="Download" onClick={exportCSV}>CSV</Btn>
          </div>
          {loading ? Array.from({length:5}).map((_,i)=><SkeletonRow key={i}/>) :
            filtered.length===0 ? <EmptyState icon="DollarSign" title="Nenhuma movimentação" message="Nenhuma movimentação no período selecionado." actionLabel="Nova Movimentação" onAction={()=>setShowModal(true)}/> :
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead><tr className="border-b border-slate-100">
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase">Data</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase">Descrição</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase hidden md:table-cell">Categoria</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase hidden lg:table-cell">Pagamento</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase">Tipo</th>
                  <th className="px-4 py-3 text-right text-xs font-semibold text-slate-400 uppercase">Valor</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase">Status</th>
                  <th className="px-4 py-3 text-right text-xs font-semibold text-slate-400 uppercase">Ações</th>
                </tr></thead>
                <tbody>
                  {filtered.map(t=>{
                    const overdue = isOverdue(t);
                    return (
                      <tr key={t.id}
                        onClick={()=>{setEditTrx(t);setShowModal(true);}}
                        className="border-b border-slate-50 hover:bg-slate-50 active:bg-slate-100 transition-colors cursor-pointer"
                        style={overdue ? { background:'#FEF2F2', borderLeft:'3px solid #EF4444' } : {}}>
                        <td className="px-4 py-3.5 text-slate-500 text-sm whitespace-nowrap">{fmtDate(t.date)}</td>
                        <td className="px-4 py-3.5 font-medium text-slate-700">
                          <div className="flex items-center gap-2 flex-wrap">
                            <span>{t.desc}</span>
                            {t.recurring && (
                              <span title="Despesa recorrente" className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-md text-[10px] font-bold" style={{ background:'#EDE9FE', color:'#6D28D9' }}>
                                <Icon name="RefreshCw" size={9} color="#6D28D9"/>fixa
                              </span>
                            )}
                            {overdue && (
                              <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-md text-[10px] font-bold" style={{ background:'#FEE2E2', color:'#B91C1C' }}>
                                VENCIDA {daysBetween(t.date, todayStr)}d
                              </span>
                            )}
                          </div>
                        </td>
                        <td className="px-4 py-3.5 hidden md:table-cell text-slate-500 text-xs">{t.category}</td>
                        <td className="px-4 py-3.5 hidden lg:table-cell"><PaymentBadge method={t.paymentMethod}/></td>
                        <td className="px-4 py-3.5"><StatusBadge status={t.type}/></td>
                        <td className="px-4 py-3.5 text-right font-bold whitespace-nowrap" style={{color:t.type==='entrada'?'#059669':'#DC2626'}}>{t.type==='saída'?'− ':''}{fmtCurrency(t.amount)}</td>
                        <td className="px-4 py-3.5"><StatusBadge status={t.status}/></td>
                        <td className="px-2 py-3.5">
                          {/* Marcar como pago — visivel sempre se pendente (acao primaria) */}
                          <div className="flex items-center justify-end gap-1">
                            {t.status==='pendente' && (
                              <button onClick={(e)=>{e.stopPropagation();handleMarkPaid(t);}} title="Marcar como pago"
                                className="w-7 h-7 rounded-lg flex items-center justify-center text-emerald-500 hover:text-white hover:bg-emerald-500 transition-colors">
                                <Icon name="Check" size={14}/>
                              </button>
                            )}
                            {/* Desktop: editar/excluir extras */}
                            <button onClick={(e)=>{e.stopPropagation();setEditTrx(t);setShowModal(true);}} className="hidden md:flex w-7 h-7 rounded-lg items-center justify-center text-slate-400 hover:text-amber-600 hover:bg-amber-50 transition-colors"><Icon name="Edit" size={13}/></button>
                            <button onClick={(e)=>{e.stopPropagation();setConfirm(t.id);}} className="hidden md:flex w-7 h-7 rounded-lg items-center justify-center text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"><Icon name="Trash2" size={13}/></button>
                            {/* Mobile: chevron */}
                            <Icon name="ChevronRight" size={16} color="#94A3B8" className="md:hidden"/>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          }
        </>}

        {tab==='receber' && (
          receivables.length===0 ? <EmptyState icon="CheckCircle" title="Tudo em dia!" message="Não há contas a receber pendentes."/> :
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead><tr className="border-b border-slate-100">
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase">Nº OS</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase">Cliente</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase hidden md:table-cell">Equipamento</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase">Status OS</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-400 uppercase">Em Aberto</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-slate-400 uppercase">Valor</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-slate-400 uppercase">Ações</th>
              </tr></thead>
              <tbody>
                {receivablesAged.map(os=>{
                  const aged = os._days > 30;
                  return (
                    <tr key={os.id} className="border-b border-slate-50 hover:bg-slate-50"
                      style={aged ? { background:'#FFFBEB' } : {}}>
                      <td className="px-4 py-3.5"><span className="font-bold text-sm" style={{color:'#0A1F44'}}>#{os.num}</span></td>
                      <td className="px-4 py-3.5 font-medium text-slate-700">{os.clientName}</td>
                      <td className="px-4 py-3.5 hidden md:table-cell text-slate-500 text-xs">{os.equipment?.brand} {os.equipment?.model}</td>
                      <td className="px-4 py-3.5"><StatusBadge status={os.status}/></td>
                      <td className="px-4 py-3.5">
                        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-bold"
                          style={aged ? { background:'#FEF3C7', color:'#92400E' } : { background:'#F1F5F9', color:'#64748B' }}>
                          <Icon name="Clock" size={10} color={aged?'#92400E':'#64748B'}/>{os._days}d
                        </span>
                      </td>
                      <td className="px-4 py-3.5 text-right font-bold whitespace-nowrap" style={{color:'#059669'}}>{fmtCurrency(os.total||0)}</td>
                      <td className="px-4 py-3.5 text-right">
                        <button onClick={()=>handleReceiveOS(os)}
                          className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold text-white transition-all hover:opacity-90 active:scale-95"
                          style={{ background:'#10B981' }}>
                          <Icon name="DollarSign" size={12} color="white"/>Receber
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
              <tfoot>
                <tr className="bg-slate-50 border-t border-slate-100">
                  <td colSpan={5} className="px-4 py-3 text-right font-bold text-sm" style={{color:'#0A1F44'}}>Total a Receber</td>
                  <td className="px-4 py-3 text-right font-bold text-base" style={{color:'#059669'}}>{fmtCurrency(totalReceivable)}</td>
                  <td/>
                </tr>
              </tfoot>
            </table>
          </div>
        )}
      </Card>

      <TrxModal open={showModal} onClose={()=>{setShowModal(false);setEditTrx(null);}}
        onSave={handleSave}
        onDelete={(id)=>{ onDelete(id); addToast({type:'info',msg:'Movimentação excluída.'}); }}
        editTrx={editTrx}/>
      <ConfirmDialog open={!!confirm} onClose={()=>setConfirm(null)}
        onConfirm={()=>{onDelete(confirm);addToast({type:'info',msg:'Movimentação excluída.'});}}
        message="Excluir esta movimentação financeira?"/>
    </div>
  );
}

Object.assign(window, { Financial });
