import { CacheProvider } from "@emotion/react";
import CssBaseline from "@mui/material/CssBaseline";
import { ThemeProvider } from "@mui/material/styles";
import React, { useMemo } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { ToastProvider } from "@/shared/ui/ToastProvider.jsx";
import { ExternalAdminApp } from "./ExternalAdminApp.jsx";
import { createExternalTheme } from "./theme.js";
import { ExternalAuthProvider } from "./auth/ExternalAuthProvider.jsx";
import { ExternalI18nProvider, useExternalI18n } from "./i18n/ExternalI18nProvider.jsx";
import { externalEmotionCache } from "./i18n/emotionCache.js";
import "@/styles/tokens.css";
import "@/styles/shared-ui.css";
import "./styles/index.css";

createRoot(document.getElementById("external-admin-root")).render(
  <React.StrictMode>
    <ExternalI18nProvider>
      <ExternalThemeRoot />
    </ExternalI18nProvider>
  </React.StrictMode>
);

function ExternalThemeRoot() {
  const { direction } = useExternalI18n();
  // A direction-aware MUI theme keeps inputs, menus and dialog controls consistent with the Arabic document direction.
  const externalTheme = useMemo(() => createExternalTheme(direction), [direction]);

  return (
    <CacheProvider value={externalEmotionCache(direction)}>
      <ThemeProvider theme={externalTheme}>
        <ToastProvider>
          <CssBaseline />
          <BrowserRouter basename="/external-admin">
            <ExternalAuthProvider>
              <ExternalAdminApp />
            </ExternalAuthProvider>
          </BrowserRouter>
        </ToastProvider>
      </ThemeProvider>
    </CacheProvider>
  );
}
