'use client'

import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useAuth } from '@/lib/context/AuthContext'
import FullPageLoader from './FullPageLoader'

interface GuestRouteProps {
  children: React.ReactNode
  fallback?: React.ReactNode
  redirectTo?: string
}

/**
 * GuestRoute component that restricts access to unauthenticated users only.
 * Redirects authenticated users to the dashboard or specified route.
 */
export default function GuestRoute({
  children,
  fallback,
  redirectTo = '/',
}: GuestRouteProps) {
  const { user, loading } = useAuth()
  const router = useRouter()

  useEffect(() => {
    if (!loading && user) {
      router.replace(redirectTo)
    }
  }, [user, loading, router, redirectTo])

  // Show loading state while checking authentication
  if (loading) {
    return fallback ?? <FullPageLoader message="Checking authentication..." />
  }

  // Don't render guest content if user is authenticated
  if (user) {
    return null
  }

  return <>{children}</>
}
