/* global React, Footer */
const { useState: useStateA } = React;

// ============================================================================
// ADMIN GATE — exige senha antes de acessar o painel
// ============================================================================
function AdminGate({ onUnlock, onCancel, showToast }) {
  const [pwd, setPwd] = useStateA("");
  const [loading, setLoading] = useStateA(false);
  const [error, setError] = useStateA(null);

  async function submit() {
    setLoading(true);
    setError(null);
    const ok = await window.BNStore.verifyAdminPassword(pwd);
    setLoading(false);
    if (ok) {
      onUnlock();
      showToast("Acesso administrativo liberado");
    } else {
      setError("Senha incorreta.");
      setPwd("");
    }
  }

  return (
    <main className="login-screen" style={{ minHeight: "calc(100vh - 90px)" }}>
      <div className="login-card">
        <div className="login-mark" aria-label="Beit Net'zer" />
        <h2>Área restrita</h2>
        <p className="login-sub">Digite a senha administrativa para continuar</p>

        {error && (
          <div className="login-error">
            <span style={{ fontSize: 16, lineHeight: 1 }}>⚠</span>
            <span>{error}</span>
          </div>
        )}

        <input
          className="login-email-input"
          type="password"
          placeholder="Senha do administrador"
          value={pwd}
          onChange={(e) => setPwd(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && submit()}
          autoFocus
        />
        <button
          className="btn btn-gold"
          style={{ width: "100%" }}
          onClick={submit}
          disabled={loading}
        >
          {loading ? "Verificando…" : "Desbloquear painel"}
        </button>
        <button
          className="btn btn-ghost btn-sm"
          style={{ width: "100%", marginTop: 10 }}
          onClick={onCancel}
        >
          Voltar
        </button>

        <p className="login-hint" style={{ marginTop: 20 }}>
          Esta área é restrita ao administrador.<br />
          Após o primeiro acesso, troque a senha em <strong style={{ color: "var(--gold)" }}>Configurações</strong>.
        </p>
      </div>
    </main>
  );
}

// ============================================================================
// ADMIN PAGE  (com store persistente em localStorage)
// ============================================================================
function AdminPage({ data, showToast, onLock }) {
  const [tab, setTab] = useStateA("students");
  const [search, setSearch] = useStateA("");
  const [modal, setModal] = useStateA(null); // 'addStudent' | 'addCourse' | {kind:'editLessons', courseId}
  const [editLessonsCourseId, setEditLessonsCourseId] = useStateA(null);

  const S = window.BNStore;
  const students = S.getStudents();
  const courses = S.getCourses();
  const approvedEmails = S.getApprovedEmails();

  const filteredStudents = students.filter(
    (s) =>
      s.name.toLowerCase().includes(search.toLowerCase()) ||
      s.email.toLowerCase().includes(search.toLowerCase())
  );
  const filteredCourses = courses.filter(
    (c) =>
      c.title.toLowerCase().includes(search.toLowerCase()) ||
      c.category.toLowerCase().includes(search.toLowerCase())
  );

  // ---- Reset / export / import ----
  function exportData() {
    const blob = new Blob([S.exportJson()], { type: "application/json" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `beit-netzer-backup-${new Date().toISOString().slice(0, 10)}.json`;
    a.click();
    showToast("Backup exportado");
  }
  function importData() {
    const inp = document.createElement("input");
    inp.type = "file"; inp.accept = "application/json";
    inp.onchange = async () => {
      const file = inp.files[0]; if (!file) return;
      try { S.importJson(await file.text()); showToast("Dados importados com sucesso"); }
      catch (e) { showToast("Erro ao importar: " + e.message); }
    };
    inp.click();
  }
  function resetData() {
    if (!confirm("Apagar todos os dados locais e voltar ao estado inicial?")) return;
    S.reset(); showToast("Dados resetados");
  }

  return (
    <main className="admin-page">
      <header className="admin-head">
        <div>
          <div className="heb">פָּנֵל נִיהוּל</div>
          <h1>Painel administrativo</h1>
          <div className="sub">Gerencie alunos, cursos, módulos e links do Google Drive</div>
        </div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", justifyContent: "flex-end" }}>
          <button className="btn btn-ghost btn-sm" onClick={importData}>↑ Importar</button>
          <button className="btn btn-ghost btn-sm" onClick={exportData}>↓ Exportar backup</button>
          <button className="btn btn-ghost btn-sm" onClick={resetData} style={{ color: "var(--err)", borderColor: "rgba(194,90,90,0.3)" }}>⟲ Resetar</button>
          <button className="btn btn-ghost btn-sm" onClick={onLock} title="Sair do painel admin">⌬ Bloquear</button>
          <button
            className="btn btn-gold btn-sm"
            onClick={() => setModal(tab === "students" ? "addStudent" : "addCourse")}
          >
            ＋ &nbsp;{tab === "students" ? "Aprovar aluno" : "Novo curso"}
          </button>
        </div>
      </header>

      <div className="admin-stats">
        <div className="stat-card">
          <div className="lbl">Alunos aprovados</div>
          <div className="val">{students.filter((s) => s.status === "Ativo").length}</div>
          <div className="delta">{approvedEmails.length} no total</div>
        </div>
        <div className="stat-card">
          <div className="lbl">Cursos publicados</div>
          <div className="val">{courses.length}</div>
          <div className="delta">{courses.filter((c) => c.featured).length} em destaque</div>
        </div>
        <div className="stat-card">
          <div className="lbl">Aulas em vídeo</div>
          <div className="val">
            {courses.reduce((a, c) => a + (S.getLessons(c.id).filter((l) => l.driveVideoUrl).length), 0)}
          </div>
          <div className="delta">com link do Drive</div>
        </div>
        <div className="stat-card">
          <div className="lbl">PDFs anexados</div>
          <div className="val">
            {courses.reduce((a, c) => a + (S.getLessons(c.id).filter((l) => l.drivePdfUrl).length), 0)}
          </div>
          <div className="delta">com link do Drive</div>
        </div>
      </div>

      <div className="admin-tabs">
        {[
          { id: "students", label: "Alunos aprovados" },
          { id: "access",   label: "Histórico de acessos" },
          { id: "classes",  label: "Turmas" },
          { id: "teachers", label: "Professores" },
          { id: "courses", label: "Cursos e módulos" },
          { id: "lessons", label: "Aulas e materiais" },
          { id: "materials", label: "Biblioteca de materiais" },
          { id: "categories", label: "Categorias" },
          { id: "settings", label: "Configurações" },
        ].map((t) => (
          <button
            key={t.id}
            className={"admin-tab " + (tab === t.id ? "active" : "")}
            onClick={() => setTab(t.id)}
          >
            {t.label}
          </button>
        ))}
      </div>

      <div className="admin-toolbar">
        <input
          className="search"
          placeholder={tab === "students" ? "Buscar por nome ou email…" : "Buscar curso ou categoria…"}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
        {tab === "students" && (
          <button className="btn btn-ghost btn-sm" onClick={() => setModal("addStudent")}>
            ＋ Adicionar email aprovado
          </button>
        )}
        {tab === "lessons" && (
          <select
            className="search"
            style={{ maxWidth: 320 }}
            value={editLessonsCourseId || ""}
            onChange={(e) => setEditLessonsCourseId(e.target.value)}
          >
            <option value="">Escolha um curso…</option>
            {courses.map((c) => <option key={c.id} value={c.id}>{c.title}</option>)}
          </select>
        )}
      </div>

      {/* STUDENTS TABLE */}
      {tab === "students" && (
        <StudentsTable
          students={filteredStudents}
          showToast={showToast}
        />
      )}

      {/* COURSES TABLE */}
      {tab === "courses" && (
        <CoursesTable
          courses={filteredCourses}
          showToast={showToast}
          onManageLessons={(c) => { setEditLessonsCourseId(c.id); setTab("lessons"); }}
        />
      )}

      {/* LESSONS TAB */}
      {tab === "lessons" && (
        <LessonsEditor
          courseId={editLessonsCourseId || courses[0]?.id}
          courses={courses}
          showToast={showToast}
        />
      )}

      {/* CATEGORIES TAB */}
      {tab === "categories" && <CategoriesTable courses={courses} data={data} />}

      {/* MATERIALS TAB */}
      {tab === "materials" && (
        <MaterialsEditor
          materials={S.getMaterials().filter(
            (m) =>
              !search ||
              m.title.toLowerCase().includes(search.toLowerCase()) ||
              (m.category || "").toLowerCase().includes(search.toLowerCase())
          )}
          showToast={showToast}
        />
      )}

      {/* TEACHERS TAB */}
      {tab === "teachers" && (
        <TeachersEditor
          teachers={S.getTeachers().filter(
            (t) =>
              !search ||
              t.name.toLowerCase().includes(search.toLowerCase()) ||
              (t.email || "").toLowerCase().includes(search.toLowerCase())
          )}
          showToast={showToast}
        />
      )}

      {/* SETTINGS TAB */}
      {tab === "settings" && <SettingsPanel showToast={showToast} onLock={onLock} />}

      {/* CLASSES TAB */}
      {tab === "classes" && <ClassesEditor showToast={showToast} />}

      {/* ACCESS LOG TAB */}
      {tab === "access" && <AccessLogPanel showToast={showToast} />}

      {/* MODALS */}
      {modal === "addStudent" && (
        <AddStudentModal onClose={() => setModal(null)} showToast={showToast} />
      )}
      {modal === "addCourse" && (
        <AddCourseModal onClose={() => setModal(null)} showToast={showToast} categories={data.rails} />
      )}

      <Footer />
    </main>
  );
}

// ----------------------------------------------------------------------------
function StudentsTable({ students, showToast }) {
  const classes = window.BNStore.getClasses();

  return (
    <div className="admin-table">
      <table>
        <thead>
          <tr>
            <th>Aluno</th>
            <th>Email</th>
            <th>Turma</th>
            <th>Status</th>
            <th style={{ textAlign: "right" }}>Ações</th>
          </tr>
        </thead>
        <tbody>
          {students.map((s) => {
            const currentClass = classes.find((c) => c.id === s.classId);
            return (
              <tr key={s.email}>
                <td style={{ fontFamily: "var(--serif)", fontSize: 15 }}>{s.name}</td>
                <td className="email">{s.email}</td>
                <td>
                  <select
                    value={s.classId || ""}
                    onChange={(e) => {
                      window.BNStore.assignStudentToClass(s.email, e.target.value || null);
                      showToast(e.target.value ? `Turma atualizada` : `Aluno sem turma`);
                    }}
                    style={{
                      background: "var(--ink-1)",
                      border: "1px solid " + (currentClass ? "var(--gold-deep)" : "var(--ink-4)"),
                      color: currentClass ? "var(--gold)" : "var(--bone-mute)",
                      borderRadius: 6,
                      padding: "6px 10px",
                      fontSize: 13,
                      fontFamily: "inherit",
                      cursor: "pointer",
                      minWidth: 160,
                    }}
                  >
                    <option value="">— sem turma —</option>
                    {classes.map((c) => (
                      <option key={c.id} value={c.id}>{c.name}</option>
                    ))}
                  </select>
                </td>
                <td>
                  <span className={"pill " + (s.status === "Ativo" ? "pill-ok" : s.status === "Pendente" ? "pill-warn" : "pill-err")}>
                    {s.status}
                  </span>
                </td>
                <td>
                  <div className="row-actions">
                    <button
                      className="icon-btn"
                      title={s.status === "Ativo" ? "Suspender" : "Ativar"}
                      onClick={() => {
                        window.BNStore.updateStudentStatus(s.email, s.status === "Ativo" ? "Suspenso" : "Ativo");
                        showToast(s.status === "Ativo" ? "Aluno suspenso" : "Aluno ativado");
                      }}
                    >{s.status === "Ativo" ? "⏸" : "▶"}</button>
                    <button
                      className="icon-btn danger"
                      title="Remover"
                      onClick={() => {
                        if (!confirm(`Remover ${s.name}?`)) return;
                        window.BNStore.removeStudent(s.email);
                        showToast("Aluno removido");
                      }}
                    >✕</button>
                  </div>
                </td>
              </tr>
            );
          })}
          {students.length === 0 && (
            <tr><td colSpan="5" style={{ textAlign: "center", padding: 40, color: "var(--bone-mute)" }}>
              Nenhum aluno encontrado.
            </td></tr>
          )}
        </tbody>
      </table>
    </div>
  );
}

// ----------------------------------------------------------------------------
function ClassesEditor({ showToast }) {
  const classes = window.BNStore.getClasses();
  const courses = window.BNStore.getCourses();
  const students = window.BNStore.getStudents();

  const [editing, setEditing] = useStateA(null); // class id being edited
  const [newClass, setNewClass] = useStateA({ name: "", hebrew: "", description: "" });

  function addClass() {
    if (!newClass.name) { showToast("Nome da turma é obrigatório"); return; }
    window.BNStore.addClass(newClass);
    setNewClass({ name: "", hebrew: "", description: "" });
    showToast(`Turma "${newClass.name}" criada`);
  }

  function toggleCourse(classId, courseId) {
    const cls = classes.find((c) => c.id === classId);
    if (!cls) return;
    const has = (cls.courseIds || []).includes(courseId);
    const next = has
      ? cls.courseIds.filter((id) => id !== courseId)
      : [...(cls.courseIds || []), courseId];
    window.BNStore.setClassCourses(classId, next);
  }

  return (
    <div>
      {/* Form criar turma */}
      <div style={{ padding: 20, background: "linear-gradient(180deg, rgba(20,19,26,0.6), rgba(13,12,18,0.6))", border: "1px solid var(--ink-3)", borderRadius: 10, marginBottom: 24 }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginBottom: 4, color: "var(--gold)" }}>＋ Criar nova turma</div>
        <div style={{ color: "var(--bone-mute)", fontSize: 12, marginBottom: 16 }}>
          Turmas agrupam alunos com o mesmo nível de acesso. Você escolhe quais cursos cada turma vê.
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 200px 1fr", gap: 12 }}>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Nome da turma *</label>
            <input value={newClass.name} onChange={(e) => setNewClass({ ...newClass, name: e.target.value })} placeholder="Ex: Avançado, Iniciante, Classe A" />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Nome em hebraico</label>
            <input value={newClass.hebrew} onChange={(e) => setNewClass({ ...newClass, hebrew: e.target.value })} placeholder="מַתְחִיל" style={{ fontFamily: "var(--hebrew)", fontSize: 15 }} />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Descrição</label>
            <input value={newClass.description} onChange={(e) => setNewClass({ ...newClass, description: e.target.value })} placeholder="Quem entra nessa turma" />
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 14 }}>
          <button className="btn btn-gold" onClick={addClass}>＋ Criar turma</button>
        </div>
      </div>

      {/* Lista de turmas */}
      {classes.map((cls) => {
        const isEditing = editing === cls.id;
        const studentCount = students.filter((s) => s.classId === cls.id).length;
        return (
          <div key={cls.id} style={{
            marginBottom: 16,
            border: "1px solid " + (isEditing ? "var(--gold-deep)" : "var(--ink-3)"),
            background: "rgba(20,19,26,0.5)",
            borderRadius: 10,
            overflow: "hidden",
          }}>
            {/* Cabeçalho da turma */}
            <div style={{ padding: "16px 20px", display: "flex", alignItems: "center", gap: 16, background: "rgba(13,12,18,0.4)" }}>
              <div style={{ flex: 1 }}>
                {cls.hebrew && (
                  <div style={{ fontFamily: "var(--hebrew)", color: "var(--gold)", fontSize: 16, marginBottom: 2, direction: "rtl" }}>{cls.hebrew}</div>
                )}
                <div style={{ fontFamily: "var(--serif)", fontSize: 20 }}>{cls.name}</div>
                {cls.description && <div style={{ fontSize: 12, color: "var(--bone-mute)", marginTop: 2 }}>{cls.description}</div>}
              </div>
              <div style={{ textAlign: "right", fontSize: 12 }}>
                <div style={{ color: "var(--bone-mute)" }}>{studentCount} aluno(s)</div>
                <div style={{ color: "var(--gold)", marginTop: 2 }}>{(cls.courseIds || []).length} curso(s) liberado(s)</div>
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                <button
                  className="btn btn-ghost btn-sm"
                  onClick={() => setEditing(isEditing ? null : cls.id)}
                >
                  {isEditing ? "Fechar" : "Editar cursos"}
                </button>
                <button
                  className="icon-btn danger"
                  title="Remover turma"
                  onClick={() => {
                    if (!confirm(`Remover turma "${cls.name}"? Alunos dessa turma ficarão sem turma.`)) return;
                    window.BNStore.removeClass(cls.id);
                    showToast("Turma removida");
                  }}
                >✕</button>
              </div>
            </div>

            {/* Editor de cursos */}
            {isEditing && (
              <div style={{ padding: 20, borderTop: "1px solid var(--ink-3)" }}>
                <div style={{ fontSize: 12, color: "var(--bone-mute)", marginBottom: 14 }}>
                  Marque os cursos que essa turma pode acessar:
                </div>
                {courses.length === 0 ? (
                  <div style={{ color: "var(--bone-mute)", padding: 20, textAlign: "center" }}>
                    Nenhum curso cadastrado ainda.
                  </div>
                ) : (
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                    {courses.map((c) => {
                      const has = (cls.courseIds || []).includes(c.id);
                      return (
                        <label key={c.id} style={{
                          display: "flex", alignItems: "center", gap: 10,
                          padding: "10px 12px",
                          background: has ? "rgba(212,173,90,0.06)" : "var(--ink-1)",
                          border: "1px solid " + (has ? "var(--gold-deep)" : "var(--ink-3)"),
                          borderRadius: 6, cursor: "pointer",
                        }}>
                          <input
                            type="checkbox"
                            checked={has}
                            onChange={() => toggleCourse(cls.id, c.id)}
                            style={{ accentColor: "var(--gold)", width: 16, height: 16, cursor: "pointer" }}
                          />
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontFamily: "var(--serif)", fontSize: 14, color: "var(--bone)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                              {c.title}
                            </div>
                            <div style={{ fontSize: 11, color: "var(--bone-mute)" }}>{c.category}</div>
                          </div>
                        </label>
                      );
                    })}
                  </div>
                )}
              </div>
            )}
          </div>
        );
      })}

      {classes.length === 0 && (
        <div style={{ padding: 60, textAlign: "center", color: "var(--bone-mute)", border: "1px dashed var(--ink-4)", borderRadius: 10 }}>
          Nenhuma turma criada ainda. Use o formulário acima.
        </div>
      )}
    </div>
  );
}

// ----------------------------------------------------------------------------
function StudentPermissionsModal({ student, onClose, showToast }) {
  const courses = window.BNStore.getCourses();
  const [mode, setMode] = useStateA(student.accessMode || "all");
  const [allowed, setAllowed] = useStateA(new Set(student.allowedCourses || []));

  function toggle(courseId) {
    const next = new Set(allowed);
    if (next.has(courseId)) next.delete(courseId); else next.add(courseId);
    setAllowed(next);
  }
  function toggleAllInCategory(cat) {
    const inCat = courses.filter((c) => c.category === cat).map((c) => c.id);
    const next = new Set(allowed);
    const allSelected = inCat.every((id) => next.has(id));
    if (allSelected) inCat.forEach((id) => next.delete(id));
    else inCat.forEach((id) => next.add(id));
    setAllowed(next);
  }
  function save() {
    window.BNStore.updateStudent(student.email, {
      accessMode: mode,
      allowedCourses: Array.from(allowed),
    });
    showToast(`Permissões de ${student.name} atualizadas`);
    onClose();
  }

  const categories = Array.from(new Set(courses.map((c) => c.category)));

  return (
    <div className="modal-backdrop" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="modal" style={{ maxWidth: 720, width: "100%", maxHeight: "85vh", display: "flex", flexDirection: "column" }}>
        <h3>Permissões de acesso</h3>
        <p className="sub">
          <strong style={{ color: "var(--bone)" }}>{student.name}</strong> · <span className="email">{student.email}</span>
        </p>

        {/* Modo: todos / seletivo */}
        <div style={{ display: "flex", gap: 8, marginBottom: 18 }}>
          <button
            className={"btn btn-sm " + (mode === "all" ? "btn-gold" : "btn-ghost")}
            style={{ flex: 1 }}
            onClick={() => setMode("all")}
          >
            ✓ &nbsp;Acesso total
          </button>
          <button
            className={"btn btn-sm " + (mode === "selected" ? "btn-gold" : "btn-ghost")}
            style={{ flex: 1 }}
            onClick={() => setMode("selected")}
          >
            ⚙ &nbsp;Acesso seletivo
          </button>
        </div>

        {mode === "all" ? (
          <div style={{ padding: 28, textAlign: "center", border: "1px dashed var(--ink-4)", borderRadius: 10, color: "var(--bone-dim)" }}>
            <div style={{ fontSize: 32, marginBottom: 8, color: "var(--gold)" }}>✓</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginBottom: 4 }}>Vê todos os cursos da plataforma</div>
            <div style={{ fontSize: 12, color: "var(--bone-mute)" }}>
              Mude para "Acesso seletivo" para escolher cursos específicos.
            </div>
          </div>
        ) : (
          <div style={{ overflowY: "auto", flex: 1, paddingRight: 6 }}>
            <div style={{ fontSize: 12, color: "var(--bone-mute)", marginBottom: 12, padding: 10, background: "var(--ink-1)", border: "1px solid var(--ink-3)", borderRadius: 6 }}>
              {allowed.size === 0
                ? "⚠ Este aluno NÃO terá acesso a nenhum curso até você marcar pelo menos um abaixo."
                : `${allowed.size} curso(s) selecionado(s).`}
            </div>
            {categories.map((cat) => {
              const inCat = courses.filter((c) => c.category === cat);
              const allOn = inCat.every((c) => allowed.has(c.id));
              return (
                <div key={cat} style={{ marginBottom: 18 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10, paddingBottom: 8, borderBottom: "1px solid var(--ink-3)" }}>
                    <h4 style={{ margin: 0, fontFamily: "var(--serif)", fontSize: 16, color: "var(--gold)", flex: 1 }}>{cat}</h4>
                    <button
                      className="btn btn-ghost btn-sm"
                      style={{ fontSize: 11, padding: "4px 10px" }}
                      onClick={() => toggleAllInCategory(cat)}
                    >
                      {allOn ? "Desmarcar todos" : "Marcar todos"}
                    </button>
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                    {inCat.map((c) => (
                      <label
                        key={c.id}
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: 10,
                          padding: "10px 12px",
                          background: allowed.has(c.id) ? "rgba(212,173,90,0.06)" : "var(--ink-1)",
                          border: "1px solid " + (allowed.has(c.id) ? "var(--gold-deep)" : "var(--ink-3)"),
                          borderRadius: 6,
                          cursor: "pointer",
                          transition: "all 0.15s",
                        }}
                      >
                        <input
                          type="checkbox"
                          checked={allowed.has(c.id)}
                          onChange={() => toggle(c.id)}
                          style={{ accentColor: "var(--gold)", cursor: "pointer", width: 16, height: 16 }}
                        />
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontFamily: "var(--serif)", fontSize: 14, color: "var(--bone)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                            {c.title}
                          </div>
                          <div style={{ fontSize: 11, color: "var(--bone-mute)", fontFamily: "var(--mono)" }}>{c.level} · {c.duration}</div>
                        </div>
                      </label>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        <div className="modal-actions">
          <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="btn btn-gold" onClick={save}>Salvar permissões</button>
        </div>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------------------
function CoursesTable({ courses, showToast, onManageLessons }) {
  return (
    <div className="admin-table">
      <table>
        <thead>
          <tr>
            <th>Curso</th>
            <th>Categoria</th>
            <th>Mestre</th>
            <th>Aulas</th>
            <th>Destaque</th>
            <th style={{ textAlign: "right" }}>Ações</th>
          </tr>
        </thead>
        <tbody>
          {courses.map((c) => (
            <tr key={c.id}>
              <td>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div
                    style={{
                      width: 42, height: 28,
                      borderRadius: 4,
                      background: `linear-gradient(135deg, oklch(0.3 0.08 ${c.hue}), oklch(0.15 0.04 ${c.hue}))`,
                      border: "1px solid var(--ink-4)",
                      display: "grid", placeItems: "center",
                      fontFamily: "var(--hebrew)", color: "var(--gold)", fontSize: 13,
                    }}
                  >{c.hebrew.slice(0, 2)}</div>
                  <div>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 15 }}>{c.title}</div>
                    <div style={{ fontSize: 11, color: "var(--bone-mute)", fontFamily: "var(--mono)" }}>{c.id}</div>
                  </div>
                </div>
              </td>
              <td style={{ color: "var(--bone-dim)" }}>{c.category}</td>
              <td style={{ color: "var(--bone-dim)" }}>{c.teacher}</td>
              <td>{window.BNStore.getLessons(c.id).length}</td>
              <td>
                <button
                  className={"pill " + (c.featured ? "pill-ok" : "")}
                  style={{ cursor: "pointer", background: c.featured ? undefined : "transparent", color: c.featured ? undefined : "var(--bone-mute)", borderColor: c.featured ? undefined : "var(--ink-4)" }}
                  onClick={() => window.BNStore.setFeatured(c.id, !c.featured)}
                  title="Alternar destaque"
                >{c.featured ? "Destaque" : "—"}</button>
              </td>
              <td>
                <div className="row-actions">
                  <button className="icon-btn" title="Gerenciar aulas" onClick={() => onManageLessons(c)}>≡</button>
                  <button
                    className="icon-btn danger"
                    title="Remover curso"
                    onClick={() => {
                      if (!confirm(`Remover curso "${c.title}" e todas suas aulas?`)) return;
                      window.BNStore.removeCourse(c.id);
                      showToast("Curso removido");
                    }}
                  >✕</button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ----------------------------------------------------------------------------
function LessonsEditor({ courseId, courses, showToast }) {
  const course = courses.find((c) => c.id === courseId);
  const lessons = courseId ? window.BNStore.getLessons(courseId) : [];

  const [newLesson, setNewLesson] = useStateA({
    title: "", duration: "", desc: "", driveVideoUrl: "", drivePdfUrl: "",
  });
  const [editingId, setEditingId] = useStateA(null);
  const [editForm, setEditForm] = useStateA({});

  function addLesson() {
    if (!courseId) { showToast("Escolha um curso primeiro"); return; }
    if (!newLesson.title) { showToast("Título é obrigatório"); return; }
    window.BNStore.addLesson(courseId, newLesson);
    setNewLesson({ title: "", duration: "", desc: "", driveVideoUrl: "", drivePdfUrl: "" });
    showToast(`Aula "${newLesson.title}" adicionada`);
  }
  function startEdit(l) {
    setEditingId(l.id);
    setEditForm({ ...l });
  }
  function saveEdit() {
    window.BNStore.updateLesson(courseId, editingId, editForm);
    setEditingId(null);
    showToast("Aula atualizada");
  }

  if (!course) {
    return (
      <div style={{ padding: 60, textAlign: "center", color: "var(--bone-mute)", border: "1px dashed var(--ink-4)", borderRadius: 10 }}>
        Selecione um curso na barra acima para gerenciar as aulas.
      </div>
    );
  }

  return (
    <div>
      {/* Header do curso */}
      <div style={{ padding: "16px 20px", background: "rgba(20,19,26,0.4)", border: "1px solid var(--ink-3)", borderRadius: 10, marginBottom: 18, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div>
          <div style={{ fontFamily: "var(--hebrew)", color: "var(--gold)", fontSize: 16 }}>{course.hebrew}</div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 20 }}>{course.title}</div>
          <div style={{ color: "var(--bone-mute)", fontSize: 12 }}>{course.category} · {course.teacher}</div>
        </div>
        <div style={{ color: "var(--bone-mute)", fontFamily: "var(--mono)", fontSize: 12 }}>
          {lessons.length} aula(s) cadastrada(s)
        </div>
      </div>

      {/* Form de nova aula */}
      <div style={{ padding: 20, background: "linear-gradient(180deg, rgba(20,19,26,0.6), rgba(13,12,18,0.6))", border: "1px solid var(--ink-3)", borderRadius: 10, marginBottom: 20 }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 17, marginBottom: 14, color: "var(--gold)" }}>＋ Adicionar nova aula</div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 12 }}>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Título</label>
            <input value={newLesson.title} onChange={(e) => setNewLesson({ ...newLesson, title: e.target.value })} placeholder="Ex: Bereshit Bará — No princípio" />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Duração</label>
            <input value={newLesson.duration} onChange={(e) => setNewLesson({ ...newLesson, duration: e.target.value })} placeholder="Ex: 42 min" />
          </div>
        </div>
        <div className="field" style={{ marginTop: 12 }}>
          <label>Descrição (opcional)</label>
          <textarea rows="2" value={newLesson.desc} onChange={(e) => setNewLesson({ ...newLesson, desc: e.target.value })} placeholder="Resumo curto da aula" />
        </div>
        <DriveUrlField
          label="Link do vídeo (Google Drive)"
          value={newLesson.driveVideoUrl}
          onChange={(v) => setNewLesson({ ...newLesson, driveVideoUrl: v })}
        />
        <DriveUrlField
          label="Link do PDF (Google Drive)"
          value={newLesson.drivePdfUrl}
          onChange={(v) => setNewLesson({ ...newLesson, drivePdfUrl: v })}
        />
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 14 }}>
          <button className="btn btn-gold" onClick={addLesson}>＋ Adicionar aula</button>
        </div>
      </div>

      {/* Lista de aulas existentes */}
      <div className="admin-table">
        <table>
          <thead>
            <tr>
              <th style={{ width: 50 }}>#</th>
              <th>Aula</th>
              <th>Duração</th>
              <th>Vídeo</th>
              <th>PDF</th>
              <th style={{ textAlign: "right" }}>Ações</th>
            </tr>
          </thead>
          <tbody>
            {lessons.map((l, i) => (
              <React.Fragment key={l.id}>
                <tr>
                  <td style={{ fontFamily: "var(--serif)", color: "var(--bone-mute)" }}>{String(i + 1).padStart(2, "0")}</td>
                  <td style={{ fontFamily: "var(--serif)", fontSize: 14 }}>{l.title}</td>
                  <td className="email">{l.duration || "—"}</td>
                  <td>
                    {l.driveVideoUrl ? (
                      <span className="pill pill-ok" style={{ fontSize: 10 }}>OK</span>
                    ) : (
                      <span style={{ color: "var(--bone-mute)", fontSize: 12 }}>—</span>
                    )}
                  </td>
                  <td>
                    {l.drivePdfUrl ? (
                      <span className="pill pill-ok" style={{ fontSize: 10 }}>OK</span>
                    ) : (
                      <span style={{ color: "var(--bone-mute)", fontSize: 12 }}>—</span>
                    )}
                  </td>
                  <td>
                    <div className="row-actions">
                      <button className="icon-btn" title="Editar" onClick={() => startEdit(l)}>✎</button>
                      <button
                        className="icon-btn danger"
                        title="Remover"
                        onClick={() => {
                          if (!confirm(`Remover aula "${l.title}"?`)) return;
                          window.BNStore.removeLesson(courseId, l.id);
                          showToast("Aula removida");
                        }}
                      >✕</button>
                    </div>
                  </td>
                </tr>
                {editingId === l.id && (
                  <tr>
                    <td colSpan="6" style={{ background: "var(--ink-1)", padding: 20 }}>
                      <div className="field"><label>Título</label><input value={editForm.title} onChange={(e) => setEditForm({ ...editForm, title: e.target.value })} /></div>
                      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                        <div className="field"><label>Duração</label><input value={editForm.duration || ""} onChange={(e) => setEditForm({ ...editForm, duration: e.target.value })} /></div>
                        <div className="field"><label>Status padrão</label>
                          <select value={editForm.status || "not_started"} onChange={(e) => setEditForm({ ...editForm, status: e.target.value })}>
                            <option value="not_started">Não iniciada</option>
                            <option value="in_progress">Em curso</option>
                            <option value="completed">Concluída</option>
                          </select>
                        </div>
                      </div>
                      <div className="field"><label>Descrição</label><textarea rows="2" value={editForm.desc || ""} onChange={(e) => setEditForm({ ...editForm, desc: e.target.value })} /></div>
                      <DriveUrlField label="Link do vídeo (Google Drive)" value={editForm.driveVideoUrl || ""} onChange={(v) => setEditForm({ ...editForm, driveVideoUrl: v })} />
                      <DriveUrlField label="Link do PDF (Google Drive)" value={editForm.drivePdfUrl || ""} onChange={(v) => setEditForm({ ...editForm, drivePdfUrl: v })} />
                      <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 12 }}>
                        <button className="btn btn-ghost btn-sm" onClick={() => setEditingId(null)}>Cancelar</button>
                        <button className="btn btn-gold btn-sm" onClick={saveEdit}>Salvar alterações</button>
                      </div>
                    </td>
                  </tr>
                )}
              </React.Fragment>
            ))}
            {lessons.length === 0 && (
              <tr><td colSpan="6" style={{ textAlign: "center", padding: 40, color: "var(--bone-mute)" }}>
                Nenhuma aula cadastrada. Use o formulário acima para adicionar.
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------------------
// Campo de URL do Drive com validação visual + preview do ID extraído
function DriveUrlField({ label, value, onChange }) {
  const id = window.extractDriveId(value);
  const valid = !value || !!id;
  return (
    <div className="field" style={{ marginTop: 12 }}>
      <label>{label}</label>
      <input
        type="url"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder="https://drive.google.com/file/d/SEU_FILE_ID/view"
        style={{ borderColor: valid ? undefined : "var(--err)" }}
      />
      {value && id && (
        <div style={{ fontSize: 11, color: "var(--ok)", fontFamily: "var(--mono)", marginTop: 4 }}>
          ✓ ID detectado: {id.slice(0, 24)}{id.length > 24 ? "…" : ""}
        </div>
      )}
      {value && !id && (
        <div style={{ fontSize: 11, color: "var(--err)", marginTop: 4 }}>
          Link inválido — use o formato https://drive.google.com/file/d/…/view
        </div>
      )}
    </div>
  );
}

// ----------------------------------------------------------------------------
function CategoriesTable({ courses, data }) {
  return (
    <div className="admin-table">
      <table>
        <thead>
          <tr>
            <th>Categoria</th>
            <th>Hebraico</th>
            <th>Cursos</th>
            <th>Visível</th>
          </tr>
        </thead>
        <tbody>
          {[
            ["Módulos de Torah", "תּוֹרָה"],
            ["Brit Chadashah", "ברית חדשה"],
            ["Hebraico Bíblico", "עברית"],
            ["PDFs de Estudo", "מסמכים"],
            ["Shiurim Especiais", "שיעורים"],
            ["Aulas Recentes", "לאחרונה"],
          ].map(([cat, heb]) => (
            <tr key={cat}>
              <td style={{ fontFamily: "var(--serif)", fontSize: 15 }}>{cat}</td>
              <td style={{ fontFamily: "var(--hebrew)", color: "var(--gold)", fontSize: 16 }}>{heb}</td>
              <td>{courses.filter((c) => c.category === cat).length}</td>
              <td><span className="pill pill-ok">Visível</span></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ----------------------------------------------------------------------------
function AddStudentModal({ onClose, showToast }) {
  const [name, setName] = useStateA("");
  const [email, setEmail] = useStateA("");
  function save() {
    if (!name || !email) { showToast("Preencha nome e email"); return; }
    window.BNStore.addStudent({ name, email, status: "Ativo" });
    showToast(`${name} aprovado(a)`);
    onClose();
  }
  return (
    <div className="modal-backdrop" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="modal">
        <h3>Aprovar novo aluno</h3>
        <p className="sub">Apenas Gmails listados aqui poderão fazer login</p>
        <div className="field">
          <label>Nome completo</label>
          <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Yaakov Almeida" />
        </div>
        <div className="field">
          <label>Email Gmail</label>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="aluno@gmail.com" />
        </div>
        <div className="modal-actions">
          <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="btn btn-gold" onClick={save}>Aprovar acesso</button>
        </div>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------------------
function AddCourseModal({ onClose, showToast, categories }) {
  const [form, setForm] = useStateA({
    title: "", category: categories[0] || "Módulos de Torah",
    teacher: "", description: "", hebrew: "", level: "Iniciante",
  });
  function save() {
    if (!form.title) { showToast("Título é obrigatório"); return; }
    const c = window.BNStore.addCourse(form);
    showToast(`Curso "${c.title}" criado`);
    onClose();
  }
  return (
    <div className="modal-backdrop" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="modal" style={{ maxWidth: 560 }}>
        <h3>Novo curso ou módulo</h3>
        <p className="sub">Crie o curso, depois adicione aulas com links do Drive</p>
        <div className="field">
          <label>Título</label>
          <input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="Devarim — A Repetição da Torah" />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div className="field">
            <label>Categoria</label>
            <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}>
              {categories.map((r) => <option key={r}>{r}</option>)}
            </select>
          </div>
          <div className="field">
            <label>Nível</label>
            <select value={form.level} onChange={(e) => setForm({ ...form, level: e.target.value })}>
              <option>Iniciante</option><option>Intermediário</option><option>Avançado</option><option>Todos</option>
            </select>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div className="field">
            <label>Mestre</label>
            <input value={form.teacher} onChange={(e) => setForm({ ...form, teacher: e.target.value })} placeholder="Rav Eliezer" />
          </div>
          <div className="field">
            <label>Título em hebraico</label>
            <input value={form.hebrew} onChange={(e) => setForm({ ...form, hebrew: e.target.value })} placeholder="דְּבָרִים" style={{ fontFamily: "var(--hebrew)", fontSize: 16 }} />
          </div>
        </div>
        <div className="field">
          <label>Descrição</label>
          <textarea rows="3" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} />
        </div>
        <div className="modal-actions">
          <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="btn btn-gold" onClick={save}>Criar curso</button>
        </div>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------------------
function MaterialsEditor({ materials, showToast }) {
  const KINDS = ["PDF", "Documento", "Áudio", "Vídeo", "Apostila", "Outro"];
  const CATEGORIES = ["Geral", "Torah", "Brit Chadashah", "Hebraico", "Tehilim", "Midrash", "Halachá", "Shiurim"];
  const classes = window.BNStore.getClasses();

  const [form, setForm] = useStateA({
    title: "", kind: "PDF", category: "Geral",
    description: "", driveUrl: "", hebrew: "", allowedClasses: [],
  });
  const [editingId, setEditingId] = useStateA(null);
  const [editForm, setEditForm] = useStateA({});

  function addMaterial() {
    if (!form.title) { showToast("Título é obrigatório"); return; }
    if (!form.driveUrl) { showToast("Link do Drive é obrigatório"); return; }
    if (!window.extractDriveId(form.driveUrl)) { showToast("Link do Drive inválido"); return; }
    window.BNStore.addMaterial(form);
    setForm({ title: "", kind: "PDF", category: "Geral", description: "", driveUrl: "", hebrew: "", allowedClasses: [] });
    showToast(`"${form.title}" adicionado à biblioteca`);
  }
  function startEdit(m) { setEditingId(m.id); setEditForm({ ...m, allowedClasses: m.allowedClasses || [] }); }
  function saveEdit() {
    window.BNStore.updateMaterial(editingId, editForm);
    setEditingId(null);
    showToast("Material atualizado");
  }

  function ClassPicker({ value, onChange }) {
    const selected = new Set(value || []);
    const toggleClass = (cid) => {
      const next = new Set(selected);
      if (next.has(cid)) next.delete(cid); else next.add(cid);
      onChange(Array.from(next));
    };
    return (
      <div className="field" style={{ marginTop: 12 }}>
        <label>Quais turmas podem ver este material?</label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6, padding: 10, border: "1px solid var(--ink-4)", borderRadius: 6, background: "var(--ink-1)" }}>
          <button
            type="button"
            onClick={() => onChange([])}
            className="pill"
            style={{
              cursor: "pointer", fontSize: 11,
              color: selected.size === 0 ? "var(--ok)" : "var(--bone-mute)",
              borderColor: selected.size === 0 ? "rgba(111,191,143,0.4)" : "var(--ink-4)",
              background: selected.size === 0 ? "rgba(111,191,143,0.06)" : "transparent",
            }}
          >✓ Todas as turmas</button>
          {classes.map((c) => {
            const on = selected.has(c.id);
            return (
              <button
                key={c.id}
                type="button"
                onClick={() => toggleClass(c.id)}
                className="pill"
                style={{
                  cursor: "pointer", fontSize: 11,
                  color: on ? "var(--gold)" : "var(--bone-mute)",
                  borderColor: on ? "var(--gold-deep)" : "var(--ink-4)",
                  background: on ? "rgba(212,173,90,0.08)" : "transparent",
                }}
              >{on ? "✓ " : ""}{c.name}</button>
            );
          })}
        </div>
        <div style={{ fontSize: 11, color: "var(--bone-mute)", marginTop: 4 }}>
          {selected.size === 0
            ? "Sem restrição — todos os alunos (de qualquer turma) verão este material."
            : `Apenas alunos das turmas marcadas verão este material. Você pode mudar isso a qualquer momento.`}
        </div>
      </div>
    );
  }

  return (
    <div>
      {/* Formulário de novo material */}
      <div style={{ padding: 20, background: "linear-gradient(180deg, rgba(20,19,26,0.6), rgba(13,12,18,0.6))", border: "1px solid var(--ink-3)", borderRadius: 10, marginBottom: 20 }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginBottom: 4, color: "var(--gold)" }}>＋ Subir material para a biblioteca</div>
        <div style={{ color: "var(--bone-mute)", fontSize: 12, marginBottom: 16 }}>
          Adicione qualquer documento do Google Drive — PDFs, apostilas, áudios. Materiais aparecem na biblioteca dos alunos aprovados.
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 12 }}>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Título</label>
            <input value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="Ex: Apostila Aleph-Bet Hebraico" />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Tipo</label>
            <select value={form.kind} onChange={(e) => setForm({ ...form, kind: e.target.value })}>
              {KINDS.map((k) => <option key={k}>{k}</option>)}
            </select>
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Categoria</label>
            <select value={form.category} onChange={(e) => setForm({ ...form, category: e.target.value })}>
              {CATEGORIES.map((c) => <option key={c}>{c}</option>)}
            </select>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "3fr 1fr", gap: 12, marginTop: 12 }}>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Descrição (opcional)</label>
            <input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Breve descrição do conteúdo" />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Título em hebraico (opcional)</label>
            <input value={form.hebrew} onChange={(e) => setForm({ ...form, hebrew: e.target.value })} placeholder="תּוֹרָה" style={{ fontFamily: "var(--hebrew)", fontSize: 15 }} />
          </div>
        </div>
        <DriveUrlField
          label="Link do Google Drive *"
          value={form.driveUrl}
          onChange={(v) => setForm({ ...form, driveUrl: v })}
        />
        <ClassPicker
          value={form.allowedClasses}
          onChange={(v) => setForm({ ...form, allowedClasses: v })}
        />
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 14 }}>
          <button className="btn btn-gold" onClick={addMaterial}>＋ Adicionar à biblioteca</button>
        </div>
      </div>

      {/* Tabela de materiais existentes */}
      <div className="admin-table">
        <table>
          <thead>
            <tr>
              <th>Material</th>
              <th>Tipo</th>
              <th>Categoria</th>
              <th>Turmas</th>
              <th>Link Drive</th>
              <th style={{ textAlign: "right" }}>Ações</th>
            </tr>
          </thead>
          <tbody>
            {materials.map((m) => (
              <React.Fragment key={m.id}>
                <tr>
                  <td>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 15 }}>{m.title}</div>
                    {m.description && <div style={{ fontSize: 12, color: "var(--bone-mute)", marginTop: 2 }}>{m.description}</div>}
                  </td>
                  <td>
                    <span className="pill pill-ok" style={{ fontSize: 10 }}>{m.kind}</span>
                  </td>
                  <td style={{ color: "var(--bone-dim)" }}>{m.category}</td>
                  <td>
                    {(!m.allowedClasses || m.allowedClasses.length === 0) ? (
                      <span className="pill pill-ok" style={{ fontSize: 10 }}>Todas</span>
                    ) : (
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
                        {m.allowedClasses.map((cid) => {
                          const cls = classes.find((c) => c.id === cid);
                          return (
                            <span key={cid} className="pill" style={{ fontSize: 10, color: "var(--gold)", borderColor: "var(--gold-deep)", background: "rgba(212,173,90,0.06)" }}>
                              {cls ? cls.name : cid}
                            </span>
                          );
                        })}
                      </div>
                    )}
                  </td>
                  <td>
                    <a href={m.driveUrl} target="_blank" rel="noreferrer" className="email" style={{ color: "var(--gold)", textDecoration: "underline" }}>
                      {window.extractDriveId(m.driveUrl)?.slice(0, 20)}…
                    </a>
                  </td>
                  <td>
                    <div className="row-actions">
                      <a className="icon-btn" title="Abrir no Drive" href={m.driveUrl} target="_blank" rel="noreferrer">↗</a>
                      <button className="icon-btn" title="Editar" onClick={() => startEdit(m)}>✎</button>
                      <button
                        className="icon-btn danger"
                        title="Remover"
                        onClick={() => {
                          if (!confirm(`Remover "${m.title}" da biblioteca?`)) return;
                          window.BNStore.removeMaterial(m.id);
                          showToast("Material removido");
                        }}
                      >✕</button>
                    </div>
                  </td>
                </tr>
                {editingId === m.id && (
                  <tr>
                    <td colSpan="6" style={{ background: "var(--ink-1)", padding: 20 }}>
                      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gap: 12 }}>
                        <div className="field"><label>Título</label><input value={editForm.title} onChange={(e) => setEditForm({ ...editForm, title: e.target.value })} /></div>
                        <div className="field"><label>Tipo</label>
                          <select value={editForm.kind} onChange={(e) => setEditForm({ ...editForm, kind: e.target.value })}>
                            {KINDS.map((k) => <option key={k}>{k}</option>)}
                          </select>
                        </div>
                        <div className="field"><label>Categoria</label>
                          <select value={editForm.category} onChange={(e) => setEditForm({ ...editForm, category: e.target.value })}>
                            {CATEGORIES.map((c) => <option key={c}>{c}</option>)}
                          </select>
                        </div>
                      </div>
                      <div className="field"><label>Descrição</label><textarea rows="2" value={editForm.description || ""} onChange={(e) => setEditForm({ ...editForm, description: e.target.value })} /></div>
                      <DriveUrlField label="Link do Google Drive" value={editForm.driveUrl || ""} onChange={(v) => setEditForm({ ...editForm, driveUrl: v })} />
                      <ClassPicker
                        value={editForm.allowedClasses}
                        onChange={(v) => setEditForm({ ...editForm, allowedClasses: v })}
                      />
                      <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 12 }}>
                        <button className="btn btn-ghost btn-sm" onClick={() => setEditingId(null)}>Cancelar</button>
                        <button className="btn btn-gold btn-sm" onClick={saveEdit}>Salvar alterações</button>
                      </div>
                    </td>
                  </tr>
                )}
              </React.Fragment>
            ))}
            {materials.length === 0 && (
              <tr><td colSpan="6" style={{ textAlign: "center", padding: 50, color: "var(--bone-mute)" }}>
                <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginBottom: 8 }}>Biblioteca vazia</div>
                <div style={{ fontSize: 13 }}>Use o formulário acima para subir seu primeiro material do Drive.</div>
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ----------------------------------------------------------------------------
function TeachersEditor({ teachers, showToast }) {
  const [form, setForm] = useStateA({ name: "", email: "", subjects: "", bio: "", password: "" });
  const [editingId, setEditingId] = useStateA(null);
  const [editForm, setEditForm] = useStateA({});
  const [pwdResetTarget, setPwdResetTarget] = useStateA(null);
  const [pwdResetValue, setPwdResetValue] = useStateA("");

  async function addTeacher() {
    if (!form.name) { showToast("Nome é obrigatório"); return; }
    if (!form.email) { showToast("Email é obrigatório para acesso de professor"); return; }
    window.BNStore.addTeacher({
      name: form.name,
      email: form.email,
      bio: form.bio,
      subjects: form.subjects ? form.subjects.split(",").map((s) => s.trim()) : [],
    });
    // Set password if provided
    if (form.password) {
      // wait for the addTeacher to settle (sync), then find the newly created teacher
      const created = window.BNStore.getTeachers().find((t) => t.email === form.email);
      if (created) await window.BNStore.setTeacherPassword(created.id, form.password);
    }
    setForm({ name: "", email: "", subjects: "", bio: "", password: "" });
    showToast(`${form.name} adicionado(a) ao corpo docente`);
  }
  function startEdit(t) {
    setEditingId(t.id);
    setEditForm({ ...t, subjects: (t.subjects || []).join(", ") });
  }
  function saveEdit() {
    window.BNStore.updateTeacher(editingId, {
      name: editForm.name, email: editForm.email, bio: editForm.bio,
      subjects: editForm.subjects ? editForm.subjects.split(",").map((s) => s.trim()) : [],
    });
    setEditingId(null);
    showToast("Professor atualizado");
  }
  async function resetTeacherPassword() {
    if (!pwdResetValue || pwdResetValue.length < 6) {
      showToast("Senha precisa ter pelo menos 6 caracteres");
      return;
    }
    await window.BNStore.setTeacherPassword(pwdResetTarget.id, pwdResetValue);
    setPwdResetTarget(null);
    setPwdResetValue("");
    showToast(`Senha de ${pwdResetTarget.name} definida`);
  }

  return (
    <div>
      {/* Form novo professor */}
      <div style={{ padding: 20, background: "linear-gradient(180deg, rgba(20,19,26,0.6), rgba(13,12,18,0.6))", border: "1px solid var(--ink-3)", borderRadius: 10, marginBottom: 20 }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginBottom: 4, color: "var(--gold)" }}>＋ Adicionar professor</div>
        <div style={{ color: "var(--bone-mute)", fontSize: 12, marginBottom: 16 }}>
          Professores aparecem como instrutores dos cursos. Eles <strong>não têm</strong> acesso ao painel administrativo.
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Nome completo *</label>
            <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Rav Eliezer Avraham" />
          </div>
          <div className="field" style={{ marginBottom: 0 }}>
            <label>Email para login *</label>
            <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="professor@beitnetzer.com" />
          </div>
        </div>
        <div className="field" style={{ marginTop: 12 }}>
          <label>Disciplinas (separadas por vírgula)</label>
          <input value={form.subjects} onChange={(e) => setForm({ ...form, subjects: e.target.value })} placeholder="Torah, Talmud, Hebraico" />
        </div>
        <div className="field">
          <label>Mini biografia</label>
          <textarea rows="2" value={form.bio} onChange={(e) => setForm({ ...form, bio: e.target.value })} placeholder="Breve descrição do mestre" />
        </div>
        <div className="field">
          <label>Senha inicial para acesso (mín. 6 caracteres)</label>
          <input type="password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} placeholder="Senha que o professor usará para entrar" />
          <div style={{ fontSize: 11, color: "var(--bone-mute)", marginTop: 4 }}>
            O professor usa <strong style={{ color: "var(--gold)" }}>email + senha</strong> no botão "כְּנִיסַת מוֹרִים" do topo. Você pode redefinir a senha depois.
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 14 }}>
          <button className="btn btn-gold" onClick={addTeacher}>＋ Adicionar professor</button>
        </div>
      </div>

      {/* Tabela */}
      <div className="admin-table">
        <table>
          <thead>
            <tr>
              <th>Professor</th>
              <th>Email</th>
              <th>Disciplinas</th>
              <th style={{ textAlign: "right" }}>Ações</th>
            </tr>
          </thead>
          <tbody>
            {teachers.map((t) => (
              <React.Fragment key={t.id}>
                <tr>
                  <td>
                    <div style={{ fontFamily: "var(--serif)", fontSize: 15 }}>{t.name}</div>
                    {t.bio && <div style={{ fontSize: 12, color: "var(--bone-mute)", marginTop: 2 }}>{t.bio}</div>}
                  </td>
                  <td className="email">{t.email || "—"}</td>
                  <td>
                    <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                      {(t.subjects || []).map((s) => (
                        <span key={s} className="pill" style={{ color: "var(--gold)", borderColor: "var(--gold-deep)", background: "rgba(212,173,90,0.05)", fontSize: 10 }}>{s}</span>
                      ))}
                    </div>
                  </td>
                  <td>
                    <div className="row-actions">
                      <button
                        className="icon-btn"
                        title={t.passwordHash ? "Redefinir senha" : "Definir senha de acesso"}
                        onClick={() => { setPwdResetTarget(t); setPwdResetValue(""); }}
                        style={{ color: t.passwordHash ? "var(--ok)" : "var(--warn)", borderColor: t.passwordHash ? "rgba(111,191,143,0.3)" : "rgba(217,154,74,0.3)" }}
                      >🔑</button>
                      <button className="icon-btn" title="Editar" onClick={() => startEdit(t)}>✎</button>
                      <button
                        className="icon-btn danger"
                        title="Remover"
                        onClick={() => {
                          if (!confirm(`Remover ${t.name}?`)) return;
                          window.BNStore.removeTeacher(t.id);
                          showToast("Professor removido");
                        }}
                      >✕</button>
                    </div>
                  </td>
                </tr>
                {editingId === t.id && (
                  <tr>
                    <td colSpan="5" style={{ background: "var(--ink-1)", padding: 20 }}>
                      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                        <div className="field"><label>Nome</label><input value={editForm.name} onChange={(e) => setEditForm({ ...editForm, name: e.target.value })} /></div>
                        <div className="field"><label>Email</label><input value={editForm.email || ""} onChange={(e) => setEditForm({ ...editForm, email: e.target.value })} /></div>
                      </div>
                      <div className="field"><label>Disciplinas</label><input value={editForm.subjects || ""} onChange={(e) => setEditForm({ ...editForm, subjects: e.target.value })} /></div>
                      <div className="field"><label>Biografia</label><textarea rows="2" value={editForm.bio || ""} onChange={(e) => setEditForm({ ...editForm, bio: e.target.value })} /></div>
                      <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
                        <button className="btn btn-ghost btn-sm" onClick={() => setEditingId(null)}>Cancelar</button>
                        <button className="btn btn-gold btn-sm" onClick={saveEdit}>Salvar</button>
                      </div>
                    </td>
                  </tr>
                )}
              </React.Fragment>
            ))}
            {teachers.length === 0 && (
              <tr><td colSpan="4" style={{ textAlign: "center", padding: 40, color: "var(--bone-mute)" }}>
                Nenhum professor cadastrado.
              </td></tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Password reset modal */}
      {pwdResetTarget && (
        <div className="modal-backdrop" onClick={(e) => e.target === e.currentTarget && setPwdResetTarget(null)}>
          <div className="modal">
            <h3>Senha de acesso — {pwdResetTarget.name}</h3>
            <p className="sub">
              {pwdResetTarget.passwordHash
                ? "Redefinir a senha do professor. Ele precisará usar a nova senha no próximo login."
                : "Defina uma senha para esse professor poder acessar pelo botão כְּנִיסַת מוֹרִים."}
            </p>
            <div className="field">
              <label>Email de login</label>
              <input value={pwdResetTarget.email} disabled style={{ opacity: 0.6 }} />
            </div>
            <div className="field">
              <label>Nova senha (mín. 6 caracteres)</label>
              <input
                type="password"
                value={pwdResetValue}
                onChange={(e) => setPwdResetValue(e.target.value)}
                autoFocus
                onKeyDown={(e) => e.key === "Enter" && resetTeacherPassword()}
              />
            </div>
            <div className="modal-actions">
              <button className="btn btn-ghost" onClick={() => setPwdResetTarget(null)}>Cancelar</button>
              <button className="btn btn-gold" onClick={resetTeacherPassword}>Salvar senha</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ----------------------------------------------------------------------------
function SettingsPanel({ showToast, onLock }) {
  const [current, setCurrent] = useStateA("");
  const [next, setNext] = useStateA("");
  const [confirm, setConfirm] = useStateA("");
  const [loading, setLoading] = useStateA(false);
  const sessions = window.BNStore.listActiveSessions();

  async function changePassword() {
    if (!current || !next) { showToast("Preencha todos os campos"); return; }
    if (next !== confirm) { showToast("As senhas novas não coincidem"); return; }
    if (next.length < 6) { showToast("Senha nova precisa de pelo menos 6 caracteres"); return; }
    setLoading(true);
    const ok = await window.BNStore.verifyAdminPassword(current);
    if (!ok) {
      setLoading(false);
      showToast("Senha atual incorreta");
      return;
    }
    await window.BNStore.setAdminPassword(next);
    setLoading(false);
    setCurrent(""); setNext(""); setConfirm("");
    showToast("Senha alterada com sucesso");
  }

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
      <div style={{ padding: 26, background: "rgba(20,19,26,0.6)", border: "1px solid var(--ink-3)", borderRadius: 10 }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 20, marginBottom: 4 }}>Trocar senha do administrador</div>
        <div style={{ color: "var(--bone-mute)", fontSize: 12, marginBottom: 20 }}>
          A senha protege o acesso a esta área. Use pelo menos 6 caracteres e prefira combinações fortes.
        </div>
        <div className="field">
          <label>Senha atual</label>
          <input type="password" value={current} onChange={(e) => setCurrent(e.target.value)} autoComplete="current-password" />
        </div>
        <div className="field">
          <label>Nova senha</label>
          <input type="password" value={next} onChange={(e) => setNext(e.target.value)} autoComplete="new-password" />
        </div>
        <div className="field">
          <label>Confirmar nova senha</label>
          <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} autoComplete="new-password" />
        </div>
        <button className="btn btn-gold" style={{ marginTop: 6 }} onClick={changePassword} disabled={loading}>
          {loading ? "Salvando…" : "Alterar senha"}
        </button>
      </div>

      <div style={{ padding: 26, background: "rgba(20,19,26,0.6)", border: "1px solid var(--ink-3)", borderRadius: 10 }}>
        <div style={{ fontFamily: "var(--serif)", fontSize: 20, marginBottom: 4 }}>Segurança</div>
        <div style={{ color: "var(--bone-mute)", fontSize: 12, marginBottom: 20 }}>
          Controles de sessão e proteção da área administrativa.
        </div>

        <div style={{ padding: 14, background: "rgba(212,173,90,0.05)", border: "1px solid rgba(212,173,90,0.2)", borderRadius: 8, marginBottom: 16 }}>
          <div style={{ fontSize: 13, color: "var(--gold)", marginBottom: 6, letterSpacing: "0.05em" }}>Admin atual</div>
          <div style={{ fontFamily: "var(--mono)", fontSize: 13 }}>marcelo.santos304@gmail.com</div>
          <div style={{ fontSize: 11, color: "var(--bone-mute)", marginTop: 6 }}>
            Apenas este email vê o link "Admin" na navegação.
          </div>
        </div>

        <button className="btn btn-ghost" style={{ width: "100%", marginBottom: 10 }} onClick={onLock}>
          ⌬ &nbsp;Bloquear painel agora
        </button>

        <div style={{ fontSize: 11, color: "var(--bone-mute)", lineHeight: 1.6, marginTop: 14, padding: 12, background: "var(--ink-1)", border: "1px solid var(--ink-3)", borderRadius: 6 }}>
          <strong style={{ color: "var(--warn)" }}>⚠ Observação de segurança:</strong><br />
          Esta é uma camada de proteção local (cliente). A senha fica como hash SHA-256 no navegador.
          Para segurança real em produção, a verificação deve ocorrer no servidor —
          o que acontece automaticamente quando você migrar para Supabase
          (ver guia em <code>production/</code>).
        </div>
      </div>

      {/* Sessões ativas */}
      <div style={{ gridColumn: "1 / -1", padding: 26, background: "rgba(20,19,26,0.6)", border: "1px solid var(--ink-3)", borderRadius: 10 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
          <div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 20, marginBottom: 4 }}>Sessões ativas</div>
            <div style={{ color: "var(--bone-mute)", fontSize: 12 }}>
              {sessions.length === 0
                ? "Ninguém está logado no momento."
                : `${sessions.length} pessoa(s) logada(s) agora`}
            </div>
          </div>
          {sessions.length > 0 && (
            <button
              className="btn btn-ghost btn-sm"
              style={{ color: "var(--err)", borderColor: "rgba(194,90,90,0.3)" }}
              onClick={() => {
                if (!confirm("Encerrar TODAS as sessões ativas?")) return;
                sessions.forEach((s) => window.BNStore.forceEndSession(s.email));
                showToast("Todas as sessões encerradas");
              }}
            >⏏ Encerrar todas</button>
          )}
        </div>

        {sessions.length > 0 && (
          <div style={{ border: "1px solid var(--ink-3)", borderRadius: 8, overflow: "hidden" }}>
            <table style={{ width: "100%", borderCollapse: "collapse" }}>
              <thead>
                <tr>
                  <th style={{ textAlign: "left", padding: "10px 14px", fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--bone-mute)", background: "var(--ink-1)", borderBottom: "1px solid var(--ink-3)" }}>Email</th>
                  <th style={{ textAlign: "left", padding: "10px 14px", fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--bone-mute)", background: "var(--ink-1)", borderBottom: "1px solid var(--ink-3)" }}>Conectou em</th>
                  <th style={{ textAlign: "right", padding: "10px 14px", fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase", color: "var(--bone-mute)", background: "var(--ink-1)", borderBottom: "1px solid var(--ink-3)" }}>Ação</th>
                </tr>
              </thead>
              <tbody>
                {sessions.map((s) => (
                  <tr key={s.email}>
                    <td className="email" style={{ padding: "12px 14px", borderBottom: "1px solid var(--ink-3)" }}>{s.email}</td>
                    <td style={{ padding: "12px 14px", borderBottom: "1px solid var(--ink-3)", color: "var(--bone-dim)", fontSize: 12 }}>
                      {new Date(s.startedAt).toLocaleString("pt-BR")}
                    </td>
                    <td style={{ padding: "12px 14px", borderBottom: "1px solid var(--ink-3)", textAlign: "right" }}>
                      <button
                        className="btn btn-ghost btn-sm"
                        style={{ color: "var(--err)", borderColor: "rgba(194,90,90,0.3)" }}
                        onClick={() => {
                          window.BNStore.forceEndSession(s.email);
                          showToast(`Sessão de ${s.email} encerrada`);
                        }}
                      >⏏ Encerrar</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <div style={{ fontSize: 11, color: "var(--bone-mute)", lineHeight: 1.6, marginTop: 16, padding: 12, background: "rgba(217,154,74,0.05)", border: "1px solid rgba(217,154,74,0.2)", borderRadius: 6 }}>
          <strong style={{ color: "var(--warn)" }}>Como funciona a proteção:</strong><br />
          • Se um aluno entrar com o mesmo email em outro navegador/tab, a sessão antiga é encerrada automaticamente (~4 segundos).<br />
          • Você pode encerrar manualmente qualquer sessão a partir desta lista.<br />
          • <strong>Limitação atual:</strong> sem servidor, navegadores em computadores diferentes não conseguem "ver" um ao outro. A proteção total contra compartilhamento entre dispositivos vem com Supabase.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AdminPage, AdminGate });

// ----------------------------------------------------------------------------
function AccessLogPanel({ showToast }) {
  const log = window.BNStore.getAccessLog();
  const classes = window.BNStore.getClasses();
  const activeSessions = window.BNStore.listActiveSessions();
  const activeEmails = new Set(activeSessions.map((s) => s.email));
  const [search, setSearch] = useStateA("");

  const filtered = log.filter((a) =>
    !search ||
    a.name.toLowerCase().includes(search.toLowerCase()) ||
    a.email.toLowerCase().includes(search.toLowerCase())
  );

  const fmt = (iso) => new Date(iso).toLocaleString("pt-BR", { day: "2-digit", month: "2-digit", year: "2-digit", hour: "2-digit", minute: "2-digit" });
  const duration = (a) => {
    if (!a.loggedInAt) return "—";
    const end = a.loggedOutAt ? new Date(a.loggedOutAt) : new Date();
    const sec = Math.round((end - new Date(a.loggedInAt)) / 1000);
    if (sec < 60) return `${sec}s`;
    const mins = Math.floor(sec / 60);
    if (mins < 60) return `${mins} min`;
    return `${Math.floor(mins / 60)}h ${mins % 60}min`;
  };

  return (
    <div>
      <div style={{ display: "flex", gap: 12, marginBottom: 16, alignItems: "center" }}>
        <input
          className="search"
          placeholder="Buscar por nome ou email…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          style={{ flex: 1, maxWidth: 360 }}
        />
        <span style={{ fontSize: 12, color: "var(--bone-mute)" }}>
          {activeSessions.length} ativo(s) · {log.length} registro(s)
        </span>
        {log.length > 0 && (
          <button
            className="btn btn-ghost btn-sm"
            style={{ color: "var(--err)", borderColor: "rgba(194,90,90,0.3)", marginLeft: "auto" }}
            onClick={() => {
              if (!confirm("Apagar todo o histórico de acessos?")) return;
              window.BNStore.clearAccessLog();
              showToast("Histórico limpo");
            }}
          >⟲ Limpar histórico</button>
        )}
      </div>

      <div className="admin-table">
        <table>
          <thead>
            <tr>
              <th>Aluno</th>
              <th>Email</th>
              <th>Turma</th>
              <th>Entrou</th>
              <th>Saiu</th>
              <th>Duração</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((a) => {
              const cls = classes.find((c) => c.id === a.classId);
              const isActive = activeEmails.has(a.email) && !a.loggedOutAt;
              return (
                <tr key={a.id}>
                  <td style={{ fontFamily: "var(--serif)", fontSize: 14 }}>{a.name}</td>
                  <td className="email">{a.email}</td>
                  <td>
                    {cls ? (
                      <span className="pill" style={{ color: "var(--gold)", borderColor: "var(--gold-deep)", background: "rgba(212,173,90,0.06)", fontSize: 10 }}>{cls.name}</span>
                    ) : a.role === "admin" ? (
                      <span className="pill pill-ok" style={{ fontSize: 10 }}>Admin</span>
                    ) : a.role === "teacher" ? (
                      <span className="pill pill-warn" style={{ fontSize: 10 }}>Professor</span>
                    ) : (
                      <span style={{ color: "var(--bone-mute)", fontSize: 12 }}>—</span>
                    )}
                  </td>
                  <td style={{ color: "var(--bone-dim)", fontSize: 12 }}>{fmt(a.loggedInAt)}</td>
                  <td style={{ color: "var(--bone-dim)", fontSize: 12 }}>{a.loggedOutAt ? fmt(a.loggedOutAt) : "—"}</td>
                  <td style={{ color: "var(--bone-dim)", fontFamily: "var(--mono)", fontSize: 12 }}>{duration(a)}</td>
                  <td>
                    {isActive ? (
                      <span className="pill pill-ok" style={{ fontSize: 10 }}>Online</span>
                    ) : (
                      <span style={{ color: "var(--bone-mute)", fontSize: 11 }}>Encerrado</span>
                    )}
                  </td>
                </tr>
              );
            })}
            {filtered.length === 0 && (
              <tr><td colSpan="7" style={{ textAlign: "center", padding: 50, color: "var(--bone-mute)" }}>
                <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginBottom: 8 }}>Nenhum acesso registrado</div>
                <div style={{ fontSize: 13 }}>Logins de alunos, professores e admin aparecerão aqui.</div>
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.AccessLogPanel = AccessLogPanel;
