"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 localStorage.removeItem("teamData"); sessionStorage.removeItem("teamData"); localStorage.removeItem("userLeftTeam"); if (status === "authenticated") { 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); if (userData.role === "admin") { router.push("/admin"); } else if (userData.teamId) { // Use router.push for client-side navigation router.push(`/${userData.teamId}`); } else { setIsLoading(false); } }) .catch((error) => { console.error("Failed to fetch user data:", error); setIsLoading(false); }); } else if (status === "unauthenticated") { router.push("/login"); } else { setIsLoading(true); } }, [status, 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 */}
); }