import { useDeferredValue, useEffect } from "react"; import { ArrowDown, ArrowDownUp, CalendarDays, List, Search, Users, X, } from "lucide-react"; import { useLocation, useParams, useSearchParams } from "react-router"; import { useCommunity, useCommunityInternalStatsMatches, useCommunityLeaderboard, useCommunityStatsSeasons, useDdragonManifest, useTeamInsights, } from "../api/hooks"; import { DEFAULT_COMMUNITY_ID } from "../config"; import { Btn, Chip } from "../ui"; import { filterLeaderboardRows } from "../lib/internal-stats-presentation"; import { internalMatchDetailPath, internalMatchGamePath, } from "../lib/internal-match-routes"; import { LANE_LABELS } from "../lib/riot-history"; import { StatsEvent, StatsEventJump, } from "../components/internal-stats/StatsEvent"; import { StatsLeaderboard } from "../components/internal-stats/StatsLeaderboard"; import { StatsSummary } from "../components/internal-stats/StatsSummary"; import { StatsFeedback, StatsLaneSelect, StatsSeasonControls, } from "../components/internal-stats/StatsShared"; import { parseStatsLane, statsRoot, statsTarget, statsPeriod, useStatsRestoration, } from "../components/internal-stats/stats-navigation"; import { STATS_SORTS, parseStatsSort, sortStatsRows, } from "../components/internal-stats/stats-model"; type Changes = Record; export default function CommunityInternalStatsView() { const { cid } = useParams(); const communityId = cid ?? DEFAULT_COMMUNITY_ID; const location = useLocation(); const [params, setParams] = useSearchParams(); const ranking = ["ranking", "players"].includes(params.get("view") ?? ""); const seasonId = params.get("seasonId") || "current"; const lane = parseStatsLane(params.get("lane")); const sort = parseStatsSort(params.get("sort")); const direction = params.get("dir") === "asc" ? "asc" : "desc"; const minimum = ["0", "5", "10", "20"].includes(params.get("min") ?? "") ? Number(params.get("min")) : 5; const queryKey = ranking ? "playerQ" : "matchQ"; const query = params.get(queryKey) ?? params.get("q") ?? ""; const keyword = useDeferredValue(query.trim().slice(0, 100)); const format = params.get("format"), playerId = params.get("player"); const from = params.get("from") ?? "", to = params.get("to") ?? ""; const invalidDates = Boolean(from && to && from > to); const champion = Number(params.get("championId")); const championId = Number.isInteger(champion) && champion > 0 ? champion : undefined; const scope = { seasonId, championId }; const community = useCommunity(communityId); const seasons = useCommunityStatsSeasons(communityId); const insights = useTeamInsights({ seasonId }, communityId); const leaderboard = useCommunityLeaderboard( { ...scope, lane, query: ranking ? keyword : undefined }, communityId, ranking, ); const matchesQuery = useCommunityInternalStatsMatches( { ...scope, query: keyword, format: format === "pair" || format === "tournament" ? format : undefined, playerId: playerId ?? undefined, from: from || undefined, to: to || undefined, limit: 4, }, communityId, !ranking && !invalidDates, ); const { data: manifest } = useDdragonManifest(); const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; const pageCount = matchesQuery.data?.pages.length ?? 0; const requestedPages = Math.max( 1, Math.min(30, Number(params.get("pages")) || 1), ); const { fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError, } = matchesQuery; useEffect(() => { if ( !ranking && pageCount > 0 && pageCount < requestedPages && hasNextPage && !isFetchingNextPage && !isFetchNextPageError ) void fetchNextPage(); }, [ ranking, pageCount, requestedPages, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage, ]); const season = insights.data?.season ?? leaderboard.data?.season ?? matchesQuery.data?.pages[0]?.season; const sortedRows = sortStatsRows( leaderboard.data?.rows ?? [], sort, minimum, direction, ); const visibleRows = filterLeaderboardRows( sortedRows, keyword, leaderboard.data?.matchedUserIds, ).filter((row) => params.get("qualified") !== "1" || row.games >= minimum); const current = location.pathname + location.search, root = statsRoot(communityId); const playerHref = (id: string) => statsTarget(`${root}/players/${id}`, params, current); const eventHref = (id: string) => statsTarget(internalMatchDetailPath(communityId, id), params, current); const gameHref = (id: string, number: number) => statsTarget( internalMatchGamePath(communityId, id, number), params, current, ); useStatsRestoration( ranking ? !leaderboard.isPending : !matchesQuery.isPending && (pageCount >= requestedPages || !hasNextPage), ); function update(changes: Changes, replace = false) { const next = new URLSearchParams(params); Object.entries(changes).forEach(([key, value]) => value ? next.set(key, value) : next.delete(key), ); setParams(next, { replace, preventScrollReset: true }); } function changeView(next: boolean) { update({ view: next ? "ranking" : null, [queryKey]: query, q: null }); } function resetFilters() { update( ranking ? { playerQ: null, q: null, lane: null, min: null, sort: null, dir: null, qualified: null, championId: null, } : { matchQ: null, q: null, format: null, from: null, to: null, player: null, playerName: null, pages: null, championId: null, }, ); } function participationHref(id: string) { const next = new URLSearchParams(params); ["view", "q", "matchQ", "format", "pages"].forEach((k) => next.delete(k)); next.set("player", id); next.set( "playerName", sortedRows.find((row) => row.userId === id)?.summonerName ?? "선택한 선수", ); return `${root}?${next}`; } const active: Array<{ text: string; clear: Changes }> = [ ...(query ? [{ text: `검색: ${query}`, clear: { [queryKey]: null, q: null } }] : []), ...(championId ? [{ text: "챔피언 필터", clear: { championId: null } }] : []), ...(ranking ? [ ...(lane ? [{ text: `${LANE_LABELS[lane]} 플레이`, clear: { lane: null } }] : []), ...(minimum !== 5 ? [ { text: minimum ? `최소 ${minimum}판` : "판수 제한 없음", clear: { min: null }, }, ] : []), ] : [ ...(format ? [ { text: format === "pair" ? "두 팀 내전" : "대회", clear: { format: null }, }, ] : []), ...(from || to ? [ { text: `${from || "처음"} ~ ${to || "마지막"}`, clear: { from: null, to: null }, }, ] : []), ...(playerId ? [ { text: `${params.get("playerName") ?? "선택한 선수"} 참가 내전`, clear: { player: null, playerName: null }, }, ] : []), ]), ]; const staleLane = lane && leaderboard.data && leaderboard.data.lane !== lane; const reset = 검색 조건 초기화; return (

{community.data?.name ?? "COMMUNITY"}

내전 전적

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

update({ seasonId: value, pages: null })} />
{insights.data ? ( statsTarget( highlight.isSingleGame && highlight.internalMatchId && highlight.gameNumber ? internalMatchGamePath( communityId, highlight.internalMatchId, highlight.gameNumber, ) : `${root}/players/${highlight.userId}`, new URLSearchParams({ seasonId }), current, ) } /> ) : ( void insights.refetch()}>다시 시도 ) } /> )}
{[false, true].map((isRank) => ( ))} {season?.label} · {statsPeriod(season)}
{ranking ? ( <> update({ lane: value })} /> ) : ( <>
{[ ["", "전체"], ["pair", "두 팀 내전"], ["tournament", "대회"], ].map(([value, label]) => ( update({ format: value, pages: null })} > {label} ))}
—
)}
{active.length > 0 && (
적용 조건 {active.map((item) => ( ))}
)} {ranking ? ( <>

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

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

{leaderboard.isPending ? ( ) : leaderboard.isError || staleLane ? ( void leaderboard.refetch()}> 다시 시도 } > 선택한 시즌과 검색 조건은 유지됩니다. ) : visibleRows.length ? ( update({ sort: key, dir: sort === key && direction === "desc" ? "asc" : "desc", }) } playerHref={playerHref} participationHref={participationHref} manifest={manifest} /> ) : ( 검색어, 포지션 또는 최소 판수를 바꿔 보세요. )} ) : invalidDates ? ( 종료일을 시작일과 같거나 이후 날짜로 선택해 주세요. ) : matchesQuery.isPending ? ( ) : matchesQuery.isError && !matches.length ? ( void matchesQuery.refetch()}>다시 시도 } > 선택한 시즌과 검색 조건은 유지됩니다. ) : ( <>

경기 기록 {matches.length}회

{matches.length}개 표시 {hasNextPage ? " · 이전 기록 더 있음" : " · 조회 완료"}

{matches.length ? (
{matches.map((match) => ( gameHref(match.matchId, number)} /> ))} {matchesQuery.isFetchNextPageError && ( void fetchNextPage()}> 다시 시도 } /> )} {hasNextPage && ( )}
) : ( 날짜나 검색어를 바꾸면 다른 내전을 찾을 수 있습니다. )} )}
); }