import React, { Suspense, lazy, useEffect } from "react";
import { Switch, Route, Redirect, useLocation } from "wouter";
import { HotToaster } from "@/components/ui/hot-toast";
import LoadingSpinner from "@/components/loading-spinner";
import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient } from "./lib/queryClient";
import { ProtectedRoute } from "./components/protected-route";
import { AuthProvider, useAuth } from "@/hooks/use-auth";
import { useMaintenanceMode } from "@/hooks/use-maintenance-mode";
import { AdminAuthProvider } from "@/hooks/use-admin-auth";
import { FeatureToggleProvider } from "@/hooks/use-feature-toggles";
import { CreditsProvider } from "@/hooks/use-credits";
import { FeatureGate } from "@/components/feature-gate";
import { FEATURE_TOGGLE_IDS } from "@/constants/feature-toggle-constants";
import { LocalizationProvider } from "@/hooks/use-localization";
import Login from "./components/auth/login";
import ForgotPassword from "./pages/forgot-password";
import Student from "./pages/parent/student";
import { setGlobalAuthErrorHandler } from "@/lib/api";
import { initializeClarity } from "@/analytics/clarity-analytics";
import { initializeGoogleAnalytics } from "@/analytics/google-analytics";
import CookieConsent from "@/components/CookieConsent";
import { pageView } from "@/lib/analytics";
import { trackPageNavigation } from "@/analytics/analytics-integration";
import { GoogleReCaptchaProvider } from "react-google-recaptcha-v3";
import { ConnectionStatusIndicator } from "@/components/ui/connection-status-indicator";
import { updateColorTheme } from "@/lib/theme-utils";

const RECAPTCHA_SITE_KEY = import.meta.env.VITE_ReCAPTCHA3_NOTIFY_FORM_SITE_KEY;

// Dynamically import pages
const NotFound = lazy(() => import("@/pages/not-found"));
const ParentDashboard = lazy(() => import("@/pages/parent-dashboard"));
const StudentDashboard = lazy(() => import("@/pages/student-dashboard"));
const HomePage = lazy(() => import("@/pages/home-page"));
const OurStoryPage = lazy(() => import("@/pages/our-story"));
const AboutUsPage = lazy(() => import("@/pages/about-us"));
const ContactUsPage = lazy(() => import("@/pages/contact-us"));
const ClassesPage = lazy(() => import("@/pages/classes"));
const OldPricingPage = lazy(() => import("@/pages/pricing"));
const PricingPage = lazy(() => import("@/pages/pricing"));
const ReferralPage = lazy(() => import("@/pages/referral-program"));
const MaintenanceMode = lazy(() => import("@/pages/maintenance-mode"));
const MaintenanceAdmin = lazy(
  () => import("@/components/dev/maintenance-admin")
);
const AdminDashboard = lazy(() => import("@/pages/admin-dashboard"));
const AdminFeatureToggles = lazy(() => import("@/pages/admin/feature-toggles"));
const PrivacyPolicy = lazy(() => import("@/pages/privacy-policy"));
const TermsOfService = lazy(() => import("@/pages/terms-of-service"));
const AIPolicy = lazy(() => import("@/pages/ai-policy"));
const ReturnRefundPolicy = lazy(() => import("@/pages/return-refund-policy"));
const FAQ = lazy(() => import("@/pages/faq"));
const BlogPage = lazy(() => import("@/pages/blog"));
const BlogDetailPage = lazy(() => import("@/pages/blog-detail"));
// Azure auth components
import { ProtectedAdminRoute } from "@/components/admin/protected-admin-route";
import {
  ADMIN_BASE_PATH,
  getAdminPath,
  isAdminPath,
} from "@/config/admin-config";

// Parent portal pages (dynamic imports)
const ParentProgressReports = lazy(
  () => import("@/pages/parent/progress-reports")
);
const ParentChildren = lazy(() => import("@/pages/parent/children"));
const ParentBilling = lazy(() => import("@/pages/parent/billing"));
const ParentSettings = lazy(() => import("@/pages/parent/settings"));
const ParentProfile = lazy(() => import("@/pages/parent/profile"));
const ParentAssignPlan = lazy(() => import("@/pages/parent/assign"));
const ParentFeedback = lazy(() => import("@/pages/parent/feedback"));

// Student portal pages (dynamic imports)
const StudentSubjects = lazy(() => import("@/pages/student/subjects"));
const StudentQuestions = lazy(() => import("@/pages/student/questions"));
const StudentAchievements = lazy(() => import("@/pages/student/achievements"));
const StudentSettings = lazy(() => import("@/pages/student/settings"));
const StudentProfile = lazy(() => import("@/pages/student/profile"));
const StudentBilling = lazy(() => import("@/pages/student/billing"));
const StudentCart = lazy(() => import("@/pages/student/cart"));
const ReferEarnPage = lazy(() => import("@/pages/student/refer"));
const CreditsPage = lazy(() => import("@/pages/student/credits-page"));
const ClassContentPage = lazy(
  () => import("@/components/home/class-content-page")
);
// const StudentStarredQuestions = lazy(
//   () => import("@/pages/student/starred-questions")
// );
const StudentQuestionPage = lazy(() => import("@/pages/student/question-page"));
const QuestionHistoryPage = lazy(
  () => import("@/pages/student/question-history")
);
const ReadingBooksPage = lazy(() => import("@/pages/student/reading-books"));
const HobbiesPage = lazy(() => import("@/pages/student/hobbies-page"));
const LearningGamesPage = lazy(() => import("@/pages/student/learning-games"));
const MediaGalleryPage = lazy(() => import("@/pages/student/media-gallery"));
const CollaborativeChallenges = lazy(
  () => import("@/pages/student/collaborative-challenges")
);
const PeersPage = lazy(() => import("@/pages/student/peers"));
const VocabularyGamePage = lazy(
  () => import("@/pages/student/games/vocabulary-game")
);
const VocabularyWordDetails = lazy(
  () => import("@/pages/student/games/vocabulary-word-details")
);
const VocabularyWordAdventure = lazy(
  () => import("@/pages/student/vocabulary-word-adventure")
);

// New game pages
const FractionMasterPage = lazy(
  () => import("@/pages/student/games/fraction-master")
);
const NumberNinjaPage = lazy(
  () => import("@/pages/student/games/number-ninja")
);
const ChemistryLabPage = lazy(
  () => import("@/pages/student/games/chemistry-lab")
);
const ChessMasterPage = lazy(
  () => import("@/pages/student/games/chess-master")
);
const GeometryExplorerPage = lazy(
  () => import("@/pages/student/games/geometry-explorer")
);
const AlgebraAdventuresPage = lazy(
  () => import("@/pages/student/games/algebra-adventures")
);
const PhysicsPlaygroundPage = lazy(
  () => import("@/pages/student/games/physics-playground")
);
const BiologyQuestPage = lazy(
  () => import("@/pages/student/games/biology-quest")
);
const SpaceExplorerPage = lazy(
  () => import("@/pages/student/games/space-explorer")
);
const ChessPuzzlesPage = lazy(
  () => import("@/pages/student/games/chess-puzzles")
);
const MemoryGamePage = lazy(() => import("@/pages/student/games/memory-game"));
const ScienceMemoryGame = lazy(
  () => import("@/pages/student/games/science-memory-game")
);
const EnglishMemoryGame = lazy(
  () => import("@/pages/student/games/english-memory-game")
);
const SubjectPage = lazy(() => import("@/pages/subject-page"));
const ClassSubjectPage = lazy(() => import("@/pages/class-subject-page"));
const ParentCart = lazy(() => import("@/pages/parent/cart"));

// Marketing variants (Temporary)
const HomeVariantB = lazy(() => import("@/pages/marketing/HomeVariantB"));
const PricingVariantB = lazy(() => import("@/pages/marketing/PricingVariantB"));
const NationalEssayCompetitionPage = lazy(
  () => import("@/pages/competition/national-essay-competition")
);
const StudentEssayCompetitionPage = lazy(
  () => import("@/pages/student/competition/essay-submission")
);
const WinnersPage = lazy(() => import("@/pages/student/winners"));
const CompetitionHubPage = lazy(
  () => import("@/pages/student/competition-hub")
);

// Dashboard redirect component to handle auth-based redirections
function DashboardRedirect() {
  const { user, isLoading } = useAuth();

  // If still loading, show a loading indicator
  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <LoadingSpinner
          size="lg"
          message="Loading dashboard..."
          showBooks={true}
        />
      </div>
    );
  }

  // If user is authenticated, redirect to appropriate dashboard
  if (user) {
    if (user.userType === "parent") {
      return <Redirect to="/parent/dashboard" />;
    } else {
      return <Redirect to="/student/dashboard" />;
    }
  }

  // If not authenticated, redirect to auth page
  return <Redirect to="/auth" />;
}

// Router component with all application routes
function AppRoutes() {
  const [location] = useLocation();
  const { user } = useAuth();

  // Track page views and stop audio when location changes
  useEffect(() => {
    window.dispatchEvent(new CustomEvent("stop-all-sikho-audio"));

    // Only track page views when not in admin area (for privacy)
    if (!location.startsWith("/admin")) {
      // derive a reasonable page title for diagnostics and GA
      const deriveTitle = (path: string) => {
        if (!path || path === "/") return "Home Page";
        if (path.startsWith("/blog/")) return "Blog Detail";
        if (path === "/blog") return "Blogs";
        if (path === "/our-story") return "Our Story";
        if (path === "/about") return "About";
        if (path === "/contact") return "Contact";
        if (path.startsWith("/student")) return "Student Portal";
        if (path.startsWith("/parent")) return "Parent Portal";
        if (path.startsWith("/admin")) return "Admin";
        // fallback: use path segments converted to title
        return path
          .replace(/(^\/+|\/+$)/g, "")
          .split("/")
          .map((s) =>
            s
              .replace(/[-_]/g, " ")
              .replace(/\b\w/g, (c) => c.toUpperCase())
              .trim()
          )
          .join(" - ");
      };

      const pageTitle = deriveTitle(location);
      const userType = user?.userType || "guest";
      try {
        trackPageNavigation(location, pageTitle, userType as any);
      } catch (err) {
        // fallback to legacy pageView in case of tracking errors
        try {
          pageView(location);
        } catch (_) {
          // ignore
        }
      }
    }
  }, [location, user]);

  return (
    // Wrap routes with Suspense for lazy loading fallback
    <Suspense
      fallback={
        <div className="flex h-screen items-center justify-center">
          <LoadingSpinner
            size="lg"
            message="Loading page..."
            showBooks={true}
          />
        </div>
      }
    >
      <Switch>
        {/* Home page - using HomeVariantB as the new default homepage */}
        <Route path="/" component={HomeVariantB} />
        <Route path="/old-home" component={HomePage} />
        <Route path="/our-story" component={OurStoryPage} />
        <Route path="/about" component={AboutUsPage} />
        <Route path="/contact" component={ContactUsPage} />
        <Route path="/classes" component={ClassesPage} />
        {/* Pricing page - using PricingVariantB as the new default pricing page */}
        {import.meta.env.VITE_HIDE_PRICING_LINK !== "true" && (
          <>
            <Route path="/pricing" component={PricingVariantB} />
            <Route path="/old-pricing" component={PricingPage} />
          </>
        )}
        <Route path="/referral" component={ReferralPage} />
        <Route path="/class-content" component={ClassContentPage} />
        <Route
          path="/competition/national-essay-2026/results"
          component={WinnersPage}
        />
        <Route
          path="/competition/national-essay-2026"
          component={NationalEssayCompetitionPage}
        />
        <ProtectedRoute
          path="/student/competition/national-essay-2026/results"
          component={WinnersPage}
          userType="student"
        />

        {/* Marketing Variants */}
        <Route path="/new-pricing" component={PricingVariantB} />

        {/* Legal and policy pages */}
        <Route path="/privacy" component={PrivacyPolicy} />
        <Route path="/terms" component={TermsOfService} />
        <Route path="/ai-policy" component={AIPolicy} />
        <Route path="/return-refund-policy" component={ReturnRefundPolicy} />
        <Route path="/faq" component={FAQ} />

        {/* Blog pages */}
        <Route path="/blog" component={BlogPage} />
        <Route path="/blog/:slug" component={BlogDetailPage} />

        {/* Maintenance mode page for testing */}
        <Route path="/maintenance" component={() => <MaintenanceMode />} />

        {/* Admin routes - Protected with obscured URL and authentication */}
        {/* Legacy admin route - redirect to 404 for security */}
        <Route path="/admin" component={() => <NotFound />} />
        <Route path="/admin/*" component={() => <NotFound />} />

        {/* Actual admin routes with obscured path */}
        <Route
          path={ADMIN_BASE_PATH}
          component={() => (
            <ProtectedAdminRoute>
              <AdminDashboard />
            </ProtectedAdminRoute>
          )}
        />

        <Route
          path={getAdminPath("MAINTENANCE")}
          component={() => (
            <ProtectedAdminRoute>
              <MaintenanceAdmin />
            </ProtectedAdminRoute>
          )}
        />

        <Route
          path={getAdminPath("FEATURE_TOGGLES")}
          component={() => (
            <ProtectedAdminRoute>
              <AdminFeatureToggles />
            </ProtectedAdminRoute>
          )}
        />

        {/* Future admin routes can be added here with ProtectedAdminRoute */}

        {/* Auth pages */}
        {/* <Route path="/auth" component={AuthPage} /> */}
        {/* Conditionally render auth route based on environment variable */}
        {import.meta.env.VITE_HIDE_AUTH_LINKS !== "true" && (
          <Route path="/auth" component={Login} />
        )}
        <Route path="/forgot-password" component={ForgotPassword} />
        <Route path="/dashboard" component={DashboardRedirect} />
        {/* Subject pages */}
        <Route path="/subject/:subjectName" component={SubjectPage} />

        {/* Parent portal routes - protected for parent users only */}
        <ProtectedRoute
          path="/parent/dashboard"
          component={() => <ParentDashboard />}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/progress-reports"
          component={() => <ParentProgressReports />}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/children"
          component={() => <ParentChildren />}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/billing"
          component={() => <ParentBilling />}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/settings"
          component={() => <ParentSettings />}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/profile"
          component={() => <ParentProfile />}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/cart"
          component={ParentCart}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/assign"
          component={() => <ParentAssignPlan />}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/feedback"
          component={() => <ParentFeedback />}
          userType="parent"
        />
        <ProtectedRoute
          path="/parent/student"
          component={() => <Student />}
          userType="parent"
        />

        {/* Student portal routes - protected for student users only */}
        <ProtectedRoute
          path="/student/dashboard"
          component={() => <StudentDashboard />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/subjects"
          component={() => <StudentSubjects />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/questions"
          component={() => <StudentQuestions />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/question/:id"
          component={(params: any) => <StudentQuestionPage {...params} />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/refer"
          component={() => <ReferEarnPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/achievements"
          component={() => <StudentAchievements />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/feedback"
          component={() => <ParentFeedback />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/media"
          component={() => <MediaGalleryPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/settings"
          component={() => <StudentSettings />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/profile"
          component={() => <StudentSettings />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/credits"
          component={() => <CreditsPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/billing"
          component={() => <StudentBilling />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/cart"
          component={() => <StudentCart />}
          userType="student"
        />
        {/* <ProtectedRoute
          path="/student/starred-questions"
          component={() => <StudentStarredQuestions />}
          userType="student"
        /> */}
        <ProtectedRoute
          path="/student/question-history"
          component={() => <QuestionHistoryPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/reading-books"
          component={() => (
            <FeatureGate featureId={FEATURE_TOGGLE_IDS.READING_BOOKS}>
              <ReadingBooksPage />
            </FeatureGate>
          )}
          userType="student"
        />

        <ProtectedRoute
          path="/student/hobbies-page"
          component={() => <HobbiesPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games"
          component={() => <LearningGamesPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/collaborative-challenges"
          component={() => <CollaborativeChallenges />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/peers"
          component={() => <PeersPage />}
          userType="student"
        />
        <Route
          path="/student/games/vocabulary-game"
          component={() => <VocabularyGamePage />}
        />
        <Route
          path="/student/games/vocabulary-word-details/:word"
          component={VocabularyWordDetails}
        />
        <Route
          path="/student/games/vocabulary/:word"
          component={VocabularyWordAdventure}
        />

        {/* New game routes */}
        <ProtectedRoute
          path="/student/games/fraction-master"
          component={() => <FractionMasterPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/number-ninja"
          component={() => <NumberNinjaPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/chemistry-lab"
          component={() => <ChemistryLabPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/chess-master"
          component={() => <ChessMasterPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/geometry-explorer"
          component={() => <GeometryExplorerPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/algebra-adventures"
          component={() => <AlgebraAdventuresPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/physics-playground"
          component={() => <PhysicsPlaygroundPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/biology-quest"
          component={() => <BiologyQuestPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/space-explorer"
          component={() => <SpaceExplorerPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/chess-puzzles"
          component={() => <ChessPuzzlesPage />}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/memory-game/mathematics"
          component={MemoryGamePage}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/memory-game/science"
          component={ScienceMemoryGame}
          userType="student"
        />
        <ProtectedRoute
          path="/student/games/memory-game/english"
          component={EnglishMemoryGame}
          userType="student"
        />

        <ProtectedRoute
          path="/student/competition-hub"
          component={() => <CompetitionHubPage />}
          userType="student"
        />

        <ProtectedRoute
          path="/student/essay-competition"
          component={() => <StudentEssayCompetitionPage />}
          userType="student"
        />

        {/* Catch-all route for class/subject pages - MUST be last before NotFound */}
        <Route path="/:className/:subjectName" component={ClassSubjectPage} />

        {/* Fallback route */}
        <Route component={NotFound} />
      </Switch>
      <CookieConsent />
    </Suspense>
  );
}

// Component to initialize theme color on app load
function ThemeInitializer() {
  React.useEffect(() => {
    // Initialize theme color from localStorage
    const savedButtonColor = localStorage.getItem("button_color");
    if (savedButtonColor) {
      updateColorTheme(savedButtonColor);
    }
  }, []);

  return null;
}

// Smart wrapper for FeatureToggleProvider that detects admin mode
function SmartFeatureToggleProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [location] = useLocation();
  const isAdminMode = location.startsWith("/admin");

  return (
    <FeatureToggleProvider isAdminMode={isAdminMode}>
      {children}
    </FeatureToggleProvider>
  );
}

// Main app component that sets up provider hierarchy
function App() {
  // Initialize analytics on app startup
  useEffect(() => {
    initializeClarity();
    initializeGoogleAnalytics();
  }, []);

  // Right-click is disabled by default, only enabled when VITE_ENABLE_RIGHT_CLICK=true
  useEffect(() => {
    const enableRightClick = import.meta.env.VITE_ENABLE_RIGHT_CLICK === "true";

    // If right-click is not explicitly enabled, disable it
    if (!enableRightClick) {
      const handleContextMenu = (e: MouseEvent) => {
        e.preventDefault();
        return false;
      };

      document.addEventListener("contextmenu", handleContextMenu);

      return () => {
        document.removeEventListener("contextmenu", handleContextMenu);
      };
    }
  }, []);

  const appTree = (
    <QueryClientProvider client={queryClient}>
      <LocalizationProvider>
        <AuthProvider>
          <AdminAuthProvider>
            <SmartFeatureToggleProvider>
              <ThemeInitializer />
              <MaintenanceWrapper>
                <GlobalAuthErrorHandler>
                  <CreditsProvider>
                    <AppRoutes />
                  </CreditsProvider>
                </GlobalAuthErrorHandler>
                <HotToaster />
                {/* Connection Status Indicator - Simple offline banner */}
                <ConnectionStatusIndicator position="bottom-right" />
              </MaintenanceWrapper>
            </SmartFeatureToggleProvider>
          </AdminAuthProvider>
        </AuthProvider>
      </LocalizationProvider>
    </QueryClientProvider>
  );

  if (!RECAPTCHA_SITE_KEY) {
    console.warn(
      "reCAPTCHA site key not found. Please set VITE_ReCAPTCHA3_NOTIFY_FORM_SITE_KEY in environment variables."
    );
    return appTree;
  }

  return (
    <GoogleReCaptchaProvider
      reCaptchaKey={RECAPTCHA_SITE_KEY}
      scriptProps={{
        async: true,
        defer: true,
        appendTo: "head",
      }}
    >
      {appTree}
    </GoogleReCaptchaProvider>
  );
}

// Component to check maintenance mode and show maintenance page if needed
function MaintenanceWrapper({ children }: { children: React.ReactNode }) {
  const { maintenanceStatus, loading } = useMaintenanceMode();
  const [location] = useLocation();

  // Show loading while checking maintenance status
  if (loading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <LoadingSpinner
          size="lg"
          message="Checking system status..."
          showBooks={true}
        />
      </div>
    );
  }

  // Allow access to admin routes even in maintenance mode
  const isAdminRoute = isAdminPath(location);
  const isMaintenanceRoute = location === "/maintenance";

  // Show maintenance mode page if maintenance is active (but not for admin routes)
  if (
    maintenanceStatus.isMaintenanceMode &&
    !isAdminRoute &&
    !isMaintenanceRoute
  ) {
    return (
      <Suspense
        fallback={
          <div className="flex h-screen items-center justify-center">
            <LoadingSpinner
              size="lg"
              message="Loading maintenance info..."
              showBooks={true}
            />
          </div>
        }
      >
        <MaintenanceMode
          message={maintenanceStatus.message}
          estimatedDuration={maintenanceStatus.estimatedDuration}
          startTime={maintenanceStatus.startTime}
          features={maintenanceStatus.features}
        />
      </Suspense>
    );
  }

  // Show normal app if not in maintenance mode or if accessing admin routes
  return <>{children}</>;
}

// Component to handle global authentication errors
function GlobalAuthErrorHandler({ children }: { children: React.ReactNode }) {
  const [, setLocation] = useLocation();

  React.useEffect(() => {
    // Set up the global auth error handler for API layer
    setGlobalAuthErrorHandler(() => {
      setLocation("/auth");
    });

    // Listen for manual auth errors from service layer
    const handleAuthError = (event: CustomEvent) => {
      setLocation("/auth");
    };

    window.addEventListener("auth-error", handleAuthError as EventListener);

    return () => {
      window.removeEventListener(
        "auth-error",
        handleAuthError as EventListener
      );
    };
  }, [setLocation]);

  return <>{children}</>;
}

export default App;
