Files
peworkshop/app/(main)/[teamId]/page.js
T

504 lines
15 KiB
JavaScript

"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 { use } from "react"; // Add this import for React.use()
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();
// Unwrap the params Promise using React.use()
const unwrappedParams = use(params);
const teamId = unwrappedParams.teamId;
// Add a function to check if the hunt has been activated by admin
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 (!teamId || isNaN(parseInt(teamId, 10))) {
throw new Error("Invalid team ID");
}
// First check if the user is still part of this team by fetching current user data
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 || userData.teamId != teamId) {
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:", teamId);
// Add timestamp to URL to ensure fresh data on every request
const timestamp = new Date().getTime();
const response = await fetch(`/api/teams/${teamId}?_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("");
// Check hunt status whenever we fetch team data
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);
}
}, [teamId, router, checkHuntStatus]);
useEffect(() => {
// Only attempt to fetch data when session is ready and we have a teamId
if (status === "authenticated" && teamId) {
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");
}
}, [teamId, status, fetchTeamData, router]);
if (status === "loading" || loading) {
return (
<div className="loading-container">
<div className="loading-spinner"></div>
<div className="loading-text">Loading team data...</div>
</div>
);
}
if (error) {
return (
<div className="error-container">
<div className="error-icon">⚠️</div>
<div className="error-message">Error: {error}</div>
<Link href="/team-selection">
<button className="back-button">Back to Team Selection</button>
</Link>
</div>
);
}
if (!team) {
return (
<div className="error-container">
<div className="error-icon">🔍</div>
<div className="error-message">Team not found</div>
<Link href="/team-selection">
<button className="back-button">Back to Team Selection</button>
</Link>
</div>
);
}
return (
<div className="team-page">
<div className="team-banner">
<div className="team-info">
<h1 className="team-name">Team Name: {team.name}</h1>
<div className="team-code">{team.code}</div>
</div>
</div>
<div className="members-container">
<h2 className="members-title">Team Members</h2>
{teamMembers.length > 0 ? (
<div className="members-list">
{teamMembers.map((member) => (
<div key={member.id} className="member-card">
<div className="member-avatar">👤</div>
<div className="member-details">
<div className="member-name">
{member.username}
{member.id === session?.user?.id && " (You)"}
</div>
</div>
</div>
))}
</div>
) : (
<div className="empty-state">No team members found</div>
)}
</div>
<div className="team-actions">
<button
className="action-button leave-button"
onClick={async () => {
if (confirm("Are you sure you want to leave this team?")) {
try {
setLoading(true);
const response = await fetch(`/api/teams/${teamId}/leave`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
});
if (response.ok) {
// Immediately remove team data from all storage
localStorage.removeItem("teamData");
sessionStorage.removeItem("teamData");
// Set a flag so we know the user has left this team
localStorage.setItem("userLeftTeam", "true");
// Force redirect to team selection
window.location.href = "/team-selection";
} else {
const errorData = await response.json();
throw new Error(errorData.error || "Failed to leave team");
}
} catch (err) {
setError(err.message);
setLoading(false);
}
}
}}
>
Leave Team
</button>
{/* New Start Hunt button with conditional behavior */}
{session?.user?.role !== "admin" && (
<button
className="action-button start-button"
onClick={async () => {
try {
setLoading(true);
// Use the dedicated start hunt API endpoint
const response = await fetch("/api/hunt/start", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
},
credentials: "include",
});
const data = await response.json();
if (data.success && data.active) {
// Redirect to map page using window.location for a clean reload
window.location.href = data.redirectUrl || "/map";
} else if (!data.active) {
// Hunt is not active
router.push(`/hunt-not-started?teamId=${teamId}`);
} else {
// Some other error
throw new Error(data.error || "Failed to start hunt journey");
}
} catch (err) {
console.error("Error starting hunt:", err);
setError(`Failed to start hunt: ${err.message}`);
setLoading(false);
}
}}
>
Start Hunt
</button>
)}
</div>
<div className="nav-bar">
{/* Update the Home link to point to the current team page */}
<Link href={`/${teamId}`} className="nav-item">
<div className="nav-icon">🏠</div>
<div className="nav-label">Home</div>
</Link>
<Link href="/leaderboard" className="nav-item">
<div className="nav-icon">📊</div>
<div className="nav-label">Stats</div>
</Link>
<Link href="/team-selection" className="nav-item active">
<div className="nav-icon">👥</div>
<div className="nav-label">Team</div>
</Link>
<Link href="/profile" className="nav-item">
<div className="nav-icon">👤</div>
<div className="nav-label">Profile</div>
</Link>
</div>
<style jsx>{`
.team-page {
display: flex;
flex-direction: column;
min-height: 100vh;
background-color: #f4f4f4;
font-family: Arial, sans-serif;
position: relative;
overflow-x: hidden; /* Prevent horizontal scroll */
width: 100%;
padding-bottom: 70px; /* Add padding to accommodate fixed navbar */
}
.team-banner {
background-color: #68543c;
color: white;
padding: 20px;
position: relative;
display: flex;
align-items: center;
}
.team-info {
flex: 1;
display: flex;
justify-content: space-between; /* This spreads items to opposite ends */
align-items: center;
}
.team-name {
margin: 0;
font-size: 24px;
font-weight: bold;
color: white; /* Explicitly setting color to white */
}
.team-code {
font-size: 24px;
font-weight: bold;
color: white; /* Ensuring team code is also white */
margin-left: auto; /* Pushes the code to the right */
}
.members-container {
padding: 20px;
flex: 1;
}
.members-title {
font-size: 18px;
margin-bottom: 15px;
color: #333;
}
.members-list {
display: flex;
flex-direction: column;
gap: 10px;
}
.member-card {
background-color: white;
border-radius: 8px;
padding: 15px;
display: flex;
align-items: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
border: 2px solid #68543c; /* Add 2px thick border with the same brown color as banner */
}
.member-avatar {
font-size: 24px;
margin-right: 15px;
}
.member-name {
font-weight: 600;
}
.empty-state {
text-align: center;
padding: 30px;
color: #888;
}
.team-actions {
display: flex;
gap: 10px;
padding: 20px;
}
.action-button {
flex: 1;
padding: 15px;
border: none;
border-radius: 8px;
font-weight: bold;
cursor: pointer;
}
.leave-button {
background-color: #f6bd60;
color: #333;
}
.start-button {
background-color: #588157;
color: white;
}
.nav-bar {
display: flex;
justify-content: space-around;
background-color: white;
border-top: 1px solid #ddd;
padding: 10px 0;
position: fixed; /* Fix the navbar at the bottom */
bottom: 0;
left: 0;
width: 100%; /* Use 100% instead of 100vw to prevent overflow issues */
box-sizing: border-box; /* Include padding in width calculation */
z-index: 100; /* Ensure navbar is above other content */
}
.nav-item {
display: flex;
flex-direction: column;
align-items: center;
text-decoration: none;
color: #666;
flex: 1;
padding: 8px 0;
max-width: 25%; /* Ensure each item takes up equal space */
}
.nav-item.active {
color: #68543c;
}
.nav-icon {
font-size: 22px;
margin-bottom: 3px;
}
.nav-label {
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 100%;
text-align: center;
}
/* Responsive adjustments for smaller screens */
@media (max-width: 375px) {
.nav-icon {
font-size: 20px;
}
.nav-label {
font-size: 10px;
}
}
.loading-container,
.error-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
padding: 20px;
text-align: center;
}
.loading-spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #68543c;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin-bottom: 20px;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.error-icon {
font-size: 48px;
margin-bottom: 20px;
}
.error-message {
margin-bottom: 20px;
color: #d32f2f;
}
`}</style>
</div>
);
}