import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { MantineProvider } from "@mantine/core";
import posthog from "posthog-js";
import { PostHogProvider } from "@posthog/react";
import "@mantine/core/styles.css";
import "@mantine/dates/styles.css";
import "@edr/ui-common/styles.css";
import "../index.css";
import "@edr/ui-common/theme.css";

import { Toaster } from "react-hot-toast";
import { Toaster as SonnerToaster } from "./shared/common/ui/sonner";

// Initialize i18next before first paint so the detected/persisted language
// applies immediately (the vendored IAM UI also imports this via @/i18n).
import "./i18n";

import App from "./App";
import { ApiErrorModal } from "./components/errors/ApiErrorModal";
import { ErrorBoundary } from "./components/ErrorBoundary";
import { AuthProvider } from "./auth/AuthProvider";
import { queryClient } from "./lib/queryClient";
import { initPostHog } from "./lib/posthog";
import { freightMantineTheme } from "./theme/freight-brand";
import { QueryClientProvider } from "@tanstack/react-query";

const THEME_STORAGE_KEY = "edr-theme";

const applyStoredTheme = () => {
  const storedTheme = window.localStorage.getItem(THEME_STORAGE_KEY);
  const prefersDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches;
  const theme = storedTheme === "dark" || storedTheme === "light"
    ? storedTheme
    : prefersDark
      ? "dark"
      : "light";

  if (theme === "dark") {
    document.documentElement.classList.add("dark");
    return;
  }

  document.documentElement.classList.remove("dark");
};

applyStoredTheme();

// Must run before render so replay and exception capture cover startup errors.
// No-ops when VITE_POSTHOG_KEY is unset.
initPostHog();

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

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

createRoot(rootElement).render(
  <PostHogProvider client={posthog}>
    <QueryClientProvider client={queryClient}>
      <MantineProvider theme={freightMantineTheme}>
        <StrictMode>
          <BrowserRouter>
            <AuthProvider>
              <ErrorBoundary>
                <App />
              </ErrorBoundary>
              {/* Global API error modal — shows the server's actual error
                  message (suppressed on warehouse / mile / onboarding pages). */}
              <ApiErrorModal />
              <Toaster position="top-right" />
              {/* sonner toasts (used across super-admin & user-management)
                  rendered nowhere without this mount */}
              <SonnerToaster position="top-right" richColors />
            </AuthProvider>
          </BrowserRouter>
        </StrictMode>
      </MantineProvider>
    </QueryClientProvider>
  </PostHogProvider>
);

// run