import { useState, type ReactNode } from "react"; import type { ApiInternalMatchDetailResponse, DdragonManifest, TeamSide } from "../api/types"; import { championDisplayName, championIconUrl, } from "../lib/ddragon"; import { teamIndexLabel } from "../lib/league"; import { LANE_LABELS } from "../lib/riot-history"; import { DEFAULT_LANE_CHECKPOINT, pairLaneParticipants, resolveCheckpointComparison, type LaneCheckpointKey, type LaneParticipantLike, type NormalizedLanePosition, } from "../lib/internal-game-matchups"; import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip"; import { Tab, TabList } from "@astryxdesign/core/TabList"; export type InternalGameDetailTab = "scoreboard" | "matchup" | "build"; type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number]; type InternalGameTeam = InternalGameDetail["teams"][number]; type InternalGameParticipant = InternalGameTeam["participants"][number]; type CheckpointParticipant = InternalGameParticipant & LaneParticipantLike; type DdragonManifestData = DdragonManifest | null | undefined; type RuneStyleEntry = DdragonManifest["runesReforged"][number]; const DETAIL_TABS: Array<{ id: InternalGameDetailTab; label: string }> = [ { id: "scoreboard", label: "스코어보드" }, { id: "matchup", label: "라인전" }, { id: "build", label: "룬 / 빌드" }, ]; const SKILL_ROWS: Array<{ slot: 1 | 2 | 3 | 4; label: string; className: string; }> = [ { slot: 1, label: "Q", className: "bg-win text-white" }, { slot: 2, label: "W", className: "bg-cyan-500 text-white" }, { slot: 3, label: "E", className: "bg-amber-500 text-black" }, { slot: 4, label: "R", className: "bg-loss text-white" }, ]; const STAT_PERK_LABELS: Record = { 5001: "체력", 5002: "방어", 5003: "마저", 5005: "공속", 5007: "가속", 5008: "적응", 5010: "이속", 5011: "체력", }; function formatDuration(seconds: number) { const minutes = Math.floor(seconds / 60); const rest = seconds % 60; return `${minutes}:${String(rest).padStart(2, "0")}`; } function formatNumber(value: number) { return new Intl.NumberFormat("ko-KR").format(value); } function formatSignedNumber(value: number) { if (value === 0) return "0"; return `${value > 0 ? "+" : "-"}${formatNumber(Math.abs(value))}`; } function sideTone(side: TeamSide) { return side === "blue" ? { border: "border-win-line", bg: "bg-win-tint", text: "text-win", bar: "bg-win", } : { border: "border-loss-line", bg: "bg-loss-tint", text: "text-loss", bar: "bg-loss", }; } function getTeamName( detail: ApiInternalMatchDetailResponse, teamIndex: number, ) { return teamIndexLabel( teamIndex, detail.match.teams.find((team) => team.teamIndex === teamIndex)?.name, ); } function participantBuildKey(participant: InternalGameParticipant) { return `${participant.side}-${participant.userId ?? participant.summonerName}-${participant.championId}`; } function findRuneStyle( manifest: DdragonManifestData, styleId: number | undefined, ) { return manifest?.runesReforged.find((style) => style.id === styleId) ?? null; } function selectedRuneIds(participant: InternalGameParticipant) { const explicit = participant.perks.selectedPerkIds ?? []; const fromStyles = participant.perks.styles?.flatMap((style) => style.perkIds) ?? []; return new Set([ ...explicit, ...fromStyles, ...(participant.perks.keystone ? [participant.perks.keystone] : []), ]); } function runeStyleSelection( participant: InternalGameParticipant, styleId: number | undefined, ) { return participant.perks.styles?.find((style) => style.styleId === styleId); } function ChampionCell({ participant, manifest, }: { participant: InternalGameParticipant; manifest: DdragonManifestData; }) { const icon = championIconUrl(manifest, participant.championId); const name = championDisplayName(manifest, participant.championId) ?? String(participant.championId); return (
{icon ? ( {name} ) : null} {participant.championLevel > 0 && ( {participant.championLevel} )}
{name} {LANE_LABELS[participant.teamPosition] ?? participant.teamPosition ?? "-"}
); } function ChampionAvatar({ participant, manifest, size = "h-9 w-9", }: { participant: InternalGameParticipant; manifest: DdragonManifestData; size?: string; }) { const icon = championIconUrl(manifest, participant.championId); const name = championDisplayName(manifest, participant.championId) ?? String(participant.championId); return ( {icon ? ( {name} ) : null} {participant.championLevel > 0 ? ( {participant.championLevel} ) : null} ); } function RuneBuildPanel({ selectedGame, detail, manifest, }: { selectedGame: InternalGameDetail; detail: ApiInternalMatchDetailResponse; manifest: DdragonManifestData; }) { const orderedTeams = [...selectedGame.teams].sort((left, right) => left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, ); const participants = orderedTeams.flatMap((team) => team.participants); const defaultKey = participants[0] ? participantBuildKey(participants[0]) : ""; const [selectedKey, setSelectedKey] = useState(defaultKey); const effectiveSelectedKey = participants.some( (participant) => participantBuildKey(participant) === selectedKey, ) ? selectedKey : defaultKey; const selectedParticipant = participants.find( (participant) => participantBuildKey(participant) === effectiveSelectedKey, ) ?? participants[0]; if (!selectedParticipant) { return (
빌드 데이터가 없습니다
); } return (
); } function BuildChampionSelector({ selectedGame, detail, manifest, selectedKey, onSelect, }: { selectedGame: InternalGameDetail; detail: ApiInternalMatchDetailResponse; manifest: DdragonManifestData; selectedKey: string; onSelect: (key: string) => void; }) { const orderedTeams = [...selectedGame.teams].sort((left, right) => left.side === right.side ? 0 : left.side === "blue" ? -1 : 1, ); return (
{orderedTeams.map((team) => { const tone = sideTone(team.side); return (
{team.side === "blue" ? "블루" : "레드"}
{getTeamName(detail, team.teamIndex)}
{team.participants.map((participant) => ( onSelect(participantBuildKey(participant))} /> ))}
); })}
); } function BuildChampionButton({ participant, manifest, selected, onClick, }: { participant: InternalGameParticipant; manifest: DdragonManifestData; selected: boolean; onClick: () => void; }) { const icon = championIconUrl(manifest, participant.championId); const championName = championDisplayName(manifest, participant.championId) ?? String(participant.championId); const tone = sideTone(participant.side); return ( ); } function RunesPanel({ participant, manifest, }: { participant: InternalGameParticipant; manifest: DdragonManifestData; }) { const selectedIds = selectedRuneIds(participant); const primaryStyleId = participant.perks.primaryStyle ?? participant.perks.styles?.[0]?.styleId; const subStyleId = participant.perks.subStyle ?? participant.perks.styles?.[1]?.styleId; const primaryStyle = findRuneStyle(manifest, primaryStyleId); const subStyle = findRuneStyle(manifest, subStyleId); return (
룬
{participant.summonerName}
); } function RuneTreeColumn({ label, isPrimary, runeStyle, selection, selectedIds, manifest, }: { label: string; isPrimary: boolean; runeStyle: RuneStyleEntry | null; selection: ReturnType; selectedIds: Set; manifest: DdragonManifestData; }) { if (!runeStyle) { return (
{label}
룬 데이터 없음
); } const selectionIds = new Set(selection?.perkIds ?? []); return (
{label}
{runeStyle.name}
{runeStyle.slots.map((slot, slotIndex) => { // 보조 룬 트리는 핵심 룬(0번 행)을 선택하지 않으므로 숨긴다. if (!isPrimary && slotIndex === 0) return null; const isKeystoneRow = isPrimary && slotIndex === 0; const cell = isKeystoneRow ? "2.5rem" : "2.25rem"; const iconSize = isKeystoneRow ? "h-10 w-10" : "h-9 w-9"; return (
{slot.runes.map((rune) => { const selected = selectedIds.has(rune.id) || selectionIds.has(rune.id); return ( ); })}
); })}
); } function RuneShardRows({ participant }: { participant: InternalGameParticipant }) { const statPerks = participant.perks.statPerks; const shards = [ { label: "공격", value: statPerks?.offense }, { label: "보조", value: statPerks?.flex }, { label: "방어", value: statPerks?.defense }, ].filter((shard) => typeof shard.value === "number" && shard.value > 0); if (shards.length === 0) return null; return (
스탯 파편 {shards.map((shard) => ( {shard.label} {STAT_PERK_LABELS[shard.value ?? 0] ?? shard.value} ))}
); } function ItemBuildPanel({ participant, manifest, }: { participant: InternalGameParticipant; manifest: DdragonManifestData; }) { const buildEvents = (participant.itemBuild ?? []).filter( (event) => event.itemId > 0 && event.type === "purchased", ); const fallbackItems = [ ...participant.items .filter((itemId) => itemId > 0) .map((itemId) => ({ itemId, trinket: false })), ...(participant.trinket > 0 ? [{ itemId: participant.trinket, trinket: true }] : []), ]; return (
아이템 빌드
{buildEvents.length > 0 ? (
{buildEvents.map((event, index) => (
{index < buildEvents.length - 1 ? ( > ) : null}
))}
) : fallbackItems.length > 0 ? (
{fallbackItems.map((item, index) => ( ))}
) : (
아이템 빌드 데이터 없음
)}
); } function ItemBuildNode({ itemId, timestamp, manifest, }: { itemId: number; timestamp: number; manifest: DdragonManifestData; }) { return (
{formatDuration(timestamp)}
); } function SkillBuildPanel({ participant, }: { participant: InternalGameParticipant; }) { const skillEvents = participant.skillBuild ?? []; const skillByLevel = new Map( skillEvents.map((event) => [event.level, event]), ); return (
스킬 빌드
Lv. {skillEvents.length || participant.championLevel || "-"}
{skillEvents.length > 0 ? (
{SKILL_ROWS.map((row) => (
{row.label}
{Array.from({ length: 18 }, (_, index) => index + 1).map( (level) => { const event = skillByLevel.get(level); const active = event?.skillSlot === row.slot; return (
{active ? level : ""}
); }, )}
))}
) : (
스킬 빌드 데이터 없음
)}
); } function MatchupMetricRow({ label, difference, blueLead, redLead, blueText, redText, }: { label: string; difference?: string; blueLead: boolean; redLead: boolean; blueText: string; redText: string; }) { return (
{blueText} {label} {difference ? ( {difference} ) : null} {redText}
); } function checkpointKda(kills: number, deaths: number, assists: number) { return deaths === 0 ? kills + assists : (kills + assists) / deaths; } function LaneParticipantIdentity({ participant, manifest, align, ambiguous, }: { participant: CheckpointParticipant | null; manifest: DdragonManifestData; align: "left" | "right"; ambiguous: boolean; }) { if (!participant) { return (
{ambiguous ? "포지션 중복" : "선수 없음"}
); } const championName = championDisplayName(manifest, participant.championId) ?? String(participant.championId); const details = (
{participant.summonerName}
{championName}
); return (
{align === "right" ? details : null} {align === "left" ? details : null}
); } function LaneMatchupCard({ position, blue, red, ambiguousBlue, ambiguousRed, checkpointKey, manifest, }: { position: NormalizedLanePosition; blue: CheckpointParticipant | null; red: CheckpointParticipant | null; ambiguousBlue: boolean; ambiguousRed: boolean; checkpointKey: LaneCheckpointKey; manifest: DdragonManifestData; }) { const laneLabel = LANE_LABELS[position] ?? position; const comparison = resolveCheckpointComparison(blue, red, checkpointKey); const metrics = comparison ? [ { key: "gold", label: "골드", difference: `GD ${formatSignedNumber(comparison.goldDiff)}`, blueValue: comparison.blue.gold, redValue: comparison.red.gold, blueText: formatNumber(comparison.blue.gold), redText: formatNumber(comparison.red.gold), }, { key: "cs", label: "CS", difference: `CSD ${formatSignedNumber(comparison.csDiff)}`, blueValue: comparison.blue.cs, redValue: comparison.red.cs, blueText: formatNumber(comparison.blue.cs), redText: formatNumber(comparison.red.cs), }, { key: "xp", label: "경험치", difference: `XPD ${formatSignedNumber(comparison.xpDiff)}`, blueValue: comparison.blue.xp, redValue: comparison.red.xp, blueText: formatNumber(comparison.blue.xp), redText: formatNumber(comparison.red.xp), }, { key: "kda", label: "K / D / A", blueValue: checkpointKda( comparison.blue.kills, comparison.blue.deaths, comparison.blue.assists, ), redValue: checkpointKda( comparison.red.kills, comparison.red.deaths, comparison.red.assists, ), blueText: `${comparison.blue.kills}/${comparison.blue.deaths}/${comparison.blue.assists}`, redText: `${comparison.red.kills}/${comparison.red.deaths}/${comparison.red.assists}`, }, ] : []; return (
{laneLabel}
{comparison ? ( <>
{metrics.map((metric) => ( metric.redValue} redLead={metric.redValue > metric.blueValue} blueText={metric.blueText} redText={metric.redText} /> ))}
실제 기준 {formatDuration(comparison.blue.timestamp)} · {formatDuration(comparison.red.timestamp)}
) : (
{ambiguousBlue || ambiguousRed ? "포지션이 중복되어 상대를 확정할 수 없습니다" : "선택한 시점의 라인전 데이터가 없습니다"}
)}
); } function LaneMatchupPanel({ selectedGame, detail, manifest, }: { selectedGame: InternalGameDetail; detail: ApiInternalMatchDetailResponse; manifest: DdragonManifestData; }) { const [checkpointKey, setCheckpointKey] = useState(DEFAULT_LANE_CHECKPOINT); const blueTeam = selectedGame.teams.find((team) => team.side === "blue"); const redTeam = selectedGame.teams.find((team) => team.side === "red"); if (!blueTeam || !redTeam) { return (
라인전 비교 데이터가 없습니다
); } const matchups = pairLaneParticipants( blueTeam.participants as CheckpointParticipant[], redTeam.participants as CheckpointParticipant[], ); const blueTeamName = getTeamName(detail, blueTeam.teamIndex); const redTeamName = getTeamName(detail, redTeam.teamIndex); return (
{blueTeamName} VS {redTeamName}
{(["at10", "at15"] as const).map((key) => ( ))}
{matchups.length > 0 ? ( matchups.map((matchup) => ( )) ) : (
비교 가능한 포지션 정보가 없습니다
)}
); } export function InternalGameDetailTabBar({ activeTab, onChange, }: { activeTab: InternalGameDetailTab; onChange: (tab: InternalGameDetailTab) => void; }) { return ( { const tab = DETAIL_TABS.find((candidate) => candidate.id === next); if (tab) onChange(tab.id); }} > {DETAIL_TABS.map((tab) => ( ))} ); } export function InternalGameAnalysisPanel({ activeTab, selectedGame, detail, manifest, scoreboard, }: { activeTab: InternalGameDetailTab; selectedGame: InternalGameDetail; detail: ApiInternalMatchDetailResponse; manifest: DdragonManifestData; scoreboard: ReactNode; }) { if (activeTab === "scoreboard") { return <>{scoreboard}; } if (activeTab === "build") { return ( ); } return ( ); }