import React, { useState, useMemo, useCallback } from 'react';
import { MOCK_TEAM, MOCK_EQUIPMENT, MOCK_PROJECTS } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';

// ── Helpers ────────────────────────────────────────────────────────────────────
// Auto-compute resource status from tasks: INACTIVO only when no active or pending tasks
const computeStatus = (member) => {
  const t = member.tasks || {};
  const active = (t.EN_PROCESO || 0) + (t.PENDIENTE || 0) + (t.BLOQUEADA || 0);
  return active > 0 ? 'ACTIVO' : 'INACTIVO';
};

const fmtUSD  = n => `$${Number(n).toLocaleString('en-US', { minimumFractionDigits: 0 })}`;
const fmtRate = (r, t) => {
  const labels = { HORA:'/ hr', DIA:'/ día', SEMANA:'/ sem', MES:'/ mes', FIJO:'fijo' };
  return `${fmtUSD(r)} ${labels[t] || ''}`;
};

const COST_COLORS = {
  HORA: 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300',
  DIA:  'bg-teal-100 text-teal-700 dark:bg-teal-500/20 dark:text-teal-300',
  SEMANA: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-500/20 dark:text-cyan-300',
  MES:  'bg-violet-100 text-violet-700 dark:bg-violet-500/20 dark:text-violet-300',
  FIJO: 'bg-slate-100 text-slate-600 dark:bg-gray-500/20 dark:text-gray-400',
};
const STATUS_COLORS = {
  ACTIVO:   'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400',
  INACTIVO: 'bg-slate-100 text-slate-500 dark:bg-gray-500/20 dark:text-gray-500',
  EN_USO:   'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-400',
};
const TYPE_ICON = {
  HUMANO:      <PeopleIcon />,
  EQUIPO:      <EquipmentIcon />,
  MATERIAL:    <MaterialIcon />,
  SUBCONTRATO: <ContractIcon />,
};

// ── Small icons ────────────────────────────────────────────────────────────────
function PeopleIcon()    { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/></svg>; }
function EquipmentIcon() { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>; }
function MaterialIcon()  { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/></svg>; }
function ContractIcon()  { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 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>; }
function AllIcon()       { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>; }
function ChartBarIcon()  { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>; }
function AddIcon()       { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"/></svg>; }
function SearchIcon()    { return <svg className="w-3.5 h-3.5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="11" cy="11" r="8"/><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35"/></svg>; }
function CalendarIcon()  { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>; }
function GridIcon()      { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M3 10h18M3 14h18M10 3v18M14 3v18"/></svg>; }
function TagIcon()       { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"/></svg>; }
function ChevronLeftIcon()  { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7"/></svg>; }
function ChevronRightIcon() { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7"/></svg>; }
function PencilIcon()    { return <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>; }
function XIcon()         { return <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>; }

// ── Sub-components ─────────────────────────────────────────────────────────────
function Badge({ label, color }) {
  return <span className={`text-xs px-2 py-0.5 rounded-full font-medium whitespace-nowrap ${color}`}>{label}</span>;
}

function Avatar({ member }) {
  return (
    <div className="w-7 h-7 rounded-full font-bold flex items-center justify-center flex-shrink-0 text-xs"
      style={{ background: (member?.color || '#2563eb') + '22', color: member?.color || '#2563eb' }}
      title={`${member?.firstName} ${member?.lastName}`}>
      {member?.avatar}
    </div>
  );
}

function CapacityBar({ used, total }) {
  const pct  = total > 0 ? Math.min(100, Math.round((used / total) * 100)) : 0;
  const over = pct >= 100;
  const warn = pct >= 85 && !over;
  const color = over ? '#EF4444' : warn ? '#F59E0B' : '#10B981';
  return (
    <div className="flex items-center gap-2 min-w-[100px]">
      <div className="flex-1 h-1.5 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
        <div className="h-full rounded-full transition-all" style={{ width: `${pct}%`, background: color }} />
      </div>
      <span className="text-xs tabular-nums font-semibold w-9 text-right" style={{ color }}>
        {pct}%
      </span>
    </div>
  );
}

// ── Detail drawer ─────────────────────────────────────────────────────────────
function ResourceDrawer({ resource, onClose, onDelete, onUpdateMember, allProjects }) {
  if (!resource) return null;
  const isHuman = resource.resourceType === 'HUMANO';
  const [editingProjects, setEditingProjects] = useState(false);
  const [selectedProjects, setSelectedProjects] = useState(resource.projects || []);

  const toggleProject = (code) => {
    setSelectedProjects(prev =>
      prev.includes(code) ? prev.filter(c => c !== code) : [...prev, code]
    );
  };

  const saveProjects = () => {
    onUpdateMember?.({ ...resource, projects: selectedProjects });
    setEditingProjects(false);
  };

  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div className="w-full max-w-md h-full bg-white dark:bg-surface-800 shadow-2xl border-l border-slate-200 dark:border-surface-700 flex flex-col overflow-y-auto"
        onClick={e => e.stopPropagation()}>

        {/* Header */}
        <div className="flex items-start justify-between px-6 py-5 border-b border-slate-100 dark:border-surface-700">
          <div className="flex items-center gap-3">
            {isHuman ? (
              <div className="w-10 h-10 rounded-full font-bold flex items-center justify-center text-sm flex-shrink-0"
                style={{ background: (resource.color || '#2563eb') + '22', color: resource.color || '#2563eb' }}>
                {resource.avatar}
              </div>
            ) : (
              <div className="w-10 h-10 rounded-xl bg-slate-100 dark:bg-surface-700 flex items-center justify-center flex-shrink-0 text-slate-500 dark:text-gray-400">
                {TYPE_ICON[resource.resourceType]}
              </div>
            )}
            <div>
              <h2 className="text-base font-bold text-slate-900 dark:text-white leading-tight">
                {isHuman ? `${resource.firstName} ${resource.lastName}` : resource.name}
              </h2>
              <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">
                {isHuman ? resource.title : resource.category}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-1">
            <button onClick={() => { if (window.confirm('¿Eliminar este recurso?')) onDelete?.(resource.id); }}
              className="p-2 rounded-xl text-red-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-500/10 transition cursor-pointer"
              title="Eliminar recurso">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
            </button>
            <button onClick={onClose}
              className="p-2 rounded-xl text-slate-400 hover:text-slate-600 dark:hover:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 transition cursor-pointer">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 px-6 py-5 space-y-5">

          {/* Cost info */}
          <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
            <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-3">Tarifa de costo</p>
            <div className="flex items-end gap-2">
              <span className="text-2xl font-bold text-slate-900 dark:text-white">{fmtUSD(resource.costRate)}</span>
              <span className="text-sm text-slate-400 dark:text-gray-500 mb-0.5">
                {resource.costType === 'HORA' ? '/ hr' : resource.costType === 'DIA' ? '/ día' : resource.costType === 'MES' ? '/ mes' : resource.costType === 'SEMANA' ? '/ sem' : '(fijo)'}
              </span>
              <span className="ml-auto text-xs font-semibold text-slate-500 dark:text-gray-400">{resource.currency}</span>
            </div>
          </div>

          {/* Human-specific */}
          {isHuman && (
            <>
              <div>
                <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-2">Información de contacto</p>
                <div className="space-y-1.5 text-sm">
                  <div className="flex items-center gap-2 text-slate-600 dark:text-gray-300">
                    <svg className="w-4 h-4 text-slate-300 dark:text-gray-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                    {resource.email}
                  </div>
                  <div className="flex items-center gap-2 text-slate-600 dark:text-gray-300">
                    <svg className="w-4 h-4 text-slate-300 dark:text-gray-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/></svg>
                    {resource.phone}
                  </div>
                </div>
              </div>

              <div>
                <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-2">Horario laboral</p>
                <div className="grid grid-cols-2 gap-2 text-xs text-slate-600 dark:text-gray-300">
                  <div className="bg-slate-50 dark:bg-surface-700 rounded-lg p-2.5">
                    <p className="text-slate-400 dark:text-gray-500 mb-0.5">Entrada / Salida</p>
                    <p className="font-semibold">{resource.startTime} – {resource.endTime}</p>
                  </div>
                  <div className="bg-slate-50 dark:bg-surface-700 rounded-lg p-2.5">
                    <p className="text-slate-400 dark:text-gray-500 mb-0.5">Capacidad semanal</p>
                    <p className="font-semibold">{resource.capacityHrsWeek} hrs</p>
                  </div>
                </div>
                <div className="flex gap-1 mt-2">
                  {['Lun','Mar','Mié','Jue','Vie','Sáb','Dom'].map(d => (
                    <div key={d} className={`flex-1 rounded py-1 text-center text-xs font-medium ${
                      resource.workDays?.includes(d)
                        ? 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400'
                        : 'bg-slate-100 text-slate-300 dark:bg-surface-700 dark:text-gray-600'
                    }`}>{d[0]}</div>
                  ))}
                </div>
              </div>

              <div>
                <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-2">Habilidades</p>
                <div className="flex flex-wrap gap-1.5">
                  {(resource.skills || []).map(s => (
                    <span key={s} className="text-xs px-2.5 py-1 rounded-lg bg-slate-100 dark:bg-surface-700 text-slate-600 dark:text-gray-300 font-medium">{s}</span>
                  ))}
                </div>
              </div>

              <div>
                <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-2">Tareas</p>
                <div className="grid grid-cols-2 gap-2">
                  {[
                    { label:'Completadas', val: resource.tasks?.COMPLETADA || 0, color:'text-emerald-600 dark:text-emerald-400' },
                    { label:'En proceso',  val: resource.tasks?.EN_PROCESO  || 0, color:'text-blue-600 dark:text-blue-400' },
                    { label:'Pendientes',  val: resource.tasks?.PENDIENTE   || 0, color:'text-slate-500 dark:text-gray-400' },
                    { label:'Bloqueadas',  val: resource.tasks?.BLOQUEADA   || 0, color:'text-red-500' },
                  ].map(({ label, val, color }) => (
                    <div key={label} className="bg-slate-50 dark:bg-surface-700 rounded-lg p-2.5 text-center">
                      <p className={`text-lg font-bold ${color}`}>{val}</p>
                      <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{label}</p>
                    </div>
                  ))}
                </div>
              </div>

              <div>
                <div className="flex items-center justify-between mb-2">
                  <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider">Proyectos asignados</p>
                  {onUpdateMember && !editingProjects && (
                    <button onClick={() => setEditingProjects(true)}
                      className="text-xs text-blue-600 dark:text-blue-400 hover:underline cursor-pointer">Editar</button>
                  )}
                </div>
                {editingProjects ? (
                  <div className="space-y-2">
                    {(allProjects || []).map(p => (
                      <label key={p.id} className="flex items-center gap-2 cursor-pointer">
                        <input type="checkbox" checked={selectedProjects.includes(p.code)}
                          onChange={() => toggleProject(p.code)}
                          className="rounded border-slate-300 text-blue-600 focus:ring-blue-500"/>
                        <span className="font-mono text-xs text-slate-600 dark:text-gray-300">{p.code}</span>
                        <span className="text-xs text-slate-400 dark:text-gray-500 truncate">{p.name}</span>
                      </label>
                    ))}
                    <div className="flex gap-2 pt-1">
                      <button onClick={saveProjects}
                        className="flex-1 py-1.5 text-xs rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-medium cursor-pointer">Guardar</button>
                      <button onClick={() => { setEditingProjects(false); setSelectedProjects(resource.projects || []); }}
                        className="flex-1 py-1.5 text-xs rounded-lg border border-slate-200 dark:border-surface-600 text-slate-500 cursor-pointer">Cancelar</button>
                    </div>
                  </div>
                ) : (
                  <div className="flex flex-wrap gap-1.5">
                    {(resource.projects || []).length > 0
                      ? (resource.projects || []).map(code => (
                          <span key={code} className="font-mono text-xs bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded-lg px-2.5 py-1">{code}</span>
                        ))
                      : <span className="text-xs text-slate-400 dark:text-gray-500">Sin proyectos asignados</span>
                    }
                  </div>
                )}
              </div>
            </>
          )}

          {/* Equipment / Material / Contract-specific */}
          {!isHuman && (
            <>
              <div>
                <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-2">Proveedor / Vendor</p>
                <p className="text-sm text-slate-700 dark:text-gray-300">{resource.vendor || '—'}</p>
              </div>
              {resource.notes && (
                <div>
                  <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-2">Notas</p>
                  <p className="text-sm text-slate-600 dark:text-gray-400 leading-relaxed">{resource.notes}</p>
                </div>
              )}
              {resource.unit && (
                <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-3">
                  <p className="text-xs text-slate-400 dark:text-gray-500">Unidad de medida</p>
                  <p className="text-sm font-semibold text-slate-800 dark:text-gray-200 mt-0.5">{resource.unit}</p>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ── ResourceEditModal ─────────────────────────────────────────────────────────
const ROLES_OPTS = ['PROJECT_MANAGER','DEVELOPER','DESIGNER','ANALYST','QA','DEVOPS','FINANCE','ADMIN','OTHER'];
const COST_TYPES = ['FIJO','VARIABLE','MIXTO'];
const DEPT_OPTS  = ['Gerencia','Tecnología','Diseño','Finanzas','Operaciones','Calidad','RRHH','Otro'];

function ResourceEditModal({ resource, onClose, onSave }) {
  const isEdit = !!resource;
  const [f, setF] = useState({
    firstName:       resource?.firstName       || '',
    lastName:        resource?.lastName        || '',
    title:           resource?.title           || '',
    email:           resource?.email           || '',
    dept:            resource?.dept            || 'Tecnología',
    role:            resource?.role            || 'DEVELOPER',
    costRate:        resource?.costRate        || 0,
    costType:        resource?.costType        || 'FIJO',
    capacityHrsWeek: resource?.capacityHrsWeek || 40,
    skills:          (resource?.skills || []).join(', '),
    avatar:          resource?.avatar          || '',
  });
  const set = (k, v) => setF(prev => ({ ...prev, [k]: v }));
  const [err, setErr] = useState('');

  const handleSave = () => {
    if (!f.firstName.trim() || !f.lastName.trim()) { setErr('Nombre y apellido son obligatorios.'); return; }
    const skillsArr = f.skills.split(',').map(s => s.trim()).filter(Boolean);
    const avatar    = f.avatar.trim() || `${f.firstName[0]}${f.lastName[0]}`.toUpperCase();
    const updated = {
      ...(resource || {}),
      id:              resource?.id || `u_${Date.now()}`,
      resourceType:    'HUMANO',
      firstName:       f.firstName.trim(),
      lastName:        f.lastName.trim(),
      title:           f.title.trim(),
      email:           f.email.trim(),
      dept:            f.dept,
      role:            f.role,
      costRate:        Number(f.costRate) || 0,
      costType:        f.costType,
      capacityHrsWeek: Number(f.capacityHrsWeek) || 40,
      skills:          skillsArr,
      avatar,
      color:           resource?.color || '#2563eb',
      projects:        resource?.projects || [],
      allocatedHrs:    resource?.allocatedHrs || {},
      tasks:           resource?.tasks || {},
    };
    onSave(updated);
  };

  const FLD = 'w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500';

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm" onClick={onClose}>
      <div className="w-full max-w-lg bg-white dark:bg-surface-800 rounded-2xl shadow-2xl border border-slate-200 dark:border-surface-700 overflow-y-auto max-h-[90vh]"
        onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-5 border-b border-slate-100 dark:border-surface-700">
          <h2 className="text-base font-bold text-slate-900 dark:text-white">{isEdit ? 'Editar recurso humano' : 'Nuevo recurso humano'}</h2>
          <button onClick={onClose} className="p-2 rounded-xl text-slate-400 hover:text-slate-600 hover:bg-slate-100 dark:hover:bg-surface-700 cursor-pointer">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>
        <div className="p-6 space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Nombre *</label>
              <input className={FLD} value={f.firstName} onChange={e => set('firstName', e.target.value)} placeholder="Álvaro"/>
            </div>
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Apellido *</label>
              <input className={FLD} value={f.lastName}  onChange={e => set('lastName',  e.target.value)} placeholder="Romero"/>
            </div>
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Cargo / Título</label>
            <input className={FLD} value={f.title} onChange={e => set('title', e.target.value)} placeholder="CEO & Lead Developer"/>
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Email</label>
            <input className={FLD} type="email" value={f.email} onChange={e => set('email', e.target.value)} placeholder="nombre@empresa.com"/>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Departamento</label>
              <select className={FLD} value={f.dept} onChange={e => set('dept', e.target.value)}>
                {DEPT_OPTS.map(d => <option key={d}>{d}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Rol</label>
              <select className={FLD} value={f.role} onChange={e => set('role', e.target.value)}>
                {ROLES_OPTS.map(r => <option key={r} value={r}>{r.replace(/_/g,' ')}</option>)}
              </select>
            </div>
          </div>
          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Tarifa/hr (USD)</label>
              <input className={FLD} type="number" min="0" value={f.costRate} onChange={e => set('costRate', e.target.value)}/>
            </div>
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Tipo tarifa</label>
              <select className={FLD} value={f.costType} onChange={e => set('costType', e.target.value)}>
                {COST_TYPES.map(c => <option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Cap. hr/semana</label>
              <input className={FLD} type="number" min="1" max="80" value={f.capacityHrsWeek} onChange={e => set('capacityHrsWeek', e.target.value)}/>
            </div>
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Habilidades (separadas por coma)</label>
            <input className={FLD} value={f.skills} onChange={e => set('skills', e.target.value)} placeholder="React, Node.js, Diseño UX"/>
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-gray-400 mb-1">Iniciales avatar (ej. AR)</label>
            <input className={FLD} maxLength={3} value={f.avatar} onChange={e => set('avatar', e.target.value.toUpperCase())} placeholder="Auto"/>
          </div>
          {err && <p className="text-xs text-red-600 dark:text-red-400">{err}</p>}
          <div className="flex gap-2 pt-2">
            <button onClick={onClose} className="flex-1 py-2.5 text-sm rounded-xl border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-surface-700 cursor-pointer">Cancelar</button>
            <button onClick={handleSave} className="flex-1 py-2.5 text-sm rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-medium cursor-pointer">{isEdit ? 'Guardar cambios' : 'Crear recurso'}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Tab: Recursos Humanos ─────────────────────────────────────────────────────
function TabHumanos({ members, onSelect, onSaveMember }) {
  const [search,     setSearch]    = useState('');
  const [sortBy,     setSortBy]    = useState('name');
  const [showInact,  setShowInact] = useState(false);
  const [editModal,  setEditModal] = useState(null); // null | false (new) | member obj (edit)

  const filtered = useMemo(() => {
    let list = members
      .map(m => ({ ...m, _status: computeStatus(m) }))
      .filter(m => showInact ? m._status === 'INACTIVO' : m._status === 'ACTIVO')
      .filter(m =>
        !search || `${m.firstName} ${m.lastName} ${m.dept} ${m.title} ${(m.skills||[]).join(' ')}`.toLowerCase().includes(search.toLowerCase())
      );
    if (sortBy === 'name')  list = list.sort((a, b) => a.firstName.localeCompare(b.firstName));
    if (sortBy === 'cost')  list = list.sort((a, b) => b.costRate - a.costRate);
    if (sortBy === 'dept')  list = list.sort((a, b) => a.dept.localeCompare(b.dept));
    return list;
  }, [members, search, sortBy]);

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2 flex-1">
          <div className="relative flex-1 max-w-xs">
            <span className="absolute left-3 top-1/2 -translate-y-1/2"><SearchIcon /></span>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar recurso humano..."
              className="w-full pl-8 pr-3 py-2 text-sm rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-gray-200 placeholder-slate-300 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
          </div>
          <select value={sortBy} onChange={e => setSortBy(e.target.value)}
            className="text-sm bg-white dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-xl px-3 py-2 text-slate-600 dark:text-gray-300 cursor-pointer focus:outline-none focus:ring-1 focus:ring-blue-500">
            <option value="name">Ordenar: Nombre</option>
            <option value="cost">Ordenar: Tarifa ↓</option>
            <option value="dept">Ordenar: Depto.</option>
          </select>
        </div>
        <button onClick={() => setShowInact(p => !p)}
          className={`px-4 py-2 text-sm font-medium rounded-xl border transition cursor-pointer ${showInact ? 'bg-slate-700 text-white border-slate-600' : 'border-slate-200 dark:border-surface-600 text-slate-500 dark:text-gray-400 hover:border-slate-300'}`}>
          {showInact ? 'Ver activos' : 'Ver inactivos'}
        </button>
        <button onClick={() => setEditModal(false)}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer">
          <AddIcon /> Agregar recurso
        </button>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-100 dark:border-surface-700">
              {['Recurso','Estado','Departamento','Rol','Tarifa','Capacidad','Asignación actual','Proyectos','Habilidades',''].map(h => (
                <th key={h} className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4 whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700/50">
            {filtered.map(m => {
              const effectiveStatus = computeStatus(m);
              const totalAllocated = Object.values(m.allocatedHrs || {}).reduce((s, h) => s + h, 0);
              const cap = m.capacityHrsWeek || 40;
              return (
                <tr key={m.id} onClick={() => onSelect(m)}
                  className="hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors cursor-pointer">
                  <td className="py-3 pr-4">
                    <div className="flex items-center gap-2.5">
                      <Avatar member={m} />
                      <div>
                        <p className="font-semibold text-slate-800 dark:text-gray-200">{m.firstName} {m.lastName}</p>
                        <p className="text-xs text-slate-400 dark:text-gray-500">{m.title}</p>
                      </div>
                    </div>
                  </td>
                  <td className="py-3 pr-4">
                    <Badge label={effectiveStatus} color={STATUS_COLORS[effectiveStatus] || STATUS_COLORS.INACTIVO} />
                  </td>
                  <td className="py-3 pr-4 text-slate-600 dark:text-gray-300 text-xs">{m.dept}</td>
                  <td className="py-3 pr-4">
                    <span className="text-xs text-slate-500 dark:text-gray-400 bg-slate-100 dark:bg-surface-700 rounded-md px-2 py-0.5">
                      {m.role?.replace(/_/g, ' ')}
                    </span>
                  </td>
                  <td className="py-3 pr-4 font-mono text-xs font-semibold text-slate-700 dark:text-gray-300 whitespace-nowrap">
                    {fmtUSD(m.costRate)}
                  </td>
                  <td className="py-3 pr-4">
                    <Badge label={m.costType} color={COST_COLORS[m.costType] || COST_COLORS.FIJO} />
                  </td>
                  <td className="py-3 pr-4 text-xs text-slate-500 dark:text-gray-400 whitespace-nowrap">
                    {cap} hrs/sem
                  </td>
                  <td className="py-3 pr-4">
                    <CapacityBar used={totalAllocated} total={cap} />
                    <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{totalAllocated}/{cap} hr</p>
                  </td>
                  <td className="py-3 pr-4">
                    <div className="flex flex-wrap gap-1">
                      {(m.projects || []).map(code => (
                        <span key={code} className="font-mono text-xs bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded px-1.5 py-0.5">{code}</span>
                      ))}
                    </div>
                  </td>
                  <td className="py-3 pr-4">
                    <div className="flex flex-wrap gap-1">
                      {(m.skills || []).slice(0, 3).map(s => (
                        <span key={s} className="text-xs bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 rounded px-1.5 py-0.5">{s}</span>
                      ))}
                      {(m.skills || []).length > 3 && (
                        <span className="text-xs text-slate-400 dark:text-gray-500">+{m.skills.length - 3}</span>
                      )}
                    </div>
                  </td>
                  <td className="py-3">
                    <div className="flex items-center gap-1">
                      <button onClick={e => { e.stopPropagation(); onSelect(m); }}
                        className="text-xs px-2.5 py-1.5 rounded-lg bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 hover:bg-blue-50 dark:hover:bg-blue-500/10 hover:text-blue-600 dark:hover:text-blue-400 transition font-medium cursor-pointer whitespace-nowrap">
                        Ver
                      </button>
                      <button onClick={e => { e.stopPropagation(); setEditModal(m); }}
                        className="text-xs px-2.5 py-1.5 rounded-lg bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 hover:bg-amber-50 dark:hover:bg-amber-500/10 hover:text-amber-600 dark:hover:text-amber-400 transition font-medium cursor-pointer whitespace-nowrap">
                        Editar
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      {editModal !== null && (
        <ResourceEditModal
          resource={editModal || null}
          onClose={() => setEditModal(null)}
          onSave={m => { onSaveMember?.(m); setEditModal(null); }}
        />
      )}
    </div>
  );
}

// ── Tab: Equipos & Materiales ─────────────────────────────────────────────────
function TabEquipos({ equipment, onSelect }) {
  const [search, setSearch]   = useState('');
  const [typeFilter, setType] = useState('ALL');

  const filtered = useMemo(() => {
    return equipment.filter(e => {
      const matchType   = typeFilter === 'ALL' || e.resourceType === typeFilter;
      const matchSearch = !search || `${e.name} ${e.category} ${e.vendor || ''} ${e.project || ''}`.toLowerCase().includes(search.toLowerCase());
      return matchType && matchSearch;
    });
  }, [equipment, search, typeFilter]);

  const TYPES = [
    { id:'ALL',         label:'Todos',        Icon: AllIcon },
    { id:'EQUIPO',      label:'Equipos',      Icon: EquipmentIcon },
    { id:'MATERIAL',    label:'Materiales',   Icon: MaterialIcon },
    { id:'SUBCONTRATO', label:'Subcontratos', Icon: ContractIcon },
  ];

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3 flex-wrap">
        <div className="flex gap-1">
          {TYPES.map(({ id, label, Icon }) => (
            <button key={id} onClick={() => setType(id)}
              className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg transition cursor-pointer ${
                typeFilter === id
                  ? 'bg-blue-600 text-white'
                  : 'bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 hover:bg-slate-200 dark:hover:bg-surface-600'
              }`}>
              <Icon /> {label}
            </button>
          ))}
        </div>
        <div className="relative flex-1 max-w-xs ml-auto">
          <span className="absolute left-3 top-1/2 -translate-y-1/2"><SearchIcon /></span>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar equipo / material..."
            className="w-full pl-8 pr-3 py-2 text-sm rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-gray-200 placeholder-slate-300 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
        </div>
        <button className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer">
          <AddIcon /> Agregar
        </button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
        {filtered.map(eq => (
          <div key={eq.id} onClick={() => onSelect(eq)}
            className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600 hover:border-blue-200 dark:hover:border-blue-500/30 transition-colors cursor-pointer group">
            <div className="flex items-start justify-between gap-2 mb-3">
              <div className="flex items-center gap-2.5">
                <div className="w-8 h-8 rounded-lg bg-white dark:bg-surface-600 border border-slate-200 dark:border-surface-500 flex items-center justify-center text-slate-500 dark:text-gray-400">
                  {TYPE_ICON[eq.resourceType]}
                </div>
                <div>
                  <p className="text-sm font-semibold text-slate-900 dark:text-white leading-snug group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">{eq.name}</p>
                  <p className="text-xs text-slate-400 dark:text-gray-500">{eq.category}</p>
                </div>
              </div>
              <Badge label={eq.status || 'ACTIVO'} color={STATUS_COLORS[eq.status] || STATUS_COLORS.ACTIVO} />
            </div>

            <div className="space-y-1.5 text-xs">
              <div className="flex justify-between items-center">
                <span className="text-slate-400 dark:text-gray-500">Tarifa</span>
                <span className="font-mono font-semibold text-slate-700 dark:text-gray-300">
                  {fmtRate(eq.costRate, eq.costType)}
                </span>
              </div>
              {eq.project && (
                <div className="flex justify-between items-center">
                  <span className="text-slate-400 dark:text-gray-500">Proyecto</span>
                  <span className="font-mono text-xs bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded px-1.5 py-0.5">{eq.project}</span>
                </div>
              )}
              {eq.vendor && (
                <div className="flex justify-between items-center">
                  <span className="text-slate-400 dark:text-gray-500">Vendor</span>
                  <span className="text-slate-600 dark:text-gray-300 truncate max-w-[140px] text-right">{eq.vendor}</span>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Tab: Carga (Capacity) ─────────────────────────────────────────────────────
function TabCarga({ members }) {
  const projects = MOCK_PROJECTS;

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2 bg-blue-50 dark:bg-blue-500/10 border border-blue-100 dark:border-blue-500/20 rounded-xl px-4 py-2.5">
        <svg className="w-4 h-4 text-blue-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        <p className="text-xs text-blue-700 dark:text-blue-300">
          Vista de capacidad semanal. Verde ≤ 84%, Amarillo 85–99%, Rojo ≥ 100% (sobrecargado).
        </p>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-100 dark:border-surface-700">
              <th className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4 whitespace-nowrap">Recurso</th>
              <th className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4 whitespace-nowrap">Capacidad</th>
              {projects.map(p => (
                <th key={p.id} className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4 whitespace-nowrap">
                  <span className="font-mono text-blue-500">{p.code.slice(-3)}</span>
                </th>
              ))}
              <th className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4 whitespace-nowrap">Total asig.</th>
              <th className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3">Carga</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700/50">
            {members.map(m => {
              const cap   = m.capacityHrsWeek || 40;
              const total = Object.values(m.allocatedHrs || {}).reduce((s, h) => s + h, 0);
              const pct   = cap > 0 ? Math.min(100, Math.round((total / cap) * 100)) : 0;
              const color = pct >= 100 ? 'text-red-500' : pct >= 85 ? 'text-amber-500' : 'text-emerald-600 dark:text-emerald-400';

              return (
                <tr key={m.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors">
                  <td className="py-3 pr-4">
                    <div className="flex items-center gap-2">
                      <Avatar member={m} />
                      <div>
                        <p className="text-sm font-medium text-slate-800 dark:text-gray-200">{m.firstName} {m.lastName}</p>
                        <p className="text-xs text-slate-400 dark:text-gray-500">{m.dept}</p>
                      </div>
                    </div>
                  </td>
                  <td className="py-3 pr-4 text-xs text-slate-500 dark:text-gray-400">{cap} hr/sem</td>
                  {projects.map(p => {
                    const hrs = m.allocatedHrs?.[p.code] || 0;
                    const bar = cap > 0 ? Math.round((hrs / cap) * 100) : 0;
                    return (
                      <td key={p.id} className="py-3 pr-4">
                        {hrs > 0 ? (
                          <div className="min-w-[70px]">
                            <div className="h-1.5 rounded-full bg-slate-100 dark:bg-surface-700 overflow-hidden mb-1">
                              <div className="h-full rounded-full bg-blue-400" style={{ width: `${bar}%` }} />
                            </div>
                            <span className="text-xs text-slate-600 dark:text-gray-300">{hrs} hr</span>
                          </div>
                        ) : (
                          <span className="text-xs text-slate-200 dark:text-gray-700">—</span>
                        )}
                      </td>
                    );
                  })}
                  <td className={`py-3 pr-4 text-sm font-bold tabular-nums ${color}`}>{total} hr</td>
                  <td className="py-3"><CapacityBar used={total} total={cap} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>

        {/* Legend de proyectos */}
        <div className="mt-4 flex gap-3 flex-wrap">
          {projects.map(p => (
            <div key={p.id} className="flex items-center gap-1.5 text-xs text-slate-500 dark:text-gray-400">
              <span className="font-mono font-bold text-blue-500">{p.code.slice(-3)}</span>
              <span>=</span>
              <span>{p.name}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Tab: Costo Total ───────────────────────────────────────────────────────────
function TabCosto({ members, equipment }) {
  const humanCost  = members.reduce((sum, m) => {
    const hrs = Object.values(m.allocatedHrs || {}).reduce((s, h) => s + h, 0);
    if (m.costType === 'HORA') return sum + hrs * m.costRate;
    if (m.costType === 'MES')  return sum + m.costRate;
    return sum + m.costRate;
  }, 0);

  const equipCost  = equipment
    .filter(e => e.resourceType === 'EQUIPO' || e.resourceType === 'MATERIAL')
    .reduce((s, e) => s + (e.costRate || 0), 0);

  const subCost    = equipment
    .filter(e => e.resourceType === 'SUBCONTRATO')
    .reduce((s, e) => s + (e.costRate || 0), 0);

  const totalCost  = humanCost + equipCost + subCost;

  const byProject  = MOCK_PROJECTS.map(p => {
    const mCost = members.reduce((sum, m) => {
      const hrs = m.allocatedHrs?.[p.code] || 0;
      if (!hrs) return sum;
      if (m.costType === 'HORA') return sum + hrs * m.costRate;
      if (m.costType === 'MES')  return sum + (m.projects?.includes(p.code) ? m.costRate : 0);
      return sum;
    }, 0);
    const eCost = equipment.filter(e => e.project === p.code).reduce((s, e) => s + (e.costRate || 0), 0);
    return { project: p, mCost, eCost, total: mCost + eCost };
  }).filter(r => r.total > 0);

  return (
    <div className="space-y-5">
      {/* KPI cards */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label:'Costo RRHH',       val: fmtUSD(humanCost), color:'text-blue-600 dark:text-blue-400',     bg:'bg-blue-50 dark:bg-blue-500/10' },
          { label:'Equipos / Mat.',   val: fmtUSD(equipCost), color:'text-teal-600 dark:text-teal-400',     bg:'bg-teal-50 dark:bg-teal-500/10' },
          { label:'Subcontratos',     val: fmtUSD(subCost),   color:'text-violet-600 dark:text-violet-400', bg:'bg-violet-50 dark:bg-violet-500/10' },
          { label:'Costo total',      val: fmtUSD(totalCost), color:'text-emerald-600 dark:text-emerald-400',bg:'bg-emerald-50 dark:bg-emerald-500/10' },
        ].map(({ label, val, color, bg }) => (
          <div key={label} className={`${bg} rounded-xl p-4 border border-slate-100 dark:border-surface-600`}>
            <p className="text-xs text-slate-500 dark:text-gray-400 mb-1">{label}</p>
            <p className={`text-lg font-bold tabular-nums ${color}`}>{val}</p>
          </div>
        ))}
      </div>

      {/* Desglose por proyecto */}
      <div className="bg-white dark:bg-surface-800 rounded-xl border border-slate-200 dark:border-surface-700 overflow-hidden">
        <div className="px-5 py-3 border-b border-slate-100 dark:border-surface-700">
          <p className="text-sm font-semibold text-slate-800 dark:text-gray-200">Desglose por proyecto</p>
        </div>
        <div className="divide-y divide-slate-50 dark:divide-surface-700">
          {byProject.map(({ project: p, mCost, eCost, total }) => {
            const bar = totalCost > 0 ? (total / totalCost) * 100 : 0;
            return (
              <div key={p.id} className="px-5 py-4">
                <div className="flex items-center justify-between gap-3 mb-2">
                  <div>
                    <span className="font-mono text-xs font-bold text-blue-600 dark:text-blue-400 mr-2">{p.code}</span>
                    <span className="text-sm text-slate-700 dark:text-gray-300">{p.name}</span>
                  </div>
                  <span className="text-sm font-bold text-slate-800 dark:text-gray-200 tabular-nums">{fmtUSD(total)}</span>
                </div>
                <div className="h-2 rounded-full bg-slate-100 dark:bg-surface-700 overflow-hidden mb-2">
                  <div className="h-full rounded-full bg-blue-500" style={{ width: `${bar}%` }} />
                </div>
                <div className="flex gap-4 text-xs text-slate-400 dark:text-gray-500">
                  <span>RRHH: <strong className="text-slate-600 dark:text-gray-300">{fmtUSD(mCost)}</strong></span>
                  <span>Equipos: <strong className="text-slate-600 dark:text-gray-300">{fmtUSD(eCost)}</strong></span>
                  <span className="ml-auto">{bar.toFixed(1)}% del total</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Desglose RRHH individual */}
      <div>
        <p className="text-xs font-bold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-3">Costo por recurso humano</p>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-100 dark:border-surface-700">
                {['Recurso','Tarifa','Tipo','Hrs asig.','Costo estimado','% del total RRHH'].map(h => (
                  <th key={h} className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4 whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-surface-700/50">
              {members.map(m => {
                const hrs  = Object.values(m.allocatedHrs || {}).reduce((s, h) => s + h, 0);
                const cost = m.costType === 'HORA' ? hrs * m.costRate : m.costRate;
                const pct  = humanCost > 0 ? ((cost / humanCost) * 100).toFixed(1) : '0.0';
                return (
                  <tr key={m.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors">
                    <td className="py-3 pr-4">
                      <div className="flex items-center gap-2">
                        <Avatar member={m} />
                        <span className="text-slate-800 dark:text-gray-200">{m.firstName} {m.lastName}</span>
                      </div>
                    </td>
                    <td className="py-3 pr-4 font-mono text-xs text-slate-600 dark:text-gray-300">{fmtUSD(m.costRate)}</td>
                    <td className="py-3 pr-4"><Badge label={m.costType} color={COST_COLORS[m.costType] || COST_COLORS.FIJO} /></td>
                    <td className="py-3 pr-4 text-slate-600 dark:text-gray-300">{hrs} hr</td>
                    <td className="py-3 pr-4 font-semibold font-mono text-slate-800 dark:text-gray-200">{fmtUSD(cost)}</td>
                    <td className="py-3">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 h-1.5 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden max-w-[80px]">
                          <div className="h-full rounded-full bg-blue-400" style={{ width: `${pct}%` }} />
                        </div>
                        <span className="text-xs text-slate-500 dark:text-gray-400 tabular-nums">{pct}%</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ── Tab: Calendario (Week View) ────────────────────────────────────────────────
const PROJECT_COLORS = {
  'PRY-2026-004': { bg: '#3b82f6', light: '#eff6ff', border: '#bfdbfe', text: '#1d4ed8' },
  'PRY-2026-004': { bg: '#10b981', light: '#ecfdf5', border: '#a7f3d0', text: '#065f46' },
  'PRY-2026-004': { bg: '#8b5cf6', light: '#f5f3ff', border: '#ddd6fe', text: '#5b21b6' },
  'PRY-2026-004': { bg: '#f59e0b', light: '#fffbeb', border: '#fde68a', text: '#92400e' },
};

const WEEK_HOURS = Array.from({ length: 10 }, (_, i) => i + 8); // 8..17

function getWeekStart(date) {
  const d = new Date(date);
  const day = d.getDay();
  const diff = day === 0 ? -6 : 1 - day;
  d.setDate(d.getDate() + 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 formatDate(date) {
  return date.toLocaleDateString('es-ES', { day: '2-digit', month: 'short' });
}

function isSameDay(a, b) {
  return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}

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

// Mock calendar events per member
function generateCalendarEvents(members) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const events = [];
  const projectCodes = MOCK_PROJECTS.map(p => p.code);

  members.forEach(m => {
    (m.projects || []).forEach((code, pi) => {
      const proj = MOCK_PROJECTS.find(p => p.code === code);
      if (!proj) return;
      // Scatter a few events across the current week
      [0, 1, 2, 3, 4].forEach(dayOff => {
        if ((pi + dayOff) % 3 !== 0) return;
        const startH = 9 + (pi % 3) * 2;
        const dur    = 1 + (dayOff % 2);
        const eventDate = addDays(getWeekStart(today), dayOff);
        events.push({
          id: `${m.id}-${code}-${dayOff}`,
          memberId: m.id,
          projectCode: code,
          projectName: proj.name,
          date: eventDate,
          startHour: startH,
          endHour: startH + dur,
          task: `${proj.name.split(' ')[0]} — Tarea ${dayOff + 1}`,
        });
      });
    });
  });
  return events;
}

function NewAssignmentModal({ members, onClose, onSave }) {
  const [form, setForm] = useState({
    memberId: members[0]?.id || '',
    projectCode: MOCK_PROJECTS[0]?.code || '',
    date: new Date().toISOString().split('T')[0],
    startHour: '9',
    endHour: '11',
    task: '',
  });

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSave = () => {
    if (!form.task.trim()) return;
    const proj = MOCK_PROJECTS.find(p => p.code === form.projectCode);
    const eventDate = new Date(form.date + 'T00:00:00');
    onSave({
      id: `new-${Date.now()}`,
      memberId: form.memberId,
      projectCode: form.projectCode,
      projectName: proj?.name || form.projectCode,
      date: eventDate,
      startHour: parseInt(form.startHour, 10),
      endHour: parseInt(form.endHour, 10),
      task: form.task,
    });
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 w-full max-w-md p-6"
        onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-base font-bold text-slate-900 dark:text-white">Nueva asignación</h3>
          <button onClick={onClose} className="p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 cursor-pointer"><XIcon /></button>
        </div>
        <div className="space-y-4">
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Miembro</label>
            <select value={form.memberId} onChange={e => set('memberId', e.target.value)}
              className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
              {members.map(m => <option key={m.id} value={m.id}>{m.firstName} {m.lastName}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Proyecto</label>
            <select value={form.projectCode} onChange={e => set('projectCode', e.target.value)}
              className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
              {MOCK_PROJECTS.map(p => <option key={p.id} value={p.code}>{p.code} — {p.name}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Fecha</label>
            <input type="date" value={form.date} onChange={e => set('date', e.target.value)}
              className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Hora inicio</label>
              <select value={form.startHour} onChange={e => set('startHour', e.target.value)}
                className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
                {WEEK_HOURS.map(h => <option key={h} value={h}>{h}:00</option>)}
              </select>
            </div>
            <div>
              <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Hora fin</label>
              <select value={form.endHour} onChange={e => set('endHour', e.target.value)}
                className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
                {WEEK_HOURS.filter(h => h > parseInt(form.startHour, 10)).concat([18]).map(h => <option key={h} value={h}>{h}:00</option>)}
              </select>
            </div>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Descripcion de tarea</label>
            <input value={form.task} onChange={e => set('task', e.target.value)} placeholder="Ej: Revision de planos, Sprint planning..."
              className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 placeholder-slate-300 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
          </div>
        </div>
        <div className="flex gap-2 mt-6">
          <button onClick={onClose} className="flex-1 py-2 text-sm rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer">Cancelar</button>
          <button onClick={handleSave} className="flex-1 py-2 text-sm rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-medium cursor-pointer">Guardar</button>
        </div>
      </div>
    </div>
  );
}

function TabCalendario({ members }) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const [weekStart, setWeekStart] = useState(() => getWeekStart(today));
  const [selectedMemberId, setSelectedMemberId] = useState(members[0]?.id || '');
  const [extraEvents, setExtraEvents] = useState([]);
  const [showModal, setShowModal] = useState(false);

  const allEvents = useMemo(() => {
    const base = generateCalendarEvents(members);
    return [...base, ...extraEvents];
  }, [members, extraEvents]);

  const weekDays = useMemo(() => Array.from({ length: 7 }, (_, i) => addDays(weekStart, i)), [weekStart]);

  const selectedMember = members.find(m => m.id === selectedMemberId);

  const memberEvents = useMemo(() =>
    allEvents.filter(e => e.memberId === selectedMemberId),
    [allEvents, selectedMemberId]
  );

  const goToday = () => setWeekStart(getWeekStart(today));
  const prevWeek = () => setWeekStart(d => addDays(d, -7));
  const nextWeek = () => setWeekStart(d => addDays(d, 7));

  const handleSave = (event) => setExtraEvents(prev => [...prev, event]);

  const HOUR_HEIGHT = 56; // px per hour row

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="flex items-center gap-1">
          <button onClick={prevWeek} className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 dark:hover:bg-surface-700 cursor-pointer"><ChevronLeftIcon /></button>
          <button onClick={goToday} className="px-3 py-1.5 text-xs font-medium rounded-lg border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-surface-700 cursor-pointer">Hoy</button>
          <button onClick={nextWeek} className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 dark:hover:bg-surface-700 cursor-pointer"><ChevronRightIcon /></button>
        </div>
        <span className="text-sm font-semibold text-slate-700 dark:text-gray-200">
          {formatDate(weekDays[0])} — {formatDate(weekDays[6])}
        </span>
        <div className="ml-auto flex items-center gap-2">
          <select value={selectedMemberId} onChange={e => setSelectedMemberId(e.target.value)}
            className="text-sm bg-white dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500 cursor-pointer">
            {members.map(m => <option key={m.id} value={m.id}>{m.firstName} {m.lastName}</option>)}
          </select>
          <button onClick={() => setShowModal(true)}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer">
            <AddIcon /> Nueva asignacion
          </button>
        </div>
      </div>

      {/* Member badge */}
      {selectedMember && (
        <div className="flex items-center gap-2">
          <Avatar member={selectedMember} />
          <span className="text-sm font-medium text-slate-700 dark:text-gray-200">{selectedMember.firstName} {selectedMember.lastName}</span>
          <span className="text-xs text-slate-400 dark:text-gray-500">— {selectedMember.title}</span>
        </div>
      )}

      {/* Calendar grid */}
      <div className="overflow-x-auto rounded-xl border border-slate-200 dark:border-surface-700">
        <div style={{ minWidth: 640 }}>
          {/* Header row */}
          <div className="grid bg-slate-50 dark:bg-surface-800 border-b border-slate-200 dark:border-surface-700"
            style={{ gridTemplateColumns: '56px repeat(7, 1fr)' }}>
            <div className="p-2" />
            {weekDays.map((d, i) => {
              const isToday = isSameDay(d, today);
              return (
                <div key={i} className={`p-2 text-center border-l border-slate-200 dark:border-surface-700 ${isToday ? 'bg-blue-50 dark:bg-blue-500/10' : ''}`}>
                  <p className="text-xs font-semibold text-slate-500 dark:text-gray-400">{DAY_LABELS[i]}</p>
                  <p className={`text-sm font-bold mt-0.5 ${isToday ? 'text-blue-600 dark:text-blue-400' : 'text-slate-800 dark:text-gray-200'}`}>
                    {d.getDate()}
                  </p>
                </div>
              );
            })}
          </div>

          {/* Time rows */}
          <div className="relative bg-white dark:bg-surface-900">
            {WEEK_HOURS.map(hour => (
              <div key={hour} className="grid border-b border-slate-100 dark:border-surface-800"
                style={{ gridTemplateColumns: '56px repeat(7, 1fr)', height: HOUR_HEIGHT }}>
                <div className="flex items-start justify-end pr-2 pt-1">
                  <span className="text-xs text-slate-400 dark:text-gray-600">{hour}:00</span>
                </div>
                {weekDays.map((_, di) => (
                  <div key={di} className="border-l border-slate-100 dark:border-surface-800" />
                ))}
              </div>
            ))}

            {/* Event blocks (absolute positioned) */}
            {memberEvents.map(ev => {
              const dayIdx = weekDays.findIndex(d => isSameDay(d, ev.date));
              if (dayIdx < 0) return null;
              const startSlot = ev.startHour - 8;
              const duration = Math.max(0.5, ev.endHour - ev.startHour);
              if (startSlot < 0 || startSlot >= 10) return null;
              const colors = PROJECT_COLORS[ev.projectCode] || { bg: '#6b7280', light: '#f9fafb', border: '#e5e7eb', text: '#374151' };
              const topPx = startSlot * HOUR_HEIGHT + 2;
              const heightPx = duration * HOUR_HEIGHT - 4;
              const colWidth = `calc((100% - 56px) / 7)`;
              const leftOffset = `calc(56px + ${dayIdx} * (100% - 56px) / 7 + 2px)`;

              return (
                <div key={ev.id}
                  className="absolute rounded-lg px-2 py-1 overflow-hidden text-xs shadow-sm border cursor-pointer hover:shadow-md transition-shadow"
                  style={{
                    top: topPx,
                    left: leftOffset,
                    width: `calc((100% - 56px) / 7 - 4px)`,
                    height: heightPx,
                    background: colors.light,
                    borderColor: colors.border,
                    borderLeftWidth: 3,
                    borderLeftColor: colors.bg,
                  }}>
                  <p className="font-semibold leading-tight truncate" style={{ color: colors.text }}>{ev.task}</p>
                  <p className="mt-0.5 opacity-70" style={{ color: colors.text }}>{ev.startHour}:00 – {ev.endHour}:00</p>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Project color legend */}
      <div className="flex gap-3 flex-wrap">
        {MOCK_PROJECTS.map(p => {
          const c = PROJECT_COLORS[p.code];
          return (
            <div key={p.id} className="flex items-center gap-1.5 text-xs text-slate-500 dark:text-gray-400">
              <span className="w-3 h-3 rounded-sm flex-shrink-0" style={{ background: c?.bg || '#6b7280' }} />
              <span>{p.code}</span>
            </div>
          );
        })}
      </div>

      {showModal && (
        <NewAssignmentModal members={members} onClose={() => setShowModal(false)} onSave={handleSave} />
      )}
    </div>
  );
}

// ── Tab: Matriz de Habilidades ─────────────────────────────────────────────────
const ALL_SKILLS = [
  'React', 'Node.js', 'AutoCAD', 'BIM/Revit', 'MS Project', 'Primavera P6',
  'HSE', 'Gestión Contractual', 'Idiomas', 'Liderazgo', 'Excel Avanzado', 'Power BI',
];

// Build mock skill ratings per member
function buildSkillMatrix(members) {
  const seed = [
    [3, 2, 0, 0, 2, 1, 0, 1, 2, 3, 2, 3],
    [3, 3, 0, 0, 1, 0, 0, 0, 1, 2, 3, 2],
    [0, 1, 3, 3, 3, 2, 2, 3, 2, 3, 2, 1],
    [1, 2, 2, 2, 3, 3, 3, 2, 2, 2, 2, 2],
    [2, 1, 0, 0, 2, 1, 1, 2, 3, 3, 2, 1],
    [3, 3, 0, 0, 1, 0, 0, 1, 1, 2, 2, 3],
    [0, 0, 3, 3, 2, 1, 3, 3, 2, 3, 1, 0],
    [1, 0, 1, 2, 3, 3, 2, 3, 2, 3, 2, 2],
  ];
  return members.map((m, i) => ({
    member: m,
    ratings: seed[i % seed.length].map(r => r),
  }));
}

const SKILL_LEVEL_LABEL = ['', 'Básico', 'Intermedio', 'Experto'];
const SKILL_BG = [
  '',
  'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400',
  'bg-blue-300 dark:bg-blue-700/50 text-blue-800 dark:text-blue-200',
  'bg-blue-600 text-white',
];

function TabMatrizHabilidades({ members }) {
  const matrix = useMemo(() => buildSkillMatrix(members), [members]);
  const [filterLevel, setFilterLevel] = useState(0); // 0=all
  const [highlightSkill, setHighlightSkill] = useState(null);

  // Average per skill
  const skillAvgs = useMemo(() =>
    ALL_SKILLS.map((_, si) => {
      const vals = matrix.map(r => r.ratings[si]).filter(v => v > 0);
      return vals.length > 0 ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;
    }),
    [matrix]
  );

  const filteredMatrix = useMemo(() => {
    if (!filterLevel) return matrix;
    return matrix.filter(r => r.ratings.some(v => v >= filterLevel));
  }, [matrix, filterLevel]);

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="flex items-center gap-1">
          <span className="text-xs text-slate-500 dark:text-gray-400 mr-1">Filtrar nivel minimo:</span>
          {[0, 1, 2, 3].map(l => (
            <button key={l} onClick={() => setFilterLevel(l)}
              className={`px-3 py-1.5 text-xs font-medium rounded-lg transition cursor-pointer ${
                filterLevel === l
                  ? 'bg-blue-600 text-white'
                  : 'bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 hover:bg-slate-200'
              }`}>
              {l === 0 ? 'Todos' : SKILL_LEVEL_LABEL[l]}
            </button>
          ))}
        </div>
        <div className="ml-auto flex items-center gap-2 text-xs text-slate-400 dark:text-gray-500">
          <span className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-blue-100 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700" />Basico</span>
          <span className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-blue-300 dark:bg-blue-700" />Intermedio</span>
          <span className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-blue-600" />Experto</span>
          <span className="flex items-center gap-1"><span className="w-3 h-3 rounded bg-amber-300 dark:bg-amber-600 border border-amber-400" />Gap (&lt;2 promedio)</span>
        </div>
      </div>

      {/* Matrix table */}
      <div className="overflow-x-auto rounded-xl border border-slate-200 dark:border-surface-700">
        <table className="w-full text-xs">
          <thead>
            <tr className="bg-slate-50 dark:bg-surface-800 border-b border-slate-200 dark:border-surface-700">
              <th className="text-left px-4 py-3 text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider whitespace-nowrap sticky left-0 bg-slate-50 dark:bg-surface-800 z-10 min-w-[160px]">
                Recurso
              </th>
              {ALL_SKILLS.map((skill, si) => {
                const isGap = skillAvgs[si] < 2 && skillAvgs[si] > 0;
                return (
                  <th key={skill}
                    onClick={() => setHighlightSkill(highlightSkill === skill ? null : skill)}
                    className={`px-3 py-3 text-center font-semibold uppercase tracking-wider whitespace-nowrap cursor-pointer transition-colors ${
                      highlightSkill === skill
                        ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-300'
                        : isGap
                          ? 'text-amber-600 dark:text-amber-400'
                          : 'text-slate-500 dark:text-gray-400'
                    }`}>
                    <span className="block max-w-[80px] mx-auto truncate" title={skill}>{skill}</span>
                    {isGap && (
                      <span className="block mt-0.5 text-amber-500 dark:text-amber-400" title="Gap de habilidad">!</span>
                    )}
                  </th>
                );
              })}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 dark:divide-surface-800">
            {filteredMatrix.map(({ member: m, ratings }) => (
              <tr key={m.id} className="hover:bg-slate-50 dark:hover:bg-surface-800/50 transition-colors">
                <td className="px-4 py-2.5 sticky left-0 bg-white dark:bg-surface-900 z-10">
                  <div className="flex items-center gap-2">
                    <Avatar member={m} />
                    <div>
                      <p className="font-semibold text-slate-800 dark:text-gray-200 text-xs">{m.firstName} {m.lastName}</p>
                      <p className="text-slate-400 dark:text-gray-500" style={{ fontSize: 10 }}>{m.title}</p>
                    </div>
                  </div>
                </td>
                {ALL_SKILLS.map((skill, si) => {
                  const level = ratings[si] || 0;
                  const isHighlighted = highlightSkill === skill;
                  return (
                    <td key={skill} className={`px-2 py-2 text-center ${isHighlighted ? 'bg-blue-50 dark:bg-blue-500/10' : ''}`}>
                      {level > 0 ? (
                        <span className={`inline-flex items-center justify-center w-7 h-7 rounded-lg font-bold text-xs ${SKILL_BG[level]}`}
                          title={SKILL_LEVEL_LABEL[level]}>
                          {level}
                        </span>
                      ) : (
                        <span className="inline-flex items-center justify-center w-7 h-7 rounded-lg text-slate-200 dark:text-slate-700 text-xs">
                          —
                        </span>
                      )}
                    </td>
                  );
                })}
              </tr>
            ))}

            {/* Average row */}
            <tr className="bg-slate-50 dark:bg-surface-800 border-t-2 border-slate-200 dark:border-surface-700">
              <td className="px-4 py-2.5 sticky left-0 bg-slate-50 dark:bg-surface-800 z-10">
                <p className="font-bold text-slate-600 dark:text-gray-300 text-xs">Promedio equipo</p>
              </td>
              {skillAvgs.map((avg, si) => {
                const isGap = avg < 2 && avg > 0;
                return (
                  <td key={si} className="px-2 py-2.5 text-center">
                    <span className={`text-xs font-bold tabular-nums ${isGap ? 'text-amber-600 dark:text-amber-400' : 'text-slate-600 dark:text-gray-300'}`}>
                      {avg > 0 ? avg.toFixed(1) : '—'}
                    </span>
                  </td>
                );
              })}
            </tr>
          </tbody>
        </table>
      </div>

      <p className="text-xs text-slate-400 dark:text-gray-500">
        Haz clic en el encabezado de una columna para resaltar esa habilidad. Las habilidades marcadas con ! tienen promedio de equipo menor a 2 (gap de equipo).
      </p>
    </div>
  );
}

// ── Tab: Tarifas ───────────────────────────────────────────────────────────────
const CONTRACTOR_TYPES = ['INTERNO', 'EXTERNO', 'CONTRATISTA'];
const CONTRACTOR_COLORS = {
  INTERNO:    'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300',
  EXTERNO:    'bg-violet-100 text-violet-700 dark:bg-violet-500/20 dark:text-violet-300',
  CONTRATISTA:'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300',
};
const RATE_STATUS_COLORS = {
  ACTIVA:   'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400',
  INACTIVA: 'bg-slate-100 text-slate-500 dark:bg-gray-500/20 dark:text-gray-400',
};

function buildRatesData(members) {
  const typeAssign = ['INTERNO', 'INTERNO', 'CONTRATISTA', 'EXTERNO', 'INTERNO', 'CONTRATISTA', 'EXTERNO', 'INTERNO'];
  return members.map((m, i) => ({
    id: `rate-${m.id}`,
    memberId: m.id,
    member: m,
    role: m.title,
    type: typeAssign[i % typeAssign.length],
    rate: m.costRate,
    currency: m.currency || 'USD',
    effectiveDate: `2026-01-01`,
    status: 'ACTIVA',
  }));
}

function NewTarifaModal({ members, onClose, onSave }) {
  const [form, setForm] = useState({
    memberId: members[0]?.id || '',
    type: 'INTERNO',
    rate: '',
    currency: 'USD',
    effectiveDate: new Date().toISOString().split('T')[0],
  });

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSave = () => {
    if (!form.rate) return;
    const m = members.find(x => x.id === form.memberId);
    onSave({
      id: `rate-new-${Date.now()}`,
      memberId: form.memberId,
      member: m,
      role: m?.title || '',
      type: form.type,
      rate: parseFloat(form.rate),
      currency: form.currency,
      effectiveDate: form.effectiveDate,
      status: 'ACTIVA',
    });
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 w-full max-w-md p-6"
        onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-5">
          <h3 className="text-base font-bold text-slate-900 dark:text-white">Nueva tarifa</h3>
          <button onClick={onClose} className="p-1.5 rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 cursor-pointer"><XIcon /></button>
        </div>
        <div className="space-y-4">
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Recurso</label>
            <select value={form.memberId} onChange={e => set('memberId', e.target.value)}
              className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
              {members.map(m => <option key={m.id} value={m.id}>{m.firstName} {m.lastName}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Tipo</label>
            <div className="flex gap-1">
              {CONTRACTOR_TYPES.map(t => (
                <button key={t} onClick={() => set('type', t)}
                  className={`flex-1 py-1.5 text-xs font-medium rounded-lg transition cursor-pointer ${
                    form.type === t ? 'bg-blue-600 text-white' : 'bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-gray-300 hover:bg-slate-200'
                  }`}>{t}</button>
              ))}
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Tarifa ($/hora)</label>
              <input type="number" value={form.rate} onChange={e => set('rate', e.target.value)} placeholder="0"
                className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
            </div>
            <div>
              <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Moneda</label>
              <select value={form.currency} onChange={e => set('currency', e.target.value)}
                className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
                <option>USD</option><option>EUR</option><option>COP</option><option>MXN</option>
              </select>
            </div>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider block mb-1.5">Fecha efectiva</label>
            <input type="date" value={form.effectiveDate} onChange={e => set('effectiveDate', e.target.value)}
              className="w-full text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 text-slate-700 dark:text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
          </div>
        </div>
        <div className="flex gap-2 mt-6">
          <button onClick={onClose} className="flex-1 py-2 text-sm rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-slate-800 cursor-pointer">Cancelar</button>
          <button onClick={handleSave} className="flex-1 py-2 text-sm rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-medium cursor-pointer">Guardar</button>
        </div>
      </div>
    </div>
  );
}

function TabTarifas({ members }) {
  const [rates, setRates] = useState(() => buildRatesData(members));
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [editingVal, setEditingVal] = useState('');

  // Monthly cost projection: rate * 160 hrs/month (standard)
  const HOURS_PER_MONTH = 160;
  const totalMonthlyCost = rates
    .filter(r => r.status === 'ACTIVA')
    .reduce((s, r) => s + r.rate * HOURS_PER_MONTH, 0);

  const handleSave = (newRate) => {
    setRates(prev => [...prev, newRate]);
  };

  const startEdit = (id, currentVal) => {
    setEditingId(id);
    setEditingVal(String(currentVal));
  };

  const commitEdit = (id) => {
    const val = parseFloat(editingVal);
    if (!isNaN(val) && val >= 0) {
      setRates(prev => prev.map(r => r.id === id ? { ...r, rate: val } : r));
    }
    setEditingId(null);
  };

  const toggleStatus = (id) => {
    setRates(prev => prev.map(r => r.id === id
      ? { ...r, status: r.status === 'ACTIVA' ? 'INACTIVA' : 'ACTIVA' }
      : r
    ));
  };

  return (
    <div className="space-y-5">
      {/* Top cost card */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <div className="bg-emerald-50 dark:bg-emerald-500/10 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
          <p className="text-xs text-slate-500 dark:text-gray-400 mb-1">Costo mensual estimado del equipo</p>
          <p className="text-xl font-bold tabular-nums text-emerald-600 dark:text-emerald-400">{fmtUSD(totalMonthlyCost)}</p>
          <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">Basado en {HOURS_PER_MONTH} hrs/mes por recurso</p>
        </div>
        <div className="bg-blue-50 dark:bg-blue-500/10 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
          <p className="text-xs text-slate-500 dark:text-gray-400 mb-1">Tarifas activas</p>
          <p className="text-xl font-bold tabular-nums text-blue-600 dark:text-blue-400">{rates.filter(r => r.status === 'ACTIVA').length}</p>
          <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">de {rates.length} registros totales</p>
        </div>
        <div className="bg-amber-50 dark:bg-amber-500/10 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
          <p className="text-xs text-slate-500 dark:text-gray-400 mb-1">Tarifa promedio</p>
          <p className="text-xl font-bold tabular-nums text-amber-600 dark:text-amber-400">
            {rates.length > 0 ? fmtUSD(Math.round(rates.reduce((s, r) => s + r.rate, 0) / rates.length)) : '$0'}
          </p>
          <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">por hora</p>
        </div>
      </div>

      {/* Actions */}
      <div className="flex justify-end">
        <button onClick={() => setShowModal(true)}
          className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer">
          <AddIcon /> Nueva Tarifa
        </button>
      </div>

      {/* Table */}
      <div className="overflow-x-auto rounded-xl border border-slate-200 dark:border-surface-700">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-surface-800 border-b border-slate-200 dark:border-surface-700">
              {['Recurso', 'Rol', 'Tipo', 'Tarifa ($/hr)', 'Moneda', 'Fecha efectiva', 'Costo mensual est.', 'Estado', ''].map(h => (
                <th key={h} className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider px-4 py-3 whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700/50">
            {rates.map(r => {
              const monthlyCost = r.rate * HOURS_PER_MONTH;
              const isEditing = editingId === r.id;
              return (
                <tr key={r.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2.5">
                      <Avatar member={r.member} />
                      <div>
                        <p className="font-semibold text-slate-800 dark:text-gray-200 text-sm">{r.member?.firstName} {r.member?.lastName}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400 whitespace-nowrap">{r.role}</td>
                  <td className="px-4 py-3">
                    <Badge label={r.type} color={CONTRACTOR_COLORS[r.type] || CONTRACTOR_COLORS.INTERNO} />
                  </td>
                  <td className="px-4 py-3">
                    {isEditing ? (
                      <input
                        type="number"
                        value={editingVal}
                        onChange={e => setEditingVal(e.target.value)}
                        onBlur={() => commitEdit(r.id)}
                        onKeyDown={e => { if (e.key === 'Enter') commitEdit(r.id); if (e.key === 'Escape') setEditingId(null); }}
                        autoFocus
                        className="w-24 text-sm font-mono border border-blue-400 rounded-lg px-2 py-1 text-slate-800 dark:text-gray-200 bg-white dark:bg-slate-800 focus:outline-none focus:ring-1 focus:ring-blue-500"
                      />
                    ) : (
                      <button
                        onClick={() => startEdit(r.id, r.rate)}
                        className="flex items-center gap-1.5 group cursor-pointer"
                        title="Clic para editar">
                        <span className="font-mono font-semibold text-slate-700 dark:text-gray-200">{fmtUSD(r.rate)}</span>
                        <span className="text-slate-300 dark:text-slate-600 group-hover:text-blue-500 transition-colors"><PencilIcon /></span>
                      </button>
                    )}
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400">{r.currency}</td>
                  <td className="px-4 py-3 text-xs text-slate-500 dark:text-gray-400 whitespace-nowrap">{r.effectiveDate}</td>
                  <td className="px-4 py-3 font-mono text-xs font-semibold text-slate-700 dark:text-gray-200">{fmtUSD(monthlyCost)}</td>
                  <td className="px-4 py-3">
                    <button onClick={() => toggleStatus(r.id)} className="cursor-pointer">
                      <Badge label={r.status} color={RATE_STATUS_COLORS[r.status] || RATE_STATUS_COLORS.ACTIVA} />
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    <button onClick={() => startEdit(r.id, r.rate)}
                      className="text-xs px-2 py-1.5 rounded-lg bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 hover:bg-blue-50 dark:hover:bg-blue-500/10 hover:text-blue-600 dark:hover:text-blue-400 transition font-medium cursor-pointer">
                      Editar
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {showModal && (
        <NewTarifaModal members={members} onClose={() => setShowModal(false)} onSave={handleSave} />
      )}
    </div>
  );
}

// ── Tabs config ────────────────────────────────────────────────────────────────
const TABS = [
  { id:'humanos',    label:'Recursos Humanos',   Icon: PeopleIcon },
  { id:'equipos',    label:'Equipos & Mat.',      Icon: EquipmentIcon },
  { id:'carga',      label:'Carga / Capacidad',   Icon: ChartBarIcon },
  { id:'costo',      label:'Costo de recursos',   Icon: () => <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> },
  { id:'calendario', label:'Calendario',          Icon: CalendarIcon },
  { id:'habilidades',label:'Matriz de Habilidades',Icon: GridIcon },
  { id:'tarifas',    label:'Tarifas',             Icon: TagIcon },
];

// ── localStorage helpers ──────────────────────────────────────────────────────
const LS_TEAM = 'arpm_team';
const LS_EQUIP = 'arpm_equipment';
function loadTeam()  { try { const s = localStorage.getItem(LS_TEAM);  return s ? JSON.parse(s) : MOCK_TEAM;      } catch { return MOCK_TEAM;      } }
function loadEquip() { try { const s = localStorage.getItem(LS_EQUIP); return s ? JSON.parse(s) : MOCK_EQUIPMENT; } catch { return MOCK_EQUIPMENT; } }

// ── Main Page ─────────────────────────────────────────────────────────────────
export default function ResourcesPage() {
  const { selectedProjectId } = useProject();
  const [tab,       setTab]    = useState('humanos');
  const [drawer,    setDrawer] = useState(null);
  const [allMembers,  setAllMembers]  = useState(loadTeam);
  const [allEquipment,setAllEquipment]= useState(loadEquip);

  const saveTeam  = (list) => { setAllMembers(list);   localStorage.setItem(LS_TEAM,  JSON.stringify(list)); };
  const saveEquip = (list) => { setAllEquipment(list); localStorage.setItem(LS_EQUIP, JSON.stringify(list)); };

  const handleDeleteMember = (id) => {
    saveTeam(allMembers.filter(m => m.id !== id));
    setDrawer(null);
  };
  const handleDeleteEquip = (id) => {
    saveEquip(allEquipment.filter(e => e.id !== id));
    setDrawer(null);
  };
  const handleUpdateMember = (updated) => {
    const withStatus = { ...updated, status: computeStatus(updated) };
    const exists = allMembers.some(m => m.id === withStatus.id);
    const list = exists
      ? allMembers.map(m => m.id === withStatus.id ? withStatus : m)
      : [...allMembers, withStatus];
    saveTeam(list);
    if (exists) setDrawer(withStatus);
  };

  const members = useMemo(() => {
    if (!selectedProjectId) return allMembers;
    const proj = MOCK_PROJECTS.find(p => p.id === selectedProjectId);
    if (!proj) return allMembers;
    return allMembers.filter(m => m.projects?.includes(proj.code));
  }, [allMembers, selectedProjectId]);

  const equipment = useMemo(() => {
    if (!selectedProjectId) return allEquipment;
    const proj = MOCK_PROJECTS.find(p => p.id === selectedProjectId);
    if (!proj) return allEquipment;
    return allEquipment.filter(e => e.project === proj.code);
  }, [allEquipment, selectedProjectId]);

  // KPI totals
  const totalCap   = members.reduce((s, m) => s + (m.capacityHrsWeek || 0), 0);
  const totalAlloc = members.reduce((s, m) => s + Object.values(m.allocatedHrs || {}).reduce((x, h) => x + h, 0), 0);
  const overloaded = members.filter(m => {
    const tot = Object.values(m.allocatedHrs || {}).reduce((s, h) => s + h, 0);
    return tot >= (m.capacityHrsWeek || 40);
  }).length;
  const totalEqCost = equipment.reduce((s, e) => s + (e.costRate || 0), 0);

  return (
    <div className="flex flex-col gap-4">
      {/* Header */}
      <div className="flex items-start justify-between gap-3 flex-wrap">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">Recursos</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">
            Humanos · Equipos · Materiales · Carga · Costos · Calendario · Habilidades · Tarifas
          </p>
        </div>
        {overloaded > 0 && (
          <div className="flex items-center gap-2 bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/20 rounded-xl px-3 py-2">
            <svg className="w-4 h-4 text-red-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
            <p className="text-xs text-red-700 dark:text-red-300">
              <strong>{overloaded}</strong> {overloaded === 1 ? 'recurso sobrecargado' : 'recursos sobrecargados'}
            </p>
          </div>
        )}
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label:'Recursos humanos',    val: members.length,                                   color:'text-blue-600 dark:text-blue-400',     bg:'bg-blue-50 dark:bg-blue-500/10' },
          { label:'Capacidad total',     val: `${totalCap} hr/sem`,                             color:'text-slate-800 dark:text-gray-200',    bg:'bg-slate-50 dark:bg-surface-700' },
          { label:'Horas asignadas',     val: `${totalAlloc} / ${totalCap} hr`,                color:'text-emerald-600 dark:text-emerald-400',bg:'bg-emerald-50 dark:bg-emerald-500/10' },
          { label:'Equip. y materiales', val: equipment.length,                                 color:'text-violet-600 dark:text-violet-400', bg:'bg-violet-50 dark:bg-violet-500/10' },
        ].map(({ label, val, color, bg }) => (
          <div key={label} className={`${bg} rounded-xl p-4 border border-slate-100 dark:border-surface-600`}>
            <p className="text-xs text-slate-500 dark:text-gray-400 mb-1">{label}</p>
            <p className={`text-lg font-bold tabular-nums ${color}`}>{val}</p>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
        <div className="flex border-b border-slate-100 dark:border-surface-700 px-4 gap-0.5 overflow-x-auto">
          {TABS.map(({ id, label, Icon }) => (
            <button key={id} onClick={() => setTab(id)}
              className={`flex items-center gap-1.5 px-4 py-3.5 text-sm font-medium whitespace-nowrap border-b-2 transition-colors cursor-pointer ${
                tab === id
                  ? 'border-blue-600 text-blue-700 dark:text-blue-400'
                  : 'border-transparent text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200'
              }`}>
              <Icon />
              {label}
              {id === 'humanos' && overloaded > 0 && (
                <span className="ml-1 bg-red-500 text-white text-xs rounded-full px-1.5 py-0.5 font-bold leading-none">{overloaded}</span>
              )}
            </button>
          ))}
        </div>

        <div className="p-6">
          {tab === 'humanos'     && <TabHumanos    members={members}                   onSelect={setDrawer} onSaveMember={handleUpdateMember} />}
          {tab === 'equipos'     && <TabEquipos    equipment={equipment}               onSelect={setDrawer} />}
          {tab === 'carga'       && <TabCarga      members={members} />}
          {tab === 'costo'       && <TabCosto      members={members} equipment={equipment} />}
          {tab === 'calendario'  && <TabCalendario members={members} />}
          {tab === 'habilidades' && <TabMatrizHabilidades members={members} />}
          {tab === 'tarifas'     && <TabTarifas    members={members} />}
        </div>
      </div>

      {/* Side drawer */}
      {drawer && (
        <ResourceDrawer
          resource={drawer}
          onClose={() => setDrawer(null)}
          onDelete={drawer.resourceType === 'HUMANO' ? handleDeleteMember : handleDeleteEquip}
          onUpdateMember={drawer.resourceType === 'HUMANO' ? handleUpdateMember : null}
          allProjects={MOCK_PROJECTS}
        />
      )}
    </div>
  );
}
