"use client"; import { useState, useEffect } from "react"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; export default function AdminLeaderboardPage() { const { data: session, status } = useSession(); const [teams, setTeams] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const router = useRouter(); // Check if user is admin useEffect(() => { if (status === "authenticated") { if (session?.user?.role !== "admin") { router.push("/team-selection"); } else { fetchLeaderboardData(); } } else if (status === "unauthenticated") { router.push("/login"); } }, [session, status, router]); // Fetch leaderboard data const fetchLeaderboardData = async () => { try { setLoading(true); setError(""); const response = await fetch("/api/admin/leaderboard", { method: "GET", headers: { "Content-Type": "application/json", "Cache-Control": "no-cache, no-store, must-revalidate", }, credentials: "include", }); if (!response.ok) { throw new Error("Failed to fetch leaderboard data"); } const data = await response.json(); setTeams(data); } catch (err) { console.error("Error fetching leaderboard data:", err); setError(err.message); } finally { setLoading(false); } }; // Handle resetting a team's progress const handleResetTeamProgress = async (teamId, teamName) => { if ( !confirm( `Are you sure you want to reset progress for team "${teamName}"?` ) ) { return; } try { setLoading(true); const response = await fetch( `/api/admin/teams/${teamId}/reset-progress`, { method: "POST", headers: { "Content-Type": "application/json", }, credentials: "include", } ); if (!response.ok) { throw new Error("Failed to reset team progress"); } // Refresh the data after successful reset fetchLeaderboardData(); } catch (err) { console.error("Error resetting team progress:", err); setError(err.message); setLoading(false); } }; // Auto refresh data every 30 seconds useEffect(() => { if (session?.user?.role === "admin") { const interval = setInterval(() => { fetchLeaderboardData(); }, 30000); return () => clearInterval(interval); } }, [session]); if (status === "loading" || loading) { return
{error}
}No teams currently participating.
) : (| Rank | Team Name | Members | Progress | Last Activity | Actions |
|---|---|---|---|---|---|
| {index + 1} | {team.name} ({team.code}) | {team.memberCount} |
{team.cluesFound} / {team.totalClues} (
{team.progress}%)
|
{team.lastActivity ? new Date(team.lastActivity).toLocaleString() : "Never"} |