1
0
Fork 0
polaris-task-force/src/components/frontend/opord/OpordLeaderboard.tsx
Z8MB1E eaa0325b6d feat(minigames): add OPORD Recall briefing-recall minigame
- seeded OPORD generator (grid, azimuth, H-HOUR, phase lines, codewords, callsign, frequency) in pure lib src/lib/opord-recall.ts with per-tier memo windows (25/18/12s) and quiz sizes (4/6/8)
- server action submitOpordRecallResult validates input, recomputes score server-side, persists to Profiles progression.minigames.opordRecall, broadcasts XP, emits minigame:opord-recall event
- UI at /opord: briefing countdown, one-at-a-time quiz, debrief metres, tier radio group, SSE presence, REST leaderboard per tier
- profiles migration 20260908_152021 (7 additive columns) + XP hook wiring
- nav entries in command palette and NavUser Exercises submenu
- e2e spec plays a full round and asserts debrief + leaderboard row
2026-09-08 11:26:18 -04:00

219 lines
8.7 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import { Trophy } from "lucide-react";
import type { OpordDifficulty } from "@/lib/opord-recall";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import type { PresenceParticipant } from "@/hooks/useRealtimePresence";
import { cn } from "@/lib/utils";
import { OPORD_LEADERBOARD_FIELDS, readOpordProfiles } from "./opordLeaderboardData";
type LeaderboardRow = {
readonly id: number;
readonly userId: number | null;
readonly name: string;
readonly gamesPlayed: number;
readonly bestScore: number;
readonly bestAccuracy: number;
readonly isCurrentUser: boolean;
readonly isOutsideTopTen?: boolean;
};
function rankClass(index: number): string {
if (index === 0) return "font-bold text-amber-400";
if (index === 1) return "font-semibold text-slate-300";
if (index === 2) return "font-semibold text-amber-700";
return "text-muted-foreground";
}
export function OpordLeaderboard({
refreshKey = 0,
difficulty,
currentUserId,
activeOperators = [],
}: {
readonly refreshKey?: number;
readonly difficulty: OpordDifficulty;
readonly currentUserId?: number | string;
readonly activeOperators?: readonly PresenceParticipant[];
}) {
const [rows, setRows] = useState<readonly LeaderboardRow[] | null>(null);
const [failed, setFailed] = useState<string | null>(null);
const tier = OPORD_LEADERBOARD_FIELDS[difficulty];
useEffect(() => {
let cancelled = false;
setFailed(null);
setRows(null);
const field = `progression.minigames.opordRecall.${tier.scoreField}`;
const params = new URLSearchParams({
sort: `-${field}`,
limit: "100",
depth: "1",
});
fetch(`/api/profiles?${params.toString()}`)
.then(async (response) => {
if (!response.ok) throw new Error("leaderboard fetch failed");
const payload: unknown = await response.json();
return readOpordProfiles(payload);
})
.then((profiles) => {
if (cancelled) return;
const mapped: LeaderboardRow[] = profiles.map((profile) => {
const user =
typeof profile.user === "object" && profile.user !== null ? profile.user : null;
const userId = user?.id ?? (typeof profile.user === "number" ? profile.user : null);
const name =
user?.displayName ||
user?.payloadDisplayName ||
profile.profileTitle ||
user?.username ||
`Operator #${profile.id}`;
const opordRecall = profile.opordRecall;
return {
id: profile.id,
userId,
name,
gamesPlayed: opordRecall?.gamesPlayed ?? 0,
bestScore: opordRecall?.[tier.scoreField] ?? 0,
bestAccuracy: opordRecall?.bestAccuracy ?? 0,
isCurrentUser: userId !== null && String(userId) === String(currentUserId),
};
});
const scored = mapped
.filter((row) => row.bestScore > 0)
.sort(
(left, right) =>
right.bestScore - left.bestScore || right.bestAccuracy - left.bestAccuracy,
);
const visible = scored.slice(0, 10);
const current = mapped.find((row) => row.isCurrentUser);
if (current && !visible.some((row) => row.id === current.id)) {
visible.push({ ...current, isOutsideTopTen: true });
}
setRows(visible);
})
.catch((error: unknown) => {
if (cancelled) return;
setFailed(error instanceof Error ? error.message : "leaderboard fetch failed");
});
return () => {
cancelled = true;
};
}, [currentUserId, difficulty, refreshKey, tier.scoreField]);
return (
<Card className="w-full max-w-3xl overflow-hidden">
<CardHeader className="gap-1 border-b border-border px-4 py-3">
<div className="flex items-center gap-2">
<Trophy aria-hidden="true" className="size-4 text-amber-400" />
<CardTitle className="text-sm">OPORD Recall leaderboard</CardTitle>
<span className="ml-auto text-xs text-muted-foreground">{tier.label} · Top 10</span>
</div>
<CardDescription>Best score for the selected briefing tier.</CardDescription>
</CardHeader>
<div
className="border-b border-border px-4 py-2 text-xs text-muted-foreground"
aria-live="polite"
>
<span className="font-medium text-emerald-400">{activeOperators.length}</span>{" "}
{activeOperators.length === 1 ? "operator is" : "operators are"} studying briefings
{activeOperators.length > 0 && (
<span className="ml-1 text-foreground">
({activeOperators.map((operator) => operator.name).join(", ")})
</span>
)}
</div>
<CardContent className="p-0">
{failed !== null ? (
<p className="px-4 py-4 text-sm text-muted-foreground">Could not load the leaderboard.</p>
) : rows === null ? (
<div className="flex flex-col gap-2 px-4 py-4">
<Skeleton className="h-4 w-full motion-reduce:animate-none" />
<Skeleton className="h-4 w-3/4 motion-reduce:animate-none" />
<Skeleton className="h-4 w-1/2 motion-reduce:animate-none" />
</div>
) : rows.length === 0 ? (
<p className="px-4 py-4 text-sm text-muted-foreground">
No scores logged for this tier yet. Be the first to brief up.
</p>
) : (
<div className="overflow-x-auto">
<table className="w-full min-w-lg text-sm">
<thead>
<tr className="text-left text-xs uppercase tracking-wider text-muted-foreground">
<th className="px-4 py-2 font-medium">#</th>
<th className="px-2 py-2 font-medium">Operator</th>
<th className="px-2 py-2 text-right font-medium">Games</th>
<th className="px-2 py-2 text-right font-medium">Accuracy</th>
<th
aria-sort="descending"
className="px-4 py-2 text-right font-medium text-foreground"
>
Score
</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{rows.map((row, index) => (
<tr
key={row.id}
className={cn(
row.isCurrentUser && "bg-accent/40",
row.isOutsideTopTen && "text-muted-foreground opacity-70",
)}
title={
row.isOutsideTopTen
? "Operator status: not currently ranked in the top 10"
: undefined
}
>
<td className="px-4 py-2">
<span className={rankClass(index)}>
{row.isOutsideTopTen ? "-" : index + 1}
</span>
</td>
<td className="px-2 py-2 font-medium">
<span className="flex items-center gap-2">
<span className="max-w-48 truncate">{row.name}</span>
{row.isCurrentUser && (
<span className="shrink-0 text-xs text-muted-foreground">(you)</span>
)}
{row.isOutsideTopTen && (
<span className="shrink-0 text-xs font-normal uppercase tracking-wide text-muted-foreground">
unranked
</span>
)}
{row.userId !== null && activeOperators.some((operator) => operator.id === row.userId) && (
<span
className="size-2 rounded-full bg-emerald-400"
title="Playing now"
aria-label="Playing now"
/>
)}
</span>
</td>
<td className="px-2 py-2 text-right font-mono tabular-nums text-muted-foreground">
{row.gamesPlayed}
</td>
<td className="px-2 py-2 text-right font-mono tabular-nums text-muted-foreground">
{Math.round(row.bestAccuracy * 100)}%
</td>
<td className="px-4 py-2 text-right font-mono font-semibold tabular-nums">
{row.bestScore}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
);
}