/* global React, ReactDOM, YESHIVAH_DATA,
   Nav, Toast,
   LandingPage, LoginPage, DashboardPage,
   CoursePage, LessonPage, AdminPage */
const { useState, useEffect } = React;

function App() {
  const [user, setUser] = useState(null);
  const [page, setPage] = useState("landing");
  const [activeCourse, setActiveCourse] = useState(null);
  const [activeLesson, setActiveLesson] = useState(null);
  const [scrolled, setScrolled] = useState(false);
  const [toast, setToast] = useState(null);
  const [sessionToken, setSessionToken] = useState(null);
  // Admin password gate — true if password was verified in this browser tab
  const [adminUnlocked, setAdminUnlocked] = useState(
    () => sessionStorage.getItem("bn-admin-unlocked") === "1"
  );
  // Force re-render whenever store changes
  const [storeVersion, setStoreVersion] = useState(0);
  useEffect(() => window.BNStore.subscribe(() => setStoreVersion((v) => v + 1)), []);

  // Session enforcement — checa a cada 4 segundos se a sessão ainda é válida.
  // Se outro login com o mesmo email aconteceu (mesmo navegador), derruba a sessão atual.
  useEffect(() => {
    if (!user || !sessionToken) return;
    const interval = setInterval(() => {
      const valid = window.BNStore.isSessionValid(user.email, sessionToken);
      if (!valid) {
        setUser(null);
        setSessionToken(null);
        setPage("landing");
        setActiveCourse(null);
        setActiveLesson(null);
        sessionStorage.removeItem("bn-admin-unlocked");
        setAdminUnlocked(false);
        setToast("Sua sessão foi encerrada porque este email foi acessado em outro lugar.");
      }
    }, 4000);
    return () => clearInterval(interval);
  }, [user, sessionToken]);

  useEffect(() => {
    function onScroll() { setScrolled(window.scrollY > 30); }
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Scroll to top on page change
  useEffect(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [page, activeCourse, activeLesson]);

  const data = {
    ...YESHIVAH_DATA,
    courses: window.BNStore.getCourses(),
    bereshitLessons: window.BNStore.getLessons("torah-bereshit"),
    adminUsers: window.BNStore.getStudents(),
    approvedEmails: window.BNStore.getApprovedEmails(),
  };

  function go(p) {
    if (p === "courses" || p === "library") {
      // For demo, jump to dashboard with toast
      setPage("dashboard");
      setToast(p === "courses" ? "Catálogo completo" : "Biblioteca");
      return;
    }
    setPage(p);
  }
  function openCourse(course) {
    setActiveCourse(course);
    setPage("course");
  }
  function openLesson(lesson) {
    setActiveLesson(lesson);
    setPage("lesson");
  }
  function handleLogin(u) {
    // Inicia sessão (invalida qualquer sessão anterior do mesmo email)
    const token = window.BNStore.startSession(u.email);
    setSessionToken(token);
    // Salva perfil pra próxima vez (estilo Disney+)
    window.BNStore.saveRecentProfile(u.email, u.name, u.role);
    setUser(u);
    setPage("dashboard");
    setToast(`Shalom, ${u.name.split(" ")[0]} — bem-vindo(a) ao Beit Midrash`);
  }
  function logout() {
    if (user) window.BNStore.endSession(user.email);
    setUser(null);
    setSessionToken(null);
    setPage("landing");
    setActiveCourse(null);
    setActiveLesson(null);
    setAdminUnlocked(false);
    sessionStorage.removeItem("bn-admin-unlocked");
    setToast("Sessão encerrada");
  }

  function unlockAdmin() {
    setAdminUnlocked(true);
    sessionStorage.setItem("bn-admin-unlocked", "1");
  }
  function lockAdmin() {
    setAdminUnlocked(false);
    sessionStorage.removeItem("bn-admin-unlocked");
    setPage("dashboard");
  }

  // Guard: any page except landing/login requires user
  const protectedPages = ["dashboard", "course", "lesson", "admin"];
  useEffect(() => {
    if (protectedPages.includes(page) && !user) setPage("login");
  }, [page, user]);

  let content;
  if (page === "landing") {
    content = <LandingPage go={go} />;
  } else if (page === "login") {
    content = <LoginPage onLogin={handleLogin} approvedEmails={data.approvedEmails} />;
  } else if (page === "professor-login") {
    content = <ProfessorLoginPage onLogin={handleLogin} goBack={() => setPage("landing")} />;
  } else if (page === "dashboard") {
    content = <DashboardPage user={user} go={go} openCourse={openCourse} data={data} />;
  } else if (page === "course") {
    // Permission check
    if (user && user.role === "student" && !window.BNStore.studentCanAccessCourse(user.email, activeCourse.id)) {
      content = (
        <main style={{ padding: 80, textAlign: "center", minHeight: "60vh" }}>
          <div style={{ fontFamily: "var(--hebrew)", color: "var(--gold)", fontSize: 26, marginBottom: 16 }}>אֵין גִּישָׁה</div>
          <h2 style={{ fontFamily: "var(--serif)", fontSize: 32 }}>Acesso restrito</h2>
          <p style={{ color: "var(--bone-mute)", maxWidth: 460, margin: "12px auto 24px", lineHeight: 1.6 }}>
            Você ainda não tem permissão para acessar este curso. Contate a administração.
          </p>
          <button className="btn btn-gold" onClick={() => setPage("dashboard")}>Voltar ao dashboard</button>
        </main>
      );
    } else {
      // Pull lessons from the store; if course has none, synthesize so the UI isn't empty
      const stored = window.BNStore.getLessons(activeCourse.id);
      const lessons = stored.length > 0
        ? stored
        : Array.from({ length: Math.max(3, Math.min(activeCourse.lessonsCount || 5, 8)) }, (_, i) => ({
            id: i + 1,
            title: `Aula ${i + 1} — ${activeCourse.title.split(" — ")[0] || activeCourse.title}`,
            duration: 30 + ((i * 7) % 25) + " min",
            status: i === 0 ? "completed" : i === 1 ? "in_progress" : "not_started",
            desc: "Estudo guiado com leitura do texto original, comentários clássicos e aplicação prática.",
          }));
      content = (
        <CoursePage
          course={activeCourse}
          lessons={lessons}
          go={go}
          openLesson={openLesson}
        />
      );
    }
  } else if (page === "lesson") {
    const stored = window.BNStore.getLessons(activeCourse.id);
    const lessons = stored.length > 0
      ? stored
      : Array.from({ length: 5 }, (_, i) => ({
          id: i + 1,
          title: `Aula ${i + 1}`,
          duration: 30 + i * 5 + " min",
          status: "not_started",
          desc: "Estudo guiado.",
        }));
    content = (
      <LessonPage
        course={activeCourse}
        lesson={activeLesson || lessons[0]}
        lessons={lessons}
        go={go}
        openLesson={openLesson}
        openCourse={openCourse}
      />
    );
  } else if (page === "admin") {
    if (!adminUnlocked) {
      content = <AdminGate onUnlock={unlockAdmin} onCancel={() => setPage("dashboard")} showToast={setToast} />;
    } else {
      content = <AdminPage data={data} showToast={setToast} onLock={lockAdmin} />;
    }
  }

  const showNav = page !== "login" && page !== "professor-login";

  return (
    <div className="app-root">
      {showNav && (
        <Nav user={user} currentPage={page} go={go} scrolled={scrolled} onLogout={logout} />
      )}
      {content}
      <Toast msg={toast} onDone={() => setToast(null)} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
