This commit is contained in:
Zeeshaun
2026-05-06 16:27:48 +00:00
parent 02186dcdfa
commit 1d587599fc
17 changed files with 834 additions and 136 deletions
@@ -0,0 +1,321 @@
"use client";
import { FileText, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { ConfirmDialog } from "@/components/ConfirmDialog";
import { EmptyState } from "@/components/EmptyState";
import { SectionCard } from "@/components/SectionCard";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { fetchJson } from "@/lib/client";
import type { GamePlayerStatsInput, GameRecord, LineupRecord } from "@/lib/types";
const statFields = [
["atBats", "AB"],
["runs", "R"],
["hits", "H"],
["doubles", "2B"],
["triples", "3B"],
["homeRuns", "HR"],
["runsBattedIn", "RBI"],
["walks", "BB"],
["strikeouts", "SO"],
["stolenBases", "SB"]
] as const;
function pickDefaultLineupId(gameDate: string, lineups: LineupRecord[]) {
const exactDate = lineups.find((lineup) => lineup.gameDate === gameDate);
return exactDate?._id ?? lineups[0]?._id ?? "";
}
export function GameScoringClient() {
const [gameDate, setGameDate] = useState(new Date().toISOString().slice(0, 10));
const [lineups, setLineups] = useState<LineupRecord[]>([]);
const [selectedLineupId, setSelectedLineupId] = useState("");
const [savedGames, setSavedGames] = useState<GameRecord[]>([]);
const [gamePendingDelete, setGamePendingDelete] = useState<GameRecord | null>(null);
const [opponent, setOpponent] = useState("");
const [teamScore, setTeamScore] = useState<string>("");
const [opponentScore, setOpponentScore] = useState<string>("");
const [notes, setNotes] = useState("");
const [playerStats, setPlayerStats] = useState<Record<string, GamePlayerStatsInput>>({});
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
async function loadLineups() {
try {
const response = await fetchJson<LineupRecord[]>("/api/lineups");
setLineups(response);
setSelectedLineupId((current) => (current && response.some((lineup) => lineup._id === current) ? current : pickDefaultLineupId(gameDate, response)));
} catch (loadError) {
setError(loadError instanceof Error ? loadError.message : "Failed to load lineups.");
}
}
async function loadSavedGames(targetDate: string) {
try {
const response = await fetchJson<GameRecord[]>(`/api/games?gameDate=${targetDate}`);
setSavedGames(response);
} catch (loadError) {
setError(loadError instanceof Error ? loadError.message : "Failed to load games.");
}
}
useEffect(() => {
void loadLineups();
}, []);
useEffect(() => {
void loadSavedGames(gameDate);
setSelectedLineupId((current) => {
if (current && lineups.some((lineup) => lineup._id === current)) {
return current;
}
return pickDefaultLineupId(gameDate, lineups);
});
}, [gameDate, lineups]);
const selectedLineup = useMemo(
() => lineups.find((lineup) => lineup._id === selectedLineupId) ?? null,
[lineups, selectedLineupId]
);
useEffect(() => {
if (!selectedLineup) {
setPlayerStats({});
return;
}
setPlayerStats((current) =>
Object.fromEntries(
selectedLineup.battingOrder.map((slot) => [
slot.playerId,
current[slot.playerId] ?? {
playerId: slot.playerId,
playerName: slot.playerName
}
])
)
);
}, [selectedLineup]);
function updatePlayerStat(playerId: string, playerName: string, field: keyof Omit<GamePlayerStatsInput, "playerId" | "playerName">, value: string) {
setPlayerStats((current) => ({
...current,
[playerId]: {
...(current[playerId] ?? { playerId, playerName }),
playerId,
playerName,
[field]: value === "" ? null : Number(value)
}
}));
}
async function saveGame() {
if (!selectedLineup || !selectedLineup._id) {
setError("Select a saved lineup before scoring the game.");
return;
}
try {
const payload = {
gameDate,
lineupId: selectedLineup._id,
opponent,
teamScore: teamScore === "" ? null : Number(teamScore),
opponentScore: opponentScore === "" ? null : Number(opponentScore),
notes,
playerStats: selectedLineup.battingOrder.map((slot) => playerStats[slot.playerId] ?? { playerId: slot.playerId, playerName: slot.playerName })
};
const saved = await fetchJson<GameRecord>("/api/games", {
method: "POST",
body: JSON.stringify(payload)
});
setMessage(`Saved game #${saved.gameNumber} for ${saved.gameDate}.`);
setOpponent("");
setTeamScore("");
setOpponentScore("");
setNotes("");
setPlayerStats({});
await loadSavedGames(gameDate);
} catch (saveError) {
setError(saveError instanceof Error ? saveError.message : "Unable to save game.");
}
}
async function deleteGame(game: GameRecord) {
if (!game._id) return;
try {
await fetchJson(`/api/games/${game._id}`, { method: "DELETE" });
setMessage(`Deleted game #${game.gameNumber}.`);
setGamePendingDelete(null);
await loadSavedGames(gameDate);
} catch (deleteError) {
setError(deleteError instanceof Error ? deleteError.message : "Unable to delete game.");
}
}
return (
<AppShell
title="Score Game"
subtitle="Pick the lineup used, enter the results, and roll the stats into each player automatically."
>
<ConfirmDialog
open={gamePendingDelete !== null}
title="Delete Saved Game?"
description={
gamePendingDelete
? `Delete game #${gamePendingDelete.gameNumber} for ${gamePendingDelete.gameDate}? Player stats from that game will be reversed.`
: ""
}
confirmLabel="Delete Game"
onCancel={() => setGamePendingDelete(null)}
onConfirm={() => (gamePendingDelete ? void deleteGame(gamePendingDelete) : undefined)}
/>
{message ? <Alert tone="success">{message}</Alert> : null}
{error ? <Alert tone="error">{error}</Alert> : null}
<SectionCard
title="Game Setup"
description="Choose the lineup used in the game. The latest saved lineup is selected by default."
>
{lineups.length > 0 ? (
<div className="grid gap-4 md:grid-cols-2">
<label>
<span className="field-label">Game Date</span>
<Input type="date" value={gameDate} onChange={(event) => setGameDate(event.target.value)} />
</label>
<label>
<span className="field-label">Lineup Used</span>
<select className="field-select" value={selectedLineupId} onChange={(event) => setSelectedLineupId(event.target.value)}>
{lineups.map((lineup) => (
<option key={lineup._id} value={lineup._id}>
{lineup.gameDate} · Lineup #{lineup.lineupNumber}
</option>
))}
</select>
</label>
<label>
<span className="field-label">Opponent</span>
<Input value={opponent} onChange={(event) => setOpponent(event.target.value)} placeholder="Optional" />
</label>
<div className="grid grid-cols-2 gap-3">
<label>
<span className="field-label">Our Score</span>
<Input type="number" min={0} value={teamScore} onChange={(event) => setTeamScore(event.target.value)} />
</label>
<label>
<span className="field-label">Their Score</span>
<Input type="number" min={0} value={opponentScore} onChange={(event) => setOpponentScore(event.target.value)} />
</label>
</div>
<label className="md:col-span-2">
<span className="field-label">Game Notes</span>
<Textarea rows={3} value={notes} onChange={(event) => setNotes(event.target.value)} />
</label>
</div>
) : (
<EmptyState
title="No lineup available"
description="Save a lineup on the lineup tab first, then return here to score the game."
/>
)}
</SectionCard>
{selectedLineup ? (
<SectionCard
title="Player Results"
description="Stat entry is optional. Leave any field blank if you do not want to track it for that player."
>
<div className="grid gap-3">
{selectedLineup.battingOrder.map((slot, index) => {
const statLine = playerStats[slot.playerId] ?? { playerId: slot.playerId, playerName: slot.playerName };
return (
<Card key={slot.playerId}>
<CardContent className="grid gap-3 pt-4">
<div className="flex items-center gap-3">
<div className="inline-flex h-8 w-8 items-center justify-center rounded-full bg-muted text-xs font-semibold text-muted-foreground">
{index + 1}
</div>
<div>
<h3 className="text-sm font-semibold">{slot.playerName}</h3>
<p className="text-xs text-muted-foreground">Batting order slot {index + 1}</p>
</div>
</div>
<div className="grid grid-cols-3 gap-2 sm:grid-cols-5">
{statFields.map(([field, label]) => (
<label key={field}>
<span className="field-label">{label}</span>
<Input
type="number"
min={0}
value={statLine[field] ?? ""}
onChange={(event) => updatePlayerStat(slot.playerId, slot.playerName, field, event.target.value)}
/>
</label>
))}
</div>
</CardContent>
</Card>
);
})}
<div>
<Button onClick={() => void saveGame()}>Save Game</Button>
</div>
</div>
</SectionCard>
) : null}
<SectionCard
title="Saved Games"
description="Previously saved games for the selected date can be deleted."
>
{savedGames.length > 0 ? (
<div className="grid gap-3">
{savedGames.map((game) => (
<Card key={game._id}>
<CardContent className="flex items-start justify-between gap-3 pt-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 rounded-full bg-muted p-2 text-muted-foreground">
<FileText className="h-4 w-4" />
</div>
<div>
<h3 className="text-sm font-semibold">
{game.gameDate} · Game #{game.gameNumber}
</h3>
<p className="mt-1 text-xs text-muted-foreground">
Lineup #{game.lineupNumber ?? "?"}
{game.opponent ? ` · vs ${game.opponent}` : ""}
{game.teamScore !== null && game.teamScore !== undefined && game.opponentScore !== null && game.opponentScore !== undefined
? ` · ${game.teamScore}-${game.opponentScore}`
: ""}
</p>
</div>
</div>
<Button size="sm" variant="destructive" className="gap-1" onClick={() => setGamePendingDelete(game)}>
<Trash2 className="h-3.5 w-3.5" />
Delete
</Button>
</CardContent>
</Card>
))}
</div>
) : (
<EmptyState
title="No saved games"
description="Score and save a game to keep a dated history here."
/>
)}
</SectionCard>
</AppShell>
);
}