import { Suspense, lazy, useState, useEffect, useRef } from "react";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route, Navigate, Outlet, useLocation, useNavigate } from "react-router-dom";
import { AuthProvider, useAuth } from "@/contexts/AuthContext";
import { CookieConsentProvider } from "@/contexts/CookieConsentContext";
import { BootProvider } from "@/contexts/BootContext";
import { useSubscription } from "@/contexts/SubscriptionContext";
import BrandedLoader from "@/components/ui/branded-loader";
import AppShell from "@/components/AppShell";
import AuthUrlHandler from "@/components/auth/AuthUrlHandler";
import { globalFocusManager } from "@/utils/focusManager";
import { setupAutoSave } from "@/store/calculatorStore";
import AuthErrorBoundary from "@/components/auth/AuthErrorBoundary";
import { PWAInstallPrompt, PWAUpdatePrompt } from "@/components/pwa";
import { useIsPWAMode } from "@/hooks/usePWA";
import { isMobileAppSync } from "@/hooks/useMobileApp";
import { useSplashScreen } from "@/hooks/useSplashScreen";
import { initializeRevenueCat } from "@/lib/revenuecat";
// import { SessionTimeoutModal } from "@/components/security/SessionTimeoutModal";

// Lazy load main app components to reduce initial bundle
const Index = lazy(() => import("./pages/Index"));
import Auth from "./pages/Auth"; // Don't lazy load auth - it's critical and needs immediate context access
const ProtectedRoute = lazy(() => import("@/components/ProtectedRoute"));
const Landing = lazy(() => import("./pages/Landing"));
const Start = lazy(() => import("./pages/Start"));
const Discover = lazy(() => import("./pages/Discover"));
const Pricing = lazy(() => import("./pages/Pricing"));
const Contact = lazy(() => import("./pages/Contact"));
const Terms = lazy(() => import("./pages/Terms"));
const PrivacyPolicy = lazy(() => import("./pages/PrivacyPolicy"));
const NotFound = lazy(() => import("./pages/NotFound"));
const Dashboard = lazy(() => import("./pages/Dashboard"));
const ForgotPassword = lazy(() => import("./pages/ForgotPassword"));
const ResetPassword = lazy(() => import("./pages/ResetPassword"));
const Settings = lazy(() => import("./pages/Settings"));
const AppSettings = lazy(() => import("./pages/AppSettings"));
const SubscriptionSettings = lazy(() => import("./pages/SubscriptionSettings"));
const Team = lazy(() => import("./pages/Team"));
const Invite = lazy(() => import("./pages/Invite"));
const Verify = lazy(() => import("./pages/Verify"));
const PasswordReset = lazy(() => import("./pages/PasswordReset"));
const PasswordUpdate = lazy(() => import("./pages/PasswordUpdate"));
const Logout = lazy(() => import("./pages/Logout"));
const Features = lazy(() => import("./pages/Features"));
const Support = lazy(() => import("./pages/Support"));
const AcceptInvite = lazy(() => import("./pages/AcceptInvite"));
const SupportRequest = lazy(() => import("./pages/SupportRequest"));
const SupportRequests = lazy(() => import("./pages/SupportRequests"));
const SupportRequestView = lazy(() => import("./pages/SupportRequestView"));
const ScopeOfWorks = lazy(() => import("./pages/ScopeOfWorks"));
const ScopeOfWork = lazy(() => import("./pages/ScopeOfWork"));
const MaterialLists = lazy(() => import("./pages/MaterialLists"));
const MaterialList = lazy(() => import("./pages/MaterialList"));
const MaterialListNew = lazy(() => import("./pages/MaterialListNew"));
const MaterialListEdit = lazy(() => import("./pages/MaterialListEdit"));
const ScopeOfWorkNew = lazy(() => import("./pages/ScopeOfWorkNew"));
const ScopeOfWorkEdit = lazy(() => import("./pages/ScopeOfWorkEdit"));
const Billing = lazy(() => import("./pages/Billing"));
const AuthCallback = lazy(() => import("./pages/AuthCallback"));
const SubscriptionVerification = lazy(() => import("./pages/SubscriptionVerification"));
const VerifyEmail = lazy(() => import("./pages/VerifyEmail"));
const CookieTest = lazy(() => import("./pages/CookieTest"));
const CheckoutSuccess = lazy(() => import("./pages/CheckoutSuccess"));
const CheckoutLoading = lazy(() => import("./pages/CheckoutLoading"));
const WelcomeOnboarding = lazy(() => import("./pages/WelcomeOnboarding"));
const AdminReviews = lazy(() => import("./pages/AdminReviews"));
const AdminLeads = lazy(() => import("./pages/AdminLeads"));
const AdminAnalytics = lazy(() => import("./pages/AdminAnalytics"));
const AdminDiscoveryAnalytics = lazy(() => import("./pages/AdminDiscoveryAnalytics"));
const AdminCancellationFeedback = lazy(() => import("./pages/AdminCancellationFeedback"));
const Offline = lazy(() => import("./pages/Offline"));
const AppLanding = lazy(() => import("./pages/AppLanding"));
import AppWelcome from "./pages/AppWelcome"; // Eager load - critical for smooth boot splash transition
const EmailOtpAuth = lazy(() => import("./pages/EmailOtpAuth"));
const CompleteProfile = lazy(() => import("./pages/CompleteProfile"));
const WelcomeSuccess = lazy(() => import("./pages/WelcomeSuccess"));
const WelcomeVideo = lazy(() => import("./pages/WelcomeVideo"));
const GetStarted = lazy(() => import("./pages/GetStarted"));

// Mobile App / PWA Root Handler - handles routing based on app context
function PWARootHandler() {
  const isPWA = useIsPWAMode();
  const isMobileApp = isMobileAppSync();
  const { user, loading: authLoading } = useAuth();
  const { 
    active: hasActiveSubscription, 
    loading: subscriptionLoading, 
    verified: subscriptionVerified 
  } = useSubscription();
  const navigate = useNavigate();
  const location = useLocation();
  
  // Track if we've already made a navigation decision
  const hasNavigatedRef = useRef(false);
  const bootTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  
  // Hide native Capacitor splash after initial route determination
  useSplashScreen();
  
  // Cleanup timeout on unmount
  useEffect(() => {
    return () => {
      if (bootTimeoutRef.current) {
        clearTimeout(bootTimeoutRef.current);
      }
    };
  }, []);
  
  // Reset navigation tracking when location changes (e.g., user manually navigates)
  useEffect(() => {
    if (location.pathname !== '/') {
      hasNavigatedRef.current = false;
      if (bootTimeoutRef.current) {
        clearTimeout(bootTimeoutRef.current);
        bootTimeoutRef.current = null;
      }
    }
  }, [location.pathname]);
  
  useEffect(() => {
    // Prevent duplicate navigation
    if (hasNavigatedRef.current) return;
    
    // Wait for auth to settle first
    if (authLoading) return;

    // Handle root path routing based on context
    if (location.pathname === '/' && !(location.state as any)?.intentional) {
      // Capacitor mobile app users
      if (isMobileApp) {
        const isFirstLaunch = !localStorage.getItem('bq_app_launched');
        
        if (user) {
          // Check if subscription is verified OR if timeout should apply
          const isSubscriptionReady = subscriptionVerified && !subscriptionLoading;
          
          if (isSubscriptionReady) {
            // Subscription status is known - navigate accordingly
            hasNavigatedRef.current = true;
            
            if (hasActiveSubscription) {
              console.log('✅ PWARootHandler: User has subscription - go to dashboard');
              navigate('/dashboard', { replace: true });
            } else {
              console.log('📱 PWARootHandler: User needs subscription - go to welcome');
              navigate('/welcome', { replace: true });
            }
          } else {
            // Subscription still loading - set up timeout fallback (only once)
            if (!bootTimeoutRef.current) {
              console.log('⏱️ PWARootHandler: Waiting for subscription (3s timeout)...');
              
              bootTimeoutRef.current = setTimeout(() => {
                if (hasNavigatedRef.current) return;
                hasNavigatedRef.current = true;
                
                console.log('⏱️ PWARootHandler: Timeout reached - using best-known state');
                console.log('📊 Current state:', { user: !!user, hasActiveSubscription, subscriptionVerified, subscriptionLoading });
                
                // Guard: If user became null during the wait, go to entry point instead of paywall
                if (!user) {
                  const isMobilePWA = localStorage.getItem('bq_mobile_app') === 'true';
                  console.log('⚠️ PWARootHandler: User is null at timeout - redirecting to entry point');
                  navigate(isMobilePWA ? '/app-welcome' : '/', { replace: true });
                  return;
                }
                
                // Check localStorage cache as fallback for returning subscribers
                let cachedActive = false;
                try {
                  const cacheKey = `sub:v1:${user.id}`;
                  const cached = JSON.parse(localStorage.getItem(cacheKey) || '{}');
                  cachedActive = cached?.active === true && cached?.userId === user.id;
                  if (cachedActive) {
                    console.log('📦 PWARootHandler: localStorage cache shows active subscription');
                  }
                } catch {}
                
                if (hasActiveSubscription || cachedActive) {
                  navigate('/dashboard', { replace: true });
                } else {
                  navigate('/welcome', { replace: true });
                }
              }, 3000); // 3 second timeout
            }
          }
        } else {
          // No user - go to sign-in
          hasNavigatedRef.current = true;
          if (isFirstLaunch) {
            localStorage.setItem('bq_app_launched', 'true');
          }
          navigate('/app-welcome', { replace: true });
        }
      }
      // PWA users (not Capacitor)
      else if (isPWA) {
        hasNavigatedRef.current = true;
        if (user) {
          navigate('/dashboard', { replace: true });
        } else {
          navigate('/app', { replace: true });
        }
      }
      // Web users - stay on Start page (no navigation needed)
    }
  }, [
    isPWA, 
    isMobileApp, 
    user, 
    authLoading, 
    subscriptionLoading, 
    subscriptionVerified, 
    hasActiveSubscription, 
    navigate, 
    location.pathname
  ]);
  
  return null;
}

function App() {
  const [queryClient] = useState(() => new QueryClient({
    defaultOptions: {
      queries: {
        // Core stability settings
        refetchOnWindowFocus: false,
        refetchOnReconnect: false,
        refetchOnMount: false,
        staleTime: 300000,
        // 5 minutes
        gcTime: 1800000,
        // 30 minutes
        retry: 2,
        // Performance optimizations
        refetchInterval: false,
        // Disable automatic polling by default
        networkMode: 'online'
      },
      mutations: {
        retry: 1,
        networkMode: 'online'
      }
    }
  }));

  // Boot splash is now controlled by BootProvider via appReady signal
  // No hideBootSplash() call here - it's triggered when first route mounts

  // Initialize focus manager, auto-save, and RevenueCat
  useEffect(() => {
    const cleanup = setupAutoSave();
    
    // Early RevenueCat configuration for mobile apps (anonymous init)
    if (isMobileAppSync()) {
      initializeRevenueCat();
    }
    
    return () => {
      cleanup();
      // Focus manager cleanup is now minimal and safe
      try {
        globalFocusManager.cleanup();
      } catch (error) {
        console.warn('Focus manager cleanup error:', error);
      }
    };
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider>
        <BootProvider>
          <CookieConsentProvider>
            <TooltipProvider>
              <Toaster />
              <PWAInstallPrompt />
              <PWAUpdatePrompt />
              {/* <SessionTimeoutModal /> */}
              <BrowserRouter>
                <PWARootHandler />
                <AuthUrlHandler />
                <Routes>
                  {/* Root layout with signalReady() for all routes */}
                  <Route element={<AppShell />}>
                    {/* Public routes */}
                    <Route path="/landing" element={<Navigate to="/" replace />} />
                    <Route path="/discover" element={<Suspense fallback={<BrandedLoader />}><Discover /></Suspense>} />
                    <Route path="/pricing" element={<Suspense fallback={<BrandedLoader />}><Pricing /></Suspense>} />
                    <Route path="/contact" element={<Suspense fallback={<BrandedLoader />}><Contact /></Suspense>} />
                    <Route path="/terms" element={<Suspense fallback={<BrandedLoader />}><Terms /></Suspense>} />
                    <Route path="/privacy-policy" element={<Suspense fallback={<BrandedLoader />}><PrivacyPolicy /></Suspense>} />
                    <Route path="/features" element={<Suspense fallback={<BrandedLoader />}><Features /></Suspense>} />
                    
                    <Route path="/checkout-success" element={<AuthErrorBoundary>
                        <Suspense fallback={<BrandedLoader />}><CheckoutSuccess /></Suspense>
                      </AuthErrorBoundary>} />
                    <Route path="/checkout/loading" element={<Suspense fallback={<BrandedLoader />}><CheckoutLoading /></Suspense>} />

                    {/* Auth routes */}
                    <Route path="/auth" element={<Auth />} />
                    <Route path="/auth/otp" element={<Suspense fallback={<BrandedLoader />}><EmailOtpAuth /></Suspense>} />
                    <Route path="/auth/sign-in" element={<Navigate to="/auth?intent=signin" replace />} />
                    <Route path="/auth/verify-email" element={<Suspense fallback={<BrandedLoader />}><VerifyEmail /></Suspense>} />
                    <Route path="/auth/callback" element={<AuthErrorBoundary>
                        <Suspense fallback={<BrandedLoader />}><AuthCallback /></Suspense>
                      </AuthErrorBoundary>} />
                    <Route path="/forgot-password" element={<Suspense fallback={<BrandedLoader />}><ForgotPassword /></Suspense>} />
                    <Route path="/reset-password" element={<Suspense fallback={<BrandedLoader />}><ResetPassword /></Suspense>} />
                    <Route path="/verify" element={<Suspense fallback={<BrandedLoader />}><Verify /></Suspense>} />
                    <Route path="/password-reset" element={<Suspense fallback={<BrandedLoader />}><PasswordReset /></Suspense>} />
                    <Route path="/password-update" element={<Suspense fallback={<BrandedLoader />}><PasswordUpdate /></Suspense>} />
                    <Route path="/logout" element={<Suspense fallback={<BrandedLoader />}><Logout /></Suspense>} />
                    <Route path="/subscription-verification" element={<Suspense fallback={<BrandedLoader />}><SubscriptionVerification /></Suspense>} />
                    <Route path="/verify-email" element={<AuthErrorBoundary>
                        <Suspense fallback={<BrandedLoader />}><VerifyEmail /></Suspense>
                      </AuthErrorBoundary>} />
                    <Route path="/welcome" element={<AuthErrorBoundary>
                        <Suspense fallback={<BrandedLoader />}><WelcomeOnboarding /></Suspense>
                      </AuthErrorBoundary>} />
                    <Route path="/welcome-success" element={<AuthErrorBoundary>
                        <Suspense fallback={<BrandedLoader />}><WelcomeSuccess /></Suspense>
                      </AuthErrorBoundary>} />
                    <Route path="/welcome-video" element={<AuthErrorBoundary>
                        <Suspense fallback={<BrandedLoader />}><WelcomeVideo /></Suspense>
                      </AuthErrorBoundary>} />
                    <Route path="/get-started" element={<AuthErrorBoundary>
                        <Suspense fallback={<BrandedLoader />}><GetStarted /></Suspense>
                      </AuthErrorBoundary>} />
                    <Route path="/complete-profile" element={<Suspense fallback={<BrandedLoader />}><CompleteProfile /></Suspense>} />
                    <Route path="/accept-invite" element={<Suspense fallback={<BrandedLoader />}><AcceptInvite /></Suspense>} />

                    {/* Public landing pages */}
                    <Route path="/" element={<Suspense fallback={<BrandedLoader />}><Start /></Suspense>} />
                    <Route path="/landing-old" element={<Suspense fallback={<BrandedLoader />}><Landing /></Suspense>} />
                    
                    {/* Protected app routes */}
                    <Route path="/dashboard" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />
                    <Route path="/enquiries" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />
                    <Route path="/projects" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />
                    <Route path="/quotes" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />
                    <Route path="/calculator" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />
                    <Route path="/support" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />
                    <Route path="/more" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />
                    <Route path="/tutorials" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />
                    <Route path="/calendar" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Index /></ProtectedRoute></Suspense>} />

                    <Route path="/settings" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Settings /></ProtectedRoute></Suspense>} />
                    <Route path="/app-settings" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><AppSettings /></ProtectedRoute></Suspense>} />
                    <Route path="/subscription-settings" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><SubscriptionSettings /></ProtectedRoute></Suspense>} />
                    <Route path="/billing" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Billing /></ProtectedRoute></Suspense>} />
                    
                    {/* Redirect old routes to /settings */}
                    <Route path="/profile" element={<Navigate to="/settings" replace />} />
                    <Route path="/account-settings" element={<Navigate to="/settings" replace />} />

                    <Route path="/team" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Team /></ProtectedRoute></Suspense>} />
                    <Route path="/team/invite" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><Invite /></ProtectedRoute></Suspense>} />

                    <Route path="/support-request/new" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><SupportRequest /></ProtectedRoute></Suspense>} />
                    <Route path="/support-requests" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><SupportRequests /></ProtectedRoute></Suspense>} />
                    <Route path="/support-request/:id" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><SupportRequestView /></ProtectedRoute></Suspense>} />

                    <Route path="/scope-of-works" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><ScopeOfWorks /></ProtectedRoute></Suspense>} />
                    <Route path="/scope-of-work/:id" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><ScopeOfWork /></ProtectedRoute></Suspense>} />
                    <Route path="/scope-of-work/new" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><ScopeOfWorkNew /></ProtectedRoute></Suspense>} />
                    <Route path="/scope-of-work/:id/edit" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><ScopeOfWorkEdit /></ProtectedRoute></Suspense>} />

                    <Route path="/material-lists" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><MaterialLists /></ProtectedRoute></Suspense>} />
                    <Route path="/material-list/:id" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><MaterialList /></ProtectedRoute></Suspense>} />
                    <Route path="/material-list/new" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><MaterialListNew /></ProtectedRoute></Suspense>} />
                    <Route path="/material-list/:id/edit" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><MaterialListEdit /></ProtectedRoute></Suspense>} />

                    <Route path="/admin/buildquo/reviews" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><AdminReviews /></ProtectedRoute></Suspense>} />
                    <Route path="/admin/buildquo/analytics" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><AdminAnalytics /></ProtectedRoute></Suspense>} />
                    <Route path="/admin/leads" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><AdminLeads /></ProtectedRoute></Suspense>} />
                    <Route path="/admin/buildquo/discovery-analytics" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><AdminDiscoveryAnalytics /></ProtectedRoute></Suspense>} />
                    <Route path="/admin/buildquo/cancellation-feedback" element={<Suspense fallback={<BrandedLoader />}><ProtectedRoute><AdminCancellationFeedback /></ProtectedRoute></Suspense>} />

                    {/* PWA App Landing */}
                    <Route path="/app" element={<Suspense fallback={<BrandedLoader />}><AppLanding /></Suspense>} />
                    
                    {/* Mobile App (Capacitor) Routes - No Suspense needed, eagerly loaded */}
                    <Route path="/app-welcome" element={<AppWelcome />} />

                    <Route path="/cookie-test" element={<Suspense fallback={<BrandedLoader />}><CookieTest /></Suspense>} />
                    <Route path="/offline" element={<Suspense fallback={<BrandedLoader />}><Offline /></Suspense>} />
                    <Route path="*" element={<Suspense fallback={<BrandedLoader />}><NotFound /></Suspense>} />
                  </Route>
                </Routes>
              </BrowserRouter>
            </TooltipProvider>
          </CookieConsentProvider>
        </BootProvider>
      </AuthProvider>
    </QueryClientProvider>
  );
}
export default App;
