﻿import React, { Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import '../../css/app.css';
import { AppearanceProvider, 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>
      <AppearanceProvider>
        <SharedPhotoStandalone />
      </AppearanceProvider>
    </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');
  const { default: MatomoTracker } = await import('@/components/analytics/MatomoTracker');
  const rawMatomo = (window as any).__MATOMO_GUEST__ as { enabled?: boolean; url?: string; siteId?: string } | undefined;
  const matomoConfig = rawMatomo
    ? {
        enabled: Boolean(rawMatomo.enabled),
        url: rawMatomo.url ?? '',
        siteId: rawMatomo.siteId ?? '',
      }
    : undefined;

  // 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>
      <AppearanceProvider>
        <LocaleProvider>
          <ToastProvider>
            <MatomoTracker config={matomoConfig} />
            <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>
      </AppearanceProvider>
    </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>
    );
  });
}
