brackt/app/components/scoring/QualifyingPointsStandings.tsx
2026-04-12 17:06:20 -07:00

293 lines
11 KiB
TypeScript

import { Form } from "react-router";
import { Button } from "~/components/ui/button";
import { TeamOwnerBadge } from "~/components/ui/team-owner-badge";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "~/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "~/components/ui/table";
import { Trophy, CheckCircle2 } from "lucide-react";
interface TeamOwnership {
participantId: string;
teamName: string;
teamId: string;
ownerName?: string;
}
interface QPStanding {
id: string;
totalQualifyingPoints: string;
eventsScored: number;
finalRanking: number | null;
participant: {
id: string;
name: string;
};
}
interface ScoringRules {
pointsFor1st: number;
pointsFor2nd: number;
pointsFor3rd: number;
pointsFor4th: number;
pointsFor5th: number;
pointsFor6th: number;
pointsFor7th: number;
pointsFor8th: number;
}
interface QualifyingPointsStandingsProps {
standings: QPStanding[];
scoringRules: ScoringRules | null;
isFinalized: boolean;
totalMajors?: number | null;
majorsCompleted?: number;
canFinalize: boolean; // Whether all majors are complete
teamOwnerships?: TeamOwnership[];
}
export function QualifyingPointsStandings({
standings,
scoringRules,
isFinalized,
totalMajors,
majorsCompleted = 0,
canFinalize,
teamOwnerships = [],
}: QualifyingPointsStandingsProps) {
const ownershipMap = new Map(teamOwnerships.map((o) => [o.participantId, o]));
const pointsMap: Record<number, number> = scoringRules
? {
1: scoringRules.pointsFor1st,
2: scoringRules.pointsFor2nd,
3: scoringRules.pointsFor3rd,
4: scoringRules.pointsFor4th,
5: scoringRules.pointsFor5th,
6: scoringRules.pointsFor6th,
7: scoringRules.pointsFor7th,
8: scoringRules.pointsFor8th,
}
: {};
// Assign current ranks with tie handling
const rankedStandings: Array<typeof standings[0] & { currentRank: number }> = [];
let previousQP = -1;
let previousRankStart = -1;
for (let index = 0; index < standings.length; index++) {
const standing = standings[index];
const currentQP = parseFloat(standing.totalQualifyingPoints);
let currentRank: number;
if (index > 0 && Math.abs(currentQP - previousQP) < 0.001) {
currentRank = previousRankStart;
} else {
currentRank = index + 1;
}
rankedStandings.push({ ...standing, currentRank });
previousRankStart = currentRank;
previousQP = currentQP;
}
// Pre-compute tied counts per rank to avoid O(N²) scanning per row
const tiedCountByRank = new Map<number, number>();
for (const s of rankedStandings) {
tiedCountByRank.set(s.currentRank, (tiedCountByRank.get(s.currentRank) ?? 0) + 1);
}
// Calculate EV for a rank by averaging points across all tied positions
const calculateEV = (currentRank: number): number => {
if (!scoringRules || currentRank > 8) return 0;
const tiedCount = tiedCountByRank.get(currentRank) ?? 1;
let total = 0;
for (let i = 0; i < tiedCount; i++) {
total += pointsMap[currentRank + i] ?? 0;
}
return total / tiedCount;
};
return (
<Card className={isFinalized ? "border-emerald-500/30" : "border-amber-accent/30"}>
<CardHeader>
<CardTitle className={isFinalized ? "text-emerald-400" : "text-amber-accent"}>
<Trophy className="inline mr-2 h-5 w-5" />
Qualifying Points Standings
</CardTitle>
<CardDescription>
{isFinalized ? (
<span className="text-emerald-400 font-semibold">
<CheckCircle2 className="inline h-4 w-4 mr-1" />
Finalized - Fantasy points have been assigned
</span>
) : (
<>
Current standings based on {majorsCompleted} of {totalMajors || '?'} major tournaments completed.
{scoringRules ? (
<span className="block mt-1">
Projected points account for ties tied participants share the available points equally.
</span>
) : (
<span className="block mt-1 text-muted-foreground">
Projected points will be shown when linked to a fantasy season.
</span>
)}
</>
)}
</CardDescription>
</CardHeader>
<CardContent>
{standings.length === 0 ? (
<p className="text-sm text-muted-foreground">
No qualifying points awarded yet. Complete a qualifying event to see standings.
</p>
) : (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-20">Rank</TableHead>
<TableHead>Participant</TableHead>
{teamOwnerships.length > 0 && (
<TableHead className="w-40">Owner</TableHead>
)}
<TableHead className="w-28 text-right">Total QP</TableHead>
<TableHead className="w-24 text-right">Events</TableHead>
{scoringRules && !isFinalized && (
<TableHead className="w-32 text-right">Projected Points</TableHead>
)}
</TableRow>
</TableHeader>
<TableBody>
{rankedStandings.map((standing) => {
const projectedPoints = calculateEV(standing.currentRank);
const isTop8 = standing.currentRank <= 8;
const isTied = (tiedCountByRank.get(standing.currentRank) ?? 1) > 1;
return (
<TableRow key={standing.id} className={!isTop8 ? "opacity-60" : ""}>
<TableCell>
<div className="flex items-center gap-2">
{standing.currentRank === 1 && !isTied && <span className="text-xl">🥇</span>}
{standing.currentRank === 2 && !isTied && <span className="text-xl">🥈</span>}
{standing.currentRank === 3 && !isTied && <span className="text-xl">🥉</span>}
<span className="font-semibold">
{isTied && "T"}
{standing.currentRank}
{standing.currentRank === 1
? "st"
: standing.currentRank === 2
? "nd"
: standing.currentRank === 3
? "rd"
: "th"}
</span>
</div>
</TableCell>
<TableCell className="font-medium">
{standing.participant.name}
</TableCell>
{teamOwnerships.length > 0 && (
<TableCell>
{(() => {
const ownership = ownershipMap.get(standing.participant.id);
return ownership ? (
<TeamOwnerBadge
teamName={ownership.teamName}
ownerName={ownership.ownerName}
/>
) : (
<span className="text-xs text-muted-foreground">Undrafted</span>
);
})()}
</TableCell>
)}
<TableCell className="text-right">
<span className="font-semibold text-amber-accent">
{parseFloat(standing.totalQualifyingPoints).toFixed(2)} QP
</span>
</TableCell>
<TableCell className="text-right text-muted-foreground">
{standing.eventsScored}
</TableCell>
{scoringRules && !isFinalized && (
<TableCell className="text-right">
{isTop8 ? (
<span className="font-semibold text-emerald-400">
{projectedPoints % 1 === 0
? projectedPoints
: projectedPoints.toFixed(1)}{" "}
pts
</span>
) : (
<span className="text-muted-foreground">0 pts</span>
)}
</TableCell>
)}
</TableRow>
);
})}
</TableBody>
</Table>
{!isFinalized && canFinalize && (
<div className="mt-6 p-4 border-t">
<div className="space-y-3">
<div>
<h4 className="font-semibold text-sm mb-1">Ready to finalize?</h4>
<p className="text-sm text-muted-foreground">
All {totalMajors} major tournaments are complete. Finalizing will:
</p>
<ul className="list-disc list-inside text-sm text-muted-foreground mt-2 space-y-1">
<li>Convert the top 8 participants to fantasy placements 1-8</li>
<li>Award fantasy points based on league scoring rules</li>
<li>Update all league standings</li>
<li>Lock the qualifying points (no further changes)</li>
</ul>
</div>
<Form method="post">
<input type="hidden" name="intent" value="finalize-qp" />
<Button
type="submit"
className="bg-amber-600 hover:bg-amber-700"
onClick={(e) => {
if (!confirm("Are you sure you want to finalize qualifying points? This action cannot be undone.")) {
e.preventDefault();
}
}}
>
<CheckCircle2 className="mr-2 h-4 w-4" />
Finalize Qualifying Points & Assign Fantasy Points
</Button>
</Form>
</div>
</div>
)}
{!isFinalized && !canFinalize && (
<div className="mt-6 p-4 border-t">
<p className="text-sm text-muted-foreground">
<span className="font-semibold">Not ready to finalize yet.</span> Complete all {totalMajors} major tournaments before finalizing qualifying points.
({majorsCompleted} of {totalMajors} completed)
</p>
</div>
)}
</>
)}
</CardContent>
</Card>
);
}