import { useState, useEffect, Suspense } from 'react';
import './App.css';
import { Routes, Route, BrowserRouter, Navigate } from 'react-router-dom';
import { QueryClient } from '@tanstack/react-query';
import { Toaster } from 'sonner';

import { ErrorBoundary } from "@/components/common/ErrorBoundary";
import { BrushStrokeLoader } from "@/components/ui/BrushStrokeLoader";
import { SecurityAlerts } from "@/components/security/SecurityAlerts";
import { HomeRouter } from '@/components/HomeRouter';
import { SitemapGenerator } from './components/seo/SitemapGenerator';
import { ProtectedRoute } from '@/components/ProtectedRoute';
import ReferralTracker from '@/components/referral/ReferralTracker';
import { MobileLayout } from '@/components/layout/MobileLayout';
import { dailyEliteStocksManager } from '@/services/eliteStocks/dailyRefreshManager';
import { APIHealthMonitor } from '@/services/api/apiHealthMonitor';
import { EnhancedCacheManager } from '@/services/api/enhancedCacheManager';
import { AppProviders } from '@/providers/AppProviders';
import { logger } from '@/utils/logger';

// Page components
import Auth from '@/pages/Auth';
import Dashboard from '@/pages/Dashboard';
import BriansMasterpiece from '@/pages/BriansMasterpiece';
import MarketPulsePro from '@/pages/MarketPulsePro';
import EliteInsiders from '@/pages/EliteInsiders';
import Analytics from '@/pages/Analytics';
import ReferralDashboard from '@/pages/ReferralDashboard';
import ReferralAnalysis from '@/pages/ReferralAnalysis';
import EnhancedCommunityHub from './pages/EnhancedCommunityHub';
import InfluencerHubPage from './pages/InfluencerHub';
import SmartPicksPage from '@/pages/SmartPicksPage';

// Lazy loaded components
import { lazy } from 'react';
const Backtesting = lazy(() => import('@/pages/Backtesting'));
const CompareStocks = lazy(() => import('@/pages/CompareStocks'));
const Compliance = lazy(() => import('@/pages/Compliance'));
const CryptoPicasso = lazy(() => import('@/pages/CryptoPicasso'));
const FAQ = lazy(() => import('@/pages/FAQ'));
const HowAIWorks = lazy(() => import('@/pages/HowAIWorks'));
const LearnArticle = lazy(() => import('@/pages/LearnArticle'));
const LearnHub = lazy(() => import('@/pages/LearnHub'));
const NotFound = lazy(() => import('@/pages/NotFound'));
const OptionDetails = lazy(() => import('@/pages/OptionDetails'));
const Portfolio = lazy(() => import('@/pages/Portfolio'));
const Pricing = lazy(() => import('@/pages/Pricing'));
const Profile = lazy(() => import('@/pages/Profile'));
const PutsPower = lazy(() => import('@/pages/PutsPower'));
const RiskManagement = lazy(() => import('@/pages/RiskManagement'));
const Roadmap = lazy(() => import('@/pages/Roadmap'));
const SectorPage = lazy(() => import('@/pages/SectorPage'));
const Settings = lazy(() => import('@/pages/Settings'));
const StockPage = lazy(() => import('@/pages/StockPage'));
const SubscriptionSuccess = lazy(() => import('@/pages/SubscriptionSuccess'));
const SubscriptionTiers = lazy(() => import('@/pages/SubscriptionTiers'));
const SuperInvestorAnalytics = lazy(() => import('@/pages/SuperInvestorAnalytics'));
const TrendingStocks = lazy(() => import('@/pages/TrendingStocks'));
import * as LazyComponents from '@/utils/codesplitting/LazyComponents';

export const App = () => {
  const [queryClient] = useState(() => {
    return new QueryClient({
      defaultOptions: {
        queries: {
          retry: 1,
          staleTime: 5 * 60 * 1000, // 5 minutes
          refetchOnWindowFocus: false,
        },
      },
    });
  });

  useEffect(() => {
    const initializeServices = async () => {
      try {
        // Initialize existing services with safety checks
        if (dailyEliteStocksManager?.initialize) {
          dailyEliteStocksManager.initialize();
        }
        if (APIHealthMonitor?.initialize) {
          APIHealthMonitor.initialize();
        }
        if (EnhancedCacheManager?.initialize) {
          EnhancedCacheManager.initialize();
        }
        
        logger.info('Stock Picasso services initialized successfully');
      } catch (error) {
        // Fallback to console.error if logger fails
        console.error('Service initialization failed:', error);
        // Continue execution even if services fail to initialize
      }
    };

    initializeServices();
    
    return () => {
      try {
        if (dailyEliteStocksManager?.cleanup) {
          dailyEliteStocksManager.cleanup();
        }
        if (APIHealthMonitor?.stop) {
          APIHealthMonitor.stop();
        }
      } catch (error) {
        console.error('Service cleanup failed:', error);
      }
    };
  }, []);
  
  return (
    <AppProviders queryClient={queryClient}>
      <BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
        <ReferralTracker />
        <SecurityAlerts />
        <Toaster />
        <ErrorBoundary variant="page">
          <MobileLayout>
            <Suspense fallback={
              <BrushStrokeLoader 
                title="Loading Stock Picasso..."
                description="Preparing your investment canvas"
                useRealProgress={true}
                realProgress={80}
                currentStage="Loading application components..."
                duration={1500}
              />
            }>
              <Routes>
                <Route path="/" element={
                  <ErrorBoundary fallback={
                    <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted/10 flex items-center justify-center p-6">
                      <div className="max-w-md text-center bg-card rounded-lg border p-6 shadow-lg">
                        <div className="text-6xl mb-4">🏠</div>
                        <h1 className="text-2xl font-bold mb-2">Welcome to Stock Picasso</h1>
                        <p className="text-muted-foreground mb-4">
                          Loading your personalized investment dashboard...
                        </p>
                        <div className="animate-spin inline-block w-6 h-6 border-[3px] border-current border-t-transparent text-primary rounded-full" />
                        <p className="text-xs text-muted-foreground mt-4">
                          If this continues loading, please refresh the page
                        </p>
                      </div>
                    </div>
                  }>
                    <HomeRouter />
                  </ErrorBoundary>
                } />
                <Route path="/auth/*" element={<Auth />} />
                <Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
                
                {/* Core Feature Routes */}
                <Route path="/brians-masterpiece" element={<ProtectedRoute><BriansMasterpiece /></ProtectedRoute>} />
                <Route path="/market-pulse" element={<ProtectedRoute><MarketPulsePro /></ProtectedRoute>} />
                <Route path="/elite-insiders" element={<ProtectedRoute><EliteInsiders /></ProtectedRoute>} />
                <Route path="/analytics" element={<ProtectedRoute><Analytics /></ProtectedRoute>} />
                <Route path="/analytics-dashboard" element={<Navigate to="/analytics" replace />} />
                <Route path="/smart-picks" element={<ProtectedRoute><SmartPicksPage /></ProtectedRoute>} />
                
                {/* Additional Routes */}
                <Route path="/learn" element={<LearnHub />} />
                <Route path="/learn/:slug" element={<LearnArticle />} />
                <Route path="/subscription-tiers" element={<SubscriptionTiers />} />
                <Route path="/pricing" element={<Pricing />} />
                <Route path="/trending" element={<TrendingStocks />} />
                <Route path="/faq" element={<FAQ />} />
                <Route path="/roadmap" element={<Roadmap />} />
                <Route path="/how-ai-works" element={<HowAIWorks />} />
                <Route path="/compliance" element={<Compliance />} />
                <Route path="/sector/:sector" element={<SectorPage />} />
                <Route path="/education" element={<Navigate to="/learn" replace />} />
                <Route path="/stock-search" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
                <Route path="/stock/:ticker" element={<ProtectedRoute><StockPage /></ProtectedRoute>} />
                <Route path="/stocks/:ticker" element={<ProtectedRoute><StockPage /></ProtectedRoute>} />
                <Route path="/crypto-picasso" element={<ProtectedRoute><CryptoPicasso /></ProtectedRoute>} />
                <Route path="/super-investor-analytics" element={<Navigate to="/super-investor" replace />} />
                <Route path="/super-investor" element={<ProtectedRoute><SuperInvestorAnalytics /></ProtectedRoute>} />
                <Route path="/market-pulse-pro" element={<Navigate to="/market-pulse" replace />} />
                <Route path="/puts-power" element={<ProtectedRoute><PutsPower /></ProtectedRoute>} />
                <Route path="/settings" element={<ProtectedRoute><Settings /></ProtectedRoute>} />
                <Route path="/profile" element={<ProtectedRoute><Profile /></ProtectedRoute>} />
                <Route path="/portfolio" element={<ProtectedRoute><Portfolio /></ProtectedRoute>} />
                <Route path="/risk-management" element={<ProtectedRoute><RiskManagement /></ProtectedRoute>} />
                <Route path="/option/:symbol/:type/:expiry/:strike" element={<ProtectedRoute><OptionDetails /></ProtectedRoute>} />
                <Route path="/backtesting" element={<ProtectedRoute><Backtesting /></ProtectedRoute>} />
                <Route path="/compare/:comparison?" element={<ProtectedRoute><CompareStocks /></ProtectedRoute>} />
                <Route path="/subscription-success" element={<ProtectedRoute><SubscriptionSuccess /></ProtectedRoute>} />
                <Route path="/community" element={<EnhancedCommunityHub />} />
                <Route path="/community/legacy" element={<Navigate to="/community" replace />} />
                <Route path="/community/social" element={<Navigate to="/community" replace />} />
                <Route path="/education-hub" element={<Navigate to="/learn" replace />} />
                <Route path="/partners" element={<InfluencerHubPage />} />
                <Route path="/referrals" element={<ProtectedRoute><ReferralDashboard /></ProtectedRoute>} />
                <Route path="/referral-analysis" element={<ProtectedRoute><ReferralAnalysis /></ProtectedRoute>} />
                <Route path="/sitemap.xml" element={<SitemapGenerator />} />
                
                <Route path="*" element={<NotFound />} />
              </Routes>
            </Suspense>
          </MobileLayout>
        </ErrorBoundary>
      </BrowserRouter>
    </AppProviders>
  );
};