mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
372 lines
12 KiB
JavaScript
372 lines
12 KiB
JavaScript
"use client";
|
|
import { useState, useEffect, useRef } from "react";
|
|
import { useSession } from "next-auth/react";
|
|
import { useRouter } from "next/navigation";
|
|
import Link from "next/link";
|
|
import styles from "./map.module.css";
|
|
|
|
export default function MapPage() {
|
|
const { data: session, status } = useSession();
|
|
const [loading, setLoading] = useState(true);
|
|
const [mapError, setMapError] = useState(false);
|
|
const [error, setError] = useState(null);
|
|
const [teamData, setTeamData] = useState(null);
|
|
const [elapsedTime, setElapsedTime] = useState("00:00:00");
|
|
const mapContainerRef = useRef(null);
|
|
const router = useRouter();
|
|
|
|
// Add local state for hunt active status
|
|
const [huntActive, setHuntActive] = useState(null);
|
|
|
|
// Add function to fetch team hunt start time
|
|
const fetchTeamHuntStartTime = async () => {
|
|
try {
|
|
// First check localStorage for cached start time
|
|
const cachedStartTime = localStorage.getItem("teamHuntStartTime");
|
|
|
|
// If we have a cached time, use it
|
|
if (cachedStartTime) {
|
|
return cachedStartTime;
|
|
}
|
|
|
|
// Otherwise fetch from the server
|
|
if (session?.user?.teamId) {
|
|
const response = await fetch(
|
|
`/api/teams/${session.user.teamId}/hunt-session`,
|
|
{
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
},
|
|
credentials: "include",
|
|
}
|
|
);
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
if (data.startTime) {
|
|
// Cache the start time for future use
|
|
localStorage.setItem("teamHuntStartTime", data.startTime);
|
|
return data.startTime;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Fallback to current time if we couldn't get a start time
|
|
return new Date().toISOString();
|
|
} catch (error) {
|
|
console.error("Failed to fetch team hunt start time:", error);
|
|
return new Date().toISOString();
|
|
}
|
|
};
|
|
|
|
// Initial hunt status check
|
|
useEffect(() => {
|
|
// Check if hunt is active
|
|
checkHuntAndTimer();
|
|
|
|
// Set up periodic checks
|
|
const interval = setInterval(checkHuntAndTimer, 3000);
|
|
return () => clearInterval(interval);
|
|
}, []);
|
|
|
|
// Handle authentication and hunt status
|
|
useEffect(() => {
|
|
// Only redirect if explicitly not authenticated
|
|
if (status === "unauthenticated") {
|
|
router.push("/login");
|
|
return;
|
|
}
|
|
|
|
// If hunt is not active, redirect to waiting page
|
|
if (huntActive === false) {
|
|
console.log("Hunt is not active, redirecting to waiting page");
|
|
router.push("/waiting");
|
|
return;
|
|
}
|
|
|
|
// Only fetch team data if authenticated and hunt is active or status unknown
|
|
if (status === "authenticated" && huntActive !== false) {
|
|
fetchTeamData();
|
|
}
|
|
}, [status, huntActive, router]);
|
|
|
|
// Function to check hunt status and timer
|
|
async function checkHuntAndTimer() {
|
|
try {
|
|
const response = await fetch("/api/hunt-status", {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
},
|
|
credentials: "include",
|
|
});
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
console.log("Hunt status check from map:", data);
|
|
|
|
// If hunt is not active, check if it has ended
|
|
if (!data.active) {
|
|
console.log("Hunt not active, checking if it ended...");
|
|
|
|
// Check if we had an active hunt before (using localStorage)
|
|
const wasActive = localStorage.getItem("teamHuntStartTime");
|
|
|
|
if (wasActive) {
|
|
// Hunt was active before but not now - it ended
|
|
console.log("Hunt has ended, redirecting to leaderboard");
|
|
localStorage.removeItem("teamHuntStartTime"); // Clean up
|
|
window.location.href = "/leaderboard?huntEnded=true";
|
|
return;
|
|
}
|
|
|
|
// Otherwise just show the waiting page
|
|
setHuntActive(false);
|
|
router.push("/waiting");
|
|
return;
|
|
}
|
|
|
|
// If timer endTime exists and has passed, redirect to leaderboard
|
|
if (data.endTime && new Date(data.endTime) <= new Date()) {
|
|
console.log("Timer expired, redirecting to leaderboard");
|
|
// Clean up the storage
|
|
localStorage.removeItem("teamHuntStartTime");
|
|
router.push("/leaderboard?huntEnded=true");
|
|
return;
|
|
}
|
|
|
|
// Otherwise, hunt is active and timer is running
|
|
setHuntActive(true);
|
|
}
|
|
} catch (err) {
|
|
console.error("Failed to check hunt status:", err);
|
|
}
|
|
}
|
|
|
|
// Use team hunt start time for elapsed time calculation
|
|
useEffect(() => {
|
|
if (!teamData?.team) return;
|
|
|
|
let startTimePromise = fetchTeamHuntStartTime();
|
|
startTimePromise.then((startTimeStr) => {
|
|
// Parse the ISO string to milliseconds
|
|
const startTime = new Date(startTimeStr).getTime();
|
|
|
|
const timer = setInterval(() => {
|
|
const now = Date.now();
|
|
const elapsed = Math.floor((now - startTime) / 1000);
|
|
|
|
const hours = Math.floor(elapsed / 3600)
|
|
.toString()
|
|
.padStart(2, "0");
|
|
const minutes = Math.floor((elapsed % 3600) / 60)
|
|
.toString()
|
|
.padStart(2, "0");
|
|
const seconds = Math.floor(elapsed % 60)
|
|
.toString()
|
|
.padStart(2, "0");
|
|
|
|
setElapsedTime(`${hours}:${minutes}:${seconds}`);
|
|
}, 1000);
|
|
|
|
return () => clearInterval(timer);
|
|
});
|
|
}, [teamData, session]);
|
|
|
|
const fetchTeamData = async () => {
|
|
try {
|
|
setLoading(true);
|
|
setError(null);
|
|
const response = await fetch("/api/user/team", {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
},
|
|
credentials: "include",
|
|
});
|
|
|
|
if (!response.ok) {
|
|
// Handle specific error cases without immediate redirect
|
|
const errorData = await response.json().catch(() => ({}));
|
|
|
|
if (response.status === 401) {
|
|
// Set error but don't redirect immediately - let the session handling take care of it
|
|
setError(
|
|
"Authentication error: " + (errorData.error || "Not logged in")
|
|
);
|
|
setLoading(false);
|
|
return;
|
|
} else if (
|
|
response.status === 404 ||
|
|
errorData.error?.includes("not part of a team")
|
|
) {
|
|
setError("You need to join a team before viewing the map");
|
|
setLoading(false);
|
|
// Give user time to read the error message before redirect
|
|
setTimeout(() => router.push("/team-selection"), 2000);
|
|
return;
|
|
} else {
|
|
throw new Error(errorData.error || "Failed to fetch team data");
|
|
}
|
|
}
|
|
|
|
const data = await response.json();
|
|
setTeamData(data);
|
|
setLoading(false);
|
|
} catch (err) {
|
|
console.error("Error fetching team data:", err);
|
|
setError(err.message);
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
// Check hunt status every second to ensure immediate updates
|
|
useEffect(() => {
|
|
const checkHuntStatus = async () => {
|
|
try {
|
|
const timestamp = Date.now(); // Add cache-busting timestamp
|
|
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) {
|
|
console.error("Failed to fetch hunt status:", response.statusText);
|
|
return;
|
|
}
|
|
|
|
const data = await response.json();
|
|
console.log("Map page hunt status check:", data);
|
|
|
|
// If hunt is not active, force redirect to waiting page
|
|
if (!data.active) {
|
|
console.log("Hunt not active, redirecting to waiting page");
|
|
window.location.href = "/waiting";
|
|
return;
|
|
}
|
|
|
|
// If timer endTime exists and has passed, redirect to leaderboard
|
|
if (data.endTime && new Date(data.endTime) <= new Date()) {
|
|
console.log("Timer expired, redirecting to leaderboard");
|
|
window.location.href = "/leaderboard?huntEnded=true";
|
|
return;
|
|
}
|
|
|
|
// Otherwise, hunt is active and timer is running
|
|
setHuntActive(true);
|
|
} catch (err) {
|
|
console.error("Failed to check hunt status:", err);
|
|
}
|
|
};
|
|
|
|
// Check immediately and every second
|
|
checkHuntStatus();
|
|
const intervalId = setInterval(checkHuntStatus, 1000);
|
|
return () => clearInterval(intervalId);
|
|
}, []);
|
|
|
|
if (status === "loading" || loading) {
|
|
return (
|
|
<div className={styles["loading-container"]}>
|
|
<div className={styles["loading-spinner"]}></div>
|
|
<div>Loading map...</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// If hunt status is known to be inactive, show message
|
|
if (huntActive === false) {
|
|
return (
|
|
<div className={styles["map-error"]}>
|
|
<h2>Hunt Not Active</h2>
|
|
<p>The treasure hunt has not started yet.</p>
|
|
<button onClick={() => router.push("/waiting")}>
|
|
Go to Waiting Room
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (error) {
|
|
return (
|
|
<div className={styles["map-error"]}>
|
|
<h2>Error</h2>
|
|
<p>{error}</p>
|
|
<button onClick={fetchTeamData}>Retry</button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (mapError) {
|
|
return (
|
|
<div className={styles["map-error"]}>
|
|
<h2>Error Loading Map</h2>
|
|
<p>We couldn't load the treasure map. Please try again.</p>
|
|
<button onClick={fetchTeamData}>Retry</button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className={styles["map-page"]}>
|
|
{/* Map Banner with team info and timer */}
|
|
<div className={styles["map-banner"]}>
|
|
<div className={styles["team-name"]}>
|
|
{teamData?.team?.name || "Your Team"}
|
|
</div>
|
|
<div className={styles["elapsed-time"]}>
|
|
<span className={styles["time-value"]}>{elapsedTime}</span>
|
|
</div>
|
|
<div className={styles["team-code"]}>{teamData?.team?.code || ""}</div>
|
|
</div>
|
|
|
|
{/* Main map content area - showing map as background */}
|
|
<div className={styles["map-container"]} ref={mapContainerRef}>
|
|
<div className={styles["treasure-map"]}>
|
|
{/* Using background-image for the map SVG */}
|
|
<div
|
|
className={styles["map-background"]}
|
|
role="img"
|
|
aria-label="Treasure Map"
|
|
></div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Navigation bar - Map as first button */}
|
|
<nav className={styles["nav-bar"]}>
|
|
<Link
|
|
href="/map"
|
|
className={`${styles["nav-item"]} ${styles["active"]}`}
|
|
>
|
|
<div className={styles["nav-icon"]}>🗺️</div>
|
|
<div className={styles["nav-label"]}>Map</div>
|
|
</Link>
|
|
<Link href="/leaderboard" className={styles["nav-item"]}>
|
|
<div className={styles["nav-icon"]}>📊</div>
|
|
<div className={styles["nav-label"]}>Stats</div>
|
|
</Link>
|
|
<Link
|
|
href={teamData?.team ? `/${teamData.team.id}` : "/team-selection"}
|
|
className={styles["nav-item"]}
|
|
>
|
|
<div className={styles["nav-icon"]}>👥</div>
|
|
<div className={styles["nav-label"]}>Team</div>
|
|
</Link>
|
|
<Link href="/team-selection" className={styles["nav-item"]}>
|
|
<div className={styles["nav-icon"]}>🔙</div>
|
|
<div className={styles["nav-label"]}>Back</div>
|
|
</Link>
|
|
</nav>
|
|
</div>
|
|
);
|
|
}
|