Files
peworkshop/app/(main)/admin/page.js
T
bobbert 7d6b73ffb4 fixed user leaderboard. need to add features to admin leaderboard and fix timing issue on admin dashboard.
Grey = cant click
Red = current
Green = complete
blue = skipped?

Need to add Clue page Need to fix Leaderboard.
2025-03-15 17:31:39 +00:00

492 lines
13 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,
} 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 [elapsedTime, setElapsedTime] = useState(0); // in seconds
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 router = useRouter();
// Load timer status on page load
useEffect(() => {
async function loadTimerStatus() {
try {
setLoading(true);
const response = await fetch("/api/hunt/timer", {
credentials: "include",
headers: {
"Cache-Control": "no-cache",
},
});
const data = await response.json();
if (data.active) {
setTimerActive(true);
// Calculate elapsed time
if (data.startTime) {
// Store the start time in the centralized service
setHuntTimer(data.startTime, data.endTime);
// If there's an end time, set it
if (data.endTime) {
setTimerEndTime(new Date(data.endTime).getTime());
}
}
}
setLoading(false);
} catch (err) {
console.error("Failed to load timer status:", err);
setError("Failed to load timer status");
setLoading(false);
}
}
if (status === "authenticated") {
loadTimerStatus();
}
}, [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]);
// Timer update effect - use the centralized timer service
useEffect(() => {
let intervalId;
if (timerActive) {
// Use the existing timer data from the centralized service
intervalId = setInterval(() => {
const timerData = getHuntTimer();
if (timerData && timerData.startTime) {
// Format the elapsed time using the centralized service
const formattedTime = formatElapsedTime(timerData.startTime);
setTimerDisplay(formattedTime);
// If there's an end time, check if we've reached it
if (timerEndTime && Date.now() >= timerEndTime) {
stopTimer();
}
} else {
setTimerDisplay("--:--:--");
}
}, 1000);
} else {
setTimerDisplay("--:--:--");
}
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
}, [timerActive, timerEndTime]);
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,
}),
});
const data = await response.json();
if (data.success) {
setTimerActive(true);
if (endTime) {
setTimerEndTime(new Date(endTime).getTime());
} else {
setTimerEndTime(null);
}
// Update global timer data for all clients
setHuntTimer(data.startTime, data.endTime);
setError("");
} else {
setError(data.error || "Failed to start timer");
}
} catch (err) {
console.error("Failed to start timer:", err);
setError("Failed to start timer");
} 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" }),
});
const data = await response.json();
if (data.success) {
setTimerActive(false);
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");
} 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;
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>
);
}