import React from "react";
import axios from "axios";
import { Chart } from "chart.js";
import ReactDOM from "react-dom/client";
import reportWebVitals from "./reportWebVitals";
import { initSentry } from "./sentry";
import { initDevTools } from "./devutils";
import { App } from "./App";
import { setCustomHeaders } from "@/services/auth/setCustomHeaders";
import { removeStaleStorage } from "@/utils/Store/removeStaleStorage";
import { isMockEnable } from "@/services/env/envVariables";
import { suppressUnhandledApiErrors } from "@/utils/api/suppressUnhandledApiErrors";
import { registerStaleChunkRecovery } from "@/utils/Browser/staleChunkRecovery";
import { enableMapSet } from "immer";
import { Spinner } from "@heroui/react";
import { API_TIMEOUTS } from "@/constants/timers";

import "@/style/legacy/index.scss";
import "@/style/tailwind/index.css";

Chart.defaults.font = {
  size: 12,
  family: "Sora",
};

// set withCredential to true in axios defaults
// to enable the usage of cloudflare against demo
axios.defaults.withCredentials = true;
axios.defaults.timeout = API_TIMEOUTS.DEFAULT;

// Early, so no rejection fires before the listener is attached.
suppressUnhandledApiErrors();
// Early too: a chunk from a previous deploy can fail on the very first import.
registerStaleChunkRecovery();
initSentry();
initDevTools();
// https://immerjs.github.io/immer/map-set/
enableMapSet();

// set custom headers from local storage
setCustomHeaders();
removeStaleStorage();
async function enableMocking() {
  if (import.meta.env.VITE_INCLUDE_MSW !== "1") {
    return;
  }

  const { worker, startMockRecovery, MOCK_SERVICE_WORKER_OPTIONS } =
    await import("@/mock/Browser");
  await worker.start(MOCK_SERVICE_WORKER_OPTIONS);

  const stopMockRecovery = startMockRecovery();
  window.addEventListener("pagehide", stopMockRecovery, { once: true });
}

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

if (isMockEnable()) {
  root.render(
    <React.StrictMode
      children={
        <div className="dark bg-background size-full p-4 fixed flex flex-col items-end justify-end">
          <div className="flex flex-center gap-4 text-foreground">
            <Spinner size="sm" />
            <h6 className="m-0">LOADING MOCKS</h6>
          </div>
        </div>
      }
    />
  );
  enableMocking().then(() => {
    // render with strict mode
    root.render(<React.StrictMode children={<App />} />);
  });
} else {
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
}

// 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();
