import React, { Suspense } from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { XerticaProvider } from 'xertica-ui/brand';
import { AuthProvider } from './context/AuthContext';
import { AuthGuard } from './components/AuthGuard';
import { AppErrorBoundary, PageErrorBoundary } from '../shared/error-boundary';

// ─── Query client ─────────────────────────────────────────────────────────────
// Shared instance — configure defaults here.
// To add React Query Devtools: npm i @tanstack/react-query-devtools and wrap below.

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

// ─── App ─────────────────────────────────────────────────────────────────────

export default function App() {
  const geminiApiKey = import.meta.env.VITE_GEMINI_API_KEY;
  const googleMapsApiKey = import.meta.env.VITE_GOOGLE_MAPS_API_KEY;

  return (
    <AppErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <XerticaProvider apiKey={geminiApiKey} googleMapsApiKey={googleMapsApiKey}>
          <Router>
            {/* AuthProvider must be inside Router (needs useNavigate) */}
            <AuthProvider>
              <PageErrorBoundary>
                <Suspense fallback={null}>
                  <AuthGuard />
                </Suspense>
              </PageErrorBoundary>
            </AuthProvider>
          </Router>
        </XerticaProvider>
      </QueryClientProvider>
    </AppErrorBoundary>
  );
}
