import ReactDOM from 'react-dom/client';
import { App as AntdApp, ConfigProvider } from 'antd';
import koKR from 'antd/locale/ko_KR';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import { initializeAppUpdate } from './app/main/appUpdate';
import { applyBootstrapInstallMetadataForCurrentRoute, swapInstallDocumentMetadata } from './app/main/pwa/installManifest';
import { setupMobileNavigationGestureBlocker } from './app/main/mobileNavigationGestureBlocker';
import { ensurePreviewRuntimeFreshState, installPreviewRuntimeConsoleBridge, isPreviewRuntime } from './app/main/previewRuntime';
import { installAppThemeColorSync } from './app/main/themeColorSync';
import { applyViewportCssVars } from './app/main/viewportCssVars';
import { GestureProvider, GpsLayerProvider, SearchLayerProvider } from './layer';
import { AppStoreProvider } from './store';
import './styles.css';

async function bootstrap() {
  let restoreBootstrapInstallMetadata = () => undefined;

  if (typeof window !== 'undefined') {
    const bootstrapInstallMetadata = applyBootstrapInstallMetadataForCurrentRoute();

    if (bootstrapInstallMetadata?.manifestObjectUrl) {
      restoreBootstrapInstallMetadata = swapInstallDocumentMetadata({
        manifestHref: bootstrapInstallMetadata.manifestObjectUrl,
        title: bootstrapInstallMetadata.title,
        themeColor: bootstrapInstallMetadata.themeColor,
      });
    }
    if (isPreviewRuntime()) {
      await ensurePreviewRuntimeFreshState();
      installPreviewRuntimeConsoleBridge();
    } else {
      initializeAppUpdate();
    }

    applyViewportCssVars();
    installAppThemeColorSync();
    setupMobileNavigationGestureBlocker();
  }

  ReactDOM.createRoot(document.getElementById('root')!).render(
    <ConfigProvider
      locale={koKR}
      theme={{
        token: {
          colorPrimary: '#165dff',
          borderRadius: 14,
          fontFamily:
            "'SUIT Variable', 'Pretendard Variable', Pretendard, -apple-system, BlinkMacSystemFont, sans-serif",
        },
      }}
    >
      <AntdApp>
        <BrowserRouter>
          <AppStoreProvider>
            <GpsLayerProvider>
              <SearchLayerProvider>
                <GestureProvider>
                  <App />
                </GestureProvider>
              </SearchLayerProvider>
            </GpsLayerProvider>
          </AppStoreProvider>
        </BrowserRouter>
      </AntdApp>
    </ConfigProvider>,
  );
}

void bootstrap();
