import React, { useEffect, lazy, Suspense, startTransition } from "react";
import { Switch, Route, Redirect, useLocation } from "wouter";
import { queryClient } from "./lib/queryClient";
import { QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "next-themes";
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { AuthProvider } from "@/hooks/use-auth";
import { BrandingProvider, useBranding } from "@/hooks/use-branding";
import { useHeartbeat } from "@/hooks/use-heartbeat";
import { ProtectedRoute } from "@/lib/protected-route";
import { AdminRoute } from "@/lib/admin-route";

import Layout from "@/components/Layout";
import NotFound from "@/pages/not-found";
import { LazyComponentWrapper } from "@/components/ErrorBoundary";
import { ConcurrentErrorBoundary } from "@/components/ConcurrentErrorBoundary";

// Mobile-compatible lazy loading with error recovery
const createMobileSafeLazyComponent = (importFn: () => Promise<{ default: React.ComponentType<any> }>) => {
  return lazy(() => importFn().catch(error => {
    console.error('Mobile import error:', error);
    // Return a fallback component for mobile module loading issues
    return { 
      default: () => (
        <div className="flex items-center justify-center min-h-screen p-4">
          <div className="text-center max-w-md">
            <h2 className="text-xl font-semibold mb-4 text-foreground">Loading Issue</h2>
            <p className="text-muted-foreground mb-6 text-sm">
              There was a problem loading the page content. Please try refreshing the page.
            </p>
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-primary text-primary-foreground rounded hover:bg-primary/90 transition-colors mr-2"
            >
              Refresh Page
            </button>
            <button
              onClick={() => window.location.href = '/home'}
              className="px-4 py-2 bg-secondary text-secondary-foreground rounded hover:bg-secondary/90 transition-colors"
            >
              Go Home
            </button>
          </div>
        </div>
      )
    };
  }));
};

// Core pages - lazy loaded for optimal bundle splitting with mobile safety
const Home = createMobileSafeLazyComponent(() => import("@/pages/Home"));
const AuthPage = createMobileSafeLazyComponent(() => import("@/pages/auth-page"));

// ScandiCrime pages - lazy loaded for better code splitting with mobile safety
const ScandiCrimeAuthPage = createMobileSafeLazyComponent(() => import("@/pages/ScandiCrimeAuthPage"));
const ScandiCrimeSeriesPage = createMobileSafeLazyComponent(() => import("@/pages/ScandiCrimeSeriesPage"));
const ScandiCrimeWatchlistPage = createMobileSafeLazyComponent(() => import("@/pages/ScandiCrimeWatchlistPage"));

// Regular pages - lazy loaded with mobile safety
const Trending = createMobileSafeLazyComponent(() => import("@/pages/Trending"));
const SeriesPage = createMobileSafeLazyComponent(() => import("@/pages/SeriesPage"));
const SeriesDetails = createMobileSafeLazyComponent(() => import("@/pages/SeriesDetails"));
const WatchEpisode = createMobileSafeLazyComponent(() => import("@/pages/WatchEpisode"));
const WatchlistPage = createMobileSafeLazyComponent(() => import("@/pages/WatchlistPage"));
const ProfilePage = createMobileSafeLazyComponent(() => import("@/pages/ProfilePage"));

// Admin pages - lazy loaded (heavy components) with mobile safety
const Upload = createMobileSafeLazyComponent(() => import("@/pages/Upload"));
const AdminPage = createMobileSafeLazyComponent(() => import("@/pages/AdminPage"));
const EditSeries = createMobileSafeLazyComponent(() => import("@/pages/EditSeries"));
const EditSeason = createMobileSafeLazyComponent(() => import("@/pages/EditSeason"));
const EditEpisode = createMobileSafeLazyComponent(() => import("@/pages/EditEpisode"));
const BatchEditEpisodes = createMobileSafeLazyComponent(() => import("@/pages/BatchEditEpisodes"));
const AdvancedAnalytics = createMobileSafeLazyComponent(() => import("@/pages/AdvancedAnalytics"));

// Payment is now handled by Stripe Checkout (hosted page) — see
// /api/create-checkout-session. No client-side checkout component
// is needed.

// Debug/Test pages - lazy loaded (development only) with mobile safety
const VideoDebugPage = createMobileSafeLazyComponent(() => import("@/pages/video-debug-page"));
const EnhancedVideoDebugPage = createMobileSafeLazyComponent(() => import("@/pages/enhanced-video-debug"));
const MobileVideoTestPage = createMobileSafeLazyComponent(() => import("@/pages/MobileVideoTestPage"));
const SimpleMobileTest = createMobileSafeLazyComponent(() => import("@/pages/SimpleMobileTest"));
const MobileVideoPage = createMobileSafeLazyComponent(() => import("@/pages/MobileVideoPage"));
const DirectLinkPage = createMobileSafeLazyComponent(() => import("@/pages/DirectLinkPage"));
const TestUpload = createMobileSafeLazyComponent(() => import("@/pages/TestUpload"));
const MediaStorageTestPage = createMobileSafeLazyComponent(() => import("@/pages/MediaStorageTestPage"));
const MigrationAnalysis = createMobileSafeLazyComponent(() => import("@/pages/MigrationAnalysis"));
const StorageConfig = createMobileSafeLazyComponent(() => import("@/pages/StorageConfig"));
const GCSMediaTest = createMobileSafeLazyComponent(() => import("@/pages/GCSMediaTest"));
const MediaTest = createMobileSafeLazyComponent(() => import("@/pages/MediaTest"));

// Support pages - lazy loaded with mobile safety
const FeedbackPage = createMobileSafeLazyComponent(() => import("@/pages/FeedbackPage"));
const ReportIssuePage = createMobileSafeLazyComponent(() => import("@/pages/ReportIssuePage"));

// Loading component for better UX
const PageLoader = () => (
  <div className="flex items-center justify-center min-h-screen">
    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
  </div>
);

// Enhanced wrapper for mobile-safe lazy components
const LazyWrapper = ({ Component }: { Component: React.LazyExoticComponent<React.ComponentType<any>> }) => (
  <LazyComponentWrapper>
    <Component />
  </LazyComponentWrapper>
);

// Scroll restoration component
const ScrollToTop = () => {
  const [location] = useLocation();
  
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [location]);
  
  return null;
};

// Enhanced Series Details route component with mobile-aware branding detection
const SeriesDetailsRoute = () => {
  const { isScandiCrime } = useBranding();
  
  // Enhanced mobile-specific ScandiCrime detection
  const detectMobileScandiCrime = () => {
    if (typeof window === 'undefined') return false;
    
    const urlParams = new URLSearchParams(window.location.search);
    const brandParam = urlParams.get('brand');
    const hostname = window.location.hostname.toLowerCase();
    const href = window.location.href.toLowerCase();
    const storedBrand = localStorage.getItem('mobileBrand');
    const isMobile = /Mobile|Android|iPhone|iPad/i.test(navigator.userAgent);
    
    // Explicit brand parameter takes priority
    if (brandParam === 'scandicrime') {
      if (isMobile) localStorage.setItem('mobileBrand', 'scandicrime');
      return true;
    }
    
    // Check stored mobile preference
    if (isMobile && storedBrand === 'scandicrime') {
      return true;
    }
    
    // Check hostname/URL patterns
    if (hostname.includes('scandicrime') || 
        hostname.includes('scandi-crime') ||
        href.includes('scandicrime') ||
        href.includes('brand=scandicrime')) {
      if (isMobile) localStorage.setItem('mobileBrand', 'scandicrime');
      return true;
    }
    
    return false;
  };
  
  const shouldUseScandiCrime = isScandiCrime || detectMobileScandiCrime();
  
  return shouldUseScandiCrime ? (
    <LazyComponentWrapper>
      <ScandiCrimeSeriesPage />
    </LazyComponentWrapper>
  ) : (
    <LazyComponentWrapper>
      <SeriesDetails />
    </LazyComponentWrapper>
  );
};

// Watchlist route component that chooses right page based on branding
const WatchlistRoute = () => {
  const { isScandiCrime } = useBranding();
  return (
    <LazyComponentWrapper>
      {isScandiCrime ? <ScandiCrimeWatchlistPage /> : <WatchlistPage />}
    </LazyComponentWrapper>
  );
};

// Auth route component that chooses right page based on branding
const AuthRoute = () => {
  const { isScandiCrime } = useBranding();
  
  // Use window.location to ensure we're checking the latest URL parameters
  const urlParams = new URLSearchParams(window.location.search);
  const brandParam = urlParams.get('brand');
  const isExplicitScandiCrime = brandParam === 'scandicrime';
  
  // Enhanced mobile-friendly detection
  const hostname = window.location.hostname.toLowerCase();
  const href = window.location.href.toLowerCase();
  const isScandiCrimeURL = hostname.includes('scandicrime') || 
                          hostname.includes('scandi-crime') ||
                          href.includes('scandicrime') ||
                          href.includes('brand=scandicrime');
  
  // Check if mobile device accessing via scandicrime domain
  const isMobile = /Mobile|Android|iPhone|iPad/i.test(navigator.userAgent);
  const mobileOverride = isMobile && localStorage.getItem('mobileBrand') === 'scandicrime';
  
  console.log('[AuthRoute] Branding check:', {
    isScandiCrime,
    isExplicitScandiCrime,
    isScandiCrimeURL,
    mobileOverride,
    isMobile,
    hostname,
    href: window.location.href
  });
  
  // Use comprehensive check for ScandiCrime branding
  const shouldUseScandiCrime = isExplicitScandiCrime || isScandiCrime || isScandiCrimeURL || mobileOverride;
  
  console.log('[AuthRoute] Using ScandiCrime auth:', shouldUseScandiCrime);
  
  return shouldUseScandiCrime ? (
    <LazyComponentWrapper>
      <ScandiCrimeAuthPage />
    </LazyComponentWrapper>
  ) : (
    <LazyComponentWrapper>
      <AuthPage />
    </LazyComponentWrapper>
  );
};

function Router() {
  // Add heartbeat to track active users
  useHeartbeat();
  
  return (
    <Suspense fallback={
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    }>
      <ScrollToTop />
      <Switch>
        <Route path="/" component={Home} />
        <Route path="/auth" component={AuthRoute} />
        <Route path="/home" component={Home} />
        <Route path="/trending" component={() => <LazyWrapper Component={Trending} />} />
        <Route path="/series" component={() => <LazyWrapper Component={SeriesPage} />} />
        <Route path="/series/:id" component={SeriesDetailsRoute} />
        <Route path="/watch/:id" component={() => <LazyWrapper Component={WatchEpisode} />} />
        <ProtectedRoute path="/my-list" component={WatchlistRoute} />
        <ProtectedRoute path="/profile" component={() => <LazyWrapper Component={ProfilePage} />} />
        <ProtectedRoute path="/feedback" component={() => <LazyWrapper Component={FeedbackPage} />} />
        <ProtectedRoute path="/report-issue" component={() => <LazyWrapper Component={ReportIssuePage} />} />
        <AdminRoute path="/upload" component={() => <LazyWrapper Component={Upload} />} />
        <AdminRoute path="/admin" component={() => <LazyWrapper Component={AdminPage} />} />
        <AdminRoute path="/analytics" component={() => <LazyWrapper Component={AdvancedAnalytics} />} />
        <AdminRoute path="/admin/analytics" component={() => <LazyWrapper Component={AdvancedAnalytics} />} />
        <AdminRoute path="/advanced-analytics" component={() => <LazyWrapper Component={AdvancedAnalytics} />} />
        <AdminRoute path="/edit/series/:id" component={() => <LazyWrapper Component={EditSeries} />} />
        <AdminRoute path="/edit/season/:id" component={() => <LazyWrapper Component={EditSeason} />} />
        <AdminRoute path="/edit/episode/:id" component={() => <LazyWrapper Component={EditEpisode} />} />
        <AdminRoute path="/batch-edit/episodes" component={() => <LazyWrapper Component={BatchEditEpisodes} />} />
        <AdminRoute path="/video-debug" component={() => <LazyWrapper Component={VideoDebugPage} />} />
        <AdminRoute path="/enhanced-video-debug" component={() => <LazyWrapper Component={EnhancedVideoDebugPage} />} />
        <AdminRoute path="/mobile-video-test" component={() => <LazyWrapper Component={MobileVideoTestPage} />} />
        <AdminRoute path="/media-storage-test" component={() => <LazyWrapper Component={MediaStorageTestPage} />} />
        <AdminRoute path="/migration-analysis" component={() => <LazyWrapper Component={MigrationAnalysis} />} />
        <AdminRoute path="/storage-config" component={() => <LazyWrapper Component={StorageConfig} />} />
        <AdminRoute path="/gcs-media-test" component={() => <LazyWrapper Component={GCSMediaTest} />} />
        <AdminRoute path="/media-test" component={() => <LazyWrapper Component={MediaTest} />} />
        <Route path="/mobile-test" component={() => <LazyWrapper Component={SimpleMobileTest} />} />
        <Route path="/mobile-video/:episodeId" component={() => <LazyWrapper Component={MobileVideoPage} />} />
        <Route path="/direct-play/:episodeId" component={() => <LazyWrapper Component={DirectLinkPage} />} />
        <AdminRoute path="/test-upload" component={() => <LazyWrapper Component={TestUpload} />} />
        <Route component={NotFound} />
      </Switch>
    </Suspense>
  );
}

function App() {
  return (
    <ConcurrentErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <ThemeProvider attribute="class" defaultTheme="dark">
          <AuthProvider>
            <BrandingProvider>
              <TooltipProvider>
                <Layout>
                  <Router />
                </Layout>
                <Toaster />
              </TooltipProvider>
            </BrandingProvider>
          </AuthProvider>
        </ThemeProvider>
      </QueryClientProvider>
    </ConcurrentErrorBoundary>
  );
}

export default App;
