import React, { useState } from 'react';
import { useProject } from '../../context/ProjectContext';
import { MOCK_PROJECTS } from '../../services/mockData';

// ── Mock data ──────────────────────────────────────────────────────────────────
const MOCK_PAYMENTS = [
  { id:'pag1', ref:'PAG-2026-001', poCode:'PO-2026-001', supplier:'ElectroSur Ltda.',
    concept:'Licencias software servidor — 5 uds', project:'AR-ProjectManagement', projectCode:'PRY-2026-004', projectId:'p4',
    amount:4250000, currency:'COP', dueDate:'2026-07-05', status:'PENDIENTE',
    paymentMethod:null, accountingEntry:null, approvedBy:'Carmen Fuentes',
    createdAt:'2026-06-16', receivedDate:'2026-06-21', receivedBy:'Luis M.' },
  { id:'pag2', ref:'PAG-2026-002', poCode:'PO-2026-002', supplier:'Aceros del Norte S.A.',
    concept:'Varilla corrugada 3/8" × 500 und', project:'AR-ProjectManagement', projectCode:'PRY-2026-004', projectId:'p4',
    amount:21000000, currency:'COP', dueDate:'2026-08-19', status:'PENDIENTE',
    paymentMethod:null, accountingEntry:null, approvedBy:'Carmen Fuentes',
    createdAt:'2026-06-24', receivedDate:null, receivedBy:null },
  { id:'pag3', ref:'PAG-2026-003', poCode:'PO-2025-088', supplier:'CementoMax Industrial',
    concept:'Cemento gris Tipo I × 300 sacos', project:'AR-ProjectManagement', projectCode:'PRY-2026-004', projectId:'p4',
    amount:8400000, currency:'COP', dueDate:'2026-06-15', status:'PAGADO',
    paymentMethod:'Transferencia bancaria', accountingEntry:'AC-2026-0441',
    approvedBy:'Carmen Fuentes',
    createdAt:'2026-05-30', receivedDate:'2026-06-02', receivedBy:'Carlos R.',
    paidDate:'2026-06-14', paidBy:'Ana T.' },
  { id:'pag4', ref:'PAG-2026-004', poCode:'PO-2025-091', supplier:'Andamios & Equipos S.A.',
    concept:'Renta andamios tubulares — 60 días', project:'AR-ProjectManagement', projectCode:'PRY-2026-004', projectId:'p4',
    amount:6300000, currency:'COP', dueDate:'2026-06-10', status:'VENCIDO',
    paymentMethod:null, accountingEntry:null, approvedBy:'Carmen Fuentes',
    createdAt:'2026-05-28', receivedDate:'2026-06-01', receivedBy:'Carlos R.' },
];

const MOCK_TRANSACTIONS = [
  { id:'tx1', entry:'AC-2026-0441', date:'2026-06-14', type:'EGRESO', concept:'Pago a CementoMax Industrial — PO-2025-088',
    debit:'51050 — Materiales y Suministros', credit:'11100 — Bancos', amount:8400000, ref:'PAG-2026-003',
    approvedBy:'Ana T.', project:'AR-ProjectManagement' },
  { id:'tx2', entry:'AC-2026-0388', date:'2026-05-20', type:'EGRESO', concept:'Pago nomina mayo 2026',
    debit:'51010 — Sueldos y Salarios', credit:'11100 — Bancos', amount:18500000, ref:'NOM-2026-005',
    approvedBy:'Carmen F.', project:'General' },
  { id:'tx3', entry:'AC-2026-0312', date:'2026-04-30', type:'INGRESO', concept:'Anticipo cliente AR-ProjectManagement',
    debit:'11100 — Bancos', credit:'24050 — Anticipos de clientes', amount:45000000, ref:'FAC-2026-011',
    approvedBy:'Ana T.', project:'AR-ProjectManagement' },
];

const STATUS_STYLE = {
  PENDIENTE: 'bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400 border-amber-200 dark:border-amber-500/20',
  PAGADO:    'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20',
  VENCIDO:   'bg-red-50 text-red-700 dark:bg-red-500/10 dark:text-red-400 border-red-200 dark:border-red-500/20',
  APROBADO:  'bg-blue-50 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400 border-blue-200 dark:border-blue-500/20',
};

const TABS = ['Pagos a proveedores', 'Contratos / Contratistas', 'Nómina y Horas Extra', 'Libro de transacciones', 'Flujo de caja'];

// ── Mock contratos ─────────────────────────────────────────────────────────────
const MOCK_CONTRACTS = [
  { id:'con1', code:'CON-2026-001', contractor:'Construciones Rápidas S.A.S.', contact:'Hernán Díaz',
    project:'AR-ProjectManagement', projectCode:'PRY-2026-004',
    scope:'Excavación y movimiento de tierras — Lote B (3.200 m³)',
    value:45000000, currency:'COP',
    signedDate:'2026-05-15', startDate:'2026-05-20', endDate:'2026-07-31',
    retentionPct:10, advancePct:30, advancePaid:true,
    status:'EN_EJECUCION', progress:62,
    milestones:[
      { id:'m1', desc:'Movilización de maquinaria', pct:30, amount:13500000, dueDate:'2026-05-25', receivedDate:'2026-05-24', qcStatus:'APROBADO', qcBy:'Carlos R.', payStatus:'PAGADO', paidDate:'2026-05-28' },
      { id:'m2', desc:'Excavación 50% avance',     pct:40, amount:18000000, dueDate:'2026-06-30', receivedDate:'2026-06-28', qcStatus:'APROBADO', qcBy:'Carlos R.', payStatus:'PAGADO', paidDate:'2026-07-02' },
      { id:'m3', desc:'Excavación 100% + limpieza', pct:30, amount:13500000, dueDate:'2026-07-31', receivedDate:null, qcStatus:null, payStatus:'PENDIENTE', paidDate:null },
    ]},
  { id:'con2', code:'CON-2026-002', contractor:'Electro Instalaciones del Caribe',  contact:'Rosa Mendoza',
    project:'AR-ProjectManagement', projectCode:'PRY-2026-004',
    scope:'Instalación eléctrica pisos 1–5 (tableros, canaletas, tomacorrientes)',
    value:28000000, currency:'COP',
    signedDate:'2026-06-01', startDate:'2026-06-10', endDate:'2026-08-15',
    retentionPct:10, advancePct:30, advancePaid:true,
    status:'EN_EJECUCION', progress:30,
    milestones:[
      { id:'m4', desc:'Tendido canaletas y tuberías', pct:40, amount:11200000, dueDate:'2026-07-10', receivedDate:null, qcStatus:null, payStatus:'PENDIENTE', paidDate:null },
      { id:'m5', desc:'Instalación tableros pisos 1-3', pct:35, amount:9800000, dueDate:'2026-07-25', receivedDate:null, qcStatus:null, payStatus:'PENDIENTE', paidDate:null },
      { id:'m6', desc:'Pruebas finales y entrega',     pct:25, amount:7000000, dueDate:'2026-08-15', receivedDate:null, qcStatus:null, payStatus:'PENDIENTE', paidDate:null },
    ]},
  { id:'con3', code:'CON-2026-003', contractor:'Dev Studio Latam',  contact:'Felipe Arango',
    project:'AR-ProjectManagement', projectCode:'PRY-2026-004',
    scope:'Desarrollo módulo de inventarios y WMS — Sprint 3 y 4',
    value:18000000, currency:'COP',
    signedDate:'2026-06-10', startDate:'2026-06-15', endDate:'2026-07-30',
    retentionPct:5, advancePct:0, advancePaid:false,
    status:'EN_EJECUCION', progress:45,
    milestones:[
      { id:'m7', desc:'Sprint 3 — CRUD inventario', pct:50, amount:9000000, dueDate:'2026-07-05', receivedDate:'2026-07-04', qcStatus:'OBSERVACIONES', qcBy:'Luis M.', qcNotes:'Faltan pruebas unitarias en módulo de ajustes.', payStatus:'EN_REVISION', paidDate:null },
      { id:'m8', desc:'Sprint 4 — integración WMS', pct:50, amount:9000000, dueDate:'2026-07-30', receivedDate:null, qcStatus:null, payStatus:'PENDIENTE', paidDate:null },
    ]},
];

// ── Mock nómina/overtime ────────────────────────────────────────────────────────
const MOCK_EMPLOYEES = [
  { id:'e1', name:'Paula Soto',    role:'Gerente de Proyecto', dept:'PM',          salary:6500000, avatar:'AT' },
  { id:'e2', name:'Luis Moreno',   role:'Desarrollador Sr.',   dept:'Tecnología',  salary:4800000, avatar:'LM' },
  { id:'e3', name:'Carlos Ríos',   role:'Ingeniero Civil',     dept:'Operaciones', salary:4200000, avatar:'CR' },
  { id:'e4', name:'María Jiménez', role:'Arquitecta',          dept:'Diseño',      salary:4500000, avatar:'MJ' },
  { id:'e5', name:'Pedro Salcedo', role:'Electricista',        dept:'Operaciones', salary:2800000, avatar:'PS' },
];

const MOCK_OVERTIME = [
  { id:'ot1', employeeId:'e2', date:'2026-06-20', hours:4, project:'AR-ProjectManagement', task:'Corrección bugs críticos módulo auth', authorizedBy:'e1', authName:'Paula Soto', reason:'Despliegue urgente cliente', costHour:30000, status:'APROBADO', reportedToHR:true,  hrReportDate:'2026-06-21' },
  { id:'ot2', employeeId:'e3', date:'2026-06-22', hours:6, project:'AR-ProjectManagement', task:'Supervisión vaciado concreto nocturno', authorizedBy:'e1', authName:'Paula Soto', reason:'Condiciones climáticas óptimas solo en noche', costHour:26250, status:'APROBADO', reportedToHR:false, hrReportDate:null },
  { id:'ot3', employeeId:'e2', date:'2026-06-25', hours:3, project:'AR-ProjectManagement', task:'Reunión técnica cliente — zona horaria diferente', authorizedBy:'e1', authName:'Paula Soto', reason:'Cliente en España', costHour:30000, status:'PENDIENTE', reportedToHR:false, hrReportDate:null },
  { id:'ot4', employeeId:'e5', date:'2026-06-26', hours:5, project:'AR-ProjectManagement', task:'Instalación tablero principal piso 1', authorizedBy:'e4', authName:'María Jiménez', reason:'Avance cronograma crítico', costHour:17500, status:'PENDIENTE', reportedToHR:false, hrReportDate:null },
  { id:'ot5', employeeId:'e4', date:'2026-06-15', hours:2, project:'AR-ProjectManagement', task:'Revisión planos estructura Level 3', authorizedBy:'e1', authName:'Paula Soto', reason:'Cambio de diseño solicitado por cliente', costHour:28125, status:'RECHAZADO', reportedToHR:false, hrReportDate:null },
];

const fmtM  = n => `$${Number(n).toLocaleString('es-CO')}`;
const fmtD  = d => d ? new Date(d).toLocaleDateString('es-CO', {day:'2-digit',month:'short',year:'numeric'}) : '—';

// ── Modal de pago ─────────────────────────────────────────────────────────────
function PaymentModal({ pago, onClose, onSave }) {
  const [form, setForm] = useState({
    paymentMethod: 'Transferencia bancaria',
    accountingEntry: `AC-2026-${String(Math.floor(Math.random()*9000)+1000)}`,
    paidDate: new Date().toISOString().split('T')[0],
    notes: '',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={onClose}>
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-lg border border-slate-200 dark:border-surface-700" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-surface-700">
          <div>
            <h2 className="text-base font-bold text-slate-900 dark:text-white">Registrar pago</h2>
            <p className="text-xs text-slate-400 mt-0.5">{pago.ref} · {pago.supplier}</p>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-white cursor-pointer">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>

        <div className="p-6 space-y-4">
          {/* Resumen */}
          <div className="bg-blue-50 dark:bg-blue-500/10 rounded-xl p-4 border border-blue-100 dark:border-blue-500/20">
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div><p className="text-xs text-slate-400">OC relacionada</p><p className="font-semibold text-slate-800 dark:text-white">{pago.poCode}</p></div>
              <div><p className="text-xs text-slate-400">Monto a pagar</p><p className="font-bold text-blue-700 dark:text-blue-400 text-lg">{fmtM(pago.amount)}</p></div>
              <div><p className="text-xs text-slate-400">Proveedor</p><p className="font-semibold text-slate-800 dark:text-white">{pago.supplier}</p></div>
              <div><p className="text-xs text-slate-400">Proyecto</p><p className="font-semibold text-slate-800 dark:text-white">{pago.project}</p></div>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-xs font-semibold text-slate-500 dark:text-gray-400 block mb-1.5">Fecha de pago</label>
              <input type="date" value={form.paidDate} onChange={e => set('paidDate', e.target.value)}
                className="w-full text-sm bg-slate-50 dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-lg px-3 py-2 text-slate-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500"/>
            </div>
            <div>
              <label className="text-xs font-semibold text-slate-500 dark:text-gray-400 block mb-1.5">Método de pago</label>
              <select value={form.paymentMethod} onChange={e => set('paymentMethod', e.target.value)}
                className="w-full text-sm bg-slate-50 dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-lg px-3 py-2 text-slate-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option>Transferencia bancaria</option>
                <option>Cheque</option>
                <option>Efectivo</option>
                <option>PSE</option>
                <option>Débito automático</option>
              </select>
            </div>
          </div>

          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-gray-400 block mb-1.5">
              Asiento contable <span className="font-normal text-slate-400">(auto-generado)</span>
            </label>
            <input value={form.accountingEntry} onChange={e => set('accountingEntry', e.target.value)}
              className="w-full text-sm font-mono bg-slate-50 dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-lg px-3 py-2 text-slate-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500"/>
          </div>

          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-gray-400 block mb-1.5">Notas / soporte</label>
            <textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} placeholder="Número de transacción, referencia bancaria..."
              className="w-full text-sm bg-slate-50 dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-lg px-3 py-2 text-slate-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"/>
          </div>

          {/* Asientos automáticos */}
          <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-3 border border-slate-100 dark:border-surface-600">
            <p className="text-xs font-semibold text-slate-500 dark:text-gray-400 mb-2">Asientos generados automáticamente</p>
            <div className="space-y-1 text-xs font-mono">
              <div className="flex justify-between">
                <span className="text-slate-600 dark:text-gray-300">DÉBITO  51050 — Materiales y Suministros</span>
                <span className="text-slate-800 dark:text-white font-bold">{fmtM(pago.amount)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-600 dark:text-gray-300">CRÉDITO 11100 — Bancos</span>
                <span className="text-slate-800 dark:text-white font-bold">{fmtM(pago.amount)}</span>
              </div>
            </div>
          </div>
        </div>

        <div className="flex justify-end gap-2 px-6 py-4 border-t border-slate-100 dark:border-surface-700">
          <button onClick={onClose} className="px-4 py-2 text-sm text-slate-600 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 rounded-lg cursor-pointer transition-colors">Cancelar</button>
          <button onClick={() => { onSave({ ...pago, ...form, status:'PAGADO', paidBy:'Usuario actual' }); onClose(); }}
            className="px-4 py-2 text-sm bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg cursor-pointer transition-colors flex items-center gap-2">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>
            Confirmar pago
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Tab: Pagos ────────────────────────────────────────────────────────────────
function TabPagos() {
  const { selectedProjectId } = useProject();
  const [payments, setPayments] = useState(MOCK_PAYMENTS);
  const [filter, setFilter]     = useState('TODOS');
  const [paying, setPaying]     = useState(null);
  const [search, setSearch]     = useState('');

  const counts = { TODOS: payments.length, PENDIENTE: 0, VENCIDO: 0, PAGADO: 0 };
  payments.forEach(p => { if (counts[p.status] !== undefined) counts[p.status]++; });

  const filtered = payments.filter(p =>
    (!selectedProjectId || p.projectId === selectedProjectId) &&
    (filter === 'TODOS' || p.status === filter) &&
    (!search || `${p.ref} ${p.supplier} ${p.concept} ${p.project}`.toLowerCase().includes(search.toLowerCase()))
  );

  const totalPendiente = payments.filter(p => p.status === 'PENDIENTE').reduce((s,p) => s+p.amount, 0);
  const totalVencido   = payments.filter(p => p.status === 'VENCIDO').reduce((s,p) => s+p.amount, 0);
  const totalPagado    = payments.filter(p => p.status === 'PAGADO').reduce((s,p) => s+p.amount, 0);

  const handleSave = (updated) => {
    setPayments(prev => prev.map(p => p.id === updated.id ? updated : p));
  };

  return (
    <div className="space-y-4">
      {/* KPI strip */}
      <div className="grid grid-cols-3 gap-3">
        {[
          { label:'Por pagar', value: fmtM(totalPendiente), color:'text-amber-600 dark:text-amber-400', bg:'bg-amber-50 dark:bg-amber-500/10 border-amber-100 dark:border-amber-500/20' },
          { label:'Vencido',   value: fmtM(totalVencido),   color:'text-red-600 dark:text-red-400',     bg:'bg-red-50 dark:bg-red-500/10 border-red-100 dark:border-red-500/20' },
          { label:'Pagado mes', value: fmtM(totalPagado),   color:'text-emerald-600 dark:text-emerald-400', bg:'bg-emerald-50 dark:bg-emerald-500/10 border-emerald-100 dark:border-emerald-500/20' },
        ].map(k => (
          <div key={k.label} className={`rounded-xl p-4 border ${k.bg}`}>
            <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wide mb-1">{k.label}</p>
            <p className={`text-xl font-bold tabular-nums ${k.color}`}>{k.value}</p>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 max-w-xs">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="11" cy="11" r="8"/><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35"/></svg>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar pago..."
            className="w-full pl-8 pr-3 py-2 text-sm rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-gray-200 placeholder-slate-300 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
        </div>
        <div className="flex gap-1 bg-slate-100 dark:bg-surface-800 rounded-xl p-1 border border-slate-200 dark:border-surface-700">
          {['TODOS','PENDIENTE','VENCIDO','PAGADO'].map(s => (
            <button key={s} onClick={() => setFilter(s)}
              className={`px-3 py-1 text-xs font-semibold rounded-lg transition cursor-pointer ${filter===s ? 'bg-white dark:bg-surface-700 text-slate-900 dark:text-white shadow-sm' : 'text-slate-400 dark:text-gray-500 hover:text-slate-700 dark:hover:text-gray-300'}`}>
              {s} {counts[s] > 0 && <span className="ml-1 opacity-60">({counts[s]})</span>}
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-surface-700 border-b border-slate-100 dark:border-surface-600">
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">Ref.</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">Proveedor / Concepto</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">Proyecto</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">OC</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">Recepción</th>
              <th className="px-4 py-3 text-right text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">Monto</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">Vencimiento</th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">Estado</th>
              <th className="px-4 py-3"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
            {filtered.map(p => {
              const vencido = p.status !== 'PAGADO' && new Date(p.dueDate) < new Date();
              return (
                <tr key={p.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/50 transition-colors">
                  <td className="px-4 py-3 font-mono text-xs font-bold text-slate-600 dark:text-gray-300 whitespace-nowrap">{p.ref}</td>
                  <td className="px-4 py-3">
                    <p className="font-semibold text-slate-800 dark:text-white text-sm">{p.supplier}</p>
                    <p className="text-xs text-slate-400 dark:text-gray-500 truncate max-w-[200px]">{p.concept}</p>
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400">{p.projectCode}</td>
                  <td className="px-4 py-3 font-mono text-xs text-blue-600 dark:text-blue-400">{p.poCode}</td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400">
                    {p.receivedDate
                      ? <><span className="text-emerald-600 dark:text-emerald-400 font-medium">✓ {fmtD(p.receivedDate)}</span><br/><span className="text-slate-400">{p.receivedBy}</span></>
                      : <span className="text-amber-500">Pendiente recepción</span>}
                  </td>
                  <td className="px-4 py-3 text-right font-bold text-slate-900 dark:text-white tabular-nums whitespace-nowrap">{fmtM(p.amount)}</td>
                  <td className={`px-4 py-3 text-xs font-semibold whitespace-nowrap ${vencido ? 'text-red-600 dark:text-red-400' : 'text-slate-600 dark:text-gray-400'}`}>
                    {fmtD(p.dueDate)}{vencido && <span className="ml-1 text-red-500">⚠</span>}
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-semibold px-2.5 py-1 rounded-full border ${STATUS_STYLE[p.status] || ''}`}>
                      {p.status}
                    </span>
                    {p.accountingEntry && <p className="text-xs text-slate-400 font-mono mt-0.5">{p.accountingEntry}</p>}
                  </td>
                  <td className="px-4 py-3">
                    {(p.status === 'PENDIENTE' || p.status === 'VENCIDO') && p.receivedDate && (
                      <button onClick={() => setPaying(p)}
                        className="px-3 py-1.5 text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg cursor-pointer transition-colors whitespace-nowrap">
                        Registrar pago
                      </button>
                    )}
                    {(p.status === 'PENDIENTE' || p.status === 'VENCIDO') && !p.receivedDate && (
                      <button
                        onClick={() => setPayments(prev => prev.map(x => x.id === p.id ? {...x, receivedDate: new Date().toISOString().split('T')[0], receivedBy:'Usuario actual'} : x))}
                        className="px-3 py-1.5 text-xs font-semibold border border-blue-300 dark:border-blue-500/40 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-500/10 rounded-lg cursor-pointer transition-colors whitespace-nowrap">
                        Confirmar recepción
                      </button>
                    )}
                    {p.status === 'PAGADO' && (
                      <span className="text-xs text-emerald-600 dark:text-emerald-400 font-medium">✓ Pagado {fmtD(p.paidDate)}</span>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {paying && <PaymentModal pago={paying} onClose={() => setPaying(null)} onSave={handleSave}/>}
    </div>
  );
}

// ── Tab: Contratos / Contratistas ────────────────────────────────────────────
const CONTRACT_STATUS = {
  EN_EJECUCION: 'bg-blue-50 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400 border-blue-200 dark:border-blue-500/20',
  COMPLETADO:   'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400 border-emerald-100 dark:border-emerald-500/20',
  SUSPENDIDO:   'bg-red-50 text-red-700 dark:bg-red-500/10 dark:text-red-400 border-red-100 dark:border-red-500/20',
};
const QC_STYLE = {
  APROBADO:      'text-emerald-600 dark:text-emerald-400',
  OBSERVACIONES: 'text-amber-600 dark:text-amber-400',
  RECHAZADO:     'text-red-600 dark:text-red-400',
};

function QCModal({ milestone, contract, onClose, onSave }) {
  const [result, setResult] = useState('APROBADO');
  const [notes, setNotes]   = useState('');
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={onClose}>
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-md border border-slate-200 dark:border-surface-700" onClick={e=>e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-surface-700">
          <div>
            <h2 className="text-base font-bold text-slate-900 dark:text-white">Control de calidad — Recepción</h2>
            <p className="text-xs text-slate-400 mt-0.5">{contract.code} · {milestone.desc}</p>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 cursor-pointer"><svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg></button>
        </div>
        <div className="p-6 space-y-4">
          <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
            <p className="text-xs text-slate-400 mb-1">Hito</p>
            <p className="font-semibold text-slate-800 dark:text-white">{milestone.desc}</p>
            <p className="text-xs text-slate-400 mt-1">Valor del hito: <span className="font-bold text-slate-700 dark:text-gray-300">{fmtM(milestone.amount)}</span></p>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-gray-400 block mb-2">Resultado de la inspección</label>
            <div className="flex gap-2">
              {['APROBADO','OBSERVACIONES','RECHAZADO'].map(r => (
                <button key={r} onClick={() => setResult(r)}
                  className={`flex-1 py-2 text-xs font-semibold rounded-lg border cursor-pointer transition-all ${result===r ? {APROBADO:'bg-emerald-600 text-white border-emerald-600', OBSERVACIONES:'bg-amber-500 text-white border-amber-500', RECHAZADO:'bg-red-600 text-white border-red-600'}[r] : 'bg-white dark:bg-surface-700 text-slate-600 dark:text-gray-300 border-slate-200 dark:border-surface-600 hover:border-slate-400'}`}>
                  {r}
                </button>
              ))}
            </div>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-gray-400 block mb-1.5">Observaciones / acta</label>
            <textarea rows={3} value={notes} onChange={e=>setNotes(e.target.value)} placeholder="Descripción de la inspección, observaciones técnicas..."
              className="w-full text-sm bg-slate-50 dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-lg px-3 py-2 text-slate-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"/>
          </div>
        </div>
        <div className="flex justify-end gap-2 px-6 py-4 border-t border-slate-100 dark:border-surface-700">
          <button onClick={onClose} className="px-4 py-2 text-sm text-slate-600 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 rounded-lg cursor-pointer">Cancelar</button>
          <button onClick={() => { onSave(milestone.id, result, notes); onClose(); }}
            className="px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg cursor-pointer flex items-center gap-2">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>
            Registrar resultado
          </button>
        </div>
      </div>
    </div>
  );
}

function TabContratos() {
  const [contracts, setContracts] = useState(MOCK_CONTRACTS);
  const [expanded, setExpanded]   = useState(null);
  const [qcModal, setQcModal]     = useState(null); // {contract, milestone}
  const [payModal, setPayModal]   = useState(null);

  const handleQCSave = (contractId, milestoneId, result, notes) => {
    setContracts(prev => prev.map(c => c.id !== contractId ? c : {
      ...c,
      milestones: c.milestones.map(m => m.id !== milestoneId ? m : {
        ...m, qcStatus: result, qcNotes: notes, qcBy: 'Usuario actual',
        payStatus: result === 'APROBADO' ? 'LISTO_PARA_PAGO' : 'EN_REVISION',
      })
    }));
  };

  const handlePaySave = (contractId, milestoneId) => {
    setContracts(prev => prev.map(c => c.id !== contractId ? c : {
      ...c,
      milestones: c.milestones.map(m => m.id !== milestoneId ? m : {
        ...m, payStatus:'PAGADO', paidDate: new Date().toISOString().split('T')[0],
      })
    }));
  };

  const totalContratos    = contracts.reduce((s,c)=>s+c.value,0);
  const totalPagadoCon    = contracts.reduce((s,c)=>s+c.milestones.filter(m=>m.payStatus==='PAGADO').reduce((a,m)=>a+m.amount,0),0);
  const totalPendienteCon = contracts.reduce((s,c)=>s+c.milestones.filter(m=>m.payStatus!=='PAGADO').reduce((a,m)=>a+m.amount,0),0);

  return (
    <div className="space-y-4">
      {/* KPIs */}
      <div className="grid grid-cols-3 gap-3">
        {[
          { label:'Valor total contratos', value:fmtM(totalContratos),    color:'text-slate-900 dark:text-white',              bg:'bg-white dark:bg-surface-800 border-slate-200 dark:border-surface-700' },
          { label:'Pagado a contratistas', value:fmtM(totalPagadoCon),    color:'text-emerald-600 dark:text-emerald-400',      bg:'bg-emerald-50 dark:bg-emerald-500/10 border-emerald-100 dark:border-emerald-500/20' },
          { label:'Por pagar (hitos)',      value:fmtM(totalPendienteCon), color:'text-amber-600 dark:text-amber-400',          bg:'bg-amber-50 dark:bg-amber-500/10 border-amber-100 dark:border-amber-500/20' },
        ].map(k=>(
          <div key={k.label} className={`rounded-xl p-4 border ${k.bg}`}>
            <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wide mb-1">{k.label}</p>
            <p className={`text-xl font-bold tabular-nums ${k.color}`}>{k.value}</p>
          </div>
        ))}
      </div>

      {/* Contratos */}
      <div className="space-y-3">
        {contracts.map(con => (
          <div key={con.id} className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
            {/* Header del contrato */}
            <button onClick={()=>setExpanded(expanded===con.id?null:con.id)}
              className="w-full flex items-center gap-4 px-5 py-4 hover:bg-slate-50 dark:hover:bg-surface-700/50 transition-colors cursor-pointer text-left">
              <div className="flex-1 grid grid-cols-4 gap-4 items-center">
                <div>
                  <p className="text-xs font-mono text-blue-600 dark:text-blue-400">{con.code}</p>
                  <p className="text-sm font-bold text-slate-900 dark:text-white mt-0.5">{con.contractor}</p>
                  <p className="text-xs text-slate-400 dark:text-gray-500">{con.contact}</p>
                </div>
                <div>
                  <p className="text-xs text-slate-400 dark:text-gray-500">Proyecto</p>
                  <p className="text-sm font-medium text-slate-700 dark:text-gray-300">{con.projectCode}</p>
                </div>
                <div>
                  <p className="text-xs text-slate-400 dark:text-gray-500">Valor contrato</p>
                  <p className="text-sm font-bold text-slate-800 dark:text-white tabular-nums">{fmtM(con.value)}</p>
                </div>
                <div className="flex items-center gap-3">
                  <div className="flex-1">
                    <div className="flex justify-between text-xs mb-1">
                      <span className="text-slate-400 dark:text-gray-500">Avance</span>
                      <span className="font-bold text-slate-700 dark:text-gray-300">{con.progress}%</span>
                    </div>
                    <div className="h-1.5 bg-slate-100 dark:bg-surface-600 rounded-full overflow-hidden">
                      <div className="h-full bg-blue-500 rounded-full" style={{width:`${con.progress}%`}}/>
                    </div>
                  </div>
                  <span className={`text-xs font-semibold px-2.5 py-1 rounded-full border whitespace-nowrap ${CONTRACT_STATUS[con.status]||''}`}>
                    {con.status.replace('_',' ')}
                  </span>
                </div>
              </div>
              <svg className={`w-4 h-4 text-slate-400 transition-transform flex-shrink-0 ${expanded===con.id?'rotate-180':''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7"/></svg>
            </button>

            {/* Hitos */}
            {expanded===con.id && (
              <div className="border-t border-slate-100 dark:border-surface-700">
                <div className="px-5 py-2 bg-slate-50 dark:bg-surface-700/50">
                  <p className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-widest">Alcance: {con.scope}</p>
                </div>
                <table className="w-full text-sm">
                  <thead>
                    <tr className="bg-slate-50 dark:bg-surface-700">
                      <th className="px-5 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-gray-400">Hito / Entregable</th>
                      <th className="px-5 py-2.5 text-right text-xs font-semibold text-slate-500 dark:text-gray-400">Valor</th>
                      <th className="px-5 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-gray-400">Vencimiento</th>
                      <th className="px-5 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-gray-400">Recepción</th>
                      <th className="px-5 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-gray-400">QC</th>
                      <th className="px-5 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-gray-400">Pago</th>
                      <th className="px-5 py-2.5"></th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
                    {con.milestones.map(m => (
                      <tr key={m.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/30">
                        <td className="px-5 py-3">
                          <p className="font-medium text-slate-800 dark:text-white">{m.desc}</p>
                          <p className="text-xs text-slate-400 dark:text-gray-500">{m.pct}% del contrato</p>
                        </td>
                        <td className="px-5 py-3 text-right font-bold tabular-nums text-slate-800 dark:text-white whitespace-nowrap">{fmtM(m.amount)}</td>
                        <td className="px-5 py-3 text-xs text-slate-500 dark:text-gray-400 whitespace-nowrap">{fmtD(m.dueDate)}</td>
                        <td className="px-5 py-3 text-xs">
                          {m.receivedDate
                            ? <><span className="text-emerald-600 dark:text-emerald-400 font-medium">✓ {fmtD(m.receivedDate)}</span></>
                            : <span className="text-slate-400 dark:text-gray-500">Pendiente</span>}
                        </td>
                        <td className="px-5 py-3 text-xs">
                          {m.qcStatus
                            ? <><span className={`font-semibold ${QC_STYLE[m.qcStatus]}`}>{m.qcStatus}</span>{m.qcBy && <p className="text-slate-400 dark:text-gray-500">{m.qcBy}</p>}</>
                            : <span className="text-slate-300 dark:text-gray-600">—</span>}
                          {m.qcNotes && <p className="text-amber-600 dark:text-amber-400 text-xs max-w-[140px] truncate" title={m.qcNotes}>⚠ {m.qcNotes}</p>}
                        </td>
                        <td className="px-5 py-3 text-xs">
                          {m.payStatus==='PAGADO'
                            ? <><span className="text-emerald-600 dark:text-emerald-400 font-semibold">✓ Pagado</span><p className="text-slate-400 dark:text-gray-500">{fmtD(m.paidDate)}</p></>
                            : <span className={`font-semibold ${m.payStatus==='LISTO_PARA_PAGO'?'text-blue-600 dark:text-blue-400':m.payStatus==='EN_REVISION'?'text-amber-500':'text-slate-400 dark:text-gray-500'}`}>
                                {m.payStatus.replace('_',' ')}
                              </span>}
                        </td>
                        <td className="px-5 py-3 text-right">
                          <div className="flex gap-2 justify-end">
                            {m.receivedDate && !m.qcStatus && (
                              <button onClick={()=>setQcModal({contract:con,milestone:m})}
                                className="px-2.5 py-1.5 text-xs font-semibold bg-blue-600 hover:bg-blue-700 text-white rounded-lg cursor-pointer whitespace-nowrap">
                                Inspección QC
                              </button>
                            )}
                            {!m.receivedDate && (
                              <button onClick={()=>setContracts(prev=>prev.map(c=>c.id!==con.id?c:{...c,milestones:c.milestones.map(x=>x.id!==m.id?x:{...x,receivedDate:new Date().toISOString().split('T')[0]})}))}
                                className="px-2.5 py-1.5 text-xs font-semibold border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 rounded-lg cursor-pointer whitespace-nowrap">
                                Recibir
                              </button>
                            )}
                            {m.payStatus==='LISTO_PARA_PAGO' && (
                              <button onClick={()=>handlePaySave(con.id,m.id)}
                                className="px-2.5 py-1.5 text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg cursor-pointer whitespace-nowrap">
                                Pagar hito
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        ))}
      </div>

      {qcModal && (
        <QCModal
          contract={qcModal.contract} milestone={qcModal.milestone}
          onClose={()=>setQcModal(null)}
          onSave={(milId,result,notes)=>{ handleQCSave(qcModal.contract.id,milId,result,notes); }}
        />
      )}
    </div>
  );
}

// ── Modal Reporte HR ──────────────────────────────────────────────────────────
function HRReportModal({ overtime, employees, onConfirm, onClose }) {
  const pending = overtime.filter(o => o.status === 'APROBADO' && !o.reportedToHR);

  // Agrupar por empleado
  const byEmployee = {};
  pending.forEach(o => {
    if (!byEmployee[o.employeeId]) {
      const emp = employees.find(e => e.id === o.employeeId);
      byEmployee[o.employeeId] = { emp, records: [] };
    }
    byEmployee[o.employeeId].records.push(o);
  });
  const groups = Object.values(byEmployee);
  const today = new Date().toLocaleDateString('es-CO', { day:'2-digit', month:'long', year:'numeric' });

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={onClose}>
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-2xl border border-slate-200 dark:border-surface-700 max-h-[90vh] flex flex-col" onClick={e=>e.stopPropagation()}>
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-surface-700">
          <div>
            <h2 className="text-base font-bold text-slate-900 dark:text-white">Reporte de Horas Extra — Recursos Humanos</h2>
            <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{pending.length} registro{pending.length!==1?'s':''} aprobado{pending.length!==1?'s':''} pendiente{pending.length!==1?'s':''} de reporte · {today}</p>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-white cursor-pointer">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>

        <div className="overflow-y-auto flex-1 p-6 space-y-5">
          {groups.length === 0 && (
            <div className="text-center py-10 text-slate-400 dark:text-gray-500">
              <svg className="w-10 h-10 mx-auto mb-3 opacity-30" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
              <p className="text-sm font-medium">Todas las HE aprobadas ya fueron reportadas a HR</p>
            </div>
          )}

          {groups.map(({ emp, records }) => {
            const totalHoras = records.reduce((s,r)=>s+r.hours,0);
            const totalCosto = records.reduce((s,r)=>s+r.hours*r.costHour,0);
            return (
              <div key={emp.id} className="border border-slate-200 dark:border-surface-600 rounded-xl overflow-hidden">
                {/* Cabecera empleado */}
                <div className="flex items-center gap-3 px-4 py-3 bg-blue-50 dark:bg-blue-500/10">
                  <div className="w-9 h-9 rounded-full bg-blue-600 flex items-center justify-center flex-shrink-0">
                    <span className="text-white text-xs font-bold">{emp.avatar}</span>
                  </div>
                  <div className="flex-1">
                    <p className="text-sm font-bold text-slate-900 dark:text-white">{emp.name}</p>
                    <p className="text-xs text-slate-500 dark:text-gray-400">{emp.role} · {emp.dept}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-xs text-slate-400 dark:text-gray-500">Total HE</p>
                    <p className="text-base font-bold text-blue-700 dark:text-blue-400">{totalHoras}h · {fmtM(totalCosto)}</p>
                  </div>
                </div>
                {/* Detalle de registros */}
                <table className="w-full text-xs">
                  <thead>
                    <tr className="bg-slate-50 dark:bg-surface-700">
                      {['Fecha','Horas','Proyecto / Tarea','Motivo','Autorizado por'].map(h=>(
                        <th key={h} className="px-3 py-2 text-left font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50 dark:divide-surface-600">
                    {records.map(r => (
                      <tr key={r.id}>
                        <td className="px-3 py-2 text-slate-600 dark:text-gray-300 whitespace-nowrap">{fmtD(r.date)}</td>
                        <td className="px-3 py-2 font-bold text-slate-800 dark:text-white">{r.hours}h</td>
                        <td className="px-3 py-2">
                          <p className="font-medium text-slate-700 dark:text-gray-300">{r.project}</p>
                          <p className="text-slate-400 dark:text-gray-500 truncate max-w-[180px]">{r.task}</p>
                        </td>
                        <td className="px-3 py-2 text-slate-500 dark:text-gray-400 max-w-[140px] truncate">{r.reason}</td>
                        <td className="px-3 py-2 font-medium text-slate-700 dark:text-gray-300">{r.authName}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            );
          })}
        </div>

        <div className="flex items-center justify-between px-6 py-4 border-t border-slate-100 dark:border-surface-700">
          <p className="text-xs text-slate-400 dark:text-gray-500">
            Este reporte se enviará al módulo de RRHH y quedará registrado con fecha y hora de envío.
          </p>
          <div className="flex gap-2">
            <button onClick={onClose} className="px-4 py-2 text-sm text-slate-600 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 rounded-lg cursor-pointer transition-colors">Cancelar</button>
            {groups.length > 0 && (
              <button onClick={onConfirm}
                className="px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg cursor-pointer flex items-center gap-2 transition-colors">
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                Enviar a HR ({groups.length} empleado{groups.length!==1?'s':''})
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Tab: Nómina y Horas Extra ─────────────────────────────────────────────────
function TabNomina() {
  const [overtime, setOvertime] = useState(MOCK_OVERTIME);
  const [showForm, setShowForm] = useState(false);
  const [filterEmp, setFilterEmp] = useState('TODOS');
  const [showHRModal, setShowHRModal] = useState(false);
  const [hrSent, setHrSent] = useState(false);

  const totalOTAprobado  = overtime.filter(o=>o.status==='APROBADO').reduce((s,o)=>s+o.hours*o.costHour,0);
  const totalOTPendiente = overtime.filter(o=>o.status==='PENDIENTE').reduce((s,o)=>s+o.hours*o.costHour,0);
  const pendingHRCount   = overtime.filter(o=>o.status==='APROBADO' && !o.reportedToHR).length;

  const handleApprove = (id, action) => {
    setOvertime(prev => prev.map(o => o.id!==id ? o : {...o, status: action}));
  };

  const handleSendToHR = () => {
    const today = new Date().toISOString().split('T')[0];
    setOvertime(prev => prev.map(o =>
      o.status==='APROBADO' && !o.reportedToHR ? {...o, reportedToHR:true, hrReportDate:today} : o
    ));
    setShowHRModal(false);
    setHrSent(true);
    setTimeout(() => setHrSent(false), 4000);
  };

  const salarioBase = MOCK_EMPLOYEES.reduce((s,e)=>s+e.salary,0);
  const totalMes = salarioBase + totalOTAprobado;

  const filtered = overtime.filter(o => filterEmp==='TODOS' || o.employeeId===filterEmp);

  return (
    <div className="space-y-5">
      {/* KPIs nómina */}
      <div className="grid grid-cols-4 gap-3">
        {[
          { label:'Salarios base / mes', value:fmtM(salarioBase),     color:'text-slate-900 dark:text-white', bg:'bg-white dark:bg-surface-800 border-slate-200 dark:border-surface-700' },
          { label:'HE aprobadas (costo)', value:fmtM(totalOTAprobado),  color:'text-amber-600 dark:text-amber-400', bg:'bg-amber-50 dark:bg-amber-500/10 border-amber-100 dark:border-amber-500/20' },
          { label:'HE pendientes aprobación', value:fmtM(totalOTPendiente), color:'text-blue-600 dark:text-blue-400', bg:'bg-blue-50 dark:bg-blue-500/10 border-blue-100 dark:border-blue-500/20' },
          { label:'Nómina proyectada mes', value:fmtM(totalMes),       color:'text-slate-900 dark:text-white', bg:'bg-white dark:bg-surface-800 border-slate-200 dark:border-surface-700' },
        ].map(k=>(
          <div key={k.label} className={`rounded-xl p-4 border ${k.bg}`}>
            <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wide mb-1">{k.label}</p>
            <p className={`text-lg font-bold tabular-nums ${k.color}`}>{k.value}</p>
          </div>
        ))}
      </div>

      {/* Resumen de empleados */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-100 dark:border-surface-700 flex items-center justify-between">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Nómina base</p>
          <span className="text-xs text-slate-400">Junio 2026</span>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-surface-700">
              {['Empleado','Cargo','Dpto.','Salario base','HE horas','HE costo','Total mes'].map(h=>(
                <th key={h} className="px-4 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
            {MOCK_EMPLOYEES.map(emp => {
              const empOT = overtime.filter(o=>o.employeeId===emp.id && o.status==='APROBADO');
              const horasOT = empOT.reduce((s,o)=>s+o.hours,0);
              const costoOT = empOT.reduce((s,o)=>s+o.hours*o.costHour,0);
              return (
                <tr key={emp.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/50">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2.5">
                      <div className="w-7 h-7 rounded-full bg-blue-100 dark:bg-blue-500/20 flex items-center justify-center flex-shrink-0">
                        <span className="text-xs font-bold text-blue-700 dark:text-blue-400">{emp.avatar}</span>
                      </div>
                      <span className="font-medium text-slate-800 dark:text-white">{emp.name}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400">{emp.role}</td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400">{emp.dept}</td>
                  <td className="px-4 py-3 font-bold tabular-nums text-slate-800 dark:text-white">{fmtM(emp.salary)}</td>
                  <td className="px-4 py-3 text-center">
                    {horasOT > 0
                      ? <span className="text-xs font-bold text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-500/10 px-2 py-0.5 rounded-full">{horasOT}h</span>
                      : <span className="text-xs text-slate-300 dark:text-gray-600">—</span>}
                  </td>
                  <td className="px-4 py-3 font-bold tabular-nums text-amber-600 dark:text-amber-400">{costoOT ? fmtM(costoOT) : '—'}</td>
                  <td className="px-4 py-3 font-bold tabular-nums text-slate-900 dark:text-white">{fmtM(emp.salary + costoOT)}</td>
                </tr>
              );
            })}
            <tr className="bg-slate-50 dark:bg-surface-700 font-bold">
              <td colSpan={3} className="px-4 py-3 text-sm text-slate-700 dark:text-gray-300">TOTAL NÓMINA</td>
              <td className="px-4 py-3 tabular-nums text-slate-900 dark:text-white">{fmtM(salarioBase)}</td>
              <td className="px-4 py-3"></td>
              <td className="px-4 py-3 tabular-nums text-amber-600 dark:text-amber-400">{fmtM(totalOTAprobado)}</td>
              <td className="px-4 py-3 tabular-nums text-slate-900 dark:text-white text-base">{fmtM(totalMes)}</td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Horas extra */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-100 dark:border-surface-700 flex items-center justify-between">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Registro de horas extra</p>
          <div className="flex items-center gap-2 flex-wrap">
            <select value={filterEmp} onChange={e=>setFilterEmp(e.target.value)}
              className="text-xs bg-slate-50 dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-lg px-2 py-1.5 text-slate-700 dark:text-gray-300 focus:outline-none">
              <option value="TODOS">Todos los empleados</option>
              {MOCK_EMPLOYEES.map(e=><option key={e.id} value={e.id}>{e.name}</option>)}
            </select>
            {hrSent && (
              <span className="flex items-center gap-1.5 text-xs font-semibold text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-500/10 px-3 py-1.5 rounded-lg border border-emerald-100 dark:border-emerald-500/20">
                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>
                Reporte enviado a HR
              </span>
            )}
            {pendingHRCount > 0 && !hrSent && (
              <button onClick={()=>setShowHRModal(true)}
                className="relative flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold bg-purple-600 hover:bg-purple-700 text-white rounded-lg cursor-pointer transition-colors">
                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                Enviar a HR
                <span className="absolute -top-1.5 -right-1.5 w-4 h-4 bg-red-500 text-white text-xs rounded-full flex items-center justify-center font-bold leading-none">
                  {pendingHRCount}
                </span>
              </button>
            )}
            <button onClick={()=>setShowForm(f=>!f)}
              className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold bg-blue-600 hover:bg-blue-700 text-white rounded-lg cursor-pointer">
              <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"/></svg>
              Registrar HE
            </button>
          </div>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-surface-700">
              {['Empleado','Fecha','Horas','Proyecto / Tarea','Motivo','Autorizado por','Costo','Estado',''].map(h=>(
                <th key={h} className="px-4 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
            {filtered.map(o => {
              const emp = MOCK_EMPLOYEES.find(e=>e.id===o.employeeId);
              return (
                <tr key={o.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/50">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-500/20 flex items-center justify-center flex-shrink-0">
                        <span className="text-xs font-bold text-blue-700 dark:text-blue-400">{emp?.avatar}</span>
                      </div>
                      <span className="text-xs font-medium text-slate-800 dark:text-white">{emp?.name}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400 whitespace-nowrap">{fmtD(o.date)}</td>
                  <td className="px-4 py-3 text-center">
                    <span className="font-bold text-slate-800 dark:text-white">{o.hours}</span>
                    <span className="text-xs text-slate-400 ml-0.5">h</span>
                  </td>
                  <td className="px-4 py-3 text-xs">
                    <p className="font-medium text-slate-700 dark:text-gray-300">{o.project}</p>
                    <p className="text-slate-400 dark:text-gray-500 truncate max-w-[160px]">{o.task}</p>
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400 max-w-[140px] truncate">{o.reason}</td>
                  <td className="px-4 py-3 text-xs font-medium text-slate-700 dark:text-gray-300">{o.authName}</td>
                  <td className="px-4 py-3 text-xs font-bold tabular-nums text-amber-600 dark:text-amber-400 whitespace-nowrap">{fmtM(o.hours*o.costHour)}</td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-semibold px-2 py-0.5 rounded-full border ${
                      o.status==='APROBADO'  ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400 border-emerald-100 dark:border-emerald-500/20' :
                      o.status==='PENDIENTE' ? 'bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400 border-amber-100 dark:border-amber-500/20' :
                                               'bg-red-50 text-red-700 dark:bg-red-500/10 dark:text-red-400 border-red-100 dark:border-red-500/20'
                    }`}>{o.status}</span>
                  </td>
                  <td className="px-4 py-3">
                    {o.status==='PENDIENTE' && (
                      <div className="flex gap-1.5">
                        <button onClick={()=>handleApprove(o.id,'APROBADO')}
                          title="Aprobar"
                          className="px-2 py-1 text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white rounded cursor-pointer">✓</button>
                        <button onClick={()=>handleApprove(o.id,'RECHAZADO')}
                          title="Rechazar"
                          className="px-2 py-1 text-xs font-semibold bg-red-500 hover:bg-red-600 text-white rounded cursor-pointer">✗</button>
                      </div>
                    )}
                    {o.status==='APROBADO' && (
                      o.reportedToHR
                        ? <span className="text-xs text-purple-600 dark:text-purple-400 font-medium" title={`Reportado a HR el ${fmtD(o.hrReportDate)}`}>
                            ✓ HR {fmtD(o.hrReportDate)}
                          </span>
                        : <span className="text-xs text-amber-500 font-medium">Pendiente HR</span>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {showHRModal && (
        <HRReportModal
          overtime={overtime}
          employees={MOCK_EMPLOYEES}
          onConfirm={handleSendToHR}
          onClose={()=>setShowHRModal(false)}
        />
      )}
    </div>
  );
}

// ── Tab: Libro de transacciones ───────────────────────────────────────────────
function TabLibro() {
  const [txs] = useState(MOCK_TRANSACTIONS);
  const [search, setSearch] = useState('');

  const filtered = txs.filter(t => !search ||
    `${t.entry} ${t.concept} ${t.debit} ${t.credit} ${t.ref}`.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <div className="relative flex-1 max-w-xs">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="11" cy="11" r="8"/><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35"/></svg>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar asiento, concepto..."
            className="w-full pl-8 pr-3 py-2 text-sm rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-gray-200 placeholder-slate-300 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
        </div>
      </div>

      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-surface-700 border-b border-slate-100 dark:border-surface-600">
              {['Asiento','Fecha','Tipo','Concepto','Débito','Crédito','Monto','Ref.','Aprobó'].map(h => (
                <th key={h} className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
            {filtered.map(tx => (
              <tr key={tx.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/50">
                <td className="px-4 py-3 font-mono text-xs font-bold text-slate-600 dark:text-gray-300 whitespace-nowrap">{tx.entry}</td>
                <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400 whitespace-nowrap">{fmtD(tx.date)}</td>
                <td className="px-4 py-3">
                  <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${tx.type === 'EGRESO' ? 'bg-red-50 text-red-600 dark:bg-red-500/10 dark:text-red-400' : 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400'}`}>
                    {tx.type}
                  </span>
                </td>
                <td className="px-4 py-3 text-xs text-slate-700 dark:text-gray-300 max-w-[200px] truncate">{tx.concept}</td>
                <td className="px-4 py-3 text-xs font-mono text-slate-500 dark:text-gray-400 whitespace-nowrap">{tx.debit}</td>
                <td className="px-4 py-3 text-xs font-mono text-slate-500 dark:text-gray-400 whitespace-nowrap">{tx.credit}</td>
                <td className={`px-4 py-3 text-sm font-bold tabular-nums whitespace-nowrap ${tx.type === 'EGRESO' ? 'text-red-600 dark:text-red-400' : 'text-emerald-600 dark:text-emerald-400'}`}>
                  {tx.type === 'EGRESO' ? '-' : '+'}{fmtM(tx.amount)}
                </td>
                <td className="px-4 py-3 font-mono text-xs text-blue-600 dark:text-blue-400">{tx.ref}</td>
                <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400">{tx.approvedBy}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Tab: Flujo de caja ────────────────────────────────────────────────────────
const CASH_FLOW = [
  { mes:'Ene', ingresos:45000000, egresos:22000000, saldo:23000000 },
  { mes:'Feb', ingresos:0,        egresos:18500000, saldo:4500000 },
  { mes:'Mar', ingresos:30000000, egresos:25000000, saldo:9500000 },
  { mes:'Abr', ingresos:0,        egresos:19000000, saldo:-9500000 },
  { mes:'May', ingresos:60000000, egresos:28000000, saldo:22500000 },
  { mes:'Jun', ingresos:0,        egresos:33000000, saldo:-10500000 },
  { mes:'Jul', ingresos:0,        egresos:57750000, saldo:-68250000, proyectado:true },
  { mes:'Ago', ingresos:80000000, egresos:21000000, saldo:-9250000,  proyectado:true },
];

function TabFlujoCaja() {
  const compromisosPendientes = 57750000;
  const saldoBanco = 48500000;
  const deficit = compromisosPendientes - saldoBanco;

  return (
    <div className="space-y-4">
      {/* Alerta si hay déficit */}
      {deficit > 0 && (
        <div className="flex items-start gap-3 bg-red-50 dark:bg-red-500/10 border-2 border-red-200 dark:border-red-500/30 rounded-2xl px-5 py-4">
          <svg className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5 animate-pulse" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
          <div>
            <p className="text-sm font-bold text-red-800 dark:text-red-300">Déficit de flujo de caja proyectado en julio</p>
            <p className="text-xs text-red-600 dark:text-red-400 mt-0.5">
              Compromisos julio: <strong>{fmtM(compromisosPendientes)}</strong> · Saldo disponible: <strong>{fmtM(saldoBanco)}</strong> · Déficit: <strong>{fmtM(deficit)}</strong>
            </p>
          </div>
        </div>
      )}

      {/* KPIs */}
      <div className="grid grid-cols-3 gap-3">
        <div className="bg-white dark:bg-surface-800 rounded-2xl p-4 border border-slate-200 dark:border-surface-700">
          <p className="text-xs text-slate-400 dark:text-gray-500 font-semibold uppercase tracking-wide mb-1">Saldo en banco</p>
          <p className="text-2xl font-bold text-slate-900 dark:text-white tabular-nums">{fmtM(saldoBanco)}</p>
        </div>
        <div className="bg-white dark:bg-surface-800 rounded-2xl p-4 border border-slate-200 dark:border-surface-700">
          <p className="text-xs text-slate-400 dark:text-gray-500 font-semibold uppercase tracking-wide mb-1">Compromisos julio</p>
          <p className="text-2xl font-bold text-amber-600 dark:text-amber-400 tabular-nums">{fmtM(compromisosPendientes)}</p>
        </div>
        <div className={`rounded-2xl p-4 border ${deficit > 0 ? 'bg-red-50 dark:bg-red-500/10 border-red-200 dark:border-red-500/30' : 'bg-emerald-50 dark:bg-emerald-500/10 border-emerald-200 dark:border-emerald-500/30'}`}>
          <p className="text-xs text-slate-400 dark:text-gray-500 font-semibold uppercase tracking-wide mb-1">Posición neta</p>
          <p className={`text-2xl font-bold tabular-nums ${deficit > 0 ? 'text-red-600 dark:text-red-400' : 'text-emerald-600 dark:text-emerald-400'}`}>{deficit > 0 ? '-' : '+'}{fmtM(Math.abs(deficit))}</p>
        </div>
      </div>

      {/* Tabla mensual */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-100 dark:border-surface-700 flex items-center justify-between">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Flujo de caja 2026</p>
          <span className="text-xs text-slate-400 dark:text-gray-500">· Proyectado = estimado</span>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-surface-700">
              {['Mes','Ingresos','Egresos','Saldo acum.',''].map(h => (
                <th key={h} className="px-5 py-2.5 text-left text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wide">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
            {CASH_FLOW.map(row => (
              <tr key={row.mes} className={`hover:bg-slate-50 dark:hover:bg-surface-700/50 ${row.proyectado ? 'opacity-60' : ''}`}>
                <td className="px-5 py-3 font-semibold text-slate-800 dark:text-white">
                  {row.mes} {row.proyectado && <span className="text-xs font-normal text-slate-400 dark:text-gray-500 ml-1">(proyectado)</span>}
                </td>
                <td className="px-5 py-3 text-emerald-600 dark:text-emerald-400 font-bold tabular-nums">{row.ingresos ? `+${fmtM(row.ingresos)}` : '—'}</td>
                <td className="px-5 py-3 text-red-600 dark:text-red-400 font-bold tabular-nums">{row.egresos ? `-${fmtM(row.egresos)}` : '—'}</td>
                <td className={`px-5 py-3 font-bold tabular-nums ${row.saldo >= 0 ? 'text-slate-800 dark:text-white' : 'text-red-600 dark:text-red-400'}`}>
                  {row.saldo >= 0 ? fmtM(row.saldo) : `-${fmtM(Math.abs(row.saldo))}`}
                </td>
                <td className="px-5 py-3">
                  {row.saldo < 0 && <span className="text-xs text-red-500 font-semibold">⚠ Déficit</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Main ──────────────────────────────────────────────────────────────────────
export default function AccountingPage() {
  const [tab, setTab] = useState(0);

  return (
    <div className="space-y-5 pb-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">Contabilidad</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">Pagos a proveedores, libro de transacciones y flujo de caja</p>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-slate-100 dark:bg-surface-800 rounded-xl p-1 w-fit border border-slate-200 dark:border-surface-700">
        {TABS.map((t, i) => (
          <button key={t} onClick={() => setTab(i)}
            className={`px-4 py-1.5 text-sm font-medium rounded-lg transition cursor-pointer ${
              tab === i ? 'bg-white dark:bg-surface-700 text-slate-900 dark:text-white shadow-sm'
                        : 'text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200'}`}>
            {t}
          </button>
        ))}
      </div>

      {tab === 0 && <TabPagos/>}
      {tab === 1 && <TabContratos/>}
      {tab === 2 && <TabNomina/>}
      {tab === 3 && <TabLibro/>}
      {tab === 4 && <TabFlujoCaja/>}
    </div>
  );
}
