import '@fontsource-variable/inter';
import '@fontsource-variable/jetbrains-mono';
import './index.css';

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

import { AppProviders } from '@/app/providers';
import { AppRouter } from '@/app/router';
import { initTheme } from '@/features/theme/theme';
import { env } from '@/lib/env';

async function enableMocks(): Promise<void> {
  if (!env.useMocks) return;
  const { worker } = await import('@/mocks/browser');
  // Restore any persisted mock state before the app makes its first request.
  const { loadPersisted } = await import('@/mocks/persist');
  await loadPersisted();
  await worker.start({
    // Only warn about unhandled requests to our own API — ignore Vite/HMR noise.
    onUnhandledRequest(request, print) {
      if (request.url.startsWith(env.apiBaseUrl)) print.warning();
    },
  });
}

function render(): void {
  initTheme();
  const rootEl = document.getElementById('root');
  if (!rootEl) throw new Error('Root element #root not found');

  createRoot(rootEl).render(
    <StrictMode>
      <AppProviders>
        <AppRouter />
      </AppProviders>
    </StrictMode>,
  );
}

void enableMocks().then(render);
