Files
lolympus-tournament-support/apps/web/src/pages/MatchDetailPage.tsx
T
2026-04-26 05:38:58 -07:00

659 lines
23 KiB
TypeScript

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 (
<span
className={`inline-flex items-center gap-1.5 text-[11px] font-medium px-1.5 py-0.5 border ${
sub
? 'border-base-content/8 text-base-content/35 bg-transparent'
: 'border-primary/20 text-primary bg-primary/5'
}`}
>
<img
src={positionIcon[pos]}
alt=""
className="w-3.5 h-3.5 object-contain mr-4px"
/>
<span>{positionLabel[pos]}</span>
</span>
);
}
function TierCell({ participant }: { participant: ParticipantView }) {
if (!participant.tier) {
return (
<div className="text-[11px] text-base-content/25 whitespace-nowrap">
티어 정보 없음
</div>
);
}
return (
<div className="flex items-center gap-1.5 text-[11px] whitespace-nowrap">
<span className={`font-bold ${getTierColorToken(participant.tier)}`}>
{formatTierLabel(participant.tier)}
</span>
{participant.tier.leaguePoints > 0 && (
<span className="text-base-content/25">
{participant.tier.leaguePoints}LP
</span>
)}
</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 ParticipantRow({
participant,
index,
assignedPos,
}: {
participant: ParticipantView;
index: number;
assignedPos?: Position;
}) {
const { data: ddragon } = useDdragonManifest();
return (
<tr className="border-b border-base-content/5 last:border-b-0 hover:bg-base-content/[0.02] transition-colors">
<td className="py-2 px-3 text-center text-[11px] text-base-content/30 w-8">
{index + 1}
</td>
<td className="py-2 px-3">
<div className="flex items-center gap-2">
<div className="w-7 h-7 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-[13px] text-base-content truncate block leading-tight">
{participant.summonerName}
</span>
<span className="text-[10px] text-base-content/25 leading-tight">
#{participant.tag}
</span>
</div>
</div>
</td>
<td className="py-2 px-3">
<TierCell participant={participant} />
</td>
{assignedPos ? (
<td className="py-2 px-3">
<PosBadge pos={assignedPos} />
</td>
) : (
<>
<td className="py-2 px-3">
<PosBadge pos={participant.mainPosition} />
</td>
<td className="py-2 px-3">
<PosBadge pos={participant.subPosition} sub />
</td>
</>
)}
</tr>
);
}
function ParticipantTable({
participants,
maxParticipants,
joined,
canJoin,
onJoin,
isJoining,
}: {
participants: ParticipantView[];
maxParticipants: number;
joined: boolean;
canJoin: boolean;
onJoin: () => void;
isJoining: boolean;
}) {
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-[11px] 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-[11px] font-semibold disabled:opacity-40"
>
{joined ? '참가 완료' : isJoining ? '신청 중...' : '참가 신청'}
</button>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left">
<thead>
<tr className="border-b border-base-content/10 bg-base-200/40 text-[11px] uppercase tracking-wider text-base-content/35 font-semibold">
<th className="py-2 px-3 w-8">#</th>
<th className="py-2 px-3">소환사</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>
{participants.map((participant, index) => (
<ParticipantRow
key={participant.id}
participant={participant}
index={index}
/>
))}
</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-[11px] text-base-content/25">
{maxParticipants - participants.length}자리 남음
</span>
</div>
)}
</div>
);
}
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 (
<div className={`border ${borderColor} overflow-hidden bg-base-100 relative`}>
<div className={`absolute left-0 top-0 bottom-0 w-0.5 ${accentBar}`} />
<div
className={`${headerBg} px-4 py-2 flex items-center justify-between border-b ${borderColor}`}
>
<div className="flex items-center gap-2">
<span className={`text-xs font-bold uppercase tracking-wide ${sideColor}`}>
{team.name}
</span>
{isWinner && (
<span className="inline-flex items-center text-[10px] font-bold px-1.5 py-0.5 bg-amber-500/15 text-amber-400 border border-amber-500/20">
WIN
</span>
)}
</div>
</div>
<table className="w-full text-left">
<thead>
<tr className="border-b border-base-content/8 bg-base-200/30 text-[11px] uppercase tracking-wider text-base-content/35 font-semibold">
<th className="py-2 px-3 w-8">#</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-[11px] font-bold uppercase tracking-wider text-base-content/40">
{title}
</h3>
</div>
<div className="p-4">{children}</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 [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 (
<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 canStartAuction =
canManageAuction &&
match.status === 'recruiting' &&
matchQuery.data.participants.length >= 2 &&
auctionNotStarted &&
blueCaptainUserId &&
redCaptainUserId &&
blueCaptainUserId !== redCaptainUserId;
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-[11px] 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-[11px] 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>
)}
{match.status === 'finished' && match.result && (
<div className="mb-6 border border-base-content/10 bg-base-content/[0.02] p-5">
<div className="flex items-center justify-center gap-8">
<div
className={`text-center ${match.result.winner === '블루팀' ? 'text-blue-400' : 'text-blue-400/30'}`}
>
<div className="text-3xl font-black tabular-nums">
{match.result.blueScore}
</div>
<div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold">
블루팀
</div>
</div>
<div className="text-base-content/20 text-xs font-bold uppercase tracking-widest">
VS
</div>
<div
className={`text-center ${match.result.winner === '레드팀' ? 'text-red-400' : 'text-red-400/30'}`}
>
<div className="text-3xl font-black tabular-nums">
{match.result.redScore}
</div>
<div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold">
레드팀
</div>
</div>
</div>
<div className="text-center mt-3 text-[11px] font-bold text-amber-400 uppercase tracking-wide">
{match.result.winner} 승리
</div>
</div>
)}
<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}
/>
{isCheckingPermissions ? (
<div className="border border-base-content/10 bg-base-100 p-4">
<h3 className="text-[11px] 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-[11px] font-bold uppercase tracking-wider text-base-content/40">
경매 시작
</h3>
<p className="mt-1 text-xs text-base-content/40">
두 팀장을 선택하면 경매를 시작할 수 있습니다.
</p>
</div>
{showAuctionLink ? (
<Link to={`/match/${match.id}/auction`} className="btn btn-primary btn-sm px-5 text-xs">
경매 페이지 열기
</Link>
) : (
<div className="grid sm:grid-cols-2 gap-3">
<label className="text-xs text-base-content/45">
블루팀 팀장
<select
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
value={blueCaptainUserId}
onChange={(event) => setBlueCaptainUserId(event.target.value)}
>
<option value="">선택하세요</option>
{matchQuery.data.participants.map((participant) => (
<option key={`blue-${participant.userId}`} value={participant.userId}>
{participant.gameName ?? participant.userId}
</option>
))}
</select>
</label>
<label className="text-xs text-base-content/45">
레드팀 팀장
<select
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
value={redCaptainUserId}
onChange={(event) => setRedCaptainUserId(event.target.value)}
>
<option value="">선택하세요</option>
{matchQuery.data.participants.map((participant) => (
<option key={`red-${participant.userId}`} value={participant.userId}>
{participant.gameName ?? participant.userId}
</option>
))}
</select>
</label>
<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.side}
team={team}
isWinner={
match.status === 'finished'
? match.result?.winner === team.name
: 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-[13px]">
<span className="font-mono text-[11px] 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.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-[13px] text-base-content/60"
>
<span className="text-amber-400 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-[13px] text-base-content/60"
>
<span className="text-base-content/20 shrink-0">•</span>
<span>{notice}</span>
</li>
))}
</ul>
</SideCard>
)}
</div>
</div>
</main>
);
}