import { CacheProvider } from "@emotion/react";
import { ClientStyleContext } from "./context.js";
import createEmotionCache from "./createEmotionCache.js";
import { hydrateRoot } from "react-dom/client";
import { RemixBrowser, useLocation, useMatches } from "@remix-run/react";
import * as Sentry from "@sentry/remix";
import { type ReactNode, StrictMode, useEffect, useState } from "react";

Sentry.init({
  dsn:
    document.querySelector("meta[name='dsn']")?.getAttribute("content") ??
    undefined,
  integrations: [
    Sentry.browserTracingIntegration({
      useEffect,
      useLocation,
      useMatches,
    }),
    Sentry.replayIntegration({
      blockAllMedia: false,
      maskAllInputs: false,
      maskAllText: false,
    }),
  ],
  replaysOnErrorSampleRate: 1,
  replaysSessionSampleRate: 0.02,
  release:
    document
      .querySelector("meta[name='commit_sha']")
      ?.getAttribute("content") ?? undefined,
  sendDefaultPii: true,
  tracesSampleRate: 0.1,
  tunnel: "/api/st",
});

function ClientCacheProvider({ children }: { children: ReactNode }) {
  const [cache, setCache] = useState(createEmotionCache());

  function reset() {
    setCache(createEmotionCache());
  }

  return (
    <ClientStyleContext.Provider value={{ reset }}>
      <CacheProvider value={cache}>{children}</CacheProvider>
    </ClientStyleContext.Provider>
  );
}

hydrateRoot(
  document,
  <StrictMode>
    <ClientCacheProvider>
      <RemixBrowser />
    </ClientCacheProvider>
  </StrictMode>,
);
