'use client';

import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { useAuth } from "../../../context/AuthContext";

interface Props {
    children: React.ReactNode;
    roles?: string[];
}

export default function ProtectedRoute({ children, roles }: Props) {
    const { user, isAuthenticated, loading } = useAuth();
    const router = useRouter();

    useEffect(() => {
        if (loading) return;

        if (!isAuthenticated) {
            router.push("/login");
            return;
        }

        if (roles && user && !roles.includes(user.role)) {
            router.push("/");
        }

    }, [loading, isAuthenticated, user, roles, router]);

    if (loading) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <div className="h-10 w-10 border-4 border-[#2f7d5f] border-t-transparent rounded-full animate-spin" />
            </div>
        );
    }

    /*
    éviter le flash avant redirect
    */
    if (!isAuthenticated) {
        return null;
    }

    /*
    sécurité rôle
    */
    if (roles && user && !roles.includes(user.role)) {
        return null;
    }

    return <>{children}</>;
}