feat(web): add match detail and community stats views

This commit is contained in:
dahyeon committed 2026-04-24 04:14:00 +09:00
1 parent ec4daea814
commit a1a77f3338
3 files changed
+1535

No files matched your search

@@ -0,0 +1,388 @@
import { Link, useSearchParams } from 'react-router';
import {
useCommunity,
useCommunityInternalStatsMatches,
useCommunityLeaderboard,
useDdragonManifest,
useTeamInsights,
} from '../api/hooks';
import type {
ApiInternalMatchCard,
ApiLeaderHighlight,
ApiLeaderboardRow,
TeamSide,
} from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import { championDisplayName, championIconUrl, profileIconUrl } from '../lib/ddragon';
function formatDateTime(value: string) {
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function formatDuration(seconds: number) {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
return `${minutes}:${String(rest).padStart(2, '0')}`;
}
function sideLabel(side: TeamSide) {
return side === 'blue' ? '블루팀' : '레드팀';
}
function sideText(side: TeamSide) {
return side === 'blue' ? 'text-blue-400' : 'text-red-400';
}
function ratioClass(value: number) {
if (value >= 55) return 'text-blue-400';
if (value >= 50) return 'text-amber-400';
return 'text-base-content/45';
}
function ChampionChip({
championId,
manifest,
}: {
championId: number;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
const icon = championIconUrl(manifest, championId);
const name = championDisplayName(manifest, championId) ?? String(championId);
return (
<span className="inline-flex items-center gap-1.5">
<span className="w-5 h-5 bg-base-content/10 overflow-hidden">
{icon ? <img src={icon} alt="" className="w-full h-full object-cover" /> : null}
</span>
<span>{name}</span>
</span>
);
}
function MatchCard({
match,
manifest,
}: {
match: ApiInternalMatchCard;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
return (
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats/match/${match.matchId}`}
className="block group"
>
<article className="border border-base-content/10 bg-base-100 hover:border-primary/25 transition-colors">
<div className="p-4 grid lg:grid-cols-[1fr_auto_1fr] gap-4 items-center">
<div className="min-w-0">
<div className="text-[11px] text-base-content/35">
{formatDateTime(match.scheduledAt)}
</div>
<h3 className="mt-1 text-base font-black text-base-content truncate group-hover:text-primary">
{match.title}
</h3>
<div className="mt-2 flex flex-wrap gap-1.5">
{match.games.map((game) => (
<span
key={game.gameNumber}
className="inline-flex items-center gap-1 border border-base-content/10 px-2 py-1 text-[10px] text-base-content/45"
>
{game.gameNumber}경기
{game.winnerSide ? (
<span className={sideText(game.winnerSide)}>
{sideLabel(game.winnerSide)} 승
</span>
) : (
'대기'
)}
<span>{formatDuration(game.gameDuration)}</span>
</span>
))}
</div>
</div>
<div className="text-center px-8">
<div className="flex items-center justify-center gap-5">
<div className={match.winnerSide === 'blue' ? 'text-blue-400' : 'text-blue-400/30'}>
<div className="text-4xl font-black tabular-nums">{match.blueScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">BLUE</div>
</div>
<div className="text-base-content/15 text-xs font-black">VS</div>
<div className={match.winnerSide === 'red' ? 'text-red-400' : 'text-red-400/30'}>
<div className="text-4xl font-black tabular-nums">{match.redScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">RED</div>
</div>
</div>
</div>
<div className="grid sm:grid-cols-2 gap-2">
{match.teams.map((team) => (
<div
key={team.side}
className={`border ${team.side === 'blue' ? 'border-blue-500/15' : 'border-red-500/15'} p-2`}
>
<div className={`text-[10px] font-black uppercase tracking-wider ${sideText(team.side)}`}>
{team.name}
</div>
<div className="mt-2 space-y-1">
{team.members.slice(0, 5).map((member) => (
<div key={member.userId} className="flex items-center gap-1.5 min-w-0">
<span className="w-5 h-5 bg-base-content/10 overflow-hidden shrink-0">
<img
src={profileIconUrl(manifest, member.profileIconId)}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
</span>
<span className="text-[11px] truncate text-base-content/65">
{member.summonerName}
</span>
</div>
))}
</div>
</div>
))}
</div>
</div>
</article>
</Link>
);
}
function HighlightCard({
title,
highlight,
suffix = '',
}: {
title: string;
highlight: ApiLeaderHighlight | null | undefined;
suffix?: string;
}) {
return (
<div className="border border-base-content/10 bg-base-100 p-4">
<div className="text-[10px] font-black uppercase tracking-wider text-base-content/30">
{title}
</div>
<div className="mt-2 text-xl font-black text-base-content tabular-nums">
{highlight ? `${highlight.metric}${suffix}` : '-'}
</div>
<div className="mt-1 text-[12px] text-base-content/45">
{highlight?.summonerName ?? '기록 없음'}
</div>
</div>
);
}
function LeaderboardTable({
rows,
manifest,
}: {
rows: ApiLeaderboardRow[];
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
return (
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left min-w-[920px]">
<thead>
<tr className="border-b border-base-content/10 bg-base-200/50 text-[11px] uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2.5">#</th>
<th className="px-3 py-2.5">소환사</th>
<th className="px-3 py-2.5 text-center">승률</th>
<th className="px-3 py-2.5 text-center">게임</th>
<th className="px-3 py-2.5 text-center">KDA</th>
<th className="px-3 py-2.5 text-center">GPM</th>
<th className="px-3 py-2.5 text-center">킬관여</th>
<th className="px-3 py-2.5 text-center">분당 CS</th>
<th className="px-3 py-2.5">주 챔피언</th>
</tr>
</thead>
<tbody>
{rows.map((row, index) => (
<tr key={row.userId} className="border-b border-base-content/5 last:border-b-0">
<td className="px-3 py-2.5 text-[11px] text-base-content/30">
{index + 1}
</td>
<td className="px-3 py-2.5">
<Link
to={`/users/${row.userId}/history?queueGroup=internal`}
className="flex items-center gap-2 group"
>
<span className="w-7 h-7 bg-base-content/10 overflow-hidden">
<img
src={profileIconUrl(manifest, row.profileIconId)}
alt=""
className="w-full h-full object-cover"
loading="lazy"
/>
</span>
<span className="font-bold text-[13px] group-hover:text-primary">
{row.summonerName}
</span>
</Link>
</td>
<td className={`px-3 py-2.5 text-center text-[13px] font-black ${ratioClass(row.winRate)}`}>
{row.winRate}%
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.games}
</td>
<td className="px-3 py-2.5 text-center text-[12px] font-bold tabular-nums">
{row.kda}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.avgGoldPerMin}
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.avgKillParticipation}%
</td>
<td className="px-3 py-2.5 text-center text-[12px] tabular-nums">
{row.avgCsPerMin}
</td>
<td className="px-3 py-2.5">
<div className="flex flex-wrap gap-2 text-[11px] text-base-content/55">
{row.topChampions.map((champion) => (
<ChampionChip
key={champion.championId}
championId={champion.championId}
manifest={manifest}
/>
))}
</div>
</td>
</tr>
))}
{rows.length === 0 && (
<tr>
<td colSpan={9} className="py-10 text-center text-sm text-base-content/35">
아직 집계할 내전 기록이 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
);
}
export default function CommunityInternalStatsPage() {
const [searchParams] = useSearchParams();
const championIdParam = Number(searchParams.get('championId'));
const championId =
Number.isFinite(championIdParam) && championIdParam > 0
? championIdParam
: undefined;
const filters = {
seasonId: searchParams.get('seasonId') ?? undefined,
championId,
limit: 12,
};
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const matchesQuery = useCommunityInternalStatsMatches(filters);
const leaderboardQuery = useCommunityLeaderboard(filters);
const insightsQuery = useTeamInsights(filters);
const { data: ddragon } = useDdragonManifest();
const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? [];
const season =
leaderboardQuery.data?.season ?? matchesQuery.data?.pages[0]?.season ?? null;
if (!DEFAULT_COMMUNITY_ID) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center text-sm text-amber-600">
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link to="/" className="text-xs text-base-content/40 hover:text-base-content">
← 홈으로
</Link>
<section className="mt-5 mb-6 border border-base-content/10 bg-base-100 p-5">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4">
<div>
<p className="text-[11px] font-black uppercase tracking-[0.24em] text-primary">
Community Records
</p>
<h1 className="mt-2 text-3xl font-black text-base-content">
{communityQuery.data?.name ?? '커뮤니티'} 내전 전적
</h1>
<p className="mt-2 text-sm text-base-content/45">
토너먼트 코드로 수집된 결과를 기준으로 매치, 선수 순위, 팀 인사이트를 보여줍니다.
</p>
</div>
<div className="border border-base-content/10 px-4 py-3 text-sm text-base-content/55">
<div className="text-[10px] uppercase tracking-wider text-base-content/30">
시즌
</div>
<div className="mt-1 font-bold">{season?.label ?? '현재 시즌'}</div>
</div>
</div>
</section>
<section className="grid sm:grid-cols-2 lg:grid-cols-5 gap-3 mb-6">
<HighlightCard title="최고 KDA" highlight={insightsQuery.data?.topKda} />
<HighlightCard title="누적 킬 1위" highlight={insightsQuery.data?.mostKills} />
<HighlightCard title="단일 경기 GPM" highlight={insightsQuery.data?.topTeamGpm} />
<HighlightCard title="킬 관여율" highlight={insightsQuery.data?.topKillParticipation} suffix="%" />
<HighlightCard title="분당 CS" highlight={insightsQuery.data?.bestFarm} />
</section>
<section className="mb-8">
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-sm font-black text-base-content">최근 내전</h2>
<div className="text-[11px] text-base-content/35">
블루 승률 {insightsQuery.data?.sideWinRate.blue ?? 0}% · 레드 승률{' '}
{insightsQuery.data?.sideWinRate.red ?? 0}%
</div>
</div>
{matchesQuery.isLoading ? (
<div className="border border-base-content/10 bg-base-100 px-4 py-12 text-center text-sm text-base-content/35">
내전 기록을 불러오는 중...
</div>
) : (
<div className="space-y-3">
{matches.map((match) => (
<MatchCard key={match.matchId} match={match} manifest={ddragon} />
))}
{matches.length === 0 && (
<div className="border border-base-content/10 bg-base-100 px-4 py-12 text-center text-sm text-base-content/35">
아직 수집된 내전 결과가 없습니다.
</div>
)}
</div>
)}
{matchesQuery.hasNextPage && (
<button
type="button"
className="mt-3 w-full border border-base-content/15 bg-base-100 py-3 text-sm font-bold text-base-content/60 hover:text-primary hover:border-primary/30 disabled:opacity-40"
disabled={matchesQuery.isFetchingNextPage}
onClick={() => matchesQuery.fetchNextPage()}
>
{matchesQuery.isFetchingNextPage ? '불러오는 중...' : '+ 더 보기'}
</button>
)}
</section>
<section>
<div className="flex items-center justify-between gap-3 mb-3">
<h2 className="text-sm font-black text-base-content">선수 순위</h2>
<div className="text-[11px] text-base-content/35">
포지션은 Riot Match의 라인 정보를 기준으로 합니다.
</div>
</div>
<LeaderboardTable
rows={leaderboardQuery.data?.rows ?? []}
manifest={ddragon}
/>
</section>
</main>
);
}
@@ -0,0 +1,262 @@
import { Link, useParams } from 'react-router';
import { useDdragonManifest, useInternalMatchDetail } from '../api/hooks';
import type { ApiInternalMatchDetailResponse, TeamSide } from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import { championDisplayName, championIconUrl, itemIconUrl } from '../lib/ddragon';
import { LANE_LABELS } from '../lib/riot-history';
function formatDateTime(value: string | number) {
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function formatDuration(seconds: number) {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
return `${minutes}:${String(rest).padStart(2, '0')}`;
}
function sideLabel(side: TeamSide) {
return side === 'blue' ? '블루팀' : '레드팀';
}
function sideClass(side: TeamSide) {
return side === 'blue' ? 'text-blue-400 border-blue-500/20' : 'text-red-400 border-red-500/20';
}
function ChampionCell({
championId,
manifest,
}: {
championId: number;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
const icon = championIconUrl(manifest, championId);
const name = championDisplayName(manifest, championId) ?? String(championId);
return (
<div className="flex items-center gap-2 min-w-0">
<span className="w-8 h-8 bg-base-content/10 overflow-hidden shrink-0">
{icon ? <img src={icon} alt="" className="w-full h-full object-cover" /> : null}
</span>
<span className="font-bold text-[13px] truncate">{name}</span>
</div>
);
}
function ItemStrip({
items,
trinket,
manifest,
}: {
items: number[];
trinket: number;
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
return (
<div className="flex flex-wrap gap-1">
{[...items, trinket].map((itemId, index) => {
const icon = itemIconUrl(manifest, itemId);
return (
<span
key={`${itemId}-${index}`}
className="w-5 h-5 bg-base-content/10 border border-base-content/5 overflow-hidden"
>
{icon ? <img src={icon} alt="" className="w-full h-full object-cover" /> : null}
</span>
);
})}
</div>
);
}
function GamePanel({
game,
manifest,
}: {
game: ApiInternalMatchDetailResponse['games'][number];
manifest: ReturnType<typeof useDdragonManifest>['data'];
}) {
return (
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="px-4 py-3 border-b border-base-content/10 bg-base-200/40 flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-sm font-black text-base-content">
{game.gameNumber}경기
</h2>
<p className="mt-1 text-[11px] text-base-content/35">
{formatDateTime(game.gameCreation)} · {formatDuration(game.gameDuration)} ·{' '}
<span className="font-mono">{game.riotMatchId}</span>
</p>
</div>
<div className="flex gap-2">
{game.teams.map((team) => (
<span
key={team.side}
className={`border px-2 py-1 text-[11px] font-black ${sideClass(team.side)} ${
team.win ? 'bg-base-content/5' : 'opacity-40'
}`}
>
{sideLabel(team.side)} {team.win ? '승' : '패'}
</span>
))}
</div>
</div>
{game.teams.map((team) => (
<div key={team.side} className="border-b border-base-content/8 last:border-b-0">
<div className={`px-4 py-2 text-[11px] font-black uppercase tracking-wider ${sideClass(team.side)}`}>
{sideLabel(team.side)} · 바론 {team.objectives.baron} · 드래곤{' '}
{team.objectives.dragon} · 타워 {team.objectives.tower}
</div>
<div className="overflow-x-auto">
<table className="w-full text-left min-w-[980px]">
<thead>
<tr className="bg-base-content/[0.02] text-[11px] text-base-content/35 uppercase tracking-wider">
<th className="px-3 py-2">소환사</th>
<th className="px-3 py-2">챔피언</th>
<th className="px-3 py-2 text-center">포지션</th>
<th className="px-3 py-2 text-center">K/D/A</th>
<th className="px-3 py-2 text-center">CS</th>
<th className="px-3 py-2 text-center">GPM</th>
<th className="px-3 py-2 text-center">킬관여</th>
<th className="px-3 py-2 text-center">피해비중</th>
<th className="px-3 py-2">아이템</th>
</tr>
</thead>
<tbody>
{team.participants.map((participant) => (
<tr
key={`${team.side}-${participant.userId}-${participant.championId}`}
className="border-t border-base-content/5"
>
<td className="px-3 py-2">
{participant.userId ? (
<Link
to={`/users/${participant.userId}/history?queueGroup=internal`}
className="font-bold text-[13px] hover:text-primary"
>
{participant.summonerName}
</Link>
) : (
<span className="font-bold text-[13px]">
{participant.summonerName}
</span>
)}
</td>
<td className="px-3 py-2">
<ChampionCell championId={participant.championId} manifest={manifest} />
</td>
<td className="px-3 py-2 text-center text-[12px]">
{LANE_LABELS[participant.teamPosition] ?? participant.teamPosition ?? '-'}
</td>
<td className="px-3 py-2 text-center text-[13px] font-black tabular-nums">
{participant.kills}
<span className="text-base-content/25"> / </span>
<span className="text-red-400">{participant.deaths}</span>
<span className="text-base-content/25"> / </span>
{participant.assists}
</td>
<td className="px-3 py-2 text-center text-[12px] tabular-nums">
{participant.cs} ({participant.csPerMin}/m)
</td>
<td className="px-3 py-2 text-center text-[12px] tabular-nums">
{participant.gpm}
</td>
<td className="px-3 py-2 text-center text-[12px] tabular-nums">
{participant.killParticipation}%
</td>
<td className="px-3 py-2 text-center text-[12px] tabular-nums">
{participant.damageShare}%
</td>
<td className="px-3 py-2">
<ItemStrip
items={participant.items}
trinket={participant.trinket}
manifest={manifest}
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
))}
</section>
);
}
export default function InternalMatchDetailPage() {
const { cid, matchId } = useParams();
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const detailQuery = useInternalMatchDetail(matchId, communityId);
const { data: ddragon } = useDdragonManifest();
const detail = detailQuery.data;
if (detailQuery.isLoading) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center text-sm text-base-content/40">
내전 상세 기록을 불러오는 중...
</main>
);
}
if (detailQuery.error || !detail) {
return (
<main className="max-w-6xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">내전 기록을 찾을 수 없습니다</h1>
<Link
to={`/communities/${communityId}/internal-stats`}
className="btn btn-ghost btn-sm mt-4"
>
내전 전적으로 돌아가기
</Link>
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link
to={`/communities/${communityId}/internal-stats`}
className="text-xs text-base-content/40 hover:text-base-content"
>
← 내전 전적
</Link>
<section className="mt-5 mb-6 border border-base-content/10 bg-base-100 p-5">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-2xl font-black text-base-content">
{detail.match.title}
</h1>
<p className="mt-2 text-sm text-base-content/45">
{formatDateTime(detail.match.scheduledAt)} · {detail.match.gameCount}전제
</p>
</div>
<div className="flex items-center gap-6">
<div className={detail.match.winnerSide === 'blue' ? 'text-blue-400' : 'text-blue-400/30'}>
<div className="text-4xl font-black tabular-nums">{detail.match.blueScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">BLUE</div>
</div>
<div className="text-base-content/15 text-xs font-black">VS</div>
<div className={detail.match.winnerSide === 'red' ? 'text-red-400' : 'text-red-400/30'}>
<div className="text-4xl font-black tabular-nums">{detail.match.redScore}</div>
<div className="text-[10px] font-bold uppercase tracking-wider">RED</div>
</div>
</div>
</div>
</section>
<div className="space-y-4">
{detail.games.map((game) => (
<GamePanel key={game.riotMatchId} game={game} manifest={ddragon} />
))}
</div>
</main>
);
}
+885
View File
@@ -0,0 +1,885 @@
import { useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate, useParams } from 'react-router';
import {
useAuction,
useDdragonManifest,
useMatch,
useMe,
usePollTournamentResult,
useTournamentCodeStats,
} 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, TournamentCodeSlotView } 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">
<Link
to={`/users/${participant.userId}/history`}
className="flex items-center gap-2 group"
>
<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 group-hover:text-primary transition-colors">
{participant.summonerName}
</span>
<span className="text-[10px] text-base-content/25 leading-tight">
#{participant.tag}
</span>
</div>
</Link>
</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>
);
}
function formatTournamentCodeExpiry(value: string | null) {
if (!value) return null;
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function isExpiringSoon(value: string | null) {
if (!value) return false;
const expiresAt = new Date(value).getTime();
return expiresAt - Date.now() <= 24 * 60 * 60 * 1000;
}
function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) {
const [copied, setCopied] = useState(false);
const expired = slot.state === 'expired';
const used = slot.state === 'used';
const expiringSoon = isExpiringSoon(slot.expiresAt);
async function copyCode() {
if (!slot.code) return;
await navigator.clipboard.writeText(slot.code);
setCopied(true);
window.setTimeout(() => setCopied(false), 1600);
}
return (
<div className="flex-1 min-w-0">
<div
className={`flex items-center gap-2 border px-2 py-1.5 ${
expired
? 'border-red-500/20 bg-red-500/8 text-red-400'
: used
? 'border-base-content/8 bg-base-content/5 text-base-content/35'
: 'border-primary/20 bg-primary/5 text-base-content'
}`}
>
<code className="font-mono text-[12px] font-bold truncate">
{expired ? '코드 만료' : slot.code}
</code>
{slot.code && !expired && (
<button
type="button"
className="ml-auto text-[10px] px-1.5 py-0.5 border border-base-content/10 text-base-content/45 hover:text-primary"
onClick={copyCode}
>
{copied ? '복사됨' : '복사'}
</button>
)}
</div>
<div
className={`mt-1 text-[10px] ${
expired || expiringSoon ? 'text-amber-500' : 'text-base-content/30'
}`}
>
{used
? '사용됨'
: expired
? '운영자에게 새 코드를 요청해주세요.'
: `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`}
</div>
</div>
);
}
function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
return (
<div className="space-y-2">
{slots.map((slot) => (
<div key={slot.gameNumber} className="flex items-start gap-2">
<span className="text-[11px] font-bold text-base-content/40 w-11 shrink-0 pt-1.5">
{slot.gameNumber}경기
</span>
{slot.code ? (
<TournamentCodeDisplay slot={slot} />
) : (
<span className="text-[11px] text-base-content/30 border border-dashed border-base-content/10 px-2 py-2 flex-1">
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
</span>
)}
</div>
))}
</div>
);
}
function PoolStatsHint({ enabled }: { enabled: boolean }) {
const statsQuery = useTournamentCodeStats(DEFAULT_COMMUNITY_ID, enabled);
if (!enabled) return null;
const available = statsQuery.data?.available ?? 0;
const expiringSoon = statsQuery.data?.expiringSoon ?? 0;
return (
<div className="mt-3 border-t border-base-content/8 pt-3 text-[11px]">
<div className={available < 5 ? 'text-red-400' : 'text-base-content/35'}>
풀 잔여 {available}개
{expiringSoon > 0 ? ` · 만료 임박 ${expiringSoon}개` : ''}
</div>
<Link
to={`/admin/communities/${DEFAULT_COMMUNITY_ID}/tournament-codes`}
className="mt-1 inline-flex text-primary hover:underline"
>
코드 풀 관리
</Link>
</div>
);
}
function formatGameDuration(seconds: number) {
const minutes = Math.floor(seconds / 60);
const rest = seconds % 60;
return `${minutes}:${String(rest).padStart(2, '0')}`;
}
function resultSideLabel(side: 'blue' | 'red') {
return side === 'blue' ? '블루팀' : '레드팀';
}
function resultSideClass(side: 'blue' | 'red') {
return side === 'blue' ? 'text-blue-400' : 'text-red-400';
}
function MatchResultPanel({ match }: { match: MatchDetailView }) {
if (!match.result) return null;
const gamesByNumber = new Map(
match.result.games.map((game) => [game.gameNumber, game]),
);
const gameNumbers = Array.from(
{ length: match.gameCount },
(_, index) => index + 1,
);
return (
<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.winnerSide === 'blue' ? '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.winnerSide === 'red' ? '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
? `${match.result.winner} 승리`
: `결과 수집 중 · ${match.result.games.length}/${match.gameCount}경기`}
</div>
<div className="mt-5 border border-base-content/8 divide-y divide-base-content/8">
{gameNumbers.map((gameNumber) => {
const game = gamesByNumber.get(gameNumber);
return (
<div
key={gameNumber}
className="grid grid-cols-[56px_1fr_auto] gap-3 items-center px-3 py-2.5 text-xs"
>
<span className="text-base-content/35 font-bold">
{gameNumber}경기
</span>
{game ? (
<div>
<span className={`font-black ${resultSideClass(game.winnerSide)}`}>
{resultSideLabel(game.winnerSide)} 승
</span>
<span className="ml-2 text-base-content/35 font-mono">
{game.riotMatchId}
</span>
</div>
) : (
<span className="text-base-content/25">대기 중</span>
)}
<span className="text-base-content/35 font-mono">
{game ? formatGameDuration(game.gameDuration) : '-'}
</span>
</div>
);
})}
</div>
</div>
);
}
export default function MatchDetailPage() {
const { id } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const authUserId = useAuthUserId();
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
const meQuery = useMe();
const currentUser =
meQuery.data?.memberships.find(
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user ?? null;
const canUseMemberActions = Boolean(currentUser || authUserId);
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
const [blueCaptainUserId, setBlueCaptainUserId] = useState('');
const [redCaptainUserId, setRedCaptainUserId] = useState('');
const pollTournamentResultMutation = usePollTournamentResult(
DEFAULT_COMMUNITY_ID,
);
const joinMatchMutation = useMutation({
mutationFn: () =>
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`, {
method: 'POST',
body: JSON.stringify({
preferredPositions:
currentUser?.preferredPositions.length
? currentUser.preferredPositions.slice(0, 5)
: buildDefaultPreferredPositions(),
}),
}),
onSuccess: async () => {
await Promise.all([
queryClient.invalidateQueries({
queryKey: ['match', DEFAULT_COMMUNITY_ID, id ?? null],
}),
queryClient.invalidateQueries({
queryKey: ['matches', DEFAULT_COMMUNITY_ID],
}),
]);
},
});
const startAuctionMutation = useMutation({
mutationFn: () =>
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, {
method: 'POST',
body: JSON.stringify({
captains: [
{ 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`);
},
});
function handlePollTournamentResult() {
if (!id) return;
pollTournamentResultMutation.mutate(id, {
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ['match', DEFAULT_COMMUNITY_ID, id ?? null],
});
},
});
}
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>
)}
{pollTournamentResultMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{pollTournamentResultMutation.error.message}
</div>
)}
<MatchResultPanel match={match} />
<div className="flex flex-col lg:flex-row gap-5">
<div className="flex-1 min-w-0 space-y-4">
{match.status === 'recruiting' ? (
<>
<ParticipantTable
participants={match.participants}
maxParticipants={match.maxParticipants}
joined={match.joined}
canJoin={canUseMemberActions}
onJoin={() => joinMatchMutation.mutate()}
isJoining={joinMatchMutation.isPending}
/>
{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.status === 'team-built' || match.status === 'in-progress') && (
<SideCard title="토너먼트 코드">
<TournamentCodeList slots={match.tournamentCodes} />
<PoolStatsHint enabled={canManageAuction} />
</SideCard>
)}
{canManageAuction &&
(match.status === 'team-built' || match.status === 'in-progress') && (
<SideCard title="결과 수집">
<p className="text-[12px] text-base-content/45 mb-3">
Riot match-v5에서 토너먼트 코드가 붙은 경기를 다시 찾습니다.
</p>
<button
type="button"
className="btn btn-primary btn-sm w-full text-xs"
disabled={pollTournamentResultMutation.isPending}
onClick={handlePollTournamentResult}
>
{pollTournamentResultMutation.isPending
? '등록 중...'
: '결과 다시 수집'}
</button>
</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>
);
}