Files
peworkshop/app/(main)/map/page.js
T

224 lines
6.8 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 Image from "next/image";
import styles from "./map.module.css";
import { useHuntStatusCheck } from "@/hooks/useHuntStatusCheck";
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();
// Use the custom hook to check if hunt is still active
const huntActive = useHuntStatusCheck();
// Debug log for hunt status
useEffect(() => {
console.log("Hunt active status in map page:", huntActive);
}, [huntActive]);
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]);
// Update elapsed time every second
useEffect(() => {
if (!teamData?.team) return;
const startTime = new Date(teamData?.huntStartTime || Date.now()).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]);
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);
}
};
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 */}
<div className={styles["map-container"]} ref={mapContainerRef}>
<div className={styles["treasure-map"]}>
{/* Use Image component with fill layout for better SVG handling */}
<Image
src="/images/treasure-map.svg"
alt="Treasure Map"
className={styles["map-svg"]}
width={1000}
height={1000}
priority
onError={() => {
// Fallback to a static image if SVG fails to load
setMapError(true);
}}
/>
</div>
</div>
{/* Navigation bar - now sticky */}
<nav className={styles["nav-bar"]}>
<Link
href={teamData?.teamId ? `/${teamData.teamId}` : "/"}
className={styles["nav-item"]}
>
<div className={styles["nav-icon"]}>🏠</div>
<div className={styles["nav-label"]}>Home</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="/team-selection" className={styles["nav-item"]}>
<div className={styles["nav-icon"]}>👥</div>
<div className={styles["nav-label"]}>Team</div>
</Link>
<Link
href="/map"
className={`${styles["nav-item"]} ${styles["active"]}`}
>
<div className={styles["nav-icon"]}>🗺️</div>
<div className={styles["nav-label"]}>Map</div>
</Link>
</nav>
</div>
);
}