import "normalize.css"
import "../shared/theme/tokens.generated.css"
import "./index.scss"
import "./utils/disponsiblestack"
import { StrictMode, memo } from "react"
import { ApolloProvider } from "@apollo/client"
import { createRoot } from "react-dom/client"
import { type DefaultToastOptions, Toaster } from "react-hot-toast"
import { I18nextProvider } from "react-i18next"
import { client } from "~/shared/apolloClient"
import Options from "./App"
import { PrimerCSS, color, token } from "./theme"
import { RootContextProvider } from "./store"
import SideEffect from "./SideEffect"
import { cascade } from "~/shared/cascade"
import { getI18n } from "~/shared/i18n"
import { ConfirmClose } from "./editor/useConfirmClose"

const i18n = await getI18n()

const Providers = cascade(
  <ApolloProvider client={client} />,
  <RootContextProvider />,
  <I18nextProvider i18n={i18n} />,
)

const toastOptions: DefaultToastOptions = {
  style: {
    background: color("#fff", "#303746"),
    color: token.fg.default,
  },
}

const App = memo(() => (
  <>
    <Toaster toastOptions={toastOptions} />
    <ConfirmClose />
    <PrimerCSS />
    <Providers>
      <SideEffect />
      <Options />
    </Providers>
  </>
))

const root = document.getElementById("root")!

document.querySelector("not-loaded")?.remove()
if (navigator.platform === "MacIntel") {
  document.body.classList.add("platform-mac")
}

createRoot(root).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

if (process.env.NODE_ENV === "development") {
  const source = new EventSource(`http://localhost:${process.env.SERVE_PORT}/esbuild`)
  source.addEventListener("change", () => {
    location.reload()
  })
}
