import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./App";
import { ServerApi } from "./api/ServerApi";
import "./index.css";

// Roboto font
import "@fontsource/roboto/300.css";
import "@fontsource/roboto/400.css";
import "@fontsource/roboto/500.css";
import "@fontsource/roboto/700.css";
import { AlertDialogProvider } from "./hooks/context_providers/AlertDialogProvider";
import { ConfirmDialogProvider } from "./hooks/context_providers/ConfirmDialogProvider";
import { DarkThemeProvider } from "./hooks/context_providers/DarkThemeProvider";
import { SnackbarProvider } from "./hooks/context_providers/SnackbarProvider";
import { AsyncWidget } from "./widgets/AsyncWidget";
import { LoadingMessageProvider } from "./hooks/context_providers/LoadingMessageProvider";
import { APIClient } from "./api/ApiClient";

async function init() {
  try {
    if (
      APIClient.IsBackendSecure() &&
      !window.location.href.startsWith("https") &&
      window.location.hostname !== "localhost"
    ) {
      window.location.href = window.location.href.replace("http:", "https:");
    }

    const root = ReactDOM.createRoot(
      document.getElementById("root") as HTMLElement
    );

    root.render(
      <React.StrictMode>
        <DarkThemeProvider>
          <AlertDialogProvider>
            <ConfirmDialogProvider>
              <SnackbarProvider>
                <LoadingMessageProvider>
                  <div style={{ height: "100vh" }}>
                    <AsyncWidget
                      loadKey={1}
                      load={async () => await ServerApi.LoadConfig()}
                      errMsg="Echec de la connexion au serveur pour la récupération de la configuration statique !"
                      build={() => <App />}
                    />
                  </div>
                </LoadingMessageProvider>
              </SnackbarProvider>
            </ConfirmDialogProvider>
          </AlertDialogProvider>
        </DarkThemeProvider>
      </React.StrictMode>
    );
  } catch (e) {
    console.error(e);
    alert("Echec de l'initialisation de l'application !");
  }
}

init();
