'use client'
import { useEffect } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { useRouter } from 'next/navigation'

interface RequireAuthProps {
  children: React.ReactNode
  redirectTo?: string
}

export function RequireAuth({ children, redirectTo = '/auth' }: RequireAuthProps) {
  const { user, loading, checkAuth } = useAuth()
  const router = useRouter()

  useEffect(() => {
    // Trigger auth check when component mounts
    checkAuth()
  }, [checkAuth])

  useEffect(() => {
    // Redirect if not authenticated after loading
    if (!loading && !user) {
      // Store the current path as the return URL
      const currentPath = window.location.pathname + window.location.search
      const returnUrl = encodeURIComponent(currentPath)
      router.push(`${redirectTo}?returnUrl=${returnUrl}`)
    }
  }, [user, loading, router, redirectTo])

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    )
  }

  if (!user) {
    return null
  }

  return <>{children}</>
}
