import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ToastContainer } from './components/ui/Toast';
import { Modal } from './components/ui/Modal';
import { ProtectedRoute } from './components/layout/ProtectedRoute';
import { FullPageSpinner } from './components/ui/Spinner';

const EventEntry    = lazy(() => import('./pages/EventEntry').then(m => ({ default: m.EventEntry })));
const LoadingRestore = lazy(() => import('./pages/LoadingRestore').then(m => ({ default: m.LoadingRestore })));
const Dashboard     = lazy(() => import('./pages/Dashboard').then(m => ({ default: m.Dashboard })));
const Scanner       = lazy(() => import('./pages/Scanner').then(m => ({ default: m.Scanner })));
const Search        = lazy(() => import('./pages/Search').then(m => ({ default: m.Search })));
const GuestDetail   = lazy(() => import('./pages/GuestDetail').then(m => ({ default: m.GuestDetail })));
const GuestsList    = lazy(() => import('./pages/GuestsList').then(m => ({ default: m.GuestsList })));

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 15_000,
      retry: 2,
      refetchOnWindowFocus: false,
    },
  },
});

export function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
        <Suspense fallback={<FullPageSpinner />}>
          <Routes>
            {/* Public — event code entry */}
            <Route path="/checkin-app" element={<EventEntry />} />

            {/* Session restore after page refresh */}
            <Route path="/checkin-app/loading" element={<LoadingRestore />} />

            {/* Protected app routes */}
            <Route path="/checkin-app/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
            <Route path="/checkin-app/scan"      element={<ProtectedRoute><Scanner /></ProtectedRoute>} />
            <Route path="/checkin-app/search"    element={<ProtectedRoute><Search /></ProtectedRoute>} />
            <Route path="/checkin-app/guest/:id" element={<ProtectedRoute><GuestDetail /></ProtectedRoute>} />
            <Route path="/checkin-app/guests"    element={<ProtectedRoute><GuestsList /></ProtectedRoute>} />

            {/* Fallback */}
            <Route path="*" element={<Navigate to="/checkin-app" replace />} />
          </Routes>
        </Suspense>

        <ToastContainer />
        <Modal />
      </BrowserRouter>
    </QueryClientProvider>
  );
}
