1
0
Fork 0
polaris-task-force/src/components/frontend/qualification/AimTrainerLeaderboard.tsx
Z8MB1E dd2c868c89 fix(qualification): expose updated aim trainer leaderboard data
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphus.ai>
2026-09-04 12:04:44 -04:00

222 lines
8.8 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import { Trophy } from "lucide-react";
import type { AimTrainerDifficulty } from "@/lib/aim-trainer";
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 {
AIM_TRAINER_LEADERBOARD_FIELDS,
readAimTrainerProfiles,
} from "./aimTrainerLeaderboardData";
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 AimTrainerLeaderboard({
refreshKey = 0,
difficulty,
currentUserId,
activeTrainees = [],
}: {
readonly refreshKey?: number;
readonly difficulty: AimTrainerDifficulty;
readonly currentUserId?: number | string;
readonly activeTrainees?: readonly PresenceParticipant[];
}) {
const [rows, setRows] = useState<readonly LeaderboardRow[] | null>(null);
const [failed, setFailed] = useState<string | null>(null);
const tier = AIM_TRAINER_LEADERBOARD_FIELDS[difficulty];
useEffect(() => {
let cancelled = false;
setFailed(null);
setRows(null);
const field = `progression.minigames.aimTrainer.${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 readAimTrainerProfiles(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 aimTrainer = profile.aimTrainer;
return {
id: profile.id,
userId,
name,
gamesPlayed: aimTrainer?.gamesPlayed ?? 0,
bestScore: aimTrainer?.[tier.scoreField] ?? 0,
bestAccuracy: aimTrainer?.[tier.accuracyField] ?? 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.accuracyField, 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">Qualification leaderboard</CardTitle>
<span className="ml-auto text-xs text-muted-foreground">{tier.label} · Top 10</span>
</div>
<CardDescription>Best score for the selected qualification lane.</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">{activeTrainees.length}</span>{" "}
{activeTrainees.length === 1 ? "trainee is" : "trainees are"} on the line
{activeTrainees.length > 0 && (
<span className="ml-1 text-foreground">
({activeTrainees.map((trainee) => trainee.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 lane yet — take the first qualification slot.
</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
aria-sort="descending"
className="px-2 py-2 text-right font-medium text-foreground"
>
Score
</th>
<th className="px-4 py-2 text-right font-medium">Accuracy</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 && activeTrainees.some((trainee) => trainee.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 font-semibold tabular-nums">
{row.bestScore}
</td>
<td className="px-4 py-2 text-right font-mono font-semibold tabular-nums">
{Math.round(row.bestAccuracy * 100)}%
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
);
}