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

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

const TEAM_MEMBERS = [
  { id: 'm1', name: 'Carlos Mendez',   initials: 'CM', role: 'Tech Lead',          projectId: 'p4', color: 'bg-blue-500' },
  { id: 'm2', name: 'Laura Gómez',     initials: 'LG', role: 'Frontend Dev',       projectId: 'p4', color: 'bg-purple-500' },
  { id: 'm3', name: 'Diego Ríos',      initials: 'DR', role: 'Backend Dev',        projectId: 'p4', color: 'bg-green-500' },
  { id: 'm4', name: 'Sofía Herrera',   initials: 'SH', role: 'Scrum Master',       projectId: 'p4', color: 'bg-amber-500' },
  { id: 'm5', name: 'Andrés Vargas',   initials: 'AV', role: 'Arquitecto',         projectId: 'p4', color: 'bg-teal-500' },
  { id: 'm6', name: 'Valentina Cruz',  initials: 'VC', role: 'QA Engineer',        projectId: 'p4', color: 'bg-rose-500' },
];

const TODAY_KEY = '2026-06-26';

const INITIAL_TODAY_STANDUPS = {
  m1: { yesterday: 'Completé la integración del módulo de autenticación con JWT y revisé los PRs pendientes del equipo.', today: 'Implementaré el endpoint de refresh token y haré code review del módulo de recursos.', blocker: '', submitted: true },
  m2: { yesterday: 'Terminé los componentes de la página de Recursos y el diseño responsive del dashboard.', today: 'Trabajaré en la página de Standup y los componentes de calendario.', blocker: '', submitted: true },
  m3: { yesterday: 'Migré las tablas de proveedores a la nueva estructura de base de datos.', today: 'Implementaré los endpoints REST para el módulo de inventario.', blocker: 'El entorno de staging está caído desde ayer por la tarde. Bloquea las pruebas de integración.', submitted: true },
  m4: { yesterday: 'Facilité la retrospectiva del sprint y actualicé el backlog con las nuevas historias.', today: 'Planificaré el sprint 8 con el equipo y actualizaré la documentación.', blocker: '', submitted: true },
  m5: { yesterday: '', today: '', blocker: '', submitted: false },
  m6: { yesterday: '', today: '', blocker: '', submitted: false },
};

const WEEK_HISTORY = {
  '2026-06-22': {
    m1: { submitted: true,  blocker: '' },
    m2: { submitted: true,  blocker: '' },
    m3: { submitted: true,  blocker: 'Acceso denegado al servidor de CI/CD' },
    m4: { submitted: true,  blocker: '' },
    m5: { submitted: false, blocker: '' },
    m6: { submitted: true,  blocker: '' },
  },
  '2026-06-23': {
    m1: { submitted: true,  blocker: '' },
    m2: { submitted: true,  blocker: '' },
    m3: { submitted: true,  blocker: 'Acceso denegado al servidor de CI/CD' },
    m4: { submitted: false, blocker: '' },
    m5: { submitted: true,  blocker: '' },
    m6: { submitted: true,  blocker: '' },
  },
  '2026-06-24': {
    m1: { submitted: true,  blocker: '' },
    m2: { submitted: true,  blocker: '' },
    m3: { submitted: true,  blocker: '' },
    m4: { submitted: true,  blocker: '' },
    m5: { submitted: true,  blocker: '' },
    m6: { submitted: false, blocker: '' },
  },
  '2026-06-25': {
    m1: { submitted: true,  blocker: '' },
    m2: { submitted: true,  blocker: 'Falta acceso al repositorio de diseño' },
    m3: { submitted: true,  blocker: 'Entorno de staging caído' },
    m4: { submitted: true,  blocker: '' },
    m5: { submitted: false, blocker: '' },
    m6: { submitted: true,  blocker: '' },
  },
  '2026-06-26': {
    m1: { submitted: true,  blocker: '' },
    m2: { submitted: true,  blocker: '' },
    m3: { submitted: true,  blocker: 'Entorno de staging caído' },
    m4: { submitted: true,  blocker: '' },
    m5: { submitted: false, blocker: '' },
    m6: { submitted: false, blocker: '' },
  },
};

const PREV_WEEK = {
  '2026-06-15': { m1:{submitted:true,blocker:''}, m2:{submitted:true,blocker:''}, m3:{submitted:false,blocker:''}, m4:{submitted:true,blocker:''}, m5:{submitted:true,blocker:''}, m6:{submitted:true,blocker:''} },
  '2026-06-16': { m1:{submitted:true,blocker:''}, m2:{submitted:false,blocker:''}, m3:{submitted:true,blocker:'Dependencia npm con conflicto de versiones'}, m4:{submitted:true,blocker:''}, m5:{submitted:true,blocker:''}, m6:{submitted:true,blocker:''} },
  '2026-06-17': { m1:{submitted:true,blocker:''}, m2:{submitted:true,blocker:''}, m3:{submitted:true,blocker:''}, m4:{submitted:true,blocker:''}, m5:{submitted:true,blocker:''}, m6:{submitted:false,blocker:''} },
  '2026-06-18': { m1:{submitted:false,blocker:''}, m2:{submitted:true,blocker:''}, m3:{submitted:true,blocker:''}, m4:{submitted:true,blocker:''}, m5:{submitted:true,blocker:''}, m6:{submitted:true,blocker:''} },
  '2026-06-19': { m1:{submitted:true,blocker:''}, m2:{submitted:true,blocker:''}, m3:{submitted:true,blocker:''}, m4:{submitted:true,blocker:''}, m5:{submitted:true,blocker:''}, m6:{submitted:true,blocker:''} },
};

const INITIAL_BLOCKERS = [
  { id: 'b1', description: 'Entorno de staging caído desde el martes. Bloquea todas las pruebas de integración del backend.', reporter: 'm3', projectId: 'p4', dateReported: '2026-06-21', daysOpen: 5, owner: null, status: 'REPORTADO', critical: true },
  { id: 'b2', description: 'Falta acceso al repositorio de diseño en Figma para revisar los componentes actualizados.', reporter: 'm2', projectId: 'p4', dateReported: '2026-06-24', daysOpen: 2, owner: 'm1', status: 'EN_RESOLUCIÓN', critical: false },
  { id: 'b3', description: 'Acceso denegado al servidor de CI/CD. No se pueden desplegar los builds automáticos.', reporter: 'm3', projectId: 'p4', dateReported: '2026-06-25', daysOpen: 1, owner: null, status: 'RESUELTO', critical: false },
];

const WEEK_DAYS = [
  { key: '2026-06-22', label: 'Lun 22' },
  { key: '2026-06-23', label: 'Mar 23' },
  { key: '2026-06-24', label: 'Mié 24' },
  { key: '2026-06-25', label: 'Jue 25' },
  { key: '2026-06-26', label: 'Vie 26' },
];

const PREV_WEEK_DAYS = [
  { key: '2026-06-15', label: 'Lun 15' },
  { key: '2026-06-16', label: 'Mar 16' },
  { key: '2026-06-17', label: 'Mié 17' },
  { key: '2026-06-18', label: 'Jue 18' },
  { key: '2026-06-19', label: 'Vie 19' },
];

const STANDUP_CONTENT = {
  '2026-06-25-m1': { yesterday: 'Revisé arquitectura del módulo de autenticación.', today: 'Implementaré JWT.', blocker: '' },
  '2026-06-25-m2': { yesterday: 'Diseñé componentes del dashboard.', today: 'Trabajo en componentes de Recursos.', blocker: 'Falta acceso al repositorio de diseño en Figma.' },
  '2026-06-25-m3': { yesterday: 'Migré estructura de base de datos.', today: 'Endpoints REST para inventario.', blocker: 'Entorno de staging caído.' },
  '2026-06-24-m1': { yesterday: 'Code review del módulo de login.', today: 'Arquitectura de autenticación.', blocker: '' },
};

const PROJECT_NAMES = { p1: 'AR-ProjectManagement', p2: 'Álbum Horizontes', p3: 'AR-ProjectManagement', p4: 'AR-ProjectManagement' };

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

function getMemberById(id) { return TEAM_MEMBERS.find(m => m.id === id); }

function calcParticipation(days, history) {
  let total = 0, submitted = 0;
  days.forEach(d => {
    TEAM_MEMBERS.forEach(m => {
      total++;
      if (history[d.key]?.[m.id]?.submitted) submitted++;
    });
  });
  return total ? Math.round((submitted / total) * 100) : 0;
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function Avatar({ member, size = 'md' }) {
  const sz = size === 'lg' ? 'w-12 h-12 text-base' : 'w-9 h-9 text-sm';
  return (
    <div className={`${sz} ${member.color} rounded-full flex items-center justify-center text-white font-bold flex-shrink-0`}>
      {member.initials}
    </div>
  );
}

function MemberCard({ member, standup, onChange, onSubmit }) {
  const hasBlocker = standup.blocker.trim().length > 0;

  return (
    <div className={`bg-white dark:bg-slate-900 rounded-2xl border p-5 space-y-4 transition-all ${standup.submitted ? 'border-green-200 dark:border-green-800' : 'border-slate-200 dark:border-slate-700'}`}>
      <div className="flex items-center gap-3">
        <Avatar member={member} />
        <div className="min-w-0">
          <p className="font-semibold text-slate-900 dark:text-white text-sm truncate">{member.name}</p>
          <p className="text-xs text-slate-500 dark:text-slate-400">{member.role}</p>
        </div>
        {standup.submitted && (
          <div className="ml-auto flex-shrink-0 w-7 h-7 bg-green-100 dark:bg-green-900/40 rounded-full flex items-center justify-center">
            <span className="text-green-600 dark:text-green-400 text-sm">✓</span>
          </div>
        )}
      </div>

      <div className="space-y-3">
        <div>
          <label className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 dark:text-slate-300 mb-1.5">
            <span>✅</span> ¿Qué hice ayer?
          </label>
          <textarea
            rows={2}
            disabled={standup.submitted}
            value={standup.yesterday}
            onChange={e => onChange('yesterday', e.target.value)}
            placeholder="Describe lo que completaste ayer..."
            className="w-full text-sm rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white placeholder-slate-400 px-3 py-2 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-60"
          />
        </div>
        <div>
          <label className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 dark:text-slate-300 mb-1.5">
            <span>🔲</span> ¿Qué haré hoy?
          </label>
          <textarea
            rows={2}
            disabled={standup.submitted}
            value={standup.today}
            onChange={e => onChange('today', e.target.value)}
            placeholder="Describe lo que planeas hacer hoy..."
            className="w-full text-sm rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white placeholder-slate-400 px-3 py-2 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-60"
          />
        </div>
        <div>
          <label className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 dark:text-slate-300 mb-1.5">
            <span>🚫</span> ¿Tengo bloqueadores?
          </label>
          <textarea
            rows={2}
            disabled={standup.submitted}
            value={standup.blocker}
            onChange={e => onChange('blocker', e.target.value)}
            placeholder="Deja vacío si no tienes bloqueadores..."
            className={`w-full text-sm rounded-lg border bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white placeholder-slate-400 px-3 py-2 resize-none focus:outline-none focus:ring-2 disabled:opacity-60 ${hasBlocker ? 'border-red-400 dark:border-red-500 focus:ring-red-400' : 'border-slate-200 dark:border-slate-700 focus:ring-blue-500'}`}
          />
        </div>
      </div>

      {!standup.submitted && (
        <button
          onClick={onSubmit}
          disabled={!standup.yesterday.trim() || !standup.today.trim()}
          className="w-full bg-blue-600 hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors"
        >
          Enviar standup
        </button>
      )}
      {standup.submitted && (
        <p className="text-center text-xs text-green-600 dark:text-green-400 font-medium">Standup enviado ✓</p>
      )}
    </div>
  );
}

function CellPopup({ dayKey, memberId, onClose }) {
  const member = getMemberById(memberId);
  const histKey = `${dayKey}-${memberId}`;
  const content = STANDUP_CONTENT[histKey];
  const hist = (WEEK_HISTORY[dayKey] || PREV_WEEK[dayKey] || {})[memberId];

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={onClose}>
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 w-full max-w-md shadow-2xl" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            {member && <Avatar member={member} />}
            <div>
              <p className="font-bold text-slate-900 dark:text-white">{member?.name}</p>
              <p className="text-xs text-slate-500 dark:text-slate-400">{dayKey}</p>
            </div>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-xl leading-none">&times;</button>
        </div>
        {hist?.submitted && content ? (
          <div className="space-y-3 text-sm">
            <div><p className="font-semibold text-slate-600 dark:text-slate-300 mb-1">✅ Ayer</p><p className="text-slate-700 dark:text-slate-300">{content.yesterday}</p></div>
            <div><p className="font-semibold text-slate-600 dark:text-slate-300 mb-1">🔲 Hoy</p><p className="text-slate-700 dark:text-slate-300">{content.today}</p></div>
            {content.blocker && <div><p className="font-semibold text-red-500 mb-1">🚫 Bloqueador</p><p className="text-red-600 dark:text-red-400">{content.blocker}</p></div>}
          </div>
        ) : hist?.submitted ? (
          <p className="text-slate-500 dark:text-slate-400 text-sm">Standup enviado — detalle no disponible.</p>
        ) : (
          <p className="text-slate-500 dark:text-slate-400 text-sm">No envió standup este día.</p>
        )}
      </div>
    </div>
  );
}

// ─── Tab 1: Today ─────────────────────────────────────────────────────────────

function TodayTab({ selectedProjectId }) {
  const [standups, setStandups] = useState(INITIAL_TODAY_STANDUPS);

  const filtered = TEAM_MEMBERS.filter(m => !selectedProjectId || m.projectId === selectedProjectId);
  const submitted = filtered.filter(m => standups[m.id]?.submitted).length;

  function handleChange(memberId, field, value) {
    setStandups(prev => ({ ...prev, [memberId]: { ...prev[memberId], [field]: value } }));
  }

  function handleSubmit(memberId) {
    setStandups(prev => ({ ...prev, [memberId]: { ...prev[memberId], submitted: true } }));
  }

  const pct = filtered.length ? Math.round((submitted / filtered.length) * 100) : 0;

  return (
    <div className="space-y-6">
      {/* Summary bar */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
        <div className="flex items-center justify-between mb-3">
          <p className="text-sm font-semibold text-slate-700 dark:text-slate-200">
            Participación hoy — <span className="text-blue-600 dark:text-blue-400">{submitted}/{filtered.length} miembros enviaron</span>
          </p>
          <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${pct === 100 ? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400' : 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400'}`}>
            {pct}%
          </span>
        </div>
        <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-2">
          <div className="bg-blue-600 h-2 rounded-full transition-all duration-500" style={{ width: `${pct}%` }} />
        </div>
      </div>

      {/* Member cards grid */}
      {filtered.length === 0 ? (
        <p className="text-center text-slate-500 dark:text-slate-400 py-12">No hay miembros para este proyecto.</p>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {filtered.map(member => (
            <MemberCard
              key={member.id}
              member={member}
              standup={standups[member.id] || { yesterday: '', today: '', blocker: '', submitted: false }}
              onChange={(field, val) => handleChange(member.id, field, val)}
              onSubmit={() => handleSubmit(member.id)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Tab 2: History ───────────────────────────────────────────────────────────

function HistoryTab({ selectedProjectId }) {
  const [weekIndex, setWeekIndex] = useState(1); // 0 = prev week, 1 = current week
  const [popup, setPopup] = useState(null);

  const weeks = [
    { label: 'Semana 15–19 Jun 2026', days: PREV_WEEK_DAYS, history: PREV_WEEK },
    { label: 'Semana 22–26 Jun 2026', days: WEEK_DAYS, history: WEEK_HISTORY },
  ];

  const { label, days, history } = weeks[weekIndex];
  const filtered = TEAM_MEMBERS.filter(m => !selectedProjectId || m.projectId === selectedProjectId);
  const pct = calcParticipation(days, history);

  const weekBlockers = [];
  days.forEach(d => {
    filtered.forEach(m => {
      const h = history[d.key]?.[m.id];
      if (h?.blocker) weekBlockers.push({ day: d.label, member: m, blocker: h.blocker });
    });
  });

  function cellIcon(dayKey, memberId) {
    const h = history[dayKey]?.[memberId];
    if (!h) return <span className="text-slate-300 dark:text-slate-600">—</span>;
    if (!h.submitted) return <span className="text-slate-400 dark:text-slate-500 text-base">—</span>;
    if (h.blocker) return <span className="text-red-500 text-base" title={h.blocker}>✕</span>;
    return <span className="text-green-500 text-base">✓</span>;
  }

  return (
    <div className="space-y-6">
      {/* Week navigation */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
        <div className="flex items-center justify-between mb-4">
          <button
            onClick={() => setWeekIndex(i => Math.max(0, i - 1))}
            disabled={weekIndex === 0}
            className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 disabled:opacity-30 text-slate-600 dark:text-slate-300 transition-colors"
          >
            ←
          </button>
          <div className="text-center">
            <p className="font-semibold text-slate-900 dark:text-white text-sm">{label}</p>
            <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Participación: {pct}%</p>
          </div>
          <button
            onClick={() => setWeekIndex(i => Math.min(weeks.length - 1, i + 1))}
            disabled={weekIndex === weeks.length - 1}
            className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 disabled:opacity-30 text-slate-600 dark:text-slate-300 transition-colors"
          >
            →
          </button>
        </div>
        <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-2 mb-4">
          <div className="bg-green-500 h-2 rounded-full transition-all" style={{ width: `${pct}%` }} />
        </div>

        {/* Table */}
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-200 dark:border-slate-700">
                <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">Miembro</th>
                {days.map(d => (
                  <th key={d.key} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-center">{d.label}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(member => (
                <tr key={member.id} className="border-b border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <Avatar member={member} size="sm" />
                      <span className="font-medium text-slate-900 dark:text-white text-sm">{member.name}</span>
                    </div>
                  </td>
                  {days.map(d => (
                    <td key={d.key} className="px-4 py-3 text-center">
                      <button
                        onClick={() => setPopup({ dayKey: d.key, memberId: member.id })}
                        className="w-8 h-8 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 flex items-center justify-center mx-auto transition-colors"
                      >
                        {cellIcon(d.key, member.id)}
                      </button>
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="flex items-center gap-4 mt-3 text-xs text-slate-500 dark:text-slate-400">
          <span className="flex items-center gap-1"><span className="text-green-500">✓</span> Enviado</span>
          <span className="flex items-center gap-1"><span className="text-red-500">✕</span> Con bloqueador</span>
          <span className="flex items-center gap-1"><span>—</span> No enviado</span>
        </div>
      </div>

      {/* Blockers this week */}
      {weekBlockers.length > 0 && (
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
          <h3 className="font-bold text-slate-900 dark:text-white mb-4">Bloqueadores de la semana</h3>
          <div className="space-y-3">
            {weekBlockers.map((b, i) => (
              <div key={i} className="flex items-start gap-3 p-3 bg-red-50 dark:bg-red-900/10 rounded-xl border border-red-100 dark:border-red-900/30">
                <Avatar member={b.member} size="sm" />
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2 mb-0.5">
                    <span className="text-xs font-semibold text-slate-600 dark:text-slate-300">{b.member.name}</span>
                    <span className="text-xs text-slate-400">· {b.day}</span>
                  </div>
                  <p className="text-sm text-red-700 dark:text-red-300">{b.blocker}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {popup && <CellPopup dayKey={popup.dayKey} memberId={popup.memberId} onClose={() => setPopup(null)} />}
    </div>
  );
}

// ─── Tab 3: Blockers ──────────────────────────────────────────────────────────

function BlockersTab({ selectedProjectId }) {
  const [blockers, setBlockers] = useState(INITIAL_BLOCKERS);

  const filtered = blockers.filter(b => !selectedProjectId || b.projectId === selectedProjectId);
  const cols = ['REPORTADO', 'EN_RESOLUCIÓN', 'RESUELTO'];
  const colLabels = { REPORTADO: 'Reportado', EN_RESOLUCIÓN: 'En resolución', RESUELTO: 'Resuelto' };
  const colColors = { REPORTADO: 'text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/20', EN_RESOLUCIÓN: 'text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20', RESUELTO: 'text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-900/20' };

  function takeOwnership(id) {
    setBlockers(prev => prev.map(b => b.id === id ? { ...b, owner: 'm1', status: 'EN_RESOLUCIÓN' } : b));
  }

  function markResolved(id) {
    setBlockers(prev => prev.map(b => b.id === id ? { ...b, status: 'RESUELTO' } : b));
  }

  const resolved = filtered.filter(b => b.status === 'RESUELTO');
  const avgResolution = resolved.length > 0 ? '1.5 días' : 'N/A';
  const sprintActive = filtered.filter(b => b.status !== 'RESUELTO').length;

  return (
    <div className="space-y-6">
      {/* Summary */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: 'Activos este sprint', value: sprintActive, color: 'text-red-600 dark:text-red-400' },
          { label: 'Resueltos esta semana', value: resolved.length, color: 'text-green-600 dark:text-green-400' },
          { label: 'Tiempo promedio resolución', value: avgResolution, color: 'text-blue-600 dark:text-blue-400' },
          { label: 'Críticos (>3 días)', value: filtered.filter(b => b.daysOpen > 3 && b.status !== 'RESUELTO').length, color: 'text-amber-600 dark:text-amber-400' },
        ].map(s => (
          <div key={s.label} className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
            <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">{s.label}</p>
            <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
          </div>
        ))}
      </div>

      {/* Kanban */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {cols.map(col => {
          const colItems = filtered.filter(b => b.status === col);
          return (
            <div key={col} className="bg-slate-100 dark:bg-slate-800/50 rounded-2xl p-4 space-y-3">
              <div className="flex items-center justify-between">
                <h3 className={`text-xs font-bold uppercase tracking-wider px-2 py-1 rounded-lg ${colColors[col]}`}>{colLabels[col]}</h3>
                <span className="text-xs text-slate-500 dark:text-slate-400 font-medium">{colItems.length}</span>
              </div>
              {colItems.length === 0 && (
                <p className="text-center text-xs text-slate-400 dark:text-slate-500 py-6">Sin bloqueadores</p>
              )}
              {colItems.map(b => {
                const reporter = getMemberById(b.reporter);
                const owner = b.owner ? getMemberById(b.owner) : null;
                const isCritical = b.daysOpen > 3 && b.status !== 'RESUELTO';
                return (
                  <div key={b.id} className={`bg-white dark:bg-slate-900 rounded-xl border p-4 space-y-3 ${isCritical ? 'border-red-300 dark:border-red-700' : 'border-slate-200 dark:border-slate-700'}`}>
                    {isCritical && (
                      <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400">
                        🔴 Crítico — {b.daysOpen} días abierto
                      </span>
                    )}
                    <p className="text-sm text-slate-700 dark:text-slate-200 leading-snug">{b.description}</p>
                    <div className="space-y-1.5 text-xs text-slate-500 dark:text-slate-400">
                      <div className="flex items-center gap-1.5">
                        {reporter && <Avatar member={reporter} size="sm" />}
                        <span>{reporter?.name} · {PROJECT_NAMES[b.projectId]}</span>
                      </div>
                      <p>Reportado: {b.dateReported} · {b.daysOpen}d abierto</p>
                      {owner && <p className="text-blue-600 dark:text-blue-400">Owner: {owner.name}</p>}
                    </div>
                    {col === 'REPORTADO' && (
                      <button
                        onClick={() => takeOwnership(b.id)}
                        className="w-full text-xs bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400 border border-amber-200 dark:border-amber-800 hover:bg-amber-100 dark:hover:bg-amber-900/40 rounded-lg px-3 py-2 font-medium transition-colors"
                      >
                        Tomar ownership
                      </button>
                    )}
                    {col === 'EN_RESOLUCIÓN' && (
                      <button
                        onClick={() => markResolved(b.id)}
                        className="w-full text-xs bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 border border-green-200 dark:border-green-800 hover:bg-green-100 dark:hover:bg-green-900/40 rounded-lg px-3 py-2 font-medium transition-colors"
                      >
                        Marcar resuelto
                      </button>
                    )}
                    {col === 'RESUELTO' && (
                      <span className="block text-center text-xs text-green-600 dark:text-green-400 font-medium">✓ Resuelto</span>
                    )}
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function StandupPage() {
  const { selectedProjectId } = useProject();
  const [activeTab, setActiveTab] = useState(0);

  const tabs = ['Standup de Hoy', 'Historial', 'Bloqueadores'];

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

        {/* Header */}
        <div>
          <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Daily Standup</h1>
          <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">
            Standup — Lunes 26 de junio 2026
            {selectedProjectId && (
              <span className="ml-2 rounded-full px-2.5 py-0.5 text-xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400">
                {PROJECT_NAMES[selectedProjectId]}
              </span>
            )}
          </p>
        </div>

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

        {/* Tab content */}
        {activeTab === 0 && <TodayTab selectedProjectId={selectedProjectId} />}
        {activeTab === 1 && <HistoryTab selectedProjectId={selectedProjectId} />}
        {activeTab === 2 && <BlockersTab selectedProjectId={selectedProjectId} />}
      </div>
    </div>
  );
}
