import { useState, useMemo } from 'react';
import { useProject } from '../../context/ProjectContext';

// ── Mock Data ────────────────────────────────────────────────────────────────
const PROJECTS = {
  p1: { code: 'PRY-2026-004', name: 'AR-ProjectManagement Norte', color: '#3b82f6', bg: 'bg-blue-100 dark:bg-blue-900/40', text: 'text-blue-700 dark:text-blue-300', border: 'border-blue-300 dark:border-blue-700' },
  p2: { code: 'PRY-2026-004', name: 'AR-ProjectManagement "Horizontes"', color: '#8b5cf6', bg: 'bg-purple-100 dark:bg-purple-900/40', text: 'text-purple-700 dark:text-purple-300', border: 'border-purple-300 dark:border-purple-700' },
  p3: { code: 'PRY-2026-004', name: 'Implementación AR-ProjectManagement', color: '#f59e0b', bg: 'bg-amber-100 dark:bg-amber-900/40', text: 'text-amber-700 dark:text-amber-300', border: 'border-amber-300 dark:border-amber-700' },
  p4: { code: 'PRY-2026-004', name: 'AR-ProjectManagement ERP', color: '#10b981', bg: 'bg-emerald-100 dark:bg-emerald-900/40', text: 'text-emerald-700 dark:text-emerald-300', border: 'border-emerald-300 dark:border-emerald-700' },
};

const RESOURCES = [
  {
    id: 'r1', name: 'Paula Soto', role: 'Gerente Senior', dept: 'Tecnología', avatar: 'AT', color: '#10B981',
    skills: ['Gestión', 'PMP', 'Agile', 'Presupuesto'],
    allocations: { p1: 60, p3: 20 },
  },
  {
    id: 'r2', name: 'Ricardo Mora', role: 'Desarrollador', dept: 'Tecnología', avatar: 'RM', color: '#3b82f6',
    skills: ['React', 'Node.js', 'PostgreSQL', 'Docker'],
    allocations: { p3: 80, p4: 40 },
  },
  {
    id: 'r3', name: 'Carmen Vidal', role: 'Ingeniera', dept: 'Ingeniería', avatar: 'CV', color: '#8b5cf6',
    skills: ['AutoCAD', 'BIM', 'Estructuras', 'React'],
    allocations: { p2: 50, p4: 30 },
  },
  {
    id: 'r4', name: 'Paula Soto', role: 'Arquitecto', dept: 'Diseño', avatar: 'FS', color: '#f59e0b',
    skills: ['Revit', 'SketchUp', 'Arquitectura', 'BIM'],
    allocations: { p1: 40, p4: 60 },
  },
  {
    id: 'r5', name: 'Álvaro Romero', role: 'QC Inspector', dept: 'Calidad', avatar: 'PV', color: '#ef4444',
    skills: ['ISO 9001', 'Inspección', 'Auditoría', 'QA'],
    allocations: { p1: 30, p2: 20, p3: 30 },
  },
  {
    id: 'r6', name: 'Jorge Salcedo', role: 'HSE', dept: 'Seguridad', avatar: 'JS', color: '#14b8a6',
    skills: ['OHSAS 18001', 'Riesgo', 'Normativa', 'HSE'],
    allocations: { p1: 25, p2: 25, p3: 25, p4: 25 },
  },
];

// ── Helpers ──────────────────────────────────────────────────────────────────
function getMonday(date) {
  const d = new Date(date);
  const day = d.getDay();
  const diff = d.getDate() - day + (day === 0 ? -6 : 1);
  d.setDate(diff);
  d.setHours(0, 0, 0, 0);
  return d;
}

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

function addWeeks(date, n) {
  return addDays(date, n * 7);
}

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

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

const DAY_LABELS = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];

function totalAlloc(resource, projectFilter) {
  if (projectFilter && projectFilter !== 'all') {
    return resource.allocations[projectFilter] || 0;
  }
  return Object.values(resource.allocations).reduce((a, b) => a + b, 0);
}

function getAllocColor(pct) {
  if (pct > 100) return 'bg-red-500';
  if (pct >= 80) return 'bg-amber-400';
  if (pct >= 50) return 'bg-blue-500';
  return 'bg-emerald-400';
}

function getCellBg(pct) {
  if (pct > 100) return 'bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300';
  if (pct >= 80) return 'bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300';
  if (pct >= 50) return 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300';
  if (pct > 0) return 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300';
  return 'bg-slate-50 dark:bg-slate-800/30 text-slate-400 dark:text-slate-500';
}

// ── Modals ───────────────────────────────────────────────────────────────────
function ResourceModal({ resource, day, onClose }) {
  const [form, setForm] = useState({ projectId: 'p4', pct: 50 });
  if (!resource) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 w-full max-w-md shadow-2xl">
        <h3 className="text-slate-900 dark:text-white font-bold text-lg mb-1">Asignar recurso</h3>
        <p className="text-slate-500 dark:text-slate-400 text-sm mb-4">
          {resource.name} — {DAY_LABELS[day % 7]} {formatDate(day instanceof Date ? day : new Date())}
        </p>
        <div className="space-y-4">
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1">Proyecto</label>
            <select
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm"
              value={form.projectId}
              onChange={e => setForm(f => ({ ...f, projectId: e.target.value }))}
            >
              {Object.entries(PROJECTS).map(([id, p]) => (
                <option key={id} value={id}>{p.code} — {p.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1">% Asignación</label>
            <input
              type="number" min={0} max={100}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm"
              value={form.pct}
              onChange={e => setForm(f => ({ ...f, pct: Number(e.target.value) }))}
            />
          </div>
        </div>
        <div className="flex gap-2 mt-6 justify-end">
          <button onClick={onClose} className="px-4 py-2 rounded-xl text-sm font-medium text-slate-600 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800">
            Cancelar
          </button>
          <button onClick={onClose} className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium">
            Guardar
          </button>
        </div>
      </div>
    </div>
  );
}

function AssignModal({ resource, onClose }) {
  const [form, setForm] = useState({ projectId: 'p4', pct: 25, startDate: '', endDate: '' });
  if (!resource) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 w-full max-w-md shadow-2xl">
        <h3 className="text-slate-900 dark:text-white font-bold text-lg mb-1">Asignar a proyecto</h3>
        <p className="text-slate-500 dark:text-slate-400 text-sm mb-4">{resource.name} — {resource.role}</p>
        <div className="space-y-4">
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1">Proyecto</label>
            <select
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm"
              value={form.projectId}
              onChange={e => setForm(f => ({ ...f, projectId: e.target.value }))}
            >
              {Object.entries(PROJECTS).map(([id, p]) => (
                <option key={id} value={id}>{p.code} — {p.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1">% Dedicación</label>
            <input
              type="number" min={0} max={100}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm"
              value={form.pct}
              onChange={e => setForm(f => ({ ...f, pct: Number(e.target.value) }))}
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1">Desde</label>
              <input type="date" className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm"
                value={form.startDate} onChange={e => setForm(f => ({ ...f, startDate: e.target.value }))} />
            </div>
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1">Hasta</label>
              <input type="date" className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm"
                value={form.endDate} onChange={e => setForm(f => ({ ...f, endDate: e.target.value }))} />
            </div>
          </div>
        </div>
        <div className="flex gap-2 mt-6 justify-end">
          <button onClick={onClose} className="px-4 py-2 rounded-xl text-sm font-medium text-slate-600 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800">
            Cancelar
          </button>
          <button onClick={onClose} className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium">
            Asignar
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Tab 1: Calendario Semanal ─────────────────────────────────────────────────
function WeeklyCalendar({ resources }) {
  const [weekStart, setWeekStart] = useState(() => getMonday(new Date()));
  const [modal, setModal] = useState(null); // { resource, dayDate }

  const days = Array.from({ length: 7 }, (_, i) => addDays(weekStart, i));

  const weekLabel = `${formatDate(days[0])} — ${formatDate(days[6])}`;

  return (
    <div className="space-y-4">
      {/* Navigation */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button
            onClick={() => setWeekStart(d => addWeeks(d, -1))}
            className="p-2 rounded-xl border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300"
          >
            ‹
          </button>
          <span className="text-sm font-semibold text-slate-700 dark:text-slate-200">{weekLabel}</span>
          <button
            onClick={() => setWeekStart(d => addWeeks(d, 1))}
            className="p-2 rounded-xl border border-slate-200 dark:border-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-300"
          >
            ›
          </button>
        </div>
        <button
          onClick={() => setWeekStart(getMonday(new Date()))}
          className="text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline"
        >
          Hoy
        </button>
      </div>

      {/* Grid */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-x-auto">
        <table className="w-full min-w-[700px]">
          <thead>
            <tr className="border-b border-slate-200 dark:border-slate-700">
              <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left w-40">Recurso</th>
              {days.map((d, i) => (
                <th key={i} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-2 py-3 text-center">
                  <div>{DAY_LABELS[i]}</div>
                  <div className="font-normal normal-case mt-0.5">{formatDate(d)}</div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {resources.map(r => {
              const total = totalAlloc(r, null);
              const isOverloaded = total > 100;
              return (
                <tr key={r.id} className="border-b border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div
                        className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0"
                        style={{ backgroundColor: r.color }}
                      >
                        {r.avatar}
                      </div>
                      <div>
                        <div className="text-sm font-medium text-slate-800 dark:text-slate-200">{r.name}</div>
                        <div className="text-xs text-slate-500 dark:text-slate-400">{r.role}</div>
                      </div>
                    </div>
                  </td>
                  {days.map((d, di) => {
                    const isWeekend = di >= 5;
                    return (
                      <td key={di} className={`px-1 py-2 text-center ${isWeekend ? 'bg-slate-50 dark:bg-slate-800/20' : ''}`}>
                        {isWeekend ? (
                          <div className="text-xs text-slate-300 dark:text-slate-600">—</div>
                        ) : (
                          <div
                            className="cursor-pointer group"
                            onClick={() => setModal({ resource: r, dayDate: d })}
                          >
                            {isOverloaded ? (
                              <div className="rounded-lg bg-red-100 dark:bg-red-900/40 border border-red-300 dark:border-red-700 p-1">
                                <div className="text-xs font-bold text-red-700 dark:text-red-300">{total}% ⚠</div>
                              </div>
                            ) : (
                              <div className="space-y-0.5">
                                {Object.entries(r.allocations).map(([pid, pct]) => {
                                  const proj = PROJECTS[pid];
                                  if (!proj) return null;
                                  return (
                                    <div key={pid} className={`rounded text-xs font-medium px-1 py-0.5 ${proj.bg} ${proj.text} truncate`}>
                                      {pct}%
                                    </div>
                                  );
                                })}
                              </div>
                            )}
                          </div>
                        )}
                      </td>
                    );
                  })}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Legend */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
        <div className="flex flex-wrap gap-4">
          <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase self-center">Proyectos:</span>
          {Object.entries(PROJECTS).map(([id, p]) => (
            <div key={id} className={`flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium ${p.bg} ${p.text}`}>
              <div className="w-2 h-2 rounded-full" style={{ backgroundColor: p.color }} />
              {p.code}
            </div>
          ))}
          <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase self-center ml-4">Estado:</span>
          <div className="flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300">
            ⚠ Sobrecargado (&gt;100%)
          </div>
        </div>
      </div>

      {modal && (
        <ResourceModal
          resource={modal.resource}
          day={modal.dayDate}
          onClose={() => setModal(null)}
        />
      )}
    </div>
  );
}

// ── Tab 2: Heatmap de Carga ───────────────────────────────────────────────────
function HeatmapTooltip({ resource, week }) {
  const total = totalAlloc(resource, null);
  return (
    <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl shadow-lg p-3 text-xs min-w-[160px]">
      <div className="font-bold text-slate-800 dark:text-slate-100 mb-2">{resource.name}</div>
      <div className="text-slate-500 dark:text-slate-400 mb-2">Semana {week}</div>
      {Object.entries(resource.allocations).map(([pid, pct]) => {
        const proj = PROJECTS[pid];
        if (!proj) return null;
        return (
          <div key={pid} className="flex justify-between gap-4">
            <span className={proj.text}>{proj.code}</span>
            <span className="font-semibold">{pct}%</span>
          </div>
        );
      })}
      <div className="border-t border-slate-200 dark:border-slate-700 mt-2 pt-2 flex justify-between font-bold">
        <span>Total</span>
        <span className={total > 100 ? 'text-red-600' : 'text-slate-800 dark:text-slate-100'}>{total}%</span>
      </div>
    </div>
  );
}

function WorkloadHeatmap({ resources }) {
  const [tooltip, setTooltip] = useState(null); // { resource, weekIdx, x, y }
  const weeks = Array.from({ length: 8 }, (_, i) => i + 1);
  const weekStart = getMonday(new Date());
  const weekLabels = weeks.map(w => formatMonth(addWeeks(weekStart, w - 1)));

  // Overloaded resources this week
  const overloaded = resources.filter(r => totalAlloc(r, null) > 100);

  return (
    <div className="space-y-4">
      {/* Alerts */}
      {overloaded.length > 0 && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-2xl p-4">
          <div className="flex items-center gap-2 mb-2">
            <span className="text-red-600 dark:text-red-400 font-bold text-sm">⚠ Recursos sobrecargados esta semana</span>
          </div>
          <div className="flex flex-wrap gap-2">
            {overloaded.map(r => (
              <span key={r.id} className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300">
                {r.name} — {totalAlloc(r, null)}%
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Heatmap grid */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-x-auto p-4">
        <div className="min-w-[600px]">
          {/* Header */}
          <div className="flex mb-1">
            <div className="w-44 flex-shrink-0" />
            {weekLabels.map((label, i) => (
              <div key={i} className="flex-1 text-center text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase pb-2">
                S{i + 1}<br /><span className="font-normal normal-case">{label}</span>
              </div>
            ))}
          </div>

          {/* Resource rows */}
          {resources.map(r => {
            const total = totalAlloc(r, null);
            return (
              <div key={r.id} className="flex items-center mb-1">
                <div className="w-44 flex-shrink-0 flex items-center gap-2 pr-3">
                  <div
                    className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0"
                    style={{ backgroundColor: r.color }}
                  >
                    {r.avatar}
                  </div>
                  <div className="text-xs font-medium text-slate-700 dark:text-slate-300 truncate">{r.name}</div>
                </div>
                {weeks.map((w, wi) => {
                  // Slight variation per week for visual realism
                  const variation = Math.sin(wi * 1.3 + r.id.charCodeAt(1)) * 8;
                  const pct = Math.max(0, Math.round(total + variation));
                  const cellCls = getCellBg(pct);
                  return (
                    <div
                      key={wi}
                      className={`flex-1 mx-0.5 rounded-lg h-10 flex items-center justify-center text-xs font-bold cursor-pointer transition-transform hover:scale-105 ${cellCls}`}
                      onMouseEnter={e => setTooltip({ resource: r, weekIdx: wi + 1, x: e.clientX, y: e.clientY })}
                      onMouseLeave={() => setTooltip(null)}
                    >
                      {pct}%
                    </div>
                  );
                })}
              </div>
            );
          })}

          {/* Summary row */}
          <div className="flex items-center mt-2 border-t border-slate-200 dark:border-slate-700 pt-2">
            <div className="w-44 flex-shrink-0 text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase pr-3">Equipo</div>
            {weeks.map((w, wi) => {
              const teamTotal = Math.round(resources.reduce((sum, r) => {
                const total = totalAlloc(r, null);
                const variation = Math.sin(wi * 1.3 + r.id.charCodeAt(1)) * 8;
                return sum + Math.max(0, total + variation);
              }, 0) / resources.length);
              const cellCls = getCellBg(teamTotal);
              return (
                <div key={wi} className={`flex-1 mx-0.5 rounded-lg h-8 flex items-center justify-center text-xs font-bold ${cellCls}`}>
                  {teamTotal}%
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Legend */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
        <div className="flex flex-wrap gap-3 items-center">
          <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase">Carga:</span>
          {[
            { label: '< 50%', cls: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' },
            { label: '50–80%', cls: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' },
            { label: '80–100%', cls: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' },
            { label: '> 100%', cls: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' },
          ].map(item => (
            <span key={item.label} className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${item.cls}`}>{item.label}</span>
          ))}
        </div>
      </div>

      {/* Tooltip */}
      {tooltip && (
        <div
          className="fixed z-50 pointer-events-none"
          style={{ left: tooltip.x + 12, top: tooltip.y - 10 }}
        >
          <HeatmapTooltip resource={tooltip.resource} week={tooltip.weekIdx} />
        </div>
      )}
    </div>
  );
}

// ── Tab 3: Disponibilidad ─────────────────────────────────────────────────────
function AvailabilityTab({ resources }) {
  const [skillFilter, setSkillFilter] = useState('');
  const [deptFilter, setDeptFilter] = useState('all');
  const [assignModal, setAssignModal] = useState(null);

  const allDepts = ['all', ...Array.from(new Set(resources.map(r => r.dept)))];

  const filtered = resources.filter(r => {
    const matchDept = deptFilter === 'all' || r.dept === deptFilter;
    const matchSkill = !skillFilter || r.skills.some(s => s.toLowerCase().includes(skillFilter.toLowerCase()));
    return matchDept && matchSkill;
  });

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex flex-wrap gap-3">
        <input
          type="text"
          placeholder="Buscar por habilidad..."
          className="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-800 dark:text-slate-200 px-3 py-2 text-sm w-52 focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={skillFilter}
          onChange={e => setSkillFilter(e.target.value)}
        />
        <select
          className="rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 text-slate-800 dark:text-slate-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          value={deptFilter}
          onChange={e => setDeptFilter(e.target.value)}
        >
          {allDepts.map(d => (
            <option key={d} value={d}>{d === 'all' ? 'Todos los departamentos' : d}</option>
          ))}
        </select>
      </div>

      {/* Resource cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
        {filtered.map(r => {
          const total = totalAlloc(r, null);
          const available = Math.max(0, 100 - total);
          const isOverloaded = total > 100;
          const nextAvailable = total >= 100 ? 'Próx. lunes' : null;

          return (
            <div key={r.id} className={`bg-white dark:bg-slate-900 rounded-2xl border p-5 space-y-4 ${isOverloaded ? 'border-red-300 dark:border-red-700' : 'border-slate-200 dark:border-slate-700'}`}>
              {/* Header */}
              <div className="flex items-start justify-between">
                <div className="flex items-center gap-3">
                  <div
                    className="w-10 h-10 rounded-full flex items-center justify-center text-white text-sm font-bold"
                    style={{ backgroundColor: r.color }}
                  >
                    {r.avatar}
                  </div>
                  <div>
                    <div className="font-bold text-slate-900 dark:text-white text-sm">{r.name}</div>
                    <div className="text-xs text-slate-500 dark:text-slate-400">{r.role} · {r.dept}</div>
                  </div>
                </div>
                {isOverloaded && (
                  <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300">
                    Sobrecargado
                  </span>
                )}
              </div>

              {/* Allocation bar */}
              <div>
                <div className="flex justify-between text-xs mb-1">
                  <span className="font-medium text-slate-700 dark:text-slate-300">{Math.min(total, 100)}% asignado</span>
                  <span className="text-slate-500 dark:text-slate-400">{available}% disponible</span>
                </div>
                <div className="w-full bg-slate-100 dark:bg-slate-800 rounded-full h-2.5 overflow-hidden">
                  <div
                    className={`h-2.5 rounded-full transition-all ${isOverloaded ? 'bg-red-500' : 'bg-blue-500'}`}
                    style={{ width: `${Math.min(total, 100)}%` }}
                  />
                </div>
                {isOverloaded && (
                  <div className="text-xs text-red-600 dark:text-red-400 mt-1 font-medium">
                    ⚠ Sobrecargado en {total - 100}%
                  </div>
                )}
              </div>

              {/* Project assignments */}
              <div>
                <div className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-2">Proyectos asignados</div>
                <div className="space-y-1">
                  {Object.entries(r.allocations).map(([pid, pct]) => {
                    const proj = PROJECTS[pid];
                    if (!proj) return null;
                    return (
                      <div key={pid} className="flex items-center justify-between">
                        <div className="flex items-center gap-1.5">
                          <div className="w-2 h-2 rounded-full" style={{ backgroundColor: proj.color }} />
                          <span className="text-xs text-slate-600 dark:text-slate-300">{proj.code}</span>
                        </div>
                        <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${proj.bg} ${proj.text}`}>{pct}%</span>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Skills */}
              <div>
                <div className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-2">Habilidades</div>
                <div className="flex flex-wrap gap-1">
                  {r.skills.map(s => (
                    <span key={s} className="rounded-full px-2 py-0.5 text-xs font-medium bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300">
                      {s}
                    </span>
                  ))}
                </div>
              </div>

              {/* Next available */}
              {nextAvailable && (
                <div className="text-xs text-slate-500 dark:text-slate-400">
                  Próxima disponibilidad: <span className="font-medium text-slate-700 dark:text-slate-300">{nextAvailable}</span>
                </div>
              )}

              {/* Action */}
              <button
                onClick={() => setAssignModal(r)}
                className="w-full bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors"
              >
                Asignar a proyecto
              </button>
            </div>
          );
        })}
      </div>

      {assignModal && (
        <AssignModal resource={assignModal} onClose={() => setAssignModal(null)} />
      )}
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────
export default function ResourceCalendarPage() {
  const { selectedProjectId } = useProject();
  const [activeTab, setActiveTab] = useState('weekly');

  const filteredResources = useMemo(() => {
    if (!selectedProjectId) return RESOURCES;
    return RESOURCES.filter(r => Object.keys(r.allocations).includes(selectedProjectId));
  }, [selectedProjectId]);

  const tabs = [
    { id: 'weekly', label: 'Calendario Semanal' },
    { id: 'heatmap', label: 'Heatmap de Carga' },
    { id: 'availability', label: 'Disponibilidad' },
  ];

  const overloadedCount = filteredResources.filter(r => totalAlloc(r, null) > 100).length;

  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 items-start justify-between flex-wrap gap-4">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Calendario de Recursos</h1>
            <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">
              Planificación visual de disponibilidad y carga de trabajo
            </p>
          </div>
          <div className="flex items-center gap-3">
            {overloadedCount > 0 && (
              <span className="rounded-full px-3 py-1 text-sm font-medium bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300">
                ⚠ {overloadedCount} recurso{overloadedCount > 1 ? 's' : ''} sobrecargado{overloadedCount > 1 ? 's' : ''}
              </span>
            )}
            <span className="text-sm text-slate-500 dark:text-slate-400">
              {filteredResources.length} recurso{filteredResources.length !== 1 ? 's' : ''}
            </span>
          </div>
        </div>

        {/* Tabs */}
        <div className="border-b border-slate-200 dark:border-slate-700">
          <nav className="flex gap-0">
            {tabs.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-5 py-3 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 === 'weekly' && <WeeklyCalendar resources={filteredResources} />}
        {activeTab === 'heatmap' && <WorkloadHeatmap resources={filteredResources} />}
        {activeTab === 'availability' && <AvailabilityTab resources={filteredResources} />}
      </div>
    </div>
  );
}
