import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MantineProvider } from "@mantine/core";
import "@mantine/core/styles.css";
import "@edr/ui-common/styles.css";
import "../index.css";
import "@edr/ui-common/theme.css";
import { mantineTheme } from "./theme/mantine";

import App from "./App";

// Purge cookies that were stored as the literal string "undefined" before the
// envelope interceptor fix. Without this, stale sessions would keep sending
// "Authorization: Bearer undefined" and get 401 JsonWebTokenError forever.
["auth-token", "refresh-token"].forEach((name) => {
  const entry = document.cookie
    .split("; ")
    .find((c) => c.startsWith(`${name}=`));
  const value = entry?.split("=").slice(1).join("=");
  if (value === "undefined" || value === "null" || value === "") {
    document.cookie = `${name}=; Max-Age=0; path=/`;
  }
});

const queryClient = new QueryClient();

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

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

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <MantineProvider theme={mantineTheme} defaultColorScheme="light">
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </QueryClientProvider>
    </MantineProvider>
  </StrictMode>,
);
