Files
peworkshop/app/(main)/team-selection/page.js
T
2025-03-18 20:35:31 +00:00

258 lines
7.6 KiB
JavaScript

"use client";
import { useState, useEffect } from "react";
import { useSession, signOut } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
export default function TeamSelection() {
const { data: session, status, update: updateSession } = 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("");
// Validate team code before submitting
if (!teamCode || teamCode.trim() === "") {
setError("Please enter a team code");
setIsLoading(false);
return;
}
// Clean the team code of any whitespace
const cleanedTeamCode = teamCode.trim().toUpperCase();
console.log("Joining team with code:", cleanedTeamCode);
try {
// First check if we have a valid session
if (status !== "authenticated" || !session?.user) {
console.log("Session not authenticated, refreshing session...");
await updateSession();
// If still not authenticated after refresh, redirect to login
if (status !== "authenticated") {
throw new Error(
"Your session appears to be invalid. Please log in again."
);
}
}
// Now attempt to join the team
const response = await fetch("/api/teams/join", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
},
body: JSON.stringify({ teamCode: cleanedTeamCode }),
credentials: "include",
});
// Improved error handling for response
let data;
try {
// First try to parse as JSON
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
data = await response.json();
} else {
// If not JSON, get as text
const text = await response.text();
console.log("Non-JSON response:", text);
throw new Error(
`Unexpected response format: ${text.substring(0, 100)}...`
);
}
} catch (parseError) {
console.error("Error parsing response:", parseError);
throw new Error(
"Failed to parse server response: " + parseError.message
);
}
// Now check if the response was successful
if (!response.ok) {
console.error("Join team failed:", data);
throw new Error(
data.error || `Failed to join team (Status: ${response.status})`
);
}
// Add validation before constructing the URL
if (!data.teamId || isNaN(parseInt(data.teamId))) {
throw new Error("Invalid team ID received from server");
}
console.log("Join team successful:", data);
// Update the session with new team info
if (data.token) {
try {
await updateSession();
console.log("Session updated successfully");
} catch (sessionErr) {
console.warn("Session update failed:", sessionErr);
}
}
// Navigate to the team page
router.push(`/${data.teamId}`);
} catch (err) {
console.error("Join team error:", err);
// If it's an "Invalid session" error, suggest reauthentication
if (
err.message.includes("session") ||
err.message.includes("unauthorized") ||
err.message.includes("Unauthorized")
) {
setError("Your session has expired. Please log in again.");
// Attempt to sign out and redirect to login
await signOut({ redirect: false });
setTimeout(() => {
router.push("/login?error=session_expired");
}, 2000);
} else {
setError(err.message);
}
setIsLoading(false);
}
};
if (isLoading) {
return <div className="loading">Loading...</div>;
}
return (
<div className="auth-page">
<div className="page-header">
<div className="back-button"></div>
<div className="page-title">Team Selection</div>
<div className="placeholder"></div>
</div>
<div className="auth-container">
<div className="auth-card">
<h1>Join a Team</h1>
<form onSubmit={handleJoinTeam}>
<div className="form-group">
<input
type="text"
placeholder="Team Code"
value={teamCode}
onChange={(e) => setTeamCode(e.target.value.toUpperCase())}
required
className="auth-input"
/>
</div>
<button type="submit" className="auth-button" disabled={isLoading}>
{isLoading ? "Joining..." : "Join Team"}
</button>
</form>
{error && <p className="error-message">{error}</p>}
<div className="team-options">
<Link href="/create-team">
<button className="auth-button">Create a new team</button>
</Link>
</div>
</div>
</div>
<style jsx>{`
.auth-page {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
overflow: hidden;
}
.auth-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
max-width: 400px;
padding: 20px;
box-sizing: border-box;
}
.auth-card {
width: 100%;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #fff;
}
.form-group {
margin-bottom: 10px;
}
.auth-input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
text-transform: uppercase;
}
.auth-button {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #68543c; /* Updated brown color */
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-align: center;
}
.error-message {
color: red;
margin-top: 10px;
}
`}</style>
</div>
);
}