import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { HelmetProvider } from 'react-helmet-async';
import React, { Suspense, useEffect } from "react";
import ScrollToTop from "@/components/ScrollToTop";
import LoadingFallback from "@/components/LoadingFallback";
import Analytics from "@/components/Analytics";
import OrganizationSchema from "@/components/OrganizationSchema";
import GoogleSearchConsole from "@/components/GoogleSearchConsole";
import CoreWebVitals from "@/components/CoreWebVitals";
import ServiceWorkerRegistration from "@/components/ServiceWorkerRegistration";
import CriticalResourceLoader from "@/components/CriticalResourceLoader";
import StickyCTA from "@/components/StickyCTA";
import MobilePhoneButton from "@/components/MobilePhoneButton";
import ExitIntentPopup from "@/components/ExitIntentPopup";
import SocialProofToasts from "@/components/SocialProofToasts";
import Index from "./pages/Index";
import OgImage from "./pages/OgImage";
import NotFound from "./pages/NotFound";
import { initializeSecurity } from "@/utils/security";
import { useVisitorTracking } from "@/hooks/useVisitorTracking";

// Import SEO audit utility
import "@/utils/seoAudit";

// Lazy load non-critical pages
import LazyMisfitMethod from "./pages/LazyMisfitMethod";
import LazyServices from "./pages/LazyServices";
import LazyTestimonials from "./pages/LazyTestimonials";
import LazySTRInsights from "./pages/LazySTRInsights";
import LazyCaseStudies from "./pages/LazyCaseStudies";
import LazyWhatToExpect from "./pages/LazyWhatToExpect";
import LazyScheduleCall from "./pages/LazyScheduleCall";
import LazyContactUs from "./pages/LazyContactUs";
import LazyRevenueCalculator from "./pages/LazyRevenueCalculator";
import LazyBlogArticleDetail from "./pages/LazyBlogArticleDetail";
import LazyApplyNow from "./pages/LazyApplyNow";

// Lazy load service detail pages
const LazyPropertyDesign = React.lazy(() => import('./pages/services/PropertyDesign'));
const LazyRevenueOptimization = React.lazy(() => import('./pages/services/RevenueOptimization'));
const LazyGuestServices = React.lazy(() => import('./pages/services/GuestServices'));
const LazyPropertyMaintenance = React.lazy(() => import('./pages/services/PropertyMaintenance'));
const LazyPermitCompliance = React.lazy(() => import('./pages/services/PermitCompliance'));

// Lazy location page wrapper
const LazyLocationPage = ({ component }: { component: () => Promise<any> }) => {
  const Component = React.lazy(component);
  return <Component />;
};

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      gcTime: 10 * 60 * 1000, // 10 minutes
    },
  },
});

const AppRoutes = () => {
  useVisitorTracking();

  return (
    <Suspense fallback={<LoadingFallback />}>
      <Routes>
        <Route path="/" element={<Index />} />
        <Route path="/misfit-method" element={<LazyMisfitMethod />} />
        <Route path="/services" element={<LazyServices />} />
        <Route path="/services/property-design" element={<Suspense fallback={<LoadingFallback />}><LazyPropertyDesign /></Suspense>} />
        <Route path="/services/revenue-optimization" element={<Suspense fallback={<LoadingFallback />}><LazyRevenueOptimization /></Suspense>} />
        <Route path="/services/guest-services" element={<Suspense fallback={<LoadingFallback />}><LazyGuestServices /></Suspense>} />
        <Route path="/services/property-maintenance" element={<Suspense fallback={<LoadingFallback />}><LazyPropertyMaintenance /></Suspense>} />
        <Route path="/services/permit-compliance" element={<Suspense fallback={<LoadingFallback />}><LazyPermitCompliance /></Suspense>} />
        <Route path="/what-to-expect" element={<LazyWhatToExpect />} />
        <Route path="/revenue-calculator" element={<LazyRevenueCalculator />} />
        <Route path="/testimonials" element={<LazyTestimonials />} />
        <Route path="/str-insights" element={<LazySTRInsights />} />
        <Route path="/str-insights/:slug" element={<LazyBlogArticleDetail />} />
        <Route path="/case-studies" element={<LazyCaseStudies />} />
        <Route path="/schedule-call" element={<LazyScheduleCall />} />
        <Route path="/schedule-call/:category/:item" element={<LazyScheduleCall />} />
        <Route path="/apply-now" element={<LazyApplyNow />} />
        <Route path="/contact-us" element={<LazyContactUs />} />
        
        {/* High-Value Content Pages */}
        <Route path="/nashville-str-regulations" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/NashvilleSTRRegulations')} /></Suspense>} />
        <Route path="/airbnb-vs-vrbo-nashville" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/AirbnbVsVRBO')} /></Suspense>} />
        
        {/* Location Pages */}
        <Route path="/locations/sobro" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/SoBro')} /></Suspense>} />
        <Route path="/locations/the-gulch" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/TheGulch')} /></Suspense>} />
        <Route path="/locations/midtown" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/Midtown')} /></Suspense>} />
        <Route path="/locations/east-nashville" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/EastNashville')} /></Suspense>} />
        <Route path="/locations/12-south" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/TwelveSouth')} /></Suspense>} />
        <Route path="/locations/germantown" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/Germantown')} /></Suspense>} />
        <Route path="/locations/wedgewood-houston" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/WedgewoodHouston')} /></Suspense>} />
        <Route path="/locations/edgehill" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/Edgehill')} /></Suspense>} />
        <Route path="/locations/sylvan-park" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/SylvanPark')} /></Suspense>} />
        <Route path="/locations/belmont-hillsboro-village" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/BelmontHillsboro')} /></Suspense>} />
        <Route path="/locations/west-end" element={<Suspense fallback={<LoadingFallback />}><LazyLocationPage component={() => import('./pages/locations/WestEnd')} /></Suspense>} />
        
        <Route path="/og-image" element={<OgImage />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </Suspense>
  );
};

const App = () => {
  useEffect(() => {
    // Initialize security measures
    initializeSecurity();
  }, []);

  return (
    <HelmetProvider>
      <QueryClientProvider client={queryClient}>
        <TooltipProvider>
          <OrganizationSchema />
          <GoogleSearchConsole />
          <CoreWebVitals />
          <ServiceWorkerRegistration />
          <CriticalResourceLoader />
          <Analytics
            gaId="TODO-ADD-YOUR-GA4-ID" 
            gtmId="TODO-ADD-YOUR-GTM-ID" 
            fbPixelId="TODO-ADD-YOUR-FB-PIXEL-ID" 
          />
          <Toaster />
          <Sonner />
          <BrowserRouter>
            <ScrollToTop />
            <AppRoutes />
            <StickyCTA />
            <MobilePhoneButton />
            <ExitIntentPopup />
            <SocialProofToasts />
          </BrowserRouter>
        </TooltipProvider>
      </QueryClientProvider>
    </HelmetProvider>
  );
};

export default App;
