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

// ---------------------------------------------------------------------------
// Mock Data
// ---------------------------------------------------------------------------
const MOCK_PROJECTS = [
  { id: 'p4', code: 'PRY-2026-004', name: 'Construcción AR-ProjectManagement Norte', client: 'Inmobiliaria Del Valle', type: 'Construcción', startDate: '2026-01-15', endDate: '2026-12-31', progress: 38, ragStatus: 'AMBER' },
  { id: 'p4', code: 'PRY-2026-004', name: 'AR-ProjectManagement "Horizontes"', client: 'Sony Music Latin', type: 'Producción Musical', startDate: '2026-02-01', endDate: '2026-08-30', progress: 65, ragStatus: 'GREEN' },
  { id: 'p4', code: 'PRY-2026-004', name: 'Implementación AR-ProjectManagement', client: 'Grupo Empresarial XYZ', type: 'Software', startDate: '2026-03-01', endDate: '2026-11-30', progress: 22, ragStatus: 'RED' },
  { id: 'p4', code: 'PRY-2026-004', name: 'AR-ProjectManagement — Plataforma ERP', client: 'AR Electronics', type: 'Software', startDate: '2026-01-01', endDate: '2026-09-30', progress: 55, ragStatus: 'GREEN' },
];

const MOCK_MILESTONES = [
  { id: 'm1', projectId: 'p4', name: 'Fundaciones completadas', date: '2026-02-28', status: 'COMPLETADO' },
  { id: 'm2', projectId: 'p4', name: 'Estructura nivel 5', date: '2026-04-30', status: 'COMPLETADO' },
  { id: 'm3', projectId: 'p4', name: 'Fachada exterior', date: '2026-07-15', status: 'EN_PROGRESO' },
  { id: 'm4', projectId: 'p4', name: 'Instalaciones MEP', date: '2026-09-30', status: 'PENDIENTE' },
  { id: 'm5', projectId: 'p4', name: 'Entrega final', date: '2026-12-31', status: 'PENDIENTE' },
  { id: 'm6', projectId: 'p4', name: 'Grabación pistas base', date: '2026-03-15', status: 'COMPLETADO' },
  { id: 'm7', projectId: 'p4', name: 'Mezcla y masterización', date: '2026-06-01', status: 'EN_PROGRESO' },
  { id: 'm8', projectId: 'p4', name: 'Lanzamiento', date: '2026-08-30', status: 'PENDIENTE' },
  { id: 'm9', projectId: 'p4', name: 'Análisis de requerimientos', date: '2026-04-01', status: 'COMPLETADO' },
  { id: 'm10', projectId: 'p4', name: 'Diseño de módulos', date: '2026-06-30', status: 'EN_PROGRESO' },
  { id: 'm11', projectId: 'p4', name: 'MVP Frontend', date: '2026-04-15', status: 'COMPLETADO' },
  { id: 'm12', projectId: 'p4', name: 'Módulos de gestión', date: '2026-07-01', status: 'EN_PROGRESO' },
];

const MOCK_ACTIVITY = [
  { id: 'a1', projectId: 'p4', date: '2026-06-24', type: 'ENTREGABLE_APROBADO', text: 'Planos estructurales Nivel 5 fueron aprobados' },
  { id: 'a2', projectId: 'p4', date: '2026-06-22', type: 'RFI_RESPONDIDO', text: 'RFI-003 respondido: Especificaciones de vidrio templado' },
  { id: 'a3', projectId: 'p4', date: '2026-06-20', type: 'HITO', text: 'Hito alcanzado: Estructura nivel 5 completada' },
  { id: 'a4', projectId: 'p4', date: '2026-06-18', type: 'ENTREGABLE_ENVIADO', text: 'Memoria de cálculo fachada enviada para revisión' },
  { id: 'a5', projectId: 'p4', date: '2026-06-15', type: 'RFI_NUEVO', text: 'Nueva RFI creada: Cambio en especificaciones MEP' },
  { id: 'a6', projectId: 'p4', date: '2026-06-23', type: 'ENTREGABLE_APROBADO', text: 'Demo pista "Horizontes" aprobada' },
  { id: 'a7', projectId: 'p4', date: '2026-06-21', type: 'RFI_RESPONDIDO', text: 'RFI-001 respondido: Integración con sistemas legacy' },
  { id: 'a8', projectId: 'p4', date: '2026-06-25', type: 'HITO', text: 'MVP Frontend entregado con 18 módulos' },
];

const MOCK_DELIVERABLES = [
  { id: 'd1', projectId: 'p4', code: 'ENT-001', name: 'Planos arquitectónicos planta baja', submittedBy: 'Arq. González', submissionDate: '2026-06-01', status: 'APROBADO' },
  { id: 'd2', projectId: 'p4', code: 'ENT-002', name: 'Planos estructurales Nivel 5', submittedBy: 'Ing. Martínez', submissionDate: '2026-06-15', status: 'APROBADO' },
  { id: 'd3', projectId: 'p4', code: 'ENT-003', name: 'Memoria de cálculo fachada', submittedBy: 'Ing. Martínez', submissionDate: '2026-06-18', status: 'ENVIADO' },
  { id: 'd4', projectId: 'p4', code: 'ENT-004', name: 'Especificaciones sistema MEP', submittedBy: 'Ing. Torres', submissionDate: '2026-06-20', status: 'EN_REVISION' },
  { id: 'd5', projectId: 'p4', code: 'ENT-005', name: 'Informe de avance Q2', submittedBy: 'PM Rodríguez', submissionDate: '2026-06-22', status: 'ENVIADO' },
  { id: 'd6', projectId: 'p4', code: 'ENT-006', name: 'Planos de instalaciones eléctricas', submittedBy: 'Ing. López', submissionDate: '2026-05-30', status: 'RECHAZADO' },
  { id: 'd7', projectId: 'p4', code: 'ENT-001', name: 'Demo pista principal', submittedBy: 'Prod. Silva', submissionDate: '2026-06-10', status: 'APROBADO' },
  { id: 'd8', projectId: 'p4', code: 'ENT-001', name: 'Documento de requerimientos', submittedBy: 'Ana Cons.', submissionDate: '2026-06-05', status: 'ENVIADO' },
  { id: 'd9', projectId: 'p4', code: 'ENT-001', name: 'MVP Frontend v1.0', submittedBy: 'Dev Team', submissionDate: '2026-06-20', status: 'APROBADO' },
];

const MOCK_RFIS = [
  { id: 'r1', projectId: 'p4', number: 'RFI-001', subject: 'Especificaciones de hormigón armado', submittedDate: '2026-05-10', respondedDate: '2026-05-18', status: 'RESPONDIDO', question: '¿Cuál es la resistencia mínima requerida para el hormigón de las columnas del núcleo central?', response: 'La resistencia mínima requerida es f\'c = 350 kg/cm². Se debe usar aditivo retardante en épocas de calor.' },
  { id: 'r2', projectId: 'p4', number: 'RFI-002', subject: 'Sistema de impermeabilización cubierta', submittedDate: '2026-05-25', respondedDate: '2026-06-05', status: 'RESPONDIDO', question: '¿Se aprueba el sistema de membrana asfáltica modificada propuesto por el contratista?', response: 'Aprobado con la condición de agregar una capa de protección mecánica en zonas de tráfico de mantenimiento.' },
  { id: 'r3', projectId: 'p4', number: 'RFI-003', subject: 'Especificaciones de vidrio templado fachada', submittedDate: '2026-06-10', respondedDate: '2026-06-22', status: 'RESPONDIDO', question: '¿El vidrio laminado 8+8 cumple los requisitos de seguridad al fuego indicados en el proyecto?', response: 'Sí cumple. Adicionalmente se requiere tratamiento de baja emisividad en la cara interior para mejorar eficiencia energética.' },
  { id: 'r4', projectId: 'p4', number: 'RFI-004', subject: 'Cambio en especificaciones MEP', submittedDate: '2026-06-15', respondedDate: null, status: 'PENDIENTE', question: '¿Es posible reubicar el cuarto de máquinas del piso 3 al piso 2 por restricciones estructurales encontradas en obra?', response: null },
  { id: 'r5', projectId: 'p4', number: 'RFI-005', subject: 'Acabados interiores lobby', submittedDate: '2026-06-23', respondedDate: null, status: 'PENDIENTE', question: '¿Se mantiene la especificación original de mármol travertino o se acepta el sustituto propuesto de porcelanato imitación piedra?', response: null },
  { id: 'r6', projectId: 'p4', number: 'RFI-001', subject: 'Derechos de autor samples', submittedDate: '2026-05-20', respondedDate: '2026-05-28', status: 'RESPONDIDO', question: '¿Se han obtenido los clearances necesarios para los samples utilizados?', response: 'Confirmado. Todos los clearances están firmados y archivados en el departamento legal.' },
  { id: 'r7', projectId: 'p4', number: 'RFI-001', subject: 'Integración con sistemas legacy', submittedDate: '2026-06-01', respondedDate: '2026-06-21', status: 'RESPONDIDO', question: '¿Qué versión de API expone el sistema SAP actual para la integración?', response: 'El sistema SAP expone API REST versión 2.1. Se compartirán los endpoints y credenciales de sandbox.' },
];

const MOCK_DOCUMENTS = [
  { id: 'doc1', projectId: 'p4', name: 'Contrato Principal Firmado', type: 'PDF', version: 'v1.0', approvedDate: '2026-01-20', category: 'Contractual' },
  { id: 'doc2', projectId: 'p4', name: 'Planos Arquitectónicos Aprobados', type: 'PDF', version: 'v3.2', approvedDate: '2026-03-15', category: 'Técnico' },
  { id: 'doc3', projectId: 'p4', name: 'Especificaciones Técnicas Generales', type: 'PDF', version: 'v2.0', approvedDate: '2026-02-10', category: 'Técnico' },
  { id: 'doc4', projectId: 'p4', name: 'Cronograma Maestro Aprobado', type: 'XLSX', version: 'v4.1', approvedDate: '2026-04-01', category: 'Planificación' },
  { id: 'doc5', projectId: 'p4', name: 'Informe de Avance Q1 2026', type: 'PDF', version: 'v1.0', approvedDate: '2026-04-05', category: 'Informe' },
  { id: 'doc6', projectId: 'p4', name: 'Manual de Calidad del Proyecto', type: 'PDF', version: 'v1.2', approvedDate: '2026-02-28', category: 'Calidad' },
  { id: 'doc7', projectId: 'p4', name: 'Contrato de Producción', type: 'PDF', version: 'v1.0', approvedDate: '2026-02-05', category: 'Contractual' },
  { id: 'doc8', projectId: 'p4', name: 'SOW Implementación ERP', type: 'PDF', version: 'v2.0', approvedDate: '2026-03-10', category: 'Contractual' },
  { id: 'doc9', projectId: 'p4', name: 'Product Requirements Document', type: 'PDF', version: 'v1.5', approvedDate: '2026-01-25', category: 'Técnico' },
];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const RAG_CONFIG = {
  GREEN: { label: 'En Tiempo', bg: 'bg-green-100 dark:bg-green-900/40', text: 'text-green-700 dark:text-green-400', dot: 'bg-green-500' },
  AMBER: { label: 'En Riesgo', bg: 'bg-amber-100 dark:bg-amber-900/40', text: 'text-amber-700 dark:text-amber-400', dot: 'bg-amber-500' },
  RED: { label: 'Con Problemas', bg: 'bg-red-100 dark:bg-red-900/40', text: 'text-red-700 dark:text-red-400', dot: 'bg-red-500' },
};

const DELIVERABLE_STATUS_CONFIG = {
  ENVIADO: { label: 'Enviado', bg: 'bg-blue-100 dark:bg-blue-900/40', text: 'text-blue-700 dark:text-blue-400' },
  APROBADO: { label: 'Aprobado', bg: 'bg-green-100 dark:bg-green-900/40', text: 'text-green-700 dark:text-green-400' },
  RECHAZADO: { label: 'Rechazado', bg: 'bg-red-100 dark:bg-red-900/40', text: 'text-red-700 dark:text-red-400' },
  EN_REVISION: { label: 'En Revisión', bg: 'bg-amber-100 dark:bg-amber-900/40', text: 'text-amber-700 dark:text-amber-400' },
};

const RFI_STATUS_CONFIG = {
  PENDIENTE: { label: 'Pendiente', bg: 'bg-amber-100 dark:bg-amber-900/40', text: 'text-amber-700 dark:text-amber-400' },
  RESPONDIDO: { label: 'Respondido', bg: 'bg-green-100 dark:bg-green-900/40', text: 'text-green-700 dark:text-green-400' },
};

const MILESTONE_STATUS_CONFIG = {
  COMPLETADO: { dot: 'bg-green-500', text: 'text-green-600 dark:text-green-400' },
  EN_PROGRESO: { dot: 'bg-blue-500 animate-pulse', text: 'text-blue-600 dark:text-blue-400' },
  PENDIENTE: { dot: 'bg-slate-300 dark:bg-slate-600', text: 'text-slate-400 dark:text-slate-500' },
};

const DOC_ICON = {
  PDF: (
    <svg className="w-8 h-8 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
    </svg>
  ),
  XLSX: (
    <svg className="w-8 h-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 0v10m0-10a2 2 0 012 2h2a2 2 0 012-2V7" />
    </svg>
  ),
};

const ACTIVITY_ICONS = {
  ENTREGABLE_APROBADO: { icon: '✓', bg: 'bg-green-100 dark:bg-green-900/40', text: 'text-green-600 dark:text-green-400' },
  ENTREGABLE_ENVIADO: { icon: '→', bg: 'bg-blue-100 dark:bg-blue-900/40', text: 'text-blue-600 dark:text-blue-400' },
  RFI_RESPONDIDO: { icon: '↩', bg: 'bg-purple-100 dark:bg-purple-900/40', text: 'text-purple-600 dark:text-purple-400' },
  RFI_NUEVO: { icon: '?', bg: 'bg-amber-100 dark:bg-amber-900/40', text: 'text-amber-600 dark:text-amber-400' },
  HITO: { icon: '⬧', bg: 'bg-indigo-100 dark:bg-indigo-900/40', text: 'text-indigo-600 dark:text-indigo-400' },
};

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

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

function Badge({ status, config }) {
  const cfg = config[status] || { label: status, bg: 'bg-slate-100', text: 'text-slate-600' };
  return (
    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${cfg.bg} ${cfg.text}`}>
      {cfg.label}
    </span>
  );
}

function Toast({ message, onClose }) {
  React.useEffect(() => {
    const t = setTimeout(onClose, 3000);
    return () => clearTimeout(t);
  }, [onClose]);
  return (
    <div className="fixed bottom-6 right-6 z-50 flex items-center gap-3 bg-slate-900 dark:bg-slate-700 text-white px-5 py-3 rounded-xl shadow-xl">
      <svg className="w-5 h-5 text-green-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
      </svg>
      <span className="text-sm font-medium">{message}</span>
    </div>
  );
}

// Tab 1: Resumen
function ResumenTab({ project, milestones, activity, deliverables, rfis }) {
  const approvedDel = deliverables.filter(d => d.status === 'APROBADO').length;
  const pendingRFIs = rfis.filter(r => r.status === 'PENDIENTE').length;
  const nextMilestone = milestones.find(m => m.status !== 'COMPLETADO');

  const kpis = [
    {
      label: 'Avance General',
      value: `${project.progress}%`,
      icon: (
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
        </svg>
      ),
      color: 'text-blue-600',
      bg: 'bg-blue-50 dark:bg-blue-900/20',
    },
    {
      label: 'Entregables Aprobados',
      value: `${approvedDel} / ${deliverables.length}`,
      icon: (
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      ),
      color: 'text-green-600',
      bg: 'bg-green-50 dark:bg-green-900/20',
    },
    {
      label: 'RFIs Pendientes',
      value: pendingRFIs,
      icon: (
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      ),
      color: 'text-amber-600',
      bg: 'bg-amber-50 dark:bg-amber-900/20',
    },
    {
      label: 'Próximo Hito',
      value: nextMilestone ? nextMilestone.name : 'Todos completados',
      sub: nextMilestone ? formatDate(nextMilestone.date) : null,
      icon: (
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 21v-4m0 0V5a2 2 0 012-2h6.5l1 1H21l-3 6 3 6h-8.5l-1-1H5a2 2 0 00-2 2zm9-13.5V9" />
        </svg>
      ),
      color: 'text-indigo-600',
      bg: 'bg-indigo-50 dark:bg-indigo-900/20',
    },
  ];

  const ragCfg = RAG_CONFIG[project.ragStatus] || RAG_CONFIG.GREEN;

  return (
    <div className="space-y-6">
      {/* Project header */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
        <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-4">
          <div>
            <p className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-1">{project.code}</p>
            <h2 className="text-xl font-bold text-slate-900 dark:text-white mb-1">{project.name}</h2>
            <p className="text-sm text-slate-500 dark:text-slate-400">{project.type} · {project.client}</p>
          </div>
          <div className="flex items-center gap-3">
            <span className={`inline-flex items-center gap-2 rounded-full px-3 py-1.5 text-sm font-medium ${ragCfg.bg} ${ragCfg.text}`}>
              <span className={`w-2 h-2 rounded-full ${ragCfg.dot}`}></span>
              {ragCfg.label}
            </span>
          </div>
        </div>
        <div className="mt-4 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
          <div>
            <p className="text-xs text-slate-400 dark:text-slate-500 font-medium uppercase tracking-wide">Inicio</p>
            <p className="text-slate-700 dark:text-slate-200 font-semibold">{formatDate(project.startDate)}</p>
          </div>
          <div>
            <p className="text-xs text-slate-400 dark:text-slate-500 font-medium uppercase tracking-wide">Finalización</p>
            <p className="text-slate-700 dark:text-slate-200 font-semibold">{formatDate(project.endDate)}</p>
          </div>
          <div>
            <p className="text-xs text-slate-400 dark:text-slate-500 font-medium uppercase tracking-wide">Cliente</p>
            <p className="text-slate-700 dark:text-slate-200 font-semibold">{project.client}</p>
          </div>
          <div>
            <p className="text-xs text-slate-400 dark:text-slate-500 font-medium uppercase tracking-wide">Tipo</p>
            <p className="text-slate-700 dark:text-slate-200 font-semibold">{project.type}</p>
          </div>
        </div>
      </div>

      {/* KPI cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpis.map((kpi, i) => (
          <div key={i} 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-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">{kpi.label}</p>
              <div className={`p-2 rounded-lg ${kpi.bg} ${kpi.color}`}>{kpi.icon}</div>
            </div>
            <p className={`text-2xl font-bold ${kpi.color}`}>{kpi.value}</p>
            {kpi.sub && <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">{kpi.sub}</p>}
          </div>
        ))}
      </div>

      {/* Progress timeline */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
        <h3 className="text-sm font-semibold text-slate-900 dark:text-white mb-5">Línea de Tiempo — Hitos del Proyecto</h3>
        <div className="relative">
          {/* Horizontal connector */}
          <div className="absolute top-4 left-4 right-4 h-0.5 bg-slate-200 dark:bg-slate-700"></div>
          <div
            className="absolute top-4 left-4 h-0.5 bg-blue-500 transition-all"
            style={{ width: `${project.progress}%` }}
          ></div>
          <div className="relative flex justify-between">
            {milestones.map((m, idx) => {
              const cfg = MILESTONE_STATUS_CONFIG[m.status];
              return (
                <div key={m.id} className="flex flex-col items-center gap-2 flex-1">
                  <div className={`w-8 h-8 rounded-full border-2 border-white dark:border-slate-900 flex items-center justify-center ${cfg.dot.includes('animate') ? 'bg-blue-500' : cfg.dot.replace('animate-pulse', '').trim()}`}>
                    {m.status === 'COMPLETADO' && (
                      <svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                      </svg>
                    )}
                    {m.status === 'EN_PROGRESO' && <span className="w-3 h-3 bg-white rounded-full"></span>}
                  </div>
                  <div className="text-center">
                    <p className={`text-xs font-medium ${cfg.text} max-w-20 leading-tight`}>{m.name}</p>
                    <p className="text-xs text-slate-400 dark:text-slate-500 mt-0.5">{formatDate(m.date)}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Recent activity */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
        <h3 className="text-sm font-semibold text-slate-900 dark:text-white mb-4">Actividad Reciente</h3>
        <div className="space-y-3">
          {activity.slice(0, 5).map(ev => {
            const cfg = ACTIVITY_ICONS[ev.type] || { icon: '·', bg: 'bg-slate-100', text: 'text-slate-600' };
            return (
              <div key={ev.id} className="flex items-start gap-3">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-bold ${cfg.bg} ${cfg.text}`}>
                  {cfg.icon}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm text-slate-700 dark:text-slate-200">{ev.text}</p>
                  <p className="text-xs text-slate-400 dark:text-slate-500 mt-0.5">{formatDate(ev.date)}</p>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// Approval modal
function ApprovalModal({ deliverable, action, onConfirm, onClose }) {
  const [comments, setComments] = useState('');
  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>
      <div className="relative bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 w-full max-w-md shadow-2xl">
        <h3 className="text-base font-semibold text-slate-900 dark:text-white mb-1">
          {action === 'APROBAR' ? 'Aprobar Entregable' : 'Rechazar Entregable'}
        </h3>
        <p className="text-sm text-slate-500 dark:text-slate-400 mb-4">{deliverable.name}</p>
        <div className="mb-4">
          <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">
            Comentarios {action === 'RECHAZAR' ? '(requeridos)' : '(opcionales)'}
          </label>
          <textarea
            rows={4}
            value={comments}
            onChange={e => setComments(e.target.value)}
            placeholder={action === 'APROBAR' ? 'Aprobado sin observaciones...' : 'Indique el motivo del rechazo...'}
            className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white text-sm px-3 py-2.5 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
        <div className="flex gap-3 justify-end">
          <button
            onClick={onClose}
            className="px-4 py-2.5 rounded-xl border border-slate-200 dark:border-slate-700 text-sm font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800"
          >
            Cancelar
          </button>
          <button
            onClick={() => onConfirm(comments)}
            className={`px-4 py-2.5 rounded-xl text-sm font-medium text-white ${action === 'APROBAR' ? 'bg-green-600 hover:bg-green-700' : 'bg-red-600 hover:bg-red-700'}`}
          >
            {action === 'APROBAR' ? 'Confirmar Aprobación' : 'Confirmar Rechazo'}
          </button>
        </div>
      </div>
    </div>
  );
}

// Tab 2: Entregables
function EntregablesTab({ deliverables, onToast }) {
  const [items, setItems] = useState(deliverables);
  const [modal, setModal] = useState(null); // { deliverable, action }

  const handleConfirm = (comments) => {
    setItems(prev => prev.map(d =>
      d.id === modal.deliverable.id
        ? { ...d, status: modal.action === 'APROBAR' ? 'APROBADO' : 'RECHAZADO' }
        : d
    ));
    onToast(modal.action === 'APROBAR' ? 'Entregable aprobado correctamente' : 'Entregable rechazado');
    setModal(null);
  };

  return (
    <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
      {modal && (
        <ApprovalModal
          deliverable={modal.deliverable}
          action={modal.action}
          onConfirm={handleConfirm}
          onClose={() => setModal(null)}
        />
      )}
      <div className="p-5 border-b border-slate-100 dark:border-slate-800">
        <h3 className="text-sm font-semibold text-slate-900 dark:text-white">Entregables del Proyecto</h3>
        <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Revise y apruebe los entregables enviados por el equipo</p>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-slate-800/60">
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Código</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Nombre</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Enviado por</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Fecha</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Estado</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Acción</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
            {items.map(d => (
              <tr key={d.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors">
                <td className="px-5 py-3.5 font-mono text-xs text-slate-500 dark:text-slate-400">{d.code}</td>
                <td className="px-5 py-3.5 font-medium text-slate-900 dark:text-white">{d.name}</td>
                <td className="px-5 py-3.5 text-slate-600 dark:text-slate-300">{d.submittedBy}</td>
                <td className="px-5 py-3.5 text-slate-500 dark:text-slate-400">{formatDate(d.submissionDate)}</td>
                <td className="px-5 py-3.5">
                  <Badge status={d.status} config={DELIVERABLE_STATUS_CONFIG} />
                </td>
                <td className="px-5 py-3.5">
                  {d.status === 'ENVIADO' && (
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => setModal({ deliverable: d, action: 'APROBAR' })}
                        className="bg-green-600 hover:bg-green-700 text-white rounded-lg px-3 py-1.5 text-xs font-medium"
                      >
                        Aprobar
                      </button>
                      <button
                        onClick={() => setModal({ deliverable: d, action: 'RECHAZAR' })}
                        className="bg-red-50 hover:bg-red-100 dark:bg-red-900/30 dark:hover:bg-red-900/50 text-red-600 dark:text-red-400 rounded-lg px-3 py-1.5 text-xs font-medium border border-red-200 dark:border-red-800"
                      >
                        Rechazar
                      </button>
                    </div>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// RFI Detail Modal
function RFIModal({ rfi, onClose }) {
  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>
      <div className="relative bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 w-full max-w-lg shadow-2xl">
        <div className="flex items-start justify-between mb-4">
          <div>
            <p className="text-xs font-mono text-slate-400 dark:text-slate-500">{rfi.number}</p>
            <h3 className="text-base font-semibold text-slate-900 dark:text-white mt-0.5">{rfi.subject}</h3>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 p-1">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="space-y-4">
          <div className="bg-slate-50 dark:bg-slate-800 rounded-xl p-4">
            <p className="text-xs font-semibold text-slate-400 dark:text-slate-500 uppercase tracking-wide mb-2">Consulta — {formatDate(rfi.submittedDate)}</p>
            <p className="text-sm text-slate-700 dark:text-slate-200">{rfi.question}</p>
          </div>
          {rfi.response ? (
            <div className="bg-green-50 dark:bg-green-900/20 rounded-xl p-4 border border-green-100 dark:border-green-800">
              <p className="text-xs font-semibold text-green-600 dark:text-green-400 uppercase tracking-wide mb-2">Respuesta — {formatDate(rfi.respondedDate)}</p>
              <p className="text-sm text-slate-700 dark:text-slate-200">{rfi.response}</p>
            </div>
          ) : (
            <div className="bg-amber-50 dark:bg-amber-900/20 rounded-xl p-4 border border-amber-100 dark:border-amber-800">
              <p className="text-xs font-semibold text-amber-600 dark:text-amber-400 uppercase tracking-wide mb-1">Pendiente de Respuesta</p>
              <p className="text-sm text-slate-500 dark:text-slate-400">Esta consulta está siendo revisada por el equipo del proyecto.</p>
            </div>
          )}
        </div>
        <div className="mt-5 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">
            Cerrar
          </button>
        </div>
      </div>
    </div>
  );
}

// New RFI Modal
function NewRFIModal({ onSubmit, onClose }) {
  const [subject, setSubject] = useState('');
  const [description, setDescription] = useState('');

  const handleSubmit = () => {
    if (!subject.trim() || !description.trim()) return;
    onSubmit({ subject, description });
  };

  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>
      <div className="relative bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 w-full max-w-lg shadow-2xl">
        <h3 className="text-base font-semibold text-slate-900 dark:text-white mb-4">Nueva Consulta / RFI</h3>
        <div className="space-y-4">
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">Asunto</label>
            <input
              type="text"
              value={subject}
              onChange={e => setSubject(e.target.value)}
              placeholder="Breve descripción de la consulta..."
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white text-sm px-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="block text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">Descripción detallada</label>
            <textarea
              rows={5}
              value={description}
              onChange={e => setDescription(e.target.value)}
              placeholder="Explique su consulta con el mayor detalle posible..."
              className="w-full rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white text-sm px-3 py-2.5 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>
        <div className="mt-5 flex gap-3 justify-end">
          <button onClick={onClose} className="px-4 py-2.5 rounded-xl border border-slate-200 dark:border-slate-700 text-sm font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800">
            Cancelar
          </button>
          <button
            onClick={handleSubmit}
            disabled={!subject.trim() || !description.trim()}
            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"
          >
            Enviar Consulta
          </button>
        </div>
      </div>
    </div>
  );
}

// Tab 3: RFIs
function RFIsTab({ rfis, onToast }) {
  const [items, setItems] = useState(rfis);
  const [detailRFI, setDetailRFI] = useState(null);
  const [showNewRFI, setShowNewRFI] = useState(false);

  const handleNewRFI = ({ subject, description }) => {
    const newRFI = {
      id: `r-${Date.now()}`,
      projectId: rfis[0]?.projectId || 'p4',
      number: `RFI-${String(items.length + 1).padStart(3, '0')}`,
      subject,
      submittedDate: new Date().toISOString().slice(0, 10),
      respondedDate: null,
      status: 'PENDIENTE',
      question: description,
      response: null,
    };
    setItems(prev => [newRFI, ...prev]);
    onToast('Consulta enviada correctamente');
    setShowNewRFI(false);
  };

  return (
    <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
      {detailRFI && <RFIModal rfi={detailRFI} onClose={() => setDetailRFI(null)} />}
      {showNewRFI && <NewRFIModal onSubmit={handleNewRFI} onClose={() => setShowNewRFI(false)} />}
      <div className="p-5 border-b border-slate-100 dark:border-slate-800 flex items-center justify-between">
        <div>
          <h3 className="text-sm font-semibold text-slate-900 dark:text-white">RFIs y Comunicaciones</h3>
          <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Consultas formales y sus respuestas</p>
        </div>
        <button
          onClick={() => setShowNewRFI(true)}
          className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium flex items-center gap-2"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
          Nueva Consulta
        </button>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-slate-800/60">
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">N° RFI</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Asunto</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Enviado</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Respondido</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Estado</th>
              <th className="text-left text-xs font-semibold text-slate-500 dark:text-slate-400 px-5 py-3">Acción</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
            {items.map(r => (
              <tr key={r.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors">
                <td className="px-5 py-3.5 font-mono text-xs text-slate-500 dark:text-slate-400">{r.number}</td>
                <td className="px-5 py-3.5 font-medium text-slate-900 dark:text-white max-w-xs truncate">{r.subject}</td>
                <td className="px-5 py-3.5 text-slate-500 dark:text-slate-400">{formatDate(r.submittedDate)}</td>
                <td className="px-5 py-3.5 text-slate-500 dark:text-slate-400">{formatDate(r.respondedDate)}</td>
                <td className="px-5 py-3.5">
                  <Badge status={r.status} config={RFI_STATUS_CONFIG} />
                </td>
                <td className="px-5 py-3.5">
                  <button
                    onClick={() => setDetailRFI(r)}
                    className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 text-xs font-medium underline underline-offset-2"
                  >
                    Ver Detalle
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// Tab 4: Documentos
function DocumentosTab({ documents, onToast }) {
  const categoryColors = {
    Contractual: 'bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-400',
    Técnico: 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-400',
    Planificación: 'bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-400',
    Informe: 'bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300',
    Calidad: 'bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-400',
  };

  return (
    <div>
      <div className="mb-4 flex items-center justify-between">
        <div>
          <h3 className="text-sm font-semibold text-slate-900 dark:text-white">Documentos Aprobados</h3>
          <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Solo documentos aprobados y disponibles para el cliente</p>
        </div>
        <span className="text-xs text-slate-400 dark:text-slate-500">{documents.length} documentos</span>
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {documents.map(doc => (
          <div key={doc.id} className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5 flex flex-col gap-4 hover:shadow-md transition-shadow">
            <div className="flex items-start gap-3">
              <div className="flex-shrink-0 p-2 bg-slate-50 dark:bg-slate-800 rounded-xl">
                {DOC_ICON[doc.type] || DOC_ICON.PDF}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold text-slate-900 dark:text-white leading-tight">{doc.name}</p>
                <div className="flex items-center gap-2 mt-1.5 flex-wrap">
                  <span className="text-xs text-slate-400 dark:text-slate-500">{doc.version}</span>
                  <span className="text-slate-300 dark:text-slate-600">·</span>
                  <span className={`text-xs font-medium rounded-full px-2 py-0.5 ${categoryColors[doc.category] || categoryColors.Informe}`}>
                    {doc.category}
                  </span>
                </div>
              </div>
            </div>
            <div className="flex items-center justify-between pt-3 border-t border-slate-100 dark:border-slate-800">
              <div>
                <p className="text-xs text-slate-400 dark:text-slate-500">Aprobado el</p>
                <p className="text-xs font-semibold text-slate-600 dark:text-slate-300">{formatDate(doc.approvedDate)}</p>
              </div>
              <button
                onClick={() => onToast(`Descarga iniciada: ${doc.name}`)}
                className="flex items-center gap-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-3 py-2 text-xs font-medium"
              >
                <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                </svg>
                Descargar
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main Page
// ---------------------------------------------------------------------------
const TABS = [
  { id: 'resumen', label: 'Resumen del Proyecto' },
  { id: 'entregables', label: 'Entregables' },
  { id: 'rfis', label: 'RFIs y Comunicaciones' },
  { id: 'documentos', label: 'Documentos Aprobados' },
];

export default function ClientPortalPage() {
  const { selectedProjectId } = useProject();
  const [activeTab, setActiveTab] = useState('resumen');
  const [toast, setToast] = useState(null);

  const activeProjectId = selectedProjectId || 'p4';

  const project = useMemo(
    () => MOCK_PROJECTS.find(p => p.id === activeProjectId) || MOCK_PROJECTS[0],
    [activeProjectId]
  );

  const milestones = useMemo(
    () => MOCK_MILESTONES.filter(m => m.projectId === activeProjectId),
    [activeProjectId]
  );

  const activity = useMemo(
    () => MOCK_ACTIVITY.filter(a => a.projectId === activeProjectId),
    [activeProjectId]
  );

  const deliverables = useMemo(
    () => MOCK_DELIVERABLES.filter(d => d.projectId === activeProjectId),
    [activeProjectId]
  );

  const rfis = useMemo(
    () => MOCK_RFIS.filter(r => r.projectId === activeProjectId),
    [activeProjectId]
  );

  const documents = useMemo(
    () => MOCK_DOCUMENTS.filter(d => d.projectId === activeProjectId),
    [activeProjectId]
  );

  const showToast = (msg) => setToast(msg);

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 md:p-6 lg:p-8">
      {toast && <Toast message={toast} onClose={() => setToast(null)} />}

      {/* Client portal banner */}
      <div className="mb-6 flex items-start gap-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-2xl px-5 py-4">
        <svg className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <div>
          <p className="text-sm font-semibold text-blue-800 dark:text-blue-300">Vista del Portal del Cliente</p>
          <p className="text-sm text-blue-600 dark:text-blue-400 mt-0.5">
            Solo información relevante para <span className="font-semibold">{project.client}</span>. Esta vista no incluye datos internos, costos ni información del equipo.
          </p>
        </div>
      </div>

      {/* Tabs */}
      <div className="mb-6 border-b border-slate-200 dark:border-slate-800">
        <nav className="-mb-px flex gap-6 overflow-x-auto">
          {TABS.map(tab => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`whitespace-nowrap pb-3 text-sm font-medium border-b-2 transition-colors ${
                activeTab === tab.id
                  ? '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-200'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab content */}
      {activeTab === 'resumen' && (
        <ResumenTab
          project={project}
          milestones={milestones}
          activity={activity}
          deliverables={deliverables}
          rfis={rfis}
        />
      )}
      {activeTab === 'entregables' && (
        <EntregablesTab deliverables={deliverables} onToast={showToast} />
      )}
      {activeTab === 'rfis' && (
        <RFIsTab rfis={rfis} onToast={showToast} />
      )}
      {activeTab === 'documentos' && (
        <DocumentosTab documents={documents} onToast={showToast} />
      )}
    </div>
  );
}
