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

615 lines
17 KiB
JavaScript

"use client";
import { useState, useEffect, useRef } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import {
setHuntTimer,
clearHuntTimer,
getHuntTimer,
formatElapsedTime,
syncTimerWithServer,
} from "@/utils/timerService";
export default function AdminDashboard() {
const { data: session, status } = useSession();
const [timerActive, setTimerActive] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [timerDisplay, setTimerDisplay] = useState("--:--:--");
const [presetHours, setPresetHours] = useState("");
const [presetMinutes, setPresetMinutes] = useState("");
const [presetSeconds, setPresetSeconds] = useState("");
const [timerEndTime, setTimerEndTime] = useState(null);
const timerRef = useRef(null);
const timerIntervalRef = useRef(null);
const timerStartTimeRef = useRef(null); // New ref to store the start time
const router = useRouter();
// Load timer status on page load
useEffect(() => {
async function loadTimerStatus() {
try {
setLoading(true);
// First, check if we already have timer data in localStorage
const existingTimer = getHuntTimer();
if (existingTimer && existingTimer.startTime) {
// Store the start time in the ref to prevent it from being lost on re-renders
timerStartTimeRef.current = existingTimer.startTime;
// If we have timer data, immediately set the display
setTimerActive(existingTimer.isActive !== false);
setTimerDisplay(formatElapsedTime(existingTimer.startTime));
if (existingTimer.endTime) {
setTimerEndTime(new Date(existingTimer.endTime).getTime());
}
}
// Then, fetch fresh data from the server to ensure we're in sync
const response = await fetch("/api/hunt/timer", {
credentials: "include",
headers: {
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
},
});
if (!response.ok) {
throw new Error(`Server responded with status: ${response.status}`);
}
const data = await response.json();
// Check both activity indicators to handle cases where they might be inconsistent
const isActive = data.active || data.timerActive;
if (isActive && data.startTime) {
setTimerActive(true);
// Store the start time in the ref for persistence across renders
timerStartTimeRef.current = data.startTime;
// Store the start time in the centralized service
setHuntTimer(data.startTime, data.endTime, true); // Explicitly set isActive=true
// Update the display immediately with the correct time
setTimerDisplay(formatElapsedTime(data.startTime));
if (data.endTime) {
setTimerEndTime(new Date(data.endTime).getTime());
} else {
setTimerEndTime(null);
}
} else {
// Only clear local timer if server explicitly says timer is not active
if (data.active === false && data.timerActive === false) {
clearHuntTimer();
timerStartTimeRef.current = null; // Clear the start time ref
setTimerActive(false);
setTimerDisplay("--:--:--");
setTimerEndTime(null);
}
}
setLoading(false);
} catch (err) {
console.error("Failed to load timer status:", err);
setError(`Failed to load timer status: ${err.message}`);
setLoading(false);
}
}
if (status === "authenticated") {
loadTimerStatus();
}
// Clear interval when component unmounts
return () => {
if (timerIntervalRef.current) {
clearInterval(timerIntervalRef.current);
timerIntervalRef.current = null;
}
};
}, [status]);
// Check if user is admin
useEffect(() => {
if (status === "authenticated") {
if (session?.user?.role !== "admin") {
router.push("/team-selection");
}
} else if (status === "unauthenticated") {
router.push("/login");
}
}, [session, status, router]);
// Create a separate effect for updating the timer display - but only have one instance
useEffect(() => {
// Clear any existing interval to avoid duplicates
if (timerIntervalRef.current) {
clearInterval(timerIntervalRef.current);
timerIntervalRef.current = null;
}
const updateTimer = () => {
// Use the ref to access the persisted start time
const startTime = timerStartTimeRef.current;
if (timerActive && startTime) {
// Format time using the start time from our ref, which persists across renders
setTimerDisplay(formatElapsedTime(startTime));
// Check if timer has ended
if (timerEndTime && Date.now() >= timerEndTime) {
stopTimer();
}
} else if (timerActive) {
// If timer is active but no data, try to restore
syncTimerWithServer().then((result) => {
if (result.success && result.data) {
timerStartTimeRef.current = result.data.startTime;
}
});
} else {
setTimerDisplay("--:--:--");
}
};
// Initial update
updateTimer();
// Set up interval for timer updates
if (timerActive) {
timerIntervalRef.current = setInterval(updateTimer, 1000);
}
return () => {
if (timerIntervalRef.current) {
clearInterval(timerIntervalRef.current);
timerIntervalRef.current = null;
}
};
}, [timerActive, timerEndTime]); // Include timerEndTime as a dependency
// Add a function to fetch timer status directly from the server
const fetchTimerStatusFromServer = async () => {
try {
const response = await fetch("/api/hunt/timer", {
credentials: "include",
headers: {
"Cache-Control": "no-cache, no-store, must-revalidate",
Pragma: "no-cache",
},
});
if (!response.ok) {
console.error("Server responded with status:", response.status);
return;
}
const data = await response.json();
// Check both activity indicators for consistency
const isActive = data.active || data.timerActive;
if (isActive && data.startTime) {
setTimerActive(true);
timerStartTimeRef.current = data.startTime; // Update the ref
setHuntTimer(data.startTime, data.endTime);
if (data.endTime) {
setTimerEndTime(new Date(data.endTime).getTime());
} else {
setTimerEndTime(null);
}
setTimerDisplay(formatElapsedTime(data.startTime));
} else if (data.active === false && data.timerActive === false) {
// Only clear timer if server explicitly says timer is inactive
setTimerActive(false);
timerStartTimeRef.current = null; // Clear the ref
clearHuntTimer();
setTimerDisplay("--:--:--");
}
} catch (err) {
console.error("Error fetching timer status:", err);
}
};
const startTimer = async (preset = false) => {
setLoading(true);
try {
let endTime = null;
// If using preset, calculate the end time
if (preset) {
const hours = parseInt(presetHours || "0");
const minutes = parseInt(presetMinutes || "0");
const seconds = parseInt(presetSeconds || "0");
// Validate input
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
setError(
"Please enter valid numbers for hours, minutes, and seconds"
);
setLoading(false);
return;
}
// Calculate total duration in milliseconds
const durationMs = (hours * 3600 + minutes * 60 + seconds) * 1000;
if (durationMs <= 0) {
setError("Please enter a duration greater than zero");
setLoading(false);
return;
}
// Set end time
endTime = new Date(Date.now() + durationMs).toISOString();
}
// API call to start timer
const response = await fetch("/api/hunt/timer", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
action: "start",
endTime: endTime,
}),
});
if (!response.ok) {
throw new Error(`Server responded with status: ${response.status}`);
}
const data = await response.json();
if (data.success) {
setTimerActive(true);
// Store the start time in the ref
timerStartTimeRef.current = data.startTime;
if (endTime) {
setTimerEndTime(new Date(endTime).getTime());
} else {
setTimerEndTime(null);
}
// Update global timer data for all clients
setHuntTimer(data.startTime, data.endTime);
// Immediately display the current elapsed time
setTimerDisplay(formatElapsedTime(data.startTime));
setError("");
} else {
setError(data.error || "Failed to start timer");
}
} catch (err) {
console.error("Failed to start timer:", err);
setError(`Failed to start timer: ${err.message}`);
} finally {
setLoading(false);
}
};
const stopTimer = async () => {
setLoading(true);
try {
const response = await fetch("/api/hunt/timer", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ action: "stop" }),
});
if (!response.ok) {
throw new Error(`Server responded with status: ${response.status}`);
}
const data = await response.json();
if (data.success) {
setTimerActive(false);
timerStartTimeRef.current = null; // Clear the ref
setTimerEndTime(null);
setTimerDisplay("--:--:--");
// Clear timer data for all clients
clearHuntTimer();
} else {
setError(data.error || "Failed to stop timer");
}
} catch (err) {
console.error("Failed to stop timer:", err);
setError(`Failed to stop timer: ${err.message}`);
} finally {
setLoading(false);
}
};
const startPresetTimer = () => {
startTimer(true);
};
// Handle access denied and loading states
if (status === "loading" || loading) {
return <div className="admin-page loading">Loading...</div>;
}
if (status === "unauthenticated") {
return null; // Will redirect via useEffect
}
if (session?.user?.role !== "admin") {
return null; // Will redirect via useEffect
}
return (
<div className="admin-page">
<div className="page-header">
<div className="page-title">Admin Dashboard</div>
<div className="placeholder"></div>
</div>
<div className="admin-content">
<div className="timer-display-container">
<h2>Hunt Timer</h2>
<div className="timer-display">{timerDisplay}</div>
<div className="timer-controls">
<button
className="admin-button"
onClick={stopTimer}
disabled={!timerActive || loading}
>
Stop Timer
</button>
<button
className="admin-button"
onClick={() => startTimer(false)}
disabled={timerActive || loading}
>
Start Timer
</button>
</div>
<div className="preset-timer-container">
<h3>Set Timer Duration</h3>
<div className="preset-inputs">
<div className="time-input">
<label>Hours</label>
<input
type="number"
min="0"
value={presetHours}
onChange={(e) => setPresetHours(e.target.value)}
disabled={timerActive || loading}
className="admin-input"
/>
</div>
<div className="time-input">
<label>Minutes</label>
<input
type="number"
min="0"
max="59"
value={presetMinutes}
onChange={(e) => setPresetMinutes(e.target.value)}
disabled={timerActive || loading}
className="admin-input"
/>
</div>
<div className="time-input">
<label>Seconds</label>
<input
type="number"
min="0"
max="59"
value={presetSeconds}
onChange={(e) => setPresetSeconds(e.target.value)}
disabled={timerActive || loading}
className="admin-input"
/>
</div>
</div>
<button
className="admin-button"
onClick={startPresetTimer}
disabled={timerActive || loading}
>
Start Preset Timer
</button>
</div>
{error && <p className="error-message">{error}</p>}
</div>
</div>
{/* Admin Navigation Bar */}
<div className="admin-nav-bar">
<button
className="admin-nav-button active"
onClick={() => router.push("/admin")}
>
<div className="admin-nav-icon">⏱️</div>
<div className="admin-nav-label">Timer</div>
</button>
<button
className="admin-nav-button"
onClick={() => router.push("/admin/clues")}
>
<div className="admin-nav-icon">📝</div>
<div className="admin-nav-label">Clues</div>
</button>
<button
className="admin-nav-button"
onClick={() => router.push("/admin/leaderboard")}
>
<div className="admin-nav-icon">🏆</div>
<div className="admin-nav-label">Leaderboard</div>
</button>
</div>
<style jsx>{`
.admin-page {
display: flex;
flex-direction: column;
min-height: 100vh;
background-color: #f4e9dc;
}
.page-header {
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
background-color: #68543c;
color: white;
}
.page-title {
font-size: 1.2rem;
font-weight: 600;
}
.placeholder {
width: 40px;
display: none;
}
.admin-content {
flex: 1;
padding: 1rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding-bottom: 70px; /* Add space for the navbar */
}
.timer-display-container {
width: 100%;
max-width: 500px;
background-color: white;
border-radius: 8px;
padding: 2rem;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
.timer-display {
font-size: 3rem;
font-weight: 700;
font-family: monospace;
padding: 1.5rem 0;
}
.timer-controls {
display: flex;
gap: 1rem;
margin-bottom: 2rem;
}
.admin-button {
background-color: #68543c;
color: white;
border: none;
border-radius: 4px;
padding: 0.75rem 1rem;
font-size: 1rem;
cursor: pointer;
flex: 1;
}
.admin-button:disabled {
background-color: #d0c8c0;
cursor: not-allowed;
}
.preset-timer-container {
margin-top: 1.5rem;
padding-top: 1.5rem;
border-top: 1px solid #eee;
}
.preset-inputs {
display: flex;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1rem;
}
.time-input {
flex: 1;
display: flex;
flex-direction: column;
}
.admin-input {
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
text-align: center;
}
.error-message {
color: red;
margin-top: 1rem;
}
/* Admin Navigation Bar Styles */
.admin-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%;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
z-index: 100;
}
.admin-nav-button {
display: flex;
flex-direction: column;
align-items: center;
background: transparent;
border: none;
padding: 8px 0;
flex: 1;
cursor: pointer;
color: #666;
transition: all 0.2s ease;
}
.admin-nav-button.active {
color: #68543c;
font-weight: bold;
}
.admin-nav-button:hover {
background-color: rgba(104, 84, 60, 0.1);
}
.admin-nav-icon {
font-size: 24px;
margin-bottom: 4px;
}
.admin-nav-label {
font-size: 13px;
}
`}</style>
</div>
);
}