import { lazy, Suspense, useEffect, useMemo, useRef, useState, type FormEvent, type KeyboardEvent, } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { AlertTriangle, SendHorizontal } from 'lucide-react'; import { Link, useLocation, useNavigate, useParams } from 'react-router'; import { useAuction, useAuctionHistory, useDdragonManifest, useMatch, useMe, useResetAuction, useUndoAuction, useUserHistoryProfile, } from '../api/hooks'; import { mapApiAuctionToAuctionState, type AuctionPlayerView, type AuctionStateView, } from '../api/mappers'; import { useAuctionSocket } from '../api/useAuctionSocket'; import { DEFAULT_COMMUNITY_ID, setDevCaptainTeamIndex, useDevCaptainTeamIndex, } from '../config'; import { ApiError } from '../lib/api'; import { championDisplayName, championIconUrl, profileIconUrl, } from '../lib/ddragon'; import { positionIcon, positionLabel, teamIndexColorClasses, teamIndexLabel, } from '../lib/league'; import { RankBadge, ResponsiveTierLabel } from '../components/RankBadge'; import type { ApiAuction, ApiAuctionChatMessage, ApiRiotLaneStats, ApiUser, Position, } from '../api/types'; const TierHistoryChart = lazy(() => import('../components/TierHistoryChart')); type CaptainRole = { teamIndex: number; }; function formatPoints(value: number) { return value.toLocaleString(); } function relativeTime(dateLike: string) { const seconds = Math.max( 0, Math.floor((Date.now() - new Date(dateLike).getTime()) / 1000), ); if (seconds < 60) return `${seconds}초 전`; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `${minutes}분 전`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours}시간 전`; return `${Math.floor(hours / 24)}일 전`; } function formatChatTime(dateLike: string) { return new Intl.DateTimeFormat('ko-KR', { hour: '2-digit', minute: '2-digit', }).format(new Date(dateLike)); } function resolveChatSenderLabel( currentUser: ApiUser | null, captainRole: CaptainRole | null, ) { const primaryRiotAccount = currentUser?.riotAccounts.find((entry) => entry.isPrimary) ?? currentUser?.riotAccounts[0]; if (primaryRiotAccount?.gameName) { return primaryRiotAccount.tagLine ? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}` : primaryRiotAccount.gameName; } if (currentUser?.kakaoTalkNickname) return currentUser.kakaoTalkNickname; if (currentUser?.discordNickname) return currentUser.discordNickname; if (captainRole) return `${teamIndexLabel(captainRole.teamIndex)} 팀장`; return '관전자'; } function isCurrentBidder( currentBidder: AuctionStateView['currentBidder'], team: Pick, ) { return currentBidder?.teamIndex === team.teamIndex; } function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) { if (!auction) return 0; return Date.parse(auction.updatedAt ?? auction.createdAt ?? '') || 0; } function pickLatestAuction( socketAuction: ApiAuction | null, queryAuction: ApiAuction | undefined, ) { if (!socketAuction) return queryAuction ?? null; if (!queryAuction) return socketAuction; return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction) ? queryAuction : socketAuction; } const AUCTION_MAX_TEAM_SIZE = 5; const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; const POSITION_TO_RIOT_LANE = { TOP: 'TOP', JGL: 'JUNGLE', MID: 'MIDDLE', ADC: 'BOTTOM', SUP: 'UTILITY', } as const; function PosBadge({ pos }: { pos: Position }) { return ( {positionLabel[pos]} ); } function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) { const pct = maxTimer > 0 ? (timer / maxTimer) * 100 : 0; const urgent = timer <= 5; return (
); } function getWinRate(stats: ApiRiotLaneStats) { return stats.games > 0 ? Math.round((stats.wins / stats.games) * 100) : 0; } function getWinRateClass(winRate: number) { if (winRate >= 55) return 'text-blue-400'; if (winRate >= 50) return 'text-base-content'; return 'text-red-400'; } function formatKdaRatio(stats: ApiRiotLaneStats) { if (stats.avgDeaths === 0) return 'Perfect'; return ((stats.avgKills + stats.avgAssists) / stats.avgDeaths).toFixed(2); } function RecentSoloStats({ player, }: { player: NonNullable; }) { const primaryStats = player.recentStats.primary; if (!primaryStats) { return (

최근 솔로랭크

최근 솔로랭크 기록이 없습니다
); } const primaryWinRate = getWinRate(primaryStats); const primaryKdaRatio = formatKdaRatio(primaryStats); return (

최근 솔로랭크

{positionLabel[player.mainPosition]} {player.recentStats.primarySource === 'overall' ? ( 전체 기준 ) : null}
{primaryWinRate}%
전적 {primaryStats.wins}W{' '} {primaryStats.losses}L
KDA {primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists} = 3 ? 'text-emerald-400' : 'text-base-content/50'}`} > ({primaryKdaRatio})
분당 CS {primaryStats.avgCsPerMin}
{LANE_ROWS.map((position) => { const laneStats = player.recentStats.byLane[POSITION_TO_RIOT_LANE[position]]; const isMainLane = position === player.mainPosition; return (
{positionLabel[position]} {laneStats && laneStats.games > 0 ? ( {laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/ {laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '} {laneStats.avgCsPerMin} CS/min ) : ( — )}
); })}
); } function TeamPanel({ team, isActive, isLeft, historyBackTo, }: { team: AuctionStateView['teams'][number]; isActive: boolean; isLeft: boolean; historyBackTo: string; }) { const { data: ddragon } = useDdragonManifest(); const tone = teamIndexColorClasses(team.teamIndex); const teamSize = team.members.length + 1; const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE; return (
{teamIndexLabel(team.teamIndex, team.name)} 팀장: {team.captainName}
{formatPoints(team.points)}P
팀장 포함 {teamSize}/{AUCTION_MAX_TEAM_SIZE} {isFull && 정원 완료}
{team.members.length === 0 ? (
아직 멤버가 없습니다
) : ( team.members.map((member) => (
{member.summonerName}
{positionLabel[member.assignedPosition]} {member.cost}
)) )} {Array.from({ length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length), }).map((_, index) => (
—
))}
); } function PlayerSpotlight({ state, historyBackTo, }: { state: AuctionStateView; historyBackTo: string; }) { const { data: ddragon } = useDdragonManifest(); const player = state.currentPlayer; const historyProfileQuery = useUserHistoryProfile( player?.userId, DEFAULT_COMMUNITY_ID, Boolean(player && player.tierHistory.length === 0), ); if (!player) return null; const tierHistory = player.tierHistory.length > 0 ? player.tierHistory : (historyProfileQuery.data?.tierHistory ?? []); return (
{player.summonerName} #{player.tag}
{' '} {positionLabel[player.subPosition]}
{tierHistory.length > 0 && ( } > )}

숙련도 높은 챔피언

{player.masteries.length > 0 ? ( player.masteries.map((mastery) => { const iconUrl = championIconUrl(ddragon, mastery.championId); const displayName = championDisplayName(ddragon, mastery.championId) ?? String(mastery.championId); return (
{iconUrl ? ( {displayName} ) : null}
{displayName}
Lv.{mastery.level} · {(mastery.points / 1000).toFixed(0)}K
); }) ) : (
숙련도 데이터가 없습니다.
)}
{(state.phase === 'bidding' || state.phase === 'sold') && (
{state.phase === 'sold' ? '낙찰가' : '현재 입찰가'}
{state.currentBidder && ( {teamIndexLabel(state.currentBidder.teamIndex)} )} {state.currentBid > 0 ? formatPoints(state.currentBid) : '—'}
)} {state.phase === 'passed' && (
유찰{' '} {state.auctionRound === 1 ? '— 마지막에 다시 등장합니다' : '— 강제 배정 대상'}
)}
); } function BidControls({ state, captainRole, onBid, }: { state: AuctionStateView; captainRole: CaptainRole | null; onBid: (teamIndex: number, amount: number) => void; }) { const [bidAmount, setBidAmount] = useState(100); const minBid = state.currentBid + 10; const activeTeam = captainRole ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) : null; const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; useEffect(() => { setBidAmount(Math.max(minBid, Math.ceil(minBid / 10) * 10)); }, [state.currentBid, minBid]); if (state.phase !== 'bidding') return null; if (!activeTeam) { return (
관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다.
); } const presets = [50, 100, 150, 200, 300, 500]; return (
{presets.map((preset) => ( ))} setBidAmount(Math.max(minBid, Number(event.target.value))) } min={minBid} disabled={isActiveTeamFull} className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30" />
); } function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { const endRef = useRef(null); useEffect(() => { endRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [bids.length]); if (bids.length === 0) return null; return (
입찰 기록
{bids.map((bid, index) => (
{teamIndexLabel(bid.teamIndex)} → {formatPoints(bid.amount)}P
))}
); } export default function AuctionPage() { const { id } = useParams(); const location = useLocation(); const navigate = useNavigate(); const queryClient = useQueryClient(); const meQuery = useMe(); const currentUser = meQuery.data?.memberships.find( (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, )?.user ?? null; const canManageAuction = import.meta.env.DEV || currentUser?.role === 'owner' || currentUser?.role === 'admin'; const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, { refetchInterval: 5000, }); const historyQuery = useAuctionHistory(id, DEFAULT_COMMUNITY_ID, { enabled: canManageAuction, refetchInterval: 3000, }); const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID); const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID); const socket = useAuctionSocket(id); const captainTeamIndex = useDevCaptainTeamIndex(); const [now, setNow] = useState(() => Date.now()); const [assignedPosition, setAssignedPosition] = useState('MID'); const [showCancelModal, setShowCancelModal] = useState(false); const [cancelConfirmText, setCancelConfirmText] = useState(''); const cancelConfirmInputRef = useRef(null); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; const canConfirmAuctionCancel = cancelConfirmText.trim() === '예'; async function invalidateAuctionData() { if (!id) return; await Promise.all([ queryClient.invalidateQueries({ queryKey: ['auction', DEFAULT_COMMUNITY_ID, id], }), queryClient.invalidateQueries({ queryKey: ['auction-history', DEFAULT_COMMUNITY_ID, id], }), queryClient.invalidateQueries({ queryKey: ['match', DEFAULT_COMMUNITY_ID, id], }), ]); } useEffect(() => { const timer = window.setInterval(() => setNow(Date.now()), 1000); return () => window.clearInterval(timer); }, []); useEffect(() => { if (!showCancelModal) return; cancelConfirmInputRef.current?.focus(); }, [showCancelModal]); const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); const auctionState = liveAuction && matchQuery.data ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) : null; const availableTeamIndexes = useMemo(() => { const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); return [...indexes].sort((left, right) => left - right); }, [auctionState?.teams]); const captainRole: CaptainRole | null = captainTeamIndex === null ? null : { teamIndex: captainTeamIndex, }; const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole); useEffect(() => { if (auctionState?.currentPlayer) { setAssignedPosition(auctionState.currentPlayer.mainPosition); } }, [auctionState?.currentPlayer?.id]); useEffect(() => { if (availableTeamIndexes.length === 0) return; if (captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex)) { setDevCaptainTeamIndex(availableTeamIndexes[0]); } }, [availableTeamIndexes, captainTeamIndex]); useEffect(() => { if (!socket.resetAt || !id) return; void invalidateAuctionData().finally(() => { navigate(`/match/${id}`, { replace: true }); }); }, [id, navigate, socket.resetAt]); if (!DEFAULT_COMMUNITY_ID) { return (
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
); } if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) { return (
경매를 연결하는 중...
); } if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) { return (

경매가 아직 시작되지 않았습니다

내전 상세로 돌아가기
); } if (!auctionState || !matchQuery.data) { return (
경매 상태를 불러오지 못했습니다.
); } const phaseLabel: Record = { waiting: '경매 준비 중...', presenting: '다음 선수 등장', bidding: '입찰 진행 중', sold: '낙찰!', passed: '유찰 — 다음 선수로', complete: '경매 완료', }; const errorMessage = socket.error ?? (auctionQuery.error instanceof Error ? auctionQuery.error.message : null); function handleUndo(sequence: number) { if (!id) return; if (!window.confirm(`${sequence}번 액션 직전으로 되돌릴까요?`)) return; undoMutation.mutate( { matchId: id, sequence }, { onSuccess: async () => { await Promise.all([ queryClient.invalidateQueries({ queryKey: ['auction', DEFAULT_COMMUNITY_ID, id], }), queryClient.invalidateQueries({ queryKey: ['auction-history', DEFAULT_COMMUNITY_ID, id], }), queryClient.invalidateQueries({ queryKey: ['match', DEFAULT_COMMUNITY_ID, id], }), ]); }, }, ); } function handleResetAuction() { if (!id || !canConfirmAuctionCancel) return; resetAuctionMutation.mutate( { matchId: id }, { onSuccess: async () => { setShowCancelModal(false); setCancelConfirmText(''); await invalidateAuctionData(); navigate(`/match/${id}`, { replace: true }); }, }, ); } const undoPanel = canManageAuction ? (
되돌리기 (Undo)
{historyQuery.data?.length ? ( historyQuery.data.map((entry) => ( )) ) : (
기록이 없습니다
)}
) : null; return (
내전 상세로 {errorMessage && (
{errorMessage}
)} {undoMutation.error instanceof Error && (
{undoMutation.error.message}
)} {resetAuctionMutation.error instanceof Error && (
{resetAuctionMutation.error.message}
)}

경매 팀빌딩

{Math.min(auctionState.currentPlayerIndex + 1, Math.max(auctionState.totalPlayers, 1))} /{' '} {auctionState.totalPlayers} 선수

{phaseLabel[auctionState.phase]} {auctionState.phase === 'bidding' && ( {auctionState.timer}s )}
소켓: {socket.connectionStatus} {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */}
{auctionState.phase === 'bidding' && ( )}
{auctionState.teams.map((team) => ( ))}
{auctionState.phase === 'complete' ? ( <>
경매 완료
모든 선수가 팀에 배정되었습니다.
결과 확인
{undoPanel} ) : ( <> {auctionState.phase === 'sold' && auctionState.currentBidder && (
{teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰 {' '}— {formatPoints(auctionState.currentBid)}P
)} socket.placeBid({ teamIndex, amount }) } /> {canManageAuction && (
Auction Controls
{auctionState.phase === 'presenting' && ( )} {auctionState.phase === 'bidding' && (
)} {(auctionState.phase === 'sold' || auctionState.phase === 'passed') && ( )}

경매 데이터와 진행 기록을 삭제하고 내전을 모집 상태로 되돌립니다.

)} {undoPanel} )}
socket.sendChatMessage({ displayName: chatSenderLabel, message, }) } className="h-[420px]" />
{showCancelModal && (

경매 진행 취소

정말 경매를 취소하고 모집 상태로 되돌리시겠습니까? 경매 데이터, 입찰 기록, 팀 배정 정보가 삭제됩니다.

setCancelConfirmText(event.target.value)} onKeyDown={(event) => { if (event.key === 'Escape') { setShowCancelModal(false); setCancelConfirmText(''); } if (event.key === 'Enter' && canConfirmAuctionCancel) { handleResetAuction(); } }} className="mt-2 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm text-base-content outline-none transition-colors focus:border-red-400/60" placeholder="예" />
)}
); } type PoolTab = 'waiting' | 'passed'; // 풀 리스트는 경매 등장 순서를 노출하면 안 되므로 게임명 알파벳 순으로 독립 정렬한다. const POOL_COLLATOR = new Intl.Collator(['ko', 'en'], { sensitivity: 'base' }); function comparePoolPlayers(a: AuctionPlayerView, b: AuctionPlayerView) { return POOL_COLLATOR.compare(a.summonerName, b.summonerName); } function PoolPanel({ state }: { state: AuctionStateView }) { const { data: ddragon } = useDdragonManifest(); const [tab, setTab] = useState('waiting'); const { waitingPool, passedPool } = useMemo(() => { const captainIds = new Set(state.teams.map((team) => team.captainUserId)); const memberIds = new Set( state.teams.flatMap((team) => team.members.map((member) => member.userId), ), ); const passedIds = new Set( state.passedQueue.map((player) => player.userId), ); const currentId = state.currentPlayer?.userId; const startIndex = state.phase === 'complete' ? state.totalPlayers : state.currentPlayerIndex + 1; const waiting = state.auctionOrder .slice(startIndex) .filter( (player) => !captainIds.has(player.userId) && !memberIds.has(player.userId) && !passedIds.has(player.userId) && player.userId !== currentId, ) .sort(comparePoolPlayers); const passed = [...state.passedQueue].sort(comparePoolPlayers); return { waitingPool: waiting, passedPool: passed }; }, [state]); const activePool = tab === 'waiting' ? waitingPool : passedPool; return (
setTab('waiting')} /> setTab('passed')} />
{activePool.length === 0 ? (
{tab === 'waiting' ? '대기 중인 유저가 없습니다' : '유찰된 유저가 없습니다'}
) : (
    {activePool.map((player) => ( ))}
)}
); } function PoolTabButton({ label, count, active, onClick, }: { label: string; count: number; active: boolean; onClick: () => void; }) { return ( ); } function PoolListItem({ player, ddragon, showPassCount, }: { player: AuctionPlayerView; ddragon: ReturnType['data']; showPassCount: boolean; }) { return (
  • {player.summonerName} {showPassCount && player.passCount > 0 ? ( {player.passCount}회 유찰 ) : null}
  • ); } function ChatPanel({ messages, connectionStatus, senderLabel, onSend, className = '', }: { messages: ApiAuctionChatMessage[]; connectionStatus: ReturnType['connectionStatus']; senderLabel: string; onSend: (message: string) => void; className?: string; }) { const [draft, setDraft] = useState(''); const messagesEndRef = useRef(null); const trimmedDraft = draft.trim(); const isConnected = connectionStatus === 'connected'; const canSend = isConnected && trimmedDraft.length > 0; useEffect(() => { messagesEndRef.current?.scrollIntoView({ block: 'end' }); }, [messages.length]); function handleSubmit(event: FormEvent) { event.preventDefault(); if (!canSend) return; onSend(trimmedDraft); setDraft(''); } function handleKeyDown(event: KeyboardEvent) { if (event.key !== 'Enter' || event.shiftKey) return; event.preventDefault(); if (!canSend) return; onSend(trimmedDraft); setDraft(''); } const statusLabel = connectionStatus === 'connected' ? '실시간' : connectionStatus === 'connecting' ? '연결 중' : '오프라인'; return (
    채팅
    {statusLabel}
    {messages.length === 0 ? (
    아직 메시지가 없습니다
    ) : (
      {messages.map((message) => (
    1. {message.displayName}

      {message.message}

    2. ))}
    )}
    {senderLabel} {draft.length}/300