/* admin-progress.jsx — Gestión de progreso de estudiantes ASSYST */
const { useState: useStateAP } = React;

/* ─────────────────────────────────────────────────────────────────────────────
   ManageProgressModal
   Modal principal con las 3 opciones de reinicio
───────────────────────────────────────────────────────────────────────────── */
function ManageProgressModal({ student, onClose, onAskConfirm, tick }) {
  const [expandedMods, setExpandedMods] = useStateAP({});

  var modules = getModules();
  var prog     = getProgress(student.id);
  var evalRes  = getEvalResults(student.id);
  var attempts = getEvalAttempts(student.id);

  var det = modules.map(function (m, i) {
    var lecciones = m.lecciones.map(function (l) {
      return Object.assign({}, l, { completada: !!prog[l.id], tipo: 'leccion' });
    });
    var evaluaciones = (m.evaluaciones || []).map(function (e) {
      return Object.assign({}, e, {
        completada: !!prog[e.id],
        resultado:  evalRes[e.id]  || null,
        intentos:   attempts[e.id] || 0,
        tipo: 'evaluacion'
      });
    });
    var doneLessons = lecciones.filter(function (l) { return l.completada; }).length;
    return Object.assign({}, m, {
      lecciones:    lecciones,
      evaluaciones: evaluaciones,
      done:         doneLessons,
      pct: m.lecciones.length > 0 ? Math.round((doneLessons / m.lecciones.length) * 100) : 0
    });
  });

  function toggleMod(modId) {
    setExpandedMods(function (prev) {
      var next = Object.assign({}, prev);
      next[modId] = !next[modId];
      return next;
    });
  }

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,61,94,.75)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 660, maxHeight: '88vh', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 64px rgba(0,0,0,.28)' }}>

        {/* ── Header ── */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '20px 28px', borderBottom: '1px solid #f1f5f9', flexShrink: 0 }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 17, fontWeight: 800, color: '#1c79b4' }}>Gestionar progreso</h3>
            <p style={{ margin: '3px 0 0', fontSize: 12, color: '#9ca3af' }}>{student.nombre} · {student.empresa}</p>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 24, cursor: 'pointer', color: '#9ca3af', lineHeight: 1, padding: '0 6px' }}>×</button>
        </div>

        {/* ── Scrollable body ── */}
        <div style={{ overflowY: 'auto', padding: '22px 28px 28px', flex: 1 }}>

          {/* ═══ OPCIÓN A: Reiniciar curso completo ═══ */}
          <div style={{ background: '#fff5f5', border: '1.5px solid #fecaca', borderRadius: 12, padding: '16px 20px', marginBottom: 26 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5 }}>
                  <div style={{ width: 22, height: 22, background: '#dc2626', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="1 4 1 10 7 10"></polyline>
                      <path d="M3.51 15a9 9 0 1 0 .49-3.85"></path>
                    </svg>
                  </div>
                  <span style={{ fontSize: 13, fontWeight: 800, color: '#b91c1c' }}>Reiniciar curso completo</span>
                </div>
                <div style={{ fontSize: 11, color: '#6b7280', lineHeight: 1.55, paddingLeft: 30 }}>
                  Elimina <strong>absolutamente todo</strong>: lecciones, evaluaciones e intentos de todos los módulos.
                </div>
              </div>
              <button
                onClick={function () { onAskConfirm({ type: 'full' }); }}
                style={{ background: '#dc2626', color: 'white', border: 'none', borderRadius: 8, padding: '9px 18px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap', flexShrink: 0 }}
                onMouseOver={function (e) { e.currentTarget.style.background = '#b91c1c'; }}
                onMouseOut={function (e) { e.currentTarget.style.background = '#dc2626'; }}
              >Reiniciar todo</button>
            </div>
          </div>

          {/* ═══ OPCIONES B + C: Por módulo ═══ */}
          <div style={{ fontSize: 10, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 12 }}>Por módulo</div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {det.map(function (mod, i) {
              var isExp       = !!expandedMods[mod.id];
              var totalItems  = mod.lecciones.length + mod.evaluaciones.length;
              var hasEvals    = mod.evaluaciones.length > 0;
              var doneEvals   = mod.evaluaciones.filter(function (e) { return e.completada; }).length;

              return (
                <div key={mod.id} style={{ border: '1.5px solid #e5e7eb', borderRadius: 12, overflow: 'hidden' }}>

                  {/* ── Fila del módulo (Opción B) ── */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '13px 16px', background: isExp ? '#f8fafc' : 'white' }}>
                    <div style={{ width: 28, height: 28, background: '#1c79b4', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#c4b400', fontSize: 11, fontWeight: 800, flexShrink: 0 }}>{i + 1}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: '#1c79b4', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mod.titulo}</div>
                      <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 2 }}>
                        {mod.done}/{mod.lecciones.length} lecciones completadas
                        {hasEvals ? ' · ' + doneEvals + '/' + mod.evaluaciones.length + ' eval.' : ''}
                      </div>
                    </div>
                    {/* Botón Opción B */}
                    <button
                      onClick={function () { onAskConfirm({ type: 'module', mod: mod }); }}
                      style={{ background: '#fee2e2', color: '#dc2626', border: 'none', borderRadius: 7, padding: '6px 12px', fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap', flexShrink: 0 }}
                      onMouseOver={function (e) { e.currentTarget.style.background = '#fecaca'; }}
                      onMouseOut={function (e) { e.currentTarget.style.background = '#fee2e2'; }}
                    >Reiniciar módulo</button>
                    {/* Toggle expandir */}
                    <button
                      onClick={function () { toggleMod(mod.id); }}
                      title={isExp ? 'Colapsar' : 'Ver items individuales'}
                      style={{ background: isExp ? '#f1f5f9' : 'transparent', border: '1px solid ' + (isExp ? '#e2e8f0' : 'transparent'), borderRadius: 6, padding: '5px 10px', cursor: 'pointer', color: '#64748b', fontSize: 10, fontFamily: 'inherit', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 4, fontWeight: 700 }}
                      onMouseOver={function (e) { e.currentTarget.style.background = '#f1f5f9'; }}
                      onMouseOut={function (e) { e.currentTarget.style.background = isExp ? '#f1f5f9' : 'transparent'; }}
                    >
                      {isExp ? '▲' : '▼'} <span style={{ fontSize: 11 }}>{totalItems}</span>
                    </button>
                  </div>

                  {/* ── Items individuales expandidos (Opción C) ── */}
                  {isExp && (
                    <div style={{ borderTop: '1px solid #f1f5f9' }}>

                      {/* Lecciones */}
                      {mod.lecciones.map(function (les, li) {
                        var isLastItem = li === mod.lecciones.length - 1 && mod.evaluaciones.length === 0;
                        return (
                          <div key={les.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 16px 9px 54px', borderBottom: isLastItem ? 'none' : '1px solid #f8fafc', background: 'white' }}>
                            <div style={{ width: 18, height: 18, borderRadius: '50%', background: les.completada ? '#dcfce7' : '#f1f5f9', border: les.completada ? 'none' : '1.5px solid #e2e8f0', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                              {les.completada && <span style={{ color: '#15803d', fontSize: 8, fontWeight: 900 }}>✓</span>}
                            </div>
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ fontSize: 12, color: '#374151', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{les.titulo}</div>
                              <div style={{ fontSize: 10, marginTop: 1, fontWeight: 600, color: les.completada ? '#15803d' : '#9ca3af' }}>
                                Lección · {les.completada ? 'Completada ✓' : 'Pendiente'}
                              </div>
                            </div>
                            {les.completada && (
                              <button
                                onClick={function () { onAskConfirm({ type: 'lesson', item: les }); }}
                                style={{ background: 'none', color: '#dc2626', border: '1px solid #fecaca', borderRadius: 6, padding: '4px 9px', fontSize: 10, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap', flexShrink: 0 }}
                                onMouseOver={function (e) { e.currentTarget.style.background = '#fff5f5'; }}
                                onMouseOut={function (e) { e.currentTarget.style.background = 'none'; }}
                              >Reiniciar</button>
                            )}
                          </div>
                        );
                      })}

                      {/* Evaluaciones */}
                      {mod.evaluaciones.map(function (ev, ei) {
                        var isLastEval = ei === mod.evaluaciones.length - 1;
                        return (
                          <div key={ev.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 16px 9px 54px', borderBottom: isLastEval ? 'none' : '1px solid #f8fafc', background: ev.completada ? '#fffbeb' : 'white' }}>
                            <div style={{ width: 18, height: 18, borderRadius: 5, background: ev.completada ? '#fef3c7' : 'rgba(196,180,0,.12)', border: '1.5px solid #c4b400', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 8 }}>
                              {ev.completada ? <span style={{ color: '#92400e', fontWeight: 900 }}>✓</span> : '📝'}
                            </div>
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ fontSize: 12, color: '#374151', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ev.titulo}</div>
                              <div style={{ fontSize: 10, marginTop: 1, fontWeight: 600, color: '#c4b400' }}>
                                Evaluación · {ev.completada ? 'Completada ✓' : 'Pendiente'}
                                {ev.intentos > 0 ? ' · ' + ev.intentos + ' intento(s)' : ''}
                                {ev.resultado && ev.resultado.score !== undefined ? ' · ' + ev.resultado.score + '/' + ev.resultado.total + ' pts' : ''}
                              </div>
                            </div>
                            <button
                              onClick={function () { onAskConfirm({ type: 'eval', item: ev }); }}
                              style={{ background: 'none', color: '#dc2626', border: '1px solid #fecaca', borderRadius: 6, padding: '4px 9px', fontSize: 10, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap', flexShrink: 0 }}
                              onMouseOver={function (e) { e.currentTarget.style.background = '#fff5f5'; }}
                              onMouseOut={function (e) { e.currentTarget.style.background = 'none'; }}
                            >Reiniciar</button>
                          </div>
                        );
                      })}

                      {/* Sin items */}
                      {totalItems === 0 && (
                        <div style={{ padding: '14px 54px', fontSize: 12, color: '#cbd5e1' }}>No hay contenido en este módulo.</div>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* ── Footer ── */}
        <div style={{ padding: '12px 28px', borderTop: '1px solid #f1f5f9', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 6, background: '#fafbfc', borderBottomLeftRadius: 16, borderBottomRightRadius: 16 }}>
          <div style={{ width: 6, height: 6, background: '#c4b400', borderRadius: '50%' }}></div>
          <span style={{ fontSize: 10, color: '#9ca3af', fontWeight: 500 }}>Los cambios se aplican de inmediato · ASSYST SG-SST</span>
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   ConfirmResetDialog
   Diálogo de confirmación antes de ejecutar cualquier reinicio
───────────────────────────────────────────────────────────────────────────── */
function ConfirmResetDialog({ confirm, studentName, onConfirm, onCancel }) {
  var isFull   = confirm.type === 'full';
  var isModule = confirm.type === 'module';
  var isLesson = confirm.type === 'lesson';
  var isEval   = confirm.type === 'eval';

  var title = isFull   ? '¿Reiniciar curso completo?'  :
              isModule ? '¿Reiniciar módulo?'           :
              isLesson ? '¿Reiniciar lección?'          :
                         '¿Reiniciar evaluación?';

  var desc = isFull
    ? 'Se eliminará todo el progreso de ' + studentName + ': lecciones completadas, resultados de evaluaciones e intentos de todos los módulos. Esta acción no se puede deshacer.'
    : isModule
    ? 'Se reiniciarán todas las lecciones y evaluaciones del módulo "' + (confirm.mod ? confirm.mod.titulo : '') + '" para ' + studentName + '. Esta acción no se puede deshacer.'
    : isLesson
    ? 'Se marcará la lección "' + (confirm.item ? confirm.item.titulo : '') + '" como no completada para ' + studentName + '.'
    : 'Se eliminará el resultado de "' + (confirm.item ? confirm.item.titulo : '') + '" y se reseteará el contador de intentos a 0. Se enviará una notificación al estudiante indicando que puede intentarlo de nuevo.';

  var btnLabel = isFull   ? 'Sí, reiniciar todo'       :
                 isModule ? 'Sí, reiniciar módulo'      :
                 isLesson ? 'Sí, reiniciar lección'     :
                            'Sí, reiniciar evaluación';

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,61,94,.85)', zIndex: 1200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ background: 'white', borderRadius: 14, width: '100%', maxWidth: 420, padding: '28px', boxShadow: '0 24px 64px rgba(0,0,0,.32)' }}>
        <div style={{ width: 46, height: 46, background: '#fee2e2', borderRadius: 13, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#dc2626" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
            <line x1="12" y1="9" x2="12" y2="13"></line>
            <line x1="12" y1="17" x2="12.01" y2="17"></line>
          </svg>
        </div>
        <h3 style={{ margin: '0 0 10px', fontSize: 16, fontWeight: 800, color: '#1e293b' }}>{title}</h3>
        <p style={{ margin: '0 0 26px', fontSize: 13, color: '#6b7280', lineHeight: 1.65, textWrap: 'pretty' }}>{desc}</p>
        {isEval && (
          <div style={{ background: '#eff6ff', border: '1px solid #bfdbfe', borderRadius: 8, padding: '10px 14px', marginBottom: 20, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
            <span style={{ fontSize: 14, flexShrink: 0, marginTop: 1 }}>🔔</span>
            <span style={{ fontSize: 11, color: '#1e40af', lineHeight: 1.5, fontWeight: 500 }}>Se notificará al estudiante: <em>"El instructor habilitó un nuevo intento para {confirm.item ? confirm.item.titulo : 'esta evaluación'}"</em></span>
          </div>
        )}
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button
            onClick={onCancel}
            style={{ background: '#f1f5f9', color: '#475569', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
            onMouseOver={function (e) { e.currentTarget.style.background = '#e2e8f0'; }}
            onMouseOut={function (e) { e.currentTarget.style.background = '#f1f5f9'; }}
          >Cancelar</button>
          <button
            onClick={onConfirm}
            style={{ background: '#dc2626', color: 'white', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}
            onMouseOver={function (e) { e.currentTarget.style.background = '#b91c1c'; }}
            onMouseOut={function (e) { e.currentTarget.style.background = '#dc2626'; }}
          >{btnLabel}</button>
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────────────────
   AdminProgress — Componente principal
───────────────────────────────────────────────────────────────────────────── */
function AdminProgress() {
  const [selected,        setSelected]        = useStateAP(null);
  const [tick,            setTick]            = useStateAP(0);
  const [showManageModal, setShowManageModal] = useStateAP(false);
  const [pendingConfirm,  setPendingConfirm]  = useStateAP(null);

  var modules      = getModules();
  var students     = getUsers().filter(function (u) { return u.rol === 'estudiante'; });
  var totalLessons = modules.reduce(function (a, m) { return a + m.lecciones.length; }, 0);

  /* ── Helpers de progreso ── */
  function pct(uid) {
    var prog = getProgress(uid);
    var done = modules.reduce(function (a, m) {
      return a + m.lecciones.filter(function (l) { return prog[l.id]; }).length;
    }, 0);
    return totalLessons > 0 ? Math.round((done / totalLessons) * 100) : 0;
  }

  function detail(uid) {
    var prog     = getProgress(uid);
    var evalRes  = getEvalResults(uid);
    var attempts = getEvalAttempts(uid);
    return modules.map(function (m) {
      var done = m.lecciones.filter(function (l) { return prog[l.id]; }).length;
      return Object.assign({}, m, {
        lecciones: m.lecciones.map(function (l) {
          return Object.assign({}, l, { completada: !!prog[l.id] });
        }),
        evaluaciones: (m.evaluaciones || []).map(function (e) {
          return Object.assign({}, e, {
            completada: !!prog[e.id],
            resultado:  evalRes[e.id]  || null,
            intentos:   attempts[e.id] || 0
          });
        }),
        pct:  m.lecciones.length > 0 ? Math.round((done / m.lecciones.length) * 100) : 0,
        done: done
      });
    });
  }

  /* ── Ejecutar reinicio ── */
  function executeReset(confirm) {
    var uid  = selected;
    var type = confirm.type;

    if (type === 'full') {
      /* Reiniciar absolutamente todo */
      setProgress(uid, {});
      try {
        localStorage.setItem('sst_evalres_'      + uid, '{}');
        localStorage.setItem('sst_evalattempts_' + uid, '{}');
        if (typeof window.sbSave === 'function') { window.sbSave('sst_evalres_' + uid, {}); window.sbSave('sst_evalattempts_' + uid, {}); }
      } catch (e) {}
      /* Borrar fechas + certificado del ciclo anterior:
         el próximo ciclo captura fechas frescas desde cero.
         (Regla: reinicio COMPLETO = borra todo, incluidas fechas.) */
      clearCourseTracking(uid);
      /* Reiniciar estado del tour: el estudiante verá el tour de bienvenida en su próxima sesión */
      if (typeof clearTourState === 'function') clearTourState(uid);
      /* Reiniciar métricas de tiempo: tiempo total, último acceso, sesiones y promedio */
      saveTimeData(uid, { totalMinutes: 0, lastAccess: null, sessionCount: 0, avgMinutes: 0 });

    } else if (type === 'module') {
      /* Reiniciar solo este módulo */
      var progM = getProgress(uid);
      var mod   = confirm.mod;
      mod.lecciones.forEach(function (l) { delete progM[l.id]; });
      (mod.evaluaciones || []).forEach(function (e) { delete progM[e.id]; });
      setProgress(uid, progM);
      var erM = getEvalResults(uid);
      var atM = getEvalAttempts(uid);
      (mod.evaluaciones || []).forEach(function (e) {
        delete erM[e.id];
        delete atM[e.id];
      });
      try {
        localStorage.setItem('sst_evalres_'      + uid, JSON.stringify(erM));
        localStorage.setItem('sst_evalattempts_' + uid, JSON.stringify(atM));
        if (typeof window.sbSave === 'function') { window.sbSave('sst_evalres_' + uid, erM); window.sbSave('sst_evalattempts_' + uid, atM); }
      } catch (e) {}

    } else if (type === 'lesson') {
      /* Reiniciar una lección */
      var progL = getProgress(uid);
      delete progL[confirm.item.id];
      setProgress(uid, progL);

    } else if (type === 'eval') {
      /* Reiniciar una evaluación + resetear intentos + notificar estudiante */
      var progE = getProgress(uid);
      delete progE[confirm.item.id];
      setProgress(uid, progE);
      var erE = getEvalResults(uid);
      var atE = getEvalAttempts(uid);
      delete erE[confirm.item.id];
      delete atE[confirm.item.id];
      try {
        localStorage.setItem('sst_evalres_'      + uid, JSON.stringify(erE));
        localStorage.setItem('sst_evalattempts_' + uid, JSON.stringify(atE));
        if (typeof window.sbSave === 'function') { window.sbSave('sst_evalres_' + uid, erE); window.sbSave('sst_evalattempts_' + uid, atE); }
      } catch (e) {}
      /* Notificación al estudiante */
      if (window.pushStudentNotifById) {
        window.pushStudentNotifById(uid, {
          id:   'eval_reset_' + confirm.item.id + '_' + Date.now(),
          type: 'new_announcement',
          text: 'El instructor habilitó un nuevo intento para ' + confirm.item.titulo,
          read: false,
          time: Date.now()
        });
      }
    }

    /* Cerrar confirm, refrescar vista */
    setPendingConfirm(null);
    setTick(function (t) { return t + 1; });
    if (window.showToast) {
      window.showToast('Progreso reiniciado correctamente. El estudiante puede volver a intentarlo.');
    }
  }

  var sel    = selected ? students.find(function (s) { return s.id === selected; }) : null;
  var det    = sel ? detail(sel.id) : null;
  var selPct = sel ? pct(sel.id) : 0;

  /* ──────────────────────────────────────────────────────────────────────── */
  return (
    <div>

      {/* ── Cabecera ── */}
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ margin: 0, fontSize: 22, fontWeight: 800, color: '#1c79b4' }}>Progreso de Estudiantes</h2>
        <p style={{ margin: '4px 0 0', fontSize: 13, color: '#6b7280' }}>{totalLessons} lecciones totales · {students.length} estudiantes</p>
      </div>

      {!sel ? (
        /* ════ LISTA DE ESTUDIANTES ════ */
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14 }}>
          {students.map(function (s) {
            var p    = pct(s.id);
            var prog = getProgress(s.id);
            var done = modules.reduce(function (a, m) {
              return a + m.lecciones.filter(function (l) { return prog[l.id]; }).length;
            }, 0);
            return (
              <div
                key={s.id + tick}
                onClick={function () { setSelected(s.id); }}
                style={{ background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', padding: 20, cursor: 'pointer', transition: 'box-shadow .18s, transform .18s' }}
                onMouseOver={function (e) { e.currentTarget.style.boxShadow = '0 6px 24px rgba(15,32,68,.12)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
                onMouseOut={function (e) { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = ''; }}
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
                  <StudentAvatar userId={s.id} userName={s.nombre} size={40} style={{ flexShrink: 0, border: '2px solid #e5e7eb' }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14, color: '#1c79b4', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.nombre}</div>
                    <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1 }}>{s.empresa}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 7 }}>
                  <span style={{ fontSize: 12, color: '#6b7280' }}>{done}/{totalLessons} lecciones</span>
                  <span style={{ fontSize: 14, fontWeight: 800, color: p === 100 ? '#15803d' : '#1c79b4' }}>{p}%</span>
                </div>
                <div style={{ height: 6, background: '#f1f5f9', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: p + '%', background: p === 100 ? '#22c55e' : '#c4b400', borderRadius: 3, transition: 'width .4s' }} />
                </div>

                {/* ── Métricas de tiempo (resumen) ── */}
                {(function () {
                  var td = getTimeData(s.id);
                  return (
                    <div style={{ marginTop: 12, paddingTop: 10, borderTop: '1px solid #f1f5f9', display: 'flex', flexDirection: 'column', gap: 5 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: '#6b7280' }}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#1c79b4" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                          <circle cx="12" cy="12" r="10"></circle>
                          <polyline points="12 6 12 12 16 14"></polyline>
                        </svg>
                        <span>Tiempo total en plataforma: <strong style={{ color: '#1c79b4' }}>{formatTimeDisplay(td.totalMinutes)}</strong></span>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: '#9ca3af' }}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                          <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                          <line x1="16" y1="2" x2="16" y2="6"></line>
                          <line x1="8" y1="2" x2="8" y2="6"></line>
                          <line x1="3" y1="10" x2="21" y2="10"></line>
                        </svg>
                        <span>Último acceso: {formatLastAccess(td.lastAccess)}</span>
                      </div>
                    </div>
                  );
                })()}

                {!s.activo && <div style={{ marginTop: 10, fontSize: 10, color: '#dc2626', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Inactivo</div>}
              </div>
            );
          })}
          {students.length === 0 && (
            <div style={{ color: '#d1d5db', fontSize: 14, padding: 20 }}>No hay estudiantes registrados.</div>
          )}
        </div>

      ) : (
        /* ════ DETALLE DEL ESTUDIANTE ════ */
        <div>
          <div style={{ marginBottom: 20 }}>
            <button
              onClick={function () { setSelected(null); setShowManageModal(false); setPendingConfirm(null); }}
              style={{ background: 'none', border: 'none', color: '#6b7280', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit', padding: 0, display: 'flex', alignItems: 'center', gap: 4 }}
            >← Volver</button>
          </div>

          {/* Tarjeta del estudiante */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '18px 22px', background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', marginBottom: 20 }}>
            <StudentAvatar userId={sel.id} userName={sel.nombre} size={52} style={{ flexShrink: 0, border: '2px solid #e5e7eb' }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800, fontSize: 17, color: '#1c79b4' }}>{sel.nombre}</div>
              <div style={{ fontSize: 13, color: '#6b7280', marginTop: 2 }}>{sel.empresa} · {sel.cargo}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 28, fontWeight: 900, color: selPct === 100 ? '#15803d' : '#c4b400' }}>{selPct}%</div>
              <div style={{ fontSize: 11, color: '#9ca3af' }}>completado</div>
            </div>
            {/* ── Botón principal: Gestionar progreso ── */}
            <button
              onClick={function () { setShowManageModal(true); }}
              style={{ background: '#1c79b4', color: 'white', border: 'none', borderRadius: 9, padding: '10px 18px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', marginLeft: 8, display: 'flex', alignItems: 'center', gap: 7 }}
              onMouseOver={function (e) { e.currentTarget.style.background = '#1565a0'; }}
              onMouseOut={function (e) { e.currentTarget.style.background = '#1c79b4'; }}
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="3"></circle>
                <path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14"></path>
              </svg>
              Gestionar progreso
            </button>
          </div>

          {/* ── Panel de 4 métricas de tiempo ── */}
          {sel && (function () {
            var td = getTimeData(sel.id);
            return (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 20 }}>

                {/* Tiempo total */}
                <div style={{ background: '#eff6ff', borderRadius: 10, border: '1px solid #bfdbfe', padding: '14px 16px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                    <div style={{ width: 24, height: 24, background: '#1c79b4', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <circle cx="12" cy="12" r="10"></circle>
                        <polyline points="12 6 12 12 16 14"></polyline>
                      </svg>
                    </div>
                    <span style={{ fontSize: 10, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Tiempo total</span>
                  </div>
                  <div style={{ fontSize: 16, fontWeight: 900, color: '#1c79b4', lineHeight: 1.2 }}>{formatTimeDisplay(td.totalMinutes)}</div>
                  <div style={{ fontSize: 10, color: '#93c5fd', marginTop: 3, fontWeight: 500 }}>en la plataforma</div>
                </div>

                {/* Último acceso */}
                <div style={{ background: '#f8fafc', borderRadius: 10, border: '1px solid #e2e8f0', padding: '14px 16px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                    <div style={{ width: 24, height: 24, background: '#475569', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                        <line x1="16" y1="2" x2="16" y2="6"></line>
                        <line x1="8" y1="2" x2="8" y2="6"></line>
                        <line x1="3" y1="10" x2="21" y2="10"></line>
                      </svg>
                    </div>
                    <span style={{ fontSize: 10, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Último acceso</span>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 800, color: '#1e293b', lineHeight: 1.3 }}>{formatLastAccess(td.lastAccess)}</div>
                </div>

                {/* Sesiones */}
                <div style={{ background: '#eff6ff', borderRadius: 10, border: '1px solid #bfdbfe', padding: '14px 16px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                    <div style={{ width: 24, height: 24, background: '#1c79b4', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                        <circle cx="9" cy="7" r="4"></circle>
                        <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                        <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                      </svg>
                    </div>
                    <span style={{ fontSize: 10, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Sesiones</span>
                  </div>
                  <div style={{ fontSize: 16, fontWeight: 900, color: '#1c79b4', lineHeight: 1.2 }}>{td.sessionCount || 0}</div>
                  <div style={{ fontSize: 10, color: '#93c5fd', marginTop: 3, fontWeight: 500 }}>inicio{(td.sessionCount || 0) !== 1 ? 's' : ''} de sesión</div>
                </div>

                {/* Promedio por sesión */}
                <div style={{ background: '#fffbeb', borderRadius: 10, border: '1px solid #fde68a', padding: '14px 16px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                    <div style={{ width: 24, height: 24, background: '#c4b400', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline>
                      </svg>
                    </div>
                    <span style={{ fontSize: 10, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Prom. / sesión</span>
                  </div>
                  <div style={{ fontSize: 16, fontWeight: 900, color: '#92400e', lineHeight: 1.2 }}>
                    {(td.sessionCount || 0) > 0 ? formatTimeDisplay(td.avgMinutes) : '—'}
                  </div>
                  <div style={{ fontSize: 10, color: '#fbbf24', marginTop: 3, fontWeight: 500 }}>tiempo promedio</div>
                </div>

              </div>
            );
          })()}

          {/* Tarjetas de módulos */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {det.map(function (mod, i) {
              return (
                <div key={mod.id + '-' + tick} style={{ background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', padding: '18px 22px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{ width: 30, height: 30, background: '#1c79b4', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#c4b400', fontSize: 11, fontWeight: 800 }}>{i + 1}</div>
                      <span style={{ fontWeight: 700, color: '#1c79b4', fontSize: 14 }}>{mod.titulo}</span>
                    </div>
                    <span style={{ fontSize: 14, fontWeight: 800, color: mod.pct === 100 ? '#15803d' : '#64748b' }}>{mod.pct}%</span>
                  </div>
                  <div style={{ height: 4, background: '#f1f5f9', borderRadius: 2, marginBottom: 12 }}>
                    <div style={{ height: '100%', width: mod.pct + '%', background: mod.pct === 100 ? '#22c55e' : '#c4b400', borderRadius: 2, transition: 'width .3s' }} />
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {mod.lecciones.map(function (l) {
                      return (
                        <span key={l.id} style={{ padding: '4px 10px', borderRadius: 20, fontSize: 11, fontWeight: 600, background: l.completada ? '#dcfce7' : '#f1f5f9', color: l.completada ? '#15803d' : '#9ca3af' }}>
                          {l.completada ? '✓ ' : ''}{l.titulo.length > 32 ? l.titulo.substring(0, 32) + '…' : l.titulo}
                        </span>
                      );
                    })}
                    {(mod.evaluaciones || []).map(function (ev) {
                      return (
                        <span key={ev.id} style={{ padding: '4px 10px', borderRadius: 20, fontSize: 11, fontWeight: 600, background: ev.completada ? '#fef3c7' : '#f1f5f9', color: ev.completada ? '#92400e' : '#9ca3af', border: ev.completada ? '1px solid #fcd34d' : 'none' }}>
                          {ev.completada ? '✓ ' : '📝 '}{ev.titulo.length > 32 ? ev.titulo.substring(0, 32) + '…' : ev.titulo}
                        </span>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ════ MODAL: Gestionar progreso ════ */}
      {showManageModal && sel && (
        <ManageProgressModal
          student={sel}
          tick={tick}
          onClose={function () { setShowManageModal(false); }}
          onAskConfirm={function (confirmData) { setPendingConfirm(confirmData); }}
        />
      )}

      {/* ════ DIÁLOGO: Confirmación ════ */}
      {pendingConfirm && sel && (
        <ConfirmResetDialog
          confirm={pendingConfirm}
          studentName={sel.nombre}
          onConfirm={function () { executeReset(pendingConfirm); }}
          onCancel={function () { setPendingConfirm(null); }}
        />
      )}
    </div>
  );
}

window.AdminProgress = AdminProgress;
