Files
peworkshop/app/(main)/clue/[clueId]/page.js
T
bobbert 0afa6817a8 cannot fix issue with elapsed timer on admin dashboard. fixing issues with QR code editing.
Grey = cant click
Red = current
Green = complete
blue = skipped?
2025-03-15 20:01:51 +00:00

620 lines
17 KiB
JavaScript

"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { formatElapsedTime, getHuntTimer } from "@/utils/timerService";
import Link from "next/link";
import dynamic from "next/dynamic";
// Dynamically import QR scanner component with no SSR to avoid hydration issues
const QRScanner = dynamic(() => import("@/components/QRScanner"), {
ssr: false,
});
export default function CluePage({ params }) {
const [clue, setClue] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [foundNow, setFoundNow] = useState(false);
const [elapsedTime, setElapsedTime] = useState("00:00:00");
const [showScanner, setShowScanner] = useState(false);
const [scanResult, setScanResult] = useState(null);
const [scanMessage, setScanMessage] = useState(null);
const [lastRefresh, setLastRefresh] = useState(0); // Track last refresh time
const router = useRouter();
const { data: session, status } = useSession(); // Get session to check if user is admin
const { clueId } = params;
// Check if user is admin
const isAdmin = session?.user?.role === "admin";
// This effect handles authentication and initial clue data fetch
useEffect(() => {
let isMounted = true; // Flag to prevent state updates after unmount
const now = Date.now();
// Only allow refreshes every 10 seconds (more for admins)
const minRefreshInterval = isAdmin ? 30000 : 10000; // 30 seconds for admins, 10 seconds for regular users
// Skip if we refreshed too recently and this isn't the first load
if (loading === false && now - lastRefresh < minRefreshInterval) {
return;
}
if (status === "unauthenticated") {
router.push("/login");
return;
}
if (status === "loading") {
return;
}
// One-time fetch clue data with debouncing
async function fetchClue() {
try {
setLoading(true);
// Add timestamp to avoid browser caching
const timestamp = Date.now();
const response = await fetch(`/api/clues/${clueId}?t=${timestamp}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
},
credentials: "include",
});
if (!response.ok) {
if (response.status === 404) {
throw new Error("Clue not found");
} else {
const data = await response.json();
throw new Error(data.error || "Failed to fetch clue");
}
}
const data = await response.json();
// Only update state if the component is still mounted
if (isMounted) {
setClue(data);
// Only set foundNow on initial load or if it's actually newly found
if (loading === true) {
setFoundNow(data.foundNow);
}
setLoading(false);
setLastRefresh(Date.now()); // Update last refresh timestamp
}
} catch (err) {
console.error("Error fetching clue:", err);
if (isMounted) {
setError(err.message);
setLoading(false);
}
}
}
fetchClue();
// Cleanup function to prevent state updates after unmount
return () => {
isMounted = false;
};
}, [clueId, router, status, lastRefresh, loading, isAdmin]); // Add isAdmin and lastRefresh to dependencies
// Separate effect to handle timer updates - doesn't re-fetch data
useEffect(() => {
let timerId;
// Set up timer display updates
const timerData = getHuntTimer();
if (!timerData || !timerData.isActive) {
return;
}
// Initial set
setElapsedTime(formatElapsedTime(timerData.startTime));
// Update timer every second
timerId = setInterval(() => {
setElapsedTime(formatElapsedTime(timerData.startTime));
}, 1000);
return () => {
if (timerId) clearInterval(timerId);
};
}, []); // Empty dependency array so it only runs once
// Handle QR scan result
const handleScan = (data) => {
setScanResult(data);
setScanMessage(`QR Code scanned: ${data}`);
try {
// Handle both "QR123" format and just "123" format
let scannedClueId;
const match = data.match(/^QR(\d+)$/i);
if (match) {
// Extract the number from QR[number]
scannedClueId = parseInt(match[1], 10);
} else {
// Try to parse the raw value
scannedClueId = parseInt(data, 10);
}
if (!isNaN(scannedClueId) && scannedClueId === parseInt(clueId)) {
// Correct QR code scanned, mark as found and move to next clue
markClueAsFound(clueId);
} else {
setScanMessage(
"Incorrect QR code. Please scan the correct code for this clue."
);
}
} catch (err) {
setScanMessage("Invalid QR code format. Please try again.");
}
};
// Function to mark clue as found and navigate to the next clue
const markClueAsFound = async (currentClueId) => {
try {
// Mark the clue as found via API
const response = await fetch("/api/mark-clue", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ clueId: currentClueId }),
});
if (response.ok) {
// Success message
setScanMessage("Clue verified! Moving to the next clue...");
// Fetch all clues to find the next available one
const allCluesResponse = await fetch("/api/clues");
const allClues = await allCluesResponse.json();
// Find the current clue index
const currentIndex = allClues.findIndex(
(c) => c.id === parseInt(currentClueId)
);
if (currentIndex !== -1 && currentIndex < allClues.length - 1) {
// Navigate to the next clue after a brief delay
setTimeout(() => {
router.push(`/clue/${allClues[currentIndex + 1].id}`);
}, 1500);
} else {
// This was the last clue
setTimeout(() => {
router.push("/map");
}, 1500);
}
} else {
setScanMessage("Error verifying clue. Please try again.");
}
} catch (err) {
console.error("Error marking clue as found:", err);
setScanMessage("Error verifying clue. Please try again.");
}
};
// Function to handle skip button
const handleSkip = async () => {
// Fetch all clues to find the next one
try {
const response = await fetch("/api/clues");
const allClues = await response.json();
// Find the current clue index
const currentIndex = allClues.findIndex((c) => c.id === parseInt(clueId));
if (currentIndex !== -1 && currentIndex < allClues.length - 1) {
// Navigate to the next clue
router.push(`/clue/${allClues[currentIndex + 1].id}`);
} else {
// This was the last clue
router.push("/map");
}
} catch (err) {
console.error("Error skipping to next clue:", err);
setError("Failed to skip to next clue");
}
};
// Function for manual refresh - for admins to test without waiting
const handleManualRefresh = () => {
// Force a refresh by setting lastRefresh to 0
setLastRefresh(0);
};
if (loading) {
return (
<div className="clue-container">
<div className="loading">
<div className="loading-spinner"></div>
<p>Loading clue...</p>
</div>
</div>
);
}
if (error) {
return (
<div className="clue-container">
<div className="error">Error: {error}</div>
<div className="nav-buttons">
<button onClick={() => router.push("/map")} className="map-button">
Back to Map
</button>
<button onClick={() => router.push("/")} className="home-button">
Back to Home
</button>
</div>
</div>
);
}
if (!clue) {
return (
<div className="clue-container">
<div className="not-found">Clue not found</div>
<div className="nav-buttons">
<button onClick={() => router.push("/map")} className="map-button">
Back to Map
</button>
<button onClick={() => router.push("/")} className="home-button">
Back to Home
</button>
</div>
</div>
);
}
return (
<div className="clue-container">
<div className="timer-display">{elapsedTime}</div>
<div className="clue-content-wrapper">
{/* Admin tools section - only visible to admins */}
{isAdmin && (
<div className="admin-tools">
<div className="admin-badge">Admin View</div>
<button
onClick={handleManualRefresh}
className="admin-refresh-button"
>
Refresh Clue Data
</button>
</div>
)}
{/* QR Scanner Section */}
<div className="scanner-section">
<h2>Scan QR Code</h2>
<QRScanner onScan={handleScan} width={280} height={280} />
{scanMessage && <div className="scan-message">{scanMessage}</div>}
</div>
{/* Clue Information Section */}
<div className="clue-scroll">
{foundNow && (
<div className="new-discovery">
<div className="discovery-icon">🎉</div>
<div className="discovery-text">New Clue Discovered!</div>
</div>
)}
<h1 className="clue-title">{clue.title}</h1>
<div className="clue-content">
<h2>Description</h2>
<p className="clue-description">{clue.description}</p>
{clue.location && (
<div className="clue-location">
<h2>Location Hint</h2>
<p>{clue.location}</p>
</div>
)}
</div>
</div>
{/* Action Buttons */}
<div className="action-buttons">
<button onClick={handleSkip} className="skip-button">
Skip
</button>
<button onClick={() => setShowScanner(true)} className="scan-button">
Scan Clue
</button>
</div>
</div>
{/* Bottom Navigation */}
<div className="nav-bar">
<Link href="/map" className="nav-item">
<div className="nav-icon">🗺️</div>
<div className="nav-label">Map</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">
<div className="nav-icon">👥</div>
<div className="nav-label">Team</div>
</Link>
<Link href="/" className="nav-item">
<div className="nav-icon">🏠</div>
<div className="nav-label">Home</div>
</Link>
</div>
<style jsx>{`
.clue-container {
display: flex;
flex-direction: column;
min-height: 100vh;
background-color: #f4f1ea;
padding: 20px;
padding-bottom: 70px; /* Space for bottom navbar */
position: relative;
}
.clue-content-wrapper {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
max-width: 600px;
margin: 0 auto;
}
.timer-display {
position: absolute;
top: 15px;
right: 15px;
background-color: rgba(0, 0, 0, 0.1);
padding: 5px 10px;
border-radius: 5px;
font-family: monospace;
font-weight: bold;
font-size: 1rem;
z-index: 10;
}
.scanner-section {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 20px;
background-color: white;
border-radius: 10px;
padding: 15px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.scanner-section h2 {
margin-top: 0;
margin-bottom: 15px;
color: #68543c;
}
.scan-message {
margin-top: 10px;
padding: 8px;
background-color: #e8f5e9;
border-radius: 4px;
text-align: center;
width: 100%;
}
.clue-scroll {
background-color: #f8f3e3;
border-radius: 10px;
padding: 20px;
width: 100%;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
position: relative;
margin-bottom: 20px;
border: 1px dashed #9c6b30;
}
h2 {
color: #9c6b30;
font-size: 1.5rem;
margin-top: 10px;
margin-bottom: 15px;
}
.clue-description {
font-size: 1.1rem;
line-height: 1.5;
color: #5d4037;
margin-bottom: 20px;
}
.clue-location {
margin-top: 20px;
padding-top: 15px;
border-top: 1px dashed #9c6b30;
}
.action-buttons {
display: flex;
justify-content: space-between;
width: 100%;
margin-top: 10px;
margin-bottom: 20px;
}
.skip-button,
.scan-button {
padding: 12px 0;
border: none;
border-radius: 5px;
cursor: pointer;
font-weight: bold;
transition: all 0.2s;
width: 48%;
font-size: 16px;
}
.skip-button {
background-color: #a98467;
color: white;
}
.scan-button {
background-color: #68543c;
color: white;
}
.skip-button:hover,
.scan-button:hover {
opacity: 0.9;
}
.loading,
.error,
.not-found {
text-align: center;
padding: 30px;
}
.loading-spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #9c6b30;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto 20px;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.error {
color: #d32f2f;
}
.clue-title {
color: #68543c;
font-size: 1.8rem;
text-align: center;
margin-bottom: 20px;
border-bottom: 2px solid #9c6b30;
padding-bottom: 10px;
}
.new-discovery {
background-color: #feefb3;
border: 1px solid #9f6000;
color: #9f6000;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
display: flex;
align-items: center;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.7;
}
100% {
opacity: 1;
}
}
.discovery-icon {
font-size: 1.5rem;
margin-right: 10px;
}
.discovery-text {
font-weight: bold;
}
.nav-bar {
display: flex;
justify-content: space-around;
background-color: white;
border-top: 1px solid #ddd;
padding: 10px 0;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
z-index: 10;
}
.nav-item {
display: flex;
flex-direction: column;
align-items: center;
text-decoration: none;
color: #666;
flex: 1;
}
.nav-icon {
font-size: 24px;
margin-bottom: 4px;
}
.nav-label {
font-size: 12px;
}
/* Admin tools styling */
.admin-tools {
background-color: #f8d7da;
border: 2px dashed #d9534f;
border-radius: 8px;
padding: 12px;
margin-bottom: 15px;
text-align: center;
width: 100%;
}
.admin-badge {
font-weight: bold;
margin-bottom: 8px;
color: #d9534f;
}
.admin-refresh-button {
background-color: #d9534f;
color: white;
border: none;
border-radius: 4px;
padding: 8px 16px;
cursor: pointer;
font-size: 14px;
}
.admin-refresh-button:hover {
background-color: #c9302c;
}
`}</style>
</div>
);
}