"use client"; import { useState, useEffect } from "react"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import Link from "next/link"; import styles from "./stats.module.css"; export default function StatsPage() { const { data: session, status } = useSession(); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [teamStats, setTeamStats] = useState(null); const [expanded, setExpanded] = useState(false); const router = useRouter(); useEffect(() => { // Redirect to login if not authenticated if (status === "unauthenticated") { router.push("/login"); return; } if (status === "authenticated") { fetchTeamStats(); } }, [status, router]); const fetchTeamStats = async () => { try { setLoading(true); setError(null); const response = await fetch("/api/team-stats", { method: "GET", headers: { "Content-Type": "application/json", "Cache-Control": "no-cache, no-store, must-revalidate", }, credentials: "include", }); if (!response.ok) { // Handle specific error cases const errorData = await response.json().catch(() => ({})); if (response.status === 401) { throw new Error("Authentication error: Not logged in"); } else if ( response.status === 404 || errorData.error?.includes("not part of a team") ) { throw new Error("You need to join a team before viewing stats"); } else { throw new Error(errorData.error || "Failed to fetch team stats"); } } const data = await response.json(); setTeamStats(data); } catch (err) { console.error("Error fetching team stats:", err); setError(err.message); } finally { setLoading(false); } }; const toggleExpanded = () => { setExpanded(!expanded); }; // Format timestamp to a more readable format const formatTimestamp = (timestamp) => { const date = new Date(timestamp); return date.toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", }); }; const renderCluesList = () => { if (!teamStats) return null; const { foundClues, skippedClues } = teamStats; return (

Found Clues ({foundClues?.length || 0})

Skipped Clues ({skippedClues?.length || 0})

); }; if (loading) { return (

Loading team stats...

); } if (error) { return (

Error

{error}

); } if (!teamStats) { return (

No team stats available.

); } return (

Team Stats

{teamStats.team.name}

Total Clues: {teamStats.totalClues}
Clues Found: {teamStats.foundClues.length}
Clues Remaining: {teamStats.remainingClues}
Clues Skipped: {teamStats.skippedClues}
Current Rank: {teamStats.currentRank}
{expanded && (
{renderCluesList()}
)}
πŸ—ΊοΈ
Map
πŸ“Š
Stats
πŸ‘₯
Team
πŸ†
Leaderboard
); }