import React, { Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { AuthProvider } from './auth/context';
import { router } from './router';
import '../../css/app.css';
import './i18n';
import './dev-tools';
import { initializeTheme } from '@/hooks/use-appearance';
import { OnboardingProgressProvider } from './onboarding';
import { EventProvider } from './context/EventContext';

const DevTenantSwitcher = React.lazy(() => import('./components/DevTenantSwitcher'));

const enableDevSwitcher = import.meta.env.DEV || import.meta.env.VITE_ENABLE_TENANT_SWITCHER === 'true';

initializeTheme();
const rootEl = document.getElementById('root')!;
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60, // 1 minute
      cacheTime: 1000 * 60 * 5,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
      retry: 1,
    },
    mutations: {
      retry: 1,
    },
  },
});

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/admin-sw.js').catch(() => {});
  });
}

createRoot(rootEl).render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <AuthProvider>
        <EventProvider>
          <OnboardingProgressProvider>
            <Suspense
              fallback={(
                <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
                  Oberfläche wird geladen …
                </div>
              )}
            >
              <RouterProvider router={router} />
            </Suspense>
          </OnboardingProgressProvider>
        </EventProvider>
      </AuthProvider>
      {enableDevSwitcher ? (
        <Suspense fallback={null}>
          <DevTenantSwitcher />
        </Suspense>
      ) : null}
    </QueryClientProvider>
  </React.StrictMode>
);
