import { useState } from 'react';

// ── Helpers ─────────────────────────────────────────────────────────────────
const fmtM = n =>
  n == null ? '—'
  : n >= 1_000_000 ? `$${(n / 1_000_000).toFixed(2)}M`
  : n >= 1000     ? `$${(n / 1000).toFixed(0)}K`
  : `$${n}`;

const fmtPct = n => `${n?.toFixed(1) ?? 0}%`;

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

// ── Mock data ────────────────────────────────────────────────────────────────
const MOCK_REPORT = {
  project: {
    code: 'PRY-001', name: 'AR-ProjectManagement', client: 'Constructora Andina S.A.',
    contract: 'CT-2025-047', type: 'Precio Fijo', currency: 'COP',
    manager: 'Paula Soto', startDate: '2025-03-01', endDate: '2026-12-31',
    status: 'EN_EJECUCION',
  },
  budget: { approved: 850000000, spent: 312500000, committed: 187000000, remaining: 350500000 },
  laborCost: { budget: 180000000, incurred: 67500000, overtime: 8750000, total: 76250000 },
  contracts: {
    total: 420000000, paid: 95000000, pending: 325000000,
    items: [
      { code: 'CON-001', contractor: 'Excavaciones del Norte',   scope: 'Excavación Lote B',               value: 85000000,  paid: 85000000, status: 'COMPLETADO'   },
      { code: 'CON-002', contractor: 'Eléctricos Modernos S.A.', scope: 'Instalación eléctrica pisos 1-5', value: 120000000, paid: 10000000, status: 'EN_EJECUCION'  },
      { code: 'CON-003', contractor: 'Sistemas AR Ltda',         scope: 'Sistema de automatización',       value: 215000000, paid: 0,        status: 'POR_INICIAR'   },
    ],
  },
  purchases: {
    total: 145000000, paid: 95500000, pending: 49500000,
    items: [
      { code: 'OC-001', supplier: 'Aceros del Valle',       desc: 'Varilla corrugada 1/2"',      value: 45000000, paid: 45000000, status: 'PAGADO'   },
      { code: 'OC-002', supplier: 'Cementos Andina',        desc: 'Cemento Portland x500 bultos', value: 28500000, paid: 28500000, status: 'PAGADO'   },
      { code: 'OC-003', supplier: 'Eléctricos Central',     desc: 'Tablero principal 400A',       value: 22000000, paid: 22000000, status: 'PAGADO'   },
      { code: 'OC-004', supplier: 'Vidrios y Aluminios S.A.', desc: 'Fachada vidrio templado',   value: 49500000, paid: 0,        status: 'PENDIENTE' },
    ],
  },
  cashflow: {
    received: 255000000, disbursed: 194250000, balance: 60750000,
    projectedOut: 187000000,
    items: [
      { date: '2025-04-01', desc: 'Anticipo 30% cliente',          type: 'INGRESO', amount: 255000000 },
      { date: '2025-05-15', desc: 'Pago contratista excavación',   type: 'EGRESO',  amount: 85000000  },
      { date: '2025-06-01', desc: 'Compra materiales estructura',  type: 'EGRESO',  amount: 73500000  },
      { date: '2025-09-10', desc: 'Nómina y HE Q3',               type: 'EGRESO',  amount: 35750000  },
    ],
  },
  evm: { bac: 850000000, pv: 340000000, ev: 312500000, ac: 269250000 },
};

const MOCK_REPORT_2 = {
  project: {
    code: 'PRY-002', name: 'Sistema Eléctrico Planta', client: 'Industrias Metálicas del Valle',
    contract: 'CT-2025-098', type: 'Precio Unitario', currency: 'COP',
    manager: 'Ricardo Mora', startDate: '2025-06-01', endDate: '2026-03-31',
    status: 'EN_EJECUCION',
  },
  budget: { approved: 320000000, spent: 198000000, committed: 62000000, remaining: 60000000 },
  laborCost: { budget: 95000000, incurred: 61000000, overtime: 12500000, total: 73500000 },
  contracts: {
    total: 180000000, paid: 130000000, pending: 50000000,
    items: [
      { code: 'CON-011', contractor: 'Eléctricos del Sur S.A.',   scope: 'Instalación tableros MT/BT',     value: 95000000,  paid: 95000000,  status: 'COMPLETADO'  },
      { code: 'CON-012', contractor: 'Automatización Industrial',  scope: 'PLC y sistemas SCADA',           value: 85000000,  paid: 35000000,  status: 'EN_EJECUCION'},
    ],
  },
  purchases: {
    total: 87000000, paid: 72000000, pending: 15000000,
    items: [
      { code: 'OC-011', supplier: 'Schneider Electric Colombia', desc: 'Tablero principal 630A',     value: 38000000, paid: 38000000, status: 'PAGADO'   },
      { code: 'OC-012', supplier: 'Cables y Conductores S.A.',   desc: 'Cable 4/0 AWG x 800m',      value: 19000000, paid: 19000000, status: 'PAGADO'   },
      { code: 'OC-013', supplier: 'Siemens Colombia',            desc: 'Variadores de frecuencia x8',value: 30000000, paid: 15000000, status: 'PENDIENTE'},
    ],
  },
  cashflow: {
    received: 200000000, disbursed: 198000000, balance: 2000000,
    projectedOut: 62000000,
    items: [
      { date: '2025-07-01', desc: 'Anticipo 40% cliente',           type: 'INGRESO', amount: 128000000 },
      { date: '2025-08-15', desc: 'Pago CON-011 avance 50%',        type: 'EGRESO',  amount: 47500000  },
      { date: '2025-10-01', desc: 'Factura #2 cliente hito 2',      type: 'INGRESO', amount: 72000000  },
      { date: '2025-11-20', desc: 'Compra tableros y cables',        type: 'EGRESO',  amount: 57000000  },
      { date: '2026-01-10', desc: 'Pago nómina y HE Q4',            type: 'EGRESO',  amount: 38500000  },
    ],
  },
  evm: { bac: 320000000, pv: 240000000, ev: 198000000, ac: 210500000 },
};

const MOCK_REPORT_3 = {
  project: {
    code: 'PRY-003', name: 'Automatización Línea Producción', client: 'Confecciones Moda S.A.',
    contract: 'CT-2026-012', type: 'Precio Fijo', currency: 'USD',
    manager: 'Carmen Vidal', startDate: '2026-01-15', endDate: '2026-09-30',
    status: 'EN_EJECUCION',
  },
  budget: { approved: 180000, spent: 42000, committed: 28000, remaining: 110000 },
  laborCost: { budget: 55000, incurred: 13500, overtime: 1200, total: 14700 },
  contracts: {
    total: 95000, paid: 22000, pending: 73000,
    items: [
      { code: 'CON-021', contractor: 'Robótica Aplicada Ltda',  scope: 'Brazos robóticos x4 + integración', value: 65000, paid: 22000, status: 'EN_EJECUCION'},
      { code: 'CON-022', contractor: 'Ingeniería de Procesos',  scope: 'Rediseño línea de producción',       value: 30000, paid: 0,     status: 'POR_INICIAR' },
    ],
  },
  purchases: {
    total: 43000, paid: 19000, pending: 24000,
    items: [
      { code: 'OC-021', supplier: 'Fanuc América',        desc: 'Controladores CNC x4',   value: 28000, paid: 19000, status: 'PAGADO'   },
      { code: 'OC-022', supplier: 'Sensores & Visión S.A.', desc: 'Cámaras visión x8',   value: 15000, paid: 0,     status: 'PENDIENTE'},
    ],
  },
  cashflow: {
    received: 54000, disbursed: 41000, balance: 13000,
    projectedOut: 28000,
    items: [
      { date: '2026-01-20', desc: 'Anticipo 30% contrato',       type: 'INGRESO', amount: 54000 },
      { date: '2026-02-10', desc: 'Primer pago contratista',      type: 'EGRESO',  amount: 22000 },
      { date: '2026-03-01', desc: 'Compra equipos Fanuc',         type: 'EGRESO',  amount: 19000 },
    ],
  },
  evm: { bac: 180000, pv: 63000, ev: 42000, ac: 41000 },
};

const MOCK_REPORT_4 = {
  project: {
    code: 'PRY-004', name: 'Expansión Almacén Logístico', client: 'Distribuidora Nacional S.A.',
    contract: 'CT-2025-201', type: 'Administración Delegada', currency: 'COP',
    manager: 'Jorge Salcedo', startDate: '2025-09-01', endDate: '2026-08-31',
    status: 'EN_EJECUCION',
  },
  budget: { approved: 620000000, spent: 89000000, committed: 145000000, remaining: 386000000 },
  laborCost: { budget: 120000000, incurred: 22000000, overtime: 3500000, total: 25500000 },
  contracts: {
    total: 310000000, paid: 48000000, pending: 262000000,
    items: [
      { code: 'CON-031', contractor: 'Estructuras Metálicas CR',  scope: 'Estructura metálica nave',      value: 185000000, paid: 48000000, status: 'EN_EJECUCION'},
      { code: 'CON-032', contractor: 'Pisos Industriales Ltda',   scope: 'Piso epóxico 8.000 m²',         value: 75000000,  paid: 0,        status: 'POR_INICIAR' },
      { code: 'CON-033', contractor: 'Sistemas de Rack S.A.S.',   scope: 'Estanterías drive-in x120',     value: 50000000,  paid: 0,        status: 'POR_INICIAR' },
    ],
  },
  purchases: {
    total: 78000000, paid: 21000000, pending: 57000000,
    items: [
      { code: 'OC-031', supplier: 'Teja y Cubierta S.A.',  desc: 'Cubierta termoacústica 9.000m²', value: 42000000, paid: 21000000, status: 'PAGADO'   },
      { code: 'OC-032', supplier: 'Puertas Industriales',  desc: 'Puertas seccionales x6',         value: 18000000, paid: 0,        status: 'PENDIENTE'},
      { code: 'OC-033', supplier: 'Sistemas contra incendio', desc: 'Red húmeda NFPA',             value: 18000000, paid: 0,        status: 'PENDIENTE'},
    ],
  },
  cashflow: {
    received: 186000000, disbursed: 89000000, balance: 97000000,
    projectedOut: 145000000,
    items: [
      { date: '2025-09-15', desc: 'Anticipo 30% cliente',         type: 'INGRESO', amount: 186000000 },
      { date: '2025-10-20', desc: 'Pago anticipo estructuras',     type: 'EGRESO',  amount: 55500000  },
      { date: '2025-12-01', desc: 'Compra cubierta 50%',           type: 'EGRESO',  amount: 21000000  },
      { date: '2026-01-15', desc: 'Nómina Q4 2025',               type: 'EGRESO',  amount: 12500000  },
    ],
  },
  evm: { bac: 620000000, pv: 124000000, ev: 89000000, ac: 89000000 },
};

const PROJECTS = [
  { id: 'PRY-001', label: 'PRY-001 — AR-ProjectManagement',           data: MOCK_REPORT   },
  { id: 'PRY-002', label: 'PRY-002 — Sistema Eléctrico Planta',    data: MOCK_REPORT_2 },
  { id: 'PRY-003', label: 'PRY-003 — Automatización Producción',   data: MOCK_REPORT_3 },
  { id: 'PRY-004', label: 'PRY-004 — Expansión Almacén Logístico', data: MOCK_REPORT_4 },
];

// ── Status helpers ───────────────────────────────────────────────────────────
const STATUS_MAP = {
  EN_EJECUCION: { label: 'En ejecución', cls: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' },
  COMPLETADO:   { label: 'Completado',   cls: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' },
  POR_INICIAR:  { label: 'Por iniciar',  cls: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300' },
  INICIO:       { label: 'Inicio',       cls: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' },
  PAGADO:       { label: 'Pagado',       cls: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' },
  PENDIENTE:    { label: 'Pendiente',    cls: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' },
};

const Badge = ({ status }) => {
  const s = STATUS_MAP[status] ?? { label: status, cls: 'bg-slate-100 text-slate-600' };
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${s.cls}`}>
      {s.label}
    </span>
  );
};

// ── Shared UI atoms ──────────────────────────────────────────────────────────
const Card = ({ children, className = '' }) => (
  <div className={`bg-white dark:bg-surface-800 border border-slate-200 dark:border-surface-700 rounded-2xl p-5 ${className}`}>
    {children}
  </div>
);

const SectionTitle = ({ children }) => (
  <h2 className="text-base font-semibold text-slate-800 dark:text-slate-100 mb-4">{children}</h2>
);

const Th = ({ children, right = false }) => (
  <th className={`px-4 py-3 text-xs font-semibold uppercase tracking-wide text-slate-500 dark:text-slate-400 ${right ? 'text-right' : 'text-left'}`}>
    {children}
  </th>
);

const Td = ({ children, right = false, className = '' }) => (
  <td className={`px-4 py-3 text-sm text-slate-700 dark:text-slate-300 ${right ? 'text-right tabular-nums' : ''} ${className}`}>
    {children}
  </td>
);

const TFoot = ({ children }) => (
  <tfoot className="bg-slate-50 dark:bg-surface-700/50 border-t border-slate-200 dark:border-surface-700">
    {children}
  </tfoot>
);

const TfTd = ({ children, right = false, className = '' }) => (
  <td className={`px-4 py-3 text-sm font-semibold text-slate-800 dark:text-slate-100 ${right ? 'text-right tabular-nums' : ''} ${className}`}>
    {children}
  </td>
);

// ── Budget progress bar ──────────────────────────────────────────────────────
const BudgetBar = ({ pct }) => {
  const color =
    pct < 70  ? 'bg-emerald-500'
    : pct < 90 ? 'bg-amber-500'
    : 'bg-red-500';
  const textColor =
    pct < 70  ? 'text-emerald-600 dark:text-emerald-400'
    : pct < 90 ? 'text-amber-600 dark:text-amber-400'
    : 'text-red-600 dark:text-red-400';
  return (
    <div className="mt-3">
      <div className="flex justify-between text-xs mb-1">
        <span className="text-slate-500 dark:text-slate-400">Ejecución presupuestal</span>
        <span className={`font-semibold ${textColor}`}>{fmtPct(pct)}</span>
      </div>
      <div className="h-2 rounded-full bg-slate-100 dark:bg-surface-700 overflow-hidden">
        <div className={`h-full rounded-full transition-all ${color}`} style={{ width: `${Math.min(pct, 100)}%` }} />
      </div>
    </div>
  );
};

// ── KPI card ─────────────────────────────────────────────────────────────────
const KpiCard = ({ label, value, sub, accent = 'slate', showBar = false, barPct = 0 }) => {
  const accents = {
    emerald: 'text-emerald-600 dark:text-emerald-400',
    blue:    'text-blue-600 dark:text-blue-400',
    amber:   'text-amber-600 dark:text-amber-400',
    red:     'text-red-600 dark:text-red-400',
    slate:   'text-slate-800 dark:text-slate-100',
  };
  return (
    <Card className="flex flex-col gap-1">
      <p className="text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{label}</p>
      <p className={`text-2xl font-bold ${accents[accent]}`}>{value}</p>
      {sub && <p className="text-xs text-slate-400 dark:text-slate-500">{sub}</p>}
      {showBar && <BudgetBar pct={barPct} />}
    </Card>
  );
};

// ── EVM indicator ─────────────────────────────────────────────────────────────
const EvmIndex = ({ label, value, isRatio = false }) => {
  const color =
    !isRatio ? 'text-slate-800 dark:text-slate-100'
    : value >= 1   ? 'text-emerald-600 dark:text-emerald-400'
    : value >= 0.9 ? 'text-amber-600 dark:text-amber-400'
    : 'text-red-600 dark:text-red-400';
  return (
    <div className="flex flex-col items-center gap-1 p-4 bg-slate-50 dark:bg-surface-700/50 rounded-xl">
      <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">{label}</p>
      <p className={`text-xl font-bold ${color}`}>
        {isRatio ? value.toFixed(2) : fmtM(value)}
      </p>
      {isRatio && (
        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
          value >= 1 ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
          : value >= 0.9 ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'
          : 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'
        }`}>
          {value >= 1 ? '▲ Eficiente' : value >= 0.9 ? '◆ En riesgo' : '▼ Crítico'}
        </span>
      )}
    </div>
  );
};

// ── Main component ────────────────────────────────────────────────────────────
export default function ProjectFinancialReport() {
  const [selectedId, setSelectedId] = useState('PRY-001');
  const report = PROJECTS.find(p => p.id === selectedId)?.data ?? MOCK_REPORT;

  const { project, budget, laborCost, contracts, purchases, cashflow, evm } = report;

  // Derived totals
  const totalIncurred = laborCost.total + contracts.paid + purchases.paid;
  const totalCommitted = contracts.pending + purchases.pending;
  const availableBalance = budget.approved - totalIncurred - totalCommitted;
  const execPct = (totalIncurred / budget.approved) * 100;

  // EVM
  const cpi = evm.ac > 0 ? evm.ev / evm.ac : 0;
  const spi = evm.pv > 0 ? evm.ev / evm.pv : 0;

  // Cost table rows
  const costRows = [
    { cat: 'Mano de obra base', budgeted: laborCost.budget, incurred: laborCost.incurred },
    { cat: 'Horas extra',       budgeted: 0,                incurred: laborCost.overtime },
    { cat: 'Contratistas',      budgeted: contracts.total,  incurred: contracts.paid      },
    { cat: 'Proveedores',       budgeted: purchases.total,  incurred: purchases.paid      },
  ];

  const cashflowAlert = cashflow.balance < totalCommitted;

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-surface-900 p-6">
      <div className="max-w-7xl mx-auto space-y-6">

        {/* ── Header ─────────────────────────────────────────────────────── */}
        <Card>
          <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
            {/* Left: project info */}
            <div className="space-y-2 flex-1 min-w-0">
              <div className="flex items-center gap-3 flex-wrap">
                <span className="text-xs font-mono font-semibold text-slate-400 dark:text-slate-500 bg-slate-100 dark:bg-surface-700 px-2 py-1 rounded-lg">
                  {project.code}
                </span>
                <Badge status={project.status} />
                <span className="text-xs text-slate-400 dark:text-slate-500">{project.currency}</span>
              </div>
              <h1 className="text-xl font-bold text-slate-900 dark:text-white truncate">{project.name}</h1>
              <div className="flex flex-wrap gap-x-6 gap-y-1 text-sm text-slate-500 dark:text-slate-400">
                <span><span className="font-medium text-slate-700 dark:text-slate-300">Cliente:</span> {project.client}</span>
                <span><span className="font-medium text-slate-700 dark:text-slate-300">Contrato:</span> {project.contract}</span>
                <span><span className="font-medium text-slate-700 dark:text-slate-300">Tipo:</span> {project.type}</span>
                <span><span className="font-medium text-slate-700 dark:text-slate-300">Gerente:</span> {project.manager}</span>
                <span><span className="font-medium text-slate-700 dark:text-slate-300">Inicio:</span> {fmtD(project.startDate)}</span>
                <span><span className="font-medium text-slate-700 dark:text-slate-300">Fin:</span> {fmtD(project.endDate)}</span>
              </div>
            </div>

            {/* Right: selector + export */}
            <div className="flex flex-col sm:items-end gap-3 shrink-0">
              <select
                value={selectedId}
                onChange={e => setSelectedId(e.target.value)}
                className="text-sm border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-800 text-slate-700 dark:text-slate-200 rounded-xl px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {PROJECTS.map(p => (
                  <option key={p.id} value={p.id}>{p.label}</option>
                ))}
              </select>
              <button className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-xl transition-colors">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                Exportar PDF
              </button>
            </div>
          </div>
        </Card>

        {/* ── KPIs principales ────────────────────────────────────────────── */}
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
          <KpiCard
            label="Presupuesto aprobado"
            value={fmtM(budget.approved)}
            sub={`Contrato ${project.contract}`}
            accent="slate"
            showBar
            barPct={execPct}
          />
          <KpiCard
            label="Costo incurrido total"
            value={fmtM(totalIncurred)}
            sub={`${fmtPct((totalIncurred / budget.approved) * 100)} del presupuesto`}
            accent={execPct < 70 ? 'emerald' : execPct < 90 ? 'amber' : 'red'}
          />
          <KpiCard
            label="Compromisos pendientes"
            value={fmtM(totalCommitted)}
            sub={`Contratos ${fmtM(contracts.pending)} · OC ${fmtM(purchases.pending)}`}
            accent="amber"
          />
          <KpiCard
            label="Saldo disponible"
            value={fmtM(availableBalance)}
            sub={availableBalance < 0 ? '⚠ Sobregiro presupuestal' : 'Presupuesto sin comprometer'}
            accent={availableBalance < 0 ? 'red' : 'emerald'}
          />
        </div>

        {/* ── Costos incurridos ────────────────────────────────────────────── */}
        <Card>
          <SectionTitle>Costos incurridos por categoría</SectionTitle>
          <div className="overflow-x-auto -mx-1">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 dark:border-surface-700">
                  <Th>Categoría</Th>
                  <Th right>Presupuestado</Th>
                  <Th right>Incurrido</Th>
                  <Th right>Variación</Th>
                  <Th right>% Ejec.</Th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
                {costRows.map(row => {
                  const variation = row.incurred - row.budgeted;
                  const pct = row.budgeted > 0 ? (row.incurred / row.budgeted) * 100 : null;
                  return (
                    <tr key={row.cat} className="hover:bg-slate-50/50 dark:hover:bg-surface-700/30 transition-colors">
                      <Td>{row.cat}</Td>
                      <Td right>{fmtM(row.budgeted)}</Td>
                      <Td right>{fmtM(row.incurred)}</Td>
                      <Td right className={variation > 0 ? 'text-red-600 dark:text-red-400' : variation < 0 ? 'text-emerald-600 dark:text-emerald-400' : ''}>
                        {variation === 0 ? '—' : (variation > 0 ? '+' : '') + fmtM(variation)}
                      </Td>
                      <Td right>{pct != null ? fmtPct(pct) : '—'}</Td>
                    </tr>
                  );
                })}
              </tbody>
              <TFoot>
                <tr>
                  <TfTd>Total incurrido</TfTd>
                  <TfTd right>{fmtM(laborCost.budget + contracts.total + purchases.total)}</TfTd>
                  <TfTd right>{fmtM(totalIncurred)}</TfTd>
                  <TfTd right className={(totalIncurred - (laborCost.budget + contracts.total + purchases.total)) > 0 ? 'text-red-600' : 'text-emerald-600'}>
                    {fmtM(totalIncurred - (laborCost.budget + contracts.total + purchases.total))}
                  </TfTd>
                  <TfTd right>{fmtPct((totalIncurred / (laborCost.budget + contracts.total + purchases.total)) * 100)}</TfTd>
                </tr>
              </TFoot>
            </table>
          </div>
        </Card>

        {/* ── Contratos ────────────────────────────────────────────────────── */}
        <Card>
          <SectionTitle>Contratos</SectionTitle>
          <div className="overflow-x-auto -mx-1">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 dark:border-surface-700">
                  <Th>Código</Th>
                  <Th>Contratista</Th>
                  <Th>Alcance</Th>
                  <Th right>Valor</Th>
                  <Th right>Pagado</Th>
                  <Th right>Pendiente</Th>
                  <Th>Estado</Th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
                {contracts.items.map(c => (
                  <tr key={c.code} className="hover:bg-slate-50/50 dark:hover:bg-surface-700/30 transition-colors">
                    <Td className="font-mono text-xs">{c.code}</Td>
                    <Td>{c.contractor}</Td>
                    <Td className="max-w-xs truncate">{c.scope}</Td>
                    <Td right>{fmtM(c.value)}</Td>
                    <Td right className="text-emerald-600 dark:text-emerald-400">{fmtM(c.paid)}</Td>
                    <Td right className={c.value - c.paid > 0 ? 'text-amber-600 dark:text-amber-400' : ''}>{fmtM(c.value - c.paid)}</Td>
                    <Td><Badge status={c.status} /></Td>
                  </tr>
                ))}
              </tbody>
              <TFoot>
                <tr>
                  <TfTd colSpan={3}>Total contratos</TfTd>
                  <TfTd right>{fmtM(contracts.total)}</TfTd>
                  <TfTd right className="text-emerald-600 dark:text-emerald-400">{fmtM(contracts.paid)}</TfTd>
                  <TfTd right className="text-amber-600 dark:text-amber-400">{fmtM(contracts.pending)}</TfTd>
                  <TfTd />
                </tr>
              </TFoot>
            </table>
          </div>
        </Card>

        {/* ── Órdenes de compra ─────────────────────────────────────────────── */}
        <Card>
          <SectionTitle>Órdenes de compra</SectionTitle>
          <div className="overflow-x-auto -mx-1">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 dark:border-surface-700">
                  <Th>OC</Th>
                  <Th>Proveedor</Th>
                  <Th>Descripción</Th>
                  <Th right>Valor</Th>
                  <Th right>Pagado</Th>
                  <Th right>Pendiente</Th>
                  <Th>Estado</Th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
                {purchases.items.map(p => (
                  <tr key={p.code} className="hover:bg-slate-50/50 dark:hover:bg-surface-700/30 transition-colors">
                    <Td className="font-mono text-xs">{p.code}</Td>
                    <Td>{p.supplier}</Td>
                    <Td>{p.desc}</Td>
                    <Td right>{fmtM(p.value)}</Td>
                    <Td right className="text-emerald-600 dark:text-emerald-400">{fmtM(p.paid)}</Td>
                    <Td right className={p.value - p.paid > 0 ? 'text-amber-600 dark:text-amber-400' : ''}>{fmtM(p.value - p.paid)}</Td>
                    <Td><Badge status={p.status} /></Td>
                  </tr>
                ))}
              </tbody>
              <TFoot>
                <tr>
                  <TfTd colSpan={3}>Total órdenes de compra</TfTd>
                  <TfTd right>{fmtM(purchases.total)}</TfTd>
                  <TfTd right className="text-emerald-600 dark:text-emerald-400">{fmtM(purchases.paid)}</TfTd>
                  <TfTd right className="text-amber-600 dark:text-amber-400">{fmtM(purchases.pending)}</TfTd>
                  <TfTd />
                </tr>
              </TFoot>
            </table>
          </div>
        </Card>

        {/* ── Flujo de caja ─────────────────────────────────────────────────── */}
        <Card>
          <SectionTitle>Flujo de caja</SectionTitle>

          {/* KPIs */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-5">
            <div className="bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 rounded-xl p-4">
              <p className="text-xs font-medium text-emerald-700 dark:text-emerald-400 uppercase tracking-wide">Recibido del cliente</p>
              <p className="text-2xl font-bold text-emerald-700 dark:text-emerald-400 mt-1">{fmtM(cashflow.received)}</p>
            </div>
            <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-4">
              <p className="text-xs font-medium text-red-700 dark:text-red-400 uppercase tracking-wide">Desembolsado</p>
              <p className="text-2xl font-bold text-red-700 dark:text-red-400 mt-1">{fmtM(cashflow.disbursed)}</p>
            </div>
            <div className={`rounded-xl p-4 border ${cashflowAlert ? 'bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800' : 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'}`}>
              <p className={`text-xs font-medium uppercase tracking-wide ${cashflowAlert ? 'text-amber-700 dark:text-amber-400' : 'text-blue-700 dark:text-blue-400'}`}>Saldo actual</p>
              <p className={`text-2xl font-bold mt-1 ${cashflowAlert ? 'text-amber-700 dark:text-amber-400' : 'text-blue-700 dark:text-blue-400'}`}>{fmtM(cashflow.balance)}</p>
            </div>
          </div>

          {/* Alerta */}
          {cashflowAlert && (
            <div className="mb-5 flex items-start gap-3 p-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700 rounded-xl">
              <svg className="w-5 h-5 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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-semibold text-amber-800 dark:text-amber-300">Alerta de liquidez</p>
                <p className="text-xs text-amber-700 dark:text-amber-400 mt-0.5">
                  El saldo actual ({fmtM(cashflow.balance)}) es insuficiente para cubrir los compromisos pendientes ({fmtM(totalCommitted)}).
                  Déficit proyectado: {fmtM(totalCommitted - cashflow.balance)}.
                </p>
              </div>
            </div>
          )}

          {/* Movimientos */}
          <div className="overflow-x-auto -mx-1">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 dark:border-surface-700">
                  <Th>Fecha</Th>
                  <Th>Descripción</Th>
                  <Th>Tipo</Th>
                  <Th right>Monto</Th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
                {cashflow.items.map((item, i) => (
                  <tr key={i} className="hover:bg-slate-50/50 dark:hover:bg-surface-700/30 transition-colors">
                    <Td className="whitespace-nowrap">{fmtD(item.date)}</Td>
                    <Td>{item.desc}</Td>
                    <Td>
                      <span className={`inline-flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded-full ${
                        item.type === 'INGRESO'
                          ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300'
                          : 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'
                      }`}>
                        {item.type === 'INGRESO' ? '▲' : '▼'} {item.type}
                      </span>
                    </Td>
                    <Td right className={item.type === 'INGRESO' ? 'text-emerald-600 dark:text-emerald-400 font-medium' : 'text-red-600 dark:text-red-400 font-medium'}>
                      {item.type === 'INGRESO' ? '+' : '-'}{fmtM(item.amount)}
                    </Td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>

        {/* ── EVM ──────────────────────────────────────────────────────────── */}
        <Card>
          <SectionTitle>Gestión del valor ganado (EVM)</SectionTitle>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
            <EvmIndex label="BAC" value={evm.bac} />
            <EvmIndex label="PV — Valor planificado" value={evm.pv} />
            <EvmIndex label="EV — Valor ganado" value={evm.ev} />
            <EvmIndex label="AC — Costo real" value={evm.ac} />
            <EvmIndex label="CPI — Eficiencia costo" value={cpi} isRatio />
            <EvmIndex label="SPI — Eficiencia plazo" value={spi} isRatio />
          </div>
          <div className="mt-4 p-4 bg-slate-50 dark:bg-surface-700/40 rounded-xl">
            <p className="text-xs text-slate-500 dark:text-slate-400">
              <span className="font-semibold text-slate-700 dark:text-slate-300">CPI = EV / AC</span> — mide eficiencia de costo. CPI &gt; 1: bajo presupuesto. &nbsp;|&nbsp;
              <span className="font-semibold text-slate-700 dark:text-slate-300">SPI = EV / PV</span> — mide eficiencia de cronograma. SPI &gt; 1: adelantado. &nbsp;|&nbsp;
              <span className="font-semibold text-slate-700 dark:text-slate-300">Estimación a completar (EAC):</span> {fmtM(evm.bac / cpi)}.
            </p>
          </div>
        </Card>

        {/* Footer */}
        <p className="text-center text-xs text-slate-400 dark:text-slate-600 pb-2">
          Reporte generado el {fmtD(new Date().toISOString())} · AR-ProjectManagement · Solo para uso interno
        </p>
      </div>
    </div>
  );
}
