import { Suspense } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { BrowserRouter, useNavigate } from 'react-router-dom';
import { I18nextProvider } from 'react-i18next';
import { Toaster } from 'react-hot-toast';
import { ErrorBoundary } from './components/layout/ErrorBoundary';
import { LoadingSpinner } from './components/ui';
import { AppRouter } from './router/AppRouter';
import { ThemeProvider } from './contexts/ThemeContext';
import { AuthProvider } from './contexts/AuthContext';
import { SSEProvider } from './contexts/SSEContext';
import { SubscriptionEventsProvider } from './contexts/SubscriptionEventsContext';
import { EnterpriseProvider } from './contexts/EnterpriseContext';
import GlobalSubscriptionHandler from './components/auth/GlobalSubscriptionHandler';
import { CookieBanner } from './components/ui/CookieConsent';
import { useTenantInitializer } from './stores/useTenantInitializer';
import i18n from './i18n';

// PHASE 1 OPTIMIZATION: Optimized React Query configuration
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      gcTime: 10 * 60 * 1000, // 10 minutes
      retry: 2, // Reduced from 3 to 2 for faster failure
      refetchOnWindowFocus: true, // Changed to true for better UX
      refetchOnMount: 'stale', // Only refetch if data is stale (not always)
      structuralSharing: true, // Enable request deduplication
    },
  },
});

function AppContent() {
  const navigate = useNavigate();

  // Initialize tenant data when user is authenticated or in demo mode
  useTenantInitializer();

  return (
    <>
      <Suspense fallback={<LoadingSpinner overlay />}>
        <AppRouter />
        <GlobalSubscriptionHandler />
        <CookieBanner onPreferencesClick={() => navigate('/cookie-preferences')} />
        <Toaster
          position="top-right"
          toastOptions={{
            // Default toast options
            duration: 4000,
            style: {
              background: 'white',
              color: 'black',
              border: '1px solid #e5e7eb',
              borderRadius: '0.5rem',
              boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
              minWidth: '300px',
            },
            success: {
              style: {
                background: '#f0fdf4', // bg-green-50 equivalent
                color: '#166534',      // text-green-800 equivalent
                border: '1px solid #bbf7d0', // border-green-200 equivalent
              },
            },
            error: {
              style: {
                background: '#fef2f2', // bg-red-50 equivalent
                color: '#b91c1c',      // text-red-800 equivalent
                border: '1px solid #fecaca', // border-red-200 equivalent
              },
            },
            warning: {
              style: {
                background: '#fffbf0', // bg-yellow-50 equivalent
                color: '#92400e',      // text-yellow-800 equivalent
                border: '1px solid #fde68a', // border-yellow-200 equivalent
              },
            },
            info: {
              style: {
                background: '#eff6ff', // bg-blue-50 equivalent
                color: '#1e40af',      // text-blue-800 equivalent
                border: '1px solid #bfdbfe', // border-blue-200 equivalent
              },
            },
          }}
        />
      </Suspense>
    </>
  );
}

function App() {
  return (
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <I18nextProvider i18n={i18n}>
          <BrowserRouter
            future={{
              v7_startTransition: true,
              v7_relativeSplatPath: true,
            }}
          >
            <ThemeProvider>
              <AuthProvider>
                <SSEProvider>
                  <SubscriptionEventsProvider>
                    <EnterpriseProvider>
                      <AppContent />
                    </EnterpriseProvider>
                  </SubscriptionEventsProvider>
                </SSEProvider>
              </AuthProvider>
            </ThemeProvider>
          </BrowserRouter>
          <ReactQueryDevtools initialIsOpen={false} />
        </I18nextProvider>
      </QueryClientProvider>
    </ErrorBoundary>
  );
}

export default App;
