Files
lolympus-tournament-support/apps/web/src/pages/AuctionPage.tsx
T

2876 lines
95 KiB
TypeScript

import {
lazy,
memo,
Suspense,
useEffect,
useLayoutEffect,
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,
useUserInternalHistory,
} from "../api/hooks";
import {
mapApiAuctionToAuctionState,
type AuctionPlayerView,
type AuctionStateView,
} from "../api/mappers";
import {
useAuctionSocket,
type BidLatencyDiagnostics,
} 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 { internalMatchGamePath } from "../lib/internal-match-routes";
import { formatRankDetail, RankBadge } from "../components/RankBadge";
import type {
ApiAuction,
ApiAuctionChatMessage,
ApiTierInfo,
ApiRecentMatchView,
ApiTierHistoryEntry,
ApiRiotLaneStats,
ApiUser,
ApiUserInternalHistoryResponse,
Position,
} from "../api/types";
import { LANE_LABELS } from "../lib/riot-history";
const TierHistoryChart = lazy(() => import("../components/TierHistoryChart"));
type CaptainRole = {
teamIndex: number;
};
function formatPoints(value: number) {
return value.toLocaleString();
}
function createClientRequestId(): string {
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
return crypto.randomUUID();
}
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
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<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 getAuctionRevision(auction: ApiAuction | null | undefined) {
return typeof auction?.revision === "number" ? auction.revision : null;
}
function pickLatestAuction(
socketAuction: ApiAuction | null,
queryAuction: ApiAuction | undefined,
) {
if (!socketAuction) return queryAuction ?? null;
if (!queryAuction) return socketAuction;
if (
socketAuction.auctionLifecycleId &&
queryAuction.auctionLifecycleId &&
socketAuction.auctionLifecycleId === queryAuction.auctionLifecycleId
) {
const socketRevision = getAuctionRevision(socketAuction);
const queryRevision = getAuctionRevision(queryAuction);
if (socketRevision !== null && queryRevision !== null) {
return queryRevision > socketRevision ? queryAuction : socketAuction;
}
}
return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction)
? queryAuction
: socketAuction;
}
const AUCTION_MAX_TEAM_SIZE = 5;
const AUCTION_MIN_BID_POINTS = 10;
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;
const LIVE_TIMER_TICK_MS = 100;
const PROFILE_TIER_ORDER = [
"IRON",
"BRONZE",
"SILVER",
"GOLD",
"PLATINUM",
"EMERALD",
"DIAMOND",
"MASTER",
"GRANDMASTER",
"CHALLENGER",
];
const PROFILE_APEX_TIERS = new Set(["MASTER", "GRANDMASTER", "CHALLENGER"]);
const PROFILE_RANK_INDEX: Record<string, number> = {
IV: 0,
III: 1,
II: 2,
I: 3,
};
function getAuctionTeamSize(team: AuctionStateView["teams"][number]) {
return team.members.length + 1;
}
function getReservedPointsAfterCurrentBid(
team: AuctionStateView["teams"][number],
) {
const remainingSlotsAfterCurrentBid = Math.max(
0,
AUCTION_MAX_TEAM_SIZE - getAuctionTeamSize(team) - 1,
);
return remainingSlotsAfterCurrentBid * AUCTION_MIN_BID_POINTS;
}
function getMaxBidForTeam(team: AuctionStateView["teams"][number]) {
return Math.max(0, team.points - getReservedPointsAfterCurrentBid(team));
}
function formatLatencyMs(value: number | undefined) {
return typeof value === "number" && Number.isFinite(value)
? `${Math.round(value)}ms`
: "-";
}
function formatBidLatencyDiagnostics(
diagnostics: BidLatencyDiagnostics | null,
) {
if (!diagnostics) return null;
const serverDeadlineTimestampMS =
diagnostics.bidDiagnostics?.currentBidRoundDeadlineTimestampMS;
const serverTimestampMS =
diagnostics.bidDiagnostics?.currentServerTimestampMS;
const serverRemainingMS =
typeof diagnostics.serverObservedRemainingBidRoundTimeMS === "number"
? diagnostics.serverObservedRemainingBidRoundTimeMS
: typeof serverDeadlineTimestampMS === "number" &&
typeof serverTimestampMS === "number"
? serverDeadlineTimestampMS - serverTimestampMS
: undefined;
const timing = diagnostics.bidServerTiming;
const parts = [
`RTT ${formatLatencyMs(diagnostics.serverRoundTripDurationMS)}`,
`gateway ${formatLatencyMs(timing?.gatewayTotalDurationMS)}`,
`service ${formatLatencyMs(timing?.serviceTotalDurationMS)}`,
`redis ${formatLatencyMs(timing?.redisBidCommandDurationMS)}`,
`context ${formatLatencyMs(timing?.redisBidContextReadDurationMS)}`,
];
if (timing?.fallbackFullStatePath) {
parts.push("fallback full-state");
}
if (typeof diagnostics.clientObservedRemainingBidRoundTimeMS === "number") {
parts.push(
`client-left ${formatLatencyMs(
diagnostics.clientObservedRemainingBidRoundTimeMS,
)}`,
);
}
if (typeof serverRemainingMS === "number") {
parts.push(`server-left ${formatLatencyMs(serverRemainingMS)}`);
}
return parts.join(" · ");
}
function getSoloTierHistory(entries: ApiTierHistoryEntry[]) {
return entries.filter((entry) => entry.queueType === "RANKED_SOLO_5x5");
}
function getProfileTierValue(
tier: Pick<ApiTierInfo, "tier" | "rank" | "leaguePoints">,
) {
const tierIndex = PROFILE_TIER_ORDER.indexOf(tier.tier);
const base = Math.max(0, tierIndex) * 400;
if (PROFILE_APEX_TIERS.has(tier.tier)) {
return base + (tier.leaguePoints ?? 0);
}
return (
base +
(PROFILE_RANK_INDEX[tier.rank ?? "IV"] ?? 0) * 100 +
(tier.leaguePoints ?? 0)
);
}
function tierHistoryEntryToTierInfo(entry: ApiTierHistoryEntry): ApiTierInfo {
return {
queueType: entry.queueType,
tier: entry.tier,
rank: entry.rank ?? "",
leaguePoints: entry.leaguePoints ?? 0,
wins: entry.wins ?? 0,
losses: entry.losses ?? 0,
fetchedAt: entry.recordedAt,
};
}
function getPeakSoloTier(
currentTier: ApiTierInfo | undefined,
tierHistory: ApiTierHistoryEntry[],
) {
const candidates = tierHistory.map(tierHistoryEntryToTierInfo);
if (currentTier?.queueType === "RANKED_SOLO_5x5") {
candidates.push(currentTier);
}
return candidates.reduce<ApiTierInfo | undefined>((peak, tier) => {
if (!peak) return tier;
return getProfileTierValue(tier) > getProfileTierValue(peak) ? tier : peak;
}, undefined);
}
type PlayerProfileTab = "internal" | "solo";
const INTERNAL_PROFILE_TOP_CHAMPION_LIMIT = 6;
const INTERNAL_PROFILE_RECENT_MATCH_LIMIT = 5;
function formatAuctionHistoryDate(ms: number) {
return new Intl.DateTimeFormat("ko-KR", {
month: "short",
day: "numeric",
}).format(new Date(ms));
}
function PosBadge({ pos }: { pos: Position }) {
return (
<span className="inline-flex items-center gap-1.5 text-xs 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>
);
}
// 티어 뱃지(RankBadge)와 같은 높이의 텍스트 칩. 포지션 키(TOP/JGL/MID/ADC/SUP)는
// 전부 3글자라 폭이 통일된다. 색은 중립 톤으로 둬서 컬러풀한 티어 뱃지와 경쟁하지 않게 한다.
function PosTag({ pos }: { pos: Position }) {
return (
<span
className="inline-flex h-[18px] shrink-0 items-center justify-center rounded-[3px] border border-base-content/20 bg-base-content/5 px-0.5 text-xs font-bold leading-none text-base-content/70"
title={`선호 포지션: ${positionLabel[pos]}`}
aria-label={`선호 포지션: ${positionLabel[pos]}`}
>
{/* 자간(음수 letter-spacing)·장평(scaleX)을 글자에만 적용해 칩 폭을 더 줄인다. */}
<span className="inline-block origin-center scale-x-85 tracking-tighter">
{pos}
</span>
</span>
);
}
function getLiveRemainingSeconds(
deadline: string | undefined,
serverTimeOffsetMs: number,
) {
if (!deadline) return 0;
const deadlineTimestampMS = Date.parse(deadline);
if (!Number.isFinite(deadlineTimestampMS)) return 0;
return Math.max(
0,
(deadlineTimestampMS - (Date.now() + serverTimeOffsetMs)) / 1000,
);
}
function useLiveRemainingSeconds(
deadline: string | undefined,
serverTimeOffsetMs: number,
enabled: boolean,
) {
const [remainingSeconds, setRemainingSeconds] = useState(() =>
getLiveRemainingSeconds(deadline, serverTimeOffsetMs),
);
useEffect(() => {
let timeoutId: ReturnType<typeof window.setTimeout> | null = null;
let timerId: ReturnType<typeof window.setInterval> | null = null;
const updateRemainingSeconds = () => {
const nextRemainingSeconds = getLiveRemainingSeconds(
deadline,
serverTimeOffsetMs,
);
setRemainingSeconds(nextRemainingSeconds);
if (nextRemainingSeconds <= 0 && timerId) {
window.clearInterval(timerId);
timerId = null;
}
};
timeoutId = window.setTimeout(updateRemainingSeconds, 0);
if (!enabled) {
return () => {
if (timeoutId) window.clearTimeout(timeoutId);
};
}
timerId = window.setInterval(updateRemainingSeconds, LIVE_TIMER_TICK_MS);
return () => {
if (timeoutId) window.clearTimeout(timeoutId);
if (timerId) window.clearInterval(timerId);
};
}, [deadline, enabled, serverTimeOffsetMs]);
return remainingSeconds;
}
function useIsDeadlineExpired(
deadline: string | undefined,
serverTimeOffsetMs: number,
enabled: boolean,
) {
const [isExpired, setIsExpired] = useState(
() => getLiveRemainingSeconds(deadline, serverTimeOffsetMs) <= 0,
);
useEffect(() => {
let syncTimeoutId: ReturnType<typeof window.setTimeout> | null = null;
let expireTimeoutId: ReturnType<typeof window.setTimeout> | null = null;
const remainingMs =
getLiveRemainingSeconds(deadline, serverTimeOffsetMs) * 1000;
syncTimeoutId = window.setTimeout(() => {
setIsExpired(remainingMs <= 0);
}, 0);
if (enabled && remainingMs > 0) {
expireTimeoutId = window.setTimeout(() => {
setIsExpired(true);
}, remainingMs);
}
return () => {
if (syncTimeoutId) window.clearTimeout(syncTimeoutId);
if (expireTimeoutId) window.clearTimeout(expireTimeoutId);
};
}, [deadline, enabled, serverTimeOffsetMs]);
return isExpired;
}
function AuctionTimerText({
deadline,
serverTimeOffsetMs,
}: {
deadline: string | undefined;
serverTimeOffsetMs: number;
}) {
const timer = useLiveRemainingSeconds(deadline, serverTimeOffsetMs, true);
return (
<span
className={`text-lg font-black tabular-nums ${timer <= 5 ? "text-red-500" : "text-base-content"}`}
>
{timer.toFixed(1)}s
</span>
);
}
function TimerBar({
deadline,
heightClassName = "h-1.5",
maxTimer,
serverTimeOffsetMs,
}: {
deadline: string | undefined;
heightClassName?: string;
maxTimer: number;
serverTimeOffsetMs: number;
}) {
const barRef = useRef<HTMLDivElement>(null);
const serverTimeOffsetRef = useRef(serverTimeOffsetMs);
useEffect(() => {
serverTimeOffsetRef.current = serverTimeOffsetMs;
}, [serverTimeOffsetMs]);
useLayoutEffect(() => {
const bar = barRef.current;
if (!bar) return;
let animationFrameId: number | null = null;
let urgentTimeoutId: ReturnType<typeof window.setTimeout> | null = null;
const remainingSeconds = getLiveRemainingSeconds(
deadline,
serverTimeOffsetRef.current,
);
const nextScale =
maxTimer > 0 ? Math.max(0, Math.min(1, remainingSeconds / maxTimer)) : 0;
bar.style.transition = "none";
bar.style.transform = `scaleX(${nextScale})`;
bar.classList.toggle("bg-red-500", remainingSeconds <= 5);
bar.classList.toggle("bg-primary", remainingSeconds > 5);
void bar.offsetWidth;
if (remainingSeconds > 5) {
urgentTimeoutId = window.setTimeout(
() => {
bar.classList.remove("bg-primary");
bar.classList.add("bg-red-500");
},
(remainingSeconds - 5) * 1000,
);
}
animationFrameId = window.requestAnimationFrame(() => {
const currentRemainingSeconds = getLiveRemainingSeconds(
deadline,
serverTimeOffsetRef.current,
);
bar.style.transition = `transform ${Math.round(
currentRemainingSeconds * 1000,
)}ms linear`;
bar.style.transform = "scaleX(0)";
});
return () => {
if (animationFrameId !== null) {
window.cancelAnimationFrame(animationFrameId);
}
if (urgentTimeoutId) window.clearTimeout(urgentTimeoutId);
};
}, [deadline, maxTimer]);
return (
<div
className={`${heightClassName} w-full overflow-hidden bg-base-content/5`}
>
<div
ref={barRef}
className="h-full origin-left transform-gpu bg-primary will-change-transform"
style={{ transform: "scaleX(0)" }}
/>
</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-xs 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-xs 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-xs font-bold uppercase tracking-wider text-base-content/30">
최근 솔로랭크
</h4>
<div className="mt-1 flex items-center gap-2">
<span className="text-xs font-semibold text-base-content">
{positionLabel[player.mainPosition]}
</span>
{player.recentStats.primarySource === "overall" ? (
<span className="text-xs 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-xs text-base-content/40">전적</span>
<span className="text-xs 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-xs text-base-content/40">KDA</span>
<span className="text-xs 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-xs text-base-content/40">분당 CS</span>
<span className="text-xs 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-xs ${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}
</span>
) : (
<span className="text-base-content/20">—</span>
)}
</div>
);
})}
</div>
</div>
);
}
function PlayerProfileTabButton({
active,
children,
onClick,
}: {
active: boolean;
children: string;
onClick: () => void;
}) {
return (
<button
type="button"
role="tab"
aria-selected={active}
onClick={onClick}
className={`relative px-3 py-2 text-xs font-bold transition-colors ${
active
? "text-primary"
: "text-base-content/40 hover:text-base-content/70"
}`}
>
{children}
{active ? (
<span className="absolute inset-x-3 bottom-0 h-px bg-primary" />
) : null}
</button>
);
}
function AuctionProfileMetric({
label,
value,
sub,
}: {
label: string;
value: string | number;
sub: string;
}) {
return (
<div className="border border-base-content/8 px-3 py-2">
<div className="text-xs font-bold uppercase tracking-wider text-base-content/30">
{label}
</div>
<div className="mt-1 text-lg font-black tabular-nums text-base-content">
{value}
</div>
<div className="text-xs text-base-content/35">{sub}</div>
</div>
);
}
function ProfileTierSummary({
label,
tier,
}: {
label: string;
tier: ApiTierInfo | undefined;
}) {
return (
<div className="flex min-w-0 items-center gap-1.5">
<RankBadge tier={tier} size="sm" />
<span className="truncate text-xs font-semibold text-base-content/55">
{formatRankDetail(tier)}{" "}
<span className="font-normal text-base-content/35">({label})</span>
</span>
</div>
);
}
function InternalChampionSummary({
champion,
ddragon,
}: {
champion: {
championId: number;
games: number;
winRate: number;
avgRating?: number;
kda?: number;
};
ddragon: ReturnType<typeof useDdragonManifest>["data"];
}) {
const iconUrl = championIconUrl(ddragon, champion.championId);
const displayName =
championDisplayName(ddragon, champion.championId) ??
String(champion.championId);
const rating = champion.avgRating ?? champion.kda ?? 0;
return (
<div className="flex min-w-0 items-center gap-2">
<div className="h-8 w-8 shrink-0 overflow-hidden bg-base-content/10">
{iconUrl ? (
<img
src={iconUrl}
alt={displayName}
className="h-full w-full object-cover"
loading="lazy"
/>
) : null}
</div>
<div className="min-w-0">
<div className="truncate text-xs font-semibold text-base-content">
{displayName}
</div>
<div className="text-xs text-base-content/35">
{champion.games}게임 · {champion.winRate}% · 평점 {rating}
</div>
</div>
</div>
);
}
function InternalRecentMatchRow({
match,
ddragon,
historyBackTo,
}: {
match: ApiRecentMatchView;
ddragon: ReturnType<typeof useDdragonManifest>["data"];
historyBackTo: string;
}) {
const iconUrl = championIconUrl(ddragon, match.championId);
const championName =
championDisplayName(ddragon, match.championId) ?? String(match.championId);
const resultTone = match.win ? "text-blue-400" : "text-red-400";
const detailPath =
match.internalMatchId && match.gameNumber
? internalMatchGamePath(
DEFAULT_COMMUNITY_ID,
match.internalMatchId,
match.gameNumber,
)
: null;
const content = (
<>
<div className="h-7 w-7 shrink-0 overflow-hidden bg-base-content/10">
{iconUrl ? (
<img
src={iconUrl}
alt={championName}
className="h-full w-full object-cover"
loading="lazy"
/>
) : null}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className={`text-xs font-black ${resultTone}`}>
{match.remake ? "다시하기" : match.win ? "승리" : "패배"}
</span>
<span className="truncate text-xs font-semibold text-base-content">
{championName}
</span>
</div>
<div className="text-xs text-base-content/35">
{formatAuctionHistoryDate(match.gameCreation)} ·{" "}
{LANE_LABELS[match.teamPosition] ?? match.teamPosition}
</div>
</div>
<div className="text-right text-xs tabular-nums text-base-content/60">
<div className="font-bold">
{match.kills}/{match.deaths}/{match.assists}
</div>
<div>{match.deaths === 0 ? "Perfect" : `${match.kda} 평점`}</div>
</div>
</>
);
const className =
"flex items-center gap-2 border border-base-content/8 px-2.5 py-2";
if (!detailPath) return <div className={className}>{content}</div>;
return (
<Link
to={detailPath}
state={{ backTo: historyBackTo, backLabel: "경매로 돌아가기" }}
className={`${className} transition-colors hover:border-primary/40 hover:bg-primary/[0.04] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`}
aria-label={`${championName} ${match.remake ? "다시하기" : match.win ? "승리" : "패배"} 내전 상세 보기`}
>
{content}
</Link>
);
}
function InternalHistorySkeleton() {
return (
<div className="p-4" aria-busy="true" aria-label="내전 기록 불러오는 중">
<div className="mb-3 flex items-center justify-between gap-3">
<div className="h-3 w-32 animate-pulse bg-base-content/10" />
<div className="h-3 w-10 animate-pulse bg-base-content/10" />
</div>
<div className="grid grid-cols-2 gap-2">
{Array.from({ length: 2 }).map((_, index) => (
<div key={index} className="border border-base-content/8 px-3 py-2">
<div className="h-3 w-10 animate-pulse bg-base-content/10" />
<div className="mt-2 h-6 w-14 animate-pulse bg-base-content/10" />
<div className="mt-2 h-3 w-20 animate-pulse bg-base-content/10" />
</div>
))}
</div>
<div className="mt-4 grid gap-4 md:grid-cols-2">
{["champions", "matches"].map((section) => (
<div key={section}>
<div className="mb-2 h-3 w-24 animate-pulse bg-base-content/10" />
<div className="space-y-2">
{Array.from({ length: 3 }).map((_, index) => (
<div
key={index}
className="flex items-center gap-2 border border-base-content/8 px-2.5 py-2"
>
<div className="h-8 w-8 shrink-0 animate-pulse bg-base-content/10" />
<div className="min-w-0 flex-1 space-y-2">
<div className="h-3 w-24 animate-pulse bg-base-content/10" />
<div className="h-3 w-32 animate-pulse bg-base-content/10" />
</div>
</div>
))}
</div>
</div>
))}
</div>
</div>
);
}
function InternalHistorySnapshot({
player,
ddragon,
historyBackTo,
isLoading,
firstPage,
}: {
player: NonNullable<AuctionStateView["currentPlayer"]>;
ddragon: ReturnType<typeof useDdragonManifest>["data"];
historyBackTo: string;
isLoading: boolean;
firstPage: ApiUserInternalHistoryResponse | undefined;
}) {
const summary = firstPage?.summary;
const matches = (firstPage?.matches ?? []).slice(
0,
INTERNAL_PROFILE_RECENT_MATCH_LIMIT,
);
const topChampions = (firstPage?.championStats.champions ?? []).slice(
0,
INTERNAL_PROFILE_TOP_CHAMPION_LIMIT,
);
if (isLoading) {
return <InternalHistorySkeleton />;
}
if (!summary && matches.length === 0) {
return (
<div className="px-4 py-8 text-center">
<div className="text-sm font-bold text-base-content">
저장된 내전 기록이 없습니다
</div>
<Link
to={`/users/${player.userId}/history?queueGroup=internal`}
state={{ backTo: historyBackTo }}
className="mt-3 inline-flex text-xs font-semibold text-primary hover:text-primary/80"
>
내전 전적 페이지 보기
</Link>
</div>
);
}
return (
<div className="p-4">
<div className="mb-3 flex items-center justify-between gap-3">
<h4 className="text-xs font-bold uppercase tracking-wider text-base-content/30">
최근 {summary?.windowSize ?? matches.length}게임 내전 요약
</h4>
<Link
to={`/users/${player.userId}/history?queueGroup=internal`}
state={{ backTo: historyBackTo }}
className="shrink-0 text-xs font-semibold text-primary hover:text-primary/80"
>
자세히
</Link>
</div>
<div className="grid grid-cols-2 gap-2">
<AuctionProfileMetric
label="승률"
value={`${summary?.winRate ?? 0}%`}
sub={`${summary?.wins ?? 0}승 ${summary?.losses ?? 0}패`}
/>
<AuctionProfileMetric
label="KDA"
value={summary?.kda ?? 0}
sub={`${summary?.avgKills ?? 0}/${summary?.avgDeaths ?? 0}/${summary?.avgAssists ?? 0}`}
/>
</div>
<div className="mt-4 grid gap-4 md:grid-cols-2">
<div>
<h5 className="mb-2 text-xs font-bold uppercase tracking-wider text-base-content/30">
자주 플레이한 챔피언
</h5>
<div className="space-y-2">
{topChampions.length > 0 ? (
topChampions.map((champion) => (
<InternalChampionSummary
key={champion.championId}
champion={champion}
ddragon={ddragon}
/>
))
) : (
<div className="text-xs text-base-content/25">기록 없음</div>
)}
</div>
</div>
<div>
<h5 className="mb-2 text-xs font-bold uppercase tracking-wider text-base-content/30">
최근 내전
</h5>
<div className="space-y-1.5">
{matches.length > 0 ? (
matches.map((match) => (
<InternalRecentMatchRow
key={`${match.matchId}-${match.gameNumber ?? match.gameCreation}`}
match={match}
ddragon={ddragon}
historyBackTo={historyBackTo}
/>
))
) : (
<div className="text-xs text-base-content/25">기록 없음</div>
)}
</div>
</div>
</div>
</div>
);
}
function SoloRankSnapshot({
player,
ddragon,
tierHistory,
}: {
player: NonNullable<AuctionStateView["currentPlayer"]>;
ddragon: ReturnType<typeof useDdragonManifest>["data"];
tierHistory: ApiTierHistoryEntry[];
}) {
return (
<>
{tierHistory.length > 0 && (
<Suspense
fallback={
<div className="h-[180px] bg-base-100" />
}
>
<TierHistoryChart
key={`${player.userId}-solo-tier-history`}
entries={tierHistory}
className="bg-base-100 overflow-hidden"
summaryVariant="inline"
height={180}
showHeader={false}
/>
</Suspense>
)}
<div className="grid grid-cols-2 divide-x divide-base-content/5 border-t border-base-content/8">
<div className="p-4">
<h4 className="text-xs 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-xs font-medium text-base-content truncate">
{displayName}
</div>
<div className="text-xs text-base-content/25">
Lv.{mastery.level} ·{" "}
{(mastery.points / 1000).toFixed(0)}K
</div>
</div>
</div>
);
})
) : (
<div className="text-xs text-base-content/25">
숙련도 데이터가 없습니다.
</div>
)}
</div>
</div>
<RecentSoloStats player={player} />
</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 = getAuctionTeamSize(team);
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-xs font-bold uppercase tracking-wide ${tone.text}`}
>
{teamIndexLabel(team.teamIndex, team.name)}
</span>
<span className="text-xs 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-xs">
<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-xs 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-xs 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-xs font-semibold text-base-content/45">
{positionLabel[member.assignedPosition]}
</span>
<span className="text-xs 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-xs text-base-content/10">—</span>
</div>
))}
</div>
</div>
);
}
const MemoTeamPanel = memo(TeamPanel);
function PlayerSpotlight({
state,
captainRole,
serverTimeOffsetMs,
historyBackTo,
}: {
state: AuctionStateView;
captainRole: CaptainRole | null;
serverTimeOffsetMs: number;
historyBackTo: string;
}) {
const player = state.currentPlayer;
if (!player) return null;
return (
<div className="border border-base-content/10 bg-base-100">
<MemoPlayerProfileDetails player={player} historyBackTo={historyBackTo} />
<PlayerBidStatus
state={state}
captainRole={captainRole}
serverTimeOffsetMs={serverTimeOffsetMs}
/>
</div>
);
}
// serverTimeOffsetMs는 5초마다 갱신되지만 비교자에 넣지 않는다. deadline이 바뀌는
// 순간(phase/currentBid 변화)에 항상 함께 리렌더되어 최신 offset이 반영되므로,
// 굳이 5초마다 리렌더할 필요가 없다.
const MemoPlayerSpotlight = memo(
PlayerSpotlight,
(previous, next) =>
previous.historyBackTo === next.historyBackTo &&
previous.captainRole?.teamIndex === next.captainRole?.teamIndex &&
areSameAuctionPlayerProfile(
previous.state.currentPlayer,
next.state.currentPlayer,
) &&
previous.state.phase === next.state.phase &&
previous.state.currentBid === next.state.currentBid &&
previous.state.currentBidder?.teamIndex ===
next.state.currentBidder?.teamIndex &&
previous.state.auctionRound === next.state.auctionRound,
);
function PlayerProfileDetails({
player,
historyBackTo,
}: {
player: NonNullable<AuctionStateView["currentPlayer"]>;
historyBackTo: string;
}) {
const { data: ddragon } = useDdragonManifest();
const [tabState, setTabState] = useState<{
playerId: string;
tab: PlayerProfileTab;
}>({ playerId: player.userId, tab: "internal" });
const activeTab =
tabState.playerId === player.userId ? tabState.tab : "internal";
const setActiveTab = (tab: PlayerProfileTab) =>
setTabState({ playerId: player.userId, tab });
const snapshotSoloTierHistory = getSoloTierHistory(player.tierHistory);
const historyProfileQuery = useUserHistoryProfile(
player.userId,
DEFAULT_COMMUNITY_ID,
snapshotSoloTierHistory.length === 0,
);
const internalHistoryQuery = useUserInternalHistory(
player.userId,
{ queueGroup: "internal" },
DEFAULT_COMMUNITY_ID,
activeTab === "internal",
);
const internalFirstPage = internalHistoryQuery.data?.pages[0];
const tierHistory =
snapshotSoloTierHistory.length > 0
? snapshotSoloTierHistory
: getSoloTierHistory(historyProfileQuery.data?.tierHistory ?? []);
const peakSoloTier = getPeakSoloTier(player.tier, tierHistory);
return (
<>
<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-xs text-base-content/25">
#{player.tag}
</span>
</div>
<div className="mb-2 min-w-0 space-y-1">
<ProfileTierSummary label="현재" tier={player.tier} />
<ProfileTierSummary label="최고" tier={peakSoloTier} />
</div>
<div className="flex items-center gap-1.5">
<PosBadge pos={player.mainPosition} />
<span className="inline-flex items-center gap-0.5 text-xs 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
role="tablist"
aria-label="선수 전적 종류"
className="flex border-t border-base-content/8 px-2"
>
<PlayerProfileTabButton
active={activeTab === "internal"}
onClick={() => setActiveTab("internal")}
>
내전
</PlayerProfileTabButton>
<PlayerProfileTabButton
active={activeTab === "solo"}
onClick={() => setActiveTab("solo")}
>
솔로랭크
</PlayerProfileTabButton>
</div>
<div className="h-[500px] overflow-y-auto border-t border-base-content/8">
{activeTab === "internal" ? (
<InternalHistorySnapshot
player={player}
ddragon={ddragon}
historyBackTo={historyBackTo}
isLoading={
!internalFirstPage &&
(internalHistoryQuery.isLoading || internalHistoryQuery.isFetching)
}
firstPage={internalFirstPage}
/>
) : (
<SoloRankSnapshot
player={player}
ddragon={ddragon}
tierHistory={tierHistory}
/>
)}
</div>
</>
);
}
const MemoPlayerProfileDetails = memo(
PlayerProfileDetails,
(previous, next) =>
areSameAuctionPlayerProfile(previous.player, next.player) &&
previous.historyBackTo === next.historyBackTo,
);
function areSameAuctionPlayerProfile(
previous: AuctionPlayerView | null,
next: AuctionPlayerView | null,
) {
if (previous === next) return true;
if (!previous || !next) return false;
return (
previous.userId === next.userId &&
previous.summonerName === next.summonerName &&
previous.tag === next.tag &&
previous.mainPosition === next.mainPosition &&
previous.subPosition === next.subPosition &&
previous.profileIconId === next.profileIconId &&
previous.passCount === next.passCount &&
JSON.stringify(previous.tier) === JSON.stringify(next.tier) &&
JSON.stringify(previous.tierHistory) === JSON.stringify(next.tierHistory) &&
JSON.stringify(previous.masteries) === JSON.stringify(next.masteries) &&
JSON.stringify(previous.recentStats) === JSON.stringify(next.recentStats)
);
}
const OUTBID_ALERT_RESET_MS = 4000;
// 입찰가가 오를 때 이전값→새값으로 굴려 "방금 올랐다"를 몸으로 느끼게 한다.
function useCountUp(value: number, durationMs = 450) {
const [display, setDisplay] = useState(value);
const displayRef = useRef(value);
useEffect(() => {
displayRef.current = display;
}, [display]);
useEffect(() => {
const from = displayRef.current;
const to = value;
if (from === to) return;
// 라운드가 바뀌어 입찰가가 초기화/감소하거나 동작 줄이기(reduced-motion)가 켜져 있으면
// 역방향/불필요한 롤링 없이 즉시 스냅(duration 0). reduced-motion은 CSS 미디어 쿼리로는
// JS rAF 애니메이션을 막을 수 없어 여기서 직접 확인한다.
const prefersReducedMotion =
typeof window !== 'undefined' &&
window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
const effectiveDuration = to < from || prefersReducedMotion ? 0 : durationMs;
let rafId = 0;
const start = performance.now();
const tick = (now: number) => {
const progress =
effectiveDuration > 0
? Math.min(1, (now - start) / effectiveDuration)
: 1;
const eased = 1 - Math.pow(1 - progress, 3);
setDisplay(Math.round(from + (to - from) * eased));
if (progress < 1) {
rafId = window.requestAnimationFrame(tick);
}
};
rafId = window.requestAnimationFrame(tick);
return () => window.cancelAnimationFrame(rafId);
}, [value, durationMs]);
return display;
}
function AnimatedBidPoints({
amount,
className = "",
}: {
amount: number;
className?: string;
}) {
const display = useCountUp(amount);
const [popToken, setPopToken] = useState(0);
const isFirstRenderRef = useRef(true);
// 값이 바뀔 때마다 key를 갱신해 pop 애니메이션을 처음부터 재생한다.
useEffect(() => {
if (isFirstRenderRef.current) {
isFirstRenderRef.current = false;
return;
}
const timeoutId = window.setTimeout(
() => setPopToken((token) => token + 1),
0,
);
return () => window.clearTimeout(timeoutId);
}, [amount]);
return (
<span
key={popToken}
className={`inline-block tabular-nums ${popToken > 0 ? "animate-bid-pop" : ""} ${className}`}
>
{amount > 0 ? formatPoints(display) : "—"}
</span>
);
}
// 내가 최고가였다가 다른 팀에게 밀린 "순간"을 일정 시간 동안만 강조한다.
function useJustOutbid(
currentBidderTeamIndex: number | undefined,
myTeamIndex: number | null,
) {
const [justOutbid, setJustOutbid] = useState(false);
const previousBidderRef = useRef(currentBidderTeamIndex);
useEffect(() => {
const previousBidder = previousBidderRef.current;
previousBidderRef.current = currentBidderTeamIndex;
const becameOutbid =
myTeamIndex !== null &&
previousBidder === myTeamIndex &&
currentBidderTeamIndex !== undefined &&
currentBidderTeamIndex !== myTeamIndex;
if (!becameOutbid) {
// 내가 다시 최고가가 되거나 라운드가 바뀌면 해제.
const clearId = window.setTimeout(() => setJustOutbid(false), 0);
return () => window.clearTimeout(clearId);
}
const setId = window.setTimeout(() => setJustOutbid(true), 0);
const resetId = window.setTimeout(
() => setJustOutbid(false),
OUTBID_ALERT_RESET_MS,
);
return () => {
window.clearTimeout(setId);
window.clearTimeout(resetId);
};
}, [currentBidderTeamIndex, myTeamIndex]);
return justOutbid;
}
function PlayerBidStatus({
state,
captainRole,
serverTimeOffsetMs,
}: {
state: AuctionStateView;
captainRole: CaptainRole | null;
serverTimeOffsetMs: number;
}) {
const myTeamIndex = captainRole?.teamIndex ?? null;
const currentBidderTeamIndex = state.currentBidder?.teamIndex;
const iAmHighestBidder =
myTeamIndex !== null && currentBidderTeamIndex === myTeamIndex;
const justOutbid = useJustOutbid(currentBidderTeamIndex, myTeamIndex);
const isSold = state.phase === "sold";
const hasBid = state.currentBid > 0 && state.currentBidder != null;
// 컨테이너 톤: 내가 최고가(안심·초록) / 밀린 순간(주의·빨강) / 중립.
const containerTone = iAmHighestBidder
? "border-emerald-500/30 bg-emerald-500/[0.06]"
: justOutbid
? "border-red-500/40 bg-red-500/[0.08] animate-outbid-shake"
: "border-base-content/8 bg-base-content/[0.02]";
const amountTone = iAmHighestBidder ? "text-emerald-400" : "text-amber-400";
// 상태 라벨은 항상 "나" 1인칭 기준으로 분기한다.
let statusText: string;
let statusTone: string;
if (isSold) {
statusText = iAmHighestBidder ? "내가 낙찰!" : "낙찰 완료";
statusTone = iAmHighestBidder ? "text-emerald-400" : "text-base-content/30";
} else if (!hasBid) {
statusText = "첫 입찰 대기 중";
statusTone = "text-base-content/30";
} else if (iAmHighestBidder) {
statusText = "내가 최고 입찰 중";
statusTone = "text-emerald-400";
} else if (justOutbid && currentBidderTeamIndex !== undefined) {
statusText = `${teamIndexLabel(currentBidderTeamIndex)}에게 밀렸어요`;
statusTone = "text-red-400";
} else if (currentBidderTeamIndex !== undefined) {
statusText = `${teamIndexLabel(currentBidderTeamIndex)} 입찰 중`;
statusTone = "text-base-content/45";
} else {
statusText = "입찰 중";
statusTone = "text-base-content/45";
}
return (
<>
{(state.phase === "bidding" || isSold) && (
<div className={`border-t transition-colors ${containerTone}`}>
<div className="flex items-center justify-between px-4 py-3">
<div className="flex flex-col gap-0.5">
<span className="text-xs text-base-content/30 uppercase tracking-wider font-semibold">
{isSold ? "낙찰가" : "현재 입찰가"}
</span>
<span
className={`text-xs font-bold ${statusTone}`}
aria-live="polite"
>
{statusText}
</span>
</div>
<div className="flex items-center gap-2">
{state.currentBidder && (
<span
className={`text-xs font-bold uppercase ${teamIndexColorClasses(state.currentBidder.teamIndex).text}`}
>
{teamIndexLabel(state.currentBidder.teamIndex)}
</span>
)}
<AnimatedBidPoints
amount={state.currentBid}
className={`text-lg font-black ${amountTone}`}
/>
</div>
</div>
{/* 타이머를 입찰가 박스 하단에 붙여 시선 이동 없이 마감 임박을 전달한다. */}
{state.phase === "bidding" && (
<TimerBar
deadline={state.deadline}
heightClassName="h-0.5"
maxTimer={state.maxTimer}
serverTimeOffsetMs={serverTimeOffsetMs}
/>
)}
</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>
)}
</>
);
}
function BidControls({
state,
captainRole,
isBidPending,
serverTimeOffsetMs,
onBid,
}: {
state: AuctionStateView;
captainRole: CaptainRole | null;
isBidPending: boolean;
serverTimeOffsetMs: number;
onBid: (teamIndex: number, amount: number) => void;
}) {
const [bidAmount, setBidAmount] = useState(100);
const minBid = state.currentBid + AUCTION_MIN_BID_POINTS;
const activeTeam = captainRole
? state.teams.find((team) => team.teamIndex === captainRole.teamIndex)
: null;
const activeTeamSize = activeTeam ? getAuctionTeamSize(activeTeam) : 0;
const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE;
const reservedPoints = activeTeam
? getReservedPointsAfterCurrentBid(activeTeam)
: 0;
const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0;
const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid;
const isBidExpired = useIsDeadlineExpired(
state.deadline,
serverTimeOffsetMs,
state.phase === "bidding",
);
const effectiveBidAmount = activeTeam
? Math.min(maxBid, Math.max(minBid, bidAmount))
: Math.max(minBid, bidAmount);
useEffect(() => {
const nextBid = Math.max(minBid, Math.ceil(minBid / 10) * 10);
setBidAmount(activeTeam ? Math.min(maxBid, nextBid) : nextBid);
}, [activeTeam, maxBid, 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 bidIncrements = [10, 50, 100, 200];
const teamTone = teamIndexColorClasses(activeTeam.teamIndex);
const handlePlaceBid = () => onBid(activeTeam.teamIndex, effectiveBidAmount);
const isBidDisabled =
isBidPending ||
!canAffordNextBid ||
isBidExpired ||
effectiveBidAmount > maxBid ||
effectiveBidAmount <= state.currentBid;
const bidButtonLabel = isActiveTeamFull
? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
: isBidPending
? "입찰 반영 중..."
: isBidExpired
? "입찰 마감 확인 중"
: !canAffordNextBid
? `입찰 불가 (다음 ${formatPoints(minBid)}P · 최대 ${formatPoints(maxBid)}P)`
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(effectiveBidAmount)}P)`;
const bidButtonToneClassName = `${teamTone.border} ${teamTone.bg} ${teamTone.text} hover:bg-base-content/5`;
return (
<>
<div className="border border-base-content/10 bg-base-100 p-4">
<div className="mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-3">
<div className="border border-base-content/10 px-2.5 py-2">
<div className="text-base-content/30">보유</div>
<div className="mt-0.5 font-bold tabular-nums text-base-content">
{formatPoints(activeTeam.points)}P
</div>
</div>
<div className="border border-primary/20 bg-primary/5 px-2.5 py-2">
<div className="text-primary/70">이번 최대</div>
<div className="mt-0.5 font-black tabular-nums text-primary">
{formatPoints(maxBid)}P
</div>
</div>
<div
className="border border-base-content/10 px-2.5 py-2 text-base-content/45"
title={`현재 선수를 낙찰받은 뒤 남은 자리를 채우도록 자리당 ${AUCTION_MIN_BID_POINTS}P씩 보존합니다.`}
aria-label={`보존 ${reservedPoints}P. 현재 선수를 낙찰받은 뒤 남은 자리를 채우도록 자리당 ${AUCTION_MIN_BID_POINTS}P씩 보존합니다.`}
>
<div>보존</div>
<div className="mt-0.5 font-bold tabular-nums">
{formatPoints(reservedPoints)}P
</div>
</div>
</div>
<div className="flex items-center gap-2 mb-3 flex-wrap">
{bidIncrements.map((increment) => {
const presetBid = state.currentBid + increment;
const isSelected = bidAmount === presetBid;
return (
<button
key={increment}
onClick={() => setBidAmount(Math.min(maxBid, presetBid))}
disabled={
isBidPending || !canAffordNextBid || presetBid > maxBid
}
className={`text-xs px-2.5 py-1 border transition-colors ${
isSelected
? "border-primary/40 bg-primary/10 text-primary"
: "border-base-content/10 text-base-content/40 hover:border-base-content/20 disabled:opacity-30 disabled:cursor-not-allowed"
}`}
>
+{increment}P
</button>
);
})}
<button
onClick={() => setBidAmount(maxBid)}
disabled={isBidPending || !canAffordNextBid}
className={`text-xs px-2.5 py-1 border transition-colors ${
bidAmount === maxBid && maxBid > minBid
? "border-primary/40 bg-primary/10 text-primary"
: "border-base-content/10 text-base-content/40 hover:border-base-content/20 disabled:opacity-30 disabled:cursor-not-allowed"
}`}
>
올인 {formatPoints(maxBid)}P
</button>
{/* 타이핑 중에는 클램프하지 않고(자릿수 입력 방해 방지) blur 시점에만 보정한다. */}
<input
type="number"
value={bidAmount}
onChange={(event) => setBidAmount(Number(event.target.value))}
onBlur={(event) =>
setBidAmount(
Math.min(
maxBid,
Math.max(minBid, Number(event.target.value) || minBid),
),
)
}
min={minBid}
max={maxBid}
disabled={isBidPending || !canAffordNextBid}
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={handlePlaceBid}
disabled={isBidDisabled}
className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${bidButtonToneClassName}`}
>
{bidButtonLabel}
</button>
</div>
{/* 모바일 sticky 입찰 바: 스크롤 위치와 무관하게 항상 입찰 가능하게 한다. */}
<div className="fixed inset-x-0 bottom-0 z-40 border-t border-base-content/10 bg-base-100/95 px-4 pt-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] backdrop-blur xl:hidden">
<button
onClick={handlePlaceBid}
disabled={isBidDisabled}
className={`w-full py-3 text-sm font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${bidButtonToneClassName}`}
>
{bidButtonLabel}
</button>
</div>
</>
);
}
function BidLog({ bids }: { bids: AuctionStateView["bids"] }) {
const scrollRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const scrollContainer = scrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}, [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-xs font-bold uppercase tracking-wider text-base-content/30">
입찰 기록
</span>
</div>
<div ref={scrollRef} 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-xs"
>
<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>
</div>
);
}
const MemoBidLog = memo(BidLog);
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 [assignedPosition, setAssignedPosition] = useState<Position>("MID");
const [showCancelModal, setShowCancelModal] = useState(false);
const [cancelConfirmText, setCancelConfirmText] = useState("");
const [undoTargetSequence, setUndoTargetSequence] = useState<number | null>(
null,
);
const cancelConfirmInputRef = useRef<HTMLInputElement>(null);
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
const canConfirmAuctionCancel = cancelConfirmText.trim() === "예";
async function clearAuctionDataAfterCancel() {
if (!id) return;
const auctionQueryKey = ["auction", DEFAULT_COMMUNITY_ID, id] as const;
const auctionHistoryQueryKey = [
"auction-history",
DEFAULT_COMMUNITY_ID,
id,
] as const;
await Promise.all([
queryClient.cancelQueries({ queryKey: auctionQueryKey, exact: true }),
queryClient.cancelQueries({
queryKey: auctionHistoryQueryKey,
exact: true,
}),
]);
queryClient.removeQueries({ queryKey: auctionQueryKey, exact: true });
queryClient.removeQueries({
queryKey: auctionHistoryQueryKey,
exact: true,
});
await queryClient.invalidateQueries({
queryKey: ["match", DEFAULT_COMMUNITY_ID, id],
exact: true,
});
}
useEffect(() => {
if (!showCancelModal) return;
cancelConfirmInputRef.current?.focus();
}, [showCancelModal]);
const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
const auctionState = useMemo(
() =>
liveAuction && matchQuery.data
? mapApiAuctionToAuctionState(liveAuction, matchQuery.data)
: null,
[liveAuction, matchQuery.data],
);
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 clearAuctionDataAfterCancel().finally(() => {
navigate(`/match/${id}`, { replace: true });
});
}, [id, navigate, socket.resetAt]);
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);
const bidLatencyMessage = formatBidLatencyDiagnostics(
socket.bidLatencyDiagnostics,
);
const matchSideEffectMessage = resolveMatchSideEffectMessage(
auctionState.matchSideEffectStatus,
);
function confirmUndo() {
if (undoTargetSequence === null) return;
const sequence = undoTargetSequence;
setUndoTargetSequence(null);
handleUndo(sequence);
}
function handleUndo(sequence: number) {
if (!id) return;
undoMutation.mutate(
{
auctionActionRequestId: createClientRequestId(),
clientObservedAuctionLifecycleId: liveAuction?.auctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
liveAuction?.currentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
liveAuction?.currentBidRoundPlayerUserId,
clientObservedPhase: liveAuction?.phase,
clientObservedRevision: liveAuction?.revision,
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(
{
auctionActionRequestId: createClientRequestId(),
clientObservedAuctionLifecycleId: liveAuction?.auctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
liveAuction?.currentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
liveAuction?.currentBidRoundPlayerUserId,
clientObservedPhase: liveAuction?.phase,
clientObservedRevision: liveAuction?.revision,
matchId: id,
},
{
onSuccess: async () => {
setShowCancelModal(false);
setCancelConfirmText("");
await clearAuctionDataAfterCancel();
navigate(`/match/${id}`, { replace: true });
},
},
);
}
const undoPanel = canManageAuction ? (
<div className="border border-base-content/10 bg-base-100 p-4 space-y-3">
<div className="text-xs font-bold uppercase tracking-wider text-base-content/35">
되돌리기 (Undo)
</div>
<div className="max-h-48 overflow-y-auto space-y-1 text-xs">
{historyQuery.data?.length ? (
historyQuery.data.map((entry) => (
<button
key={entry.sequence}
type="button"
onClick={() => setUndoTargetSequence(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-xs 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-[1600px] mx-auto px-4 sm:px-6 ${
captainRole && auctionState.phase === "bidding"
? "pt-6 pb-28 xl:pb-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>
)}
{import.meta.env.DEV && canManageAuction && bidLatencyMessage && (
<div className="mb-4 border border-base-content/10 bg-base-100 px-4 py-2 text-xs text-base-content/45">
입찰 계측 · {bidLatencyMessage}
</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>
)}
{resetAuctionMutation.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">
{resetAuctionMutation.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-xs 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-xs 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" && (
<AuctionTimerText
deadline={auctionState.deadline}
serverTimeOffsetMs={socket.serverTimeOffsetMs}
/>
)}
</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>
<div className="h-1.5">
{auctionState.phase === "bidding" ? (
<TimerBar
deadline={auctionState.deadline}
maxTimer={auctionState.maxTimer}
serverTimeOffsetMs={socket.serverTimeOffsetMs}
/>
) : (
<div aria-hidden className="h-full" />
)}
</div>
<div className="grid grid-cols-1 xl:grid-cols-[260px_minmax(0,1fr)_minmax(340px,440px)_320px] gap-4 mt-4">
<aside className="hidden xl:block">
<MemoPoolPanel state={auctionState} historyBackTo={historyBackTo} />
</aside>
<div className="grid sm:grid-cols-2 gap-4 content-start">
{auctionState.teams.map((team) => (
<MemoTeamPanel
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>
{matchSideEffectMessage && (
<div className="mt-3 border border-amber-500/20 bg-amber-500/10 px-3 py-2 text-xs text-amber-600">
{matchSideEffectMessage}
</div>
)}
<Link
to={`/match/${id}`}
className="btn btn-primary btn-sm mt-4 px-6 text-xs"
>
결과 확인
</Link>
</div>
{undoPanel}
</>
) : (
<>
<MemoPlayerSpotlight
state={auctionState}
captainRole={captainRole}
serverTimeOffsetMs={socket.serverTimeOffsetMs}
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}
isBidPending={socket.isBidPending}
serverTimeOffsetMs={socket.serverTimeOffsetMs}
onBid={(teamIndex, amount) =>
socket.placeBid({
bidderTeamIndex: teamIndex,
bidPointAmount: amount,
})
}
/>
<MemoBidLog bids={auctionState.bids} />
{canManageAuction && (
<div className="border border-base-content/10 bg-base-100 p-4 space-y-3">
<div className="text-xs 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()}
disabled={socket.isAuctionActionPending}
>
{socket.isAuctionActionPending
? "반영 중..."
: "입찰 열기"}
</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)}
disabled={
socket.isAuctionActionPending ||
!(
auctionState.currentBid > 0 &&
auctionState.currentBidder != null
)
}
title={
auctionState.currentBid > 0
? undefined
: "입찰이 있어야 낙찰할 수 있습니다."
}
>
{socket.isAuctionActionPending
? "반영 중..."
: "낙찰 처리"}
</button>
<button
type="button"
className="btn btn-outline btn-sm px-5 text-xs"
onClick={() => socket.markPassed()}
disabled={
socket.isAuctionActionPending ||
auctionState.currentBid > 0
}
>
{socket.isAuctionActionPending
? "반영 중..."
: "유찰 처리"}
</button>
</div>
)}
{(auctionState.phase === "sold" ||
auctionState.phase === "passed") && (
<button
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
onClick={() => socket.next()}
disabled={socket.isAuctionActionPending}
>
{socket.isAuctionActionPending
? "반영 중..."
: "다음 선수"}
</button>
)}
<div className="border-t border-base-content/10 pt-3">
<button
type="button"
className="btn btn-outline btn-error btn-sm inline-flex items-center gap-1.5 px-4 text-xs"
onClick={() => {
setCancelConfirmText("");
setShowCancelModal(true);
}}
disabled={resetAuctionMutation.isPending}
>
<AlertTriangle className="h-3.5 w-3.5" />
경매 진행 취소
</button>
<p className="mt-2 text-xs leading-relaxed text-base-content/35">
경매 데이터와 진행 기록을 삭제하고 내전을 모집 상태로
되돌립니다.
</p>
</div>
</div>
)}
{undoPanel}
</>
)}
</div>
<aside className="hidden xl:block">
<ChatPanel
messages={socket.chatMessages}
connectionStatus={socket.connectionStatus}
senderLabel={chatSenderLabel}
onSend={(message) =>
socket.sendChatMessage({
displayName: chatSenderLabel,
message,
})
}
className="sticky top-4 h-[520px] max-h-[calc(100vh-2rem)]"
/>
</aside>
</div>
<div className="mt-4 xl:hidden">
<ChatPanel
messages={socket.chatMessages}
connectionStatus={socket.connectionStatus}
senderLabel={chatSenderLabel}
onSend={(message) =>
socket.sendChatMessage({
displayName: chatSenderLabel,
message,
})
}
className="h-[420px]"
/>
</div>
{undoTargetSequence !== null && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 px-4"
role="dialog"
aria-modal="true"
aria-labelledby="auction-undo-title"
onClick={() => setUndoTargetSequence(null)}
>
<div
className="w-full max-w-md border border-base-content/15 bg-base-100 p-5 shadow-2xl"
onClick={(event) => event.stopPropagation()}
>
<h2
id="auction-undo-title"
className="text-base font-bold text-base-content"
>
되돌리기 확인
</h2>
<p className="mt-2 text-sm leading-6 text-base-content/60">
#{undoTargetSequence}번 액션 직전 상태로 되돌릴까요? 이후 진행
내역은 사라집니다.
</p>
<div className="mt-5 flex justify-end gap-2">
<button
type="button"
className="btn btn-ghost btn-sm px-4 text-xs"
onClick={() => setUndoTargetSequence(null)}
disabled={undoMutation.isPending}
>
닫기
</button>
<button
type="button"
className="btn btn-primary btn-sm px-4 text-xs"
onClick={confirmUndo}
disabled={undoMutation.isPending}
>
{undoMutation.isPending ? "되돌리는 중..." : "되돌리기"}
</button>
</div>
</div>
</div>
)}
{showCancelModal && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 px-4"
role="dialog"
aria-modal="true"
aria-labelledby="auction-cancel-title"
>
<div className="w-full max-w-md border border-red-500/25 bg-base-100 p-5 shadow-2xl">
<div className="flex items-start gap-3">
<span className="inline-flex h-9 w-9 shrink-0 items-center justify-center border border-red-500/25 bg-red-500/10 text-red-400">
<AlertTriangle className="h-4 w-4" />
</span>
<div className="min-w-0">
<h2
id="auction-cancel-title"
className="text-base font-bold text-base-content"
>
경매 진행 취소
</h2>
<p className="mt-2 text-sm leading-6 text-base-content/60">
정말 경매를 취소하고 모집 상태로 되돌리시겠습니까? 경매
데이터, 입찰 기록, 팀 배정 정보가 삭제됩니다.
</p>
</div>
</div>
<label
htmlFor="auction-cancel-confirm"
className="mt-5 block text-xs font-bold uppercase tracking-wider text-base-content/40"
>
계속하려면 예 입력
</label>
<input
id="auction-cancel-confirm"
ref={cancelConfirmInputRef}
value={cancelConfirmText}
onChange={(event) => 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="예"
/>
<div className="mt-5 flex flex-wrap justify-end gap-2">
<button
type="button"
className="btn btn-ghost btn-sm px-4 text-xs"
onClick={() => {
setShowCancelModal(false);
setCancelConfirmText("");
}}
disabled={resetAuctionMutation.isPending}
>
닫기
</button>
<button
type="button"
className="btn btn-error btn-sm px-4 text-xs"
onClick={handleResetAuction}
disabled={
!canConfirmAuctionCancel || resetAuctionMutation.isPending
}
>
{resetAuctionMutation.isPending
? "취소 처리 중..."
: "경매 취소 진행"}
</button>
</div>
</div>
</div>
)}
</main>
);
}
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,
historyBackTo,
}: {
state: AuctionStateView;
historyBackTo: string;
}) {
const { data: ddragon } = useDdragonManifest();
const [tab, setTab] = useState<PoolTab>("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 (
<div className="border border-base-content/10 bg-base-100 sticky top-4 max-h-[calc(100vh-2rem)] flex flex-col">
<div role="tablist" className="flex border-b border-base-content/10 px-3">
<PoolTabButton
label="대기"
count={waitingPool.length}
active={tab === "waiting"}
onClick={() => setTab("waiting")}
/>
<PoolTabButton
label="유찰"
count={passedPool.length}
active={tab === "passed"}
onClick={() => setTab("passed")}
/>
</div>
<div className="flex-1 overflow-y-auto">
{activePool.length === 0 ? (
<div className="px-3 py-8 text-center text-xs text-base-content/30">
{tab === "waiting"
? "대기 중인 유저가 없습니다"
: "유찰된 유저가 없습니다"}
</div>
) : (
<ul className="divide-y divide-base-content/5">
{activePool.map((player) => (
<PoolListItem
key={player.userId}
player={player}
ddragon={ddragon}
historyBackTo={historyBackTo}
showPassCount={tab === "passed"}
/>
))}
</ul>
)}
</div>
</div>
);
}
const MemoPoolPanel = memo(
PoolPanel,
(previous, next) =>
previous.historyBackTo === next.historyBackTo &&
previous.state.phase === next.state.phase &&
previous.state.currentPlayerIndex === next.state.currentPlayerIndex &&
previous.state.currentPlayer?.userId === next.state.currentPlayer?.userId &&
previous.state.auctionOrder === next.state.auctionOrder &&
previous.state.passedQueue === next.state.passedQueue &&
previous.state.teams === next.state.teams,
);
function PoolTabButton({
label,
count,
active,
onClick,
}: {
label: string;
count: number;
active: boolean;
onClick: () => void;
}) {
return (
<button
role="tab"
type="button"
onClick={onClick}
className={`relative px-1 pt-3 pb-2.5 mr-5 text-xs font-semibold transition-colors ${
active
? "text-base-content"
: "text-base-content/40 hover:text-base-content/70"
}`}
>
{label}
<span className="ml-1 text-xs tabular-nums text-base-content/30">
{count}
</span>
{active ? (
<span className="absolute -bottom-px left-0 right-0 h-px bg-primary" />
) : null}
</button>
);
}
function PoolListItem({
player,
ddragon,
historyBackTo,
showPassCount,
}: {
player: AuctionPlayerView;
ddragon: ReturnType<typeof useDdragonManifest>["data"];
historyBackTo: string;
showPassCount: boolean;
}) {
return (
<li>
<Link
to={`/users/${player.userId}/history`}
state={{ backTo: historyBackTo }}
className="group flex items-center gap-2 px-3 py-2 transition-colors hover:bg-base-content/[0.03]"
>
<img
src={profileIconUrl(ddragon, player.profileIconId)}
alt=""
className="w-7 h-7 shrink-0 rounded-sm border border-base-content/10 object-cover"
loading="lazy"
/>
<div className="min-w-0 flex-1 flex items-center gap-1.5">
<span className="truncate text-xs font-semibold text-base-content transition-colors group-hover:text-primary">
{player.summonerName}
</span>
<RankBadge tier={player.tier} />
<PosTag pos={player.mainPosition} />
{showPassCount && player.passCount > 0 ? (
<span className="inline-flex items-center text-xs font-medium px-1.5 py-0.5 border border-amber-500/30 text-amber-500 bg-amber-500/5">
{player.passCount}회 유찰
</span>
) : null}
</div>
</Link>
</li>
);
}
function ChatPanel({
messages,
connectionStatus,
senderLabel,
onSend,
className = "",
}: {
messages: ApiAuctionChatMessage[];
connectionStatus: ReturnType<typeof useAuctionSocket>["connectionStatus"];
senderLabel: string;
onSend: (message: string) => void;
className?: string;
}) {
const [draft, setDraft] = useState("");
const messagesScrollRef = useRef<HTMLDivElement | null>(null);
const trimmedDraft = draft.trim();
const isConnected = connectionStatus === "connected";
const canSend = isConnected && trimmedDraft.length > 0;
useEffect(() => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}, [messages.length]);
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!canSend) return;
onSend(trimmedDraft);
setDraft("");
}
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key !== "Enter" || event.shiftKey) return;
event.preventDefault();
if (!canSend) return;
onSend(trimmedDraft);
setDraft("");
}
const statusLabel =
connectionStatus === "connected"
? "실시간"
: connectionStatus === "connecting"
? "연결 중"
: "오프라인";
return (
<div
className={`border border-base-content/10 bg-base-100 flex min-h-0 flex-col ${className}`}
>
<div className="border-b border-base-content/10 px-3 py-2.5 flex items-center justify-between">
<div className="text-xs font-bold uppercase tracking-wider text-base-content/35">
채팅
</div>
<span
className={`text-xs ${
isConnected ? "text-green-500" : "text-base-content/30"
}`}
>
{statusLabel}
</span>
</div>
<div
ref={messagesScrollRef}
className="flex-1 min-h-0 overflow-y-auto px-3 py-3"
>
{messages.length === 0 ? (
<div className="flex h-full items-center justify-center text-center text-xs text-base-content/25">
아직 메시지가 없습니다
</div>
) : (
<ol className="space-y-3">
{messages.map((message) => (
<li key={message.id} className="space-y-1">
<div className="flex items-center justify-between gap-2">
<span className="min-w-0 truncate text-xs font-bold text-base-content/70">
{message.displayName}
</span>
<time className="shrink-0 text-xs tabular-nums text-base-content/25">
{formatChatTime(message.sentAt)}
</time>
</div>
<p className="whitespace-pre-wrap break-words border border-base-content/8 bg-base-content/[0.03] px-2.5 py-2 text-xs leading-relaxed text-base-content/75">
{message.message}
</p>
</li>
))}
</ol>
)}
</div>
<form
onSubmit={handleSubmit}
className="border-t border-base-content/10 p-2 space-y-2"
>
<div className="flex items-center justify-between gap-2 px-0.5 text-xs text-base-content/30">
<span className="truncate">{senderLabel}</span>
<span className="tabular-nums">{draft.length}/300</span>
</div>
<textarea
value={draft}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={handleKeyDown}
disabled={!isConnected}
maxLength={300}
placeholder="메시지를 입력하세요"
className="w-full resize-none border border-base-content/10 bg-base-content/5 px-2 py-1.5 text-xs text-base-content/80 placeholder:text-base-content/25 focus:border-primary/40 focus:outline-none disabled:cursor-not-allowed disabled:text-base-content/30"
rows={2}
aria-label="경매 채팅 메시지"
/>
<button
type="submit"
disabled={!canSend}
className="btn btn-primary btn-sm w-full text-xs"
>
<SendHorizontal className="h-3.5 w-3.5" aria-hidden="true" />
전송
</button>
</form>
</div>
);
}
function resolveMatchSideEffectMessage(
status: AuctionStateView["matchSideEffectStatus"],
): string | null {
if (status === "pending" || status === "processing") {
return "팀 편성, 토너먼트 코드, 결과 수집 예약을 반영 중입니다.";
}
if (status === "failed") {
return "팀 편성 후속 처리에 실패했습니다. 운영진 확인이 필요합니다.";
}
return null;
}