Better bracket logic

This commit is contained in:
2026-02-14 01:04:54 +01:00 Verified
parent 87d3ea5ef0
commit 7b878b3abe
32 changed files with 1326 additions and 1348 deletions
-46
View File
@@ -1,46 +0,0 @@
/* frontend/src/App.css */
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
+9 -4
View File
@@ -1,23 +1,28 @@
// frontend/src/App.jsx
import React, { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import Layout from './components/Layout/Layout';
import Dashboard from './pages/Dashboard';
import TournamentPage from './pages/TournamentPage';
import Login from './pages/Login';
import Tournament from './pages/Tournament';
export default function App() {
const [darkMode, setDarkMode] = useState(() => localStorage.theme === 'dark');
useEffect(() => {
const root = window.document.documentElement;
const body = window.document.body;
if (darkMode) {
root.classList.add('dark');
localStorage.setItem('theme', 'dark');
root.style.backgroundColor = '#09090b'; // zinc-950
body.style.backgroundColor = '#09090b';
} else {
root.classList.remove('dark');
localStorage.setItem('theme', 'light');
root.style.backgroundColor = '#fafafa'; // zinc-50
body.style.backgroundColor = '#fafafa';
}
}, [darkMode]);
@@ -29,7 +34,7 @@ export default function App() {
{/* Main App Layout */}
<Route element={<Layout darkMode={darkMode} setDarkMode={setDarkMode} />}>
<Route path="/" element={<Dashboard />} />
<Route path="/tournaments/:id" element={<TournamentPage />} />
<Route path="/tournaments/:id" element={<Tournament />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
@@ -1,99 +0,0 @@
// frontend/src/components/Bracket/BracketNode.jsx
import React, { useState } from 'react';
import clsx from 'clsx';
import ScoreModal from '../Tournament/ScoreModal';
export default function BracketNode({ node, tournamentId, isAdmin, isFinal }) {
const [showScore, setShowScore] = useState(false);
const match = node.match;
// Display Logic
const p1 = node.p1_team;
const p2 = node.p2_team;
const isBye = !p2 && node.round_number === 1; // Simplistic BYE detection
// Don't show score modal if it's not a real match
const canInteract = match && !isBye;
return (
<>
<div
className={clsx(
"relative w-64 bg-white dark:bg-zinc-900 rounded-lg border shadow-sm transition-all overflow-hidden group",
match?.winner_team_id ? "border-orange-500/50 dark:border-orange-500/50" : "border-zinc-300 dark:border-zinc-800",
canInteract ? "cursor-pointer hover:border-orange-500 hover:shadow-md" : "opacity-80"
)}
onClick={() => canInteract && setShowScore(true)}
>
{/* Anchors for Lines */}
<div id={`node-left-${node.id}`} className="absolute top-1/2 -left-1 w-1 h-1" />
<div id={`node-right-${node.id}`} className="absolute top-1/2 -right-1 w-1 h-1" />
{/* Header */}
<div className="flex justify-between items-center px-3 py-1.5 bg-zinc-50 dark:bg-zinc-950/50 border-b border-zinc-200 dark:border-zinc-800">
<div className="flex items-center gap-2">
<span className="text-[9px] font-black text-zinc-400">#{node.display_number}</span>
{node.match?.court && (
<span className="text-[8px] font-bold text-white px-1.5 py-0.5 rounded bg-[#0891b2] uppercase tracking-wider">
{node.match.court.name}
</span>
)}
</div>
<div className="text-[9px] font-bold text-zinc-500 font-mono">
{new Date(node.match?.start_time || node.planned_start_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</div>
</div>
{/* Teams */}
<div className="p-2 space-y-1">
{/* P1 Row */}
<div className="flex justify-between items-center px-1 rounded hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition">
<span className={clsx(
"text-xs font-bold uppercase truncate max-w-[180px]",
match?.winner_team_id && match.winner_team_id === p1?.id ? "text-orange-600 dark:text-orange-500" : "text-zinc-700 dark:text-zinc-300",
!p1 && "text-zinc-400 italic font-medium"
)}>
{p1 ? p1.name : (node.source_p1_type ? 'TBD' : 'Bye')}
</span>
{match && <span className="text-[10px] font-mono font-black text-zinc-400 dark:text-zinc-600 bg-zinc-100 dark:bg-zinc-800 px-1.5 rounded">{getWinCount(match, p1?.id)}</span>}
</div>
{/* P2 Row */}
<div className="flex justify-between items-center px-1 rounded hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition">
<span className={clsx(
"text-xs font-bold uppercase truncate max-w-[180px]",
match?.winner_team_id && match.winner_team_id === p2?.id ? "text-orange-600 dark:text-orange-500" : "text-zinc-700 dark:text-zinc-300",
!p2 && "text-zinc-400 italic font-medium"
)}>
{p2 ? p2.name : (node.source_p2_type ? 'TBD' : 'Bye')}
</span>
{match && <span className="text-[10px] font-mono font-black text-zinc-400 dark:text-zinc-600 bg-zinc-100 dark:bg-zinc-800 px-1.5 rounded">{getWinCount(match, p2?.id)}</span>}
</div>
</div>
</div>
{match && (
<ScoreModal
isOpen={showScore}
onClose={() => setShowScore(false)}
match={match}
tournamentId={tournamentId}
isAdmin={isAdmin}
p1Name={p1?.name || 'TBD'}
p2Name={p2?.name || 'TBD'}
/>
)}
</>
);
}
function getWinCount(match, teamId) {
if (!match.sets || !teamId) return 0;
let wins = 0;
match.sets.forEach(s => {
if (teamId === match.p1_team_id && s.p1 > s.p2) wins++;
if (teamId === match.p2_team_id && s.p2 > s.p1) wins++;
});
return wins;
}
+100 -103
View File
@@ -1,142 +1,139 @@
// frontend/src/components/Bracket/BracketView.jsx
import { Check, Trophy } from 'lucide-react';
import { useEffect, useRef } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { Check } from 'lucide-react';
import { stringToColor } from '../../utils/helpers';
// --- EXACT COPY OF YOUR OLD MATCHCARD (Adapted data props) ---
const MatchCard = ({ node, onClick }) => {
// GHOST NODE LOGIC: If no display number, it's a structural/hidden node
if (!node.display_number) return <div id={`node-${node.id}`} className="hidden" />;
const MatchCard = ({ match, onClick }) => {
const isFinished = match.status === "Finished";
const badgeColor = match.time ? stringToColor(match.court) : null;
const match = node.match;
const p1 = node.p1_team;
const p2 = node.p2_team;
let borderClass = 'border-zinc-300 dark:border-zinc-700';
if (isFinished) borderClass = 'border-orange-500 ring-2 ring-orange-500/10';
// Old logic: "isPending" means we don't have two players yet
const isPending = !p1 || !p2;
const badgeColor = match?.court ? stringToColor(match.court.name) : null;
const timeDisplay = match?.start_time || node.planned_start_time;
const canInteract = match.hasTeams;
// Calculate wins for display
const getWins = (teamId) => {
if (!match?.sets) return 0;
return match.sets.reduce((acc, s) => acc + (s.p1 > s.p2 && match.p1_team_id === teamId ? 1 : (s.p2 > s.p1 && match.p2_team_id === teamId ? 1 : 0)), 0);
}
const p1Wins = p1 ? getWins(p1.id) : 0;
const p2Wins = p2 ? getWins(p2.id) : 0;
const winnerId = match?.winner_team_id;
const cursorClass = canInteract
? 'cursor-pointer hover:shadow-md hover:-translate-y-0.5'
: 'cursor-default opacity-100';
return (
<div
id={`node-${node.id}`}
onClick={() => !isPending && onClick(node)}
className={`w-64 bg-white dark:bg-zinc-900 rounded-xl border-2 ${winnerId ? 'border-orange-500 ring-4 ring-orange-500/10' : 'border-zinc-300 dark:border-zinc-800'} shadow-sm ${!isPending ? 'cursor-pointer hover:-translate-y-1 transition duration-200 group' : 'opacity-80 cursor-default'} overflow-hidden transition-all`}
id={`match-${match.id}`}
onClick={() => canInteract && onClick(match)}
className={`w-64 bg-white dark:bg-zinc-900 rounded-lg border ${borderClass} shadow-sm transition-all duration-200 relative z-10 flex flex-col ${cursorClass}`}
>
{/* Header */}
<div className="bg-zinc-50 dark:bg-zinc-950/50 px-3 py-2 flex justify-between items-center border-b border-zinc-200 dark:border-zinc-800">
<div className="bg-zinc-50 dark:bg-zinc-900/50 px-3 py-2 flex justify-between items-center border-b border-zinc-200 dark:border-zinc-800 rounded-t-lg">
<div className="flex items-center gap-2">
<span className="font-mono text-[10px] font-black text-zinc-500 dark:text-zinc-500 uppercase"># {node.display_number}</span>
{match?.court && <span className="text-[9px] font-black text-white px-1.5 py-0.5 rounded uppercase" style={{ background: badgeColor }}>{match.court.name}</span>}
<span className="font-mono text-[10px] font-bold text-zinc-400"># {match.number}</span>
{match.time && <span className="text-[9px] font-black text-white px-1.5 py-0.5 rounded-sm uppercase" style={{ background: badgeColor }}>{match.court}</span>}
</div>
{winnerId ? <Check className="text-orange-500" size={14} strokeWidth={4} /> : <span className="text-[10px] font-black text-zinc-800 dark:text-zinc-300 font-mono">{timeDisplay ? new Date(timeDisplay).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : 'TBD'}</span>}
{isFinished ? <Check className="text-orange-500" size={14} strokeWidth={3} /> : <span className="text-[10px] font-bold text-zinc-500 font-mono">{match.time || 'TBD'}</span>}
</div>
{/* Content */}
<div className="p-3 space-y-1.5">
{/* P1 */}
<div className={`flex justify-between items-center ${winnerId === p1?.id ? 'text-orange-600 dark:text-orange-500 font-black' : 'text-zinc-900 dark:text-zinc-400 font-bold'}`}>
<span className="truncate text-xs uppercase tracking-tight font-bold">{p1 ? p1.name : (node.source_p1_type ? 'TBD' : 'Bye')}</span>
<span className="bg-zinc-100 dark:bg-zinc-800 px-2 py-0.5 rounded text-[10px] font-black">{p1Wins}</span>
</div>
{/* P2 */}
<div className={`flex justify-between items-center ${winnerId === p2?.id ? 'text-orange-600 dark:text-orange-500 font-black' : 'text-zinc-900 dark:text-zinc-400 font-bold'}`}>
<span className="truncate text-xs uppercase tracking-tight font-bold">{p2 ? p2.name : (node.source_p2_type ? 'TBD' : 'Bye')}</span>
<span className="bg-zinc-100 dark:bg-zinc-800 px-2 py-0.5 rounded text-[10px] font-black">{p2Wins}</span>
</div>
<div className="p-3 space-y-2">
{[{ n: match.p1, s: match.p1_sets, win: match.winner === match.p1, real: match.p1_is_real },
{ n: match.p2, s: match.p2_sets, win: match.winner === match.p2, real: match.p2_is_real }].map((p, i) => (
<div key={i} className={`flex justify-between items-center ${p.win ? 'text-zinc-900 dark:text-white font-black' : p.real ? 'text-zinc-600 dark:text-zinc-300' : 'text-zinc-400 italic'}`}>
<span className="truncate text-xs uppercase tracking-tight">{p.n}</span>
<span className={`px-2 py-0.5 rounded text-[10px] font-bold ${p.win ? 'bg-orange-100 dark:bg-orange-900/30 text-orange-700' : 'bg-zinc-100 dark:bg-zinc-800 text-zinc-500'}`}>{p.s}</span>
</div>
))}
</div>
</div>
);
};
export default function BracketView({ nodes, onMatchClick }) {
export default function BracketView({ matches, onMatchClick }) {
const containerRef = useRef(null);
const svgRef = useRef(null);
const [lines, setLines] = useState([]);
useEffect(() => {
// --- EXACT COPY OF YOUR SVG LOGIC ---
if (!containerRef.current || !svgRef.current) return;
const container = containerRef.current.getBoundingClientRect();
const svg = svgRef.current;
while (svg.firstChild) svg.removeChild(svg.firstChild);
const draw = () => {
if (!containerRef.current) return;
const container = containerRef.current.getBoundingClientRect();
const newLines = [];
matches.forEach(m => {
if (!m.winner_next_match_id) return;
const sEl = document.getElementById(`match-${m.id}`);
const eEl = document.getElementById(`match-${m.winner_next_match_id}`);
if (sEl && eEl) {
const r1 = sEl.getBoundingClientRect(), r2 = eEl.getBoundingClientRect();
const sx = r1.right - container.left, sy = r1.top + r1.height / 2 - container.top;
const ex = r2.left - container.left, ey = r2.top + r2.height / 2 - container.top;
const c1 = sx + (ex - sx) / 2;
newLines.push(<path key={`${m.id}-${m.winner_next_match_id}`} d={`M ${sx} ${sy} C ${c1} ${sy}, ${c1} ${ey}, ${ex} ${ey}`} className="stroke-zinc-300 dark:stroke-zinc-700 fill-none stroke-[1.5px]" />);
}
});
setLines(newLines);
};
const t = setTimeout(draw, 100);
window.addEventListener('resize', draw);
return () => { clearTimeout(t); window.removeEventListener('resize', draw); };
}, [matches]);
nodes.forEach(node => {
// Logic: Find DOM elements by ID
const sEl = document.getElementById(`node-${node.id}`);
const eEl = document.getElementById(`node-${node.winner_next_node_id}`);
// Only draw if both exist and are visible
if (sEl && eEl && sEl.offsetParent !== null && eEl.offsetParent !== null) {
const r1 = sEl.getBoundingClientRect(), r2 = eEl.getBoundingClientRect();
// Calculate connection points
const sx = r1.right - container.left, sy = r1.top + r1.height / 2 - container.top;
const ex = r2.left - container.left, ey = r2.top + r2.height / 2 - container.top;
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
const c1 = sx + (ex - sx) / 2; // Control point X
path.setAttribute("d", `M ${sx} ${sy} C ${c1} ${sy}, ${c1} ${ey}, ${ex} ${ey}`);
path.setAttribute("class", "stroke-zinc-300 dark:stroke-zinc-800 fill-none stroke-[2px] opacity-40");
svg.appendChild(path);
}
});
}, [nodes]); // Re-run when nodes change
const renderTree = (list, align = 'justify-center') => {
const renderRound = (list) => {
const rounds = {};
list.forEach(n => { if (!rounds[n.round_number]) rounds[n.round_number] = []; rounds[n.round_number].push(n); });
list.forEach(m => (rounds[m.round] = rounds[m.round] || []).push(m));
return Object.keys(rounds)
.sort((a, b) => a - b)
.filter(r => rounds[r].some(n => n.display_number)) // Filter empty rounds
.map(r => (
<div key={r} className={`flex flex-col ${align} gap-12 min-w-[280px] z-10`}>
{rounds[r].sort((a, b) => a.display_number - b.display_number).map(n => (
<MatchCard key={n.id} node={n} onClick={onMatchClick} />
))}
const roundKeys = Object.keys(rounds).sort((a, b) => Number(a) - Number(b));
let prevRoundMap = new Map();
return roundKeys.map((r, rIdx) => {
let matchesInRound = rounds[r];
if (rIdx === 0) {
matchesInRound.sort((a, b) => a.number - b.number);
} else {
matchesInRound.sort((a, b) => {
const getSourceAvg = (match) => {
const sources = list.filter(x => x.next_win === match.id);
if (sources.length === 0) return 9999;
const indices = sources.map(s => prevRoundMap.get(s.id)).filter(i => i !== undefined);
if (indices.length === 0) return 9999;
return indices.reduce((sum, val) => sum + val, 0) / indices.length;
};
return getSourceAvg(a) - getSourceAvg(b);
});
}
matchesInRound.forEach((m, idx) => prevRoundMap.set(m.id, idx));
return (
<div key={r} className="flex flex-col gap-10 z-10 w-64 shrink-0 justify-around">
{matchesInRound.map(m => <MatchCard key={m.id} match={m} onClick={onMatchClick} />)}
</div>
));
);
});
};
const wb = nodes.filter(n => n.bracket_type === 'Winners');
const lb = nodes.filter(n => n.bracket_type === 'Losers');
const finals = nodes.filter(n => n.bracket_type === 'Finals');
const wb = matches.filter(m => m.bracket === 'Winner');
const lb = matches.filter(m => m.bracket === 'Loser');
const finals = matches.filter(m => m.bracket === 'Finals');
return (
<div className="w-full h-full overflow-auto p-8 bg-[radial-gradient(#d1d5db_1px,transparent_1px)] dark:bg-[radial-gradient(#18181b_1px,transparent_1px)] [background-size:20px_20px]">
<div ref={containerRef} className="relative min-w-max p-4 flex gap-24">
<svg ref={svgRef} className="absolute inset-0 w-full h-full pointer-events-none z-0" />
<div className="w-full h-full overflow-auto bg-[#f8f9fa] dark:bg-zinc-950 bg-[radial-gradient(#e5e7eb_1px,transparent_1px)] dark:bg-[radial-gradient(#27272a_1px,transparent_1px)] [background-size:24px_24px]">
{/* UPDATED: items-center ensures Finals (right col) are centered vertically
relative to the Winners/Losers block (left col).
*/}
<div ref={containerRef} className="relative min-w-max min-h-full p-12 flex gap-20 items-center">
<svg className="absolute inset-0 w-full h-full pointer-events-none z-0">
{lines}
</svg>
<div className="flex flex-col gap-24">
<div className="relative flex gap-16">
<div className="absolute -top-10 left-0 text-[10px] font-black uppercase tracking-[0.2em] text-zinc-500 dark:text-zinc-600">Winners Bracket</div>
{renderTree(wb)}
<div className="relative">
<div className="absolute -top-8 left-0 text-[10px] font-black uppercase tracking-[0.2em] text-zinc-400">Winners Bracket</div>
<div className="flex gap-20">{renderRound(wb)}</div>
</div>
{lb.length > 0 && (
<div className="relative flex flex-col gap-12 pt-16 border-t border-zinc-300 dark:border-zinc-800 w-full">
<div className="absolute top-6 left-0 text-[10px] font-black uppercase tracking-[0.2em] text-zinc-500 dark:text-zinc-600">Losers Bracket</div>
<div className="flex gap-16 justify-start">{renderTree(lb, 'justify-start')}</div>
{matches.some(m => m.bracket === 'Loser') && (
<div className="relative pt-8 border-t border-dashed border-zinc-300 dark:border-zinc-800">
<div className="absolute top-0 left-0 text-[10px] font-black uppercase tracking-[0.2em] text-zinc-400">Losers Bracket</div>
<div className="flex gap-20 mt-8">{renderRound(lb)}</div>
</div>
)}
</div>
{finals.length > 0 && (
<div className="flex flex-col justify-center items-center gap-4 relative z-10 min-w-[280px]">
<div className="absolute top-1/2 -translate-y-[calc(50%+140px)] flex items-center gap-2 bg-orange-100 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400 px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest border border-orange-200 dark:border-orange-800 shadow-sm">
<Trophy size={14} /> Championship
</div>
{finals.map(n => <MatchCard key={n.id} node={n} onClick={onMatchClick} />)}
{matches.some(m => m.bracket === 'Finals') && (
<div className="flex flex-col justify-center gap-6">
<div className="text-[10px] font-black uppercase bg-orange-100 dark:bg-orange-900/30 text-orange-600 px-4 py-1.5 rounded-full border border-orange-200 dark:border-orange-800 shadow-sm mx-auto">Championship</div>
{finals.map(m => <MatchCard key={m.id} match={m} onClick={onMatchClick} />)}
</div>
)}
</div>
+159 -48
View File
@@ -1,83 +1,194 @@
// frontend/src/components/Forms/TournamentForm.jsx
import { useState } from 'react';
import React, { useState } from 'react';
import api from '../../services/api';
export default function TournamentForm({ initialData, onSuccess }) {
export default function TournamentForm({ tournament, onSuccess, onDelete }) {
const [error, setError] = useState(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
setError(null);
const formData = new FormData(e.target);
const data = Object.fromEntries(formData.entries());
// Extract raw values to transform
const rawTeams = formData.get('teams');
const rawCourts = formData.get('courts');
const date = formData.get('date');
const startTime = formData.get('start_time');
const typeRaw = formData.get('type');
const duration = formData.get('duration');
const name = formData.get('name');
const code = formData.get('code');
const teams = rawTeams.split('\n').map(t => t.trim()).filter(t => t.length > 0);
const courts = rawCourts.split(',').map(c => c.trim()).filter(c => c.length > 0);
if (teams.length < 2) {
setError("At least 2 teams required.");
setIsSubmitting(false);
return;
}
const timestamp = new Date(`${date}T${startTime}`).toISOString();
// Format Arrays
const payload = {
...data,
duration: parseInt(data.duration),
timestamp: `${data.date}T${data.time}:00`,
courts: data.courts.split(',').map(s => s.trim()).filter(Boolean),
teams: data.teams.split('\n').map(s => s.trim()).filter(Boolean)
name,
code,
type: typeRaw.charAt(0).toUpperCase() + typeRaw.slice(1),
timestamp,
duration: parseInt(duration),
teams,
courts
};
try {
if (initialData) await api.patch(`/tournaments/${initialData.id}`, payload);
if (tournament) await api.patch(`/tournaments/${tournament.id}`, payload);
else await api.post('/tournaments', payload);
onSuccess();
} catch (err) {
setError(typeof err.detail === 'string' ? err.detail : "Error saving");
console.error(err);
if (Array.isArray(err.detail)) {
setError(err.detail.map(e => `${e.loc.join('.')}: ${e.msg}`).join(', '));
} else {
setError(typeof err.detail === 'string' ? err.detail : "Error saving tournament");
}
} finally {
setIsSubmitting(false);
}
};
const handleDelete = async () => {
if (!window.confirm("Purge this tournament and all its history?")) return;
try {
await api.delete(`/tournaments/${initialData.id}`);
window.location.href = '/';
} catch (err) { alert("Error deleting"); }
};
// Calculate default date/time for form
const defaultDate = tournament?.timestamp
? new Date(tournament.timestamp).toISOString().split('T')[0]
: new Date().toISOString().split('T')[0];
// Defaults
const defaultDate = initialData?.timestamp ? new Date(initialData.timestamp).toISOString().split('T')[0] : new Date().toISOString().split('T')[0];
const defaultTime = initialData?.timestamp ? new Date(initialData.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false }) : "09:00";
const defaultTeams = initialData?.teams?.map(t => t.name).join('\n');
const defaultCourts = initialData?.courts?.map(c => c.name).join(', ');
const defaultTime = tournament?.timestamp
? new Date(tournament.timestamp).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })
: "09:00";
return (
<form onSubmit={handleSubmit} className="space-y-4">
{error && <div className="bg-red-50 text-red-600 p-3 rounded-xl text-center text-sm font-bold border border-red-100">{error}</div>}
<div>
<label className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Name</label>
<input name="name" defaultValue={initialData?.name} required className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl dark:text-white outline-none focus:border-orange-500 font-bold" />
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Access Code</label>
<input name="code" defaultValue={initialData?.code} required className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl text-center font-mono dark:text-white font-bold" />
{error && (
<div className="text-xs text-red-500 dark:text-red-400 text-center mb-4 bg-red-50 dark:bg-red-900/10 p-2 rounded border border-red-200 dark:border-red-900/30">
{error}
</div>
)}
<div className="space-y-4">
<div>
<label className="text-[10px] font-black uppercase tracking-widest text-zinc-500">Type</label>
<select name="type" defaultValue={initialData?.type || "Double"} className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl dark:text-white outline-none font-bold">
<option value="Double">Double Elimination</option>
<option value="Single">Single Elimination</option>
</select>
<label className="text-xs font-bold text-zinc-500 uppercase">Name</label>
<input
name="name"
defaultValue={tournament?.name}
required
placeholder="My Awesome Tournament"
autoFocus
className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-600 rounded p-2 focus:border-orange-500 outline-none transition text-zinc-900 dark:text-white"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="font-bold text-zinc-500 text-xs uppercase">Code</label>
<input
name="code"
defaultValue={tournament?.code}
required
placeholder="••••"
autoComplete="off"
className="w-full h-10 bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-600 rounded p-2 text-center font-mono focus:border-orange-500 outline-none transition text-zinc-900 dark:text-white"
/>
</div>
<div>
<label className="font-bold text-zinc-500 text-xs uppercase">Type</label>
<select
name="type"
defaultValue={tournament?.type?.toLowerCase() || "double"}
className="w-full h-10 bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-600 rounded p-2 focus:border-orange-500 outline-none transition text-zinc-900 dark:text-white"
>
<option value="double">Double Elimination</option>
<option value="single">Single Elimination</option>
</select>
</div>
</div>
<div className="grid grid-cols-7 gap-4">
<div className="col-span-2">
<label className="text-xs font-bold text-zinc-500 uppercase mb-1 block">Duration</label>
<input
type="number"
name="duration"
defaultValue={tournament?.duration || 30}
min="0"
className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-600 rounded p-2 h-10 text-base appearance-none focus:border-orange-500 outline-none transition text-zinc-900 dark:text-white"
/>
</div>
<div className="col-span-2">
<label className="text-xs font-bold text-zinc-500 uppercase mb-1 block">Start Time</label>
<input
type="time"
name="start_time"
defaultValue={defaultTime}
className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-600 rounded p-2 h-10 text-base appearance-none focus:border-orange-500 outline-none transition text-zinc-900 dark:text-white"
/>
</div>
<div className="col-span-3">
<label className="text-xs font-bold text-zinc-500 uppercase mb-1 block">Date</label>
<input
type="date"
name="date"
defaultValue={defaultDate}
className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 rounded p-2 h-10 text-base appearance-none focus:border-orange-500 outline-none transition text-zinc-900 dark:text-white"
/>
</div>
</div>
<div>
<label className="text-xs font-bold text-zinc-500 uppercase">Courts</label>
<input
name="courts"
placeholder="Center Court, Court 1"
defaultValue={tournament?.courts?.map(c => c.name || c).join(', ')}
required
className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-600 rounded p-2 focus:border-orange-500 outline-none transition text-zinc-900 dark:text-white"
/>
</div>
<div>
<label className="text-xs font-bold text-zinc-500 uppercase">Teams</label>
<textarea
name="teams"
placeholder="One team per line..."
defaultValue={tournament?.teams?.map(t => t.name || t).join('\n')}
rows={5}
required
className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-600 rounded p-2 font-mono text-sm focus:border-orange-500 outline-none transition text-zinc-900 dark:text-white resize-none"
/>
</div>
</div>
<div className="grid grid-cols-3 gap-4">
<input type="number" name="duration" placeholder="Min" defaultValue={initialData?.duration || 30} className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl dark:text-white font-bold" />
<input type="time" name="time" defaultValue={defaultTime} className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl dark:text-white font-bold" />
<input type="date" name="date" defaultValue={defaultDate} className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl dark:text-white font-bold" />
</div>
<input name="courts" placeholder="Courts (e.g. Center, Court 1)" defaultValue={defaultCourts} required className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl dark:text-white font-bold" />
<textarea name="teams" placeholder="Teams (one per line)" defaultValue={defaultTeams} rows={5} required className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl font-mono text-sm dark:text-white font-bold" />
<div className="flex justify-between pt-4 border-t border-zinc-200 dark:border-zinc-800">
{initialData && <button type="button" onClick={handleDelete} className="text-red-500 text-sm font-black uppercase tracking-widest hover:underline">Delete Tournament</button>}
<button disabled={isSubmitting} type="submit" className="bg-orange-600 hover:bg-orange-500 text-white px-8 py-3 rounded-xl font-black uppercase tracking-widest text-xs transition active:scale-95 ml-auto shadow-lg shadow-orange-600/20">
{isSubmitting ? 'Saving...' : (initialData ? 'Save Changes' : 'Create Tournament')}
<div className="flex justify-between mt-4 pt-4 border-t border-zinc-200 dark:border-zinc-800 flex-wrap gap-y-4">
{tournament && onDelete && (
<button
type="button"
onClick={() => onDelete(tournament.id)}
className="text-red-500 text-sm hover:underline h-5 self-end"
>
Delete Tournament
</button>
)}
{!tournament && <div className="hidden"></div>}
<button
disabled={isSubmitting}
type="submit"
className="bg-orange-600 hover:bg-orange-500 text-white px-6 py-2 rounded font-bold shadow-lg shadow-orange-900/20 ml-auto transition active:scale-95"
>
{isSubmitting ? 'Saving...' : (tournament ? 'Save Changes' : 'Create')}
</button>
</div>
</form>
+44 -23
View File
@@ -1,44 +1,65 @@
// frontend/src/components/Layout/Layout.jsx
import React from 'react';
import { Outlet, useOutletContext } from 'react-router-dom';
import Navbar from './Navbar';
import { Moon, Sun } from 'lucide-react';
import api from '../../services/api';
import { useEffect, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import api, { getToken } from '../../services/api';
import Navbar from './Navbar';
export default function Layout({ darkMode, setDarkMode }) {
const [isAdmin, setIsAdmin] = React.useState(false);
const [isAdmin, setIsAdmin] = useState(false);
const [navTitle, setNavTitle] = useState('');
const [navSubtitle, setNavSubtitle] = useState('');
// Shared state for the navbar title, settable by child pages
const [navTitle, setNavTitle] = React.useState('');
const [navSubtitle, setNavSubtitle] = React.useState('');
// State to trigger settings modals from Navbar
const [showSettings, setShowSettings] = useState(false);
React.useEffect(() => {
const location = useLocation();
const navigate = useNavigate();
const isDashboard = location.pathname === '/';
useEffect(() => {
const checkAuth = async () => {
try {
const res = await api.get('/auth/check');
setIsAdmin(true); // Endpoint returns 200 OK if token valid
} catch {
setIsAdmin(false);
if (getToken()) {
try {
const res = await api.get('/auth/check');
setIsAdmin(res.is_admin);
} catch {
setIsAdmin(false);
}
}
};
if (localStorage.getItem('volleyToken')) checkAuth();
}, []);
checkAuth();
}, [location.pathname]);
const handleLogout = () => {
localStorage.removeItem('volleyToken');
window.location.reload();
};
return (
<div className="min-h-screen bg-zinc-50 dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 flex flex-col">
<Navbar title={navTitle} subtitle={navSubtitle} isAdmin={isAdmin} />
<div className="fixed inset-0 bg-zinc-50 dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 transition-colors selection:bg-orange-500/30 flex flex-col overflow-hidden">
<Navbar
title={navTitle}
subtitle={navSubtitle}
isAdmin={isAdmin}
onLogout={handleLogout}
onOpenSettings={() => setShowSettings(true)}
isDashboard={isDashboard}
/>
<main className="flex-1 relative overflow-hidden flex flex-col">
<Outlet context={{ setNavTitle, setNavSubtitle, isAdmin }} />
<main className="flex-1 overflow-hidden relative flex flex-col">
<Outlet context={{ setNavTitle, setNavSubtitle, isAdmin, showSettings, setShowSettings }} />
</main>
<div className="fixed bottom-8 right-8 z-40">
{/* Dark Mode FAB */}
<div className="fixed bottom-6 sm:bottom-8 right-6 sm:right-8 z-40">
<button
onClick={() => setDarkMode(!darkMode)}
className="p-4 bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 rounded-full shadow-2xl transition hover:scale-110 active:scale-95 border-2 border-zinc-700 dark:border-zinc-300"
title="Toggle Theme"
className="p-4 sm:p-5 bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 rounded-[1.5rem] sm:rounded-[2rem] shadow-2xl transition hover:scale-110 active:scale-95 border-2 border-zinc-700 dark:border-zinc-300 group"
>
{darkMode ? <Sun size={24} /> : <Moon size={24} />}
{darkMode ? <Sun size={24} strokeWidth={2.5} className="sm:size-7" /> : <Moon size={24} strokeWidth={2.5} className="sm:size-7" />}
</button>
</div>
</div>
+29 -25
View File
@@ -1,48 +1,52 @@
// frontend/src/components/Layout/Navbar.jsx
import React from 'react';
import { Link, useLocation } from 'react-router-dom';
import { Volleyball, LogOut, Lock } from 'lucide-react';
export default function Navbar({ title, subtitle, isAdmin }) {
const location = useLocation();
const isDashboard = location.pathname === '/';
import { Lock, LogOut, Plus, SlidersHorizontal, Volleyball } from 'lucide-react';
import { Link } from 'react-router-dom';
export default function Navbar({ title, subtitle, isAdmin, onLogout, onOpenSettings, isDashboard }) {
return (
<nav className="bg-white/95 dark:bg-zinc-900/95 backdrop-blur-lg border-b border-zinc-300 dark:border-zinc-800 sticky top-0 z-[100] px-6 py-4 flex justify-between items-center shadow-sm">
<Link to="/" className="flex items-center gap-4 cursor-pointer group select-none shrink-0">
<div className="p-2.5 bg-orange-600 rounded-xl group-hover:rotate-12 transition-transform shadow-lg shadow-orange-600/30">
<Volleyball className="text-white" size={24} />
<nav className="bg-white/95 dark:bg-zinc-900/95 backdrop-blur-lg border-b border-zinc-300 dark:border-zinc-800 sticky top-0 z-[100] px-3 sm:px-6 py-3 sm:py-4 flex justify-between items-center shadow-md shrink-0">
<Link to="/" className="flex items-center gap-2 sm:gap-4 cursor-pointer group select-none shrink-0">
<div className="p-1.5 sm:p-2.5 bg-orange-600 rounded-xl group-hover:rotate-12 transition-transform shadow-lg shadow-orange-600/30 active:scale-90">
<Volleyball className="text-white" size={20} />
</div>
<div className="hidden sm:block">
<h1 className="text-2xl font-black tracking-tighter leading-none text-zinc-900 dark:text-white">VolleyManager</h1>
<p className="text-[10px] font-black text-zinc-500 dark:text-zinc-400 uppercase tracking-widest mt-0.5">Tournament Ops</p>
<p className="text-[9px] font-black text-zinc-500 dark:text-zinc-400 uppercase tracking-widest mt-0.5">Tournament Ops</p>
</div>
</Link>
<div className="absolute left-1/2 -translate-x-1/2 text-center pointer-events-none">
<div className="font-black uppercase text-sm tracking-[0.3em] text-zinc-900 dark:text-white truncate leading-none mb-1">
<div className="absolute left-1/2 -translate-x-1/2 text-center pointer-events-none w-full max-w-[140px] xs:max-w-[180px] sm:max-w-[400px]">
<div className="font-black uppercase text-[10px] sm:text-sm tracking-[0.1em] sm:tracking-[0.3em] text-zinc-900 dark:text-white truncate leading-none mb-1">
{title || 'Dashboard'}
</div>
{subtitle && (
<div className="text-[10px] font-black text-zinc-400 dark:text-zinc-500 uppercase tracking-widest leading-none">
<div className="text-[8px] sm:text-[10px] font-black text-zinc-400 dark:text-zinc-500 uppercase tracking-widest leading-none">
{subtitle}
</div>
)}
</div>
<div className="flex gap-4 items-center">
<div className="flex gap-2 sm:gap-4 items-center shrink-0">
{isAdmin ? (
<button
onClick={() => { localStorage.removeItem('volleyToken'); window.location.reload(); }}
className="text-zinc-400 hover:text-red-500 transition active:scale-90"
title="Logout"
>
<LogOut size={22} />
</button>
<>
{isDashboard ? (
<button onClick={onOpenSettings} className="bg-orange-600 hover:bg-orange-500 text-white px-3 sm:px-5 py-2 sm:py-2.5 rounded-xl flex items-center gap-2 text-[9px] sm:text-[10px] font-black uppercase tracking-wider sm:tracking-[0.2em] transition shadow-xl shadow-orange-600/20 active:scale-95 shrink-0">
<Plus size={16} strokeWidth={4} /> <span className="hidden xs:inline">Create</span>
</button>
) : (
<button onClick={onOpenSettings} className="text-zinc-500 hover:text-orange-500 transition p-2 sm:p-3 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-2xl active:scale-90">
<SlidersHorizontal size={18} className="sm:size-[22px]" strokeWidth={2.5} />
</button>
)}
<div className="w-px h-5 sm:h-6 bg-zinc-200 dark:bg-zinc-800 mx-0.5 sm:mx-1" />
<button onClick={onLogout} title="Sign Out" className="text-zinc-400 hover:text-red-500 transition active:scale-90 shrink-0">
<LogOut size={18} className="sm:size-[22px]" />
</button>
</>
) : (
<Link to="/login" className="text-orange-600 font-black flex items-center gap-2 text-[10px] uppercase tracking-widest hover:text-orange-500 transition group p-2 rounded-xl hover:bg-orange-50 dark:hover:bg-orange-950/20">
<Lock size={14} className="group-hover:-translate-y-0.5 transition-transform" /> <span>Login</span>
<Link to="/login" className="text-orange-600 font-black flex items-center gap-1.5 text-[9px] sm:text-[10px] uppercase tracking-widest hover:text-orange-500 transition group p-1.5 sm:p-2 rounded-xl hover:bg-orange-50 dark:hover:bg-orange-950/20">
<Lock size={12} className="sm:size-[14px] group-hover:-translate-y-0.5 transition-transform" /> <span className="hidden xs:inline">Login</span>
</Link>
)}
</div>
@@ -1,87 +1,96 @@
// frontend/src/components/Schedule/ScheduleView.jsx
import { Search } from 'lucide-react';
import { useState } from 'react';
import { CheckCircle, Pencil, Plus, Search, Trophy } from 'lucide-react';
import React, { useState } from 'react';
import { stringToColor } from '../../utils/helpers';
export default function ScheduleView({ nodes, onMatchClick }) {
export default function ScheduleView({ schedule, onMatchClick }) {
const [filter, setFilter] = useState("");
// Flatten and prepare matches
const schedule = nodes
.filter(n => n.match) // Only real matches
.map(n => {
const m = n.match;
return {
id: m.id, // For API calls
node: n, // Pass full node for context if needed
number: n.display_number,
time: new Date(m.start_time || n.planned_start_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
timestamp: new Date(m.start_time || n.planned_start_time),
court: m.court ? m.court.name : 'TBD',
p1: n.p1_team?.name,
p2: n.p2_team?.name,
p1_label: n.source_p1_type ? `Winner of #${n.source_p1_node_id}` : 'TBD', // Simplified label logic
p2_label: n.source_p2_type ? `Winner of #${n.source_p2_node_id}` : 'TBD',
bracket: n.bracket_type,
round: n.round_number,
winner: m.winner_team_id,
p1_sets: m.sets.filter(s => s.p1 > s.p2).length,
p2_sets: m.sets.filter(s => s.p2 > s.p1).length
};
})
.sort((a, b) => a.timestamp - b.timestamp);
const longestCourt = schedule.reduce((max, m) => {
const c = m.court || "Court";
return c.length > max.length ? c : max;
}, "Court");
const badgeWidth = Math.max(100, longestCourt.length * 9);
const filtered = schedule.filter(m =>
(m.p1 || "").toLowerCase().includes(filter.toLowerCase()) ||
(m.p2 || "").toLowerCase().includes(filter.toLowerCase())
(m.p1 + m.p2 + m.number).toLowerCase().includes(filter.toLowerCase())
);
return (
<div className="h-full overflow-y-auto overflow-x-hidden relative flex flex-col">
{/* STICKY SEARCH BAR */}
<div className="sticky top-0 z-20 bg-zinc-50 dark:bg-zinc-950 p-6 pb-2">
<div className="relative group max-w-3xl mx-auto w-full">
<input
placeholder="Search teams..."
className="w-full bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-800 rounded-2xl p-4 pl-12 outline-none focus:ring-2 focus:ring-orange-500 transition shadow-sm text-zinc-900 dark:text-white font-bold"
value={filter}
onChange={e => setFilter(e.target.value)}
/>
<Search className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400 group-focus-within:text-orange-500 transition" size={20} />
<div className="h-full overflow-hidden relative flex flex-col">
<div className="absolute top-0 inset-x-0 z-30 p-6 pb-2 bg-transparent pointer-events-none">
<div className="relative group max-w-3xl mx-auto w-full pointer-events-auto">
<input placeholder="Search matches..." className="w-full bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-800 rounded-2xl p-4 pl-12 focus:ring-2 focus:ring-orange-500 outline-none transition shadow-sm text-zinc-900 dark:text-white font-bold" value={filter} onChange={e => setFilter(e.target.value)} />
<Search className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400" size={20} />
</div>
</div>
<div className="p-6 pt-2 max-w-4xl mx-auto w-full space-y-3 pb-32">
{filtered.map(m => (
<div key={m.id} className="bg-white dark:bg-zinc-900 p-4 rounded-2xl border border-zinc-300 dark:border-zinc-800 shadow-sm flex items-center justify-between group transition-all hover:border-orange-500/30">
<div className="flex gap-6 items-center">
<div className="text-center min-w-[70px]">
<div className="text-xl font-black font-mono text-zinc-900 dark:text-white leading-none mb-1">{m.time}</div>
<div className="text-[9px] font-black text-white px-2 py-0.5 rounded uppercase tracking-wider" style={{ background: stringToColor(m.court) }}>{m.court}</div>
</div>
<div>
<div className="font-black text-base uppercase tracking-tight text-zinc-900 dark:text-zinc-100">
{m.p1 || <span className="text-zinc-400 italic lowercase font-medium">{m.p1_label}</span>}
<span className="text-zinc-300 dark:text-zinc-700 mx-2 text-xs font-black">VS</span>
{m.p2 || <span className="text-zinc-400 italic lowercase font-medium">{m.p2_label}</span>}
<div className="flex-1 overflow-y-auto p-6 pt-28 pb-32 [mask-image:linear-gradient(to_bottom,transparent_0px,transparent_60px,black_110px)]">
<div className="max-w-4xl mx-auto w-full space-y-3">
{filtered.map(m => {
const courtColor = stringToColor(m.court);
const isFinished = m.isFinished;
return (
<div key={m.id} className="bg-white dark:bg-zinc-900 p-4 rounded-2xl border border-zinc-300 dark:border-zinc-800 shadow-sm flex items-center justify-between transition-all hover:border-orange-500/30">
<div className="flex gap-4 md:gap-6 items-center flex-1 min-w-0">
{/* UNIFORM WIDTH METADATA COLUMN */}
<div className="flex flex-col gap-1 items-center shrink-0" style={{ minWidth: badgeWidth }}>
<div className="text-lg md:text-xl font-black font-mono text-zinc-900 dark:text-white">{m.time}</div>
<div className="text-[9px] font-black text-white px-2 py-1 rounded uppercase w-full truncate text-center" style={{ background: courtColor }}>
{m.court}
</div>
<div className="text-[9px] font-black bg-zinc-100 dark:bg-zinc-800 text-zinc-400 px-2 py-0.5 rounded w-full md:hidden text-center">#{m.number}</div>
</div>
<div className="flex-1 flex flex-col gap-0.5 min-w-0">
<div className="flex flex-col md:flex-row md:items-center gap-1 md:gap-2">
{[{ n: m.p1, win: m.winnerName === m.p1, real: m.p1_is_real },
{ n: m.p2, win: m.winnerName === m.p2, real: m.p2_is_real }].map((p, i) => (
<React.Fragment key={i}>
<div className="flex items-center gap-2 min-w-0">
{p.win && <Trophy size={14} className="text-orange-500 shrink-0" />}
<span className={`truncate text-sm md:text-base font-bold ${p.win ? 'text-orange-600' : p.real ? 'text-zinc-900 dark:text-zinc-100' : 'text-zinc-400 italic font-normal'}`}>{p.n}</span>
</div>
{i === 0 && <span className="hidden md:block text-zinc-300 text-xs font-black px-1">VS</span>}
</React.Fragment>
))}
</div>
<div className="hidden md:block text-[10px] font-black bg-zinc-100 dark:bg-zinc-800 text-zinc-400 px-2 py-0.5 rounded w-fit">Match #{m.number}</div>
</div>
</div>
<div className="text-[10px] font-black text-zinc-400 uppercase tracking-widest mt-1">Match #{m.number} {m.bracket} Round {m.round}</div>
</div>
</div>
<div className="flex items-center gap-4">
{m.winner ? (
<div className="text-right shrink-0">
<div className="text-orange-500 font-black text-[10px] uppercase tracking-wider mb-0.5">Finished</div>
<div className="text-sm font-black font-mono text-zinc-900 dark:text-zinc-300">{m.p1_sets} - {m.p2_sets}</div>
<div className="ml-3 flex items-center shrink-0">
{isFinished ? (
<button
onClick={() => onMatchClick(m)}
className="flex flex-col items-center md:items-end hover:bg-zinc-50 dark:hover:bg-zinc-800 p-2 rounded-xl transition min-w-[80px] group cursor-pointer"
title="Edit Score"
>
{/* Normal View: Finished + Score */}
<div className="group-hover:hidden flex flex-col items-center md:items-end">
<div className="text-orange-500 font-black text-[10px] uppercase flex items-center gap-1"><CheckCircle size={12} /> Finished</div>
<div className="text-sm font-black font-mono text-zinc-900 dark:text-zinc-300">{m.p1_sets} - {m.p2_sets}</div>
</div>
{/* Hover View: Edit Icon */}
<div className="hidden group-hover:flex flex-col items-center md:items-end text-zinc-500 dark:text-zinc-400 animate-in fade-in zoom-in duration-200">
<div className="text-[10px] font-black uppercase flex items-center gap-1"><Pencil size={12} /> Edit</div>
<div className="text-sm font-black font-mono">{m.p1_sets} - {m.p2_sets}</div>
</div>
</button>
) : m.isReady && (
<button onClick={() => onMatchClick(m)} className="bg-orange-600 hover:bg-orange-500 text-white p-2 md:px-4 md:py-2 rounded-xl shadow-lg active:scale-95 transition-all flex items-center gap-2">
<Plus size={18} strokeWidth={3} /> <span className="text-xs font-bold uppercase hidden md:inline">Report score</span>
</button>
)}
</div>
) : (m.p1 && m.p2) && (
<button onClick={() => onMatchClick(m.node)} className="bg-orange-600 hover:bg-orange-500 text-white text-[10px] font-black uppercase px-5 py-2.5 rounded-xl transition shadow-lg shadow-orange-600/20 active:scale-95 shrink-0">Report</button>
)}
</div>
</div>
))}
{filtered.length === 0 && <div className="text-center py-20 text-zinc-400 font-black uppercase tracking-widest text-xs">No matching matches found</div>}
</div>
);
})}
</div>
</div>
</div>
);
+129 -83
View File
@@ -1,37 +1,19 @@
// frontend/src/components/Tournament/ScoreModal.jsx
import { Trash2 } from 'lucide-react';
import { useState } from 'react';
import api from '../../services/api';
import React, { useState } from 'react';
import { Eraser, Clock, MapPin } from 'lucide-react';
import { stringToColor } from '../../utils/helpers';
import Modal from '../UI/Modal';
export default function ScoreModal({ isOpen, onClose, node, tournamentId, isAdmin }) {
const match = node.match;
const initialSets = match.sets?.length ? match.sets : [{ p1: '', p2: '' }];
const [sets, setSets] = useState(initialSets);
const ScoreForm = ({ match, isAdmin, onSubmit, onClear }) => {
// Safe init of sets
const [sets, setSets] = useState(match.sets && match.sets.length ? match.sets : [{ p1: '', p2: '' }]);
const [code, setCode] = useState('');
const [error, setError] = useState(null);
const handleSubmit = async () => {
try {
await api.post(`/tournaments/${tournamentId}/matches/${match.id}/score`, {
code: code || undefined,
sets: sets.map(s => ({ p1: Number(s.p1), p2: Number(s.p2) }))
});
onClose();
} catch (err) {
setError("Check code or scores");
}
};
const handleClear = async () => {
if (!confirm("Clear match?")) return;
try {
await api.delete(`/tournaments/${tournamentId}/matches/${match.id}/score`, { params: { code: code || undefined } });
onClose();
} catch (err) { setError("Error clearing"); }
try { await onSubmit(match.id, sets, code); }
catch (err) { setError(typeof err.detail === 'string' ? err.detail : "Check code or scores"); }
};
const removeSet = (idx) => {
@@ -44,68 +26,132 @@ export default function ScoreModal({ isOpen, onClose, node, tournamentId, isAdmi
setSets(n);
};
const timeDisplay = match.start_time || node.planned_start_time;
const courtName = match.court?.name || 'TBD';
const p1Name = node.p1_team?.name || 'TBD';
const p2Name = node.p2_team?.name || 'TBD';
return (
<Modal isOpen={isOpen} onClose={onClose} title={`Match Protocol #${node.display_number}`}>
<div className="space-y-6">
{error && <div className="bg-red-50 text-red-600 p-3 rounded-xl text-center text-sm font-bold border border-red-100">{error}</div>}
<div className="flex justify-around items-center bg-zinc-50 dark:bg-zinc-950 p-5 rounded-2xl border border-zinc-200 dark:border-zinc-800 shadow-inner">
<div className="text-center">
<div className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-400 mb-1">Time</div>
<div className="text-xl font-black font-mono text-zinc-900 dark:text-white">{new Date(timeDisplay).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</div>
</div>
<div className="w-px h-10 bg-zinc-200 dark:bg-zinc-800" />
<div className="text-center">
<div className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-400 mb-1">Court</div>
<div className="text-xl font-black uppercase text-zinc-900 dark:text-white tracking-tighter flex items-center gap-2">
<div className="w-2.5 h-2.5 rounded-full" style={{ background: stringToColor(courtName) }} />
{courtName}
</div>
</div>
<div className="space-y-6">
{/* Top Info Bar */}
<div className="flex justify-center items-center gap-4 bg-zinc-50 dark:bg-zinc-950 p-3 rounded-lg border border-gray-200 dark:border-zinc-800 shadow-sm transition-colors">
<div className="flex items-center gap-2 text-sm font-mono text-zinc-600 dark:text-zinc-300">
<Clock className="text-orange-500" size={18} />
<span>{match.time || "10:00"}</span>
</div>
{!isAdmin && (
<div className="space-y-2">
<label className="text-[10px] font-black uppercase tracking-widest text-zinc-400">Authorization</label>
<input type="password" value={code} onChange={e => setCode(e.target.value)} placeholder="•••••" className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-3 rounded-xl text-center tracking-[0.5em] dark:text-white font-bold outline-none focus:border-orange-500" />
</div>
)}
<div className="grid grid-cols-3 gap-2 text-center font-black text-zinc-800 dark:text-zinc-200 items-center">
<div className="text-sm truncate uppercase tracking-tight">{p1Name}</div>
<div className="text-[10px] bg-orange-600 text-white px-3 py-1.5 rounded-full w-fit mx-auto shadow-lg shadow-orange-600/20">VS</div>
<div className="text-sm truncate uppercase tracking-tight">{p2Name}</div>
</div>
<div className="space-y-4">
{sets.map((s, i) => (
<div key={i} className="animate-in slide-in-from-top-1 px-1">
<div className="flex items-center gap-4">
<div className="flex-1 flex items-center gap-3">
<input type="number" value={s.p1} onChange={e => updateSet(i, 'p1', e.target.value)} className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-4 rounded-xl text-center dark:text-white font-black text-xl outline-none focus:border-orange-500 shadow-sm" />
<div className="w-4 h-0.5 bg-zinc-300 dark:bg-zinc-700 rounded-full shrink-0" />
<input type="number" value={s.p2} onChange={e => updateSet(i, 'p2', e.target.value)} className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-4 rounded-xl text-center dark:text-white font-black text-xl outline-none focus:border-orange-500 shadow-sm" />
</div>
<button onClick={() => removeSet(i)} title="Remove Set" className="p-3 text-zinc-300 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30 rounded-xl transition shrink-0 group">
<Trash2 size={20} className="group-hover:scale-110 transition-transform" />
</button>
</div>
</div>
))}
</div>
<button onClick={() => setSets([...sets, { p1: '', p2: '' }])} className="w-full py-4 border-2 border-dashed border-zinc-300 dark:border-zinc-800 text-zinc-500 rounded-xl text-[10px] font-black uppercase tracking-[0.2em] hover:border-orange-500 hover:text-orange-500 transition active:bg-orange-50 dark:active:bg-orange-900/10">+ Add Set</button>
<div className="flex gap-3 pt-4 border-t border-zinc-100 dark:border-zinc-800">
{match.winner_team_id && <button onClick={handleClear} className="w-1/3 bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded-xl font-black uppercase tracking-widest text-[10px] transition active:scale-95 border border-red-200 dark:border-red-900/50">Clear Match</button>}
<button onClick={handleSubmit} className="flex-1 bg-orange-600 hover:bg-orange-500 text-white py-4 rounded-xl font-black uppercase tracking-widest text-sm shadow-xl shadow-orange-600/20 transition active:scale-95">Submit Result</button>
<div className="h-4 w-px bg-zinc-300 dark:bg-zinc-800" />
<div className="flex items-center gap-2 text-sm font-mono text-zinc-900 dark:text-white">
<MapPin className="text-orange-500" size={18} />
<span>{match.court || "TBD"}</span>
</div>
</div>
{error && (
<div className="text-xs text-red-500 dark:text-red-400 text-center bg-red-50 dark:bg-red-900/10 p-2 rounded border border-red-200 dark:border-red-900/30">
{error}
</div>
)}
{!isAdmin && (
<div className="bg-zinc-50 dark:bg-zinc-950 p-4 rounded-lg border border-gray-200 dark:border-zinc-800">
<label className="block text-xs font-bold text-orange-500 uppercase mb-2">Tournament Code</label>
<input
type="password"
value={code}
onChange={e => setCode(e.target.value)}
placeholder="•••••"
autoComplete="off"
className="w-full bg-white dark:bg-zinc-900 border border-gray-300 dark:border-zinc-700 rounded p-3 text-center text-lg tracking-[0.5em] focus:ring-1 focus:ring-orange-500 outline-none transition text-zinc-900 dark:text-white shadow-sm"
/>
</div>
)}
<div className="grid grid-cols-3 gap-2 text-center font-bold text-zinc-700 dark:text-zinc-200 items-center px-2">
<div className="break-words text-sm leading-tight uppercase">{match.p1 || match.p1_label}</div>
<div className="text-zinc-400 dark:text-zinc-600 text-[10px] font-bold uppercase bg-zinc-100 dark:bg-zinc-950 px-3 py-1 rounded-full w-fit mx-auto shadow-sm">VS</div>
<div className="break-words text-sm leading-tight uppercase">{match.p2 || match.p2_label}</div>
</div>
<div className="space-y-2 max-h-48 overflow-y-auto pr-1">
{sets.map((s, i) => (
<div key={i} className="animate-in slide-in-from-top-1 px-1">
<div className="flex items-center justify-center gap-2">
<div className="grid grid-cols-3 gap-2 items-center justify-items-center w-full">
<input
type="number"
min="0"
pattern="[0-9]*"
value={s.p1}
onChange={(e) => updateSet(i, "p1", e.target.value)}
className="w-full bg-gray-50 dark:bg-zinc-950 border border-gray-300 dark:border-zinc-800 p-2 rounded text-center focus:border-orange-500 outline-none text-zinc-900 dark:text-white"
/>
{sets.length > 1 ? (
<button
onClick={() => removeSet(i)}
title="Remove Set"
className="mx-auto p-2 text-zinc-300 hover:text-red-500 transition shrink-0 group"
>
<Eraser
size={18}
className="group-hover:scale-110 transition-transform"
/>
</button>
) : (
<span className="text-zinc-400 dark:text-zinc-600 text-center font-bold">
-
</span>
)}
<input
type="number"
min="0"
pattern="[0-9]*"
value={s.p2}
onChange={(e) => updateSet(i, "p2", e.target.value)}
className="w-full bg-gray-50 dark:bg-zinc-950 border border-gray-300 dark:border-zinc-800 p-2 rounded text-center focus:border-orange-500 outline-none text-zinc-900 dark:text-white"
/>
</div>
</div>
</div>
))}
</div>
<button onClick={() => setSets([...sets, { p1: '', p2: '' }])} className="w-full py-2 border border-dashed border-zinc-300 dark:border-zinc-700 text-zinc-500 dark:text-zinc-400 text-sm hover:border-orange-500 hover:text-orange-500 transition rounded">+ Add Set</button>
<div className="flex gap-2">
{match.isFinished && (
<button
onClick={() => onClear(match.id, code)}
className="w-1/3 bg-red-100 dark:bg-red-900/50 hover:bg-red-200 dark:hover:bg-red-900 text-red-600 dark:text-red-300 py-3 rounded-lg font-bold transition text-sm"
>
Clear
</button>
)}
<button
onClick={handleSubmit}
className={`${match.isFinished ? 'w-2/3' : 'w-full'} bg-orange-600 hover:bg-orange-500 py-3 rounded-lg font-bold shadow-lg shadow-orange-900/20 transition text-white active:scale-95`}
>
Submit Result
</button>
</div>
</div>
);
};
export default function ScoreModal({ isOpen, onClose, match, isAdmin, onSubmit, onClear }) {
if (!isOpen || !match) return null;
return (
<Modal isOpen={isOpen} onClose={onClose} title={`Match #${match.number}`}>
<ScoreForm
match={match}
isAdmin={isAdmin}
onSubmit={async (id, sets, code) => {
await onSubmit(id, sets, code);
onClose();
}}
onClear={async (id, code) => {
await onClear(id, code);
onClose();
}}
/>
</Modal>
);
}
+3 -4
View File
@@ -1,17 +1,16 @@
// frontend/src/components/UI/Modal.jsx
import React from 'react';
import { X } from 'lucide-react';
export default function Modal({ isOpen, onClose, title, children }) {
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-black/75 backdrop-blur-sm animate-in fade-in duration-200">
<div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-2xl w-full max-w-md border border-zinc-200 dark:border-zinc-800 max-h-[90vh] overflow-y-auto">
<div className="bg-white dark:bg-zinc-900 rounded-2xl shadow-2xl w-full max-w-lg border border-zinc-300 dark:border-zinc-800 max-h-[90vh] overflow-y-auto">
<div className="p-6">
<div className="flex justify-between items-center mb-6">
<h2 className="text-lg font-black text-zinc-900 dark:text-white uppercase tracking-tight">{title}</h2>
<button onClick={onClose} className="text-zinc-400 hover:text-zinc-900 dark:hover:text-white transition">
<h2 className="text-xl font-black text-zinc-900 dark:text-white flex items-center gap-2 uppercase tracking-tight">{title}</h2>
<button onClick={onClose} className="text-zinc-500 hover:text-zinc-900 dark:hover:text-white transition p-1 rounded-full hover:bg-zinc-100 dark:hover:bg-zinc-800">
<X size={24} />
</button>
</div>
+140 -87
View File
@@ -1,72 +1,112 @@
// frontend/src/pages/Dashboard.jsx
import { Calendar, ChevronDown, ChevronUp, History, Loader2, Plus, SlidersHorizontal, Users } from 'lucide-react';
import { Calendar, ChevronDown, ChevronUp, History, Plus, SlidersHorizontal, Users, MapPin, Clock } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useNavigate, useOutletContext } from 'react-router-dom';
import TournamentForm from '../components/Forms/TournamentForm';
import Modal from '../components/UI/Modal';
import api from '../services/api';
import api, { WS_URL } from '../services/api';
// --- EXACT COPY OF YOUR DASHCARD ---
const DashCard = ({ t, isAdmin, onClick, onEdit }) => (
<div onClick={onClick} className="bg-white dark:bg-zinc-900 rounded-3xl p-5 shadow-sm border border-zinc-200 dark:border-zinc-800 cursor-pointer hover:shadow-2xl hover:-translate-y-1.5 transition-all relative overflow-hidden group">
<div className="absolute top-0 left-0 w-2 h-full bg-orange-600 group-hover:w-3 transition-all"></div>
// --- RESTORED DASHCARD DESIGN ---
const DashCard = ({ t, isAdmin, onSelect, onEdit }) => (
<div
onClick={() => onSelect(t.id)}
className="block bg-white dark:bg-zinc-900 p-6 rounded-xl shadow-sm border border-zinc-200 dark:border-zinc-800 relative group hover:shadow-md hover:scale-[1.02] transition-all duration-200 will-change-transform transform-gpu cursor-pointer"
>
<div className="flex justify-between items-start mb-4">
<h3 className="font-black text-xl text-zinc-900 dark:text-white truncate pr-4 leading-tight">{t.name}</h3>
<div className="min-w-0 pr-4">
<h2 className="text-xl font-bold truncate text-zinc-900 dark:text-white group-hover:text-orange-500 dark:group-hover:text-orange-400 transition">
{t.name}
</h2>
<div className="text-xs text-zinc-400 dark:text-zinc-500 mt-1 font-mono flex items-center gap-2">
{/* Parse date safely */}
<span>{t.timestamp ? new Date(t.timestamp).toLocaleDateString() : 'TBD'}</span>
<span>{t.timestamp ? new Date(t.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}</span>
</div>
</div>
<span className="bg-orange-100 dark:bg-orange-900/50 text-orange-700 dark:text-orange-300 text-[10px] px-2 py-1 rounded font-mono border border-orange-200 dark:border-orange-800 uppercase tracking-tight shrink-0">
{t.type}
</span>
</div>
<div className="flex gap-4 text-sm text-zinc-500 dark:text-zinc-400 items-center">
<div className="flex items-center gap-1.5 font-medium">
<Users size={16} className="text-orange-500" />
{t.team_count} Teams
</div>
<div className="flex items-center gap-1.5 font-medium">
<MapPin size={16} className="text-orange-500" />
{t.court_count} Courts
</div>
{isAdmin && (
<button
onClick={(e) => { e.stopPropagation(); onEdit(t); }}
className="text-zinc-300 hover:text-orange-500 transition p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-2xl shrink-0"
className="ml-auto hover:text-orange-500 transition z-10 h-8 w-8 flex items-center justify-center rounded-full text-zinc-500 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800"
title="Tournament Settings"
>
<SlidersHorizontal size={18} strokeWidth={2.5} />
<SlidersHorizontal size={18} />
</button>
)}
</div>
<div className="space-y-2.5">
<div className="flex items-center gap-2.5 text-zinc-700 dark:text-zinc-300 font-bold text-sm tracking-tight">
<Calendar size={16} className="text-orange-600 shrink-0" />
{/* Use safe date parsing */}
<span>{t.timestamp ? new Date(t.timestamp).toLocaleDateString() : 'TBD'} <span className="text-zinc-300 dark:text-zinc-700 mx-1">/</span> {t.timestamp ? new Date(t.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}</span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2.5 text-zinc-700 dark:text-zinc-300 font-bold text-sm tracking-tight">
<Users size={16} className="text-orange-600 shrink-0" />
<span>{t.team_count} Teams</span>
</div>
<span className="bg-zinc-100 dark:bg-zinc-800 px-2 py-0.5 rounded-lg text-[10px] font-black uppercase tracking-widest border border-zinc-200 dark:border-zinc-700 text-zinc-500">
{t.type}
</span>
</div>
</div>
</div>
);
export default function Dashboard() {
const { setNavTitle, isAdmin } = useOutletContext();
const { setNavTitle, setNavSubtitle, isAdmin, showSettings, setShowSettings } = useOutletContext();
const [tournaments, setTournaments] = useState([]);
const [loading, setLoading] = useState(true);
const [showCreate, setShowCreate] = useState(false);
const [editTarget, setEditTarget] = useState(null);
const [showPast, setShowPast] = useState(false);
const [showAllFuture, setShowAllFuture] = useState(false);
const navigate = useNavigate();
const loadDashboard = async () => {
try {
const res = await api.get('/tournaments');
const list = Array.isArray(res) ? res : (res.items || []);
setTournaments(list);
} catch (e) { console.error(e); }
};
useEffect(() => {
setNavTitle('Dashboard');
loadTournaments();
setNavSubtitle('');
loadDashboard();
let ws;
const connect = () => {
try {
ws = new WebSocket(WS_URL);
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
if (msg.type === 'dashboard_update') loadDashboard();
};
} catch (err) { }
};
connect();
return () => { if (ws) ws.close(); };
}, []);
const loadTournaments = async () => {
try {
const data = await api.get('/tournaments');
setTournaments(data);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
const handleEdit = (t) => {
setEditTarget(t);
setShowSettings(true);
};
const handleSuccess = () => {
setShowSettings(false);
setEditTarget(null);
loadDashboard();
};
const handleDelete = async (id) => {
if (window.confirm("Purge this tournament and all its history?")) {
await api.delete(`/tournaments/${id}`);
handleSuccess();
}
};
// --- REPLICATED GROUPING LOGIC ---
// Grouping Logic
const now = new Date();
const groups = { live: [], future: [], past: [] };
@@ -78,65 +118,78 @@ export default function Dashboard() {
else groups.past.push(t);
});
// Sort
groups.future.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
groups.live.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
groups.past.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
if (loading) return <div className="flex h-full items-center justify-center"><Loader2 className="animate-spin text-orange-600" size={48} /></div>;
const futureShow = showAllFuture ? groups.future : groups.future.slice(0, 4);
return (
<div className="container mx-auto max-w-5xl p-6 pb-24 space-y-16 animate-in slide-in-from-bottom-4 duration-500">
<div className="h-full overflow-y-auto pt-8 sm:pt-12 pb-32">
<div className="container mx-auto max-w-5xl px-4 space-y-12">
{/* Create Button only if Admin */}
<div className="flex justify-end">
{isAdmin && (
<button onClick={() => { setEditTarget(null); setShowCreate(true); }} className="bg-orange-600 hover:bg-orange-500 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 text-[10px] font-black uppercase tracking-wider shadow-xl shadow-orange-600/20 active:scale-95 transition">
<Plus size={16} strokeWidth={4} /> Create
</button>
{/* Create Button */}
<div className="flex justify-end">
{isAdmin && (
<button onClick={() => { setEditTarget(null); setShowSettings(true); }} className="bg-orange-600 hover:bg-orange-500 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 text-[10px] font-black uppercase tracking-wider shadow-xl shadow-orange-600/20 active:scale-95 transition">
<Plus size={16} strokeWidth={4} /> Create
</button>
)}
</div>
{groups.live.length > 0 && (
<section>
<h2 className="text-[10px] font-black text-green-500 uppercase tracking-[0.4em] mb-6 flex items-center gap-3">
<div className="w-2.5 h-2.5 bg-green-500 rounded-full animate-ping shadow-lg shadow-green-500/50" /> Live Events
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{groups.live.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
</div>
</section>
)}
<section>
<h2 className="text-[10px] font-black text-zinc-400 dark:text-zinc-600 uppercase tracking-[0.4em] mb-6 flex items-center gap-3">
<Calendar size={18} /> Upcoming
</h2>
{groups.future.length > 0 ? (
<>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{futureShow.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
</div>
{groups.future.length > 4 && (
<div className="mt-8 text-center">
<button onClick={() => setShowAllFuture(!showAllFuture)} className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-500 hover:text-orange-500 transition border-b-2 border-transparent hover:border-orange-500 pb-1 flex items-center justify-center gap-1 mx-auto">
{showAllFuture ? 'Show Less' : `Show All (${groups.future.length})`}
{showAllFuture ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
</button>
</div>
)}
</>
) : <div className="p-16 text-center rounded-3xl border-2 border-dashed border-zinc-300 dark:border-zinc-800 text-zinc-400 text-xs font-black uppercase tracking-[0.3em]">No Upcoming Events</div>}
</section>
{groups.past.length > 0 && (
<section>
<button onClick={() => setShowPast(!showPast)} className="w-full flex items-center justify-between group py-6 border-t border-zinc-300 dark:border-zinc-800 transition-colors hover:border-zinc-400">
<h2 className="text-[10px] font-black text-zinc-400 dark:text-zinc-600 uppercase tracking-[0.4em] mb-6 flex items-center gap-3"><History size={18} />Archive</h2>
{showPast ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
</button>
{showPast && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4 opacity-75 hover:opacity-100 transition-opacity">
{groups.past.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onSelect={(id) => navigate(`/tournaments/${id}`)} onEdit={handleEdit} />)}
</div>
)}
</section>
)}
</div>
{groups.live.length > 0 && (
<section>
<h2 className="text-[10px] font-black text-green-500 uppercase tracking-[0.4em] mb-6 flex items-center gap-3">
<div className="w-2.5 h-2.5 bg-green-500 rounded-full animate-ping shadow-lg shadow-green-500/50" /> Live Events
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{groups.live.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onClick={() => navigate(`/tournaments/${t.id}`)} onEdit={(item) => { setEditTarget(item); setShowCreate(true); }} />)}
</div>
</section>
)}
<section>
<h2 className="text-[10px] font-black text-zinc-400 dark:text-zinc-600 uppercase tracking-[0.4em] mb-6 flex items-center gap-3">
<Calendar size={18} /> Upcoming
</h2>
{groups.future.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{groups.future.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onClick={() => navigate(`/tournaments/${t.id}`)} onEdit={(item) => { setEditTarget(item); setShowCreate(true); }} />)}
</div>
) : (
<div className="p-16 text-center rounded-3xl border-2 border-dashed border-zinc-300 dark:border-zinc-800 text-zinc-400 text-xs font-black uppercase tracking-[0.3em]">No Upcoming Events</div>
)}
</section>
{groups.past.length > 0 && (
<section>
<button onClick={() => setShowPast(!showPast)} className="w-full flex items-center justify-between group py-6 border-t border-zinc-300 dark:border-zinc-800 transition-colors hover:border-zinc-400">
<h2 className="text-[10px] font-black text-zinc-400 dark:text-zinc-600 uppercase tracking-[0.4em] mb-6 flex items-center gap-3"><History size={18} />Archive</h2>
{showPast ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
</button>
{showPast && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4 opacity-75 hover:opacity-100 transition-opacity">
{groups.past.map(t => <DashCard key={t.id} t={t} isAdmin={isAdmin} onClick={() => navigate(`/tournaments/${t.id}`)} onEdit={(item) => { setEditTarget(item); setShowCreate(true); }} />)}
</div>
)}
</section>
)}
<Modal isOpen={showCreate} onClose={() => setShowCreate(false)} title={editTarget ? "Modify Event" : "New Tournament"}>
<TournamentForm initialData={editTarget} isEdit={!!editTarget} onSuccess={(newT) => { setShowCreate(false); loadTournaments(); }} />
<Modal isOpen={showSettings} onClose={() => { setShowSettings(false); setEditTarget(null); }} title={editTarget ? 'Modify Event' : 'Initialize Event'}>
<TournamentForm
tournament={editTarget}
onSuccess={handleSuccess}
onDelete={handleDelete}
/>
</Modal>
</div>
);
+15 -28
View File
@@ -1,8 +1,8 @@
// frontend/src/pages/Login.jsx
import React, { useState } from 'react';
import { Loader2, Volleyball } from 'lucide-react';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Volleyball, ArrowRight, Loader2 } from 'lucide-react';
import api from '../services/api';
export default function Login() {
@@ -14,23 +14,21 @@ export default function Login() {
e.preventDefault();
setLoading(true);
setError(null);
const formData = new FormData(e.target);
try {
// The backend expects x-www-form-urlencoded for OAuth2
const res = await api.postForm('/auth/token', formData);
localStorage.setItem('volleyToken', res.access_token);
navigate('/');
} catch (err) {
setError('Invalid credentials. Please try again.');
setError('Invalid credentials.');
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-zinc-50 dark:bg-zinc-950 p-4">
<div className="min-h-screen flex items-center justify-center bg-zinc-50 dark:bg-zinc-950 p-4 transition-colors">
<div className="w-full max-w-md bg-white dark:bg-zinc-900 rounded-3xl shadow-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
<div className="p-8">
<div className="flex justify-center mb-8">
@@ -39,8 +37,8 @@ export default function Login() {
</div>
</div>
<h1 className="text-2xl font-black text-center text-zinc-900 dark:text-white tracking-tight mb-2">Admin Access</h1>
<p className="text-center text-zinc-500 text-sm font-medium mb-8">Enter your credentials to manage events</p>
<h1 className="text-2xl font-black text-center text-zinc-900 dark:text-white tracking-tight mb-2">System Access</h1>
<p className="text-center text-zinc-500 text-sm font-medium mb-8">Enter administrative credentials</p>
{error && (
<div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-xs font-bold uppercase tracking-wide rounded-xl text-center border border-red-100 dark:border-red-900/50">
@@ -48,34 +46,23 @@ export default function Login() {
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1">
<label className="text-[10px] font-black uppercase tracking-widest text-zinc-400 ml-1">Username</label>
<input
name="username"
placeholder="admin"
required
className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 p-4 rounded-xl font-bold dark:text-white outline-none focus:border-orange-500 focus:ring-4 focus:ring-orange-500/10 transition"
/>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="space-y-2">
<label className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-500">Identity</label>
<input name="username" placeholder="Admin UID" required className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-4 rounded-2xl dark:text-white outline-none focus:border-orange-500 transition font-bold" />
</div>
<div className="space-y-1">
<label className="text-[10px] font-black uppercase tracking-widest text-zinc-400 ml-1">Password</label>
<input
name="password"
type="password"
placeholder="••••••••"
required
className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 p-4 rounded-xl font-bold dark:text-white outline-none focus:border-orange-500 focus:ring-4 focus:ring-orange-500/10 transition"
/>
<div className="space-y-2">
<label className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-500">Secret Key</label>
<input name="password" type="password" placeholder="••••••••" required className="w-full bg-zinc-50 dark:bg-zinc-950 border border-zinc-300 dark:border-zinc-800 p-4 rounded-2xl dark:text-white outline-none focus:border-orange-500 transition font-bold" />
</div>
<button
type="submit"
disabled={loading}
className="w-full bg-orange-600 hover:bg-orange-500 text-white p-4 rounded-xl font-black uppercase tracking-widest text-xs shadow-xl shadow-orange-600/20 transition active:scale-95 flex items-center justify-center gap-2 mt-4"
className="w-full bg-orange-600 hover:bg-orange-500 text-white py-5 rounded-2xl font-black uppercase tracking-[0.2em] text-xs shadow-2xl shadow-orange-600/30 transition active:scale-95 mt-4 flex justify-center items-center gap-2"
>
{loading ? <Loader2 className="animate-spin" size={18} /> : <>Sign In <ArrowRight size={18} /></>}
{loading ? <Loader2 className="animate-spin" size={18} /> : 'Authenticate'}
</button>
</form>
</div>
+146
View File
@@ -0,0 +1,146 @@
// frontend/src/pages/Tournament.jsx
import { CalendarDays, Loader2, Network, Settings } from 'lucide-react';
import { useEffect, useState, useRef } from 'react';
import { useOutletContext, useParams } from 'react-router-dom';
import BracketView from '../components/Bracket/BracketView';
import TournamentForm from '../components/Forms/TournamentForm';
import ScheduleView from '../components/Schedule/ScheduleView';
import ScoreModal from '../components/Tournament/ScoreModal';
import Modal from '../components/UI/Modal';
import api, { WS_URL } from '../services/api';
export default function Tournament() {
const { id } = useParams();
const { setNavTitle, setNavSubtitle, isAdmin } = useOutletContext();
const [details, setDetails] = useState(null);
const [matches, setMatches] = useState([]);
const [view, setView] = useState('bracket');
const [loading, setLoading] = useState(true);
const [showSettings, setShowSettings] = useState(false);
const [scoreMatch, setScoreMatch] = useState(null);
const wsRef = useRef(null);
// --- DATA PROCESSOR ---
const processMatches = (rawMatches, courts, teams) => {
if (!rawMatches) return [];
const courtMap = Object.fromEntries(courts.map(c => [c.id, c.name]));
const teamMap = Object.fromEntries(teams.map(t => [t.id, t.name]));
const incoming = {};
rawMatches.forEach(m => {
const num = m.match_number;
if (m.winner_next_match_id) {
(incoming[m.winner_next_match_id] = incoming[m.winner_next_match_id] || []).push({ label: `Winner of #${num}`, id: m.id });
}
if (m.loser_next_match_id) {
(incoming[m.loser_next_match_id] = incoming[m.loser_next_match_id] || []).push({ label: `Loser of #${num}`, id: m.id });
}
});
return rawMatches.map(m => {
const sources = incoming[m.id] || [];
const p1 = m.p1_team_id ? teamMap[m.p1_team_id] : (sources[0]?.label || 'TBD');
const p2 = m.p2_team_id ? teamMap[m.p2_team_id] : (sources[1]?.label || 'TBD');
const winnerName = m.winner_team_id ? teamMap[m.winner_team_id] : null;
const hasTeams = !!(m.p1_team_id && m.p2_team_id);
const isFinished = m.status === "Finished";
const isReady = hasTeams && !isFinished;
return {
...m,
bracket: m.bracket_type,
round: m.round_number,
number: m.match_number,
p1,
p2,
p1_is_real: !!m.p1_team_id,
p2_is_real: !!m.p2_team_id,
winnerName,
isReady,
court: courtMap[m.court_id] || 'TBD',
time: m.start_time ? new Date(m.start_time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '',
p1_sets: m.sets?.filter(s => s.p1 > s.p2).length || 0,
p2_sets: m.sets?.filter(s => s.p2 > s.p1).length || 0,
hasTeams,
isReady,
isFinished
};
});
};
const fetchData = async () => {
try {
const res = await api.get(`/tournaments/${id}`);
setDetails(res);
setNavTitle(res.name);
setNavSubtitle(new Date(res.timestamp).toLocaleDateString());
setMatches(processMatches(res.matches, res.courts, res.teams));
} catch (err) { console.error(err); } finally { setLoading(false); }
};
useEffect(() => {
fetchData();
if (wsRef.current) return;
const connect = () => {
const ws = new WebSocket(WS_URL);
wsRef.current = ws;
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
if (msg.type === 'tournament_update' && msg.id === id) fetchData();
};
ws.onclose = () => { wsRef.current = null; };
};
connect();
return () => { if (wsRef.current?.readyState === 1) wsRef.current.close(); wsRef.current = null; };
}, [id]);
const handleDeleteTournament = async (tId) => {
if (window.confirm("Purge this tournament?")) {
await api.delete(`/tournaments/${tId}`);
window.location.href = '/';
}
};
if (loading) return <div className="flex h-full items-center justify-center"><Loader2 className="animate-spin text-orange-600" size={48} /></div>;
return (
<div className="h-full flex flex-col">
<div className="border-b border-zinc-200 dark:border-zinc-800 bg-white/50 dark:bg-zinc-900/50 backdrop-blur px-6 py-3 flex justify-between items-center shrink-0 z-20">
<div className="flex gap-2">
<button onClick={() => setView('bracket')} className={`flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition ${view === 'bracket' ? 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' : 'text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800'}`}>
<Network size={16} /> Bracket
</button>
<button onClick={() => setView('schedule')} className={`flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition ${view === 'schedule' ? 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' : 'text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800'}`}>
<CalendarDays size={16} /> Schedule
</button>
</div>
{isAdmin && <button onClick={() => setShowSettings(true)} className="p-2 text-zinc-400 hover:text-orange-600 transition rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800"><Settings size={20} /></button>}
</div>
<div className="flex-1 overflow-hidden relative">
{view === 'bracket'
? <BracketView matches={matches} onMatchClick={setScoreMatch} />
: <ScheduleView schedule={matches} onMatchClick={setScoreMatch} />
}
</div>
{scoreMatch && (
<ScoreModal
isOpen={!!scoreMatch} onClose={() => setScoreMatch(null)} match={scoreMatch} isAdmin={isAdmin}
onClear={async (mid, c) => { await api.delete(`/tournaments/${id}/matches/${mid}/score?code=${encodeURIComponent(c || '')}`); setScoreMatch(null); }}
onSubmit={async (mid, s, c) => { await api.post(`/tournaments/${id}/matches/${mid}/score`, { sets: s, code: c }); setScoreMatch(null); }}
/>
)}
<Modal isOpen={showSettings} onClose={() => setShowSettings(false)} title="Edit Tournament">
<TournamentForm tournament={details} onSuccess={() => { setShowSettings(false); fetchData(); }} onDelete={handleDeleteTournament} />
</Modal>
</div>
);
}
-107
View File
@@ -1,107 +0,0 @@
// frontend/src/pages/TournamentPage.jsx
import { CalendarDays, Loader2, Network, Settings } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useOutletContext, useParams } from 'react-router-dom';
import BracketView from '../components/Bracket/BracketView';
import TournamentForm from '../components/Forms/TournamentForm';
import ScheduleView from '../components/Schedule/ScheduleView';
import ScoreModal from '../components/Tournament/ScoreModal';
import Modal from '../components/UI/Modal';
import api, { WS_URL } from '../services/api';
export default function TournamentPage() {
const { id } = useParams();
const { setNavTitle, setNavSubtitle, isAdmin } = useOutletContext();
const [details, setDetails] = useState(null);
const [nodes, setNodes] = useState([]);
const [view, setView] = useState('bracket'); // 'bracket' | 'schedule'
const [loading, setLoading] = useState(true);
const [showSettings, setShowSettings] = useState(false);
const [scoreMatchNode, setScoreMatchNode] = useState(null);
const fetchData = async () => {
try {
// 1. Fetch Metadata
const meta = await api.get(`/tournaments/${id}`);
setDetails(meta);
setNavTitle(meta.name);
setNavSubtitle(new Date(meta.timestamp).toLocaleDateString());
// 2. Fetch Structure (Nodes)
const bracketData = await api.get(`/tournaments/${id}/bracket`);
setNodes(bracketData);
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
// WebSocket for Live Updates
const ws = new WebSocket(WS_URL);
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
if (msg.type === 'tournament_update' && msg.id === id) {
fetchData();
}
};
return () => ws.close();
}, [id]);
if (loading) return <div className="flex h-full items-center justify-center"><Loader2 className="animate-spin text-orange-600" size={48} /></div>;
return (
<div className="h-full flex flex-col">
{/* Toolbar */}
<div className="border-b border-zinc-200 dark:border-zinc-800 bg-white/50 dark:bg-zinc-900/50 backdrop-blur px-6 py-3 flex justify-between items-center shrink-0">
<div className="flex gap-2">
<button
onClick={() => setView('bracket')}
className={`flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition ${view === 'bracket' ? 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' : 'text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800'}`}
>
<Network size={16} /> Bracket
</button>
<button
onClick={() => setView('schedule')}
className={`flex items-center gap-2 px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider transition ${view === 'schedule' ? 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400' : 'text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800'}`}
>
<CalendarDays size={16} /> Schedule
</button>
</div>
{isAdmin && (
<button onClick={() => setShowSettings(true)} className="p-2 text-zinc-400 hover:text-orange-600 transition rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800">
<Settings size={20} />
</button>
)}
</div>
{/* Main Content Area */}
<div className="flex-1 overflow-hidden relative">
{view === 'bracket'
? <BracketView nodes={nodes} onMatchClick={setScoreMatchNode} />
: <ScheduleView nodes={nodes} onMatchClick={setScoreMatchNode} />
}
</div>
{scoreMatchNode && (
<ScoreModal
isOpen={!!scoreMatchNode}
onClose={() => setScoreMatchNode(null)}
node={scoreMatchNode}
tournamentId={id}
isAdmin={isAdmin}
/>
)}
<Modal isOpen={showSettings} onClose={() => setShowSettings(false)} title="Edit Tournament">
<TournamentForm initialData={details} onSuccess={() => { setShowSettings(false); fetchData(); }} isEdit />
</Modal>
</div>
);
}
+35 -29
View File
@@ -1,42 +1,48 @@
// frontend/src/services/api.js
import axios from 'axios';
const getBackendHost = () => {
const host = window.location.hostname || 'localhost';
return host;
};
// Updated to include /api prefix
export const API_BASE = `${window.location.protocol}//${getBackendHost()}:8000/api`;
export const WS_URL = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${getBackendHost()}:8000/ws`;
const port = '8000';
const api = axios.create({
baseURL: API_BASE,
headers: {
'Content-Type': 'application/json',
},
});
export const API_BASE = `${window.location.protocol}//${getBackendHost()}:${port}/api`;
export const WS_URL = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${getBackendHost()}:${port}/api/ws`;
// Request Interceptor for Auth
api.interceptors.request.use((config) => {
const token = localStorage.getItem('volleyToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Response Interceptor for Errors
api.interceptors.response.use(
(response) => response.data,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('volleyToken');
window.location.href = '/login';
export const getToken = () => localStorage.getItem('volleyToken');
const api = {
request: async (method, url, data = null, isFormData = false) => {
const headers = {};
const token = getToken();
if (token) headers['Authorization'] = `Bearer ${token}`;
if (!isFormData) headers['Content-Type'] = 'application/json';
const opts = { method, headers };
if (data) opts.body = isFormData ? data : JSON.stringify(data);
// Ensure clean URL concatenation
const baseUrl = API_BASE.endsWith('/') ? API_BASE.slice(0, -1) : API_BASE;
const endpoint = url.startsWith('/') ? url : `/${url}`;
const res = await fetch(`${baseUrl}${endpoint}`, opts);
if (!res.ok) {
if (res.status === 401) {
localStorage.removeItem('volleyToken');
window.location.href = '/login';
}
throw await res.json();
}
return Promise.reject(error.response?.data || error.message);
}
);
return res.json();
},
get: (url) => api.request('GET', url),
post: (url, data) => api.request('POST', url, data),
postForm: (url, data) => api.request('POST', url, data, true),
put: (url, data) => api.request('PUT', url, data),
patch: (url, data) => api.request('PATCH', url, data),
delete: (url) => api.request('DELETE', url)
};
export default api;
+1 -2
View File
@@ -14,8 +14,7 @@ export default defineConfig({
},
resolve: {
alias: {
"/": path.resolve(__dirname, "./public"),
'@': path.resolve(__dirname, './src'),
},
},
})