"use client";

import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useSelector, useDispatch } from "react-redux";
import { selectCurrentUser, selectIsAuthenticated, logout } from "@/redux/slices/authSlice";

export default function AuthGuard({ children }: { children: React.ReactNode }) {
    const pathname = usePathname();
    const router = useRouter();
    const dispatch = useDispatch();
    const user = useSelector(selectCurrentUser);
    const isAuthenticated = useSelector(selectIsAuthenticated);

    // Identify public paths
    const isLoginPage = pathname === "/login" || pathname === "/login/";
    const isPublic = isLoginPage || pathname?.startsWith("/_next") || pathname?.startsWith("/api");

    useEffect(() => {
        // Skip checks for public paths
        if (isPublic) return;

        // Check if user is authenticated
        if (!isAuthenticated || !user) {
            // Not logged in or no user data
            dispatch(logout());
            router.replace("/login");
            return;
        }

        // Check if user has admin role
        if (user.role !== "admin") {
            // User is logged in but not an admin
            dispatch(logout());
            router.replace("/login");
            return;
        }
    }, [pathname, isAuthenticated, user, router, dispatch, isPublic]);

    // If it's a public path, render immediately
    if (isPublic) {
        return <>{children}</>;
    }

    // If fully authenticated and authorized (admin), render children
    if (isAuthenticated && user?.role === "admin") {
        return <>{children}</>;
    }

    // Otherwise show loader while checking/redirecting
    return (
        <div className="min-h-screen flex items-center justify-center bg-[#0a0a0a]">
            <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
        </div>
    );
}
