import "core-js/stable";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";

import "@dndbeyond/ttui/styles/palette.css";
import "@dndbeyond/ttui/styles/typography.css";
import wayOfLight from "@dndbeyond/ttui/themes/wayOfLight";

import { Layout } from "./components/Layout";
import config from "./config";
import { AuthProvider, useAuth } from "./contexts/Authentication";
import { FeatureFlagProvider, useFeatureFlags } from "./contexts/FeatureFlag";
import { FiltersProvider } from "./contexts/Filters";
import { HeadContextProvider } from "./contexts/Head";
import { ThemeManagerProvider } from "./contexts/ThemeManager";
import { reportWebVitals } from "./helpers/reportWebVitals";
import { useDatadogRum } from "./hooks/useDatadogRum";
import { Routes } from "./routes";
import "./styles/global.css";
import "./styles/index.scss";
import "./styles/reset.css";
import "./styles/variables.css";
import "./styles/waterdeep-stat-blocks.css";

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 60 * 60 * 1000 } },
});

const DatadogGate = () => {
  const { datadogRumCharactersAppFlag } = useFeatureFlags();
  return datadogRumCharactersAppFlag ? <DatadogBootstrap /> : null;
};

const DatadogBootstrap = () => {
  const user = useAuth();
  useDatadogRum(user ?? null);

  return null;
};

const environment = config.environment;

const App = () => (
  <>
    <style>{wayOfLight}</style>
    <BrowserRouter>
      <QueryClientProvider client={queryClient}>
        <ThemeManagerProvider manager={{ lightOrDark: "light" }}>
          <HeadContextProvider>
            <AuthProvider>
              <FeatureFlagProvider>
                {environment !== "development" && <DatadogGate />}
                <FiltersProvider>
                  <Layout>
                    <Routes />
                  </Layout>
                </FiltersProvider>
              </FeatureFlagProvider>
            </AuthProvider>
          </HeadContextProvider>
        </ThemeManagerProvider>
      </QueryClientProvider>
    </BrowserRouter>
  </>
);

const root = createRoot(document.getElementById("character-tools-target")!);

root.render(<App />);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
