From b4be06ae83264623702320ee540047580108e2fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=8B=A4=ED=98=84=20=28Dahyeon=20Park=29?= Date: Tue, 14 Apr 2026 23:28:00 +0900 Subject: [PATCH] feat(web): add match detail page --- apps/web/src/pages/MatchDetailPage.tsx | 1883 ++++++++++++++++++++++++ 1 file changed, 1883 insertions(+) create mode 100644 apps/web/src/pages/MatchDetailPage.tsx diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx new file mode 100644 index 00000000..cf330b08 --- /dev/null +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -0,0 +1,1883 @@ +import { useEffect, useState } from "react"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { Link, useLocation, useNavigate, useParams } from "react-router"; +import { + useAuction, + useCollectTournamentResultByRiotMatch, + useCollectTournamentResultByWindow, + useDdragonManifest, + useMatch, + useMe, + usePollTournamentResult, + useTournamentCodeStats, + useUserHistoryProfile, +} from "../api/hooks"; +import { + buildDefaultPreferredPositions, + formatTierLabel, + mapApiMatchToMatchDetail, + type MatchDetailView, + type ParticipantView, + type TeamView, +} from "../api/mappers"; +import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config"; +import { apiFetch, ApiError } from "../lib/api"; +import { profileIconUrl } from "../lib/ddragon"; +import { + positionIcon, + positionLabel, + sideShortLabel, + teamIndexColorClasses, + teamIndexLabel, +} from "../lib/league"; +import type { + AuctionTopTierThreshold, + ApiMatchParticipant, + ApiTierInfo, + ManualTournamentResultCollectResponse, + Position, + TeamSide, + TournamentCodeSlotView, +} from "../api/types"; + +type CaptainSelectionSlot = { + teamIndex: number; +}; + +type CaptainSelection = { + userId: string; + initialPoints: string; +}; + +const DEFAULT_AUCTION_MAX_TIMER_SECONDS = 30; +const DEFAULT_AUCTION_BID_EXTENSION_SECONDS = 5; +const MAX_AUCTION_TIMER_SECONDS = 3600; + +function captainSlotKey(slot: CaptainSelectionSlot) { + return String(slot.teamIndex); +} + +function parseInitialPointsInput(value: string) { + if (!value.trim()) return null; + const points = Number(value); + if (!Number.isInteger(points) || points < 100 || points > 100000) { + return null; + } + return points; +} + +function parseAuctionSecondsInput(value: string, min: number) { + if (!value.trim()) return null; + const seconds = Number(value); + if ( + !Number.isInteger(seconds) || + seconds < min || + seconds > MAX_AUCTION_TIMER_SECONDS + ) { + return null; + } + return seconds; +} + +function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) { + const ordered = [...participants].sort( + (left, right) => + new Date(left.joinedAt).getTime() - new Date(right.joinedAt).getTime(), + ); + const auctionParticipantCount = Math.floor(ordered.length / 10) * 10; + return ordered.slice(0, auctionParticipantCount); +} + +function buildCaptainSlots( + participants: ApiMatchParticipant[], +): CaptainSelectionSlot[] { + const teamCount = Math.floor( + buildAuctionParticipantPool(participants).length / 5, + ); + return Array.from({ length: teamCount }, (_, index) => ({ + teamIndex: index + 1, + })); +} + +function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) { + return ( + + + {positionLabel[pos]} + + ); +} + +function tierByQueue(tiers: ApiTierInfo[], queueType: string) { + return tiers.find((tier) => tier.queueType === queueType); +} + +function normalizeRank(rank: string | undefined) { + switch (rank) { + case "I": + return "1"; + case "II": + return "2"; + case "III": + return "3"; + case "IV": + return "4"; + default: + return rank; + } +} + +function formatRankTooltip(tier: ApiTierInfo | undefined) { + if (!tier) return "언랭크"; + const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier); + const normalizedTier = { + ...tier, + rank: normalizeRank(tier.rank) ?? tier.rank, + }; + const label = highTier + ? formatTierLabel({ ...normalizedTier, leaguePoints: 0 }) + : formatTierLabel(normalizedTier); + return `${label} - ${tier.leaguePoints}LP`; +} + +function formatRankBadge(tier: ApiTierInfo | undefined) { + if (!tier) return "U"; + const tierInitial = + tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1); + const rank = normalizeRank(tier.rank); + return rank ? `${tierInitial}${rank}` : tierInitial; +} + +function rankBadgeClass(tier: ApiTierInfo | undefined) { + switch (tier?.tier) { + case "CHALLENGER": + return "border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200"; + case "GRANDMASTER": + return "border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200"; + case "MASTER": + return "border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200"; + case "DIAMOND": + return "border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200"; + case "EMERALD": + return "border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200"; + case "PLATINUM": + return "border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200"; + case "GOLD": + return "border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200"; + case "SILVER": + return "border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200"; + case "BRONZE": + return "border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200"; + case "IRON": + return "border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300"; + default: + return "border-base-content/30 bg-transparent text-base-content/50"; + } +} + +function RankBadge({ tier }: { tier?: ApiTierInfo }) { + const tooltip = formatRankTooltip(tier); + + return ( + + + {formatRankBadge(tier)} + + + ); +} + +function QueueRankCell({ + label, + tier, +}: { + label: "SOLO" | "FLEX"; + tier?: ApiTierInfo; +}) { + return ( + + {label} + + + ); +} + +function SoloRankPrefix({ tier }: { tier?: ApiTierInfo }) { + return ( + + {/* SOLO */} + + + ); +} + +function TierCell({ participant }: { participant: ParticipantView }) { + const profileQuery = useUserHistoryProfile( + participant.userId, + DEFAULT_COMMUNITY_ID, + ); + const tiers = profileQuery.data?.tiers ?? []; + const soloTier = + tierByQueue(tiers, "RANKED_SOLO_5x5") ?? + (participant.tier?.queueType === "RANKED_SOLO_5x5" + ? participant.tier + : undefined); + const flexTier = tierByQueue(tiers, "RANKED_FLEX_SR"); + + return ( +
+ + +
+ ); +} + +function statusBadge(status: MatchDetailView["status"]) { + switch (status) { + case "recruiting": + return { + label: "모집 중", + cls: "bg-green-500/15 text-green-500 border-green-500/20", + }; + case "team-built": + return { + label: "팀빌딩 완료", + cls: "bg-amber-500/15 text-amber-500 border-amber-500/20", + }; + case "in-progress": + return { + label: "진행 중", + cls: "bg-blue-500/15 text-blue-400 border-blue-500/20", + }; + case "finished": + return { + label: "종료", + cls: "bg-base-content/8 text-base-content/40 border-base-content/10", + }; + } +} + +function ParticipantRow({ + participant, + index, + assignedPos, +}: { + participant: ParticipantView; + index: number; + assignedPos?: Position; +}) { + const { data: ddragon } = useDdragonManifest(); + const location = useLocation(); + const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + + return ( + + + {index + 1} + + + +
+ +
+
+ + {participant.summonerName} + + + #{participant.tag} + {participant.excluded && ( + + 제외 + + )} + +
+ + + + + + {assignedPos ? ( + + + + ) : ( + <> + + + + + + + + )} + + ); +} + +function ParticipantTable({ + participants, + maxParticipants, + joined, + canJoin, + onJoin, + isJoining, +}: { + participants: ParticipantView[]; + maxParticipants: number; + joined: boolean; + canJoin: boolean; + onJoin: () => void; + isJoining: boolean; +}) { + return ( +
+
+

+ 참가자 ({participants.length}/{maxParticipants}) +

+ +
+
+ + + + + + + + + + + + {participants.map((participant, index) => ( + + ))} + +
#소환사현재 티어주 포지션부 포지션
+
+ {participants.length < maxParticipants && ( +
+ + {maxParticipants - participants.length}자리 남음 + +
+ )} +
+ ); +} + +function TeamCard({ + team, + matchId, + isWinner, +}: { + team: TeamView; + matchId: string; + isWinner?: boolean; +}) { + const tone = teamIndexColorClasses(team.teamIndex); + + return ( +
+
+
+
+ + {team.name} + + {isWinner && ( + + WIN + + )} +
+ + 진행 페이지 + +
+ + + + + + + + + + + {team.participants.map((participant, index) => ( + + ))} + +
#소환사현재 티어포지션
+
+ ); +} + +function SideCard({ + title, + children, +}: { + title: string; + children: React.ReactNode; +}) { + return ( +
+
+

+ {title} +

+
+
{children}
+
+ ); +} + +function formatTournamentCodeExpiry(value: string | null) { + if (!value) return null; + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }).format(new Date(value)); +} + +function isExpiringSoon(value: string | null) { + if (!value) return false; + const expiresAt = new Date(value).getTime(); + return expiresAt - Date.now() <= 24 * 60 * 60 * 1000; +} + +function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) { + const [copied, setCopied] = useState(false); + const expired = slot.state === "expired"; + const used = slot.state === "used"; + const expiringSoon = isExpiringSoon(slot.expiresAt); + + async function copyCode() { + if (!slot.code) return; + await navigator.clipboard.writeText(slot.code); + setCopied(true); + window.setTimeout(() => setCopied(false), 1600); + } + + return ( +
+
+ + {expired ? "코드 만료" : slot.code} + + {slot.code && !expired && ( + + )} +
+
+ {used + ? "사용됨" + : expired + ? "운영자에게 새 코드를 요청해주세요." + : `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`} +
+
+ ); +} + +function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) { + if (slots.length === 0) { + return ( +
+ 아직 배정된 코드가 없습니다. +
+ ); + } + + return ( +
+ {slots.map((slot) => ( +
+ + {slot.gameNumber}경기 + {(slot.teamAIndex > 1 || slot.teamBIndex > 2) && ( + + {teamIndexLabel(slot.teamAIndex)} vs{" "} + {teamIndexLabel(slot.teamBIndex)} + + )} + + {slot.code ? ( + + ) : ( + + 발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다. + + )} +
+ ))} +
+ ); +} + +function toIsoFromLocalDateTime(value: string): string | null { + if (!value) return null; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return null; + return date.toISOString(); +} + +function formatManualCollectSummary( + result: ManualTournamentResultCollectResponse | undefined, +) { + if (!result) return null; + const games = result.gameNumbers.length + ? ` · ${result.gameNumbers.join(", ")}경기` + : ""; + return `${result.matched}/${result.scanned}개 반영${games}`; +} + +function PoolStatsHint({ enabled }: { enabled: boolean }) { + const statsQuery = useTournamentCodeStats(DEFAULT_COMMUNITY_ID, enabled); + if (!enabled) return null; + const available = statsQuery.data?.available ?? 0; + const expiringSoon = statsQuery.data?.expiringSoon ?? 0; + + return ( +
+
+ 풀 잔여 {available}개 + {expiringSoon > 0 ? ` · 만료 임박 ${expiringSoon}개` : ""} +
+ + 코드 풀 관리 + +
+ ); +} + +function formatGameDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, "0")}`; +} + +function resultSideClass(side: "blue" | "red") { + return side === "blue" ? "text-blue-400" : "text-red-400"; +} + +function resultSideLabel(side: TeamSide) { + return sideShortLabel(side); +} + +function resolveMatchTeamName(match: MatchDetailView, teamIndex: number) { + const team = match.teams.find((item) => item.teamIndex === teamIndex); + return teamIndexLabel(teamIndex, team?.name); +} + +type RoundRobinStanding = { + teamIndex: number; + name: string; + seriesWins: number; + seriesLosses: number; + gameWins: number; + gameLosses: number; + gameDiff: number; + kills: number; + deaths: number; + assists: number; + kdaScore: number; + winRate: number; +}; + +function formatRecordRate(value: number) { + if (!Number.isFinite(value)) return "-"; + return value.toFixed(2).replace(/\.?0+$/, ""); +} + +function formatSignedNumber(value: number) { + return String(value); +} + +function formatKda(standing: RoundRobinStanding) { + if (standing.deaths === 0) { + return standing.kills + standing.assists > 0 ? "Perfect" : "-"; + } + return formatRecordRate(standing.kdaScore); +} + +function buildRoundRobinStandings( + match: MatchDetailView, +): RoundRobinStanding[] { + const standings = new Map(); + + const getStanding = (teamIndex: number) => { + const existing = standings.get(teamIndex); + if (existing) return existing; + + const standing: RoundRobinStanding = { + teamIndex, + name: resolveMatchTeamName(match, teamIndex), + seriesWins: 0, + seriesLosses: 0, + gameWins: 0, + gameLosses: 0, + gameDiff: 0, + kills: 0, + deaths: 0, + assists: 0, + kdaScore: 0, + winRate: 0, + }; + standings.set(teamIndex, standing); + return standing; + }; + + match.teams.forEach((team) => getStanding(team.teamIndex)); + + const seriesResults = match.result?.seriesResults ?? []; + seriesResults.forEach((series) => { + const teamA = getStanding(series.teamAIndex); + const teamB = getStanding(series.teamBIndex); + const teamAWins = series.teamAWins ?? 0; + const teamBWins = series.teamBWins ?? 0; + const winnerTeamIndex = + series.winnerTeamIndex ?? + (teamAWins === teamBWins + ? undefined + : teamAWins > teamBWins + ? series.teamAIndex + : series.teamBIndex); + + teamA.gameWins += teamAWins; + teamA.gameLosses += teamBWins; + teamB.gameWins += teamBWins; + teamB.gameLosses += teamAWins; + + if (winnerTeamIndex === series.teamAIndex) { + teamA.seriesWins += 1; + teamB.seriesLosses += 1; + } + if (winnerTeamIndex === series.teamBIndex) { + teamB.seriesWins += 1; + teamA.seriesLosses += 1; + } + }); + + match.result?.games.forEach((game) => { + game.participants.forEach((participant) => { + const standing = getStanding(participant.teamIndex); + standing.kills += participant.kills; + standing.deaths += participant.deaths; + standing.assists += participant.assists; + }); + }); + + standings.forEach((standing) => { + standing.gameDiff = standing.gameWins - standing.gameLosses; + const totalSeries = standing.seriesWins + standing.seriesLosses; + standing.winRate = totalSeries > 0 ? standing.seriesWins / totalSeries : 0; + standing.kdaScore = + standing.deaths > 0 + ? (standing.kills + standing.assists) / standing.deaths + : standing.kills + standing.assists; + }); + + return [...standings.values()].sort((left, right) => { + if (right.seriesWins !== left.seriesWins) { + return right.seriesWins - left.seriesWins; + } + if (left.seriesLosses !== right.seriesLosses) { + return left.seriesLosses - right.seriesLosses; + } + if (right.gameDiff !== left.gameDiff) { + return right.gameDiff - left.gameDiff; + } + if (right.winRate !== left.winRate) { + return right.winRate - left.winRate; + } + if (right.kdaScore !== left.kdaScore) { + return right.kdaScore - left.kdaScore; + } + if (right.kills !== left.kills) { + return right.kills - left.kills; + } + return left.teamIndex - right.teamIndex; + }); +} + +function RoundRobinStandingsTable({ match }: { match: MatchDetailView }) { + const standings = buildRoundRobinStandings(match); + + return ( +
+
+
+

+ 라운드로빈 순위 +

+

+ {standings.length}팀 · {match.result?.games.length ?? 0}경기 완료 +

+
+ {match.result?.winner && ( +
+
+ 1위 +
+
+ {match.result.winner} +
+
+ )} +
+
+ + + + + + + + + + + + + + + + {standings.map((standing, index) => { + const tone = teamIndexColorClasses(standing.teamIndex); + const isWinner = + match.result?.winnerTeamIndex === standing.teamIndex; + + return ( + + + + + + + + + + + + ); + })} + +
팀 순위 + 승 + 패득실차승률KDA킬데스어시스트
+
+ + {index + 1} + +
+
+ {standing.seriesWins} + + {standing.seriesLosses} + + {formatSignedNumber(standing.gameDiff)} + + {formatRecordRate(standing.winRate)} + + {formatKda(standing)} + + {standing.kills} + + {standing.deaths} + + {standing.assists} +
+
+
+ ); +} + +function MatchResultPanel({ match }: { match: MatchDetailView }) { + if (!match.result) return null; + + const gamesByNumber = new Map( + match.result.games.map((game) => [game.gameNumber, game]), + ); + const maxGameNumber = Math.max( + match.gameCount, + match.tournamentCodes.length, + ...match.result.games.map((game) => game.gameNumber), + ); + const gameNumbers = Array.from( + { length: maxGameNumber }, + (_, index) => index + 1, + ); + const seriesResults = match.result.seriesResults ?? []; + const primarySeries = seriesResults[0]; + const showRoundRobinStandings = + match.gameMode === "round-robin" && match.teams.length > 2; + + return ( +
+ {showRoundRobinStandings ? ( + + ) : ( + <> + {primarySeries && ( +
+
+
+ {primarySeries.teamAWins} +
+
+ {resolveMatchTeamName(match, primarySeries.teamAIndex)} +
+
+
+ VS +
+
+
+ {primarySeries.teamBWins} +
+
+ {resolveMatchTeamName(match, primarySeries.teamBIndex)} +
+
+
+ )} +
+ {match.result.winner + ? `${match.result.winner} 승리` + : `결과 수집 중 · ${match.result.games.length}/${maxGameNumber}경기`} +
+ {seriesResults.length > 1 && ( +
+ {seriesResults.map((series) => ( +
+
+ {resolveMatchTeamName(match, series.teamAIndex)} vs{" "} + {resolveMatchTeamName(match, series.teamBIndex)} +
+
+ + {series.teamAWins} + + : + + {series.teamBWins} + +
+
+ ))} +
+ )} + + )} +
+ {gameNumbers.map((gameNumber) => { + const game = gamesByNumber.get(gameNumber); + return ( +
+ + {gameNumber}경기 + + {game ? ( +
+ + {resolveMatchTeamName(match, game.winnerTeamIndex)} 승 + + + ({resultSideLabel(game.winnerSide)} 진영) + + + {game.riotMatchId} + +
+ ) : ( + 대기 중 + )} + + {game ? formatGameDuration(game.gameDuration) : "-"} + +
+ ); + })} +
+
+ ); +} + +export default function MatchDetailPage() { + const { id } = useParams(); + const navigate = useNavigate(); + const queryClient = useQueryClient(); + const authUserId = useAuthUserId(); + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + const meQuery = useMe(); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, + )?.user ?? null; + const canUseMemberActions = Boolean(currentUser || authUserId); + const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); + const [captainSelections, setCaptainSelections] = useState< + Record + >({}); + const [topTierThreshold, setTopTierThreshold] = + useState("NONE"); + const [manualTopTierUserIds, setManualTopTierUserIds] = useState( + [], + ); + const [maxTimerSeconds, setMaxTimerSeconds] = useState( + String(DEFAULT_AUCTION_MAX_TIMER_SECONDS), + ); + const [bidExtensionSeconds, setBidExtensionSeconds] = useState( + String(DEFAULT_AUCTION_BID_EXTENSION_SECONDS), + ); + const [manualResultStartTime, setManualResultStartTime] = useState(""); + const [manualResultEndTime, setManualResultEndTime] = useState(""); + const [manualRiotMatchId, setManualRiotMatchId] = useState(""); + const pollTournamentResultMutation = + usePollTournamentResult(DEFAULT_COMMUNITY_ID); + const collectResultByWindowMutation = useCollectTournamentResultByWindow( + DEFAULT_COMMUNITY_ID, + ); + const collectResultByRiotMatchMutation = + useCollectTournamentResultByRiotMatch(DEFAULT_COMMUNITY_ID); + + const joinMatchMutation = useMutation({ + mutationFn: () => + apiFetch( + `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`, + { + method: "POST", + body: JSON.stringify({ + preferredPositions: currentUser?.preferredPositions.length + ? currentUser.preferredPositions.slice(0, 5) + : buildDefaultPreferredPositions(), + }), + }, + ), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ["matches", DEFAULT_COMMUNITY_ID], + }), + ]); + }, + }); + + const startAuctionMutation = useMutation({ + mutationFn: () => + apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, { + method: "POST", + body: JSON.stringify({ + captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map( + (slot) => ({ + teamIndex: slot.teamIndex, + userId: captainSelections[captainSlotKey(slot)]?.userId, + initialPoints: + parseInitialPointsInput( + captainSelections[captainSlotKey(slot)]?.initialPoints ?? "", + ) ?? 1000, + }), + ), + initialPoints: 1000, + topTierThreshold, + manualTopTierUserIds: + topTierThreshold === "MANUAL" ? selectedManualTopTierUserIds : [], + maxTimerSeconds: + parseAuctionSecondsInput(maxTimerSeconds, 5) ?? + DEFAULT_AUCTION_MAX_TIMER_SECONDS, + bidExtensionSeconds: + parseAuctionSecondsInput(bidExtensionSeconds, 0) ?? + DEFAULT_AUCTION_BID_EXTENSION_SECONDS, + }), + }), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ["auction", DEFAULT_COMMUNITY_ID, id ?? null], + }), + ]); + navigate(`/match/${id}/auction`); + }, + }); + + function handlePollTournamentResult() { + if (!id) return; + pollTournamentResultMutation.mutate(id, { + onSuccess: async () => { + await invalidateCurrentMatch(); + }, + }); + } + + async function invalidateCurrentMatch() { + await queryClient.invalidateQueries({ + queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], + }); + } + + function handleCollectResultByWindow() { + if (!id) return; + const startTime = toIsoFromLocalDateTime(manualResultStartTime); + const endTime = toIsoFromLocalDateTime(manualResultEndTime); + if (!startTime || !endTime) return; + collectResultByWindowMutation.mutate( + { matchId: id, startTime, endTime }, + { onSuccess: invalidateCurrentMatch }, + ); + } + + function handleCollectResultByRiotMatch() { + if (!id || !manualRiotMatchId.trim()) return; + collectResultByRiotMatchMutation.mutate( + { matchId: id, riotMatchId: manualRiotMatchId.trim() }, + { onSuccess: invalidateCurrentMatch }, + ); + } + + useEffect(() => { + const participants = buildAuctionParticipantPool( + matchQuery.data?.participants ?? [], + ); + const slots = buildCaptainSlots(matchQuery.data?.participants ?? []); + if (slots.length === 0) { + setCaptainSelections({}); + return; + } + + setCaptainSelections((current) => { + const next: Record = {}; + const usedUserIds = new Set(); + + for (const slot of slots) { + const key = captainSlotKey(slot); + const currentSelection = current[key]; + const currentUserId = currentSelection?.userId; + const currentIsValid = + currentUserId && + participants.some( + (participant) => participant.userId === currentUserId, + ) && + !usedUserIds.has(currentUserId); + + if (currentIsValid) { + next[key] = { + userId: currentUserId, + initialPoints: currentSelection?.initialPoints ?? "1000", + }; + usedUserIds.add(currentUserId); + continue; + } + + const fallback = participants.find( + (participant) => !usedUserIds.has(participant.userId), + ); + next[key] = { + userId: fallback?.userId ?? "", + initialPoints: currentSelection?.initialPoints ?? "1000", + }; + if (fallback) usedUserIds.add(fallback.userId); + } + + return next; + }); + }, [matchQuery.data?.participants]); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
+ ); + } + + if (matchQuery.isLoading) { + return ( +
+ + 매치 정보를 불러오는 중... + +
+ ); + } + + if (matchQuery.error || !matchQuery.data) { + return ( +
+

내전을 찾을 수 없습니다

+ + 홈으로 돌아가기 + +
+ ); + } + + const match = mapApiMatchToMatchDetail(matchQuery.data); + const si = statusBadge(match.status); + const canManageAuction = + currentUser?.role === "owner" || currentUser?.role === "admin"; + const isCheckingPermissions = + meQuery.isLoading || (meQuery.isFetching && !meQuery.data); + const auctionNotStarted = + auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404; + const showAuctionLink = Boolean(auctionQuery.data); + const auctionParticipantPool = buildAuctionParticipantPool( + matchQuery.data.participants, + ); + const captainSlots = buildCaptainSlots(matchQuery.data.participants); + const selectedCaptainIds = captainSlots + .map((slot) => captainSelections[captainSlotKey(slot)]?.userId) + .filter((userId): userId is string => Boolean(userId)); + const hasUniqueCaptainSelections = + selectedCaptainIds.length === captainSlots.length && + new Set(selectedCaptainIds).size === selectedCaptainIds.length; + const hasValidCaptainInitialPoints = captainSlots.every((slot) => + Boolean( + parseInitialPointsInput( + captainSelections[captainSlotKey(slot)]?.initialPoints ?? "", + ), + ), + ); + const manualPriorityCandidates = auctionParticipantPool.filter( + (participant) => !selectedCaptainIds.includes(participant.userId), + ); + const manualPriorityCandidateIds = new Set( + manualPriorityCandidates.map((participant) => participant.userId), + ); + const selectedManualTopTierUserIds = manualTopTierUserIds.filter((userId) => + manualPriorityCandidateIds.has(userId), + ); + const parsedMaxTimerSeconds = parseAuctionSecondsInput(maxTimerSeconds, 5); + const parsedBidExtensionSeconds = parseAuctionSecondsInput( + bidExtensionSeconds, + 0, + ); + const hasValidAuctionTimerSettings = + parsedMaxTimerSeconds !== null && parsedBidExtensionSeconds !== null; + const waitingParticipantCount = + matchQuery.data.participants.length - auctionParticipantPool.length; + const canStartAuction = + canManageAuction && + match.status === "recruiting" && + auctionParticipantPool.length >= 10 && + auctionNotStarted && + hasUniqueCaptainSelections && + hasValidCaptainInitialPoints && + hasValidAuctionTimerSettings; + + return ( +
+ + + + + 목록으로 + + +
+
+

+ {match.title} +

+ + {si.label} + +
+

+ {match.description} +

+
+ + {match.date} {match.time} + + | + + {match.participants.length}/{match.maxParticipants}명 + + | + + {match.map} + +
+
+ + {joinMatchMutation.error instanceof Error && ( +
+ {joinMatchMutation.error.message} +
+ )} + + {startAuctionMutation.error instanceof Error && ( +
+ {startAuctionMutation.error.message} +
+ )} + + {pollTournamentResultMutation.error instanceof Error && ( +
+ {pollTournamentResultMutation.error.message} +
+ )} + + {collectResultByWindowMutation.error instanceof Error && ( +
+ {collectResultByWindowMutation.error.message} +
+ )} + + {collectResultByRiotMatchMutation.error instanceof Error && ( +
+ {collectResultByRiotMatchMutation.error.message} +
+ )} + + + +
+
+ {match.status === "recruiting" ? ( + <> + joinMatchMutation.mutate()} + isJoining={joinMatchMutation.isPending} + /> + + {isCheckingPermissions ? ( +
+

+ 권한 확인 중 +

+

+ 관리자 권한을 확인한 뒤 경매 시작 버튼을 표시합니다. +

+
+ ) : canManageAuction ? ( +
+
+

+ 경매 시작 +

+

+ 참가 신청 순서 기준 5명당 1개 팀이 만들어지고, 각 팀의 + 팀장을 지정합니다. +

+ {waitingParticipantCount > 0 && ( +

+ {waitingParticipantCount}명은 10명 단위에 맞지 않아 이번 + 경매에서 제외됩니다. +

+ )} +
+ + {showAuctionLink ? ( + + 경매 페이지 열기 + + ) : ( +
+ {captainSlots.length > 0 ? ( +
+ {captainSlots.map((slot) => { + const key = captainSlotKey(slot); + const currentSelection = captainSelections[key]; + const currentValue = currentSelection?.userId ?? ""; + return ( + + ); + })} +
+ ) : ( +
+ 경매를 시작하려면 최소 10명이 필요합니다. +
+ )} +
+ + + +
+ {topTierThreshold === "MANUAL" && ( +
+
+ 우선 등장 선수 +
+
+ {manualPriorityCandidates.map((participant) => { + const checked = + selectedManualTopTierUserIds.includes( + participant.userId, + ); + const soloTier = + participant.tier?.queueType === + "RANKED_SOLO_5x5" + ? participant.tier + : undefined; + return ( + + ); + })} + {manualPriorityCandidates.length === 0 && ( +
+ 팀장을 제외한 우선 등장 후보가 없습니다. +
+ )} +
+
+ )} +
+ + {!canUseMemberActions && ( + + 로그인 또는 Dev Auth에 owner/admin User ID를 먼저 + 입력해주세요. + + )} +
+
+ )} +
+ ) : null} + + ) : ( +
+ {match.teams.map((team) => ( + + ))} + {showAuctionLink && ( +
+ + 경매 페이지 열기 + +
+ )} +
+ )} +
+ +
+ {match.schedule.length > 0 && ( + +
    + {match.schedule.map((item, index) => ( +
  • + + {item.time} + + {item.label} +
  • + ))} +
+
+ )} + + {(match.status === "team-built" || + match.status === "in-progress") && ( + + + + + )} + + {canManageAuction && + (match.status === "team-built" || + match.status === "in-progress") && ( + +
+
+
+ 토너먼트 코드 +
+ +
+ +
+
+ 시간 범위 +
+
+ + + + {formatManualCollectSummary( + collectResultByWindowMutation.data, + ) && ( +
+ {formatManualCollectSummary( + collectResultByWindowMutation.data, + )} +
+ )} +
+
+ +
+
+ Riot Match ID +
+
+ + setManualRiotMatchId(event.target.value) + } + placeholder="KR_1234567890" + className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-[11px] text-base-content focus:outline-none focus:border-primary/30" + /> + + {formatManualCollectSummary( + collectResultByRiotMatchMutation.data, + ) && ( +
+ {formatManualCollectSummary( + collectResultByRiotMatchMutation.data, + )} +
+ )} +
+
+
+
+ )} + + {match.prizes.length > 0 && ( + +
    + {match.prizes.map((prize, index) => ( +
  • + ▸ + {prize} +
  • + ))} +
+
+ )} + + {match.notices.length > 0 && ( + +
    + {match.notices.map((notice, index) => ( +
  • + • + {notice} +
  • + ))} +
+
+ )} +
+
+
+ ); +}