import React, { useState, useMemo, useCallback, useRef } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
  PieChart, Pie, Cell, ResponsiveContainer, RadarChart, Radar,
  PolarGrid, PolarAngleAxis, PolarRadiusAxis, LineChart, Line, ReferenceLine,
} from 'recharts';
import { MOCK_PROJECTS, MOCK_TASKS, MOCK_EVM } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';

const COLORS = ['#2563EB','#10B981','#F59E0B','#EF4444','#8B5CF6','#EC4899'];
const TT = { background:'#fff', border:'1px solid #e2e8f0', borderRadius:8, fontSize:12, color:'#0f172a' };
const fmt = n => n >= 1_000_000 ? `$${(n/1_000_000).toFixed(1)}M` : n >= 1000 ? `$${(n/1000).toFixed(0)}K` : `$${Math.round(n)}`;

const STATUS_LABELS = {
  PENDIENTE:'Pendiente', EN_PROCESO:'En proceso',
  BLOQUEADA:'Bloqueada', EN_VERIFICACION:'En verificación', COMPLETADA:'Completada',
};
const STATUS_COLORS = {
  PENDIENTE:'#94a3b8', EN_PROCESO:'#2563EB', BLOQUEADA:'#EF4444',
  EN_VERIFICACION:'#F59E0B', COMPLETADA:'#10B981',
};

const TABS_PORTFOLIO = ['Resumen ejecutivo','Tareas','Presupuesto','Salud del portafolio'];
const TABS_PROJECT   = ['Resumen','Tareas','Cronograma','Financiero','Equipo'];

// ── Mock EVM data per project (CPI, SPI, etc.) ────────────────────────────────
const MOCK_PROJECT_METRICS = {
  p1: { cpi:0.94, spi:0.88, spent:1_850_000, variance:-150_000, schedVariance:-12, qualityScore:87, activeRisks:4, nps:62 },
  p2: { cpi:1.05, spi:1.02, spent:320_000,   variance:30_000,    schedVariance:3,  qualityScore:93, activeRisks:1, nps:78 },
  p3: { cpi:0.82, spi:0.76, spent:580_000,   variance:-120_000,  schedVariance:-21,qualityScore:71, activeRisks:7, nps:41 },
  p4: { cpi:0.97, spi:0.99, spent:195_000,   variance:-5_000,    schedVariance:-1, qualityScore:90, activeRisks:2, nps:70 },
};

// ── Helpers ───────────────────────────────────────────────────────────────────
function KPI({ label, value, sub, color = 'text-slate-900 dark:text-white' }) {
  return (
    <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-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>
      {sub && <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">{sub}</p>}
    </div>
  );
}

function SectionTitle({ children }) {
  return <p className="text-sm font-semibold text-slate-800 dark:text-white mb-4">{children}</p>;
}

// Star icon
function StarIcon({ filled }) {
  return (
    <svg className={`w-4 h-4 transition-colors ${filled ? 'text-amber-400 fill-amber-400' : 'text-slate-300 dark:text-slate-600 fill-none'}`}
      viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
    </svg>
  );
}

// ── Comparativo de Proyectos ──────────────────────────────────────────────────
function ComparativoProyectos() {
  const metrics = useMemo(() => MOCK_PROJECTS.map(p => {
    const m = MOCK_PROJECT_METRICS[p.id] || {};
    return {
      id: p.id,
      name: p.name,
      code: p.code,
      progress: p.progressPct,
      cpi: m.cpi,
      spi: m.spi,
      budget: p.budget || 0,
      spent: m.spent || 0,
      variance: m.variance || 0,
      schedVariance: m.schedVariance || 0,
      qualityScore: m.qualityScore || 0,
      activeRisks: m.activeRisks || 0,
      nps: m.nps || 0,
    };
  }), []);

  function cellColor(metric, value) {
    const thresholds = {
      progress:     { green: v => v >= 70,  amber: v => v >= 40 },
      cpi:          { green: v => v >= 0.95, amber: v => v >= 0.85 },
      spi:          { green: v => v >= 0.95, amber: v => v >= 0.80 },
      variance:     { green: v => v >= 0,    amber: v => v >= -50_000 },
      schedVariance:{ green: v => v >= 0,    amber: v => v >= -7 },
      qualityScore: { green: v => v >= 85,   amber: v => v >= 70 },
      activeRisks:  { green: v => v <= 2,    amber: v => v <= 5 },
      nps:          { green: v => v >= 65,   amber: v => v >= 45 },
    };
    const t = thresholds[metric];
    if (!t) return '';
    if (t.green(value)) return 'bg-emerald-50 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400';
    if (t.amber(value)) return 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400';
    return 'bg-red-50 dark:bg-red-500/10 text-red-700 dark:text-red-400';
  }

  function exportCSV() {
    const rows = [
      ['Métrica', ...metrics.map(m => m.code)],
      ['% Avance', ...metrics.map(m => `${m.progress}%`)],
      ['CPI', ...metrics.map(m => m.cpi)],
      ['SPI', ...metrics.map(m => m.spi)],
      ['Presupuesto', ...metrics.map(m => fmt(m.budget))],
      ['Gastado', ...metrics.map(m => fmt(m.spent))],
      ['Varianza $', ...metrics.map(m => fmt(m.variance))],
      ['Varianza días', ...metrics.map(m => `${m.schedVariance}d`)],
      ['Calidad', ...metrics.map(m => `${m.qualityScore}/100`)],
      ['Riesgos activos', ...metrics.map(m => m.activeRisks)],
      ['NPS', ...metrics.map(m => m.nps)],
    ];
    const csv = rows.map(r => r.join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'comparativo-proyectos.csv'; a.click();
    URL.revokeObjectURL(url);
  }

  const rows = [
    { key: 'progress',      label: '% Avance',        fmt: v => `${v}%` },
    { key: 'cpi',           label: 'CPI',              fmt: v => v?.toFixed(2) },
    { key: 'spi',           label: 'SPI',              fmt: v => v?.toFixed(2) },
    { key: 'budget',        label: 'Presupuesto',      fmt: v => fmt(v) },
    { key: 'spent',         label: 'Gastado',          fmt: v => fmt(v) },
    { key: 'variance',      label: 'Varianza ($)',     fmt: v => (v>=0?'+':'')+fmt(v) },
    { key: 'schedVariance', label: 'Varianza (días)',  fmt: v => (v>=0?'+':'')+v+'d' },
    { key: 'qualityScore',  label: 'Calidad',          fmt: v => `${v}/100` },
    { key: 'activeRisks',   label: 'Riesgos activos', fmt: v => v },
    { key: 'nps',           label: 'NPS',              fmt: v => v },
  ];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Comparativo de Proyectos</p>
          <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">Métricas clave lado a lado para todos los proyectos del portafolio</p>
        </div>
        <button onClick={exportCSV}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white transition cursor-pointer shadow-sm">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
          Exportar comparativo
        </button>
      </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="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/30">
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider w-40">Métrica</th>
                {metrics.map(m => (
                  <th key={m.id} className="px-4 py-3 text-center text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider min-w-[130px]">
                    <p className="text-slate-800 dark:text-white font-bold normal-case text-sm truncate max-w-[160px]">{m.name.split(' ').slice(0,3).join(' ')}</p>
                    <p className="font-mono text-slate-400 dark:text-gray-500 text-xs normal-case mt-0.5">{m.code}</p>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
              {rows.map(row => (
                <tr key={row.key} className="hover:bg-slate-50/50 dark:hover:bg-surface-700/20 transition-colors">
                  <td className="px-4 py-3 text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">{row.label}</td>
                  {metrics.map(m => {
                    const val = m[row.key];
                    const cls = cellColor(row.key, val);
                    return (
                      <td key={m.id} className="px-4 py-3 text-center">
                        <span className={`inline-block px-2.5 py-1 rounded-lg text-sm font-semibold tabular-nums ${cls}`}>
                          {row.fmt(val)}
                        </span>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="px-4 py-3 border-t border-slate-100 dark:border-surface-700 flex gap-4 text-xs text-slate-500 dark:text-slate-400">
          <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-sm bg-emerald-100 dark:bg-emerald-500/20 inline-block"/><span>Bueno</span></span>
          <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-sm bg-amber-100 dark:bg-amber-500/20 inline-block"/><span>Atención</span></span>
          <span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-sm bg-red-100 dark:bg-red-500/20 inline-block"/><span>Crítico</span></span>
        </div>
      </div>
    </div>
  );
}

// ── Resumen Ejecutivo Semanal ─────────────────────────────────────────────────
function ResumenEjecutivoSemanal() {
  const allTasks = useMemo(() =>
    MOCK_PROJECTS.flatMap(p => (MOCK_TASKS[p.id] || []).map(t => ({ ...t, projectId: p.id }))),
  []);
  const activeProjects = MOCK_PROJECTS.filter(p => p.status === 'ACTIVO').length;
  const avgCPI = Object.values(MOCK_PROJECT_METRICS).reduce((s, m) => s + m.cpi, 0) / Object.keys(MOCK_PROJECT_METRICS).length;
  const blocked = allTasks.filter(t => t.status === 'BLOQUEADA').length;
  const completedPct = Math.round(allTasks.filter(t => t.status === 'COMPLETADA').length / allTasks.length * 100);

  const highlights = [
    `El proyecto "${MOCK_PROJECTS[1].name}" alcanzó un CPI de 1.05 con entrega adelantada 3 días al cronograma.`,
    `El equipo completó el ${completedPct}% de tareas globales, superando la meta semanal del 65%.`,
    `La puntuación de calidad promedio del portafolio se mantiene en 85/100, por encima del benchmark sectorial.`,
  ];

  const concerns = [
    `"${MOCK_PROJECTS[2].name}" presenta SPI 0.76 y ${blocked > 0 ? blocked : 7} tareas bloqueadas. Riesgo alto de retraso en hito de julio.`,
    `El CPI promedio del portafolio es ${avgCPI.toFixed(2)}, indicando desviación de costos que requiere revisión del presupuesto.`,
  ];

  const actions = [
    { priority: 'Alta',  text: `Convocar reunión de emergencia para "${MOCK_PROJECTS[2].name}" y desbloquear tareas críticas antes del viernes.`, color: 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400' },
    { priority: 'Media', text: 'Revisar estimaciones de costo con el equipo financiero y actualizar forecast Q3.', color: 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400' },
    { priority: 'Baja',  text: 'Documentar lecciones aprendidas del sprint de "AR-ProjectManagement Horizontes" para replicar buenas prácticas.', color: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400' },
  ];

  return (
    <div className="space-y-4">
      {/* AI-styled narrative */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
        <div className="flex items-center gap-2 mb-4">
          <div className="w-6 h-6 rounded-lg bg-blue-600 flex items-center justify-center flex-shrink-0">
            <svg className="w-3.5 h-3.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>
          </div>
          <div>
            <p className="text-sm font-semibold text-slate-800 dark:text-white">Narrativa ejecutiva — semana del 23 al 27 de junio 2026</p>
            <p className="text-xs text-slate-400 dark:text-gray-500">Generado automáticamente por AR Analytics</p>
          </div>
        </div>
        <p className="text-sm text-slate-600 dark:text-gray-300 leading-relaxed">
          Esta semana el portafolio presenta <strong className="text-slate-800 dark:text-white">{activeProjects} proyectos activos</strong> con un CPI promedio de <strong className={`${avgCPI >= 0.95 ? 'text-emerald-600 dark:text-emerald-400' : avgCPI >= 0.85 ? 'text-amber-600 dark:text-amber-400' : 'text-red-600 dark:text-red-400'}`}>{avgCPI.toFixed(2)}</strong>, lo que indica una leve desviación respecto al costo planificado. El 40% de los proyectos operan dentro de parámetros saludables, mientras que la implementación ERP requiere intervención inmediata. El valor ganado acumulado del portafolio asciende a <strong className="text-slate-800 dark:text-white">$2.1M</strong>, frente a un costo real de <strong className="text-slate-800 dark:text-white">$2.95M</strong>, generando una varianza negativa de $850K que deberá recuperarse en el trimestre.
        </p>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
        {/* Highlights */}
        <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-3">Puntos positivos de la semana</p>
          <ul className="space-y-2.5">
            {highlights.map((h, i) => (
              <li key={i} className="flex items-start gap-2.5 text-sm text-slate-600 dark:text-gray-300">
                <span className="w-5 h-5 rounded-full bg-emerald-100 dark:bg-emerald-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                  <svg className="w-3 h-3 text-emerald-600 dark:text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>
                </span>
                {h}
              </li>
            ))}
          </ul>
        </div>

        {/* Concerns */}
        <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-3">Alertas y preocupaciones</p>
          <ul className="space-y-2.5">
            {concerns.map((c, i) => (
              <li key={i} className="flex items-start gap-2.5 text-sm text-slate-600 dark:text-gray-300">
                <span className="w-5 h-5 rounded-full bg-red-100 dark:bg-red-500/20 flex items-center justify-center flex-shrink-0 mt-0.5">
                  <svg className="w-3 h-3 text-red-600 dark:text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01"/><path strokeLinecap="round" strokeLinejoin="round" d="M10.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>
                </span>
                {c}
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* Recommended actions */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Acciones recomendadas</p>
          <a href="/exports" className="flex items-center gap-1.5 text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline">
            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"/></svg>
            Generar PDF
          </a>
        </div>
        <div className="space-y-3">
          {actions.map((a, i) => (
            <div key={i} className="flex items-start gap-3 p-3 rounded-xl bg-slate-50 dark:bg-surface-700/40">
              <span className={`text-xs font-semibold px-2 py-0.5 rounded-full flex-shrink-0 mt-0.5 ${a.color}`}>{a.priority}</span>
              <p className="text-sm text-slate-600 dark:text-gray-300">{a.text}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Enhanced Export Panel ─────────────────────────────────────────────────────
function ExportPanel({ printTitle }) {
  const [format, setFormat] = useState('PDF');
  const [scheduled, setScheduled] = useState(false);
  const [recipients, setRecipients] = useState([]);
  const [inputVal, setInputVal] = useState('');
  const [showPreview, setShowPreview] = useState(false);

  function addRecipient(e) {
    if ((e.key === 'Enter' || e.key === ',') && inputVal.trim()) {
      e.preventDefault();
      const email = inputVal.trim().replace(/,$/, '');
      if (email && !recipients.includes(email)) setRecipients(r => [...r, email]);
      setInputVal('');
    }
  }

  function removeRecipient(email) {
    setRecipients(r => r.filter(x => x !== email));
  }

  function handleExport() {
    if (format === 'PDF') exportPDF(printTitle);
    else {
      // Mock for Excel/PPT
      const ext = format === 'Excel' ? 'xlsx' : 'pptx';
      alert(`[Mock] Descarga simulada: reporte.${ext}`);
    }
  }

  return (
    <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm space-y-5">
      <p className="text-sm font-semibold text-slate-800 dark:text-white">Exportar reporte</p>

      {/* Format selector */}
      <div>
        <p className="text-xs font-medium text-slate-500 dark:text-slate-400 mb-2 uppercase tracking-wide">Formato</p>
        <div className="flex gap-2">
          {['PDF','Excel','PowerPoint'].map(f => (
            <button key={f} onClick={() => setFormat(f)}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium transition cursor-pointer border ${
                format === f
                  ? 'bg-blue-600 text-white border-blue-600'
                  : 'bg-white dark:bg-surface-700 text-slate-600 dark:text-gray-300 border-slate-200 dark:border-surface-600 hover:border-blue-400'
              }`}>
              {f}
            </button>
          ))}
        </div>
      </div>

      {/* Schedule toggle */}
      <div className="flex items-center justify-between py-2 border-t border-slate-100 dark:border-surface-700">
        <div>
          <p className="text-sm font-medium text-slate-700 dark:text-gray-200">Envío automático semanal</p>
          <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">Todos los lunes a las 8:00 AM</p>
        </div>
        <button onClick={() => setScheduled(s => !s)}
          className={`relative w-10 h-6 rounded-full transition-colors cursor-pointer focus:outline-none ${scheduled ? 'bg-blue-600' : 'bg-slate-200 dark:bg-surface-600'}`}>
          <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white shadow transition-transform ${scheduled ? 'translate-x-4' : ''}`}/>
        </button>
      </div>

      {/* Recipients chip input */}
      <div>
        <p className="text-xs font-medium text-slate-500 dark:text-slate-400 mb-2 uppercase tracking-wide">Destinatarios</p>
        <div className="min-h-[42px] flex flex-wrap gap-1.5 p-2 border border-slate-200 dark:border-surface-600 rounded-xl bg-slate-50 dark:bg-surface-700/40 focus-within:ring-2 focus-within:ring-blue-500/30 focus-within:border-blue-400">
          {recipients.map(email => (
            <span key={email} className="flex items-center gap-1 bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-300 px-2 py-0.5 rounded-full text-xs font-medium">
              {email}
              <button onClick={() => removeRecipient(email)} className="hover:text-blue-900 cursor-pointer ml-0.5">
                <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
              </button>
            </span>
          ))}
          <input
            type="email"
            value={inputVal}
            onChange={e => setInputVal(e.target.value)}
            onKeyDown={addRecipient}
            placeholder={recipients.length === 0 ? 'email@empresa.com, Enter para agregar' : ''}
            className="flex-1 min-w-[140px] bg-transparent outline-none text-sm text-slate-700 dark:text-gray-200 placeholder:text-slate-300 dark:placeholder:text-gray-600"
          />
        </div>
        <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">Presiona Enter o coma para agregar</p>
      </div>

      {/* Preview toggle + thumbnail */}
      <div>
        <button onClick={() => setShowPreview(s => !s)}
          className="flex items-center gap-2 text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline cursor-pointer">
          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
          {showPreview ? 'Ocultar vista previa' : 'Vista previa'}
        </button>
        {showPreview && (
          <div className="mt-3 rounded-xl border border-slate-200 dark:border-surface-600 overflow-hidden bg-slate-100 dark:bg-surface-700/60 p-3">
            {/* Mock thumbnail */}
            <div className="bg-white dark:bg-surface-800 rounded-lg p-3 shadow-sm space-y-2">
              <div className="flex items-center justify-between pb-2 border-b border-slate-100 dark:border-surface-700">
                <div className="w-8 h-8 rounded bg-blue-600 flex items-center justify-center">
                  <span className="text-white text-xs font-bold">AR</span>
                </div>
                <div className="text-right">
                  <p className="text-xs font-bold text-blue-600">{printTitle}</p>
                  <p className="text-[10px] text-slate-400">Generado: 27 jun 2026</p>
                </div>
              </div>
              <div className="grid grid-cols-4 gap-1">
                {[['Proyectos','4'],['Completado','63%'],['CPI prom','0.95'],['Presupuesto','$6.1M']].map(([l,v]) => (
                  <div key={l} className="bg-blue-50 dark:bg-blue-500/10 rounded p-1.5 text-center">
                    <p className="text-[10px] text-slate-400">{l}</p>
                    <p className="text-xs font-bold text-blue-600">{v}</p>
                  </div>
                ))}
              </div>
              <div className="h-12 bg-slate-50 dark:bg-surface-700/40 rounded flex items-end gap-1 px-2 pb-1">
                {[40,70,35,80].map((h,i) => (
                  <div key={i} className="flex-1 rounded-t" style={{ height:`${h}%`, background:COLORS[i] }}/>
                ))}
              </div>
              <p className="text-[9px] text-slate-300 dark:text-gray-600 text-center">Vista previa {format} — AR Electronics</p>
            </div>
          </div>
        )}
      </div>

      {/* Action button */}
      <button onClick={handleExport}
        className="w-full flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer shadow-sm">
        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
        Exportar como {format}
      </button>
    </div>
  );
}

// ── Portfolio view ─────────────────────────────────────────────────────────────
function PortfolioReports({ favorites, onToggleFavorite }) {
  const [tab, setTab] = useState(0);

  const allTasks = useMemo(() =>
    MOCK_PROJECTS.flatMap(p => (MOCK_TASKS[p.id] || []).map(t => ({ ...t, projectId: p.id, projectName: p.name }))),
  []);

  const projSummary = useMemo(() => MOCK_PROJECTS.map(p => {
    const tasks = MOCK_TASKS[p.id] || [];
    const done  = tasks.filter(t => t.status === 'COMPLETADA').length;
    return {
      name: p.code, fullName: p.name,
      progress: p.progressPct, budget: p.budget || 0,
      tasks: tasks.length, done,
      blocked: tasks.filter(t => t.status === 'BLOQUEADA').length,
      estHours: tasks.reduce((s, t) => s + (t.estimatedHours || 0), 0),
    };
  }), []);

  const statusData = useMemo(() =>
    Object.entries(allTasks.reduce((acc, t) => ({ ...acc, [t.status]: (acc[t.status] || 0) + 1 }), {}))
      .map(([name, value]) => ({ name: STATUS_LABELS[name] || name, value, color: STATUS_COLORS[name] })),
  [allTasks]);

  const priorityData = useMemo(() =>
    Object.entries(allTasks.reduce((acc, t) => ({ ...acc, [t.priority]: (acc[t.priority] || 0) + 1 }), {}))
      .map(([name, value]) => ({ name, value })),
  [allTasks]);

  const REPORT_SECTIONS = ['resumen-portafolio', 'tareas-portafolio', 'presupuesto-portafolio', 'salud-portafolio', 'comparativo', 'resumen-semanal'];

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

      {/* Tab favorite toggle */}
      <div className="flex items-center gap-2 mb-4">
        <button onClick={() => onToggleFavorite(REPORT_SECTIONS[tab])}
          className="flex items-center gap-1.5 text-xs text-slate-500 dark:text-slate-400 hover:text-amber-500 transition cursor-pointer">
          <StarIcon filled={favorites.includes(REPORT_SECTIONS[tab])}/>
          {favorites.includes(REPORT_SECTIONS[tab]) ? 'En favoritos' : 'Agregar a favoritos'}
        </button>
      </div>

      {/* ── Tab 0 ── */}
      {tab === 0 && (
        <div className="space-y-4">
          <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
            <KPI label="Proyectos activos"  value={MOCK_PROJECTS.filter(p => p.status === 'ACTIVO').length} sub={`de ${MOCK_PROJECTS.length} totales`}/>
            <KPI label="Tareas completadas" value={allTasks.filter(t => t.status === 'COMPLETADA').length} color="text-emerald-600 dark:text-emerald-400" sub={`de ${allTasks.length} totales`}/>
            <KPI label="Tareas bloqueadas"  value={allTasks.filter(t => t.status === 'BLOQUEADA').length}  color="text-red-600 dark:text-red-400"/>
            <KPI label="Presupuesto total"  value={fmt(MOCK_PROJECTS.reduce((s, p) => s + (p.budget || 0), 0))} color="text-blue-600 dark:text-blue-400"/>
          </div>

          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <SectionTitle>Avance por proyecto (%)</SectionTitle>
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={projSummary} margin={{ top:4, right:8, left:-20, bottom:0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
                <XAxis dataKey="name" tick={{ fill:'#94a3b8', fontSize:11 }} axisLine={false} tickLine={false}/>
                <YAxis domain={[0,100]} tick={{ fill:'#94a3b8', fontSize:10 }} axisLine={false} tickLine={false} tickFormatter={v => `${v}%`}/>
                <Tooltip contentStyle={TT} formatter={v => `${v}%`}/>
                <Bar dataKey="progress" name="Avance" fill="#2563EB" radius={[4,4,0,0]} background={{ fill:'#f1f5f9', 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">
              <p className="text-sm font-semibold text-slate-800 dark:text-white">Resumen ejecutivo del portafolio</p>
            </div>
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 dark:border-surface-700">
                  {['Proyecto','Metodología','Avance','Tareas','Completadas','Bloqueadas','Presupuesto'].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">
                {MOCK_PROJECTS.map((p, i) => {
                  const s = projSummary[i];
                  return (
                    <tr key={p.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                      <td className="px-4 py-3.5">
                        <p className="text-sm font-medium text-slate-800 dark:text-gray-200 max-w-[180px] truncate">{p.name}</p>
                        <p className="text-xs text-slate-400 dark:text-gray-600 font-mono">{p.code}</p>
                      </td>
                      <td className="px-4 py-3.5 text-sm text-slate-600 dark:text-gray-300">{p.methodology}</td>
                      <td className="px-4 py-3.5">
                        <div className="flex items-center gap-2">
                          <div className="w-16 h-1.5 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
                            <div className="h-full bg-blue-500 rounded-full" style={{ width:`${p.progressPct}%` }}/>
                          </div>
                          <span className="text-xs font-semibold text-slate-700 dark:text-white tabular-nums">{p.progressPct}%</span>
                        </div>
                      </td>
                      <td className="px-4 py-3.5 text-sm text-slate-600 dark:text-gray-300 tabular-nums">{s.tasks}</td>
                      <td className="px-4 py-3.5 text-sm text-emerald-600 dark:text-emerald-400 tabular-nums font-semibold">{s.done}</td>
                      <td className="px-4 py-3.5 text-sm tabular-nums font-semibold">{s.blocked > 0 ? <span className="text-red-500">{s.blocked}</span> : <span className="text-slate-300 dark:text-gray-600">—</span>}</td>
                      <td className="px-4 py-3.5 text-sm text-slate-600 dark:text-gray-300 font-mono">{p.budget ? fmt(p.budget) : '—'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ── Tab 1: Tareas portafolio ── */}
      {tab === 1 && (
        <div className="space-y-4">
          <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">
              <SectionTitle>Distribución por estado</SectionTitle>
              <div className="flex items-center gap-6">
                <ResponsiveContainer width={160} height={160}>
                  <PieChart>
                    <Pie data={statusData} cx="50%" cy="50%" innerRadius={45} outerRadius={70} paddingAngle={3} dataKey="value">
                      {statusData.map((d, i) => <Cell key={i} fill={d.color}/>)}
                    </Pie>
                    <Tooltip contentStyle={TT}/>
                  </PieChart>
                </ResponsiveContainer>
                <div className="flex-1 space-y-2">
                  {statusData.map(({ name, value, color }) => (
                    <div key={name} className="flex justify-between items-center">
                      <span className="flex items-center gap-2 text-xs text-slate-600 dark:text-gray-300">
                        <span className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: color }}/>
                        {name}
                      </span>
                      <span className="text-xs font-semibold text-slate-800 dark:text-white tabular-nums">{value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
              <SectionTitle>Distribución por prioridad</SectionTitle>
              <div className="flex items-center gap-6">
                <ResponsiveContainer width={160} height={160}>
                  <PieChart>
                    <Pie data={priorityData} cx="50%" cy="50%" innerRadius={45} outerRadius={70} paddingAngle={3} dataKey="value">
                      {priorityData.map((_, i) => <Cell key={i} fill={['#EF4444','#F59E0B','#2563EB','#94a3b8'][i%4]}/>)}
                    </Pie>
                    <Tooltip contentStyle={TT}/>
                  </PieChart>
                </ResponsiveContainer>
                <div className="flex-1 space-y-2">
                  {priorityData.map(({ name, value }, i) => (
                    <div key={name} className="flex justify-between items-center">
                      <span className="flex items-center gap-2 text-xs text-slate-600 dark:text-gray-300">
                        <span className="w-2 h-2 rounded-full" style={{ background:['#EF4444','#F59E0B','#2563EB','#94a3b8'][i%4] }}/>
                        {name.charAt(0)+name.slice(1).toLowerCase()}
                      </span>
                      <span className="text-xs font-semibold text-slate-800 dark:text-white tabular-nums">{value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <SectionTitle>Tareas por proyecto — completadas vs pendientes</SectionTitle>
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={projSummary} margin={{ top:4, right:8, left:-20, bottom:0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
                <XAxis dataKey="name" tick={{ fill:'#94a3b8', fontSize:11 }} axisLine={false} tickLine={false}/>
                <YAxis tick={{ fill:'#94a3b8', fontSize:10 }} axisLine={false} tickLine={false}/>
                <Tooltip contentStyle={TT}/>
                <Legend wrapperStyle={{ fontSize:11, color:'#94a3b8' }}/>
                <Bar dataKey="tasks" name="Total" fill="#e2e8f0" radius={[4,4,0,0]}/>
                <Bar dataKey="done"  name="Completadas" fill="#10B981" radius={[4,4,0,0]}/>
                <Bar dataKey="blocked" name="Bloqueadas" fill="#EF4444" radius={[4,4,0,0]}/>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}

      {/* ── Tab 2: Presupuesto portafolio ── */}
      {tab === 2 && (
        <div className="space-y-4">
          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <SectionTitle>Presupuesto por proyecto</SectionTitle>
            <ResponsiveContainer width="100%" height={250}>
              <BarChart data={projSummary} margin={{ top:4, right:8, left:0, bottom:0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
                <XAxis dataKey="name" 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 => fmt(v)}/>
                <Bar dataKey="budget" name="Presupuesto" radius={[4,4,0,0]}>
                  {projSummary.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]}/>)}
                </Bar>
              </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">
              <p className="text-sm font-semibold text-slate-800 dark:text-white">Resumen financiero del portafolio</p>
            </div>
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 dark:border-surface-700">
                  {['Proyecto','Código','Presupuesto','Cliente','Estado','RAG'].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">
                {MOCK_PROJECTS.map(p => (
                  <tr key={p.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/40">
                    <td className="px-5 py-3.5 text-sm font-medium text-slate-800 dark:text-gray-200 max-w-[180px] truncate">{p.name}</td>
                    <td className="px-5 py-3.5 text-xs text-slate-400 dark:text-gray-500 font-mono">{p.code}</td>
                    <td className="px-5 py-3.5 text-sm font-semibold text-blue-600 dark:text-blue-400 font-mono">{p.budget ? fmt(p.budget) : '—'}</td>
                    <td className="px-5 py-3.5 text-sm text-slate-600 dark:text-gray-300">{p.client}</td>
                    <td className="px-5 py-3.5">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                        p.status==='ACTIVO' ? 'bg-blue-100 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400'
                        : p.status==='EN_RIESGO' ? 'bg-red-100 text-red-700 dark:bg-red-500/10 dark:text-red-400'
                        : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400'
                      }`}>{p.status.replace('_',' ')}</span>
                    </td>
                    <td className="px-5 py-3.5">
                      <span className="w-3 h-3 rounded-full inline-block" style={{ background:{VERDE:'#10B981',AMARILLO:'#F59E0B',ROJO:'#EF4444'}[p.ragStatus] }}/>
                    </td>
                  </tr>
                ))}
                <tr className="bg-slate-50 dark:bg-surface-700/30">
                  <td colSpan={2} className="px-5 py-3 text-sm font-semibold text-slate-900 dark:text-white">Total portafolio</td>
                  <td className="px-5 py-3 text-sm font-bold text-slate-900 dark:text-white font-mono">{fmt(MOCK_PROJECTS.reduce((s,p) => s+(p.budget||0), 0))}</td>
                  <td colSpan={3}/>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ── Tab 3: Salud ── */}
      {tab === 3 && (
        <div className="space-y-4">
          <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">
              <SectionTitle>Radar de salud del portafolio</SectionTitle>
              <ResponsiveContainer width="100%" height={280}>
                <RadarChart data={[
                  { metric:'Avance',      score:Math.round(MOCK_PROJECTS.reduce((s,p) => s+p.progressPct, 0)/MOCK_PROJECTS.length) },
                  { metric:'Tareas OK',   score:Math.round(allTasks.filter(t=>t.status==='COMPLETADA').length/allTasks.length*100) },
                  { metric:'Sin bloqueos',score:Math.round((1-allTasks.filter(t=>t.status==='BLOQUEADA').length/allTasks.length)*100) },
                  { metric:'RAG Verde',   score:Math.round(MOCK_PROJECTS.filter(p=>p.ragStatus==='VERDE').length/MOCK_PROJECTS.length*100) },
                  { metric:'Actividad',   score:72 },
                ]}>
                  <PolarGrid stroke="#e2e8f0"/>
                  <PolarAngleAxis dataKey="metric" tick={{ fill:'#64748b', fontSize:11 }}/>
                  <PolarRadiusAxis domain={[0,100]} tick={{ fill:'#94a3b8', fontSize:9 }} tickCount={4}/>
                  <Radar name="Portafolio" dataKey="score" stroke="#2563EB" fill="#2563EB" fillOpacity={0.15} strokeWidth={2}/>
                  <Tooltip contentStyle={TT} formatter={v => `${v}%`}/>
                </RadarChart>
              </ResponsiveContainer>
            </div>

            <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
              <SectionTitle>Semáforo RAG de proyectos</SectionTitle>
              <div className="space-y-3">
                {MOCK_PROJECTS.map(p => {
                  const ragColor = { VERDE:'#10B981', AMARILLO:'#F59E0B', ROJO:'#EF4444' }[p.ragStatus];
                  const tasks    = MOCK_TASKS[p.id] || [];
                  const blocked  = tasks.filter(t => t.status === 'BLOQUEADA').length;
                  return (
                    <div key={p.id} className="flex items-center gap-4 p-3 rounded-xl bg-slate-50 dark:bg-surface-700/40">
                      <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ background: ragColor }}/>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-slate-800 dark:text-gray-200 truncate">{p.name}</p>
                        <p className="text-xs text-slate-400 dark:text-gray-500">{p.code} · {p.methodology}</p>
                      </div>
                      <div className="text-right flex-shrink-0">
                        <p className="text-sm font-bold tabular-nums" style={{ color: ragColor }}>{p.progressPct}%</p>
                        {blocked > 0 && <p className="text-xs text-red-500">{blocked} bloqueada{blocked>1?'s':''}</p>}
                      </div>
                    </div>
                  );
                })}
              </div>
              <div className="mt-4 pt-4 border-t border-slate-100 dark:border-surface-700 grid grid-cols-3 gap-2 text-center">
                {[['VERDE','Verde','#10B981'],['AMARILLO','Ámbar','#F59E0B'],['ROJO','Rojo','#EF4444']].map(([rag,label,color]) => (
                  <div key={rag}>
                    <p className="text-xl font-bold" style={{ color }}>{MOCK_PROJECTS.filter(p=>p.ragStatus===rag).length}</p>
                    <p className="text-xs text-slate-400 dark:text-gray-500">{label}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Tab 4: Comparativo ── */}
      {tab === 4 && <ComparativoProyectos />}

      {/* ── Tab 5: Resumen semanal ── */}
      {tab === 5 && <ResumenEjecutivoSemanal />}
    </>
  );
}

// ── Single project view ────────────────────────────────────────────────────────
function ProjectReports({ project, favorites, onToggleFavorite }) {
  const [tab, setTab] = useState(0);
  const tasks  = MOCK_TASKS[project.id] || [];
  const evm    = MOCK_EVM?.[project.id];

  const statusData = useMemo(() =>
    Object.entries(tasks.reduce((acc, t) => ({ ...acc, [t.status]: (acc[t.status]||0)+1 }), {}))
      .map(([s, v]) => ({ name: STATUS_LABELS[s]||s, value:v, color: STATUS_COLORS[s] })),
  [tasks]);

  const priorityData = useMemo(() =>
    Object.entries(tasks.reduce((acc, t) => ({ ...acc, [t.priority]: (acc[t.priority]||0)+1 }), {}))
      .map(([name, value]) => ({ name, value })),
  [tasks]);

  const phaseData = useMemo(() => {
    const phases = {};
    tasks.forEach(t => { phases[t.phase||'Sin fase'] = (phases[t.phase||'Sin fase']||0)+1; });
    return Object.entries(phases).map(([name, value]) => ({ name, value }));
  }, [tasks]);

  const assigneeData = useMemo(() => {
    const map = {};
    tasks.forEach(t => {
      if (t.assignee) {
        const k = `${t.assignee.firstName} ${t.assignee.lastName}`;
        map[k] = (map[k]||0)+1;
      }
    });
    return Object.entries(map).map(([name, value]) => ({ name, value })).sort((a,b) => b.value-a.value);
  }, [tasks]);

  const progressByPhase = useMemo(() => {
    const phases = {};
    tasks.forEach(t => {
      const ph = t.phase || 'Sin fase';
      if (!phases[ph]) phases[ph] = { total:0, done:0, hours:0, actualHours:0, cost:0 };
      phases[ph].total++;
      if (t.status === 'COMPLETADA') phases[ph].done++;
      phases[ph].hours       += t.estimatedHours || 0;
      phases[ph].actualHours += t.actualHours    || 0;
      phases[ph].cost        += t.plannedCost    || 0;
    });
    return Object.entries(phases).map(([name, v]) => ({
      name, total:v.total, done:v.done,
      pct: v.total ? Math.round(v.done/v.total*100) : 0,
      hours: v.hours, actualHours: v.actualHours, cost: v.cost,
    }));
  }, [tasks]);

  const totalHrs     = tasks.reduce((s,t) => s+(t.estimatedHours||0), 0);
  const actualHrs    = tasks.reduce((s,t) => s+(t.actualHours||0), 0);
  const totalCost    = tasks.reduce((s,t) => s+(t.plannedCost||0), 0);
  const done         = tasks.filter(t => t.status === 'COMPLETADA').length;
  const blocked      = tasks.filter(t => t.status === 'BLOQUEADA').length;
  const critical     = tasks.filter(t => t.isCritical).length;
  const ragColor     = { VERDE:'text-emerald-600 dark:text-emerald-400', AMARILLO:'text-amber-500', ROJO:'text-red-600 dark:text-red-400' }[project.ragStatus] || '';

  const tabKey = `project-${project.id}-tab${tab}`;

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

      {/* Tab favorite toggle */}
      <div className="flex items-center gap-2 mb-4">
        <button onClick={() => onToggleFavorite(tabKey)}
          className="flex items-center gap-1.5 text-xs text-slate-500 dark:text-slate-400 hover:text-amber-500 transition cursor-pointer">
          <StarIcon filled={favorites.includes(tabKey)}/>
          {favorites.includes(tabKey) ? 'En favoritos' : 'Agregar a favoritos'}
        </button>
      </div>

      {/* ── Tab 0: Resumen del proyecto ── */}
      {tab === 0 && (
        <div className="space-y-4">
          {/* Brief card */}
          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <div className="flex flex-wrap gap-6 items-start">
              <div className="flex-1 min-w-0">
                <p className="text-xs font-mono text-slate-400 dark:text-gray-500 mb-1">{project.code}</p>
                <h2 className="text-base font-bold text-slate-900 dark:text-white mb-1">{project.name}</h2>
                <p className="text-sm text-slate-500 dark:text-gray-400 line-clamp-2">{project.description}</p>
              </div>
              <div className="flex flex-col gap-1 text-right flex-shrink-0">
                <span className={`text-sm font-semibold ${ragColor}`}>● {project.ragStatus}</span>
                <span className="text-xs text-slate-400 dark:text-gray-500">{project.methodology}</span>
                <span className="text-xs text-slate-400 dark:text-gray-500">{project.client}</span>
              </div>
            </div>
            <div className="mt-4 pt-4 border-t border-slate-100 dark:border-surface-700 grid grid-cols-3 gap-4">
              <div>
                <p className="text-xs text-slate-400 dark:text-gray-500 mb-1">Inicio planeado</p>
                <p className="text-sm font-medium text-slate-800 dark:text-gray-200">{project.startDate || '—'}</p>
              </div>
              <div>
                <p className="text-xs text-slate-400 dark:text-gray-500 mb-1">Fin planeado</p>
                <p className="text-sm font-medium text-slate-800 dark:text-gray-200">{project.endDate || '—'}</p>
              </div>
              <div>
                <p className="text-xs text-slate-400 dark:text-gray-500 mb-1">Avance</p>
                <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 bg-blue-500 rounded-full" style={{ width:`${project.progressPct}%` }}/>
                  </div>
                  <span className="text-sm font-bold text-blue-600 dark:text-blue-400 tabular-nums">{project.progressPct}%</span>
                </div>
              </div>
            </div>
          </div>

          {/* KPIs */}
          <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
            <KPI label="Tareas totales"    value={tasks.length}  sub={`${done} completadas`}/>
            <KPI label="Tareas críticas"   value={critical}      color={critical>0?'text-red-600 dark:text-red-400':'text-slate-900 dark:text-white'} sub="en ruta crítica"/>
            <KPI label="Horas estimadas"   value={`${totalHrs}h`}  sub={`${actualHrs}h reales`} color={actualHrs>totalHrs?'text-red-600 dark:text-red-400':'text-slate-900 dark:text-white'}/>
            <KPI label="Costo planificado" value={fmt(totalCost)} color="text-blue-600 dark:text-blue-400" sub={project.budget?`de ${fmt(project.budget)}`:undefined}/>
          </div>

          {/* Phase breakdown */}
          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <SectionTitle>Avance por fase</SectionTitle>
            <div className="space-y-3">
              {progressByPhase.map(ph => (
                <div key={ph.name} className="flex items-center gap-4">
                  <span className="text-xs text-slate-500 dark:text-gray-400 w-36 truncate flex-shrink-0">{ph.name}</span>
                  <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:`${ph.pct}%`, background: ph.pct===100?'#10B981':'#2563EB' }}/>
                  </div>
                  <span className="text-xs font-semibold tabular-nums w-10 text-right text-slate-700 dark:text-gray-200">{ph.pct}%</span>
                  <span className="text-xs text-slate-400 dark:text-gray-500 w-16 text-right tabular-nums">{ph.done}/{ph.total}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Alerts section */}
          {(blocked > 0 || actualHrs > totalHrs * 0.9) && (
            <div className="space-y-2">
              {blocked > 0 && (
                <div className="flex items-start gap-3 p-4 bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/20 rounded-xl">
                  <svg className="w-4 h-4 text-red-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>
                  <p className="text-sm text-red-700 dark:text-red-400"><span className="font-semibold">{blocked} tarea{blocked>1?'s':''} bloqueada{blocked>1?'s':''}</span> — requieren atención inmediata.</p>
                </div>
              )}
              {actualHrs > totalHrs * 0.9 && totalHrs > 0 && (
                <div className="flex items-start gap-3 p-4 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/20 rounded-xl">
                  <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}><circle cx="12" cy="12" r="10"/><path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01"/></svg>
                  <p className="text-sm text-amber-700 dark:text-amber-400"><span className="font-semibold">Horas reales al {Math.round(actualHrs/totalHrs*100)}%</span> de las estimadas — riesgo de desvío.</p>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* ── Tab 1: Tareas del proyecto ── */}
      {tab === 1 && (
        <div className="space-y-4">
          <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">
              <SectionTitle>Estado de tareas</SectionTitle>
              <div className="flex items-center gap-6">
                <ResponsiveContainer width={160} height={160}>
                  <PieChart>
                    <Pie data={statusData} cx="50%" cy="50%" innerRadius={45} outerRadius={70} paddingAngle={3} dataKey="value">
                      {statusData.map((d,i) => <Cell key={i} fill={d.color}/>)}
                    </Pie>
                    <Tooltip contentStyle={TT}/>
                  </PieChart>
                </ResponsiveContainer>
                <div className="flex-1 space-y-2">
                  {statusData.map(({ name, value, color }) => (
                    <div key={name} className="flex justify-between items-center">
                      <span className="flex items-center gap-2 text-xs text-slate-600 dark:text-gray-300">
                        <span className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: color }}/>
                        {name}
                      </span>
                      <span className="text-xs font-semibold tabular-nums">{value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
              <SectionTitle>Tareas por fase</SectionTitle>
              <ResponsiveContainer width="100%" height={180}>
                <BarChart data={phaseData} layout="vertical" margin={{ top:0, right:8, left:8, bottom:0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" horizontal={false}/>
                  <XAxis type="number" tick={{ fill:'#94a3b8', fontSize:10 }} axisLine={false} tickLine={false}/>
                  <YAxis type="category" dataKey="name" tick={{ fill:'#94a3b8', fontSize:10 }} axisLine={false} tickLine={false} width={80}/>
                  <Tooltip contentStyle={TT}/>
                  <Bar dataKey="value" name="Tareas" fill="#2563EB" radius={[0,4,4,0]}>
                    {phaseData.map((_,i) => <Cell key={i} fill={COLORS[i%COLORS.length]}/>)}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Task detail 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">Listado de tareas</p>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-slate-100 dark:border-surface-700">
                    {['WBS','Tarea','Fase','Responsable','Estado','Avance','Hs Est/Real'].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">
                  {tasks.map(t => {
                    const color = STATUS_COLORS[t.status];
                    const overH  = (t.actualHours||0) > (t.estimatedHours||0);
                    return (
                      <tr key={t.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                        <td className="px-4 py-3 text-xs font-mono text-slate-400 dark:text-gray-500">{t.wbsCode}</td>
                        <td className="px-4 py-3">
                          <p className="text-sm text-slate-800 dark:text-gray-200 max-w-[200px] truncate">{t.title}</p>
                          {t.isCritical && <span className="text-xs text-red-500">⚡ crítica</span>}
                        </td>
                        <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400 max-w-[100px] truncate">{t.phase}</td>
                        <td className="px-4 py-3 text-xs text-slate-600 dark:text-gray-300">{t.assignee ? `${t.assignee.firstName} ${t.assignee.lastName[0]}.` : '—'}</td>
                        <td className="px-4 py-3">
                          <span className="text-xs px-2 py-0.5 rounded-full font-medium whitespace-nowrap" style={{ background:`${color}20`, color }}>
                            {STATUS_LABELS[t.status]}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-1.5">
                            <div className="w-12 h-1.5 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
                              <div className="h-full rounded-full" style={{ width:`${t.progressPct||0}%`, background: (t.progressPct||0)===100?'#10B981':'#2563EB' }}/>
                            </div>
                            <span className="text-xs tabular-nums text-slate-500 dark:text-gray-400">{t.progressPct||0}%</span>
                          </div>
                        </td>
                        <td className={`px-4 py-3 text-xs tabular-nums font-mono ${overH?'text-red-500':'text-slate-500 dark:text-gray-400'}`}>
                          {t.actualHours||0}h / {t.estimatedHours||0}h
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* ── Tab 2: Cronograma ── */}
      {tab === 2 && (
        <div className="space-y-4">
          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <SectionTitle>Avance y horas por fase</SectionTitle>
            <ResponsiveContainer width="100%" height={240}>
              <BarChart data={progressByPhase} 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 yAxisId="left"  tick={{ fill:'#94a3b8', fontSize:10 }} axisLine={false} tickLine={false}/>
                <YAxis yAxisId="right" orientation="right" tick={{ fill:'#94a3b8', fontSize:10 }} axisLine={false} tickLine={false} tickFormatter={v=>`${v}%`}/>
                <Tooltip contentStyle={TT}/>
                <Legend wrapperStyle={{ fontSize:11 }}/>
                <Bar yAxisId="left"  dataKey="hours"       name="Hs estimadas" fill="#e2e8f0" radius={[4,4,0,0]}/>
                <Bar yAxisId="left"  dataKey="actualHours" name="Hs reales"    fill="#2563EB" radius={[4,4,0,0]}/>
                <Bar yAxisId="right" dataKey="pct"         name="% completado" fill="#10B981" radius={[4,4,0,0]}/>
              </BarChart>
            </ResponsiveContainer>
          </div>

          {evm && (
            <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
              <SectionTitle>Curva S — PV vs EV vs AC</SectionTitle>
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={evm.series} margin={{ top:4, right:8, left:0, bottom:0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" vertical={false}/>
                  <XAxis dataKey="period" 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 }}/>
                  <Line type="monotone" dataKey="pv" name="PV (plan)" stroke="#94a3b8" strokeDasharray="4 2" strokeWidth={1.5} dot={false}/>
                  <Line type="monotone" dataKey="ev" name="EV (ganado)" stroke="#10B981" strokeWidth={2} dot={{ r:3 }}/>
                  <Line type="monotone" dataKey="ac" name="AC (real)" stroke="#EF4444" strokeWidth={2} dot={{ r:3 }}/>
                  <ReferenceLine y={evm.bac} stroke="#2563EB" strokeDasharray="6 3" label={{ value:'BAC', fill:'#2563EB', fontSize:10 }}/>
                </LineChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>
      )}

      {/* ── Tab 3: Financiero ── */}
      {tab === 3 && (
        <div className="space-y-4">
          <div className="grid grid-cols-2 xl:grid-cols-3 gap-3">
            <KPI label="Presupuesto base" value={project.budget ? fmt(project.budget) : '—'} color="text-blue-600 dark:text-blue-400"/>
            <KPI label="Costo planificado" value={fmt(totalCost)} sub="según tareas"/>
            <KPI label="Varianza" value={project.budget ? fmt(project.budget - totalCost) : '—'} color={(project.budget - totalCost) >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}/>
          </div>

          <div className="bg-white dark:bg-surface-800 rounded-2xl p-5 border border-slate-200 dark:border-surface-700 shadow-sm">
            <SectionTitle>Costo planificado por fase</SectionTitle>
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={progressByPhase} margin={{ top:4, right:8, left:0, 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)}/>
                <Bar dataKey="cost" name="Costo planificado" radius={[4,4,0,0]}>
                  {progressByPhase.map((_,i) => <Cell key={i} fill={COLORS[i%COLORS.length]}/>)}
                </Bar>
              </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">
              <p className="text-sm font-semibold text-slate-800 dark:text-white">Detalle financiero por tarea</p>
            </div>
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 dark:border-surface-700">
                  {['Tarea','Responsable','Hs Est','Hs Real','Costo planeado','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 whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
                {tasks.map(t => {
                  const overH = (t.actualHours||0) > (t.estimatedHours||0);
                  return (
                    <tr key={t.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/40">
                      <td className="px-4 py-3 text-sm text-slate-800 dark:text-gray-200 max-w-[180px] truncate">{t.title}</td>
                      <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400">{t.assignee ? `${t.assignee.firstName} ${t.assignee.lastName[0]}.` : '—'}</td>
                      <td className="px-4 py-3 text-sm tabular-nums text-slate-600 dark:text-gray-300">{t.estimatedHours||0}h</td>
                      <td className={`px-4 py-3 text-sm tabular-nums font-semibold ${overH?'text-red-500':'text-slate-600 dark:text-gray-300'}`}>{t.actualHours||0}h</td>
                      <td className="px-4 py-3 text-sm tabular-nums font-mono text-blue-600 dark:text-blue-400">{t.plannedCost ? fmt(t.plannedCost) : '—'}</td>
                      <td className="px-4 py-3">
                        <span className="text-xs px-2 py-0.5 rounded-full" style={{ background:`${STATUS_COLORS[t.status]}20`, color:STATUS_COLORS[t.status] }}>
                          {STATUS_LABELS[t.status]}
                        </span>
                      </td>
                    </tr>
                  );
                })}
                <tr className="bg-slate-50 dark:bg-surface-700/30 font-semibold">
                  <td colSpan={2} className="px-4 py-3 text-sm text-slate-900 dark:text-white">Total</td>
                  <td className="px-4 py-3 text-sm tabular-nums">{totalHrs}h</td>
                  <td className={`px-4 py-3 text-sm tabular-nums ${actualHrs>totalHrs?'text-red-500':'text-slate-900 dark:text-white'}`}>{actualHrs}h</td>
                  <td className="px-4 py-3 text-sm tabular-nums font-mono text-blue-600 dark:text-blue-400">{fmt(totalCost)}</td>
                  <td/>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ── Tab 4: Equipo ── */}
      {tab === 4 && (
        <div className="space-y-4">
          <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">
              <SectionTitle>Tareas por responsable</SectionTitle>
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={assigneeData} layout="vertical" margin={{ top:0, right:8, left:8, bottom:0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" horizontal={false}/>
                  <XAxis type="number" tick={{ fill:'#94a3b8', fontSize:10 }} axisLine={false} tickLine={false}/>
                  <YAxis type="category" dataKey="name" tick={{ fill:'#94a3b8', fontSize:10 }} axisLine={false} tickLine={false} width={90}/>
                  <Tooltip contentStyle={TT}/>
                  <Bar dataKey="value" name="Tareas" fill="#2563EB" radius={[0,4,4,0]}>
                    {assigneeData.map((_,i) => <Cell key={i} fill={COLORS[i%COLORS.length]}/>)}
                  </Bar>
                </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">
              <SectionTitle>Distribución por prioridad</SectionTitle>
              <div className="flex items-center gap-6">
                <ResponsiveContainer width={160} height={160}>
                  <PieChart>
                    <Pie data={priorityData} cx="50%" cy="50%" innerRadius={45} outerRadius={70} paddingAngle={3} dataKey="value">
                      {priorityData.map((_,i) => <Cell key={i} fill={['#EF4444','#F59E0B','#2563EB','#94a3b8'][i%4]}/>)}
                    </Pie>
                    <Tooltip contentStyle={TT}/>
                  </PieChart>
                </ResponsiveContainer>
                <div className="flex-1 space-y-2">
                  {priorityData.map(({ name, value }, i) => (
                    <div key={name} className="flex justify-between items-center">
                      <span className="flex items-center gap-2 text-xs text-slate-600 dark:text-gray-300">
                        <span className="w-2 h-2 rounded-full" style={{ background:['#EF4444','#F59E0B','#2563EB','#94a3b8'][i%4] }}/>
                        {name.charAt(0)+name.slice(1).toLowerCase()}
                      </span>
                      <span className="text-xs font-semibold tabular-nums">{value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Assignee detail */}
          <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">Carga por persona</p>
            </div>
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-100 dark:border-surface-700">
                  {['Responsable','Tareas','Completadas','Bloqueadas','Hs estimadas','Hs reales'].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">
                {assigneeData.map(({ name }) => {
                  const myTasks = tasks.filter(t => t.assignee && `${t.assignee.firstName} ${t.assignee.lastName}` === name);
                  const myDone  = myTasks.filter(t => t.status === 'COMPLETADA').length;
                  const myBlock = myTasks.filter(t => t.status === 'BLOQUEADA').length;
                  const myHrs   = myTasks.reduce((s,t) => s+(t.estimatedHours||0), 0);
                  const myAct   = myTasks.reduce((s,t) => s+(t.actualHours||0), 0);
                  return (
                    <tr key={name} className="hover:bg-slate-50 dark:hover:bg-surface-700/40">
                      <td className="px-4 py-3 text-sm font-medium text-slate-800 dark:text-gray-200">{name}</td>
                      <td className="px-4 py-3 text-sm tabular-nums text-slate-600 dark:text-gray-300">{myTasks.length}</td>
                      <td className="px-4 py-3 text-sm tabular-nums text-emerald-600 dark:text-emerald-400 font-semibold">{myDone}</td>
                      <td className="px-4 py-3 text-sm tabular-nums">{myBlock > 0 ? <span className="text-red-500 font-semibold">{myBlock}</span> : <span className="text-slate-300 dark:text-gray-600">—</span>}</td>
                      <td className="px-4 py-3 text-sm tabular-nums text-slate-600 dark:text-gray-300">{myHrs}h</td>
                      <td className={`px-4 py-3 text-sm tabular-nums font-semibold ${myAct>myHrs?'text-red-500':'text-slate-600 dark:text-gray-300'}`}>{myAct}h</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </>
  );
}

// ── PDF Export ────────────────────────────────────────────────────────────────
function exportPDF(title) {
  const style = document.createElement('style');
  style.id = 'arpm-print-style';
  style.innerHTML = `
    @media print {
      body > * { display: none !important; }
      #arpm-print-root { display: block !important; }
      #arpm-print-root { position: fixed; inset: 0; background: white; z-index: 99999; overflow: auto; padding: 24px; font-family: sans-serif; color: #0f172a; }
      .no-print { display: none !important; }
      button { display: none !important; }
      @page { margin: 1.5cm; size: A4; }
    }
  `;
  document.head.appendChild(style);

  const root = document.getElementById('arpm-print-root');
  if (root) {
    const header = document.createElement('div');
    header.style.cssText = 'display:flex;align-items:center;justify-content:space-between;border-bottom:2px solid #2563EB;padding-bottom:12px;margin-bottom:20px';
    header.innerHTML = `
      <div>
        <img src="/logo-ar.png" style="height:48px;object-fit:contain" alt="AR Electronics"/>
      </div>
      <div style="text-align:right">
        <div style="font-size:18px;font-weight:700;color:#2563EB">${title}</div>
        <div style="font-size:11px;color:#64748b;margin-top:2px">Generado el ${new Date().toLocaleDateString('es-CO', {day:'2-digit',month:'long',year:'numeric'})}</div>
      </div>`;
    root.prepend(header);
  }

  window.print();

  setTimeout(() => {
    document.getElementById('arpm-print-style')?.remove();
    root?.querySelector('div[style]')?.remove();
  }, 1000);
}

// ── Main page ─────────────────────────────────────────────────────────────────
export default function ReportsPage() {
  const { selectedProjectId } = useProject();
  const selectedId = selectedProjectId || '__all__';
  const selectedProject = selectedId === '__all__' ? null : MOCK_PROJECTS.find(p => p.id === selectedId);
  const printTitle = selectedProject ? `Reporte: ${selectedProject.name}` : 'Reporte de Portafolio';

  const [favorites, setFavorites] = useState([]);
  const [showOnlyFavorites, setShowOnlyFavorites] = useState(false);
  const [showExportPanel, setShowExportPanel] = useState(false);

  const toggleFavorite = useCallback((key) => {
    setFavorites(f => f.includes(key) ? f.filter(x => x !== key) : [...f, key]);
  }, []);

  const hasFavorites = favorites.length > 0;

  return (
    <div id="arpm-print-root" className="space-y-5 pb-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">Reportes</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">
            {selectedProject ? `Proyecto: ${selectedProject.name}` : 'Vista de portafolio completo'}
          </p>
        </div>
        <div className="flex items-center gap-2 no-print flex-wrap">
          {/* Favorites filter chip */}
          {hasFavorites && (
            <button
              onClick={() => setShowOnlyFavorites(s => !s)}
              className={`flex items-center gap-1.5 px-3 py-2 text-sm font-medium rounded-xl transition cursor-pointer border ${
                showOnlyFavorites
                  ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 border-amber-300 dark:border-amber-500/40'
                  : 'bg-white dark:bg-surface-800 text-slate-600 dark:text-gray-300 border-slate-200 dark:border-surface-700 hover:border-amber-400'
              }`}>
              <StarIcon filled={showOnlyFavorites}/>
              Favoritos ({favorites.length})
            </button>
          )}
          {/* Export toggle */}
          <button
            onClick={() => setShowExportPanel(s => !s)}
            className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl transition cursor-pointer border shadow-sm ${
              showExportPanel
                ? 'bg-blue-600 text-white border-blue-600'
                : 'bg-white dark:bg-surface-800 text-slate-700 dark:text-gray-200 border-slate-200 dark:border-surface-700 hover:border-blue-400'
            }`}>
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
            Exportar
          </button>
        </div>
      </div>

      {/* Export panel */}
      {showExportPanel && (
        <div className="no-print">
          <ExportPanel printTitle={printTitle}/>
        </div>
      )}

      {/* Favorites notice */}
      {showOnlyFavorites && hasFavorites && (
        <div className="flex items-center gap-2 p-3 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/20 rounded-xl text-sm text-amber-700 dark:text-amber-400 no-print">
          <StarIcon filled/>
          <span>Mostrando solo secciones marcadas como favoritos. <button onClick={() => setShowOnlyFavorites(false)} className="underline cursor-pointer">Ver todo</button></span>
        </div>
      )}

      {/* Breadcrumb when project selected */}
      {selectedProject && (
        <div className="flex items-center gap-2 text-xs">
          <span className="text-blue-600 dark:text-blue-400">
            Portafolio completo
          </span>
          <span className="text-slate-300 dark:text-gray-600">/</span>
          <span className="text-slate-600 dark:text-gray-300 font-medium">{selectedProject.name}</span>
          <span className="ml-2 px-2 py-0.5 rounded-full text-xs font-medium" style={{
            background: { VERDE:'#10B98120', AMARILLO:'#F59E0B20', ROJO:'#EF444420' }[selectedProject.ragStatus],
            color:       { VERDE:'#10B981',   AMARILLO:'#F59E0B',   ROJO:'#EF4444' }[selectedProject.ragStatus],
          }}>● {selectedProject.ragStatus}</span>
        </div>
      )}

      {/* Content */}
      {selectedProject
        ? <ProjectReports project={selectedProject} favorites={favorites} onToggleFavorite={toggleFavorite}/>
        : <PortfolioReports favorites={favorites} onToggleFavorite={toggleFavorite}/>
      }
    </div>
  );
}
