import React, { useState } from 'react';
import {
  LineChart, Line, BarChart, Bar, AreaChart, Area,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ReferenceLine,
  ResponsiveContainer, Cell,
} from 'recharts';
import { MOCK_PROJECTS, MOCK_EVM, MOCK_TASKS, getAllProjects, getProjectById, getEVMForProject, getTasksForProject } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';

const fmt  = n => n>=1000000?`$${(n/1000000).toFixed(2)}M`:n>=1000?`$${(n/1000).toFixed(1)}K`:`$${Math.round(n)}`;
const fmtI = n => n.toFixed(2);
const fmtP = n => `${n.toFixed(1)}%`;
const TT   = { background:'#fff', border:'1px solid #e2e8f0', borderRadius:8, fontSize:11, color:'#0f172a' };

// ── Mock data ────────────────────────────────────────────────────────────────
const MOCK_EVM_HISTORY = [
  { mes:'Ene 26', pv:85000000,  ev:78000000,  ac:82000000,  projectId:'p4' },
  { mes:'Feb 26', pv:130000000, ev:118000000, ac:125000000, projectId:'p4' },
  { mes:'Mar 26', pv:180000000, ev:165000000, ac:172000000, projectId:'p4' },
  { mes:'Abr 26', pv:235000000, ev:215000000, ac:228000000, projectId:'p4' },
  { mes:'May 26', pv:295000000, ev:268000000, ac:287000000, projectId:'p4' },
  { mes:'Jun 26', pv:340000000, ev:312500000, ac:335000000, projectId:'p4' },
  { mes:'Ene 26', pv:50000000,  ev:45000000,  ac:48000000,  projectId:'p4' },
  { mes:'Feb 26', pv:90000000,  ev:82000000,  ac:95000000,  projectId:'p4' },
  { mes:'Mar 26', pv:140000000, ev:125000000, ac:148000000, projectId:'p4' },
  { mes:'Abr 26', pv:200000000, ev:178000000, ac:215000000, projectId:'p4' },
  { mes:'May 26', pv:320000000, ev:290000000, ac:352000000, projectId:'p4' },
  { mes:'Jun 26', pv:480000000, ev:430000000, ac:530000000, projectId:'p4' },
  { mes:'Ene 26', pv:40000000,  ev:38000000,  ac:39000000,  projectId:'p4' },
  { mes:'Feb 26', pv:80000000,  ev:76000000,  ac:79000000,  projectId:'p4' },
  { mes:'Mar 26', pv:130000000, ev:122000000, ac:128000000, projectId:'p4' },
  { mes:'Abr 26', pv:190000000, ev:178000000, ac:187000000, projectId:'p4' },
  { mes:'May 26', pv:255000000, ev:240000000, ac:252000000, projectId:'p4' },
  { mes:'Jun 26', pv:312500000, ev:298000000, ac:310000000, projectId:'p4' },
  { mes:'Ene 26', pv:15000000,  ev:12000000,  ac:18000000,  projectId:'p4' },
  { mes:'Feb 26', pv:28000000,  ev:22000000,  ac:34000000,  projectId:'p4' },
  { mes:'Mar 26', pv:38000000,  ev:30000000,  ac:48000000,  projectId:'p4' },
  { mes:'Abr 26', pv:46000000,  ev:36000000,  ac:58000000,  projectId:'p4' },
  { mes:'May 26', pv:50000000,  ev:42000000,  ac:65000000,  projectId:'p4' },
  { mes:'Jun 26', pv:55000000,  ev:50000000,  ac:72000000,  projectId:'p4' },
];

const MOCK_PARTIDAS = [
  { name:'Estructura',         bac:220000000, ev:180000000, ac:195000000, projectId:'p4' },
  { name:'Instalaciones',      bac:180000000, ev:95000000,  ac:105000000, projectId:'p4' },
  { name:'Acabados',           bac:150000000, ev:25000000,  ac:28000000,  projectId:'p4' },
  { name:'Equipos especiales', bac:120000000, ev:12000000,  ac:14000000,  projectId:'p4' },
  { name:'Gestión',            bac:80000000,  ev:500000,    ac:500000,    projectId:'p4' },
  { name:'Contingencia',       bac:100000000, ev:0,         ac:0,         projectId:'p4' },
  { name:'Arquitectura',       bac:300000000, ev:240000000, ac:275000000, projectId:'p4' },
  { name:'Locales comerciales',bac:250000000, ev:130000000, ac:155000000, projectId:'p4' },
  { name:'Instalaciones',      bac:200000000, ev:70000000,  ac:80000000,  projectId:'p4' },
  { name:'Áreas comunes',      bac:180000000, ev:30000000,  ac:35000000,  projectId:'p4' },
  { name:'Gestión',            bac:120000000, ev:10000000,  ac:15000000,  projectId:'p4' },
  { name:'Contingencia',       bac:150000000, ev:0,         ac:0,         projectId:'p4' },
  { name:'Backend',            bac:180000000, ev:160000000, ac:165000000, projectId:'p4' },
  { name:'Frontend',           bac:140000000, ev:110000000, ac:115000000, projectId:'p4' },
  { name:'Integraciones',      bac:120000000, ev:85000000,  ac:90000000,  projectId:'p4' },
  { name:'QA & Testing',       bac:100000000, ev:40000000,  ac:42000000,  projectId:'p4' },
  { name:'Gestión',            bac:80000000,  ev:3500000,   ac:4000000,   projectId:'p4' },
  { name:'Contingencia',       bac:60000000,  ev:0,         ac:0,         projectId:'p4' },
  { name:'Diseño',             bac:80000000,  ev:45000000,  ac:60000000,  projectId:'p4' },
  { name:'Desarrollo',         bac:150000000, ev:80000000,  ac:110000000, projectId:'p4' },
  { name:'Infraestructura',    bac:90000000,  ev:30000000,  ac:45000000,  projectId:'p4' },
  { name:'Pruebas',            bac:60000000,  ev:10000000,  ac:18000000,  projectId:'p4' },
  { name:'Gestión',            bac:40000000,  ev:5000000,   ac:8000000,   projectId:'p4' },
];

const MOCK_SEMAFORO_PROJECTS = [
  { id:'p4', name:'Torre Residencial Norte', code:'PRY-001', bac:850000000, ev:340000000, ac:295000000 },
  { id:'p4', name:'Centro Comercial Sur',    code:'PRY-002', bac:1200000000,ev:480000000, ac:530000000 },
  { id:'p4', name:'Oficinas Corporativas',   code:'PRY-003', bac:680000000, ev:312500000, ac:335000000 },
  { id:'p4', name:'Parque Industrial Este',  code:'PRY-004', bac:420000000, ev:50000000,  ac:72000000  },
];

// ── EVM calculations ─────────────────────────────────────────────────────────
function calcEVM(series, bac) {
  const last = [...series].reverse().find(p => p.ev !== null && p.ev !== undefined);
  if (!last) return null;
  const pv  = last.pv  || 0;
  const ev  = last.ev  || 0;
  const ac  = last.ac  || 0;
  const spi = pv  ? ev/pv  : 1;
  const cpi = ac  ? ev/ac  : 1;
  const cv  = ev - ac;
  const sv  = ev - pv;
  const eac = cpi ? bac/cpi : bac;
  const etc = eac - ac;
  const vac = bac - eac;
  const tcpi= (bac-ev) / (bac-ac);
  const pctComplete = bac ? ev/bac*100 : 0;
  return { pv, ev, ac, spi, cpi, cv, sv, eac, etc, vac, tcpi, pctComplete };
}

// ── Sub-components ────────────────────────────────────────────────────────────
function KPIBox({ label, value, sub, good, neutral }) {
  const cls = neutral ? 'text-slate-900 dark:text-white'
    : good  ? 'text-emerald-600 dark:text-emerald-400'
    : 'text-red-600 dark:text-red-400';
  return (
    <div className="bg-white dark:bg-surface-800 rounded-2xl p-4 border border-slate-200 dark:border-surface-700 shadow-sm">
      <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-widest mb-1.5">{label}</p>
      <p className={`text-xl font-bold tabular-nums ${cls}`}>{value}</p>
      {sub && <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{sub}</p>}
    </div>
  );
}

function TabButton({ active, onClick, children }) {
  return (
    <button
      onClick={onClick}
      className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors whitespace-nowrap ${
        active
          ? 'bg-primary-600 text-white shadow-sm'
          : 'text-slate-600 dark:text-gray-400 hover:bg-slate-100 dark:hover:bg-surface-700'
      }`}
    >
      {children}
    </button>
  );
}

// ── CPI color helper ──────────────────────────────────────────────────────────
function cpiColor(cpi) {
  if (cpi >= 1)   return { bg:'bg-emerald-50 dark:bg-emerald-900/20', text:'text-emerald-700 dark:text-emerald-400', badge:'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300' };
  if (cpi >= 0.9) return { bg:'bg-amber-50 dark:bg-amber-900/20',   text:'text-amber-700 dark:text-amber-400',   badge:'bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300' };
  return                  { bg:'bg-red-50 dark:bg-red-900/20',       text:'text-red-700 dark:text-red-400',       badge:'bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300' };
}

function semStatus(cpi, spi) {
  if (cpi >= 1 && spi >= 1)    return { label:'En control',  color:'text-emerald-600 dark:text-emerald-400', dot:'bg-emerald-500' };
  if (cpi >= 0.9 || spi >= 0.9)return { label:'En riesgo',   color:'text-amber-600 dark:text-amber-400',   dot:'bg-amber-500' };
  return                               { label:'Crítico',     color:'text-red-600 dark:text-red-400',       dot:'bg-red-500' };
}

// ── Tab 1: Indicadores EVM ────────────────────────────────────────────────────
function TabIndicadores({ evm, bac, chartData }) {
  return (
    <div className="space-y-5">
      {evm && (
        <>
          <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
            <KPIBox label="PV — Valor planeado"    value={fmt(evm.pv)}  sub="a la fecha" neutral/>
            <KPIBox label="EV — Valor ganado"       value={fmt(evm.ev)}  sub={`${evm.pctComplete.toFixed(1)}% completado`} neutral/>
            <KPIBox label="AC — Costo actual"       value={fmt(evm.ac)}  sub="gastado" neutral/>
            <KPIBox label="BAC — Presupuesto total" value={fmt(bac)}     sub="línea base" neutral/>
          </div>
          <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
            <KPIBox label="SPI — Índice de cronograma" value={fmtI(evm.spi)} sub={evm.spi>=1?'Adelantado':'Atrasado'} good={evm.spi>=1}/>
            <KPIBox label="CPI — Índice de costo"      value={fmtI(evm.cpi)} sub={evm.cpi>=1?'Bajo presupuesto':'Sobre presupuesto'} good={evm.cpi>=1}/>
            <KPIBox label="SV — Variación cronograma"  value={fmt(evm.sv)}   sub={evm.sv>=0?'Adelantado':'Atrasado'} good={evm.sv>=0}/>
            <KPIBox label="CV — Variación costo"       value={fmt(evm.cv)}   sub={evm.cv>=0?'Ahorro':'Sobrecosto'} good={evm.cv>=0}/>
          </div>
          <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
            <KPIBox label="EAC — Costo estimado final"  value={fmt(evm.eac)}  sub={`vs BAC ${fmt(bac)}`} good={evm.eac<=bac}/>
            <KPIBox label="ETC — Costo para terminar"   value={fmt(evm.etc)}  sub="estimado restante" neutral/>
            <KPIBox label="VAC — Variación al cierre"   value={fmt(evm.vac)}  sub={evm.vac>=0?'Bajo presupuesto':'Sobrecosto'} good={evm.vac>=0}/>
            <KPIBox label="TCPI — Eficiencia requerida" value={fmtI(evm.tcpi)} sub={evm.tcpi<=1?'Alcanzable':'Difícil de alcanzar'} good={evm.tcpi<=1}/>
          </div>
        </>
      )}

      {/* S-Curve */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
        <p className="text-sm font-semibold text-slate-800 dark:text-white mb-1">Curva S — PV vs EV vs AC</p>
        <p className="text-xs text-slate-400 dark:text-gray-500 mb-4">Valor planeado, ganado y costo real acumulado</p>
        <ResponsiveContainer width="100%" height={280}>
          <LineChart data={chartData} margin={{top:4,right:16,left:0,bottom:0}}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
            <XAxis dataKey="month" tick={{fill:'#94a3b8',fontSize:11}} axisLine={false} tickLine={false}/>
            <YAxis tick={{fill:'#94a3b8',fontSize:10}} axisLine={false} tickLine={false} tickFormatter={v=>fmt(v)}/>
            <Tooltip contentStyle={TT} formatter={v=>v!=null?fmt(v):'—'}/>
            <Legend wrapperStyle={{fontSize:11,color:'#94a3b8'}}/>
            {evm && <ReferenceLine y={bac} stroke="#94a3b8" strokeDasharray="6 3" label={{value:'BAC',fill:'#94a3b8',fontSize:10}}/>}
            {evm && <ReferenceLine y={evm.eac} stroke="#EF4444" strokeDasharray="6 3" label={{value:'EAC',fill:'#EF4444',fontSize:10}}/>}
            <Line type="monotone" dataKey="pv" name="PV (Planeado)" stroke="#94a3b8" strokeWidth={2} strokeDasharray="5 3" dot={false} connectNulls/>
            <Line type="monotone" dataKey="ev" name="EV (Ganado)"   stroke="#10B981" strokeWidth={2.5} dot={{r:3,fill:'#10B981'}} connectNulls={false}/>
            <Line type="monotone" dataKey="ac" name="AC (Real)"     stroke="#EF4444" strokeWidth={2.5} dot={{r:3,fill:'#EF4444'}} connectNulls={false}/>
          </LineChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

// ── Tab 2: Análisis de tendencia ──────────────────────────────────────────────
function TabTendencia({ selectedProjectId }) {
  const history = MOCK_EVM_HISTORY.filter(h => !selectedProjectId || h.projectId === selectedProjectId).map(h => ({
    ...h,
    cpi: h.ac ? +(h.ev / h.ac).toFixed(3) : 1,
    spi: h.pv ? +(h.ev / h.pv).toFixed(3) : 1,
  }));

  function cpiCellCls(v) {
    if (v >= 1)   return 'text-emerald-700 dark:text-emerald-400 font-semibold';
    if (v >= 0.9) return 'text-amber-600 dark:text-amber-400 font-semibold';
    return 'text-red-600 dark:text-red-400 font-semibold';
  }

  return (
    <div className="space-y-5">
      {/* Line chart CPI & SPI */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
        <p className="text-sm font-semibold text-slate-800 dark:text-white mb-1">Evolución de índices CPI y SPI</p>
        <p className="text-xs text-slate-400 dark:text-gray-500 mb-4">Tendencia mensual — línea punteada en 1.0 como referencia</p>
        <ResponsiveContainer width="100%" height={260}>
          <LineChart data={history} margin={{top:4,right:16,left:0,bottom:0}}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
            <XAxis dataKey="mes" tick={{fill:'#94a3b8',fontSize:11}} axisLine={false} tickLine={false}/>
            <YAxis tick={{fill:'#94a3b8',fontSize:10}} axisLine={false} tickLine={false} domain={[0.8, 1.1]} tickCount={7}/>
            <Tooltip contentStyle={TT} formatter={(v,n)=>[fmtI(v), n]}/>
            <Legend wrapperStyle={{fontSize:11,color:'#94a3b8'}}/>
            <ReferenceLine y={1} stroke="#94a3b8" strokeDasharray="6 3" label={{value:'1.0',fill:'#94a3b8',fontSize:10,position:'right'}}/>
            <Line type="monotone" dataKey="cpi" name="CPI" stroke="#2563EB" strokeWidth={2.5} dot={{r:4,fill:'#2563EB'}}/>
            <Line type="monotone" dataKey="spi" name="SPI" stroke="#F97316" strokeWidth={2.5} dot={{r:4,fill:'#F97316'}}/>
          </LineChart>
        </ResponsiveContainer>
      </div>

      {/* Tabla historial */}
      <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-4 border-b border-slate-100 dark:border-surface-700">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Historial mensual EVM</p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100 dark:border-surface-700 bg-slate-50 dark:bg-surface-700/40">
                {['Mes','PV','EV','AC','CPI','SPI'].map(h => (
                  <th key={h} className="px-4 py-2.5 text-left text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
              {history.map(row => (
                <tr key={row.mes} className="hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors">
                  <td className="px-4 py-2.5 text-sm font-medium text-slate-700 dark:text-gray-300">{row.mes}</td>
                  <td className="px-4 py-2.5 text-xs font-mono text-slate-500 dark:text-gray-400 tabular-nums">{fmt(row.pv)}</td>
                  <td className="px-4 py-2.5 text-xs font-mono text-emerald-600 dark:text-emerald-400 tabular-nums">{fmt(row.ev)}</td>
                  <td className="px-4 py-2.5 text-xs font-mono text-slate-500 dark:text-gray-400 tabular-nums">{fmt(row.ac)}</td>
                  <td className={`px-4 py-2.5 text-xs font-mono tabular-nums ${cpiCellCls(row.cpi)}`}>{fmtI(row.cpi)}</td>
                  <td className={`px-4 py-2.5 text-xs font-mono tabular-nums ${cpiCellCls(row.spi)}`}>{fmtI(row.spi)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ── Tab 3: Proyección a completar ─────────────────────────────────────────────
function TabProyeccion({ evm, bac }) {
  if (!evm) return <p className="text-slate-400 dark:text-gray-500 text-sm">Sin datos EVM disponibles.</p>;

  const cpiOpt  = 1.0;
  const cpiExp  = evm.cpi;
  const cpiPes  = 0.85;

  const eacOpt  = bac / cpiOpt;
  const eacExp  = bac / cpiExp;
  const eacPes  = bac / cpiPes;

  const scenarios = [
    { label:'Optimista',  cpi:cpiOpt,  eac:eacOpt,  color:'#10B981' },
    { label:'Esperado',   cpi:cpiExp,  eac:eacExp,  color:'#2563EB' },
    { label:'Pesimista',  cpi:cpiPes,  eac:eacPes,  color:'#EF4444' },
    { label:'BAC (base)', cpi:null,    eac:bac,      color:'#94a3b8' },
  ];

  const barData = scenarios.map(s => ({ name: s.label, EAC: Math.round(s.eac), color: s.color }));

  // Partidas con ETC y EAC usando CPI global
  const partidas = MOCK_PARTIDAS.map(p => {
    const cpiLocal = p.ac ? p.ev / p.ac : 1;
    const etc = cpiLocal ? (p.bac - p.ev) / cpiLocal : (p.bac - p.ev);
    const eacP = p.ac + etc;
    const varP = p.bac - eacP;
    return { ...p, cpiLocal, etc, eacP, varP };
  });

  return (
    <div className="space-y-5">
      {/* EAC scenario cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {scenarios.slice(0,3).map(s => (
          <div key={s.label} className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-widest mb-2">{s.label}</p>
            <p className="text-xs text-slate-400 dark:text-gray-500 mb-1">CPI = {fmtI(s.cpi)}</p>
            <p className="text-2xl font-bold tabular-nums" style={{color: s.color}}>{fmt(s.eac)}</p>
            <p className={`text-xs mt-1 font-medium ${bac - s.eac >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}>
              {bac - s.eac >= 0 ? '▼ ' : '▲ '}{fmt(Math.abs(bac - s.eac))} vs BAC
            </p>
          </div>
        ))}
      </div>

      {/* Bar chart comparativo */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
        <p className="text-sm font-semibold text-slate-800 dark:text-white mb-1">Comparativa EAC por escenario vs BAC</p>
        <p className="text-xs text-slate-400 dark:text-gray-500 mb-4">Valores en millones de dólares</p>
        <ResponsiveContainer width="100%" height={220}>
          <BarChart data={barData} layout="vertical" margin={{top:4,right:24,left:60,bottom:0}}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" horizontal={false}/>
            <XAxis type="number" tick={{fill:'#94a3b8',fontSize:10}} axisLine={false} tickLine={false} tickFormatter={v=>fmt(v)}/>
            <YAxis type="category" dataKey="name" tick={{fill:'#64748b',fontSize:12}} axisLine={false} tickLine={false} width={75}/>
            <Tooltip contentStyle={TT} formatter={v=>[fmt(v),'EAC']}/>
            <Bar dataKey="EAC" radius={[0,6,6,0]} maxBarSize={32}>
              {barData.map((entry, i) => <Cell key={i} fill={entry.color}/>)}
            </Bar>
            <ReferenceLine x={bac} stroke="#94a3b8" strokeDasharray="6 3"/>
          </BarChart>
        </ResponsiveContainer>
      </div>

      {/* Tabla de partidas */}
      <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-4 border-b border-slate-100 dark:border-surface-700">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">ETC / EAC por partida</p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100 dark:border-surface-700 bg-slate-50 dark:bg-surface-700/40">
                {['Partida','BAC','EV','AC','CPI local','ETC','EAC','Variación'].map(h => (
                  <th key={h} className="px-4 py-2.5 text-left text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
              {partidas.map(p => (
                <tr key={p.name} className="hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors">
                  <td className="px-4 py-2.5 text-sm font-medium text-slate-700 dark:text-gray-300 whitespace-nowrap">{p.name}</td>
                  <td className="px-4 py-2.5 text-xs font-mono text-slate-500 dark:text-gray-400 tabular-nums">{fmt(p.bac)}</td>
                  <td className="px-4 py-2.5 text-xs font-mono text-emerald-600 dark:text-emerald-400 tabular-nums">{fmt(p.ev)}</td>
                  <td className="px-4 py-2.5 text-xs font-mono text-slate-500 dark:text-gray-400 tabular-nums">{fmt(p.ac)}</td>
                  <td className="px-4 py-2.5 text-xs font-mono tabular-nums font-semibold text-blue-600 dark:text-blue-400">{p.ac ? fmtI(p.cpiLocal) : '—'}</td>
                  <td className="px-4 py-2.5 text-xs font-mono text-slate-500 dark:text-gray-400 tabular-nums">{fmt(p.etc)}</td>
                  <td className="px-4 py-2.5 text-xs font-mono text-slate-700 dark:text-gray-200 tabular-nums font-semibold">{fmt(p.eacP)}</td>
                  <td className={`px-4 py-2.5 text-xs font-mono tabular-nums font-bold ${p.varP >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}>
                    {p.varP >= 0 ? '+' : ''}{fmt(p.varP)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ── Tab 4: Semáforo de proyecto ───────────────────────────────────────────────
function TabSemaforo({ selectedProjectId }) {
  const visibleProjects = MOCK_SEMAFORO_PROJECTS.filter(p => !selectedProjectId || p.id === selectedProjectId);
  return (
    <div className="space-y-4">
      <p className="text-xs text-slate-400 dark:text-gray-500">
        Verde: CPI ≥ 1 y SPI ≥ 1 · Ámbar: CPI ≥ 0.9 o SPI ≥ 0.9 · Rojo: CPI &lt; 0.9 y SPI &lt; 0.9
      </p>
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-2 gap-5">
        {visibleProjects.map(proj => {
          const cpi = proj.ac ? proj.ev / proj.ac : 1;
          const spi = proj.bac ? proj.ev / proj.bac : 1; // spi rough: ev/bac*pct — aquí usamos ev/(bac*0.5) aprox
          // Para el semáforo usamos CPI y un SPI estimado
          const spiEst = proj.bac ? (proj.ev / proj.bac) / 0.50 : 1; // asume 50% del tiempo transcurrido
          const colors = cpiColor(cpi);
          const status = semStatus(cpi, spiEst);
          const pctEV = proj.bac ? proj.ev / proj.bac * 100 : 0;

          return (
            <div key={proj.id} className={`rounded-2xl p-6 border border-slate-200 dark:border-surface-700 shadow-sm bg-white dark:bg-surface-800`}>
              {/* Header */}
              <div className="flex items-start justify-between mb-4">
                <div>
                  <p className="text-xs font-mono text-slate-400 dark:text-gray-500 mb-0.5">{proj.code}</p>
                  <p className="text-base font-bold text-slate-800 dark:text-white leading-tight">{proj.name}</p>
                </div>
                <span className={`flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full ${status.dot === 'bg-emerald-500' ? 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300' : status.dot === 'bg-amber-500' ? 'bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300' : 'bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300'}`}>
                  <span className={`inline-block w-2 h-2 rounded-full ${status.dot}`}/>
                  {status.label}
                </span>
              </div>

              {/* CPI + SPI grandes */}
              <div className="flex gap-6 mb-5">
                <div>
                  <p className="text-xs text-slate-400 dark:text-gray-500 uppercase tracking-widest mb-1">CPI</p>
                  <p className={`text-4xl font-black tabular-nums ${colors.text}`}>{fmtI(cpi)}</p>
                </div>
                <div>
                  <p className="text-xs text-slate-400 dark:text-gray-500 uppercase tracking-widest mb-1">SPI est.</p>
                  <p className={`text-4xl font-black tabular-nums ${cpiColor(spiEst).text}`}>{fmtI(spiEst)}</p>
                </div>
                <div className="ml-auto text-right">
                  <p className="text-xs text-slate-400 dark:text-gray-500 uppercase tracking-widest mb-1">BAC</p>
                  <p className="text-base font-bold text-slate-700 dark:text-gray-300">{fmt(proj.bac)}</p>
                  <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">EV: {fmt(proj.ev)}</p>
                </div>
              </div>

              {/* Barra de avance EV/BAC */}
              <div>
                <div className="flex justify-between text-xs text-slate-400 dark:text-gray-500 mb-1.5">
                  <span>Avance físico (EV/BAC)</span>
                  <span className="font-semibold text-slate-600 dark:text-gray-300">{fmtP(pctEV)}</span>
                </div>
                <div className="h-3 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full transition-all ${
                      cpi >= 1 ? 'bg-emerald-500' : cpi >= 0.9 ? 'bg-amber-500' : 'bg-red-500'
                    }`}
                    style={{ width: `${Math.min(pctEV, 100)}%` }}
                  />
                </div>
                <div className="flex justify-between text-xs text-slate-400 dark:text-gray-500 mt-1">
                  <span>AC: {fmt(proj.ac)}</span>
                  <span>EAC est.: {fmt(proj.bac / cpi)}</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────
const TABS = [
  { id:'indicadores', label:'Indicadores EVM' },
  { id:'tendencia',   label:'Análisis de tendencia' },
  { id:'proyeccion',  label:'Proyección a completar' },
  { id:'semaforo',    label:'Semáforo de proyecto' },
];

export default function EVMPage() {
  const { selectedProjectId } = useProject();
  const projId   = selectedProjectId || getAllProjects()[0]?.id || 'p4';
  const project  = getProjectById(projId);
  const series   = getEVMForProject(projId);
  const bac      = project.baselineBudget || project.budget || 0;
  const evm      = calcEVM(series, bac);
  const [activeTab, setActiveTab] = useState('indicadores');

  // Build chart data for S-curve tab
  const chartData = series.map((p,i) => {
    const hasActual = p.ev !== null && p.ev !== undefined;
    return {
      ...p,
      month: p.date.substring(5),
    };
  });

  return (
    <div className="space-y-5 pb-6">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">Gestión del Valor Ganado (EVM)</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">Earned Value Management · BAC: {fmt(bac)}</p>
        </div>
        <span className="text-sm bg-white dark:bg-surface-800 border border-slate-200 dark:border-surface-700 rounded-lg px-3 py-1.5 text-slate-700 dark:text-gray-300 font-medium">
          {project?.code}
        </span>
      </div>

      {/* Tab navigation */}
      <div className="flex flex-wrap gap-2 bg-slate-50 dark:bg-surface-800/60 rounded-2xl p-1.5 border border-slate-200 dark:border-surface-700">
        {TABS.map(tab => (
          <TabButton key={tab.id} active={activeTab === tab.id} onClick={() => setActiveTab(tab.id)}>
            {tab.label}
          </TabButton>
        ))}
      </div>

      {/* Tab content */}
      {activeTab === 'indicadores' && <TabIndicadores evm={evm} bac={bac} chartData={chartData}/>}
      {activeTab === 'tendencia'   && <TabTendencia selectedProjectId={selectedProjectId}/>}
      {activeTab === 'proyeccion'  && <TabProyeccion evm={evm} bac={bac}/>}
      {activeTab === 'semaforo'    && <TabSemaforo selectedProjectId={selectedProjectId}/>}
    </div>
  );
}
