import { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider } from './contexts/AuthContext';
import { DashboardProvider } from './contexts/DashboardContext';
import ProtectedRoute from './components/layout/ProtectedRoute';
import UniversityProtectedRoute from './components/university/UniversityProtectedRoute';
import CookieConsent from './components/CookieConsent';
import DeviceRestriction from './components/DeviceRestriction';
import ResolvedReportNotification from './components/modals/ResolvedReportNotification';

// Critical pages - load immediately for fast initial render
import Home from './pages/Home';
import Login from './pages/auth/Login';
import Signup from './pages/auth/Signup';

// Helper to handle chunk loading errors (happens after deployments)
// Auto-reloads the page once if a dynamic import fails
const lazyWithRetry = (importFn) => {
  return lazy(() =>
    importFn().catch(() => {
      // Check if we already tried reloading
      const hasReloaded = sessionStorage.getItem('chunk_reload');
      if (!hasReloaded) {
        sessionStorage.setItem('chunk_reload', 'true');
        window.location.reload();
        return new Promise(() => {}); // Never resolves, page will reload
      }
      // If reload didn't help, clear flag and throw
      sessionStorage.removeItem('chunk_reload');
      throw new Error('Failed to load page. Please refresh.');
    })
  );
};

// Clear reload flag on successful page load
if (sessionStorage.getItem('chunk_reload')) {
  sessionStorage.removeItem('chunk_reload');
}

// Lazy load non-critical pages for better performance
// Auth pages
const CompleteProfile = lazyWithRetry(() => import('./pages/auth/CompleteProfile'));
const StudentOnboarding = lazyWithRetry(() => import('./pages/auth/StudentOnboarding'));
const ForgotPassword = lazyWithRetry(() => import('./pages/auth/ForgotPassword'));
const ResetPassword = lazyWithRetry(() => import('./pages/auth/ResetPassword'));
const VerifyEmail = lazyWithRetry(() => import('./pages/auth/VerifyEmail'));

// Exercise pages
const Exercises = lazyWithRetry(() => import('./pages/exercises/Exercises'));
const ExerciseSession = lazyWithRetry(() => import('./pages/exercises/ExerciseSession'));
const ExerciseSummary = lazyWithRetry(() => import('./pages/exercises/ExerciseSummary'));
const UnvalidatedQuestions = lazyWithRetry(() => import('./pages/exercises/UnvalidatedQuestions'));
const SessionHistory = lazyWithRetry(() => import('./pages/exercises/SessionHistory'));

// Legal pages
const PrivacyPolicy = lazyWithRetry(() => import('./pages/legal/PrivacyPolicy'));
const TermsOfService = lazyWithRetry(() => import('./pages/legal/TermsOfService'));
const RefundPolicy = lazyWithRetry(() => import('./pages/legal/RefundPolicy'));

// Other pages
const Pricing = lazyWithRetry(() => import('./pages/Pricing'));
const PaymentSuccess = lazyWithRetry(() => import('./pages/PaymentSuccess'));
const Main = lazyWithRetry(() => import('./pages/Main'));
const Dashboard = lazyWithRetry(() => import('./pages/Dashboard'));
const Agent = lazyWithRetry(() => import('./pages/Agent'));
const Profile = lazyWithRetry(() => import('./pages/Profile'));
const Courses = lazyWithRetry(() => import('./pages/main/Courses'));
const LessonPage = lazyWithRetry(() => import('./pages/main/LessonPage'));
const Contact = lazyWithRetry(() => import('./pages/Contact'));
const MasterMatches = lazyWithRetry(() => import('./pages/MasterMatches'));
const NotFound = lazyWithRetry(() => import('./pages/NotFound'));

// University pages - lazy loaded
const UniversityDashboard = lazyWithRetry(() => import('./pages/university/UniversityDashboard'));
const Students = lazyWithRetry(() => import('./pages/university/Students'));
const StudentDetail = lazyWithRetry(() => import('./pages/university/StudentDetail'));
const Cohorts = lazyWithRetry(() => import('./pages/university/Cohorts'));
const Analytics = lazyWithRetry(() => import('./pages/university/Analytics'));
const BulkImport = lazyWithRetry(() => import('./pages/university/BulkImport'));
const UniversityProfile = lazyWithRetry(() => import('./pages/university/UniversityProfile'));

// Loading fallback component
const PageLoader = () => (
  <div style={{
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '100vh',
    fontSize: '18px',
    color: '#f97316'
  }}>
    Loading...
  </div>
);

function App() {
  return (
    <Router>
      <DeviceRestriction>
        <AuthProvider>
          <DashboardProvider>
            <Suspense fallback={<PageLoader />}>
              <Routes>
                {/* University routes - protected for admin role only */}
                <Route path="/university/dashboard" element={<UniversityProtectedRoute><UniversityDashboard /></UniversityProtectedRoute>} />
                <Route path="/university/students" element={<UniversityProtectedRoute><Students /></UniversityProtectedRoute>} />
                <Route path="/university/students/:studentId" element={<UniversityProtectedRoute><StudentDetail /></UniversityProtectedRoute>} />
                <Route path="/university/cohorts" element={<UniversityProtectedRoute><Cohorts /></UniversityProtectedRoute>} />
                <Route path="/university/analytics" element={<UniversityProtectedRoute><Analytics /></UniversityProtectedRoute>} />
                <Route path="/university/bulk/import" element={<UniversityProtectedRoute><BulkImport /></UniversityProtectedRoute>} />
                <Route path="/university/profile" element={<UniversityProtectedRoute><UniversityProfile /></UniversityProtectedRoute>} />

                {/* Public routes */}
                <Route path="/" element={<Home />} />
                <Route path="/home" element={<Navigate to="/" replace />} />
                <Route path="/signup" element={<Signup />} />
                <Route path="/login" element={<Login />} />
                <Route path="/forgot-password" element={<ForgotPassword />} />
                <Route path="/reset-password" element={<ResetPassword />} />
                <Route path="/verify-email" element={<VerifyEmail />} />
                <Route path="/pricing" element={<Pricing />} />
                <Route path="/privacy-policy" element={<PrivacyPolicy />} />
                <Route path="/terms-of-service" element={<TermsOfService />} />
                <Route path="/refund-policy" element={<RefundPolicy />} />
                <Route path="/contact" element={<Contact />} />

                {/* Protected routes */}
                <Route
                  path="/payment-success"
                  element={
                    <ProtectedRoute>
                      <PaymentSuccess />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/complete-profile"
                  element={
                    <ProtectedRoute>
                      <CompleteProfile />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/student-onboarding"
                  element={
                    <ProtectedRoute>
                      <StudentOnboarding />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/main"
                  element={
                    <ProtectedRoute>
                      <Main />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/courses"
                  element={
                    <ProtectedRoute>
                      <Courses />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/courses/:lessonId"
                  element={
                    <ProtectedRoute>
                      <LessonPage />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/dashboard"
                  element={
                    <ProtectedRoute>
                      <Dashboard />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/exercises"
                  element={
                    <ProtectedRoute>
                      <Exercises />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/exercises/history"
                  element={
                    <ProtectedRoute>
                      <SessionHistory />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/exercises/unvalidated"
                  element={
                    <ProtectedRoute>
                      <UnvalidatedQuestions />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/exercises/:category"
                  element={
                    <ProtectedRoute>
                      <ExerciseSession />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/exercises/summary"
                  element={
                    <ProtectedRoute>
                      <ExerciseSummary />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/agent"
                  element={
                    <ProtectedRoute>
                      <Agent />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/profile"
                  element={
                    <ProtectedRoute>
                      <Profile />
                    </ProtectedRoute>
                  }
                />
                <Route
                  path="/master-matches"
                  element={
                    <ProtectedRoute>
                      <MasterMatches />
                    </ProtectedRoute>
                  }
                />

                {/* 404 Not Found - catch all unknown routes */}
                <Route path="*" element={<NotFound />} />
              </Routes>
            </Suspense>

            {/* Cookie Consent Banner */}
            <CookieConsent />

            {/* Resolved Error Report Notification */}
            <ResolvedReportNotification />
          </DashboardProvider>
        </AuthProvider>
      </DeviceRestriction>
    </Router>
  );
}

export default App;
