"use client"

import { GlobalLoginDialog } from "@/components/global-login-dialog"
import { ThemeSyncEffect } from "@/components/theme-sync"
import { TooltipProvider } from "@/components/ui/tooltip"
import { getCurrentUserForLogin } from "@/lib/api"
import { useAuthStore } from "@/store/auth"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { ThemeProvider } from "next-themes"
import { useEffect, useRef, useState } from "react"
import { Toaster } from "sonner"

function AuthBootstrap() {
  const login = useAuthStore((s) => s.login)
  const logout = useAuthStore((s) => s.logout)
  const tried = useRef(false)

  useEffect(() => {
    if (tried.current) return
    tried.current = true

    getCurrentUserForLogin()
      .then((user) => {
        login(user, user.verifiedRoles ?? ["consumer"])
      })
      .catch(() => {
        logout()
      })
  }, [login, logout])

  return null
}

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 60 * 1000,
            refetchOnWindowFocus: false,
          },
        },
      }),
  )

  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
        <TooltipProvider>
          <ThemeSyncEffect />
          <AuthBootstrap />
          {children}
          <Toaster richColors position="top-center" />
          <GlobalLoginDialog />
        </TooltipProvider>
      </ThemeProvider>
    </QueryClientProvider>
  )
}
