fixing some styling and component usage issues

This commit is contained in:
bobbert committed 2025-03-23 13:45:23 +00:00
1 parent c496b08d52
commit ffdc2279ec
5 files changed
+418 -147

No files matched your search

+362 -73
View File
@@ -1,68 +1,53 @@
/* eslint-disable @next/next/no-img-element */
"use client"; "use client";
import { useState, useEffect, useRef } from "react"; import { useState, useEffect, useRef, useCallback } from "react";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import Image from "next/image";
import styles from "./map.module.css"; import styles from "./map.module.css";
import NavBar from "@/components/NavBar"; import NavBar from "@/components/NavBar";
import {
getHuntTimer,
setHuntTimer,
clearHuntTimer,
formatElapsedTime,
syncTimerWithServer,
} from "@/utils/timerService";
export default function MapPage() { export default function MapPage() {
const { data: session, status } = useSession(); const { data: session, status } = useSession();
const [teamData, setTeamData] = useState(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [mapError, setMapError] = useState(false);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [mapLoaded, setMapLoaded] = useState(false); const [teamData, setTeamData] = useState(null);
const [huntActive, setHuntActive] = useState(null); const [elapsedTime, setElapsedTime] = useState("00:00:00");
const [clues, setClues] = useState([]);
const mapContainerRef = useRef(null);
const router = useRouter(); const router = useRouter();
const mapRef = useRef(null); const isMounted = useRef(true);
useEffect(() => { // Add local state for hunt active status
// Redirect to login if not authenticated const [huntActive, setHuntActive] = useState(null);
if (status === "unauthenticated") { // Add previous hunt state to detect when hunt ends
router.push("/login"); const [previousHuntState, setPreviousHuntState] = useState(null);
return;
// Use useCallback for functions called in useEffect to avoid dependency issues
const softRedirect = useCallback(
(url) => {
if (isMounted.current) {
router.push(url);
} }
if (status === "authenticated") {
checkHuntStatus();
fetchTeamData();
}
}, [status, router]);
const checkHuntStatus = async () => {
try {
const timestamp = Date.now();
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", [router]
}); );
if (response.ok) { // Hard redirect function (for when a full page reload is needed)
const data = await response.json(); const hardRedirect = useCallback((url) => {
setHuntActive(data.active); window.location.href = url;
}, []);
// Redirect to waiting page if hunt is not active // Enhanced fetchTeamData function
if (!data.active) { const fetchTeamData = useCallback(async () => {
router.push("/waiting");
return;
}
} else {
throw new Error("Failed to check hunt status");
}
} catch (err) {
console.error("Failed to check hunt status:", err);
setError("Failed to check if hunt is active. Please try again.");
setLoading(false);
}
};
const fetchTeamData = async () => {
try { try {
const response = await fetch("/api/user/team", { const response = await fetch("/api/user/team", {
method: "GET", method: "GET",
@@ -75,12 +60,12 @@ export default function MapPage() {
}); });
if (response.status === 401) { if (response.status === 401) {
router.push("/login"); softRedirect("/login");
return null; return null;
} }
if (response.status === 404) { if (response.status === 404) {
router.push("/team-selection"); softRedirect("/team-selection");
return null; return null;
} }
@@ -97,17 +82,239 @@ export default function MapPage() {
setError(err.message); setError(err.message);
return null; return null;
} }
}, [softRedirect]);
// Fetch all clues with their status
const fetchClues = useCallback(async () => {
try {
const response = await fetch("/api/clues", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
},
credentials: "include",
});
if (!response.ok) {
// Extract the error message from the response if possible
const errorData = await response.json().catch(() => ({}));
console.error("API response details:", {
status: response.status,
statusText: response.statusText,
errorData,
});
throw new Error(
errorData.error ||
`Failed to fetch clues: ${response.status} ${response.statusText}`
);
}
const data = await response.json();
// Process the clues to determine which are available
// A clue is available if it's either found already or the next in sequence
const processedClues = data.map((clue) => {
// The API now returns clues with availability already determined
return {
...clue,
available: clue.available || clue.found || clue.skipped,
};
});
setClues(processedClues);
setLoading(false); // Set loading to false after clues are fetched
return processedClues;
} catch (err) {
console.error("Failed to fetch clues:", err);
setError(err.message); // Make sure we set the error state
setLoading(false);
return [];
}
}, []);
// Handle clue button click
const handleClueClick = useCallback(
(clueId, isAvailable, isFound) => {
if (isFound || isAvailable) {
router.push(`/clue/${clueId}`);
} else {
alert("Complete previous clues to unlock this one!");
}
},
[router]
);
// Size and position the overlay to match the map image
const setupOverlay = useCallback(() => {
const overlay = document.getElementById("map-overlay-container");
const mapImg = document.getElementById("treasure-map-img");
if (overlay && mapImg) {
// Wait for the image to load to get its dimensions
mapImg.onload = () => {
const mapRect = mapImg.getBoundingClientRect();
overlay.style.width = `${mapRect.width}px`;
overlay.style.height = `${mapRect.height}px`;
}; };
const handleMapLoad = () => { // Handle resize events
setMapLoaded(true); const resizeOverlay = () => {
const mapRect = mapImg.getBoundingClientRect();
overlay.style.width = `${mapRect.width}px`;
overlay.style.height = `${mapRect.height}px`;
}; };
const handleMapError = () => { // Initial resize and listen for window resize
setError("Failed to load the map. Please try again."); setTimeout(resizeOverlay, 300);
window.addEventListener("resize", resizeOverlay);
return () => {
window.removeEventListener("resize", resizeOverlay);
};
}
}, []);
// Add this useEffect to coordinate loading the map and clues
useEffect(() => {
if (status === "authenticated") {
fetchClues();
fetchTeamData();
} else if (status === "unauthenticated") {
softRedirect("/login");
}
// Setup cleanup function for component unmount
return () => {
isMounted.current = false;
};
}, [status, fetchClues, fetchTeamData, softRedirect]);
// Setup the overlay when the component is mounted
useEffect(() => {
if (!loading && clues.length > 0) {
return setupOverlay();
}
}, [loading, clues.length, setupOverlay]);
// 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",
Pragma: "no-cache",
},
credentials: "include",
});
if (response.ok) {
const data = await response.json();
setHuntActive(data.active);
// If hunt is inactive, redirect to waiting page
if (data.active === false) {
router.push("/waiting");
return;
}
// If hunt is active, ensure we have timer data
if (data.active && data.startTime) {
setHuntTimer(data.startTime);
}
}
} catch (err) {
console.error("Failed to check hunt status:", err);
}
}
// Add this function before it's used in initializeTimer
async function fetchTeamHuntStartTime() {
try {
// First try to get any existing timer data
const timerData = getHuntTimer();
if (timerData && timerData.startTime) {
return true;
}
// If no timer data exists, sync with server
const result = await syncTimerWithServer();
return result.success;
} catch (err) {
console.error("Error fetching team hunt start time:", err);
return false;
}
}
// Use team hunt start time for elapsed time calculation
useEffect(() => {
let timerId;
// Initialize timer
async function initializeTimer() {
// First ensure we have timer data
await fetchTeamHuntStartTime();
// Set up timer updates
const updateTimer = () => {
const timerData = getHuntTimer();
if (timerData && timerData.startTime) {
setElapsedTime(formatElapsedTime(timerData.startTime));
}
}; };
if (loading) { // Initial update
updateTimer();
// Update every second
timerId = setInterval(updateTimer, 1000);
}
initializeTimer();
// Clean up interval on unmount
return () => {
if (timerId) clearInterval(timerId);
};
}, []);
// Check hunt status every 10 seconds to ensure immediate updates
useEffect(() => {
// Initial check
checkHuntAndTimer();
// Set up interval to check hunt status
const huntStatusInterval = setInterval(checkHuntAndTimer, 10000);
return () => {
clearInterval(huntStatusInterval);
};
}, [softRedirect, hardRedirect]);
// Add useEffect to load team data
useEffect(() => {
if (status === "authenticated") {
fetchTeamData();
}
}, [status, fetchTeamData]);
// Add this useEffect to detect when hunt ends
useEffect(() => {
// If previous state was active but current state is not active, the hunt just ended
if (previousHuntState === true && huntActive === false) {
console.log("Hunt has ended! Redirecting to leaderboard...");
router.push("/leaderboard?huntEnded=true");
}
// Update previous state after checking
setPreviousHuntState(huntActive);
}, [huntActive, previousHuntState, router]);
if (status === "loading" || loading) {
return ( return (
<div className={styles["loading-container"]}> <div className={styles["loading-container"]}>
<div className={styles["loading-spinner"]}></div> <div className={styles["loading-spinner"]}></div>
@@ -116,6 +323,22 @@ export default function MapPage() {
); );
} }
// Remove or modify this conditional block since we're now handling hunt ending differently
// Instead of showing an error message, we'll redirect in the useEffect
if (huntActive === false && previousHuntState === null) {
// Only show this if we just landed on the page and hunt is inactive
// (not when the hunt just ended)
return (
<div className={styles["map-error"]}>
<h2>Hunt Not Active</h2>
<p>The treasure hunt has not started yet.</p>
<button onClick={() => softRedirect("/waiting")}>
Go to Waiting Room
</button>
</div>
);
}
if (error) { if (error) {
return ( return (
<div className={styles["map-error"]}> <div className={styles["map-error"]}>
@@ -126,32 +349,98 @@ export default function MapPage() {
); );
} }
if (mapError) {
return ( return (
<div className={styles.mapPage}> <div className={styles["map-error"]}>
<div className={styles.mapHeader}> <h2>Error Loading Map</h2>
<div className={styles.teamInfo}> <p>We couldn't load the treasure map. Please try again.</p>
<h1 className={styles.teamName}> <button onClick={fetchClues}>Retry</button>
{teamData?.team ? teamData.team.name : "Loading..."}
</h1>
<div className={styles.teamProgress}>
{teamData?.progress !== undefined
? `${teamData.progress}% Complete`
: "..."}
</div> </div>
);
}
// Function to determine clue button class based on status
const getClueButtonClass = (clue) => {
if (clue.found) return `${styles["clue-button"]} ${styles["clue-found"]}`;
if (clue.skipped)
return `${styles["clue-button"]} ${styles["clue-skipped"]}`;
if (clue.available)
return `${styles["clue-button"]} ${styles["clue-available"]}`;
return `${styles["clue-button"]} ${styles["clue-locked"]}`;
};
// Get the first clue if it exists
const firstClue = clues.length > 0 ? clues[0] : null;
// Render a clue button only if the clue exists
const renderClueButton = (index, position) => {
if (index >= clues.length) return null; // Don't render if clue doesn't exist
const clue = clues[index];
return (
<button
key={clue.id}
className={getClueButtonClass(clue)}
onClick={() => handleClueClick(clue.id, clue.available, clue.found)}
style={{
left: position.left,
top: position.top,
}}
></button>
);
};
return (
<div className={styles["map-page"]}>
{/* Map Banner with team info and timer */}
<div className={styles["map-banner"]}>
<div className={styles["team-name"]}>
Team Name: {teamData?.team?.name || "Loading..."}
</div> </div>
<div className={styles["elapsed-time"]}>
<span className={styles["time-value"]}>{elapsedTime}</span>
</div>
<div className={styles["team-code"]}>{teamData?.team?.code || ""}</div>
</div> </div>
<div className={styles.mapContainer}> {/* Main map content area */}
<div className={styles.treasureMap}> <div className={styles["map-container"]} ref={mapContainerRef}>
<Image <div className={styles["treasure-map"]}>
{/* Simpler map implementation using an img element */}
<div className={styles["map-image-container"]}>
<img
id="treasure-map-img"
src="/images/map.svg" src="/images/map.svg"
alt="Treasure Map" alt="Treasure Map"
layout="fill" className={styles["map-image"]}
objectFit="contain"
onLoad={handleMapLoad}
onError={handleMapError}
ref={mapRef}
/> />
<div id="map-overlay-container" className={styles["map-overlay"]}>
{/* Render clue buttons conditionally */}
{renderClueButton(0, { left: "230px", top: "212px" })}
{renderClueButton(1, { left: "320px", top: "285px" })}
{renderClueButton(2, { left: "265px", top: "400px" })}
{renderClueButton(3, { left: "343px", top: "520px" })}
{renderClueButton(4, { left: "320px", top: "646px" })}
{renderClueButton(5, { left: "298px", top: "774px" })}
{renderClueButton(6, { left: "240px", top: "880px" })}
{renderClueButton(7, { left: "355px", top: "960px" })}
{renderClueButton(8, { left: "266px", top: "1037px" })}
{renderClueButton(9, { left: "280px", top: "1175px" })}
{renderClueButton(10, { left: "336px", top: "1303px" })}
{renderClueButton(11, { left: "250px", top: "1390px" })}
{renderClueButton(12, { left: "165px", top: "1485px" })}
{renderClueButton(13, { left: "305px", top: "1530px" })}
{renderClueButton(14, { left: "340px", top: "1650px" })}
{renderClueButton(15, { left: "225px", top: "1725px" })}
{renderClueButton(16, { left: "220px", top: "1820px" })}
{renderClueButton(17, { left: "275px", top: "1885px" })}
{renderClueButton(18, { left: "362px", top: "1917px" })}
{renderClueButton(19, { left: "300px", top: "2040px" })}
{/* Additional clue buttons can be added here when needed */}
</div>
</div>
</div> </div>
</div> </div>
+51 -44
View File
@@ -12,7 +12,6 @@ export default function StatsPage() {
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [teamStats, setTeamStats] = useState(null); const [teamStats, setTeamStats] = useState(null);
const [expanded, setExpanded] = useState(false); const [expanded, setExpanded] = useState(false);
const [huntActive, setHuntActive] = useState(null);
const router = useRouter(); const router = useRouter();
useEffect(() => { useEffect(() => {
@@ -24,34 +23,9 @@ export default function StatsPage() {
if (status === "authenticated") { if (status === "authenticated") {
fetchTeamStats(); fetchTeamStats();
checkHuntStatus();
} }
}, [status, router]); }, [status, router]);
// Check hunt status but don't redirect
const checkHuntStatus = async () => {
try {
const timestamp = Date.now();
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) {
const data = await response.json();
setHuntActive(data.active);
// We're just checking status, no redirect needed for stats page
}
} catch (err) {
console.error("Failed to check hunt status:", err);
}
};
const fetchTeamStats = async () => { const fetchTeamStats = async () => {
try { try {
setLoading(true); setLoading(true);
@@ -120,7 +94,6 @@ export default function StatsPage() {
{foundClues?.length > 0 ? ( {foundClues?.length > 0 ? (
foundClues.map((clue) => ( foundClues.map((clue) => (
<li key={clue.id} className="clue-item"> <li key={clue.id} className="clue-item">
<div className="clue-icon found">✓</div>
<div className="clue-details"> <div className="clue-details">
<div className="clue-title"> <div className="clue-title">
{clue.title || `Clue #${clue.id}`} {clue.title || `Clue #${clue.id}`}
@@ -142,8 +115,7 @@ export default function StatsPage() {
<ul className="clue-list"> <ul className="clue-list">
{skippedClues?.length > 0 ? ( {skippedClues?.length > 0 ? (
skippedClues.map((clue) => ( skippedClues.map((clue) => (
<li key={clue.id} className="clue-item"> <li key={clue.id} className="clue-item skipped-clue">
<div className="clue-icon skipped">↷</div>
<div className="clue-details"> <div className="clue-details">
<div className="clue-title"> <div className="clue-title">
{clue.title || `Clue #${clue.id}`} {clue.title || `Clue #${clue.id}`}
@@ -208,12 +180,6 @@ export default function StatsPage() {
<h2 className={styles.teamName}>{teamStats.team.name}</h2> <h2 className={styles.teamName}>{teamStats.team.name}</h2>
</div> </div>
{!huntActive && teamStats && (
<div className="hunt-inactive-banner">
<p>The treasure hunt is not currently active. Team progress will be visible here once the hunt begins.</p>
</div>
)}
<div className={styles.statsCard}> <div className={styles.statsCard}>
<div className={styles.summaryStats}> <div className={styles.summaryStats}>
<div className={styles.statItem}> <div className={styles.statItem}>
@@ -266,22 +232,63 @@ export default function StatsPage() {
<NavBar activeLink="stats" teamData={teamStats.team} /> <NavBar activeLink="stats" teamData={teamStats.team} />
<style jsx>{` <style jsx>{`
.clue-icon.found { .clues-section {
background-color: #2e7d32; padding: 10px 15px;
} }
.clue-icon.skipped { .section-title {
background-color: #1976d2; font-size: 16px;
margin: 15px 0 10px 0;
color: #444;
font-weight: 600;
} }
.hunt-inactive-banner { .clue-list {
background-color: #fff3cd; list-style: none;
color: #856404; padding: 0;
margin: 0 0 20px 0;
}
.clue-item {
padding: 12px 15px; padding: 12px 15px;
margin: 15px 20px 0; border-bottom: 1px solid #eee;
background-color: #f9f9f9;
margin-bottom: 5px;
border-radius: 4px; border-radius: 4px;
border-left: 3px solid #4caf50;
}
.skipped-clue {
border-left: 3px solid #2196f3;
}
.clue-details {
display: flex;
justify-content: space-between;
align-items: center;
}
.clue-title {
font-size: 14px;
color: #333;
flex: 1;
}
.clue-time {
font-size: 12px;
color: #666;
text-align: right;
margin-left: 10px;
white-space: nowrap;
}
.empty-state {
padding: 15px;
text-align: center; text-align: center;
font-size: 0.9rem; color: #888;
font-style: italic;
background-color: #f3f3f3;
border-radius: 4px;
} }
`}</style> `}</style>
</div> </div>
+4 -29
View File
@@ -3,6 +3,7 @@ import { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import Link from "next/link"; import Link from "next/link";
import NavBar from "@/components/NavBar";
export default function TeamPage({ params }) { export default function TeamPage({ params }) {
const { status, data: session } = useSession(); const { status, data: session } = useSession();
@@ -135,6 +136,7 @@ export default function TeamPage({ params }) {
} }
}, [effectiveTeamId, status, fetchTeamData, router]); }, [effectiveTeamId, status, fetchTeamData, router]);
// Add a function to properly handle the "Continue Hunt" button click
const continueTreasureHunt = async (e) => { const continueTreasureHunt = async (e) => {
e.preventDefault(); e.preventDefault();
setLoading(true); setLoading(true);
@@ -390,35 +392,8 @@ export default function TeamPage({ params }) {
</div> </div>
)} )}
<div className="nav-bar"> {/* Replace hardcoded navbar with NavBar component */}
<div className="nav-item"> <NavBar activeLink="team" teamData={team} />
<Link href="/map" className="nav-item">
<div className="nav-icon">🗺️</div>
<div className="nav-label">Map</div>
</Link>
</div>
<div className="nav-item">
<Link href="/stats" className="nav-item">
<div className="nav-icon">📊</div>
<div className="nav-label">Stats</div>
</Link>
</div>
<div className="nav-item">
<Link
href={teamData ? `/${teamData.id}` : "/team-selection"}
className="nav-item active"
>
<div className="nav-icon">👥</div>
<div className="nav-label">Team</div>
</Link>
</div>
<div className="nav-item">
<Link href="/leaderboard" className="nav-item">
<div className="nav-icon">🏆</div>
<div className="nav-label">Leaderboard</div>
</Link>
</div>
</div>
<style jsx>{` <style jsx>{`
.team-page { .team-page {
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -35,7 +35,7 @@ export default function NavBar({ activeLink, teamData }) {
checkHuntStatus(); checkHuntStatus();
}, []); }, []);
// Handle map link click - only redirect for map page // Handle map link click
const handleMapClick = (e) => { const handleMapClick = (e) => {
if (huntActive === false) { if (huntActive === false) {
e.preventDefault(); e.preventDefault();