feat: enhance auction interactions and player statistics UI

This commit is contained in:
dahyeon committed 2026-11-11 20:06:22 +09:00
1 parent 6c582ba3cf
commit be4de61bb7
115 files changed
+13292 -2871

No files matched your search

@@ -0,0 +1,240 @@
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<string, string | null>;
const visits = new Map<string, { y: number; focus: string | null }>();
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<typeof Link>) {
return <Link {...props} onClick={event => { rememberVisit(); props.onClick?.(event); }} />;
}
function Champion({ id, size = 'normal' }: { id: number; size?: 'small' | 'normal' | 'large' }) {
const champion = champions[id];
return <img className={`is-champion is-champion-${size}`} src={championImage(champion.key)} alt={champion.name} title={champion.name} loading="lazy" />;
}
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 <section className={`is-feedback is-feedback-${type}`} role={type === 'error' ? 'alert' : 'status'} aria-live="polite"><Icon size={26} aria-hidden="true" /><h2>{title}</h2>{children && <p>{children}</p>}{action && <div className="is-feedback-actions">{action}</div>}</section>;
}
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<ReturnType<typeof setTimeout> | 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<HTMLElement>(`[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 = <div className="is-page-actions"><button className="is-icon-button" onClick={copyLink} aria-label="현재 전적 링크 복사">{copied ? <Check size={17} /> : <Copy size={17} />}</button><label className="is-season-select"><span>집계 시즌</span><select value={season} onChange={e => update({ season: e.target.value, shown: null, returnTo: null, ...(detail !== 'player' ? { detail: null, event: null, game: null } : {}) })}>{seasons.map(s => <option value={s.id} key={s.id}>{s.name}</option>)}<option value="all">전체 시즌</option></select></label></div>;
return <div className="internal-stats-preview">
<a className="is-skip-link" href="#stats-main">전적 본문으로 건너뛰기</a>
<div className="is-preview-notice"><span><span className="is-preview-dot" /> 인터랙티브 시안 <span className="is-notice-separator">/</span> 예시 데이터</span><a href={ORIGINAL_PATH}>현재 페이지와 비교 <ArrowRight size={13} /></a></div>
<header className="is-site-header"><a className="is-brand" href="/">LOLYMPUS<span>TOURNAMENT</span></a><nav aria-label="주 메뉴"><a href="/">홈</a><a href="/inhouse">내전</a><a href="/tournaments">멸망전</a><PreviewLink to={PREVIEW_PATH} aria-current="page">전적</PreviewLink></nav><button className="is-icon-button" aria-label={theme === 'dark' ? '라이트 테마로 전환' : '다크 테마로 전환'} onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>{theme === 'dark' ? <Sun size={19} /> : <Moon size={19} />}</button></header>
<main id="stats-main" className="is-page">
{!detail ? <>
<header className="is-page-heading"><div><p className="is-eyebrow">LOLYMPUS COMMUNITY</p><h1>내전 전적</h1><p className="is-muted">함께한 경기와 선수들의 기록을 만나보세요.</p></div>{secondaryControls}</header>
<SeasonSummary metrics={metrics} label={seasonLabel} period={period} profileHref={id => target({ detail: 'player', profile: id, lane: null })} gameHref={gameHref} />
<div className="is-workspace">
<div className="is-view-tabs" role="tablist" aria-label="전적 보기">
{(['matches', 'players'] as const).map((v, index) => <button key={v} id={`tab-${v}`} role="tab" aria-selected={view === v} aria-controls="stats-view-panel" tabIndex={view === v ? 0 : -1} onClick={() => update({ view: v })} onKeyDown={e => { if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) { e.preventDefault(); const next = e.key === 'Home' ? 'matches' : e.key === 'End' ? 'players' : index === 0 ? 'players' : 'matches'; update({ view: next }); document.getElementById(`tab-${next}`)?.focus(); } }}>{v === 'matches' ? <List size={17} /> : <Users size={17} />}{v === 'matches' ? '최근 내전' : '선수 전적·순위'}<span>{v === 'matches' ? metrics.events : metrics.players}</span></button>)}
<span className="is-tabs-caption">{seasonLabel} <span>·</span> {period}</span>
</div>
<section id="stats-view-panel" role="tabpanel" aria-labelledby={`tab-${view}`}>
<div className="is-filter-bar">
<label className="is-search"><Search size={18} aria-hidden="true" /><input type="search" maxLength={100} aria-label={view === 'matches' ? '내전·팀·선수 검색' : '선수 검색'} placeholder={view === 'matches' ? '내전명, 팀명, 선수 이름 검색' : '선수 이름 검색'} value={view === 'matches' ? matchQuery : playerQuery} onChange={e => update({ [view === 'matches' ? 'matchQ' : 'playerQ']: e.target.value, shown: null }, true)} />{(view === 'matches' ? matchQuery : playerQuery) && <button aria-label="검색어 지우기" onClick={() => update({ [view === 'matches' ? 'matchQ' : 'playerQ']: null }, true)}><X size={16} /></button>}</label>
{view === 'matches' ? <>
<div className="is-type-filters" role="group" aria-label="내전 유형">{[['all', '전체'], ['pair', '두 팀 내전'], ['tournament', '대회']].map(([value, label]) => <Chip key={value} selected={format === value} onClick={() => update({ format: value === 'all' ? null : value, shown: null })}>{label}</Chip>)}</div>
<div className="is-date-range"><CalendarDays size={16} aria-hidden="true" /><label><span className="sr-only">시작일</span><input type="date" aria-label="시작일" value={from} onInput={e => update({ from: e.currentTarget.value, shown: null })} /></label><span>—</span><label><span className="sr-only">종료일</span><input type="date" aria-label="종료일" value={to} onInput={e => update({ to: e.currentTarget.value, shown: null })} /></label></div>
</> : <><label className="is-select"><Filter size={15} /><span className="sr-only">플레이 포지션</span><select aria-label="플레이 포지션" value={lane} onChange={e => update({ lane: e.target.value })}><option value="all">전체 포지션</option>{lanes.map(l => <option value={l} key={l}>{laneNames[l]}</option>)}</select></label><label className="is-select"><span>순위 기준</span><select aria-label="최소 판수" value={minimum} onChange={e => update({ min: e.target.value })}>{[0, 5, 10, 20].map(n => <option key={n} value={n}>{n === 0 ? '모든 선수' : `최소 ${n}판`}</option>)}</select></label><label className="is-sort-select"><ArrowDownUp size={16} /><select aria-label="순위 정렬" value={sort} onChange={e => update({ sort: e.target.value, dir: null })}>{Object.entries(sortLabels).map(([key, value]) => <option value={key} key={key}>{value} 순</option>)}</select></label></>}
</div>
{activeFilters.length > 0 && <div className="is-active-filters"><span>적용 조건</span>{activeFilters.map(filter => <button key={filter.label} onClick={() => update({ ...filter.clear, shown: null })} aria-label={`${filter.label} 해제`}>{filter.label}<X size={13} /></button>)}<button className="is-reset" onClick={resetFilters}>전체 초기화</button></div>}
{view === 'matches' && invalidDates && <p className="is-inline-error" role="alert">종료일을 시작일과 같거나 이후 날짜로 선택해 주세요.</p>}
{(state === 'error' || state === 'loading' || retrying) ? <Feedback type={retrying || state === 'loading' ? 'loading' : 'error'} title={retrying || state === 'loading' ? '전적을 불러오는 중입니다' : '전적을 불러오지 못했습니다'} action={<><Btn onClick={retry} disabled={retrying}>다시 시도</Btn><Btn variant="ghost" onClick={() => update({ state: null })}>목록으로 돌아가기</Btn></>}>선택한 시즌과 검색 조건은 유지됩니다.</Feedback> : view === 'matches' ? <>
<div className="is-result-heading"><h2>경기 기록 <span>{filteredEvents.length}회</span></h2><p role="status">{visibleEvents.length}개 표시{filteredEvents.length > shown && ` / 검색 결과 ${filteredEvents.length}개`}</p></div>
{visibleEvents.length ? <div className="is-events-layout"><EventJumpNav events={visibleEvents} /><div className="is-events-list">{visibleEvents.map(e => <EventSection key={e.id} event={e} eventHref={eventHref} gameHref={gameHref} />)}{filteredEvents.length > shown && <button className="is-load-more" onClick={() => update({ shown: String(shown + 2) })}>이전 내전 2개 더 보기 <ArrowDown size={16} /><span>{filteredEvents.length - shown}개 남음</span></button>}</div></div> : <Feedback type="empty" title={invalidDates ? '조회 기간을 확인해 주세요' : '조건에 맞는 내전이 없습니다'} action={<Btn onClick={resetFilters}>검색 조건 초기화</Btn>}>날짜나 검색어를 바꾸면 다른 내전을 찾을 수 있습니다.</Feedback>}
</> : <>
<div className="is-result-heading"><div><h2>{sortLabels[sort]} 순 <span>{visibleRows.length}명</span></h2><p>{lane === 'all' ? '전체 포지션' : `${laneNames[lane]} 플레이만 집계`} · {minimum > 0 ? `${minimum}판 미만은 기준 미달로 뒤에 표시` : '판수 제한 없음'}</p></div><label className="is-checkbox"><input type="checkbox" checked={params.get('qualified') === '1'} onChange={e => update({ qualified: e.target.checked ? '1' : null })} />기준 충족 선수만</label></div>
{visibleRows.length ? <LeaderboardTable rows={visibleRows} minimum={minimum} lane={lane} sort={sort} direction={direction} onSort={key => update({ sort: key, dir: sort === key && direction === 'desc' ? 'asc' : 'desc' })} profileHref={profileHref} participationHref={participationHref} /> : <Feedback type="empty" title="조건에 맞는 선수가 없습니다" action={<Btn onClick={resetFilters}>검색 조건 초기화</Btn>}>검색어, 포지션 또는 최소 판수를 바꿔 보세요.</Feedback>}
</>}
</section>
</div>
</> : <>
<PreviewLink className="is-back-link" to={backHref}><ArrowLeft size={16} />{rawReturn?.includes('detail=') ? '이전 기록으로' : '내전 전적으로 돌아가기'}</PreviewLink>
<header className="is-page-heading is-detail-heading"><div><p className="is-eyebrow">{seasonLabel} · {period}</p><h1 id="stats-detail-title" tabIndex={-1}>{detail === 'event' ? event?.name ?? '내전 기록' : detail === 'game' ? '세트 상세 분석' : profile?.name ?? '선수 전적'}</h1><p className="is-muted">{detail === 'player' ? '선택한 시즌의 개인 기록과 참가 경기를 확인합니다.' : '공식 경기 결과와 수집된 분석 기록을 함께 확인합니다.'}</p></div>{secondaryControls}</header>
{(state === 'error' || state === 'loading' || retrying) ? <Feedback type={retrying || state === 'loading' ? 'loading' : 'error'} title={retrying || state === 'loading' ? '기록을 불러오는 중입니다' : '기록을 불러오지 못했습니다'} action={<><Btn onClick={retry} disabled={retrying}>다시 시도</Btn><Btn to={backHref} variant="ghost">이전 기록으로</Btn></>}>경기 제목과 선택한 조건을 유지했습니다. 다시 시도하거나 이전 화면으로 돌아갈 수 있습니다.</Feedback> : detail === 'event' && event ? <><EventOverview event={event} /><div className="is-detail-series">{event.series.map(series => <SeriesResultGroup key={series.id} series={series} event={event} gameHref={gameHref} />)}</div></> : detail === 'game' && game ? <GameAnalysis game={game} profileHref={profileHref} eventHref={eventHref} /> : detail === 'player' && profile ? <PlayerDetail playerId={profile.id} season={season} lane={lane} onLane={value => update({ lane: value })} gameHref={gameHref} participationHref={participationHref} /> : <Feedback type="empty" title="요청한 기록을 찾을 수 없습니다" action={<Btn to={listHref}>내전 전적으로 돌아가기</Btn>}>기록의 링크를 확인하거나 목록에서 다시 선택해 주세요.</Feedback>}
</>}
<div className="is-announcement" role="status">{copyError ? '링크를 복사하지 못했습니다. 주소 표시줄의 주소를 복사해 주세요.' : copied ? '현재 검색 조건이 포함된 링크를 복사했습니다.' : ''}</div>
<footer className="is-page-footer"><span>LOLYMPUS <span>·</span> 함께하는 모든 게임의 기록</span><span>예시 데이터로 구성한 디자인 시안</span></footer>
<aside className="is-preview-tools" aria-label="시안 상태 확인"><span>시안 상태 확인</span><button onClick={() => update({ state: null })} aria-pressed={!state}>정상</button><button onClick={() => update({ state: 'loading' })} aria-pressed={state === 'loading'}>로딩</button><button onClick={() => update({ state: 'error' })} aria-pressed={state === 'error'}>조회 오류</button></aside>
</main>
</div>;
}
function SeasonSummary({ metrics: m, label, period, profileHref, gameHref }: { metrics: ReturnType<typeof seasonMetrics>; 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 <section className="is-season-summary" aria-label="커뮤니티 전체 시즌 요약"><div className="is-summary-topline"><span><span className="is-current-dot" />{label} <span className="is-muted">시즌 요약</span></span><span className="is-muted">커뮤니티 전체 · {period}</span></div><div className="is-summary-metrics"><div><span>진행한 내전</span><strong>{m.events}<small>회</small></strong></div><div><span>확정 세트</span><strong>{m.sets}<small>판</small></strong></div><div><span>참가 선수</span><strong>{m.players}<small>명</small></strong></div><div className="is-side-rate"><span>진영 승률 <small>{m.sets}세트 기준</small></span><div><strong className="is-blue">{Math.round(m.blue)}<small>%</small></strong><span>BLUE / RED</span><strong className="is-red">{100 - Math.round(m.blue)}<small>%</small></strong></div><div className="is-side-track" aria-hidden="true"><span style={{ width: `${m.blue}%` }} /></div></div></div><div className="is-records-heading"><Trophy size={14} /><h2>시즌 기록</h2><span>분석 가능한 {m.ready}세트 기준 · 검색 조건과 별도 집계</span></div><div className="is-records">{records.map(record => <div className="is-record" key={record.title}><p>{record.title}<span>{record.scope}</span></p><div><strong>{record.value ?? '—'}<small>{record.suffix}</small></strong>{record.href ? <PreviewLink to={record.href} aria-label={`${record.title} ${record.name}의 ${record.scope === '단일 경기 최고' ? '근거 경기' : '시즌 전적'} 보기`}>{record.name}<ChevronRight size={13} /></PreviewLink> : <span>기록 없음</span>}</div></div>)}</div></section>;
}
function EventJumpNav({ events: items }: { events: Event[] }) {
return <nav className="is-event-jump" aria-label="내전 바로가기"><div className="is-jump-desktop"><p><CalendarDays size={15} /> 내전 바로가기</p>{items.map(event => <a href={`#event-${event.id}`} key={event.id}><span>{formatDate(event.date)}</span><strong>{event.name}</strong><small>{event.formatLabel}</small></a>)}</div><label className="is-jump-mobile"><CalendarDays size={16} /><span>내전 이동</span><select aria-label="내전 바로가기" defaultValue="" onChange={e => { if (e.target.value) { document.getElementById(`event-${e.target.value}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }}><option value="" disabled>날짜로 바로가기</option>{items.map(e => <option key={e.id} value={e.id}>{formatDate(e.date)} · {e.name}</option>)}</select></label></nav>;
}
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 <div className="is-event-overview"><div className="is-event-meta"><span><CalendarDays size={14} />{formatDate(event.date)} {event.time}</span><span><Users size={14} />{event.teamIds.length}팀 · {event.teamIds.length * 5}명</span><span>{sets.length}세트 결과</span><span className="is-analysis-count">{ready}세트 분석 가능</span></div>{event.champion ? <span className="is-champion-label"><Trophy size={15} />우승 <strong>{teamName(event.champion)}</strong></span> : single && <span className="is-series-score">{teamName(single.a)} <strong>{single.scoreA} : {single.scoreB}</strong> {teamName(single.b)}</span>}</div>;
}
function EventSection({ event, eventHref, gameHref }: { event: Event; eventHref: (id: string) => string; gameHref: (id: string) => string }) {
return <article className="is-event-section" id={`event-${event.id}`}><header><div><div className="is-event-kicker"><span>{event.formatLabel}</span><span>{event.series.length}개 시리즈</span></div><h3><PreviewLink to={eventHref(event.id)} data-return-id={`event-link-${event.id}`}>{event.name}<ChevronRight size={18} /></PreviewLink></h3></div><PreviewLink className="is-text-link is-event-detail-link" to={eventHref(event.id)} data-return-id={`event-detail-${event.id}`}>전체 기록<ArrowRight size={15} /></PreviewLink></header><EventOverview event={event} /><div className="is-series-grid">{event.series.map(series => <SeriesResultGroup key={series.id} series={series} event={event} gameHref={gameHref} />)}</div></article>;
}
function SeriesResultGroup({ series, event, gameHref }: { series: Series; event: Event; gameHref: (id: string) => string }) {
return <section className="is-series-group" aria-label={`${series.label} ${teamName(series.a)} 대 ${teamName(series.b)}`}><header><span>{series.label}</span><span>{series.games.length}세트</span></header><div className="is-matchup"><strong className={series.winner === series.a ? 'is-winner' : ''}>{teamName(series.a)}</strong><span className="is-score"><b className={series.scoreA > series.scoreB ? 'is-winner' : ''}>{series.scoreA}</b><i>:</i><b className={series.scoreB > series.scoreA ? 'is-winner' : ''}>{series.scoreB}</b></span><strong className={series.winner === series.b ? 'is-winner' : ''}>{teamName(series.b)}</strong></div><ul>{series.games.map(game => <li key={game.id}><span className="is-set-number">{game.ordinal}세트<small>전체 #{game.number}</small></span><span className="is-set-winner"><span className="is-win-badge">승</span>{teamName(game.winner)}</span><span className="is-duration"><Clock3 size={12} />{formatDuration(game.duration)}</span><PreviewLink className={`is-analysis-link ${game.evidence !== 'ready' ? 'is-unavailable' : ''}`} to={gameHref(game.id)} data-return-id={`game-link-${game.id}`} aria-label={`${formatDate(event.date)} ${series.label} ${game.ordinal}세트 ${game.evidence === 'ready' ? '상세 분석' : '기록 상태 확인'}`}>{game.evidence === 'ready' ? '분석' : game.evidence === 'missing' ? '원본 없음' : '수집 중'}{game.evidence === 'ready' ? <ChevronRight size={13} /> : <Info size={12} />}</PreviewLink></li>)}</ul></section>;
}
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) => <th scope="col" aria-sort={sort === key ? direction === 'desc' ? 'descending' : 'ascending' : 'none'}><button className={sort === key ? 'is-sorted' : ''} onClick={() => onSort(key)}>{label}{sort === key ? <ArrowDown size={13} className={direction === 'asc' ? 'is-arrow-up' : ''} /> : <ArrowDownUp size={12} />}</button></th>;
return <><div className="is-table-hint"><ArrowRight size={14} />옆으로 이동하면 모든 지표를 볼 수 있어요. 선수 이름은 고정됩니다.</div><div className="is-table-scroll" role="region" aria-label="선수 순위표, 좌우 방향키로 지표 이동" tabIndex={0}><table className="is-leaderboard"><caption className="sr-only">{lane === 'all' ? '전체 포지션' : laneNames[lane]} 선수 순위. {sortLabels[sort]} {direction === 'desc' ? '높은' : '낮은'} 순. 최소 {minimum}판 기준.</caption><colgroup><col className="is-col-rank" /><col className="is-col-player" /><col className="is-col-win" /><col className="is-col-games" /><col className="is-col-kda" /><col className="is-col-champions" /><col /><col /><col /></colgroup><thead><tr><th scope="col" className="is-sticky-rank">순위</th><th scope="col" className="is-sticky-player">선수</th>{metric('winRate', '승률')}{metric('games', '판수')}{metric('kda', 'KDA')}<th scope="col">주 챔피언</th>{metric('gpm', 'GPM')}{metric('kp', '킬 관여')}{metric('cspm', 'CS/분')}</tr></thead><tbody>{rows.map((row, index) => <tr key={row.id} className={`${row.games < minimum ? 'is-under-qualified' : ''} ${index === firstUnder ? 'is-threshold-first' : ''}`}><td className="is-sticky-rank"><span className="is-rank-number">{row.rank}</span></td><th scope="row" className="is-sticky-player"><div className="is-player-identity"><Champion id={row.champions[0].id} /><div><PreviewLink to={profileHref(row.id)} data-return-id={`player-link-${row.id}`}>{row.name}</PreviewLink><small>{lane === 'all' ? laneNames[row.lane] : laneNames[lane]}<span>·</span><PreviewLink to={participationHref(row.id)}>참가 내전</PreviewLink></small>{row.games < minimum && <span className="is-sample-badge">기준 미달</span>}</div></div></th><td><strong className={row.winRate >= 50 ? 'is-blue' : ''}>{Math.round(row.winRate)}<small>%</small></strong><div className="is-win-track" aria-hidden="true"><span style={{ width: `${row.winRate}%` }} /></div></td><td><strong>{row.games}</strong><small className="is-win-loss">{row.wins}승 {row.losses}패</small></td><td><strong className={row.kda >= 3 ? 'is-green' : ''}>{row.kda.toFixed(2)}</strong></td><td><div className="is-champion-list">{row.champions.map(c => <span key={c.id}><Champion id={c.id} size="small" /><small>{c.games}</small></span>)}</div></td><td>{row.gpm.toFixed(1)}</td><td>{row.kp.toFixed(1)}%</td><td>{row.cspm.toFixed(1)}</td></tr>)}</tbody></table></div><div className="is-table-footnote"><Info size={14} /><p>KDA는 (킬 + 어시스트) ÷ 데스, GPM은 분당 골드입니다. {lane !== 'all' && `${laneNames[lane]}로 플레이한 경기의 모든 지표를 다시 집계했습니다. `}검색 결과의 순위는 전체 순위를 유지합니다.</p></div></>;
}
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 <>
<div className="is-game-context"><PreviewLink to={eventHref(event.id)}>{event.name}<ChevronRight size={14} /></PreviewLink><span>{series.label}</span><strong>{game.ordinal}세트 <span className="is-muted">· 전체 #{game.number}</span></strong><span><Clock3 size={14} />{formatDuration(game.duration)}</span></div>
<div className="is-game-result"><div className={game.winner === game.blue ? 'is-result-win' : ''}><span className="is-blue">BLUE SIDE</span><h2>{teamName(game.blue)}</h2><b>{game.winner === game.blue ? '승리' : '패배'}</b></div><strong>{game.evidence === 'ready' ? `${totals[0].kills} : ${totals[1].kills}` : 'VS'}<small>{game.evidence === 'ready' ? '팀 킬 스코어' : '공식 세트 결과'}</small></strong><div className={game.winner === game.red ? 'is-result-win' : ''}><span className="is-red">RED SIDE</span><h2>{teamName(game.red)}</h2><b>{game.winner === game.red ? '승리' : '패배'}</b></div></div>
{game.evidence !== 'ready' ? <Feedback type="empty" title={game.evidence === 'missing' ? '공식 결과만 남아 있는 경기입니다' : '상세 기록을 수집하고 있습니다'} action={<><Btn to={eventHref(event.id)}>내전의 전체 기록 보기</Btn>{game.evidence === 'pending' && <Btn variant="ghost" onClick={() => setRetryMessage('아직 새로운 분석 기록이 없습니다. 공식 결과는 위에서 확인할 수 있습니다.')}>수집 상태 다시 확인</Btn>}</>}>{retryMessage || (game.evidence === 'missing' ? 'Riot 원본 기록이 없어 선수별 지표와 그래프를 제공하지 않습니다. 승패 결과는 계속 확인할 수 있습니다.' : '선수별 지표는 수집이 완료되면 표시됩니다. 공식 승패와 경기 시간은 먼저 확인할 수 있습니다.')}</Feedback> : <>
<div className="is-analysis-top"><section className="is-analysis-panel"><header><h2>골드 흐름</h2><span>예시 타임라인 · 팀 누적 골드</span></header><div className="is-chart"><ResponsiveContainer width="100%" height="100%" minWidth={0} initialDimension={{ width: 520, height: 215 }}><LineChart data={timeline} margin={{ left: 0, right: 12, top: 10, bottom: 0 }} accessibilityLayer><CartesianGrid strokeDasharray="3 3" vertical={false} stroke="var(--color-border)" /><XAxis dataKey="minute" tickFormatter={n => `${n}분`} tickLine={false} axisLine={false} fontSize={11} /><YAxis tickFormatter={n => `${Number(n) / 1000}k`} width={40} tickLine={false} axisLine={false} fontSize={11} /><Tooltip formatter={value => 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 }} /><Legend /><Line type="monotone" dataKey="블루" stroke="var(--color-win)" strokeWidth={2} dot={false} isAnimationActive={false} /><Line type="monotone" dataKey="레드" stroke="var(--color-loss)" strokeWidth={2} dot={false} isAnimationActive={false} /></LineChart></ResponsiveContainer></div><p className="is-muted is-chart-description">최종 골드: 블루 {totals[0].gold.toLocaleString()} · 레드 {totals[1].gold.toLocaleString()}</p></section><section className="is-analysis-panel"><header><h2>팀 비교</h2><span>블루 / 레드</span></header><div className="is-team-comparison">{(['kills', 'gold', 'damage'] as const).map((key, i) => <div key={key}><div><strong className="is-blue">{totals[0][key].toLocaleString()}</strong><span>{['킬', '골드', '챔피언 피해량'][i]}</span><strong className="is-red">{totals[1][key].toLocaleString()}</strong></div><div className="is-comparison-track" aria-hidden="true"><span style={{ width: `${totals[0][key] / (totals[0][key] + totals[1][key]) * 100}%` }} /></div></div>)}</div></section></div>
{[game.blue, game.red].map((id, index) => <section key={id} className="is-scoreboard"><header><h2><span className={index === 0 ? 'is-blue' : 'is-red'}>{game.winner === id ? '승리' : '패배'}</span>{teamName(id)}</h2><span>{index === 0 ? '블루' : '레드'} · {totals[index].kills}킬 · {totals[index].gold.toLocaleString()}골드</span></header><div className="is-table-scroll" tabIndex={0} role="region" aria-label={`${teamName(id)} 선수별 스코어보드`}><table><thead><tr><th scope="col">선수 / 챔피언</th><th scope="col">K / D / A</th><th scope="col">킬 관여</th><th scope="col">피해량</th><th scope="col">골드</th><th scope="col">CS / 분당</th><th scope="col">시야 점수</th></tr></thead><tbody>{game.participants.filter(p => p.teamId === id).map(p => <ScoreboardRow key={p.playerId} participant={p} duration={game.duration} profileHref={profileHref} />)}</tbody></table></div></section>)}
</>}
</>;
}
function ScoreboardRow({ participant: p, duration, profileHref }: { participant: Participant; duration: number; profileHref: (id: string) => string }) {
return <tr><th scope="row"><div className="is-player-identity"><Champion id={p.champion} /><div><PreviewLink to={profileHref(p.playerId)}>{playerById.get(p.playerId)!.name}</PreviewLink><small>{laneNames[p.lane]} · {champions[p.champion].name}</small></div></div></th><td><strong>{p.kills} / {p.deaths} / {p.assists}</strong><small>{((p.kills + p.assists) / Math.max(1, p.deaths)).toFixed(2)} KDA</small></td><td>{p.kp.toFixed(1)}%</td><td>{p.damage.toLocaleString()}</td><td>{p.gold.toLocaleString()}</td><td>{p.cs}<small>{(p.cs / (duration / 60)).toFixed(1)} / 분</small></td><td>{p.vision}</td></tr>;
}
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 <><div className="is-profile-heading"><Champion id={player.champion} size="large" /><div><h2>{player.name}</h2><span>{teamName(player.teamId)} · 주 포지션 {laneNames[player.lane]}</span></div><PreviewLink className="is-action-link" to={participationHref(playerId)}>참가 내전 보기<ArrowRight size={16} /></PreviewLink></div><div className="is-profile-filters"><label className="is-select"><span>집계 포지션</span><select aria-label="선수 집계 포지션" value={lane} onChange={e => onLane(e.target.value)}><option value="all">전체 포지션</option>{lanes.map(l => <option value={l} key={l}>{laneNames[l]}</option>)}</select></label><p className="is-muted">선택한 시즌과 포지션으로 모든 지표를 집계합니다.</p></div>{row ? <><div className="is-profile-stats">{[['판수', `${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]) => <div key={label}><span>{label}</span><strong>{value}</strong><small>{desc}</small></div>)}</div><div className="is-result-heading"><h2>참가 세트 기록 <span>{appearances.length}판</span></h2><p>최근 내전부터 표시</p></div><div className="is-personal-games">{appearances.map(({ game, participant: p }) => { const event = events.find(e => e.id === game.eventId)!; return <article key={game.id} className={p.won ? 'is-personal-win' : 'is-personal-loss'}><span className={`is-personal-result ${p.won ? 'is-blue' : 'is-red'}`}>{p.won ? '승리' : '패배'}</span><Champion id={p.champion} /><div className="is-personal-event"><strong>{event.name}</strong><small>{formatDate(event.date)} · 전체 {game.number}세트 · {laneNames[p.lane]}</small></div><span className="is-personal-kda"><strong>{p.kills} / {p.deaths} / {p.assists}</strong><small>{((p.kills + p.assists) / Math.max(p.deaths, 1)).toFixed(2)} KDA</small></span><span className="is-duration">{formatDuration(game.duration)}</span><PreviewLink className="is-analysis-link" to={gameHref(game.id)} data-return-id={`personal-${game.id}`} aria-label={`${event.name} 전체 ${game.number}세트 분석`}>분석<ChevronRight size={14} /></PreviewLink></article>; })}</div></> : <Feedback type="empty" title="이 포지션의 기록이 없습니다" action={<Btn onClick={() => onLane('all')}>전체 포지션 보기</Btn>}>다른 포지션이나 시즌을 선택해 주세요.</Feedback>}</>;
}