import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react'; import { Link, useLocation, useSearchParams } from 'react-router'; import { ArrowDown, ArrowDownUp, ArrowLeft, ArrowRight, CalendarDays, Check, ChevronRight, Clock3, Copy, Filter, Info, List, LoaderCircle, Moon, Search, ShieldAlert, Sun, Trophy, Users, X } from 'lucide-react'; import { CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'; import { Btn, Chip } from '../../ui'; import { setTheme, useTheme } from '../../config'; import { champions, championImage, events, games, lanes, laneNames, ORIGINAL_PATH, playerById, PREVIEW_PATH, seasons, type Event, type Game, type Lane, type Participant, type Series } from './data'; import { aggregateRows, filterEvents, formatDate, formatDuration, playerGames, seasonMetrics, sortLabels, teamName, type PlayerRow, type SortKey } from './model'; type Changes = Record; const visits = new Map(); function visitKey(pathname: string, search: string) { const query = new URLSearchParams(search); query.delete('returnTo'); return `${pathname}?${query.toString()}`; } function rememberVisit() { const focus = document.activeElement?.getAttribute('data-return-id') ?? null; const key = visitKey(location.pathname, location.search); const value = { y: window.scrollY, focus }; visits.set(key, value); try { sessionStorage.setItem(`stats-preview:${key}`, JSON.stringify(value)); } catch { /* Memory restoration still works. */ } } function PreviewLink(props: ComponentProps) { return { rememberVisit(); props.onClick?.(event); }} />; } function Champion({ id, size = 'normal' }: { id: number; size?: 'small' | 'normal' | 'large' }) { const champion = champions[id]; return {champion.name}; } function Feedback({ type, title, children, action }: { type: 'empty' | 'error' | 'loading'; title: string; children?: ReactNode; action?: ReactNode }) { const Icon = type === 'loading' ? LoaderCircle : type === 'error' ? ShieldAlert : Search; return
; } export default function Preview() { const [params, setParams] = useSearchParams(); const location = useLocation(); const theme = useTheme(); const [copied, setCopied] = useState(false); const [copyError, setCopyError] = useState(false); const [retrying, setRetrying] = useState(false); const timer = useRef | null>(null); const view = params.get('view') === 'players' ? 'players' : 'matches'; const season = seasons.some(s => s.id === params.get('season')) || params.get('season') === 'all' ? params.get('season')! : '2026-2'; const lane = lanes.includes(params.get('lane') as Lane) ? params.get('lane') as Lane : 'all'; const sort = Object.hasOwn(sortLabels, params.get('sort') ?? '') ? params.get('sort') as SortKey : 'games'; const direction = params.get('dir') === 'asc' ? 'asc' : 'desc'; const minimum = ['0', '5', '10', '20'].includes(params.get('min') ?? '') ? Number(params.get('min')) : 5; const detail = params.get('detail'); const state = params.get('state'); const matchQuery = params.get('matchQ') ?? ''; const playerQuery = params.get('playerQ') ?? ''; const format = ['pair', 'tournament'].includes(params.get('format') ?? '') ? params.get('format')! : 'all'; const from = params.get('from') ?? '', to = params.get('to') ?? ''; const selectedPlayer = params.get('player') ?? ''; const selected = playerById.get(selectedPlayer); const shown = Math.max(4, Math.min(100, Number(params.get('shown')) || 4)); const rawReturn = params.get('returnTo'); const listParams = new URLSearchParams(params); ['detail', 'event', 'game', 'profile', 'returnTo', 'state'].forEach(key => listParams.delete(key)); const listHref = `${PREVIEW_PATH}?${listParams.toString()}`; const backHref = rawReturn?.startsWith(`${PREVIEW_PATH}?`) ? rawReturn : listHref; const current = visitKey(location.pathname, location.search); const metrics = seasonMetrics(season); const seasonLabel = season === 'all' ? '전체 시즌' : seasons.find(s => s.id === season)!.name; const period = season === 'all' ? '2026.05.01 — 06.30' : season === '2026-2' ? '2026.06.01 — 06.30' : '2026.05.01 — 05.31'; const invalidDates = Boolean(from && to && from > to); const filteredEvents = invalidDates ? [] : filterEvents({ season, query: matchQuery, format, from, to, player: selectedPlayer }); const visibleEvents = filteredEvents.slice(0, shown); const rankedRows = aggregateRows(season, lane, minimum, sort, direction); const query = playerQuery.trim().toLocaleLowerCase('ko-KR'); const visibleRows = rankedRows.filter(row => row.name.toLocaleLowerCase('ko-KR').includes(query) && (params.get('qualified') !== '1' || row.games >= minimum)); const event = events.find(e => e.id === params.get('event')); const game = games.find(g => g.id === params.get('game')); const profile = playerById.get(params.get('profile') ?? ''); function update(changes: Changes, replace = false) { const next = new URLSearchParams(params); for (const [key, value] of Object.entries(changes)) { if (value === null || value === '') next.delete(key); else next.set(key, value); } setParams(next, { replace, preventScrollReset: true }); } function target(changes: Changes, asDetail = true) { const next = new URLSearchParams(params); ['detail', 'event', 'game', 'profile', 'state'].forEach(k => next.delete(k)); Object.entries(changes).forEach(([key, value]) => value === null ? next.delete(key) : next.set(key, value)); if (asDetail) next.set('returnTo', current); else next.delete('returnTo'); return `${PREVIEW_PATH}?${next.toString()}`; } const eventHref = (id: string) => target({ detail: 'event', event: id }); const gameHref = (id: string) => target({ detail: 'game', game: id }); const profileHref = (id: string) => target({ detail: 'player', profile: id }); const participationHref = (id: string) => target({ view: 'matches', player: id, shown: null }, false); function resetFilters() { update(view === 'matches' ? { matchQ: null, format: null, from: null, to: null, player: null, shown: null } : { playerQ: null, lane: null, min: null, qualified: null, sort: null, dir: null }); } function retry() { setRetrying(true); timer.current = setTimeout(() => { setRetrying(false); update({ state: null }, true); }, 700); } async function copyLink() { try { await navigator.clipboard.writeText(window.location.href); setCopied(true); setCopyError(false); } catch { setCopyError(true); } } useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []); useEffect(() => { if (!copied && !copyError) return; const timeout = setTimeout(() => { setCopied(false); setCopyError(false); }, 3500); return () => clearTimeout(timeout); }, [copied, copyError]); useLayoutEffect(() => { const key = visitKey(location.pathname, location.search); let saved = visits.get(key); if (!saved) try { saved = JSON.parse(sessionStorage.getItem(`stats-preview:${key}`) ?? 'null'); } catch { /* Ignore obsolete preview state. */ } const frame = requestAnimationFrame(() => { if (saved) { window.scrollTo({ top: saved.y, behavior: 'instant' }); if (saved.focus) document.querySelector(`[data-return-id="${CSS.escape(saved.focus)}"]`)?.focus({ preventScroll: true }); } else if (detail) { window.scrollTo({ top: 0, behavior: 'instant' }); document.getElementById('stats-detail-title')?.focus({ preventScroll: true }); } }); return () => cancelAnimationFrame(frame); }, [location.key, location.pathname, location.search, detail]); const activeFilters: Array<{ label: string; clear: Changes }> = view === 'matches' ? [ ...(matchQuery ? [{ label: `검색: ${matchQuery}`, clear: { matchQ: null } }] : []), ...(format !== 'all' ? [{ label: format === 'pair' ? '두 팀 내전' : '대회', clear: { format: null } }] : []), ...(from || to ? [{ label: `${from || '처음'} ~ ${to || '마지막'}`, clear: { from: null, to: null } }] : []), ...(selectedPlayer ? [{ label: `${selected?.name ?? '선수'} 참가 내전`, clear: { player: null } }] : []), ] : [ ...(playerQuery ? [{ label: `검색: ${playerQuery}`, clear: { playerQ: null } }] : []), ...(lane !== 'all' ? [{ label: `${laneNames[lane]}에서 플레이한 기록`, clear: { lane: null } }] : []), ...(params.get('qualified') === '1' ? [{ label: `${minimum}판 이상만`, clear: { qualified: null } }] : []), ]; const secondaryControls =
; return
전적 본문으로 건너뛰기
인터랙티브 시안 / 예시 데이터현재 페이지와 비교
LOLYMPUSTOURNAMENT
{!detail ? <>

LOLYMPUS COMMUNITY

내전 전적

함께한 경기와 선수들의 기록을 만나보세요.

{secondaryControls}
target({ detail: 'player', profile: id, lane: null })} gameHref={gameHref} />
{(['matches', 'players'] as const).map((v, index) => )} {seasonLabel} · {period}
{view === 'matches' ? <>
{[['all', '전체'], ['pair', '두 팀 내전'], ['tournament', '대회']].map(([value, label]) => update({ format: value === 'all' ? null : value, shown: null })}>{label})}
: <>}
{activeFilters.length > 0 &&
적용 조건{activeFilters.map(filter => )}
} {view === 'matches' && invalidDates &&

종료일을 시작일과 같거나 이후 날짜로 선택해 주세요.

} {(state === 'error' || state === 'loading' || retrying) ? 다시 시도 update({ state: null })}>목록으로 돌아가기}>선택한 시즌과 검색 조건은 유지됩니다. : view === 'matches' ? <>

경기 기록 {filteredEvents.length}회

{visibleEvents.length}개 표시{filteredEvents.length > shown && ` / 검색 결과 ${filteredEvents.length}개`}

{visibleEvents.length ?
{visibleEvents.map(e => )}{filteredEvents.length > shown && }
: 검색 조건 초기화}>날짜나 검색어를 바꾸면 다른 내전을 찾을 수 있습니다.} : <>

{sortLabels[sort]} 순 {visibleRows.length}명

{lane === 'all' ? '전체 포지션' : `${laneNames[lane]} 플레이만 집계`} · {minimum > 0 ? `${minimum}판 미만은 기준 미달로 뒤에 표시` : '판수 제한 없음'}

{visibleRows.length ? update({ sort: key, dir: sort === key && direction === 'desc' ? 'asc' : 'desc' })} profileHref={profileHref} participationHref={participationHref} /> : 검색 조건 초기화}>검색어, 포지션 또는 최소 판수를 바꿔 보세요.} }
: <> {rawReturn?.includes('detail=') ? '이전 기록으로' : '내전 전적으로 돌아가기'}

{seasonLabel} · {period}

{detail === 'event' ? event?.name ?? '내전 기록' : detail === 'game' ? '세트 상세 분석' : profile?.name ?? '선수 전적'}

{detail === 'player' ? '선택한 시즌의 개인 기록과 참가 경기를 확인합니다.' : '공식 경기 결과와 수집된 분석 기록을 함께 확인합니다.'}

{secondaryControls}
{(state === 'error' || state === 'loading' || retrying) ? 다시 시도이전 기록으로}>경기 제목과 선택한 조건을 유지했습니다. 다시 시도하거나 이전 화면으로 돌아갈 수 있습니다. : detail === 'event' && event ? <>
{event.series.map(series => )}
: detail === 'game' && game ? : detail === 'player' && profile ? update({ lane: value })} gameHref={gameHref} participationHref={participationHref} /> : 내전 전적으로 돌아가기}>기록의 링크를 확인하거나 목록에서 다시 선택해 주세요.} }
{copyError ? '링크를 복사하지 못했습니다. 주소 표시줄의 주소를 복사해 주세요.' : copied ? '현재 검색 조건이 포함된 링크를 복사했습니다.' : ''}
LOLYMPUS · 함께하는 모든 게임의 기록예시 데이터로 구성한 디자인 시안
; } function SeasonSummary({ metrics: m, label, period, profileHref, gameHref }: { metrics: ReturnType; label: string; period: string; profileHref: (id: string) => string; gameHref: (id: string) => string }) { const records = [ { title: '평균 KDA', value: m.topKda?.kda.toFixed(2), suffix: '', name: m.topKda?.name, href: m.topKda ? profileHref(m.topKda.id) : '', scope: '시즌 최고 · 최소 5판' }, { title: '누적 킬', value: m.kills?.kills.toLocaleString(), suffix: '킬', name: m.kills?.player.name, href: m.kills ? profileHref(m.kills.player.id) : '', scope: '시즌 누적' }, { title: '분당 골드', value: m.bestGpm?.gpm.toFixed(1), suffix: '', name: m.bestGpm ? playerById.get(m.bestGpm.p.playerId)?.name : '', href: m.bestGpm ? gameHref(m.bestGpm.game.id) : '', scope: '단일 경기 최고' }, { title: '평균 킬 관여', value: m.topKp?.kp.toFixed(1), suffix: '%', name: m.topKp?.name, href: m.topKp ? profileHref(m.topKp.id) : '', scope: '시즌 최고 · 최소 5판' }, { title: '평균 분당 CS', value: m.topCs?.cspm.toFixed(1), suffix: '', name: m.topCs?.name, href: m.topCs ? profileHref(m.topCs.id) : '', scope: '시즌 최고 · 최소 5판' }, ]; return
{label} 시즌 요약커뮤니티 전체 · {period}
진행한 내전{m.events}회
확정 세트{m.sets}판
참가 선수{m.players}명
진영 승률 {m.sets}세트 기준
{Math.round(m.blue)}%BLUE / RED{100 - Math.round(m.blue)}%

시즌 기록

분석 가능한 {m.ready}세트 기준 · 검색 조건과 별도 집계
{records.map(record =>

{record.title}{record.scope}

{record.value ?? '—'}{record.suffix}{record.href ? {record.name} : 기록 없음}
)}
; } function EventJumpNav({ events: items }: { events: Event[] }) { return ; } function EventOverview({ event }: { event: Event }) { const sets = event.series.flatMap(s => s.games), ready = sets.filter(g => g.evidence === 'ready').length; const single = event.series.length === 1 ? event.series[0] : null; return
{formatDate(event.date)} {event.time}{event.teamIds.length}팀 · {event.teamIds.length * 5}명{sets.length}세트 결과{ready}세트 분석 가능
{event.champion ? 우승 {teamName(event.champion)} : single && {teamName(single.a)} {single.scoreA} : {single.scoreB} {teamName(single.b)}}
; } function EventSection({ event, eventHref, gameHref }: { event: Event; eventHref: (id: string) => string; gameHref: (id: string) => string }) { return
{event.formatLabel}{event.series.length}개 시리즈

{event.name}

전체 기록
{event.series.map(series => )}
; } function SeriesResultGroup({ series, event, gameHref }: { series: Series; event: Event; gameHref: (id: string) => string }) { return
{series.label}{series.games.length}세트
{teamName(series.a)} series.scoreB ? 'is-winner' : ''}>{series.scoreA}: series.scoreA ? 'is-winner' : ''}>{series.scoreB}{teamName(series.b)}
    {series.games.map(game =>
  • {game.ordinal}세트전체 #{game.number}승{teamName(game.winner)}{formatDuration(game.duration)}{game.evidence === 'ready' ? '분석' : game.evidence === 'missing' ? '원본 없음' : '수집 중'}{game.evidence === 'ready' ? : }
  • )}
; } function LeaderboardTable({ rows, minimum, lane, sort, direction, onSort, profileHref, participationHref }: { rows: PlayerRow[]; minimum: number; lane: Lane | 'all'; sort: SortKey; direction: 'asc' | 'desc'; onSort: (key: SortKey) => void; profileHref: (id: string) => string; participationHref: (id: string) => string }) { const firstUnder = rows.findIndex(row => row.games < minimum); const metric = (key: SortKey, label: string) => ; return <>
옆으로 이동하면 모든 지표를 볼 수 있어요. 선수 이름은 고정됩니다.
{metric('winRate', '승률')}{metric('games', '판수')}{metric('kda', 'KDA')}{metric('gpm', 'GPM')}{metric('kp', '킬 관여')}{metric('cspm', 'CS/분')}{rows.map((row, index) => )}
{lane === 'all' ? '전체 포지션' : laneNames[lane]} 선수 순위. {sortLabels[sort]} {direction === 'desc' ? '높은' : '낮은'} 순. 최소 {minimum}판 기준.
순위선수주 챔피언
{row.rank}
{row.name}{lane === 'all' ? laneNames[row.lane] : laneNames[lane]}·참가 내전{row.games < minimum && 기준 미달}
= 50 ? 'is-blue' : ''}>{Math.round(row.winRate)}%{row.games}{row.wins}승 {row.losses}패= 3 ? 'is-green' : ''}>{row.kda.toFixed(2)}
{row.champions.map(c => {c.games})}
{row.gpm.toFixed(1)}{row.kp.toFixed(1)}%{row.cspm.toFixed(1)}

KDA는 (킬 + 어시스트) ÷ 데스, GPM은 분당 골드입니다. {lane !== 'all' && `${laneNames[lane]}로 플레이한 경기의 모든 지표를 다시 집계했습니다. `}검색 결과의 순위는 전체 순위를 유지합니다.

; } function GameAnalysis({ game, profileHref, eventHref }: { game: Game; profileHref: (id: string) => string; eventHref: (id: string) => string }) { const event = events.find(e => e.id === game.eventId)!; const series = event.series.find(s => s.id === game.seriesId)!; const [retryMessage, setRetryMessage] = useState(''); const totals = [game.blue, game.red].map(id => game.participants.filter(p => p.teamId === id).reduce((sum, p) => ({ gold: sum.gold + p.gold, kills: sum.kills + p.kills, damage: sum.damage + p.damage }), { gold: 0, kills: 0, damage: 0 })); const timeline = [0, 5, 10, 15, 20, Math.round(game.duration / 60)].filter((n, i, a) => a.indexOf(n) === i).map((minute, i) => ({ minute, 블루: Math.round(totals[0].gold * minute / Math.round(game.duration / 60) * (i < 3 ? .85 : 1)), 레드: Math.round(totals[1].gold * minute / Math.round(game.duration / 60) * (i < 3 ? .9 : 1)) })); return <>
{event.name}{series.label}{game.ordinal}세트 · 전체 #{game.number}{formatDuration(game.duration)}
BLUE SIDE

{teamName(game.blue)}

{game.winner === game.blue ? '승리' : '패배'}
{game.evidence === 'ready' ? `${totals[0].kills} : ${totals[1].kills}` : 'VS'}{game.evidence === 'ready' ? '팀 킬 스코어' : '공식 세트 결과'}
RED SIDE

{teamName(game.red)}

{game.winner === game.red ? '승리' : '패배'}
{game.evidence !== 'ready' ? 내전의 전체 기록 보기{game.evidence === 'pending' && setRetryMessage('아직 새로운 분석 기록이 없습니다. 공식 결과는 위에서 확인할 수 있습니다.')}>수집 상태 다시 확인}}>{retryMessage || (game.evidence === 'missing' ? 'Riot 원본 기록이 없어 선수별 지표와 그래프를 제공하지 않습니다. 승패 결과는 계속 확인할 수 있습니다.' : '선수별 지표는 수집이 완료되면 표시됩니다. 공식 승패와 경기 시간은 먼저 확인할 수 있습니다.')} : <>

골드 흐름

예시 타임라인 · 팀 누적 골드
`${n}분`} tickLine={false} axisLine={false} fontSize={11} /> `${Number(n) / 1000}k`} width={40} tickLine={false} axisLine={false} fontSize={11} /> Number(value).toLocaleString()} labelFormatter={label => `${label}분`} contentStyle={{ background: 'var(--color-background-card)', color: 'var(--color-text-primary)', border: '1px solid var(--color-border)', borderRadius: 8 }} />

최종 골드: 블루 {totals[0].gold.toLocaleString()} · 레드 {totals[1].gold.toLocaleString()}

팀 비교

블루 / 레드
{(['kills', 'gold', 'damage'] as const).map((key, i) =>
{totals[0][key].toLocaleString()}{['킬', '골드', '챔피언 피해량'][i]}{totals[1][key].toLocaleString()}
)}
{[game.blue, game.red].map((id, index) =>

{game.winner === id ? '승리' : '패배'}{teamName(id)}

{index === 0 ? '블루' : '레드'} · {totals[index].kills}킬 · {totals[index].gold.toLocaleString()}골드
{game.participants.filter(p => p.teamId === id).map(p => )}
선수 / 챔피언K / D / A킬 관여피해량골드CS / 분당시야 점수
)} } ; } function ScoreboardRow({ participant: p, duration, profileHref }: { participant: Participant; duration: number; profileHref: (id: string) => string }) { return
{playerById.get(p.playerId)!.name}{laneNames[p.lane]} · {champions[p.champion].name}
{p.kills} / {p.deaths} / {p.assists}{((p.kills + p.assists) / Math.max(1, p.deaths)).toFixed(2)} KDA{p.kp.toFixed(1)}%{p.damage.toLocaleString()}{p.gold.toLocaleString()}{p.cs}{(p.cs / (duration / 60)).toFixed(1)} / 분{p.vision}; } function PlayerDetail({ playerId, season, lane, onLane, gameHref, participationHref }: { playerId: string; season: string; lane: Lane | 'all'; onLane: (lane: string) => void; gameHref: (id: string) => string; participationHref: (id: string) => string }) { const player = playerById.get(playerId)!; const row = aggregateRows(season, lane, 5, 'games').find(r => r.id === playerId); const appearances = playerGames(playerId, season, lane); return <>

{player.name}

{teamName(player.teamId)} · 주 포지션 {laneNames[player.lane]}
참가 내전 보기

선택한 시즌과 포지션으로 모든 지표를 집계합니다.

{row ? <>
{[['판수', `${row.games}`, `${row.wins}승 ${row.losses}패`], ['승률', `${Math.round(row.winRate)}%`, '수집된 경기 기준'], ['KDA', row.kda.toFixed(2), '(킬 + 어시스트) / 데스'], ['GPM', row.gpm.toFixed(1), '평균 분당 골드'], ['킬 관여', `${row.kp.toFixed(1)}%`, '평균 킬 관여율'], ['분당 CS', row.cspm.toFixed(1), '평균 CS']].map(([label, value, desc]) =>
{label}{value}{desc}
)}

참가 세트 기록 {appearances.length}판

최근 내전부터 표시

{appearances.map(({ game, participant: p }) => { const event = events.find(e => e.id === game.eventId)!; return
{p.won ? '승리' : '패배'}
{event.name}{formatDate(event.date)} · 전체 {game.number}세트 · {laneNames[p.lane]}
{p.kills} / {p.deaths} / {p.assists}{((p.kills + p.assists) / Math.max(p.deaths, 1)).toFixed(2)} KDA{formatDuration(game.duration)}분석
; })}
: onLane('all')}>전체 포지션 보기}>다른 포지션이나 시즌을 선택해 주세요.}; }