import { Toaster } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import NotFound from "@/pages/NotFound";
import { Route, Switch } from "wouter";
import ErrorBoundary from "./components/ErrorBoundary";
import { ThemeProvider } from "./contexts/ThemeContext";
import { LanguageProvider } from "./contexts/LanguageContext";
import { lazy, Suspense, useEffect, useCallback } from "react";
import { initGA, disableGA, captureUTMParams } from "@/lib/analytics";
import { usePageTracking } from "@/hooks/usePageTracking";
import CookieConsent from "@/components/CookieConsent";
import RequestQuoteModal from "@/components/RequestQuoteModal";
import { isCategoryAllowed, type CookiePreferences } from "@/lib/cookieConsent";

// Lazy load pages for better performance
const Home = lazy(() => import("./pages/Home"));
const About = lazy(() => import("./pages/About"));
const IndustryCeramics = lazy(() => import("./pages/IndustryCeramics"));
const IndustryGlass = lazy(() => import("./pages/IndustryGlass"));
const IndustryCement = lazy(() => import("./pages/IndustryCement"));
const IndustryMachinery = lazy(() => import("./pages/IndustryMachinery"));
const Partners = lazy(() => import("./pages/Partners"));
const Contact = lazy(() => import("./pages/Contact"));
const AdminDashboard = lazy(() => import("./pages/AdminDashboard"));
const CookiePolicy = lazy(() => import("./pages/CookiePolicy"));
const PrivacyPolicy = lazy(() => import("./pages/PrivacyPolicy"));
const Terms = lazy(() => import("./pages/Terms"));
const CementGrindingAids = lazy(() => import("./pages/landing/CementGrindingAids"));
const KilnRefractories = lazy(() => import("./pages/landing/KilnRefractories"));
const AZSRefractories = lazy(() => import("./pages/landing/AZSRefractories"));
const SilicaBricks = lazy(() => import("./pages/landing/SilicaBricks"));
const CeramicRawMaterials = lazy(() => import("./pages/landing/CeramicRawMaterials"));
const CompactLoadersUAE = lazy(() => import("./pages/landing/CompactLoadersUAE"));

function PageLoader() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-warm-white">
      <div className="w-8 h-8 border-3 border-teal border-t-transparent rounded-full animate-spin" />
    </div>
  );
}
function Router() {
  // make sure to consider if you need authentication for certain routes
  return (
    <Suspense fallback={<PageLoader />}>
      <Switch>
        <Route path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/industries/ceramics" component={IndustryCeramics} />
        <Route path="/industries/glass" component={IndustryGlass} />
        <Route path="/industries/cement" component={IndustryCement} />
        <Route path="/industries/machinery" component={IndustryMachinery} />
        <Route path="/partners" component={Partners} />
        <Route path="/contact" component={Contact} />
        <Route path="/admin" component={AdminDashboard} />
        <Route path="/cookie-policy" component={CookiePolicy} />
        <Route path="/privacy-policy" component={PrivacyPolicy} />
        <Route path="/terms" component={Terms} />
        <Route path="/cement/grinding-aids-uae" component={CementGrindingAids} />
        <Route path="/cement/kiln-refractories" component={KilnRefractories} />
        <Route path="/glass/azs-refractories-uae" component={AZSRefractories} />
        <Route path="/glass/silica-bricks-uae" component={SilicaBricks} />
        <Route path="/ceramics/ceramic-raw-materials-uae" component={CeramicRawMaterials} />
        <Route path="/machinery/compact-loaders-uae" component={CompactLoadersUAE} />
        <Route path="/404" component={NotFound} />
        <Route component={NotFound} />
      </Switch>
    </Suspense>
  );
}

function App() {
  // Consent-aware GA initialization
  const syncAnalyticsWithConsent = useCallback(() => {
    if (isCategoryAllowed("analytics")) {
      initGA();
    } else {
      disableGA();
    }
  }, []);

  // Initialize on mount based on stored consent + capture UTM params
  useEffect(() => {
    syncAnalyticsWithConsent();
    captureUTMParams();
  }, [syncAnalyticsWithConsent]);

  // Listen for consent changes
  useEffect(() => {
    const handler = (e: Event) => {
      const detail = (e as CustomEvent<CookiePreferences>).detail;
      if (detail?.analytics) {
        initGA();
      } else {
        disableGA();
      }
    };
    window.addEventListener("cookie-consent-updated", handler);
    return () => window.removeEventListener("cookie-consent-updated", handler);
  }, []);

  // Track page views on route changes
  usePageTracking();

  return (
    <ErrorBoundary>
      <ThemeProvider defaultTheme="light">
        <LanguageProvider>
          <TooltipProvider>
            <Toaster />
            <Router />
            <CookieConsent />
            <RequestQuoteModal />
          </TooltipProvider>
        </LanguageProvider>
      </ThemeProvider>
    </ErrorBoundary>
  );
}

export default App;
