const { useState: useStateAS, useEffect: useEffectAS, useRef: useRefAS } = React;

function AdminShell({ user, onLogout }) {
  const [tab, setTab] = useStateAS('dashboard');
  const [tick, setTick] = useStateAS(0);
  const [currentUser, setCurrentUser] = useStateAS(user);
  const [photoVer, setPhotoVer] = useStateAS(0);
  const [profileOpen, setProfileOpen] = useStateAS(false);
  const profileMenuRef = useRefAS(null);
  // Versión global de foto — se incrementa con CUALQUIER cambio de foto en la app
  const [globalPhotoVer, setGlobalPhotoVer] = useStateAS(0);

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

  // Escuchar sst:photo_changed desde cualquier componente
  useEffectAS(function () {
    function onAnyPhoto() { setGlobalPhotoVer(function (v) { return v + 1; }); }
    window.addEventListener('sst:photo_changed', onAnyPhoto);
    return function () { window.removeEventListener('sst:photo_changed', onAnyPhoto); };
  }, []);

  // Refresca datos cuando cambia localStorage desde otra pestaña/sesión
  useEffectAS(function () {
    function onStorage(e) {
      if (e.key && e.key.startsWith('sst_')) {
        setTick(function (t) { return t + 1; });
      }
    }
    window.addEventListener('storage', onStorage);
    return function () { window.removeEventListener('storage', onStorage); };
  }, []);

  // Refresca datos cada vez que el admin cambia de tab
  useEffectAS(function () {
    setTick(function (t) { return t + 1; });
  }, [tab]);

  // Polling cada 5 segundos para capturar cambios en la misma pestaña
  useEffectAS(function () {
    var interval = setInterval(function () {
      setTick(function (t) { return t + 1; });
    }, 5000);
    return function () { clearInterval(interval); };
  }, []);

  var modules = getModules();
  var users = getUsers();
  var students = users.filter(function (u) {return u.rol === 'estudiante';});
  var activeStudents = students.filter(function (u) {return u.activo;});
  var totalLessons = modules.reduce(function (a, m) {return a + m.lecciones.length;}, 0);
  var avgProg = students.length > 0 ? Math.round(
    students.reduce(function (a, s) {
      var prog = getProgress(s.id);
      var done = modules.reduce(function (b, m) {return b + m.lecciones.filter(function (l) {return prog[l.id];}).length;}, 0);
      return a + (totalLessons > 0 ? done / totalLessons * 100 : 0);
    }, 0) / students.length
  ) : 0;

  const [mobileMenu, setMobileMenu] = useStateAS(false);

  var navItems = [
  { id: 'dashboard', label: 'Dashboard', icon: '◈' },
  { id: 'homepage', label: 'Página de Inicio', icon: '⊞' },
  { id: 'forum', label: 'Foro', icon: '◉' },
  { id: 'content', label: 'Contenido', icon: '▤' },
  { id: 'students', label: 'Estudiantes', icon: '◎' },
  { id: 'progress', label: 'Progreso', icon: '▦' },
  { id: 'biblio', label: 'Bibliografía', icon: '◑' },
  { id: 'soporte', label: 'Soporte', icon: '◐' },
  { id: 'cert-config', label: 'Certificado', icon: '◆' }];


  var statCards = [
  { label: 'Módulos', value: modules.length, sub: 'en el curso', color: '#1c79b4' },
  { label: 'Lecciones', value: totalLessons, sub: 'contenido total', color: '#1e6fa3' },
  { label: 'Estudiantes activos', value: activeStudents.length, sub: 'de ' + students.length + ' totales', color: '#1c79b4' },
  { label: 'Progreso promedio', value: avgProg + '%', sub: 'del grupo', color: avgProg >= 70 ? '#15803d' : '#d97706' }];


  return (
    <window.PhotoVersionContext.Provider value={globalPhotoVer}>
    <div style={{ display: 'flex', minHeight: '100vh', background: '#EEF2F7', fontFamily: "'Montserrat',sans-serif" }}>

      {/* Mobile overlay */}
      <div className={'sst-admin-overlay' + (mobileMenu ? ' open' : '')} onClick={function () { setMobileMenu(false); }} />

      {/* Sidebar */}
      <div className={'sst-admin-sidebar' + (mobileMenu ? ' open' : '')} style={{ width: 240, background: '#1c79b4', display: 'flex', flexDirection: 'column', position: 'fixed', top: 0, left: 0, bottom: 0, zIndex: 100 }}>
        {/* Logo */}
        <div style={{ padding: '18px 16px 16px', borderBottom: '1px solid rgba(255,255,255,.12)', display: 'flex', flexDirection: 'column', alignItems: 'center', background: 'white' }}>
          <img src={(window.__resources && window.__resources.logoAssyst) || "uploads/LOGO.png"} alt="ASSYST" style={{ width: 72, height: 72, objectFit: 'contain', marginBottom: 6 }} />
          <div style={{ fontSize: 9, color: '#1c79b4', textTransform: 'uppercase', letterSpacing: '0.1em', textAlign: 'center', fontWeight: 700 }}>Panel de Administración</div>
        </div>

        {/* Nav */}
        <nav style={{ flex: 1, padding: '14px 10px' }}>
          {navItems.map(function (item) {
            var active = tab === item.id;
            return (
              <button key={item.id} onClick={function () {setTab(item.id); setMobileMenu(false);}} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '11px 14px', borderRadius: 9, border: 'none', cursor: 'pointer', fontFamily: 'inherit', background: active ? 'rgba(196,180,0,.15)' : 'transparent', color: active ? '#c4b400' : 'rgba(255,255,255,.6)', fontWeight: active ? 700 : 400, fontSize: 13, marginBottom: 3, textAlign: 'left', transition: 'all .15s', borderLeft: active ? '2px solid #c4b400' : '2px solid transparent' }}>
                <span style={{ fontSize: 15, width: 18, textAlign: 'center' }}>{item.icon}</span>
                {item.label}
              </button>);

          })}
        </nav>

        {/* Huellitas mini */}
        <div onClick={function () { window.openHuellitasModal(); }} style={{ margin: '0 10px 10px', padding: '13px 14px', background: 'rgba(196,180,0,.08)', borderRadius: 10, borderLeft: '2px solid rgba(196,180,0,.5)', cursor: 'pointer' }}>
          <div style={{ fontSize: 11, color: '#c4b400', fontWeight: 700, marginBottom: 4 }}>🐾 Huellitas en Acción</div>
          <div style={{ fontSize: 10, color: 'rgba(255,255,255,.45)', lineHeight: 1.5 }}>Cada estudiante activo genera un impacto.</div>
        </div>


      </div>

      {/* Main area */}
      <div className="sst-admin-main" style={{ marginLeft: 240, flex: 1, display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
        {/* Top bar */}
        <div className="sst-admin-topbar" style={{ background: 'white', borderBottom: '1px solid #e5e7eb', padding: '0 32px', height: 60, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button className="sst-hamburger" onClick={function () { setMobileMenu(function (v) { return !v; }); }} style={{ display: 'none', alignItems: 'center', justifyContent: 'center', width: 36, height: 36, background: 'none', border: '1.5px solid #e5e7eb', borderRadius: 8, cursor: 'pointer', padding: 0 }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#1c79b4" 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>
            <h1 style={{ margin: 0, fontSize: 18, fontWeight: 800, color: '#1c79b4' }}>{tab === 'profile' ? 'Mi Perfil' : (navItems.find(function (n) { return n.id === tab; }) || { label: '' }).label}</h1>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div className="sst-topbar-date" style={{ fontSize: 12, color: '#9ca3af' }}>{new Date().toLocaleDateString('es-CO', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</div>
            <NotificationBell role="admin" darkBg={false} />

            {/* Admin profile button */}
            <div ref={profileMenuRef} style={{ position: 'relative' }}>
              <button
                onClick={function () { setProfileOpen(function (v) { return !v; }); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 8,
                  background: profileOpen ? '#eef2f7' : 'transparent',
                  border: '1px solid',
                  borderColor: profileOpen ? '#d1d5db' : 'transparent',
                  borderRadius: 9, padding: '4px 10px 4px 5px',
                  cursor: 'pointer', fontFamily: 'inherit',
                  transition: 'all .15s',
                }}
                onMouseOver={function (e) { e.currentTarget.style.background = '#eef2f7'; e.currentTarget.style.borderColor = '#d1d5db'; }}
                onMouseOut={function (e) { if (!profileOpen) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.borderColor = 'transparent'; } }}
              >
                <StudentAvatar key={photoVer} userId={currentUser.id} userName={currentUser.nombre} size={30} style={{ border: '2px solid #e5e7eb', flexShrink: 0 }} />
                <div style={{ textAlign: 'left' }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: '#1e293b', whiteSpace: 'nowrap', lineHeight: 1.3 }}>{currentUser.nombre.split(' ').slice(0, 2).join(' ')}</div>
                  <div style={{ fontSize: 9.5, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', lineHeight: 1.3 }}>Administrador</div>
                </div>
                {/* chevron */}
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#9ca3af" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 2, transition: 'transform .2s', transform: profileOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}>
                  <polyline points="6 9 12 15 18 9" />
                </svg>
              </button>

              {/* Dropdown */}
              {profileOpen && (
                <div style={{
                  position: 'absolute', top: 'calc(100% + 8px)', right: 0,
                  background: 'white', borderRadius: 12,
                  boxShadow: '0 16px 48px rgba(15,32,68,.16), 0 4px 12px rgba(0,0,0,.07)',
                  border: '1px solid #e5e7eb',
                  minWidth: 188, overflow: 'hidden', zIndex: 700,
                  fontFamily: "'Montserrat', sans-serif",
                }}>
                  {/* Header */}
                  <div style={{ padding: '12px 14px 10px', borderBottom: '1px solid #f1f5f9', display: 'flex', alignItems: 'center', gap: 10 }}>
                    <StudentAvatar key={photoVer} userId={currentUser.id} userName={currentUser.nombre} size={36} style={{ border: '2px solid #e5e7eb', flexShrink: 0 }} />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: '#1e293b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{currentUser.nombre}</div>
                      <div style={{ fontSize: 10, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 1 }}>Administrador</div>
                    </div>
                  </div>

                  {/* Opciones */}
                  <div style={{ padding: '6px 0' }}>
                    <button
                      onClick={function () { setProfileOpen(false); setTab('profile'); }}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 10,
                        width: '100%', padding: '9px 14px',
                        background: 'none', border: 'none',
                        cursor: 'pointer', fontFamily: 'inherit',
                        fontSize: 13, fontWeight: 600, color: '#1e293b',
                        transition: 'background .12s', textAlign: 'left',
                      }}
                      onMouseOver={function (e) { e.currentTarget.style.background = '#f8fafc'; }}
                      onMouseOut={function (e) { e.currentTarget.style.background = 'none'; }}
                    >
                      <span style={{ width: 28, height: 28, background: '#eef2f7', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#1c79b4" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                      </span>
                      Mi Perfil
                    </button>

                    <div style={{ height: 1, background: '#f1f5f9', margin: '4px 0' }} />

                    <button
                      onClick={function () { setProfileOpen(false); onLogout(); }}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 10,
                        width: '100%', padding: '9px 14px',
                        background: 'none', border: 'none',
                        cursor: 'pointer', fontFamily: 'inherit',
                        fontSize: 13, fontWeight: 600, color: '#ef4444',
                        transition: 'background .12s', textAlign: 'left',
                      }}
                      onMouseOver={function (e) { e.currentTarget.style.background = '#fef2f2'; }}
                      onMouseOut={function (e) { e.currentTarget.style.background = 'none'; }}
                    >
                      <span style={{ width: 28, height: 28, background: '#fef2f2', borderRadius: 7, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#ef4444" 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>
                      </span>
                      Cerrar sesión
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="sst-content-area" style={{ padding: 32, flex: 1 }}>
          {tab === 'dashboard' &&
          <div>
              {/* Stat cards */}
              <div className="sst-stat-cards" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
                {statCards.map(function (c) {
                return (
                  <div key={c.label} style={{ background: 'white', borderRadius: 12, padding: '20px 22px', border: '1px solid #e5e7eb' }}>
                      <div style={{ fontSize: 30, fontWeight: 900, color: c.color, lineHeight: 1, marginBottom: 6 }}>{c.value}</div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: '#1e293b' }}>{c.label}</div>
                      <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 3 }}>{c.sub}</div>
                    </div>);

              })}
              </div>

              {/* Two columns */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
                {/* Módulos */}
                <div style={{ background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', padding: '22px' }}>
                  <h3 style={{ margin: '0 0 16px', fontSize: 14, fontWeight: 700, color: '#1c79b4' }}>Módulos del curso</h3>
                  {modules.map(function (m, i) {
                  return (
                    <div key={m.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: i < modules.length - 1 ? '1px solid #f9fafb' : 'none' }}>
                        <div style={{ width: 28, height: 28, background: '#c4b400', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 800, color: '#1c79b4', flexShrink: 0 }}>{i + 1}</div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 12, fontWeight: 600, color: '#1e293b', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.titulo}</div>
                          <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 1 }}>{m.lecciones.length} lecciones</div>
                        </div>
                      </div>);

                })}
                </div>

                {/* Estudiantes */}
                <div style={{ background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', padding: '22px' }}>
                  <h3 style={{ margin: '0 0 16px', fontSize: 14, fontWeight: 700, color: '#1c79b4' }}>Progreso del grupo</h3>
                  {students.map(function (s) {
                  var prog = getProgress(s.id);
                  var done = modules.reduce(function (a, m) {return a + m.lecciones.filter(function (l) {return prog[l.id];}).length;}, 0);
                  var p = totalLessons > 0 ? Math.round(done / totalLessons * 100) : 0;
                  return (
                    <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 0', borderBottom: '1px solid #f9fafb' }}>
                        <StudentAvatar userId={s.id} userName={s.nombre} size={30} style={{ flexShrink: 0, border: '1.5px solid #e5e7eb' }} />
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 12, fontWeight: 600, color: '#1e293b', marginBottom: 4 }}>{s.nombre}</div>
                          <div style={{ height: 4, background: '#f1f5f9', borderRadius: 2 }}>
                            <div style={{ height: '100%', width: p + '%', background: p === 100 ? '#22c55e' : '#c4b400', borderRadius: 2 }} />
                          </div>
                        </div>
                        <span style={{ fontSize: 12, fontWeight: 700, color: '#6b7280', minWidth: 34, textAlign: 'right' }}>{p}%</span>
                      </div>);

                })}
                </div>
              </div>

              {/* Huellitas banner */}
              <div onClick={function () { window.openHuellitasModal(); }} style={{ background: 'linear-gradient(135deg,#1c79b4 0%,#1e6fa3 100%)', borderRadius: 14, padding: '28px 32px', display: 'flex', alignItems: 'center', gap: 28, cursor: 'pointer' }}>
                <div style={{ fontSize: 48, flexShrink: 0 }}>🐾</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, color: '#c4b400', fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 6 }}>Huellitas en Acción — Iniciativa Solidaria ASSYST</div>
                  <div style={{ fontSize: 18, fontWeight: 800, color: 'white', marginBottom: 8 }}>"Convirtamos cada aprendizaje en un plato lleno"</div>
                  <div style={{ fontSize: 13, color: 'rgba(255,255,255,.65)', lineHeight: 1.6 }}>Por cada estudiante inscrito, ASSYST destina parte de los ingresos a alimentar y cuidar perros y gatos en condición de abandono. Actualmente <strong style={{ color: '#c4b400' }}>{activeStudents.length} estudiantes activos</strong> están generando un impacto real.</div>
                </div>
              </div>
            </div>
          }

          {tab === 'homepage' && <AdminHomepage />}
          {tab === 'forum' && <ForumView user={user} />}
          {tab === 'content' && <AdminContent />}
          {tab === 'students' && <AdminUsers />}
          {tab === 'progress' && <AdminProgress />}
          {tab === 'biblio' && <AdminBiblio />}
          {tab === 'soporte' && <AdminSupport />}
          {tab === 'cert-config' && <AdminCertConfig />}
          {tab === 'profile' && <AdminProfile user={currentUser} onUserUpdate={function (u) { setCurrentUser(u); }} onPhotoChange={function () { setPhotoVer(function (v) { return v + 1; }); }} />}
        </div>
      </div>
    </div>
    </window.PhotoVersionContext.Provider>);

}

window.AdminShell = AdminShell;