import React, { useState, useMemo } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, LineChart, Line, Legend,
} from 'recharts';
import { MOCK_PROJECTS } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';

// ── Mock data ──────────────────────────────────────────────────────────────
const BUDGET_DETAIL = {
  p1: {
    partidas: [
      { name: 'Materiales',      budget: 8000000, spent: 950000  },
      { name: 'Mano de obra',    budget: 4000000, spent: 520000  },
      { name: 'Maquinaria',      budget: 2000000, spent: 280000  },
      { name: 'Subcontratos',    budget: 700000,  spent: 90000   },
      { name: 'Administrativo',  budget: 300000,  spent: 35000   },
    ],
    monthly: [
      { m: 'Ene', plan: 800000,  real: 750000  },
      { m: 'Feb', plan: 1200000, real: 1100000 },
      { m: 'Mar', plan: 1500000, real: 1200000 },
      { m: 'Abr', plan: 1800000, real: 1400000 },
      { m: 'May', plan: 2000000, real: 1875000 },
      { m: 'Jun', plan: 2300000, real: null     },
    ],
  },
  p2: {
    partidas: [
      { name: 'Grabación',       budget: 80000,  spent: 28000 },
      { name: 'Producción',      budget: 60000,  spent: 21000 },
      { name: 'Mezcla & Master', budget: 40000,  spent: 14000 },
      { name: 'Marketing',       budget: 50000,  spent: 17500 },
      { name: 'Distribución',    budget: 20000,  spent: 7000  },
    ],
    monthly: [
      { m: 'Mar', plan: 30000, real: 28000 },
      { m: 'Abr', plan: 55000, real: 52000 },
      { m: 'May', plan: 80000, real: 77000 },
      { m: 'Jun', plan: 87500, real: null  },
    ],
  },
  p3: {
    partidas: [
      { name: 'Licencias',       budget: 150000, spent: 72000  },
      { name: 'Consultoría',     budget: 300000, spent: 144000 },
      { name: 'Desarrollo',      budget: 250000, spent: 120000 },
      { name: 'Infraestructura', budget: 60000,  spent: 28800  },
      { name: 'Capacitación',    budget: 40000,  spent: 19200  },
    ],
    monthly: [
      { m: 'Feb', plan: 60000,  real: 58000  },
      { m: 'Mar', plan: 120000, real: 115000 },
      { m: 'Abr', plan: 200000, real: 192000 },
      { m: 'May', plan: 300000, real: 288000 },
      { m: 'Jun', plan: 384000, real: null   },
    ],
  },
  p4: {
    partidas: [
      { name: 'Desarrollo',      budget: 80000,  spent: 17600 },
      { name: 'Diseño UI/UX',    budget: 15000,  spent: 3300  },
      { name: 'Infraestructura', budget: 10000,  spent: 0     },
      { name: 'QA & Testing',    budget: 10000,  spent: 0     },
      { name: 'Documentación',   budget: 5000,   spent: 0     },
    ],
    monthly: [
      { m: 'Jun', plan: 20000, real: 20900 },
      { m: 'Jul', plan: 35000, real: null  },
      { m: 'Ago', plan: 55000, real: null  },
      { m: 'Sep', plan: 80000, real: null  },
    ],
  },
};

const COST_CENTERS = {
  p1: [
    { cc: 'CC-001', name: 'Dirección de Proyecto', budget: 500000,  spent: 120000, responsible: 'Juan Pérez'    },
    { cc: 'CC-002', name: 'Ingeniería & Diseño',   budget: 4500000, spent: 890000, responsible: 'María García'  },
    { cc: 'CC-003', name: 'Compras & Materiales',  budget: 8000000, spent: 950000, responsible: 'Luis Torres'   },
    { cc: 'CC-004', name: 'Construcción',          budget: 1500000, spent: 280000, responsible: 'Carlos Ruiz'   },
    { cc: 'CC-005', name: 'QHSE',                  budget: 200000,  spent: 35000,  responsible: 'Ana Morales'   },
    { cc: 'CC-006', name: 'Administrativo',        budget: 300000,  spent: 60000,  responsible: 'Pedro Jiménez' },
  ],
  p2: [
    { cc: 'CC-001', name: 'Dirección Creativa',    budget: 20000,  spent: 8000,  responsible: 'Juan Pérez'   },
    { cc: 'CC-002', name: 'Estudio de Grabación',  budget: 80000,  spent: 28000, responsible: 'María García' },
    { cc: 'CC-003', name: 'Post-producción',       budget: 100000, spent: 35000, responsible: 'Luis Torres'  },
    { cc: 'CC-004', name: 'Marketing Digital',     budget: 50000,  spent: 17500, responsible: 'Carlos Ruiz'  },
  ],
  p3: [
    { cc: 'CC-001', name: 'Gestión del Proyecto',  budget: 80000,  spent: 38400, responsible: 'Juan Pérez'    },
    { cc: 'CC-002', name: 'Consultoría ERP',       budget: 300000, spent: 144000, responsible: 'María García' },
    { cc: 'CC-003', name: 'Desarrollo de Software',budget: 250000, spent: 120000, responsible: 'Luis Torres'  },
    { cc: 'CC-004', name: 'Infraestructura TI',    budget: 60000,  spent: 28800, responsible: 'Carlos Ruiz'   },
    { cc: 'CC-005', name: 'Capacitación',          budget: 40000,  spent: 19200, responsible: 'Ana Morales'   },
								  								  ],
  p4: [
    { cc: 'CC-001', name: 'Arquitectura & Diseño', budget: 25000, spent: 5500,  responsible: 'Juan Pérez'   },
    { cc: 'CC-002', name: 'Desarrollo Backend',    budget: 50000, spent: 11000, responsible: 'María García' },
    { cc: 'CC-003', name: 'Desarrollo Frontend',   budget: 30000, spent: 6600,  responsible: 'Luis Torres'  },
    { cc: 'CC-004', name: 'QA & DevOps',           budget: 15000, spent: 0,     responsible: 'Carlos Ruiz'  },
  ],
};

const CHANGE_ORDERS = {
  p1: [
    { id: 'OC-001', desc: 'Cambio en especificaciones de acero estructural', tipo: 'ALCANCE',   impacto: 320000, estado: 'APROBADA',  fecha: '2026-03-15', solicitante: 'Cliente'      },
    { id: 'OC-002', desc: 'Retraso por condiciones climáticas (30 días)',    tipo: 'TIEMPO',    impacto: 120000, estado: 'PENDIENTE', fecha: '2026-04-20', solicitante: 'Contratista'  },
    { id: 'OC-003', desc: 'Adición de sistema de seguridad perimetral',     tipo: 'ALCANCE',   impacto: 180000, estado: 'APROBADA',  fecha: '2026-04-28', solicitante: 'Cliente'      },
    { id: 'OC-004', desc: 'Reclasificación de subcontrato eléctrico',       tipo: 'COSTO',     impacto: -45000, estado: 'APROBADA',  fecha: '2026-05-10', solicitante: 'PM'           },
    { id: 'OC-005', desc: 'Incremento de costos de importación materiales', tipo: 'COSTO',     impacto: 95000,  estado: 'RECHAZADA', fecha: '2026-05-22', solicitante: 'Contratista'  },
  ],
  p2: [
    { id: 'OC-001', desc: 'Sesiones adicionales de mezcla (8 hrs)',         tipo: 'ALCANCE',   impacto: 4000,   estado: 'APROBADA',  fecha: '2026-04-10', solicitante: 'Artista'      },
    { id: 'OC-002', desc: 'Campaña adicional en redes sociales',            tipo: 'ALCANCE',   impacto: 8500,   estado: 'PENDIENTE', fecha: '2026-05-15', solicitante: 'Sello'        },
  ],
  p3: [
    { id: 'OC-001', desc: 'Módulo adicional de gestión documental',         tipo: 'ALCANCE',   impacto: 45000,  estado: 'APROBADA',  fecha: '2026-03-20', solicitante: 'Gerencia'     },
    { id: 'OC-002', desc: 'Integración con sistema legado SAP',             tipo: 'ALCANCE',   impacto: 30000,  estado: 'PENDIENTE', fecha: '2026-04-30', solicitante: 'TI'           },
    { id: 'OC-003', desc: 'Capacitación adicional 2 grupos',                tipo: 'COSTO',     impacto: 12000,  estado: 'APROBADA',  fecha: '2026-05-08', solicitante: 'RRHH'         },
  ],
  p4: [
    { id: 'OC-001', desc: 'Añadir módulo de reportes avanzados',            tipo: 'ALCANCE',   impacto: 18000,  estado: 'PENDIENTE', fecha: '2026-06-10', solicitante: 'Sponsor'      },
  ],
};

// ── Helpers ────────────────────────────────────────────────────────────────
const fmt = n =>
  n >= 1_000_000 ? `$${(n/1_000_000).toFixed(2)}M`
  : n >= 1000    ? `$${(n/1000).toFixed(1)}K`
  : `$${n.toLocaleString()}`;

const fmtSigned = n => (n >= 0 ? '+' : '') + fmt(n);

const TT = { background:'#fff', border:'1px solid #e2e8f0', borderRadius:8, fontSize:12, color:'#0f172a' };

function PctBar({ pct, color }) {
  const c = pct > 100 ? '#EF4444' : pct > 85 ? '#F59E0B' : color;
  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 h-2 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
        <div className="h-full rounded-full transition-all" style={{width:`${Math.min(pct,100)}%`, background:c}}/>
      </div>
      <span className="text-xs font-semibold w-12 text-right tabular-nums" style={{color:c}}>{pct.toFixed(1)}%</span>
    </div>
  );
}

const ESTADO_STYLES = {
  APROBADA:  'bg-emerald-100 dark:bg-emerald-500/15 text-emerald-700 dark:text-emerald-400',
  PENDIENTE: 'bg-amber-100 dark:bg-amber-500/15 text-amber-700 dark:text-amber-400',
  RECHAZADA: 'bg-red-100 dark:bg-red-500/15 text-red-700 dark:text-red-400',
};

const TIPO_STYLES = {
  ALCANCE: 'bg-blue-100 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400',
  COSTO:   'bg-violet-100 dark:bg-violet-500/15 text-violet-700 dark:text-violet-400',
  TIEMPO:  'bg-orange-100 dark:bg-orange-500/15 text-orange-700 dark:text-orange-400',
};

// ── Sub-views ──────────────────────────────────────────────────────────────
function TabPresupuesto({ detail, project, totalBudget, totalSpent, remaining, totalPct }) {
  return (
    <div className="space-y-4">
      {/* Charts */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
        <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-4">Partidas presupuestales</p>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={detail.partidas} margin={{top:4,right:8,left:-10,bottom:0}}>
              <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
              <XAxis dataKey="name" tick={{fill:'#94a3b8',fontSize:10}} axisLine={false} tickLine={false}/>
              <YAxis tick={{fill:'#94a3b8',fontSize:10}} axisLine={false} tickLine={false} tickFormatter={v=>fmt(v)}/>
              <Tooltip contentStyle={TT} formatter={v=>fmt(v)}/>
              <Legend wrapperStyle={{fontSize:11,color:'#94a3b8'}}/>
              <Bar dataKey="budget" name="Presupuesto" fill="#e2e8f0" radius={[4,4,0,0]}/>
              <Bar dataKey="spent"  name="Ejecutado"   fill="#2563EB" radius={[4,4,0,0]}/>
            </BarChart>
          </ResponsiveContainer>
        </div>
        <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-4">Curva S — Plan vs Real (acumulado)</p>
          <ResponsiveContainer width="100%" height={220}>
            <LineChart data={detail.monthly} margin={{top:4,right:8,left:-10,bottom:0}}>
              <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
              <XAxis dataKey="m" 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?fmt(v):'—'}/>
              <Legend wrapperStyle={{fontSize:11,color:'#94a3b8'}}/>
              <Line type="monotone" dataKey="plan" name="Plan" stroke="#94a3b8" strokeWidth={2} strokeDasharray="4 2" dot={false}/>
              <Line type="monotone" dataKey="real" name="Real" stroke="#2563EB" strokeWidth={2} dot={{r:3,fill:'#2563EB'}} connectNulls={false}/>
            </LineChart>
          </ResponsiveContainer>
        </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">
        <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">Detalle por partida — {project?.name}</p>
        </div>
        <table className="w-full">
          <thead>
            <tr className="border-b border-slate-100 dark:border-surface-700">
              {['Partida','Presupuesto','Ejecutado','Disponible','% Ejec.'].map(h=>(
                <th key={h} className="px-5 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">
            {detail.partidas.map(r=>{
              const pct = r.budget ? (r.spent/r.budget*100) : 0;
              const disp = r.budget - r.spent;
              return (
                <tr key={r.name} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                  <td className="px-5 py-3.5 text-sm font-medium text-slate-800 dark:text-gray-200">{r.name}</td>
                  <td className="px-5 py-3.5 text-sm text-slate-600 dark:text-gray-300 tabular-nums font-mono">{fmt(r.budget)}</td>
                  <td className="px-5 py-3.5 text-sm text-blue-600 dark:text-blue-400 tabular-nums font-mono">{fmt(r.spent)}</td>
                  <td className={`px-5 py-3.5 text-sm tabular-nums font-mono ${disp<0?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400'}`}>{fmt(disp)}</td>
                  <td className="px-5 py-3.5 min-w-[140px]"><PctBar pct={pct} color="#2563EB"/></td>
                </tr>
              );
            })}
            <tr className="bg-slate-50 dark:bg-surface-700/30 font-semibold">
              <td className="px-5 py-3 text-sm text-slate-900 dark:text-white">Total</td>
              <td className="px-5 py-3 text-sm text-slate-900 dark:text-white tabular-nums font-mono">{fmt(totalBudget)}</td>
              <td className="px-5 py-3 text-sm text-blue-600 dark:text-blue-400 tabular-nums font-mono">{fmt(totalSpent)}</td>
              <td className={`px-5 py-3 text-sm tabular-nums font-mono ${remaining<0?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400'}`}>{fmt(remaining)}</td>
              <td className="px-5 py-3 min-w-[140px]"><PctBar pct={totalPct} color="#2563EB"/></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

function TabCentroCostos({ selected }) {
  const centers = COST_CENTERS[selected] || [];
  const totalBudget = centers.reduce((s,c)=>s+c.budget,0);
  const totalSpent  = centers.reduce((s,c)=>s+c.spent,0);

  const chartData = centers.map(c=>({ name: c.cc, Presupuesto: c.budget, Ejecutado: c.spent }));

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-3 gap-3">
        {[
          { label: 'Centros activos',    value: centers.length,           color: 'text-slate-900 dark:text-white'                    },
          { label: 'Presupuesto total',  value: fmt(totalBudget),          color: 'text-slate-900 dark:text-white'                    },
          { label: '% Ejecución global', value: `${totalBudget ? (totalSpent/totalBudget*100).toFixed(1) : 0}%`,
            color: (totalSpent/totalBudget*100) > 80 ? 'text-red-600 dark:text-red-400' : 'text-emerald-600 dark:text-emerald-400'   },
        ].map(({label,value,color})=>(
          <div key={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">{label}</p>
            <p className={`text-2xl font-bold tabular-nums ${color}`}>{value}</p>
          </div>
        ))}
      </div>

      <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-4">Ejecución por Centro de Costo</p>
        <ResponsiveContainer width="100%" height={200}>
          <BarChart data={chartData} margin={{top:4,right:8,left:-10,bottom:0}}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
            <XAxis dataKey="name" tick={{fill:'#94a3b8',fontSize:10}} axisLine={false} tickLine={false}/>
            <YAxis tick={{fill:'#94a3b8',fontSize:10}} axisLine={false} tickLine={false} tickFormatter={v=>fmt(v)}/>
            <Tooltip contentStyle={TT} formatter={v=>fmt(v)}/>
            <Legend wrapperStyle={{fontSize:11,color:'#94a3b8'}}/>
            <Bar dataKey="Presupuesto" fill="#e2e8f0" radius={[4,4,0,0]}/>
            <Bar dataKey="Ejecutado"   fill="#7C3AED" radius={[4,4,0,0]}/>
          </BarChart>
        </ResponsiveContainer>
      </div>

      <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 flex items-center justify-between">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Centros de Costo</p>
          <span className="text-xs text-slate-400 dark:text-gray-500">{centers.length} centros</span>
        </div>
        <table className="w-full">
          <thead>
            <tr className="border-b border-slate-100 dark:border-surface-700">
              {['Código','Centro de Costo','Responsable','Presupuesto','Ejecutado','Varianza','% Ejec.'].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">
            {centers.map(c=>{
              const pct      = c.budget ? (c.spent/c.budget*100) : 0;
              const varianza = c.budget - c.spent;
              return (
                <tr key={c.cc} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                  <td className="px-4 py-3.5">
                    <span className="text-xs font-mono bg-violet-100 dark:bg-violet-500/15 text-violet-700 dark:text-violet-400 px-2 py-0.5 rounded-md">{c.cc}</span>
                  </td>
                  <td className="px-4 py-3.5 text-sm font-medium text-slate-800 dark:text-gray-200">{c.name}</td>
                  <td className="px-4 py-3.5 text-sm text-slate-500 dark:text-gray-400">{c.responsible}</td>
                  <td className="px-4 py-3.5 text-sm tabular-nums font-mono text-slate-600 dark:text-gray-300">{fmt(c.budget)}</td>
                  <td className="px-4 py-3.5 text-sm tabular-nums font-mono text-violet-600 dark:text-violet-400">{fmt(c.spent)}</td>
                  <td className={`px-4 py-3.5 text-sm tabular-nums font-mono ${varianza<0?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400'}`}>{fmt(varianza)}</td>
                  <td className="px-4 py-3.5 min-w-[130px]"><PctBar pct={pct} color="#7C3AED"/></td>
                </tr>
              );
            })}
            <tr className="bg-slate-50 dark:bg-surface-700/30 font-semibold">
              <td className="px-4 py-3 text-sm text-slate-900 dark:text-white" colSpan={3}>Total</td>
              <td className="px-4 py-3 text-sm tabular-nums font-mono text-slate-900 dark:text-white">{fmt(totalBudget)}</td>
              <td className="px-4 py-3 text-sm tabular-nums font-mono text-violet-600 dark:text-violet-400">{fmt(totalSpent)}</td>
              <td className={`px-4 py-3 text-sm tabular-nums font-mono ${(totalBudget-totalSpent)<0?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400'}`}>{fmt(totalBudget-totalSpent)}</td>
              <td className="px-4 py-3 min-w-[130px]"><PctBar pct={totalBudget?(totalSpent/totalBudget*100):0} color="#7C3AED"/></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

function TabCambios({ selected, totalBudget }) {
  const [filter, setFilter] = useState('TODOS');
  const orders = CHANGE_ORDERS[selected] || [];
  const filtered = filter === 'TODOS' ? orders : orders.filter(o=>o.estado===filter);

  const aprobadas  = orders.filter(o=>o.estado==='APROBADA');
  const pendientes = orders.filter(o=>o.estado==='PENDIENTE');
  const impactoNeto = aprobadas.reduce((s,o)=>s+o.impacto,0);
  const impactoPend = pendientes.reduce((s,o)=>s+o.impacto,0);

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
        {[
          { label: 'Total OC',           value: orders.length,          color: 'text-slate-900 dark:text-white'         },
          { label: 'Aprobadas',          value: aprobadas.length,       color: 'text-emerald-600 dark:text-emerald-400' },
          { label: 'Pendientes',         value: pendientes.length,      color: 'text-amber-600 dark:text-amber-400'     },
          { label: 'Impacto aprobado',   value: fmtSigned(impactoNeto), color: impactoNeto>0?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400' },
        ].map(({label,value,color})=>(
          <div key={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">{label}</p>
            <p className={`text-2xl font-bold tabular-nums ${color}`}>{value}</p>
          </div>
        ))}
      </div>

      {impactoPend !== 0 && (
        <div className="flex items-start gap-3 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/30 rounded-xl px-4 py-3">
          <svg className="w-4 h-4 text-amber-500 mt-0.5 flex-shrink-0" 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-semibold text-amber-800 dark:text-amber-300">Órdenes pendientes de aprobación</p>
            <p className="text-xs text-amber-700 dark:text-amber-400 mt-0.5">
              {pendientes.length} OC pendiente{pendientes.length!==1?'s':''} con impacto potencial de <strong>{fmtSigned(impactoPend)}</strong> sobre el presupuesto base.
            </p>
          </div>
        </div>
      )}

      <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 flex items-center justify-between gap-3">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Registro de Órdenes de Cambio</p>
          <div className="flex gap-1.5">
            {['TODOS','PENDIENTE','APROBADA','RECHAZADA'].map(f=>(
              <button key={f} onClick={()=>setFilter(f)}
                className={`px-3 py-1 rounded-lg text-xs font-medium transition-colors cursor-pointer ${filter===f?'bg-blue-600 text-white':'text-slate-500 dark:text-gray-400 hover:bg-slate-100 dark:hover:bg-surface-700'}`}>
                {f}
              </button>
            ))}
          </div>
        </div>
        <table className="w-full">
          <thead>
            <tr className="border-b border-slate-100 dark:border-surface-700">
              {['ID','Descripción','Tipo','Solicitante','Fecha','Impacto','Estado'].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">
            {filtered.length === 0 && (
              <tr><td colSpan={7} className="px-5 py-8 text-center text-sm text-slate-400 dark:text-gray-500">Sin órdenes de cambio para este filtro.</td></tr>
            )}
            {filtered.map(o=>(
              <tr key={o.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                <td className="px-4 py-3.5">
                  <span className="text-xs font-mono font-semibold text-slate-700 dark:text-gray-300">{o.id}</span>
                </td>
                <td className="px-4 py-3.5 text-sm text-slate-700 dark:text-gray-300 max-w-xs">{o.desc}</td>
                <td className="px-4 py-3.5">
                  <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${TIPO_STYLES[o.tipo]||''}`}>{o.tipo}</span>
                </td>
                <td className="px-4 py-3.5 text-sm text-slate-500 dark:text-gray-400">{o.solicitante}</td>
                <td className="px-4 py-3.5 text-sm text-slate-500 dark:text-gray-400 font-mono">{o.fecha}</td>
                <td className={`px-4 py-3.5 text-sm tabular-nums font-mono font-semibold ${o.impacto>0?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400'}`}>
                  {fmtSigned(o.impacto)}
                </td>
                <td className="px-4 py-3.5">
                  <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${ESTADO_STYLES[o.estado]||''}`}>{o.estado}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function TabAlertas({ selected, detail }) {
  const alerts = useMemo(()=>{
    const list = [];
    const orders = CHANGE_ORDERS[selected] || [];
    const centers = COST_CENTERS[selected] || [];

    // Partidas near/over limit
    detail.partidas.forEach(p=>{
      const pct = p.budget ? p.spent/p.budget*100 : 0;
      if (pct >= 100) list.push({ nivel:'CRÍTICO', desc:`Partida "${p.name}" ha superado el presupuesto (${pct.toFixed(1)}%)`, tipo:'SOBREEJEC.' });
      else if (pct >= 85) list.push({ nivel:'ADVERTENCIA', desc:`Partida "${p.name}" alcanzó el ${pct.toFixed(1)}% de ejecución`, tipo:'SOBREEJEC.' });
    });

    // Centers near limit
    centers.forEach(c=>{
      const pct = c.budget ? c.spent/c.budget*100 : 0;
      if (pct >= 90) list.push({ nivel: pct>=100?'CRÍTICO':'ADVERTENCIA', desc:`Centro ${c.cc} "${c.name}" al ${pct.toFixed(1)}% de ejecución`, tipo:'CENTRO' });
    });

    // Pending OC
    const pending = orders.filter(o=>o.estado==='PENDIENTE');
    if (pending.length > 0) {
      const total = pending.reduce((s,o)=>s+o.impacto,0);
      list.push({ nivel:'INFORMACIÓN', desc:`${pending.length} Orden${pending.length!==1?'es':''} de Cambio pendiente${pending.length!==1?'s':''} de aprobación (impacto ${fmtSigned(total)})`, tipo:'OC' });
    }

    return list;
  }, [selected, detail]);

  const niveles = { CRÍTICO:'bg-red-100 dark:bg-red-500/15 text-red-700 dark:text-red-400', ADVERTENCIA:'bg-amber-100 dark:bg-amber-500/15 text-amber-700 dark:text-amber-400', INFORMACIÓN:'bg-blue-100 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400' };
  const icons = {
    CRÍTICO: <svg className="w-4 h-4 text-red-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>,
    ADVERTENCIA: <svg className="w-4 h-4 text-amber-500 flex-shrink-0" 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>,
    INFORMACIÓN: <svg className="w-4 h-4 text-blue-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10"/><path strokeLinecap="round" strokeLinejoin="round" d="M12 16v-4m0-4h.01"/></svg>,
  };

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-3 gap-3">
        {(['CRÍTICO','ADVERTENCIA','INFORMACIÓN']).map(n=>{
          const count = alerts.filter(a=>a.nivel===n).length;
          return (
            <div key={n} className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
              <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${niveles[n]}`}>{n}</span>
              <p className="text-3xl font-bold tabular-nums mt-3 text-slate-900 dark:text-white">{count}</p>
            </div>
          );
        })}
      </div>

      <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">Panel de Alertas Financieras</p>
        </div>
        {alerts.length === 0 ? (
          <div className="px-5 py-12 text-center">
            <svg className="w-10 h-10 text-emerald-400 mx-auto mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            <p className="text-sm font-semibold text-slate-700 dark:text-gray-300">Sin alertas activas</p>
            <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">El presupuesto se encuentra dentro de los parámetros normales.</p>
          </div>
        ) : (
          <div className="divide-y divide-slate-50 dark:divide-surface-700">
            {alerts.map((a,i)=>(
              <div key={i} className="flex items-start gap-3 px-5 py-4 hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                {icons[a.nivel]}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${niveles[a.nivel]}`}>{a.nivel}</span>
                    <span className="text-xs text-slate-400 dark:text-gray-500 bg-slate-100 dark:bg-surface-700 px-2 py-0.5 rounded-full">{a.tipo}</span>
                  </div>
                  <p className="text-sm text-slate-700 dark:text-gray-300 mt-1.5">{a.desc}</p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Main ───────────────────────────────────────────────────────────────────
export default function BudgetPage() {
  const { selectedProjectId } = useProject();
  const selected = selectedProjectId || MOCK_PROJECTS[0]?.id || 'p4';
  const project  = MOCK_PROJECTS.find(p=>p.id===selected);
  const detail   = BUDGET_DETAIL[selected] || BUDGET_DETAIL.p4;

  const totalBudget = detail.partidas.reduce((s,r)=>s+r.budget,0);
  const totalSpent  = detail.partidas.reduce((s,r)=>s+r.spent,0);
  const totalPct    = totalBudget ? totalSpent/totalBudget*100 : 0;
  const remaining   = totalBudget - totalSpent;

  const [tab, setTab] = useState('presupuesto');

  const TABS = [
    { id:'presupuesto', label:'Presupuesto' },
    { id:'centros',     label:'Centro de Costos' },
    { id:'cambios',     label:'Órdenes de Cambio' },
    { id:'alertas',     label:'Alertas' },
  ];

  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">Presupuesto</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">Control de ejecución presupuestal por proyecto</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-2 text-slate-700 dark:text-gray-300 shadow-sm font-medium">
          {project?.code}
        </span>
      </div>

      {/* Summary KPIs */}
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
        {[
          { label:'Presupuesto total', value:fmt(totalBudget), color:'text-slate-900 dark:text-white' },
          { label:'Ejecutado',         value:fmt(totalSpent),  color:'text-blue-600 dark:text-blue-400' },
          { label:'Disponible',        value:fmt(remaining),   color: remaining<0?'text-red-600 dark:text-red-400':'text-emerald-600 dark:text-emerald-400' },
          { label:'% Ejecución',       value:`${totalPct.toFixed(1)}%`, color: totalPct>85?'text-red-600 dark:text-red-400':totalPct>60?'text-amber-600 dark:text-amber-400':'text-emerald-600 dark:text-emerald-400' },
        ].map(({label,value,color})=>(
          <div key={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">{label}</p>
            <p className={`text-2xl font-bold tabular-nums ${color}`}>{value}</p>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-slate-100 dark:bg-surface-800 p-1 rounded-xl w-fit">
        {TABS.map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)}
            className={`px-4 py-1.5 rounded-lg text-sm font-medium transition-all cursor-pointer ${tab===t.id?'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-300'}`}>
            {t.label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {tab === 'presupuesto' && <TabPresupuesto detail={detail} project={project} totalBudget={totalBudget} totalSpent={totalSpent} remaining={remaining} totalPct={totalPct}/>}
      {tab === 'centros'     && <TabCentroCostos selected={selected}/>}
      {tab === 'cambios'     && <TabCambios selected={selected} totalBudget={totalBudget}/>}
      {tab === 'alertas'     && <TabAlertas selected={selected} detail={detail}/>}
    </div>
  );
}
