import React, { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
import { ThemeProvider } from '@/components/theme-provider';
import { AppProvider } from '@/contexts/AppContext';
import { PezkuwiProvider } from '@/contexts/PezkuwiContext';
import { WalletProvider } from '@/contexts/WalletContext';
import { WebSocketProvider } from '@/contexts/WebSocketContext';
import { IdentityProvider } from '@/contexts/IdentityContext';
import { AuthProvider } from '@/contexts/AuthContext';
import { DashboardProvider } from '@/contexts/DashboardContext';
import { ReferralProvider } from '@/contexts/ReferralContext';
import { ProtectedRoute } from '@/components/ProtectedRoute';
import { Toaster } from '@/components/ui/toaster';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { initSentry } from '@/lib/sentry';
import './tailwind.css';
import './i18n/config';

// Initialize Sentry error monitoring
initSentry();

// Lazy load wallet-related pages
const WalletDashboard = lazy(() => import('./pages/WalletDashboard'));
const ProfileSettings = lazy(() => import('./pages/ProfileSettings'));
const NotFound = lazy(() => import('@/pages/NotFound'));

// Loading component
const PageLoader = () => (
  <div className="flex items-center justify-center min-h-screen bg-gray-950">
    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-500"></div>
  </div>
);

function ModernApp() {
  const endpoint = (process.env.WS_URL as string) || 'wss://beta-rpc.pezkuwichain.io:19944';

  return (
    <ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
      <ErrorBoundary>
        <AuthProvider>
          <AppProvider>
            <PezkuwiProvider endpoint={endpoint}>
              <WalletProvider>
                <WebSocketProvider>
                  <IdentityProvider>
                    <DashboardProvider>
                      <ReferralProvider>
                        <Suspense fallback={<PageLoader />}>
                          <Routes>
                            <Route path="/" element={<WalletDashboard />} />
                            <Route path="/settings" element={
                              <ProtectedRoute>
                                <ProfileSettings />
                              </ProtectedRoute>
                            } />
                            <Route path="*" element={<NotFound />} />
                          </Routes>
                        </Suspense>
                      </ReferralProvider>
                    </DashboardProvider>
                  </IdentityProvider>
                </WebSocketProvider>
              </WalletProvider>
            </PezkuwiProvider>
          </AppProvider>
        </AuthProvider>
        <Toaster />
      </ErrorBoundary>
    </ThemeProvider>
  );
}

export default ModernApp;
