import React, { Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import { Toaster } from 'react-hot-toast';
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';
import MatomoTracker from '@/components/analytics/MatomoTracker';
import { ConsentProvider } from '@/contexts/consent';
import CookieBanner from '@/components/consent/CookieBanner';

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
      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>
    <ConsentProvider>
      <QueryClientProvider client={queryClient}>
        <AuthProvider>
          <EventProvider>
            <OnboardingProgressProvider>
              <MatomoTracker config={(window as any).__MATOMO_ADMIN__} />
              <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>
        <CookieBanner />
        <Toaster position="top-right" toastOptions={{ duration: 4000 }} />
        {enableDevSwitcher ? (
          <Suspense fallback={null}>
            <DevTenantSwitcher />
          </Suspense>
        ) : null}
      </QueryClientProvider>
    </ConsentProvider>
  </React.StrictMode>
);
