import { useEffect, useState, type CSSProperties, type ReactNode } from 'react';
import type {
MatchDetailResponse,
MatchEventType,
MatchSummaryResponse,
} from '@lolympus/contracts';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Link, useSearchParams } from 'react-router';
import {
useCommunityLeaderboard,
useDdragonManifest,
useMatches,
useMatchesPage,
} from '../api/hooks';
import nextMatchArtwork from '../assets/next-match-hero.webp';
import pixelMedal from '../assets/pixel-medal-first.svg';
import HomeHallOfFame from '../components/HomeHallOfFame';
import { championIconUrl, profileIconUrl } from '../lib/ddragon';
import { rankLeaderboardByLane } from '../lib/internal-stats-presentation';
import { MATCH_EVENT_LABEL } from '../lib/match-event-type';
import { LANE_LABELS } from '../lib/riot-history';
import { mapIdToLabel } from '../api/mappers';
import { DEFAULT_COMMUNITY_ID } from '../config';
import {
Button,
EmptyNote,
ErrorNote,
PanelHeader,
PlainPage,
Skeleton,
pageWidthClass,
} from '../ui';
import {
getHistoryMatchTitle,
getHomeMatchEnrollment,
getHomeMatchSchedule,
getNextMatchBanner,
getMatchStageLabel,
} from './home-match-presentation';
const UPCOMING_MATCH_LIST_LIMIT = 4;
const MATCH_ARCHIVE_PAGE_SIZE = 10;
const HOME_HISTORY_LIMIT = 4;
const HOME_RANKING_LIMIT = 5;
const DEFAULT_MAP_ID = 11;
const SCHEDULE_LIST_CLASS = 'divide-y divide-line border-y border-line';
const SCHEDULE_ROW_CLASS =
'grid grid-cols-[minmax(0,1fr)_auto] gap-x-3 gap-y-2 px-2 py-3.5 md:grid-cols-[7.5rem_minmax(0,1fr)_auto] md:items-center md:gap-4';
const RANKING_COLUMNS_CLASS =
'grid grid-cols-[1.5rem_minmax(0,1fr)_3rem] items-center gap-3 px-3';
const NEXT_MATCH_CONTENT_CLASS =
'flex min-h-[16rem] items-center py-8 md:min-h-[clamp(22rem,29vw,30rem)] md:py-12';
/** 순위 카드의 슬라이드 순서. undefined는 종합 순위. */
const RANKING_SLIDES = [
undefined,
'TOP',
'JUNGLE',
'MIDDLE',
'BOTTOM',
'UTILITY',
] as const;
const RANKING_SLIDE_INTERVAL_MS = 5000;
const GENERIC_MATCH_NAME = /^(?:정기\s*)?내전$/u;
const DECISION_LABELS = {
walkover: '부전승',
forfeit: '기권승',
administrative: '판정승',
draw: '무승부',
} as const;
function NextMatch({ match }: { match: MatchDetailResponse }) {
const schedule = getHomeMatchSchedule(match.scheduledAt);
const { title, status, capacity, canApply } = getNextMatchBanner(match);
return (
다음 내전
{title}
{schedule ? (
) : '일정 미정'}
{status}
{' · '}
{capacity}
{match.mapId !== DEFAULT_MAP_ID && (
<> · {mapIdToLabel(match.mapId)}>
)}
);
}
function NextMatchSkeleton() {
return (
);
}
function UpcomingMatchesSkeleton({ title, limit }: { title: string; limit: number }) {
return (
);
}
function UpcomingMatches({
matches,
title = '이어지는 내전',
actions,
footer,
}: {
matches: MatchDetailResponse[];
title?: string;
actions?: ReactNode;
footer?: ReactNode;
}) {
return (
{matches.map((match) => (
-
))}
{matches.length === 0 && (
)}
{footer}
);
}
function ScheduleMatchRow({ match }: { match: MatchDetailResponse }) {
const { capacity, label } = getHomeMatchEnrollment(match);
return (
}
/>
);
}
function ScheduleStatus({
match,
label = getMatchStageLabel(match),
}: {
match: Pick;
label?: string;
}) {
const stage = match.eventProgress?.stage ?? match.status;
const statusColor = stage === 'in-progress'
? 'text-leaf'
: stage === 'auction'
? 'text-gold'
: 'text-content-muted';
return (
{label}
);
}
function ScheduleRow({
href,
scheduledAt,
title,
meta,
result,
resultBelowOnMobile = false,
}: {
href: string;
scheduledAt: string;
title: string;
meta: ReactNode;
result: ReactNode;
resultBelowOnMobile?: boolean;
}) {
const schedule = getHomeMatchSchedule(scheduledAt);
return (
{result}
);
}
function HistoryResult({ match }: { match: MatchSummaryResponse }) {
const result = match.historyResult;
const teamLabelClass = 'min-w-0 text-content-muted [overflow-wrap:anywhere]';
if (match.status === 'finished' && result) {
switch (result.type) {
case 'score': {
const label = result.winnerTeamName
? `${result.winnerTeamName} 승`
: undefined;
return (
{result.teamAWins}:{result.teamBWins}
{label && (
{label}
)}
);
}
case 'winners': {
const label = result.teamNames.join(', ');
return (
{result.teamNames.length > 1 ? '공동 1위' : '우승'}
{label}
);
}
case 'decision': {
return (
{DECISION_LABELS[result.decision]}
{result.winnerTeamName && (
{result.winnerTeamName}
)}
);
}
}
}
if (match.status === 'team-built' || match.status === 'in-progress') {
return ;
}
return (
{getMatchStageLabel(match)}
);
}
function ScheduleRowsSkeleton({
limit,
resultBelowOnMobile = false,
}: {
limit: number;
resultBelowOnMobile?: boolean;
}) {
return (
{Array.from({ length: limit }, (_, index) => (
-
))}
);
}
function HistoryRecords({
matches,
eventLabel,
}: {
matches: MatchSummaryResponse[];
eventLabel: string;
}) {
if (matches.length === 0) {
return ;
}
const rows = matches.map((match) => {
const schedule = getHomeMatchSchedule(match.scheduledAt);
return {
match,
title: getHistoryMatchTitle(match.title, schedule),
href: `/match/${match._id}`,
map:
match.mapId === DEFAULT_MAP_ID ? undefined : mapIdToLabel(match.mapId),
};
});
return (
{rows.map(({ match, title, href, map }) => (
-
참가 {match.participants.length}명{map && <> · {map}>}>}
result={}
resultBelowOnMobile
/>
))}
);
}
function RecentMatchResults({ matches }: { matches: MatchSummaryResponse[] }) {
if (matches.length === 0) {
return ;
}
return (
);
}
const RECENT_RESULT_ROW_CLASS =
'grid gap-2 px-2 py-3.5 md:grid-cols-[7.5rem_minmax(0,1fr)_auto] md:items-center md:gap-4';
const POSITION_ORDER = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
interface WinnerTeamSummary {
name: string;
members: MatchSummaryResponse['participants'];
}
/** 결과에 담긴 우승팀 이름을 팀 구성과 맞춰 멤버를 포지션 순으로 돌려준다. */
function getWinnerTeams(match: MatchSummaryResponse): WinnerTeamSummary[] {
const result = match.historyResult;
if (match.status !== 'finished' || !result) return [];
const names =
result.type === 'winners'
? result.teamNames
: result.winnerTeamName
? [result.winnerTeamName]
: [];
const participants = new Map(
match.participants.map((participant) => [participant.userId, participant]),
);
return names.map((name) => {
// 같은 이름의 팀이 여럿이면 누가 우승했는지 알 수 없으므로 멤버를 비운다.
const candidates = match.teams.filter(
(team) => (team.name.trim() || `${team.teamIndex}팀`) === name,
);
const members =
candidates.length === 1
? [...candidates[0].members]
.sort(
(a, b) =>
POSITION_ORDER.indexOf(a.assignedPosition) -
POSITION_ORDER.indexOf(b.assignedPosition),
)
.flatMap((member) => {
const participant = participants.get(member.userId);
return participant ? [participant] : [];
})
: [];
return { name, members };
});
}
function WinnerTeam({ team, label }: { team: WinnerTeamSummary; label: string }) {
const { data: manifest } = useDdragonManifest();
const memberNames = team.members
.map((member) => member.gameName)
.filter(Boolean)
.join(' · ');
return (
{label}
{team.name}
{team.members.length > 0 && (
{team.members.map((member) => (
))}
{memberNames && (
{memberNames}
)}
)}
);
}
function RecentMatchResultsSkeleton({ limit }: { limit: number }) {
return (
{Array.from({ length: limit }, (_, index) => (
{Array.from({ length: 5 }, (_, memberIndex) => (
))}
))}
);
}
const RANK_BADGE_CLASS = [
'bg-gold text-accent-content',
'bg-sunken-strong text-content',
'bg-gold-tint text-gold',
] as const;
function RankingSkeleton() {
return (
{Array.from({ length: HOME_RANKING_LIMIT }, (_, index) => (
))}
);
}
/** 현재 시즌 순위표의 앞부분. 전적 화면과 같은 집계를 그대로 보여준다. */
function RankingPreview({ statsPath }: { statsPath: string }) {
const leaderboardQuery = useCommunityLeaderboard({ seasonId: 'current' });
const { data: manifest } = useDdragonManifest();
const [slide, setSlide] = useState(0);
const [direction, setDirection] = useState<1 | -1>(1);
const [paused, setPaused] = useState(false);
const [touchStartX, setTouchStartX] = useState();
const lane = RANKING_SLIDES[slide];
const allRows = leaderboardQuery.data?.rows ?? [];
const rows = (lane ? rankLeaderboardByLane(allRows, lane) : allRows).slice(
0,
HOME_RANKING_LIMIT,
);
const label = lane ? LANE_LABELS[lane] : '종합';
const move = (step: 1 | -1) => {
setDirection(step);
setSlide(
(current) => (current + step + RANKING_SLIDES.length) % RANKING_SLIDES.length,
);
};
// key가 바뀌면 목록이 새로 붙으면서 넘긴 방향에서 들어오는 애니메이션이 다시 돈다.
const slideStyle = {
'--lts-rank-slide-from': `${direction * 1.5}rem`,
} as CSSProperties;
// 읽거나 누르려는 동안에는 멈추고, 직접 넘기면 그 슬라이드부터 다시 센다.
useEffect(() => {
if (leaderboardQuery.isPending || paused || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
return;
}
const timer = window.setTimeout(() => move(1), RANKING_SLIDE_INTERVAL_MS);
return () => window.clearTimeout(timer);
}, [leaderboardQuery.isPending, paused, slide]);
return (
);
}
interface MatchPaginationProps {
label: string;
page: number;
pageCount: number;
total: number;
isFetching: boolean;
onPrevious: () => void;
onNext: () => void;
}
function MatchPagination({
label,
page,
pageCount,
total,
isFetching,
onPrevious,
onNext,
}: MatchPaginationProps) {
return (
);
}
export default function HomePage({ eventType }: { eventType?: MatchEventType }) {
const showArchive = eventType !== undefined;
const selectedEventType = eventType ?? 'inhouse';
const eventLabel = MATCH_EVENT_LABEL[selectedEventType];
const [timelineNow] = useState(() => new Date().toISOString());
const [searchParams, setSearchParams] = useSearchParams();
function getPage(key: 'page' | 'activePage') {
const page = Number(searchParams.get(key));
return showArchive && Number.isSafeInteger(page) && page > 0 ? page : 1;
}
const historyPage = getPage('page');
const activePage = getPage('activePage');
const historyLimit = showArchive ? MATCH_ARCHIVE_PAGE_SIZE : HOME_HISTORY_LIMIT;
const activeLimit = showArchive ? MATCH_ARCHIVE_PAGE_SIZE : UPCOMING_MATCH_LIST_LIMIT;
function setPage(key: 'page' | 'activePage', page: number) {
setSearchParams((previous) => {
const params = new URLSearchParams(previous);
if (page > 1) params.set(key, String(page));
else params.delete(key);
return params;
}, { preventScrollReset: true });
}
const upcomingMatchesQuery = useMatches({
eventType: selectedEventType,
view: 'upcoming',
asOf: timelineNow,
limit: UPCOMING_MATCH_LIST_LIMIT,
sort: 'asc',
});
const activeMatchesQuery = useMatchesPage({
eventType: selectedEventType,
view: 'active',
asOf: timelineNow,
limit: activeLimit,
page: activePage,
sort: 'desc',
});
const historyMatchesQuery = useMatchesPage({
eventType: selectedEventType,
view: 'history',
asOf: timelineNow,
limit: historyLimit,
page: historyPage,
sort: 'desc',
includeResults: true,
});
if (!DEFAULT_COMMUNITY_ID) {
return (
);
}
const allUpcomingMatches = upcomingMatchesQuery.data ?? [];
const [nextMatch, ...upcomingMatches] = allUpcomingMatches;
const bannerMatch = showArchive ? undefined : nextMatch;
const isBannerLoading = !showArchive && upcomingMatchesQuery.isPending;
const visibleUpcomingMatches = showArchive ? allUpcomingMatches : upcomingMatches;
const historyTotal = historyMatchesQuery.data?.total ?? 0;
const activeTotal = activeMatchesQuery.data?.total ?? 0;
const activePageCount = Math.max(
1,
Math.ceil(activeTotal / (activeMatchesQuery.data?.limit ?? activeLimit)),
);
const historyPageCount = Math.max(
1,
Math.ceil(historyTotal / (historyMatchesQuery.data?.limit ?? historyLimit)),
);
const isHistoryPageLoading =
historyMatchesQuery.isPending ||
(historyMatchesQuery.isFetching && historyMatchesQuery.isPlaceholderData);
const isActivePageLoading =
activeMatchesQuery.isPending ||
(activeMatchesQuery.isFetching && activeMatchesQuery.isPlaceholderData);
const hasHistoryError =
Boolean(historyMatchesQuery.error) && !historyMatchesQuery.data;
const statsPath = `/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`;
const UpcomingStatusHeading = showArchive ? 'p' : 'h1';
const contentSpacing = 'space-y-8 pb-10 md:pb-16';
const contentTopPadding = bannerMatch || isBannerLoading ? 'pt-10 md:pt-16' : 'pt-5 sm:pt-6';
const content = (
{showArchive && (
)}
{activeMatchesQuery.isError && !activeMatchesQuery.data ? (
void activeMatchesQuery.refetch()} />} />
) : isActivePageLoading ? (
) : activeMatchesQuery.data &&
(activeMatchesQuery.data.matches.length > 0 || activePage > 1) ? (
전체 일정
)}
footer={showArchive && (activePageCount > 1 || activePage > 1) && (
setPage('activePage', Math.min(activePage - 1, activePageCount))}
onNext={() => setPage('activePage', activePage + 1)}
/>
)}
/>
) : null}
{upcomingMatchesQuery.isPending ? (
) : upcomingMatchesQuery.isError && !upcomingMatchesQuery.data ? (
{eventLabel} 일정을 불러오지 못했습니다
) : !nextMatch ? (
예정된 {eventLabel}이 없습니다
) : null}
{visibleUpcomingMatches.length > 0 && (
)}
{showArchive ? '전적 검색' : '전체 내전 기록'}
}
/>
{isHistoryPageLoading ? (
<>
{showArchive ? '종료된 일정과 결과' : '최근 내전 결과'}를 불러오는 중
{showArchive ? (
) : (
)}
>
) : hasHistoryError ? (
void historyMatchesQuery.refetch()}
/>
}
/>
) : showArchive ? (
) : (
)}
{showArchive && !hasHistoryError && (historyTotal > 0 || historyPage > 1) && (
setPage('page', Math.min(historyPage - 1, historyPageCount))}
onNext={() => setPage('page', historyPage + 1)}
/>
)}
{!showArchive &&
}
);
return (
{isBannerLoading ? : bannerMatch && }
{content}
{!showArchive && (
)}
);
}