import { useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate, useParams } from 'react-router';
import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks';
import {
buildDefaultPreferredPositions,
formatTierLabel,
getTierColorToken,
mapApiMatchToMatchDetail,
type MatchDetailView,
type ParticipantView,
type TeamView,
} from '../api/mappers';
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
import { apiFetch, ApiError } from '../lib/api';
import { profileIconUrl } from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league';
import type { Position } from '../api/types';
function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) {
return (
{positionLabel[pos]}
);
}
function TierCell({ participant }: { participant: ParticipantView }) {
if (!participant.tier) {
return (
티어 정보 없음
);
}
return (
{formatTierLabel(participant.tier)}
{participant.tier.leaguePoints > 0 && (
{participant.tier.leaguePoints}LP
)}
);
}
function statusBadge(status: MatchDetailView['status']) {
switch (status) {
case 'recruiting':
return {
label: '모집 중',
cls: 'bg-green-500/15 text-green-500 border-green-500/20',
};
case 'team-built':
return {
label: '팀빌딩 완료',
cls: 'bg-amber-500/15 text-amber-500 border-amber-500/20',
};
case 'in-progress':
return {
label: '진행 중',
cls: 'bg-blue-500/15 text-blue-400 border-blue-500/20',
};
case 'finished':
return {
label: '종료',
cls: 'bg-base-content/8 text-base-content/40 border-base-content/10',
};
}
}
function ParticipantRow({
participant,
index,
assignedPos,
}: {
participant: ParticipantView;
index: number;
assignedPos?: Position;
}) {
const { data: ddragon } = useDdragonManifest();
return (
|
{index + 1}
|
{participant.summonerName}
#{participant.tag}
|
|
{assignedPos ? (
|
) : (
<>
|
|
>
)}
);
}
function ParticipantTable({
participants,
maxParticipants,
joined,
canJoin,
onJoin,
isJoining,
}: {
participants: ParticipantView[];
maxParticipants: number;
joined: boolean;
canJoin: boolean;
onJoin: () => void;
isJoining: boolean;
}) {
return (
참가자 ({participants.length}/{maxParticipants})
| # |
소환사 |
현재 티어 |
주 포지션 |
부 포지션 |
{participants.map((participant, index) => (
))}
{participants.length < maxParticipants && (
{maxParticipants - participants.length}자리 남음
)}
);
}
function TeamCard({
team,
isWinner,
}: {
team: TeamView;
isWinner?: boolean;
}) {
const borderColor =
team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25';
const headerBg = team.side === 'blue' ? 'bg-blue-500/8' : 'bg-red-500/8';
const sideColor = team.side === 'blue' ? 'text-blue-400' : 'text-red-400';
const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500';
return (
{team.name}
{isWinner && (
WIN
)}
| # |
소환사 |
현재 티어 |
포지션 |
{team.participants.map((participant, index) => (
))}
);
}
function SideCard({
title,
children,
}: {
title: string;
children: React.ReactNode;
}) {
return (
);
}
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 [blueCaptainUserId, setBlueCaptainUserId] = useState('');
const [redCaptainUserId, setRedCaptainUserId] = useState('');
const joinMatchMutation = useMutation({
mutationFn: () =>
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`, {
method: 'POST',
body: JSON.stringify({
preferredPositions:
currentUser?.preferredPositions.length
? currentUser.preferredPositions.slice(0, 5)
: buildDefaultPreferredPositions(),
}),
}),
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({
queryKey: ['match', DEFAULT_COMMUNITY_ID, id ?? null],
}),
queryClient.invalidateQueries({
queryKey: ['matches', DEFAULT_COMMUNITY_ID],
}),
]);
},
});
const startAuctionMutation = useMutation({
mutationFn: () =>
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, {
method: 'POST',
body: JSON.stringify({
captains: [
{ side: 'blue', userId: blueCaptainUserId },
{ side: 'red', userId: redCaptainUserId },
],
initialPoints: 1000,
maxTimerSeconds: 30,
}),
}),
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`);
},
});
useEffect(() => {
const participants = matchQuery.data?.participants ?? [];
if (!blueCaptainUserId && participants[0]) {
setBlueCaptainUserId(participants[0].userId);
}
if (!redCaptainUserId && participants[1]) {
setRedCaptainUserId(participants[1].userId);
}
}, [blueCaptainUserId, redCaptainUserId, matchQuery.data?.participants]);
if (!DEFAULT_COMMUNITY_ID) {
return (
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
);
}
if (matchQuery.isLoading) {
return (
매치 정보를 불러오는 중...
);
}
if (matchQuery.error || !matchQuery.data) {
return (
내전을 찾을 수 없습니다
홈으로 돌아가기
);
}
const match = mapApiMatchToMatchDetail(matchQuery.data);
const si = statusBadge(match.status);
const canManageAuction =
currentUser?.role === 'owner' || currentUser?.role === 'admin';
const isCheckingPermissions =
meQuery.isLoading || (meQuery.isFetching && !meQuery.data);
const auctionNotStarted =
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
const showAuctionLink = Boolean(auctionQuery.data);
const canStartAuction =
canManageAuction &&
match.status === 'recruiting' &&
matchQuery.data.participants.length >= 2 &&
auctionNotStarted &&
blueCaptainUserId &&
redCaptainUserId &&
blueCaptainUserId !== redCaptainUserId;
return (
목록으로
{match.title}
{si.label}
{match.description}
{match.date} {match.time}
|
{match.participants.length}/{match.maxParticipants}명
|
{match.map}
{joinMatchMutation.error instanceof Error && (
{joinMatchMutation.error.message}
)}
{startAuctionMutation.error instanceof Error && (
{startAuctionMutation.error.message}
)}
{match.status === 'finished' && match.result && (
{match.result.blueScore}
블루팀
VS
{match.result.redScore}
레드팀
{match.result.winner} 승리
)}
{match.status === 'recruiting' ? (
<>
joinMatchMutation.mutate()}
isJoining={joinMatchMutation.isPending}
/>
{isCheckingPermissions ? (
권한 확인 중
관리자 권한을 확인한 뒤 경매 시작 버튼을 표시합니다.
) : canManageAuction ? (
경매 시작
두 팀장을 선택하면 경매를 시작할 수 있습니다.
{showAuctionLink ? (
경매 페이지 열기
) : (
{!canUseMemberActions && (
로그인 또는 Dev Auth에 owner/admin User ID를 먼저 입력해주세요.
)}
)}
) : null}
>
) : (
{match.teams.map((team) => (
))}
{showAuctionLink && (
경매 페이지 열기
)}
)}
{match.schedule.length > 0 && (
{match.schedule.map((item, index) => (
-
{item.time}
{item.label}
))}
)}
{match.prizes.length > 0 && (
{match.prizes.map((prize, index) => (
-
▸
{prize}
))}
)}
{match.notices.length > 0 && (
{match.notices.map((notice, index) => (
-
•
{notice}
))}
)}
);
}