import { useState } from 'react'; import type { CompetitionDetailResponse } from '@lolympus/contracts'; import { ChevronDown, Search, X } from 'lucide-react'; import { Link, useLocation, useParams, useSearchParams } from 'react-router'; import { useCommunity, useCompetition, useCommunityInternalStatsMatches, useCommunityLeaderboard, 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 { internalMatchDetailPath, internalMatchGamePath, } from '../lib/internal-match-routes'; import { getHistoryMatchTitle, getHomeMatchSchedule, } from './home-match-presentation'; import { getSeriesHistoryResultLabel, shouldDisplaySeriesHistoryScore, } from '../components/competition/competition-series-history'; 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 OfficialMatchResult({ competition, }: { competition: CompetitionDetailResponse; }) { const { projection, teams } = competition; const teamName = (id: string) => teams.find(({ teamId }) => teamId === id)?.name ?? '팀 미확인'; const outcome = projection.outcome; if (projection.phase === 'cancelled') return '취소'; if (projection.phase !== 'completed' || !outcome) return '결과 확정 전'; switch (outcome.type) { case 'double-elimination': return `우승 · ${teamName(outcome.championTeamId)}`; case 'round-robin': return outcome.leaderTeamIds.length > 0 ? `${outcome.leaderTeamIds.length > 1 ? '공동 1위' : '우승'} · ${outcome.leaderTeamIds.map(teamName).join(', ')}` : '대회 종료'; case 'paired-series': { if (projection.series.length !== 1) return '시리즈 종료'; const series = projection.series[0]; if (!shouldDisplaySeriesHistoryScore(series)) return getSeriesHistoryResultLabel(series) ?? '시리즈 종료'; const [left, right] = series.entries; return `${teamName(left.teamId ?? '')} ${left.gameWins} : ${right.gameWins} ${teamName(right.teamId ?? '')}`; } } } function MatchCard({ match, communityId, }: { match: ApiInternalMatchCard; communityId: string; }) { const [open, setOpen] = useState(false); const competition = useCompetition(match.matchId, communityId, open); const location = useLocation(); const backTo = `${location.pathname}${location.search}`; const recordedGames = match.games.filter( ({ winnerTeamIndex }) => winnerTeamIndex !== null, ); const schedule = getHomeMatchSchedule(match.scheduledAt); return (
  • setOpen(event.currentTarget.open)} > {' '} · {match.teams.length}팀 {getHistoryMatchTitle(match.title, schedule)} {competition.data ? ( ) : ( `${recordedGames.length}세트 수집` )} {open && (

    {competition.isLoading ? '공식 결과를 확인하는 중' : competition.data ? '수집된 세트 기록' : '공식 시리즈 정보를 확인할 수 없습니다'}

    내전 기록 전체 보기 →
    {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; return ( ); })}
    순위 소환사 승률 전적 KDA GPM 킬관여 분당 CS 주 챔피언
    {rank <= 3 ? ( {rank} ) : ( {rank} )} {row.summonerName} {row.winRate}% {row.games}전 {row.wins}승 {row.losses}패 {row.kda} {row.avgGoldPerMin} {row.avgKillParticipation}% {row.avgCsPerMin}
    {row.topChampions.map((champion) => ( ))}
    ); } 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 = query.trim().toLocaleLowerCase('ko-KR'); const format = searchParams.get('format'); const playerId = searchParams.get('player'); const championId = Number(searchParams.get('championId')); const filters = { seasonId, championId: Number.isFinite(championId) && championId > 0 ? championId : undefined, limit: 12, }; const communityQuery = useCommunity(communityId); const matchesQuery = useCommunityInternalStatsMatches( filters, communityId, !isRanking, ); const leaderboardQuery = useCommunityLeaderboard(filters, 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 = leaderboardQuery.data?.rows ?? []; const player = leaderboardRows.find((row) => row.userId === playerId); const visibleMatches = matches.filter((match) => { const matchType = match.teams.length === 2 ? 'pair' : 'tournament'; return ( ((format !== 'pair' && format !== 'tournament') || matchType === format) && (!playerId || match.teams.some((team) => team.members.some((member) => member.userId === playerId), )) && match.title.toLocaleLowerCase('ko-KR').includes(keyword) ); }); const visiblePlayers = leaderboardRows.filter((row) => row.summonerName.toLocaleLowerCase('ko-KR').includes(keyword), ); const hasMatchFilters = Boolean( keyword || format === 'pair' || format === 'tournament' || playerId, ); 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 : visibleMatches.length}

    {isRanking ? ( 승률 순 ) : (
    updateParam('format', '')} > 전체 updateParam('format', 'pair')} > 두 팀 내전 updateParam('format', 'tournament')} > 대회
    )}
    {!isRanking && playerId && (
    updateParam('player', '')} aria-label="선수 필터 해제" > {player?.summonerName ?? '선택한 선수'} 참가 내전{' '}
    )} {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()} > 다시 시도 } />
    ) : visibleMatches.length === 0 ? ( ) : (
      {visibleMatches.map((match) => ( ))}
    )} {matchesQuery.hasNextPage && (
    {hasMatchFilters && (

    필터는 불러온 {matches.length}건에 적용됩니다.

    )} {matchesQuery.isFetchNextPageError && (

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

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