"use client"

import { useEffect } from "react"
import { usePathname, useRouter, useSearchParams } from "next/navigation"

import { useAuth } from "@/lib/auth-client"

export function AuthGuard() {
  const { session, isLoading } = useAuth()
  const router = useRouter()
  const pathname = usePathname()
  const searchParams = useSearchParams()

  useEffect(() => {
    if (isLoading) return
    if (session?.user) return

    const search = searchParams?.toString()
    const callbackUrl = pathname
      ? search && search.length > 0
        ? `${pathname}?${search}`
        : pathname
      : undefined
    const nextUrl = callbackUrl ? `/login?callbackUrl=${encodeURIComponent(callbackUrl)}` : "/login"
    router.replace(nextUrl)
  }, [isLoading, session?.user, pathname, searchParams, router])

  return null
}
