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

624 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";
import { use } from "react";
import QRCodeHelper from "@/components/QRCodeHelper";
// Dynamically import the new QR scanner component with no SSR
const EnhancedQRScanner = dynamic(
() => import("@/components/EnhancedQRScanner"),
{
ssr: false,
loading: () => <div className="scanner-loading">Loading scanner...</div>,
}
);
export default function CluePage({ params }) {
// Unwrap params properly using use() from React
const unwrappedParams = use(params);
const clueId = unwrappedParams.clueId;
const [clue, setClue] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [elapsedTime, setElapsedTime] = useState("00:00:00");
const [scanMessage, setScanMessage] = useState(null);
const [lastRefresh, setLastRefresh] = useState(0);
const [clueFound, setClueFound] = useState(false);
const [allClues, setAllClues] = useState([]);
const [nextClueId, setNextClueId] = useState(null);
const router = useRouter();
const { data: session, status } = useSession();
// Check if user is admin
const isAdmin = session?.user?.role === "admin";
// This effect handles authentication and initial clue data fetch
useEffect(() => {
let isMounted = true;
const now = Date.now();
const minRefreshInterval = isAdmin ? 30000 : 10000;
// 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;
}
// Fetch all clues to get navigation context
const fetchAllClues = async () => {
try {
const response = await fetch("/api/clues");
if (!response.ok) return [];
const data = await response.json();
if (isMounted) {
setAllClues(data);
// Find next clue for navigation
const currentIndex = data.findIndex((c) => c.id === parseInt(clueId));
if (currentIndex !== -1 && currentIndex < data.length - 1) {
setNextClueId(data[currentIndex + 1].id);
}
}
return data;
} catch (err) {
console.error("Error fetching all clues:", err);
return [];
}
};
// Fetch current clue details
async function fetchClue() {
try {
setLoading(true);
await fetchAllClues();
// 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();
if (isMounted) {
setClue(data);
setClueFound(data.found);
setLoading(false);
setLastRefresh(Date.now());
}
} catch (err) {
console.error("Error fetching clue:", err);
if (isMounted) {
setError(err.message);
setLoading(false);
}
}
}
fetchClue();
return () => {
isMounted = false;
};
}, [clueId, router, status, lastRefresh, loading, isAdmin]);
// Separate effect to handle timer updates
useEffect(() => {
let timerId;
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);
};
}, []);
// Handle QR scan result
const handleScan = (data) => {
setScanMessage(`QR Code scanned: ${data}`);
try {
// Handle multiple QR code formats: "QR123", "123", or even "Clue 123"
let scannedClueId;
// Try regex patterns
const qrPattern = /^QR[^0-9]*(\d+)$/i;
const cluePattern = /^clue[^0-9]*(\d+)$/i;
const numberPattern = /^(\d+)$/;
let match =
data.match(qrPattern) ||
data.match(cluePattern) ||
data.match(numberPattern);
if (match) {
scannedClueId = parseInt(match[1], 10);
} else {
// Try direct parsing as a last resort
scannedClueId = parseInt(data, 10);
}
if (!isNaN(scannedClueId) && scannedClueId === parseInt(clueId)) {
// Correct QR code scanned, mark as found
setScanMessage("✓ Correct QR code found!");
markClueAsFound(clueId);
} else if (!isNaN(scannedClueId)) {
setScanMessage(
`QR code for clue ${scannedClueId} scanned, but you need clue ${clueId}. Please scan the correct code.`
);
} else {
setScanMessage(
"Couldn't recognize this QR code. Please scan the correct code for this clue."
);
}
} catch (err) {
console.error("Error processing scan result:", err);
setScanMessage("Invalid QR code format. Please try again.");
}
};
// Function to mark clue as found via API
const markClueAsFound = async (currentClueId) => {
try {
// Only proceed if the clue isn't already found
if (clueFound) {
setScanMessage("You've already found this clue!");
return;
}
// 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) {
// Update local state to show clue is found
setClueFound(true);
setScanMessage(
"✅ Clue verified! You can now proceed to the next clue."
);
} 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.");
}
};
// Navigate to the next clue
const handleNextClue = () => {
if (nextClueId) {
router.push(`/clue/${nextClueId}`);
} else {
router.push("/map");
}
};
// Navigate to the previous clue
const handlePrevClue = () => {
if (allClues.length > 0) {
const currentIndex = allClues.findIndex((c) => c.id === parseInt(clueId));
if (currentIndex > 0) {
router.push(`/clue/${allClues[currentIndex - 1].id}`);
} else {
router.push("/map");
}
} else {
router.push("/map");
}
};
// Function for manual refresh - for admins to test without waiting
const handleManualRefresh = () => {
setLastRefresh(0);
};
// Rendering states
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 - Removed manual entry button */}
<div className="scanner-section">
<h2>Scan QR Code</h2>
<EnhancedQRScanner onScan={handleScan} width={280} height={280} />
{scanMessage && (
<div className={`scan-message ${clueFound ? "success" : ""}`}>
{scanMessage}
</div>
)}
{/* Add the QR Code helper component */}
<QRCodeHelper clueId={clueId} />
</div>
{/* Clue Information Section */}
<div className="clue-scroll">
<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>
{/* Navigation Buttons */}
<div className="navigation-buttons">
<button onClick={handlePrevClue} className="nav-button prev-button">
Previous Clue
</button>
<button
onClick={() => router.push("/map")}
className="nav-button map-button"
>
Back to Map
</button>
<button onClick={handleNextClue} className="nav-button next-button">
Next 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="/stats" 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%;
}
.scan-message.success {
background-color: #c8e6c9;
color: #2e7d32;
font-weight: bold;
}
.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;
}
.navigation-buttons {
display: flex;
justify-content: space-between;
width: 100%;
margin-top: 20px;
margin-bottom: 20px;
flex-wrap: wrap; /* Allow buttons to wrap on small screens */
gap: 10px;
}
.nav-button {
padding: 12px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
font-weight: bold;
transition: all 0.2s;
font-size: 14px;
flex: 1;
min-width: 120px;
}
.prev-button {
background-color: #a98467;
color: white;
}
.map-button {
background-color: #607d8b;
color: white;
}
.next-button {
background-color: #68543c;
color: white;
}
.nav-button:hover {
opacity: 0.9;
transform: translateY(-2px);
}
.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;
}
.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 {
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>
);
}