"use client"; import { useState, useEffect, useCallback } from "react"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import Link from "next/link"; import NavBar from "@/components/NavBar"; export default function TeamPage({ params }) { const { status, data: session } = useSession(); const [team, setTeam] = useState(null); const [teamMembers, setTeamMembers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [huntActive, setHuntActive] = useState(false); const router = useRouter(); const { teamId } = params; // Use the authenticated teamId if available const effectiveTeamId = session?.user?.teamId || teamId; const checkHuntStatus = useCallback(async () => { try { const response = await fetch("/api/hunt-status", { method: "GET", headers: { "Content-Type": "application/json" }, credentials: "include", }); if (response.ok) { const data = await response.json(); setHuntActive(data.active || false); } } catch (err) { console.error("Failed to check hunt status:", err); } }, []); const fetchTeamData = useCallback(async () => { try { if (!effectiveTeamId || isNaN(parseInt(effectiveTeamId, 10))) { throw new Error("Invalid team ID"); } // Validate current user data against effectiveTeamId const userResponse = await fetch("/api/user", { method: "GET", headers: { "Content-Type": "application/json", }, credentials: "include", cache: "no-store", }); const userData = await userResponse.json(); // If the user is not in this team anymore, redirect to team selection if ( !userData.teamId || parseInt(userData.teamId, 10) !== parseInt(effectiveTeamId, 10) ) { console.log("User no longer in team, redirecting to team selection"); window.location.href = "/team-selection"; return; } console.log("Fetching team data for team ID:", effectiveTeamId); // Add timestamp to URL to ensure fresh data on every request const timestamp = new Date().getTime(); const response = await fetch( `/api/teams/${effectiveTeamId}?_t=${timestamp}`, { method: "GET", headers: { "Content-Type": "application/json", "Cache-Control": "no-cache, no-store, must-revalidate", Pragma: "no-cache", }, credentials: "include", cache: "no-store", } ); if (!response.ok) { const text = await response.text(); let errorMessage; try { const errorData = JSON.parse(text); errorMessage = errorData.error || "Failed to fetch team data"; } catch (unused) { errorMessage = `Failed to fetch team data: ${ response.status } ${text.slice(0, 100)}`; } throw new Error(errorMessage); } const data = await response.json(); console.log("Team data received:", data); if (!data.team) { throw new Error("Team not found"); } setTeam(data.team); setTeamMembers(data.members || []); setError(""); await checkHuntStatus(); } catch (err) { console.error("Team page error:", err); setError(err.message); // If we get a 401 error, redirect to login if (err.message.includes("401")) { router.push("/login"); } } finally { setLoading(false); } }, [effectiveTeamId, router, checkHuntStatus]); useEffect(() => { // Only attempt to fetch data when session is ready and we have a teamId if (status === "authenticated" && effectiveTeamId) { console.log("Session authenticated, fetching team data"); fetchTeamData(); // Use a shorter interval (3 seconds) for more responsive updates const refreshInterval = setInterval(fetchTeamData, 3000); // Clean up the interval when component unmounts return () => clearInterval(refreshInterval); } else if (status === "unauthenticated") { console.log("User not authenticated, redirecting to login"); router.push("/login"); } }, [effectiveTeamId, status, fetchTeamData, router]); // Add a function to properly handle the "Continue Hunt" button click const continueTreasureHunt = async (e) => { e.preventDefault(); setLoading(true); try { // Check if hunt is active first const timestamp = Date.now(); const response = await fetch(`/api/hunt-status?t=${timestamp}`, { method: "GET", headers: { "Content-Type": "application/json", "Cache-Control": "no-store, no-cache, must-revalidate", Pragma: "no-cache", }, credentials: "include", }); if (response.ok) { const data = await response.json(); if (data.active) { // Hunt is active, redirect to map router.push("/map"); } else { // Hunt is not active, redirect to waiting page router.push("/waiting"); } } else { throw new Error("Failed to check hunt status"); } } catch (err) { console.error("Error checking hunt status:", err); setError("Failed to check hunt status. Please try again."); setLoading(false); } }; if (status === "loading" || loading) { return (