// Time-off module — Vacaciones y Ausencias
// Admin view (3 tabs) + Colaborador portal view
const { useState: _to_useState, useMemo: _to_useMemo } = React;

// ─── Master data ─────────────────────────────────────────

const TYPE_META = {
  vacaciones:  { label: 'Vacaciones',  tone: 'blue',  hex: 'var(--blue-600)',  bg: 'var(--blue-100)' },
  permiso:     { label: 'Permiso',     tone: 'amber', hex: '#B57609',          bg: '#FBF1D8' },
  licencia:    { label: 'Licencia',    tone: 'navy',  hex: '#E26B26',          bg: '#FCE7D8' },
  incapacidad: { label: 'Incapacidad', tone: 'rose',  hex: 'var(--rose-600)',  bg: 'var(--rose-100)' },
};

const TO_STATE_META = {
  pendiente_jefe: { label: 'Pendiente jefe', pill: 'amber-soft', dot: '#854D0E' },
  pendiente_rrhh: { label: 'Pendiente RRHH', pill: 'amber-soft', dot: 'var(--navy-800)' },
  aprobada:       { label: 'Aprobada',       pill: 'green',      dot: 'var(--green-600)' },
  rechazada:      { label: 'Rechazada',      pill: 'rose',       dot: 'var(--rose-600)' },
};

const REQUESTS = [
  {
    id: 'TO-2026-0142', initials: 'AM', name: 'Andrés Felipe Mejía',  empId: 'E0247',
    role: 'Operario de Clasificación',  type: 'vacaciones', from: '12/05/2026', to: '23/05/2026', days: 10,
    requestedOn: '04/05/2026', motive: 'Vacaciones planificadas · viaje familiar a Santa Marta.',
    leader: 'Luis Miguel Marín', state: 'pendiente_jefe', flowStep: 1,
    site: 'Cali',
  },
  {
    id: 'TO-2026-0141', initials: 'MF', name: 'María Fernanda López', empId: 'E0198',
    role: 'Op. Aprovechamiento',          type: 'permiso',    from: '08/05/2026', to: '08/05/2026', days: 1,
    requestedOn: '03/05/2026', motive: 'Cita médica con especialista — control trimestral.',
    leader: 'Luis Miguel Marín', state: 'pendiente_rrhh', flowStep: 2,
    site: 'Cali',
  },
  {
    id: 'TO-2026-0140', initials: 'PV', name: 'Paula Valencia Ríos',  empId: 'E0156',
    role: 'Téc. Mantenimiento',   type: 'licencia',   from: '01/06/2026', to: '15/06/2026', days: 11,
    requestedOn: '02/05/2026', motive: 'Licencia no remunerada para curso de certificación CCS.',
    leader: 'Carlos A. Gómez',   state: 'pendiente_jefe', flowStep: 1,
    site: 'Cali',
  },
  {
    id: 'TO-2026-0139', initials: 'CV', name: 'Carlos Andrés Vélez',  empId: 'E0205',
    role: 'Operario de Clasificación',  type: 'incapacidad', from: '02/05/2026', to: '04/05/2026', days: 3,
    requestedOn: '02/05/2026', motive: 'Incapacidad médica IPS Megacentro · quemadura mano derecha.',
    leader: 'Luis Miguel Marín', state: 'aprobada', flowStep: 3,
    site: 'Cali',
    decidedOn: '02/05/2026 11:42',
  },
  {
    id: 'TO-2026-0138', initials: 'JR', name: 'Juan David Ruiz',      empId: 'E0245',
    role: 'Aux. Calidad',         type: 'vacaciones', from: '15/06/2026', to: '26/06/2026', days: 10,
    requestedOn: '01/05/2026', motive: 'Vacaciones primer corte 2026.',
    leader: 'Sandra M. Ortiz',   state: 'aprobada', flowStep: 3,
    site: 'Barranquilla',
    decidedOn: '03/05/2026 09:15',
  },
  {
    id: 'TO-2026-0137', initials: 'JP', name: 'Jorge Iván Patiño',    empId: 'E0177',
    role: 'Conductor',            type: 'permiso',    from: '06/05/2026', to: '06/05/2026', days: 1,
    requestedOn: '30/04/2026', motive: 'Diligencia personal en notaría · trámite de escrituras.',
    leader: 'Carolina Restrepo', state: 'rechazada', flowStep: 0,
    site: 'Barranquilla',
    decidedOn: '02/05/2026 16:08',
    rejectReason: 'Coincide con ruta crítica programada · favor reagendar para 13/05 (día sin entregas).',
  },
  {
    id: 'TO-2026-0136', initials: 'LG', name: 'Laura Gómez Restrepo', empId: 'E0246',
    role: 'Operaria de Planta',   type: 'incapacidad', from: '06/05/2026', to: '07/05/2026', days: 2,
    requestedOn: '05/05/2026', motive: 'Incapacidad médica IPS Comfamiliar · gripa común.',
    leader: 'Luis Miguel Marín', state: 'pendiente_rrhh', flowStep: 2,
    site: 'Cali',
  },
  {
    id: 'TO-2026-0135', initials: 'LM', name: 'Luis Miguel Marín',    empId: 'E0067',
    role: 'Líder de Aprovechamiento',     type: 'vacaciones', from: '20/07/2026', to: '03/08/2026', days: 11,
    requestedOn: '01/05/2026', motive: 'Vacaciones segundo corte · viaje a Barranquilla.',
    leader: 'Carolina Restrepo', state: 'aprobada', flowStep: 3,
    site: 'Cali',
    decidedOn: '02/05/2026 14:00',
  },
];

const FLOW_STEPS = ['Solicitud', 'Jefe directo', 'RRHH', 'Aprobada'];

// ─── Calendar events (May 2026) ──────────────────────────

const CAL_EVENTS = [
  { id: 'TO-2026-0139', initials: 'CV', name: 'Carlos Andrés Vélez',  type: 'incapacidad', from: 2,  to: 4,  area: 'Operaciones' },
  { id: 'TO-2026-0136', initials: 'LG', name: 'Laura Gómez Restrepo', type: 'incapacidad', from: 6,  to: 7,  area: 'Operaciones' },
  { id: 'TO-2026-0137', initials: 'JP', name: 'Jorge Iván Patiño',    type: 'permiso',     from: 13, to: 13, area: 'Recolección' },
  { id: 'TO-2026-0142', initials: 'AM', name: 'Andrés Felipe Mejía',  type: 'vacaciones',  from: 12, to: 23, area: 'Operaciones' },
  { id: 'TO-2026-X1',   initials: 'PG', name: 'Patricia Gómez Lara',  type: 'vacaciones',  from: 18, to: 27, area: 'Calidad' },
  { id: 'TO-2026-0141', initials: 'MF', name: 'María Fernanda López', type: 'permiso',     from: 8,  to: 8,  area: 'Aprovechamiento' },
  { id: 'TO-2026-X2',   initials: 'NC', name: 'Nicolás Cárdenas',     type: 'vacaciones',  from: 22, to: 31, area: 'Recolección' },
  { id: 'TO-2026-X3',   initials: 'DT', name: 'Diego Andrés Toro',    type: 'licencia',    from: 25, to: 30, area: 'Aprovechamiento' },
];

const HOLIDAYS_MAY = [1, 18]; // Día del trabajo · Ascensión del Señor

// ─── Balances ────────────────────────────────────────────

const BALANCES = [
  { id: 'E0023', initials: 'CR', name: 'Carolina Restrepo S.', role: 'Jefe de RRHH',         hire: '02/02/2019', causados: 105, tomados: 90,  pendientes: 15, compensados: 0, alert: false },
  { id: 'E0067', initials: 'LM', name: 'Luis Miguel Marín',    role: 'Líder de Aprovechamiento',     hire: '11/04/2021', causados: 75,  tomados: 45,  pendientes: 22, compensados: 8, alert: true  },
  { id: 'E0094', initials: 'MT', name: 'María Trujillo Henao', role: 'Aux. RRHH',            hire: '17/08/2022', causados: 56,  tomados: 30,  pendientes: 18, compensados: 8, alert: true  },
  { id: 'E0128', initials: 'NC', name: 'Nicolás Cárdenas',     role: 'Conductor',            hire: '05/09/2024', causados: 33,  tomados: 23,  pendientes: 10, compensados: 0, alert: false },
  { id: 'E0142', initials: 'DT', name: 'Diego Andrés Toro',    role: 'Aux. Aprovechamiento',         hire: '20/03/2025', causados: 24,  tomados: 12,  pendientes: 12, compensados: 0, alert: false },
  { id: 'E0156', initials: 'PV', name: 'Paula Valencia Ríos',  role: 'Téc. Mantenimiento',   hire: '03/02/2025', causados: 25,  tomados: 8,   pendientes: 17, compensados: 0, alert: true  },
  { id: 'E0177', initials: 'JP', name: 'Jorge Iván Patiño',    role: 'Conductor',            hire: '11/06/2023', causados: 45,  tomados: 30,  pendientes: 15, compensados: 0, alert: false },
  { id: 'E0198', initials: 'MF', name: 'María Fernanda López', role: 'Op. Aprovechamiento',          hire: '08/01/2024', causados: 36,  tomados: 30,  pendientes: 6,  compensados: 0, alert: false },
  { id: 'E0205', initials: 'CV', name: 'Carlos Andrés Vélez',  role: 'Operario de Clasificación',  hire: '14/03/2024', causados: 36,  tomados: 14,  pendientes: 22, compensados: 0, alert: true  },
  { id: 'E0247', initials: 'AM', name: 'Andrés Felipe Mejía',  role: 'Operario de Clasificación',  hire: '12/05/2024', causados: 30,  tomados: 0,   pendientes: 30, compensados: 0, alert: true  },
];

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

const TimeOff = () => {
  const [persona, setPersona] = _to_useState('admin');  // admin | colaborador
  const [tab, setTab] = _to_useState('solicitudes');

  const counts = _to_useMemo(() => ({
    pendientes: REQUESTS.filter(r => r.state.startsWith('pendiente')).length,
    aprobadas:  REQUESTS.filter(r => r.state === 'aprobada').length,
    rechazadas: REQUESTS.filter(r => r.state === 'rechazada').length,
    enCurso:    CAL_EVENTS.filter(e => 5 >= e.from && 5 <= e.to).length, // ausentes hoy (5 mayo)
  }), []);

  return (
    <div className="main" data-screen-label="Vacaciones">
      <div className="page-head">
        <div>
          <h1 className="page-title">Vacaciones y Ausencias</h1>
          <div className="page-subtitle">
            <b>{counts.pendientes} solicitudes pendientes</b> · {counts.enCurso} colaboradores ausentes hoy · 3 con saldo crítico (&gt; 15 días)
          </div>
        </div>
        <div className="to-view-toggle">
          <button className={`${persona === 'admin' ? 'active' : ''}`} onClick={() => setPersona('admin')}>
            <IconShield size={13} /> Vista RRHH
          </button>
          <button className={`${persona === 'colaborador' ? 'active' : ''}`} onClick={() => setPersona('colaborador')}>
            <IconUsers size={13} /> Vista colaborador
          </button>
        </div>
      </div>

      {persona === 'admin' ? (
        <>
          <div className="doc-tabs">
            <button className={`doc-tab ${tab === 'solicitudes' ? 'active' : ''}`} onClick={() => setTab('solicitudes')}>
              <IconDoc size={14} /> Solicitudes
              <span className="epp-tab-pill rose">{counts.pendientes}</span>
            </button>
            <button className={`doc-tab ${tab === 'calendario' ? 'active' : ''}`} onClick={() => setTab('calendario')}>
              <IconCalendar size={14} /> Calendario
            </button>
            <button className={`doc-tab ${tab === 'saldos' ? 'active' : ''}`} onClick={() => setTab('saldos')}>
              <IconBarChart size={14} /> Saldos
            </button>
          </div>

          {tab === 'solicitudes' && <RequestsTab />}
          {tab === 'calendario'  && <CalendarTab />}
          {tab === 'saldos'      && <BalancesTab />}
        </>
      ) : (
        <ColaboradorPortal />
      )}
    </div>
  );
};

// ─── Tab: Solicitudes ────────────────────────────────────

const RequestsTab = () => {
  const [filter, setFilter] = _to_useState('todas');
  const [filterType, setFilterType] = _to_useState('todos');

  const counts = {
    todas:      REQUESTS.length,
    pendientes: REQUESTS.filter(r => r.state.startsWith('pendiente')).length,
    aprobadas:  REQUESTS.filter(r => r.state === 'aprobada').length,
    rechazadas: REQUESTS.filter(r => r.state === 'rechazada').length,
  };

  const list = REQUESTS.filter(r => {
    if (filter === 'pendientes' && !r.state.startsWith('pendiente')) return false;
    if (filter === 'aprobadas'  && r.state !== 'aprobada') return false;
    if (filter === 'rechazadas' && r.state !== 'rechazada') return false;
    if (filterType !== 'todos' && r.type !== filterType) return false;
    return true;
  });

  return (
    <>
      <div className="sst-quickfilter">
        {[
          { id: 'todas',      label: 'Todas' },
          { id: 'pendientes', label: 'Pendientes', tone: 'amber' },
          { id: 'aprobadas',  label: 'Aprobadas',  tone: 'green' },
          { id: 'rechazadas', label: 'Rechazadas', 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 }} />
        <select value={filterType} onChange={(e) => setFilterType(e.target.value)}>
          <option value="todos">Todos los tipos</option>
          {Object.entries(TYPE_META).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
        </select>
        <button className="btn"><IconExternal size={14} /> Exportar</button>
      </div>

      <div className="to-req-list">
        {list.map(r => <RequestCard key={r.id} req={r} />)}
      </div>
    </>
  );
};

const RequestCard = ({ req: r }) => {
  const t = TYPE_META[r.type];
  const s = TO_STATE_META[r.state];
  const TIco = ({ name }) => {
    const map = { vacaciones: IconStar, permiso: IconClock, licencia: IconRocket, incapacidad: IconAlert };
    const I = map[r.type] || IconCalendar;
    return <I size={14} />;
  };
  return (
    <div className={`to-req-card ${r.state === 'aprobada' ? 'approved' : r.state === 'rechazada' ? 'rejected' : ''}`}>
      <div className="to-req-head">
        <div className="doc-cell-emp" style={{ flex: 1 }}>
          <div className="doc-avatar">{r.initials}</div>
          <div>
            <div style={{ fontWeight: 700, fontSize: 14 }}>{r.name}</div>
            <div className="muted" style={{ fontSize: 12 }}>{r.role} · {r.site}</div>
            <div className="muted mono" style={{ fontSize: 11, marginTop: 2 }}>{r.id} · {r.empId}</div>
          </div>
        </div>
        <span className="to-type-badge" style={{ background: t.bg, color: t.hex }}>
          <TIco /> {t.label}
        </span>
        <span className={`pill ${s.pill}`}>
          <span className="status-dot" style={{ background: s.dot }} /> {s.label}
        </span>
      </div>

      <div className="to-req-body">
        <div className="to-req-fields">
          <div>
            <div className="muted-xs">Período</div>
            <div className="to-req-val mono">{r.from} → {r.to}</div>
          </div>
          <div>
            <div className="muted-xs">Días</div>
            <div className="to-req-days">{r.days}</div>
          </div>
          <div>
            <div className="muted-xs">Solicitada</div>
            <div className="to-req-val mono">{r.requestedOn}</div>
          </div>
          <div>
            <div className="muted-xs">Jefe directo</div>
            <div className="to-req-val">{r.leader}</div>
          </div>
        </div>

        <div className="to-req-motive">
          <div className="muted-xs">Motivo</div>
          <div style={{ fontSize: 13, marginTop: 4 }}>{r.motive}</div>
        </div>

        {/* Workflow stepper */}
        <div className="to-flow">
          {FLOW_STEPS.map((step, i) => {
            const reached = r.flowStep >= i;
            const current = r.flowStep === i && r.state.startsWith('pendiente');
            const cls = r.state === 'rechazada' && i > 0 ? 'rejected'
                      : current ? 'current'
                      : reached ? 'done'
                      : 'pending';
            return (
              <React.Fragment key={i}>
                <div className={`to-flow-step ${cls}`}>
                  <span className="to-flow-num">
                    {cls === 'done' ? <IconCheck size={11} /> : cls === 'rejected' ? '×' : i + 1}
                  </span>
                  <span className="to-flow-label">{step}</span>
                </div>
                {i < FLOW_STEPS.length - 1 && <div className={`to-flow-line ${cls === 'done' ? 'done' : ''}`} />}
              </React.Fragment>
            );
          })}
        </div>

        {r.rejectReason && (
          <div className="to-req-reject">
            <IconAlert size={13} /> <b>Motivo del rechazo:</b> {r.rejectReason}
          </div>
        )}
        {r.decidedOn && r.state === 'aprobada' && (
          <div className="to-req-meta">
            <IconCheck size={13} /> Aprobada el <span className="mono">{r.decidedOn}</span>
          </div>
        )}
      </div>

      {r.state.startsWith('pendiente') && (
        <div className="to-req-foot">
          <button className="btn"><IconExternal size={13} /> Ver detalle</button>
          <div style={{ flex: 1 }} />
          <button className="btn ats-danger">Rechazar</button>
          <button className="btn primary"><IconCheck size={14} /> Aprobar</button>
        </div>
      )}
    </div>
  );
};

// ─── Tab: Calendario ─────────────────────────────────────

const CalendarTab = () => {
  const [view, setView] = _to_useState('mes'); // mes | semana | lista
  const [filterArea, setFilterArea] = _to_useState('todas');
  const [hover, setHover] = _to_useState(null);
  const areas = Array.from(new Set(CAL_EVENTS.map(e => e.area)));

  // May 2026: 31 days, May 1 is Friday
  // Layout Mon-Sun. Mon=0, Fri=4. So first row offset = 4.
  const daysInMonth = 31;
  const firstWeekday = 4; // 0=Mon for our grid
  const cells = [];
  for (let i = 0; i < firstWeekday; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  const eventsForDay = (d) => CAL_EVENTS.filter(e =>
    (filterArea === 'todas' || e.area === filterArea) &&
    d >= e.from && d <= e.to
  );

  return (
    <>
      <div className="sst-quickfilter">
        <div className="to-cal-view-toggle">
          {['mes', 'semana', 'lista'].map(v => (
            <button key={v} className={view === v ? 'active' : ''} onClick={() => setView(v)}>
              {v === 'mes' ? 'Mes' : v === 'semana' ? 'Semana' : 'Lista'}
            </button>
          ))}
        </div>
        <select value={filterArea} onChange={(e) => setFilterArea(e.target.value)}>
          <option value="todas">Todas las áreas</option>
          {areas.map(a => <option key={a}>{a}</option>)}
        </select>
        <select>
          <option>Todas las sedes</option>
          <option>Cali</option>
          <option>Barranquilla</option>
        </select>
        <select>
          <option>Todos los colaboradores</option>
          {CAL_EVENTS.map(e => <option key={e.id}>{e.name}</option>)}
        </select>
        <div style={{ flex: 1 }} />
        <div className="to-cal-legend">
          {Object.entries(TYPE_META).map(([k, t]) => (
            <span key={k} className="to-cal-legend-item">
              <span className="to-cal-legend-dot" style={{ background: t.hex }} />
              {t.label}
            </span>
          ))}
        </div>
      </div>

      <div className="to-cal-card">
        <div className="to-cal-head">
          <div>
            <div className="muted-xs">Mes en curso</div>
            <h3 className="to-cal-title">Mayo 2026</h3>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className="btn" style={{ padding: '5px 9px' }}><IconChevronLeft size={13} /></button>
            <button className="btn">Hoy</button>
            <button className="btn" style={{ padding: '5px 9px' }}><IconChevronRight size={13} /></button>
          </div>
        </div>

        {view === 'mes' && (
          <>
            <div className="to-cal-weekdays">
              {['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'].map(d => <div key={d}>{d}</div>)}
            </div>
            <div className="to-cal-grid">
              {cells.map((d, i) => {
                if (d === null) return <div key={i} className="to-cal-day empty" />;
                const events = eventsForDay(d);
                const isWeekend = (i % 7) >= 5;
                const isHoliday = HOLIDAYS_MAY.includes(d);
                const isToday = d === 5;
                return (
                  <div key={i} className={`to-cal-day ${isWeekend ? 'weekend' : ''} ${isHoliday ? 'holiday' : ''} ${isToday ? 'today' : ''}`}>
                    <div className="to-cal-day-head">
                      <span className="to-cal-day-num">{d}</span>
                      {events.length > 0 && <span className="to-cal-count">{events.length}</span>}
                      {isHoliday && <span className="to-cal-holiday-tag">festivo</span>}
                    </div>
                    <div className="to-cal-events">
                      {events.slice(0, 3).map(e => {
                        const t = TYPE_META[e.type];
                        return (
                          <div
                            key={e.id + d}
                            className="to-cal-event"
                            style={{ background: t.bg, color: t.hex }}
                            onMouseEnter={() => setHover({ ...e, day: d })}
                            onMouseLeave={() => setHover(null)}
                          >
                            <span className="to-cal-event-avatar">{e.initials}</span>
                            <span className="to-cal-event-name">{e.name.split(' ')[0]}</span>
                          </div>
                        );
                      })}
                      {events.length > 3 && <div className="to-cal-event-more">+{events.length - 3}</div>}
                    </div>
                  </div>
                );
              })}
            </div>
          </>
        )}

        {view === 'semana' && (
          <div className="to-cal-week">
            <div className="muted" style={{ padding: 28, textAlign: 'center', fontSize: 13 }}>
              Vista semanal · selecciona una semana en el calendario superior
            </div>
            <div className="to-week-strip">
              {[4, 5, 6, 7, 8, 9, 10].map((d, i) => {
                const events = eventsForDay(d);
                return (
                  <div key={d} className={`to-week-day ${d === 5 ? 'today' : ''}`}>
                    <div className="to-week-day-head">
                      <span className="muted-xs">{['Lun','Mar','Mié','Jue','Vie','Sáb','Dom'][i]}</span>
                      <span className="to-week-day-num">{d}</span>
                    </div>
                    <div className="to-cal-events" style={{ padding: '8px 6px' }}>
                      {events.map(e => {
                        const t = TYPE_META[e.type];
                        return (
                          <div key={e.id + d} className="to-cal-event" style={{ background: t.bg, color: t.hex }}>
                            <span className="to-cal-event-avatar">{e.initials}</span>
                            <span className="to-cal-event-name">{e.name.split(' ')[0]} {e.name.split(' ')[1]}</span>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {view === 'lista' && (
          <div className="to-cal-list">
            {CAL_EVENTS.filter(e => filterArea === 'todas' || e.area === filterArea).map(e => {
              const t = TYPE_META[e.type];
              return (
                <div key={e.id} className="to-list-row">
                  <span className="to-cal-event-avatar lg">{e.initials}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13.5 }}>{e.name}</div>
                    <div className="muted" style={{ fontSize: 12 }}>{e.area} · {e.id}</div>
                  </div>
                  <span className="to-type-badge" style={{ background: t.bg, color: t.hex }}>{t.label}</span>
                  <div className="to-list-dates mono">
                    {e.from === e.to ? `${e.from}/05` : `${e.from} → ${e.to}/05`}
                    <span className="muted" style={{ marginLeft: 8, fontFamily: 'Inter' }}>· {e.to - e.from + 1} día{e.to - e.from === 0 ? '' : 's'}</span>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      <div className="to-cal-tooltip">
        {hover ? (
          <>
            <span className="to-cal-event-avatar lg" style={{ background: TYPE_META[hover.type].bg, color: TYPE_META[hover.type].hex }}>{hover.initials}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 13.5 }}>{hover.name}</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{hover.area} · {hover.id}</div>
            </div>
            <div style={{ display: 'flex', gap: 18 }}>
              <div><div className="muted-xs">Tipo</div><div style={{ fontSize: 12.5, fontWeight: 600, color: TYPE_META[hover.type].hex }}>{TYPE_META[hover.type].label}</div></div>
              <div><div className="muted-xs">Período</div><div className="mono" style={{ fontSize: 12 }}>{hover.from}/05 → {hover.to}/05</div></div>
              <div><div className="muted-xs">Días</div><div style={{ fontSize: 14, fontWeight: 800 }}>{hover.to - hover.from + 1}</div></div>
            </div>
          </>
        ) : (
          <span className="muted" style={{ fontSize: 12.5 }}>
            <IconUsers size={12} /> Pasa el cursor sobre un evento para ver el detalle
          </span>
        )}
      </div>
    </>
  );
};

// ─── Tab: Saldos ─────────────────────────────────────────

const BalancesTab = () => {
  const [filter, setFilter] = _to_useState('todos');
  const list = filter === 'criticos' ? BALANCES.filter(b => b.alert) : BALANCES;
  const criticos = BALANCES.filter(b => b.alert).length;

  return (
    <>
      <div className="sst-quickfilter">
        <button className={`sst-chip ${filter === 'todos' ? 'active' : ''}`} onClick={() => setFilter('todos')}>
          Todos <span className="sst-chip-count">{BALANCES.length}</span>
        </button>
        <button className={`sst-chip rose ${filter === 'criticos' ? 'active' : ''}`} onClick={() => setFilter('criticos')}>
          &gt; 15 días pendientes <span className="sst-chip-count">{criticos}</span>
        </button>
        <div style={{ flex: 1 }} />
        <button className="btn"><IconExternal size={14} /> Exportar nómina</button>
      </div>

      <div className="doc-list-card">
        <table className="doc-table">
          <thead>
            <tr>
              <th>Colaborador</th>
              <th>Cargo</th>
              <th style={{ textAlign: 'center' }}>Causados</th>
              <th style={{ textAlign: 'center' }}>Tomados</th>
              <th>Pendientes</th>
              <th style={{ textAlign: 'center' }}>Compensados</th>
              <th>Ingreso</th>
            </tr>
          </thead>
          <tbody>
            {list.map(b => {
              const pct = b.causados ? Math.round((b.tomados / b.causados) * 100) : 0;
              const pendTone = b.pendientes > 15 ? 'rose' : b.pendientes > 10 ? 'amber' : 'green';
              return (
                <tr key={b.id}>
                  <td>
                    <div className="doc-cell-emp">
                      <div className="doc-avatar">{b.initials}</div>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{b.name}</div>
                        <div className="muted mono" style={{ fontSize: 11 }}>{b.id}</div>
                      </div>
                    </div>
                  </td>
                  <td className="muted" style={{ fontSize: 12.5 }}>{b.role}</td>
                  <td style={{ textAlign: 'center' }}>
                    <div className="to-bal-num">{b.causados}</div>
                  </td>
                  <td style={{ textAlign: 'center' }}>
                    <div className="to-bal-num muted">{b.tomados}</div>
                    <div className="tr-prog-track" style={{ marginTop: 4, width: 60, marginLeft: 'auto', marginRight: 'auto' }}>
                      <div className="tr-prog-fill green" style={{ width: `${pct}%` }} />
                    </div>
                  </td>
                  <td>
                    <div className="to-pendientes">
                      <span className={`to-pend-num ${pendTone}`}>{b.pendientes}</span>
                      {b.alert && (
                        <span className="to-pend-alert">
                          <IconAlert size={11} /> Acumulado alto · revisar plan de descanso
                        </span>
                      )}
                    </div>
                  </td>
                  <td style={{ textAlign: 'center', fontFamily: 'JetBrains Mono', fontSize: 12.5 }}>
                    {b.compensados > 0 ? b.compensados : <span className="muted">—</span>}
                  </td>
                  <td className="mono muted" style={{ fontSize: 11.5 }}>{b.hire}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

// ─── Colaborador portal ──────────────────────────────────

const TO_ME = {
  initials: 'CV', name: 'Carlos Andrés Vélez', role: 'Operario de Clasificación', site: 'Cali',
  hire: '14/03/2024', leader: 'Luis Miguel Marín',
  causados: 36, tomados: 14, compensados: 0,
};
const TO_ME_DAYS = TO_ME.causados - TO_ME.tomados - TO_ME.compensados;

const TO_ME_HISTORY = [
  { id: 'TO-2026-0139', type: 'incapacidad', from: '02/05/2026', to: '04/05/2026', days: 3,  state: 'aprobada',   when: '02/05/2026' },
  { id: 'TO-2025-0421', type: 'vacaciones',  from: '14/12/2025', to: '28/12/2025', days: 11, state: 'aprobada',   when: '02/11/2025' },
  { id: 'TO-2025-0289', type: 'permiso',     from: '14/06/2025', to: '14/06/2025', days: 1,  state: 'aprobada',   when: '10/06/2025' },
  { id: 'TO-2025-0156', type: 'vacaciones',  from: '01/04/2025', to: '03/04/2025', days: 3,  state: 'rechazada',  when: '20/03/2025' },
];

const ColaboradorPortal = () => {
  const [type, setType]   = _to_useState('vacaciones');
  const [from, setFrom]   = _to_useState('15/06/2026');
  const [to, setTo]       = _to_useState('26/06/2026');
  const [motive, setMotive] = _to_useState('');
  const [hasFile, setHasFile] = _to_useState(false);

  const requiresFile = type === 'incapacidad' || type === 'licencia';
  // simulate biz days (mock: parse and assume range matches)
  const days = type === 'permiso' ? 1 : 9;

  return (
    <div className="to-portal">
      {/* Header */}
      <div className="to-portal-head">
        <div className="ats-card-avatar lg">{TO_ME.initials}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 18, fontWeight: 700 }}>Hola, Carlos</div>
          <div className="muted" style={{ fontSize: 13 }}>{TO_ME.role} · {TO_ME.site} · ingresaste el {TO_ME.hire}</div>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>Tu jefe directo es <b style={{ color: 'var(--text)' }}>{TO_ME.leader}</b></div>
        </div>
        <div className="to-portal-balance">
          <div className="muted-xs">Días disponibles</div>
          <div className="to-portal-balance-num">{TO_ME_DAYS}</div>
          <div className="muted" style={{ fontSize: 11.5 }}>de {TO_ME.causados} causados</div>
          <div className="to-portal-balance-mini">
            <span><b>{TO_ME.tomados}</b> tomados</span>
            <span><b>{TO_ME.compensados}</b> compensados</span>
          </div>
        </div>
      </div>

      <div className="to-portal-grid">
        {/* Form */}
        <div className="to-portal-card">
          <div className="to-portal-card-head">
            <div>
              <div className="to-portal-card-title">Solicitar ausencia</div>
              <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>Tu solicitud va primero a tu jefe directo, luego a RRHH.</div>
            </div>
          </div>

          <div className="to-portal-form">
            <div>
              <label className="muted-xs">Tipo de ausencia</label>
              <div className="to-type-grid">
                {Object.entries(TYPE_META).map(([k, t]) => (
                  <button
                    key={k}
                    className={`to-type-card ${type === k ? `active ${t.tone}` : ''}`}
                    style={type === k ? { background: t.bg, color: t.hex, borderColor: t.hex } : {}}
                    onClick={() => setType(k)}
                  >
                    <span className="to-type-card-name">{t.label}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="to-portal-row-2">
              <div>
                <label className="muted-xs">Desde</label>
                <window.DatePickerCO value={from} onChange={setFrom} />
              </div>
              <div>
                <label className="muted-xs">Hasta</label>
                <window.DatePickerCO value={to} onChange={setTo} min={from} />
              </div>
            </div>

            <div className="to-days-summary">
              <div>
                <div className="muted-xs">Días hábiles</div>
                <div className="to-days-num">{days}</div>
                <div className="muted" style={{ fontSize: 11 }}>excluye fines de semana y festivos</div>
              </div>
              <div className="to-days-detail">
                <div className="to-days-row">
                  <span className="muted">Días calendario</span>
                  <span className="mono">{type === 'permiso' ? 1 : 12}</span>
                </div>
                <div className="to-days-row">
                  <span className="muted">Sábados y domingos</span>
                  <span className="mono">−{type === 'permiso' ? 0 : 2}</span>
                </div>
                <div className="to-days-row">
                  <span className="muted">Festivos en el rango</span>
                  <span className="mono">−{type === 'permiso' ? 0 : 1}</span>
                </div>
                <div className="to-days-row total">
                  <span>Total a descontar</span>
                  <span className="mono">{days} día{days === 1 ? '' : 's'}</span>
                </div>
              </div>
            </div>

            <div>
              <label className="muted-xs">Motivo</label>
              <textarea
                rows={3}
                value={motive}
                onChange={(e) => setMotive(e.target.value)}
                placeholder={type === 'permiso' ? 'Diligencia personal, cita médica, trámite…' : 'Cuéntanos brevemente el motivo de tu solicitud'}
              />
            </div>

            {requiresFile && (
              <div>
                <label className="muted-xs">Soporte adjunto · obligatorio para {TYPE_META[type].label.toLowerCase()}</label>
                <button className={`to-upload ${hasFile ? 'on' : ''}`} onClick={() => setHasFile(h => !h)}>
                  {hasFile ? (
                    <>
                      <IconCheck size={14} />
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 12.5 }}>incapacidad-IPS-Megacentro.pdf</div>
                        <div className="muted mono" style={{ fontSize: 11 }}>238 KB · subido hace un momento</div>
                      </div>
                      <span className="link-btn" style={{ marginLeft: 'auto' }}>Reemplazar</span>
                    </>
                  ) : (
                    <>
                      <IconPlus size={14} />
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 12.5 }}>Adjuntar soporte (PDF · JPG · PNG)</div>
                        <div className="muted" style={{ fontSize: 11 }}>Arrastra el archivo aquí o haz clic para seleccionar</div>
                      </div>
                    </>
                  )}
                </button>
              </div>
            )}

            <div className="to-portal-foot">
              <button className="btn">Cancelar</button>
              <button
                className="btn primary"
                disabled={motive.trim().length < 6 || (requiresFile && !hasFile)}
              >
                <IconCheck size={14} /> Enviar solicitud
              </button>
            </div>
          </div>
        </div>

        {/* Mini calendar */}
        <div className="to-portal-card">
          <div className="to-portal-card-head">
            <div>
              <div className="to-portal-card-title">Mayo 2026</div>
              <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>Tus ausencias en el mes en curso</div>
            </div>
          </div>
          <MiniCalendar />

          <div className="to-mini-legend">
            <span><span className="to-mini-dot" style={{ background: 'var(--rose-600)' }} /> Incapacidad (3 días)</span>
            <span><span className="to-mini-dot" style={{ background: 'var(--blue-600)' }} /> Vacaciones (próximas)</span>
          </div>
        </div>
      </div>

      {/* History */}
      <div className="to-portal-card">
        <div className="to-portal-card-head">
          <div>
            <div className="to-portal-card-title">Historial de solicitudes</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{TO_ME_HISTORY.length} solicitudes en los últimos 12 meses</div>
          </div>
          <button className="link-btn" style={{ marginLeft: 0 }}>Ver todo</button>
        </div>

        <div className="to-history">
          {TO_ME_HISTORY.map(h => {
            const t = TYPE_META[h.type];
            const stCls = h.state === 'aprobada' ? 'green' : h.state === 'rechazada' ? 'rose' : 'amber-soft';
            return (
              <div key={h.id} className="to-history-row">
                <span className="to-type-badge" style={{ background: t.bg, color: t.hex }}>{t.label}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13 }}>{h.from} → {h.to}</div>
                  <div className="muted mono" style={{ fontSize: 11, marginTop: 2 }}>{h.id} · {h.days} día{h.days === 1 ? '' : 's'} · solicitada {h.when}</div>
                </div>
                <span className={`pill ${stCls}`}>{h.state === 'aprobada' ? 'Aprobada' : h.state === 'rechazada' ? 'Rechazada' : 'Pendiente'}</span>
                <button className="icon-action" title="Ver detalle"><IconExternal size={14} /></button>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// ─── Mini calendar (employee portal) ─────────────────────

const MiniCalendar = () => {
  const daysInMonth = 31;
  const firstWeekday = 4;
  const cells = [];
  for (let i = 0; i < firstWeekday; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);

  // Carlos Vélez ausencias: 2-4 mayo (incapacidad), and mock vacaciones próximas 15-26 jun (not in this month)
  const myEvents = [
    { from: 2, to: 4, type: 'incapacidad' },
  ];
  const dayState = (d) => myEvents.find(e => d >= e.from && d <= e.to);

  return (
    <div className="to-mini-cal">
      <div className="to-mini-weekdays">
        {['L','M','M','J','V','S','D'].map((d, i) => <div key={i}>{d}</div>)}
      </div>
      <div className="to-mini-grid">
        {cells.map((d, i) => {
          if (d === null) return <div key={i} className="to-mini-day empty" />;
          const ev = dayState(d);
          const isWeekend = (i % 7) >= 5;
          const isHoliday = HOLIDAYS_MAY.includes(d);
          const isToday = d === 5;
          return (
            <div
              key={i}
              className={`to-mini-day ${isWeekend ? 'weekend' : ''} ${isHoliday ? 'holiday' : ''} ${isToday ? 'today' : ''} ${ev ? 'event-' + ev.type : ''}`}
            >
              {d}
            </div>
          );
        })}
      </div>
    </div>
  );
};

window.TimeOff = TimeOff;
