import { useDeferredValue, useState } from 'react'; import { ChevronDown, Search, X } from 'lucide-react'; import { Link, useLocation, useParams, useSearchParams } from 'react-router'; import { useCommunity, useCommunityInternalStatsMatches, useCommunityLeaderboard, useCommunityStatsSeasons, useDdragonManifest, useTeamInsights, } from '../api/hooks'; import type { ApiInternalMatchCard, ApiLeaderHighlight, ApiLeaderboardRow, } from '../api/types'; import { DEFAULT_COMMUNITY_ID } from '../config'; import { championDisplayName, championIconUrl, profileIconUrl, } from '../lib/ddragon'; import { filterLeaderboardRows, formatOfficialMatchResult, getMainLane, LEADERBOARD_MIN_GAMES, LEADERBOARD_SORTS, parseLeaderboardSort, sortLeaderboardRows, } from '../lib/internal-stats-presentation'; import { LANE_LABELS } from '../lib/riot-history'; import { internalMatchDetailPath, internalMatchGamePath, } from '../lib/internal-match-routes'; import { getHistoryMatchTitle, getHomeMatchSchedule, } from './home-match-presentation'; import { Btn, Chip, EmptyNote, ErrorNote, LoadingNote, Panel, PanelHeader, PlainPage, Skeleton, } from '../ui'; type Manifest = ReturnType['data']; function ratioClass(value: number) { if (value >= 60) return 'text-loss'; if (value >= 50) return 'text-win'; return 'text-content-muted'; } function kdaClass(value: number) { if (value >= 5) return 'text-gold'; if (value >= 3) return 'text-leaf'; return 'text-content-muted'; } function ChampionChip({ championId, manifest, }: { championId: number; manifest: Manifest; }) { const icon = championIconUrl(manifest, championId); const name = championDisplayName(manifest, championId) ?? String(championId); return ( {icon ? ( {name} ) : null} ); } function MatchCard({ match, communityId, }: { match: ApiInternalMatchCard; communityId: string; }) { const result = match.resultPresentation; const location = useLocation(); const backTo = `${location.pathname}${location.search}`; const recordedGames = match.games.filter( ({ winnerTeamIndex }) => winnerTeamIndex !== null, ); const schedule = getHomeMatchSchedule(match.scheduledAt); const playerCount = match.teams.reduce( (count, team) => count + team.members.length, 0, ); return (
  • {' '} · {match.teams.length}팀 {playerCount > 0 && ` · ${playerCount}명`} {recordedGames.length > 0 && ` · ${recordedGames.length}세트`} {getHistoryMatchTitle(match.title, schedule)} {formatOfficialMatchResult(result)}

    {recordedGames.length > 0 ? '수집된 세트 기록' : '수집된 세트 기록 없음'}

    내전 기록 전체 보기 →
    {recordedGames.length > 0 && (
      {recordedGames.map((game) => { const winner = match.teams.find( ({ teamIndex }) => teamIndex === game.winnerTeamIndex, ); return (
    • 전체 {game.gameNumber}세트 ·{' '} {winner ? `${winner.name} 승` : '팀 미확인'} {game.riotMatchId && ( 상세 분석 )}
    • ); })}
    )}
  • ); } function HighlightCell({ title, highlight, suffix = '', }: { title: string; highlight: ApiLeaderHighlight | null | undefined; suffix?: string; }) { const location = useLocation(); return (
    {title}
    {highlight ? `${highlight.metric}${suffix}` : '—'}
    {highlight ? ( {highlight.summonerName} ) : (
    기록 없음
    )}
    ); } function LeaderboardTable({ rows, ranks, manifest, onSelectPlayer, }: { rows: ApiLeaderboardRow[]; ranks: ReadonlyMap; manifest: Manifest; onSelectPlayer: (id: string) => void; }) { const location = useLocation(); const [showMetrics, setShowMetrics] = useState(false); const metricClass = showMetrics ? '' : 'hidden 2xl:table-cell'; const historyBackTo = `${location.pathname}${location.search}${location.hash}`; return ( <>
    setShowMetrics(!showMetrics)} > 상세 지표
    {rows.map((row) => { const rank = ranks.get(row.userId) ?? 0; const mainLane = getMainLane(row.byLane); return ( ); })}
    순위 소환사 주 챔피언 승률 KDA GPM 킬관여 분당 CS
    {rank <= 3 ? ( {rank} ) : ( {rank} )}
    {row.summonerName}
    {mainLane && ( <> {LANE_LABELS[mainLane] ?? mainLane} )}
    {row.topChampions.slice(0, 3).map((champion) => ( ))}
    {row.winRate}% {row.wins}승 {row.losses}패
    {row.kda} {row.avgGoldPerMin} {row.avgKillParticipation}% {row.avgCsPerMin}
    ); } function SideWinRate({ blue, red, sampleSize, }: { blue: number; red: number; sampleSize: number; }) { if (sampleSize === 0 || blue + red === 0) { return

    진영 승률 집계 없음

    ; } return (

    진영 승률

    블루 {blue}% 레드 {red}%

    {sampleSize}세트 집계

    ); } export default function CommunityInternalStatsPage() { const { cid } = useParams(); const communityId = cid ?? DEFAULT_COMMUNITY_ID; const [searchParams, setSearchParams] = useSearchParams(); const isRanking = searchParams.get('view') === 'ranking'; const seasonId = searchParams.get('seasonId') || 'current'; const query = searchParams.get('q') ?? ''; const keyword = useDeferredValue(query.trim().slice(0, 100)); const format = searchParams.get('format'); const playerId = searchParams.get('player'); const sort = parseLeaderboardSort(searchParams.get('sort')); const championId = Number(searchParams.get('championId')); const filters = { seasonId, championId: Number.isFinite(championId) && championId > 0 ? championId : undefined, limit: 12, }; const communityQuery = useCommunity(communityId); const seasonsQuery = useCommunityStatsSeasons(communityId); const matchesQuery = useCommunityInternalStatsMatches( { ...filters, query: isRanking ? undefined : keyword, format: format === 'pair' || format === 'tournament' ? format : undefined, playerId: playerId ?? undefined, }, communityId, !isRanking, ); const leaderboardQuery = useCommunityLeaderboard({ ...filters, query: isRanking ? keyword : undefined }, communityId); const insightsQuery = useTeamInsights(filters, communityId); const { data: ddragon } = useDdragonManifest(); const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; const season = insightsQuery.data?.season ?? leaderboardQuery.data?.season ?? matchesQuery.data?.pages[0]?.season; const insights = insightsQuery.data; const leaderboardRows = sortLeaderboardRows( leaderboardQuery.data?.rows ?? [], sort, ); const player = leaderboardRows.find((row) => row.userId === playerId); const visiblePlayers = isRanking ? filterLeaderboardRows(leaderboardRows, keyword, leaderboardQuery.data?.matchedUserIds) : leaderboardRows; const hasMatchFilters = Boolean(keyword || format || playerId); const confirmedSideWinRate = insights?.sideWinRate.confirmed; const title = isRanking ? '선수 전적·순위' : '최근 내전'; if (!communityId) { return ( ); } function updateParam(key: string, value: string) { const params = new URLSearchParams(searchParams); if (key === 'view' || key === 'seasonId' || key === 'player') { params.delete('q'); params.delete('format'); params.delete('player'); } if (key === 'player') params.delete('view'); if (value) params.set(key, value); else params.delete(key); setSearchParams(params, { replace: key === 'q', preventScrollReset: true }); } return (

    {communityQuery.data?.name ?? '커뮤니티'}

    내전 전적

    전체 일정 기록
    updateParam('view', '')} > 최근 내전 updateParam('view', 'ranking')} > 선수 전적·순위

    {title}{' '} {isRanking ? visiblePlayers.length : matches.length}

    {isRanking ? (
    {LEADERBOARD_SORTS.map(({ value, label }) => ( updateParam('sort', value === 'games' ? '' : value) } > {label} ))}
    ) : (
    updateParam('format', '')} > 전체 updateParam('format', 'pair')} > 두 팀 내전 updateParam('format', 'tournament')} > 대회
    )}
    {!isRanking && playerId && (
    updateParam('player', '')} aria-label="선수 필터 해제" > {player?.summonerName ?? '선택한 선수'} 참가 내전{' '}
    )} {isRanking && sort !== 'games' && (

    {LEADERBOARD_MIN_GAMES}판 미만인 선수는 뒤에 표시합니다.

    )} {isRanking ? ( leaderboardQuery.isLoading ? ( ) : leaderboardQuery.isError && !leaderboardQuery.data ? (
    void leaderboardQuery.refetch()} > 다시 시도 } />
    ) : visiblePlayers.length === 0 ? ( ) : ( [ row.userId, index + 1, ]), ) } manifest={ddragon} onSelectPlayer={(id) => updateParam('player', id)} /> ) ) : ( <> {matchesQuery.isLoading ? ( ) : matchesQuery.isError && !matchesQuery.data ? (
    void matchesQuery.refetch()} > 다시 시도 } />
    ) : matches.length === 0 ? ( ) : (
      {matches.map((match) => ( ))}
    )} {matchesQuery.hasNextPage && (
    {matchesQuery.isFetchNextPageError && (

    이전 기록을 불러오지 못했습니다.

    )} void matchesQuery.fetchNextPage()} > {matchesQuery.isFetchNextPageError ? '다시 시도' : '이전 기록 더 보기'}
    )} )}
    ); }