1073 lines
38 KiB
TypeScript
1073 lines
38 KiB
TypeScript
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
import { useQueryClient } from '@tanstack/react-query';
|
|
import { Link, useLocation, useParams } from 'react-router';
|
|
import {
|
|
useAuction,
|
|
useAuctionHistory,
|
|
useDdragonManifest,
|
|
useMatch,
|
|
useMe,
|
|
useUndoAuction,
|
|
} from '../api/hooks';
|
|
import {
|
|
mapApiAuctionToAuctionState,
|
|
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 type {
|
|
ApiAuction,
|
|
ApiRiotLaneStats,
|
|
ApiTierInfo,
|
|
Position,
|
|
} from '../api/types';
|
|
|
|
type CaptainRole = {
|
|
teamIndex: number;
|
|
};
|
|
|
|
const TIER_NAMES: Record<string, string> = {
|
|
IRON: '아이언',
|
|
BRONZE: '브론즈',
|
|
SILVER: '실버',
|
|
GOLD: '골드',
|
|
PLATINUM: '플래티넘',
|
|
EMERALD: '에메랄드',
|
|
DIAMOND: '다이아몬드',
|
|
MASTER: '마스터',
|
|
GRANDMASTER: '그랜드마스터',
|
|
CHALLENGER: '챌린저',
|
|
};
|
|
|
|
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 normalizeRank(rank: string | undefined) {
|
|
switch (rank) {
|
|
case 'I':
|
|
return '1';
|
|
case 'II':
|
|
return '2';
|
|
case 'III':
|
|
return '3';
|
|
case 'IV':
|
|
return '4';
|
|
default:
|
|
return rank;
|
|
}
|
|
}
|
|
|
|
function formatRankBadge(tier: ApiTierInfo | undefined) {
|
|
if (!tier) return 'U';
|
|
const tierInitial =
|
|
tier.tier === 'GRANDMASTER' ? 'GM' : tier.tier.slice(0, 1);
|
|
const rank = normalizeRank(tier.rank);
|
|
return rank ? `${tierInitial}${rank}` : tierInitial;
|
|
}
|
|
|
|
function formatRankDetail(tier: ApiTierInfo | undefined) {
|
|
if (!tier) return '랭크 정보 없음';
|
|
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
|
|
const rank = normalizeRank(tier.rank);
|
|
const label = rank ? `${tierName} ${rank}` : tierName;
|
|
return `${label} - ${tier.leaguePoints} LP`;
|
|
}
|
|
|
|
function rankBadgeClass(tier: ApiTierInfo | undefined) {
|
|
switch (tier?.tier) {
|
|
case 'CHALLENGER':
|
|
return 'border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200';
|
|
case 'GRANDMASTER':
|
|
return 'border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200';
|
|
case 'MASTER':
|
|
return 'border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200';
|
|
case 'DIAMOND':
|
|
return 'border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200';
|
|
case 'EMERALD':
|
|
return 'border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200';
|
|
case 'PLATINUM':
|
|
return 'border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200';
|
|
case 'GOLD':
|
|
return 'border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200';
|
|
case 'SILVER':
|
|
return 'border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200';
|
|
case 'BRONZE':
|
|
return 'border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200';
|
|
case 'IRON':
|
|
return 'border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300';
|
|
default:
|
|
return 'border-base-content/30 bg-transparent text-base-content/50';
|
|
}
|
|
}
|
|
|
|
function RankBadge({ tier }: { tier?: ApiTierInfo }) {
|
|
const tooltip = formatRankDetail(tier);
|
|
|
|
return (
|
|
<span className="tooltip tooltip-bottom" data-tip={tooltip}>
|
|
<span
|
|
className={`inline-flex h-[18px] min-w-[20px] shrink-0 items-center justify-center whitespace-nowrap rounded-[3px] border px-1 text-[10px] font-black leading-none ${rankBadgeClass(tier)}`}
|
|
aria-label={tooltip}
|
|
>
|
|
{formatRankBadge(tier)}
|
|
</span>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
function ResponsiveTierLabel({ tier }: { tier?: ApiTierInfo }) {
|
|
return (
|
|
<span className="inline-flex items-center gap-1.5 whitespace-nowrap">
|
|
<RankBadge tier={tier} />
|
|
<span className="hidden font-bold text-base-content/55 sm:inline">
|
|
{formatRankDetail(tier)}
|
|
</span>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
function isCurrentBidder(
|
|
currentBidder: AuctionStateView['currentBidder'],
|
|
team: Pick<AuctionStateView['teams'][number], 'teamIndex'>,
|
|
) {
|
|
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 (
|
|
<span className="inline-flex items-center gap-1.5 text-[11px] font-medium px-1.5 py-0.5 border border-primary/20 text-primary bg-primary/5">
|
|
<img src={positionIcon[pos]} alt="" className="w-3.5 h-3.5 object-contain" />
|
|
<span>{positionLabel[pos]}</span>
|
|
</span>
|
|
);
|
|
}
|
|
|
|
function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) {
|
|
const pct = maxTimer > 0 ? (timer / maxTimer) * 100 : 0;
|
|
const urgent = timer <= 5;
|
|
|
|
return (
|
|
<div className="w-full h-1.5 bg-base-content/5">
|
|
<div
|
|
className={`h-full transition-all duration-1000 linear ${urgent ? 'bg-red-500' : 'bg-primary'}`}
|
|
style={{ width: `${pct}%` }}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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<AuctionStateView['currentPlayer']>;
|
|
}) {
|
|
const primaryStats = player.recentStats.primary;
|
|
|
|
if (!primaryStats) {
|
|
return (
|
|
<div className="p-4">
|
|
<h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30 mb-2.5">
|
|
최근 솔로랭크
|
|
</h4>
|
|
<div className="rounded border border-dashed border-base-content/10 px-3 py-6 text-center text-[11px] text-base-content/25">
|
|
최근 솔로랭크 기록이 없습니다
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
const primaryWinRate = getWinRate(primaryStats);
|
|
const primaryKdaRatio = formatKdaRatio(primaryStats);
|
|
|
|
return (
|
|
<div className="p-4">
|
|
<div className="flex items-start justify-between gap-3 mb-3">
|
|
<div>
|
|
<h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
|
최근 솔로랭크
|
|
</h4>
|
|
<div className="mt-1 flex items-center gap-2">
|
|
<span className="text-[12px] font-semibold text-base-content">
|
|
{positionLabel[player.mainPosition]}
|
|
</span>
|
|
{player.recentStats.primarySource === 'overall' ? (
|
|
<span className="text-[10px] text-base-content/35">
|
|
전체 기준
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
<div
|
|
className={`text-sm font-bold tabular-nums ${getWinRateClass(primaryWinRate)}`}
|
|
>
|
|
{primaryWinRate}%
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<div className="flex items-baseline justify-between">
|
|
<span className="text-[11px] text-base-content/40">전적</span>
|
|
<span className="text-[12px] text-base-content/60 tabular-nums">
|
|
<span className="text-blue-400">{primaryStats.wins}W</span>{' '}
|
|
<span className="text-red-400">{primaryStats.losses}L</span>
|
|
</span>
|
|
</div>
|
|
<div className="flex items-baseline justify-between">
|
|
<span className="text-[11px] text-base-content/40">KDA</span>
|
|
<span className="text-[12px] text-base-content/60 tabular-nums">
|
|
{primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists}
|
|
<span
|
|
className={`ml-1 font-bold ${Number(primaryKdaRatio) >= 3 ? 'text-emerald-400' : 'text-base-content/50'}`}
|
|
>
|
|
({primaryKdaRatio})
|
|
</span>
|
|
</span>
|
|
</div>
|
|
<div className="flex items-baseline justify-between">
|
|
<span className="text-[11px] text-base-content/40">분당 CS</span>
|
|
<span className="text-[12px] text-base-content/60 tabular-nums">
|
|
{primaryStats.avgCsPerMin}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="mt-4 border-t border-base-content/8 pt-3 space-y-1.5">
|
|
{LANE_ROWS.map((position) => {
|
|
const laneStats =
|
|
player.recentStats.byLane[POSITION_TO_RIOT_LANE[position]];
|
|
const isMainLane = position === player.mainPosition;
|
|
|
|
return (
|
|
<div
|
|
key={position}
|
|
className={`flex items-center justify-between gap-3 text-[11px] ${isMainLane ? 'font-semibold text-base-content' : 'text-base-content/65'}`}
|
|
>
|
|
<span className={isMainLane ? 'text-base-content' : 'text-base-content/35'}>
|
|
{positionLabel[position]}
|
|
</span>
|
|
{laneStats && laneStats.games > 0 ? (
|
|
<span className="tabular-nums text-right">
|
|
{laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/
|
|
{laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '}
|
|
{laneStats.avgCsPerMin} CS/min
|
|
</span>
|
|
) : (
|
|
<span className="text-base-content/20">—</span>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<div
|
|
className={`border ${tone.border} bg-base-100 relative ${isActive ? 'ring-1 ring-primary/30' : ''}`}
|
|
>
|
|
<div
|
|
className={`absolute ${isLeft ? 'left-0' : 'right-0'} top-0 bottom-0 w-0.5 ${tone.bar}`}
|
|
/>
|
|
<div className={`${tone.bg} px-3 py-2 border-b ${tone.border}`}>
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<span className={`text-[11px] font-bold uppercase tracking-wide ${tone.text}`}>
|
|
{teamIndexLabel(team.teamIndex, team.name)}
|
|
</span>
|
|
<span className="text-[10px] text-base-content/30">
|
|
팀장: {team.captainName}
|
|
</span>
|
|
</div>
|
|
<span className="text-xs font-bold text-amber-400 tabular-nums">
|
|
{formatPoints(team.points)}P
|
|
</span>
|
|
</div>
|
|
<div className="mt-1 flex items-center justify-between text-[10px]">
|
|
<span className="text-base-content/25">
|
|
팀장 포함 {teamSize}/{AUCTION_MAX_TEAM_SIZE}
|
|
</span>
|
|
{isFull && <span className="font-bold text-amber-400">정원 완료</span>}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="divide-y divide-base-content/5">
|
|
{team.members.length === 0 ? (
|
|
<div className="px-3 py-6 text-center text-[11px] text-base-content/20">
|
|
아직 멤버가 없습니다
|
|
</div>
|
|
) : (
|
|
team.members.map((member) => (
|
|
<div
|
|
key={`${member.userId}-${member.assignedPosition}`}
|
|
className="px-3 py-1.5 flex items-center gap-2"
|
|
>
|
|
<Link
|
|
to={`/users/${member.userId}/history`}
|
|
state={{ backTo: historyBackTo }}
|
|
className="flex flex-1 min-w-0 items-center gap-1.5 group"
|
|
>
|
|
<div className="w-6 h-6 bg-base-content/10 overflow-hidden shrink-0">
|
|
<img
|
|
src={profileIconUrl(ddragon, member.profileIconId)}
|
|
alt=""
|
|
className="w-full h-full object-cover"
|
|
loading="lazy"
|
|
/>
|
|
</div>
|
|
<RankBadge tier={member.tier} />
|
|
<div className="flex-1 min-w-0">
|
|
<span className="text-[12px] font-medium text-base-content truncate block leading-tight group-hover:text-primary transition-colors">
|
|
{member.summonerName}
|
|
</span>
|
|
</div>
|
|
</Link>
|
|
<span className="shrink-0 text-[11px] font-semibold text-base-content/45">
|
|
{positionLabel[member.assignedPosition]}
|
|
</span>
|
|
<span className="text-[10px] text-amber-400/60 tabular-nums w-8 text-right">
|
|
{member.cost}
|
|
</span>
|
|
</div>
|
|
))
|
|
)}
|
|
|
|
{Array.from({
|
|
length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length),
|
|
}).map((_, index) => (
|
|
<div
|
|
key={`empty-${team.teamIndex}-${index}`}
|
|
className="px-3 py-1.5 h-[34px] flex items-center"
|
|
>
|
|
<div className="w-6 h-6 border border-dashed border-base-content/8 shrink-0" />
|
|
<span className="ml-2 text-[10px] text-base-content/10">—</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function PlayerSpotlight({
|
|
state,
|
|
historyBackTo,
|
|
}: {
|
|
state: AuctionStateView;
|
|
historyBackTo: string;
|
|
}) {
|
|
const { data: ddragon } = useDdragonManifest();
|
|
const player = state.currentPlayer;
|
|
if (!player) return null;
|
|
|
|
return (
|
|
<div className="border border-base-content/10 bg-base-100">
|
|
<div className="p-5 border-b border-base-content/8">
|
|
<div className="flex items-start gap-4">
|
|
<Link
|
|
to={`/users/${player.userId}/history`}
|
|
state={{ backTo: historyBackTo }}
|
|
className="w-16 h-16 bg-base-content/10 overflow-hidden shrink-0"
|
|
>
|
|
<img
|
|
src={profileIconUrl(ddragon, player.profileIconId)}
|
|
alt=""
|
|
className="w-full h-full object-cover"
|
|
/>
|
|
</Link>
|
|
<div className="flex-1">
|
|
<div className="flex items-center gap-2 mb-1">
|
|
<Link
|
|
to={`/users/${player.userId}/history`}
|
|
state={{ backTo: historyBackTo }}
|
|
className="text-lg font-bold text-base-content leading-tight hover:text-primary transition-colors"
|
|
>
|
|
{player.summonerName}
|
|
</Link>
|
|
<span className="text-[10px] text-base-content/25">
|
|
#{player.tag}
|
|
</span>
|
|
</div>
|
|
<div className="mb-2 text-[11px]">
|
|
<ResponsiveTierLabel tier={player.tier} />
|
|
</div>
|
|
<div className="flex items-center gap-1.5">
|
|
<PosBadge pos={player.mainPosition} />
|
|
<span className="inline-flex items-center gap-0.5 text-[11px] px-1.5 py-0.5 border border-base-content/8 text-base-content/35">
|
|
<img
|
|
src={positionIcon[player.subPosition]}
|
|
alt=""
|
|
className="w-3.5 h-3.5 object-contain inline"
|
|
/>{' '}
|
|
{positionLabel[player.subPosition]}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 divide-x divide-base-content/5">
|
|
<div className="p-4">
|
|
<h4 className="text-[10px] font-bold uppercase tracking-wider text-base-content/30 mb-2.5">
|
|
숙련도 높은 챔피언
|
|
</h4>
|
|
<div className="space-y-2">
|
|
{player.masteries.length > 0 ? (
|
|
player.masteries.map((mastery) => {
|
|
const iconUrl = championIconUrl(ddragon, mastery.championId);
|
|
const displayName =
|
|
championDisplayName(ddragon, mastery.championId) ??
|
|
String(mastery.championId);
|
|
return (
|
|
<div key={mastery.championId} className="flex items-center gap-2">
|
|
<div className="w-7 h-7 bg-base-content/10 overflow-hidden shrink-0">
|
|
{iconUrl ? (
|
|
<img
|
|
src={iconUrl}
|
|
alt={displayName}
|
|
className="w-full h-full object-cover"
|
|
loading="lazy"
|
|
/>
|
|
) : null}
|
|
</div>
|
|
<div className="flex-1 min-w-0">
|
|
<div className="text-[12px] font-medium text-base-content truncate">
|
|
{displayName}
|
|
</div>
|
|
<div className="text-[10px] text-base-content/25">
|
|
Lv.{mastery.level} · {(mastery.points / 1000).toFixed(0)}K
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})
|
|
) : (
|
|
<div className="text-[11px] text-base-content/25">
|
|
숙련도 데이터가 없습니다.
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<RecentSoloStats player={player} />
|
|
</div>
|
|
|
|
{(state.phase === 'bidding' || state.phase === 'sold') && (
|
|
<div className="border-t border-base-content/8 px-4 py-3 bg-base-content/[0.02]">
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-[11px] text-base-content/30 uppercase tracking-wider font-semibold">
|
|
{state.phase === 'sold' ? '낙찰가' : '현재 입찰가'}
|
|
</span>
|
|
<div className="flex items-center gap-2">
|
|
{state.currentBidder && (
|
|
<span
|
|
className={`text-[10px] font-bold uppercase ${teamIndexColorClasses(state.currentBidder.teamIndex).text}`}
|
|
>
|
|
{teamIndexLabel(state.currentBidder.teamIndex)}
|
|
</span>
|
|
)}
|
|
<span className="text-lg font-black text-amber-400 tabular-nums">
|
|
{state.currentBid > 0 ? formatPoints(state.currentBid) : '—'}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
{state.phase === 'passed' && (
|
|
<div className="border-t border-base-content/8 bg-amber-500/[0.04] px-4 py-3 text-center">
|
|
<span className="text-sm font-bold text-amber-400">
|
|
유찰{' '}
|
|
{state.auctionRound === 1
|
|
? '— 마지막에 다시 등장합니다'
|
|
: '— 강제 배정 대상'}
|
|
</span>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
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 (
|
|
<div className="border border-base-content/10 bg-base-100 px-4 py-3 text-sm text-base-content/40">
|
|
관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다.
|
|
</div>
|
|
);
|
|
}
|
|
|
|
const presets = [50, 100, 150, 200, 300, 500];
|
|
|
|
return (
|
|
<div className="border border-base-content/10 bg-base-100 p-4">
|
|
<div className="flex items-center gap-2 mb-3 flex-wrap">
|
|
{presets.map((preset) => (
|
|
<button
|
|
key={preset}
|
|
onClick={() => setBidAmount(Math.max(minBid, preset))}
|
|
disabled={isActiveTeamFull}
|
|
className={`text-[11px] px-2.5 py-1 border transition-colors ${
|
|
bidAmount === preset
|
|
? 'border-primary/40 bg-primary/10 text-primary'
|
|
: 'border-base-content/10 text-base-content/40 hover:border-base-content/20'
|
|
}`}
|
|
>
|
|
{preset}P
|
|
</button>
|
|
))}
|
|
<input
|
|
type="number"
|
|
value={bidAmount}
|
|
onChange={(event) =>
|
|
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"
|
|
/>
|
|
</div>
|
|
<button
|
|
onClick={() => onBid(activeTeam.teamIndex, bidAmount)}
|
|
disabled={
|
|
isActiveTeamFull ||
|
|
bidAmount > activeTeam.points ||
|
|
bidAmount <= state.currentBid
|
|
}
|
|
className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${
|
|
`${teamIndexColorClasses(activeTeam.teamIndex).border} ${teamIndexColorClasses(activeTeam.teamIndex).bg} ${teamIndexColorClasses(activeTeam.teamIndex).text} hover:bg-base-content/5`
|
|
}`}
|
|
>
|
|
{isActiveTeamFull
|
|
? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
|
|
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(bidAmount)}P)`}
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
|
|
const endRef = useRef<HTMLDivElement>(null);
|
|
|
|
useEffect(() => {
|
|
endRef.current?.scrollIntoView({ behavior: 'smooth' });
|
|
}, [bids.length]);
|
|
|
|
if (bids.length === 0) return null;
|
|
|
|
return (
|
|
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
|
|
<div className="px-3 py-1.5 border-b border-base-content/8 bg-base-200/40">
|
|
<span className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
|
입찰 기록
|
|
</span>
|
|
</div>
|
|
<div className="max-h-28 overflow-y-auto p-2 space-y-0.5">
|
|
{bids.map((bid, index) => (
|
|
<div key={`${bid.teamIndex}-${bid.timestamp}-${index}`} className="flex items-center gap-2 text-[11px]">
|
|
<span
|
|
className={`font-bold uppercase ${teamIndexColorClasses(bid.teamIndex).text}`}
|
|
>
|
|
{teamIndexLabel(bid.teamIndex)}
|
|
</span>
|
|
<span className="text-base-content/30">→</span>
|
|
<span className="text-amber-400 tabular-nums font-semibold">
|
|
{formatPoints(bid.amount)}P
|
|
</span>
|
|
</div>
|
|
))}
|
|
<div ref={endRef} />
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function AuctionPage() {
|
|
const { id } = useParams();
|
|
const location = useLocation();
|
|
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 socket = useAuctionSocket(id);
|
|
const captainTeamIndex = useDevCaptainTeamIndex();
|
|
const [now, setNow] = useState(() => Date.now());
|
|
const [assignedPosition, setAssignedPosition] = useState<Position>('MID');
|
|
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
|
|
|
|
useEffect(() => {
|
|
const timer = window.setInterval(() => setNow(Date.now()), 1000);
|
|
return () => window.clearInterval(timer);
|
|
}, []);
|
|
|
|
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,
|
|
};
|
|
|
|
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]);
|
|
|
|
if (!DEFAULT_COMMUNITY_ID) {
|
|
return (
|
|
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
|
<span className="text-sm text-amber-600">
|
|
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
|
|
</span>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) {
|
|
return (
|
|
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
|
<span className="text-sm text-base-content/40">경매를 연결하는 중...</span>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) {
|
|
return (
|
|
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
|
<h2 className="text-lg font-bold mb-2">경매가 아직 시작되지 않았습니다</h2>
|
|
<Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-4 px-5 text-xs">
|
|
내전 상세로 돌아가기
|
|
</Link>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
if (!auctionState || !matchQuery.data) {
|
|
return (
|
|
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
|
<span className="text-sm text-red-500">
|
|
경매 상태를 불러오지 못했습니다.
|
|
</span>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
const phaseLabel: Record<AuctionStateView['phase'], string> = {
|
|
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],
|
|
}),
|
|
]);
|
|
},
|
|
},
|
|
);
|
|
}
|
|
|
|
const undoPanel = canManageAuction ? (
|
|
<div className="border border-base-content/10 bg-base-100 p-4 space-y-3">
|
|
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35">
|
|
되돌리기 (Undo)
|
|
</div>
|
|
<div className="max-h-48 overflow-y-auto space-y-1 text-[11px]">
|
|
{historyQuery.data?.length ? (
|
|
historyQuery.data.map((entry) => (
|
|
<button
|
|
key={entry.sequence}
|
|
type="button"
|
|
onClick={() => handleUndo(entry.sequence)}
|
|
disabled={undoMutation.isPending}
|
|
className="flex w-full items-center justify-between gap-2 border border-base-content/8 px-2 py-1.5 text-left transition-colors hover:border-primary/30 hover:bg-primary/5 disabled:cursor-not-allowed disabled:opacity-40"
|
|
>
|
|
<span className="text-base-content/65 tabular-nums">
|
|
#{entry.sequence}
|
|
</span>
|
|
<span className="text-base-content/45">{entry.actionLabel}</span>
|
|
<span className="text-[10px] text-base-content/25">
|
|
{relativeTime(entry.takenAt)}
|
|
</span>
|
|
</button>
|
|
))
|
|
) : (
|
|
<div className="border border-dashed border-base-content/10 px-2 py-4 text-center text-base-content/25">
|
|
기록이 없습니다
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
) : null;
|
|
|
|
return (
|
|
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">
|
|
<Link
|
|
to={`/match/${id}`}
|
|
className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-4"
|
|
>
|
|
<svg
|
|
xmlns="http://www.w3.org/2000/svg"
|
|
className="h-3.5 w-3.5"
|
|
fill="none"
|
|
viewBox="0 0 24 24"
|
|
stroke="currentColor"
|
|
>
|
|
<path
|
|
strokeLinecap="round"
|
|
strokeLinejoin="round"
|
|
strokeWidth={2}
|
|
d="M15 19l-7-7 7-7"
|
|
/>
|
|
</svg>
|
|
내전 상세로
|
|
</Link>
|
|
|
|
{errorMessage && (
|
|
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
|
|
{errorMessage}
|
|
</div>
|
|
)}
|
|
|
|
{undoMutation.error instanceof Error && (
|
|
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
|
|
{undoMutation.error.message}
|
|
</div>
|
|
)}
|
|
|
|
<div className="mb-5 flex items-start justify-between flex-wrap gap-3">
|
|
<div>
|
|
<h1 className="text-xl font-bold text-base-content leading-tight">
|
|
경매 팀빌딩
|
|
</h1>
|
|
<p className="text-[11px] text-base-content/30 mt-0.5">
|
|
{Math.min(auctionState.currentPlayerIndex + 1, Math.max(auctionState.totalPlayers, 1))} /{' '}
|
|
{auctionState.totalPlayers} 선수
|
|
</p>
|
|
</div>
|
|
<div className="flex flex-col items-end gap-2">
|
|
<div className="flex items-center gap-2">
|
|
<span
|
|
className={`inline-flex items-center text-[11px] font-semibold px-2 py-1 border ${
|
|
auctionState.phase === 'bidding'
|
|
? 'border-green-500/20 bg-green-500/10 text-green-400'
|
|
: auctionState.phase === 'sold'
|
|
? 'border-amber-500/20 bg-amber-500/10 text-amber-400'
|
|
: auctionState.phase === 'passed'
|
|
? 'border-amber-500/20 bg-amber-500/10 text-amber-400/70'
|
|
: 'border-base-content/10 bg-base-content/5 text-base-content/40'
|
|
}`}
|
|
>
|
|
{phaseLabel[auctionState.phase]}
|
|
</span>
|
|
{auctionState.phase === 'bidding' && (
|
|
<span
|
|
className={`text-lg font-black tabular-nums ${auctionState.timer <= 5 ? 'text-red-500' : 'text-base-content'}`}
|
|
>
|
|
{auctionState.timer}s
|
|
</span>
|
|
)}
|
|
</div>
|
|
<div className="flex items-center gap-2 text-xs text-base-content/40">
|
|
<span>소켓: {socket.connectionStatus}</span>
|
|
{/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */}
|
|
<select
|
|
value={captainTeamIndex ?? 'spectator'}
|
|
onChange={(event) =>
|
|
setDevCaptainTeamIndex(
|
|
event.target.value === 'spectator'
|
|
? null
|
|
: Number(event.target.value),
|
|
)
|
|
}
|
|
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
|
|
>
|
|
<option value="spectator">관전자</option>
|
|
{availableTeamIndexes.map((teamIndex) => (
|
|
<option key={teamIndex} value={teamIndex}>
|
|
{teamIndexLabel(teamIndex)} 팀장
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{auctionState.phase === 'bidding' && (
|
|
<TimerBar timer={auctionState.timer} maxTimer={auctionState.maxTimer} />
|
|
)}
|
|
|
|
<div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(340px,440px)] gap-4 mt-4">
|
|
<div className="grid sm:grid-cols-2 gap-4 content-start">
|
|
{auctionState.teams.map((team) => (
|
|
<TeamPanel
|
|
key={team.teamIndex}
|
|
team={team}
|
|
isActive={isCurrentBidder(auctionState.currentBidder, team)}
|
|
isLeft={team.teamIndex % 2 === 1}
|
|
historyBackTo={historyBackTo}
|
|
/>
|
|
))}
|
|
</div>
|
|
|
|
<div className="flex-1 min-w-0 space-y-4">
|
|
{auctionState.phase === 'complete' ? (
|
|
<>
|
|
<div className="border border-base-content/10 bg-base-100 p-8 text-center">
|
|
<div className="text-lg font-bold text-base-content mb-2">
|
|
경매 완료
|
|
</div>
|
|
<div className="text-xs text-base-content/40">
|
|
모든 선수가 팀에 배정되었습니다.
|
|
</div>
|
|
<Link
|
|
to={`/match/${id}`}
|
|
className="btn btn-primary btn-sm mt-4 px-6 text-[11px]"
|
|
>
|
|
결과 확인
|
|
</Link>
|
|
</div>
|
|
{undoPanel}
|
|
</>
|
|
) : (
|
|
<>
|
|
<PlayerSpotlight
|
|
state={auctionState}
|
|
historyBackTo={historyBackTo}
|
|
/>
|
|
|
|
{auctionState.phase === 'sold' && auctionState.currentBidder && (
|
|
<div
|
|
className={`text-center py-3 border text-sm font-bold ${
|
|
`${teamIndexColorClasses(auctionState.currentBidder.teamIndex).border} ${teamIndexColorClasses(auctionState.currentBidder.teamIndex).bg} ${teamIndexColorClasses(auctionState.currentBidder.teamIndex).text}`
|
|
}`}
|
|
>
|
|
{teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰
|
|
{' '}— {formatPoints(auctionState.currentBid)}P
|
|
</div>
|
|
)}
|
|
|
|
<BidControls
|
|
state={auctionState}
|
|
captainRole={captainRole}
|
|
onBid={(teamIndex, amount) =>
|
|
socket.placeBid({ teamIndex, amount })
|
|
}
|
|
/>
|
|
<BidLog bids={auctionState.bids} />
|
|
|
|
{canManageAuction && (
|
|
<div className="border border-base-content/10 bg-base-100 p-4 space-y-3">
|
|
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35">
|
|
Auction Controls
|
|
</div>
|
|
{auctionState.phase === 'presenting' && (
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary btn-sm px-5 text-xs"
|
|
onClick={() => socket.openBidding()}
|
|
>
|
|
입찰 열기
|
|
</button>
|
|
)}
|
|
{auctionState.phase === 'bidding' && (
|
|
<div className="flex flex-wrap items-center gap-3">
|
|
<select
|
|
value={assignedPosition}
|
|
onChange={(event) => setAssignedPosition(event.target.value as Position)}
|
|
className="border border-base-content/10 bg-transparent px-2 py-2 text-xs"
|
|
>
|
|
<option value="TOP">탑</option>
|
|
<option value="JGL">정글</option>
|
|
<option value="MID">미드</option>
|
|
<option value="ADC">원딜</option>
|
|
<option value="SUP">서폿</option>
|
|
</select>
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary btn-sm px-5 text-xs"
|
|
onClick={() => socket.markSold(assignedPosition)}
|
|
>
|
|
낙찰 처리
|
|
</button>
|
|
</div>
|
|
)}
|
|
{(auctionState.phase === 'sold' ||
|
|
auctionState.phase === 'passed') && (
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary btn-sm px-5 text-xs"
|
|
onClick={() => socket.next()}
|
|
>
|
|
다음 선수
|
|
</button>
|
|
)}
|
|
</div>
|
|
)}
|
|
{undoPanel}
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</main>
|
|
);
|
|
}
|