// components/RequireAuth.js
'use client';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/stores/authStore';
import { useEffect } from 'react';

export default function RequireAuth({ children, requiredRole }) {
    const router = useRouter();
    const { user, isAuthenticated } = useAuthStore();

    useEffect(() => {
        if (!isAuthenticated) {
            router.push('/login');
        } else if (requiredRole && user?.role !== requiredRole) {
            router.push('/unauthorized');
        }
    }, [isAuthenticated, user, router, requiredRole]);

    if (!isAuthenticated || (requiredRole && user?.role !== requiredRole)) {
        return <div>Loading...</div>;
    }

    return children;
}