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

import { App } from '@/app/App';
import { preloadRoute } from '@/app/routes/route-loaders';
import { Toaster } from '@/components/ui/sonner';
import { registerChunkReload } from '@/lib/chunk-reload';
import { KeycloakProvider } from '@/providers/KeycloakProvider';
import { store } from '@/store';
import '@/i18n';
import '@/styles/globals.css';

/**
 * Reload once when a chunk from an earlier deploy is gone (DP2-750). FIRST, before `preloadRoute`,
 * so the start-up preload's own failure is covered too; see `lib/chunk-reload.ts`.
 */
registerChunkReload();

/**
 * Start the current page's chunk downloading before anything else happens (DP2-554).
 *
 * BEFORE `createRoot`, DELIBERATELY, and this is the earliest useful point. Pages are React.lazy
 * and PermissionRoute renders a fallback until /users/me resolves, so the chunk request could not
 * be issued until the profile call had finished: two unrelated things ran nose to tail, the second
 * being a request for a file whose URL was known before the app started. Moving it here overlaps
 * the download with Keycloak's check-sso and with /me.
 *
 * It changes nothing about what renders or when. React still suspends on the same lazy component;
 * the bytes are simply already arriving when it asks.
 */
preloadRoute(window.location.pathname);

const rootElement = document.getElementById('root');

if (!rootElement) {
  throw new Error('Root element not found');
}

createRoot(rootElement).render(
  <StrictMode>
    <Provider store={store}>
      <KeycloakProvider>
        <App />
      </KeycloakProvider>
      <Toaster />
    </Provider>
  </StrictMode>,
);
