import { useMemo, useState } from "react"; import { CartesianGrid, Line, LineChart, 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 QUEUE_LABELS: Record = { RANKED_SOLO_5x5: "솔로랭크", RANKED_FLEX_SR: "자유랭크", }; type PeriodKey = "30" | "90" | "all"; 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 formatTierShort(tier: string) { return TIER_NAMES[tier] ?? 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; }; 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", }: { entries: ApiTierHistoryEntry[]; className?: string; }) { // 데이터에 존재하는 큐 목록 (솔로 우선) 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 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 = last.value > first.value ? "up" : last.value < first.value ? "down" : "flat"; return { first, last, peak, direction }; }, [points]); const header = (

티어 변동

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