import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AuthProvider } from './hooks/useAuth';
import { BrandingProvider } from './hooks/useBranding';
import { ThemedRoot } from './components/ThemedRoot';
import { RequireAuth } from './components/RequireAuth';
import { RequireRole } from './components/RequireRole';
import { AppLayout } from './components/layout/AppLayout';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { DashboardsPage } from './pages/DashboardsPage';
import { AdminSitesPage } from './pages/AdminSitesPage';
import { SettingsPage } from './pages/SettingsPage';

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

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <BrandingProvider>
        <ThemedRoot>
          <AuthProvider>
            <BrowserRouter>
              <Routes>
                <Route path="/login" element={<LoginPage />} />
                <Route
                  path="/"
                  element={
                    <RequireAuth>
                      <AppLayout />
                    </RequireAuth>
                  }
                >
                  <Route index element={<DashboardPage />} />
                  <Route path="dashboards" element={<DashboardsPage />} />
                  <Route
                    path="admin/sites"
                    element={
                      <RequireRole role="Admin">
                        <AdminSitesPage />
                      </RequireRole>
                    }
                  />
                  <Route
                    path="settings"
                    element={
                      <RequireRole role="Admin">
                        <SettingsPage />
                      </RequireRole>
                    }
                  />
                  <Route path="admin/users" element={<Navigate to="/settings" replace />} />
                </Route>
                <Route path="*" element={<Navigate to="/" replace />} />
              </Routes>
            </BrowserRouter>
          </AuthProvider>
        </ThemedRoot>
      </BrandingProvider>
    </QueryClientProvider>
  );
}
