/* eslint-disable react-refresh/only-export-components */

import './index.css';

import {StrictMode, Suspense} from 'react';
import {createRoot} from 'react-dom/client';

import {stabilizeMobileViewportKeyboardFocus} from './mobileViewportKeyboardFocus';
import {lockMobileViewportZoom} from './mobileViewportZoomLock';
import {resolveAppRoute} from './routing/appRoutes';
import {RouteImageReadyGate} from './routing/RouteImageReadyGate';
import {RouteLoadingScreen} from './routing/RouteLoadingScreen';
import {isWechatMiniProgramWebViewRuntime} from './services/authService';

type AppRoot = ReturnType<typeof createRoot>;

declare global {
  interface Window {
    __tavernRealmsRoot__?: AppRoot;
  }
}

const route = resolveAppRoute(window.location.pathname);
const rootElement = document.getElementById('root');

if (!rootElement) {
  throw new Error('Missing #root container');
}

function markWechatMiniProgramRuntime() {
  if (isWechatMiniProgramWebViewRuntime()) {
    document.documentElement.dataset.wechatMiniProgramRuntime = 'true';
  }
}

const root = window.__tavernRealmsRoot__ ??= createRoot(rootElement);
const RouteComponent = route.Component;

lockMobileViewportZoom();
stabilizeMobileViewportKeyboardFocus();
markWechatMiniProgramRuntime();

root.render(
  <StrictMode>
    <Suspense fallback={<RouteLoadingScreen eyebrow={route.loadingEyebrow} text={route.loadingText} />}>
      <RouteImageReadyGate
        eyebrow={route.loadingEyebrow}
        text={route.loadingText}
      >
        <RouteComponent {...(route.componentProps ?? {})} />
      </RouteImageReadyGate>
    </Suspense>
  </StrictMode>,
);
