import { useMemo, useState } from "react"; import { CartesianGrid, Line, LineChart, ReferenceDot, ReferenceLine, ResponsiveContainer, Tooltip, XAxis, YAxis, } from "recharts"; import type { ApiTierHistoryEntry } from "../api/types"; const TIER_NAMES: Record = { IRON: "아이언", BRONZE: "브론즈", SILVER: "실버", GOLD: "골드", PLATINUM: "플래티넘", EMERALD: "에메랄드", DIAMOND: "다이아몬드", MASTER: "마스터", GRANDMASTER: "그랜드마스터", CHALLENGER: "챌린저", }; // 낮은 티어 → 높은 티어. 인덱스가 사다리값의 기준이 된다. const TIER_ORDER = [ "IRON", "BRONZE", "SILVER", "GOLD", "PLATINUM", "EMERALD", "DIAMOND", "MASTER", "GRANDMASTER", "CHALLENGER", ]; const APEX_TIERS = new Set(["MASTER", "GRANDMASTER", "CHALLENGER"]); // 한 티어 = 400, 한 디비전(랭크) = 100, LP는 그대로 더한다. const TIER_SPAN = 400; const RANK_SPAN = 100; const RANK_INDEX: Record = { IV: 0, III: 1, II: 2, I: 3 }; const RANK_BY_INDEX = ["IV", "III", "II", "I"]; const QUEUE_LABELS: Record = { RANKED_SOLO_5x5: "솔로랭크", RANKED_FLEX_SR: "자유랭크", }; const TIER_COMPACT_NAMES: Record = { IRON: "I", BRONZE: "B", SILVER: "S", GOLD: "G", PLATINUM: "P", EMERALD: "E", DIAMOND: "D", MASTER: "M", GRANDMASTER: "GM", CHALLENGER: "C", }; type PeriodKey = "30" | "90" | "all"; type SummaryVariant = "footer" | "inline"; type SummaryDirection = "up" | "down" | "flat"; const PERIOD_OPTIONS: { key: PeriodKey; label: string; days: number | null }[] = [ { key: "30", label: "최근 30일", days: 30 }, { key: "90", label: "최근 90일", days: 90 }, { key: "all", label: "전체", days: null }, ]; function tierIndex(tier: string) { const index = TIER_ORDER.indexOf(tier); return index === -1 ? 0 : index; } // 티어/랭크/LP를 단일 연속 스칼라(사다리값)로 환산한다. function ladderValue(entry: { tier: string; rank?: string; leaguePoints?: number; }) { const base = tierIndex(entry.tier) * TIER_SPAN; const lp = entry.leaguePoints ?? 0; if (APEX_TIERS.has(entry.tier)) { return base + lp; } const rankIdx = RANK_INDEX[entry.rank ?? "IV"] ?? 0; return base + rankIdx * RANK_SPAN + lp; } 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 formatTierLabel(entry: { tier: string; rank?: string; leaguePoints?: number; }) { const name = TIER_NAMES[entry.tier] ?? entry.tier; if (APEX_TIERS.has(entry.tier)) { return `${name} ${entry.leaguePoints ?? 0}LP`; } const rank = normalizeRank(entry.rank); return `${name}${rank ? ` ${rank}` : ""} · ${entry.leaguePoints ?? 0}LP`; } function formatTierCompactLabel(entry: { tier: string; rank?: string; leaguePoints?: number; }) { const tier = TIER_COMPACT_NAMES[entry.tier] ?? entry.tier; const lp = entry.leaguePoints ?? 0; if (APEX_TIERS.has(entry.tier)) { return `${tier} ${lp}LP`; } const rank = normalizeRank(entry.rank); return `${tier}${rank} ${lp}LP`; } function formatTierShort(tier: string) { return TIER_NAMES[tier] ?? tier; } function formatPeriodChange(summary: { first: ChartPoint; last: ChartPoint; direction: SummaryDirection; }) { const marker = summary.direction === "up" ? "▲" : summary.direction === "down" ? "▼" : "·"; return `${formatTierShort(summary.first.tier)} ${marker} ${formatTierShort(summary.last.tier)}`; } function formatDate(ms: number) { return new Intl.DateTimeFormat("ko-KR", { month: "numeric", day: "numeric", }).format(new Date(ms)); } type ChartPoint = { ts: number; value: number; tier: string; rank?: string; leaguePoints?: number; wins?: number; losses?: number; }; type YGuide = { value: number; label: string; }; function isSamePoint(left: ChartPoint, right: ChartPoint) { return left.ts === right.ts && left.value === right.value; } function nearestApexPoint(value: number, points: ChartPoint[]) { const apexPoints = points.filter((point) => APEX_TIERS.has(point.tier)); if (apexPoints.length === 0) return null; return apexPoints.reduce((best, point) => Math.abs(point.value - value) < Math.abs(best.value - value) ? point : best, ); } function compactEntryFromLadderValue(value: number, points: ChartPoint[]) { const rounded = Math.max(0, Math.round(value)); const masterBase = tierIndex("MASTER") * TIER_SPAN; if (rounded >= masterBase) { const apexPoint = nearestApexPoint(rounded, points); const apexTier = apexPoint?.tier ?? "MASTER"; const apexBase = tierIndex(apexTier) * TIER_SPAN; if (rounded >= apexBase) { return { tier: apexTier, leaguePoints: rounded - apexBase, }; } return { tier: "MASTER", leaguePoints: rounded - masterBase, }; } const tierIdx = Math.min( TIER_ORDER.length - 1, Math.floor(rounded / TIER_SPAN), ); const tier = TIER_ORDER[tierIdx]; const withinTier = rounded - tierIdx * TIER_SPAN; const rankIdx = Math.min(3, Math.floor(withinTier / RANK_SPAN)); return { tier, rank: RANK_BY_INDEX[rankIdx], leaguePoints: withinTier - rankIdx * RANK_SPAN, }; } function buildAdaptiveYGuides(points: ChartPoint[]): YGuide[] { if (points.length === 0) return []; const min = Math.min(...points.map((point) => point.value)); const max = Math.max(...points.map((point) => point.value)); const paddedMin = min - 60; const paddedMax = max + 60; const steps = [50, 100, 200, 400, 800, 1200]; for (const step of steps) { const start = Math.ceil(paddedMin / step) * step; const end = Math.floor(paddedMax / step) * step; const count = Math.floor((end - start) / step) + 1; if (count >= 2 && count <= 4) { return Array.from({ length: count }, (_, index) => { const value = start + index * step; return { value, label: formatTierCompactLabel( compactEntryFromLadderValue(value, points), ), }; }); } } const center = Math.round(((min + max) / 2) / 50) * 50; return [center - 50, center + 50].map((value) => ({ value, label: formatTierCompactLabel(compactEntryFromLadderValue(value, points)), })); } function TierTooltip({ active, payload, }: { active?: boolean; payload?: Array<{ payload: ChartPoint }>; }) { if (!active || !payload?.length) return null; const point = payload[0].payload; const games = point.wins !== undefined && point.losses !== undefined ? ` · ${point.wins}승 ${point.losses}패` : ""; return (
{formatTierLabel(point)}
{new Intl.DateTimeFormat("ko-KR", { year: "numeric", month: "long", day: "numeric", }).format(new Date(point.ts))} {games}
); } export default function TierHistoryChart({ entries, className = "border border-base-content/10 bg-base-100 mb-5 overflow-hidden", summaryVariant = "footer", height = 220, showHeader = true, }: { entries: ApiTierHistoryEntry[]; className?: string; summaryVariant?: SummaryVariant; height?: number; showHeader?: boolean; }) { // 데이터에 존재하는 큐 목록 (솔로 우선) const availableQueues = useMemo(() => { const queues = new Set(entries.map((entry) => entry.queueType)); return ["RANKED_SOLO_5x5", "RANKED_FLEX_SR"].filter((queue) => queues.has(queue), ); }, [entries]); const [queue, setQueue] = useState( availableQueues[0] ?? "RANKED_SOLO_5x5", ); const [period, setPeriod] = useState("all"); const activeQueue = availableQueues.includes(queue) ? queue : (availableQueues[0] ?? "RANKED_SOLO_5x5"); const points = useMemo(() => { const periodDays = PERIOD_OPTIONS.find((option) => option.key === period)?.days ?? null; const cutoff = periodDays === null ? 0 : Date.now() - periodDays * 24 * 60 * 60 * 1000; return entries .filter((entry) => entry.queueType === activeQueue) .map((entry) => ({ ts: new Date(entry.recordedAt).getTime(), value: ladderValue(entry), tier: entry.tier, rank: entry.rank, leaguePoints: entry.leaguePoints, wins: entry.wins, losses: entry.losses, })) .filter((point) => point.ts >= cutoff) .sort((left, right) => left.ts - right.ts); }, [entries, activeQueue, period]); // 티어 경계(가로 점선) 후보 — 데이터 범위 안에 드는 티어 floor만. const tierLines = useMemo(() => { if (points.length === 0) return []; const min = Math.min(...points.map((point) => point.value)); const max = Math.max(...points.map((point) => point.value)); return TIER_ORDER.map((tier, index) => ({ tier, value: index * TIER_SPAN, })).filter((line) => line.value >= min - TIER_SPAN && line.value <= max); }, [points]); const adaptiveYGuides = useMemo(() => { return summaryVariant === "inline" ? buildAdaptiveYGuides(points) : []; }, [points, summaryVariant]); const summary = useMemo(() => { if (points.length === 0) return null; const first = points[0]; const last = points[points.length - 1]; const peak = points.reduce((best, point) => point.value > best.value ? point : best, ); const direction: SummaryDirection = last.value > first.value ? "up" : last.value < first.value ? "down" : "flat"; return { first, last, peak, direction }; }, [points]); const xDomain = useMemo(() => { if (summaryVariant !== "inline" || points.length < 2) { return ["dataMin", "dataMax"] as const; } const min = points[0].ts; const max = points[points.length - 1].ts; const span = Math.max(1, max - min); const padding = Math.max(span * 0.18, 24 * 60 * 60 * 1000); return [min - padding, max + padding] as const; }, [points, summaryVariant]); const header = (

티어 변동

{availableQueues.length > 1 && availableQueues.map((option) => ( ))}
); return (
{showHeader && header} {points.length < 2 ? (
티어 변동 기록이 아직 부족해요.
정보를 갱신할수록 변화가 쌓여 그래프로 보여드릴게요.
) : ( <>
{summaryVariant === "inline" ? adaptiveYGuides.map((guide) => ( )) : tierLines.map((line) => ( ))} } cursor={{ stroke: "currentColor", strokeDasharray: "3 3", className: "text-base-content/20", }} /> {summaryVariant === "inline" && summary && ( <> {!isSamePoint(summary.peak, summary.last) && ( )} )}
{summary && summaryVariant === "footer" && (
현재{" "} {formatTierLabel(summary.last)} 최고{" "} {formatTierLabel(summary.peak)} 기간 변동{" "} {formatPeriodChange(summary)}
)} )}
); }