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

// ─── Mock Sprint Data ────────────────────────────────────────────────────────

const SPRINT_DATA = {
  // Construcción Torre — usa semanas/fases (PMI)
  p1: {
    label: 'Semana',
    totalPoints: 480,
    plannedEnd: '2026-12-15',
    sprints: [
      { name: 'Sem 1',  planned: 60, completed: 58, scopeTotal: 480 },
      { name: 'Sem 2',  planned: 60, completed: 55, scopeTotal: 480 },
      { name: 'Sem 3',  planned: 60, completed: 62, scopeTotal: 480 },
      { name: 'Sem 4',  planned: 60, completed: 50, scopeTotal: 480 },
      { name: 'Sem 5',  planned: 60, completed: 57, scopeTotal: 480 },
      { name: 'Sem 6',  planned: 60, completed: 59, scopeTotal: 480 },
      { name: 'Sem 7',  planned: 60, completed: 54, scopeTotal: 480 },
      { name: 'Sem 8',  planned: 60, completed: 61, scopeTotal: 480 },
    ],
  },
  // AR-ProjectManagement — sprints normales, buen ritmo
  p2: {
    label: 'Sprint',
    totalPoints: 200,
    plannedEnd: '2026-09-30',
    sprints: [
      { name: 'Sprint 1', planned: 25, completed: 23, scopeTotal: 200 },
      { name: 'Sprint 2', planned: 25, completed: 26, scopeTotal: 200 },
      { name: 'Sprint 3', planned: 25, completed: 24, scopeTotal: 200 },
      { name: 'Sprint 4', planned: 25, completed: 27, scopeTotal: 200 },
      { name: 'Sprint 5', planned: 25, completed: 25, scopeTotal: 200 },
      { name: 'Sprint 6', planned: 25, completed: 22, scopeTotal: 200 },
      { name: 'Sprint 7', planned: 25, completed: 26, scopeTotal: 200 },
      { name: 'Sprint 8', planned: 25, completed: 24, scopeTotal: 200 },
    ],
  },
  // ERP — scope creep + velocidad declinante (en problemas)
  p3: {
    label: 'Sprint',
    totalPoints: 320,
    plannedEnd: '2026-10-31',
    sprints: [
      { name: 'Sprint 1', planned: 40, completed: 38, scopeTotal: 320 },
      { name: 'Sprint 2', planned: 40, completed: 35, scopeTotal: 340 }, // scope creep +20
      { name: 'Sprint 3', planned: 40, completed: 30, scopeTotal: 340 },
      { name: 'Sprint 4', planned: 40, completed: 28, scopeTotal: 370 }, // scope creep +30
      { name: 'Sprint 5', planned: 40, completed: 25, scopeTotal: 370 },
      { name: 'Sprint 6', planned: 40, completed: 22, scopeTotal: 390 }, // scope creep +20
      { name: 'Sprint 7', planned: 40, completed: 20, scopeTotal: 390 },
      { name: 'Sprint 8', planned: 40, completed: 18, scopeTotal: 390 },
    ],
  },
  // AR-PM — buena velocidad, en camino
  p4: {
    label: 'Sprint',
    totalPoints: 260,
    plannedEnd: '2026-11-30',
    sprints: [
      { name: 'Sprint 1', planned: 32, completed: 33, scopeTotal: 260 },
      { name: 'Sprint 2', planned: 32, completed: 34, scopeTotal: 260 },
      { name: 'Sprint 3', planned: 32, completed: 32, scopeTotal: 260 },
      { name: 'Sprint 4', planned: 32, completed: 35, scopeTotal: 260 },
      { name: 'Sprint 5', planned: 32, completed: 33, scopeTotal: 260 },
      { name: 'Sprint 6', planned: 32, completed: 36, scopeTotal: 260 },
      { name: 'Sprint 7', planned: 32, completed: 34, scopeTotal: 260 },
      { name: 'Sprint 8', planned: 32, completed: 35, scopeTotal: 260 },
    ],
  },
};

// ─── Helpers ─────────────────────────────────────────────────────────────────

function addDays(dateStr, days) {
  const d = new Date(dateStr);
  d.setDate(d.getDate() + days);
  return d;
}

function formatDate(date) {
  return date.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

function computeChartData(projectId) {
  const data = SPRINT_DATA[projectId];
  if (!data) return { burndown: [], burnup: [], velocity: [] };

  const { sprints, totalPoints } = data;
  const totalSprints = 12; // full project duration
  const sprintDurationDays = projectId === 'p4' ? 7 : 14;

  // Build burndown data
  const burndown = [];
  let remaining = totalPoints;
  const idealStep = totalPoints / totalSprints;

  // Add sprint 0 (start)
  burndown.push({
    name: 'Inicio',
    ideal: totalPoints,
    real: totalPoints,
  });

  let cumulativeCompleted = 0;
  sprints.forEach((s, i) => {
    remaining -= s.completed;
    cumulativeCompleted += s.completed;
    burndown.push({
      name: s.name,
      ideal: Math.max(0, totalPoints - idealStep * (i + 1)),
      real: Math.max(0, remaining),
    });
  });

  // Trend projection from last 4 sprints
  const last4 = sprints.slice(-4);
  const avgVelocity = last4.reduce((acc, s) => acc + s.completed, 0) / last4.length;
  let trendRemaining = remaining;
  for (let i = sprints.length; i < totalSprints; i++) {
    trendRemaining = Math.max(0, trendRemaining - avgVelocity);
    burndown.push({
      name: `${data.label} ${i + 1}`,
      ideal: Math.max(0, totalPoints - idealStep * (i + 1)),
      trend: trendRemaining,
    });
  }
  // Add trend to existing historical points
  burndown.forEach((pt, idx) => {
    if (idx <= sprints.length && idx > 0) {
      pt.trend = undefined;
    }
  });
  // Set trend start = last real value
  if (burndown[sprints.length]) {
    burndown[sprints.length].trend = burndown[sprints.length].real;
  }

  // Build burnup data
  const burnup = [];
  let cumCompleted = 0;
  burnup.push({ name: 'Inicio', scope: sprints[0]?.scopeTotal ?? totalPoints, completed: 0 });
  sprints.forEach((s, i) => {
    cumCompleted += s.completed;
    burnup.push({
      name: s.name,
      scope: s.scopeTotal,
      completed: cumCompleted,
    });
  });

  // Velocity data
  const velocity = sprints.map((s) => ({
    name: s.name,
    planned: s.planned,
    completed: s.completed,
    delta: s.completed - s.planned,
  }));

  return { burndown, burnup, velocity, avgVelocity, remaining, totalPoints, cumulativeCompleted, sprintDurationDays };
}

function computePrediction(projectId, remaining, avgVelocity, sprintDurationDays) {
  const data = SPRINT_DATA[projectId];
  if (!data || avgVelocity <= 0) return null;

  const sprintsLeft = Math.ceil(remaining / avgVelocity);
  const daysLeft = sprintsLeft * sprintDurationDays;
  const today = new Date('2026-06-26');
  const predictedEnd = addDays('2026-06-26', daysLeft);
  const plannedEnd = new Date(data.plannedEnd);
  const diffDays = Math.round((predictedEnd - plannedEnd) / (1000 * 60 * 60 * 24));

  const confidence = Math.min(95, Math.max(40, Math.round(85 - Math.abs(diffDays) * 0.5)));

  return { predictedEnd, plannedEnd, diffDays, confidence, sprintsLeft };
}

// ─── Custom Tooltip ──────────────────────────────────────────────────────────

function CustomTooltip({ active, payload, label }) {
  if (!active || !payload || !payload.length) return null;
  return (
    <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl p-3 shadow-lg text-sm">
      <p className="font-semibold text-slate-700 dark:text-slate-200 mb-1">{label}</p>
      {payload.map((p) => (
        <p key={p.name} style={{ color: p.color }} className="text-xs">
          {p.name}: <span className="font-medium">{p.value != null ? Math.round(p.value) : '—'}</span>
        </p>
      ))}
    </div>
  );
}

// ─── KPI Card ────────────────────────────────────────────────────────────────

function KpiCard({ label, value, sub, color = 'blue' }) {
  const colorMap = {
    blue: 'text-blue-600 dark:text-blue-400',
    green: 'text-emerald-600 dark:text-emerald-400',
    amber: 'text-amber-600 dark:text-amber-400',
    red: 'text-red-600 dark:text-red-400',
  };
  return (
    <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
      <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-1">{label}</p>
      <p className={`text-2xl font-bold ${colorMap[color]}`}>{value}</p>
      {sub && <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">{sub}</p>}
    </div>
  );
}

// ─── Scope Creep Badge ───────────────────────────────────────────────────────

function ScopeCreepNote({ projectId }) {
  if (projectId !== 'p4') return null;
  return (
    <div className="flex items-center gap-2 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700 rounded-xl px-4 py-2 text-sm text-amber-700 dark:text-amber-400">
      <span className="font-semibold">Scope Creep detectado:</span> El alcance aumentó de 320 → 390 pts durante el proyecto (+22%). Sprint 2 (+20), Sprint 4 (+30), Sprint 6 (+20).
    </div>
  );
}

// ─── Tab: Burndown ────────────────────────────────────────────────────────────

function BurndownTab({ projectId }) {
  const { burndown, velocity, avgVelocity, remaining, totalPoints } = useMemo(() => computeChartData(projectId), [projectId]);

  return (
    <div className="space-y-6">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
        <h3 className="text-base font-bold text-slate-900 dark:text-white mb-1">Burndown Chart</h3>
        <p className="text-sm text-slate-500 dark:text-slate-400 mb-4">Trabajo restante vs ideal — puntos de historia</p>
        <ResponsiveContainer width="100%" height={300}>
          <LineChart data={burndown} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
            <XAxis dataKey="name" tick={{ fontSize: 11, fill: '#94a3b8' }} />
            <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} />
            <Tooltip content={<CustomTooltip />} />
            <Legend wrapperStyle={{ fontSize: 12 }} />
            <ReferenceLine y={0} stroke="#10b981" strokeWidth={2} label={{ value: 'Meta', position: 'insideTopRight', fill: '#10b981', fontSize: 11 }} />
            <Line type="monotone" dataKey="ideal" name="Ideal" stroke="#94a3b8" strokeDasharray="6 3" dot={false} strokeWidth={1.5} />
            <Line type="monotone" dataKey="real" name="Real" stroke="#3b82f6" dot={{ r: 3 }} strokeWidth={2} connectNulls={false} />
            <Line type="monotone" dataKey="trend" name="Tendencia" stroke="#ef4444" strokeDasharray="4 2" dot={false} strokeWidth={1.5} connectNulls={true} />
          </LineChart>
        </ResponsiveContainer>
      </div>

      {/* Velocity table */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
        <div className="p-5 border-b border-slate-100 dark:border-slate-800">
          <h3 className="text-base font-bold text-slate-900 dark:text-white">Detalle por Sprint</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 dark:bg-slate-800/60">
              <tr>
                {['Sprint', 'Planificado', 'Completado', 'Velocidad', 'Delta'].map((h) => (
                  <th key={h} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {velocity.map((s) => (
                <tr key={s.name} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                  <td className="px-4 py-3 font-medium text-slate-700 dark:text-slate-200">{s.name}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-300">{s.planned} pts</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-300">{s.completed} pts</td>
                  <td className="px-4 py-3">
                    <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300">
                      {s.completed} pts/sprint
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
                      s.delta >= 0
                        ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300'
                        : 'bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300'
                    }`}>
                      {s.delta >= 0 ? '+' : ''}{s.delta} pts
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ─── Tab: Burnup ──────────────────────────────────────────────────────────────

function BurnupTab({ projectId }) {
  const { burnup } = useMemo(() => computeChartData(projectId), [projectId]);

  // Build cumulative table
  const table = burnup.slice(1); // skip Inicio
  let cumTotal = 0;
  const tableRows = table.map((row) => {
    const pct = row.scope > 0 ? Math.round((row.completed / row.scope) * 100) : 0;
    const inc = row.completed - (cumTotal);
    cumTotal = row.completed;
    return { ...row, increment: inc, pct };
  });

  return (
    <div className="space-y-6">
      <ScopeCreepNote projectId={projectId} />

      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
        <h3 className="text-base font-bold text-slate-900 dark:text-white mb-1">Burnup Chart</h3>
        <p className="text-sm text-slate-500 dark:text-slate-400 mb-4">Trabajo completado vs alcance total del proyecto</p>
        <ResponsiveContainer width="100%" height={300}>
          <LineChart data={burnup} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
            <XAxis dataKey="name" tick={{ fontSize: 11, fill: '#94a3b8' }} />
            <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} />
            <Tooltip content={<CustomTooltip />} />
            <Legend wrapperStyle={{ fontSize: 12 }} />
            <Line type="monotone" dataKey="scope" name="Alcance Total" stroke="#f59e0b" strokeWidth={2} dot={false} />
            <Line type="monotone" dataKey="completed" name="Completado" stroke="#10b981" strokeWidth={2} dot={{ r: 3 }} />
          </LineChart>
        </ResponsiveContainer>
      </div>

      {/* Cumulative table */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
        <div className="p-5 border-b border-slate-100 dark:border-slate-800">
          <h3 className="text-base font-bold text-slate-900 dark:text-white">Completado Acumulado</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 dark:bg-slate-800/60">
              <tr>
                {['Sprint', 'Alcance Total', 'Completado Acum.', 'Incremento', '% Avance'].map((h) => (
                  <th key={h} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {tableRows.map((row) => (
                <tr key={row.name} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                  <td className="px-4 py-3 font-medium text-slate-700 dark:text-slate-200">{row.name}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-300">{row.scope} pts</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-300">{row.completed} pts</td>
                  <td className="px-4 py-3 text-emerald-600 dark:text-emerald-400 font-medium">+{row.increment} pts</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="flex-1 bg-slate-100 dark:bg-slate-700 rounded-full h-1.5 max-w-[80px]">
                        <div
                          className="bg-emerald-500 h-1.5 rounded-full"
                          style={{ width: `${Math.min(100, row.pct)}%` }}
                        />
                      </div>
                      <span className="text-xs text-slate-600 dark:text-slate-300 font-medium">{row.pct}%</span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ─── Tab: Velocity & Predicción ───────────────────────────────────────────────

function VelocityTab({ projectId }) {
  const { velocity, avgVelocity, remaining, totalPoints, cumulativeCompleted, sprintDurationDays } = useMemo(
    () => computeChartData(projectId),
    [projectId]
  );

  const prediction = useMemo(
    () => computePrediction(projectId, remaining, avgVelocity, sprintDurationDays),
    [projectId, remaining, avgVelocity, sprintDurationDays]
  );

  const currentVelocity = velocity[velocity.length - 1]?.completed ?? 0;
  const completionPct = totalPoints > 0 ? Math.round((cumulativeCompleted / totalPoints) * 100) : 0;

  let predColor = 'green';
  let predText = '';
  if (prediction) {
    if (prediction.diffDays > 14) {
      predColor = 'red';
      predText = `${prediction.diffDays} días después de lo planificado`;
    } else if (prediction.diffDays < -14) {
      predColor = 'green';
      predText = `${Math.abs(prediction.diffDays)} días antes de lo planificado`;
    } else if (prediction.diffDays < 0) {
      predColor = 'green';
      predText = `${Math.abs(prediction.diffDays)} días antes de lo planificado`;
    } else {
      predColor = 'amber';
      predText = `${prediction.diffDays} días después de lo planificado`;
    }
  }

  return (
    <div className="space-y-6">
      {/* KPI cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <KpiCard
          label="Velocidad Promedio"
          value={`${Math.round(avgVelocity)} pts`}
          sub="por sprint (histórico)"
          color="blue"
        />
        <KpiCard
          label="Velocidad Actual"
          value={`${currentVelocity} pts`}
          sub="último sprint"
          color={currentVelocity >= avgVelocity ? 'green' : 'amber'}
        />
        <KpiCard
          label="Fecha Estimada"
          value={prediction ? formatDate(prediction.predictedEnd) : '—'}
          sub={prediction ? predText : ''}
          color={predColor}
        />
        <KpiCard
          label="Confianza"
          value={prediction ? `${prediction.confidence}%` : '—'}
          sub={`${completionPct}% completado`}
          color={prediction && prediction.confidence >= 75 ? 'green' : 'amber'}
        />
      </div>

      {/* Predictive text banner */}
      {prediction && (
        <div className={`rounded-2xl border px-5 py-4 text-sm font-medium ${
          predColor === 'green'
            ? 'bg-emerald-50 dark:bg-emerald-900/20 border-emerald-200 dark:border-emerald-700 text-emerald-800 dark:text-emerald-300'
            : predColor === 'amber'
            ? 'bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-700 text-amber-800 dark:text-amber-300'
            : 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-700 text-red-800 dark:text-red-300'
        }`}>
          A la velocidad actual de <strong>{Math.round(avgVelocity)} pts/sprint</strong>, el proyecto terminará el{' '}
          <strong>{formatDate(prediction.predictedEnd)}</strong> —{' '}
          {predText}. Faltan aproximadamente <strong>{prediction.sprintsLeft} sprints</strong> con{' '}
          <strong>{Math.round(remaining)} pts</strong> pendientes.
        </div>
      )}

      {/* Bar chart */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
        <h3 className="text-base font-bold text-slate-900 dark:text-white mb-1">Planificado vs Completado por Sprint</h3>
        <p className="text-sm text-slate-500 dark:text-slate-400 mb-4">Comparativa de velocidad sprint a sprint</p>
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={velocity} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
            <XAxis dataKey="name" tick={{ fontSize: 11, fill: '#94a3b8' }} />
            <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} />
            <Tooltip content={<CustomTooltip />} />
            <Legend wrapperStyle={{ fontSize: 12 }} />
            <Bar dataKey="planned" name="Planificado" fill="#94a3b8" radius={[4, 4, 0, 0]} />
            <Bar dataKey="completed" name="Completado" fill="#3b82f6" radius={[4, 4, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

const TABS = [
  { id: 'burndown', label: 'Burndown Chart' },
  { id: 'burnup',   label: 'Burnup Chart' },
  { id: 'velocity', label: 'Velocidad & Predicción' },
];

export default function BurndownPage() {
  const [activeTab, setActiveTab] = useState('burndown');
  const [selectedProject, setSelectedProject] = useState('p4');

  const project = MOCK_PROJECTS.find((p) => p.id === selectedProject);
  const sprintData = SPRINT_DATA[selectedProject];

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 md:p-6 lg:p-8">
      <div className="max-w-7xl mx-auto space-y-6">

        {/* Header */}
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Burndown & Burnup</h1>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">
              Seguimiento de velocidad del equipo y predicción de entrega
            </p>
          </div>

          {/* Project selector */}
          <div className="flex items-center gap-3">
            <label className="text-sm font-medium text-slate-600 dark:text-slate-300 whitespace-nowrap">
              Proyecto:
            </label>
            <select
              value={selectedProject}
              onChange={(e) => setSelectedProject(e.target.value)}
              className="border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-200 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {MOCK_PROJECTS.map((p) => (
                <option key={p.id} value={p.id}>{p.code} — {p.name}</option>
              ))}
            </select>
          </div>
        </div>

        {/* Project info banner */}
        {project && (
          <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-4 flex flex-wrap gap-6 items-center">
            <div>
              <p className="text-xs text-slate-500 dark:text-slate-400 uppercase font-semibold">Cliente</p>
              <p className="text-sm font-semibold text-slate-800 dark:text-slate-100">{project.client}</p>
            </div>
            <div>
              <p className="text-xs text-slate-500 dark:text-slate-400 uppercase font-semibold">Alcance Total</p>
              <p className="text-sm font-semibold text-slate-800 dark:text-slate-100">{sprintData?.totalPoints ?? '—'} pts</p>
            </div>
            <div>
              <p className="text-xs text-slate-500 dark:text-slate-400 uppercase font-semibold">Fin Planificado</p>
              <p className="text-sm font-semibold text-slate-800 dark:text-slate-100">
                {sprintData ? formatDate(new Date(sprintData.plannedEnd)) : '—'}
              </p>
            </div>
            <div>
              <p className="text-xs text-slate-500 dark:text-slate-400 uppercase font-semibold">Metodología</p>
              <p className="text-sm font-semibold text-slate-800 dark:text-slate-100">
                {selectedProject === 'p4' ? 'PMI / Fases semanales' : 'Scrum / Sprints 2 semanas'}
              </p>
            </div>
            {selectedProject === 'p4' && (
              <span className="ml-auto rounded-full px-2.5 py-0.5 text-xs font-medium bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400">
                En riesgo
              </span>
            )}
            {selectedProject === 'p4' && (
              <span className="ml-auto rounded-full px-2.5 py-0.5 text-xs font-medium bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400">
                En camino
              </span>
            )}
          </div>
        )}

        {/* Tabs */}
        <div className="border-b border-slate-200 dark:border-slate-700">
          <nav className="-mb-px flex gap-1">
            {TABS.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-2.5 text-sm font-medium transition-colors ${
                  activeTab === tab.id
                    ? 'border-b-2 border-blue-600 text-blue-600 dark:text-blue-400'
                    : 'border-b-2 border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </nav>
        </div>

        {/* Tab content */}
        {activeTab === 'burndown' && <BurndownTab projectId={selectedProject} />}
        {activeTab === 'burnup'   && <BurnupTab   projectId={selectedProject} />}
        {activeTab === 'velocity' && <VelocityTab projectId={selectedProject} />}
      </div>
    </div>
  );
}
