import "./index.scss"
import "reflect-metadata"
import { createRoot } from "react-dom/client"
import browser from "webextension-polyfill"
import { StrictMode, createContext, useContext } from "react"
import { ApolloProvider } from "@apollo/client"
import { I18nextProvider } from "react-i18next"
import { client } from "~/shared/apolloClient"
import { PopupApp } from "./App"
import { getI18n } from "~/shared/i18n"
import { cascade } from "~/shared/cascade"

document.body.dataset.platform = navigator.platform.split(" ")[0].toLowerCase()

const PopupContext = createContext<{ url: string; tabId: number }>(undefined!)
export const usePopupContext = () => useContext(PopupContext)

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

void browser.tabs
  .query({ currentWindow: true, active: true })
  .then(([tab]) => ({ url: tab.url || "", tabId: tab.id ?? -1 }))
  .catch(() => ({ tabId: -1, url: "" }))
  .then(async tab => {
    const i18n = await getI18n()

    const Providers = cascade(
      <StrictMode />,
      <ApolloProvider client={client} />,
      <I18nextProvider i18n={i18n} />,
      <PopupContext.Provider value={tab} />,
    )

    createRoot(container).render(
      <Providers>
        <PopupApp container={container} />
      </Providers>,
    )
  })
