import { useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { AlertTriangle, ChevronDown, ChevronUp } from "lucide-react"; import { Link, useLocation, useParams } from "react-router"; import { useDdragonManifest, useMatch, useReplaceTournamentCode, useUserHistoryProfile, } from "../api/hooks"; import { formatKoreanDate } from "../api/mappers"; import { RankBadge } from "../components/RankBadge"; 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"; const GAME_MODE_LABEL: Record = { pair: "페어 매치", bracket: "토너먼트", "round-robin": "리그전", "double-elimination": "더블 엘리미네이션", }; 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, ) { 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 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 (
{assignedPosition ? positionLabel[assignedPosition] : "-"}
SOLO FLEX
); } function TeamMemberScoutLine({ isCaptain, member, participant, }: { isCaptain?: boolean; member: ApiMatch["teams"][number]["members"][number]; participant?: ApiMatchParticipant; }) { return ( ); } function ParticipantLine({ participant, assignedPosition, isCaptain, }: { participant?: ApiMatchParticipant; assignedPosition?: Position; isCaptain?: boolean; }) { const { data: ddragon } = useDdragonManifest(); const location = useLocation(); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; const name = participant?.gameName ?? "알 수 없는 참가자"; const tag = participant?.tagLine ?? "----"; const content = ( <>
{name} {isCaptain && ( 팀장 )}
#{tag}
); 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 ( {content} ); } return
{content}
; } function UpcomingGameCard({ expanded, game, isNext, onToggle, onReplaceCode, participantByUserId, parsedTeamIndex, replacingCode, slot, teamByIndex, }: { expanded: boolean; game?: ApiMatchGameResult; isNext?: boolean; onToggle: () => void; onReplaceCode?: (slot: TournamentCodeSlotView) => void; participantByUserId: Map; parsedTeamIndex: number; replacingCode?: boolean; slot: TournamentCodeSlotView; teamByIndex: Map; }) { const [copied, setCopied] = useState(false); const opponentIndex = slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex; const ourTeam = teamByIndex.get(parsedTeamIndex); const opponentTeam = opponentIndex ? teamByIndex.get(opponentIndex) : undefined; const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name); const opponentTeamName = opponentIndex ? 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"; const replaceable = Boolean(slot.code && !finished && slot.state !== "used"); 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 (
  • {isNext ? "다음 경기" : `${slot.gameNumber}경기`} {sideShortLabel(ourSide)}
    {finished ? (
    {won ? "승리" : "패배"}
    ) : ( )}
    {ourTeamName}
    {ourCaptainName && (
    팀장 {ourCaptainName}
    )}
    vs
    {opponentTeamName}
    {opponentCaptainName && (
    팀장 {opponentCaptainName}
    )}
    토너먼트 코드
    {slot.code ? ( <> {slot.code} {replaceable && ( )} ) : ( 발급 대기 )}
    {expanded && (
    상대팀 멤버
    라인 · 티어
    {opponentTeamName}
    {opponentMembers.length > 0 ? (
    {opponentMembers.map((member) => ( ))}
    ) : (
    상대팀 멤버 정보가 아직 없습니다.
    )}
    )} {finished && game?.riotMatchId && (
    {game.riotMatchId}
    )}
  • ); } function TeamGameCardsSection({ defaultExpandedGameNumber, emptyMessage, gameByNumber, isPreTeamBuilt, match, participantByUserId, parsedTeamIndex, replaceError, replacingGameNumber, teamByIndex, slots, title, onReplaceCode, }: { defaultExpandedGameNumber?: number | null; emptyMessage: string; gameByNumber: Map; isPreTeamBuilt?: boolean; match: ApiMatch; participantByUserId: Map; parsedTeamIndex: number; replaceError?: string | null; replacingGameNumber?: number | null; teamByIndex: Map; slots: TournamentCodeSlotView[]; title: string; onReplaceCode?: (slot: TournamentCodeSlotView) => void; }) { const formatted = formatKoreanDate(match.scheduledAt); const [expandedGameNumber, setExpandedGameNumber] = useState( defaultExpandedGameNumber ?? null, ); const nextGameNumber = defaultExpandedGameNumber ?? null; return (

    {title}

    {formatted.date} {formatted.time}
    {GAME_MODE_LABEL[match.gameMode]}
    {replaceError && (
    {replaceError}
    )} {isPreTeamBuilt ? (
    팀 빌딩이 끝나면 일정이 표시됩니다.
    ) : slots.length === 0 ? (
    {emptyMessage}
    ) : (
      {slots.map((slot) => ( setExpandedGameNumber((current) => current === slot.gameNumber ? null : slot.gameNumber, ) } onReplaceCode={onReplaceCode} participantByUserId={participantByUserId} parsedTeamIndex={parsedTeamIndex} replacingCode={replacingGameNumber === slot.gameNumber} slot={slot} teamByIndex={teamByIndex} /> ))}
    )}
    ); } function buildFinishedSlot( game: ApiMatchGameResult, slotByGameNumber: Map, ): 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 queryClient = useQueryClient(); const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); const replaceTournamentCodeMutation = useReplaceTournamentCode(DEFAULT_COMMUNITY_ID); const [replaceCodeSlot, setReplaceCodeSlot] = useState(null); const [replaceCodeConfirmText, setReplaceCodeConfirmText] = useState(""); function handleReplaceTournamentCode(slot: TournamentCodeSlotView) { if (!slot.code) return; setReplaceCodeConfirmText(""); setReplaceCodeSlot(slot); } function closeReplaceTournamentCodeDialog() { setReplaceCodeSlot(null); setReplaceCodeConfirmText(""); } function handleConfirmReplaceTournamentCode() { if (!id || !replaceCodeSlot || replaceCodeConfirmText.trim() !== "예") { return; } replaceTournamentCodeMutation.mutate( { matchId: id, gameNumber: replaceCodeSlot.gameNumber }, { onSuccess: async () => { await queryClient.invalidateQueries({ queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], }); closeReplaceTournamentCodeDialog(); }, }, ); } if (!DEFAULT_COMMUNITY_ID) { return (
    `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
    ); } if (matchQuery.isLoading) { return (
    팀 진행 정보를 불러오는 중...
    ); } if ( !Number.isInteger(parsedTeamIndex) || parsedTeamIndex < 1 || !matchQuery.data ) { return (

    팀 정보를 찾을 수 없습니다

    내전 상세로
    ); } 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((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) { return (

    아직 팀이 생성되지 않았습니다

    경매가 완료되면 팀별 진행 페이지를 사용할 수 있습니다.

    내전 상세로
    ); } return (
    ← 내전 상세로

    {teamIndexLabel(team.teamIndex, team.name)}

    이 팀의 다가오는 경기 일정과 결과를 한곳에서 확인합니다.

    팀 구성

    {team.members.map((member) => ( ))}
    {replaceCodeSlot && (

    토너먼트 코드 교체

    정상적인 경기 진행이 불가한 경우 우리팀과 상대팀에 상황을 알린 뒤 {replaceCodeSlot.gameNumber}경기 코드를 교체하세요.

    setReplaceCodeConfirmText(event.target.value)} onKeyDown={(event) => { if (event.key === "Escape") { closeReplaceTournamentCodeDialog(); } if ( event.key === "Enter" && replaceCodeConfirmText.trim() === "예" && !replaceTournamentCodeMutation.isPending ) { handleConfirmReplaceTournamentCode(); } }} className="mt-2 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm text-base-content outline-none transition-colors focus:border-amber-400/60" placeholder="예" />
    )}
    ); }