/**
 * @file main.tsx - Application entry point for the Rapid Workplace (RWP) web application.
 * Initializes the React root, sets up routing, and loads and freezes the runtime configuration to prevent tampering.
 */

import { createRoot } from 'react-dom/client';
import {
  createBrowserRouter,
  Navigate,
  RouterProvider,
} from 'react-router-dom';
import { AuthProvider } from './contexts/AuthContext.tsx';
import App from './App.tsx';
import { routes } from './AppRoutes.tsx';
import './i18next/config.ts';

// Create a browser router with AuthProvider wrapping the App shell component
const router = createBrowserRouter([
  {
    element: (
      <AuthProvider>
        <App />
      </AuthProvider>
    ),
    errorElement: <Navigate to={'/application-error'} replace />,
    children: routes,
  },
]);

// Freeze the runtime configuration object (window.__APP_CONFIG__) to prevent tampering
// The config is originally injected by public/config.js at load time
const desc = Object.getOwnPropertyDescriptor(window, '__APP_CONFIG__');
if (!desc || desc.writable) {
  if (!window.__APP_CONFIG__) {
    throw new Error('Runtime configuration missing');
  }

  const appConfig = { ...window.__APP_CONFIG__ };
  delete (window as any).__APP_CONFIG__;

  Object.defineProperty(window, '__APP_CONFIG__', {
    value: Object.freeze(appConfig),
    writable: false,
    configurable: false,
    enumerable: false,
  });
}

createRoot(document.getElementById('root')!).render(
  <RouterProvider router={router} />
);
