// SST module — Seguridad y Salud en el Trabajo
// 4 sections: Exámenes médicos · Accidentes · Matriz de riesgos · COPASST
const { useState: _sst_useState, useMemo: _sst_useMemo } = React;

// ─── Mock data ─────────────────────────────────────────────

const EXAMS = [
  { id: 'E0247', initials: 'AM', name: 'Andrés Felipe Mejía',  role: 'Operario de Clasificación',   site: 'Cali',    type: 'ingreso',   done: '02/05/2026', due: '02/05/2027', state: 'vigente', restrictions: null },
  { id: 'E0205', initials: 'CV', name: 'Carlos Andrés Vélez',  role: 'Operario de Clasificación',   site: 'Cali',    type: 'periodico', done: '14/03/2025', due: '14/03/2026', state: 'vencido',  restrictions: 'Hipoacusia leve · uso permanente de protector auditivo' },
  { id: 'E0198', initials: 'MF', name: 'María Fernanda López', role: 'Op. Aprovechamiento',           site: 'Cali',    type: 'periodico', done: '08/04/2025', due: '08/04/2026', state: 'vencido',  restrictions: null },
  { id: 'E0177', initials: 'JP', name: 'Jorge Iván Patiño',    role: 'Conductor',             site: 'Barranquilla',  type: 'periodico', done: '15/05/2025', due: '15/05/2026', state: 'porvencer', restrictions: 'Lumbalgia crónica · evitar carga > 15 kg' },
  { id: 'E0156', initials: 'PV', name: 'Paula Valencia Ríos',  role: 'Téc. Mantenimiento',    site: 'Cali',    type: 'periodico', done: '20/04/2025', due: '20/04/2026', state: 'vencido',  restrictions: null },
  { id: 'E0142', initials: 'DT', name: 'Diego Andrés Toro',    role: 'Aux. Aprovechamiento',          site: 'Cali',    type: 'periodico', done: '22/05/2025', due: '22/05/2026', state: 'porvencer', restrictions: null },
  { id: 'E0128', initials: 'NC', name: 'Nicolás Cárdenas',     role: 'Conductor',             site: 'Barranquilla',  type: 'periodico', done: '11/09/2025', due: '11/09/2026', state: 'vigente',  restrictions: null },
  { id: 'E0094', initials: 'MT', name: 'María Trujillo Henao', role: 'Aux. Recursos Humanos', site: 'Cali',    type: 'periodico', done: '04/02/2026', due: '04/02/2027', state: 'vigente',  restrictions: null },
  { id: 'E0067', initials: 'LM', name: 'Luis Miguel Marín',    role: 'Líder de Aprovechamiento',      site: 'Cali',    type: 'periodico', done: '18/06/2025', due: '18/06/2026', state: 'porvencer', restrictions: 'Síndrome de túnel carpiano · pausas activas cada 90 min' },
  { id: 'E0023', initials: 'CR', name: 'Carolina Restrepo S.', role: 'Jefe de RRHH',          site: 'Cali',    type: 'periodico', done: '12/02/2026', due: '12/02/2027', state: 'vigente',  restrictions: null },
  { id: 'E0011', initials: 'FH', name: 'Fernando Henao',       role: 'Operario Clasificación',      site: 'Cali',    type: 'egreso',    done: '28/04/2026', due: '—',          state: 'vigente',  restrictions: null },
  { id: 'E0246', initials: 'LG', name: 'Laura Gómez Restrepo', role: 'Operaria de Planta',    site: 'Cali',    type: 'ingreso',   done: '02/05/2026', due: '02/05/2027', state: 'vigente',  restrictions: null },
];

const STATE_EXAM = {
  vigente:    { label: 'Vigente',    pill: 'green',      dot: 'var(--green-600)' },
  porvencer:  { label: 'Por vencer', pill: 'amber-soft', dot: '#854D0E' },
  vencido:    { label: 'Vencido',    pill: 'rose',       dot: 'var(--rose-600)' },
};

const TYPE_EXAM = {
  ingreso:   { label: 'Ingreso' },
  periodico: { label: 'Periódico' },
  egreso:    { label: 'Egreso' },
};

const INCIDENTS = [
  {
    id: 'INC-2026-018', kind: 'accidente', severity: 'leve',
    emp: { name: 'Carlos Andrés Vélez', initials: 'CV', role: 'Operario de Clasificación' },
    when: '02/05/2026 · 09:42', site: 'Planta Cali · Zona Clasificación',
    body: ['hand-r'], description: 'Quemadura de segundo grado en mano derecha al manipular bandeja de material recién procesado sin guante térmico.',
    measures: 'Atención inmediata en enfermería. Aplicación de protocolo de quemaduras. Remisión a IPS Megacentro.',
    arl: { notified: true, when: '02/05/2026 · 11:30', code: 'SUR-26-1182' },
    status: 'investigacion',
    witnesses: 'Diego Andrés Toro (E0142), Luis Miguel Marín (E0067)',
  },
  {
    id: 'INC-2026-017', kind: 'incidente', severity: 'baja',
    emp: { name: 'María Fernanda López', initials: 'MF', role: 'Op. Aprovechamiento' },
    when: '28/04/2026 · 14:15', site: 'Planta Cali · Línea Aprovechamiento 2',
    body: ['foot-l'], description: 'Casi-accidente: trabajadora resbaló por derrame de aceite no señalizado. No hubo lesión.',
    measures: 'Limpieza inmediata de la zona. Refuerzo de señalización. Recordatorio de protocolo 5S al inicio de turno.',
    arl: { notified: false, when: null, code: null },
    status: 'cerrado',
    witnesses: 'Adriana Restrepo (E0298)',
  },
  {
    id: 'INC-2026-015', kind: 'accidente', severity: 'moderada',
    emp: { name: 'Jorge Iván Patiño', initials: 'JP', role: 'Conductor' },
    when: '15/04/2026 · 06:50', site: 'Vía Cali–Barranquilla · Km 23',
    body: ['back', 'leg-l'], description: 'Accidente de tránsito en ruta laboral. Vehículo de la empresa colisionó por alcance. Lesión lumbar y contusión muslo izquierdo.',
    measures: 'Atención prehospitalaria SOAT. Traslado a Clínica Comfamiliar. Reporte a tránsito y aseguradora.',
    arl: { notified: true, when: '15/04/2026 · 08:00', code: 'SUR-26-0987' },
    status: 'investigacion',
    witnesses: 'Conductor del otro vehículo · placa SVN-487',
  },
  {
    id: 'INC-2026-012', kind: 'enfermedad', severity: 'moderada',
    emp: { name: 'Luis Miguel Marín', initials: 'LM', role: 'Líder de Aprovechamiento' },
    when: '03/04/2026', site: 'Planta Cali',
    body: ['arm-r'], description: 'Diagnóstico médico de síndrome del túnel carpiano derecho — presunta enfermedad laboral por movimientos repetitivos.',
    measures: 'Reubicación temporal. Pausas activas cada 90 min. Inicio proceso calificación origen ante ARL.',
    arl: { notified: true, when: '04/04/2026 · 09:15', code: 'SUR-26-0834' },
    status: 'investigacion',
    witnesses: '—',
  },
  {
    id: 'INC-2026-009', kind: 'incidente', severity: 'baja',
    emp: { name: 'Paula Valencia Ríos', initials: 'PV', role: 'Téc. Mantenimiento' },
    when: '21/03/2026 · 11:20', site: 'Planta Cali · Cuarto eléctrico',
    body: ['head'], description: 'Casi-accidente: golpe leve contra estructura baja. Sin lesión, requirió uso de casco.',
    measures: 'Refuerzo señalización de altura libre. Inducción exprés al equipo de mantenimiento.',
    arl: { notified: false, when: null, code: null },
    status: 'cerrado',
    witnesses: 'Diego Andrés Toro (E0142)',
  },
  {
    id: 'INC-2026-006', kind: 'accidente', severity: 'leve',
    emp: { name: 'Andrés Felipe Mejía', initials: 'AM', role: 'Operario de Clasificación' },
    when: '12/02/2026 · 16:08', site: 'Planta Cali · Bodega',
    body: ['leg-r'], description: 'Caída al mismo nivel, contusión rodilla derecha. Sin incapacidad.',
    measures: 'Atención en enfermería. Reposición de cinta antideslizante en zona.',
    arl: { notified: true, when: '12/02/2026 · 17:30', code: 'SUR-26-0312' },
    status: 'cerrado',
    witnesses: 'Carlos Andrés Vélez (E0205)',
  },
];

const STATUS_INC = {
  investigacion: { label: 'En investigación', pill: 'amber-soft', dot: '#854D0E' },
  cerrado:       { label: 'Cerrado',          pill: 'green',      dot: 'var(--green-600)' },
};

const KIND_INC = {
  accidente:   { label: 'Accidente',           tone: 'rose' },
  incidente:   { label: 'Incidente',           tone: 'amber' },
  enfermedad:  { label: 'Enfermedad laboral',  tone: 'navy' },
};

const RISK_MATRIX = [
  { role: 'Operario de Clasificación',     site: 'Cali',    factor: 'físico',       sub: 'Calor · ruido', level: 'alto',     controls: ['Guantes térmicos', 'Protección auditiva 25 dB', 'Pausas en zona ventilada'], arl: 'Sura',      cot: '2.436%' },
  { role: 'Op. Aprovechamiento',             site: 'Cali',    factor: 'biomecánico',  sub: 'Movimiento repetitivo', level: 'medio', controls: ['Rotación de puestos', 'Pausas activas cada 2 h', 'Ajuste ergonómico'],         arl: 'Sura',      cot: '0.522%' },
  { role: 'Téc. Mantenimiento',      site: 'Cali',    factor: 'físico',       sub: 'Eléctrico · alturas',   level: 'critico', controls: ['LOTO obligatorio', 'Permiso de trabajo en altura', 'EPP completo categoría III', 'Compañero de seguridad'], arl: 'Sura', cot: '6.960%' },
  { role: 'Conductor',               site: 'Barranquilla',  factor: 'físico',       sub: 'Vial · postural',       level: 'alto',     controls: ['Plan estratégico de seguridad vial', 'Examen visual semestral', 'Bitácora de descansos'], arl: 'Sura',      cot: '4.350%' },
  { role: 'Aux. Calidad',            site: 'Cali',    factor: 'químico',      sub: 'Reactivos de laboratorio', level: 'medio',  controls: ['Hojas de seguridad MSDS', 'Cabina de extracción', 'EPP químico'],                          arl: 'Sura',      cot: '1.044%' },
  { role: 'Líder de Aprovechamiento',        site: 'Cali',    factor: 'psicosocial',  sub: 'Carga mental · liderazgo', level: 'medio',  controls: ['Batería riesgo psicosocial bienal', 'Espacios 1:1', 'Plan de acompañamiento'],            arl: 'Sura',      cot: '0.522%' },
  { role: 'Aux. Recursos Humanos',   site: 'Cali',    factor: 'ergonómico',   sub: 'Postura mantenida',     level: 'bajo',     controls: ['Silla ergonómica', 'Pausas activas', 'Capacitación higiene postural'],                       arl: 'Sura',      cot: '0.522%' },
  { role: 'Operaria de Planta',      site: 'Cali',    factor: 'biomecánico',  sub: 'Movimiento repetitivo · postura', level: 'alto',  controls: ['Ajuste ergonómico de puesto', 'Rotación cada 2 h', 'Programa epidemiológico DME'], arl: 'Sura',      cot: '4.350%' },
];

const RISK_LEVEL = {
  bajo:    { label: 'Bajo',    pill: 'green',      tone: 'var(--green-600)' },
  medio:   { label: 'Medio',   pill: 'amber-soft', tone: '#854D0E' },
  alto:    { label: 'Alto',    pill: 'amber',      tone: 'var(--amber-600)' },
  critico: { label: 'Crítico', pill: 'rose',       tone: 'var(--rose-600)' },
};

const FACTOR_TONE = {
  'físico':       'blue',
  'químico':      'amber',
  'biomecánico':  'navy',
  'ergonómico':   'navy',
  'psicosocial':  'rose',
  'biológico':    'green',
};

const COPASST = [
  { initials: 'CR', name: 'Carolina Restrepo Salazar', role: 'Presidenta',          source: 'Designada por empleador', from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  { initials: 'JC', name: 'Jaime Castro Ordóñez',      role: 'Vicepresidente',      source: 'Elegido por trabajadores', from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  { initials: 'PG', name: 'Patricia Gómez Lara',       role: 'Secretaria',          source: 'Designada por empleador', from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  { initials: 'AM', name: 'Andrés Felipe Mejía',       role: 'Vocal principal',     source: 'Elegido por trabajadores', from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  { initials: 'NC', name: 'Nicolás Cárdenas',          role: 'Vocal principal',     source: 'Elegido por trabajadores', from: '01/02/2025', to: '01/02/2027', site: 'Barranquilla' },
  { initials: 'PV', name: 'Paula Valencia Ríos',       role: 'Suplente',            source: 'Elegida por trabajadores', from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
];

const MEETINGS = [
  { date: '08/05/2026 · 14:00', topic: 'Análisis accidentes abril · seguimiento INC-2026-018',     status: 'pendiente', site: 'Cali', who: 'COPASST' },
  { date: '15/05/2026 · 09:00', topic: 'Simulacro de evacuación general · cronograma',             status: 'pendiente', site: 'Cali', who: 'Brigada' },
  { date: '12/04/2026 · 14:00', topic: 'Seguimiento matriz de riesgos · cierre acciones Q1',       status: 'realizada', site: 'Cali', who: 'COPASST' },
  { date: '22/04/2026 · 16:00', topic: 'Capacitación de brigada · primeros auxilios refuerzo',     status: 'realizada', site: 'Cali', who: 'Brigada' },
];

// Comité de Convivencia Laboral — Resolución 652 y 1356 de 2012, Ley 1010 de 2006
// Atica: 824 colaboradores → composición ampliada 4 principales + 4 suplentes
// Período 2025–2027 (2 años, Res. 1356 art. 3)
const CONVIVENCIA_COMITE = [
  // Principales — empleador (designados)
  { initials: 'CR', name: 'Carolina Restrepo Salazar', role: 'Jefe de RRHH',          source: 'Empleador',    kind: 'principal', position: 'Presidenta',  from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  { initials: 'PG', name: 'Patricia Gómez Lara',       role: 'Coord. Bienestar',     source: 'Empleador',    kind: 'principal', position: 'Vocal',       from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  // Principales — trabajadores (elegidos por votación)
  { initials: 'LM', name: 'Luis Miguel Marín',         role: 'Líder de Aprovechamiento',     source: 'Trabajadores', kind: 'principal', position: 'Secretario',  from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  { initials: 'PV', name: 'Paula Valencia Ríos',       role: 'Téc. Mantenimiento',   source: 'Trabajadores', kind: 'principal', position: 'Vocal',       from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  // Suplentes — empleador
  { initials: 'MR', name: 'Manuel Rodríguez García',   role: 'Gerente de Planta',    source: 'Empleador',    kind: 'suplente',  position: 'Suplente',    from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  { initials: 'AC', name: 'Ana Lucía Castaño',         role: 'Aux. RRHH',            source: 'Empleador',    kind: 'suplente',  position: 'Suplente',    from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  // Suplentes — trabajadores
  { initials: 'AM', name: 'Andrés Felipe Mejía',       role: 'Operario de Clasificación',  source: 'Trabajadores', kind: 'suplente',  position: 'Suplente',    from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
  { initials: 'MF', name: 'María Fernanda López',      role: 'Op. Aprovechamiento',          source: 'Trabajadores', kind: 'suplente',  position: 'Suplente',    from: '01/02/2025', to: '01/02/2027', site: 'Cali' },
];

// Sesiones — 4 ordinarias trimestrales (Res. 1356 art. 4) + extraordinarias por queja
const CONVIVENCIA_SESIONES = [
  { id: 'CCL-2026-Q1',   date: '12/02/2026 · 14:00', kind: 'ordinaria',     topic: 'Sesión ordinaria Q1 · Revisión casos abiertos',      site: 'Cali · Sala Junta', status: 'realizada', acta: 'CCL-ACTA-2026-001', quorum: '4/4' },
  { id: 'CCL-2026-EXT1', date: '21/03/2026 · 10:00', kind: 'extraordinaria', topic: 'Sesión extraordinaria · Caso CCL-2026-002',         site: 'Cali · Sala Junta', status: 'realizada', acta: 'CCL-ACTA-2026-002', quorum: '4/4' },
  { id: 'CCL-2026-Q2',   date: '14/05/2026 · 14:00', kind: 'ordinaria',     topic: 'Sesión ordinaria Q2 · Seguimiento conciliaciones',  site: 'Cali · Sala Junta', status: 'pendiente', acta: null,                quorum: null },
  { id: 'CCL-2026-Q3',   date: '13/08/2026 · 14:00', kind: 'ordinaria',     topic: 'Sesión ordinaria Q3 · Informe semestral',           site: 'Cali · Sala Junta', status: 'pendiente', acta: null,                quorum: null },
  { id: 'CCL-2026-Q4',   date: '12/11/2026 · 14:00', kind: 'ordinaria',     topic: 'Sesión ordinaria Q4 · Cierre anual e informe Gerencia', site: 'Cali · Sala Junta', status: 'pendiente', acta: null,            quorum: null },
];

// Casos — datos anonimizados (confidencial por art. 14 Res. 652)
const CONVIVENCIA_CASOS = [
  { id: 'CCL-2026-001', received: '08/01/2026', kind: 'maltrato',       state: 'cerrado',      daysOpen: 42, area: 'Aprovechamiento',    summary: 'Conducta verbal reiterativa entre pares · cerrado por conciliación.',         declarante: 'identificado' },
  { id: 'CCL-2026-002', received: '15/03/2026', kind: 'discriminacion', state: 'seguimiento',  daysOpen: 52, area: 'Clasificación',    summary: 'Presunta discriminación por turno · medidas pedagógicas en curso.',            declarante: 'identificado' },
  { id: 'CCL-2026-003', received: '02/04/2026', kind: 'persecucion',    state: 'conciliacion', daysOpen: 34, area: 'Logística', summary: 'Asignación inequitativa de tareas · sesión de conciliación 14/05.',             declarante: 'anonimo'      },
  { id: 'CCL-2026-004', received: '28/04/2026', kind: 'inequidad',      state: 'recibido',     daysOpen: 8,  area: 'Aprovechamiento',    summary: 'Queja sobre evaluación de desempeño · asignación pendiente.',                   declarante: 'identificado' },
];

// 6 modalidades de acoso laboral — Ley 1010 de 2006 art. 2
const KIND_CCL = {
  maltrato:        { label: 'Maltrato laboral',       tone: 'rose'  },
  persecucion:     { label: 'Persecución laboral',    tone: 'rose'  },
  discriminacion:  { label: 'Discriminación laboral', tone: 'amber' },
  inequidad:       { label: 'Inequidad laboral',      tone: 'amber' },
  desproteccion:   { label: 'Desprotección laboral',  tone: 'navy'  },
  entorpecimiento: { label: 'Entorpecimiento laboral', tone: 'navy' },
};

const STATE_CCL = {
  recibido:     { label: 'Recibido',        pill: 'navy',       dot: 'var(--navy-800)'  },
  conciliacion: { label: 'En conciliación', pill: 'amber-soft', dot: 'var(--amber-600)' },
  seguimiento:  { label: 'En seguimiento',  pill: 'blue',       dot: '#0B6BB8'          },
  cerrado:      { label: 'Cerrado',         pill: 'green',      dot: 'var(--green-600)' },
  archivado:    { label: 'Archivado',       pill: 'rose',       dot: 'var(--rose-600)'  },
};

// ─── Root ──────────────────────────────────────────────────

const SST = () => {
  const [section, setSection] = _sst_useState('exams');
  const [furatOpen, setFuratOpen]     = _sst_useState(false);
  const [casoOpen, setCasoOpen]       = _sst_useState(false);
  const [miembroOpen, setMiembroOpen] = _sst_useState(false);
  const [sesionOpen, setSesionOpen]   = _sst_useState(false);

  return (
    <div className="main" data-screen-label="SST">
      <div className="page-head">
        <div>
          <h1 className="page-title">Seguridad y Salud en el Trabajo</h1>
          <div className="page-subtitle">
            <b>SG-SST · Resolución 0312 de 2019</b> · ARL Sura · Plan vigente 2026
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn"><IconBarChart size={14} /> Reporte SG-SST</button>
          <button className="btn primary" onClick={() => setFuratOpen(true)}>
            <IconAlert size={14} /> Reportar accidente
          </button>
        </div>
      </div>

      {/* KPIs */}
      <div className="tr-kpis">
        <div className="tr-kpi">
          <div className="tr-kpi-icon rose"><IconAlert size={18} /></div>
          <div>
            <div className="tr-kpi-num">3 <small>· 4 · 5</small></div>
            <div className="tr-kpi-lbl">Exámenes vencidos · por vencer · al día (k)</div>
            <div className="tr-kpi-foot down">3 vencidos requieren acción inmediata</div>
          </div>
        </div>
        <div className="tr-kpi">
          <div className="tr-kpi-icon amber"><IconShield size={18} /></div>
          <div>
            <div className="tr-kpi-num">6 <small>/ año</small></div>
            <div className="tr-kpi-lbl">Accidentes e incidentes 2026</div>
            <div className="tr-kpi-foot up">−40% vs. 2025</div>
          </div>
        </div>
        <div className="tr-kpi">
          <div className="tr-kpi-icon navy"><IconUsers size={18} /></div>
          <div>
            <div className="tr-kpi-num">38</div>
            <div className="tr-kpi-lbl">Colaboradores en riesgo alto/crítico</div>
            <div className="tr-kpi-foot muted">de 824 con plan</div>
          </div>
        </div>
        <div className="tr-kpi">
          <div className="tr-kpi-icon green"><IconCheck size={18} /></div>
          <div>
            <div className="tr-kpi-num">87<small>%</small></div>
            <div className="tr-kpi-lbl">Cumplimiento plan SG-SST</div>
            <div className="tr-kpi-foot up">+2 pts vs. abr</div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="doc-tabs">
        <button className={`doc-tab ${section === 'exams' ? 'active' : ''}`} onClick={() => setSection('exams')}>
          <IconShield size={14} /> Exámenes médicos
        </button>
        <button className={`doc-tab ${section === 'incidents' ? 'active' : ''}`} onClick={() => setSection('incidents')}>
          <IconAlert size={14} /> Accidentes e incidentes
        </button>
        <button className={`doc-tab ${section === 'matrix' ? 'active' : ''}`} onClick={() => setSection('matrix')}>
          <IconBarChart size={14} /> Matriz de riesgos
        </button>
        <button className={`doc-tab ${section === 'copasst' ? 'active' : ''}`} onClick={() => setSection('copasst')}>
          <IconUsers size={14} /> COPASST y brigadas
        </button>
        <button className={`doc-tab ${section === 'convivencia' ? 'active' : ''}`} onClick={() => setSection('convivencia')}>
          <IconShield size={14} /> Comité de Convivencia
        </button>
      </div>

      {section === 'exams'       && <ExamsSection />}
      {section === 'incidents'   && <IncidentsSection onNew={() => setFuratOpen(true)} />}
      {section === 'matrix'      && <RiskMatrixSection />}
      {section === 'copasst'     && <CopasstSection />}
      {section === 'convivencia' && (
        <ConvivenciaSection
          onNewCase={() => setCasoOpen(true)}
          onNewMember={() => setMiembroOpen(true)}
          onNewSession={() => setSesionOpen(true)}
        />
      )}

      {furatOpen   && <FuratModal               onClose={() => setFuratOpen(false)} />}
      {casoOpen    && <CasoConvivenciaModal     onClose={() => setCasoOpen(false)} />}
      {miembroOpen && <MiembroComiteModal       onClose={() => setMiembroOpen(false)} />}
      {sesionOpen  && <SesionConvivenciaModal   onClose={() => setSesionOpen(false)} />}
    </div>
  );
};

// ─── Section: Exámenes médicos ─────────────────────────────

const ExamsSection = () => {
  const [filter, setFilter] = _sst_useState('todos');
  const counts = _sst_useMemo(() => ({
    todos:     EXAMS.length,
    vigente:   EXAMS.filter(e => e.state === 'vigente').length,
    porvencer: EXAMS.filter(e => e.state === 'porvencer').length,
    vencido:   EXAMS.filter(e => e.state === 'vencido').length,
  }), []);

  const rows = filter === 'todos' ? EXAMS : EXAMS.filter(e => e.state === filter);

  return (
    <>
      <div className="sst-quickfilter">
        {[
          { id: 'todos',     label: 'Todos',      tone: '' },
          { id: 'vigente',   label: 'Vigentes',   tone: 'green' },
          { id: 'porvencer', label: 'Por vencer', tone: 'amber' },
          { id: 'vencido',   label: 'Vencidos',   tone: 'rose' },
        ].map(o => (
          <button
            key={o.id}
            className={`sst-chip ${o.tone} ${filter === o.id ? 'active' : ''}`}
            onClick={() => setFilter(o.id)}
          >
            {o.label}
            <span className="sst-chip-count">{counts[o.id]}</span>
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <button className="btn"><IconCalendar size={14} /> Programar lote</button>
      </div>

      <div className="doc-list-card">
        <table className="doc-table">
          <thead>
            <tr>
              <th>Colaborador</th>
              <th>Cargo</th>
              <th>Tipo</th>
              <th>Realizado</th>
              <th>Vence</th>
              <th>Estado</th>
              <th>Restricciones</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {rows.map(e => {
              const s = STATE_EXAM[e.state];
              return (
                <tr key={e.id}>
                  <td>
                    <div className="doc-cell-emp">
                      <div className="doc-avatar">{e.initials}</div>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{e.name}</div>
                        <div className="muted mono" style={{ fontSize: 11 }}>{e.id} · {e.site}</div>
                      </div>
                    </div>
                  </td>
                  <td className="muted" style={{ fontSize: 12.5 }}>{e.role}</td>
                  <td><span className="pill navy" style={{ fontSize: 11 }}>{TYPE_EXAM[e.type].label}</span></td>
                  <td className="mono" style={{ fontSize: 12 }}>{e.done}</td>
                  <td className={`mono ${e.state === 'vencido' ? 'sst-due-vencido' : e.state === 'porvencer' ? 'sst-due-porvencer' : ''}`} style={{ fontSize: 12 }}>{e.due}</td>
                  <td>
                    <span className={`pill ${s.pill}`}>
                      <span className="status-dot" style={{ background: s.dot }} /> {s.label}
                    </span>
                  </td>
                  <td>
                    {e.restrictions ? (
                      <div className="sst-restr" title={e.restrictions}>
                        <IconAlert size={12} />
                        <span>{e.restrictions}</span>
                      </div>
                    ) : <span className="muted" style={{ fontSize: 12 }}>—</span>}
                  </td>
                  <td>
                    <div className="doc-actions">
                      <button className="icon-action" title="Programar nuevo examen"><IconCalendar size={14} /></button>
                      <button className="icon-action" title="Ver historial"><IconExternal size={14} /></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="doc-table-foot">
          <span className="muted" style={{ fontSize: 12 }}>Mostrando {rows.length} de {EXAMS.length} exámenes</span>
          <div className="pager">
            <button className="btn" style={{ padding: '5px 9px' }}><IconChevronLeft size={13} /></button>
            <span className="mono" style={{ fontSize: 12, padding: '0 8px' }}>1 / 4</span>
            <button className="btn" style={{ padding: '5px 9px' }}><IconChevronRight size={13} /></button>
          </div>
        </div>
      </div>
    </>
  );
};

// ─── Section: Accidentes e incidentes ──────────────────────

const IncidentsSection = ({ onNew }) => {
  const [filter, setFilter] = _sst_useState('todos');
  const list = filter === 'todos' ? INCIDENTS : INCIDENTS.filter(i => i.kind === filter);

  return (
    <>
      <div className="sst-quickfilter">
        <button className={`sst-chip ${filter === 'todos' ? 'active' : ''}`}      onClick={() => setFilter('todos')}>Todos<span className="sst-chip-count">{INCIDENTS.length}</span></button>
        <button className={`sst-chip rose ${filter === 'accidente' ? 'active' : ''}`}    onClick={() => setFilter('accidente')}>Accidentes<span className="sst-chip-count">{INCIDENTS.filter(i => i.kind === 'accidente').length}</span></button>
        <button className={`sst-chip amber ${filter === 'incidente' ? 'active' : ''}`}    onClick={() => setFilter('incidente')}>Incidentes<span className="sst-chip-count">{INCIDENTS.filter(i => i.kind === 'incidente').length}</span></button>
        <button className={`sst-chip ${filter === 'enfermedad' ? 'active' : ''}`}  onClick={() => setFilter('enfermedad')}>Enfermedad laboral<span className="sst-chip-count">{INCIDENTS.filter(i => i.kind === 'enfermedad').length}</span></button>
        <div style={{ flex: 1 }} />
        <button className="btn primary" onClick={onNew}><IconPlus size={14} /> Nuevo reporte FURAT</button>
      </div>

      <div className="sst-incident-list">
        {list.map(i => {
          const k = KIND_INC[i.kind];
          const s = STATUS_INC[i.status];
          return (
            <div key={i.id} className="sst-incident">
              <div className="sst-incident-rail">
                <div className={`sst-inc-dot ${k.tone}`}>
                  <IconAlert size={14} />
                </div>
                <div className="sst-inc-line" />
              </div>
              <div className="sst-incident-body">
                <div className="sst-incident-head">
                  <div>
                    <div className="sst-incident-id mono">{i.id}</div>
                    <div className="sst-incident-title">
                      <span className={`pill ${k.tone}`} style={{ fontSize: 11 }}>{k.label}</span>
                      <span>{i.emp.name} · {i.emp.role}</span>
                    </div>
                  </div>
                  <span className={`pill ${s.pill}`}>
                    <span className="status-dot" style={{ background: s.dot }} /> {s.label}
                  </span>
                </div>

                <div className="sst-incident-meta">
                  <div><div className="muted-xs">Fecha y hora</div><div className="sst-incident-val mono" style={{ fontSize: 12 }}>{i.when}</div></div>
                  <div><div className="muted-xs">Lugar</div><div className="sst-incident-val">{i.site}</div></div>
                  <div>
                    <div className="muted-xs">ARL</div>
                    <div className="sst-incident-val">
                      {i.arl.notified ? (
                        <>
                          <IconCheck size={11} style={{ color: 'var(--green-600)' }} /> Notificada
                          <span className="muted mono" style={{ fontSize: 11, marginLeft: 6 }}>{i.arl.code}</span>
                        </>
                      ) : (
                        <span className="muted" style={{ fontSize: 12 }}>No aplica</span>
                      )}
                    </div>
                  </div>
                </div>

                <div className="sst-incident-desc">{i.description}</div>

                <div className="sst-incident-foot">
                  <span className="muted" style={{ fontSize: 12 }}>
                    <b>Medidas:</b> {i.measures}
                  </span>
                  <button className="btn" style={{ marginLeft: 'auto' }}><IconExternal size={13} /> Ver caso</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
};

// ─── Section: Matriz de riesgos ────────────────────────────

const RiskMatrixSection = () => {
  return (
    <>
      <div className="sst-quickfilter">
        <select>
          <option>Todas las sedes</option>
          <option>Cali</option>
          <option>Barranquilla</option>
          <option>Bogotá</option>
        </select>
        <select>
          <option>Todos los factores</option>
          <option>Físico</option>
          <option>Químico</option>
          <option>Biomecánico</option>
          <option>Ergonómico</option>
          <option>Psicosocial</option>
        </select>
        <select>
          <option>Cualquier nivel</option>
          <option>Crítico</option>
          <option>Alto</option>
          <option>Medio</option>
          <option>Bajo</option>
        </select>
        <div style={{ flex: 1 }} />
        <button className="btn"><IconExternal size={14} /> Descargar matriz</button>
      </div>

      <div className="doc-list-card">
        <table className="doc-table">
          <thead>
            <tr>
              <th>Cargo · Sede</th>
              <th>Factor de riesgo</th>
              <th>Nivel</th>
              <th>Controles implementados</th>
              <th>ARL · cotización</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {RISK_MATRIX.map((r, i) => {
              const lvl = RISK_LEVEL[r.level];
              const factTone = FACTOR_TONE[r.factor] || 'navy';
              return (
                <tr key={i}>
                  <td>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{r.role}</div>
                    <div className="muted" style={{ fontSize: 11.5 }}>{r.site}</div>
                  </td>
                  <td>
                    <div className="sst-factor">
                      <span className={`tr-cat-badge ${factTone}`} style={{ textTransform: 'capitalize' }}>{r.factor}</span>
                      <span className="muted" style={{ fontSize: 12 }}>{r.sub}</span>
                    </div>
                  </td>
                  <td>
                    <span className={`pill ${lvl.pill}`} style={{ fontWeight: 700 }}>
                      <span className="status-dot" style={{ background: lvl.tone }} /> {lvl.label}
                    </span>
                  </td>
                  <td>
                    <div className="sst-controls">
                      {r.controls.map((c, j) => (
                        <span key={j} className="sst-control"><IconCheck size={10} /> {c}</span>
                      ))}
                    </div>
                  </td>
                  <td>
                    <div style={{ fontSize: 12.5, fontWeight: 600 }}>{r.arl}</div>
                    <div className="mono" style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>{r.cot}</div>
                  </td>
                  <td>
                    <div className="doc-actions">
                      <button className="icon-action" title="Editar controles"><IconExternal size={14} /></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

// ─── Section: COPASST y Brigadas ───────────────────────────

const CopasstSection = () => {
  return (
    <>
      <div className="sst-copasst-grid">
        <div className="sst-card">
          <div className="sst-card-head">
            <div>
              <div className="sst-card-title">Integrantes COPASST</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 3 }}>Período 2025–2027 · {COPASST.length} miembros</div>
            </div>
            <button className="btn"><IconPlus size={13} /> Agregar miembro</button>
          </div>
          <div className="sst-members">
            {COPASST.map((m, i) => {
              const tone = m.role.includes('Presidenta') ? 'navy'
                         : m.role.includes('Vicepresid')  ? 'navy'
                         : m.role.includes('Secret')      ? 'blue'
                         : 'green';
              return (
                <div key={i} className="sst-member">
                  <div className="doc-avatar" style={{ width: 36, height: 36, fontSize: 12 }}>{m.initials}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{m.name}</div>
                    <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>{m.source} · {m.site}</div>
                    <div className="muted mono" style={{ fontSize: 11, marginTop: 4 }}>
                      <IconCalendar size={10} /> Vig. {m.from} → {m.to}
                    </div>
                  </div>
                  <span className={`pill ${tone}`} style={{ fontSize: 11 }}>{m.role}</span>
                </div>
              );
            })}
          </div>
        </div>

        <div className="sst-card">
          <div className="sst-card-head">
            <div>
              <div className="sst-card-title">Próximas reuniones</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 3 }}>COPASST y Brigada de Emergencias</div>
            </div>
            <button className="btn primary"><IconPlus size={13} /> Programar</button>
          </div>
          <div className="sst-meetings">
            {MEETINGS.map((m, i) => (
              <div key={i} className={`sst-meeting ${m.status === 'realizada' ? 'past' : ''}`}>
                <div className="sst-meeting-date">
                  <IconCalendar size={14} />
                  <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{m.date}</span>
                </div>
                <div className="sst-meeting-body">
                  <div style={{ fontWeight: 600, fontSize: 13 }}>{m.topic}</div>
                  <div className="muted" style={{ fontSize: 11.5, marginTop: 3 }}>{m.who} · {m.site}</div>
                </div>
                <span className={`pill ${m.status === 'pendiente' ? 'amber-soft' : 'green'}`} style={{ fontSize: 11 }}>
                  {m.status === 'pendiente' ? 'Pendiente' : 'Realizada'}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
};

// ─── Section: Comité de Convivencia Laboral ───────────────
// Marco legal: Resolución 652 y 1356 de 2012 · Ley 1010 de 2006

const ConvivenciaSection = ({ onNewCase, onNewMember, onNewSession }) => {
  const [filter, setFilter] = _sst_useState('todos');

  const principales = CONVIVENCIA_COMITE.filter(m => m.kind === 'principal');
  const suplentes   = CONVIVENCIA_COMITE.filter(m => m.kind === 'suplente');

  const proxima      = CONVIVENCIA_SESIONES.find(s => s.status === 'pendiente');
  const realizadas   = CONVIVENCIA_SESIONES.filter(s => s.status === 'realizada').length;
  const cumplimiento = Math.round((realizadas / CONVIVENCIA_SESIONES.length) * 100);

  const counts = _sst_useMemo(() => ({
    todos:        CONVIVENCIA_CASOS.length,
    recibido:     CONVIVENCIA_CASOS.filter(c => c.state === 'recibido').length,
    conciliacion: CONVIVENCIA_CASOS.filter(c => c.state === 'conciliacion').length,
    seguimiento:  CONVIVENCIA_CASOS.filter(c => c.state === 'seguimiento').length,
    cerrado:      CONVIVENCIA_CASOS.filter(c => c.state === 'cerrado').length,
  }), []);

  const activos = counts.recibido + counts.conciliacion + counts.seguimiento;
  const cerrados = counts.cerrado;
  const casos = filter === 'todos' ? CONVIVENCIA_CASOS : CONVIVENCIA_CASOS.filter(c => c.state === filter);

  const slaBadge = (c) => {
    if (c.state === 'cerrado' || c.state === 'archivado') return null;
    if (c.daysOpen > 60) return <span className="pill rose" style={{ fontSize: 10.5 }}>SLA vencido</span>;
    if (c.daysOpen > 30) return <span className="pill amber-soft" style={{ fontSize: 10.5 }}>SLA por vencer</span>;
    return null;
  };

  const groupHeader = (label) => (
    <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', padding: '8px 16px 4px' }}>
      {label}
    </div>
  );

  const renderMember = (m, i) => {
    const tone = m.position === 'Presidenta' ? 'navy'
               : m.position === 'Secretario' ? 'blue'
               : m.kind === 'suplente'       ? 'amber-soft'
               :                                'green';
    return (
      <div key={`${m.kind}-${i}`} className="sst-member">
        <div className="doc-avatar" style={{ width: 36, height: 36, fontSize: 12 }}>{m.initials}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13 }}>{m.name}</div>
          <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>
            {m.role} · {m.source} · {m.site}
          </div>
          <div className="muted mono" style={{ fontSize: 11, marginTop: 4 }}>
            <IconCalendar size={10} /> Vig. {m.from} → {m.to}
          </div>
        </div>
        <span className={`pill ${tone}`} style={{ fontSize: 11 }}>{m.position}</span>
      </div>
    );
  };

  return (
    <>
      {/* Banner marco legal */}
      <div className="doc-list-card" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', marginBottom: 12, borderLeft: '3px solid var(--navy-800)' }}>
        <IconShield size={16} />
        <div style={{ fontSize: 12.5, lineHeight: 1.5 }}>
          <b>Marco legal:</b> Resolución 652 y 1356 de 2012 · Ley 1010 de 2006 ·
          <span className="muted"> Reuniones ordinarias trimestrales · Período 2025–2027 · Composición ampliada (4 + 4)</span>
        </div>
      </div>

      {/* KPIs específicos del comité */}
      <div className="tr-kpis">
        <div className="tr-kpi">
          <div className="tr-kpi-icon amber"><IconAlert size={18} /></div>
          <div>
            <div className="tr-kpi-num">{activos}</div>
            <div className="tr-kpi-lbl">Casos activos</div>
            <div className="tr-kpi-foot muted">recibido · conciliación · seguimiento</div>
          </div>
        </div>
        <div className="tr-kpi">
          <div className="tr-kpi-icon green"><IconCheck size={18} /></div>
          <div>
            <div className="tr-kpi-num">{cerrados}</div>
            <div className="tr-kpi-lbl">Casos cerrados YTD</div>
            <div className="tr-kpi-foot up">resueltos por conciliación</div>
          </div>
        </div>
        <div className="tr-kpi">
          <div className="tr-kpi-icon navy"><IconCalendar size={18} /></div>
          <div>
            <div className="tr-kpi-num mono" style={{ fontSize: 17 }}>{proxima ? proxima.date.split(' · ')[0] : '—'}</div>
            <div className="tr-kpi-lbl">Próxima sesión</div>
            <div className="tr-kpi-foot muted">{proxima ? proxima.topic.split(' · ')[0] : 'sin agendar'}</div>
          </div>
        </div>
        <div className="tr-kpi">
          <div className="tr-kpi-icon green"><IconShield size={18} /></div>
          <div>
            <div className="tr-kpi-num">{cumplimiento}<small>%</small></div>
            <div className="tr-kpi-lbl">Cumplimiento sesiones</div>
            <div className="tr-kpi-foot muted">{realizadas} de {CONVIVENCIA_SESIONES.length} realizadas</div>
          </div>
        </div>
      </div>

      {/* Grid 2 columnas: Integrantes + Sesiones */}
      <div className="sst-copasst-grid">
        {/* Integrantes */}
        <div className="sst-card">
          <div className="sst-card-head">
            <div>
              <div className="sst-card-title">Integrantes del Comité</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 3 }}>
                Período 2025–2027 · {principales.length} principales + {suplentes.length} suplentes
              </div>
            </div>
            <button className="btn" onClick={onNewMember}><IconPlus size={13} /> Agregar miembro</button>
          </div>

          {groupHeader('Principales')}
          <div className="sst-members">
            {principales.map(renderMember)}
          </div>

          {groupHeader('Suplentes')}
          <div className="sst-members">
            {suplentes.map(renderMember)}
          </div>
        </div>

        {/* Sesiones */}
        <div className="sst-card">
          <div className="sst-card-head">
            <div>
              <div className="sst-card-title">Cronograma de sesiones 2026</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 3 }}>
                Ordinarias trimestrales (Res. 1356 art. 4) + extraordinarias por queja
              </div>
            </div>
            <button className="btn primary" onClick={onNewSession}><IconPlus size={13} /> Programar sesión</button>
          </div>
          <div className="sst-meetings">
            {CONVIVENCIA_SESIONES.map((s, i) => (
              <div key={i} className={`sst-meeting ${s.status === 'realizada' ? 'past' : ''}`}>
                <div className="sst-meeting-date">
                  <IconCalendar size={14} />
                  <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{s.date}</span>
                </div>
                <div className="sst-meeting-body">
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontWeight: 600, fontSize: 13 }}>
                    <span className={`pill ${s.kind === 'extraordinaria' ? 'rose' : 'navy'}`} style={{ fontSize: 10.5 }}>
                      {s.kind === 'extraordinaria' ? 'Extraordinaria' : 'Ordinaria'}
                    </span>
                    <span>{s.topic}</span>
                  </div>
                  <div className="muted mono" style={{ fontSize: 11, marginTop: 3 }}>
                    {s.id} · {s.site}
                    {s.acta && <> · <IconExternal size={10} /> Acta {s.acta}</>}
                    {s.quorum && <> · Quórum {s.quorum}</>}
                  </div>
                </div>
                <span className={`pill ${s.status === 'pendiente' ? 'amber-soft' : 'green'}`} style={{ fontSize: 11 }}>
                  {s.status === 'pendiente' ? 'Pendiente' : 'Realizada'}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Quickfilter de casos + Nuevo caso */}
      <div className="sst-quickfilter" style={{ marginTop: 16 }}>
        {[
          { id: 'todos',        label: 'Todos',         tone: '' },
          { id: 'recibido',     label: 'Recibidos',     tone: '' },
          { id: 'conciliacion', label: 'Conciliación',  tone: 'amber' },
          { id: 'seguimiento',  label: 'Seguimiento',   tone: '' },
          { id: 'cerrado',      label: 'Cerrados',      tone: 'green' },
        ].map(o => (
          <button
            key={o.id}
            className={`sst-chip ${o.tone} ${filter === o.id ? 'active' : ''}`}
            onClick={() => setFilter(o.id)}
          >
            {o.label}
            <span className="sst-chip-count">{counts[o.id]}</span>
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <button className="btn"><IconBarChart size={14} /> Informe Gerencia</button>
        <button className="btn primary" onClick={onNewCase}><IconPlus size={14} /> Nuevo caso</button>
      </div>

      {/* Lista de casos — timeline */}
      <div className="sst-incident-list">
        {casos.map(c => {
          const k = KIND_CCL[c.kind];
          const s = STATE_CCL[c.state];
          return (
            <div key={c.id} className="sst-incident">
              <div className="sst-incident-rail">
                <div className={`sst-inc-dot ${k.tone}`}>
                  <IconShield size={14} />
                </div>
                <div className="sst-inc-line" />
              </div>
              <div className="sst-incident-body">
                <div className="sst-incident-head">
                  <div>
                    <div className="sst-incident-id mono">{c.id}</div>
                    <div className="sst-incident-title">
                      <span className={`pill ${k.tone}`} style={{ fontSize: 11 }}>{k.label}</span>
                      <span>Área: {c.area}</span>
                      <span className="pill rose" style={{ fontSize: 10.5 }}>Confidencial</span>
                      {slaBadge(c)}
                    </div>
                  </div>
                  <span className={`pill ${s.pill}`}>
                    <span className="status-dot" style={{ background: s.dot }} /> {s.label}
                  </span>
                </div>

                <div className="sst-incident-meta">
                  <div>
                    <div className="muted-xs">Recibido</div>
                    <div className="sst-incident-val mono" style={{ fontSize: 12 }}>{c.received}</div>
                  </div>
                  <div>
                    <div className="muted-xs">Días en gestión</div>
                    <div className="sst-incident-val mono" style={{ fontSize: 12 }}>{c.daysOpen} días</div>
                  </div>
                  <div>
                    <div className="muted-xs">Declarante</div>
                    <div className="sst-incident-val" style={{ fontSize: 12 }}>
                      {c.declarante === 'anonimo' ? 'Anónimo' : 'Identificado'}
                    </div>
                  </div>
                </div>

                <div style={{ marginTop: 8, fontSize: 12.5, color: 'var(--text)' }}>
                  {c.summary}
                </div>

                <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
                  <button className="btn" style={{ padding: '5px 10px', fontSize: 12 }}>
                    <IconExternal size={12} /> Expediente
                  </button>
                  <button className="btn" style={{ padding: '5px 10px', fontSize: 12 }}>
                    <IconCalendar size={12} /> Citar conciliación
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
};

// ─── FURAT modal ───────────────────────────────────────────

const BODY_PARTS = [
  { id: 'head',    label: 'Cabeza',           cx: 50, cy: 14, r: 9 },
  { id: 'neck',    label: 'Cuello',           cx: 50, cy: 25, r: 4 },
  { id: 'chest',   label: 'Tórax',            cx: 50, cy: 38, w: 22, h: 14 },
  { id: 'back',    label: 'Espalda · lumbar', cx: 50, cy: 52, w: 22, h: 8 },
  { id: 'arm-l',   label: 'Brazo izquierdo',  cx: 32, cy: 42, w: 7, h: 22 },
  { id: 'arm-r',   label: 'Brazo derecho',    cx: 68, cy: 42, w: 7, h: 22 },
  { id: 'hand-l',  label: 'Mano izquierda',   cx: 32, cy: 66, w: 7, h: 6 },
  { id: 'hand-r',  label: 'Mano derecha',     cx: 68, cy: 66, w: 7, h: 6 },
  { id: 'leg-l',   label: 'Pierna izquierda', cx: 43, cy: 75, w: 9, h: 22 },
  { id: 'leg-r',   label: 'Pierna derecha',   cx: 57, cy: 75, w: 9, h: 22 },
  { id: 'foot-l',  label: 'Pie izquierdo',    cx: 43, cy: 99, w: 9, h: 4 },
  { id: 'foot-r',  label: 'Pie derecho',      cx: 57, cy: 99, w: 9, h: 4 },
];

const BodyDiagram = ({ selected, onToggle }) => {
  return (
    <svg viewBox="0 0 100 110" className="sst-body-svg">
      {/* base body silhouette */}
      <g className="sst-body-base">
        <circle cx="50" cy="14" r="9" />
        <rect x="46" y="22" width="8" height="6" rx="2" />
        <path d="M 39 28 Q 39 26 41 26 L 59 26 Q 61 26 61 28 L 64 70 Q 64 72 62 72 L 56 72 L 56 100 Q 56 102 54 102 L 51 102 L 51 75 L 49 75 L 49 102 L 46 102 Q 44 102 44 100 L 44 72 L 38 72 Q 36 72 36 70 Z" />
        <path d="M 39 30 L 28 60 Q 27 63 30 64 L 33 64 L 36 36" />
        <path d="M 61 30 L 72 60 Q 73 63 70 64 L 67 64 L 64 36" />
      </g>
      {/* clickable hot zones */}
      {BODY_PARTS.map(p => {
        const on = selected.includes(p.id);
        const common = {
          className: `sst-body-zone ${on ? 'on' : ''}`,
          onClick: () => onToggle(p.id),
        };
        if (p.r) return <circle key={p.id} cx={p.cx} cy={p.cy} r={p.r} {...common}><title>{p.label}</title></circle>;
        return <rect key={p.id} x={p.cx - p.w / 2} y={p.cy - p.h / 2} width={p.w} height={p.h} rx="2" {...common}><title>{p.label}</title></rect>;
      })}
    </svg>
  );
};

const FuratModal = ({ onClose }) => {
  const [kind, setKind] = _sst_useState('accidente');
  const [emp, setEmp]   = _sst_useState('');
  const [whenAt, setWhenAt] = _sst_useState('05/05/2026 14:30');
  const [desc, setDesc] = _sst_useState('');
  const [parts, setParts] = _sst_useState([]);
  const [witnesses, setWitnesses] = _sst_useState('');
  const [measures, setMeasures]   = _sst_useState('');
  const [arlNotified, setArl]     = _sst_useState('si');
  const [arlDate, setArlDate]     = _sst_useState('');
  const [status, setStatus]       = _sst_useState('investigacion');

  const togglePart = (id) => setParts(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onEsc = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onEsc);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onEsc); };
  }, []);

  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={{ maxWidth: 940 }}>
        <div className="modal-head">
          <div>
            <div className="modal-title">Reporte FURAT — Accidente / incidente / enfermedad laboral</div>
            <div className="modal-sub">Formato Único de Reporte de Accidente de Trabajo. Se notificará a la ARL al guardar.</div>
          </div>
          <button className="icon-btn" onClick={onClose} title="Cerrar">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
          </button>
        </div>

        <div className="modal-body">
          <div className="furat-grid">
            {/* Left column */}
            <div className="furat-col">

              <div className="furat-row">
                <label className="furat-label">Tipo de evento</label>
                <div className="furat-segment">
                  {[
                    ['accidente',  'Accidente',           'rose'],
                    ['incidente',  'Incidente',           'amber'],
                    ['enfermedad', 'Enfermedad laboral',  'navy'],
                  ].map(([k, l, t]) => (
                    <button key={k} className={`furat-seg ${kind === k ? `active ${t}` : ''}`} onClick={() => setKind(k)}>{l}</button>
                  ))}
                </div>
              </div>

              <div className="furat-row">
                <label className="furat-label">Colaborador afectado</label>
                <select value={emp} onChange={(e) => setEmp(e.target.value)}>
                  <option value="">Selecciona el colaborador…</option>
                  {EXAMS.map(e => <option key={e.id} value={e.id}>{e.name} · {e.role}</option>)}
                </select>
              </div>

              <div className="furat-row">
                <label className="furat-label">Fecha y hora del evento</label>
                <window.DatePickerCO value={whenAt} onChange={setWhenAt} withTime />
              </div>

              <div className="furat-row">
                <label className="furat-label">Descripción del evento</label>
                <textarea
                  rows={4}
                  value={desc}
                  onChange={(e) => setDesc(e.target.value)}
                  placeholder="Narra los hechos en orden cronológico: actividad que realizaba, mecanismo de la lesión, agente material…"
                />
              </div>

              <div className="furat-row">
                <label className="furat-label">Testigos</label>
                <input type="text" value={witnesses} onChange={(e) => setWitnesses(e.target.value)} placeholder="Nombre y cédula de testigos, separados por coma" />
              </div>

              <div className="furat-row">
                <label className="furat-label">Medidas inmediatas tomadas</label>
                <textarea
                  rows={3}
                  value={measures}
                  onChange={(e) => setMeasures(e.target.value)}
                  placeholder="Atención prestada, traslado, comunicaciones, acciones correctivas inmediatas…"
                />
              </div>

              <div className="furat-grid-2">
                <div className="furat-row">
                  <label className="furat-label">¿ARL notificada?</label>
                  <div className="furat-segment compact">
                    <button className={`furat-seg ${arlNotified === 'si' ? 'active green' : ''}`} onClick={() => setArl('si')}>Sí</button>
                    <button className={`furat-seg ${arlNotified === 'no' ? 'active' : ''}`}        onClick={() => setArl('no')}>No</button>
                  </div>
                </div>
                <div className="furat-row">
                  <label className="furat-label">Fecha notificación</label>
                  <window.DatePickerCO value={arlDate} onChange={setArlDate} withTime disabled={arlNotified !== 'si'} placeholder="Seleccionar fecha y hora" />
                </div>
              </div>

              <div className="furat-row">
                <label className="furat-label">Estado</label>
                <div className="furat-segment compact">
                  <button className={`furat-seg ${status === 'investigacion' ? 'active amber' : ''}`} onClick={() => setStatus('investigacion')}>En investigación</button>
                  <button className={`furat-seg ${status === 'cerrado' ? 'active green' : ''}`}      onClick={() => setStatus('cerrado')}>Cerrado</button>
                </div>
              </div>
            </div>

            {/* Right column: body diagram */}
            <div className="furat-col">
              <div className="furat-body-card">
                <div className="furat-label">Parte del cuerpo afectada</div>
                <div className="muted" style={{ fontSize: 11.5, marginTop: 2, marginBottom: 12 }}>
                  Haz clic en cada zona afectada. {parts.length} {parts.length === 1 ? 'seleccionada' : 'seleccionadas'}.
                </div>
                <BodyDiagram selected={parts} onToggle={togglePart} />
                <div className="furat-body-tags">
                  {parts.length === 0
                    ? <span className="muted" style={{ fontSize: 11.5 }}>Ninguna zona seleccionada</span>
                    : parts.map(id => {
                        const p = BODY_PARTS.find(x => x.id === id);
                        return (
                          <span key={id} className="furat-body-tag">
                            {p.label}
                            <button onClick={() => togglePart(id)} aria-label="Quitar">×</button>
                          </span>
                        );
                      })}
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="modal-foot">
          <span className="muted" style={{ fontSize: 12, marginRight: 'auto' }}>
            <IconShield size={12} /> Al guardar se notifica automáticamente a ARL Sura
          </span>
          <button className="btn" onClick={onClose}>Cancelar</button>
          <button className="btn">Guardar borrador</button>
          <button className="btn primary"><IconCheck size={14} /> Radicar reporte</button>
        </div>
      </div>
    </div>
  );
};

// ─── Caso de Convivencia modal ─────────────────────────────
// Radicación de queja confidencial (Ley 1010 de 2006 · Res. 652/2012 art. 6)

const CasoConvivenciaModal = ({ onClose }) => {
  const [conducta, setConducta]       = _sst_useState('maltrato');
  const [whenAt, setWhenAt]           = _sst_useState('05/05/2026 14:00');
  const [area, setArea]               = _sst_useState('');
  const [hechos, setHechos]           = _sst_useState('');
  const [pruebas, setPruebas]         = _sst_useState('no');
  const [conciliacion, setConcil]     = _sst_useState('si');
  const [declarante, setDeclarante]   = _sst_useState('identificado');
  const [solicitante, setSolicitante] = _sst_useState('');

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onEsc = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onEsc);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onEsc); };
  }, []);

  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={{ maxWidth: 720 }}>
        <div className="modal-head">
          <div>
            <div className="modal-title">Radicar caso · Comité de Convivencia Laboral</div>
            <div className="modal-sub">
              Información estrictamente confidencial · Ley 1010 de 2006 · Resolución 652 de 2012 art. 6
            </div>
          </div>
          <button className="icon-btn" onClick={onClose} title="Cerrar">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
          </button>
        </div>

        <div className="modal-body">
          <div className="furat-col">

            <div className="furat-row">
              <label className="furat-label">Tipo de conducta presunta (Ley 1010 art. 2)</label>
              <div className="furat-segment" style={{ flexWrap: 'wrap' }}>
                {[
                  ['maltrato',        'Maltrato',        'rose'],
                  ['persecucion',     'Persecución',     'rose'],
                  ['discriminacion',  'Discriminación',  'amber'],
                  ['inequidad',       'Inequidad',       'amber'],
                  ['desproteccion',   'Desprotección',   ''],
                  ['entorpecimiento', 'Entorpecimiento', ''],
                ].map(([k, l, t]) => (
                  <button key={k} className={`furat-seg ${conducta === k ? `active ${t}` : ''}`} onClick={() => setConducta(k)}>{l}</button>
                ))}
              </div>
            </div>

            <div className="furat-row">
              <label className="furat-label">Fecha y hora de los hechos</label>
              <window.DatePickerCO value={whenAt} onChange={setWhenAt} withTime />
            </div>

            <div className="furat-row">
              <label className="furat-label">Área / dependencia donde ocurrieron los hechos</label>
              <select value={area} onChange={(e) => setArea(e.target.value)}>
                <option value="">Selecciona el área…</option>
                <option value="aprovechamiento">Aprovechamiento · Cali</option>
                <option value="tostion">Clasificación · Cali</option>
                <option value="logistica">Logística · Cali</option>
                <option value="mantenimiento">Mantenimiento · Cali</option>
                <option value="calidad">Calidad · Cali</option>
                <option value="rrhh">RRHH · Cali</option>
                <option value="barranquilla">Operaciones · Barranquilla</option>
              </select>
            </div>

            <div className="furat-row">
              <label className="furat-label">Descripción de los hechos</label>
              <textarea
                rows={5}
                value={hechos}
                onChange={(e) => setHechos(e.target.value)}
                placeholder="Narra los hechos en orden cronológico, sin juicios de valor. Incluye fechas, frecuencia y personas involucradas. Esta información será tratada con reserva absoluta."
              />
              <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>
                <IconShield size={11} /> Información protegida · solo el comité tendrá acceso al expediente.
              </div>
            </div>

            <div className="furat-grid-2">
              <div className="furat-row">
                <label className="furat-label">¿Adjunta pruebas?</label>
                <div className="furat-segment compact">
                  <button className={`furat-seg ${pruebas === 'si' ? 'active green' : ''}`} onClick={() => setPruebas('si')}>Sí</button>
                  <button className={`furat-seg ${pruebas === 'no' ? 'active' : ''}`}        onClick={() => setPruebas('no')}>No</button>
                </div>
              </div>
              <div className="furat-row">
                <label className="furat-label">¿Solicita conciliación?</label>
                <div className="furat-segment compact">
                  <button className={`furat-seg ${conciliacion === 'si' ? 'active green' : ''}`} onClick={() => setConcil('si')}>Sí</button>
                  <button className={`furat-seg ${conciliacion === 'no' ? 'active' : ''}`}        onClick={() => setConcil('no')}>No</button>
                </div>
              </div>
            </div>

            <div className="furat-row">
              <label className="furat-label">Declarante</label>
              <div className="furat-segment compact">
                <button className={`furat-seg ${declarante === 'identificado' ? 'active navy' : ''}`} onClick={() => setDeclarante('identificado')}>Identificado</button>
                <button className={`furat-seg ${declarante === 'anonimo' ? 'active amber' : ''}`}    onClick={() => setDeclarante('anonimo')}>Anónimo</button>
              </div>
            </div>

            {declarante === 'identificado' && (
              <div className="furat-row">
                <label className="furat-label">Nombre del solicitante</label>
                <input
                  type="text"
                  value={solicitante}
                  onChange={(e) => setSolicitante(e.target.value)}
                  placeholder="Nombres y apellidos · cargo · cédula"
                />
              </div>
            )}

          </div>
        </div>

        <div className="modal-foot">
          <span className="muted" style={{ fontSize: 12, marginRight: 'auto' }}>
            <IconShield size={12} /> Al radicar, el caso queda registrado de forma confidencial y se notifica al comité.
          </span>
          <button className="btn" onClick={onClose}>Cancelar</button>
          <button className="btn">Guardar borrador</button>
          <button className="btn primary"><IconCheck size={14} /> Radicar caso</button>
        </div>
      </div>
    </div>
  );
};

// ─── Miembro del Comité modal ──────────────────────────────
// Alta de integrante (Res. 652/2012 art. 3 · Res. 1356/2012 — paridad y período de 2 años)

const MiembroComiteModal = ({ onClose }) => {
  const [nombre, setNombre]   = _sst_useState('');
  const [cedula, setCedula]   = _sst_useState('');
  const [cargo, setCargo]     = _sst_useState('');
  const [sede, setSede]       = _sst_useState('Cali');
  const [origen, setOrigen]   = _sst_useState('Empleador');
  const [tipo, setTipo]       = _sst_useState('principal');
  const [posicion, setPos]    = _sst_useState('Vocal');
  const [from, setFrom]       = _sst_useState('05/05/2026');
  const [to, setTo]           = _sst_useState('05/05/2028');

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onEsc = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onEsc);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onEsc); };
  }, []);

  // Conteo actual del comité para mostrar paridad
  const empPrin = CONVIVENCIA_COMITE.filter(m => m.source === 'Empleador'    && m.kind === 'principal').length;
  const traPrin = CONVIVENCIA_COMITE.filter(m => m.source === 'Trabajadores' && m.kind === 'principal').length;
  const empSup  = CONVIVENCIA_COMITE.filter(m => m.source === 'Empleador'    && m.kind === 'suplente').length;
  const traSup  = CONVIVENCIA_COMITE.filter(m => m.source === 'Trabajadores' && m.kind === 'suplente').length;
  const balanced = empPrin === traPrin && empSup === traSup;

  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={{ maxWidth: 720 }}>
        <div className="modal-head">
          <div>
            <div className="modal-title">Agregar integrante · Comité de Convivencia</div>
            <div className="modal-sub">
              Resolución 652 de 2012 art. 3 · paridad obligatoria empleador / trabajadores · período de 2 años
            </div>
          </div>
          <button className="icon-btn" onClick={onClose} title="Cerrar">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
          </button>
        </div>

        <div className="modal-body">
          <div className="furat-col">

            {/* Resumen paridad actual */}
            <div className="doc-list-card" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderLeft: `3px solid ${balanced ? 'var(--green-600)' : 'var(--amber-600)'}` }}>
              <IconUsers size={16} />
              <div style={{ fontSize: 12.5, lineHeight: 1.5 }}>
                <b>Composición actual:</b> Principales {empPrin} empleador · {traPrin} trabajadores · Suplentes {empSup} empleador · {traSup} trabajadores
                {balanced
                  ? <span className="muted"> · paridad correcta</span>
                  : <span style={{ color: 'var(--amber-600)' }}> · paridad desbalanceada</span>}
              </div>
            </div>

            <div className="furat-grid-2">
              <div className="furat-row">
                <label className="furat-label">Nombres y apellidos</label>
                <input type="text" value={nombre} onChange={(e) => setNombre(e.target.value)} placeholder="Ej: Carolina Restrepo Salazar" />
              </div>
              <div className="furat-row">
                <label className="furat-label">Cédula</label>
                <input type="text" value={cedula} onChange={(e) => setCedula(e.target.value)} placeholder="Solo dígitos" />
              </div>
            </div>

            <div className="furat-grid-2">
              <div className="furat-row">
                <label className="furat-label">Cargo</label>
                <input type="text" value={cargo} onChange={(e) => setCargo(e.target.value)} placeholder="Ej: Líder de Aprovechamiento" />
              </div>
              <div className="furat-row">
                <label className="furat-label">Sede</label>
                <select value={sede} onChange={(e) => setSede(e.target.value)}>
                  <option value="Cali">Cali</option>
                  <option value="Barranquilla">Barranquilla</option>
                </select>
              </div>
            </div>

            <div className="furat-row">
              <label className="furat-label">Representa a</label>
              <div className="furat-segment">
                <button className={`furat-seg ${origen === 'Empleador' ? 'active navy' : ''}`}     onClick={() => setOrigen('Empleador')}>Empleador (designado)</button>
                <button className={`furat-seg ${origen === 'Trabajadores' ? 'active green' : ''}`} onClick={() => setOrigen('Trabajadores')}>Trabajadores (elegido)</button>
              </div>
              <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>
                Empleador: designado directamente · Trabajadores: elegido por votación secreta (Res. 652 art. 4).
              </div>
            </div>

            <div className="furat-grid-2">
              <div className="furat-row">
                <label className="furat-label">Tipo</label>
                <div className="furat-segment compact">
                  <button className={`furat-seg ${tipo === 'principal' ? 'active green' : ''}`} onClick={() => setTipo('principal')}>Principal</button>
                  <button className={`furat-seg ${tipo === 'suplente' ? 'active amber' : ''}`}  onClick={() => setTipo('suplente')}>Suplente</button>
                </div>
              </div>
              <div className="furat-row">
                <label className="furat-label">Posición en el comité</label>
                <select value={posicion} onChange={(e) => setPos(e.target.value)} disabled={tipo === 'suplente'}>
                  <option value="Presidenta">Presidenta / Presidente</option>
                  <option value="Secretario">Secretario / Secretaria</option>
                  <option value="Vocal">Vocal</option>
                </select>
              </div>
            </div>

            <div className="furat-grid-2">
              <div className="furat-row">
                <label className="furat-label">Vigencia desde</label>
                <window.DatePickerCO value={from} onChange={setFrom} />
              </div>
              <div className="furat-row">
                <label className="furat-label">Vigencia hasta</label>
                <window.DatePickerCO value={to} onChange={setTo} min={from} />
              </div>
            </div>
            <div className="muted" style={{ fontSize: 11, marginTop: -6 }}>
              <IconCalendar size={11} /> Período legal: 2 años (Res. 1356 art. 3). Reelección permitida.
            </div>

          </div>
        </div>

        <div className="modal-foot">
          <span className="muted" style={{ fontSize: 12, marginRight: 'auto' }}>
            <IconShield size={12} /> Se generará acta de posesión y se enviará al integrante.
          </span>
          <button className="btn" onClick={onClose}>Cancelar</button>
          <button className="btn primary"><IconCheck size={14} /> Guardar integrante</button>
        </div>
      </div>
    </div>
  );
};

// ─── Sesión del Comité modal ───────────────────────────────
// Programación de sesión ordinaria (trimestral) o extraordinaria (Res. 1356 art. 4)

const SesionConvivenciaModal = ({ onClose }) => {
  const [tipo, setTipo]       = _sst_useState('ordinaria');
  const [whenAt, setWhenAt]   = _sst_useState('14/05/2026 14:00');
  const [lugar, setLugar]     = _sst_useState('Cali · Sala Junta');
  const [asunto, setAsunto]   = _sst_useState('');
  const [caso, setCaso]       = _sst_useState('');
  const [convoca, setConvoca] = _sst_useState('Presidenta');
  const [asistentes, setAsistentes] = _sst_useState(
    CONVIVENCIA_COMITE.filter(m => m.kind === 'principal').map(m => m.initials)
  );

  const togglePersona = (initials) =>
    setAsistentes(a => a.includes(initials) ? a.filter(x => x !== initials) : [...a, initials]);

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    const onEsc = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onEsc);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onEsc); };
  }, []);

  const principales = CONVIVENCIA_COMITE.filter(m => m.kind === 'principal');
  const suplentes   = CONVIVENCIA_COMITE.filter(m => m.kind === 'suplente');
  const casosAbiertos = CONVIVENCIA_CASOS.filter(c => c.state !== 'cerrado' && c.state !== 'archivado');

  // Quórum mínimo: mayoría simple de principales (Res. 652 art. 5)
  const quorumMin = Math.ceil(principales.length / 2);
  const quorumActual = asistentes.filter(a => principales.find(p => p.initials === a)).length;
  const quorumOk = quorumActual >= quorumMin;

  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={{ maxWidth: 760 }}>
        <div className="modal-head">
          <div>
            <div className="modal-title">Programar sesión · Comité de Convivencia</div>
            <div className="modal-sub">
              Resolución 1356 de 2012 art. 4 · ordinarias trimestrales · extraordinarias cuando se reciba queja
            </div>
          </div>
          <button className="icon-btn" onClick={onClose} title="Cerrar">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
          </button>
        </div>

        <div className="modal-body">
          <div className="furat-col">

            <div className="furat-row">
              <label className="furat-label">Tipo de sesión</label>
              <div className="furat-segment">
                <button className={`furat-seg ${tipo === 'ordinaria' ? 'active navy' : ''}`}     onClick={() => setTipo('ordinaria')}>Ordinaria (trimestral)</button>
                <button className={`furat-seg ${tipo === 'extraordinaria' ? 'active rose' : ''}`} onClick={() => setTipo('extraordinaria')}>Extraordinaria</button>
              </div>
            </div>

            <div className="furat-row">
              <label className="furat-label">Fecha y hora</label>
              <window.DatePickerCO value={whenAt} onChange={setWhenAt} withTime />
            </div>

            <div className="furat-row">
              <label className="furat-label">Lugar / sala</label>
              <input type="text" value={lugar} onChange={(e) => setLugar(e.target.value)} placeholder="Ej: Cali · Sala de Junta" />
            </div>

            {tipo === 'extraordinaria' && (
              <div className="furat-row">
                <label className="furat-label">Caso vinculado</label>
                <select value={caso} onChange={(e) => setCaso(e.target.value)}>
                  <option value="">Selecciona un caso abierto…</option>
                  {casosAbiertos.map(c => (
                    <option key={c.id} value={c.id}>{c.id} · {KIND_CCL[c.kind].label} · área {c.area}</option>
                  ))}
                </select>
              </div>
            )}

            <div className="furat-row">
              <label className="furat-label">Agenda / asunto</label>
              <textarea
                rows={3}
                value={asunto}
                onChange={(e) => setAsunto(e.target.value)}
                placeholder={tipo === 'ordinaria'
                  ? 'Ej: Revisión de casos abiertos · seguimiento conciliaciones · informe trimestral'
                  : 'Ej: Análisis del caso CCL-2026-XXX y citación a sesión de conciliación'}
              />
            </div>

            <div className="furat-row">
              <label className="furat-label">Convoca</label>
              <select value={convoca} onChange={(e) => setConvoca(e.target.value)}>
                <option value="Presidenta">Presidenta del Comité</option>
                <option value="Secretario">Secretario del Comité</option>
              </select>
            </div>

            <div className="furat-row">
              <label className="furat-label">Asistentes esperados</label>
              <div className="muted" style={{ fontSize: 11.5, marginBottom: 8 }}>
                Marca quién es convocado. Los suplentes asisten en ausencia del principal.
              </div>

              <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', marginTop: 4 }}>Principales</div>
              <div className="sst-members">
                {principales.map(m => {
                  const on = asistentes.includes(m.initials);
                  return (
                    <label key={m.initials} className="sst-member" style={{ cursor: 'pointer', background: on ? 'var(--surface-2, #F5F6FA)' : undefined }}>
                      <input type="checkbox" checked={on} onChange={() => togglePersona(m.initials)} />
                      <div className="doc-avatar" style={{ width: 32, height: 32, fontSize: 11 }}>{m.initials}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 12.5 }}>{m.name}</div>
                        <div className="muted" style={{ fontSize: 11 }}>{m.position} · {m.source}</div>
                      </div>
                    </label>
                  );
                })}
              </div>

              <div className="muted" style={{ fontSize: 11, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', marginTop: 10 }}>Suplentes</div>
              <div className="sst-members">
                {suplentes.map(m => {
                  const on = asistentes.includes(m.initials);
                  return (
                    <label key={m.initials} className="sst-member" style={{ cursor: 'pointer', background: on ? 'var(--surface-2, #F5F6FA)' : undefined }}>
                      <input type="checkbox" checked={on} onChange={() => togglePersona(m.initials)} />
                      <div className="doc-avatar" style={{ width: 32, height: 32, fontSize: 11 }}>{m.initials}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 12.5 }}>{m.name}</div>
                        <div className="muted" style={{ fontSize: 11 }}>{m.position} · {m.source}</div>
                      </div>
                    </label>
                  );
                })}
              </div>
            </div>

            {/* Indicador de quórum */}
            <div className="doc-list-card" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderLeft: `3px solid ${quorumOk ? 'var(--green-600)' : 'var(--rose-600)'}` }}>
              <IconShield size={16} />
              <div style={{ fontSize: 12.5, lineHeight: 1.5 }}>
                <b>Quórum:</b> {quorumActual} de {principales.length} principales
                {quorumOk
                  ? <span style={{ color: 'var(--green-600)' }}> · cumple mínimo ({quorumMin})</span>
                  : <span style={{ color: 'var(--rose-600)' }}> · insuficiente · mínimo {quorumMin}</span>}
              </div>
            </div>

          </div>
        </div>

        <div className="modal-foot">
          <span className="muted" style={{ fontSize: 12, marginRight: 'auto' }}>
            <IconCalendar size={12} /> Se enviarán invitaciones de calendario y se reservará la sala.
          </span>
          <button className="btn" onClick={onClose}>Cancelar</button>
          <button className="btn">Guardar borrador</button>
          <button className="btn primary" disabled={!quorumOk}><IconCheck size={14} /> Programar sesión</button>
        </div>
      </div>
    </div>
  );
};

window.SST = SST;
