From fedca82c819297e78e0d6065177a35e69b4be08b Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sat, 2 May 2026 11:16:09 -0700 Subject: [PATCH] . --- .../dev-seeds/create-temp-finished-match.ts | 574 +++++++ apps/web/package.json | 1 + apps/web/src/pages/AuctionPage.tsx | 1485 +++++++++-------- apps/web/src/pages/MatchDetailPage.tsx | 352 +++- apps/web/src/pages/MatchTeamProgressPage.tsx | 728 ++++++-- pnpm-lock.yaml | 12 + 6 files changed, 2236 insertions(+), 916 deletions(-) create mode 100644 apps/api/src/modules/global/database/dev-seeds/create-temp-finished-match.ts diff --git a/apps/api/src/modules/global/database/dev-seeds/create-temp-finished-match.ts b/apps/api/src/modules/global/database/dev-seeds/create-temp-finished-match.ts new file mode 100644 index 00000000..79f9dc54 --- /dev/null +++ b/apps/api/src/modules/global/database/dev-seeds/create-temp-finished-match.ts @@ -0,0 +1,574 @@ +import 'reflect-metadata'; +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import mongoose from 'mongoose'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { ConnectionService, resolveMongoDbName } from '../connection.service'; +import type { + MatchGameResult, + MatchParticipant, + MatchSeriesResult, + MatchTeam, + Position, + PositionPreference, + TeamSide, + TierInfo, +} from '../schema'; +import { SecretModule } from '../../secret/secret.module'; + +const TEMP_JOB_ID = 'temp-finished-30-players-6-teams'; +const TEAM_COUNT = 6; +const TEAM_SIZE = 5; +const TOTAL_PLAYERS = TEAM_COUNT * TEAM_SIZE; +const GAME_COUNT_PER_SERIES_GROUP = 5; +const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; +const CHAMPION_IDS = [ + 266, 64, 103, 222, 412, 24, 421, 134, 145, 497, 58, 121, 777, 202, 111, 39, + 120, 7, 81, 89, 114, 104, 157, 51, 432, 92, 234, 61, 21, 53, +]; + +interface CliOptions { + communityId?: string; + dryRun: boolean; + nodeEnv: string; + replace: boolean; + scheduledAt: Date; + title: string; +} + +interface TempPlayer { + userId: mongoose.Types.ObjectId; + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + tier: TierInfo; + preferredPositions: PositionPreference[]; +} + +interface CommunityLean { + _id: mongoose.Types.ObjectId; + name?: string; +} + +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + envFilePath: [ + resolve(__dirname, '../../../../../../project.env'), + resolve(process.cwd(), '../project.env'), + resolve(process.cwd(), 'apps/project.env'), + resolve(process.cwd(), 'project.env'), + ], + }), + SecretModule, + ], + providers: [ConnectionService], +}) +class TempSeedModule {} + +async function loadMachineEnvFile() { + const homeDir = process.env.HOME ?? process.env.USERPROFILE; + if (!homeDir) return; + + const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt'); + + try { + const file = await readFile(machineEnvFile, 'utf8'); + for (const rawLine of file.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + + const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); + if (!matched) continue; + + const [, key, rawValue] = matched; + process.env[key] = rawValue.replace(/^["']|["']$/g, ''); + } + } catch { + // 로컬 machine env 파일이 없으면 그냥 지나간다. + } +} + +function parseArgs(argv: string[]): CliOptions { + let communityId = + process.env.VITE_DEFAULT_COMMUNITY_ID ?? process.env.DEFAULT_COMMUNITY_ID; + let dryRun = false; + let nodeEnv = process.env.NODE_ENV ?? 'dev'; + let replace = false; + let scheduledAt = new Date(Date.now() - 24 * 60 * 60 * 1000); + let title = `결과 검증 임시 내전 30인 6팀 ${formatStamp(new Date())}`; + + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === '--community-id') { + const value = argv[index + 1]; + if (!value) throw new Error('--community-id requires an ObjectId.'); + communityId = value; + index += 1; + continue; + } + if (arg.startsWith('--community-id=')) { + communityId = arg.slice('--community-id='.length); + continue; + } + if (arg === '--dry-run') { + dryRun = true; + continue; + } + if (arg === '--env') { + const value = argv[index + 1]; + if (!value) throw new Error('--env requires dev, test, or prod.'); + nodeEnv = value; + index += 1; + continue; + } + if (arg.startsWith('--env=')) { + nodeEnv = arg.slice('--env='.length); + continue; + } + if (arg === '--replace') { + replace = true; + continue; + } + if (arg === '--scheduled-at') { + scheduledAt = parseDateArg(argv[index + 1], '--scheduled-at'); + index += 1; + continue; + } + if (arg.startsWith('--scheduled-at=')) { + scheduledAt = parseDateArg( + arg.slice('--scheduled-at='.length), + '--scheduled-at', + ); + continue; + } + if (arg === '--title') { + const value = argv[index + 1]; + if (!value) throw new Error('--title requires a value.'); + title = value; + index += 1; + continue; + } + if (arg.startsWith('--title=')) { + title = arg.slice('--title='.length); + continue; + } + if (arg === '--help' || arg === '-h') { + printHelp(); + process.exit(0); + } + throw new Error(`Unknown argument: ${arg}`); + } + + if (!['dev', 'test', 'prod'].includes(nodeEnv)) { + throw new Error('--env must be dev, test, or prod.'); + } + if (communityId && !mongoose.isValidObjectId(communityId)) { + throw new Error('--community-id must be a valid ObjectId.'); + } + + return { + communityId: communityId?.trim() || undefined, + dryRun, + nodeEnv, + replace, + scheduledAt, + title, + }; +} + +function parseDateArg(value: string | undefined, label: string): Date { + if (!value) throw new Error(`${label} requires an ISO date value.`); + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) { + throw new Error(`${label} must be a valid ISO date value.`); + } + return parsed; +} + +function printHelp() { + console.log(`Usage: + pnpm --filter api exec ts-node src/modules/global/database/dev-seeds/create-temp-finished-match.ts + pnpm --filter api exec ts-node src/modules/global/database/dev-seeds/create-temp-finished-match.ts --replace + +Options: + --community-id Community ObjectId. Defaults to env or first community. + --dry-run Print the payload summary without writing. + --env dev | test | prod. Default: NODE_ENV or dev. + --replace Delete previous temp matches created by this script first. + --scheduled-at Scheduled date. Default: yesterday. + --title Match title. Default: timestamped temp title. +`); +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + process.env.NODE_ENV = options.nodeEnv; + await loadMachineEnvFile(); + + const app = await NestFactory.createApplicationContext(TempSeedModule, { + logger: ['log', 'warn', 'error'], + }); + + try { + const connectionService = app.get(ConnectionService); + const CommunityModel = await connectionService.getModel('community'); + const MatchModel = await connectionService.getModel('match'); + const community = await resolveCommunity( + CommunityModel, + options.communityId, + ); + + const payload = buildMatchPayload(community._id, options); + + console.log( + `[temp result seed] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${resolveMongoDbName(options.nodeEnv)}`, + ); + console.log( + `[temp result seed] community=${community.name ?? '(unnamed)'} (${community._id.toString()})`, + ); + console.log( + `[temp result seed] title="${options.title}" participants=${payload.participants.length} teams=${payload.teams.length} games=${payload.result.games.length}`, + ); + + if (options.dryRun) { + console.log('[temp result seed] No writes were made.'); + return; + } + + if (options.replace) { + const deleteResult = await MatchModel.deleteMany({ + communityId: community._id, + 'legacyImportSource.jobId': TEMP_JOB_ID, + }).exec(); + console.log( + `[temp result seed] deleted=${deleteResult.deletedCount ?? 0}`, + ); + } + + const match = await MatchModel.create(payload); + console.log(`[temp result seed] created=${match._id.toString()}`); + console.log(`[temp result seed] route=/match/${match._id.toString()}`); + } finally { + await app.close(); + } +} + +async function resolveCommunity( + CommunityModel: mongoose.Model<unknown>, + communityId?: string, +): Promise<CommunityLean> { + const community = communityId + ? await CommunityModel.findById(communityId) + .select({ name: 1 }) + .lean<CommunityLean>() + .exec() + : await CommunityModel.findOne() + .sort({ createdAt: 1 }) + .select({ name: 1 }) + .lean<CommunityLean>() + .exec(); + + if (!community) { + throw new Error( + communityId + ? `Community not found: ${communityId}` + : 'No community found. Pass --community-id.', + ); + } + + return community; +} + +function buildMatchPayload( + communityId: mongoose.Types.ObjectId, + options: CliOptions, +) { + const now = new Date(); + const players = buildPlayers(now); + const participants = players.map( + (player, index): MatchParticipant => ({ + userId: player.userId, + puuid: player.puuid, + gameName: player.gameName, + tagLine: player.tagLine, + profileIconId: player.profileIconId, + tier: player.tier, + preferredPositions: player.preferredPositions, + joinedAt: new Date( + options.scheduledAt.getTime() - (TOTAL_PLAYERS - index) * 60000, + ), + excluded: false, + }), + ); + const teams = buildTeams(players); + const games = buildGames(players, options.scheduledAt); + const seriesResults = buildSeriesResults(games); + const winnerTeamIndex = resolveOverallWinner(seriesResults); + + return { + communityId, + title: options.title, + description: + '결과 페이지 검증용으로 생성된 30명, 6팀, 15경기 완료 임시 데이터입니다.', + mapId: 11, + status: 'finished', + scheduledAt: options.scheduledAt, + maxParticipants: TOTAL_PLAYERS, + gameCount: GAME_COUNT_PER_SERIES_GROUP, + gameMode: 'round-robin', + tournamentCodeIds: [], + teamBuiltAt: new Date(options.scheduledAt.getTime() - 30 * 60000), + participants, + teams, + result: { + winnerTeamIndex, + mvpUserId: players[0].userId, + riotMatchIds: games.map((game) => game.riotMatchId), + games, + seriesResults, + }, + resultPollState: { + startedAt: new Date(options.scheduledAt.getTime() + 2 * 60 * 60 * 1000), + lastPolledAt: now, + lastPollOutcome: 'matched', + matchedCount: games.length, + expandedToAllPuuids: true, + state: 'complete', + }, + legacyImported: true, + legacyImportSource: { + importedAt: now, + importedBy: players[0].userId, + triggeringPuuid: players[0].puuid, + jobId: TEMP_JOB_ID, + }, + prizes: ['1등 팀: 결과 화면 검증용 임시 상품', 'MVP: Temp01'], + notices: ['이 매치는 UI 검증용 임시 데이터입니다.'], + schedule: [ + { time: '20:00', label: '로비 오픈' }, + { time: '20:10', label: '1경기 시작' }, + { time: '23:30', label: '풀리그 종료' }, + ], + }; +} + +function buildPlayers(now: Date): TempPlayer[] { + return Array.from({ length: TOTAL_PLAYERS }, (_, index) => { + const playerNumber = index + 1; + const primaryPosition = POSITIONS[index % POSITIONS.length]; + + return { + userId: new mongoose.Types.ObjectId(), + puuid: `temp-result-puuid-${playerNumber.toString().padStart(2, '0')}`, + gameName: `Temp${playerNumber.toString().padStart(2, '0')}`, + tagLine: `T${playerNumber.toString().padStart(3, '0')}`, + profileIconId: 20 + playerNumber, + tier: buildTier(playerNumber, now), + preferredPositions: buildPreferredPositions(primaryPosition), + }; + }); +} + +function buildPreferredPositions( + primaryPosition: Position, +): PositionPreference[] { + const ordered = [ + primaryPosition, + ...POSITIONS.filter((position) => position !== primaryPosition), + ]; + return ordered.map((position, index) => ({ + position, + priority: index + 1, + })); +} + +function buildTier(playerNumber: number, fetchedAt: Date): TierInfo { + const tiers = [ + ['CHALLENGER', 'I'], + ['GRANDMASTER', 'I'], + ['MASTER', 'I'], + ['DIAMOND', 'I'], + ['DIAMOND', 'II'], + ['EMERALD', 'I'], + ['EMERALD', 'II'], + ['PLATINUM', 'I'], + ['PLATINUM', 'II'], + ['GOLD', 'I'], + ] as const; + const [tier, rank] = tiers[(playerNumber - 1) % tiers.length]; + + return { + queueType: 'RANKED_SOLO_5x5', + tier, + rank, + leaguePoints: (playerNumber * 17) % 100, + wins: 40 + playerNumber, + losses: 22 + (playerNumber % 13), + fetchedAt, + }; +} + +function buildTeams(players: TempPlayer[]): MatchTeam[] { + return Array.from({ length: TEAM_COUNT }, (_, teamOffset) => { + const teamIndex = teamOffset + 1; + const members = players + .slice(teamOffset * TEAM_SIZE, (teamOffset + 1) * TEAM_SIZE) + .map((player, memberOffset) => ({ + userId: player.userId, + assignedPosition: POSITIONS[memberOffset], + cost: memberOffset === 0 ? 0 : 80 + teamIndex * 15 + memberOffset * 20, + })); + + return { + teamIndex, + name: `${teamIndex}팀`, + captainUserId: members[0]?.userId, + members, + }; + }); +} + +function buildGames( + players: TempPlayer[], + scheduledAt: Date, +): MatchGameResult[] { + const games: MatchGameResult[] = []; + const playersByTeam = new Map<number, TempPlayer[]>(); + + for (let teamIndex = 1; teamIndex <= TEAM_COUNT; teamIndex += 1) { + playersByTeam.set( + teamIndex, + players.slice((teamIndex - 1) * TEAM_SIZE, teamIndex * TEAM_SIZE), + ); + } + + for (let teamAIndex = 1; teamAIndex <= TEAM_COUNT; teamAIndex += 1) { + for ( + let teamBIndex = teamAIndex + 1; + teamBIndex <= TEAM_COUNT; + teamBIndex += 1 + ) { + const gameNumber = games.length + 1; + const lowerTeamStartsBlue = gameNumber % 2 === 1; + const blueTeamIndex = lowerTeamStartsBlue ? teamAIndex : teamBIndex; + const redTeamIndex = lowerTeamStartsBlue ? teamBIndex : teamAIndex; + const winnerTeamIndex = teamAIndex; + const winnerSide: TeamSide = + winnerTeamIndex === blueTeamIndex ? 'blue' : 'red'; + const gameCreation = scheduledAt.getTime() + gameNumber * 20 * 60 * 1000; + const riotMatchId = `KR_TEMP_30X6_${formatStamp(scheduledAt)}_${gameNumber + .toString() + .padStart(2, '0')}`; + + games.push({ + gameNumber, + riotMatchId, + blueTeamIndex, + redTeamIndex, + winnerTeamIndex, + winnerSide, + gameCreation, + gameDuration: 1650 + gameNumber * 23, + participants: [ + ...buildGameParticipants({ + players: playersByTeam.get(blueTeamIndex) ?? [], + teamIndex: blueTeamIndex, + side: 'blue', + winnerTeamIndex, + gameNumber, + }), + ...buildGameParticipants({ + players: playersByTeam.get(redTeamIndex) ?? [], + teamIndex: redTeamIndex, + side: 'red', + winnerTeamIndex, + gameNumber, + }), + ], + }); + } + } + + return games; +} + +function buildGameParticipants(params: { + players: TempPlayer[]; + teamIndex: number; + side: TeamSide; + winnerTeamIndex: number; + gameNumber: number; +}): MatchGameResult['participants'] { + const didWin = params.teamIndex === params.winnerTeamIndex; + + return params.players.map((player, index) => { + const championIndex = + (params.gameNumber + params.teamIndex + index) % CHAMPION_IDS.length; + return { + userId: player.userId, + teamIndex: params.teamIndex, + side: params.side, + championId: CHAMPION_IDS[championIndex], + kills: didWin + ? 4 + ((params.gameNumber + index) % 8) + : 1 + ((params.gameNumber + index) % 5), + deaths: didWin ? 1 + (index % 4) : 4 + ((params.gameNumber + index) % 7), + assists: didWin + ? 7 + ((params.gameNumber + index) % 12) + : 3 + ((params.gameNumber + index) % 8), + win: didWin, + }; + }); +} + +function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] { + return games.map((game) => { + const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); + const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); + + return { + teamAIndex, + teamBIndex, + teamAWins: game.winnerTeamIndex === teamAIndex ? 1 : 0, + teamBWins: game.winnerTeamIndex === teamBIndex ? 1 : 0, + winnerTeamIndex: game.winnerTeamIndex, + }; + }); +} + +function resolveOverallWinner( + seriesResults: MatchSeriesResult[], +): number | undefined { + const winsByTeam = new Map<number, number>(); + for (const series of seriesResults) { + if (!series.winnerTeamIndex) continue; + winsByTeam.set( + series.winnerTeamIndex, + (winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1, + ); + } + + return [...winsByTeam.entries()].sort( + (left, right) => right[1] - left[1], + )[0]?.[0]; +} + +function formatStamp(date: Date): string { + const year = date.getFullYear(); + const month = `${date.getMonth() + 1}`.padStart(2, '0'); + const day = `${date.getDate()}`.padStart(2, '0'); + const hours = `${date.getHours()}`.padStart(2, '0'); + const minutes = `${date.getMinutes()}`.padStart(2, '0'); + const seconds = `${date.getSeconds()}`.padStart(2, '0'); + return `${year}${month}${day}-${hours}${minutes}${seconds}`; +} + +void main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; +}); diff --git a/apps/web/package.json b/apps/web/package.json index 03e56ae4..e689239d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -19,6 +19,7 @@ "@azure/msal-browser": "^5.8.0", "@azure/msal-react": "^5.3.1", "@tanstack/react-query": "^5.100.1", + "lucide-react": "^1.14.0", "react": "^19.2.4", "react-dom": "^19.2.4", "react-router": "^7.14.0", diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index 0de47220..b80c418e 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -1,850 +1,867 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; -import { Link, useParams } from 'react-router'; -import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks'; +import { useState } from "react"; +import { ChevronDown, ChevronUp, ClipboardCheck, Copy } from "lucide-react"; +import { Link, useParams } from "react-router"; import { - formatTierLabel, - getTierColorToken, - mapApiAuctionToAuctionState, - type AuctionStateView, -} from '../api/mappers'; -import { useAuctionSocket } from '../api/useAuctionSocket'; -import { - DEFAULT_COMMUNITY_ID, - setDevCaptainTeamIndex, - useDevCaptainTeamIndex, -} from '../config'; -import { ApiError } from '../lib/api'; -import { - championDisplayName, - championIconUrl, - profileIconUrl, -} from '../lib/ddragon'; -import { - positionIcon, - positionLabel, - teamIndexColorClasses, - teamIndexLabel, -} from '../lib/league'; + useDdragonManifest, + useMatch, + useUserHistoryProfile, +} from "../api/hooks"; +import { formatKoreanDate, formatTierLabel } from "../api/mappers"; import type { - ApiAuction, - ApiRiotLaneStats, + ApiMatch, + ApiMatchGameResult, + ApiMatchParticipant, + ApiTierInfo, + MatchGameMode, Position, -} from '../api/types'; + TeamSide, + TournamentCodeSlotView, +} from "../api/types"; +import { DEFAULT_COMMUNITY_ID } from "../config"; +import { profileIconUrl } from "../lib/ddragon"; +import { positionLabel, sideShortLabel, teamIndexLabel } from "../lib/league"; -type CaptainRole = { - teamIndex: number; +const GAME_MODE_LABEL: Record<MatchGameMode, string> = { + pair: "페어 매치", + bracket: "토너먼트", + "round-robin": "리그전", }; -function formatPoints(value: number) { - return value.toLocaleString(); +function cn(...classes: Array<string | false | null | undefined>) { + return classes.filter(Boolean).join(" "); } -function isCurrentBidder( - currentBidder: AuctionStateView['currentBidder'], - team: Pick<AuctionStateView['teams'][number], 'teamIndex'>, +function resultBadgeClass(won: boolean) { + return won + ? "border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-300" + : "border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-300"; +} + +function sideBadgeClass(side: TeamSide) { + return side === "blue" + ? "border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300" + : "border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300"; +} + +function captainName( + team: ApiMatch["teams"][number] | undefined, + participantByUserId: Map<string, ApiMatchParticipant>, ) { - return currentBidder?.teamIndex === team.teamIndex; + if (!team?.captainUserId) return undefined; + return participantByUserId.get(team.captainUserId)?.gameName; } -function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) { - if (!auction) return 0; - return Date.parse(auction.updatedAt ?? auction.createdAt ?? '') || 0; +function tierByQueue(tiers: ApiTierInfo[], queueType: string) { + return tiers.find((tier) => tier.queueType === queueType); } -function pickLatestAuction( - socketAuction: ApiAuction | null, - queryAuction: ApiAuction | undefined, -) { - if (!socketAuction) return queryAuction ?? null; - if (!queryAuction) return socketAuction; - return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction) - ? queryAuction - : socketAuction; +function normalizeRank(rank: string | undefined) { + switch (rank) { + case "I": + return "1"; + case "II": + return "2"; + case "III": + return "3"; + case "IV": + return "4"; + default: + return rank; + } } -const AUCTION_MAX_TEAM_SIZE = 5; -const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; -const POSITION_TO_RIOT_LANE = { - TOP: 'TOP', - JGL: 'JUNGLE', - MID: 'MIDDLE', - ADC: 'BOTTOM', - SUP: 'UTILITY', -} as const; +function formatRankTooltip(tier: ApiTierInfo | undefined) { + if (!tier) return "언랭크"; + + const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier); + const normalizedTier = { + ...tier, + rank: normalizeRank(tier.rank) ?? tier.rank, + }; + + const label = highTier + ? formatTierLabel({ ...normalizedTier, leaguePoints: 0 }) + : formatTierLabel(normalizedTier); + + return `${label} - ${tier.leaguePoints}LP`; +} + +function formatRankBadge(tier: ApiTierInfo | undefined) { + if (!tier) return "U"; + + const tierInitial = + tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1); + const rank = normalizeRank(tier.rank); + + return rank ? `${tierInitial}${rank}` : tierInitial; +} + +function rankBadgeClass(tier: ApiTierInfo | undefined) { + switch (tier?.tier) { + case "CHALLENGER": + return "border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200"; + case "GRANDMASTER": + return "border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200"; + case "MASTER": + return "border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200"; + case "DIAMOND": + return "border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200"; + case "EMERALD": + return "border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200"; + case "PLATINUM": + return "border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200"; + case "GOLD": + return "border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200"; + case "SILVER": + return "border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200"; + case "BRONZE": + return "border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200"; + case "IRON": + return "border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300"; + default: + return "border-base-content/25 bg-base-content/5 text-base-content/55"; + } +} + +function RankBadge({ tier }: { tier?: ApiTierInfo }) { + const tooltip = formatRankTooltip(tier); -function PosBadge({ pos }: { pos: Position }) { return ( - <span className="inline-flex items-center gap-1.5 text-[11px] font-medium px-1.5 py-0.5 border border-primary/20 text-primary bg-primary/5"> - <img src={positionIcon[pos]} alt="" className="w-3.5 h-3.5 object-contain" /> - <span>{positionLabel[pos]}</span> + <span className="tooltip tooltip-left" data-tip={tooltip}> + <span + className={cn( + "inline-flex h-[18px] min-w-[20px] shrink-0 items-center justify-center whitespace-nowrap rounded border px-1 text-[10px] font-black leading-none", + rankBadgeClass(tier), + )} + aria-label={tooltip} + > + {formatRankBadge(tier)} + </span> </span> ); } -function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) { - const pct = maxTimer > 0 ? (timer / maxTimer) * 100 : 0; - const urgent = timer <= 5; - +function QueueRankCell({ + label, + tier, +}: { + label: "SOLO" | "FLEX"; + tier?: ApiTierInfo; +}) { return ( - <div className="w-full h-1.5 bg-base-content/5"> - <div - className={`h-full transition-all duration-1000 linear ${urgent ? 'bg-red-500' : 'bg-primary'}`} - style={{ width: `${pct}%` }} - /> - </div> + <span className="inline-flex items-center justify-end gap-1.5 whitespace-nowrap"> + <span className="text-[10px] font-black text-base-content/45"> + {label} + </span> + <RankBadge tier={tier} /> + </span> ); } -function getWinRate(stats: ApiRiotLaneStats) { - return stats.games > 0 ? Math.round((stats.wins / stats.games) * 100) : 0; -} - -function getWinRateClass(winRate: number) { - if (winRate >= 55) return 'text-blue-400'; - if (winRate >= 50) return 'text-base-content'; - return 'text-red-400'; -} - -function formatKdaRatio(stats: ApiRiotLaneStats) { - if (stats.avgDeaths === 0) return 'Perfect'; - return ((stats.avgKills + stats.avgAssists) / stats.avgDeaths).toFixed(2); -} - -function RecentSoloStats({ - player, +function ParticipantLine({ + participant, + assignedPosition, + isCaptain, }: { - player: NonNullable<AuctionStateView['currentPlayer']>; + participant?: ApiMatchParticipant; + assignedPosition?: Position; + isCaptain?: boolean; }) { - const primaryStats = player.recentStats.primary; + const { data: ddragon } = useDdragonManifest(); + const profileQuery = useUserHistoryProfile( + participant?.userId, + DEFAULT_COMMUNITY_ID, + ); - if (!primaryStats) { - return ( - <div className="p-4"> - <h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30 mb-2.5"> - 최근 솔로랭크 - </h4> - <div className="rounded border border-dashed border-base-content/10 px-3 py-6 text-center text-[11px] text-base-content/25"> - 최근 솔로랭크 기록이 없습니다 + const name = participant?.gameName ?? "알 수 없는 참가자"; + const tag = participant?.tagLine ?? "----"; + 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"); + const positionText = assignedPosition ? positionLabel[assignedPosition] : "-"; + + const content = ( + <> + <div className="h-10 w-10 shrink-0 overflow-hidden rounded-md bg-base-content/10"> + <img + src={profileIconUrl(ddragon, participant?.profileIconId ?? 0)} + alt="" + className="h-full w-full object-cover" + loading="lazy" + /> + </div> + + <div className="min-w-0"> + <div className="flex min-w-0 items-center gap-2"> + <span className="truncate text-sm font-black text-base-content"> + {name} + </span> + {isCaptain && ( + <span className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-black text-amber-600 dark:text-amber-300"> + 팀장 + </span> + )} + </div> + + <div className="mt-0.5 truncate text-[11px] font-medium text-base-content/45"> + #{tag} + </div> + + <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 sm:hidden"> + <span className="text-[11px] font-black text-primary"> + {positionText} + </span> + <QueueRankCell label="SOLO" tier={soloTier} /> + <QueueRankCell label="FLEX" tier={flexTier} /> </div> </div> + + <div className="hidden text-right text-[11px] font-black text-primary sm:block"> + {positionText} + </div> + + <div className="hidden justify-end sm:flex"> + <QueueRankCell label="SOLO" tier={soloTier} /> + </div> + + <div className="hidden justify-end sm:flex"> + <QueueRankCell label="FLEX" tier={flexTier} /> + </div> + </> + ); + + const className = + "grid grid-cols-[auto_minmax(0,1fr)] items-center gap-3 border-b border-base-content/5 px-3 py-2.5 last:border-b-0 sm:grid-cols-[auto_minmax(0,1fr)_56px_86px_86px]"; + + if (participant?.userId) { + return ( + <Link + to={`/users/${participant.userId}/history`} + className={cn( + className, + "transition-colors hover:bg-base-content/[0.035]", + )} + > + {content} + </Link> ); } - const primaryWinRate = getWinRate(primaryStats); - const primaryKdaRatio = formatKdaRatio(primaryStats); + return <div className={className}>{content}</div>; +} +function TeamMemberScoutLine({ + isCaptain, + member, + participant, +}: { + isCaptain?: boolean; + member: ApiMatch["teams"][number]["members"][number]; + participant?: ApiMatchParticipant; +}) { return ( - <div className="p-4"> - <div className="flex items-start justify-between gap-3 mb-3"> + <ParticipantLine + assignedPosition={member.assignedPosition} + isCaptain={isCaptain} + participant={participant} + /> + ); +} + +function MemberListHeader({ + title, + subtitle, + trailing, +}: { + title: string; + subtitle?: string; + trailing?: string; +}) { + return ( + <div className="border-b border-base-content/8 bg-base-200/30"> + <div className="flex items-start justify-between gap-3 px-3 py-2.5"> <div> - <h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30"> - 최근 솔로랭크 - </h4> - <div className="mt-1 flex items-center gap-2"> - <span className="text-[12px] font-semibold text-base-content"> - {positionLabel[player.mainPosition]} - </span> - {player.recentStats.primarySource === 'overall' ? ( - <span className="text-[10px] text-base-content/35"> - 전체 기준 - </span> - ) : null} + <div className="text-[11px] font-black text-base-content/70"> + {title} </div> - </div> - <div - className={`text-sm font-bold tabular-nums ${getWinRateClass(primaryWinRate)}`} - > - {primaryWinRate}% - </div> - </div> - - <div className="space-y-2"> - <div className="flex items-baseline justify-between"> - <span className="text-[11px] text-base-content/40">전적</span> - <span className="text-[12px] text-base-content/60 tabular-nums"> - <span className="text-blue-400">{primaryStats.wins}W</span>{' '} - <span className="text-red-400">{primaryStats.losses}L</span> - </span> - </div> - <div className="flex items-baseline justify-between"> - <span className="text-[11px] text-base-content/40">KDA</span> - <span className="text-[12px] text-base-content/60 tabular-nums"> - {primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists} - <span - className={`ml-1 font-bold ${Number(primaryKdaRatio) >= 3 ? 'text-emerald-400' : 'text-base-content/50'}`} - > - ({primaryKdaRatio}) - </span> - </span> - </div> - <div className="flex items-baseline justify-between"> - <span className="text-[11px] text-base-content/40">분당 CS</span> - <span className="text-[12px] text-base-content/60 tabular-nums"> - {primaryStats.avgCsPerMin} - </span> - </div> - </div> - - <div className="mt-4 border-t border-base-content/8 pt-3 space-y-1.5"> - {LANE_ROWS.map((position) => { - const laneStats = - player.recentStats.byLane[POSITION_TO_RIOT_LANE[position]]; - const isMainLane = position === player.mainPosition; - - return ( - <div - key={position} - className={`flex items-center justify-between gap-3 text-[11px] ${isMainLane ? 'font-semibold text-base-content' : 'text-base-content/65'}`} - > - <span className={isMainLane ? 'text-base-content' : 'text-base-content/35'}> - {positionLabel[position]} - </span> - {laneStats && laneStats.games > 0 ? ( - <span className="tabular-nums text-right"> - {laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/ - {laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '} - {laneStats.avgCsPerMin} CS/min - </span> - ) : ( - <span className="text-base-content/20">—</span> - )} + {subtitle && ( + <div className="mt-0.5 text-[10px] font-medium text-base-content/45"> + {subtitle} </div> - ); - })} + )} + </div> + + {trailing && ( + <div className="min-w-0 truncate text-right text-[11px] font-bold text-base-content/55"> + {trailing} + </div> + )} + </div> + + <div className="hidden grid-cols-[auto_minmax(0,1fr)_56px_86px_86px] items-center gap-3 border-t border-base-content/6 px-3 py-1.5 text-[10px] font-black uppercase tracking-wider text-base-content/35 sm:grid"> + <div /> + <div>소환사</div> + <div className="text-right">라인</div> + <div className="text-right">솔로</div> + <div className="text-right">자유</div> </div> </div> ); } -function TeamPanel({ - team, - isActive, - isLeft, +function TeamVersusPanel({ + align = "left", + captain, + label, + name, + tone = "normal", }: { - team: AuctionStateView['teams'][number]; - isActive: boolean; - isLeft: boolean; + align?: "left" | "right"; + captain?: string; + label: string; + name: string; + tone?: "primary" | "normal"; }) { - const { data: ddragon } = useDdragonManifest(); - const tone = teamIndexColorClasses(team.teamIndex); - const teamSize = team.members.length + 1; - const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE; - return ( <div - className={`border ${tone.border} bg-base-100 relative ${isActive ? 'ring-1 ring-primary/30' : ''}`} + className={cn( + "min-w-0 rounded-lg border bg-base-100 p-3", + align === "right" && "text-right", + tone === "primary" + ? "border-primary/25 bg-primary/[0.04]" + : "border-base-content/10 bg-base-200/25", + )} > + <div className="text-[11px] font-black uppercase tracking-wider text-base-content/45"> + {label} + </div> <div - className={`absolute ${isLeft ? 'left-0' : 'right-0'} top-0 bottom-0 w-0.5 ${tone.bar}`} - /> - <div className={`${tone.bg} px-3 py-2 border-b ${tone.border}`}> - <div className="flex items-center justify-between"> - <div className="flex items-center gap-2"> - <span className={`text-[11px] font-bold uppercase tracking-wide ${tone.text}`}> - {teamIndexLabel(team.teamIndex, team.name)} - </span> - <span className="text-[10px] text-base-content/30"> - 팀장: {team.captainName} - </span> - </div> - <span className="text-xs font-bold text-amber-400 tabular-nums"> - {formatPoints(team.points)}P - </span> - </div> - <div className="mt-1 flex items-center justify-between text-[10px]"> - <span className="text-base-content/25"> - 팀장 포함 {teamSize}/{AUCTION_MAX_TEAM_SIZE} - </span> - {isFull && <span className="font-bold text-amber-400">정원 완료</span>} - </div> - </div> - - <div className="divide-y divide-base-content/5"> - {team.members.length === 0 ? ( - <div className="px-3 py-6 text-center text-[11px] text-base-content/20"> - 아직 멤버가 없습니다 - </div> - ) : ( - team.members.map((member) => ( - <div key={`${member.userId}-${member.assignedPosition}`} className="px-3 py-1.5 flex items-center gap-2"> - <Link - to={`/users/${member.userId}/history`} - className="flex flex-1 min-w-0 items-center gap-2 group" - > - <div className="w-6 h-6 bg-base-content/10 overflow-hidden shrink-0"> - <img - src={profileIconUrl(ddragon, member.profileIconId)} - alt="" - className="w-full h-full object-cover" - loading="lazy" - /> - </div> - <div className="flex-1 min-w-0"> - <span className="text-[12px] font-medium text-base-content truncate block leading-tight group-hover:text-primary transition-colors"> - {member.summonerName} - </span> - </div> - </Link> - <PosBadge pos={member.assignedPosition} /> - <span className="text-[10px] text-amber-400/60 tabular-nums w-8 text-right"> - {member.cost} - </span> - </div> - )) + className={cn( + "mt-1 truncate text-sm font-black", + tone === "primary" ? "text-primary" : "text-base-content", )} - - {Array.from({ - length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length), - }).map((_, index) => ( - <div - key={`empty-${team.teamIndex}-${index}`} - className="px-3 py-1.5 h-[34px] flex items-center" - > - <div className="w-6 h-6 border border-dashed border-base-content/8 shrink-0" /> - <span className="ml-2 text-[10px] text-base-content/10">—</span> - </div> - ))} + > + {name} </div> - </div> - ); -} - -function PlayerSpotlight({ - state, -}: { - state: AuctionStateView; -}) { - const { data: ddragon } = useDdragonManifest(); - const player = state.currentPlayer; - if (!player) return null; - - return ( - <div className="border border-base-content/10 bg-base-100"> - <div className="p-5 border-b border-base-content/8"> - <div className="flex items-start gap-4"> - <Link - to={`/users/${player.userId}/history`} - className="w-16 h-16 bg-base-content/10 overflow-hidden shrink-0" - > - <img - src={profileIconUrl(ddragon, player.profileIconId)} - alt="" - className="w-full h-full object-cover" - /> - </Link> - <div className="flex-1"> - <div className="flex items-center gap-2 mb-1"> - <Link - to={`/users/${player.userId}/history`} - className="text-lg font-bold text-base-content leading-tight hover:text-primary transition-colors" - > - {player.summonerName} - </Link> - <span className="text-[10px] text-base-content/25"> - #{player.tag} - </span> - </div> - <div className={`text-[11px] mb-2 font-bold ${getTierColorToken(player.tier)}`}> - {formatTierLabel(player.tier)} - </div> - <div className="flex items-center gap-1.5"> - <PosBadge pos={player.mainPosition} /> - <span className="inline-flex items-center gap-0.5 text-[11px] px-1.5 py-0.5 border border-base-content/8 text-base-content/35"> - <img - src={positionIcon[player.subPosition]} - alt="" - className="w-3.5 h-3.5 object-contain inline" - />{' '} - {positionLabel[player.subPosition]} - </span> - </div> - </div> - </div> - </div> - - <div className="grid grid-cols-2 divide-x divide-base-content/5"> - <div className="p-4"> - <h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30 mb-2.5"> - 숙련도 높은 챔피언 - </h4> - <div className="space-y-2"> - {player.masteries.length > 0 ? ( - player.masteries.map((mastery) => { - const iconUrl = championIconUrl(ddragon, mastery.championId); - const displayName = - championDisplayName(ddragon, mastery.championId) ?? - String(mastery.championId); - return ( - <div key={mastery.championId} className="flex items-center gap-2"> - <div className="w-7 h-7 bg-base-content/10 overflow-hidden shrink-0"> - {iconUrl ? ( - <img - src={iconUrl} - alt={displayName} - className="w-full h-full object-cover" - loading="lazy" - /> - ) : null} - </div> - <div className="flex-1 min-w-0"> - <div className="text-[12px] font-medium text-base-content truncate"> - {displayName} - </div> - <div className="text-[10px] text-base-content/25"> - Lv.{mastery.level} · {(mastery.points / 1000).toFixed(0)}K - </div> - </div> - </div> - ); - }) - ) : ( - <div className="text-[11px] text-base-content/25"> - 숙련도 데이터가 없습니다. - </div> - )} - </div> - </div> - - <RecentSoloStats player={player} /> - </div> - - {(state.phase === 'bidding' || state.phase === 'sold') && ( - <div className="border-t border-base-content/8 px-4 py-3 bg-base-content/[0.02]"> - <div className="flex items-center justify-between"> - <span className="text-[11px] text-base-content/30 uppercase tracking-wider font-semibold"> - {state.phase === 'sold' ? '낙찰가' : '현재 입찰가'} - </span> - <div className="flex items-center gap-2"> - {state.currentBidder && ( - <span - className={`text-[10px] font-bold uppercase ${teamIndexColorClasses(state.currentBidder.teamIndex).text}`} - > - {teamIndexLabel(state.currentBidder.teamIndex)} - </span> - )} - <span className="text-lg font-black text-amber-400 tabular-nums"> - {state.currentBid > 0 ? formatPoints(state.currentBid) : '—'} - </span> - </div> - </div> + {captain && ( + <div className="mt-1 truncate text-[11px] font-medium text-base-content/55"> + 팀장 {captain} </div> )} </div> ); } -function BidControls({ - state, - captainRole, - onBid, +function UpcomingGameCard({ + expanded, + game, + isNext, + onToggle, + participantByUserId, + parsedTeamIndex, + slot, + teamByIndex, }: { - state: AuctionStateView; - captainRole: CaptainRole | null; - onBid: (teamIndex: number, amount: number) => void; + expanded: boolean; + game?: ApiMatchGameResult; + isNext?: boolean; + onToggle: () => void; + participantByUserId: Map<string, ApiMatchParticipant>; + parsedTeamIndex: number; + slot: TournamentCodeSlotView; + teamByIndex: Map<number, ApiMatch["teams"][number]>; }) { - const [bidAmount, setBidAmount] = useState(100); - const minBid = state.currentBid + 10; - const activeTeam = captainRole - ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) - : null; - const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; - const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; + const [copied, setCopied] = useState(false); - useEffect(() => { - setBidAmount(Math.max(minBid, Math.ceil(minBid / 10) * 10)); - }, [state.currentBid, minBid]); + const opponentIndex = + slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex; - if (state.phase !== 'bidding') return null; + const ourTeam = teamByIndex.get(parsedTeamIndex); + const opponentTeam = teamByIndex.get(opponentIndex); - if (!activeTeam) { - return ( - <div className="border border-base-content/10 bg-base-100 px-4 py-3 text-sm text-base-content/40"> - 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다. - </div> - ); + const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name); + const opponentTeamName = teamIndexLabel(opponentIndex, opponentTeam?.name); + + const ourCaptainName = captainName(ourTeam, participantByUserId); + const opponentCaptainName = captainName(opponentTeam, participantByUserId); + + const opponentMembers = opponentTeam?.members ?? []; + const finished = Boolean(game?.winnerTeamIndex); + const won = finished && game?.winnerTeamIndex === parsedTeamIndex; + + const ourSide: TeamSide = + slot.teamAIndex === parsedTeamIndex ? "blue" : "red"; + + async function handleCopy() { + if (!slot.code) return; + + try { + await navigator.clipboard.writeText(slot.code); + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + } catch { + setCopied(false); + } } - const presets = [50, 100, 150, 200, 300, 500]; - return ( - <div className="border border-base-content/10 bg-base-100 p-4"> - <div className="flex items-center gap-2 mb-3 flex-wrap"> - {presets.map((preset) => ( - <button - key={preset} - onClick={() => setBidAmount(Math.max(minBid, preset))} - disabled={isActiveTeamFull} - className={`text-[11px] px-2.5 py-1 border transition-colors ${ - bidAmount === preset - ? 'border-primary/40 bg-primary/10 text-primary' - : 'border-base-content/10 text-base-content/40 hover:border-base-content/20' - }`} + <li + className={cn( + "w-full rounded-xl border bg-base-100 p-4 shadow-sm transition-colors sm:p-5", + isNext + ? "border-primary/30 bg-primary/[0.025]" + : "border-base-content/10", + finished && "bg-base-content/[0.012]", + )} + > + <div className="flex items-center justify-between gap-3"> + <div className="flex flex-wrap items-center gap-2"> + <span + className={cn( + "inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-black", + isNext + ? "border-primary/25 bg-primary/10 text-primary" + : "border-base-content/10 bg-base-content/5 text-base-content/65", + )} > - {preset}P - </button> - ))} - <input - type="number" - value={bidAmount} - onChange={(event) => - setBidAmount(Math.max(minBid, Number(event.target.value))) - } - min={minBid} - disabled={isActiveTeamFull} - className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30" + {isNext ? "다음 경기" : `${slot.gameNumber}경기`} + </span> + + <span + className={cn( + "inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-black", + sideBadgeClass(ourSide), + )} + > + {sideShortLabel(ourSide)} + </span> + + {finished && ( + <span + className={cn( + "inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-black", + resultBadgeClass(won), + )} + > + {won ? "승리" : "패배"} + </span> + )} + </div> + + <button + type="button" + className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-base-content/45 transition-colors hover:bg-base-content/5 hover:text-primary" + onClick={onToggle} + aria-expanded={expanded} + aria-label={expanded ? "상대팀 정보 접기" : "상대팀 정보 펼치기"} + > + {expanded ? ( + <ChevronUp className="h-4 w-4" aria-hidden="true" /> + ) : ( + <ChevronDown className="h-4 w-4" aria-hidden="true" /> + )} + </button> + </div> + + <div className="mt-4 grid grid-cols-[1fr_auto_1fr] items-stretch gap-3"> + <TeamVersusPanel + label="우리 팀" + name={ourTeamName} + captain={ourCaptainName} + tone="primary" + /> + + <div className="flex items-center justify-center"> + <span className="rounded-full bg-base-content/5 px-2 py-1 text-[10px] font-black uppercase tracking-wider text-base-content/35"> + VS + </span> + </div> + + <TeamVersusPanel + align="right" + label="상대 팀" + name={opponentTeamName} + captain={opponentCaptainName} /> </div> - <button - onClick={() => onBid(activeTeam.teamIndex, bidAmount)} - disabled={ - isActiveTeamFull || - bidAmount > activeTeam.points || - bidAmount <= state.currentBid - } - className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${ - `${teamIndexColorClasses(activeTeam.teamIndex).border} ${teamIndexColorClasses(activeTeam.teamIndex).bg} ${teamIndexColorClasses(activeTeam.teamIndex).text} hover:bg-base-content/5` - }`} - > - {isActiveTeamFull - ? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})` - : `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(bidAmount)}P)`} - </button> - </div> + + <div className="mt-4 rounded-lg border border-primary/20 bg-primary/[0.045] p-3 sm:p-4"> + <div className="mb-2 flex items-center justify-between gap-3"> + <div> + <div className="text-[11px] font-black uppercase tracking-wider text-base-content/55"> + 토너먼트 코드 + </div> + <div className="mt-0.5 text-[10px] font-medium text-base-content/40"> + 클라이언트에 붙여넣어 게임에 입장하세요. + </div> + </div> + + {slot.code && ( + <button + type="button" + className={cn( + "btn btn-xs min-h-0 gap-1.5 rounded-md px-2.5 text-[11px] font-black", + copied ? "btn-success" : "btn-primary", + )} + onClick={handleCopy} + > + {copied ? ( + <ClipboardCheck className="h-3.5 w-3.5" aria-hidden="true" /> + ) : ( + <Copy className="h-3.5 w-3.5" aria-hidden="true" /> + )} + {copied ? "복사됨" : "복사"} + </button> + )} + </div> + + {slot.code ? ( + <code className="block min-w-0 break-all rounded-md bg-base-100/70 px-3 py-2 font-mono text-[12px] font-black leading-relaxed text-primary"> + {slot.code} + </code> + ) : ( + <div className="rounded-md border border-dashed border-base-content/15 bg-base-100/40 px-3 py-2 text-[12px] font-semibold text-base-content/45"> + 발급 대기 + </div> + )} + </div> + + {expanded && ( + <div className="mt-4 overflow-hidden rounded-lg border border-base-content/10 bg-base-100"> + <MemberListHeader + title="상대팀 멤버" + subtitle="라인과 랭크를 확인하고 밴픽을 준비하세요." + trailing={opponentTeamName} + /> + + {opponentMembers.length > 0 ? ( + <div> + {opponentMembers.map((member) => ( + <TeamMemberScoutLine + key={member.userId} + isCaptain={opponentTeam?.captainUserId === member.userId} + member={member} + participant={participantByUserId.get(member.userId)} + /> + ))} + </div> + ) : ( + <div className="px-3 py-8 text-center text-xs font-medium text-base-content/40"> + 상대팀 멤버 정보가 아직 없습니다. + </div> + )} + </div> + )} + + {finished && game?.riotMatchId && ( + <div className="mt-3 truncate font-mono text-[10px] text-base-content/30"> + {game.riotMatchId} + </div> + )} + </li> ); } -function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { - const endRef = useRef<HTMLDivElement>(null); - - useEffect(() => { - endRef.current?.scrollIntoView({ behavior: 'smooth' }); - }, [bids.length]); - - if (bids.length === 0) return null; +function TeamGameCardsSection({ + defaultExpandedGameNumber, + emptyMessage, + gameByNumber, + isPreTeamBuilt, + match, + participantByUserId, + parsedTeamIndex, + teamByIndex, + slots, + title, +}: { + defaultExpandedGameNumber?: number | null; + emptyMessage: string; + gameByNumber: Map<number, ApiMatchGameResult>; + isPreTeamBuilt?: boolean; + match: ApiMatch; + participantByUserId: Map<string, ApiMatchParticipant>; + parsedTeamIndex: number; + teamByIndex: Map<number, ApiMatch["teams"][number]>; + slots: TournamentCodeSlotView[]; + title: string; +}) { + const formatted = formatKoreanDate(match.scheduledAt); + const [expandedGameNumber, setExpandedGameNumber] = useState<number | null>( + defaultExpandedGameNumber ?? null, + ); + const nextGameNumber = defaultExpandedGameNumber ?? null; return ( - <div className="border border-base-content/10 bg-base-100 overflow-hidden"> - <div className="px-3 py-1.5 border-b border-base-content/8 bg-base-200/40"> - <span className="text-[10px] font-bold uppercase tracking-wider text-base-content/30"> - 입찰 기록 - </span> - </div> - <div className="max-h-28 overflow-y-auto p-2 space-y-0.5"> - {bids.map((bid, index) => ( - <div key={`${bid.teamIndex}-${bid.timestamp}-${index}`} className="flex items-center gap-2 text-[11px]"> - <span - className={`font-bold uppercase ${teamIndexColorClasses(bid.teamIndex).text}`} - > - {teamIndexLabel(bid.teamIndex)} - </span> - <span className="text-base-content/30">→</span> - <span className="text-amber-400 tabular-nums font-semibold"> - {formatPoints(bid.amount)}P - </span> + <section className="mb-5 overflow-hidden rounded-xl border border-base-content/10 bg-base-100 shadow-sm"> + <div className="flex flex-col gap-3 border-b border-base-content/10 bg-base-200/35 px-4 py-4 sm:flex-row sm:items-start sm:justify-between"> + <div> + <h2 className="text-[11px] font-black uppercase tracking-wider text-base-content/45"> + {title} + </h2> + <p className="mt-1 text-xs font-medium text-base-content/45"> + 팀별 경기 진행 상황과 입장 정보를 확인합니다. + </p> + </div> + + <div className="sm:text-right"> + <div className="text-sm font-black text-base-content"> + {formatted.date} {formatted.time} </div> - ))} - <div ref={endRef} /> + <div className="mt-1 inline-flex rounded-full border border-base-content/10 bg-base-100 px-2 py-0.5 text-[11px] font-bold text-base-content/55"> + {GAME_MODE_LABEL[match.gameMode]} + </div> + </div> </div> - </div> + + <div className="p-4"> + {isPreTeamBuilt ? ( + <div className="rounded-lg border border-dashed border-base-content/15 bg-base-200/20 px-4 py-10 text-center text-xs font-medium text-base-content/45"> + 팀 빌딩이 끝나면 일정이 표시됩니다. + </div> + ) : slots.length === 0 ? ( + <div className="rounded-lg border border-dashed border-base-content/15 bg-base-200/20 px-4 py-10 text-center text-xs font-medium text-base-content/45"> + {emptyMessage} + </div> + ) : ( + <ul className="space-y-3"> + {slots.map((slot) => ( + <UpcomingGameCard + key={slot.gameNumber} + expanded={expandedGameNumber === slot.gameNumber} + game={gameByNumber.get(slot.gameNumber)} + isNext={slot.gameNumber === nextGameNumber} + onToggle={() => + setExpandedGameNumber((current) => + current === slot.gameNumber ? null : slot.gameNumber, + ) + } + participantByUserId={participantByUserId} + parsedTeamIndex={parsedTeamIndex} + slot={slot} + teamByIndex={teamByIndex} + /> + ))} + </ul> + )} + </div> + </section> ); } -export default function AuctionPage() { - const { id } = useParams(); - const meQuery = useMe(); - const currentUser = - meQuery.data?.memberships.find( - (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, - )?.user ?? null; +function buildFinishedSlot( + game: ApiMatchGameResult, + slotByGameNumber: Map<number, TournamentCodeSlotView>, +): TournamentCodeSlotView { + const slot = slotByGameNumber.get(game.gameNumber); + + return { + gameNumber: game.gameNumber, + teamAIndex: game.blueTeamIndex, + teamBIndex: game.redTeamIndex, + code: slot?.code ?? null, + expiresAt: slot?.expiresAt ?? null, + state: slot?.state ?? "used", + riotMatchId: slot?.riotMatchId ?? game.riotMatchId, + }; +} + +export default function MatchTeamProgressPage() { + const { id, teamIndex } = useParams(); + const parsedTeamIndex = Number(teamIndex); const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); - const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, { - refetchInterval: 5000, - }); - const socket = useAuctionSocket(id); - const captainTeamIndex = useDevCaptainTeamIndex(); - const [now, setNow] = useState(() => Date.now()); - const [assignedPosition, setAssignedPosition] = useState<Position>('MID'); - - useEffect(() => { - const timer = window.setInterval(() => setNow(Date.now()), 1000); - return () => window.clearInterval(timer); - }, []); - - const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); - const auctionState = - liveAuction && matchQuery.data - ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) - : null; - const availableTeamIndexes = useMemo(() => { - const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); - return [...indexes].sort((left, right) => left - right); - }, [auctionState?.teams]); - const captainRole: CaptainRole | null = - captainTeamIndex === null - ? null - : { - teamIndex: captainTeamIndex, - }; - - useEffect(() => { - if (auctionState?.currentPlayer) { - setAssignedPosition(auctionState.currentPlayer.mainPosition); - } - }, [auctionState?.currentPlayer?.id]); - - useEffect(() => { - if (availableTeamIndexes.length === 0) return; - if (captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex)) { - setDevCaptainTeamIndex(availableTeamIndexes[0]); - } - }, [availableTeamIndexes, captainTeamIndex]); 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 className="mx-auto max-w-5xl px-4 py-20 text-center text-sm font-medium text-amber-600"> + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. </main> ); } - if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) { + 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 className="mx-auto max-w-5xl px-4 py-20 text-center text-sm font-medium text-base-content/45"> + 팀 진행 정보를 불러오는 중... </main> ); } - if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) { + if ( + !Number.isInteger(parsedTeamIndex) || + parsedTeamIndex < 1 || + !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={`/match/${id}`} className="btn btn-primary btn-sm mt-4 px-5 text-xs"> - 내전 상세로 돌아가기 + <main className="mx-auto max-w-5xl px-4 py-20 text-center"> + <h1 className="text-lg font-black">팀 정보를 찾을 수 없습니다</h1> + <Link + to={`/match/${id}`} + className="btn btn-primary btn-sm mt-4 px-5 text-xs" + > + 내전 상세로 </Link> </main> ); } - if (!auctionState || !matchQuery.data) { + const match = matchQuery.data; + const team = match.teams.find((item) => item.teamIndex === parsedTeamIndex); + + const participantByUserId = new Map( + match.participants.map((participant) => [participant.userId, participant]), + ); + + const slotByGameNumber = new Map( + (match.tournamentCodes ?? []).map((slot) => [slot.gameNumber, slot]), + ); + + const codes = (match.tournamentCodes ?? []).filter( + (slot) => + slot.teamAIndex === parsedTeamIndex || + slot.teamBIndex === parsedTeamIndex, + ); + + const upcomingSlots = [...codes].sort( + (left, right) => left.gameNumber - right.gameNumber, + ); + + const teamByIndex = new Map( + match.teams.map((item) => [item.teamIndex, item]), + ); + + const gameByNumber = new Map( + (match.result?.games ?? []).map((game) => [game.gameNumber, game]), + ); + + const isPreTeamBuilt = + match.status === "recruiting" || (match.teams ?? []).length === 0; + + const teamGames = (match.result?.games ?? []).filter( + (game) => + game.blueTeamIndex === parsedTeamIndex || + game.redTeamIndex === parsedTeamIndex, + ); + + const finishedSlots = teamGames + .filter((game) => Boolean(game.winnerTeamIndex)) + .map((game) => buildFinishedSlot(game, slotByGameNumber)) + .sort((left, right) => left.gameNumber - right.gameNumber); + + const activeSlots = upcomingSlots.filter( + (slot) => !gameByNumber.get(slot.gameNumber)?.winnerTeamIndex, + ); + + if (!team) { return ( - <main className="max-w-5xl mx-auto px-4 py-20 text-center"> - <span className="text-sm text-red-500"> - 경매 상태를 불러오지 못했습니다. - </span> + <main className="mx-auto max-w-5xl px-4 py-20 text-center"> + <h1 className="text-lg font-black">아직 팀이 생성되지 않았습니다</h1> + <p className="mt-2 text-sm font-medium text-base-content/45"> + 경매가 완료되면 팀별 진행 페이지를 사용할 수 있습니다. + </p> + <Link + to={`/match/${id}`} + className="btn btn-primary btn-sm mt-4 px-5 text-xs" + > + 내전 상세로 + </Link> </main> ); } - const canManageAuction = - import.meta.env.DEV || - currentUser?.role === 'owner' || - currentUser?.role === 'admin'; - const phaseLabel: Record<AuctionStateView['phase'], string> = { - waiting: '경매 준비 중...', - presenting: '다음 선수 등장', - bidding: '입찰 진행 중', - sold: '낙찰!', - complete: '경매 완료', - }; - const errorMessage = - socket.error ?? - (auctionQuery.error instanceof Error ? auctionQuery.error.message : null); + const captainIsInMembers = team.members.some( + (member) => member.userId === team.captainUserId, + ); return ( - <main className="max-w-5xl mx-auto px-4 sm:px-6 py-6"> + <main className="mx-auto max-w-5xl px-4 py-6 sm:px-6"> <Link to={`/match/${id}`} - className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-4" + className="mb-5 inline-flex text-xs font-semibold text-base-content/45 transition-colors hover:text-base-content" > - <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> - {errorMessage && ( - <div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500"> - {errorMessage} - </div> - )} - - <div className="mb-5 flex items-start justify-between flex-wrap gap-3"> - <div> - <h1 className="text-xl font-bold text-base-content leading-tight"> - 경매 팀빌딩 - </h1> - <p className="text-[11px] text-base-content/30 mt-0.5"> - {Math.min(auctionState.currentPlayerIndex + 1, Math.max(auctionState.totalPlayers, 1))} /{' '} - {auctionState.totalPlayers} 선수 - </p> - </div> - <div className="flex flex-col items-end gap-2"> - <div className="flex items-center gap-2"> - <span - className={`inline-flex items-center text-[11px] font-semibold px-2 py-1 border ${ - auctionState.phase === 'bidding' - ? 'border-green-500/20 bg-green-500/10 text-green-400' - : auctionState.phase === 'sold' - ? 'border-amber-500/20 bg-amber-500/10 text-amber-400' - : 'border-base-content/10 bg-base-content/5 text-base-content/40' - }`} - > - {phaseLabel[auctionState.phase]} - </span> - {auctionState.phase === 'bidding' && ( - <span - className={`text-lg font-black tabular-nums ${auctionState.timer <= 5 ? 'text-red-500' : 'text-base-content'}`} - > - {auctionState.timer}s - </span> - )} - </div> - <div className="flex items-center gap-2 text-xs text-base-content/40"> - <span>소켓: {socket.connectionStatus}</span> - {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} - <select - value={captainTeamIndex ?? 'spectator'} - onChange={(event) => - setDevCaptainTeamIndex( - event.target.value === 'spectator' - ? null - : Number(event.target.value), - ) - } - className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" - > - <option value="spectator">관전자</option> - {availableTeamIndexes.map((teamIndex) => ( - <option key={teamIndex} value={teamIndex}> - {teamIndexLabel(teamIndex)} 팀장 - </option> - ))} - </select> - </div> - </div> - </div> - - {auctionState.phase === 'bidding' && ( - <TimerBar timer={auctionState.timer} maxTimer={auctionState.maxTimer} /> - )} - - <div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(340px,440px)] gap-4 mt-4"> - <div className="grid sm:grid-cols-2 gap-4 content-start"> - {auctionState.teams.map((team) => ( - <TeamPanel - key={team.teamIndex} - team={team} - isActive={isCurrentBidder(auctionState.currentBidder, team)} - isLeft={team.teamIndex % 2 === 1} - /> - ))} - </div> - - <div className="flex-1 min-w-0 space-y-4"> - {auctionState.phase === 'complete' ? ( - <div className="border border-base-content/10 bg-base-100 p-8 text-center"> - <div className="text-lg font-bold text-base-content mb-2"> - 경매 완료 - </div> - <div className="text-xs text-base-content/40"> - 모든 선수가 팀에 배정되었습니다. - </div> - <Link - to={`/match/${id}`} - className="btn btn-primary btn-sm mt-4 px-6 text-[11px]" - > - 결과 확인 - </Link> + <div className="mb-6 rounded-xl border border-base-content/10 bg-base-100 p-5 shadow-sm"> + <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between"> + <div className="min-w-0"> + <div className="text-[11px] font-black uppercase tracking-wider text-base-content/40"> + 팀 진행 페이지 </div> - ) : ( - <> - <PlayerSpotlight state={auctionState} /> + <h1 className="mt-1 truncate text-2xl font-black text-base-content"> + {teamIndexLabel(team.teamIndex, team.name)} + </h1> + <p className="mt-1 text-sm font-medium text-base-content/50"> + 다가오는 경기 일정, 토너먼트 코드, 상대팀 정보를 한곳에서 + 확인합니다. + </p> + </div> - {auctionState.phase === 'sold' && auctionState.currentBidder && ( - <div - className={`text-center py-3 border text-sm font-bold ${ - `${teamIndexColorClasses(auctionState.currentBidder.teamIndex).border} ${teamIndexColorClasses(auctionState.currentBidder.teamIndex).bg} ${teamIndexColorClasses(auctionState.currentBidder.teamIndex).text}` - }`} - > - {teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰 - {' '}— {formatPoints(auctionState.currentBid)}P - </div> - )} - - <BidControls - state={auctionState} - captainRole={captainRole} - onBid={(teamIndex, amount) => - socket.placeBid({ teamIndex, amount }) - } - /> - <BidLog bids={auctionState.bids} /> - - {canManageAuction && ( - <div className="border border-base-content/10 bg-base-100 p-4 space-y-3"> - <div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35"> - Auction Controls - </div> - {auctionState.phase === 'presenting' && ( - <button - type="button" - className="btn btn-primary btn-sm px-5 text-xs" - onClick={() => socket.openBidding()} - > - 입찰 열기 - </button> - )} - {auctionState.phase === 'bidding' && ( - <div className="flex flex-wrap items-center gap-3"> - <select - value={assignedPosition} - onChange={(event) => setAssignedPosition(event.target.value as Position)} - className="border border-base-content/10 bg-transparent px-2 py-2 text-xs" - > - <option value="TOP">탑</option> - <option value="JGL">정글</option> - <option value="MID">미드</option> - <option value="ADC">원딜</option> - <option value="SUP">서폿</option> - </select> - <button - type="button" - className="btn btn-primary btn-sm px-5 text-xs" - onClick={() => socket.markSold(assignedPosition)} - > - 낙찰 처리 - </button> - </div> - )} - {auctionState.phase === 'sold' && ( - <button - type="button" - className="btn btn-primary btn-sm px-5 text-xs" - onClick={() => socket.next()} - > - 다음 선수 - </button> - )} - </div> - )} - </> - )} + <div className="shrink-0 rounded-lg border border-primary/20 bg-primary/[0.045] px-3 py-2 sm:text-right"> + <div className="text-[11px] font-black uppercase tracking-wider text-base-content/45"> + 다음 경기 + </div> + <div className="mt-0.5 text-sm font-black text-primary"> + {activeSlots[0] + ? `${activeSlots[0].gameNumber}경기` + : "남은 경기 없음"} + </div> + </div> </div> </div> + + <TeamGameCardsSection + defaultExpandedGameNumber={activeSlots[0]?.gameNumber ?? null} + emptyMessage="남은 경기가 없습니다." + gameByNumber={gameByNumber} + isPreTeamBuilt={isPreTeamBuilt} + match={match} + participantByUserId={participantByUserId} + parsedTeamIndex={parsedTeamIndex} + teamByIndex={teamByIndex} + slots={activeSlots} + title="다가오는 경기" + /> + + <TeamGameCardsSection + defaultExpandedGameNumber={null} + emptyMessage="아직 종료된 경기가 없습니다." + gameByNumber={gameByNumber} + match={match} + participantByUserId={participantByUserId} + parsedTeamIndex={parsedTeamIndex} + teamByIndex={teamByIndex} + slots={finishedSlots} + title="종료된 경기" + /> + + <section className="overflow-hidden rounded-xl border border-base-content/10 bg-base-100 shadow-sm"> + <MemberListHeader + title="팀 구성" + subtitle="우리 팀 멤버의 포지션과 랭크 정보입니다." + trailing={teamIndexLabel(team.teamIndex, team.name)} + /> + + {!captainIsInMembers && team.captainUserId && ( + <ParticipantLine + participant={participantByUserId.get(team.captainUserId)} + isCaptain + /> + )} + + {team.members.map((member) => ( + <ParticipantLine + key={member.userId} + participant={participantByUserId.get(member.userId)} + assignedPosition={member.assignedPosition} + isCaptain={team.captainUserId === member.userId} + /> + ))} + </section> </main> ); } diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 2f79169a..40cf88c4 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -467,6 +467,238 @@ function resolveMatchTeamName(match: MatchDetailView, teamIndex: number) { return teamIndexLabel(teamIndex, team?.name); } +type RoundRobinStanding = { + teamIndex: number; + name: string; + seriesWins: number; + seriesLosses: number; + gameWins: number; + gameLosses: number; + gameDiff: number; + kills: number; + deaths: number; + assists: number; + kdaScore: number; + winRate: number; +}; + +function formatRecordRate(value: number) { + if (!Number.isFinite(value)) return '-'; + return value.toFixed(2).replace(/\.?0+$/, ''); +} + +function formatSignedNumber(value: number) { + return String(value); +} + +function formatKda(standing: RoundRobinStanding) { + if (standing.deaths === 0) { + return standing.kills + standing.assists > 0 ? 'Perfect' : '-'; + } + return formatRecordRate(standing.kdaScore); +} + +function buildRoundRobinStandings( + match: MatchDetailView, +): RoundRobinStanding[] { + const standings = new Map<number, RoundRobinStanding>(); + + const getStanding = (teamIndex: number) => { + const existing = standings.get(teamIndex); + if (existing) return existing; + + const standing: RoundRobinStanding = { + teamIndex, + name: resolveMatchTeamName(match, teamIndex), + seriesWins: 0, + seriesLosses: 0, + gameWins: 0, + gameLosses: 0, + gameDiff: 0, + kills: 0, + deaths: 0, + assists: 0, + kdaScore: 0, + winRate: 0, + }; + standings.set(teamIndex, standing); + return standing; + }; + + match.teams.forEach((team) => getStanding(team.teamIndex)); + + const seriesResults = match.result?.seriesResults ?? []; + seriesResults.forEach((series) => { + const teamA = getStanding(series.teamAIndex); + const teamB = getStanding(series.teamBIndex); + const teamAWins = series.teamAWins ?? 0; + const teamBWins = series.teamBWins ?? 0; + const winnerTeamIndex = + series.winnerTeamIndex ?? + (teamAWins === teamBWins + ? undefined + : teamAWins > teamBWins + ? series.teamAIndex + : series.teamBIndex); + + teamA.gameWins += teamAWins; + teamA.gameLosses += teamBWins; + teamB.gameWins += teamBWins; + teamB.gameLosses += teamAWins; + + if (winnerTeamIndex === series.teamAIndex) { + teamA.seriesWins += 1; + teamB.seriesLosses += 1; + } + if (winnerTeamIndex === series.teamBIndex) { + teamB.seriesWins += 1; + teamA.seriesLosses += 1; + } + }); + + match.result?.games.forEach((game) => { + game.participants.forEach((participant) => { + const standing = getStanding(participant.teamIndex); + standing.kills += participant.kills; + standing.deaths += participant.deaths; + standing.assists += participant.assists; + }); + }); + + standings.forEach((standing) => { + standing.gameDiff = standing.gameWins - standing.gameLosses; + const totalSeries = standing.seriesWins + standing.seriesLosses; + standing.winRate = totalSeries > 0 ? standing.seriesWins / totalSeries : 0; + standing.kdaScore = + standing.deaths > 0 + ? (standing.kills + standing.assists) / standing.deaths + : standing.kills + standing.assists; + }); + + return [...standings.values()].sort((left, right) => { + if (right.seriesWins !== left.seriesWins) { + return right.seriesWins - left.seriesWins; + } + if (left.seriesLosses !== right.seriesLosses) { + return left.seriesLosses - right.seriesLosses; + } + if (right.gameDiff !== left.gameDiff) { + return right.gameDiff - left.gameDiff; + } + if (right.winRate !== left.winRate) { + return right.winRate - left.winRate; + } + if (right.kdaScore !== left.kdaScore) { + return right.kdaScore - left.kdaScore; + } + if (right.kills !== left.kills) { + return right.kills - left.kills; + } + return left.teamIndex - right.teamIndex; + }); +} + +function RoundRobinStandingsTable({ match }: { match: MatchDetailView }) { + const standings = buildRoundRobinStandings(match); + + return ( + <div> + <div className="flex items-center justify-between gap-3"> + <div> + <h3 className="text-xs font-black text-base-content/65"> + 라운드로빈 순위 + </h3> + <p className="mt-0.5 text-[11px] text-base-content/35"> + {standings.length}팀 · {match.result?.games.length ?? 0}경기 완료 + </p> + </div> + {match.result?.winner && ( + <div className="text-right"> + <div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35"> + 1위 + </div> + <div className="text-sm font-black text-amber-400"> + {match.result.winner} + </div> + </div> + )} + </div> + <div className="mt-4 overflow-x-auto border border-base-content/8"> + <table className="min-w-[760px] w-full text-xs"> + <thead className="bg-base-100 text-[11px] text-base-content/45"> + <tr className="border-b border-base-content/8"> + <th className="h-9 px-3 text-left font-semibold">팀 순위</th> + <th className="h-9 px-3 text-center font-semibold bg-primary/5 text-primary"> + 승 + </th> + <th className="h-9 px-3 text-center font-semibold">패</th> + <th className="h-9 px-3 text-center font-semibold">득실차</th> + <th className="h-9 px-3 text-center font-semibold">승률</th> + <th className="h-9 px-3 text-center font-semibold">KDA</th> + <th className="h-9 px-3 text-center font-semibold">킬</th> + <th className="h-9 px-3 text-center font-semibold">데스</th> + <th className="h-9 px-3 text-center font-semibold">어시스트</th> + </tr> + </thead> + <tbody className="divide-y divide-base-content/8 bg-base-100/60"> + {standings.map((standing, index) => { + const tone = teamIndexColorClasses(standing.teamIndex); + const isWinner = + match.result?.winnerTeamIndex === standing.teamIndex; + + return ( + <tr + key={standing.teamIndex} + className={isWinner ? 'bg-amber-400/5' : undefined} + > + <td className="h-14 px-3"> + <div className="flex items-center gap-3 min-w-0"> + <span className="w-7 shrink-0 text-center text-lg font-black italic text-base-content"> + {index + 1} + </span> + <span + className={`h-6 w-1 shrink-0 ${tone.bar}`} + aria-hidden="true" + /> + <span className="min-w-0 truncate font-semibold text-base-content/85"> + {standing.name} + </span> + </div> + </td> + <td className="h-14 px-3 text-center font-black tabular-nums bg-primary/5 text-primary"> + {standing.seriesWins} + </td> + <td className="h-14 px-3 text-center tabular-nums text-base-content/70"> + {standing.seriesLosses} + </td> + <td className="h-14 px-3 text-center tabular-nums text-base-content/70"> + {formatSignedNumber(standing.gameDiff)} + </td> + <td className="h-14 px-3 text-center tabular-nums text-base-content/70"> + {formatRecordRate(standing.winRate)} + </td> + <td className="h-14 px-3 text-center tabular-nums text-base-content/70"> + {formatKda(standing)} + </td> + <td className="h-14 px-3 text-center tabular-nums text-base-content/70"> + {standing.kills} + </td> + <td className="h-14 px-3 text-center tabular-nums text-base-content/70"> + {standing.deaths} + </td> + <td className="h-14 px-3 text-center tabular-nums text-base-content/70"> + {standing.assists} + </td> + </tr> + ); + })} + </tbody> + </table> + </div> + </div> + ); +} + function MatchResultPanel({ match }: { match: MatchDetailView }) { if (!match.result) return null; @@ -484,64 +716,76 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) { ); const seriesResults = match.result.seriesResults ?? []; const primarySeries = seriesResults[0]; + const showRoundRobinStandings = + match.gameMode === 'round-robin' && match.teams.length > 2; return ( <div className="mb-6 border border-base-content/10 bg-base-content/[0.02] p-5"> - {primarySeries && ( - <div className="flex items-center justify-center gap-8"> - <div - className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? teamIndexColorClasses(primarySeries.teamAIndex).text : 'text-base-content/30'}`} - > - <div className="text-3xl font-black tabular-nums"> - {primarySeries.teamAWins} - </div> - <div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold"> - {resolveMatchTeamName(match, primarySeries.teamAIndex)} - </div> - </div> - <div className="text-base-content/20 text-xs font-bold uppercase tracking-widest"> - VS - </div> - <div - className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? teamIndexColorClasses(primarySeries.teamBIndex).text : 'text-base-content/30'}`} - > - <div className="text-3xl font-black tabular-nums"> - {primarySeries.teamBWins} - </div> - <div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold"> - {resolveMatchTeamName(match, primarySeries.teamBIndex)} - </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}/${maxGameNumber}경기`} - </div> - {seriesResults.length > 1 && ( - <div className="mt-4 grid sm:grid-cols-2 gap-2"> - {seriesResults.map((series) => ( - <div - key={`${series.teamAIndex}-${series.teamBIndex}`} - className="border border-base-content/8 bg-base-100 px-3 py-2 text-xs" - > - <div className="font-bold text-base-content/55"> - {resolveMatchTeamName(match, series.teamAIndex)} vs{' '} - {resolveMatchTeamName(match, series.teamBIndex)} + {showRoundRobinStandings ? ( + <RoundRobinStandingsTable match={match} /> + ) : ( + <> + {primarySeries && ( + <div className="flex items-center justify-center gap-8"> + <div + className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamAIndex ? teamIndexColorClasses(primarySeries.teamAIndex).text : 'text-base-content/30'}`} + > + <div className="text-3xl font-black tabular-nums"> + {primarySeries.teamAWins} + </div> + <div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold"> + {resolveMatchTeamName(match, primarySeries.teamAIndex)} + </div> </div> - <div className="mt-1 flex items-center justify-between"> - <span className={teamIndexColorClasses(series.teamAIndex).text}> - {series.teamAWins} - </span> - <span className="text-base-content/20">:</span> - <span className={teamIndexColorClasses(series.teamBIndex).text}> - {series.teamBWins} - </span> + <div className="text-base-content/20 text-xs font-bold uppercase tracking-widest"> + VS + </div> + <div + className={`text-center ${primarySeries.winnerTeamIndex === primarySeries.teamBIndex ? teamIndexColorClasses(primarySeries.teamBIndex).text : 'text-base-content/30'}`} + > + <div className="text-3xl font-black tabular-nums"> + {primarySeries.teamBWins} + </div> + <div className="text-[10px] uppercase tracking-wider mt-0.5 font-semibold"> + {resolveMatchTeamName(match, primarySeries.teamBIndex)} + </div> </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}/${maxGameNumber}경기`} + </div> + {seriesResults.length > 1 && ( + <div className="mt-4 grid sm:grid-cols-2 gap-2"> + {seriesResults.map((series) => ( + <div + key={`${series.teamAIndex}-${series.teamBIndex}`} + className="border border-base-content/8 bg-base-100 px-3 py-2 text-xs" + > + <div className="font-bold text-base-content/55"> + {resolveMatchTeamName(match, series.teamAIndex)} vs{' '} + {resolveMatchTeamName(match, series.teamBIndex)} + </div> + <div className="mt-1 flex items-center justify-between"> + <span + className={teamIndexColorClasses(series.teamAIndex).text} + > + {series.teamAWins} + </span> + <span className="text-base-content/20">:</span> + <span + className={teamIndexColorClasses(series.teamBIndex).text} + > + {series.teamBWins} + </span> + </div> + </div> + ))} + </div> + )} + </> )} <div className="mt-5 border border-base-content/8 divide-y divide-base-content/8"> {gameNumbers.map((gameNumber) => { @@ -556,7 +800,9 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) { </span> {game ? ( <div> - <span className={`font-black ${resultSideClass(game.winnerSide)}`}> + <span + className={`font-black ${resultSideClass(game.winnerSide)}`} + > {resolveMatchTeamName(match, game.winnerTeamIndex)} 승 </span> <span className="ml-1 text-base-content/35"> diff --git a/apps/web/src/pages/MatchTeamProgressPage.tsx b/apps/web/src/pages/MatchTeamProgressPage.tsx index f62b074a..fd1d176f 100644 --- a/apps/web/src/pages/MatchTeamProgressPage.tsx +++ b/apps/web/src/pages/MatchTeamProgressPage.tsx @@ -1,18 +1,189 @@ -import { Link, useParams } from 'react-router'; -import { useDdragonManifest, useMatch } from '../api/hooks'; -import type { ApiMatchParticipant, Position } from '../api/types'; -import { DEFAULT_COMMUNITY_ID } from '../config'; -import { profileIconUrl } from '../lib/ddragon'; -import { positionLabel, sideShortLabel, teamIndexLabel } from '../lib/league'; +import { useState } from "react"; +import { ChevronDown, ChevronUp } from "lucide-react"; +import { Link, useParams } from "react-router"; +import { + useDdragonManifest, + useMatch, + useUserHistoryProfile, +} from "../api/hooks"; +import { formatKoreanDate, formatTierLabel } from "../api/mappers"; +import type { + ApiMatch, + ApiMatchGameResult, + ApiMatchParticipant, + ApiTierInfo, + MatchGameMode, + Position, + TeamSide, + TournamentCodeSlotView, +} from "../api/types"; +import { DEFAULT_COMMUNITY_ID } from "../config"; +import { profileIconUrl } from "../lib/ddragon"; +import { positionLabel, sideShortLabel, teamIndexLabel } from "../lib/league"; -function formatExpiry(value: string | null) { - if (!value) return '-'; - return new Intl.DateTimeFormat('ko-KR', { - month: 'long', - day: 'numeric', - hour: '2-digit', - minute: '2-digit', - }).format(new Date(value)); +const GAME_MODE_LABEL: Record<MatchGameMode, string> = { + pair: "페어 매치", + bracket: "토너먼트", + "round-robin": "리그전", +}; + +function resultBadgeClass(won: boolean) { + return won + ? "border-blue-500/20 bg-blue-500/10 text-blue-400" + : "border-red-500/20 bg-red-500/10 text-red-400"; +} + +function captainName( + team: ApiMatch["teams"][number] | undefined, + participantByUserId: Map<string, ApiMatchParticipant>, +) { + if (!team?.captainUserId) return undefined; + return participantByUserId.get(team.captainUserId)?.gameName; +} + +function tierByQueue(tiers: ApiTierInfo[], queueType: string) { + return tiers.find((tier) => tier.queueType === queueType); +} + +function normalizeRank(rank: string | undefined) { + switch (rank) { + case "I": + return "1"; + case "II": + return "2"; + case "III": + return "3"; + case "IV": + return "4"; + default: + return rank; + } +} + +function formatRankTooltip(tier: ApiTierInfo | undefined) { + if (!tier) return "언랭크"; + const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier); + const normalizedTier = { + ...tier, + rank: normalizeRank(tier.rank) ?? tier.rank, + }; + const label = highTier + ? formatTierLabel({ ...normalizedTier, leaguePoints: 0 }) + : formatTierLabel(normalizedTier); + return `${label} - ${tier.leaguePoints}LP`; +} + +function formatRankBadge(tier: ApiTierInfo | undefined) { + if (!tier) return "U"; + const tierInitial = + tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1); + const rank = normalizeRank(tier.rank); + return rank ? `${tierInitial}${rank}` : tierInitial; +} + +function rankBadgeClass(tier: ApiTierInfo | undefined) { + switch (tier?.tier) { + case "CHALLENGER": + return "border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200"; + + case "GRANDMASTER": + return "border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200"; + + case "MASTER": + return "border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200"; + + case "DIAMOND": + return "border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200"; + + case "EMERALD": + return "border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200"; + + case "PLATINUM": + return "border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200"; + + case "GOLD": + return "border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200"; + + case "SILVER": + return "border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200"; + + case "BRONZE": + return "border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200"; + + case "IRON": + return "border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300"; + + default: + return "border-base-content/30 bg-transparent text-base-content/50"; + } +} + +function RankBadge({ tier }: { tier?: ApiTierInfo }) { + const tooltip = formatRankTooltip(tier); + + return ( + <span className="tooltip tooltip-left" data-tip={tooltip}> + <span + className={`inline-flex h-[17px] min-w-[18px] shrink-0 items-center justify-center whitespace-nowrap rounded-[3px] border px-1 text-[10px] font-black leading-none ${rankBadgeClass(tier)}`} + aria-label={tooltip} + > + {formatRankBadge(tier)} + </span> + </span> + ); +} + +function SummonerStatsSummary({ + assignedPosition, + fallbackTier, + userId, +}: { + assignedPosition?: Position; + fallbackTier?: ApiTierInfo; + userId?: string; +}) { + const profileQuery = useUserHistoryProfile(userId, DEFAULT_COMMUNITY_ID); + const tiers = profileQuery.data?.tiers ?? []; + const soloTier = + tierByQueue(tiers, "RANKED_SOLO_5x5") ?? + (fallbackTier?.queueType === "RANKED_SOLO_5x5" ? fallbackTier : undefined); + const flexTier = tierByQueue(tiers, "RANKED_FLEX_SR"); + + return ( + <div className="ml-auto flex min-w-[148px] shrink-0 flex-col items-end text-right leading-tight"> + <div className="text-[11px] font-black text-primary"> + {assignedPosition ? positionLabel[assignedPosition] : "-"} + </div> + <div className="mt-1 flex items-center justify-end gap-2 text-[10px] font-black text-base-content/35"> + <span className="inline-flex items-center gap-1"> + <span>SOLO</span> + <RankBadge tier={soloTier} /> + </span> + <span className="inline-flex items-center gap-1"> + <span>FLEX</span> + <RankBadge tier={flexTier} /> + </span> + </div> + </div> + ); +} + +function TeamMemberScoutLine({ + isCaptain, + member, + participant, +}: { + isCaptain?: boolean; + member: ApiMatch["teams"][number]["members"][number]; + participant?: ApiMatchParticipant; +}) { + return ( + <ParticipantLine + assignedPosition={member.assignedPosition} + isCaptain={isCaptain} + participant={participant} + /> + ); } function ParticipantLine({ @@ -25,11 +196,10 @@ function ParticipantLine({ isCaptain?: boolean; }) { const { data: ddragon } = useDdragonManifest(); - const name = participant?.gameName ?? '알 수 없는 참가자'; - const tag = participant?.tagLine ?? '----'; - - return ( - <div className="flex items-center gap-3 border-b border-base-content/5 last:border-b-0 px-3 py-2"> + const name = participant?.gameName ?? "알 수 없는 참가자"; + const tag = participant?.tagLine ?? "----"; + const content = ( + <> <div className="h-8 w-8 shrink-0 overflow-hidden bg-base-content/10"> <img src={profileIconUrl(ddragon, participant?.profileIconId ?? 0)} @@ -39,23 +209,339 @@ function ParticipantLine({ /> </div> <div className="min-w-0 flex-1"> - <div className="flex items-center gap-2"> + <div className="flex min-w-0 items-center gap-2"> <span className="truncate text-sm font-bold text-base-content"> {name} </span> {isCaptain && ( - <span className="border border-amber-500/20 bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-bold text-amber-500"> + <span className="shrink-0 border border-amber-500/20 bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-bold text-amber-500"> 팀장 </span> )} </div> <div className="text-[11px] text-base-content/30">#{tag}</div> </div> - <div className="text-xs font-semibold text-primary"> - {assignedPosition ? positionLabel[assignedPosition] : '-'} - </div> - </div> + <SummonerStatsSummary + assignedPosition={assignedPosition} + fallbackTier={participant?.tier} + userId={participant?.userId} + /> + </> ); + + const className = + "flex items-center gap-3 border-b border-base-content/5 px-3 py-2 last:border-b-0"; + + if (participant?.userId) { + return ( + <Link + to={`/users/${participant.userId}/history`} + className={`${className} hover:bg-base-content/[0.025]`} + > + {content} + </Link> + ); + } + + return <div className={className}>{content}</div>; +} + +function UpcomingGameCard({ + expanded, + game, + isNext, + onToggle, + participantByUserId, + parsedTeamIndex, + slot, + teamByIndex, +}: { + expanded: boolean; + game?: ApiMatchGameResult; + isNext?: boolean; + onToggle: () => void; + participantByUserId: Map<string, ApiMatchParticipant>; + parsedTeamIndex: number; + slot: TournamentCodeSlotView; + teamByIndex: Map<number, ApiMatch["teams"][number]>; +}) { + const [copied, setCopied] = useState(false); + const opponentIndex = + slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex; + const ourTeam = teamByIndex.get(parsedTeamIndex); + const opponentTeam = teamByIndex.get(opponentIndex); + const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name); + const opponentTeamName = teamIndexLabel(opponentIndex, opponentTeam?.name); + const ourCaptainName = captainName(ourTeam, participantByUserId); + const opponentCaptainName = captainName(opponentTeam, participantByUserId); + const opponentMembers = opponentTeam?.members ?? []; + const finished = Boolean(game?.winnerTeamIndex); + const won = finished && game?.winnerTeamIndex === parsedTeamIndex; + const ourSide: TeamSide = + slot.teamAIndex === parsedTeamIndex ? "blue" : "red"; + + async function handleCopy() { + if (!slot.code) return; + try { + await navigator.clipboard.writeText(slot.code); + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + } catch { + setCopied(false); + } + } + + return ( + <li + className={`w-full border bg-base-100 p-4 ${ + isNext + ? "border-primary/30 bg-primary/[0.03]" + : "border-base-content/10" + } ${finished ? "bg-base-content/[0.015]" : ""}`} + > + <div className="flex items-center justify-between gap-2"> + <div className="flex items-center gap-2"> + <span + className={`border px-2 py-1 text-[11px] font-black ${ + isNext + ? "border-primary/25 bg-primary/10 text-primary" + : "border-base-content/10 bg-base-content/5 text-base-content/55" + }`} + > + {isNext ? "다음 경기" : `${slot.gameNumber}경기`} + </span> + <span className="text-[11px] font-semibold text-base-content/35"> + {sideShortLabel(ourSide)} + </span> + </div> + {finished ? ( + <div className="flex items-center gap-2"> + <span + className={`border px-2 py-1 text-[11px] font-black ${resultBadgeClass(won)}`} + > + {won ? "승리" : "패배"} + </span> + <button + type="button" + className="inline-flex h-7 w-7 items-center justify-center text-base-content/45 hover:text-primary" + onClick={onToggle} + aria-expanded={expanded} + aria-label={expanded ? "상대팀 정보 접기" : "상대팀 정보 펼치기"} + > + {expanded ? ( + <ChevronUp className="h-4 w-4" aria-hidden="true" /> + ) : ( + <ChevronDown className="h-4 w-4" aria-hidden="true" /> + )} + </button> + </div> + ) : ( + <button + type="button" + className="inline-flex h-7 w-7 items-center justify-center text-base-content/45 hover:text-primary" + onClick={onToggle} + aria-expanded={expanded} + aria-label={expanded ? "상대팀 정보 접기" : "상대팀 정보 펼치기"} + > + {expanded ? ( + <ChevronUp className="h-4 w-4" aria-hidden="true" /> + ) : ( + <ChevronDown className="h-4 w-4" aria-hidden="true" /> + )} + </button> + )} + </div> + + <div className="mt-4 grid grid-cols-[1fr_auto_1fr] items-start gap-2"> + <div className="min-w-0"> + <div className="truncate text-sm font-black text-primary"> + {ourTeamName} + </div> + {ourCaptainName && ( + <div className="mt-1 truncate text-[11px] text-base-content/35"> + 팀장 {ourCaptainName} + </div> + )} + </div> + <div className="pt-0.5 text-[10px] font-black uppercase tracking-wider text-base-content/25"> + vs + </div> + <div className="min-w-0 text-right"> + <div className="truncate text-sm font-bold text-base-content/70"> + {opponentTeamName} + </div> + {opponentCaptainName && ( + <div className="mt-1 truncate text-[11px] text-base-content/35"> + 팀장 {opponentCaptainName} + </div> + )} + </div> + </div> + + <div className="mt-4 border border-base-content/8 bg-base-content/[0.02] px-3 py-2"> + <div className="text-[10px] font-black uppercase tracking-wider text-base-content/35"> + 토너먼트 코드 + </div> + <div className="mt-1 flex items-center gap-2"> + {slot.code ? ( + <> + <code className="min-w-0 flex-1 truncate font-mono text-[12px] font-black text-primary"> + {slot.code} + </code> + <button + type="button" + className="border border-base-content/10 px-2 py-1 text-[10px] font-bold text-base-content/45 hover:text-primary" + onClick={handleCopy} + > + {copied ? "복사됨" : "복사"} + </button> + </> + ) : ( + <span className="text-[12px] font-semibold text-base-content/30"> + 발급 대기 + </span> + )} + </div> + </div> + + {expanded && ( + <div className="mt-3 border border-base-content/8 bg-base-content/[0.015]"> + <div className="flex items-center justify-between gap-2 border-b border-base-content/8 px-3 py-2"> + <div> + <div className="text-[11px] font-black text-base-content/55"> + 상대팀 멤버 + </div> + <div className="mt-0.5 text-[10px] text-base-content/30"> + 라인 · 티어 + </div> + </div> + <div className="truncate text-right text-[11px] font-bold text-base-content/45"> + {opponentTeamName} + </div> + </div> + {opponentMembers.length > 0 ? ( + <div> + {opponentMembers.map((member) => ( + <TeamMemberScoutLine + key={member.userId} + isCaptain={opponentTeam?.captainUserId === member.userId} + member={member} + participant={participantByUserId.get(member.userId)} + /> + ))} + </div> + ) : ( + <div className="px-3 py-5 text-center text-xs text-base-content/30"> + 상대팀 멤버 정보가 아직 없습니다. + </div> + )} + </div> + )} + + {finished && game?.riotMatchId && ( + <div className="mt-2 truncate font-mono text-[10px] text-base-content/25"> + {game.riotMatchId} + </div> + )} + </li> + ); +} + +function TeamGameCardsSection({ + defaultExpandedGameNumber, + emptyMessage, + gameByNumber, + isPreTeamBuilt, + match, + participantByUserId, + parsedTeamIndex, + teamByIndex, + slots, + title, +}: { + defaultExpandedGameNumber?: number | null; + emptyMessage: string; + gameByNumber: Map<number, ApiMatchGameResult>; + isPreTeamBuilt?: boolean; + match: ApiMatch; + participantByUserId: Map<string, ApiMatchParticipant>; + parsedTeamIndex: number; + teamByIndex: Map<number, ApiMatch["teams"][number]>; + slots: TournamentCodeSlotView[]; + title: string; +}) { + const formatted = formatKoreanDate(match.scheduledAt); + const [expandedGameNumber, setExpandedGameNumber] = useState<number | null>( + defaultExpandedGameNumber ?? null, + ); + const nextGameNumber = defaultExpandedGameNumber ?? null; + + return ( + <section className="mb-4 border border-base-content/10 bg-base-100"> + <div className="flex flex-col gap-1 border-b border-base-content/10 bg-base-200/40 px-4 py-3 sm:flex-row sm:items-center sm:justify-between"> + <h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40"> + {title} + </h2> + <div className="sm:text-right"> + <div className="text-sm font-black text-base-content/70"> + {formatted.date} {formatted.time} + </div> + <div className="mt-0.5 text-[11px] font-semibold text-base-content/35"> + {GAME_MODE_LABEL[match.gameMode]} + </div> + </div> + </div> + + <div className="p-4"> + {isPreTeamBuilt ? ( + <div className="border border-dashed border-base-content/10 px-4 py-8 text-center text-xs text-base-content/35"> + 팀 빌딩이 끝나면 일정이 표시됩니다. + </div> + ) : slots.length === 0 ? ( + <div className="border border-dashed border-base-content/10 px-4 py-8 text-center text-xs text-base-content/35"> + {emptyMessage} + </div> + ) : ( + <ul className="space-y-3"> + {slots.map((slot) => ( + <UpcomingGameCard + key={slot.gameNumber} + expanded={expandedGameNumber === slot.gameNumber} + game={gameByNumber.get(slot.gameNumber)} + isNext={slot.gameNumber === nextGameNumber} + onToggle={() => + setExpandedGameNumber((current) => + current === slot.gameNumber ? null : slot.gameNumber, + ) + } + participantByUserId={participantByUserId} + parsedTeamIndex={parsedTeamIndex} + slot={slot} + teamByIndex={teamByIndex} + /> + ))} + </ul> + )} + </div> + </section> + ); +} + +function buildFinishedSlot( + game: ApiMatchGameResult, + slotByGameNumber: Map<number, TournamentCodeSlotView>, +): TournamentCodeSlotView { + const slot = slotByGameNumber.get(game.gameNumber); + + return { + gameNumber: game.gameNumber, + teamAIndex: game.blueTeamIndex, + teamBIndex: game.redTeamIndex, + code: slot?.code ?? null, + expiresAt: slot?.expiresAt ?? null, + state: slot?.state ?? "used", + riotMatchId: slot?.riotMatchId ?? game.riotMatchId, + }; } export default function MatchTeamProgressPage() { @@ -79,11 +565,18 @@ export default function MatchTeamProgressPage() { ); } - if (!Number.isInteger(parsedTeamIndex) || parsedTeamIndex < 1 || !matchQuery.data) { + if ( + !Number.isInteger(parsedTeamIndex) || + parsedTeamIndex < 1 || + !matchQuery.data + ) { return ( <main className="mx-auto max-w-5xl px-4 py-20 text-center"> <h1 className="text-lg font-bold">팀 정보를 찾을 수 없습니다</h1> - <Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-4 px-5 text-xs"> + <Link + to={`/match/${id}`} + className="btn btn-primary btn-sm mt-4 px-5 text-xs" + > 내전 상세로 </Link> </main> @@ -95,11 +588,36 @@ export default function MatchTeamProgressPage() { const participantByUserId = new Map( match.participants.map((participant) => [participant.userId, participant]), ); - const codes = (match.tournamentCodes ?? []).filter((slot) => - slot.teamAIndex === parsedTeamIndex || slot.teamBIndex === parsedTeamIndex, + const slotByGameNumber = new Map( + (match.tournamentCodes ?? []).map((slot) => [slot.gameNumber, slot]), ); - const games = (match.result?.games ?? []).filter((game) => - game.blueTeamIndex === parsedTeamIndex || game.redTeamIndex === parsedTeamIndex, + const codes = (match.tournamentCodes ?? []).filter( + (slot) => + slot.teamAIndex === parsedTeamIndex || + slot.teamBIndex === parsedTeamIndex, + ); + const upcomingSlots = [...codes].sort( + (left, right) => left.gameNumber - right.gameNumber, + ); + const teamByIndex = new Map( + match.teams.map((team) => [team.teamIndex, team]), + ); + const gameByNumber = new Map( + (match.result?.games ?? []).map((game) => [game.gameNumber, game]), + ); + const isPreTeamBuilt = + match.status === "recruiting" || (match.teams ?? []).length === 0; + const teamGames = (match.result?.games ?? []).filter( + (game) => + game.blueTeamIndex === parsedTeamIndex || + game.redTeamIndex === parsedTeamIndex, + ); + const finishedSlots = teamGames + .filter((game) => Boolean(game.winnerTeamIndex)) + .map((game) => buildFinishedSlot(game, slotByGameNumber)) + .sort((left, right) => left.gameNumber - right.gameNumber); + const activeSlots = upcomingSlots.filter( + (slot) => !gameByNumber.get(slot.gameNumber)?.winnerTeamIndex, ); if (!team) { @@ -109,7 +627,10 @@ export default function MatchTeamProgressPage() { <p className="mt-2 text-sm text-base-content/40"> 경매가 완료되면 팀별 진행 페이지를 사용할 수 있습니다. </p> - <Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-4 px-5 text-xs"> + <Link + to={`/match/${id}`} + className="btn btn-primary btn-sm mt-4 px-5 text-xs" + > 내전 상세로 </Link> </main> @@ -130,108 +651,57 @@ export default function MatchTeamProgressPage() { {teamIndexLabel(team.teamIndex, team.name)} </h1> <p className="mt-1 text-sm text-base-content/45"> - 이 팀에 연결된 토너먼트 코드와 수집된 결과만 보여줍니다. + 이 팀의 다가오는 경기 일정과 결과를 한곳에서 확인합니다. </p> </div> - <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_320px]"> - <section className="border border-base-content/10 bg-base-100"> - <div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2"> - <h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40"> - 팀 구성 - </h2> - </div> + <TeamGameCardsSection + defaultExpandedGameNumber={activeSlots[0]?.gameNumber ?? null} + emptyMessage="남은 경기가 없습니다." + gameByNumber={gameByNumber} + isPreTeamBuilt={isPreTeamBuilt} + match={match} + participantByUserId={participantByUserId} + parsedTeamIndex={parsedTeamIndex} + teamByIndex={teamByIndex} + slots={activeSlots} + title="다가오는 경기" + /> + + <TeamGameCardsSection + defaultExpandedGameNumber={null} + emptyMessage="아직 종료된 경기가 없습니다." + gameByNumber={gameByNumber} + match={match} + participantByUserId={participantByUserId} + parsedTeamIndex={parsedTeamIndex} + teamByIndex={teamByIndex} + slots={finishedSlots} + title="종료된 경기" + /> + + <section className="border border-base-content/10 bg-base-100"> + <div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2"> + <h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40"> + 팀 구성 + </h2> + </div> + <ParticipantLine + participant={ + team.captainUserId + ? participantByUserId.get(team.captainUserId) + : undefined + } + isCaptain + /> + {team.members.map((member) => ( <ParticipantLine - participant={ - team.captainUserId - ? participantByUserId.get(team.captainUserId) - : undefined - } - isCaptain + key={member.userId} + participant={participantByUserId.get(member.userId)} + assignedPosition={member.assignedPosition} /> - {team.members.map((member) => ( - <ParticipantLine - key={member.userId} - participant={participantByUserId.get(member.userId)} - assignedPosition={member.assignedPosition} - /> - ))} - </section> - - <section className="space-y-4"> - <div className="border border-base-content/10 bg-base-100"> - <div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2"> - <h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40"> - 토너먼트 코드 - </h2> - </div> - <div className="divide-y divide-base-content/5"> - {codes.length > 0 ? ( - codes.map((slot) => ( - <div key={slot.gameNumber} className="px-4 py-3 text-xs"> - <div className="flex items-center justify-between gap-2"> - <span className="font-bold text-base-content/50"> - {slot.gameNumber}경기 - </span> - <code className="font-mono font-black text-primary"> - {slot.code ?? '발급 대기'} - </code> - </div> - <div className="mt-1 text-[11px] text-base-content/30"> - 만료 {formatExpiry(slot.expiresAt)} - </div> - </div> - )) - ) : ( - <div className="px-4 py-6 text-center text-xs text-base-content/30"> - 아직 연결된 코드가 없습니다. - </div> - )} - </div> - </div> - - <div className="border border-base-content/10 bg-base-100"> - <div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2"> - <h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40"> - 결과 - </h2> - </div> - <div className="divide-y divide-base-content/5"> - {games.length > 0 ? ( - games.map((game) => { - const won = game.winnerTeamIndex === parsedTeamIndex; - const side = - game.blueTeamIndex === parsedTeamIndex ? 'blue' : 'red'; - return ( - <div key={game.gameNumber} className="px-4 py-3 text-xs"> - <div className="flex items-center justify-between gap-2"> - <span className="font-bold text-base-content/50"> - {game.gameNumber}경기 - </span> - <span - className={won ? 'font-black text-blue-400' : 'font-black text-red-400'} - > - {won ? '승리' : '패배'} - </span> - </div> - <div className="mt-1 text-[11px] text-base-content/35"> - {sideShortLabel(side)} 진영 - </div> - <div className="mt-1 truncate font-mono text-[11px] text-base-content/30"> - {game.riotMatchId} - </div> - </div> - ); - }) - ) : ( - <div className="px-4 py-6 text-center text-xs text-base-content/30"> - 아직 수집된 결과가 없습니다. - </div> - )} - </div> - </div> - </section> - </div> + ))} + </section> </main> ); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 472ebb7c..bd504db4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -147,6 +147,9 @@ importers: '@tanstack/react-query': specifier: ^5.100.1 version: 5.100.1(react@19.2.5) + lucide-react: + specifier: ^1.14.0 + version: 1.14.0(react@19.2.5) react: specifier: ^19.2.4 version: 19.2.5 @@ -3473,6 +3476,11 @@ packages: lru-cache@5.1.1: resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + lucide-react@1.14.0: + resolution: {integrity: sha512-+1mdWcfSJVUsaTIjN9zoezmUhfXo5l0vP7ekBMPo3jcS/aIkxHnXqAPsByszMZx/Y8oQBRJxJx5xg+RH3urzxA==} + peerDependencies: + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + magic-string@0.30.17: resolution: {integrity: sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==} @@ -8490,6 +8498,10 @@ snapshots: dependencies: yallist: 3.1.1 + lucide-react@1.14.0(react@19.2.5): + dependencies: + react: 19.2.5 + magic-string@0.30.17: dependencies: '@jridgewell/sourcemap-codec': 1.5.5