import { Suspense, lazy, useEffect } from "react";
import { Route, Switch, useLocation } from "wouter";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { HelmetProvider } from "react-helmet-async";
import { preloadCriticalRoutes } from "./shared/utils/routePreloader";
import { trackFeature, trackSessionDepth, FEATURES } from "./utils/analytics";

// Core components that should load immediately
import Header from "./shared/components/Header";
import Footer from "./shared/components/Footer";
import BottomNavigationBar from "./components/navigation/BottomNavigationBar";
import FeedbackWidget from "./components/feedback/FeedbackWidget";
import CustomerSupportChat from "./shared/components/CustomerSupportChat";
import StreamlinedOnboarding from "./components/onboarding/StreamlinedOnboarding";

// Lazy load all route components for better performance
const Home = lazy(() => import("./core/pages/home"));
const Landing = lazy(() => import("./pages/Landing"));
const AboutUs = lazy(() => import("./pages/about-us"));
const Pricing = lazy(() => import("./core/pages/pricing"));
const ComplexityDashboard = lazy(
  () => import("./modules/analytics/complexity-dashboard"),
);
const EcoRecommendationEngine = lazy(
  () => import("./modules/sustainability/eco-recommendation-engine"),
);
const CommunityKnowledgeSharing = lazy(
  () => import("./pages/community-knowledge-sharing"),
);
const InteractivePestRiskAssessment = lazy(
  () => import("./pages/interactive-pest-risk-assessment"),
);
const AIFeaturesHub = lazy(() => import("./modules/ai/ai-features-hub"));
const AIPestDemo = lazy(() => import("./pages/ai-pest-demo"));
const CRM = lazy(() => import("./core/pages/crm"));
const PestControl = lazy(() => import("./core/pages/pest-control"));
const ResidentialServices = lazy(
  () => import("./core/pages/residential-services"),
);
const SpecialistServices = lazy(() => import("./pages/specialist-services"));
const Quotation = lazy(() => import("./core/pages/quotation"));
const Quote = lazy(() => import("./core/pages/quote"));
const NotFound = lazy(() => import("./pages/not-found"));
const BookDemo = lazy(() => import("./pages/book-demo"));
const BackendAdmin = lazy(() => import("./core/pages/backend-admin"));
const PricingAdmin = lazy(() => import("./pages/pricing-admin"));
const UnifiedPerformanceDashboard = lazy(
  () => import("./pages/unified-performance-dashboard"),
);
const AnalyticsDashboard = lazy(
  () => import("./modules/analytics/analytics-dashboard"),
);
const SustainabilityImpactTracker = lazy(
  () => import("./modules/sustainability/sustainability-impact-tracker"),
);
const SmartPestAlerts = lazy(() => import("./pages/smart-pest-alerts"));
const GatedAIVoiceAssistant = lazy(
  () => import("./modules/ai/GatedAIVoiceAssistant"),
);
const IoTPestSensors = lazy(() => import("./modules/iot/iot-pest-sensors"));
const SustainabilityDashboard = lazy(
  () => import("./modules/sustainability/sustainability-dashboard"),
);
const SeasonalPreventionCalendar = lazy(
  () => import("./pages/seasonal-prevention-calendar"),
);
const PreventionCoach = lazy(() => import("./pages/prevention-coach"));
const GatedARPestLens = lazy(() => import("./modules/ar-vr/GatedARPestLens"));
const SmartTreatmentOptimizer = lazy(
  () => import("./pages/smart-treatment-optimizer"),
);
const EnvironmentalRiskAssessment = lazy(
  () => import("./pages/environmental-risk-assessment"),
);
const PestRiskQuiz = lazy(() => import("./pages/pest-risk-quiz"));
const MobilePestScanner = lazy(
  () => import("./modules/ai/mobile-pest-scanner"),
);
const CommercialSolutions = lazy(
  () => import("./core/pages/commercial-solutions"),
);
const IndustrialSolutions = lazy(() => import("./pages/industrial-solutions"));
const EmergencyPestControl = lazy(
  () => import("./pages/emergency-pest-control"),
);
const HygieneServices = lazy(() => import("./pages/hygiene-services"));
const AftercareServices = lazy(() => import("./pages/aftercare-services"));
const IPMServices = lazy(() => import("./pages/ipm-services"));
const AISolutionsPlatform = lazy(() => import("./pages/ai-solutions-platform"));
const QualityAssurance = lazy(() => import("./pages/quality-assurance"));
const PestProtectionPlans = lazy(() => import("./pages/pest-protection-plans"));
const SpecialistQuote = lazy(() => import("./pages/specialist-quote"));
const AIAssistant = lazy(() => import("./modules/ai/ai-assistant"));
const AIDetectionChallengeLive = lazy(
  () => import("./modules/ai/ai-detection-challenge-live"),
);
const AIPreventionSidekick = lazy(
  () => import("./modules/ai/ai-prevention-sidekick"),
);
const ARPestIdentification = lazy(
  () => import("./modules/ar-vr/ar-pest-identification"),
);
const PredictiveCalendar = lazy(
  () => import("./modules/analytics/predictive-calendar"),
);
const FormsHub = lazy(() => import("./pages/forms-hub"));
const WorkflowAdmin = lazy(() => import("./pages/workflow-admin"));
const MarketingStrategy = lazy(() => import("./pages/marketing-strategy"));
const MarketingCalendar = lazy(() => import("./pages/marketing-calendar"));
const MarketingDashboard = lazy(() => import("./pages/marketing-dashboard"));
const HighROICampaigns = lazy(() => import("./pages/high-roi-campaigns"));
const NotificationPreferences = lazy(
  () => import("./pages/notification-preferences"),
);
const Education = lazy(() => import("./pages/education"));
const VREducation = lazy(() => import("./modules/ar-vr/vr-education"));
const LearningAudit = lazy(() => import("./pages/learning-audit"));
const PestLifecycleStorytelling = lazy(
  () => import("./pages/pest-lifecycle-storytelling"),
);
const DownloadApp = lazy(() => import("./pages/DownloadApp"));
const SeasonalForecast = lazy(
  () => import("./modules/analytics/seasonal-forecast"),
);
const BugReport = lazy(() => import("./pages/bug-report"));
const Checkout = lazy(() => import("./core/pages/checkout"));
const PaymentSuccess = lazy(() => import("./core/pages/payment-success"));
const PestLifecycleAnimations = lazy(
  () => import("./pages/pest-lifecycle-animations"),
);
const QrServiceTracking = lazy(() => import("./pages/qr-service-tracking"));
const SurveyReport = lazy(() => import("./pages/survey-report"));
const TreatmentReport = lazy(() =>
  import("./pages/treatment-report").then((module) => ({
    default: (props: any) => (
      <module.default appointmentId={props.params?.appointmentId} />
    ),
  })),
);
const Contact = lazy(() => import("./core/pages/contact"));
const Book = lazy(() => import("./core/pages/book"));
const AdminCommandCenter = lazy(
  () => import("./core/pages/admin-command-center"),
);
const KnowledgeBase = lazy(() => import("./pages/knowledge-base"));
const SopManagement = lazy(() => import("./pages/sop-management"));
const FieldTechnicianMobile = lazy(
  () => import("./pages/field-technician-mobile"),
);
const SurveyReportV2 = lazy(() => import("./pages/survey-report-v2"));
const CmsAdmin = lazy(() => import("./pages/cms-admin"));

// New Admin Monitoring & Communication Pages
const SystemLogsPage = lazy(() => import("./pages/admin/system-logs"));
const PerformanceMetricsPage = lazy(
  () => import("./pages/admin/performance-metrics"),
);
const DatabaseStatusPage = lazy(() => import("./pages/admin/database-status"));
const CommunicationManagementPage = lazy(
  () => import("./pages/admin/communication-management"),
);

const TechnicianAssessment = lazy(
  () => import("./pages/technician-assessment"),
);
const FeatureIdeas = lazy(() => import("./pages/feature-ideas"));
const EducationHub = lazy(() => import("./pages/education-hub"));
const AssessmentSchedule = lazy(() => import("./pages/assessment-schedule"));
const TermsOfService = lazy(() => import("./pages/terms-of-service"));
const PrivacyPolicy = lazy(() => import("./pages/privacy-policy"));
const SecurityPage = lazy(() => import("./pages/security"));
const EnterprisePage = lazy(() => import("./pages/enterprise"));
const FreeTrial = lazy(() => import("./pages/free-trial"));
const SeasonalTrendsDashboard = lazy(
  () => import("./modules/analytics/seasonal-trends-dashboard"),
);
const PestTrendsDashboard = lazy(() => import("./pages/pest-trends-dashboard"));
const QuickBooks = lazy(() => import("./modules/integrations/quickbooks"));
const WasteManagement = lazy(() => import("./pages/waste-management"));
const HygieneAssessment = lazy(() => import("./pages/hygiene-assessment"));
const ServiceCompletion = lazy(() => import("./pages/service-completion"));
const CoshhDataSheets = lazy(() => import("./pages/coshh-data-sheets"));
const DashboardRenderer = lazy(() =>
  import("./components/dashboard/DashboardRenderer").then((module) => ({
    default: module.DashboardRenderer,
  })),
);
const ComplianceAudit = lazy(() => import("./pages/compliance-audit"));
const TreatmentReports = lazy(() => import("./pages/treatment-reports"));
const ServiceAgreements = lazy(() => import("./pages/service-agreements"));
const CustomerFeedback = lazy(() => import("./pages/customer-feedback"));
const CommandCenter = lazy(() => import("./pages/command-center"));
const ProfilePage = lazy(() => import("./pages/profile"));
const SettingsPage = lazy(() => import("./pages/settings"));
const EcoWarriorBadges = lazy(
  () => import("./modules/sustainability/eco-warrior-badges"),
);
const AccessControl = lazy(() => import("./pages/access-control"));
const CustomerImportPage = lazy(() => import("./pages/customer-import"));
const CookiePolicy = lazy(() => import("./pages/cookie-policy"));
const Careers = lazy(() => import("./pages/careers"));
const FeatureManagement = lazy(() => import("./pages/admin/FeatureManagement"));
const Blog = lazy(() => import("./pages/blog"));
const FAQ = lazy(() => import("./pages/faq"));
const ServiceAreas = lazy(() => import("./pages/service-areas"));
const CaseStudies = lazy(() => import("./pages/case-studies"));
const Reviews = lazy(() => import("./pages/reviews"));
const Sitemap = lazy(() => import("./pages/sitemap"));
const TenderLibrary = lazy(() => import("./pages/TenderLibrary"));
const ServiceManagement = lazy(() => import("./pages/ServiceManagement"));
const RBACManagement = lazy(() => import("./pages/rbac-management"));
const IpManagementDashboard = lazy(
  () => import("./pages/IpManagementDashboard"),
);
const ComparisonPage = lazy(() => import("./pages/comparison"));

// CRM Sub-pages
const CRMCustomers = lazy(() => import("./pages/crm/customers"));
const CRMSuppliers = lazy(() => import("./pages/crm/suppliers"));
const CRMContacts = lazy(() => import("./pages/crm/contacts"));
const CRMAddresses = lazy(() => import("./pages/crm/addresses"));
const Login = lazy(() => import("./core/pages/login"));

import SidebarNav from "./components/navigation/SidebarNav";
import CommandPalette from "./components/navigation/CommandPalette";
import { queryClient } from "./shared/utils/queryClient";
import {
  BrandingProvider,
  useBranding,
} from "./shared/contexts/BrandingContext";
import { useAuth } from "./shared/hooks/useAuth";
import RouteProtection from "./components/RouteProtection";
import AuthGuard from "./components/AuthGuard";
import AdminRoute from "./components/AdminRoute";
import BrandSEOManager from "./shared/components/BrandSEOManager";
import { Toaster } from "./shared/components/ui/toaster";

// Enhanced loading and error handling components
import PageLoader from "./shared/components/PageLoader";
import ErrorBoundary from "./shared/components/ErrorBoundary";

function AppLayout() {
  const { isAegis360, currentBrand } = useBranding();
  const { isAuthenticated } = useAuth();

  // Only render sidebar for authenticated Aegis360 users
  const shouldShowSidebar = isAegis360 && isAuthenticated && currentBrand;

  return (
    <div className="relative">
      <BrandSEOManager />
      {shouldShowSidebar && <SidebarNav />}
      <CommandPalette />
      <main className="transition-all duration-300 mobile-bottom-nav-space">
        <Router />
      </main>
      <BottomNavigationBar />
    </div>
  );
}

function LoginRedirect() {
  const [, setLocation] = useLocation();

  useEffect(() => {
    setLocation("/login");
  }, [setLocation]);

  return null;
}

function Router() {
  return (
    <ErrorBoundary>
      <Suspense fallback={<PageLoader text="Loading page..." />}>
        <Switch>
          <Route path="/" component={Home} />
          <Route path="/api/login" component={LoginRedirect} />
          <Route path="/login" component={Login} />
          <Route path="/home" component={Home} />
          <Route path="/landing" component={Landing} />
          <Route path="/about-us" component={AboutUs} />
          <Route path="/pricing" component={Pricing} />
          <Route path="/services" component={PestControl} />
          <Route path="/residential-services" component={ResidentialServices} />
          <Route path="/specialist-services" component={SpecialistServices} />
          <Route path="/quotation" component={Quotation} />
          <Route path="/quote" component={Quote} />
          <Route path="/book-demo" component={BookDemo} />
          <Route path="/complexity-dashboard" component={ComplexityDashboard} />
          <Route
            path="/eco-recommendation-engine"
            component={EcoRecommendationEngine}
          />
          <Route
            path="/community-knowledge-sharing"
            component={CommunityKnowledgeSharing}
          />
          <Route
            path="/interactive-pest-risk-assessment"
            component={InteractivePestRiskAssessment}
          />
          <Route path="/ai-intelligence" component={AIFeaturesHub} />
          <Route path="/ai-features-hub" component={AIFeaturesHub} />
          <Route path="/ai-pest-demo" component={AIPestDemo} />

          {/* PROTECTED ADMIN/MANAGEMENT ROUTES - Require Authentication */}
          <Route path="/backend-admin">
            <AdminRoute>
              <BackendAdmin />
            </AdminRoute>
          </Route>
          <Route path="/pricing-admin">
            <AdminRoute>
              <PricingAdmin />
            </AdminRoute>
          </Route>
          <Route
            path="/performance-dashboard"
            component={UnifiedPerformanceDashboard}
          />
          <Route path="/analytics-dashboard">
            <AdminRoute>
              <AnalyticsDashboard />
            </AdminRoute>
          </Route>
          <Route path="/sop-management">
            <AdminRoute>
              <SopManagement />
            </AdminRoute>
          </Route>
          <Route path="/field-technician">
            <AdminRoute>
              <FieldTechnicianMobile />
            </AdminRoute>
          </Route>
          <Route path="/customer-management">
            <AdminRoute>
              <CRM />
            </AdminRoute>
          </Route>
          <Route path="/crm">
            <AdminRoute>
              <CRM />
            </AdminRoute>
          </Route>

          {/* PROTECTED CRM Sub-pages - Require Authentication */}
          <Route path="/crm/customers">
            <AdminRoute>
              <CRMCustomers />
            </AdminRoute>
          </Route>
          <Route path="/crm/suppliers">
            <AdminRoute>
              <CRMSuppliers />
            </AdminRoute>
          </Route>
          <Route path="/crm/contacts">
            <AdminRoute>
              <CRMContacts />
            </AdminRoute>
          </Route>
          <Route path="/crm/addresses">
            <AdminRoute>
              <CRMAddresses />
            </AdminRoute>
          </Route>
          <Route
            path="/sustainability-impact-tracker"
            component={SustainabilityImpactTracker}
          />
          <Route path="/smart-pest-alerts" component={SmartPestAlerts} />
          <Route path="/ai-voice-assistant" component={GatedAIVoiceAssistant} />
          <Route path="/iot-pest-sensors" component={IoTPestSensors} />
          <Route
            path="/sustainability-dashboard"
            component={SustainabilityDashboard}
          />
          <Route
            path="/seasonal-prevention-calendar"
            component={SeasonalPreventionCalendar}
          />
          <Route path="/prevention-coach" component={PreventionCoach} />
          <Route path="/ar-pest-lens" component={GatedARPestLens} />
          <Route
            path="/smart-treatment-optimizer"
            component={SmartTreatmentOptimizer}
          />
          <Route
            path="/environmental-risk-assessment"
            component={EnvironmentalRiskAssessment}
          />
          <Route path="/pest-risk-quiz" component={PestRiskQuiz} />
          <Route path="/interactive-pest-risk-quiz" component={PestRiskQuiz} />
          <Route path="/mobile-pest-scanner" component={MobilePestScanner} />

          <Route path="/commercial-services" component={CommercialSolutions} />
          <Route path="/commercial-solutions" component={CommercialSolutions} />
          <Route path="/industrial-services" component={IndustrialSolutions} />
          <Route path="/industrial-solutions" component={IndustrialSolutions} />
          <Route path="/emergency-services" component={EmergencyPestControl} />
          <Route
            path="/emergency-pest-control"
            component={EmergencyPestControl}
          />
          <Route path="/hygiene-services" component={HygieneServices} />
          <Route path="/aftercare-services" component={AftercareServices} />
          <Route path="/ipm-services" component={IPMServices} />
          <Route path="/ai-solutions" component={AISolutionsPlatform} />
          <Route path="/integrated-pest-management" component={IPMServices} />
          <Route path="/quality-assurance" component={QualityAssurance} />
          <Route
            path="/pest-protection-plans"
            component={PestProtectionPlans}
          />
          <Route path="/specialist-quote" component={SpecialistQuote} />
          <Route path="/ai-assistant" component={AIAssistant} />
          <Route
            path="/ai-detection-challenge-live"
            component={AIDetectionChallengeLive}
          />
          <Route
            path="/ai-prevention-sidekick"
            component={AIPreventionSidekick}
          />
          <Route
            path="/ar-pest-identification"
            component={ARPestIdentification}
          />
          <Route path="/predictive-calendar" component={PredictiveCalendar} />
          <Route path="/forms-hub" component={FormsHub} />
          <Route path="/workflow-admin">
            <AdminRoute>
              <WorkflowAdmin />
            </AdminRoute>
          </Route>
          {/* Marketing Strategy routes added here */}
          <Route path="/marketing-strategy" component={MarketingStrategy} />
          <Route path="/marketing-calendar" component={MarketingCalendar} />
          <Route path="/marketing-dashboard" component={MarketingDashboard} />
          <Route path="/high-roi-campaigns" component={HighROICampaigns} />
          <Route
            path="/notification-preferences"
            component={NotificationPreferences}
          />
          <Route path="/education" component={Education} />
          <Route path="/vr-education" component={VREducation} />
          <Route path="/learning-audit" component={LearningAudit} />
          <Route
            path="/pest-lifecycle-storytelling"
            component={PestLifecycleStorytelling}
          />
          <Route path="/download-app" component={DownloadApp} />

          {/* Previously missing routes - Adding now */}
          <Route path="/seasonal-forecast" component={SeasonalForecast} />
          <Route path="/bug-report" component={BugReport} />
          <Route path="/checkout" component={Checkout} />
          <Route path="/payment-success" component={PaymentSuccess} />
          <Route
            path="/pest-lifecycle-animations"
            component={PestLifecycleAnimations}
          />
          <Route path="/qr-service-tracking" component={QrServiceTracking} />
          <Route path="/survey-report" component={SurveyReport} />
          <Route path="/treatment-report" component={TreatmentReport} />
          <Route path="/contact" component={Contact} />
          <Route path="/book" component={Book} />
          <Route path="/book-appointment" component={Book} />
          <Route path="/knowledge-base" component={KnowledgeBase} />
          <Route path="/survey-report-v2" component={SurveyReportV2} />
          <Route
            path="/technician-assessment"
            component={TechnicianAssessment}
          />
          <Route path="/feature-ideas" component={FeatureIdeas} />
          <Route path="/education-hub" component={EducationHub} />
          <Route path="/assessment-schedule" component={AssessmentSchedule} />
          <Route path="/terms-of-service" component={TermsOfService} />
          <Route path="/privacy-policy" component={PrivacyPolicy} />
          <Route path="/security" component={SecurityPage} />
          <Route path="/enterprise" component={EnterprisePage} />
          <Route path="/enterprise-trust" component={EnterprisePage} />
          <Route path="/security-compliance" component={SecurityPage} />
          <Route path="/free-trial" component={FreeTrial} />
          <Route
            path="/seasonal-trends-dashboard"
            component={SeasonalTrendsDashboard}
          />
          <Route
            path="/pest-trends-dashboard"
            component={PestTrendsDashboard}
          />
          <Route path="/quickbooks" component={QuickBooks} />
          <Route path="/waste-management" component={WasteManagement} />
          <Route path="/forms-hub" component={FormsHub} />
          <Route path="/hygiene-assessment" component={HygieneAssessment} />
          <Route path="/service-completion" component={ServiceCompletion} />
          <Route path="/coshh-data-sheets" component={CoshhDataSheets} />
          <Route
            path="/chemical-safety-data-sheets"
            component={CoshhDataSheets}
          />
          <Route path="/compliance-audit" component={ComplianceAudit} />
          <Route path="/treatment-reports" component={TreatmentReports} />
          <Route path="/service-agreements" component={ServiceAgreements} />
          <Route path="/customer-feedback" component={CustomerFeedback} />
          <Route path="/eco-warrior-badges" component={EcoWarriorBadges} />
          <Route path="/access-control">
            <AdminRoute>
              <AccessControl />
            </AdminRoute>
          </Route>
          <Route path="/rbac-management">
            <AdminRoute>
              <RBACManagement />
            </AdminRoute>
          </Route>
          <Route path="/ip-management">
            <AdminRoute>
              <IpManagementDashboard />
            </AdminRoute>
          </Route>
          <Route path="/customer-import">
            <AdminRoute>
              <CustomerImportPage />
            </AdminRoute>
          </Route>
          <Route path="/cms-admin">
            <AdminRoute>
              <CmsAdmin />
            </AdminRoute>
          </Route>
          <Route path="/command-center">
            <AdminRoute>
              <CommandCenter />
            </AdminRoute>
          </Route>
          <Route path="/admin/command-center">
            <AdminRoute>
              <AdminCommandCenter />
            </AdminRoute>
          </Route>
          <Route path="/admin-command-center">
            <AdminRoute>
              <AdminCommandCenter />
            </AdminRoute>
          </Route>
          <Route path="/profile" component={ProfilePage} />
          <Route path="/settings" component={SettingsPage} />
          <Route path="/dashboard">
            <AdminRoute>
              <DashboardRenderer />
            </AdminRoute>
          </Route>
          <Route path="/feature-flags">
            <AdminRoute>
              <FeatureManagement />
            </AdminRoute>
          </Route>
          <Route path="/admin/feature-flags">
            <AdminRoute>
              <FeatureManagement />
            </AdminRoute>
          </Route>

          {/* New Admin Monitoring & Communication Routes */}
          <Route path="/admin/system-logs">
            <AdminRoute>
              <SystemLogsPage />
            </AdminRoute>
          </Route>
          <Route path="/admin/performance-metrics">
            <AdminRoute>
              <PerformanceMetricsPage />
            </AdminRoute>
          </Route>
          <Route path="/admin/database-status">
            <AdminRoute>
              <DatabaseStatusPage />
            </AdminRoute>
          </Route>
          <Route path="/admin/communication-management">
            <AdminRoute>
              <CommunicationManagementPage />
            </AdminRoute>
          </Route>

          {/* New Legal/Business Pages */}
          <Route path="/cookie-policy" component={CookiePolicy} />
          <Route path="/careers" component={Careers} />
          <Route path="/blog" component={Blog} />
          <Route path="/news" component={Blog} />
          <Route path="/faq" component={FAQ} />
          <Route path="/service-areas" component={ServiceAreas} />
          <Route path="/case-studies" component={CaseStudies} />
          <Route path="/reviews" component={Reviews} />
          <Route path="/testimonials" component={Reviews} />
          <Route path="/sitemap" component={Sitemap} />

          {/* COMPETITOR COMPARISON PAGES — dual-brand
           *
           * CHANGE [dual-brand routing]: routes use the child-render form so
           * we can pass forceBrand explicitly.  This guarantees the correct
           * brand config (hero colours, CTA label, canonical URL) on the very
           * first render — before BrandingContext’s path-detection useEffect
           * fires — and removes any risk of an incorrect "greenshield" flash
           * on an Aegis360 URL.
           *
           *   /platform/comparison   → Aegis360 brand  (B2B SaaS, blue)
           *   /technology/comparison → Greenshield brand (B2C, green)
           */}
          <Route path="/platform/comparison">
            <ComparisonPage forceBrand="aegis360" />
          </Route>
          <Route path="/technology/comparison">
            <ComparisonPage forceBrand="greenshield" />
          </Route>

          {/* PROTECTED TENDER ROUTES - Require Authentication */}
          <Route path="/tenders">
            <AdminRoute>
              <TenderLibrary />
            </AdminRoute>
          </Route>
          <Route path="/services">
            <AdminRoute>
              <ServiceManagement />
            </AdminRoute>
          </Route>

          <Route component={NotFound} />
        </Switch>
      </Suspense>
    </ErrorBoundary>
  );
}

function App() {
  // TASK 2: Session depth tracking with route navigation monitoring
  const [location] = useLocation();

  useEffect(() => {
    preloadCriticalRoutes();
  }, []);

  // TASK 2: Track feature access based on route navigation
  useEffect(() => {
    const routeToFeatureMap: Record<string, string> = {
      "/dashboard": FEATURES.DASHBOARD,
      "/settings": FEATURES.SETTINGS,
      "/reports": FEATURES.REPORTS,
      "/treatment-reports": FEATURES.REPORTS,
      "/survey-report": FEATURES.REPORTS,
      "/crm": FEATURES.CRM,
      "/quote": FEATURES.QUOTES,
      "/quotation": FEATURES.QUOTES,
      "/book": FEATURES.APPOINTMENTS,
      "/analytics-dashboard": FEATURES.ANALYTICS,
      "/unified-performance-dashboard": FEATURES.ANALYTICS,
      "/seasonal-prevention-calendar": FEATURES.PREVENTION_CALENDAR,
      "/iot-pest-sensors": FEATURES.IOT_SENSORS,
      "/compliance-audit": FEATURES.COMPLIANCE,
      "/pricing-admin": FEATURES.PRICING_ADMIN,
      "/backend-admin": FEATURES.BACKEND_ADMIN,
      "/mobile-pest-scanner": FEATURES.MOBILE_SCANNER,
      "/ar-pest-identification": FEATURES.AR_PEST_LENS,
    };

    const featureName = routeToFeatureMap[location];
    if (featureName) {
      trackFeature(featureName);
    }

    // Track session depth on major navigation events
    if (location !== "/" && location !== "/landing") {
      trackSessionDepth();
    }
  }, [location]);

  // TASK 2: Track session depth on page visibility change (user returns to tab)
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState === "visible") {
        trackSessionDepth();
      }
    };

    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, []);

  // TASK 2: Track session depth before page unload
  useEffect(() => {
    const handleBeforeUnload = () => {
      trackSessionDepth();
    };

    window.addEventListener("beforeunload", handleBeforeUnload);

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);

  return (
    <HelmetProvider>
      <QueryClientProvider client={queryClient}>
        <BrandingProvider>
          <RouteProtection>
            <div className="min-h-screen bg-gray-50">
              <Header />
              <AppLayout />
              <Footer />
              <CustomerSupportChat />
              <StreamlinedOnboarding />
              <FeedbackWidget />
              <Toaster />
            </div>
          </RouteProtection>
        </BrandingProvider>
      </QueryClientProvider>
    </HelmetProvider>
  );
}

export default App;
