import * as React from 'react';
import { createRoot } from 'react-dom/client';
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import {
  Box,
  CssBaseline,
  Toolbar
} from "@mui/material";
import Home from './Home';
import Dashboard from './Dashboard';
import { Admin, initializeApiClients } from '../react-openapi';
import { configuration, profileConfiguration } from './openapi-config';
import { Buffer } from 'buffer';
import process from 'process';
import { AuthProvider } from "../react-auth";
import Header from './Header';
import Footer from './Footer';
import AppTheme from './AppTheme';

// Polyfill Node.js globals for browser environment (needed by SwaggerParser)
window.Buffer = Buffer;
window.process = process;

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
const API_BASE = import.meta.env.VITE_API_BASE_URL;
const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;

// Initialize global API clients so all components across khata-ui have generic API access
initializeApiClients(API_BASE, AUTH_BASE);

const routerMapping = [
  { path: "/", component: Home, headerTitle: "Home" },
  { path: "/home", component: Home, headerTitle: "Home" },
  { path: "/dashboard", component: Dashboard, headerTitle: "Dashboard" },
  { path: "/admin/*", component: Admin, headerTitle: "Admin" },
];

root.render(
  <BrowserRouter>
    <AuthProvider authBaseUrl={AUTH_BASE}>
      <AppTheme>
        <CssBaseline enableColorScheme />
        <Header routerMapping={routerMapping} />

        <Box sx={{ pb: 8 }}>
          <Toolbar />

          <Routes>
            {routerMapping.map(({ path, component: Component }) => (
              <Route
                key={path}
                path={path}
                element={
                  path.startsWith("/admin") ? (
                    <Component basePath="/admin" resourceOverrides={configuration} profileConfig={profileConfiguration} />
                  ) : (
                    <Component />
                  )
                }
              />
            ))}
          </Routes>

        </Box>

        <Footer />
      </AppTheme>
    </AuthProvider>
  </BrowserRouter>
);
