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

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

const MOCK_DELIVERABLES = [
  {
    id: 'd1',
    projectId: 'p4',
    code: 'ENT-2026-001',
    description: 'Informe de avance estructural — Nivel 3',
    contractor: 'Estructuras Modernas S.A.',
    submittedDate: '2026-06-20',
    slaDeadline: '2026-06-27',
    status: 'PENDIENTE',
    inspector: null,
    inspectorAssigned: null,
  },
  {
    id: 'd2',
    projectId: 'p4',
    code: 'ENT-2026-002',
    description: 'Planos as-built cimentación',
    contractor: 'Ingeniería Total Ltda.',
    submittedDate: '2026-06-18',
    slaDeadline: '2026-06-25',
    status: 'EN_INSPECCION',
    inspector: 'Arq. Carmen Ruiz',
    inspectorAssigned: '2026-06-19',
    checklistProgress: { done: 4, total: 7 },
  },
  {
    id: 'd3',
    projectId: 'p4',
    code: 'ENT-2026-003',
    description: 'Master mix — Pistas 1 a 5',
    contractor: 'Estudio Sonido Pro',
    submittedDate: '2026-06-15',
    slaDeadline: '2026-06-22',
    status: 'APROBADO',
    inspector: 'Ing. Luis Mora',
    approver: 'Dir. Ana Solis',
    acceptanceDate: '2026-06-21',
    actaNumber: 'ACTA-2026-001',
  },
  {
    id: 'd4',
    projectId: 'p4',
    code: 'ENT-2026-004',
    description: 'Módulo de contabilidad — v1.2',
    contractor: 'SoftTech Solutions',
    submittedDate: '2026-06-22',
    slaDeadline: '2026-06-24',
    status: 'RECHAZADO',
    inspector: 'Ing. Pedro Vega',
    rejectionReason: 'Errores en cierre de período fiscal',
    inspectorAssigned: '2026-06-22',
    checklistProgress: { done: 3, total: 6 },
  },
  {
    id: 'd5',
    projectId: 'p4',
    code: 'ENT-2026-005',
    description: 'Frontend — Sprint 4 entregable',
    contractor: 'AR Dev Team',
    submittedDate: '2026-06-23',
    slaDeadline: '2026-06-24',
    status: 'EN_INSPECCION',
    inspector: 'QA Laura Jiménez',
    inspectorAssigned: '2026-06-23',
    checklistProgress: { done: 2, total: 8 },
  },
  {
    id: 'd6',
    projectId: 'p4',
    code: 'ENT-2026-006',
    description: 'Diseño portada álbum — versión final',
    contractor: 'Studio Creativo MX',
    submittedDate: '2026-06-24',
    slaDeadline: '2026-06-28',
    status: 'PENDIENTE',
    inspector: null,
    inspectorAssigned: null,
  },
  {
    id: 'd7',
    projectId: 'p4',
    code: 'ENT-2026-007',
    description: 'Certificado de calidad — concreto Nivel 5',
    contractor: 'Laboratorio CalTest',
    submittedDate: '2026-06-10',
    slaDeadline: '2026-06-18',   // OVERDUE
    status: 'PENDIENTE',
    inspector: null,
    inspectorAssigned: null,
  },
  {
    id: 'd8',
    projectId: 'p4',
    code: 'ENT-2026-008',
    description: 'Manual de usuario ERP — módulo RRHH',
    contractor: 'DocTech Redacción',
    submittedDate: '2026-06-25',
    slaDeadline: '2026-06-26',   // near deadline (same day)
    status: 'EN_INSPECCION',
    inspector: 'Ing. Marco Torres',
    inspectorAssigned: '2026-06-25',
    checklistProgress: { done: 1, total: 5 },
  },
];

const INSPECTORS = [
  'Arq. Carmen Ruiz',
  'Ing. Luis Mora',
  'Ing. Pedro Vega',
  'QA Laura Jiménez',
  'Ing. Marco Torres',
  'Dra. Sofia Blanco',
];

const CHECKLIST_ITEMS = [
  'Documentación completa y legible',
  'Cumple especificaciones técnicas del contrato',
  'Aprobación de control de calidad interna',
  'Sin defectos críticos identificados',
  'Firma y sello del contratista presente',
  'Versión corresponde a la solicitada',
  'Pruebas de aceptación superadas',
  'Entrega dentro del plazo pactado',
];

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

function getDaysLeft(deadline) {
  const now = new Date('2026-06-26');
  const dl = new Date(deadline);
  return Math.round((dl - now) / (1000 * 60 * 60 * 24));
}

function formatDate(str) {
  if (!str) return '—';
  return new Date(str).toLocaleDateString('es-ES', { day: '2-digit', month: 'short', year: 'numeric' });
}

// ─── Status Badge ─────────────────────────────────────────────────────────────

function StatusBadge({ status }) {
  const map = {
    PENDIENTE:      'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400',
    EN_INSPECCION:  'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    APROBADO:       'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    RECHAZADO:      'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
  };
  const label = {
    PENDIENTE:      'Pendiente',
    EN_INSPECCION:  'En Inspección',
    APROBADO:       'Aprobado',
    RECHAZADO:      'Rechazado',
  };
  return (
    <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${map[status] || 'bg-slate-100 text-slate-600'}`}>
      {label[status] || status}
    </span>
  );
}

// ─── SLA Pill ────────────────────────────────────────────────────────────────

function SLAPill({ deadline }) {
  const days = getDaysLeft(deadline);
  if (days < 0) {
    return <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400">{Math.abs(days)}d vencido</span>;
  }
  if (days === 0) {
    return <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400">Vence hoy</span>;
  }
  if (days <= 2) {
    return <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">{days}d restante{days !== 1 ? 's' : ''}</span>;
  }
  return <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300">{days}d restantes</span>;
}

// ─── InspectionModal ─────────────────────────────────────────────────────────

function InspectionModal({ deliverable, onClose, onStart }) {
  const [inspector, setInspector] = useState('');
  const [notes, setNotes] = useState('');
  const [checklist, setChecklist] = useState(Array(CHECKLIST_ITEMS.length).fill(false));

  const toggleCheck = (i) => setChecklist(prev => prev.map((v, idx) => idx === i ? !v : v));
  const checkedCount = checklist.filter(Boolean).length;

  const handleStart = () => {
    if (!inspector) return;
    onStart({ deliverableId: deliverable.id, inspector, notes, checklist });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 w-full max-w-lg shadow-xl">
        <div className="p-6 border-b border-slate-200 dark:border-slate-700">
          <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Iniciar Inspección</h2>
          <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">{deliverable.code} — {deliverable.description}</p>
        </div>
        <div className="p-6 space-y-5 max-h-[70vh] overflow-y-auto">
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1.5">Inspector asignado *</label>
            <select
              value={inspector}
              onChange={e => setInspector(e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Seleccionar inspector…</option>
              {INSPECTORS.map(name => (
                <option key={name} value={name}>{name}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
              Checklist de inspección ({checkedCount}/{CHECKLIST_ITEMS.length})
            </label>
            <div className="space-y-2">
              {CHECKLIST_ITEMS.map((item, i) => (
                <label key={i} className="flex items-start gap-3 cursor-pointer group">
                  <input
                    type="checkbox"
                    checked={checklist[i]}
                    onChange={() => toggleCheck(i)}
                    className="mt-0.5 h-4 w-4 rounded text-blue-600 border-slate-300 dark:border-slate-600 focus:ring-blue-500"
                  />
                  <span className={`text-sm ${checklist[i] ? 'line-through text-slate-400' : 'text-slate-700 dark:text-slate-300'}`}>{item}</span>
                </label>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1.5">Notas iniciales</label>
            <textarea
              value={notes}
              onChange={e => setNotes(e.target.value)}
              rows={3}
              placeholder="Observaciones o comentarios iniciales…"
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
            />
          </div>
        </div>
        <div className="p-6 border-t border-slate-200 dark:border-slate-700 flex justify-end gap-3">
          <button onClick={onClose} className="px-4 py-2.5 text-sm font-medium text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-xl transition-colors">Cancelar</button>
          <button
            onClick={handleStart}
            disabled={!inspector}
            className="bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors"
          >
            Iniciar Inspección
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── ResultModal ─────────────────────────────────────────────────────────────

function ResultModal({ deliverable, onClose, onSubmit }) {
  const [result, setResult] = useState(null);
  const [findings, setFindings] = useState('');
  const [evidenceNote] = useState('Adjuntar evidencia fotográfica o documental al expediente físico.');

  const handleSubmit = () => {
    if (!result) return;
    onSubmit({ deliverableId: deliverable.id, result, findings });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 w-full max-w-md shadow-xl">
        <div className="p-6 border-b border-slate-200 dark:border-slate-700">
          <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Registrar Resultado</h2>
          <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">{deliverable.code} — {deliverable.description}</p>
        </div>
        <div className="p-6 space-y-5">
          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-3">Dictamen *</label>
            <div className="grid grid-cols-2 gap-3">
              <button
                onClick={() => setResult('APROBADO')}
                className={`p-4 rounded-xl border-2 text-sm font-semibold transition-all ${result === 'APROBADO' ? 'border-green-500 bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400' : 'border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-400 hover:border-green-300'}`}
              >
                ✓ Aprobado
              </button>
              <button
                onClick={() => setResult('RECHAZADO')}
                className={`p-4 rounded-xl border-2 text-sm font-semibold transition-all ${result === 'RECHAZADO' ? 'border-red-500 bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400' : 'border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-400 hover:border-red-300'}`}
              >
                ✗ Rechazado
              </button>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1.5">Hallazgos y observaciones</label>
            <textarea
              value={findings}
              onChange={e => setFindings(e.target.value)}
              rows={4}
              placeholder="Describir hallazgos, no conformidades o motivo de rechazo…"
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
            />
          </div>

          <div className="rounded-xl bg-slate-50 dark:bg-slate-800/60 border border-slate-200 dark:border-slate-700 px-4 py-3">
            <p className="text-xs text-slate-500 dark:text-slate-400">
              <span className="font-medium text-slate-700 dark:text-slate-300">Evidencia:</span> {evidenceNote}
            </p>
          </div>
        </div>
        <div className="p-6 border-t border-slate-200 dark:border-slate-700 flex justify-end gap-3">
          <button onClick={onClose} className="px-4 py-2.5 text-sm font-medium text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-xl transition-colors">Cancelar</button>
          <button
            onClick={handleSubmit}
            disabled={!result}
            className="bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors"
          >
            Confirmar Resultado
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── ActaModal ───────────────────────────────────────────────────────────────

function ActaModal({ deliverable, onClose }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 w-full max-w-lg shadow-xl">
        <div className="p-6 border-b border-slate-200 dark:border-slate-700 flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-slate-900 dark:text-white">Acta de Recepción</h2>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">{deliverable.actaNumber}</p>
          </div>
          <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">Aceptado</span>
        </div>
        <div className="p-6 space-y-4">
          {[
            ['Número de Acta', deliverable.actaNumber],
            ['Código Entregable', deliverable.code],
            ['Descripción', deliverable.description],
            ['Contratista / Proveedor', deliverable.contractor],
            ['Fecha de Recepción', formatDate(deliverable.submittedDate)],
            ['Fecha de Aceptación', formatDate(deliverable.acceptanceDate)],
            ['Inspector', deliverable.inspector],
            ['Aprobador', deliverable.approver],
          ].map(([label, value]) => (
            <div key={label} className="flex gap-4">
              <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 w-40 shrink-0 pt-0.5">{label}</span>
              <span className="text-sm text-slate-900 dark:text-white">{value || '—'}</span>
            </div>
          ))}
          <div className="rounded-xl bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 px-4 py-3 mt-2">
            <p className="text-xs text-green-700 dark:text-green-400 font-medium">Este documento es un registro oficial de aceptación formal. Todos los campos son de solo lectura.</p>
          </div>
        </div>
        <div className="p-6 border-t border-slate-200 dark:border-slate-700 flex justify-end">
          <button onClick={onClose} className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors">Cerrar</button>
        </div>
      </div>
    </div>
  );
}

// ─── Tab 1: Cola de Inspección ────────────────────────────────────────────────

function ColaInspeccion({ items, onInspect }) {
  if (items.length === 0) {
    return <EmptyState message="No hay entregables en cola para este proyecto." />;
  }
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
      {items.map(item => (
        <div key={item.id} className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5 flex flex-col gap-3">
          <div className="flex items-start justify-between gap-2">
            <div>
              <p className="text-xs font-mono text-slate-400 dark:text-slate-500">{item.code}</p>
              <p className="text-sm font-semibold text-slate-900 dark:text-white mt-0.5 leading-snug">{item.description}</p>
            </div>
            <StatusBadge status={item.status} />
          </div>
          <div className="text-xs text-slate-500 dark:text-slate-400 space-y-1">
            <div><span className="font-medium">Contratista:</span> {item.contractor}</div>
            <div><span className="font-medium">Recibido:</span> {formatDate(item.submittedDate)}</div>
            <div><span className="font-medium">SLA:</span> {formatDate(item.slaDeadline)}</div>
          </div>
          <div className="flex items-center justify-between mt-auto pt-2 border-t border-slate-100 dark:border-slate-800">
            <SLAPill deadline={item.slaDeadline} />
            {item.status === 'PENDIENTE' && (
              <button
                onClick={() => onInspect(item)}
                className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-3 py-1.5 text-xs font-medium transition-colors"
              >
                Iniciar Inspección
              </button>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Tab 2: Inspecciones Activas ──────────────────────────────────────────────

function InspeccionesActivas({ items, onResult }) {
  if (items.length === 0) {
    return <EmptyState message="No hay inspecciones activas en este momento." />;
  }
  return (
    <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-slate-50 dark:bg-slate-800/60">
          <tr>
            {['Código', 'Entregable', 'Inspector', 'Inicio', 'Checklist', 'SLA', ''].map(h => (
              <th key={h} className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-4 py-3 whitespace-nowrap">{h}</th>
            ))}
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
          {items.map(item => {
            const prog = item.checklistProgress || { done: 0, total: 8 };
            const pct = Math.round((prog.done / prog.total) * 100);
            return (
              <tr key={item.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors">
                <td className="px-4 py-3 font-mono text-xs text-slate-500 dark:text-slate-400 whitespace-nowrap">{item.code}</td>
                <td className="px-4 py-3 text-slate-900 dark:text-white max-w-[200px]">
                  <span className="line-clamp-2">{item.description}</span>
                </td>
                <td className="px-4 py-3 text-slate-700 dark:text-slate-300 whitespace-nowrap">{item.inspector}</td>
                <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{formatDate(item.inspectorAssigned)}</td>
                <td className="px-4 py-3">
                  <div className="flex items-center gap-2">
                    <div className="w-20 h-1.5 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
                      <div className="h-full bg-blue-500 rounded-full" style={{ width: `${pct}%` }} />
                    </div>
                    <span className="text-xs text-slate-500 dark:text-slate-400 whitespace-nowrap">{prog.done}/{prog.total}</span>
                  </div>
                </td>
                <td className="px-4 py-3 whitespace-nowrap"><SLAPill deadline={item.slaDeadline} /></td>
                <td className="px-4 py-3 text-right">
                  <button
                    onClick={() => onResult(item)}
                    className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-3 py-1.5 text-xs font-medium transition-colors whitespace-nowrap"
                  >
                    Registrar Resultado
                  </button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ─── Tab 3: Actas de Recepción ────────────────────────────────────────────────

const PROJECT_NAMES = {
  p1: 'AR-ProjectManagement Norte',
  p2: 'AR-ProjectManagement Horizontes',
  p3: 'Implementación ERP',
  p4: 'AR-ProjectManagement ERP',
};

function ActasRecepcion({ items, onViewActa }) {
  if (items.length === 0) {
    return <EmptyState message="Aún no hay actas de recepción registradas." />;
  }
  return (
    <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-slate-50 dark:bg-slate-800/60">
          <tr>
            {['N° Acta', 'Proyecto', 'Entregable', 'Contratista', 'Aceptación', 'Inspector', 'Aprobador', ''].map(h => (
              <th key={h} className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-4 py-3 whitespace-nowrap">{h}</th>
            ))}
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
          {items.map(item => (
            <tr key={item.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors">
              <td className="px-4 py-3 font-mono text-xs text-slate-500 dark:text-slate-400 whitespace-nowrap">{item.actaNumber}</td>
              <td className="px-4 py-3 text-slate-700 dark:text-slate-300 whitespace-nowrap">{PROJECT_NAMES[item.projectId] || item.projectId}</td>
              <td className="px-4 py-3 text-slate-900 dark:text-white max-w-[180px]">
                <span className="line-clamp-2">{item.description}</span>
              </td>
              <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{item.contractor}</td>
              <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{formatDate(item.acceptanceDate)}</td>
              <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{item.inspector}</td>
              <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{item.approver}</td>
              <td className="px-4 py-3 text-right">
                <button
                  onClick={() => onViewActa(item)}
                  className="flex items-center gap-1.5 text-blue-600 hover:text-blue-700 text-xs font-medium whitespace-nowrap"
                >
                  <span className="text-green-500">✓</span> Ver Acta
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ─── Tab 4: Alertas SLA ───────────────────────────────────────────────────────

function AlertasSLA({ items }) {
  const alerts = items.filter(item => {
    const days = getDaysLeft(item.slaDeadline);
    return days < 0 || (days <= 1 && item.status !== 'APROBADO');
  });

  if (alerts.length === 0) {
    return (
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-12 text-center">
        <div className="text-4xl mb-3">✅</div>
        <p className="text-slate-500 dark:text-slate-400 text-sm">Sin alertas SLA activas. Todos los plazos están bajo control.</p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {alerts.map(item => {
        const days = getDaysLeft(item.slaDeadline);
        const isOverdue = days < 0;
        return (
          <div
            key={item.id}
            className={`rounded-2xl border p-5 ${isOverdue ? 'bg-red-50 dark:bg-red-900/10 border-red-200 dark:border-red-800' : 'bg-amber-50 dark:bg-amber-900/10 border-amber-200 dark:border-amber-800'}`}
          >
            <div className="flex items-start justify-between gap-4">
              <div className="flex items-start gap-3">
                <span className="text-xl mt-0.5">{isOverdue ? '🔴' : '🟡'}</span>
                <div>
                  <p className={`text-sm font-semibold ${isOverdue ? 'text-red-900 dark:text-red-300' : 'text-amber-900 dark:text-amber-300'}`}>
                    {isOverdue ? `SLA VENCIDO — ${Math.abs(days)} día${Math.abs(days) !== 1 ? 's' : ''} de retraso` : `SLA PRÓXIMO — Vence en menos de 24h`}
                  </p>
                  <p className={`text-xs mt-0.5 ${isOverdue ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}`}>
                    {item.code} — {item.description}
                  </p>
                </div>
              </div>
              <StatusBadge status={item.status} />
            </div>
            <div className={`mt-4 grid grid-cols-2 md:grid-cols-3 gap-3 text-xs ${isOverdue ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}`}>
              <div><span className="font-medium block text-xs opacity-70 mb-0.5">Contratista</span>{item.contractor}</div>
              <div><span className="font-medium block text-xs opacity-70 mb-0.5">Responsable</span>{item.inspector || 'Sin asignar'}</div>
              <div><span className="font-medium block text-xs opacity-70 mb-0.5">Fecha límite SLA</span>{formatDate(item.slaDeadline)}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Empty State ──────────────────────────────────────────────────────────────

function EmptyState({ message }) {
  return (
    <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-12 text-center">
      <p className="text-slate-500 dark:text-slate-400 text-sm">{message}</p>
    </div>
  );
}

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

export default function ReceptionPage() {
  const { selectedProjectId } = useProject();
  const [activeTab, setActiveTab] = useState(0);
  const [deliverables, setDeliverables] = useState(MOCK_DELIVERABLES);
  const [inspectionModal, setInspectionModal] = useState(null);
  const [resultModal, setResultModal] = useState(null);
  const [actaModal, setActaModal] = useState(null);

  const filtered = useMemo(
    () => deliverables.filter(d => !selectedProjectId || d.projectId === selectedProjectId),
    [deliverables, selectedProjectId]
  );

  const colaItems = useMemo(() => filtered.filter(d => ['PENDIENTE', 'EN_INSPECCION', 'RECHAZADO'].includes(d.status)), [filtered]);
  const activasItems = useMemo(() => filtered.filter(d => d.status === 'EN_INSPECCION'), [filtered]);
  const actasItems = useMemo(() => filtered.filter(d => d.status === 'APROBADO' && d.actaNumber), [filtered]);

  const slaAlertCount = useMemo(() => {
    return filtered.filter(d => {
      const days = getDaysLeft(d.slaDeadline);
      return (days < 0 || days <= 1) && d.status !== 'APROBADO';
    }).length;
  }, [filtered]);

  const tabs = [
    { label: 'Cola de Inspección', count: colaItems.length },
    { label: 'Inspecciones Activas', count: activasItems.length },
    { label: 'Actas de Recepción', count: actasItems.length },
    { label: 'Alertas SLA', count: slaAlertCount, alert: slaAlertCount > 0 },
  ];

  const handleStartInspection = ({ deliverableId, inspector }) => {
    setDeliverables(prev => prev.map(d =>
      d.id === deliverableId
        ? { ...d, status: 'EN_INSPECCION', inspector, inspectorAssigned: '2026-06-26', checklistProgress: { done: 0, total: 8 } }
        : d
    ));
    setInspectionModal(null);
    setActiveTab(1);
  };

  const handleSubmitResult = ({ deliverableId, result }) => {
    setDeliverables(prev => prev.map(d => {
      if (d.id !== deliverableId) return d;
      if (result === 'APROBADO') {
        return {
          ...d,
          status: 'APROBADO',
          acceptanceDate: '2026-06-26',
          approver: 'Dir. Ricardo Méndez',
          actaNumber: `ACTA-2026-00${actasItems.length + 2}`,
        };
      }
      return { ...d, status: 'RECHAZADO' };
    }));
    setResultModal(null);
    if (result === 'APROBADO') setActiveTab(2);
  };

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 md:p-6 lg:p-8">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Recepción y Aceptación de Entregables</h1>
        <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
          Gestión formal del ciclo de inspección con regla de 4 ojos — ejecutor ≠ inspector ≠ aprobador
        </p>
      </div>

      {/* KPI Strip */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        {[
          { label: 'Total Entregables', value: filtered.length, color: 'text-slate-900 dark:text-white' },
          { label: 'En Inspección', value: activasItems.length, color: 'text-blue-600 dark:text-blue-400' },
          { label: 'Aceptados', value: actasItems.length, color: 'text-green-600 dark:text-green-400' },
          { label: 'Alertas SLA', value: slaAlertCount, color: slaAlertCount > 0 ? 'text-red-600 dark:text-red-400' : 'text-slate-900 dark:text-white' },
        ].map(({ label, value, color }) => (
          <div key={label} className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 px-5 py-4">
            <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">{label}</p>
            <p className={`text-2xl font-bold ${color}`}>{value}</p>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div className="border-b border-slate-200 dark:border-slate-700 mb-6">
        <nav className="flex gap-1 -mb-px overflow-x-auto">
          {tabs.map((tab, i) => (
            <button
              key={i}
              onClick={() => setActiveTab(i)}
              className={`flex items-center gap-1.5 px-4 py-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
                activeTab === i
                  ? 'border-blue-600 text-blue-600 dark:text-blue-400 dark:border-blue-400'
                  : 'border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'
              }`}
            >
              {tab.label}
              {tab.count > 0 && (
                <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                  tab.alert
                    ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
                    : activeTab === i
                    ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
                    : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400'
                }`}>
                  {tab.count}
                </span>
              )}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === 0 && (
        <ColaInspeccion items={colaItems} onInspect={item => setInspectionModal(item)} />
      )}
      {activeTab === 1 && (
        <InspeccionesActivas items={activasItems} onResult={item => setResultModal(item)} />
      )}
      {activeTab === 2 && (
        <ActasRecepcion items={actasItems} onViewActa={item => setActaModal(item)} />
      )}
      {activeTab === 3 && (
        <AlertasSLA items={filtered} />
      )}

      {/* Modals */}
      {inspectionModal && (
        <InspectionModal
          deliverable={inspectionModal}
          onClose={() => setInspectionModal(null)}
          onStart={handleStartInspection}
        />
      )}
      {resultModal && (
        <ResultModal
          deliverable={resultModal}
          onClose={() => setResultModal(null)}
          onSubmit={handleSubmitResult}
        />
      )}
      {actaModal && (
        <ActaModal
          deliverable={actaModal}
          onClose={() => setActaModal(null)}
        />
      )}
    </div>
  );
}
