import { useState } from 'react';
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from 'recharts';

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

const MOCK_INCIDENTS = [
  { id:'INC-2026-001', type:'CASI_ACCIDENTE', title:'Caída de herramienta desde andamio nivel 2', project:'AR-ProjectManagement',
    date:'2026-06-05', reportedBy:'Álvaro Romero', area:'Fachada norte', severity:'LEVE',
    status:'CERRADO', injured:false, lostDays:0, rootCause:'Herramienta sin anclaje de seguridad',
    correctiveAction:'Capacitación uso de porta herramientas y check diario de andamios', closedDate:'2026-06-10',
    birdLevel:'CASI_ACCIDENTE' },
  { id:'INC-2026-002', type:'ACCIDENTE', title:'Corte menor en mano — trabajo con disco abrasivo', project:'AR-ProjectManagement',
    date:'2026-06-18', reportedBy:'Álvaro Romero', area:'Zona de corte materiales', severity:'LEVE',
    status:'CERRADO', injured:true, lostDays:1, rootCause:'EPP inadecuado (guantes desgastados)',
    correctiveAction:'Reposición inmediata de guantes. Revisión semanal de EPP', closedDate:'2026-06-20',
    birdLevel:'ACCIDENTE_LEVE' },
  { id:'INC-2026-003', type:'CONDICION_INSEGURA', title:'Iluminación insuficiente zona de excavación nocturna', project:'AR-ProjectManagement',
    date:'2026-06-22', reportedBy:'Diana Herrera', area:'Excavación Lote B', severity:'MEDIA',
    status:'ABIERTO', injured:false, lostDays:0, rootCause:'', correctiveAction:'', closedDate:null,
    birdLevel:'ACTO_CONDICION_INSEGURA' },
];

const MOCK_PERMITS = [
  { id:'PT-2026-001', type:'TRABAJO_ALTURA', activity:'Instalación fachada vidrio piso 4-5', project:'AR-ProjectManagement',
    requestedBy:'Álvaro Romero', approvedBy:'Diana Herrera', validFrom:'2026-06-28', validTo:'2026-07-05', status:'ACTIVO' },
  { id:'PT-2026-002', type:'TRABAJO_ELECTRICO', activity:'Energización tablero principal TP-01', project:'AR-ProjectManagement',
    requestedBy:'Álvaro Romero', approvedBy:'Paula Soto', validFrom:'2026-07-03', validTo:'2026-07-03', status:'PENDIENTE' },
  { id:'PT-2026-003', type:'ESPACIO_CONFINADO', activity:'Inspección cisterna subterránea', project:'AR-ProjectManagement',
    requestedBy:'Paula Soto', approvedBy:'Diana Herrera', validFrom:'2026-06-15', validTo:'2026-06-15', status:'CERRADO' },
];

const MOCK_TRAININGS = [
  { id:'CAP-001', title:'Trabajo seguro en alturas', project:'AR-ProjectManagement', date:'2026-05-20',
    instructor:'Diana Herrera', attendees:['Álvaro Romero','Álvaro Romero','Paula Soto'], hours:8, status:'COMPLETADA', cert:true },
  { id:'CAP-002', title:'Manejo de residuos y gestión ambiental', project:'General', date:'2026-06-10',
    instructor:'Consultor externo', attendees:['Todo el equipo obra Torre'], hours:4, status:'COMPLETADA', cert:false },
  { id:'CAP-003', title:'Primeros auxilios básicos', project:'General', date:'2026-07-15',
    instructor:'Cruz Roja', attendees:[], hours:8, status:'PROGRAMADA', cert:true },
];

const MOCK_CAPAS = [
  { id:'CAPA-001', origen:'INC-2026-002', tipo:'CORRECTIVA',
    descripcion:'Implementar revisión semanal de EPP y registro de condición de equipos',
    responsable:'Diana Herrera', fechaLimite:'2026-07-10',
    estado:'VERIFICACION', eficacia:null,
    causaRaiz:'EPP deteriorado no detectado en inspección previa',
    accionPropuesta:'Checklist semanal de EPP con firma de supervisor',
    closedDate:'2026-06-28', createdDate:'2026-06-20' },
  { id:'CAPA-002', origen:'INC-2026-001', tipo:'PREVENTIVA',
    descripcion:'Programa de anclaje obligatorio para todas las herramientas en andamios',
    responsable:'Álvaro Romero', fechaLimite:'2026-07-05',
    estado:'EN_IMPLEMENTACION', eficacia:null,
    causaRaiz:'Ausencia de procedimiento formal de aseguramiento de herramientas',
    accionPropuesta:'SOP para trabajo en andamios + kit porta-herramientas por cuadrilla',
    closedDate:null, createdDate:'2026-06-10' },
  { id:'CAPA-003', origen:'INC-2026-003', tipo:'CORRECTIVA',
    descripcion:'Instalación de iluminación portátil certificada en zona de excavación nocturna',
    responsable:'Álvaro Romero', fechaLimite:'2026-06-30',
    estado:'ABIERTA', eficacia:null,
    causaRaiz:'No se contempló iluminación suplementaria en plan de trabajo nocturno',
    accionPropuesta:'Adquisición de torres de iluminación portátiles LED',
    closedDate:null, createdDate:'2026-06-22' },
  { id:'CAPA-004', origen:'INC-2026-001', tipo:'PREVENTIVA',
    descripcion:'Capacitación reforzada en uso seguro de andamios para todo el personal',
    responsable:'Paula Soto', fechaLimite:'2026-06-25',
    estado:'EFECTIVA', eficacia:'EFECTIVA',
    causaRaiz:'Brecha de conocimiento en procedimientos de trabajo en altura',
    accionPropuesta:'Taller práctico + evaluación de competencias en andamios',
    closedDate:'2026-06-20', createdDate:'2026-06-08' },
  { id:'CAPA-005', origen:'INC-2026-002', tipo:'CORRECTIVA',
    descripcion:'Revisión y actualización del estándar de EPP para trabajos con abrasivos',
    responsable:'Paula Soto', fechaLimite:'2026-07-15',
    estado:'CERRADA', eficacia:null,
    causaRaiz:'Estándar desactualizado no especificaba tipo de guante para disco abrasivo',
    accionPropuesta:'Actualizar matriz de EPP según tipo de trabajo',
    closedDate:'2026-06-25', createdDate:'2026-06-20' },
];

// ─── Badge helpers ────────────────────────────────────────────────────────────

const incidentTypeBadge = (type) => {
  const map = {
    ACCIDENTE: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
    CASI_ACCIDENTE: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    CONDICION_INSEGURA: 'bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300',
  };
  const labels = { ACCIDENTE:'Accidente', CASI_ACCIDENTE:'Casi-accidente', CONDICION_INSEGURA:'Condición insegura' };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[type] || 'bg-slate-100 text-slate-600'}`}>{labels[type] || type}</span>;
};

const severityBadge = (s) => {
  const map = { LEVE:'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300', MEDIA:'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300', GRAVE:'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[s] || 'bg-slate-100 text-slate-600'}`}>{s}</span>;
};

const statusBadge = (s) => {
  const map = { CERRADO:'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300', ABIERTO:'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[s] || 'bg-slate-100 text-slate-600'}`}>{s}</span>;
};

const permitTypeBadge = (type) => {
  const map = {
    TRABAJO_ALTURA: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
    TRABAJO_ELECTRICO: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    ESPACIO_CONFINADO: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
    TRABAJO_CALIENTE: 'bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300',
  };
  const labels = { TRABAJO_ALTURA:'Altura', TRABAJO_ELECTRICO:'Eléctrico', ESPACIO_CONFINADO:'Esp. Confinado', TRABAJO_CALIENTE:'Caliente' };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[type] || 'bg-slate-100 text-slate-600'}`}>{labels[type] || type}</span>;
};

const permitStatusBadge = (s) => {
  const map = {
    ACTIVO: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
    PENDIENTE: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    CERRADO: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300',
    VENCIDO: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[s] || 'bg-slate-100 text-slate-600'}`}>{s}</span>;
};

const trainingStatusBadge = (s) => {
  const map = {
    COMPLETADA: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
    PROGRAMADA: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[s] || 'bg-slate-100 text-slate-600'}`}>{s}</span>;
};

const capaEstadoBadge = (s) => {
  const map = {
    ABIERTA: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
    EN_IMPLEMENTACION: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    VERIFICACION: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300',
    CERRADA: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300',
    EFECTIVA: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
    NO_EFECTIVA: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
  };
  const labels = {
    ABIERTA:'Abierta', EN_IMPLEMENTACION:'En implementación', VERIFICACION:'Verificación',
    CERRADA:'Cerrada', EFECTIVA:'Efectiva', NO_EFECTIVA:'No efectiva',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[s] || 'bg-slate-100 text-slate-600'}`}>{labels[s] || s}</span>;
};

const capaTipoBadge = (t) => {
  const map = {
    CORRECTIVA: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
    PREVENTIVA: 'bg-teal-100 text-teal-700 dark:bg-teal-900/40 dark:text-teal-300',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[t] || 'bg-slate-100 text-slate-600'}`}>{t}</span>;
};

// ─── Shared Modal shell ───────────────────────────────────────────────────────

function Modal({ title, onClose, children }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
      <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto border border-slate-200 dark:border-slate-700">
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 dark:border-slate-700">
          <h2 className="text-lg font-semibold text-slate-800 dark:text-slate-100">{title}</h2>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-2xl leading-none">&times;</button>
        </div>
        <div className="px-6 py-5">{children}</div>
      </div>
    </div>
  );
}

// ─── Incident modals ──────────────────────────────────────────────────────────

function IncidentDetailModal({ incident, onClose }) {
  const [rootCause, setRootCause] = useState(incident.rootCause);
  const [correctiveAction, setCorrectiveAction] = useState(incident.correctiveAction);
  return (
    <Modal title={`Detalle incidente — ${incident.id}`} onClose={onClose}>
      <div className="space-y-3 text-sm text-slate-700 dark:text-slate-300">
        <div className="grid grid-cols-2 gap-3">
          <div><span className="font-medium text-slate-500 dark:text-slate-400">Tipo:</span> <span className="ml-1">{incidentTypeBadge(incident.type)}</span></div>
          <div><span className="font-medium text-slate-500 dark:text-slate-400">Severidad:</span> <span className="ml-1">{severityBadge(incident.severity)}</span></div>
          <div><span className="font-medium text-slate-500 dark:text-slate-400">Estado:</span> <span className="ml-1">{statusBadge(incident.status)}</span></div>
          <div><span className="font-medium text-slate-500 dark:text-slate-400">Fecha:</span> <span className="ml-1">{incident.date}</span></div>
          <div><span className="font-medium text-slate-500 dark:text-slate-400">Proyecto:</span> <span className="ml-1">{incident.project}</span></div>
          <div><span className="font-medium text-slate-500 dark:text-slate-400">Área:</span> <span className="ml-1">{incident.area}</span></div>
          <div><span className="font-medium text-slate-500 dark:text-slate-400">Reportado por:</span> <span className="ml-1">{incident.reportedBy}</span></div>
          <div><span className="font-medium text-slate-500 dark:text-slate-400">¿Lesionado?</span> <span className="ml-1">{incident.injured ? 'Sí' : 'No'}</span></div>
          <div><span className="font-medium text-slate-500 dark:text-slate-400">Días perdidos:</span> <span className="ml-1">{incident.lostDays}</span></div>
          {incident.closedDate && <div><span className="font-medium text-slate-500 dark:text-slate-400">Fecha cierre:</span> <span className="ml-1">{incident.closedDate}</span></div>}
        </div>
        <div>
          <p className="font-medium text-slate-800 dark:text-slate-200 mb-1">{incident.title}</p>
        </div>
        <div>
          <label className="block font-medium text-slate-600 dark:text-slate-400 mb-1">Causa raíz</label>
          <textarea value={rootCause} onChange={e => setRootCause(e.target.value)} rows={3}
            className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400" />
        </div>
        <div>
          <label className="block font-medium text-slate-600 dark:text-slate-400 mb-1">Acción correctiva</label>
          <textarea value={correctiveAction} onChange={e => setCorrectiveAction(e.target.value)} rows={3}
            className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400" />
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cancelar</button>
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium">Guardar cierre</button>
        </div>
      </div>
    </Modal>
  );
}

function ReportIncidentModal({ onClose }) {
  return (
    <Modal title="Reportar incidente" onClose={onClose}>
      <div className="space-y-4 text-sm">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Tipo</label>
            <select className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
              <option>ACCIDENTE</option><option>CASI_ACCIDENTE</option><option>CONDICION_INSEGURA</option>
            </select>
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Severidad</label>
            <select className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
              <option>LEVE</option><option>MEDIA</option><option>GRAVE</option>
            </select>
          </div>
          <div className="col-span-2">
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Título</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Proyecto</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Área</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Fecha</label>
            <input type="date" className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Reportado por</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div className="col-span-2 flex items-center gap-2">
            <input type="checkbox" id="injured" className="rounded" />
            <label htmlFor="injured" className="text-slate-600 dark:text-slate-400 font-medium">¿Hubo lesionados?</label>
          </div>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cancelar</button>
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-red-600 hover:bg-red-700 text-white text-sm font-medium">Reportar incidente</button>
        </div>
      </div>
    </Modal>
  );
}

// ─── Permit modals ────────────────────────────────────────────────────────────

function PermitModal({ permit, onClose }) {
  return (
    <Modal title={`Permiso — ${permit.id}`} onClose={onClose}>
      <div className="space-y-3 text-sm text-slate-700 dark:text-slate-300">
        <div className="grid grid-cols-2 gap-3">
          <div><span className="font-medium text-slate-500">Tipo:</span> <span className="ml-1">{permitTypeBadge(permit.type)}</span></div>
          <div><span className="font-medium text-slate-500">Estado:</span> <span className="ml-1">{permitStatusBadge(permit.status)}</span></div>
          <div className="col-span-2"><span className="font-medium text-slate-500">Actividad:</span> <span className="ml-1">{permit.activity}</span></div>
          <div><span className="font-medium text-slate-500">Proyecto:</span> <span className="ml-1">{permit.project}</span></div>
          <div><span className="font-medium text-slate-500">Solicitado por:</span> <span className="ml-1">{permit.requestedBy}</span></div>
          <div><span className="font-medium text-slate-500">Aprobado por:</span> <span className="ml-1">{permit.approvedBy}</span></div>
          <div><span className="font-medium text-slate-500">Válido desde:</span> <span className="ml-1">{permit.validFrom}</span></div>
          <div><span className="font-medium text-slate-500">Válido hasta:</span> <span className="ml-1">{permit.validTo}</span></div>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cerrar</button>
          {permit.status === 'PENDIENTE' && (
            <button onClick={onClose} className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium">Aprobar permiso</button>
          )}
        </div>
      </div>
    </Modal>
  );
}

function SolicitudPermisoModal({ onClose }) {
  return (
    <Modal title="Solicitar permiso de trabajo" onClose={onClose}>
      <div className="space-y-4 text-sm">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Tipo</label>
            <select className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
              <option>TRABAJO_ALTURA</option><option>TRABAJO_ELECTRICO</option><option>ESPACIO_CONFINADO</option><option>TRABAJO_CALIENTE</option>
            </select>
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Proyecto</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div className="col-span-2">
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Actividad</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Válido desde</label>
            <input type="date" className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Válido hasta</label>
            <input type="date" className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cancelar</button>
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium">Solicitar</button>
        </div>
      </div>
    </Modal>
  );
}

// ─── Training modal ───────────────────────────────────────────────────────────

function NuevaCapacitacionModal({ onClose }) {
  return (
    <Modal title="Nueva capacitación" onClose={onClose}>
      <div className="space-y-4 text-sm">
        <div className="grid grid-cols-2 gap-4">
          <div className="col-span-2">
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Título</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Proyecto</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Fecha</label>
            <input type="date" className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Instructor</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Horas</label>
            <input type="number" className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div className="col-span-2 flex items-center gap-2">
            <input type="checkbox" id="cert" className="rounded" />
            <label htmlFor="cert" className="text-slate-600 dark:text-slate-400 font-medium">Otorga certificación</label>
          </div>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cancelar</button>
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium">Crear capacitación</button>
        </div>
      </div>
    </Modal>
  );
}

// ─── CAPA Modal ───────────────────────────────────────────────────────────────

function NuevaCAPAModal({ onClose }) {
  return (
    <Modal title="Nueva CAPA" onClose={onClose}>
      <div className="space-y-4 text-sm">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Origen (ref. incidente/NCR)</label>
            <input placeholder="ej. INC-2026-003" className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Tipo</label>
            <select className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
              <option>CORRECTIVA</option><option>PREVENTIVA</option>
            </select>
          </div>
          <div className="col-span-2">
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Descripción</label>
            <textarea rows={2} className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div className="col-span-2">
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Causa raíz</label>
            <textarea rows={2} className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div className="col-span-2">
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Acción propuesta</label>
            <textarea rows={2} className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Responsable</label>
            <input className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-600 dark:text-slate-400 mb-1 font-medium">Fecha límite</label>
            <input type="date" className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cancelar</button>
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium">Crear CAPA</button>
        </div>
      </div>
    </Modal>
  );
}

// ─── CAPA Stepper ─────────────────────────────────────────────────────────────

const CAPA_STATES = ['ABIERTA', 'EN_IMPLEMENTACION', 'VERIFICACION', 'CERRADA'];
const CAPA_STATE_LABELS = {
  ABIERTA: 'Abierta',
  EN_IMPLEMENTACION: 'Implementación',
  VERIFICACION: 'Verificación',
  CERRADA: 'Cerrada',
  EFECTIVA: 'Efectiva',
  NO_EFECTIVA: 'No Efectiva',
};

function CAPAStepper({ estado }) {
  const isTerminal = estado === 'EFECTIVA' || estado === 'NO_EFECTIVA';
  const displayStates = [...CAPA_STATES];
  if (isTerminal) displayStates.push(estado);

  const baseIndex = isTerminal ? CAPA_STATES.length : CAPA_STATES.indexOf(estado);

  return (
    <div className="flex items-center gap-0.5 mt-2 flex-wrap">
      {displayStates.map((s, i) => {
        const isActive = i === baseIndex || (isTerminal && i === displayStates.length - 1);
        const isPast = i < baseIndex;
        const isFinal = isTerminal && i === displayStates.length - 1;

        const circleColor = isFinal
          ? (estado === 'EFECTIVA' ? 'bg-emerald-500' : 'bg-red-500')
          : isPast || isActive
          ? 'bg-blue-500'
          : 'bg-slate-200 dark:bg-slate-700';

        const textColor = isActive || isPast
          ? 'text-slate-700 dark:text-slate-200'
          : 'text-slate-400 dark:text-slate-500';

        return (
          <div key={s} className="flex items-center">
            <div className="flex flex-col items-center">
              <div className={`w-3 h-3 rounded-full ${circleColor} transition-colors`} />
              <span className={`text-xs mt-0.5 ${textColor} whitespace-nowrap`} style={{ fontSize: '10px' }}>
                {CAPA_STATE_LABELS[s]}
              </span>
            </div>
            {i < displayStates.length - 1 && (
              <div className={`h-0.5 w-6 mx-0.5 mb-3 ${i < baseIndex ? 'bg-blue-400' : 'bg-slate-200 dark:bg-slate-700'}`} />
            )}
          </div>
        );
      })}
    </div>
  );
}

// ─── Bird Pyramid ─────────────────────────────────────────────────────────────

const BIRD_LEVELS = [
  { label: 'Accidentes graves', count: 1, ratio: '1', bg: 'bg-red-600', text: 'text-white', width: 20 },
  { label: 'Accidentes leves', count: 10, ratio: '1:10', bg: 'bg-amber-500', text: 'text-white', width: 36 },
  { label: 'Primeros auxilios', count: 30, ratio: '1:10:30', bg: 'bg-yellow-400', text: 'text-slate-800', width: 52 },
  { label: 'Incidentes sin daño', count: 100, ratio: '1:10:30:100', bg: 'bg-blue-500', text: 'text-white', width: 68 },
  { label: 'Actos/condiciones inseguras', count: 600, ratio: '1:10:30:100:600', bg: 'bg-emerald-500', text: 'text-white', width: 84 },
];

// map bird level key to actual incident list
const BIRD_INCIDENTS_MAP = {
  0: MOCK_INCIDENTS.filter(i => i.type === 'ACCIDENTE' && i.severity === 'GRAVE'),
  1: MOCK_INCIDENTS.filter(i => i.type === 'ACCIDENTE'),
  2: [],
  3: MOCK_INCIDENTS.filter(i => i.type === 'CASI_ACCIDENTE'),
  4: MOCK_INCIDENTS.filter(i => i.type === 'CONDICION_INSEGURA'),
};

// ─── Tab list ─────────────────────────────────────────────────────────────────

const TABS = ['Incidentes', 'Permisos de trabajo', 'Capacitaciones', 'Indicadores HSE', 'CAPA', 'Pirámide Bird'];

// ─── Main page ────────────────────────────────────────────────────────────────

export default function HSEPage() {
  const [activeTab, setActiveTab] = useState(0);
  const [selectedIncident, setSelectedIncident] = useState(null);
  const [showReportModal, setShowReportModal] = useState(false);
  const [selectedPermit, setSelectedPermit] = useState(null);
  const [showPermitModal, setShowPermitModal] = useState(false);
  const [showCapModal, setShowCapModal] = useState(false);
  const [showCAPAModal, setShowCAPAModal] = useState(false);
  const [selectedBirdLevel, setSelectedBirdLevel] = useState(null);

  const totalAccidentes = MOCK_INCIDENTS.filter(i => i.type === 'ACCIDENTE').length;
  const totalCasi = MOCK_INCIDENTS.filter(i => i.type === 'CASI_ACCIDENTE').length;
  const diasPerdidos = MOCK_INCIDENTS.reduce((a, b) => a + b.lostDays, 0);
  const diasSinAccidente = 8;

  const horasHombre = 12000;
  const if_ = ((totalAccidentes / horasHombre) * 1000000).toFixed(2);
  const ig = ((diasPerdidos / horasHombre) * 1000000).toFixed(2);
  // TRIR: (recordable incidents × 200,000) / hours worked
  const trir = ((totalAccidentes * 200000) / horasHombre).toFixed(2);

  const incidentesPorProyecto = [{ name: 'AR-ProjectManagement', value: MOCK_INCIDENTS.length }];

  // CAPA KPIs
  const capasAbiertas = MOCK_CAPAS.filter(c => ['ABIERTA','EN_IMPLEMENTACION','VERIFICACION'].includes(c.estado)).length;
  const capasCerradas = MOCK_CAPAS.filter(c => ['CERRADA','EFECTIVA','NO_EFECTIVA'].includes(c.estado));
  const capasEfectivas = MOCK_CAPAS.filter(c => c.estado === 'EFECTIVA').length;
  const pctEfectividad = capasCerradas.length > 0 ? Math.round((capasEfectivas / capasCerradas.length) * 100) : 0;

  // celebration tier for días sin accidente
  const celebrationTier = diasSinAccidente >= 180 ? { color: 'text-purple-500 dark:text-purple-400', label: '180+ días — Excelente!' }
    : diasSinAccidente >= 90 ? { color: 'text-emerald-500 dark:text-emerald-400', label: '90+ días — Muy bien!' }
    : diasSinAccidente >= 30 ? { color: 'text-blue-500 dark:text-blue-400', label: '30+ dias — En camino!' }
    : { color: 'text-slate-700 dark:text-slate-200', label: 'dias consecutivos' };

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-900 p-6">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-slate-800 dark:text-slate-100">HSE / SSOMA</h1>
          <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">Salud, Seguridad y Ambiente — Gestión integrada</p>
        </div>

        {/* Tabs */}
        <div className="flex gap-1 mb-6 bg-slate-100 dark:bg-slate-800 p-1 rounded-2xl flex-wrap">
          {TABS.map((tab, i) => (
            <button key={i} onClick={() => setActiveTab(i)}
              className={`px-4 py-2 rounded-xl text-sm font-medium transition-all ${activeTab === i ? 'bg-white dark:bg-slate-700 text-slate-800 dark:text-slate-100 shadow-sm' : 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200'}`}>
              {tab}
            </button>
          ))}
        </div>

        {/* ── Tab 0: Incidentes ─────────────────────────────────────────────── */}
        {activeTab === 0 && (
          <div className="space-y-5">
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              {[
                { label:'Total incidentes', value: MOCK_INCIDENTS.length, color:'text-slate-700 dark:text-slate-200' },
                { label:'Accidentes', value: totalAccidentes, color:'text-red-600 dark:text-red-400' },
                { label:'Casi-accidentes', value: totalCasi, color:'text-amber-600 dark:text-amber-400' },
                { label:'Días perdidos', value: diasPerdidos, color:'text-orange-600 dark:text-orange-400' },
                { label:'Días sin accidente', value: diasSinAccidente, color:'text-emerald-600 dark:text-emerald-400' },
              ].map((k, i) => (
                <div key={i} className="bg-white dark:bg-slate-800 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">{k.label}</p>
                  <p className={`text-3xl font-bold ${k.color}`}>{k.value}</p>
                </div>
              ))}
            </div>

            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200 dark:border-slate-700">
                <h2 className="font-semibold text-slate-800 dark:text-slate-100">Registro de incidentes</h2>
                <button onClick={() => setShowReportModal(true)} className="flex items-center gap-2 px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-xl transition-colors">
                  + Reportar incidente
                </button>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="text-left text-slate-500 dark:text-slate-400 text-xs border-b border-slate-100 dark:border-slate-700">
                      <th className="px-5 py-3">ID</th>
                      <th className="px-5 py-3">Tipo</th>
                      <th className="px-5 py-3">Título</th>
                      <th className="px-5 py-3">Fecha</th>
                      <th className="px-5 py-3">Severidad</th>
                      <th className="px-5 py-3">Estado</th>
                      <th className="px-5 py-3">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {MOCK_INCIDENTS.map(inc => (
                      <tr key={inc.id} className="border-b border-slate-50 dark:border-slate-700/50 hover:bg-slate-50 dark:hover:bg-slate-700/30 transition-colors">
                        <td className="px-5 py-3 font-mono text-xs text-slate-500 dark:text-slate-400">{inc.id}</td>
                        <td className="px-5 py-3">{incidentTypeBadge(inc.type)}</td>
                        <td className="px-5 py-3 text-slate-700 dark:text-slate-200 max-w-xs truncate">{inc.title}</td>
                        <td className="px-5 py-3 text-slate-500 dark:text-slate-400">{inc.date}</td>
                        <td className="px-5 py-3">{severityBadge(inc.severity)}</td>
                        <td className="px-5 py-3">{statusBadge(inc.status)}</td>
                        <td className="px-5 py-3">
                          <button onClick={() => setSelectedIncident(inc)} className="text-blue-600 dark:text-blue-400 hover:underline text-xs font-medium">Ver detalle</button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ── Tab 1: Permisos de trabajo ────────────────────────────────────── */}
        {activeTab === 1 && (
          <div className="space-y-5">
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200 dark:border-slate-700">
                <h2 className="font-semibold text-slate-800 dark:text-slate-100">Permisos de trabajo</h2>
                <button onClick={() => setShowPermitModal(true)} className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-xl transition-colors">
                  + Solicitar permiso
                </button>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="text-left text-slate-500 dark:text-slate-400 text-xs border-b border-slate-100 dark:border-slate-700">
                      <th className="px-5 py-3">ID</th>
                      <th className="px-5 py-3">Tipo</th>
                      <th className="px-5 py-3">Actividad</th>
                      <th className="px-5 py-3">Solicitado por</th>
                      <th className="px-5 py-3">Validez</th>
                      <th className="px-5 py-3">Estado</th>
                      <th className="px-5 py-3">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {MOCK_PERMITS.map(p => (
                      <tr key={p.id} className="border-b border-slate-50 dark:border-slate-700/50 hover:bg-slate-50 dark:hover:bg-slate-700/30 transition-colors">
                        <td className="px-5 py-3 font-mono text-xs text-slate-500 dark:text-slate-400">{p.id}</td>
                        <td className="px-5 py-3">{permitTypeBadge(p.type)}</td>
                        <td className="px-5 py-3 text-slate-700 dark:text-slate-200 max-w-xs truncate">{p.activity}</td>
                        <td className="px-5 py-3 text-slate-600 dark:text-slate-300">{p.requestedBy}</td>
                        <td className="px-5 py-3 text-slate-500 dark:text-slate-400 text-xs">{p.validFrom} → {p.validTo}</td>
                        <td className="px-5 py-3">{permitStatusBadge(p.status)}</td>
                        <td className="px-5 py-3">
                          <button onClick={() => setSelectedPermit(p)} className="text-blue-600 dark:text-blue-400 hover:underline text-xs font-medium">Ver / Aprobar</button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ── Tab 2: Capacitaciones ─────────────────────────────────────────── */}
        {activeTab === 2 && (
          <div className="space-y-5">
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200 dark:border-slate-700">
                <h2 className="font-semibold text-slate-800 dark:text-slate-100">Capacitaciones</h2>
                <button onClick={() => setShowCapModal(true)} className="flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium rounded-xl transition-colors">
                  + Nueva capacitación
                </button>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="text-left text-slate-500 dark:text-slate-400 text-xs border-b border-slate-100 dark:border-slate-700">
                      <th className="px-5 py-3">Título</th>
                      <th className="px-5 py-3">Proyecto</th>
                      <th className="px-5 py-3">Fecha</th>
                      <th className="px-5 py-3">Instructor</th>
                      <th className="px-5 py-3">Asistentes</th>
                      <th className="px-5 py-3">Horas</th>
                      <th className="px-5 py-3">Estado</th>
                      <th className="px-5 py-3">Cert.</th>
                    </tr>
                  </thead>
                  <tbody>
                    {MOCK_TRAININGS.map(t => (
                      <tr key={t.id} className="border-b border-slate-50 dark:border-slate-700/50 hover:bg-slate-50 dark:hover:bg-slate-700/30 transition-colors">
                        <td className="px-5 py-3 text-slate-700 dark:text-slate-200 font-medium">{t.title}</td>
                        <td className="px-5 py-3 text-slate-500 dark:text-slate-400">{t.project}</td>
                        <td className="px-5 py-3 text-slate-500 dark:text-slate-400">{t.date}</td>
                        <td className="px-5 py-3 text-slate-600 dark:text-slate-300">{t.instructor}</td>
                        <td className="px-5 py-3">
                          <span className="bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 px-2 py-0.5 rounded-full text-xs font-medium">
                            {t.attendees.length}
                          </span>
                        </td>
                        <td className="px-5 py-3 text-slate-600 dark:text-slate-300">{t.hours}h</td>
                        <td className="px-5 py-3">{trainingStatusBadge(t.status)}</td>
                        <td className="px-5 py-3 text-center">
                          {t.cert ? <span className="text-emerald-500 dark:text-emerald-400 font-bold">✓</span> : <span className="text-slate-300 dark:text-slate-600">—</span>}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ── Tab 3: Indicadores HSE (enhanced) ────────────────────────────── */}
        {activeTab === 3 && (
          <div className="space-y-5">
            {/* Classic KPI cards */}
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Tasa de frecuencia (IF)</p>
                <p className="text-3xl font-bold text-blue-600 dark:text-blue-400">{if_}</p>
                <p className="text-xs text-slate-400 mt-1">accidentes × 10⁶ / HH</p>
              </div>
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Tasa de gravedad (IG)</p>
                <p className="text-3xl font-bold text-orange-600 dark:text-orange-400">{ig}</p>
                <p className="text-xs text-slate-400 mt-1">días perdidos × 10⁶ / HH</p>
              </div>
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5 flex flex-col items-center justify-center">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Cumplimiento EPP</p>
                <p className="text-3xl font-bold text-emerald-600 dark:text-emerald-400">87%</p>
                <div className="mt-2 h-2 bg-slate-100 dark:bg-slate-700 rounded-full w-full">
                  <div className="h-2 bg-emerald-500 rounded-full" style={{ width: '87%' }} />
                </div>
              </div>
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Inspecciones HSE del mes</p>
                <p className="text-3xl font-bold text-slate-700 dark:text-slate-200">4</p>
                <p className="text-xs text-slate-400 mt-1">de 6 programadas</p>
              </div>
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Horas-hombre trabajadas</p>
                <p className="text-3xl font-bold text-slate-700 dark:text-slate-200">12,000</p>
                <p className="text-xs text-slate-400 mt-1">acumuladas junio 2026</p>
              </div>
            </div>

            {/* TRIR card */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
              <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-3">TRIR — Total Recordable Incident Rate</h3>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 items-center">
                <div className="text-center">
                  <p className="text-5xl font-black text-blue-600 dark:text-blue-400">{trir}</p>
                  <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">Valor actual del proyecto</p>
                </div>
                <div className="bg-slate-50 dark:bg-slate-700/50 rounded-xl p-4 text-sm">
                  <p className="font-medium text-slate-700 dark:text-slate-200 mb-2">Formula</p>
                  <p className="font-mono text-slate-600 dark:text-slate-300 text-xs leading-relaxed">
                    TRIR = (N° incidentes registrables × 200,000) / HH trabajadas
                  </p>
                  <p className="text-slate-500 dark:text-slate-400 text-xs mt-2">
                    200,000 = 100 empleados × 50 semanas × 40 horas
                  </p>
                </div>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center justify-between">
                    <span className="text-slate-600 dark:text-slate-300">Proyecto actual</span>
                    <span className={`font-bold ${parseFloat(trir) <= 3.0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}>{trir}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-slate-500 dark:text-slate-400">Benchmark construcción</span>
                    <span className="font-bold text-slate-500 dark:text-slate-400">3.0 – 5.0</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-slate-500 dark:text-slate-400">Meta del proyecto</span>
                    <span className="font-bold text-emerald-600 dark:text-emerald-400">&lt; 2.0</span>
                  </div>
                  <div className={`text-xs px-3 py-1.5 rounded-lg font-medium mt-1 ${parseFloat(trir) <= 2.0 ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' : 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'}`}>
                    {parseFloat(trir) <= 2.0 ? 'Por debajo de la meta — excelente' : 'Por encima de la meta — requiere accion'}
                  </div>
                </div>
              </div>
            </div>

            {/* Dias sin accidente — large counter */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 flex flex-col items-center text-center">
              <p className="text-sm font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide mb-2">Dias sin accidente registrable</p>
              <p className={`text-8xl font-black leading-none ${celebrationTier.color}`}>{diasSinAccidente}</p>
              <p className={`text-sm mt-3 font-semibold ${celebrationTier.color}`}>{celebrationTier.label}</p>
              <div className="flex gap-3 mt-4">
                {[{ d:30, label:'30 dias' }, { d:90, label:'90 dias' }, { d:180, label:'180 dias' }].map(milestone => (
                  <div key={milestone.d} className={`px-3 py-1.5 rounded-xl text-xs font-medium border ${diasSinAccidente >= milestone.d ? 'bg-emerald-100 text-emerald-700 border-emerald-300 dark:bg-emerald-900/40 dark:text-emerald-300 dark:border-emerald-700' : 'bg-slate-100 text-slate-400 border-slate-200 dark:bg-slate-700 dark:text-slate-500 dark:border-slate-600'}`}>
                    {milestone.label}
                  </div>
                ))}
              </div>
            </div>

            {/* Leading vs Lagging indicators */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <div className="flex items-center gap-2 mb-4">
                  <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
                  <h3 className="font-semibold text-slate-800 dark:text-slate-100">Indicadores leading (preventivos)</h3>
                </div>
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-3">Miden acciones que previenen accidentes antes de que ocurran.</p>
                <div className="space-y-3">
                  {[
                    { label: 'Charlas de seguridad (toolbox talks)', value: 18, meta: 20, unit: 'del mes' },
                    { label: 'Inspecciones completadas', value: 4, meta: 6, unit: 'del mes' },
                    { label: 'Casi-accidentes reportados', value: totalCasi, meta: null, unit: 'acumulado' },
                  ].map((ind, i) => (
                    <div key={i}>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-sm text-slate-700 dark:text-slate-200">{ind.label}</span>
                        <span className="text-sm font-bold text-emerald-600 dark:text-emerald-400">
                          {ind.value}{ind.meta ? `/${ind.meta}` : ''} <span className="text-xs font-normal text-slate-400">{ind.unit}</span>
                        </span>
                      </div>
                      {ind.meta && (
                        <div className="h-1.5 bg-slate-100 dark:bg-slate-700 rounded-full">
                          <div className="h-1.5 bg-emerald-500 rounded-full transition-all" style={{ width: `${Math.min((ind.value / ind.meta) * 100, 100)}%` }} />
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <div className="flex items-center gap-2 mb-4">
                  <span className="w-2 h-2 rounded-full bg-red-500"></span>
                  <h3 className="font-semibold text-slate-800 dark:text-slate-100">Indicadores lagging (reactivos)</h3>
                </div>
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-3">Miden eventos negativos ya ocurridos.</p>
                <div className="space-y-3">
                  {[
                    { label: 'Accidentes con lesion', value: totalAccidentes, color: 'text-red-600 dark:text-red-400' },
                    { label: 'Dias de trabajo perdidos', value: diasPerdidos, color: 'text-orange-600 dark:text-orange-400' },
                    { label: 'TRIR', value: trir, color: parseFloat(trir) <= 3.0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400' },
                    { label: 'IF (tasa de frecuencia)', value: if_, color: 'text-blue-600 dark:text-blue-400' },
                    { label: 'IG (tasa de gravedad)', value: ig, color: 'text-slate-700 dark:text-slate-200' },
                  ].map((ind, i) => (
                    <div key={i} className="flex items-center justify-between">
                      <span className="text-sm text-slate-600 dark:text-slate-300">{ind.label}</span>
                      <span className={`text-sm font-bold ${ind.color}`}>{ind.value}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Incidentes por proyecto */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
              <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-4">Incidentes por proyecto</h3>
              <div className="space-y-3">
                {incidentesPorProyecto.map(p => (
                  <div key={p.name} className="flex items-center gap-3">
                    <span className="text-sm text-slate-600 dark:text-slate-300 w-44 shrink-0">{p.name}</span>
                    <div className="flex-1 h-3 bg-slate-100 dark:bg-slate-700 rounded-full">
                      <div className="h-3 bg-blue-500 rounded-full" style={{ width: `${(p.value / MOCK_INCIDENTS.length) * 100}%` }} />
                    </div>
                    <span className="text-sm font-semibold text-slate-700 dark:text-slate-200 w-4">{p.value}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ── Tab 4: CAPA ───────────────────────────────────────────────────── */}
        {activeTab === 4 && (
          <div className="space-y-5">
            {/* CAPA KPIs */}
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <div className="bg-white dark:bg-slate-800 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">CAPAs abiertas</p>
                <p className="text-3xl font-bold text-amber-600 dark:text-amber-400">{capasAbiertas}</p>
              </div>
              <div className="bg-white dark:bg-slate-800 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">% Efectividad</p>
                <p className="text-3xl font-bold text-emerald-600 dark:text-emerald-400">{pctEfectividad}%</p>
                <p className="text-xs text-slate-400 mt-1">{capasEfectivas} de {capasCerradas.length} cerradas</p>
              </div>
              <div className="bg-white dark:bg-slate-800 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">Tiempo promedio cierre</p>
                <p className="text-3xl font-bold text-blue-600 dark:text-blue-400">12</p>
                <p className="text-xs text-slate-400 mt-1">días (estimado)</p>
              </div>
            </div>

            {/* CAPA Table */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200 dark:border-slate-700">
                <div>
                  <h2 className="font-semibold text-slate-800 dark:text-slate-100">Acciones Correctivas y Preventivas</h2>
                  <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Generadas automáticamente desde incidentes y NCRs. Revisión de eficacia a 30 días del cierre.</p>
                </div>
                <button onClick={() => setShowCAPAModal(true)} className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-xl transition-colors whitespace-nowrap">
                  + Nueva CAPA
                </button>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="text-left text-slate-500 dark:text-slate-400 text-xs border-b border-slate-100 dark:border-slate-700">
                      <th className="px-4 py-3">ID</th>
                      <th className="px-4 py-3">Origen</th>
                      <th className="px-4 py-3">Tipo</th>
                      <th className="px-4 py-3">Descripción</th>
                      <th className="px-4 py-3">Responsable</th>
                      <th className="px-4 py-3">Fecha límite</th>
                      <th className="px-4 py-3">Estado</th>
                      <th className="px-4 py-3">Eficacia</th>
                    </tr>
                  </thead>
                  <tbody>
                    {MOCK_CAPAS.map(c => (
                      <tr key={c.id} className="border-b border-slate-50 dark:border-slate-700/50 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">{c.id}</td>
                        <td className="px-4 py-3 font-mono text-xs text-blue-600 dark:text-blue-400">{c.origen}</td>
                        <td className="px-4 py-3">{capaTipoBadge(c.tipo)}</td>
                        <td className="px-4 py-3 text-slate-700 dark:text-slate-200 max-w-xs">
                          <p className="truncate">{c.descripcion}</p>
                          <p className="text-xs text-slate-400 mt-0.5 truncate">Causa: {c.causaRaiz}</p>
                        </td>
                        <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{c.responsable}</td>
                        <td className="px-4 py-3 text-slate-500 dark:text-slate-400 text-xs whitespace-nowrap">{c.fechaLimite}</td>
                        <td className="px-4 py-3">{capaEstadoBadge(c.estado)}</td>
                        <td className="px-4 py-3">
                          {c.eficacia ? (
                            <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${c.eficacia === 'EFECTIVA' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' : 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'}`}>
                              {c.eficacia}
                            </span>
                          ) : c.estado === 'CERRADA' ? (
                            <span className="text-xs text-slate-400">Pendiente 30d</span>
                          ) : (
                            <span className="text-slate-300 dark:text-slate-600 text-xs">—</span>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* CAPA Cards with stepper */}
            <div>
              <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-3">Flujo de estado por CAPA</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {MOCK_CAPAS.map(c => (
                  <div key={c.id} className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
                    <div className="flex items-start justify-between gap-2 mb-1">
                      <div>
                        <span className="font-mono text-xs text-slate-500 dark:text-slate-400">{c.id}</span>
                        <span className="mx-2 text-slate-300 dark:text-slate-600">·</span>
                        {capaTipoBadge(c.tipo)}
                      </div>
                      {capaEstadoBadge(c.estado)}
                    </div>
                    <p className="text-sm font-medium text-slate-700 dark:text-slate-200 mt-2 mb-0.5">{c.descripcion}</p>
                    <p className="text-xs text-slate-500 dark:text-slate-400">Responsable: {c.responsable} · Límite: {c.fechaLimite}</p>
                    <CAPAStepper estado={c.estado} />
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ── Tab 5: Pirámide de Bird ───────────────────────────────────────── */}
        {activeTab === 5 && (
          <div className="space-y-5">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
              {/* Pyramid */}
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
                <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-1">Pirámide de Bird</h3>
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-5">Haz clic en cada nivel para ver los incidentes de esa categoría.</p>
                <div className="flex flex-col items-center gap-1.5">
                  {BIRD_LEVELS.map((level, i) => (
                    <button
                      key={i}
                      onClick={() => setSelectedBirdLevel(selectedBirdLevel === i ? null : i)}
                      style={{ width: `${level.width}%` }}
                      className={`${level.bg} ${level.text} rounded-lg px-3 py-2.5 flex items-center justify-between text-left transition-all hover:opacity-90 hover:scale-[1.02] ${selectedBirdLevel === i ? 'ring-2 ring-offset-2 ring-slate-400 dark:ring-offset-slate-800' : ''}`}
                    >
                      <span className="text-xs font-semibold leading-tight">{level.label}</span>
                      <div className="text-right shrink-0 ml-2">
                        <div className="text-sm font-black">{level.count}</div>
                        <div className="text-xs opacity-75">{level.ratio}</div>
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              {/* Theory + current project data */}
              <div className="space-y-4">
                <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                  <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-2">Teoria de Bird</h3>
                  <p className="text-sm text-slate-600 dark:text-slate-300 leading-relaxed">
                    Por cada accidente grave ocurren estadísticamente 600 actos inseguros. Identificar y eliminar los actos inseguros en la base previene los accidentes en la cúspide.
                  </p>
                  <div className="mt-3 p-3 bg-amber-50 dark:bg-amber-900/20 rounded-xl border border-amber-200 dark:border-amber-800">
                    <p className="text-xs font-semibold text-amber-800 dark:text-amber-300 mb-1">Regla de Frank Bird (1969)</p>
                    <p className="text-xs text-amber-700 dark:text-amber-400">
                      Estudió 1,753,498 accidentes en 297 empresas. Establece la proporción 1:10:30:100:600 como modelo estadístico de referencia.
                    </p>
                  </div>
                </div>

                <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                  <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-3">Proyecto actual vs ratio teórico</h3>
                  <div className="space-y-2 text-sm">
                    {[
                      { label: 'Accidentes graves', actual: 0, teorico: 1, color: 'text-red-600 dark:text-red-400' },
                      { label: 'Accidentes leves', actual: totalAccidentes, teorico: 10, color: 'text-amber-600 dark:text-amber-400' },
                      { label: 'Casi-accidentes', actual: totalCasi, teorico: 30, color: 'text-blue-600 dark:text-blue-400' },
                      { label: 'Cond. inseguras reportadas', actual: MOCK_INCIDENTS.filter(i=>i.type==='CONDICION_INSEGURA').length, teorico: 100, color: 'text-emerald-600 dark:text-emerald-400' },
                    ].map((row, i) => (
                      <div key={i} className="flex items-center justify-between">
                        <span className="text-slate-600 dark:text-slate-300">{row.label}</span>
                        <div className="flex items-center gap-3">
                          <span className={`font-bold ${row.color}`}>{row.actual}</span>
                          <span className="text-slate-300 dark:text-slate-600">/</span>
                          <span className="text-slate-400 dark:text-slate-500 text-xs">ref. {row.teorico}</span>
                          <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${row.actual <= row.teorico ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' : 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'}`}>
                            {row.actual <= row.teorico ? 'OK' : 'ALTO'}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Drill-down panel when a level is selected */}
            {selectedBirdLevel !== null && (
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <div className="flex items-center justify-between mb-3">
                  <h3 className="font-semibold text-slate-800 dark:text-slate-100">
                    Incidentes — {BIRD_LEVELS[selectedBirdLevel].label}
                  </h3>
                  <button onClick={() => setSelectedBirdLevel(null)} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-xl leading-none">&times;</button>
                </div>
                {BIRD_INCIDENTS_MAP[selectedBirdLevel].length === 0 ? (
                  <p className="text-sm text-slate-500 dark:text-slate-400">No hay incidentes registrados en esta categoría en los datos actuales.</p>
                ) : (
                  <div className="space-y-2">
                    {BIRD_INCIDENTS_MAP[selectedBirdLevel].map(inc => (
                      <div key={inc.id} className="flex items-center gap-3 p-3 bg-slate-50 dark:bg-slate-700/50 rounded-xl">
                        <span className="font-mono text-xs text-slate-400">{inc.id}</span>
                        <span className="text-sm text-slate-700 dark:text-slate-200 flex-1">{inc.title}</span>
                        <span className="text-xs text-slate-400">{inc.date}</span>
                        {severityBadge(inc.severity)}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>

      {/* ── Modals ────────────────────────────────────────────────────────────── */}
      {selectedIncident && <IncidentDetailModal incident={selectedIncident} onClose={() => setSelectedIncident(null)} />}
      {showReportModal && <ReportIncidentModal onClose={() => setShowReportModal(false)} />}
      {selectedPermit && <PermitModal permit={selectedPermit} onClose={() => setSelectedPermit(null)} />}
      {showPermitModal && <SolicitudPermisoModal onClose={() => setShowPermitModal(false)} />}
      {showCapModal && <NuevaCapacitacionModal onClose={() => setShowCapModal(false)} />}
      {showCAPAModal && <NuevaCAPAModal onClose={() => setShowCAPAModal(false)} />}
    </div>
  );
}
