import { lazy, Suspense, useEffect, useState } from "react";
import { Routes, Route, Navigate, useLocation } from "react-router-dom";
import { ClassGate } from "@/components/guards/ClassGate";
import { AccountGuard } from "@/components/guards/AccountGuard";
import { SchoolSubdomainGuard } from "@/components/guards/SchoolSubdomainGuard";
import { AdminGuard } from "@/components/admin/AdminGuard";
import { OfflineBanner } from "@/components/OfflineBanner";
import { useIsOffline } from "@/components/OfflineFullScreen";
import { PageSkeleton } from "@/components/PageSkeleton";
import { MaintenanceGate } from "@/components/MaintenanceGate";
import { PageLayout } from "@/components/layout/PageLayout";
import { useAuthReady } from "@/hooks/useAuthReady";
import { SeniorOnlyGuard } from "@/components/guards/SeniorOnlyGuard";
import { useUserProfile } from "@/contexts/UserProfileContext";
import { isJunior } from "@/lib/grade-tier";
import { isNativeLikeShell } from "@/lib/pwa-standalone";
import { SupportChatProvider } from "@/contexts/SupportChatContext";
import { useSchoolBranding } from "@/contexts/SchoolBrandingContext";
import { NativePageTransition } from "@/components/native/NativePageTransition";
import { NativeShell } from "@/components/native/NativeShell";
import { useShell } from "@/hooks/useShell";
import { isNativeSchoolBuild } from "@/lib/subdomain";

/* ── Floating widgets / portals: lazy-loaded so they DON'T block first paint.
 *    These all mount post-auth and only render conditionally on private routes,
 *    so deferring them shaves ~120-300ms off the first MainApp chunk.        */
const XPFloatingPortal     = lazy(() => import("@/components/gamification/XPFloatingPopup").then(m => ({ default: m.XPFloatingPortal })));
const LiveChatWidget       = lazy(() => import("@/components/support/LiveChatWidget").then(m => ({ default: m.LiveChatWidget })));
const LiveClassPopup       = lazy(() => import("@/components/LiveClassPopup").then(m => ({ default: m.LiveClassPopup })));
const BadgeUnlockPortal    = lazy(() => import("@/components/gamification/BadgeUnlockPortal").then(m => ({ default: m.BadgeUnlockPortal })));
const LevelUpCelebration   = lazy(() => import("@/components/gamification/LevelUpCelebration").then(m => ({ default: m.LevelUpCelebration })));
const PWAInstallPrompt     = lazy(() => import("@/components/PWAInstallPrompt").then(m => ({ default: m.PWAInstallPrompt })));
const FirstLoginConsent    = lazy(() => import("@/components/onboarding/FirstLoginConsent").then(m => ({ default: m.FirstLoginConsent })));
const BugReportButton      = lazy(() => import("@/components/pilot/BugReportButton").then(m => ({ default: m.BugReportButton })));
const AdPopup              = lazy(() => import("@/components/AdPopup").then(m => ({ default: m.AdPopup })));
const NativeBootSplash     = lazy(() => import("@/components/native/NativeBootSplash").then(m => ({ default: m.NativeBootSplash })));

/* ── Core pages: lazy-loaded to reduce initial bundle ── */
const Dashboard = lazy(() => import("@/pages/Dashboard"));
const NativeHomeScreen = lazy(() => import("@/screens/native/HomeScreen"));
const NativeProfileScreen = lazy(() => import("@/screens/native/ProfileScreen"));
const NativeStudyScreen = lazy(() => import("@/screens/native/StudyScreen"));
const NativeNoticesScreen = lazy(() => import("@/screens/native/NoticesScreen"));
const NativeMarksScreen = lazy(() => import("@/screens/native/MarksScreen"));
const NativeLeaderboardScreen = lazy(() => import("@/screens/native/LeaderboardScreen"));
const NativeBookmarksScreen = lazy(() => import("@/screens/native/BookmarksScreen"));
const NativeSettingsScreen = lazy(() => import("@/screens/native/SettingsScreen"));
const NativeForumScreen = lazy(() => import("@/screens/native/ForumScreen"));
const NativeClassroomScreen = lazy(() => import("@/screens/native/ClassroomScreen"));
const NativeClassGroupScreen = lazy(() => import("@/screens/native/ClassGroupScreen"));
const NativeAITutorScreen = lazy(() => import("@/screens/native/AITutorScreen"));
const NotificationSettings = lazy(() => import("@/pages/NotificationSettings"));
const NotificationDebug = lazy(() => import("@/pages/NotificationDebug"));
const NotificationPermissionExplainer = lazy(() => import("@/components/notifications/NotificationPermissionExplainer").then(m => ({ default: m.NotificationPermissionExplainer })));
const AppPermissionsExplainer = lazy(() => import("@/components/notifications/AppPermissionsExplainer").then(m => ({ default: m.AppPermissionsExplainer })));
const PermissionsSettings = lazy(() => import("@/pages/PermissionsSettings"));
const NativeMCQScreen = lazy(() => import("@/screens/native/MCQScreen"));
const NativePhotoSolveScreen = lazy(() => import("@/screens/native/PhotoSolveScreen"));
const NativeNoteReaderScreen = lazy(() => import("@/screens/native/NoteReaderScreen"));
const NativeLoginScreen = lazy(() => import("@/screens/native/LoginScreen"));
const SchoolBrandedHome = lazy(() => import("@/pages/school/SchoolBrandedHome"));
const SchoolDownloadApps = lazy(() => import("@/pages/school/SchoolDownloadApps"));
const JuniorDashboard = lazy(() => import("@/pages/JuniorDashboard"));
const StudyMaterials = lazy(() => import("@/pages/StudyMaterials"));
const NoteReader = lazy(() => import("@/pages/NoteReader"));
const AiTutor = lazy(() => import("@/pages/AiTutor"));
const AITools = lazy(() => import("@/pages/AITools"));
const AIToolPage = lazy(() => import("@/pages/AIToolPage"));
const McqPractice = lazy(() => import("@/pages/McqPractice"));
const MockTests = lazy(() => import("@/pages/MockTests"));
const Login = lazy(() => import("@/pages/Login"));
const Signup = lazy(() => import("@/pages/Signup"));
const ChangePassword = lazy(() => import("@/pages/ChangePassword"));

/* ── Landing: lazy-loaded ── */
const Index = lazy(() => import("@/pages/Index"));
const Welcome = lazy(() => import("@/pages/Welcome"));
const About = lazy(() => import("@/pages/About"));
const Privacy = lazy(() => import("@/pages/Privacy"));
const Terms = lazy(() => import("@/pages/Terms"));
const Contact = lazy(() => import("@/pages/Contact"));
const FAQ = lazy(() => import("@/pages/FAQ"));
const Features = lazy(() => import("@/pages/Features"));
const PricingPage = lazy(() => import("@/pages/PricingPage"));
const PaymentSuccess = lazy(() => import("@/pages/PaymentSuccess"));
const PaymentFailed = lazy(() => import("@/pages/PaymentFailed"));
const NotFound = lazy(() => import("@/pages/NotFound"));
const PastPapers = lazy(() => import("@/pages/PastPapers"));
const ProgressTracking = lazy(() => import("@/pages/ProgressTracking"));
const HelpCenter = lazy(() => import("@/pages/HelpCenter"));
const StudyGuide = lazy(() => import("@/pages/StudyGuide"));
const Downloads = lazy(() => import("@/pages/Downloads"));
const Careers = lazy(() => import("@/pages/Careers"));
const Blog = lazy(() => import("@/pages/Blog"));
const Press = lazy(() => import("@/pages/Press"));
const Partners = lazy(() => import("@/pages/Partners"));
const SystemStatus = lazy(() => import("@/pages/SystemStatus"));
const AcceptInvite = lazy(() => import("@/pages/AcceptInvite"));
const Onboarding = lazy(() => import("@/pages/Onboarding"));
const Profile = lazy(() => import("@/pages/Profile"));
const ProfileMore = lazy(() => import("@/pages/profile/ProfileMore"));
const CommunityChat = lazy(() => import("@/pages/CommunityChat"));
const Bookmarks = lazy(() => import("@/pages/Bookmarks"));
const Notifications = lazy(() => import("@/pages/Notifications"));
const SettingsPage = lazy(() => import("@/pages/SettingsPage"));
const GlobalSearch = lazy(() => import("@/pages/GlobalSearch"));
const StudyPlanner = lazy(() => import("@/pages/StudyPlanner"));
const SmartTimetable = lazy(() => import("@/pages/SmartTimetable"));
const FlashcardsPage = lazy(() => import("@/pages/FlashcardsPage"));
const RevisionPlanner = lazy(() => import("@/pages/RevisionPlanner"));
const Leaderboard = lazy(() => import("@/pages/Leaderboard"));
const ImportantQuestions = lazy(() => import("@/pages/ImportantQuestions"));
const SupportTickets = lazy(() => import("@/pages/SupportTickets"));
const SupportCenter = lazy(() => import("@/pages/SupportCenter"));
const Forum = lazy(() => import("@/pages/Forum"));
const ForumQuestion = lazy(() => import("@/pages/ForumQuestion"));
const PhotoSolve = lazy(() => import("@/pages/PhotoSolve"));
const NEBStudy = lazy(() => import("@/pages/NEBStudy"));
const BlogPost = lazy(() => import("@/pages/BlogPost"));
const TicketDetail = lazy(() => import("@/pages/TicketDetail"));
const LiveClass = lazy(() => import("@/pages/LiveClass"));
const SchoolDirectory = lazy(() => import("@/pages/public/SchoolDirectory"));
const SchoolPublicProfile = lazy(() => import("@/pages/public/SchoolPublicProfile"));
const ForSchools = lazy(() => import("@/pages/ForSchools"));
const SwitchFromVeda = lazy(() => import("@/pages/SwitchFromVeda"));
const StudentMarks = lazy(() => import("@/pages/StudentMarks"));
const StudentClassGroup = lazy(() => import("@/pages/StudentClassGroup"));
const MyClassroom = lazy(() => import("@/pages/MyClassroom"));
const TeacherLanding = lazy(() => import("@/pages/teacher/TeacherLanding"));
const ParentLanding = lazy(() => import("@/pages/parent/ParentLanding"));
const Arena = lazy(() => import("@/pages/Arena"));
const NepaliCalendar = lazy(() => import("@/pages/NepaliCalendar"));

/* ── Prefetch high-traffic dashboard routes during idle time so
 *    nav from Dashboard → MCQ / AI Tutor / Study Materials feels
 *    instant. Centralised in src/lib/route-prefetch.ts.            */
import { prefetchOnIdle } from "@/lib/route-prefetch";
if (typeof window !== "undefined") {
  // On a school subdomain (white-label) the cohort rarely visits non-core
  // routes — prefetching 8 chunks on Nepali 4G hurts cold-start. Strip the
  // prefetch list down to the 3 most-used screens for school users.
  const isWhiteLabelHost = (() => {
    try {
      const h = window.location.hostname;
      return h.endsWith(".nepeduai.com") &&
        !["nepeduai.com", "www.nepeduai.com", "teacher.nepeduai.com",
          "parent.nepeduai.com", "parents.nepeduai.com",
          "school.nepeduai.com", "adminmanager.nepeduai.com",
          "adminmanage.nepeduai.com", "status.nepeduai.com",
          "career.nepeduai.com"].includes(h);
    } catch { return false; }
  })();
  prefetchOnIdle(
    isWhiteLabelHost
      ? ["/dashboard", "/study-materials", "/profile"]
      : [
          "/dashboard",
          "/study-materials",
          "/ai-tutor",
          "/mcq-practice",
          "/progress-tracking",
          "/profile",
          "/notifications",
          "/settings",
        ]
  );
}

/**
 * MainApp — root shell for nepeduai.com (consumer/student) and white-label
 * school subdomains.
 *
 * Pre-login home matrix (the most-asked question in this file):
 *   • White-label school host       → SchoolBrandedHome (school's branded landing)
 *   • Capacitor APK / installed PWA → <Welcome /> (minimal Log in / Create account)
 *   • Plain web browser             → <Index /> (full marketing landing)
 *
 * See `pickHomeElement()` below for the exact decision tree.
 */

/** Routes where student/app overlays should NOT render */
const PUBLIC_ROUTES = ["/", "/login", "/signup", "/about", "/contact", "/faq", "/privacy", "/terms", "/features", "/pricing", "/careers", "/blog", "/press", "/partners", "/teacher", "/parent", "/neb-study"];

function isPublicRoute(pathname: string): boolean {
  return PUBLIC_ROUTES.includes(pathname) || pathname.startsWith("/blog/") || pathname.startsWith("/schools");
}

/**
 * Decide what to render at `/` for a signed-out visitor.
 * Read top-to-bottom — first matching branch wins.
 */
function pickHomeElement(opts: {
  isReady: boolean;
  hasSession: boolean;
  treatAsWhiteLabel: boolean;
  isNativeApp: boolean;
}): JSX.Element {
  if (!opts.isReady)            return <PageSkeleton />;
  if (opts.hasSession)          return <Navigate to="/dashboard" replace />;
  if (opts.treatAsWhiteLabel)   return <SchoolBrandedHome />;
  if (opts.isNativeApp)         return <Welcome />;
  return <Index />;
}

export default function MainApp() {
  const { pathname } = useLocation();
  const isPublic = isPublicRoute(pathname);
  const { isReady, session } = useAuthReady();
  // Treat both Capacitor native and installed PWA (iOS Home Screen / Android
  // standalone) as "native shell" — no marketing landing, login-first, etc.
  const isNativeApp = isNativeLikeShell();
  const { isWhiteLabel } = useSchoolBranding();
  // School APK identity is known synchronously from the bundled
  // app-config.json BEFORE branding RPC resolves — use it to gate every
  // "show NepEduAI marketing" decision so users never see a flash of
  // the wrong brand on cold launch.
  const isSchoolApk = isNativeSchoolBuild();
  const treatAsWhiteLabel = isWhiteLabel || isSchoolApk;
  const shell = useShell(); // "native" on phone-sized native/installed shells, else "desktop"
  const useNativeShell = shell === "native" && session?.user && !isPublic;
  const offline = useIsOffline();
  // Only block the entire UI when we're in the native/installed shell —
  // a regular web tab keeps the thin OfflineBanner + their cached page.
  const blockForOffline = offline && isNativeApp;

  // Defer mounting of secondary portals (XP popups, badge unlock, level-up,
  // live-class popup, ad popup, first-login consent) until 3s after first
  // paint. Their chunks otherwise fetch eagerly and slow cold-start.
  const [portalsReady, setPortalsReady] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setPortalsReady(true), 3000);
    return () => clearTimeout(t);
  }, []);
  // True Capacitor APK / installed PWA (NOT a school subdomain). School
  // subdomains keep the branded landing for signed-out users.
  const isInstalledShell = typeof window !== "undefined" && (
    Boolean((window as any).Capacitor?.isNativePlatform?.()) || (() => {
      try {
        return (window.navigator as any).standalone === true ||
          window.matchMedia?.("(display-mode: standalone)").matches;
      } catch { return false; }
    })()
  );

  const authGate = (publicElement: JSX.Element) => {
    if (!isReady) return <PageSkeleton />;
    if (session?.user) return <Navigate to="/dashboard" replace />;
    return publicElement;
  };

  /**
   * Native (APK / installed PWA): public routes redirect login-first.
   * School subdomains: keep the branded landing on `/`, but redirect other
   * marketing routes (`/about`, `/pricing`, …) to login as well.
   */
  const nativePublicRedirect = !isReady
    ? <PageSkeleton />
    : <Navigate to={session?.user ? "/dashboard" : "/login"} replace />;

  // Pre-login home — see pickHomeElement() definition above for the full matrix.
  const homeElement = pickHomeElement({
    isReady,
    hasSession: !!session?.user,
    treatAsWhiteLabel,
    isNativeApp,
  });

  const nativeOrPublic = (publicEl: JSX.Element) =>
    (isNativeApp || treatAsWhiteLabel) ? nativePublicRedirect : publicEl;

  // Hide the floating widget when the user is on /support — Live Chat tab
  // owns the surface there, and one-at-a-time keeps the UI calm.
  const hideFloatingChat = pathname === "/support" || pathname.startsWith("/support/");

  return (
    <SupportChatProvider>
      {/* NativeBootSplash is only meaningful inside the native/installed shell.
          Skip mounting it on plain web — saves a chunk fetch + a render.   */}
      {isNativeApp && (
        <Suspense fallback={null}>
          <NativeBootSplash />
        </Suspense>
      )}
      {/* Note: full-screen offline blocker now lives in App.tsx (GlobalOfflineGate). */}
      {/* Floating widgets are lazy + Suspense-wrapped with no fallback so
          they fade in after the route is interactive — never blocking it. */}
      {!isPublic && pathname !== "/onboarding" && portalsReady && !blockForOffline && (
        <Suspense fallback={null}>
          <XPFloatingPortal />
          <BadgeUnlockPortal />
          <LevelUpCelebration />
          {/* TWA / install prompt: only the white-label school subdomain shows it
              (1st-year strategy — schools get a wrapped-web install path).
              The main NepEduAI consumer app ships exclusively as a Capacitor
              native build, so it never invites users to "install the website". */}
          {!isNativeApp && treatAsWhiteLabel && <PWAInstallPrompt />}
          <LiveClassPopup />
          <FirstLoginConsent />
          {session?.user && (isNativeApp ? <AppPermissionsExplainer /> : <NotificationPermissionExplainer />)}
          {!isNativeApp && <BugReportButton />}
          {session?.user && <AdPopup placement="dashboard" />}
        </Suspense>
      )}
      {/* OfflineBanner is mounted at the App root so it works across every subdomain. */}

      <MaintenanceGate>
        <AccountGuard>
          <SchoolSubdomainGuard>
          {!isNativeApp && !hideFloatingChat && (
            <Suspense fallback={null}><LiveChatWidget /></Suspense>
          )}
          <Suspense fallback={<PageSkeleton />}>
            <ConditionalNativeShell active={useNativeShell}>
            <NativePageTransition>
            <Routes>
              <Route path="/" element={homeElement} />
              {/* /welcome-tour was a temporary home for <Index /> while `/` showed Welcome.
                  Now that `/` shows the full landing on web, this is just a redirect. */}
              <Route path="/welcome-tour" element={<Navigate to="/" replace />} />
              <Route path="/features" element={nativeOrPublic(<Features />)} />
              <Route path="/pricing" element={nativeOrPublic(<PricingPage />)} />
              <Route path="/payment/success" element={<PaymentSuccess />} />
              <Route path="/payment/failed" element={<PaymentFailed />} />
              <Route path="/about" element={nativeOrPublic(<About />)} />
              <Route path="/privacy" element={<Privacy />} />
              <Route path="/terms" element={<Terms />} />
              <Route path="/contact" element={nativeOrPublic(<Contact />)} />
              <Route path="/faq" element={nativeOrPublic(<FAQ />)} />
              <Route path="/neb-study" element={nativeOrPublic(<NEBStudy />)} />
              <Route path="/login" element={!isReady ? <PageSkeleton /> : session?.user ? <Navigate to="/dashboard" replace /> : (shell === "native" ? <NativeLoginScreen /> : <Login />)} />
              <Route path="/signup" element={authGate(treatAsWhiteLabel ? <Navigate to="/login" replace /> : <Signup />)} />
              <Route path="/change-password" element={!isReady ? <PageSkeleton /> : session?.user ? <ChangePassword /> : <Navigate to="/login" replace />} />
              <Route path="/auth" element={!isReady ? <PageSkeleton /> : <Navigate to={session?.user ? "/dashboard" : "/login"} replace />} />

              <Route path="/photo-solve" element={<SeniorOnlyGuard>{useNativeShell ? <NativePhotoSolveScreen /> : <PhotoSolve />}</SeniorOnlyGuard>} />
              <Route path="/dashboard" element={useNativeShell ? <NativeHomeScreen /> : <TierAwareDashboard />} />
              <Route path="/ai-tutor" element={<SeniorOnlyGuard>{useNativeShell ? <NativeAITutorScreen /> : <AiTutor />}</SeniorOnlyGuard>} />
              <Route path="/study-materials" element={<SeniorOnlyGuard>{useNativeShell ? <NativeStudyScreen /> : <StudyMaterials />}</SeniorOnlyGuard>} />
              <Route path="/study-materials/:subjectId" element={<SeniorOnlyGuard><StudyMaterials /></SeniorOnlyGuard>} />
              <Route path="/study-materials/:subjectId/:chapterId" element={<SeniorOnlyGuard><StudyMaterials /></SeniorOnlyGuard>} />
              <Route path="/mock-tests" element={<SeniorOnlyGuard><MockTests /></SeniorOnlyGuard>} />
              <Route path="/past-papers" element={<SeniorOnlyGuard><PastPapers /></SeniorOnlyGuard>} />
              <Route path="/mcq-practice" element={<SeniorOnlyGuard>{useNativeShell ? <NativeMCQScreen /> : <McqPractice />}</SeniorOnlyGuard>} />
              <Route path="/progress-tracking" element={<ProgressTracking />} />
              <Route path="/help-center" element={<HelpCenter />} />
              <Route path="/study-guide" element={<StudyGuide />} />
              <Route path="/downloads" element={<Downloads />} />
              <Route path="/careers" element={nativeOrPublic(<Careers />)} />
              <Route path="/blog" element={nativeOrPublic(<Blog />)} />
              <Route path="/blog/:slug" element={nativeOrPublic(<BlogPost />)} />
              <Route path="/press" element={nativeOrPublic(<Press />)} />
              <Route path="/partners" element={nativeOrPublic(<Partners />)} />
              <Route path="/apps" element={<SchoolDownloadApps />} />
              <Route path="/schools" element={nativeOrPublic(<SchoolDirectory />)} />
              <Route path="/schools/:slug" element={nativeOrPublic(<SchoolPublicProfile />)} />
              <Route path="/for-schools" element={<ForSchoolsRouteGuard>{nativeOrPublic(<ForSchools />)}</ForSchoolsRouteGuard>} />
              <Route path="/switch-from-veda" element={nativeOrPublic(<SwitchFromVeda />)} />
              <Route path="/system-status" element={<PageLayout><SystemStatus /></PageLayout>} />
              <Route path="/onboarding" element={<Onboarding />} />
              <Route path="/profile" element={useNativeShell ? <NativeProfileScreen /> : <Profile />} />
              <Route path="/profile/more" element={<ProfileMore />} />
              <Route path="/profile/:username" element={<Profile />} />
              <Route path="/community" element={<CommunityChat />} />
              <Route path="/bookmarks" element={useNativeShell ? <NativeBookmarksScreen /> : <Bookmarks />} />
              <Route path="/notifications" element={useNativeShell ? <NativeNoticesScreen /> : <Notifications />} />
              <Route path="/settings/notifications" element={!isReady ? <PageSkeleton /> : session?.user ? <NotificationSettings /> : <Navigate to="/login" replace />} />
              <Route path="/settings/notifications/debug" element={!isReady ? <PageSkeleton /> : session?.user ? <NotificationDebug /> : <Navigate to="/login" replace />} />
              <Route path="/settings/permissions" element={!isReady ? <PageSkeleton /> : session?.user ? <PermissionsSettings /> : <Navigate to="/login" replace />} />
              <Route path="/settings" element={useNativeShell ? <NativeSettingsScreen /> : <SettingsPage />} />
              <Route path="/support" element={<SupportCenter />} />
              <Route path="/support-tickets" element={<SupportTickets />} />
              <Route path="/support/ticket/:ticketId" element={<TicketDetail />} />
              <Route path="/search" element={<GlobalSearch />} />
              <Route path="/study-planner" element={<StudyPlanner />} />
              <Route path="/smart-timetable" element={<SmartTimetable />} />
              <Route path="/ai-tools" element={<SeniorOnlyGuard><AITools /></SeniorOnlyGuard>} />
              <Route path="/ai-tools/:toolId" element={<SeniorOnlyGuard><AIToolPage /></SeniorOnlyGuard>} />

              <Route path="/class/:classId" element={<Navigate to="/study-materials" replace />} />
              <Route path="/class/:classId/:subjectId" element={<Navigate to="/study-materials" replace />} />
              <Route path="/class/:classId/:subjectId/:chapterId" element={<Navigate to="/study-materials" replace />} />
              <Route path="/learn/:chapterId/:noteId" element={<SeniorOnlyGuard>{useNativeShell ? <NativeNoteReaderScreen /> : <NoteReader />}</SeniorOnlyGuard>} />
              <Route path="/flashcards/:chapterId" element={<SeniorOnlyGuard><ClassGate><FlashcardsPage /></ClassGate></SeniorOnlyGuard>} />
              <Route path="/revision-plan" element={<SeniorOnlyGuard><RevisionPlanner /></SeniorOnlyGuard>} />
              <Route path="/leaderboard" element={<SeniorOnlyGuard>{useNativeShell ? <NativeLeaderboardScreen /> : <Leaderboard />}</SeniorOnlyGuard>} />
              <Route path="/important-questions/:chapterId" element={<SeniorOnlyGuard><ImportantQuestions /></SeniorOnlyGuard>} />
              <Route path="/ai-doubt-solver" element={<Navigate to="/ai-tutor" replace />} />
              <Route path="/forum" element={<SeniorOnlyGuard>{useNativeShell ? <NativeForumScreen /> : <Forum />}</SeniorOnlyGuard>} />
              <Route path="/forum/:questionId" element={<SeniorOnlyGuard><ForumQuestion /></SeniorOnlyGuard>} />
              <Route path="/invite/accept" element={<AcceptInvite />} />
              <Route path="/live-class/:classId" element={<SeniorOnlyGuard><LiveClass /></SeniorOnlyGuard>} />
              <Route path="/marks" element={useNativeShell ? <NativeMarksScreen /> : <StudentMarks />} />
              <Route path="/class-group" element={useNativeShell ? <NativeClassGroupScreen /> : <StudentClassGroup />} />
              <Route path="/my-classroom" element={useNativeShell ? <NativeClassroomScreen /> : <MyClassroom />} />
              <Route path="/homework" element={<Navigate to="/my-classroom" replace />} />
              <Route path="/arena" element={<SeniorOnlyGuard><Arena /></SeniorOnlyGuard>} />
              <Route path="/nepali-calendar" element={<NepaliCalendar />} />

              {/* Portal landing pages (dev mode path-prefix access).
                  On native, skip the marketing landing entirely. */}
              <Route path="/teacher" element={nativeOrPublic(<TeacherLanding />)} />
              <Route path="/parent" element={nativeOrPublic(<ParentLanding />)} />

              <Route path="*" element={<NotFound />} />
            </Routes>
            </NativePageTransition>
            </ConditionalNativeShell>
          </Suspense>
          </SchoolSubdomainGuard>
        </AccountGuard>
      </MaintenanceGate>
    </SupportChatProvider>
  );
}

/** Routes /dashboard to the right experience based on context:
 *  - White-label school subdomain → SchoolStudentDashboard (school-first)
 *  - KG–9 → JuniorDashboard
 *  - 10–12 → Dashboard (NepEduAI consumer)
 *
 *  Lazy-loaded inside the component so the school dashboard chunk is only
 *  fetched when actually rendered.
 */
function TierAwareDashboard() {
  const profile = useUserProfile();
  const { isWhiteLabel, loading: brandingLoading } = useSchoolBranding();
  if (profile.loading || brandingLoading) return <PageSkeleton />;
  if (isWhiteLabel) {
    const SchoolStudentDashboard = lazy(() => import("@/components/dashboard/SchoolStudentDashboard"));
    return (
      <Suspense fallback={<PageSkeleton />}>
        <SchoolStudentDashboard />
      </Suspense>
    );
  }
  return isJunior(profile.grade) ? <JuniorDashboard /> : <Dashboard />;
}

/**
 * /for-schools is hidden inside any school-branded context (white-label
 * subdomain or ?school=… PWA). Students using a school's app should not be
 * able to start their own school onboarding.
 */
function ForSchoolsRouteGuard({ children }: { children: JSX.Element }) {
  const { isWhiteLabel, loading } = useSchoolBranding();
  if (loading) return <PageSkeleton />;
  if (isWhiteLabel) return <Navigate to="/" replace />;
  return children;
}

/**
 * Wraps children in <NativeShell> when active; otherwise renders children
 * untouched. Lets us keep the same Routes table for both shells.
 */
function ConditionalNativeShell({ active, children }: { active: boolean; children: JSX.Element }) {
  if (!active) return children;
  return <NativeShell>{children}</NativeShell>;
}
