import { render } from "solid-js/web"
import { Show, onMount } from "solid-js"
import App from "./App"
import { ThemeProvider } from "./lib/theme"
import { ConfigProvider } from "./stores/preferences"
import { InstanceConfigProvider } from "./stores/instance-config"
import { runtimeEnv } from "./lib/runtime-env"
import LoginView from "./components/auth/LoginView"
import { isLoggedIn, initializeUserContext, patchFetch, isInitialized } from "./lib/user-context"
import { Toaster } from "solid-toast"
import "./index.css"
import "@git-diff-view/solid/styles/diff-view-pure.css"

const root = document.getElementById("root")

if (!root) {
  throw new Error("Root element not found")
}

if (typeof document !== "undefined") {
  document.documentElement.dataset.runtimeHost = runtimeEnv.host
  document.documentElement.dataset.runtimePlatform = runtimeEnv.platform
}

const Root = () => {
  onMount(() => {
    patchFetch()
    initializeUserContext()
  })

  return (
    <>
      <Toaster
        position="top-right"
        gutter={8}
        toastOptions={{
          style: {
            background: "#1a1a1a",
            color: "#fff",
            border: "1px solid rgba(255,255,255,0.1)",
          },
        }}
      />
      <Show when={isInitialized()}>
        <Show
          when={isLoggedIn()}
          fallback={<LoginView onLoginSuccess={() => initializeUserContext()} />}
        >
          <ConfigProvider>
            <InstanceConfigProvider>
              <ThemeProvider>
                <App />
              </ThemeProvider>
            </InstanceConfigProvider>
          </ConfigProvider>
        </Show>
      </Show>
    </>
  )
}

render(() => <Root />, root)
