Files
lolympus-tournament-support/apps/web/src/pages/MatchDetailPage.tsx
T

2514 lines
92 KiB
TypeScript

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,
mapApiMatchToMatchDetail,
type MatchDetailView,
type ParticipantView,
type TeamView,
} from "../api/mappers";
import { RankBadge } from "../components/RankBadge";
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
import { apiFetch, ApiError } from "../lib/api";
import { profileIconUrl } from "../lib/ddragon";
import {
POSITION_ORDER,
positionLabel,
sideShortLabel,
teamIndexColorClasses,
teamIndexLabel,
} from "../lib/league";
import type {
AuctionTopTierThreshold,
ApiMatch,
ApiMatchParticipant,
ApiPositionPreference,
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;
const ALL_PARTICIPANT_FILTER = "all";
type ParticipantPositionFilter = Position | typeof ALL_PARTICIPANT_FILTER;
type ParticipantTierFilter = string | typeof ALL_PARTICIPANT_FILTER;
const PARTICIPANT_TIER_FILTERS = [
"CHALLENGER",
"GRANDMASTER",
"MASTER",
"DIAMOND",
"EMERALD",
"PLATINUM",
"GOLD",
"SILVER",
"BRONZE",
"IRON",
"UNRANKED",
] as const;
const PARTICIPANT_TIER_LABELS: Record<string, string> = {
CHALLENGER: "챌린저",
GRANDMASTER: "그랜드마스터",
MASTER: "마스터",
DIAMOND: "다이아몬드",
EMERALD: "에메랄드",
PLATINUM: "플래티넘",
GOLD: "골드",
SILVER: "실버",
BRONZE: "브론즈",
IRON: "아이언",
UNRANKED: "언랭크",
};
const PARTICIPANT_TABLE_ROW_CLASS =
"h-12 border-b border-base-content/5 last:border-b-0";
function captainSlotKey(slot: CaptainSelectionSlot) {
return String(slot.teamIndex);
}
// 백엔드 reorderPreferredPositions와 동일 규칙. 낙관적 업데이트에서
// 캐시된 preferredPositions를 즉시 갱신하는 데 사용한다.
function reorderPreferredPositions(
mainPosition: Position,
subPosition: Position,
current: ApiPositionPreference[],
): ApiPositionPreference[] {
const ordered: Position[] = [mainPosition];
if (subPosition !== mainPosition) ordered.push(subPosition);
for (const preference of [...current].sort(
(left, right) => left.priority - right.priority,
)) {
if (!ordered.includes(preference.position)) {
ordered.push(preference.position);
}
}
return ordered.map((position, index) => ({ position, priority: index + 1 }));
}
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 tierByQueue(tiers: ApiTierInfo[], queueType: string) {
return tiers.find((tier) => tier.queueType === queueType);
}
function QueueRankCell({
label,
tier,
}: {
label: "SOLO" | "FLEX";
tier?: ApiTierInfo;
}) {
return (
<span className="grid grid-cols-[27px_auto] items-center gap-1.5">
<span className="text-xs font-medium text-base-content/50">
{label}
</span>
<RankBadge tier={tier} size="sm" tooltipPlacement="left" />
</span>
);
}
function PreferredPositionText({
mainPosition,
subPosition,
}: {
mainPosition: Position;
subPosition: Position;
}) {
return (
<span className="inline-flex flex-col gap-0.5 text-xs font-medium leading-tight text-base-content/55 whitespace-nowrap sm:flex-row sm:items-center sm:gap-1 sm:text-sm sm:leading-normal">
<span>{positionLabel[mainPosition]}</span>
<span className="hidden sm:inline">/</span>
<span>{positionLabel[subPosition]}</span>
</span>
);
}
function SoloRankPrefix({ tier }: { tier?: ApiTierInfo }) {
return (
<span className="inline-flex shrink-0 items-center gap-1 text-xs font-black text-base-content/35">
{/* <span>SOLO</span> */}
<RankBadge tier={tier} size="sm" tooltipPlacement="left" />
</span>
);
}
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 (
<div className="grid grid-cols-1 items-center gap-1 text-xs font-black text-base-content/35 whitespace-nowrap sm:grid-cols-[4.25rem_4.25rem] sm:gap-2">
<QueueRankCell label="SOLO" tier={soloTier} />
<QueueRankCell label="FLEX" tier={flexTier} />
</div>
);
}
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 participantTierFilterValue(participant: ParticipantView) {
return participant.tier?.tier ?? "UNRANKED";
}
// PARTICIPANT_TIER_FILTERS는 높은 티어 → 낮은 티어 순서이므로
// 인덱스가 작을수록 상위 티어. (없는 값은 최하위로 취급)
function tierRank(tier: string) {
const index = PARTICIPANT_TIER_FILTERS.indexOf(
tier as (typeof PARTICIPANT_TIER_FILTERS)[number],
);
return index === -1 ? PARTICIPANT_TIER_FILTERS.length : index;
}
type ParticipantRowAdmin = {
onRemove: (userId: string) => void;
onChangePositions: (
userId: string,
mainPosition: Position,
subPosition: Position,
) => void;
isRemoving: boolean;
isUpdating: boolean;
};
function PositionSelect({
value,
sub,
disabled,
onChange,
}: {
value: Position;
sub?: boolean;
disabled?: boolean;
onChange: (next: Position) => void;
}) {
return (
<select
value={value}
disabled={disabled}
onChange={(event) => onChange(event.target.value as Position)}
className={`h-7 w-16 border bg-base-100 pl-1.5 pr-1 text-xs font-medium focus:border-primary/30 focus:outline-none disabled:opacity-50 ${
sub
? "border-base-content/10 text-base-content/45"
: "border-primary/20 text-primary"
}`}
>
{POSITION_ORDER.map((position) => (
<option key={position} value={position}>
{positionLabel[position]}
</option>
))}
</select>
);
}
function ParticipantRow({
participant,
index,
assignedPos,
admin,
}: {
participant: ParticipantView;
index: number;
assignedPos?: Position;
admin?: ParticipantRowAdmin;
}) {
const { data: ddragon } = useDdragonManifest();
const location = useLocation();
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
const [confirmingRemove, setConfirmingRemove] = useState(false);
// 주/부 포지션이 겹치면 두 값을 맞바꿔 항상 서로 다르게 유지한다.
const handleMainChange = (next: Position) => {
if (!admin) return;
const sub =
next === participant.subPosition
? participant.mainPosition
: participant.subPosition;
admin.onChangePositions(participant.userId, next, sub);
};
const handleSubChange = (next: Position) => {
if (!admin) return;
const main =
next === participant.mainPosition
? participant.subPosition
: participant.mainPosition;
admin.onChangePositions(participant.userId, main, next);
};
return (
<tr
className={`${PARTICIPANT_TABLE_ROW_CLASS} hover:bg-base-content/[0.02] transition-colors`}
>
<td className="hidden py-2 px-3 text-center text-xs text-base-content/30 w-8 sm:table-cell">
{index + 1}
</td>
<td className="py-2 px-3">
<Link
to={`/users/${participant.userId}/history`}
state={{ backTo: historyBackTo }}
className="flex min-w-0 items-center gap-2 group"
>
<div className="h-8 w-8 bg-base-content/10 overflow-hidden shrink-0">
<img
src={profileIconUrl(ddragon, participant.profileIconId)}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
</div>
<div className="min-w-0">
<span className="font-medium text-sm text-base-content block leading-tight break-words group-hover:text-primary transition-colors sm:truncate">
{participant.summonerName}
</span>
<span className="inline-flex items-center gap-1 text-xs text-base-content/25 leading-tight">
#{participant.tag}
{participant.excluded && (
<span className="border border-amber-500/20 bg-amber-500/10 px-1 text-xs font-bold text-amber-500">
제외
</span>
)}
</span>
</div>
</Link>
</td>
<td className="py-2 px-3">
<TierCell participant={participant} />
</td>
{assignedPos ? (
<td className="py-2 px-3">
<PreferredPositionText
mainPosition={participant.mainPosition}
subPosition={participant.subPosition}
/>
</td>
) : admin ? (
<>
<td className="py-2 px-3">
<span className="inline-flex items-center gap-1 whitespace-nowrap">
<PositionSelect
value={participant.mainPosition}
disabled={admin.isUpdating}
onChange={handleMainChange}
/>
<span className="text-xs text-base-content/35">/</span>
<PositionSelect
value={participant.subPosition}
sub
disabled={admin.isUpdating}
onChange={handleSubChange}
/>
</span>
</td>
<td className="py-2 px-3 w-20 min-w-[5rem] whitespace-nowrap text-right">
{confirmingRemove ? (
<span className="inline-flex items-center gap-1.5 whitespace-nowrap">
<button
type="button"
disabled={admin.isRemoving}
onClick={() => admin.onRemove(participant.userId)}
className="text-xs font-bold text-red-400 hover:text-red-300 disabled:opacity-50"
>
{admin.isRemoving ? "제외 중..." : "확인"}
</button>
<button
type="button"
onClick={() => setConfirmingRemove(false)}
className="text-xs text-base-content/35 hover:text-base-content/60"
>
취소
</button>
</span>
) : (
<button
type="button"
title="참가자 제외"
aria-label="참가자 제외"
onClick={() => setConfirmingRemove(true)}
className="text-base-content/25 hover:text-red-400 transition-colors"
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
)}
</td>
</>
) : (
<td className="py-2 px-3">
<PreferredPositionText
mainPosition={participant.mainPosition}
subPosition={participant.subPosition}
/>
</td>
)}
</tr>
);
}
function TeamParticipantMobileRow({
participant,
}: {
participant: ParticipantView;
}) {
const { data: ddragon } = useDdragonManifest();
const location = useLocation();
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
return (
<div className="grid grid-cols-[minmax(0,1fr)_64px_58px] items-center gap-x-2 border-b border-base-content/5 px-3 py-2 last:border-b-0">
<Link
to={`/users/${participant.userId}/history`}
state={{ backTo: historyBackTo }}
className="flex min-w-0 items-center gap-2 group"
>
<div className="h-8 w-8 shrink-0 overflow-hidden bg-base-content/10">
<img
src={profileIconUrl(ddragon, participant.profileIconId)}
alt=""
className="h-full w-full object-cover"
loading="lazy"
/>
</div>
<div className="min-w-0">
<span className="block break-words text-sm font-medium leading-tight text-base-content transition-colors group-hover:text-primary">
{participant.summonerName}
</span>
<span className="inline-flex items-center gap-1 text-xs leading-tight text-base-content/25">
#{participant.tag}
{participant.excluded && (
<span className="border border-amber-500/20 bg-amber-500/10 px-1 text-xs font-bold text-amber-500">
제외
</span>
)}
</span>
</div>
</Link>
<TierCell participant={participant} />
<PreferredPositionText
mainPosition={participant.mainPosition}
subPosition={participant.subPosition}
/>
</div>
);
}
function ParticipantMobileRow({
participant,
admin,
}: {
participant: ParticipantView;
admin?: ParticipantRowAdmin;
}) {
const { data: ddragon } = useDdragonManifest();
const location = useLocation();
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
const [confirmingRemove, setConfirmingRemove] = useState(false);
const handleMainChange = (next: Position) => {
if (!admin) return;
const sub =
next === participant.subPosition
? participant.mainPosition
: participant.subPosition;
admin.onChangePositions(participant.userId, next, sub);
};
const handleSubChange = (next: Position) => {
if (!admin) return;
const main =
next === participant.mainPosition
? participant.subPosition
: participant.mainPosition;
admin.onChangePositions(participant.userId, main, next);
};
return (
<div className="border-b border-base-content/5 px-3 py-2 last:border-b-0">
<div className="grid grid-cols-[minmax(0,1fr)_64px_58px] items-center gap-x-2">
<Link
to={`/users/${participant.userId}/history`}
state={{ backTo: historyBackTo }}
className="flex min-w-0 items-center gap-2 group"
>
<div className="h-8 w-8 shrink-0 overflow-hidden bg-base-content/10">
<img
src={profileIconUrl(ddragon, participant.profileIconId)}
alt=""
className="h-full w-full object-cover"
loading="lazy"
/>
</div>
<div className="min-w-0">
<span className="block break-words text-sm font-medium leading-tight text-base-content transition-colors group-hover:text-primary">
{participant.summonerName}
</span>
<span className="inline-flex items-center gap-1 text-xs leading-tight text-base-content/25">
#{participant.tag}
{participant.excluded && (
<span className="border border-amber-500/20 bg-amber-500/10 px-1 text-xs font-bold text-amber-500">
제외
</span>
)}
</span>
</div>
</Link>
<TierCell participant={participant} />
<PreferredPositionText
mainPosition={participant.mainPosition}
subPosition={participant.subPosition}
/>
</div>
{admin && (
<div className="mt-2 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 border-t border-base-content/5 pt-2">
<span className="inline-flex items-center gap-1 whitespace-nowrap">
<PositionSelect
value={participant.mainPosition}
disabled={admin.isUpdating}
onChange={handleMainChange}
/>
<span className="text-xs text-base-content/35">/</span>
<PositionSelect
value={participant.subPosition}
sub
disabled={admin.isUpdating}
onChange={handleSubChange}
/>
</span>
{confirmingRemove ? (
<span className="inline-flex items-center gap-2 whitespace-nowrap">
<button
type="button"
disabled={admin.isRemoving}
onClick={() => admin.onRemove(participant.userId)}
className="text-xs font-bold text-red-400 hover:text-red-300 disabled:opacity-50"
>
{admin.isRemoving ? "제외 중..." : "확인"}
</button>
<button
type="button"
onClick={() => setConfirmingRemove(false)}
className="text-xs text-base-content/35 hover:text-base-content/60"
>
취소
</button>
</span>
) : (
<button
type="button"
onClick={() => setConfirmingRemove(true)}
className="text-xs font-bold text-base-content/35 hover:text-red-400"
>
제외
</button>
)}
</div>
)}
</div>
);
}
function ParticipantTable({
participants,
maxParticipants,
joined,
canJoin,
onJoin,
isJoining,
canManage,
onRemoveParticipant,
onUpdatePositions,
removingUserId,
updatingUserId,
}: {
participants: ParticipantView[];
maxParticipants: number;
joined: boolean;
canJoin: boolean;
onJoin: () => void;
isJoining: boolean;
canManage: boolean;
onRemoveParticipant: (userId: string) => void;
onUpdatePositions: (
userId: string,
mainPosition: Position,
subPosition: Position,
) => void;
removingUserId: string | null;
updatingUserId: string | null;
}) {
const [positionFilter, setPositionFilter] =
useState<ParticipantPositionFilter>(ALL_PARTICIPANT_FILTER);
const [tierFilter, setTierFilter] = useState<ParticipantTierFilter>(
ALL_PARTICIPANT_FILTER,
);
const filteredParticipants = participants.filter((participant) => {
const matchesPosition =
positionFilter === ALL_PARTICIPANT_FILTER ||
participant.mainPosition === positionFilter;
const matchesTier =
tierFilter === ALL_PARTICIPANT_FILTER ||
tierRank(participantTierFilterValue(participant)) <= tierRank(tierFilter);
return matchesPosition && matchesTier;
});
const isFiltered =
positionFilter !== ALL_PARTICIPANT_FILTER ||
tierFilter !== ALL_PARTICIPANT_FILTER;
const positionFilteredParticipants = participants.filter(
(participant) =>
positionFilter === ALL_PARTICIPANT_FILTER ||
participant.mainPosition === positionFilter,
);
// "이상" 임계값으로 쓸 수 있는 티어 = 참가자 중 실제 존재하는 티어.
// 언랭크는 "이상" 기준으로 전체와 동일하므로 임계값 후보에서 제외한다.
const presentTiers = new Set(
positionFilteredParticipants.map(participantTierFilterValue),
);
const availableTiers = PARTICIPANT_TIER_FILTERS.filter(
(tier) => tier !== "UNRANKED" && presentTiers.has(tier),
);
const tierAtOrAboveCounts = new Map<string, number>(
availableTiers.map((tier) => [
tier,
positionFilteredParticipants.filter(
(participant) =>
tierRank(participantTierFilterValue(participant)) <= tierRank(tier),
).length,
]),
);
const positionCounts = new Map<Position, number>(
POSITION_ORDER.map((position) => [
position,
participants.filter(
(participant) => participant.mainPosition === position,
).length,
]),
);
return (
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="px-4 py-2.5 border-b border-base-content/10 bg-base-200/40 flex items-center justify-between gap-3">
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
참가자 ({participants.length}/{maxParticipants})
</h3>
<button
type="button"
onClick={onJoin}
disabled={!canJoin || joined || isJoining}
className="btn btn-primary btn-xs px-4 text-xs font-semibold disabled:opacity-40"
>
{joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"}
</button>
</div>
<div className="border-b border-base-content/10 bg-base-100 px-4 py-2.5">
<div className="flex flex-wrap items-center gap-x-2 gap-y-2">
<div className="inline-flex items-center gap-1">
<button
type="button"
onClick={() => setPositionFilter(ALL_PARTICIPANT_FILTER)}
className={`inline-flex h-8 w-[3.75rem] items-center justify-center px-1 text-xs font-semibold border transition-colors ${
positionFilter === ALL_PARTICIPANT_FILTER
? "border-primary/30 bg-primary/5 text-primary"
: "border-base-content/10 text-base-content/40 hover:text-base-content/70"
}`}
>
전체<span className="tabular-nums">({participants.length})</span>
</button>
{POSITION_ORDER.map((position) => {
const active = positionFilter === position;
const count = positionCounts.get(position) ?? 0;
return (
<button
key={position}
type="button"
title={`${positionLabel[position]} (${count}명)`}
aria-label={`${positionLabel[position]} (${count}명)`}
aria-pressed={active}
onClick={() =>
setPositionFilter(
active ? ALL_PARTICIPANT_FILTER : position,
)
}
className={`inline-flex h-8 w-[3.75rem] items-center justify-center px-1 text-xs font-semibold border transition-colors ${
active
? "border-primary/30 bg-primary/5 text-primary"
: "border-base-content/10 text-base-content/40 hover:text-base-content/70"
}`}
>
{positionLabel[position]}
<span className="tabular-nums">({count})</span>
</button>
);
})}
</div>
<select
className="h-8 w-32 shrink-0 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
value={tierFilter}
onChange={(event) => setTierFilter(event.target.value)}
>
<option value={ALL_PARTICIPANT_FILTER}>티어 전체</option>
{availableTiers.map((tier) => (
<option key={tier} value={tier}>
{PARTICIPANT_TIER_LABELS[tier]} 이상 (
{tierAtOrAboveCounts.get(tier)})
</option>
))}
</select>
<div className="ml-auto flex min-w-[6.5rem] shrink-0 items-center justify-end gap-1 whitespace-nowrap text-xs text-base-content/35">
{isFiltered && (
<button
type="button"
className="btn btn-ghost btn-xs h-8 min-h-8 shrink-0 px-1 text-xs text-base-content/40"
onClick={() => {
setPositionFilter(ALL_PARTICIPANT_FILTER);
setTierFilter(ALL_PARTICIPANT_FILTER);
}}
>
초기화
</button>
)}
<span className="w-10 shrink-0 text-right tabular-nums">
{filteredParticipants.length}/{participants.length}명
</span>
</div>
</div>
</div>
<div className="sm:hidden">
<div className="grid grid-cols-[minmax(0,1fr)_64px_58px] gap-x-2 border-b border-base-content/8 bg-base-200/30 px-3 py-2 text-xs font-semibold uppercase tracking-wider text-base-content/35">
<span>소환사</span>
<span>현재 티어</span>
<span>포지션</span>
</div>
{filteredParticipants.length > 0 ? (
filteredParticipants.map((participant) => (
<ParticipantMobileRow
key={participant.id}
participant={participant}
admin={
canManage
? {
onRemove: onRemoveParticipant,
onChangePositions: onUpdatePositions,
isRemoving: removingUserId === participant.userId,
isUpdating: updatingUserId === participant.userId,
}
: undefined
}
/>
))
) : (
<div className="px-3 py-8 text-center text-sm text-base-content/35">
조건에 맞는 참가자가 없습니다.
</div>
)}
</div>
<div className="hidden overflow-x-auto sm:block">
<table className="w-full min-w-[40rem] table-fixed text-left">
<colgroup>
<col className="w-0 sm:w-[5%]" />
<col className={canManage ? "w-[27%]" : "w-[38%]"} />
<col className={canManage ? "w-[34%]" : "w-[34%]"} />
<col className={canManage ? "w-[22%]" : "w-[23%]"} />
{canManage && <col className="w-[12%]" />}
</colgroup>
<thead>
<tr className="border-b border-base-content/10 bg-base-200/40 text-xs uppercase tracking-wider text-base-content/35 font-semibold">
<th className="hidden py-2 px-3 w-0 sm:table-cell sm:w-[5%]">
#
</th>
<th
className={
canManage ? "py-2 px-3 w-[27%]" : "py-2 px-3 w-[38%]"
}
>
소환사
</th>
<th
className={
canManage ? "py-2 px-3 w-[34%]" : "py-2 px-3 w-[34%]"
}
>
현재 티어
</th>
<th
className={
canManage ? "py-2 px-3 w-[22%]" : "py-2 px-3 w-[23%]"
}
>
포지션
</th>
{canManage && (
<th className="py-2 px-3 w-[12%] min-w-[5rem] whitespace-nowrap text-right">
관리
</th>
)}
</tr>
</thead>
<tbody>
{filteredParticipants.length > 0 ? (
filteredParticipants.map((participant, index) => (
<ParticipantRow
key={participant.id}
participant={participant}
index={index}
admin={
canManage
? {
onRemove: onRemoveParticipant,
onChangePositions: onUpdatePositions,
isRemoving: removingUserId === participant.userId,
isUpdating: updatingUserId === participant.userId,
}
: undefined
}
/>
))
) : (
<tr>
<td
colSpan={canManage ? 5 : 4}
className="px-3 py-8 text-center text-sm text-base-content/35"
>
조건에 맞는 참가자가 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
{participants.length < maxParticipants && (
<div className="px-4 py-2.5 border-t border-base-content/5 text-center bg-base-200/20">
<span className="text-xs text-base-content/25">
{maxParticipants - participants.length}자리 남음
</span>
</div>
)}
</div>
);
}
function TeamCard({
team,
matchId,
isWinner,
}: {
team: TeamView;
matchId: string;
isWinner?: boolean;
}) {
const tone = teamIndexColorClasses(team.teamIndex);
return (
<div
className={`border ${tone.border} overflow-hidden bg-base-100 relative`}
>
<div className={`absolute left-0 top-0 bottom-0 w-0.5 ${tone.bar}`} />
<div
className={`${tone.bg} px-4 py-2 flex items-center justify-between border-b ${tone.border}`}
>
<div className="flex items-center gap-2">
<span
className={`text-xs font-bold uppercase tracking-wide ${tone.text}`}
>
{team.name}
</span>
{isWinner && (
<span className="inline-flex items-center text-xs font-bold px-1.5 py-0.5 bg-accent/15 text-amber-400 border border-accent/20">
WIN
</span>
)}
</div>
<Link
to={`/match/${matchId}/team/${team.teamIndex}`}
className="text-xs font-bold text-base-content/35 hover:text-primary"
>
진행 페이지
</Link>
</div>
<div className="sm:hidden">
<div className="grid grid-cols-[minmax(0,1fr)_64px_58px] gap-x-2 border-b border-base-content/8 bg-base-200/30 px-3 py-2 text-xs font-semibold uppercase tracking-wider text-base-content/35">
<span>소환사</span>
<span>현재 티어</span>
<span>포지션</span>
</div>
{team.participants.map((participant) => (
<TeamParticipantMobileRow
key={participant.id}
participant={participant}
/>
))}
</div>
<table className="hidden w-full table-fixed text-left sm:table">
<colgroup>
<col className="w-11" />
<col />
<col className="w-56" />
<col className="w-32" />
</colgroup>
<thead>
<tr className="border-b border-base-content/8 bg-base-200/30 text-xs uppercase tracking-wider text-base-content/35 font-semibold">
<th className="hidden py-2 px-3 w-8 sm:table-cell">#</th>
<th className="py-2 px-3">소환사</th>
<th className="py-2 px-3">현재 티어</th>
<th className="py-2 px-3">포지션</th>
</tr>
</thead>
<tbody>
{team.participants.map((participant, index) => (
<ParticipantRow
key={participant.id}
participant={participant}
index={index}
assignedPos={participant.assignedPosition}
/>
))}
</tbody>
</table>
</div>
);
}
function SideCard({
title,
children,
}: {
title: string;
children: React.ReactNode;
}) {
return (
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="px-4 py-2 border-b border-base-content/10 bg-base-200/40">
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
{title}
</h3>
</div>
<div className="p-4">{children}</div>
</div>
);
}
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 (
<div className="flex-1 min-w-0">
<div
className={`flex items-center gap-2 border px-2 py-1.5 ${
expired
? "border-red-500/20 bg-red-500/8 text-red-400"
: used
? "border-base-content/8 bg-base-content/5 text-base-content/35"
: "border-primary/20 bg-primary/5 text-base-content"
}`}
>
<code className="font-mono text-xs font-bold truncate">
{expired ? "코드 만료" : slot.code}
</code>
{slot.code && !expired && (
<button
type="button"
className="ml-auto text-xs px-1.5 py-0.5 border border-base-content/10 text-base-content/45 hover:text-primary"
onClick={copyCode}
>
{copied ? "복사됨" : "복사"}
</button>
)}
</div>
<div
className={`mt-1 text-xs ${
expired || expiringSoon ? "text-amber-500" : "text-base-content/30"
}`}
>
{used
? "사용됨"
: expired
? "운영자에게 새 코드를 요청해주세요."
: `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`}
</div>
</div>
);
}
function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
if (slots.length === 0) {
return (
<div className="border border-dashed border-base-content/10 px-3 py-3 text-xs text-base-content/30">
아직 배정된 코드가 없습니다.
</div>
);
}
return (
<div className="space-y-2">
{slots.map((slot) => (
<div key={slot.gameNumber} className="flex items-start gap-2">
<span className="text-xs font-bold text-base-content/40 w-20 shrink-0 pt-1.5">
{slot.gameNumber}경기
{(slot.teamAIndex > 1 || slot.teamBIndex > 2) && (
<span className="block text-xs font-normal text-base-content/25">
{teamIndexLabel(slot.teamAIndex)} vs{" "}
{teamIndexLabel(slot.teamBIndex)}
</span>
)}
</span>
{slot.code ? (
<TournamentCodeDisplay slot={slot} />
) : (
<span className="text-xs text-base-content/30 border border-dashed border-base-content/10 px-2 py-2 flex-1">
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
</span>
)}
</div>
))}
</div>
);
}
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 (
<div className="mt-3 border-t border-base-content/8 pt-3 text-xs">
<div className={available < 5 ? "text-red-400" : "text-base-content/35"}>
풀 잔여 {available}개
{expiringSoon > 0 ? ` · 만료 임박 ${expiringSoon}개` : ""}
</div>
<Link
to={`/admin/communities/${DEFAULT_COMMUNITY_ID}/tournament-codes`}
className="mt-1 inline-flex text-primary hover:underline"
>
코드 풀 관리
</Link>
</div>
);
}
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<number, RoundRobinStanding>();
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 (
<div>
<div className="flex items-center justify-between gap-3">
<div>
<h3 className="text-xs font-black text-base-content/65">
라운드로빈 순위
</h3>
<p className="mt-0.5 text-xs text-base-content/35">
{standings.length}팀 · {match.result?.games.length ?? 0}경기 완료
</p>
</div>
{match.result?.winner && (
<div className="text-right">
<div className="text-xs font-bold uppercase tracking-wider text-base-content/35">
1위
</div>
<div className="text-sm font-black text-amber-400">
{match.result.winner}
</div>
</div>
)}
</div>
<div className="mt-4 overflow-x-auto border border-base-content/8">
<table className="min-w-[760px] w-full text-xs">
<thead className="bg-base-100 text-xs text-base-content/45">
<tr className="border-b border-base-content/8">
<th className="h-9 px-3 text-left font-semibold">팀 순위</th>
<th className="h-9 px-3 text-center font-semibold bg-primary/5 text-primary">
승
</th>
<th className="h-9 px-3 text-center font-semibold">패</th>
<th className="h-9 px-3 text-center font-semibold">득실차</th>
<th className="h-9 px-3 text-center font-semibold">승률</th>
<th className="h-9 px-3 text-center font-semibold">KDA</th>
<th className="h-9 px-3 text-center font-semibold">킬</th>
<th className="h-9 px-3 text-center font-semibold">데스</th>
<th className="h-9 px-3 text-center font-semibold">어시스트</th>
</tr>
</thead>
<tbody className="divide-y divide-base-content/8 bg-base-100/60">
{standings.map((standing, index) => {
const tone = teamIndexColorClasses(standing.teamIndex);
const isWinner =
match.result?.winnerTeamIndex === standing.teamIndex;
return (
<tr
key={standing.teamIndex}
className={isWinner ? "bg-amber-400/5" : undefined}
>
<td className="h-14 px-3">
<div className="flex items-center gap-3 min-w-0">
<span className="w-7 shrink-0 text-center text-lg font-black italic text-base-content">
{index + 1}
</span>
<span
className={`h-6 w-1 shrink-0 ${tone.bar}`}
aria-hidden="true"
/>
<span className="min-w-0 truncate font-semibold text-base-content/85">
{standing.name}
</span>
</div>
</td>
<td className="h-14 px-3 text-center font-black tabular-nums bg-primary/5 text-primary">
{standing.seriesWins}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.seriesLosses}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{formatSignedNumber(standing.gameDiff)}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{formatRecordRate(standing.winRate)}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{formatKda(standing)}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.kills}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.deaths}
</td>
<td className="h-14 px-3 text-center tabular-nums text-base-content/70">
{standing.assists}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}
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 (
<div className="mb-6 border border-base-content/10 bg-base-content/[0.02] p-5">
{showRoundRobinStandings ? (
<RoundRobinStandingsTable match={match} />
) : (
<>
{primarySeries && (
<div className="flex items-center justify-center gap-8">
<div
className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? teamIndexColorClasses(primarySeries.teamAIndex).text : "text-base-content/30"}`}
>
<div className="text-3xl font-black tabular-nums">
{primarySeries.teamAWins}
</div>
<div className="text-xs uppercase tracking-wider mt-0.5 font-semibold">
{resolveMatchTeamName(match, primarySeries.teamAIndex)}
</div>
</div>
<div className="text-base-content/20 text-xs font-bold uppercase tracking-widest">
VS
</div>
<div
className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? teamIndexColorClasses(primarySeries.teamBIndex).text : "text-base-content/30"}`}
>
<div className="text-3xl font-black tabular-nums">
{primarySeries.teamBWins}
</div>
<div className="text-xs uppercase tracking-wider mt-0.5 font-semibold">
{resolveMatchTeamName(match, primarySeries.teamBIndex)}
</div>
</div>
</div>
)}
<div className="text-center mt-3 text-xs font-bold text-amber-400 uppercase tracking-wide">
{match.result.winner
? `${match.result.winner} 승리`
: `결과 수집 중 · ${match.result.games.length}/${maxGameNumber}경기`}
</div>
{seriesResults.length > 1 && (
<div className="mt-4 grid sm:grid-cols-2 gap-2">
{seriesResults.map((series) => (
<div
key={`${series.teamAIndex}-${series.teamBIndex}`}
className="border border-base-content/8 bg-base-100 px-3 py-2 text-xs"
>
<div className="font-bold text-base-content/55">
{resolveMatchTeamName(match, series.teamAIndex)} vs{" "}
{resolveMatchTeamName(match, series.teamBIndex)}
</div>
<div className="mt-1 flex items-center justify-between">
<span
className={teamIndexColorClasses(series.teamAIndex).text}
>
{series.teamAWins}
</span>
<span className="text-base-content/20">:</span>
<span
className={teamIndexColorClasses(series.teamBIndex).text}
>
{series.teamBWins}
</span>
</div>
</div>
))}
</div>
)}
</>
)}
<div className="mt-5 border border-base-content/8 divide-y divide-base-content/8">
{gameNumbers.map((gameNumber) => {
const game = gamesByNumber.get(gameNumber);
return (
<div
key={gameNumber}
className="grid grid-cols-[56px_1fr_auto] gap-3 items-center px-3 py-2.5 text-xs"
>
<span className="text-base-content/35 font-bold">
{gameNumber}경기
</span>
{game ? (
<div>
<span
className={`font-black ${resultSideClass(game.winnerSide)}`}
>
{resolveMatchTeamName(match, game.winnerTeamIndex)} 승
</span>
<span className="ml-1 text-base-content/35">
({resultSideLabel(game.winnerSide)} 진영)
</span>
<span className="ml-2 text-base-content/35 font-mono">
{game.riotMatchId}
</span>
</div>
) : (
<span className="text-base-content/25">대기 중</span>
)}
<span className="text-base-content/35 font-mono">
{game ? formatGameDuration(game.gameDuration) : "-"}
</span>
</div>
);
})}
</div>
</div>
);
}
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<string, CaptainSelection>
>({});
const [topTierThreshold, setTopTierThreshold] =
useState<AuctionTopTierThreshold>("NONE");
const [manualTopTierUserIds, setManualTopTierUserIds] = useState<string[]>(
[],
);
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 matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null];
const removeParticipantMutation = useMutation({
mutationFn: (userId: string) =>
apiFetch(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`,
{ method: "DELETE" },
),
onMutate: async (userId: string) => {
await queryClient.cancelQueries({ queryKey: matchQueryKey });
const previous = queryClient.getQueryData<ApiMatch>(matchQueryKey);
if (previous) {
queryClient.setQueryData<ApiMatch>(matchQueryKey, {
...previous,
participants: previous.participants.filter(
(participant) => participant.userId !== userId,
),
});
}
return { previous };
},
onError: (_error, _userId, context) => {
if (context?.previous) {
queryClient.setQueryData(matchQueryKey, context.previous);
}
},
onSettled: () => {
void queryClient.invalidateQueries({ queryKey: matchQueryKey });
void queryClient.invalidateQueries({
queryKey: ["matches", DEFAULT_COMMUNITY_ID],
});
},
});
const updateParticipantMutation = useMutation({
mutationFn: ({
userId,
mainPosition,
subPosition,
}: {
userId: string;
mainPosition: Position;
subPosition: Position;
}) =>
apiFetch(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`,
{
method: "PATCH",
body: JSON.stringify({ mainPosition, subPosition }),
},
),
onMutate: async ({ userId, mainPosition, subPosition }) => {
await queryClient.cancelQueries({ queryKey: matchQueryKey });
const previous = queryClient.getQueryData<ApiMatch>(matchQueryKey);
if (previous) {
queryClient.setQueryData<ApiMatch>(matchQueryKey, {
...previous,
participants: previous.participants.map((participant) =>
participant.userId === userId
? {
...participant,
preferredPositions: reorderPreferredPositions(
mainPosition,
subPosition,
participant.preferredPositions,
),
}
: participant,
),
});
}
return { previous };
},
onError: (_error, _variables, context) => {
if (context?.previous) {
queryClient.setQueryData(matchQueryKey, context.previous);
}
},
onSettled: () => {
void queryClient.invalidateQueries({ queryKey: matchQueryKey });
},
});
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<string, CaptainSelection> = {};
const usedUserIds = new Set<string>();
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 (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<span className="text-sm text-amber-600">
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
</span>
</main>
);
}
if (matchQuery.isLoading) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<span className="text-sm text-base-content/40">
매치 정보를 불러오는 중...
</span>
</main>
);
}
if (matchQuery.error || !matchQuery.data) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h2 className="text-lg font-bold mb-2">내전을 찾을 수 없습니다</h2>
<Link to="/" className="btn btn-ghost btn-sm mt-4">
홈으로 돌아가기
</Link>
</main>
);
}
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 (
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">
<Link
to="/"
className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-5"
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 19l-7-7 7-7"
/>
</svg>
목록으로
</Link>
<div className="mb-6 pb-5 border-b border-base-content/8">
<div className="flex items-center gap-2.5 flex-wrap mb-2">
<h1 className="text-xl sm:text-2xl font-bold text-base-content leading-tight">
{match.title}
</h1>
<span
className={`inline-flex items-center text-xs font-semibold px-1.5 py-0.5 border ${si.cls}`}
>
{si.label}
</span>
</div>
<p className="text-sm text-base-content/50 mb-2.5">
{match.description}
</p>
<div className="flex items-center gap-3 text-xs text-base-content/40 flex-wrap">
<span>
{match.date} {match.time}
</span>
<span className="text-base-content/15">|</span>
<span>
{match.participants.length}/{match.maxParticipants}명
</span>
<span className="text-base-content/15">|</span>
<span className="inline-flex items-center text-xs px-1.5 py-0.5 border border-base-content/10 text-base-content/40">
{match.map}
</span>
</div>
</div>
{joinMatchMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{joinMatchMutation.error.message}
</div>
)}
{startAuctionMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{startAuctionMutation.error.message}
</div>
)}
{removeParticipantMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{removeParticipantMutation.error.message}
</div>
)}
{updateParticipantMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{updateParticipantMutation.error.message}
</div>
)}
{pollTournamentResultMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{pollTournamentResultMutation.error.message}
</div>
)}
{collectResultByWindowMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{collectResultByWindowMutation.error.message}
</div>
)}
{collectResultByRiotMatchMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{collectResultByRiotMatchMutation.error.message}
</div>
)}
<MatchResultPanel match={match} />
<div className="flex flex-col lg:flex-row gap-5">
<div className="flex-1 min-w-0 space-y-4">
{match.status === "recruiting" ? (
<>
<ParticipantTable
participants={match.participants}
maxParticipants={match.maxParticipants}
joined={match.joined}
canJoin={canUseMemberActions}
onJoin={() => joinMatchMutation.mutate()}
isJoining={joinMatchMutation.isPending}
canManage={canManageAuction}
onRemoveParticipant={(userId) =>
removeParticipantMutation.mutate(userId)
}
onUpdatePositions={(userId, mainPosition, subPosition) =>
updateParticipantMutation.mutate({
userId,
mainPosition,
subPosition,
})
}
removingUserId={
removeParticipantMutation.isPending
? (removeParticipantMutation.variables ?? null)
: null
}
updatingUserId={
updateParticipantMutation.isPending
? (updateParticipantMutation.variables?.userId ?? null)
: null
}
/>
{isCheckingPermissions ? (
<div className="border border-base-content/10 bg-base-100 p-4">
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
권한 확인 중
</h3>
<p className="mt-1 text-xs text-base-content/40">
관리자 권한을 확인한 뒤 경매 시작 버튼을 표시합니다.
</p>
</div>
) : canManageAuction ? (
<div className="border border-base-content/10 bg-base-100 p-4 space-y-3">
<div>
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
경매 시작
</h3>
<p className="mt-1 text-xs text-base-content/40">
참가 신청 순서 기준 5명당 1개 팀이 만들어지고, 각 팀의
팀장을 지정합니다.
</p>
{waitingParticipantCount > 0 && (
<p className="mt-1 text-xs text-amber-500">
{waitingParticipantCount}명은 10명 단위에 맞지 않아 이번
경매에서 제외됩니다.
</p>
)}
</div>
{showAuctionLink ? (
<Link
to={`/match/${match.id}/auction`}
className="btn btn-primary btn-sm px-5 text-xs"
>
경매 페이지 열기
</Link>
) : (
<div className="space-y-3">
{captainSlots.length > 0 ? (
<div className="grid sm:grid-cols-2 gap-3">
{captainSlots.map((slot) => {
const key = captainSlotKey(slot);
const currentSelection = captainSelections[key];
const currentValue = currentSelection?.userId ?? "";
return (
<label
key={key}
className="text-xs text-base-content/45"
>
{teamIndexLabel(slot.teamIndex)} 팀장
<div className="mt-1 grid grid-cols-[minmax(0,1fr)_96px] gap-2">
<select
className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
value={currentValue}
onChange={(event) =>
setCaptainSelections((current) => ({
...current,
[key]: {
userId: event.target.value,
initialPoints:
current[key]?.initialPoints ??
"1000",
},
}))
}
>
<option value="">선택하세요</option>
{auctionParticipantPool.map(
(participant) => {
const selectedByOtherSlot =
selectedCaptainIds.includes(
participant.userId,
) &&
currentValue !== participant.userId;
return (
<option
key={`${key}-${participant.userId}`}
value={participant.userId}
disabled={selectedByOtherSlot}
>
{participant.gameName ??
participant.userId}
{selectedByOtherSlot
? " (선택됨)"
: ""}
</option>
);
},
)}
</select>
<input
type="number"
min={100}
max={100000}
step={50}
className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm tabular-nums"
value={
currentSelection?.initialPoints ?? "1000"
}
onChange={(event) =>
setCaptainSelections((current) => ({
...current,
[key]: {
userId: current[key]?.userId ?? "",
initialPoints: event.target.value,
},
}))
}
onBlur={() =>
setCaptainSelections((current) => {
const points = parseInitialPointsInput(
current[key]?.initialPoints ?? "",
);
if (points !== null) return current;
return {
...current,
[key]: {
userId: current[key]?.userId ?? "",
initialPoints: "1000",
},
};
})
}
/>
</div>
</label>
);
})}
</div>
) : (
<div className="border border-dashed border-base-content/10 px-3 py-4 text-xs text-base-content/35">
경매를 시작하려면 최소 10명이 필요합니다.
</div>
)}
<div className="grid gap-x-3 gap-y-4 sm:grid-cols-2">
<label className="block text-xs text-base-content/45">
경매 제한 시간
<div className="mt-1 flex items-center border border-base-content/10 bg-transparent focus-within:border-primary/30">
<input
type="number"
min={5}
max={MAX_AUCTION_TIMER_SECONDS}
step={5}
className="min-w-0 flex-1 bg-transparent px-2 py-2 text-sm tabular-nums focus:outline-none"
value={maxTimerSeconds}
onChange={(event) =>
setMaxTimerSeconds(event.target.value)
}
onBlur={() => {
if (
parseAuctionSecondsInput(maxTimerSeconds, 5)
) {
return;
}
setMaxTimerSeconds(
String(DEFAULT_AUCTION_MAX_TIMER_SECONDS),
);
}}
/>
<span className="shrink-0 px-2 text-xs text-base-content/30">
초
</span>
</div>
</label>
<label className="block text-xs text-base-content/45">
최저 입찰 보장 시간
<div className="mt-1 flex items-center border border-base-content/10 bg-transparent focus-within:border-primary/30">
<input
type="number"
min={0}
max={MAX_AUCTION_TIMER_SECONDS}
step={1}
className="min-w-0 flex-1 bg-transparent px-2 py-2 text-sm tabular-nums focus:outline-none"
value={bidExtensionSeconds}
onChange={(event) =>
setBidExtensionSeconds(event.target.value)
}
onBlur={() => {
if (
parseAuctionSecondsInput(
bidExtensionSeconds,
0,
) !== null
) {
return;
}
setBidExtensionSeconds(
String(DEFAULT_AUCTION_BID_EXTENSION_SECONDS),
);
}}
/>
<span className="shrink-0 px-2 text-xs text-base-content/30">
초
</span>
</div>
<span className="mt-1 block text-xs text-base-content/30">
남은 시간이 이 값보다 적을 때 입찰하면 이 시간까지
늘어납니다.
</span>
</label>
<label className="block text-xs text-base-content/45">
상위 티어 우선 등장
<select
className="mt-1 h-[38px] w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm focus:border-primary/30 focus:outline-none"
value={topTierThreshold}
onChange={(event) =>
setTopTierThreshold(
event.target.value as AuctionTopTierThreshold,
)
}
>
<option value="NONE">없음</option>
<option value="EMERALD">EMERALD+</option>
<option value="DIAMOND">DIAMOND+</option>
<option value="MASTER">MASTER+</option>
<option value="MANUAL">수동 선택</option>
</select>
</label>
</div>
{topTierThreshold === "MANUAL" && (
<div className="border border-base-content/10 bg-base-200/20 p-3">
<div className="mb-2 text-xs font-bold uppercase tracking-wider text-base-content/35">
우선 등장 선수
</div>
<div className="max-h-48 overflow-y-auto space-y-1">
{manualPriorityCandidates.map((participant) => {
const checked =
selectedManualTopTierUserIds.includes(
participant.userId,
);
const soloTier =
participant.tier?.queueType ===
"RANKED_SOLO_5x5"
? participant.tier
: undefined;
return (
<label
key={participant.userId}
className="flex cursor-pointer items-center justify-between gap-3 border border-base-content/8 px-2 py-1.5 text-xs text-base-content/55 transition-colors hover:border-primary/25 hover:bg-primary/5"
>
<span className="flex min-w-0 items-center gap-2">
<SoloRankPrefix tier={soloTier} />
<span className="min-w-0 truncate">
{participant.gameName ??
participant.userId}
<span className="ml-1 text-base-content/25">
#{participant.tagLine ?? "----"}
</span>
</span>
</span>
<input
type="checkbox"
className="checkbox checkbox-primary checkbox-xs"
checked={checked}
onChange={(event) =>
setManualTopTierUserIds((current) =>
event.target.checked
? [
...new Set([
...current,
participant.userId,
]),
]
: current.filter(
(userId) =>
userId !== participant.userId,
),
)
}
/>
</label>
);
})}
{manualPriorityCandidates.length === 0 && (
<div className="border border-dashed border-base-content/10 px-3 py-4 text-xs text-base-content/35">
팀장을 제외한 우선 등장 후보가 없습니다.
</div>
)}
</div>
</div>
)}
<div className="sm:col-span-2 flex items-center gap-3">
<button
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
disabled={
!canStartAuction || startAuctionMutation.isPending
}
onClick={() => startAuctionMutation.mutate()}
>
{startAuctionMutation.isPending
? "시작 중..."
: "경매 시작"}
</button>
{!canUseMemberActions && (
<span className="text-xs text-amber-600">
로그인 또는 Dev Auth에 owner/admin User ID를 먼저
입력해주세요.
</span>
)}
</div>
</div>
)}
</div>
) : null}
</>
) : (
<div className="space-y-4">
{match.teams.map((team) => (
<TeamCard
key={team.teamIndex}
team={team}
matchId={match.id}
isWinner={
match.status === "finished"
? match.result?.winnerTeamIndex === team.teamIndex
: undefined
}
/>
))}
{showAuctionLink && (
<div className="flex justify-end">
<Link
to={`/match/${match.id}/auction`}
className="btn btn-primary btn-sm px-5 text-xs"
>
경매 페이지 열기
</Link>
</div>
)}
</div>
)}
</div>
<div className="w-full lg:w-64 shrink-0 space-y-4">
{match.schedule.length > 0 && (
<SideCard title="일정">
<ul className="space-y-2">
{match.schedule.map((item, index) => (
<li
key={index}
className="flex items-start gap-2.5 text-sm"
>
<span className="font-mono text-xs text-base-content/30 w-11 shrink-0 pt-px">
{item.time}
</span>
<span className="text-base-content/60">{item.label}</span>
</li>
))}
</ul>
</SideCard>
)}
{(match.status === "team-built" ||
match.status === "in-progress") && (
<SideCard title="토너먼트 코드">
<TournamentCodeList slots={match.tournamentCodes} />
<PoolStatsHint enabled={canManageAuction} />
</SideCard>
)}
{canManageAuction &&
(match.status === "team-built" ||
match.status === "in-progress") && (
<SideCard title="결과 수집">
<div className="space-y-4">
<div>
<div className="mb-2 text-xs font-bold text-base-content/45">
토너먼트 코드
</div>
<button
type="button"
className="btn btn-primary btn-sm w-full text-xs"
disabled={pollTournamentResultMutation.isPending}
onClick={handlePollTournamentResult}
>
{pollTournamentResultMutation.isPending
? "등록 중..."
: "결과 다시 수집"}
</button>
</div>
<div className="border-t border-base-content/8 pt-4">
<div className="mb-2 text-xs font-bold text-base-content/45">
시간 범위
</div>
<div className="space-y-2">
<label className="block text-xs text-base-content/35">
시작
<input
type="datetime-local"
aria-label="수집 시작 시간"
value={manualResultStartTime}
onChange={(event) =>
setManualResultStartTime(event.target.value)
}
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-xs text-base-content focus:outline-none focus:border-primary/30"
/>
</label>
<label className="block text-xs text-base-content/35">
종료
<input
type="datetime-local"
aria-label="수집 종료 시간"
value={manualResultEndTime}
onChange={(event) =>
setManualResultEndTime(event.target.value)
}
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-xs text-base-content focus:outline-none focus:border-primary/30"
/>
</label>
<button
type="button"
className="btn btn-outline btn-sm w-full text-xs"
disabled={
collectResultByWindowMutation.isPending ||
!toIsoFromLocalDateTime(manualResultStartTime) ||
!toIsoFromLocalDateTime(manualResultEndTime)
}
onClick={handleCollectResultByWindow}
>
{collectResultByWindowMutation.isPending
? "수집 중..."
: "시간 범위로 수집"}
</button>
{formatManualCollectSummary(
collectResultByWindowMutation.data,
) && (
<div className="text-xs text-base-content/35">
{formatManualCollectSummary(
collectResultByWindowMutation.data,
)}
</div>
)}
</div>
</div>
<div className="border-t border-base-content/8 pt-4">
<div className="mb-2 text-xs font-bold text-base-content/45">
Riot Match ID
</div>
<div className="space-y-2">
<input
aria-label="Riot Match ID"
value={manualRiotMatchId}
onChange={(event) =>
setManualRiotMatchId(event.target.value)
}
placeholder="KR_1234567890"
className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-xs text-base-content focus:outline-none focus:border-primary/30"
/>
<button
type="button"
className="btn btn-outline btn-sm w-full text-xs"
disabled={
collectResultByRiotMatchMutation.isPending ||
!manualRiotMatchId.trim()
}
onClick={handleCollectResultByRiotMatch}
>
{collectResultByRiotMatchMutation.isPending
? "수집 중..."
: "Match ID로 수집"}
</button>
{formatManualCollectSummary(
collectResultByRiotMatchMutation.data,
) && (
<div className="text-xs text-base-content/35">
{formatManualCollectSummary(
collectResultByRiotMatchMutation.data,
)}
</div>
)}
</div>
</div>
</div>
</SideCard>
)}
{match.prizes.length > 0 && (
<SideCard title="상품">
<ul className="space-y-1.5">
{match.prizes.map((prize, index) => (
<li
key={index}
className="flex items-start gap-2 text-sm text-base-content/60"
>
<span className="text-accent shrink-0 text-xs">▸</span>
<span>{prize}</span>
</li>
))}
</ul>
</SideCard>
)}
{match.notices.length > 0 && (
<SideCard title="안내사항">
<ul className="space-y-1.5">
{match.notices.map((notice, index) => (
<li
key={index}
className="flex items-start gap-2 text-sm text-base-content/60"
>
<span className="text-info shrink-0 font-bold">•</span>
<span>{notice}</span>
</li>
))}
</ul>
</SideCard>
)}
</div>
</div>
</main>
);
}