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

// Merge mock + localStorage projects filtered by ACTIVO
function getAllActiveProjects() {
  const extra = (() => { try { return JSON.parse(localStorage.getItem('arpm_projects') || '[]'); } catch { return []; } })();
  const all = [...MOCK_PROJECTS, ...extra];
  return all.filter(p => !p.status || p.status === 'ACTIVO' || p.status === 'EN_RIESGO');
}

// ── Helpers ───────────────────────────────────────────────────────────────────
const fmt  = n => n >= 1_000_000 ? `$${(n/1_000_000).toFixed(1)}M` : n >= 1000 ? `$${(n/1000).toFixed(1)}K` : `$${Math.round(n)}`;
const fmtR = m => {
  if (!m) return '—';
  if (m.costType === 'HORA') return `$${m.costRate}/hr`;
  if (m.costType === 'DIA')  return `$${m.costRate}/día`;
  if (m.costType === 'MES')  return `$${m.costRate.toLocaleString()}/mes`;
  if (m.costType === 'FIJO') return `$${m.costRate.toLocaleString()} fijo`;
  return `$${m.costRate}`;
};

const rateToHour = m => {
  if (!m) return 0;
  if (m.costType === 'HORA') return m.costRate;
  if (m.costType === 'DIA')  return m.costRate / (m.hoursPerDay || 8);
  if (m.costType === 'MES')  return m.costRate / ((m.hoursPerDay || 8) * (m.daysPerWeek || 5) * 4.33);
  return 0;
};

const weeklyRate = m => {
  if (!m) return 0;
  if (m.costType === 'HORA') return m.costRate * (m.capacityHrsWeek || 40);
  if (m.costType === 'DIA')  return m.costRate * (m.daysPerWeek || 5);
  if (m.costType === 'MES')  return m.costRate / 4.33;
  return 0;
};

const ROLE_LABELS = {
  SUPER_ADMIN:'Super Admin', DIRECTOR:'Director', GERENTE:'Gerente',
  JEFE_AREA:'Jefe de Área', COLABORADOR:'Colaborador', FINANCIERO:'Financiero', AUDITOR:'Auditor',
};
const ROLE_COLOR = {
  SUPER_ADMIN:'bg-purple-100 text-purple-700 dark:bg-purple-500/20 dark:text-purple-300',
  DIRECTOR:'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300',
  GERENTE:'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300',
  JEFE_AREA:'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300',
  COLABORADOR:'bg-slate-100 text-slate-600 dark:bg-gray-500/20 dark:text-gray-300',
  FINANCIERO:'bg-rose-100 text-rose-700 dark:bg-rose-500/20 dark:text-rose-300',
};

const EQ_TYPE_COLOR = {
  EQUIPO:'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300',
  MATERIAL:'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300',
  SUBCONTRATO:'bg-purple-100 text-purple-700 dark:bg-purple-500/20 dark:text-purple-300',
};

const TABS = ['Equipo humano','Equipos & Materiales','Capacidad & Carga','Costos'];

// ── Subcomponents ─────────────────────────────────────────────────────────────
function Avatar({ m, size = 'md' }) {
  const sz = size === 'lg' ? 'w-10 h-10 text-sm' : 'w-8 h-8 text-xs';
  return (
    <div className={`${sz} rounded-full flex items-center justify-center font-bold flex-shrink-0`}
      style={{ background: m.color + '22', color: m.color }}>
      {m.avatar}
    </div>
  );
}

// ── Member modal ──────────────────────────────────────────────────────────────
function MemberModal({ member: m, onClose }) {
  const projNames = MOCK_PROJECTS.filter(p => m.projects && m.projects.includes(p.code));
  const weekCost  = weeklyRate(m);
  const monthCost = weekCost * 4.33;
  const hourRate  = rateToHour(m);
  const totalAlloc= Object.values(m.allocatedHrs || {}).reduce((s,h) => s+h, 0);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onClose}/>
      <div className="relative w-full max-w-xl bg-white dark:bg-surface-800 rounded-2xl shadow-2xl border border-slate-200 dark:border-surface-700 overflow-hidden max-h-[88vh] flex flex-col">
        <div className="flex items-center gap-4 px-6 py-5 border-b border-slate-100 dark:border-surface-700 flex-shrink-0"
          style={{ background: m.color + '10' }}>
          <Avatar m={m} size="lg"/>
          <div className="flex-1 min-w-0">
            <h2 className="text-base font-bold text-slate-900 dark:text-white">{m.firstName} {m.lastName}</h2>
            <p className="text-sm text-slate-500 dark:text-gray-400">{m.title} · {m.dept}</p>
          </div>
          <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${ROLE_COLOR[m.role] || ''}`}>
            {ROLE_LABELS[m.role] || m.role}
          </span>
          <button onClick={onClose} className="p-1.5 rounded-lg text-slate-400 hover:text-slate-700 dark:hover:text-white hover:bg-black/5 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 className="overflow-y-auto flex-1 p-6 space-y-5">
          <div className="grid grid-cols-2 gap-3 text-sm">
            <div><p className="text-xs text-slate-400 dark:text-gray-500 mb-0.5">Email</p><p className="text-slate-700 dark:text-gray-200 truncate">{m.email}</p></div>
            <div><p className="text-xs text-slate-400 dark:text-gray-500 mb-0.5">Teléfono</p><p className="text-slate-700 dark:text-gray-200">{m.phone}</p></div>
          </div>

          <div className="bg-blue-50 dark:bg-blue-500/10 border border-blue-100 dark:border-blue-500/20 rounded-xl p-4">
            <p className="text-xs font-bold text-blue-700 dark:text-blue-400 uppercase tracking-wider mb-3">Estructura de costos</p>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div><p className="text-xs text-slate-400 dark:text-gray-500">Tarifa</p><p className="font-bold text-slate-900 dark:text-white">{fmtR(m)}</p></div>
              <div><p className="text-xs text-slate-400 dark:text-gray-500">Equiv. / hora</p><p className="font-semibold text-blue-600 dark:text-blue-400">${hourRate.toFixed(2)}/hr</p></div>
              <div><p className="text-xs text-slate-400 dark:text-gray-500">Costo semana</p><p className="font-semibold text-slate-700 dark:text-gray-200">{fmt(weekCost)}</p></div>
              <div><p className="text-xs text-slate-400 dark:text-gray-500">Costo mes</p><p className="font-semibold text-slate-700 dark:text-gray-200">{fmt(monthCost)}</p></div>
            </div>
          </div>

          <div>
            <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-2">Horario de trabajo</p>
            <div className="grid grid-cols-3 gap-3 text-sm">
              <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-3 text-center">
                <p className="text-lg font-bold text-slate-900 dark:text-white">{m.hoursPerDay}h</p>
                <p className="text-xs text-slate-400 dark:text-gray-500">por día</p>
              </div>
              <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-3 text-center">
                <p className="text-lg font-bold text-slate-900 dark:text-white">{m.daysPerWeek}d</p>
                <p className="text-xs text-slate-400 dark:text-gray-500">por semana</p>
              </div>
              <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-3 text-center">
                <p className="text-lg font-bold text-slate-900 dark:text-white">{m.capacityHrsWeek}h</p>
                <p className="text-xs text-slate-400 dark:text-gray-500">cap./sem</p>
              </div>
            </div>
            <p className="text-xs text-slate-400 dark:text-gray-500 mt-2">{m.startTime} — {m.endTime} · {m.workDays && m.workDays.join(', ')}</p>
          </div>

          <div>
            <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-3">Capacidad vs asignado</p>
            {[{ label:'Total', used: totalAlloc, cap: m.capacityHrsWeek }, ...projNames.map(p => ({ label: p.code, used: m.allocatedHrs && m.allocatedHrs[p.code] || 0, cap: m.capacityHrsWeek }))].map(({ label, used, cap }) => {
              const pct = cap > 0 ? Math.min(Math.round(used / cap * 100), 120) : 0;
              const over = pct > 100;
              return (
                <div key={label} className="mb-2">
                  <div className="flex justify-between text-xs mb-1">
                    <span className="text-slate-500 dark:text-gray-400">{label}</span>
                    <span className={`font-semibold tabular-nums ${over ? 'text-red-500' : 'text-slate-700 dark:text-gray-200'}`}>{used}h / {cap}h{over && ' ⚠'}</span>
                  </div>
                  <div className="h-2 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
                    <div className={`h-full rounded-full ${over ? 'bg-red-500' : pct > 80 ? 'bg-amber-400' : 'bg-emerald-500'}`} style={{ width: `${Math.min(pct, 100)}%` }}/>
                  </div>
                </div>
              );
            })}
          </div>

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

          {m.skills && m.skills.length > 0 && (
            <div>
              <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-2">Habilidades</p>
              <div className="flex flex-wrap gap-1.5">
                {m.skills.map(s => (
                  <span key={s} className="text-xs px-2.5 py-1 bg-slate-100 dark:bg-surface-700 text-slate-600 dark:text-gray-300 rounded-full border border-slate-200 dark:border-surface-600">{s}</span>
                ))}
              </div>
            </div>
          )}

          {projNames.length > 0 && (
            <div>
              <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-2">Proyectos activos</p>
              <div className="space-y-2">
                {projNames.map(p => (
                  <div key={p.id} className="flex items-center justify-between px-3 py-2 bg-slate-50 dark:bg-surface-700 rounded-xl text-sm">
                    <div><span className="font-mono text-xs text-slate-400 dark:text-gray-500 mr-2">{p.code}</span><span className="text-slate-700 dark:text-gray-200">{p.name}</span></div>
                    <span className="text-xs text-blue-600 dark:text-blue-400 font-semibold tabular-nums ml-3 flex-shrink-0">{m.allocatedHrs && m.allocatedHrs[p.code] || 0}h asig.</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Tab 0: Equipo humano ──────────────────────────────────────────────────────
function TeamHumano({ team = MOCK_TEAM, onSelect, onEdit, projectId }) {
  const [search, setSearch] = useState('');
  const filtered = useMemo(() =>
    team.filter(m => {
      const matchSearch = `${m.firstName} ${m.lastName} ${m.title} ${m.dept}`.toLowerCase().includes(search.toLowerCase());
      const matchProj = !projectId || Object.keys(m.allocatedHrs || {}).some(k => k === projectId || MOCK_PROJECTS.find(p=>p.id===projectId)?.code === k);
      return matchSearch && matchProj;
    }), [search, projectId, team]);

  return (
    <div className="space-y-4">
      <div className="relative max-w-xs">
        <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 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>
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar nombre o cargo..."
          className="field-input pl-9 text-sm"/>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
        {filtered.map(m => {
          const totalAlloc  = Object.values(m.allocatedHrs || {}).reduce((s,h) => s+h, 0);
          const pct         = m.capacityHrsWeek > 0 ? Math.round(totalAlloc / m.capacityHrsWeek * 100) : 0;
          const over        = pct > 100;
          const wCost       = weeklyRate(m);
          const assignedProjs = MOCK_PROJECTS.filter(p => (m.allocatedHrs?.[p.code] || 0) > 0);
          const multiProj   = assignedProjs.length > 1;

          // Segmented load bar: each project gets a slice proportional to its hours
          const barSegments = assignedProjs.map((p, i) => ({
            code: p.code,
            hrs:  m.allocatedHrs[p.code],
            pct:  m.capacityHrsWeek > 0 ? m.allocatedHrs[p.code] / m.capacityHrsWeek * 100 : 0,
            color: COLORS[i % COLORS.length],
          }));

          return (
            <div key={m.id} onClick={() => onSelect(m)}
              className={`bg-white dark:bg-surface-800 rounded-2xl border hover:shadow-md transition-all cursor-pointer p-4 ${
                multiProj
                  ? 'border-violet-200 dark:border-violet-500/30 hover:border-violet-400 dark:hover:border-violet-400/60'
                  : 'border-slate-200 dark:border-surface-700 hover:border-blue-300 dark:hover:border-blue-500/50'
              }`}>
              <div className="flex items-start gap-3">
                {/* Avatar with multi-project ring */}
                <div className="relative flex-shrink-0">
                  <Avatar m={m} size="lg"/>
                  {multiProj && (
                    <span className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-violet-500 border-2 border-white dark:border-surface-800 flex items-center justify-center">
                      <span className="text-white font-bold" style={{fontSize:'8px'}}>{assignedProjs.length}</span>
                    </span>
                  )}
                </div>

                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <p className="text-sm font-semibold text-slate-900 dark:text-white">{m.firstName} {m.lastName}</p>
                    <span className={`text-xs px-1.5 py-0.5 rounded-full font-medium ${ROLE_COLOR[m.role] || ''}`}>{ROLE_LABELS[m.role] || m.role}</span>
                    {multiProj && (
                      <span className="text-xs px-1.5 py-0.5 rounded-full font-semibold bg-violet-100 text-violet-700 dark:bg-violet-500/20 dark:text-violet-300">
                        {assignedProjs.length} proyectos
                      </span>
                    )}
                  </div>
                  <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{m.title} · {m.dept}</p>

                  <div className="flex items-center gap-3 mt-2 flex-wrap">
                    <span className="text-xs font-semibold text-blue-600 dark:text-blue-400">{fmtR(m)}</span>
                    <span className="text-xs text-slate-400 dark:text-gray-500">{m.startTime}–{m.endTime}</span>
                    <span className="text-xs text-slate-400 dark:text-gray-500">{m.hoursPerDay}h/día · {m.daysPerWeek}d/sem</span>
                    {wCost > 0 && <span className="text-xs text-slate-500 dark:text-gray-400 ml-auto">{fmt(wCost)}/sem</span>}
                  </div>

                  {/* Load bar — segmented when multi-project */}
                  <div className="mt-2.5">
                    <div className="flex justify-between text-xs mb-1">
                      <span className="text-slate-400 dark:text-gray-500">Carga ({totalAlloc}h / {m.capacityHrsWeek}h)</span>
                      <span className={`font-semibold tabular-nums ${over ? 'text-red-500' : pct > 80 ? 'text-amber-500' : 'text-emerald-600 dark:text-emerald-400'}`}>{pct}%{over && ' ⚠'}</span>
                    </div>
                    <div className="h-1.5 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden flex">
                      {multiProj
                        ? barSegments.map(seg => (
                            <div key={seg.code} className="h-full" style={{ width:`${Math.min(seg.pct, 100)}%`, background: seg.color }}/>
                          ))
                        : <div className={`h-full rounded-full ${over ? 'bg-red-500' : pct > 80 ? 'bg-amber-400' : 'bg-emerald-500'}`} style={{ width:`${Math.min(pct,100)}%` }}/>
                      }
                    </div>
                  </div>

                  {/* Project pills — shown when multi-project */}
                  {multiProj && (
                    <div className="flex gap-1.5 mt-2 flex-wrap">
                      {assignedProjs.map((p, i) => (
                        <span key={p.id} className="flex items-center gap-1 text-xs px-1.5 py-0.5 rounded-md font-medium bg-slate-50 dark:bg-surface-700 text-slate-600 dark:text-gray-300 border border-slate-200 dark:border-surface-600">
                          <span className="w-1.5 h-1.5 rounded-full flex-shrink-0" style={{background: COLORS[i % COLORS.length]}}/>
                          {p.code} · {m.allocatedHrs[p.code]}h
                        </span>
                      ))}
                    </div>
                  )}

                  <div className="flex gap-1.5 mt-2 flex-wrap">
                    {m.tasks && m.tasks.COMPLETADA > 0 && <span className="text-xs px-1.5 py-0.5 bg-emerald-50 dark:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 rounded-md">✓ {m.tasks.COMPLETADA}</span>}
                    {m.tasks && m.tasks.EN_PROCESO > 0  && <span className="text-xs px-1.5 py-0.5 bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded-md">▶ {m.tasks.EN_PROCESO}</span>}
                    {m.tasks && m.tasks.BLOQUEADA > 0   && <span className="text-xs px-1.5 py-0.5 bg-red-50 dark:bg-red-500/10 text-red-600 dark:text-red-400 rounded-md">⬛ {m.tasks.BLOQUEADA}</span>}
                    {m.skills && m.skills.slice(0,2).map(s => (
                      <span key={s} className="text-xs px-1.5 py-0.5 bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400 rounded-md">{s}</span>
                    ))}
                    {m.skills && m.skills.length > 2 && <span className="text-xs text-slate-400 dark:text-gray-500">+{m.skills.length - 2}</span>}
                  </div>
                </div>
              </div>
              {/* Edit button */}
              <div className="flex justify-end mt-3 pt-3 border-t border-slate-50 dark:border-surface-700">
                <button onClick={e => { e.stopPropagation(); onEdit?.(m); }}
                  className="text-xs px-3 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">
                  Editar
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Tab 1: Equipos & materiales ───────────────────────────────────────────────
function TeamEquipos({ projectId }) {
  const equipos = projectId
    ? MOCK_EQUIPMENT.filter(eq => {
        const proj = MOCK_PROJECTS.find(p => p.code === eq.project || p.id === eq.project);
        return proj?.id === projectId;
      })
    : MOCK_EQUIPMENT;
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
        {equipos.map(eq => {
          const proj = MOCK_PROJECTS.find(p => p.code === eq.project || p.id === eq.project);
          return (
            <div key={eq.id} className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 p-4 hover:shadow-sm transition-all">
              <div className="flex items-start justify-between gap-3 mb-3">
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-slate-900 dark:text-white leading-snug">{eq.name}</p>
                  <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">{eq.vendor}</p>
                </div>
                <div className="flex flex-col items-end gap-1 flex-shrink-0">
                  <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${EQ_TYPE_COLOR[eq.resourceType] || 'bg-slate-100 text-slate-500'}`}>{eq.resourceType}</span>
                  <span className={`text-xs px-2 py-0.5 rounded-full ${eq.status === 'ACTIVO' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400' : 'bg-slate-100 text-slate-500'}`}>{eq.status}</span>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-2 text-sm">
                <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-2.5">
                  <p className="text-xs text-slate-400 dark:text-gray-500 mb-0.5">Costo</p>
                  <p className="font-bold text-blue-600 dark:text-blue-400">
                    {eq.costType === 'FIJO' ? `${fmt(eq.costRate)} fijo` : `${fmt(eq.costRate)}/${eq.costType.toLowerCase()}`}
                    {eq.unit && <span className="font-normal text-slate-400 dark:text-gray-500"> / {eq.unit}</span>}
                  </p>
                </div>
                <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-2.5">
                  <p className="text-xs text-slate-400 dark:text-gray-500 mb-0.5">Proyecto</p>
                  <p className="font-semibold text-slate-700 dark:text-gray-200 text-xs truncate">{proj ? proj.code : eq.project}</p>
                </div>
              </div>

              {eq.notes && (
                <p className="mt-2.5 text-xs text-slate-400 dark:text-gray-500 bg-slate-50 dark:bg-surface-700 rounded-lg px-3 py-2">{eq.notes}</p>
              )}
            </div>
          );
        })}
      </div>

      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 p-5">
        <p className="text-sm font-semibold text-slate-800 dark:text-white mb-3">Resumen de recursos no-humanos</p>
        <div className="grid grid-cols-3 gap-3">
          {['EQUIPO','MATERIAL','SUBCONTRATO'].map(type => {
            const items = MOCK_EQUIPMENT.filter(e => e.resourceType === type);
            const totalFijo = items.filter(e => e.costType === 'FIJO').reduce((s,e) => s+e.costRate, 0);
            return (
              <div key={type} className="bg-slate-50 dark:bg-surface-700 rounded-xl p-3 text-center">
                <p className="text-lg font-bold text-slate-900 dark:text-white">{items.length}</p>
                <p className={`text-xs font-semibold mt-0.5 ${EQ_TYPE_COLOR[type]?.split(' ')[1] || 'text-slate-600'}`}>{type.charAt(0)+type.slice(1).toLowerCase()}{items.length !== 1 ? 's':''}</p>
                {totalFijo > 0 && <p className="text-xs text-slate-500 dark:text-gray-400 mt-1">{fmt(totalFijo)} comprometido</p>}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── Tab 2: Capacidad & carga ───────────────────────────────────────────────────
function TeamCapacidad({ team = MOCK_TEAM, projectId }) {
  const proyectos = projectId ? MOCK_PROJECTS.filter(p => p.id === projectId) : MOCK_PROJECTS;

  return (
    <div className="space-y-4">
      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 overflow-hidden">
        <div className="px-5 py-4 border-b border-slate-100 dark:border-surface-700">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Heatmap de carga — horas asignadas por proyecto</p>
          <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">Verde = dentro de capacidad · Ámbar = &gt;40% · Rojo = &gt;80%</p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100 dark:border-surface-700">
                <th className="px-4 py-3 text-left text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider">Recurso</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider">Cap./sem</th>
                {proyectos.map(p => (
                  <th key={p.id} className="px-3 py-3 text-center text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider whitespace-nowrap">{p.code}</th>
                ))}
                <th className="px-3 py-3 text-center text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider">Total</th>
                <th className="px-3 py-3 text-center text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider">%</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
              {team.filter(m => {
                if (!projectId) return true;
                return proyectos.some(p => (m.allocatedHrs?.[p.code] || 0) > 0);
              }).map(m => {
                // Total siempre = suma de TODOS los proyectos (carga real del recurso)
                const totalAlloc = Object.values(m.allocatedHrs || {}).reduce((s,h) => s+h, 0);
                const pct        = m.capacityHrsWeek > 0 ? Math.round(totalAlloc / m.capacityHrsWeek * 100) : 0;
                const over       = pct > 100;
                return (
                  <tr key={m.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">
                        <Avatar m={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.title}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-3 py-3 text-center text-sm tabular-nums text-slate-600 dark:text-gray-300 font-semibold">{m.capacityHrsWeek}h</td>
                    {proyectos.map(p => {
                      const hrs = m.allocatedHrs && m.allocatedHrs[p.code] || 0;
                      const cellPct = m.capacityHrsWeek > 0 ? hrs / m.capacityHrsWeek * 100 : 0;
                      const bg  = hrs === 0 ? '' : cellPct > 80 ? 'bg-red-100 dark:bg-red-500/20' : cellPct > 40 ? 'bg-amber-100 dark:bg-amber-500/20' : 'bg-emerald-100 dark:bg-emerald-500/20';
                      const txt = hrs === 0 ? 'text-slate-200 dark:text-gray-700' : cellPct > 80 ? 'text-red-700 dark:text-red-400' : cellPct > 40 ? 'text-amber-700 dark:text-amber-400' : 'text-emerald-700 dark:text-emerald-400';
                      return (
                        <td key={p.id} className="px-3 py-3 text-center">
                          <span className={`text-xs font-bold tabular-nums px-2 py-1 rounded-lg ${bg} ${txt}`}>{hrs > 0 ? `${hrs}h` : '—'}</span>
                        </td>
                      );
                    })}
                    <td className="px-3 py-3 text-center text-sm font-semibold tabular-nums text-slate-700 dark:text-gray-200">{totalAlloc}h</td>
                    <td className="px-3 py-3 text-center">
                      <span className={`text-xs font-bold px-2 py-1 rounded-full ${over ? 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400' : pct > 80 ? 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-400' : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400'}`}>{pct}%</span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {team.filter(m => {
        const total = Object.values(m.allocatedHrs || {}).reduce((s,h) => s+h, 0);
        return total > m.capacityHrsWeek;
      }).map(m => {
        const total = Object.values(m.allocatedHrs || {}).reduce((s,h) => s+h, 0);
        return (
          <div key={m.id} className="flex items-center gap-3 p-3 bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/20 rounded-xl">
            <Avatar m={m}/>
            <p className="text-sm text-red-700 dark:text-red-400 flex-1">
              <span className="font-semibold">{m.firstName} {m.lastName}</span> está sobreasignado/a — {total}h asignadas vs {m.capacityHrsWeek}h de capacidad ({Math.round(total/m.capacityHrsWeek*100)}%)
            </p>
          </div>
        );
      })}
    </div>
  );
}

// ── Tab 3: Costos ─────────────────────────────────────────────────────────────
function TeamCostos({ team = MOCK_TEAM, projectId }) {
  const proyectos = projectId ? MOCK_PROJECTS.filter(p => p.id === projectId) : MOCK_PROJECTS;

  const costoHumanoTotal = useMemo(() => team.reduce((s, m) => s + weeklyRate(m) * 4.33, 0), [team]);
  const costoEquipoTotal = useMemo(() =>
    MOCK_EQUIPMENT.filter(e => e.costType !== 'FIJO').reduce((s, e) => {
      const monthly = e.costType === 'MES' ? e.costRate : e.costType === 'DIA' ? e.costRate * 22 : 0;
      return s + monthly;
    }, 0), []);
  const costoFijoTotal = useMemo(() => MOCK_EQUIPMENT.filter(e => e.costType === 'FIJO').reduce((s, e) => s + e.costRate, 0), []);

  const costoPorProyecto = useMemo(() =>
    proyectos.map(p => {
      const miembros = team.filter(m => m.projects && m.projects.includes(p.code));
      const costo = miembros.reduce((s, m) => {
        const hrs = m.allocatedHrs && m.allocatedHrs[p.code] || 0;
        return s + hrs * rateToHour(m);
      }, 0);
      return { project: p, costo, miembros: miembros.length };
    }), [proyectos]);

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 xl:grid-cols-4 gap-3">
        {[
          { label:'Equipo humano/mes',   val: costoHumanoTotal, sub: `${team.length} personas`,                                             color:'text-blue-600 dark:text-blue-400' },
          { label:'Equipos/software/mes',val: costoEquipoTotal, sub: `${MOCK_EQUIPMENT.filter(e=>e.costType!=='FIJO').length} recursos recurrentes`, color:'text-amber-600 dark:text-amber-400' },
          { label:'Contratos fijos',     val: costoFijoTotal,   sub: `${MOCK_EQUIPMENT.filter(e=>e.costType==='FIJO').length} contratos`,          color:'text-purple-600 dark:text-purple-400' },
          { label:'Total operativo/mes', val: costoHumanoTotal+costoEquipoTotal, sub: 'Sin contratos fijos',                                        color:'text-slate-900 dark:text-white' },
        ].map(({ label, val, sub, color }) => (
          <div key={label} className="bg-white dark:bg-surface-800 rounded-2xl p-4 border border-slate-200 dark:border-surface-700 shadow-sm">
            <p className="text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider mb-2">{label}</p>
            <p className={`text-xl font-bold tabular-nums ${color}`}>{fmt(val)}</p>
            <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">{sub}</p>
          </div>
        ))}
      </div>

      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
        <div className="px-5 py-4 border-b border-slate-100 dark:border-surface-700">
          <p className="text-sm font-semibold text-slate-800 dark:text-white">Estructura de costos — equipo humano</p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100 dark:border-surface-700">
                {['Recurso','Rol','Tarifa','Equiv. $/hr','Cap. sem','Costo sem','Costo mes'].map(h => (
                  <th key={h} className="px-4 py-2.5 text-left text-xs font-medium text-slate-400 dark:text-gray-500 uppercase tracking-wider whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
              {team.map(m => {
                const hr = rateToHour(m);
                const wk = weeklyRate(m);
                const mo = wk * 4.33;
                return (
                  <tr key={m.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <Avatar m={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="px-4 py-3"><span className={`text-xs px-1.5 py-0.5 rounded-full ${ROLE_COLOR[m.role] || ''}`}>{ROLE_LABELS[m.role] || m.role}</span></td>
                    <td className="px-4 py-3 text-sm font-semibold text-blue-600 dark:text-blue-400 tabular-nums">{fmtR(m)}</td>
                    <td className="px-4 py-3 text-sm tabular-nums text-slate-600 dark:text-gray-300 font-mono">${hr.toFixed(2)}/hr</td>
                    <td className="px-4 py-3 text-sm tabular-nums text-slate-600 dark:text-gray-300">{m.capacityHrsWeek}h</td>
                    <td className="px-4 py-3 text-sm tabular-nums font-semibold text-slate-700 dark:text-gray-200">{fmt(wk)}</td>
                    <td className="px-4 py-3 text-sm tabular-nums font-bold text-slate-900 dark:text-white">{fmt(mo)}</td>
                  </tr>
                );
              })}
              <tr className="bg-slate-50 dark:bg-surface-700/30">
                <td colSpan={5} className="px-4 py-3 text-sm font-semibold text-slate-900 dark:text-white">Total equipo</td>
                <td className="px-4 py-3 text-sm font-bold tabular-nums text-blue-600 dark:text-blue-400">{fmt(team.reduce((s,m) => s+weeklyRate(m), 0))}</td>
                <td className="px-4 py-3 text-sm font-bold tabular-nums text-blue-600 dark:text-blue-400">{fmt(costoHumanoTotal)}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm p-5">
        <p className="text-sm font-semibold text-slate-800 dark:text-white mb-1">Costo de recursos humanos por proyecto</p>
        <p className="text-xs text-slate-400 dark:text-gray-500 mb-4">Basado en horas asignadas × tarifa/hora equivalente</p>
        <div className="space-y-4">
          {costoPorProyecto.map(({ project: p, costo, miembros }) => (
            <div key={p.id}>
              <div className="flex items-center justify-between mb-1.5">
                <div>
                  <span className="text-xs font-mono text-slate-400 dark:text-gray-500 mr-2">{p.code}</span>
                  <span className="text-sm font-medium text-slate-800 dark:text-gray-200">{p.name}</span>
                </div>
                <div className="text-right">
                  <span className="text-sm font-bold text-blue-600 dark:text-blue-400 tabular-nums">{fmt(costo)}</span>
                  <span className="text-xs text-slate-400 dark:text-gray-500 ml-2">{miembros} persona{miembros !== 1 ? 's' : ''}</span>
                </div>
              </div>
              <div className="h-2 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
                <div className="h-full rounded-full bg-blue-500" style={{ width: `${costoHumanoTotal > 0 ? Math.round(costo / costoHumanoTotal * 100) : 0}%` }}/>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────
const COLORS = ['#2563EB','#10B981','#8B5CF6','#F59E0B','#EF4444','#06B6D4','#EC4899','#14B8A6'];
const ROLES  = ['SUPER_ADMIN','GERENTE','LIDER','DEVELOPER','ANALISTA','DISEÑADOR','QA','CONSULTOR','INSPECTOR','OTRO'];
const DEPTS  = ['Dirección','Tecnología','Construcción','Finanzas','Arte','Legal','Operaciones','RRHH'];
const DAYS   = ['Lun','Mar','Mié','Jue','Vie','Sáb','Dom'];

function AddResourceModal({ onClose, onSave, initialData }) {
  const allProjects = getAllActiveProjects();
  const isEdit = !!initialData;
  const [form, setForm] = useState({
    firstName: initialData?.firstName || '',
    lastName:  initialData?.lastName  || '',
    role:      initialData?.role      || 'DEVELOPER',
    dept:      initialData?.dept      || 'Tecnología',
    title:     initialData?.title     || '',
    email:     initialData?.email     || '',
    phone:     initialData?.phone     || '',
    color:     initialData?.color     || COLORS[0],
    costType:  initialData?.costType  || 'MES',
    costRate:  initialData?.costRate  || '',
    currency:  initialData?.currency  || 'USD',
    hoursPerDay:  initialData?.hoursPerDay  || 8,
    daysPerWeek:  initialData?.daysPerWeek  || 5,
    startTime:    initialData?.startTime    || '09:00',
    endTime:      initialData?.endTime      || '17:00',
    workDays:     initialData?.workDays     || ['Lun','Mar','Mié','Jue','Vie'],
    skills: (initialData?.skills || []).join(', '),
  });
  // hours per project: { 'PRY-2026-004': 20, ... }
  const [projHours, setProjHours] = useState(initialData?.allocatedHrs || {});
  const set = (k,v) => setForm(f => ({...f, [k]:v}));
  const toggleDay = d => set('workDays', form.workDays.includes(d) ? form.workDays.filter(x=>x!==d) : [...form.workDays,d]);
  const setHrs = (code, val) => setProjHours(h => ({ ...h, [code]: val === '' ? 0 : Math.max(0, +val) }));

  const capacity   = form.hoursPerDay * form.daysPerWeek;
  const totalAssigned = Object.values(projHours).reduce((s,h) => s+(+h||0), 0);
  const overCapacity  = totalAssigned > capacity;
  const initials   = `${form.firstName.charAt(0)}${form.lastName.charAt(0)}`.toUpperCase() || '?';
  const canSave    = form.firstName.trim() && form.lastName.trim() && form.email.trim() && form.costRate;

  const handleSave = () => {
    const allocatedHrs = Object.fromEntries(
      Object.entries(projHours).filter(([,h]) => (+h||0) > 0)
    );
    const assignedCodes = Object.keys(allocatedHrs);
    const saved = {
      ...(initialData || {}),
      id: initialData?.id || `u${Date.now()}`,
      resourceType:'HUMANO',
      firstName: form.firstName.trim(), lastName: form.lastName.trim(),
      role: form.role, dept: form.dept, title: form.title.trim(),
      email: form.email.trim(), phone: form.phone.trim(),
      avatar: initials, color: form.color,
      costType: form.costType, costRate: parseFloat(form.costRate)||0, currency: form.currency,
      hoursPerDay: +form.hoursPerDay, daysPerWeek: +form.daysPerWeek,
      startTime: form.startTime, endTime: form.endTime,
      workDays: form.workDays, capacityHrsWeek: capacity,
      projects: assignedCodes,
      tasks: initialData?.tasks || { COMPLETADA:0, EN_PROCESO:0, PENDIENTE:0, BLOQUEADA:0 },
      allocatedHrs,
      skills: form.skills.split(',').map(s=>s.trim()).filter(Boolean),
    };
    onSave(saved);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-xl border border-slate-200 dark:border-surface-700 w-full max-w-lg max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-surface-700">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold text-white" style={{background: form.color}}>{initials}</div>
            <div>
              <p className="text-sm font-bold text-slate-900 dark:text-white">{isEdit ? 'Editar recurso' : 'Agregar recurso'}</p>
              <p className="text-xs text-slate-400 dark:text-gray-500">{isEdit ? `${initialData.firstName} ${initialData.lastName}` : 'Nuevo miembro del equipo'}</p>
            </div>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-surface-700 transition cursor-pointer">
            <svg className="w-4 h-4 text-slate-400" 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>
        {/* Body */}
        <div className="overflow-y-auto px-6 py-4 space-y-4 flex-1">
          {/* Nombre */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="field-label">Nombre *</label>
              <input className="field-input" value={form.firstName} onChange={e=>set('firstName',e.target.value)} placeholder="Ana"/>
            </div>
            <div>
              <label className="field-label">Apellido *</label>
              <input className="field-input" value={form.lastName} onChange={e=>set('lastName',e.target.value)} placeholder="Torres"/>
            </div>
          </div>
          {/* Rol / Dpto / Título */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="field-label">Rol</label>
              <select className="field-input" value={form.role} onChange={e=>set('role',e.target.value)}>
                {ROLES.map(r=><option key={r}>{r}</option>)}
              </select>
            </div>
            <div>
              <label className="field-label">Departamento</label>
              <select className="field-input" value={form.dept} onChange={e=>set('dept',e.target.value)}>
                {DEPTS.map(d=><option key={d}>{d}</option>)}
              </select>
            </div>
          </div>
          <div>
            <label className="field-label">Título / Cargo</label>
            <input className="field-input" value={form.title} onChange={e=>set('title',e.target.value)} placeholder="Desarrollador Senior"/>
          </div>
          {/* Contacto */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="field-label">Email *</label>
              <input className="field-input" type="email" value={form.email} onChange={e=>set('email',e.target.value)} placeholder="nombre@empresa.com"/>
            </div>
            <div>
              <label className="field-label">Teléfono</label>
              <input className="field-input" value={form.phone} onChange={e=>set('phone',e.target.value)} placeholder="+1 555-0000"/>
            </div>
          </div>
          {/* Color avatar */}
          <div>
            <label className="field-label">Color avatar</label>
            <div className="flex gap-2 flex-wrap">
              {COLORS.map(c=>(
                <button key={c} onClick={()=>set('color',c)} className="w-7 h-7 rounded-full border-2 transition cursor-pointer" style={{background:c, borderColor: form.color===c ? '#0f172a' : 'transparent'}}/>
              ))}
            </div>
          </div>
          {/* Costo */}
          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className="field-label">Tipo tarifa</label>
              <select className="field-input" value={form.costType} onChange={e=>set('costType',e.target.value)}>
                {['HORA','DIA','MES'].map(t=><option key={t}>{t}</option>)}
              </select>
            </div>
            <div>
              <label className="field-label">Tarifa * (USD)</label>
              <input className="field-input" type="number" min="0" value={form.costRate} onChange={e=>set('costRate',e.target.value)} placeholder="5000"/>
            </div>
            <div>
              <label className="field-label">Moneda</label>
              <select className="field-input" value={form.currency} onChange={e=>set('currency',e.target.value)}>
                {['USD','EUR','COP','MXN'].map(c=><option key={c}>{c}</option>)}
              </select>
            </div>
          </div>
          {/* Horario */}
          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className="field-label">Hrs/día</label>
              <input className="field-input" type="number" min="1" max="24" value={form.hoursPerDay} onChange={e=>set('hoursPerDay',+e.target.value)}/>
            </div>
            <div>
              <label className="field-label">Entrada</label>
              <input className="field-input" type="time" value={form.startTime} onChange={e=>set('startTime',e.target.value)}/>
            </div>
            <div>
              <label className="field-label">Salida</label>
              <input className="field-input" type="time" value={form.endTime} onChange={e=>set('endTime',e.target.value)}/>
            </div>
          </div>
          {/* Días laborables */}
          <div>
            <label className="field-label">Días laborables · capacidad {capacity}h/sem</label>
            <div className="flex gap-2 flex-wrap">
              {DAYS.map(d=>(
                <button key={d} onClick={()=>toggleDay(d)} className={`px-3 py-1 text-xs font-semibold rounded-lg border transition cursor-pointer ${form.workDays.includes(d) ? 'bg-blue-600 text-white border-blue-600' : 'border-slate-200 dark:border-surface-600 text-slate-500 dark:text-gray-400 hover:border-blue-400'}`}>{d}</button>
              ))}
            </div>
          </div>
          {/* Asignación a proyectos */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="field-label mb-0">Asignación a proyectos</label>
              {totalAssigned > 0 && (
                <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${overCapacity ? 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400' : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400'}`}>
                  {totalAssigned}h / {capacity}h sem {overCapacity ? '⚠ sobreasignado' : ''}
                </span>
              )}
            </div>
            <div className="space-y-2">
              {allProjects.map(p => (
                <div key={p.id} className="flex items-center gap-3">
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-medium text-slate-700 dark:text-gray-300 truncate">{p.name}</p>
                    <p className="text-xs text-slate-400 dark:text-gray-500 font-mono">{p.code}</p>
                  </div>
                  <div className="flex items-center gap-1.5 flex-shrink-0">
                    <input
                      type="number" min="0" max={capacity}
                      value={projHours[p.code] || ''}
                      onChange={e => setHrs(p.code, e.target.value)}
                      placeholder="0"
                      className="w-16 px-2 py-1.5 text-sm text-center rounded-lg border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500 transition"
                    />
                    <span className="text-xs text-slate-400 dark:text-gray-500 w-6">h</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
          {/* Skills */}
          <div>
            <label className="field-label">Habilidades (separadas por coma)</label>
            <input className="field-input" value={form.skills} onChange={e=>set('skills',e.target.value)} placeholder="React, Node.js, SQL"/>
          </div>
        </div>
        {/* Footer */}
        <div className="px-6 py-4 border-t border-slate-100 dark:border-surface-700 flex justify-end gap-2">
          <button onClick={onClose} className="px-4 py-2 text-sm font-medium 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 transition cursor-pointer">Cancelar</button>
          <button onClick={handleSave} disabled={!canSave} className="px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed text-white transition cursor-pointer shadow-sm">{isEdit ? 'Guardar cambios' : 'Guardar recurso'}</button>
        </div>
      </div>
    </div>
  );
}

export default function TeamPage() {
  const { selectedProjectId } = useProject();
  const [tab, setTab]       = useState(0);
  const [selected,    setSelected]    = useState(null);
  const [addOpen,     setAddOpen]     = useState(false);
  const [editTarget,  setEditTarget]  = useState(null);
  const [localTeam,   setLocalTeam]   = useState(() => {
    try { const s = localStorage.getItem('arpm_team'); return s ? JSON.parse(s) : MOCK_TEAM; } catch { return MOCK_TEAM; }
  });

  const saveTeam = (list) => { setLocalTeam(list); localStorage.setItem('arpm_team', JSON.stringify(list)); };

  const totalMonthlyCost = useMemo(() => localTeam.reduce((s, m) => s + weeklyRate(m) * 4.33, 0), [localTeam]);
  const overloaded = localTeam.filter(m => {
    const tot = Object.values(m.allocatedHrs || {}).reduce((s,h) => s+h, 0);
    return tot > m.capacityHrsWeek;
  }).length;

  return (
    <div className="space-y-5 pb-6">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">Equipo & Recursos</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">
            {localTeam.length} personas · {MOCK_EQUIPMENT.length} recursos no-humanos · {fmt(totalMonthlyCost)}/mes
            {overloaded > 0 && <span className="ml-2 text-red-500 font-semibold">⚠ {overloaded} sobreasignado{overloaded > 1 ? 's' : ''}</span>}
          </p>
        </div>
        <button onClick={() => setAddOpen(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 shadow-sm">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"/></svg>
          Agregar recurso
        </button>
      </div>

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

      {tab === 0 && <TeamHumano team={localTeam} onSelect={setSelected} onEdit={m => setEditTarget(m)} projectId={selectedProjectId}/>}
      {tab === 1 && <TeamEquipos projectId={selectedProjectId}/>}
      {tab === 2 && <TeamCapacidad team={localTeam} projectId={selectedProjectId}/>}
      {tab === 3 && <TeamCostos team={localTeam} projectId={selectedProjectId}/>}

      {selected && <MemberModal member={selected} onClose={() => setSelected(null)}/>}
      {addOpen && (
        <AddResourceModal
          onClose={() => setAddOpen(false)}
          onSave={m => saveTeam([...localTeam, m])}
        />
      )}
      {editTarget && (
        <AddResourceModal
          initialData={editTarget}
          onClose={() => setEditTarget(null)}
          onSave={m => { saveTeam(localTeam.map(x => x.id === m.id ? m : x)); setEditTarget(null); }}
        />
      )}
    </div>
  );
}
