const { useState: useStateSV, useEffect: useEffectSV, useRef: useRefSV } = React;

// Converts any Google Drive URL to the correct preview embed format
function toDriveEmbed(url) {
  if (!url) return '';
  if (url.includes('drive.google.com/file/d/')) {
    var idMatch = url.match(/\/file\/d\/([^\/\?]+)/);
    if (idMatch) return 'https://drive.google.com/file/d/' + idMatch[1] + '/preview?usp=sharing';
  }
  var qidMatch = url.match(/[?&]id=([^&\s]+)/);
  if (qidMatch) return 'https://drive.google.com/file/d/' + qidMatch[1] + '/preview?usp=sharing';
  return url;
}

// Converts any YouTube URL to the embed format
function toYouTubeEmbed(url) {
  if (!url) return '';
  var id = '';
  var m = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([^&\?\/\s]+)/);
  if (m) id = m[1];
  if (!id) { var m2 = url.match(/[?&]v=([^&\s]+)/); if (m2) id = m2[1]; }
  if (!id) return url;
  return 'https://www.youtube.com/embed/' + id + '?rel=0&modestbranding=1&playsinline=1';
}

// Returns the correct embed URL based on videoType
function getVideoEmbed(les) {
  if (!les.videoUrl) return '';
  if (les.videoType === 'youtube') return toYouTubeEmbed(les.videoUrl);
  return toDriveEmbed(les.videoUrl);
}

// Returns a Drive open URL for the fallback link
function toDriveOpen(url) {
  if (!url) return '#';
  if (url.includes('drive.google.com/file/d/')) {
    var idMatch = url.match(/\/file\/d\/([^\/\?]+)/);
    if (idMatch) return 'https://drive.google.com/file/d/' + idMatch[1] + '/view?usp=sharing';
  }
  var qidMatch = url.match(/[?&]id=([^&\s]+)/);
  if (qidMatch) return 'https://drive.google.com/file/d/' + qidMatch[1] + '/view?usp=sharing';
  return url;
}

// Tooltip flotante para ítems en modo colapsado
function SidebarItemTooltip({ label, children }) {
  var _s = useStateSV(null);
  var pos = _s[0]; var setPos = _s[1];
  function handleEnter(e) {
    var rect = e.currentTarget.getBoundingClientRect();
    setPos({ top: Math.round(rect.top + rect.height / 2) });
  }
  return (
    <div onMouseEnter={handleEnter} onMouseLeave={function() { setPos(null); }}>
      {children}
      {label && pos && (
        <div style={{ position: 'fixed', left: 72, top: pos.top, transform: 'translateY(-50%)', background: '#1e293b', color: 'white', padding: '6px 12px', borderRadius: 7, fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap', pointerEvents: 'none', zIndex: 3000, boxShadow: '0 4px 18px rgba(0,0,0,.32)', fontFamily: "'Montserrat',sans-serif", letterSpacing: '0.02em' }}>
          <div style={{ position: 'absolute', right: '100%', top: '50%', transform: 'translateY(-50%)', width: 0, height: 0, borderTop: '5px solid transparent', borderBottom: '5px solid transparent', borderRight: '6px solid #1e293b' }} />
          {label}
        </div>
      )}
    </div>
  );
}

function StudentView({ user, onLogout }) {
  const [modules] = useStateSV(getModules());
  const [prog, setProg] = useStateSV(getProgress(user.id));
  const [view, setView] = useStateSV('home'); // 'home' | 'module' | 'lesson' | 'forum'
  const [activeMod, setActiveMod] = useStateSV(null);
  const [activeLes, setActiveLes] = useStateSV(null);
  const [videoError, setVideoError] = useStateSV(false);
  const [showCert, setShowCert] = useStateSV(false);
  const prevPct = useRefSV(-1);
  const [videoModal, setVideoModal] = useStateSV(false);
  const [showBio, setShowBio] = useStateSV(false);
  const [showProfile, setShowProfile] = useStateSV(false);
  const [photoVer, setPhotoVer] = useStateSV(0);
  const [showTour, setShowTour] = useStateSV(false);

  // Escuchar CUALQUIER cambio de foto (propio o asignado por admin)
  useEffectSV(function () {
    function onAnyPhoto() { setPhotoVer(function (v) { return v + 1; }); }
    window.addEventListener('sst:photo_changed', onAnyPhoto);
    return function () { window.removeEventListener('sst:photo_changed', onAnyPhoto); };
  }, []);

  // Tour: mostrar automáticamente la primera vez que el estudiante inicia sesión
  useEffectSV(function () {
    if (typeof getTourDone === 'function' && !getTourDone(user.id)) {
      setSidebarCollapsed(false);
      try { localStorage.setItem('sst_sidebar_collapsed', '0'); } catch (e) {}
      setShowTour(true);
    }
  }, []);

  // Exponer window.startTour para el botón "Ver tour de nuevo" del perfil
  useEffectSV(function () {
    window.startTour = function () {
      setView('home');
      setActiveMod(null);
      setActiveLes(null);
      setSidebarCollapsed(false);
      try { localStorage.setItem('sst_sidebar_collapsed', '0'); } catch (e) {}
      setShowTour(true);
    };
    return function () { try { delete window.startTour; } catch (e) {} };
  }, []);
  const [profileMenu, setProfileMenu] = useStateSV(false);
  const profileMenuRef = useRefSV(null);
  const [sidebarCollapsed, setSidebarCollapsed] = useStateSV(function() {
    return localStorage.getItem('sst_sidebar_collapsed') === '1';
  });
  const [showSupport, setShowSupport] = useStateSV(false);
  const [supportAsunto, setSupportAsunto] = useStateSV('');
  const [supportDesc, setSupportDesc] = useStateSV('');
  const [supportSent, setSupportSent] = useStateSV(false);
  const [activeEval, setActiveEval] = useStateSV(null);
  const [activeSurvey, setActiveSurvey] = useStateSV(null);
  const [quizAnswers, setQuizAnswers] = useStateSV({});
  const [quizResult, setQuizResult] = useStateSV(null);
  const [shuffledQuestions, setShuffledQuestions] = useStateSV(null);
  const [evalResults, setEvalResults] = useStateSV(function () { return getEvalResults(user.id); });
  const [evalAttempts, setEvalAttempts] = useStateSV(function () { return getEvalAttempts(user.id); });
  const [showCertBlock, setShowCertBlock] = useStateSV(false);
  const [mobileMenuSV, setMobileMenuSV] = useStateSV(false);
  function toggleSidebar() {
    setSidebarCollapsed(function(v) {
      localStorage.setItem('sst_sidebar_collapsed', !v ? '1' : '0');
      return !v;
    });
  }

  var totalLessons = modules.reduce(function (a, m) { return a + m.lecciones.length + (m.evaluaciones || []).length + (m.encuestas || []).length; }, 0);
  var doneLessons = modules.reduce(function (a, m) { return a + m.lecciones.filter(function (l) { return prog[l.id]; }).length + (m.evaluaciones || []).filter(function (ev) { return prog[ev.id]; }).length + (m.encuestas || []).filter(function (enc) { return prog[enc.id]; }).length; }, 0);
  var overallPct = totalLessons > 0 ? Math.round((doneLessons / totalLessons) * 100) : 0;

  // ── Elegibilidad para certificado ────────────────────────────────────────────
  var totalLessonCount = modules.reduce(function(a, m) { return a + m.lecciones.length; }, 0);
  var doneLessonCount  = modules.reduce(function(a, m) { return a + m.lecciones.filter(function(l) { return prog[l.id]; }).length; }, 0);
  var lessonsAllDone   = totalLessonCount > 0 && doneLessonCount === totalLessonCount;
  var allEvalsFlat     = modules.reduce(function(a, m) { return a.concat(m.evaluaciones || []); }, []);
  var evalsAllPassed   = allEvalsFlat.length === 0 || allEvalsFlat.every(function(ev) { return !!prog[ev.id]; });
  var allEncuestasFlat = modules.reduce(function(a, m) { return a.concat(m.encuestas || []); }, []);
  var encuestasAllDone = allEncuestasFlat.length === 0 || allEncuestasFlat.every(function(enc) { return !!prog[enc.id]; });
  var certEligible     = lessonsAllDone && evalsAllPassed && encuestasAllDone;

  function getPendingItems() {
    var items = [];
    modules.forEach(function(mod, i) {
      mod.lecciones.forEach(function(les) {
        if (!prog[les.id]) items.push({ type: 'lesson', modIdx: i + 1, modId: mod.id, itemId: les.id, titulo: les.titulo });
      });
      (mod.evaluaciones || []).forEach(function(ev) {
        if (!prog[ev.id]) items.push({ type: 'eval', modIdx: i + 1, modId: mod.id, itemId: ev.id, titulo: ev.titulo });
      });
      (mod.encuestas || []).forEach(function(enc) {
        if (!prog[enc.id]) items.push({ type: 'survey', modIdx: i + 1, modId: mod.id, itemId: enc.id, titulo: enc.titulo });
      });
    });
    return items;
  }

  function handleCertClick() {
    if (certEligible) {
      // Capturar fecha de finalización en este momento exacto (idempotente: no
      // sobreescribe si ya estaba guardada desde markDone o el useEffect).
      setCourseFinishDate(user.id);
      issueCertificate(user.id);
      setShowCert(true);
    } else {
      setShowCertBlock(true);
    }
  }

  function goToFirstPending() {
    var pending = getPendingItems();
    if (!pending.length) return;
    var first = pending[0];
    setShowCertBlock(false);
    goModule(first.modId);
    if (first.type === 'lesson') goLesson(first.itemId);
    else if (first.type === 'survey') goSurvey(first.itemId);
    else goQuiz(first.itemId);
  }

  function modPct(mod) {
    var total = mod.lecciones.length + (mod.evaluaciones || []).length + (mod.encuestas || []).length;
    if (total === 0) return 0;
    var done = mod.lecciones.filter(function (l) { return prog[l.id]; }).length + (mod.evaluaciones || []).filter(function (ev) { return prog[ev.id]; }).length + (mod.encuestas || []).filter(function (enc) { return prog[enc.id]; }).length;
    return Math.round((done / total) * 100);
  }

  function markDone(lesId) {
    // ── Fecha de inicio: capturar solo la primera vez que se completa algo ──
    if (!getCourseStartDate(user.id)) {
      setCourseStartDate(user.id);
    }

    var np = Object.assign({}, prog, { [lesId]: true });

    // ── Fecha de finalización: capturar en el instante exacto en que el
    //    estudiante cumple 100 % lecciones + 100 % evaluaciones aprobadas.
    //    setCourseFinishDate es idempotente (solo guarda la primera vez).
    var newDoneLessonCount = modules.reduce(function(a, m) {
      return a + m.lecciones.filter(function(l) { return np[l.id]; }).length;
    }, 0);
    var newLessonsAllDone = totalLessonCount > 0 && newDoneLessonCount === totalLessonCount;
    var newEvalsAllPassed = allEvalsFlat.length === 0 ||
      allEvalsFlat.every(function(ev) { return !!np[ev.id]; });
    if (newLessonsAllDone && newEvalsAllPassed) {
      setCourseFinishDate(user.id);
    }

    setProg(np); setProgress(user.id, np);
  }
  function markUndone(lesId) {
    var np = Object.assign({}, prog);
    delete np[lesId];
    setProg(np); setProgress(user.id, np);
  }
  function submitQuiz(ev) {
    var currentCount = getEvalAttempts(user.id)[ev.id] || 0;
    var maxAllowed = ev.intentosMaximos || 3;
    if (!prog[ev.id] && currentCount >= maxAllowed) return;
    var newAttemptCount = currentCount + 1;
    var newAttemptMap = Object.assign({}, evalAttempts, { [ev.id]: newAttemptCount });
    setEvalAttempts(newAttemptMap);
    setEvalAttempt(user.id, ev.id, newAttemptCount);
    var total = ev.preguntas.length;
    var correct = ev.preguntas.filter(function (q) {
      var sel = quizAnswers[q.id];
      var cor = q.opciones.find(function (o) { return o.correcta; });
      return sel && cor && sel === cor.id;
    }).length;
    var puntaje = total > 0 ? Math.round((correct / total) * 100) : 0;
    var aprobado = puntaje >= (ev.puntajeMinimo || 0);
    var result = { puntaje: puntaje, aprobado: aprobado, correctas: correct, total: total };
    setQuizResult(result);
    var nr = Object.assign({}, evalResults, { [ev.id]: result });
    setEvalResults(nr);
    setEvalResult(user.id, ev.id, result);
    if (aprobado) markDone(ev.id);
  }

  function handleSupportSubmit(e) {
    e.preventDefault();
    if (!supportAsunto.trim() || !supportDesc.trim()) return;
    var req = {
      id: 'sup_' + Date.now(),
      estudianteId: user.id,
      estudianteNombre: user.nombre,
      asunto: supportAsunto.trim(),
      descripcion: supportDesc.trim(),
      fecha: new Date().toISOString(),
      estado: 'Pendiente',
    };
    if (window.addSupportRequest) window.addSupportRequest(req);
    if (window.pushAdminNotif) {
      window.pushAdminNotif({
        id: 'notif_sup_' + Date.now(),
        type: 'support_request',
        text: user.nombre + ' envió una solicitud de soporte: "' + supportAsunto.trim() + '"',
        time: Date.now(),
        read: false,
        studentId: user.id,
        studentName: user.nombre,
      });
    }
    /* Confirmación visual para el estudiante */
    if (window.showToast) window.showToast('Solicitud enviada — el equipo te responderá pronto 🎫', 'success');
    setSupportSent(true);
  }

  // Auto-mostrar certificado al completar el 100% por primera vez
  useEffectSV(function () {
    if (certEligible && overallPct === 100 && prevPct.current < 100) {
      // Garantizar que la fecha de finalización esté guardada antes de emitir
      // el certificado (por si este efecto corre antes que markDone en casos
      // de carga inicial con datos ya completos).
      setCourseFinishDate(user.id);
      issueCertificate(user.id);
      var shownKey = 'sst_cert_shown_' + user.id;
      if (!localStorage.getItem(shownKey)) {
        localStorage.setItem(shownKey, '1');
        if (typeof window.sbSave === 'function') window.sbSave(shownKey, 1);
        /* Notificar al admin que el estudiante completó el 100% */
        if (window.pushAdminNotif) {
          window.pushAdminNotif({
            id: 'notif_complete_' + user.id + '_' + Date.now(),
            type: 'course_complete',
            text: user.nombre + ' completó el 100% del curso y obtuvo su certificado. 🏆',
            time: Date.now(),
            read: false,
            studentId: user.id,
            studentName: user.nombre,
          });
        }
        setTimeout(function () { setShowCert(true); }, 400);
      }
    }
    prevPct.current = overallPct;
  }, [overallPct]);

  // Migrar datos históricos tomados antes de que existiera el rastreo de intentos.
  useEffectSV(function () {
    var existing = getEvalAttempts(user.id);
    var results  = getEvalResults(user.id);
    var progress = getProgress(user.id);

    // 1. Contar intentos fallidos sin rastrear como 1 intento usado
    var migrated = Object.assign({}, existing);
    var attemptsChanged = false;
    Object.keys(results).forEach(function (evalId) {
      if (!existing[evalId] && !progress[evalId] && results[evalId] && !results[evalId].aprobado) {
        migrated[evalId] = 1;
        setEvalAttempt(user.id, evalId, 1);
        attemptsChanged = true;
      }
    });
    if (attemptsChanged) setEvalAttempts(migrated);

    // 2. Sincronizar prog para evaluaciones aprobadas antes del rastreo
    var progFixed = Object.assign({}, progress);
    var progChanged = false;
    Object.keys(results).forEach(function (evalId) {
      if (results[evalId] && results[evalId].aprobado && !progFixed[evalId]) {
        progFixed[evalId] = true;
        progChanged = true;
      }
    });
    if (progChanged) {
      setProgress(user.id, progFixed);
      setProg(progFixed);
    }
  }, []);

  // Cerrar modal con Escape
  useEffectSV(function () {
    function onKey(e) { if (e.key === 'Escape') { setVideoModal(false); setProfileMenu(false); setShowSupport(false); setShowCertBlock(false); } }
    document.addEventListener('keydown', onKey);
    return function () { document.removeEventListener('keydown', onKey); };
  }, []);

  // Cerrar menú de perfil al hacer clic fuera
  useEffectSV(function () {
    if (!profileMenu) return;
    function onClickOutside(e) {
      if (profileMenuRef.current && !profileMenuRef.current.contains(e.target)) {
        setProfileMenu(false);
      }
    }
    document.addEventListener('mousedown', onClickOutside);
    return function () { document.removeEventListener('mousedown', onClickOutside); };
  }, [profileMenu]);

  // ── Rastreo de tiempo de sesión ───────────────────────────────────────────────
  // Al montar: registra la hora de entrada y el último acceso.
  // Al desmontar (logout) o al cerrar la ventana (beforeunload): acumula el tiempo.
  useEffectSV(function () {
    var sessionStart = Date.now();
    var sessionSaved = false;

    // Registrar inicio de sesión: actualizar lastAccess e incrementar contador
    var td0 = getTimeData(user.id);
    saveTimeData(user.id, Object.assign({}, td0, {
      lastAccess:   new Date().toISOString(),
      sessionCount: (td0.sessionCount || 0) + 1
    }));

    function saveSession() {
      if (sessionSaved) return;
      sessionSaved = true;
      var elapsedMin = Math.max(1, Math.round((Date.now() - sessionStart) / 60000));
      var td = getTimeData(user.id);
      var newTotal   = (td.totalMinutes || 0) + elapsedMin;
      var sessCount  = td.sessionCount || 1;
      saveTimeData(user.id, Object.assign({}, td, {
        totalMinutes: newTotal,
        avgMinutes:   Math.round(newTotal / sessCount)
      }));
    }

    window.addEventListener('beforeunload', saveSession);
    return function () {
      window.removeEventListener('beforeunload', saveSession);
      saveSession(); // También guardar al cerrar sesión (unmount del componente)
    };
  }, []);

  function shuffleArray(arr) {
    var a = arr.slice();
    for (var i = a.length - 1; i > 0; i--) {
      var j = Math.floor(Math.random() * (i + 1));
      var tmp = a[i]; a[i] = a[j]; a[j] = tmp;
    }
    return a;
  }
  function applyQuizShuffle(ev) {
    if (ev && ev.ordenAleatorio && ev.preguntas && ev.preguntas.length > 0) {
      setShuffledQuestions(shuffleArray(ev.preguntas));
    } else {
      setShuffledQuestions(null);
    }
  }
  function goModule(modId) { setActiveMod(modId); setActiveLes(null); setActiveEval(null); setActiveSurvey(null); setView('module'); setQuizResult(null); setQuizAnswers({}); setShuffledQuestions(null); }
  function goLesson(lesId) { setActiveLes(lesId); setActiveEval(null); setActiveSurvey(null); setView('lesson'); setVideoError(false); }
  function goHome() { setView('home'); setActiveMod(null); setActiveLes(null); setActiveEval(null); setActiveSurvey(null); setQuizResult(null); setQuizAnswers({}); setShuffledQuestions(null); }
  function goForum() { setView('forum'); setActiveMod(null); setActiveLes(null); setActiveEval(null); setActiveSurvey(null); }
  function goQuiz(evalId) {
    setActiveEval(evalId); setActiveLes(null); setActiveSurvey(null); setView('quiz'); setQuizAnswers({}); setQuizResult(null);
    var ev = null;
    for (var i = 0; i < modules.length; i++) {
      var found = (modules[i].evaluaciones || []).find(function(e) { return e.id === evalId; });
      if (found) { ev = found; break; }
    }
    applyQuizShuffle(ev);
  }
  function goSurvey(encId) {
    setActiveSurvey(encId); setActiveLes(null); setActiveEval(null); setView('survey');
  }

  // ── Array plano con TODOS los elementos del curso en orden ──────────────────
  var courseSequence = [];
  modules.forEach(function(mod) {
    mod.lecciones.forEach(function(les) {
      courseSequence.push({ type: 'lesson', modId: mod.id, id: les.id });
    });
    (mod.evaluaciones || []).forEach(function(ev) {
      courseSequence.push({ type: 'eval', modId: mod.id, id: ev.id });
    });
    (mod.encuestas || []).forEach(function(enc) {
      courseSequence.push({ type: 'survey', modId: mod.id, id: enc.id });
    });
  });

  // Índice del elemento activo dentro del array plano
  var currentFlatIdx = -1;
  if (view === 'lesson' && activeLes) {
    currentFlatIdx = courseSequence.findIndex(function(item) { return item.type === 'lesson' && item.id === activeLes; });
  } else if (view === 'quiz' && activeEval) {
    currentFlatIdx = courseSequence.findIndex(function(item) { return item.type === 'eval' && item.id === activeEval; });
  } else if (view === 'survey' && activeSurvey) {
    currentFlatIdx = courseSequence.findIndex(function(item) { return item.type === 'survey' && item.id === activeSurvey; });
  }

  // Navega a cualquier elemento actualizando todos los estados necesarios
  function navigateTo(item) {
    setActiveMod(item.modId);
    if (item.type === 'lesson') {
      setActiveLes(item.id); setActiveEval(null); setActiveSurvey(null); setView('lesson'); setVideoError(false); setVideoModal(false);
    } else if (item.type === 'survey') {
      setActiveSurvey(item.id); setActiveLes(null); setActiveEval(null); setView('survey');
    } else {
      setActiveEval(item.id); setActiveLes(null); setActiveSurvey(null); setView('quiz'); setQuizAnswers({}); setQuizResult(null);
      var evNav = null;
      for (var ni = 0; ni < modules.length; ni++) {
        var nfound = (modules[ni].evaluaciones || []).find(function(e) { return e.id === item.id; });
        if (nfound) { evNav = nfound; break; }
      }
      applyQuizShuffle(evNav);
    }
  }
  function goNext() {
    if (currentFlatIdx < 0 || currentFlatIdx >= courseSequence.length - 1) return;
    navigateTo(courseSequence[currentFlatIdx + 1]);
  }
  function goPrev() {
    if (currentFlatIdx <= 0) return;
    navigateTo(courseSequence[currentFlatIdx - 1]);
  }

  var curMod = activeMod ? modules.find(function (m) { return m.id === activeMod; }) : null;
  var curLes = (curMod && activeLes) ? curMod.lecciones.find(function (l) { return l.id === activeLes; }) : null;
  var curLesIdx = curMod && curLes ? curMod.lecciones.findIndex(function (l) { return l.id === activeLes; }) : -1;
  var curEval = (curMod && activeEval) ? (curMod.evaluaciones || []).find(function (ev) { return ev.id === activeEval; }) : null;
  var curSurvey = (curMod && activeSurvey) ? (curMod.encuestas || []).find(function (enc) { return enc.id === activeSurvey; }) : null;
  var evalMaxIntentos = curEval ? (curEval.intentosMaximos || 3) : 3;
  var evalUsedAttempts = curEval ? (evalAttempts[curEval.id] || 0) : 0;
  var evalAttemptsExhausted = !!(curEval && !prog[curEval.id] && evalUsedAttempts >= evalMaxIntentos);

  var sidebarItems = modules.map(function (m, i) {
    return { mod: m, idx: i, pct: modPct(m), active: m.id === activeMod };
  });

  return (
    <window.PhotoVersionContext.Provider value={photoVer}>
    <>
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', background: '#EEF2F7', fontFamily: "'Montserrat',sans-serif", overflow: 'hidden' }}>

      {/* Topbar */}
      <div className="sst-student-topbar" style={{ background: '#1c79b4', height: 60, display: 'flex', alignItems: 'center', padding: '0 24px', gap: 16, flexShrink: 0, zIndex: 1200 }}>
        <button className="sst-student-hamburger" onClick={function () { setMobileMenuSV(function (v) { return !v; }); }} style={{ display: 'none', alignItems: 'center', justifyContent: 'center', width: 36, height: 36, background: 'rgba(255,255,255,.12)', border: 'none', borderRadius: 8, cursor: 'pointer', padding: 0, flexShrink: 0 }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
        </button>
        <button onClick={goHome} style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
          <div style={{ background: 'white', borderRadius: 10, padding: '4px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <img src={(window.__resources && window.__resources.logoAssyst) || "uploads/LOGO.png"} alt="ASSYST" style={{ width: 38, height: 38, objectFit: 'contain', display: 'block' }} />
          </div>
        </button>

        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div data-tour-id="tour-progress" className="sst-progress-bar-wrap" style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'rgba(255,255,255,.08)', borderRadius: 20, padding: '7px 18px' }}>
            <div className="sst-progress-bar-track" style={{ width: 130, height: 5, background: 'rgba(255,255,255,.15)', borderRadius: 3, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: overallPct + '%', background: '#c4b400', borderRadius: 3, transition: 'width .5s' }} />
            </div>
            <span style={{ fontSize: 12, fontWeight: 700, color: overallPct === 100 ? '#4ade80' : '#c4b400', whiteSpace: 'nowrap' }}>{overallPct}% completado</span>
          </div>
        </div>

      </div>

      <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
        {/* Mobile overlay */}
        <div className={'sst-student-overlay' + (mobileMenuSV ? ' open' : '')} onClick={function () { setMobileMenuSV(false); }} />
        {/* Sidebar */}
        <div data-tour-id="tour-sidebar" className={'sst-student-sidebar' + (mobileMenuSV ? ' open' : '')} style={{ width: sidebarCollapsed ? 64 : 272, background: 'white', borderRight: '1px solid #e5e7eb', overflowY: 'auto', overflowX: 'hidden', flexShrink: 0, transition: 'width 0.28s cubic-bezier(0.4,0,0.2,1)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: sidebarCollapsed ? '12px 0' : '14px 18px 10px', borderBottom: '1px solid #f1f5f9', display: 'flex', alignItems: 'center', justifyContent: sidebarCollapsed ? 'center' : 'space-between', minHeight: 60, gap: 8 }}>
            {!sidebarCollapsed && (
              <button onClick={goHome} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'inherit', padding: 0, textAlign: 'left', flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 4 }}>Contenido del Curso</div>
                <div style={{ fontSize: 12, color: '#6b7280' }}>{doneLessons} de {totalLessons} elementos completados</div>
              </button>
            )}
            <button
              onClick={toggleSidebar}
              title={sidebarCollapsed ? 'Expandir panel' : 'Colapsar panel'}
              style={{ width: 30, height: 30, background: '#f1f5f9', border: 'none', borderRadius: 7, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'background .15s, color .15s', color: '#6b7280' }}
              onMouseOver={function (e) { e.currentTarget.style.background = '#e2e8f0'; e.currentTarget.style.color = '#1c79b4'; }}
              onMouseOut={function (e) { e.currentTarget.style.background = '#f1f5f9'; e.currentTarget.style.color = '#6b7280'; }}
            >
              {sidebarCollapsed ? (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="13 17 18 12 13 7"></polyline>
                  <polyline points="6 17 11 12 6 7"></polyline>
                </svg>
              ) : (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="11 17 6 12 11 7"></polyline>
                  <polyline points="18 17 13 12 18 7"></polyline>
                </svg>
              )}
            </button>
          </div>

          {/* User block */}
          <div style={{ borderBottom: '1px solid #e5e7eb', padding: sidebarCollapsed ? '10px 6px' : '12px 14px' }}>
            {sidebarCollapsed ? (
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
                <button onClick={function () { setShowProfile(true); }} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
                  <StudentAvatar key={photoVer} userId={user.id} userName={user.nombre} size={32} style={{ border: '2px solid #e5e7eb' }} />
                </button>
                <div data-tour-id="tour-notifications" style={{ display: 'inline-flex' }}><NotificationBell role={user.id} darkBg={false} openRight={true} /></div>
              </div>
            ) : (
              <>
                <div ref={profileMenuRef} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                  <button onClick={function () { setShowProfile(true); }} style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit', textAlign: 'left', flex: 1, minWidth: 0 }}>
                    <StudentAvatar key={photoVer} userId={user.id} userName={user.nombre} size={34} style={{ border: '2px solid #e5e7eb', flexShrink: 0 }} />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 700, color: '#1e293b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.nombre}</div>
                      <div style={{ fontSize: 10, color: '#9ca3af' }}>{user.empresa || 'Estudiante'}</div>
                    </div>
                  </button>
                  <div data-tour-id="tour-notifications" style={{ display: 'inline-flex', flexShrink: 0 }}><NotificationBell role={user.id} darkBg={false} openRight={true} /></div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button onClick={function () { setShowProfile(true); }} style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, padding: '8px', background: '#f1f5f9', border: 'none', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, color: '#1c79b4' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M6 20v-2a6 6 0 0 1 12 0v2"/></svg>
                    Mi Perfil
                  </button>
                  <button onClick={onLogout} style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, padding: '8px', background: '#fef2f2', border: 'none', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, color: '#dc2626' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
                    Salir
                  </button>
                </div>
              </>
            )}
          </div>

          {/* Foro — primer ítem del menú */}
          <div data-tour-id="tour-forum" style={{ borderBottom: '1px solid #f1f5f9' }}>
            {sidebarCollapsed ? (
              <SidebarItemTooltip label="Foro">
                <button onClick={goForum} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%', padding: '12px 0', background: view === 'forum' ? '#fafbff' : 'white', border: 'none', cursor: 'pointer', transition: 'background .12s' }}>
                  <div style={{ width: 28, height: 28, background: view === 'forum' ? '#1c79b4' : '#f1f5f9', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={view === 'forum' ? '#c4b400' : '#94a3b8'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                    </svg>
                  </div>
                </button>
              </SidebarItemTooltip>
            ) : (
              <button onClick={goForum} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '13px 18px', background: view === 'forum' ? '#fafbff' : 'white', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', transition: 'background .12s' }}>
                <div style={{ width: 28, height: 28, background: view === 'forum' ? '#1c79b4' : '#f1f5f9', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={view === 'forum' ? '#c4b400' : '#94a3b8'} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                  </svg>
                </div>
                <div style={{ fontSize: 12, fontWeight: view === 'forum' ? 700 : 500, color: view === 'forum' ? '#1c79b4' : '#374151' }}>Foro</div>
              </button>
            )}
          </div>

          {/* Bibliografía del Autor */}
          <div style={{ borderBottom: '1px solid #f1f5f9' }}>
            {sidebarCollapsed ? (
              <SidebarItemTooltip label="Bibliografía del Creador">
                <button onClick={function () { setShowBio(true); }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%', padding: '12px 0', background: 'white', border: 'none', cursor: 'pointer', transition: 'background .12s' }}
                  onMouseOver={function (e) { e.currentTarget.style.background = '#fffbf0'; }}
                  onMouseOut={function (e) { e.currentTarget.style.background = 'white'; }}>
                  <div style={{ width: 28, height: 28, background: 'rgba(196,180,0,0.13)', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#c4b400" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <circle cx="12" cy="8" r="4"></circle>
                      <path d="M6 20v-2a6 6 0 0 1 12 0v2"></path>
                    </svg>
                  </div>
                </button>
              </SidebarItemTooltip>
            ) : (
              <button
                onClick={function () { setShowBio(true); }}
                style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '13px 18px', background: 'white', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', transition: 'background .12s' }}
                onMouseOver={function (e) { e.currentTarget.style.background = '#fffbf0'; }}
                onMouseOut={function (e) { e.currentTarget.style.background = 'white'; }}
              >
                <div style={{ width: 28, height: 28, background: 'rgba(196,180,0,0.13)', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#c4b400" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="12" cy="8" r="4"></circle>
                    <path d="M6 20v-2a6 6 0 0 1 12 0v2"></path>
                  </svg>
                </div>
                <div style={{ fontSize: 12, fontWeight: 500, color: '#374151' }}>Bibliografía del Creador del Curso</div>
              </button>
            )}
          </div>

          {/* Soporte Técnico */}
          <div data-tour-id="tour-support" style={{ borderBottom: '1px solid #f1f5f9' }}>
            {sidebarCollapsed ? (
              <SidebarItemTooltip label="Soporte Técnico">
                <button
                  onClick={function () { setSupportAsunto(''); setSupportDesc(''); setSupportSent(false); setShowSupport(true); }}
                  style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%', padding: '12px 0', background: 'white', border: 'none', cursor: 'pointer', transition: 'background .12s' }}
                  onMouseOver={function (e) { e.currentTarget.style.background = '#f0f6ff'; }}
                  onMouseOut={function (e) { e.currentTarget.style.background = 'white'; }}
                >
                  <div style={{ width: 28, height: 28, background: 'rgba(28,121,180,0.1)', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#1c79b4" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M3 18v-6a9 9 0 0 1 18 0v6"></path>
                      <path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"></path>
                    </svg>
                  </div>
                </button>
              </SidebarItemTooltip>
            ) : (
              <button
                onClick={function () { setSupportAsunto(''); setSupportDesc(''); setSupportSent(false); setShowSupport(true); }}
                style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '13px 18px', background: 'white', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', transition: 'background .12s' }}
                onMouseOver={function (e) { e.currentTarget.style.background = '#f0f6ff'; }}
                onMouseOut={function (e) { e.currentTarget.style.background = 'white'; }}
              >
                <div style={{ width: 28, height: 28, background: 'rgba(28,121,180,0.1)', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#1c79b4" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M3 18v-6a9 9 0 0 1 18 0v6"></path>
                    <path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"></path>
                  </svg>
                </div>
                <div style={{ fontSize: 12, fontWeight: 500, color: '#374151' }}>Soporte Técnico</div>
              </button>
            )}
          </div>

          {sidebarItems.map(function (item) {
            return (
              <div key={item.mod.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                {sidebarCollapsed ? (
                  <SidebarItemTooltip label={'Módulo ' + (item.idx + 1) + ': ' + item.mod.titulo}>
                    <button onClick={function () { goModule(item.mod.id); }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%', padding: '12px 0', background: item.active ? '#fafbff' : 'white', border: 'none', cursor: 'pointer', transition: 'background .12s' }}>
                      <div style={{ position: 'relative' }}>
                        <div style={{ width: 28, height: 28, background: item.active ? '#1c79b4' : '#f1f5f9', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, color: item.active ? '#c4b400' : '#94a3b8' }}>{item.idx + 1}</div>
                        {item.pct > 0 && (
                          <div style={{ position: 'absolute', bottom: -2, right: -2, width: 10, height: 10, background: item.pct === 100 ? '#22c55e' : '#c4b400', borderRadius: '50%', border: '2px solid white' }} />
                        )}
                      </div>
                    </button>
                  </SidebarItemTooltip>
                ) : (
                  <>
                  <button onClick={function () { goModule(item.mod.id); }} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, width: '100%', padding: '13px 18px', background: item.active ? '#fafbff' : 'white', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', transition: 'background .12s' }}>
                    <div style={{ width: 28, height: 28, background: item.active ? '#1c79b4' : '#f1f5f9', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, color: item.active ? '#c4b400' : '#94a3b8', flexShrink: 0, marginTop: 1 }}>{item.idx + 1}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: item.active ? 700 : 500, color: item.active ? '#1c79b4' : '#374151', lineHeight: 1.35, marginBottom: 6 }}>{item.mod.titulo}</div>
                      <div style={{ height: 3, background: '#f1f5f9', borderRadius: 2, overflow: 'hidden' }}>
                        <div style={{ height: '100%', width: item.pct + '%', background: item.pct === 100 ? '#22c55e' : '#c4b400', borderRadius: 2 }} />
                      </div>
                      <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 3 }}>{item.pct}% · {item.mod.lecciones.length} lec.{(item.mod.evaluaciones || []).length > 0 ? ' · ' + (item.mod.evaluaciones || []).length + ' eval.' : ''}{(item.mod.encuestas || []).length > 0 ? ' · ' + (item.mod.encuestas || []).length + ' enc.' : ''} · {formatDuracion(getModuleMinutes(item.mod))}</div>
                    </div>
                  </button>
                  {item.active && (
                    <>
                    {item.mod.lecciones.map(function (les) {
                      var done = !!prog[les.id];
                      var isSel = les.id === activeLes;
                      return (
                        <button key={les.id} onClick={function () { goLesson(les.id); }} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '9px 18px 9px 28px', background: isSel ? 'rgba(15,32,68,.05)' : 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
                          <div style={{ width: 20, height: 20, borderRadius: '50%', background: done ? '#22c55e' : 'transparent', border: done ? 'none' : '2px solid #d1d5db', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                            {done && <span style={{ color: 'white', fontSize: 9, fontWeight: 900 }}>✓</span>}
                          </div>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontSize: 11, fontWeight: isSel ? 700 : 400, color: isSel ? '#1c79b4' : '#6b7280', lineHeight: 1.3 }}>{les.titulo}</div>
                            <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 1 }}>{les.duracion}</div>
                          </div>
                        </button>
                      );
                    })}
                    {(item.mod.evaluaciones || []).map(function (ev) {
                      var done = !!prog[ev.id];
                      var isSel = ev.id === activeEval && view === 'quiz';
                      return (
                        <button key={ev.id} onClick={function () { goQuiz(ev.id); }} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '9px 18px 9px 28px', background: isSel ? 'rgba(196,180,0,.09)' : 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
                          <div style={{ width: 20, height: 20, borderRadius: '50%', background: done ? '#22c55e' : 'rgba(196,180,0,.18)', border: done ? 'none' : '2px solid #c4b400', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                            {done ? <span style={{ color: 'white', fontSize: 9, fontWeight: 900 }}>✓</span> : <span style={{ fontSize: 9 }}>📝</span>}
                          </div>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontSize: 11, fontWeight: isSel ? 700 : 400, color: isSel ? '#c4b400' : '#6b7280', lineHeight: 1.3 }}>{ev.titulo}</div>
                            <div style={{ fontSize: 10, color: '#c4b400', marginTop: 1, fontWeight: 600 }}>Evaluación</div>
                          </div>
                        </button>
                      );
                    })}
                    {(item.mod.encuestas || []).map(function (enc) {
                      var done = !!prog[enc.id];
                      var isSel = enc.id === activeSurvey && view === 'survey';
                      return (
                        <button key={enc.id} onClick={function () { goSurvey(enc.id); }} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '9px 18px 9px 28px', background: isSel ? 'rgba(245,166,35,.09)' : 'transparent', border: 'none', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left' }}>
                          <div style={{ width: 20, height: 20, borderRadius: '50%', background: done ? '#22c55e' : 'rgba(245,166,35,.18)', border: done ? 'none' : '2px solid #F5A623', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                            {done ? <span style={{ color: 'white', fontSize: 9, fontWeight: 900 }}>✓</span> : <span style={{ fontSize: 11 }}>⭐</span>}
                          </div>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontSize: 11, fontWeight: isSel ? 700 : 400, color: isSel ? '#F5A623' : '#6b7280', lineHeight: 1.3 }}>{enc.titulo}</div>
                            <div style={{ fontSize: 10, color: '#F5A623', marginTop: 1, fontWeight: 600 }}>Encuesta</div>
                          </div>
                        </button>
                      );
                    })}
                    </>
                  )}
                  </>
                )}
              </div>
            );
          })}

          {/* Huellitas sidebar */}
          {sidebarCollapsed ? (
            <div style={{ padding: '10px 0', display: 'flex', justifyContent: 'center' }}>
              <SidebarItemTooltip label="Huellitas en Acción">
                <button onClick={function () { window.openHuellitasModal(); }} style={{ width: 36, height: 36, background: 'linear-gradient(135deg,#1c79b4,#1e6fa3)', border: 'none', borderRadius: 9, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>🐾</button>
              </SidebarItemTooltip>
            </div>
          ) : (
            <div style={{ margin: '14px 12px 16px', padding: '14px', background: 'linear-gradient(135deg,#1c79b4,#1e6fa3)', borderRadius: 10 }}>
              <div onClick={function () { window.openHuellitasModal(); }} style={{ fontSize: 11, color: '#c4b400', fontWeight: 800, marginBottom: 5, cursor: 'pointer' }}>🐾 Huellitas en Acción</div>
              <div style={{ fontSize: 10, color: 'rgba(255,255,255,.65)', lineHeight: 1.55 }}>Cuando tú creces, ellos también ganan. Tu aprendizaje genera impacto real.</div>
            </div>
          )}

        </div>

        {/* Main */}
        <div className="sst-student-main sst-content-area" style={{ flex: 1, overflowY: 'auto', padding: 36 }}>

          {/* HOME */}
          {view === 'home' && (
            <div>
              <div style={{ marginBottom: 28 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: '#c4b400', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Bienvenido de nuevo</div>
                <h1 style={{ margin: '0 0 4px', fontSize: 26, fontWeight: 900, color: '#1c79b4' }}>{user.nombre.split(' ')[0]} 👋</h1>
                <p style={{ margin: 0, fontSize: 14, color: '#6b7280' }}>{user.empresa} · {user.cargo}</p>
              </div>

              {/* Progress card */}
              <div style={{ background: 'white', borderRadius: 14, border: '1px solid #e5e7eb', padding: '24px 28px', marginBottom: 24, display: 'flex', alignItems: 'center', gap: 24 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#374151', marginBottom: 10 }}>Progreso general del curso</div>
                  <div style={{ height: 10, background: '#f1f5f9', borderRadius: 5, overflow: 'hidden', marginBottom: 8 }}>
                    <div style={{ height: '100%', width: overallPct + '%', background: overallPct === 100 ? '#22c55e' : '#c4b400', borderRadius: 5, transition: 'width .6s' }} />
                  </div>
                  <div style={{ fontSize: 12, color: '#9ca3af' }}>{doneLessons} de {totalLessons} elementos completados</div>
                  <div style={{ fontSize: 11, color: '#1c79b4', fontWeight: 600, marginTop: 4 }}>Duración total: {formatDuracion(getTotalCourseMinutes())}</div>
                </div>
                <div style={{ textAlign: 'center', flexShrink: 0 }}>
                  <div style={{ fontSize: 42, fontWeight: 900, color: certEligible ? '#15803d' : '#1c79b4', lineHeight: 1 }}>{overallPct}%</div>
                  <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 4 }}>{certEligible ? '¡Listo para certificarte!' : overallPct === 100 ? '¡Curso completado!' : 'completado'}</div>
                  <button
                    onClick={handleCertClick}
                    title={certEligible ? 'Ver tu certificado' : 'Aún tienes pendientes por completar'}
                    style={{ marginTop: 10, background: certEligible ? '#1c79b4' : '#d1d5db', color: certEligible ? 'white' : '#9ca3af', border: 'none', borderRadius: 8, padding: '8px 16px', fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 6 }}
                  >
                    {certEligible
                      ? (<>🎓 Ver certificado</>)
                      : (<><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg> Ver certificado</>)
                    }
                  </button>
                </div>
              </div>

              {/* Module cards */}
              <div data-tour-id="tour-modules" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14, marginBottom: 28 }}>
                {modules.map(function (mod, i) {
                  var p = modPct(mod);
                  var done = mod.lecciones.filter(function (l) { return prog[l.id]; }).length + (mod.evaluaciones || []).filter(function (ev) { return prog[ev.id]; }).length + (mod.encuestas || []).filter(function (enc) { return prog[enc.id]; }).length;
                  var totalItems = mod.lecciones.length + (mod.evaluaciones || []).length + (mod.encuestas || []).length;
                  return (
                    <div key={mod.id} onClick={function () { goModule(mod.id); }} style={{ background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', padding: '20px', cursor: 'pointer', transition: 'all .18s' }}
                      onMouseOver={function (e) { e.currentTarget.style.boxShadow = '0 6px 24px rgba(15,32,68,.10)'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.borderColor = '#1c79b4'; }}
                      onMouseOut={function (e) { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = ''; e.currentTarget.style.borderColor = '#e5e7eb'; }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
                        <div style={{ width: 36, height: 36, background: p === 100 ? '#22c55e' : '#1c79b4', borderRadius: 9, display: 'flex', alignItems: 'center', justifyContent: 'center', color: p === 100 ? 'white' : '#c4b400', fontSize: 14, fontWeight: 800 }}>{p === 100 ? '✓' : i + 1}</div>
                        <span style={{ fontSize: 14, fontWeight: 800, color: p === 100 ? '#15803d' : '#1c79b4' }}>{p}%</span>
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: '#1e293b', lineHeight: 1.35, marginBottom: 10 }}>{mod.titulo}</div>
                      <div style={{ height: 4, background: '#f1f5f9', borderRadius: 2, marginBottom: 8, overflow: 'hidden' }}>
                        <div style={{ height: '100%', width: p + '%', background: p === 100 ? '#22c55e' : '#c4b400', borderRadius: 2 }} />
                      </div>
                      <div style={{ fontSize: 11, color: '#9ca3af' }}>{done}/{totalItems} elementos</div>
                    </div>
                  );
                })}
              </div>

              {/* Huellitas home banner */}
              <div onClick={function () { window.openHuellitasModal(); }} style={{ background: 'linear-gradient(135deg,#1c79b4 0%,#145580 60%,#1e6fa3 100%)', borderRadius: 14, padding: '26px 32px', display: 'flex', alignItems: 'center', gap: 24, cursor: 'pointer' }}>
                <span style={{ fontSize: 44, flexShrink: 0 }}>🐾</span>
                <div>
                  <div style={{ fontSize: 10, color: '#c4b400', fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 5 }}>Huellitas en Acción — ASSYST</div>
                  <div style={{ fontSize: 16, fontWeight: 800, color: 'white', marginBottom: 6 }}>"Cuando tú creces, ellos también ganan."</div>
                  <div style={{ fontSize: 12, color: 'rgba(255,255,255,.65)', lineHeight: 1.6 }}>Tu inscripción a este curso contribuye a alimentar y cuidar perros y gatos en condición de abandono. Cada lección que completas convierte tu aprendizaje en un acto de amor.</div>
                </div>
              </div>
            </div>
          )}

          {/* MODULE VIEW */}
          {view === 'module' && curMod && (
            <div>
              <button onClick={goHome} style={{ background: 'none', border: 'none', color: '#6b7280', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit', padding: 0, marginBottom: 20, display: 'flex', alignItems: 'center', gap: 4 }}>← Inicio</button>
              <div style={{ fontSize: 10, fontWeight: 700, color: '#c4b400', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Módulo {modules.findIndex(function (m) { return m.id === activeMod; }) + 1}</div>
              <h1 style={{ margin: '0 0 8px', fontSize: 22, fontWeight: 800, color: '#1c79b4' }}>{curMod.titulo}</h1>
              <p style={{ margin: '0 0 24px', fontSize: 14, color: '#6b7280', lineHeight: 1.6 }}>{curMod.descripcion}</p>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
                {curMod.lecciones.map(function (les, li) {
                  var done = !!prog[les.id];
                  return (
                    <div key={les.id} onClick={function () { goLesson(les.id); }} style={{ background: 'white', borderRadius: 11, border: '2px solid ' + (done ? '#bbf7d0' : '#e5e7eb'), padding: '18px', cursor: 'pointer', transition: 'all .18s' }}
                      onMouseOver={function (e) { e.currentTarget.style.borderColor = '#1c79b4'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 4px 16px rgba(15,32,68,.09)'; }}
                      onMouseOut={function (e) { e.currentTarget.style.borderColor = done ? '#bbf7d0' : '#e5e7eb'; e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = ''; }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                        <div style={{ width: 30, height: 30, background: done ? '#22c55e' : '#f1f5f9', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, color: done ? 'white' : '#94a3b8' }}>{done ? '✓' : li + 1}</div>
                        {les.videoUrl && <span style={{ fontSize: 9, fontWeight: 700, color: '#6b7280', background: '#f1f5f9', padding: '3px 8px', borderRadius: 10, textTransform: 'uppercase', letterSpacing: '0.05em' }}>VIDEO</span>}
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: '#1e293b', marginBottom: 6, lineHeight: 1.35 }}>{les.titulo}</div>
                      <div style={{ fontSize: 11, color: '#9ca3af' }}>{les.duracion}{les.docs && les.docs.length > 0 ? ' · ' + les.docs.length + ' doc(s)' : ''}</div>
                    </div>
                  );
                })}
                {(curMod.evaluaciones || []).map(function (ev) {
                  var done = !!prog[ev.id];
                  var lastRes = evalResults[ev.id];
                  return (
                    <div key={ev.id} onClick={function () { goQuiz(ev.id); }} style={{ background: done ? 'rgba(34,197,94,0.04)' : 'rgba(196,180,0,0.04)', borderRadius: 11, border: '2px solid ' + (done ? '#bbf7d0' : '#e9d96e'), padding: '18px', cursor: 'pointer', transition: 'all .18s' }}
                      onMouseOver={function (e) { e.currentTarget.style.borderColor = '#c4b400'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 4px 16px rgba(196,180,0,.14)'; }}
                      onMouseOut={function (e) { e.currentTarget.style.borderColor = done ? '#bbf7d0' : '#e9d96e'; e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = ''; }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                        <div style={{ width: 30, height: 30, background: done ? '#22c55e' : 'rgba(196,180,0,0.2)', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: done ? 13 : 16, fontWeight: 700, color: done ? 'white' : '#c4b400' }}>{done ? '✓' : '📝'}</div>
                        <span style={{ fontSize: 9, fontWeight: 700, color: '#c4b400', background: 'rgba(196,180,0,0.14)', padding: '3px 8px', borderRadius: 10, textTransform: 'uppercase', letterSpacing: '0.05em' }}>EVALUACIÓN</span>
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: '#1e293b', marginBottom: 6, lineHeight: 1.35 }}>{ev.titulo}</div>
                      <div style={{ fontSize: 11, color: '#9ca3af' }}>
                        {ev.preguntas.length} pregunta{ev.preguntas.length !== 1 ? 's' : ''} · Mín. {ev.puntajeMinimo}%
                        {lastRes && <span style={{ marginLeft: 8, fontWeight: 700, color: lastRes.aprobado ? '#15803d' : '#dc2626' }}>· Último: {lastRes.puntaje}%</span>}
                        {!prog[ev.id] && (evalAttempts[ev.id] || 0) > 0 && <span style={{ marginLeft: 8, color: (evalAttempts[ev.id] || 0) >= (ev.intentosMaximos || 3) ? '#dc2626' : '#94a3b8' }}>· {evalAttempts[ev.id]}/{ev.intentosMaximos || 3} intentos</span>}
                      </div>
                    </div>
                  );
                })}
                {(curMod.encuestas || []).map(function (enc) {
                  var done = !!prog[enc.id];
                  return (
                    <div key={enc.id} onClick={function () { goSurvey(enc.id); }} style={{ background: done ? 'rgba(34,197,94,0.04)' : 'rgba(245,166,35,0.04)', borderRadius: 11, border: '2px solid ' + (done ? '#bbf7d0' : 'rgba(245,166,35,0.45)'), padding: '18px', cursor: 'pointer', transition: 'all .18s' }}
                      onMouseOver={function (e) { e.currentTarget.style.borderColor = '#F5A623'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 4px 16px rgba(245,166,35,.18)'; }}
                      onMouseOut={function (e) { e.currentTarget.style.borderColor = done ? '#bbf7d0' : 'rgba(245,166,35,0.45)'; e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = ''; }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                        <div style={{ width: 30, height: 30, background: done ? '#22c55e' : 'rgba(245,166,35,0.18)', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: done ? 13 : 17, fontWeight: 700, color: done ? 'white' : '#F5A623' }}>{done ? '✓' : '⭐'}</div>
                        <span style={{ fontSize: 9, fontWeight: 700, color: '#0F2044', background: 'rgba(245,166,35,0.22)', padding: '3px 8px', borderRadius: 10, textTransform: 'uppercase', letterSpacing: '0.05em' }}>ENCUESTA</span>
                      </div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: '#1e293b', marginBottom: 6, lineHeight: 1.35 }}>{enc.titulo}</div>
                      <div style={{ fontSize: 11, color: done ? '#15803d' : '#9ca3af', fontWeight: done ? 600 : 400 }}>{done ? 'Completada ✓' : 'Pendiente'}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* FORUM VIEW */}
          {view === 'forum' && <ForumView user={user} />}

          {/* LESSON VIEW */}
          {view === 'lesson' && curMod && curLes && (
            <div style={{ maxWidth: 680 }}>
              <button onClick={function () { setView('module'); setActiveLes(null); }} style={{ background: 'none', border: 'none', color: '#6b7280', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit', padding: 0, marginBottom: 20, display: 'flex', alignItems: 'center', gap: 4 }}>
                ← {curMod.titulo}
              </button>
              <div style={{ fontSize: 10, fontWeight: 700, color: '#c4b400', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>
                Módulo {modules.findIndex(function (m) { return m.id === activeMod; }) + 1} · Lección {curLesIdx + 1}
              </div>
              <h1 style={{ margin: '0 0 8px', fontSize: 22, fontWeight: 800, color: '#1c79b4' }}>{curLes.titulo}</h1>
              <p style={{ margin: '0 0 24px', fontSize: 14, color: '#6b7280', lineHeight: 1.65 }}>{curLes.descripcion}</p>

              {/* Video */}
              {curLes.videoUrl ? (
                <div style={{ marginBottom: 20 }}>
                  {!videoError ? (
                    <>
                    <div className="sst-video-container" style={{ borderRadius: 12, overflow: 'hidden', background: '#000', position: 'relative', width: '100%', aspectRatio: '16/9' }}>
                      <iframe
                        key={curLes.id}
                        src={getVideoEmbed(curLes)}
                        title={curLes.titulo}
                        style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', border: 'none', display: 'block' }}
                        allow="autoplay; fullscreen; encrypted-media"
                        sandbox="allow-scripts allow-same-origin allow-presentation allow-popups"
                        allowFullScreen={true}
                        playsInline={true}
                        webkit-playsinline=""
                        onError={function () { setVideoError(true); }}
                      />
                      {/* Botón expandir ventana */}
                      <button
                        onClick={function () { setVideoModal(true); }}
                        title="Ampliar video"
                        style={{
                          position: 'absolute', top: 10, right: 10, zIndex: 10,
                          width: 34, height: 34,
                          background: 'rgba(0,0,0,0.55)',
                          border: 'none', borderRadius: 7,
                          cursor: 'pointer',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          transition: 'background 0.2s',
                          fontFamily: 'inherit',
                        }}
                        onMouseOver={function (e) { e.currentTarget.style.background = 'rgba(0,0,0,0.82)'; }}
                        onMouseOut={function (e) { e.currentTarget.style.background = 'rgba(0,0,0,0.55)'; }}
                      >
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                          <polyline points="15 3 21 3 21 9"></polyline>
                          <polyline points="9 21 3 21 3 15"></polyline>
                          <line x1="21" y1="3" x2="14" y2="10"></line>
                          <line x1="3" y1="21" x2="10" y2="14"></line>
                        </svg>
                      </button>
                    </div>

                    {/* Modal ventana ampliada */}
                    {videoModal && (
                      <div
                        onClick={function () { setVideoModal(false); }}
                        style={{
                          position: 'fixed', inset: 0, zIndex: 1000,
                          background: 'rgba(0,0,0,0.82)',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          padding: 24,
                        }}
                      >
                        <div
                          onClick={function (e) { e.stopPropagation(); }}
                          className="sst-video-container"
                          style={{
                            width: '100%', maxWidth: 960,
                            background: '#000', borderRadius: 14,
                            overflow: 'hidden', position: 'relative',
                            aspectRatio: '16/9',
                            boxShadow: '0 32px 80px rgba(0,0,0,0.6)',
                          }}
                        >
                          <iframe
                            key={'modal-' + curLes.id}
                            src={getVideoEmbed(curLes)}
                            title={curLes.titulo}
                            style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', border: 'none', display: 'block' }}
                            allow="autoplay; fullscreen; encrypted-media"
                            sandbox="allow-scripts allow-same-origin allow-presentation allow-popups"
                            allowFullScreen={true}
                            playsInline={true}
                            webkit-playsinline=""
                          />
                          <button
                            onClick={function () { setVideoModal(false); }}
                            title="Cerrar (Esc)"
                            style={{
                              position: 'absolute', top: 12, right: 12, zIndex: 10,
                              width: 36, height: 36,
                              background: 'rgba(0,0,0,0.6)',
                              border: 'none', borderRadius: 8,
                              cursor: 'pointer', color: 'white', fontSize: 18,
                              display: 'flex', alignItems: 'center', justifyContent: 'center',
                              lineHeight: 1,
                            }}
                          >✕</button>
                        </div>
                      </div>
                    )}
                    </>
                  ) : (
                    <div style={{ padding: '32px 22px', background: '#f8fafc', borderRadius: 12, textAlign: 'center', border: '2px dashed #e5e7eb' }}>
                      <div style={{ fontSize: 28, marginBottom: 8 }}>⚠️</div>
                      <div style={{ fontSize: 13, color: '#6b7280', marginBottom: 16 }}>El video no pudo cargarse dentro de la plataforma.</div>
                      <a
                        href={toDriveOpen(curLes.videoUrl)}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: '#1c79b4', color: 'white', borderRadius: 10, padding: '11px 22px', fontSize: 13, fontWeight: 700, textDecoration: 'none' }}
                      >
                        <span style={{ fontSize: 16 }}>▶</span> Abrir en Google Drive
                      </a>
                    </div>
                  )}

                </div>
              ) : (
                <div style={{ padding: '22px', background: '#f8fafc', borderRadius: 12, marginBottom: 20, textAlign: 'center', color: '#9ca3af', fontSize: 13, border: '2px dashed #e5e7eb' }}>
                  <div style={{ fontSize: 28, marginBottom: 6 }}>📹</div>
                  Video no disponible aún
                </div>
              )}

              {/* Docs */}
              {curLes.docs && curLes.docs.length > 0 && (
                <div style={{ marginBottom: 22 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 10 }}>Materiales descargables</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {curLes.docs.map(function (doc) {
                      return (
                        <a key={doc.id} href={doc.url} target="_blank" rel="noopener noreferrer" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', background: 'white', borderRadius: 10, border: '1px solid #e5e7eb', textDecoration: 'none', color: '#374151', transition: 'all .15s' }}
                          onMouseOver={function (e) { e.currentTarget.style.borderColor = '#c4b400'; e.currentTarget.style.background = '#fffbf0'; }}
                          onMouseOut={function (e) { e.currentTarget.style.borderColor = '#e5e7eb'; e.currentTarget.style.background = 'white'; }}>
                          <span style={{ fontSize: 18 }}>📎</span>
                          <span style={{ fontWeight: 600, fontSize: 13, flex: 1 }}>{doc.nombre}</span>
                          <span style={{ fontSize: 11, color: '#c4b400', fontWeight: 700 }}>↓ Descargar</span>
                        </a>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Complete */}
              <div style={{ padding: '20px 22px', background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
                {!prog[curLes.id] ? (
                  <>
                    <div style={{ flex: 1, minWidth: 200 }}>
                      <div style={{ fontWeight: 700, fontSize: 14, color: '#1e293b' }}>¿Completaste esta lección?</div>
                      <div style={{ fontSize: 12, color: '#9ca3af', marginTop: 2 }}>Márcala para llevar tu registro de avance</div>
                    </div>
                    <button onClick={function () { markDone(curLes.id); }} style={{ background: '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '12px 22px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>
                      ✓ Marcar como completada
                    </button>
                  </>
                ) : (
                  <>
                    <div style={{ width: 40, height: 40, background: '#22c55e', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontSize: 18, flexShrink: 0 }}>✓</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 700, fontSize: 14, color: '#15803d' }}>¡Lección completada!</div>
                      <div style={{ fontSize: 12, color: '#9ca3af', marginTop: 2 }}>Sigue avanzando en el módulo</div>
                    </div>
                    <button onClick={function () { markUndone(curLes.id); }} style={{ background: 'none', border: '1px solid #e5e7eb', borderRadius: 8, padding: '8px 14px', fontSize: 11, color: '#9ca3af', cursor: 'pointer', fontFamily: 'inherit' }}>Desmarcar</button>
                  </>
                )}
              </div>

              {/* ── Navegación lineal Anterior / Siguiente ── */}
              {(function() {
                var ok = !!prog[activeLes];
                return (
                  <div style={{ display: 'flex', gap: 10, marginTop: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                    {currentFlatIdx > 0 && (
                      <button
                        onClick={goPrev}
                        style={{ display: 'flex', alignItems: 'center', gap: 6, background: 'white', color: '#374151', border: '1.5px solid #d1d5db', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', transition: 'all .15s' }}
                        onMouseOver={function(e){ e.currentTarget.style.borderColor='#1c79b4'; e.currentTarget.style.color='#1c79b4'; }}
                        onMouseOut={function(e){ e.currentTarget.style.borderColor='#d1d5db'; e.currentTarget.style.color='#374151'; }}
                      >← Anterior</button>
                    )}
                    <div style={{ flex: 1 }} />
                    {!ok && (
                      <span style={{ fontSize: 11, color: '#f59e0b', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>⚠ Marca la lección como completada para continuar</span>
                    )}
                    {currentFlatIdx < courseSequence.length - 1 ? (
                      <button
                        onClick={ok ? goNext : undefined}
                        disabled={!ok}
                        title={!ok ? 'Marca la lección como completada primero' : ''}
                        style={{ display: 'flex', alignItems: 'center', gap: 6, background: ok ? '#1c79b4' : '#e5e7eb', color: ok ? 'white' : '#9ca3af', border: 'none', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 700, cursor: ok ? 'pointer' : 'not-allowed', fontFamily: 'inherit', transition: 'background .2s, color .2s' }}
                      >Siguiente →</button>
                    ) : (
                      <button
                        onClick={ok ? handleCertClick : undefined}
                        disabled={!ok}
                        style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: ok && certEligible ? '#22c55e' : ok ? '#9ca3af' : '#e5e7eb', color: ok ? 'white' : '#9ca3af', border: 'none', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 700, cursor: ok ? 'pointer' : 'not-allowed', fontFamily: 'inherit' }}
                      >🎓 Finalizar curso</button>
                    )}
                  </div>
                );
              })()}
            </div>
          )}

          {/* QUIZ VIEW */}
          {view === 'quiz' && curMod && curEval && (
            <div style={{ maxWidth: 680 }}>
              <button onClick={function () { setView('module'); setActiveEval(null); }} style={{ background: 'none', border: 'none', color: '#6b7280', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit', padding: 0, marginBottom: 20, display: 'flex', alignItems: 'center', gap: 4 }}>
                ← {curMod.titulo}
              </button>
              <div style={{ fontSize: 10, fontWeight: 700, color: '#c4b400', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>
                Evaluación · Módulo {modules.findIndex(function (m) { return m.id === activeMod; }) + 1}
              </div>
              <h1 style={{ margin: '0 0 8px', fontSize: 22, fontWeight: 800, color: '#1c79b4' }}>{curEval.titulo}</h1>
              {curEval.descripcion && <p style={{ margin: '0 0 20px', fontSize: 14, color: '#6b7280', lineHeight: 1.65 }}>{curEval.descripcion}</p>}
              <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap', padding: '12px 18px', background: 'white', borderRadius: 10, border: '1px solid #e5e7eb', marginBottom: 24, fontSize: 13, color: '#374151', alignItems: 'center' }}>
                <span>📊 Mínimo para aprobar: <strong style={{ color: '#1c79b4' }}>{curEval.puntajeMinimo}%</strong></span>
                <span>❓ {curEval.preguntas.length} pregunta{curEval.preguntas.length !== 1 ? 's' : ''}</span>
                {!prog[curEval.id] && (
                  <span>🔄 Intentos: <strong style={{ color: evalUsedAttempts >= evalMaxIntentos ? '#dc2626' : '#374151' }}>{evalUsedAttempts}/{evalMaxIntentos}</strong></span>
                )}
                {prog[curEval.id] && <span style={{ color: '#15803d', fontWeight: 700 }}>✓ Aprobada</span>}
              </div>
              {!quizResult ? (
                prog[curEval.id] ? (
                  /* ── Ya aprobada — bloqueada ── */
                  <div style={{ background: 'rgba(34,197,94,0.06)', border: '2px solid #bbf7d0', borderRadius: 14, padding: '44px 28px', textAlign: 'center' }}>
                    <div style={{ width: 72, height: 72, background: '#dcfce7', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px', fontSize: 32 }}>🏆</div>
                    <div style={{ fontSize: 18, fontWeight: 800, color: '#15803d', marginBottom: 10 }}>¡Ya aprobaste esta evaluación!</div>
                    <div style={{ fontSize: 13, color: '#6b7280', lineHeight: 1.65, maxWidth: 380, margin: '0 auto 16px' }}>Esta evaluación ya fue completada y aprobada exitosamente. No es necesario volver a realizarla.</div>
                    {evalResults[curEval.id] && (
                      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: '#dcfce7', borderRadius: 10, padding: '10px 22px', marginBottom: 24 }}>
                        <span style={{ fontSize: 26, fontWeight: 900, color: '#15803d' }}>{evalResults[curEval.id].puntaje}%</span>
                        <div style={{ textAlign: 'left' }}>
                          <div style={{ fontSize: 11, fontWeight: 700, color: '#15803d' }}>Puntaje obtenido</div>
                          <div style={{ fontSize: 11, color: '#6b7280' }}>{evalResults[curEval.id].correctas} de {evalResults[curEval.id].total} correctas</div>
                        </div>
                      </div>
                    )}
                    <div style={{ display: 'flex', justifyContent: 'center', gap: 10, flexWrap: 'wrap' }}>
                      <button onClick={function () { setView('module'); setActiveEval(null); }} style={{ background: '#22c55e', color: 'white', border: 'none', borderRadius: 10, padding: '12px 28px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                        ← Volver al módulo
                      </button>
                    </div>
                  </div>
                ) : evalAttemptsExhausted ? (
                  <div style={{ background: '#fef2f2', border: '1.5px solid #fecaca', borderRadius: 14, padding: '40px 28px', textAlign: 'center' }}>
                    <div style={{ width: 60, height: 60, background: '#fee2e2', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px', fontSize: 26 }}>🚫</div>
                    <div style={{ fontSize: 16, fontWeight: 800, color: '#dc2626', marginBottom: 10 }}>Intentos agotados</div>
                    <p style={{ margin: '0 0 24px', fontSize: 13, color: '#6b7280', lineHeight: 1.65, maxWidth: 380, marginLeft: 'auto', marginRight: 'auto' }}>Has agotado tus intentos disponibles. Contacta a soporte para solicitar una nueva oportunidad.</p>
                    <button onClick={function () { setSupportAsunto('Solicitud de nuevo intento — ' + curEval.titulo); setSupportDesc(''); setSupportSent(false); setShowSupport(true); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '12px 24px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 18v-6a9 9 0 0 1 18 0v6"></path><path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"></path></svg>
                      Solicitar nueva oportunidad
                    </button>
                  </div>
                ) : (
                <div>
                  {curEval.preguntas.length === 0 && (
                    <div style={{ textAlign: 'center', padding: '40px', color: '#9ca3af', fontSize: 14, background: 'white', borderRadius: 12, border: '1px solid #e5e7eb' }}>Esta evaluación no tiene preguntas aún.</div>
                  )}
                  {(shuffledQuestions || curEval.preguntas).map(function (q, qi) {
                    return (
                      <div key={q.id} style={{ background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', padding: '20px 22px', marginBottom: 14 }}>
                        <div style={{ fontSize: 13, fontWeight: 700, color: '#1e293b', marginBottom: 14, lineHeight: 1.5 }}>
                          <span style={{ color: '#1c79b4', marginRight: 8 }}>{qi + 1}.</span>{q.texto}
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                          {q.opciones.map(function (op) {
                            var selected = quizAnswers[q.id] === op.id;
                            return (
                              <label key={op.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 16px', borderRadius: 9, border: '1.5px solid ' + (selected ? '#1c79b4' : '#e5e7eb'), cursor: 'pointer', background: selected ? 'rgba(28,121,180,0.06)' : 'white', transition: 'all .15s', userSelect: 'none' }}>
                                <input type="radio" name={'q_' + q.id} value={op.id} checked={selected} onChange={function () { setQuizAnswers(function (a) { return Object.assign({}, a, { [q.id]: op.id }); }); }} style={{ accentColor: '#1c79b4', width: 16, height: 16, flexShrink: 0, cursor: 'pointer' }} />
                                <span style={{ fontSize: 13, color: '#374151', fontWeight: selected ? 600 : 400 }}>{op.texto}</span>
                              </label>
                            );
                          })}
                        </div>
                      </div>
                    );
                  })}
                  {curEval.preguntas.length > 0 && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 8, flexWrap: 'wrap' }}>
                      <button
                        onClick={function () { submitQuiz(curEval); }}
                        disabled={Object.keys(quizAnswers).length < curEval.preguntas.length}
                        style={{ background: Object.keys(quizAnswers).length < curEval.preguntas.length ? '#d1d5db' : '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '13px 28px', fontSize: 14, fontWeight: 700, cursor: Object.keys(quizAnswers).length < curEval.preguntas.length ? 'not-allowed' : 'pointer', fontFamily: 'inherit', transition: 'background .2s' }}
                      >
                        Enviar evaluación
                      </button>
                      {Object.keys(quizAnswers).length < curEval.preguntas.length && (
                        <span style={{ fontSize: 12, color: '#9ca3af' }}>Responde todas las preguntas ({Object.keys(quizAnswers).length}/{curEval.preguntas.length})</span>
                      )}
                    </div>
                  )}
                </div>
                )
              ) : (
                <div>
                  <div style={{ textAlign: 'center', padding: '36px 24px', background: quizResult.aprobado ? 'rgba(34,197,94,0.06)' : 'rgba(239,68,68,0.05)', borderRadius: 14, border: '2px solid ' + (quizResult.aprobado ? '#bbf7d0' : '#fecaca'), marginBottom: 24 }}>
                    <div style={{ fontSize: 56, fontWeight: 900, color: quizResult.aprobado ? '#15803d' : '#dc2626', lineHeight: 1, marginBottom: 10 }}>{quizResult.puntaje}%</div>
                    <div style={{ fontSize: 18, fontWeight: 800, color: quizResult.aprobado ? '#15803d' : '#dc2626', marginBottom: 10 }}>
                      {quizResult.aprobado ? '¡Felicitaciones, aprobaste!' : 'No aprobaste esta vez'}
                    </div>
                    <div style={{ fontSize: 13, color: '#6b7280' }}>
                      {quizResult.correctas} de {quizResult.total} correctas · Mínimo requerido: {curEval.puntajeMinimo}%
                    </div>
                  </div>
                  {curEval.mostrarRespuestas !== false && <div style={{ marginBottom: 24 }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: 12 }}>Detalle por pregunta</div>
                    {(shuffledQuestions || curEval.preguntas).map(function (q, qi) {
                      var selectedId = quizAnswers[q.id];
                      var correctOp = q.opciones.find(function (o) { return o.correcta; });
                      var isCorrect = selectedId && correctOp && selectedId === correctOp.id;
                      var selectedOp = q.opciones.find(function (o) { return o.id === selectedId; });
                      return (
                        <div key={q.id} style={{ padding: '14px 18px', borderRadius: 10, marginBottom: 8, border: '1.5px solid ' + (isCorrect ? '#bbf7d0' : '#fecaca'), background: isCorrect ? 'rgba(34,197,94,0.04)' : 'rgba(239,68,68,0.04)' }}>
                          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: isCorrect ? 0 : 8 }}>
                            <span style={{ fontSize: 14, flexShrink: 0 }}>{isCorrect ? '✅' : '❌'}</span>
                            <div style={{ fontSize: 13, color: '#1e293b', fontWeight: 600, flex: 1, lineHeight: 1.4 }}>{qi + 1}. {q.texto}</div>
                          </div>
                          {!isCorrect && (
                            <div style={{ marginLeft: 24 }}>
                              {selectedOp && <div style={{ fontSize: 12, color: '#dc2626', marginBottom: 4 }}>Tu respuesta: {selectedOp.texto}</div>}
                              <div style={{ fontSize: 12, color: '#15803d', fontWeight: 600 }}>Respuesta correcta: {correctOp ? correctOp.texto : '—'}</div>
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>}
                  <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                    {quizResult.aprobado ? (
                      <>
                        <button onClick={function () { setView('module'); setActiveEval(null); }} style={{ background: '#22c55e', color: 'white', border: 'none', borderRadius: 10, padding: '12px 24px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                          Volver al módulo ✓
                        </button>
                        {modules.findIndex(function(m) { return m.id === activeMod; }) === modules.length - 1 && (
                          <button onClick={handleCertClick} title={certEligible ? 'Obtener certificado' : 'Aún tienes pendientes'} style={{ background: certEligible ? '#1c79b4' : '#9ca3af', color: 'white', border: 'none', borderRadius: 10, padding: '12px 24px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 7 }}>
                            {certEligible
                              ? (<><span>🎓</span> Finalizar curso</>)
                              : (<><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg> Finalizar curso</>)
                            }
                          </button>
                        )}
                      </>
                    ) : evalAttemptsExhausted ? (
                      <div>
                        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, background: '#fef2f2', border: '1.5px solid #fecaca', borderRadius: 10, padding: '14px 18px', marginBottom: 14 }}>
                          <span style={{ fontSize: 18, flexShrink: 0, marginTop: 1 }}>🚫</span>
                          <p style={{ margin: 0, fontSize: 13, color: '#6b7280', lineHeight: 1.55 }}>Has agotado tus intentos disponibles. Contacta a soporte para solicitar una nueva oportunidad.</p>
                        </div>
                        <button onClick={function () { setSupportAsunto('Solicitud de nuevo intento — ' + curEval.titulo); setSupportDesc(''); setSupportSent(false); setShowSupport(true); }} style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '12px 22px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 18v-6a9 9 0 0 1 18 0v6"></path><path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"></path></svg>
                          Solicitar nueva oportunidad
                        </button>
                      </div>
                    ) : (
                      <button onClick={function () { setQuizAnswers({}); setQuizResult(null); applyQuizShuffle(curEval); }} style={{ background: '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '12px 24px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                        Intentar de nuevo
                      </button>
                    )}
                    <button onClick={function () { setView('module'); setActiveEval(null); }} style={{ background: 'none', border: '1px solid #e5e7eb', borderRadius: 10, padding: '12px 24px', fontSize: 13, color: '#6b7280', cursor: 'pointer', fontFamily: 'inherit' }}>
                      Volver al módulo
                    </button>
                  </div>
                </div>
              )}

              {/* ── Navegación lineal Anterior / Siguiente ── */}
              {(function() {
                var ok = !!(quizResult || prog[activeEval] || evalAttemptsExhausted);
                var passed = !!(prog[activeEval] || (quizResult && quizResult.aprobado));
                return (
                  <div style={{ display: 'flex', gap: 10, marginTop: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                    {currentFlatIdx > 0 && (
                      <button
                        onClick={goPrev}
                        style={{ display: 'flex', alignItems: 'center', gap: 6, background: 'white', color: '#374151', border: '1.5px solid #d1d5db', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', transition: 'all .15s' }}
                        onMouseOver={function(e){ e.currentTarget.style.borderColor='#1c79b4'; e.currentTarget.style.color='#1c79b4'; }}
                        onMouseOut={function(e){ e.currentTarget.style.borderColor='#d1d5db'; e.currentTarget.style.color='#374151'; }}
                      >← Anterior</button>
                    )}
                    <div style={{ flex: 1 }} />
                    {!ok && (
                      <span style={{ fontSize: 11, color: '#f59e0b', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>⚠ Realiza la evaluación para continuar</span>
                    )}
                    {currentFlatIdx < courseSequence.length - 1 ? (
                      passed ? (
                        <button
                          onClick={goNext}
                          style={{ display: 'flex', alignItems: 'center', gap: 6, background: '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', transition: 'background .2s, color .2s' }}
                        >Siguiente →</button>
                      ) : null
                    ) : (
                      <button
                        onClick={ok ? handleCertClick : undefined}
                        disabled={!ok}
                        style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: ok && certEligible ? '#22c55e' : ok ? '#9ca3af' : '#e5e7eb', color: ok ? 'white' : '#9ca3af', border: 'none', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 700, cursor: ok ? 'pointer' : 'not-allowed', fontFamily: 'inherit' }}
                      >🎓 Finalizar curso</button>
                    )}
                  </div>
                );
              })()}
            </div>
          )}

          {/* SURVEY VIEW */}
          {view === 'survey' && curMod && curSurvey && (
            <div style={{ maxWidth: 680 }}>
              <button onClick={function () { setView('module'); setActiveSurvey(null); }} style={{ background: 'none', border: 'none', color: '#6b7280', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit', padding: 0, marginBottom: 20, display: 'flex', alignItems: 'center', gap: 4 }}>
                ← {curMod.titulo}
              </button>
              <div style={{ fontSize: 10, fontWeight: 700, color: '#F5A623', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>
                Encuesta · Módulo {modules.findIndex(function (m) { return m.id === activeMod; }) + 1}
              </div>
              <h1 style={{ margin: '0 0 32px', fontSize: 22, fontWeight: 800, color: '#0F2044' }}>{curSurvey.titulo}</h1>

              <div style={{ background: 'white', borderRadius: 16, border: '1.5px solid rgba(245,166,35,0.35)', padding: '44px 36px', textAlign: 'center', marginBottom: 20 }}>
                <div style={{ width: 72, height: 72, background: 'rgba(245,166,35,0.1)', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 22px', fontSize: 34 }}>⭐</div>
                <h2 style={{ margin: '0 0 10px', fontSize: 17, fontWeight: 800, color: '#0F2044' }}>{curSurvey.titulo}</h2>
                <p style={{ margin: '0 0 32px', fontSize: 13, color: '#6b7280', lineHeight: 1.7, maxWidth: 400, marginLeft: 'auto', marginRight: 'auto' }}>Tu opinión es muy importante para nosotros. Completa esta encuesta de satisfacción y luego márcala como completada para registrar tu avance.</p>
                {curSurvey.formUrl ? (
                  <a
                    href={curSurvey.formUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: '#F5A623', color: '#0F2044', borderRadius: 12, padding: '16px 36px', fontSize: 15, fontWeight: 800, textDecoration: 'none', boxShadow: '0 4px 18px rgba(245,166,35,.32)', letterSpacing: '0.01em' }}
                    onMouseOver={function (e) { e.currentTarget.style.background = '#d9911e'; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 8px 24px rgba(245,166,35,.45)'; }}
                    onMouseOut={function (e) { e.currentTarget.style.background = '#F5A623'; e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = '0 4px 18px rgba(245,166,35,.32)'; }}
                  >
                    Responder encuesta →
                  </a>
                ) : (
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: '#f1f5f9', color: '#9ca3af', borderRadius: 12, padding: '16px 32px', fontSize: 14, fontWeight: 600 }}>Encuesta no disponible aún</div>
                )}
              </div>

              <div style={{ padding: '20px 22px', background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
                {!prog[curSurvey.id] ? (
                  <>
                    <div style={{ flex: 1, minWidth: 200 }}>
                      <div style={{ fontWeight: 700, fontSize: 14, color: '#1e293b' }}>¿Ya respondiste la encuesta?</div>
                      <div style={{ fontSize: 12, color: '#9ca3af', marginTop: 2 }}>Márcala como completada para registrar tu avance</div>
                    </div>
                    <button onClick={function () { markDone(curSurvey.id); }} style={{ background: '#F5A623', color: '#0F2044', border: 'none', borderRadius: 10, padding: '12px 22px', fontSize: 13, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>
                      Encuesta completada ✓
                    </button>
                  </>
                ) : (
                  <>
                    <div style={{ width: 40, height: 40, background: '#22c55e', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontSize: 18, flexShrink: 0 }}>✓</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 700, fontSize: 14, color: '#15803d' }}>¡Encuesta completada!</div>
                      <div style={{ fontSize: 12, color: '#9ca3af', marginTop: 2 }}>Gracias por tu participación</div>
                    </div>
                    <button onClick={function () { markUndone(curSurvey.id); }} style={{ background: 'none', border: '1px solid #e5e7eb', borderRadius: 8, padding: '8px 14px', fontSize: 11, color: '#9ca3af', cursor: 'pointer', fontFamily: 'inherit' }}>Desmarcar</button>
                  </>
                )}
              </div>

              {(function() {
                var ok = !!prog[curSurvey.id];
                return (
                  <div style={{ display: 'flex', gap: 10, marginTop: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                    {currentFlatIdx > 0 && (
                      <button onClick={goPrev}
                        style={{ display: 'flex', alignItems: 'center', gap: 6, background: 'white', color: '#374151', border: '1.5px solid #d1d5db', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
                        onMouseOver={function(e){ e.currentTarget.style.borderColor='#1c79b4'; e.currentTarget.style.color='#1c79b4'; }}
                        onMouseOut={function(e){ e.currentTarget.style.borderColor='#d1d5db'; e.currentTarget.style.color='#374151'; }}
                      >← Anterior</button>
                    )}
                    <div style={{ flex: 1 }} />
                    {!ok && <span style={{ fontSize: 11, color: '#f59e0b', fontWeight: 600 }}>⚠ Completa la encuesta para continuar</span>}
                    {currentFlatIdx < courseSequence.length - 1 ? (
                      <button onClick={ok ? goNext : undefined} disabled={!ok}
                        style={{ background: ok ? '#1c79b4' : '#e5e7eb', color: ok ? 'white' : '#9ca3af', border: 'none', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 700, cursor: ok ? 'pointer' : 'not-allowed', fontFamily: 'inherit' }}
                      >Siguiente →</button>
                    ) : (
                      <button onClick={ok ? handleCertClick : undefined} disabled={!ok}
                        style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: ok && certEligible ? '#22c55e' : ok ? '#9ca3af' : '#e5e7eb', color: ok ? 'white' : '#9ca3af', border: 'none', borderRadius: 10, padding: '10px 18px', fontSize: 13, fontWeight: 700, cursor: ok ? 'pointer' : 'not-allowed', fontFamily: 'inherit' }}
                      >🎓 Finalizar curso</button>
                    )}
                  </div>
                );
              })()}
            </div>
          )}
        </div>
      </div>
    </div>
    {/* Modal Soporte Técnico */}
    {showSupport && (
      <div
        onClick={function () { setShowSupport(false); }}
        style={{ position: 'fixed', inset: 0, background: 'rgba(15,32,68,.45)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, fontFamily: "'Montserrat',sans-serif" }}
      >
        <div
          onClick={function (e) { e.stopPropagation(); }}
          style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 480, boxShadow: '0 24px 64px rgba(0,0,0,.22)', overflow: 'hidden' }}
        >
          {/* Cabecera */}
          <div style={{ background: '#1c79b4', padding: '20px 28px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 10, color: '#c4b400', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>ASSYST — Plataforma SG-SST</div>
              <div style={{ fontSize: 16, fontWeight: 800, color: 'white' }}>Soporte Técnico</div>
            </div>
            <button
              onClick={function () { setShowSupport(false); }}
              style={{ background: 'rgba(255,255,255,.15)', border: 'none', borderRadius: 8, width: 34, height: 34, cursor: 'pointer', color: 'white', fontSize: 18, display: 'flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1 }}
            >✕</button>
          </div>

          {/* Cuerpo */}
          <div style={{ padding: '28px 28px 32px' }}>
            {!supportSent ? (
              <>
                <p style={{ margin: '0 0 22px', fontSize: 13, color: '#6b7280', lineHeight: 1.6 }}>Describe el inconveniente que estás experimentando. El equipo de soporte te responderá a la brevedad.</p>
                <form onSubmit={handleSupportSubmit}>
                  <div style={{ marginBottom: 18 }}>
                    <label style={{ fontSize: 11, fontWeight: 700, color: '#374151', textTransform: 'uppercase', letterSpacing: '0.07em', display: 'block', marginBottom: 7 }}>Asunto <span style={{ color: '#ef4444' }}>*</span></label>
                    <input
                      type="text"
                      value={supportAsunto}
                      onChange={function (e) { setSupportAsunto(e.target.value); }}
                      placeholder="Ej: No puedo reproducir el video del Módulo 2"
                      required
                      maxLength={120}
                      style={{ width: '100%', border: '1.5px solid #e5e7eb', borderRadius: 9, padding: '11px 14px', fontSize: 13, fontFamily: 'inherit', outline: 'none', color: '#1e293b', boxSizing: 'border-box' }}
                      onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                      onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
                    />
                  </div>
                  <div style={{ marginBottom: 24 }}>
                    <label style={{ fontSize: 11, fontWeight: 700, color: '#374151', textTransform: 'uppercase', letterSpacing: '0.07em', display: 'block', marginBottom: 7 }}>Descripción <span style={{ color: '#ef4444' }}>*</span></label>
                    <textarea
                      value={supportDesc}
                      onChange={function (e) { setSupportDesc(e.target.value); }}
                      placeholder="Describe con detalle el problema: qué pasó, en qué lección, qué navegador usas..."
                      required
                      rows={5}
                      style={{ width: '100%', border: '1.5px solid #e5e7eb', borderRadius: 9, padding: '11px 14px', fontSize: 13, fontFamily: 'inherit', outline: 'none', color: '#1e293b', resize: 'vertical', boxSizing: 'border-box', lineHeight: 1.6 }}
                      onFocus={function (e) { e.target.style.borderColor = '#1c79b4'; }}
                      onBlur={function (e) { e.target.style.borderColor = '#e5e7eb'; }}
                    />
                  </div>
                  <button
                    type="submit"
                    style={{ width: '100%', background: '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '13px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}
                    onMouseOver={function (e) { e.currentTarget.style.background = '#1565c0'; }}
                    onMouseOut={function (e) { e.currentTarget.style.background = '#1c79b4'; }}
                  >Enviar solicitud</button>
                </form>
              </>
            ) : (
              <div style={{ textAlign: 'center', padding: '12px 0 8px' }}>
                <div style={{ width: 64, height: 64, background: '#dcfce7', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#15803d" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="20 6 9 17 4 12"></polyline>
                  </svg>
                </div>
                <h3 style={{ margin: '0 0 10px', fontSize: 18, fontWeight: 800, color: '#15803d' }}>¡Solicitud enviada!</h3>
                <p style={{ margin: '0 0 26px', fontSize: 13, color: '#6b7280', lineHeight: 1.65 }}>Tu solicitud fue enviada. El equipo de soporte te responderá pronto.</p>
                <button
                  onClick={function () { setShowSupport(false); setSupportSent(false); }}
                  style={{ background: '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '12px 32px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}
                >Cerrar</button>
              </div>
            )}
          </div>
        </div>
      </div>
    )}
    {showCertBlock && (
      <div onClick={function () { setShowCertBlock(false); }} style={{ position: 'fixed', inset: 0, background: 'rgba(15,32,68,.58)', zIndex: 1100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, fontFamily: "'Montserrat',sans-serif" }}>
        <div onClick={function (e) { e.stopPropagation(); }} style={{ background: 'white', borderRadius: 18, width: '100%', maxWidth: 520, boxShadow: '0 32px 80px rgba(0,0,0,.30)', overflow: 'hidden' }}>

          {/* Cabecera */}
          <div style={{ background: 'linear-gradient(135deg,#d97706 0%,#b45309 100%)', padding: '22px 28px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 46, height: 46, background: 'rgba(255,255,255,.18)', borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
              </div>
              <div>
                <div style={{ fontSize: 10, color: 'rgba(255,255,255,.75)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Certificado bloqueado</div>
                <div style={{ fontSize: 16, fontWeight: 800, color: 'white', lineHeight: 1.25 }}>Aún no puedes obtener tu certificado</div>
              </div>
            </div>
            <button onClick={function () { setShowCertBlock(false); }} style={{ background: 'rgba(255,255,255,.18)', border: 'none', borderRadius: 8, width: 32, height: 32, cursor: 'pointer', color: 'white', fontSize: 17, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, lineHeight: 1 }}>✕</button>
          </div>

          {/* Cuerpo */}
          <div style={{ padding: '24px 28px 28px' }}>
            <p style={{ margin: '0 0 16px', fontSize: 13, color: '#6b7280', lineHeight: 1.65 }}>Para recibir tu certificado debes completar lo siguiente:</p>

            {/* Lista de pendientes */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 24, maxHeight: 272, overflowY: 'auto' }}>
              {getPendingItems().map(function(item, idx) {
                var isLesson = item.type === 'lesson';
                var isSurvey = item.type === 'survey';
                var bgColor   = isLesson ? '#fffbf0' : isSurvey ? 'rgba(245,166,35,0.05)' : 'rgba(196,180,0,0.05)';
                var borderColor = isLesson ? '#fde68a' : isSurvey ? 'rgba(245,166,35,0.45)' : '#e9d96e';
                var iconBg    = isLesson ? '#fef3c7' : isSurvey ? 'rgba(245,166,35,0.18)' : 'rgba(196,180,0,0.18)';
                var typeLabel = isLesson ? 'Lección' : isSurvey ? 'Encuesta' : 'Evaluación';
                var statusLabel = isLesson ? 'Sin completar' : isSurvey ? 'Sin responder' : 'No aprobada';
                var statusColor = isLesson ? '#d97706' : isSurvey ? '#b87800' : '#b45309';
                return (
                  <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', background: bgColor, borderRadius: 10, border: '1.5px solid ' + borderColor }}>
                    <div style={{ width: 28, height: 28, borderRadius: 7, background: iconBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 13 }}>
                      {isLesson
                        ? <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#d97706" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                        : isSurvey ? <span>⭐</span>
                        : <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#b45309" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>
                      }
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 700, color: '#374151', lineHeight: 1.35 }}>
                        Módulo {item.modIdx} — {typeLabel}: {item.titulo}
                      </div>
                      <div style={{ fontSize: 11, marginTop: 2, fontWeight: 600, color: statusColor }}>
                        {statusLabel}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Botones de acción */}
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <button
                onClick={goToFirstPending}
                style={{ flex: 1, minWidth: 140, background: '#1c79b4', color: 'white', border: 'none', borderRadius: 10, padding: '13px 18px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}
                onMouseOver={function(e) { e.currentTarget.style.background = '#1565c0'; }}
                onMouseOut={function(e) { e.currentTarget.style.background = '#1c79b4'; }}
              >
                Ir a completar →
              </button>
              <button
                onClick={function() { setShowCertBlock(false); setSupportAsunto('Consulta sobre mi certificado'); setSupportDesc(''); setSupportSent(false); setShowSupport(true); }}
                style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'white', color: '#374151', border: '1.5px solid #e5e7eb', borderRadius: 10, padding: '13px 18px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
                onMouseOver={function(e) { e.currentTarget.style.background = '#f8fafc'; }}
                onMouseOut={function(e) { e.currentTarget.style.background = 'white'; }}
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#1c79b4" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 18v-6a9 9 0 0 1 18 0v6"></path><path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"></path></svg>
                Contactar soporte
              </button>
            </div>
          </div>
        </div>
      </div>
    )}
    {showProfile && <ProfileModal user={user} onClose={function () { setShowProfile(false); }} onPhotoChange={function () { setPhotoVer(function (v) { return v + 1; }); }} />}
    {showBio && <BibliografiaModal onClose={function () { setShowBio(false); }} />}
    {showCert && <CertificateOverlay user={user} onClose={function () { setShowCert(false); }} />}
    {showTour && <GuidedTour userId={user.id} onFinish={function () { setShowTour(false); }} />}
    </>
    </window.PhotoVersionContext.Provider>
  );
}

window.StudentView = StudentView;
