import "@fontsource-variable/hanken-grotesk/index.css"
import "@fontsource/ibm-plex-mono/400.css"
import "@fontsource/ibm-plex-mono/500.css"
import "./index.css"
import React from "react"
import ReactDOM from "react-dom/client"
import { QueryCache, QueryClient, QueryClientProvider, MutationCache } from "@tanstack/react-query"
import { BrowserRouter } from "react-router-dom"
import { UnauthorizedError } from "@/api/client"
import { AuthProvider, notifyUnauthorized } from "@/auth/AuthContext"
import { App } from "./App"

// A 401 from *any* query or mutation means the session died server-side
// (expired/destroyed cookie) — drop it from here rather than requiring every
// hook in useApi.ts to remember to handle it individually. AuthContext reacts
// via notifyUnauthorized (registered by AuthProvider), which resets
// user/project and clears the cache; ProtectedRoute then redirects to
// /login on the next render.
function onQueryError(error: unknown) {
  if (error instanceof UnauthorizedError) notifyUnauthorized()
}

const queryClient = new QueryClient({
  queryCache: new QueryCache({ onError: onQueryError }),
  mutationCache: new MutationCache({ onError: onQueryError }),
})

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <AuthProvider>
        <BrowserRouter>
          <App />
        </BrowserRouter>
      </AuthProvider>
    </QueryClientProvider>
  </React.StrictMode>,
)
