"use client"; import { useState, useEffect } from "react"; import { useSearchParams } from "next/navigation"; import { useRouter } from "next/navigation"; import { useSession } from "next-auth/react"; import Link from "next/link"; import NavBar from "@/components/NavBar"; import Image from "next/image"; export default function LeaderboardPage() { const [teams, setTeams] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const searchParams = useSearchParams(); const huntJustEnded = searchParams.get("huntEnded") === "true"; const router = useRouter(); const { data: session, status } = useSession(); // Fix: Properly destructure session from useSession() // Function to fetch leaderboard data const fetchLeaderboard = async () => { try { setLoading(true); // Fetch from the public leaderboard endpoint const response = await fetch("/api/leaderboard", { headers: { "Cache-Control": "no-cache, no-store, must-revalidate", Pragma: "no-cache", }, credentials: "include", }); if (!response.ok) { throw new Error("Failed to fetch leaderboard data"); } const data = await response.json(); setTeams(data); setError(""); } catch (err) { console.error("Error fetching leaderboard:", err); setError(err.message); } finally { setLoading(false); } }; // Fetch data on mount and set up refresh interval useEffect(() => { // Only proceed if authenticated if (status === "authenticated") { fetchLeaderboard(); // Refresh data every 30 seconds const interval = setInterval(fetchLeaderboard, 30000); return () => clearInterval(interval); } else if (status === "unauthenticated") { router.push("/login"); } }, [status, router]); if (loading) { return (

Loading leaderboard...

); } return (
{huntJustEnded ? "Final Results" : "Leaderboard"}
{huntJustEnded && (
🎯

The Hunt Has Ended!

The timer has been stopped by an administrator. Here are the final results.

)} {error ? (
{error}
) : teams.length > 0 ? (
{!huntJustEnded && ( <> )} {teams.map((team, index) => ( {!huntJustEnded && ( <> )} ))}
Rank TeamProgress Last Activity
{index < 3 ? (
{index === 0 && "🥇"} {index === 1 && "🥈"} {index === 2 && "🥉"}
) : ( `${index + 1}` )}
{team.name}
{team.cluesFound} / {team.totalClues} {team.progress > 0 && ` (${team.progress}%)`}
{team.lastActivity ? new Date(team.lastActivity).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", }) : "Never"}
) : (
No teams on the leaderboard yet
)} {/* Decorative corner images */}
Cannon Ball
Barrel
{/* Only show navigation bar when the hunt hasn't ended */} {!huntJustEnded && ( )} {/* Add a "back to home" button when the hunt has ended */} {huntJustEnded && (
)}
); }