import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

const withAuth = (WrappedComponent: React.FC) => {
    return (props: any) => {
        const [isAuthenticated, setIsAuthenticated] = useState(false)
        const router = useRouter()

        useEffect(() => {
            const token = localStorage.getItem("token")

            if (!token) {
                router.replace("/login") // Redirect to login if no token
            } else {
                setIsAuthenticated(true)
            }
        }, [])

        if (!isAuthenticated) {
            return null // Avoid rendering until auth check is done
        }

        return <WrappedComponent {...props} />
    };
};

export default withAuth
