"use client";
import { useEffect, useState, Suspense } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth/useAuth";
import { hasLiveSession } from "@/lib/api/mode";
import { isDemoPreviewSession } from "@/lib/auth/auth-client";
import { getPublicDemoMode } from "@/lib/env";
import { CleanSidebar } from "./CleanSidebar";
import { CleanHeader } from "./CleanHeader";
const isLiveFrontendMode = getPublicDemoMode() === "live";
// =============================================================================
// CleanAppLayout — full-bleed light workspace. One top-left menu opens the nav
// drawer at every breakpoint (no permanent rail, no bottom tab bar).
// =============================================================================
type CleanAppLayoutProps = {
children: React.ReactNode;
};
function LoadingFallback() {
return (
Preparing your study space…
);
}
export function CleanAppLayout({ children }: CleanAppLayoutProps) {
const router = useRouter();
const pathname = usePathname();
const { isLoading: isAuthLoading } = useAuth();
const [navOpen, setNavOpen] = useState(false);
const isLocalTuitionBetaRoute =
pathname === "/tuition" || pathname?.startsWith("/tuition/");
// ── Auth guard ──
const unauthenticated =
!isLocalTuitionBetaRoute &&
isLiveFrontendMode &&
!hasLiveSession() &&
!isDemoPreviewSession();
useEffect(() => {
if (!isLocalTuitionBetaRoute && !isAuthLoading && unauthenticated) {
const next = encodeURIComponent(pathname ?? "/home");
router.replace(`/login?next=${next}`);
}
}, [isAuthLoading, isLocalTuitionBetaRoute, unauthenticated, pathname, router]);
const blockChildren =
!isLocalTuitionBetaRoute && (isAuthLoading || unauthenticated);
// Close the drawer on route change.
useEffect(() => {
const t = window.setTimeout(() => setNavOpen(false), 0);
return () => window.clearTimeout(t);
}, [pathname]);
// Escape closes; lock body scroll while the drawer is open.
useEffect(() => {
if (!navOpen) return;
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") setNavOpen(false);
}
window.addEventListener("keydown", onKeyDown);
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
window.removeEventListener("keydown", onKeyDown);
document.body.style.overflow = prevOverflow;
};
}, [navOpen]);
const closeNav = () => setNavOpen(false);
return (
setNavOpen(true)} />
{/* ── Nav drawer (all breakpoints) ── */}
{navOpen && (
)}
{/* ── Main content ── */}
}>
{blockChildren ? (
) : (
{children}
)}
);
}