﻿import React, { Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import '../../css/app.css';
import { initializeTheme } from '@/hooks/use-appearance';
import { enableGuestDemoMode, shouldEnableGuestDemoMode } from './demo/demoMode';

initializeTheme();
if (shouldEnableGuestDemoMode()) {
  enableGuestDemoMode();
}
const rootEl = document.getElementById('root')!;
const isShareRoute = typeof window !== 'undefined' && window.location.pathname.startsWith('/share/');

const shareRoot = async () => {
  const { SharedPhotoStandalone } = await import('./pages/SharedPhotoPage');
  createRoot(rootEl).render(
    <React.StrictMode>
      <SharedPhotoStandalone />
    </React.StrictMode>
  );
};

const appRoot = async () => {
  const { RouterProvider } = await import('react-router-dom');
  const { router } = await import('./router');
  const { ToastProvider } = await import('./components/ToastHost');
  const { LocaleProvider } = await import('./i18n/LocaleContext');

  // 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>
  );
};

if (isShareRoute) {
  shareRoot().catch(() => {
    createRoot(rootEl).render(
      <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
        Dieses Foto kann gerade nicht geladen werden.
      </div>
    );
  });
} else {
  appRoot().catch(() => {
    createRoot(rootEl).render(
      <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
        Erlebnisse können nicht geladen werden.
      </div>
    );
  });
}
