Files
lolympus-tournament-support/apps/web/src/pages/MatchDetailPage.tsx
T
dahyeon 0d7617e2d2 feat: connect tournament views to APIs and recover archived stats
Remove development previews and complete hall of fame, match history, official results, and multi-kill API integration.

Fix active match pagination and team-ready controls, preserve basic scoreboards, and recover statistics when Riot archives arrive.

Use bounded in-process cache invalidation retries and add the Riot match lookup index migration with regression coverage.
2026-11-11 02:00:35 +09:00

2806 lines
104 KiB
TypeScript

import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type {
MatchDetailResponse,
MatchParticipantView,
} from "@lolympus/contracts";
import {
CalendarDays,
Map as MapIcon,
Search,
Users,
X,
} from "lucide-react";
import {
EmptyNote,
ErrorNote,
LoadingNote,
MetaDot,
PageBody,
PageHero,
Panel,
Pill,
PlainPage,
type PillTone,
} from "../ui";
import {
Link,
useLocation,
useNavigate,
useParams,
useSearchParams,
} from "react-router";
import {
useAuction,
useCollectTournamentResultByRiotMatch,
useCollectTournamentResultByWindow,
useCompetition,
useCommunityUserSearch,
useDdragonManifest,
useMatch,
useMe,
usePollTournamentResult,
useUserHistoryProfile,
} from "../api/hooks";
import {
buildDefaultPreferredPositions,
mapApiMatchToMatchDetail,
type MatchDetailView,
type ParticipantView,
type TeamView,
} from "../api/mappers";
import { RankBadge } from "../components/RankBadge";
import { CompetitionAdminControls } from "../components/competition/CompetitionAdminControls";
import { CompetitionResults } from "../components/competition/CompetitionResults";
import { MatchDetailTabBar } from "../components/competition/MatchDetailTabBar";
import {
createMatchDetailTabSearchParams,
createMatchDetailTabs,
resolveMatchDetailTab,
type MatchDetailTabId,
} from "../components/competition/match-detail-tabs";
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
import { apiFetch, ApiError } from "../lib/api";
import { getMatchStageLabel } from "./home-match-presentation";
import { profileIconUrl } from "../lib/ddragon";
import {
POSITION_ORDER,
positionLabel,
teamIndexColorClasses,
teamIndexLabel,
} from "../lib/league";
import type {
AuctionTopTierThreshold,
ApiCommunityUserSearchCandidate,
ApiCommunityUserSearchRiotAccount,
ApiPositionPreference,
ApiTierInfo,
ManualTournamentResultCollectResponse,
Position,
} from "../api/types";
import { Btn } from "../ui/Btn";
type CaptainSelectionSlot = {
teamIndex: number;
};
type CaptainSelection = {
userId: string;
initialTeamBidPointAmountInput: 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: MatchParticipantView[]) {
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: MatchParticipantView[],
): CaptainSelectionSlot[] {
const teamCount = Math.floor(
buildAuctionParticipantPool(participants).length / 5,
);
return Array.from({ length: teamCount }, (_, index) => ({
teamIndex: index + 1,
}));
}
function getDefaultSearchAccount(candidate: ApiCommunityUserSearchCandidate) {
return (
candidate.riotAccounts.find(
(account) => account.puuid === candidate.matchedRiotPuuid,
) ??
candidate.riotAccounts.find((account) => account.isPrimary) ??
candidate.riotAccounts[0]
);
}
function getSelectedSearchAccount(
candidate: ApiCommunityUserSearchCandidate,
selectedPuuid: string | undefined,
) {
return (
candidate.riotAccounts.find((account) => account.puuid === selectedPuuid) ??
getDefaultSearchAccount(candidate)
);
}
function getCandidateTier(account?: ApiCommunityUserSearchRiotAccount) {
return (
account?.tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ??
account?.tiers[0]
);
}
function resolveCandidateMainSub(
candidate: ApiCommunityUserSearchCandidate,
): [Position, Position] {
const ordered = [...candidate.preferredPositions].sort(
(left, right) => left.priority - right.priority,
);
const main = ordered[0]?.position ?? POSITION_ORDER[0];
const sub =
ordered.find((preference) => preference.position !== main)?.position ??
POSITION_ORDER.find((position) => position !== main) ??
POSITION_ORDER[1];
return [main, sub];
}
function buildPreferredPositionsFromMainSub(
mainPosition: Position,
subPosition: Position,
) {
const ordered: Position[] = [mainPosition];
if (subPosition !== mainPosition) ordered.push(subPosition);
for (const position of POSITION_ORDER) {
if (!ordered.includes(position)) ordered.push(position);
}
return ordered.map((position, index) => ({
position,
priority: 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"]): {
label: string;
tone: PillTone;
live?: boolean;
} {
switch (status) {
case "recruiting":
return { label: "모집 중", tone: "live", live: true };
case "team-built":
return { label: "팀빌딩 완료", tone: "gold" };
case "in-progress":
return { label: "진행 중", tone: "accent", live: true };
case "finished":
return { label: "종료", tone: "ink" };
}
}
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-warning/20 bg-warning/10 px-1 text-xs font-bold text-warning">
제외
</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-error hover:text-error 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-error transition-colors"
>
<X className="h-3.5 w-3.5" aria-hidden="true" />
</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-warning/20 bg-warning/10 px-1 text-xs font-bold text-warning">
제외
</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-warning/20 bg-warning/10 px-1 text-xs font-bold text-warning">
제외
</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-error hover:text-error 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-error"
>
제외
</button>
)}
</div>
)}
</div>
);
}
function AdminAddParticipantModal({
participants,
maxParticipants,
onClose,
onAddParticipant,
addingUserId,
error,
}: {
participants: ParticipantView[];
maxParticipants: number;
onClose: () => void;
onAddParticipant: (params: {
userId: string;
riotPuuid?: string;
preferredPositions: ApiPositionPreference[];
}) => void;
addingUserId: string | null;
error?: Error | null;
}) {
const { data: ddragon } = useDdragonManifest();
const [searchText, setSearchText] = useState("");
const [debouncedSearchText, setDebouncedSearchText] = useState("");
const [selectedRiotPuuidByUserId, setSelectedRiotPuuidByUserId] = useState<
Record<string, string>
>({});
const [positionOverrides, setPositionOverrides] = useState<
Record<string, { mainPosition: Position; subPosition: Position }>
>({});
const participantUserIds = new Set(
participants.map((participant) => participant.userId),
);
const isFull = participants.length >= maxParticipants;
useEffect(() => {
const timer = window.setTimeout(() => {
setDebouncedSearchText(searchText.trim());
}, 250);
return () => window.clearTimeout(timer);
}, [searchText]);
const searchQuery = useCommunityUserSearch(
debouncedSearchText,
DEFAULT_COMMUNITY_ID,
debouncedSearchText.length >= 2,
);
function positionsFor(candidate: ApiCommunityUserSearchCandidate) {
const override = positionOverrides[candidate.userId];
if (override) return override;
const [mainPosition, subPosition] = resolveCandidateMainSub(candidate);
return { mainPosition, subPosition };
}
function setCandidatePosition(
candidate: ApiCommunityUserSearchCandidate,
key: "mainPosition" | "subPosition",
position: Position,
) {
const current = positionsFor(candidate);
setPositionOverrides((previous) => ({
...previous,
[candidate.userId]: {
...current,
[key]: position,
},
}));
}
return (
<div
className="fixed inset-0 z-50 flex items-start justify-center bg-black/55 px-3 py-6 sm:items-center"
role="dialog"
aria-modal="true"
aria-labelledby="admin-add-participant-title"
>
<div className="w-full max-w-3xl border border-base-content/12 bg-base-100 shadow-xl">
<div className="flex items-start justify-between gap-4 border-b border-base-content/10 px-4 py-3">
<div>
<h3
id="admin-add-participant-title"
className="text-sm font-black text-base-content"
>
참여자 추가
</h3>
<p className="mt-1 text-xs text-base-content/45">
카카오 닉네임 또는 Riot ID로 커뮤니티 유저를 찾습니다.
</p>
</div>
<Btn
variant="ghost" size="sm"
aria-label="참여자 추가 닫기"
onClick={onClose}
>
<X size={15} aria-hidden="true" />
</Btn>
</div>
<div className="space-y-3 px-4 py-4">
<label className="block">
<span className="mb-1.5 block text-xs font-bold text-base-content/45">
검색
</span>
<span className="flex h-10 items-center gap-2 border border-base-content/10 bg-base-200/30 px-3 focus-within:border-primary/40">
<Search
size={15}
className="text-base-content/35"
aria-hidden="true"
/>
<input
type="search"
value={searchText}
onChange={(event) => {
setSearchText(event.target.value);
setSelectedRiotPuuidByUserId({});
}}
aria-label="참여자 검색"
placeholder="카카오 닉네임 또는 Riot ID (GameName#TagLine)"
className="lts-input min-w-0 flex-1 outline-none"
/>
</span>
</label>
{error && (
<div className="border border-error/20 bg-error/10 px-3 py-2 text-xs text-error">
{error.message}
</div>
)}
<div className="max-h-[56vh] overflow-y-auto border border-base-content/10">
{debouncedSearchText.length < 2 ? (
<div className="px-4 py-8 text-center text-sm text-base-content/35">
두 글자 이상 입력하면 검색합니다.
</div>
) : searchQuery.isLoading ? (
<div className="px-4 py-8 text-center text-sm text-base-content/35">
검색 중...
</div>
) : searchQuery.error instanceof Error ? (
<div className="px-4 py-8 text-center text-sm text-error">
{searchQuery.error.message}
</div>
) : searchQuery.data && searchQuery.data.length > 0 ? (
<div className="divide-y divide-base-content/8">
{searchQuery.data.map((candidate) => {
const selectedRiotPuuid =
selectedRiotPuuidByUserId[candidate.userId];
const account = getSelectedSearchAccount(
candidate,
selectedRiotPuuid,
);
const tier = getCandidateTier(account);
const positions = positionsFor(candidate);
const disabledReason = participantUserIds.has(
candidate.userId,
)
? "이미 참가중"
: !candidate.isActivated
? "비활성"
: !account
? "Riot 계정 없음"
: isFull
? "정원 초과"
: null;
const isAdding = addingUserId === candidate.userId;
return (
<div
key={candidate.userId}
className="grid gap-3 px-3 py-3 sm:grid-cols-[minmax(0,1fr)_190px_82px] sm:items-center"
>
<div className="flex min-w-0 items-center gap-3">
<img
src={profileIconUrl(
ddragon,
account?.profileIconId ?? 0,
)}
alt=""
className="h-9 w-9 shrink-0 border border-base-content/10 bg-base-200 object-cover"
/>
<div className="min-w-0">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
<span className="truncate text-sm font-bold text-base-content">
{candidate.kakaoTalkNickname ?? "닉네임 없음"}
</span>
<span
className={`shrink-0 border px-1.5 py-0.5 text-xs font-bold ${
disabledReason
? "border-base-content/10 text-base-content/35"
: "border-primary/25 bg-primary/5 text-primary"
}`}
>
{disabledReason ?? "추가 가능"}
</span>
</div>
<div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-base-content/40">
{candidate.riotAccounts.length > 1 ? (
<select
value={account?.puuid ?? ""}
aria-label={`${candidate.kakaoTalkNickname ?? "유저"} Riot ID 선택`}
onChange={(event) =>
setSelectedRiotPuuidByUserId((previous) => ({
...previous,
[candidate.userId]: event.target.value,
}))
}
className="lts-select min-w-0 flex-1"
>
{candidate.riotAccounts.map((riotAccount) => (
<option
key={riotAccount.puuid}
value={riotAccount.puuid}
>
{riotAccount.gameName}#{riotAccount.tagLine}
{riotAccount.isPrimary ? " · 대표" : ""}
</option>
))}
</select>
) : (
<span className="truncate">
{account
? `${account.gameName}#${account.tagLine}`
: "Riot 계정 없음"}
</span>
)}
<RankBadge tier={tier} size="sm" />
</div>
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<label className="text-xs font-bold text-base-content/35">
주
<select
value={positions.mainPosition}
onChange={(event) =>
setCandidatePosition(
candidate,
"mainPosition",
event.target.value as Position,
)
}
className="lts-select mt-1 w-full"
>
{POSITION_ORDER.map((position) => (
<option key={position} value={position}>
{positionLabel[position]}
</option>
))}
</select>
</label>
<label className="text-xs font-bold text-base-content/35">
부
<select
value={positions.subPosition}
onChange={(event) =>
setCandidatePosition(
candidate,
"subPosition",
event.target.value as Position,
)
}
className="lts-select mt-1 w-full"
>
{POSITION_ORDER.map((position) => (
<option key={position} value={position}>
{positionLabel[position]}
</option>
))}
</select>
</label>
</div>
<Btn
disabled={Boolean(disabledReason) || isAdding}
onClick={() =>
onAddParticipant({
userId: candidate.userId,
riotPuuid: account?.puuid,
preferredPositions:
buildPreferredPositionsFromMainSub(
positions.mainPosition,
positions.subPosition,
),
})
}
variant="primary" className="w-full"
>
{isAdding ? "추가 중..." : "추가"}
</Btn>
</div>
);
})}
</div>
) : (
<div className="px-4 py-8 text-center text-sm text-base-content/35">
검색 결과가 없습니다.
</div>
)}
</div>
</div>
</div>
</div>
);
}
function MatchRegistration({
match,
canJoin,
checkingAccount,
initialPosition,
joining,
error,
onJoin,
cancelling,
cancelError,
onCancel,
}: {
match: MatchDetailView;
canJoin: boolean;
checkingAccount: boolean;
initialPosition: Position;
joining: boolean;
error: Error | null;
onJoin: (position: Position) => void;
cancelling: boolean;
cancelError: Error | null;
onCancel: () => void;
}) {
const [selectedPosition, setSelectedPosition] = useState<Position>();
const position = selectedPosition ?? initialPosition;
const count = match.participants.length;
const remaining = Math.max(0, match.maxParticipants - count);
const progress = match.maxParticipants > 0 ? Math.min(100, count / match.maxParticipants * 100) : 0;
return (
<Panel className="mb-5 px-4 py-4 sm:px-5" aria-labelledby="match-registration-title">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 id="match-registration-title" className="text-base font-bold">참가 신청</h2>
<Pill tone={match.joined ? "live" : remaining > 0 ? "neutral" : "gold"}>
{count}/{match.maxParticipants}명
</Pill>
</div>
<p className="mt-2 font-semibold" role="status">
{match.joined ? "참가 신청 완료" : remaining > 0 ? `${remaining}자리 남음` : "정원이 찼습니다"}
</p>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-sunken-strong" aria-hidden="true">
<div className="h-full rounded-full bg-brand-coral" style={{ width: `${progress}%` }} />
</div>
{!match.joined && remaining > 0 && (
checkingAccount ? (
<p className="mt-4 text-sm text-content-muted">참가 권한을 확인하고 있습니다.</p>
) : canJoin ? (
<form className="mt-4 flex flex-wrap items-end justify-between gap-4" onSubmit={(event) => {
event.preventDefault();
if (!joining) onJoin(position);
}}>
<fieldset disabled={joining}>
<legend className="mb-2 text-sm font-semibold">1순위 희망 포지션</legend>
<div className="flex flex-wrap gap-2">
{POSITION_ORDER.map((role) => (
<label key={role} className="cursor-pointer">
<input type="radio" name="preferred-position" value={role} checked={role === position} onChange={() => setSelectedPosition(role)} className="peer sr-only" />
<span className="inline-flex min-h-9 items-center rounded-full border border-line-strong px-3 text-sm peer-checked:border-transparent peer-checked:bg-secondary peer-checked:text-secondary-content peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2">
{positionLabel[role]}
</span>
</label>
))}
</div>
</fieldset>
<Btn type="submit" variant="primary" size="lg" disabled={joining}>
{joining ? "신청 중…" : "참가 신청"}
</Btn>
</form>
) : (
<div className="mt-4"><Btn to={`/login?next=${encodeURIComponent(`/match/${match.id}`)}`} variant="primary">로그인하고 참가하기</Btn></div>
)
)}
{error && <ErrorNote className="mt-4" title="참가 신청을 완료하지 못했습니다" description={error.message} />}
{match.joined && canJoin && (
<Btn className="mt-4" variant="secondary" loading={cancelling}
disabled={cancelling} onClick={onCancel}>
참가 신청 취소
</Btn>
)}
{cancelError && <ErrorNote className="mt-4" title="참가 신청을 취소하지 못했습니다" description={cancelError.message} />}
</Panel>
);
}
function ParticipantTable({
participants,
maxParticipants,
canManage,
onOpenAddParticipant,
onRemoveParticipant,
onUpdatePositions,
removingUserId,
updatingUserId,
}: {
participants: ParticipantView[];
maxParticipants: number;
canManage: boolean;
onOpenAddParticipant: () => void;
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="flex flex-wrap items-center justify-between gap-3 border-b border-base-content/10 bg-base-200/40 px-4 py-2.5">
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
참가자 ({participants.length}/{maxParticipants})
</h3>
<div className="flex flex-wrap items-center justify-end gap-2">
{canManage && (
<Btn
onClick={onOpenAddParticipant}
disabled={participants.length >= maxParticipants}
variant="secondary" size="sm"
>
참여자 추가
</Btn>
)}
</div>
</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="lts-select w-32 shrink-0"
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 && (
<Btn
variant="ghost" size="sm" className="shrink-0"
onClick={() => {
setPositionFilter(ALL_PARTICIPANT_FILTER);
setTierFilter(ALL_PARTICIPANT_FILTER);
}}
>
초기화
</Btn>
)}
<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>
</div>
);
}
function TeamCard({ team, isWinner }: { team: TeamView; 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="min-w-0">
<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-warning border border-accent/20">
WIN
</span>
)}
</div>
{team.captainName && (
<div className="mt-0.5 truncate text-xs text-base-content/35">
팀장 {team.captainName}
{team.captainTag ? (
<span className="ml-1 text-base-content/20">
#{team.captainTag}
</span>
) : null}
</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>
{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 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}`;
}
export default function MatchDetailPage() {
const { id } = useParams();
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const queryClient = useQueryClient();
function invalidateMatchLists() {
return Promise.all([
queryClient.invalidateQueries({ queryKey: ["matches", DEFAULT_COMMUNITY_ID] }),
queryClient.invalidateQueries({ queryKey: ["matches-page", DEFAULT_COMMUNITY_ID] }),
]);
}
const authUserId = useAuthUserId();
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
const competitionEnabled = Boolean(
matchQuery.data &&
matchQuery.data.status !== "recruiting" &&
matchQuery.data.teams.length >= 2,
);
const competitionQuery = useCompetition(
id,
DEFAULT_COMMUNITY_ID,
competitionEnabled,
);
const meQuery = useMe();
const currentUser =
meQuery.data?.memberships.find(
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user ?? null;
const canManageAuction =
currentUser?.role === "owner" || currentUser?.role === "admin";
const isCheckingPermissions =
meQuery.isLoading || (meQuery.isFetching && !meQuery.data);
const canUseMemberActions = Boolean(currentUser || authUserId);
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
const [captainSelections, setCaptainSelections] = useState<
Record<string, CaptainSelection>
>({});
const [topTierAuctionPriorityThreshold, setTopTierAuctionPriorityThreshold] =
useState<AuctionTopTierThreshold>("NONE");
const [
manualTopTierAuctionPriorityUserIds,
setManualTopTierAuctionPriorityUserIds,
] = useState<string[]>([]);
const [
maximumBidRoundDurationSecondsInput,
setMaximumBidRoundDurationSecondsInput,
] = useState(String(DEFAULT_AUCTION_MAX_TIMER_SECONDS));
const [bidRoundExtensionSecondsInput, setBidRoundExtensionSecondsInput] =
useState(String(DEFAULT_AUCTION_BID_EXTENSION_SECONDS));
const [manualResultStartTime, setManualResultStartTime] = useState("");
const [manualResultEndTime, setManualResultEndTime] = useState("");
const [manualRiotMatchId, setManualRiotMatchId] = useState("");
const [addParticipantOpen, setAddParticipantOpen] = useState(false);
const pollTournamentResultMutation =
usePollTournamentResult(DEFAULT_COMMUNITY_ID);
const collectResultByWindowMutation =
useCollectTournamentResultByWindow(DEFAULT_COMMUNITY_ID);
const collectResultByRiotMatchMutation =
useCollectTournamentResultByRiotMatch(DEFAULT_COMMUNITY_ID);
const preferredPositions = currentUser?.preferredPositions.length
? [...currentUser.preferredPositions].sort((left, right) => left.priority - right.priority)
: buildDefaultPreferredPositions();
const matchQueryKey = matchQuery.queryKey;
const joinMatchMutation = useMutation({
mutationFn: (position: Position) => {
const positions = [position, ...preferredPositions.map((entry) => entry.position)];
return apiFetch<MatchDetailResponse>(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`,
{
method: "POST",
body: JSON.stringify({
preferredPositions: [...new Set(positions)].slice(0, 5).map((entry, index) => ({
position: entry,
priority: index + 1,
})),
}),
},
);
},
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({
queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null],
}),
invalidateMatchLists(),
]);
},
onError: () => {
void queryClient.invalidateQueries({ queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null] });
},
});
const cancelJoinMutation = useMutation({
mutationFn: () => apiFetch<MatchDetailResponse>(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`,
{ method: "DELETE" },
),
onSettled: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null] }),
invalidateMatchLists(),
]);
},
});
const addParticipantMutation = useMutation({
mutationFn: ({
userId,
preferredPositions,
riotPuuid,
}: {
userId: string;
preferredPositions: ApiPositionPreference[];
riotPuuid?: string;
}) =>
apiFetch<MatchDetailResponse>(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`,
{
method: "POST",
body: JSON.stringify({ preferredPositions, riotPuuid }),
},
),
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: matchQueryKey }),
invalidateMatchLists(),
]);
},
});
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<MatchDetailResponse>(matchQueryKey);
if (previous) {
queryClient.setQueryData<MatchDetailResponse>(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 invalidateMatchLists();
},
});
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<MatchDetailResponse>(matchQueryKey);
if (previous) {
queryClient.setQueryData<MatchDetailResponse>(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: (startAuctionRequestId: string) =>
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, {
method: "POST",
body: JSON.stringify({
startAuctionRequestId,
captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map(
(slot) => ({
teamIndex: slot.teamIndex,
userId: captainSelections[captainSlotKey(slot)]?.userId,
initialTeamBidPointAmount:
parseInitialPointsInput(
captainSelections[captainSlotKey(slot)]
?.initialTeamBidPointAmountInput ?? "",
) ?? 1000,
}),
),
initialTeamBidPointAmount: 1000,
topTierAuctionPriorityThreshold,
manualTopTierAuctionPriorityUserIds:
topTierAuctionPriorityThreshold === "MANUAL"
? selectedManualTopTierUserIds
: [],
maximumBidRoundDurationSeconds:
parseAuctionSecondsInput(maximumBidRoundDurationSecondsInput, 5) ??
DEFAULT_AUCTION_MAX_TIMER_SECONDS,
bidRoundExtensionSeconds:
parseAuctionSecondsInput(bidRoundExtensionSecondsInput, 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],
}),
invalidateMatchLists(),
]);
navigate(`/match/${id}/auction`);
},
});
function handlePollTournamentResult() {
if (!id) return;
pollTournamentResultMutation.mutate(id, {
onSuccess: async () => {
await invalidateCurrentMatch();
},
});
}
async function invalidateCurrentMatch() {
await Promise.all([
queryClient.invalidateQueries({
queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null],
}),
queryClient.invalidateQueries({
queryKey: ["competition", DEFAULT_COMMUNITY_ID, id ?? null],
}),
queryClient.invalidateQueries({
queryKey: ["competition-team", 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 timer = window.setTimeout(() => {
const participants = buildAuctionParticipantPool(
matchQuery.data?.participants ?? [],
);
const slots = buildCaptainSlots(matchQuery.data?.participants ?? []);
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,
initialTeamBidPointAmountInput:
currentSelection?.initialTeamBidPointAmountInput ?? "1000",
};
usedUserIds.add(currentUserId);
continue;
}
const fallback = participants.find(
(participant) => !usedUserIds.has(participant.userId),
);
next[key] = {
userId: fallback?.userId ?? "",
initialTeamBidPointAmountInput:
currentSelection?.initialTeamBidPointAmountInput ?? "1000",
};
if (fallback) usedUserIds.add(fallback.userId);
}
return next;
});
}, 0);
return () => window.clearTimeout(timer);
}, [matchQuery.data?.participants]);
useEffect(() => {
const status = matchQuery.data?.status;
const requestedTab = searchParams.get("tab");
if (
isCheckingPermissions ||
!requestedTab ||
(status !== "in-progress" && status !== "finished")
) return;
const resolvedTab = resolveMatchDetailTab(
requestedTab,
createMatchDetailTabs({ status, canManage: canManageAuction }),
);
if (!resolvedTab || resolvedTab === requestedTab) return;
setSearchParams(
createMatchDetailTabSearchParams(searchParams, resolvedTab),
{ replace: true, preventScrollReset: true },
);
}, [
canManageAuction,
isCheckingPermissions,
matchQuery.data?.status,
searchParams,
setSearchParams,
]);
if (!DEFAULT_COMMUNITY_ID) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<span className="text-sm text-warning">
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
</span>
</main>
);
}
if (matchQuery.isLoading) {
return (
<PlainPage>
<LoadingNote label="내전 정보를 불러오는 중" />
</PlainPage>
);
}
if (matchQuery.error || !matchQuery.data) {
return (
<PlainPage>
<EmptyNote
title="내전을 찾을 수 없습니다"
description="주소가 바뀌었거나 삭제된 내전일 수 있습니다."
action={
<Btn to="/inhouse" variant="secondary">
내전 목록으로
</Btn>
}
/>
</PlainPage>
);
}
const match = mapApiMatchToMatchDetail(matchQuery.data);
const si = { ...statusBadge(match.status), label: getMatchStageLabel(matchQuery.data) };
const auctionNotStarted =
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
const activeAuction = auctionNotStarted ? null : auctionQuery.data;
const showAuctionLink = Boolean(activeAuction);
const hasTeamProgress = Boolean(competitionQuery.data?.teams.length) &&
(matchQuery.data.eventProgress?.stage === "team-ready" ||
match.status === "in-progress" ||
match.status === "finished");
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)]
?.initialTeamBidPointAmountInput ?? "",
),
),
);
const manualPriorityCandidates = auctionParticipantPool.filter(
(participant) => !selectedCaptainIds.includes(participant.userId),
);
const manualPriorityCandidateIds = new Set<string>(
manualPriorityCandidates.map((participant) => participant.userId),
);
const selectedManualTopTierUserIds =
manualTopTierAuctionPriorityUserIds.filter((userId) =>
manualPriorityCandidateIds.has(userId),
);
const parsedMaxTimerSeconds = parseAuctionSecondsInput(
maximumBidRoundDurationSecondsInput,
5,
);
const parsedBidExtensionSeconds = parseAuctionSecondsInput(
bidRoundExtensionSecondsInput,
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;
const matchTabs = createMatchDetailTabs({
status: match.status,
canManage: canManageAuction,
});
const activeMatchTab = resolveMatchDetailTab(
searchParams.get("tab"),
matchTabs,
);
const usesTabbedLayout = activeMatchTab !== null;
const showCompetitionState =
!usesTabbedLayout ||
activeMatchTab === "bracket" ||
activeMatchTab === "games" ||
activeMatchTab === "ops";
const showCompetitionResults =
!usesTabbedLayout ||
activeMatchTab === "bracket" ||
activeMatchTab === "games";
const showOperationsPanel =
!usesTabbedLayout || activeMatchTab === "ops";
const showTeamsPanel = !usesTabbedLayout || activeMatchTab === "teams";
const showInfoPanel = !usesTabbedLayout || activeMatchTab === "info";
const hasMatchInfo =
match.schedule.length > 0 ||
match.prizes.length > 0 ||
match.notices.length > 0;
const showSupportingLayout =
!usesTabbedLayout ||
showTeamsPanel ||
showInfoPanel ||
(showOperationsPanel && match.status === "in-progress");
const showEmptyOperationsState =
usesTabbedLayout &&
activeMatchTab === "ops" &&
match.status === "finished" &&
!competitionQuery.isLoading &&
!competitionQuery.error &&
(!competitionEnabled ||
competitionQuery.data?.projection.series.length === 0);
const supportingAsideClassName = usesTabbedLayout
? showInfoPanel
? "grid w-full gap-4 lg:grid-cols-2"
: showOperationsPanel
? "w-full space-y-4 lg:max-w-sm"
: "hidden"
: "w-full lg:w-64 shrink-0 space-y-4";
function handleMatchDetailTabChange(nextTab: MatchDetailTabId) {
setSearchParams(
createMatchDetailTabSearchParams(searchParams, nextTab),
{ preventScrollReset: true },
);
}
return (
<>
<PageHero
crumbs={[{ label: "내전", to: "/" }, { label: match.title }]}
title={match.title}
badges={
<Pill tone={si.tone} dot={si.live} pulse={si.live}>
{si.label}
</Pill>
}
meta={
<>
<span className="inline-flex items-center gap-1.5">
<CalendarDays className="size-4" aria-hidden="true" />
{match.date} {match.time}
</span>
<MetaDot />
<span className="inline-flex items-center gap-1.5">
<MapIcon className="size-4" aria-hidden="true" />
{match.map}
</span>
<MetaDot />
<span className="tabular inline-flex items-center gap-1.5">
<Users className="size-4" aria-hidden="true" />
<span>
<strong className="text-on-ink">
{match.participants.length}
</strong>
/{match.maxParticipants}명
</span>
</span>
</>
}
description={match.description || undefined}
actions={
hasTeamProgress ? (
<Btn to={`/match/${match.id}/team`} variant="primary" size="lg">
팀 경기 현황
</Btn>
) : showAuctionLink && match.status !== "recruiting" ? (
<Btn to={`/match/${match.id}/auction`} variant="primary" size="lg">경매 보기</Btn>
) : undefined
}
/>
<PageBody className={!usesTabbedLayout && match.status !== "recruiting" ? "pt-12" : undefined}>
{match.status === "recruiting" && (
<MatchRegistration
key={match.id}
match={match}
canJoin={canUseMemberActions}
checkingAccount={isCheckingPermissions && !canUseMemberActions}
initialPosition={preferredPositions[0]?.position ?? "TOP"}
joining={joinMatchMutation.isPending}
error={joinMatchMutation.error}
onJoin={joinMatchMutation.mutate}
cancelling={cancelJoinMutation.isPending}
cancelError={cancelJoinMutation.error}
onCancel={() => cancelJoinMutation.mutate()}
/>
)}
{startAuctionMutation.error instanceof Error && (
<ErrorNote className="mb-4" title="요청을 처리하지 못했습니다" description={startAuctionMutation.error.message} />
)}
{removeParticipantMutation.error instanceof Error && (
<ErrorNote className="mb-4" title="요청을 처리하지 못했습니다" description={removeParticipantMutation.error.message} />
)}
{updateParticipantMutation.error instanceof Error && (
<ErrorNote className="mb-4" title="요청을 처리하지 못했습니다" description={updateParticipantMutation.error.message} />
)}
{pollTournamentResultMutation.error instanceof Error && (
<ErrorNote className="mb-4" title="요청을 처리하지 못했습니다" description={pollTournamentResultMutation.error.message} />
)}
{collectResultByWindowMutation.error instanceof Error && (
<ErrorNote className="mb-4" title="요청을 처리하지 못했습니다" description={collectResultByWindowMutation.error.message} />
)}
{collectResultByRiotMatchMutation.error instanceof Error && (
<ErrorNote className="mb-4" title="요청을 처리하지 못했습니다" description={collectResultByRiotMatchMutation.error.message} />
)}
{usesTabbedLayout && activeMatchTab && (
<MatchDetailTabBar
tabs={matchTabs}
activeTab={activeMatchTab}
onChange={handleMatchDetailTabChange}
/>
)}
{usesTabbedLayout &&
activeMatchTab &&
matchTabs
.filter((tab) => tab.id !== activeMatchTab)
.map((tab) => (
<div
key={tab.id}
id={`match-detail-panel-${tab.id}`}
role="tabpanel"
aria-labelledby={`match-detail-tab-${tab.id}`}
hidden
/>
))}
<div
id={
usesTabbedLayout && activeMatchTab
? `match-detail-panel-${activeMatchTab}`
: undefined
}
role={usesTabbedLayout ? "tabpanel" : undefined}
aria-labelledby={
usesTabbedLayout && activeMatchTab
? `match-detail-tab-${activeMatchTab}`
: undefined
}
tabIndex={usesTabbedLayout ? 0 : undefined}
className={
usesTabbedLayout
? "scroll-mt-24 pt-5 focus-visible:outline-none"
: undefined
}
>
{usesTabbedLayout &&
showCompetitionResults &&
!competitionEnabled && (
<div
className="mb-6 border border-dashed border-base-content/15 bg-base-content/[0.02] px-4 py-5 text-sm text-base-content/45"
role="status"
>
공식 경기 결과가 아직 준비되지 않았습니다.
</div>
)}
{showCompetitionState && competitionQuery.isLoading && competitionEnabled && (
<div
className="mb-6 space-y-3 border border-base-content/10 p-4"
aria-busy="true"
aria-label="공식 경기 결과를 불러오는 중"
>
<div className="h-4 w-32 animate-pulse bg-base-200" />
<div className="h-24 animate-pulse bg-base-200/70" />
</div>
)}
{showCompetitionState &&
competitionQuery.error &&
!(
competitionQuery.error instanceof ApiError &&
competitionQuery.error.status === 404
) && (
<div className="mb-6 border border-error/20 bg-error/8 px-4 py-3 text-sm text-error">
공식 경기 결과를 불러오지 못했습니다. 잠시 후 다시 시도해주세요.
</div>
)}
{showCompetitionState && competitionEnabled && competitionQuery.data && (
<>
{showCompetitionResults && (
<CompetitionResults
competition={competitionQuery.data}
showTeamLink={!hasTeamProgress}
view={
usesTabbedLayout
? activeMatchTab === "games"
? "games"
: "bracket"
: "all"
}
/>
)}
{showOperationsPanel && (
<CompetitionAdminControls
competition={competitionQuery.data}
communityId={DEFAULT_COMMUNITY_ID}
canManage={canManageAuction}
/>
)}
</>
)}
{showCompetitionState &&
competitionEnabled &&
competitionQuery.error instanceof ApiError &&
competitionQuery.error.status === 404 && (
<div
className="mb-6 border border-dashed border-base-content/15 bg-base-content/[0.02] px-4 py-5 text-sm text-base-content/45"
role="status"
>
공식 경기 결과가 아직 준비되지 않았습니다.
</div>
)}
{showEmptyOperationsState && (
<div
className="mb-6 border border-dashed border-base-content/15 px-4 py-8 text-center text-sm text-base-content/40"
role="status"
>
운영할 공식 경기 데이터가 없습니다.
</div>
)}
{showSupportingLayout && (
<div
className={
usesTabbedLayout ? "block" : "flex flex-col lg:flex-row gap-5"
}
>
{showTeamsPanel && (
<div className="flex-1 min-w-0 space-y-4">
{match.status === "recruiting" ? (
<>
<ParticipantTable
participants={match.participants}
maxParticipants={match.maxParticipants}
canManage={canManageAuction}
onOpenAddParticipant={() => setAddParticipantOpen(true)}
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
}
/>
{addParticipantOpen && (
<AdminAddParticipantModal
participants={match.participants}
maxParticipants={match.maxParticipants}
onClose={() => setAddParticipantOpen(false)}
onAddParticipant={(params) =>
addParticipantMutation.mutate(params)
}
addingUserId={
addParticipantMutation.isPending
? (addParticipantMutation.variables?.userId ?? null)
: null
}
error={
addParticipantMutation.error instanceof Error
? addParticipantMutation.error
: 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-warning">
{waitingParticipantCount}명은 10명 단위에 맞지 않아 이번
경매에서 제외됩니다.
</p>
)}
</div>
{showAuctionLink ? (
<Btn
to={`/match/${match.id}/auction`}
variant="primary"
>
경매 페이지 열기
</Btn>
) : (
<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="lts-select w-full"
value={currentValue}
onChange={(event) =>
setCaptainSelections((current) => ({
...current,
[key]: {
userId: event.target.value,
initialTeamBidPointAmountInput:
current[key]
?.initialTeamBidPointAmountInput ??
"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="lts-input w-full tabular-nums"
value={
currentSelection?.initialTeamBidPointAmountInput ??
"1000"
}
onChange={(event) =>
setCaptainSelections((current) => ({
...current,
[key]: {
userId: current[key]?.userId ?? "",
initialTeamBidPointAmountInput:
event.target.value,
},
}))
}
onBlur={() =>
setCaptainSelections((current) => {
const points = parseInitialPointsInput(
current[key]
?.initialTeamBidPointAmountInput ??
"",
);
if (points !== null) return current;
return {
...current,
[key]: {
userId: current[key]?.userId ?? "",
initialTeamBidPointAmountInput:
"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="lts-input min-w-0 flex-1 tabular-nums"
value={maximumBidRoundDurationSecondsInput}
onChange={(event) =>
setMaximumBidRoundDurationSecondsInput(
event.target.value,
)
}
onBlur={() => {
if (
parseAuctionSecondsInput(
maximumBidRoundDurationSecondsInput,
5,
)
) {
return;
}
setMaximumBidRoundDurationSecondsInput(
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="lts-input min-w-0 flex-1 tabular-nums"
value={bidRoundExtensionSecondsInput}
onChange={(event) =>
setBidRoundExtensionSecondsInput(
event.target.value,
)
}
onBlur={() => {
if (
parseAuctionSecondsInput(
bidRoundExtensionSecondsInput,
0,
) !== null
) {
return;
}
setBidRoundExtensionSecondsInput(
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="lts-select mt-1 w-full"
value={topTierAuctionPriorityThreshold}
onChange={(event) =>
setTopTierAuctionPriorityThreshold(
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>
{topTierAuctionPriorityThreshold === "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="lts-checkbox"
checked={checked}
onChange={(event) =>
setManualTopTierAuctionPriorityUserIds(
(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">
<Btn
variant="primary"
disabled={
!canStartAuction || startAuctionMutation.isPending
}
onClick={() =>
startAuctionMutation.mutate(crypto.randomUUID())
}
>
{startAuctionMutation.isPending
? "시작 중..."
: "경매 시작"}
</Btn>
{!canUseMemberActions && (
<span className="text-xs text-warning">
로그인 또는 Dev Auth에 owner/admin User ID를 먼저
입력해주세요.
</span>
)}
</div>
</div>
)}
</div>
) : null}
</>
) : (
<div className="space-y-4">
{usesTabbedLayout &&
showTeamsPanel &&
match.teams.length === 0 && (
<div
className="border border-dashed border-base-content/15 px-4 py-8 text-center text-sm text-base-content/40"
role="status"
>
등록된 팀이 없습니다.
</div>
)}
{!usesTabbedLayout && match.teams.length === 0 && (
<div className="lts-panel">
<EmptyNote
title={
showAuctionLink
? "경매로 팀을 구성하고 있습니다"
: "팀이 아직 확정되지 않았습니다"
}
description={
showAuctionLink
? "경매가 끝나면 팀 구성과 대진표가 이 화면에 표시됩니다."
: "팀 구성이 끝나면 팀과 대진표가 이 화면에 표시됩니다."
}
action={
showAuctionLink ? (
<Btn
to={`/match/${match.id}/auction`}
variant="secondary"
>
경매 진행 상황 보기
</Btn>
) : undefined
}
/>
</div>
)}
{match.teams.map((team) => (
<TeamCard key={team.teamIndex} team={team} />
))}
{showAuctionLink && hasTeamProgress && (
<div className="flex justify-end">
<Btn
to={`/match/${match.id}/auction`}
variant="secondary"
>
경매 기록 보기
</Btn>
</div>
)}
</div>
)}
</div>
)}
<div className={supportingAsideClassName}>
{usesTabbedLayout && showInfoPanel && !hasMatchInfo && (
<div
className="lg:col-span-2 border border-dashed border-base-content/15 px-4 py-8 text-center text-sm text-base-content/40"
role="status"
>
등록된 일정이나 안내가 없습니다.
</div>
)}
{showInfoPanel && 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>
)}
{showOperationsPanel &&
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>
<Btn
variant="primary" className="w-full"
disabled={pollTournamentResultMutation.isPending}
onClick={handlePollTournamentResult}
>
{pollTournamentResultMutation.isPending
? "등록 중..."
: "결과 다시 수집"}
</Btn>
</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="lts-input mt-1 w-full"
/>
</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="lts-input mt-1 w-full"
/>
</label>
<Btn
variant="secondary" className="w-full"
disabled={
collectResultByWindowMutation.isPending ||
!toIsoFromLocalDateTime(manualResultStartTime) ||
!toIsoFromLocalDateTime(manualResultEndTime)
}
onClick={handleCollectResultByWindow}
>
{collectResultByWindowMutation.isPending
? "수집 중..."
: "시간 범위로 수집"}
</Btn>
{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="lts-input w-full"
/>
<Btn
variant="secondary" className="w-full"
disabled={
collectResultByRiotMatchMutation.isPending ||
!manualRiotMatchId.trim()
}
onClick={handleCollectResultByRiotMatch}
>
{collectResultByRiotMatchMutation.isPending
? "수집 중..."
: "Match ID로 수집"}
</Btn>
{formatManualCollectSummary(
collectResultByRiotMatchMutation.data,
) && (
<div className="text-xs text-base-content/35">
{formatManualCollectSummary(
collectResultByRiotMatchMutation.data,
)}
</div>
)}
</div>
</div>
</div>
</SideCard>
)}
{showInfoPanel && 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>
)}
{showInfoPanel && 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>
)}
</div>
</PageBody>
</>
);
}