import React, { Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import '../../css/app.css';
import { enableGuestDemoMode, shouldEnableGuestDemoMode } from './demo/demoMode';
import { Sentry, initSentry } from '@/lib/sentry';

const GuestFallback: React.FC<{ message: string }> = ({ message }) => (
  <div className="flex min-h-screen items-center justify-center text-sm text-muted-foreground">
    {message}
  </div>
);

initSentry('guest');
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(
    <Sentry.ErrorBoundary fallback={<GuestFallback message="Dieses Foto kann gerade nicht geladen werden." />}>
      <React.StrictMode>
        <SharedPhotoStandalone />
      </React.StrictMode>
    </Sentry.ErrorBoundary>
  );
};

const appRoot = async () => {
  const { RouterProvider } = await import('react-router-dom');
  const { router } = await import('./router');
  const { ToastProvider } = await import('./components/ToastHost');
  const { default: PwaManager } = await import('./components/PwaManager');
  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;

  createRoot(rootEl).render(
    <Sentry.ErrorBoundary fallback={<GuestFallback message="Erlebnisse können nicht geladen werden." />}>
      <React.StrictMode>
        <LocaleProvider>
          <ToastProvider>
            <MatomoTracker config={matomoConfig} />
            <PwaManager />
            <Suspense fallback={<GuestFallback message="Erlebnisse werden geladen …" />}>
              <RouterProvider router={router} />
            </Suspense>
          </ToastProvider>
        </LocaleProvider>
      </React.StrictMode>
    </Sentry.ErrorBoundary>
  );
};

if (isShareRoute) {
  shareRoot().catch(() => {
    createRoot(rootEl).render(<GuestFallback message="Dieses Foto kann gerade nicht geladen werden." />);
  });
} else {
  appRoot().catch(() => {
    createRoot(rootEl).render(<GuestFallback message="Erlebnisse können nicht geladen werden." />);
  });
}
