﻿import React, { Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import { router } from './router';
import '../../css/app.css';
import { initializeTheme } from '@/hooks/use-appearance';
import { ToastProvider } from './components/ToastHost';
import { LocaleProvider } from './i18n/LocaleContext';

initializeTheme();
const rootEl = document.getElementById('root')!;

// Register a minimal service worker for background sync (best-effort)
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/guest-sw.js').catch(() => {});
  navigator.serviceWorker.addEventListener('message', (evt) => {
    if (evt.data?.type === 'sync-queue') {
      import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
    }
  });
  // Also attempt to process queue on load and when going online
  import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
  window.addEventListener('online', () => {
    import('./queue/queue').then((m) => m.processQueue().catch(() => {}));
  });
}
createRoot(rootEl).render(
  <React.StrictMode>
    <LocaleProvider>
      <ToastProvider>
        <Suspense
          fallback={(
            <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
              Erlebnisse werden geladen …
            </div>
          )}
        >
          <RouterProvider router={router} />
        </Suspense>
      </ToastProvider>
    </LocaleProvider>
  </React.StrictMode>
);
