'use client'

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

interface ProtectedRouteProps {
  children: React.ReactNode
  fallback?: React.ReactNode
}

/**
 * ProtectedRoute component that restricts access to authenticated users only.
 * Redirects unauthenticated users to the login page.
 */
export default function ProtectedRoute({
  children,
  fallback,
}: ProtectedRouteProps) {
  const { user, loading } = useAuth()
  const router = useRouter()
  const pathname = usePathname()

  useEffect(() => {
    if (!loading && !user) {
      router.replace(`/login?redirect=${encodeURIComponent(pathname)}`)
    }

    // Reset scroll position on route change
    window.scrollTo(0, 0)
  }, [user, loading, router, pathname])

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

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

  return <>{children}</>
}
