"use client"; import { useState, useEffect } from "react"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import Link from "next/link"; export default function TeamSelection() { const { data: session, status } = useSession(); const [teamCode, setTeamCode] = useState(""); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(true); const router = useRouter(); useEffect(() => { // Clear any leftover team data cache from previous teams localStorage.removeItem("teamData"); sessionStorage.removeItem("teamData"); localStorage.removeItem("userLeftTeam"); if (status === "authenticated") { // Always verify team status with a fresh API call to avoid stale session data fetch(`/api/user?_t=${Date.now()}`, { headers: { "Cache-Control": "no-cache, no-store, must-revalidate", Pragma: "no-cache", }, credentials: "include", }) .then((res) => res.json()) .then((userData) => { console.log("User data:", userData); // Debug user data // Check if user is an admin first if (userData.role === "admin") { // Redirect admin to admin dashboard with correct path router.push("/admin"); // Changed from /admin-dashboard to /admin } else if (userData.teamId) { // Only attempt to construct URL if teamId is valid if (userData.teamId && !isNaN(parseInt(userData.teamId))) { window.location.href = `/${userData.teamId}`; } else { console.error("Invalid teamId received:", userData.teamId); setIsLoading(false); } } else { setIsLoading(false); } }) .catch((error) => { console.error("Failed to fetch user data:", error); setIsLoading(false); }); } else if (status === "unauthenticated") { router.push("/login"); } else { // Still loading session setIsLoading(true); } }, [status, session, router]); const handleJoinTeam = async (e) => { e.preventDefault(); setIsLoading(true); setError(""); try { const response = await fetch("/api/join-team", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ teamCode }), }); const data = await response.json(); if (!response.ok) { throw new Error(data.error || "Failed to join team"); } // Add validation before constructing the URL if (!data.teamId || isNaN(parseInt(data.teamId))) { throw new Error("Invalid team ID received"); } // Navigate to the team page using the correct URL format window.location.href = `/${data.teamId}`; } catch (err) { setError(err.message); setIsLoading(false); } }; if (isLoading) { return
Loading...
; } return (
Team Selection

Join a Team

setTeamCode(e.target.value)} required className="auth-input" />
{error &&

{error}

}
{/* Navbar removed from here */}
); }