import { useAuth } from '@/context/AuthContext'
import { type FC, type ReactNode, useEffect } from 'react'

type PrivateRouteProps = {
    children: ReactNode
    /** When true (default), user must be logged in to access the route */
    requireAuth?: boolean
}

const PrivateRoute: FC<PrivateRouteProps> = ({
    children,
    requireAuth = true,
}) => {
    const { isAuthenticated, isChecking } = useAuth()

    useEffect(() => {
        if (requireAuth && !isChecking && !isAuthenticated) {
            window.location.href = import.meta.env.VITE_LOGIN_URL
        }
    }, [requireAuth, isChecking, isAuthenticated])

    if (!requireAuth) {
        return children
    }

    if (isChecking || !isAuthenticated) {
        return (
            <div className="flex flex-1 items-center justify-center">
                <div className="text-gray-600">در حال بارگذاری...</div>
            </div>
        )
    }

    return children
}

export default PrivateRoute
