feat: KBO/MLB 운영 안정화 — 순위 탭·라이브 개선·취소/더블헤더 지원·야구 점수제

AI 예측
- 생성 시점을 킥오프 22시간 전으로 변경(선발투수 예고 이후), 잡 매시간 실행
- 경기 시작 후 생성 금지(사후 예측 방지), 경기 단위 커밋으로 중단 시 진행분 보존

일정·라이브 UI
- 야구 일정에 순위 탭 추가 (KBO 단일 순위표 · MLB 6개 디비전, /api/standings 신설)
- 경기중 카드에 현재 이닝·실시간 스코어 표시 (30s 폴링, 서버 15s 캐시)
- MLB 선발 누락 수정: statsapi 날짜 파라미터 미국 날짜 기준 보정(-1일)
- 라이브 대기타석 스크롤바 다크 테마 처리

운영 견고성
- 우천취소: 경기 삭제 → cancelled 상태 보존 (투표·예측 기록 유지, 정산/투표/AI 제외)
- 더블헤더: 시작시각순 seq로 1·2차전 분리 등록 (match_id _2, 정산·라이브·프리뷰 매핑)
- 축구 데이터 수집을 wc 리그로 한정 (야구 팀을 축구 API에 검색하던 쿼터 낭비 수정)

점수제
- 야구 판정 완화: 근접=득실차 ±1, 부분=한 팀 득점 ±1 (등급·배점은 리그 공통 유지)
- 채점 판정을 _grade_of() 단일 함수로 통합, 종료된 야구 경기 재채점
- 배점 안내 모달 야구 문구 분리, docs/SCORING.md 갱신

기타
- 야구 전용 댓글 닉네임 풀 (종목별 세션 캐시 분리)
- 리더보드 리그별 조회 연동 (?league=)
This commit is contained in:
JinwooKim committed 2026-07-22 11:01:10 +09:00
1 parent bfaf621949
commit 4e1ebc8989
46 files changed
+2560 -188

No files matched your search

+28 -14
View File
@@ -101,6 +101,9 @@ export default function Arena({
const rightShort = flip ? aShort : bShort;
// 마스코트(사자·버튼 양옆 캐릭터)는 모든 경기에서 노출.
const [outcome, setOutcome] = useState<Outcome | null>("DRAW");
// 야구(KBO/MLB): 스코어 상한 25, 마스코트 미노출
const isBaseball = match.league === "kbo" || match.league === "mlb";
const maxScore = isBaseball ? 25 : 9;
const [scoreA, setScoreA] = useState(0);
const [scoreB, setScoreB] = useState(0);
const [step, setStep] = useState<Step>("form");
@@ -227,7 +230,8 @@ export default function Arena({
{/* ===== 레이어드 화이트 시트 (002) ===== */}
<section className="sheet relative mt-4 p-5 text-[var(--ink)]">
{/* AI 박스 오른쪽 위 사자 — 모든 경기 노출 */}
{/* AI 박스 오른쪽 위 사자 — 축구 전용 */}
{!isBaseball && (
<div className="absolute right-1 -top-4 z-10 h-20 sm:h-24">
<TalkingMascot
src="/assets/mascots/lion_point.webp"
@@ -236,10 +240,18 @@ export default function Arena({
draggable
/>
</div>
)}
<div className="mb-3">
<h2 className="text-[22px] font-extrabold">{t.aiBattle}</h2>
</div>
{predictions.length === 0 && (
<p className="rounded-xl bg-black/[0.04] px-3 py-2.5 text-[12px] font-semibold text-[var(--ink-muted)]">
{lang === "en"
? "AI picks are generated daily at midnight — check back soon."
: "AI 예측은 매일 자정에 생성됩니다. 잠시 후 다시 확인해주세요."}
</p>
)}
<div className="flex flex-col gap-3">
{predictions.map((p) => {
const wp = winProb(match, p);
@@ -328,15 +340,15 @@ export default function Arena({
<div className="mt-3 flex items-center justify-center gap-5 rounded-xl border border-[var(--line-l)] bg-white py-3">
{flip ? (
<>
<Stepper label={bShort} value={scoreB} onChange={setScoreB} disabled={disabled} />
<Stepper label={bShort} value={scoreB} onChange={setScoreB} disabled={disabled} max={maxScore} />
<span className="text-[26px] font-extrabold text-[var(--ink-muted)]">:</span>
<Stepper label={aShort} value={scoreA} onChange={setScoreA} disabled={disabled} />
<Stepper label={aShort} value={scoreA} onChange={setScoreA} disabled={disabled} max={maxScore} />
</>
) : (
<>
<Stepper label={aShort} value={scoreA} onChange={setScoreA} disabled={disabled} />
<Stepper label={aShort} value={scoreA} onChange={setScoreA} disabled={disabled} max={maxScore} />
<span className="text-[26px] font-extrabold text-[var(--ink-muted)]">:</span>
<Stepper label={bShort} value={scoreB} onChange={setScoreB} disabled={disabled} />
<Stepper label={bShort} value={scoreB} onChange={setScoreB} disabled={disabled} max={maxScore} />
</>
)}
</div>
@@ -378,14 +390,14 @@ export default function Arena({
)}
{/* 투표하기 버튼 — 모든 경기에서 양옆에 캐릭터(자동 말풍선) */}
<div className="mt-3.5 flex items-end justify-center gap-1">
<TalkingMascot
{!isBaseball && <TalkingMascot
src="/assets/mascots/dog_point.webp"
lines={DOG_LINES}
className="h-16 w-auto select-none sm:h-20"
auto
autoDelayMs={1200}
autoIntervalMs={6000}
/>
/>}
<button
onClick={confirmSubmit}
disabled={!emailValid || submitting}
@@ -393,14 +405,14 @@ export default function Arena({
>
{submitting ? "…" : <>{t.submit} <span aria-hidden>→</span></>}
</button>
<TalkingMascot
{!isBaseball && <TalkingMascot
src="/assets/mascots/tiger_point.webp"
lines={TIGER_LINES}
className="h-16 w-auto select-none sm:h-20"
auto
autoDelayMs={4200}
autoIntervalMs={6000}
/>
/>}
</div>
</div>
)}
@@ -554,8 +566,8 @@ export default function Arena({
</section>
)}
{/* ===== 누적 랭킹 TOP 10 (골드 카드 위 · 폴딩) — 랭킹→상금 도전 흐름 ===== */}
<RankingBoard lang={lang} />
{/* ===== 누적 랭킹 TOP 10 (골드 카드 위 · 폴딩) — 현재 리그 기준 집계 ===== */}
<RankingBoard lang={lang} league={match.league} />
{/* ===== 골드 상금 (003) ===== */}
<section className="gold-card mt-5 rounded-2xl p-5">
@@ -599,9 +611,9 @@ export default function Arena({
{(
[
[t.rulesExact, 5],
[t.rulesCloseGrade, 3],
[isBaseball ? t.rulesCloseGradeBB : t.rulesCloseGrade, 3],
[t.rulesOutcome, 2],
[t.rulesPartial, 1],
[isBaseball ? t.rulesPartialBB : t.rulesPartial, 1],
[t.rulesMiss, 0],
] as [string, number][]
).map(([label, pt]) => (
@@ -670,11 +682,13 @@ function Stepper({
value,
onChange,
disabled,
max = 9,
}: {
label: string;
value: number;
onChange: (n: number) => void;
disabled?: boolean;
max?: number;
}) {
return (
<div className="flex items-center gap-3">
@@ -687,7 +701,7 @@ function Stepper({
</span>
<span className="mt-1 text-[11px] text-[var(--ink-muted)]">{label}</span>
</div>
<StepBtn disabled={disabled || value >= 9} onClick={() => onChange(Math.min(9, value + 1))}>
<StepBtn disabled={disabled || value >= max} onClick={() => onChange(Math.min(max, value + 1))}>
+
</StepBtn>
</div>
+51 -1
View File
@@ -2,6 +2,7 @@ import { Link, useNavigate } from "react-router-dom";
import ShareButton from "./ShareButton";
import LangSwitch from "./LangSwitch";
import { type Lang, dict } from "@/lib/i18n";
import type { League } from "@/lib/types";
type Share = { url: string; title: string; text: string };
@@ -10,10 +11,12 @@ export default function Hero({
back = false,
share,
lang = "ko",
league = "wc",
}: {
back?: boolean;
share?: Share;
lang?: Lang;
league?: League;
}) {
const t = dict(lang);
const navigate = useNavigate();
@@ -54,8 +57,55 @@ export default function Hero({
</div>
</div>
<div className="mt-2 inline-block rounded-full border border-white/12 bg-white/8 px-3 py-1 text-[13px] font-semibold text-white/85">
{t.heroPill}
{league === "kbo"
? lang === "en"
? "AI-powered 2026 KBO League game predictions"
: "AI와 함께하는 2026 프로야구 KBO 승부예측 챌린지"
: league === "mlb"
? lang === "en"
? "AI-powered 2026 MLB game predictions"
: "AI와 함께하는 2026 MLB 승부예측 챌린지"
: t.heroPill}
</div>
<LeagueTabs lang={lang} current={league} />
</header>
);
}
// 리그 전환 탭 — 단일 앱 내 전환. 탭 클릭 시 해당 리그 대시보드로 이동.
function LeagueTabs({ lang, current }: { lang: Lang; current: League }) {
const navigate = useNavigate();
const tabs: { key: League; label: string }[] = [
{ key: "wc", label: lang === "en" ? "World Cup" : "월드컵" },
{ key: "kbo", label: "KBO" },
{ key: "mlb", label: "MLB" },
];
return (
<div className="mt-3 flex justify-center">
<div className="inline-flex rounded-full border border-white/12 bg-white/5 p-1 text-[13px] font-bold">
{tabs.map((tab) =>
tab.key === current ? (
<span
key={tab.key}
className="rounded-full bg-[var(--green)] px-4 py-1.5 text-black"
>
{tab.label}
</span>
) : (
<button
key={tab.key}
onClick={() =>
navigate(
`/?league=${tab.key}${lang === "en" ? "&lang=en" : ""}`
)
}
className="rounded-full px-4 py-1.5 text-white/45 transition hover:text-white/75"
>
{tab.label}
</button>
),
)}
</div>
</div>
);
}
+295
View File
@@ -0,0 +1,295 @@
import { useEffect, useState } from "react";
import type { Lang } from "@/lib/i18n";
import { timeOnly } from "@/lib/format";
import { getLive, type LiveData } from "@/lib/api";
import type { Match } from "@/lib/types";
// 라이브 필드 뷰 — 수비 배치 다이아몬드 + 현재 타자/투수 + B/S/O + 주자 + 대기타석.
// phase === "live" 일 때 20초 폴링. (?debugLive=1 로 종료 경기에서도 강제 표시)
// 포지션 → 필드 위 좌표(%) — left/top (SVG viewBox 100×70 과 동일 비율)
const POS_XY: Record<string, [number, number]> = {
포수: [50, 90],
"1루수": [71, 55],
"2루수": [61, 39],
유격수: [39, 39],
"3루수": [29, 55],
좌익수: [20, 26],
중견수: [50, 14],
우익수: [80, 26],
};
// 필드 SVG 상 베이스 좌표 (viewBox 0 0 100 70) — 1루·2루·3루
const BASE_XY: [number, number][] = [
[63.5, 42.5],
[50, 29],
[36.5, 42.5],
];
function NameChip({
name,
sub,
accent = false,
x,
y,
}: {
name: string;
sub?: string;
accent?: boolean;
x: number;
y: number;
}) {
return (
<div
className="absolute -translate-x-1/2 -translate-y-1/2 text-center"
style={{ left: `${x}%`, top: `${y}%` }}
>
<div
className={`whitespace-nowrap rounded-full px-2.5 py-1 text-[11px] font-bold shadow-[0_1px_3px_rgba(0,0,0,0.25)] ${
accent ? "bg-[#d94141] text-white" : "bg-white text-[#222]"
}`}
>
{name}
</div>
{sub && (
<div className="mt-0.5 text-[9px] font-bold text-[#245c2a]/80">{sub}</div>
)}
</div>
);
}
function Dot({ on, color }: { on: boolean; color: string }) {
return (
<span
className="inline-block h-2.5 w-2.5 rounded-full"
style={{ background: on ? color : "rgba(255,255,255,0.14)" }}
/>
);
}
// 구장 SVG — 부채꼴 외야 + 파울라인 + 흙 내야 + 마운드 + 베이스(주자 점등).
// 경기 전(빈 구장)·경기 중·종료 스냅샷 모두 공용.
function BallparkSvg({ bases }: { bases?: boolean[] }) {
return (
<svg
viewBox="0 0 100 70"
preserveAspectRatio="none"
className="absolute inset-0 h-full w-full"
>
<rect width="100" height="70" fill="#4e8a48" />
<path
d="M50,62 L8,20 A60,60 0 0 1 92,20 Z"
fill="#6cb163"
stroke="rgba(255,255,255,0.85)"
strokeWidth="0.5"
/>
<polygon points="50,20 73,43 50,66 27,43" fill="#cd9f63" />
<polygon
points="50,29 63.5,42.5 50,56 36.5,42.5"
fill="#6cb163"
stroke="rgba(255,255,255,0.4)"
strokeWidth="0.4"
/>
<circle cx="50" cy="43" r="3.2" fill="#cd9f63" />
<circle cx="50" cy="60.5" r="4.2" fill="#cd9f63" />
{BASE_XY.map(([cx, cy], i) => (
<rect
key={i}
x={cx - 1.5}
y={cy - 1.5}
width="3"
height="3"
rx="0.5"
transform={`rotate(45 ${cx} ${cy})`}
fill={bases?.[i] ? "#ffd23e" : "#ffffff"}
stroke="rgba(0,0,0,0.15)"
strokeWidth="0.3"
/>
))}
<rect x="48.8" y="59.3" width="2.4" height="2.4" rx="0.4" fill="#ffffff" />
</svg>
);
}
export default function LiveField({ match, lang = "ko" }: { match: Match; lang?: Lang }) {
const isLive = match.phase === "live";
// 경기 중엔 20초 폴링, 그 외(경기 전·종료)는 1회 로드.
// 경기 전엔 중계 미게시(available=false)라도 빈 구장 + "경기 전"으로 표시.
const [data, setData] = useState<LiveData | null>(null);
const isBaseball = match.league === "kbo" || match.league === "mlb";
useEffect(() => {
if (!isBaseball) return;
let alive = true;
const load = () =>
getLive(match.matchId)
.then((d) => alive && setData(d))
.catch(() => {});
load();
if (!isLive) return () => { alive = false; };
const id = setInterval(load, 20_000);
return () => {
alive = false;
clearInterval(id);
};
}, [isBaseball, isLive, match.matchId]);
// 야구 전용 위젯 — 축구(월드컵)에서는 렌더하지 않음
if (!isBaseball) return null;
// 중계 데이터 없음 (경기 전 또는 시작 직후) — 빈 구장 + 상태 라벨
if (!data?.available) {
if (match.phase === "finished") return null; // 종료인데 기록 없음 — 표시할 것 없음
return (
<section className="mt-4">
<div className="rounded-3xl border border-white/10 bg-[#171b21] p-4">
<div className="flex items-center justify-between">
<span className="text-[13px] font-extrabold text-white/45">
{lang === "en" ? "FIELD" : "필드"}
</span>
<span className="font-mono text-[13px] font-bold text-white/55">
{timeOnly(match.kickoffKst)} KST
</span>
</div>
<div className="relative mt-3 aspect-[10/7] overflow-hidden rounded-2xl">
<BallparkSvg />
<div className="absolute inset-0 grid place-items-center">
<span className="rounded-full bg-black/50 px-4 py-1.5 text-[13px] font-extrabold text-white/95">
{isLive
? lang === "en"
? "Starting soon…"
: "경기 시작 대기 중"
: lang === "en"
? "Pre-game · lineups TBA"
: "경기 전 · 라인업 발표 전"}
</span>
</div>
</div>
</div>
</section>
);
}
const half = data.half === "B" ? (lang === "en" ? "Bot" : "말") : lang === "en" ? "Top" : "초";
const battingTeam = data.half === "B" ? match.teamB : match.teamA;
const num = (v: unknown) => Number(v ?? 0) || 0;
return (
<section className="mt-4">
<div className="rounded-3xl border border-white/10 bg-[#171b21] p-4">
{/* 헤더: 이닝·스코어·B/S/O */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{isLive ? (
<>
<span className="flex h-2 w-2">
<span className="absolute inline-flex h-2 w-2 animate-ping rounded-full bg-[#FF5B5B] opacity-60" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-[#FF5B5B]" />
</span>
<span className="text-[13px] font-extrabold text-[#FF5B5B]">
LIVE · {data.inn}
{lang === "en" ? ` (${half})` : `회${half}`}
</span>
</>
) : (
<span className="text-[13px] font-extrabold text-white/45">
{lang === "en" ? "FINAL" : "경기 종료"} · {data.inn}
{lang === "en" ? ` (${half})` : `회${half}`}
</span>
)}
</div>
<span className="font-mono text-[18px] font-extrabold tabular-nums">
{match.teamA.shortName} {num(data.score?.away)}
<span className="px-1 text-white/40">:</span>
{num(data.score?.home)} {match.teamB.shortName}
</span>
</div>
{/* B/S/O + 주자 다이아몬드 */}
<div className="mt-3 flex items-center justify-between rounded-2xl bg-white/[0.04] px-3 py-2">
<div className="space-y-1 text-[10px] font-bold text-white/50">
<div className="flex items-center gap-1.5">
B{" "}
{[0, 1, 2].map((i) => (
<Dot key={i} on={num(data.bso?.b) > i} color="#4ade80" />
))}
</div>
<div className="flex items-center gap-1.5">
S{" "}
{[0, 1].map((i) => (
<Dot key={i} on={num(data.bso?.s) > i} color="#facc15" />
))}
</div>
<div className="flex items-center gap-1.5">
O{" "}
{[0, 1].map((i) => (
<Dot key={i} on={num(data.bso?.o) > i} color="#f87171" />
))}
</div>
</div>
<div className="text-right text-[11px] font-semibold text-white/55">
<div>
{lang === "en" ? "AB" : "타석"}{" "}
<span className="font-extrabold text-white/90">{battingTeam.shortName}</span>
</div>
{data.vsRecord && <div className="mt-0.5 text-[10px] text-white/35">{data.vsRecord}</div>}
</div>
</div>
{/* 필드: 구장 SVG + 수비 배치/투수/타자 칩 */}
<div className="relative mt-3 aspect-[10/7] overflow-hidden rounded-2xl">
<BallparkSvg bases={data.bases} />
{data.defense?.map((f) => {
const xy = POS_XY[f.pos ?? ""];
if (!xy) return null;
return <NameChip key={f.pos} name={f.name} sub={f.pos} x={xy[0]} y={xy[1]} />;
})}
{data.pitcher && (
<NameChip
name={data.pitcher.name}
sub={`${lang === "en" ? "P" : "투구수"} ${num(data.pitcher.ballCount)}`}
x={50}
y={61}
/>
)}
{data.batter && (
<NameChip
name={`${data.batter.order ?? ""}. ${data.batter.name}`}
accent
x={50}
y={79}
/>
)}
</div>
{/* 대기타석 */}
{data.batter && data.offenseLineup && (
<div className="mt-3 flex items-center gap-2 overflow-x-auto pb-1 text-[11px] font-semibold text-white/55 [scrollbar-width:thin] [scrollbar-color:rgba(255,255,255,.22)_transparent] [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-white/20">
<span className="shrink-0 text-white/35">{lang === "en" ? "Next" : "대기타석"}</span>
{data.offenseLineup
.filter((b) => {
const cur = data.batter!.order ?? 0;
const diff = ((b.order ?? 0) - cur + 9) % 9;
return diff >= 1 && diff <= 3;
})
.sort((a, b) => {
const cur = data.batter!.order ?? 0;
return (((a.order ?? 0) - cur + 9) % 9) - (((b.order ?? 0) - cur + 9) % 9);
})
.map((b) => (
<span
key={b.order}
className="shrink-0 rounded-full border border-white/10 px-2 py-0.5"
>
{b.order}. {b.name}
{b.sub ? " ↺" : ""}
</span>
))}
</div>
)}
</div>
</section>
);
}
+112 -12
View File
@@ -5,17 +5,39 @@ import BallIcon from "./BallIcon";
import TeamFlag from "./TeamFlag";
import WaveStrip from "./WaveStrip";
// 순위 캐시 → "3위 · 52승37패 (0.584)" 한 줄 (야구)
function standingLine(
st: { rank?: number | null; w?: number; l?: number; wra?: string | number } | null | undefined,
lang: Lang,
): string | null {
if (!st?.rank) return null;
const rank = lang === "en" ? `#${st.rank}` : `${st.rank}위`;
if (st.w == null || st.l == null) return rank;
const rec = lang === "en" ? `${st.w}W ${st.l}L` : `${st.w}승${st.l}패`;
return `${rank} · ${rec}${st.wra ? ` (${st.wra})` : ""}`;
}
export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?: Lang }) {
const t = dict(lang);
const { group } = match;
const finished = !!match.result;
// 한국을 항상 왼쪽에 표시(요청). 데이터/투표는 원본 A/B 프레임 유지, 화면 좌우만 교체.
const flip = match.teamB.code === "KOR" && match.teamA.code !== "KOR";
const isBaseball = match.league === "kbo" || match.league === "mlb";
// 축구: 한국을 항상 왼쪽에. 야구: A=원정(좌), B=홈(우) 고정.
const flip = !isBaseball && match.teamB.code === "KOR" && match.teamA.code !== "KOR";
const left = flip ? match.teamB : match.teamA;
const right = flip ? match.teamA : match.teamB;
const leftScore = flip ? match.result?.scoreB : match.result?.scoreA;
const rightScore = flip ? match.result?.scoreA : match.result?.scoreB;
// 마스코트(파도타기 등)는 모든 경기에서 노출.
const ex = match.extras;
const spL = ex?.starterA;
const spR = ex?.starterB;
const stL = standingLine(ex?.standings?.a, lang);
const stR = standingLine(ex?.standings?.b, lang);
const vs = ex?.seasonVs;
const hasVs = !!vs && vs.aWin != null && vs.bWin != null;
const flagCls = isBaseball ? "mx-auto h-[72px] w-[72px]" : "mx-auto h-[68px] w-[104px]";
return (
<section className="mt-6">
{/* 대결 카드 (녹색 글로우 보더) */}
@@ -23,10 +45,12 @@ export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?
className="relative rounded-3xl border-2 border-[var(--green)] bg-[#171b21] p-5"
style={{ boxShadow: "0 0 28px rgba(74,255,160,0.35), inset 0 0 24px rgba(74,255,160,0.06)" }}
>
{/* 박스 오른쪽 상단 파도타기 (응원 5마리) — 모든 경기 노출 */}
<div className="absolute right-2 top-2 z-10">
<WaveStrip />
</div>
{/* 파도타기 마스코트 — 축구 전용 (야구는 미노출) */}
{!isBaseball && (
<div className="absolute right-2 top-2 z-10">
<WaveStrip />
</div>
)}
{/* 헤더: 브랜드 아이콘 + 팀명 + 일시 */}
<div className="flex items-center gap-3">
@@ -38,15 +62,22 @@ export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?
</div>
<div className="mt-1 text-[15px] font-bold text-[var(--green)]">
{kickoffDisplay(match.kickoffKst, lang)} ·{" "}
{group ? t.group(group) : tRound(match.roundLabel, lang)}
{!isBaseball && group ? t.group(group) : tRound(match.roundLabel, lang)}
</div>
<div className="mt-0.5 text-[12px] text-white/65">
{match.venue}
{isBaseball && (
<span className="text-white/40">
{" "}· {lang === "en" ? "Home: " : "홈 "}{teamShort(right, lang)}
</span>
)}
</div>
<div className="mt-0.5 text-[12px] text-white/65">{match.venue}</div>
</div>
</div>
{/* 국기 + 라이트닝 VS (종료 시 최종 스코어) */}
{/* 국기/로고 + 라이트닝 VS (종료 시 최종 스코어) */}
<div className="mt-5 grid grid-cols-[1fr_auto_1fr] items-center gap-3">
<TeamFlag team={left} className="mx-auto h-[68px] w-[104px]" />
<TeamFlag team={left} className={flagCls} />
<div className="relative grid place-items-center">
<div className="vs-glow absolute h-28 w-28" />
{finished && match.result ? (
@@ -64,9 +95,78 @@ export default function MatchupHUD({ match, lang = "ko" }: { match: Match; lang?
</span>
)}
</div>
<TeamFlag team={right} className="mx-auto h-[68px] w-[104px]" />
<TeamFlag team={right} className={flagCls} />
</div>
{/* 야구 정보 패널: 선발 매치업 · 순위 · 시즌 상대전적 (캐시 있을 때만) */}
{isBaseball && (spL || spR || stL || stR || hasVs) && (
<div className="mt-4 rounded-2xl bg-white/[0.04] p-3.5 text-[12px]">
{(spL || spR) && (
<div className="grid grid-cols-[1fr_auto_1fr] items-start gap-2">
<div className="min-w-0">
<div className="truncate font-extrabold text-white/90">
{spL?.name ?? (lang === "en" ? "TBA" : "미정")}
{spL?.hitType ? (
<span className="ml-1 font-semibold text-white/40">{spL.hitType.slice(0, 2)}</span>
) : null}
</div>
{spL?.era != null && (
<div className="mt-0.5 text-white/50">
ERA {spL.era}
{spL.w != null ? ` · ${spL.w}${lang === "en" ? "W" : "승"}${spL.l ?? 0}${lang === "en" ? "L" : "패"}` : ""}
</div>
)}
</div>
<span className="pt-0.5 text-[11px] font-bold text-[var(--green)]">
{lang === "en" ? "Starting P" : "선발 투수"}
</span>
<div className="min-w-0 text-right">
<div className="truncate font-extrabold text-white/90">
{spR?.hitType ? (
<span className="mr-1 font-semibold text-white/40">{spR.hitType.slice(0, 2)}</span>
) : null}
{spR?.name ?? (lang === "en" ? "TBA" : "미정")}
</div>
{spR?.era != null && (
<div className="mt-0.5 text-white/50">
ERA {spR.era}
{spR.w != null ? ` · ${spR.w}${lang === "en" ? "W" : "승"}${spR.l ?? 0}${lang === "en" ? "L" : "패"}` : ""}
</div>
)}
</div>
</div>
)}
{(stL || stR) && (
<div className="mt-2.5 flex items-center justify-between border-t border-white/10 pt-2.5 text-white/55">
<span className="truncate">{stL ?? "—"}</span>
<span className="px-2 text-[10px] text-white/30">{lang === "en" ? "STANDINGS" : "순위"}</span>
<span className="truncate text-right">{stR ?? "—"}</span>
</div>
)}
{hasVs && (
<div className="mt-2.5 border-t border-white/10 pt-2.5">
<div className="flex items-center justify-between font-bold text-white/75">
<span>{vs!.aWin}{lang === "en" ? "W" : "승"}</span>
<span className="text-[10px] text-white/35">
{lang === "en" ? "SEASON H2H" : "시즌 상대전적"}
{vs!.draw ? ` · ${vs!.draw}${lang === "en" ? "D" : "무"}` : ""}
</span>
<span>{vs!.bWin}{lang === "en" ? "W" : "승"}</span>
</div>
<div className="mt-1.5 flex h-1.5 gap-0.5 overflow-hidden rounded-full">
<div
className="bg-[var(--green)]/80"
style={{ width: `${(100 * (vs!.aWin ?? 0)) / Math.max(1, (vs!.aWin ?? 0) + (vs!.bWin ?? 0))}%` }}
/>
<div className="flex-1 bg-white/20" />
</div>
</div>
)}
</div>
)}
{finished && (
<div className="mt-3 text-center text-[12px] font-bold text-[var(--green)]">
{t.matchEnded}
+4 -2
View File
@@ -9,9 +9,11 @@ import type { RankingEntry, RankingTab } from "@/lib/types";
export default function RankingBoard({
lang = "ko",
defaultOpen = false,
league = "",
}: {
lang?: Lang;
defaultOpen?: boolean;
league?: string; // 리그별 집계 ("" = 전체 통합)
}) {
const t = dict(lang);
const [open, setOpen] = useState(defaultOpen);
@@ -24,7 +26,7 @@ export default function RankingBoard({
if (!open) return;
let alive = true;
setLoaded(false);
fetchRanking(tab)
fetchRanking(tab, league)
.then((r) => {
if (!alive) return;
setRows(r);
@@ -38,7 +40,7 @@ export default function RankingBoard({
return () => {
alive = false;
};
}, [open, tab]);
}, [open, tab, league]);
return (
<section className="mt-5 rounded-2xl border border-[var(--line-d)] bg-[var(--bg2)] p-4">
+200 -45
View File
@@ -1,9 +1,11 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { timeOnly, dateKey } from "@/lib/format";
import { getLive, type LiveData } from "@/lib/api";
import { type Lang, dict, teamShort, roundLabel as tRound, dayName, monthEn } from "@/lib/i18n";
import type { Match, MatchPhase } from "@/lib/types";
import type { League, Match, MatchPhase } from "@/lib/types";
import TeamFlag from "./TeamFlag";
import StandingsTable from "./StandingsTable";
// 칩용 짧은 날짜: "6.12 (금)" / "Jun 12 (Fri)"
function shortDate(iso: string, lang: Lang): string {
@@ -20,22 +22,27 @@ const PHASE_CLS: Record<MatchPhase, string> = {
locked: "border-[var(--line-d)] text-white/45",
live: "border-[#FF5B5B] text-[#FF5B5B]",
finished: "border-white/15 text-white/55",
cancelled: "border-white/10 text-white/35",
};
// 토너먼트 탭 라운드 칩 정렬(대진 순서)
const KO_ROUND_ORDER = ["32강", "16강", "8강", "4강", "3·4위전", "결승"];
const isGroupLetter = (s: string) => /^[A-Z]$/.test(s);
type Tab = "date" | "group" | "tournament";
type Tab = "date" | "group" | "tournament" | "team" | "rank";
export default function ScheduleBoard({
matches,
lang = "ko",
league = "wc",
}: {
matches: Match[];
lang?: Lang;
league?: League;
}) {
const t = dict(lang);
// 야구(KBO/MLB)는 조/토너먼트 대신 날짜별/팀별 탭 제공
const isBaseball = league !== "wc";
// 날짜 목록 (정렬)
const dates = useMemo(
@@ -63,11 +70,34 @@ export default function ScheduleBoard({
// 시작 탭: 토너먼트가 시작됐으면 '토너먼트', 아니면 '날짜별'.
// 단, 직전 세션 선택이 있으면 우선(상세 진입 후 뒤로가기 복원).
const [tab, setTab] = useState<Tab>(() => {
const [tab, setTabRaw] = useState<Tab>(() => {
const saved = sessionStorage.getItem("tp.sched.tab");
if (saved === "date" || saved === "group" || saved === "tournament") return saved;
if (
saved === "date" || saved === "group" || saved === "tournament" ||
saved === "team" || saved === "rank"
)
return saved;
if (isBaseball) return "date";
return rounds.length > 0 ? "tournament" : "date";
});
// 리그에 없는 탭이 저장돼 있으면 날짜별로 강등 (야구↔축구 전환 시)
const effTab: Tab = isBaseball
? (tab === "team" || tab === "rank" ? tab : "date")
: (tab === "team" || tab === "rank" ? "date" : tab);
const setTab = setTabRaw;
// 팀별 탭: 등장 팀 목록 (짧은 이름 가나다/알파벳 순)
const teams = useMemo(() => {
if (!isBaseball) return [];
const byCode = new Map<string, Match["teamA"]>();
for (const m of matches) {
byCode.set(m.teamA.code, m.teamA);
byCode.set(m.teamB.code, m.teamB);
}
return [...byCode.values()].sort((a, b) =>
teamShort(a, lang).localeCompare(teamShort(b, lang), lang === "en" ? "en" : "ko"),
);
}, [matches, isBaseball, lang]);
// 기본 선택: 오늘(없으면 첫 날짜) / A조 / 현재 진행 라운드.
// 단, 직전 세션 선택을 sessionStorage 에 보관 → 상세 진입 후 뒤로가기 시 그대로 복원(오늘로 초기화 X).
@@ -87,6 +117,9 @@ export default function ScheduleBoard({
if (saved && rounds.includes(saved)) return saved;
return currentRound;
});
const [selTeam, setSelTeam] = useState(
() => sessionStorage.getItem("tp.sched.team") ?? "",
);
// 선택 변경 시 보관(다음 진입/뒤로가기에서 복원)
useEffect(() => {
@@ -101,29 +134,58 @@ export default function ScheduleBoard({
useEffect(() => {
sessionStorage.setItem("tp.sched.tab", tab);
}, [tab]);
useEffect(() => {
if (selTeam) sessionStorage.setItem("tp.sched.team", selTeam);
}, [selTeam]);
useEffect(() => {
if (dates.length && !dates.includes(selDate)) {
setSelDate(dates.includes(todayKey) ? todayKey : dates[0]);
}
}, [dates, selDate, todayKey]);
// 리그 전환 시 목록에 없는 팀이면 첫 팀으로
useEffect(() => {
if (teams.length && !teams.some((tm) => tm.code === selTeam)) {
setSelTeam(teams[0].code);
}
}, [teams, selTeam]);
const shown = useMemo(() => {
let list: Match[];
if (tab === "date") list = matches.filter((m) => dateKey(m.kickoffKst) === selDate);
else if (tab === "group") list = matches.filter((m) => !!m.group && m.group === selGroup);
if (effTab === "date") list = matches.filter((m) => dateKey(m.kickoffKst) === selDate);
else if (effTab === "team")
list = matches.filter((m) => m.teamA.code === selTeam || m.teamB.code === selTeam);
else if (effTab === "group") list = matches.filter((m) => !!m.group && m.group === selGroup);
else list = matches.filter((m) => m.roundLabel === selRound); // 토너먼트
return [...list].sort(
(a, b) => new Date(a.kickoffKst).getTime() - new Date(b.kickoffKst).getTime(),
);
}, [matches, tab, selDate, selGroup, selRound]);
}, [matches, effTab, selDate, selGroup, selRound, selTeam]);
const tabLabel = (k: Tab) =>
k === "date"
? lang === "en"
? "By date"
: "날짜별"
: k === "group"
: k === "team"
? lang === "en"
? "Groups"
: "조별리그"
: lang === "en"
? "Tournament"
: "토너먼트";
? "By team"
: "팀별"
: k === "rank"
? lang === "en"
? "Standings"
: "순위"
: k === "group"
? lang === "en"
? "Groups"
: "조별리그"
: lang === "en"
? "Tournament"
: "토너먼트";
const leagueTabs: Tab[] = isBaseball
? ["date", "team", "rank"]
: ["date", "group", "tournament"];
return (
<section className="mt-6">
@@ -132,14 +194,14 @@ export default function ScheduleBoard({
<span className="whitespace-nowrap text-[12px] text-white/55">{t.schedGuide}</span>
</div>
{/* 탭: 날짜별 / 조별리그 / 토너먼트 */}
{/* 탭: 축구 = 날짜별/조별리그/토너먼트 · 야구 = 날짜별/팀별 */}
<div className="mb-3 flex gap-5 border-b border-[var(--line-d)]">
{(["date", "group", "tournament"] as Tab[]).map((k) => (
{leagueTabs.map((k) => (
<button
key={k}
onClick={() => setTab(k)}
className={`-mb-px border-b-2 pb-2 text-[15px] font-bold transition ${
tab === k
effTab === k
? "border-[var(--green)] text-white"
: "border-transparent text-white/45"
}`}
@@ -149,32 +211,47 @@ export default function ScheduleBoard({
))}
</div>
{/* 순위 탭: 칩/카드 대신 순위표 */}
{effTab === "rank" && <StandingsTable league={league} lang={lang} />}
{/* 칩: 날짜 / 조 / 라운드 — 단일 줄 가로 스크롤 + 양 끝 화살표(PC에서 마우스로 넘김, 끝 도달 시 숨김) */}
<ChipScroller resetKey={tab}>
{tab === "date"
{effTab !== "rank" && (
<ChipScroller resetKey={`${league}:${effTab}`}>
{effTab === "date"
? dates.map((d) => (
<Chip key={d} active={d === selDate} onClick={() => setSelDate(d)}>
{shortDate(d, lang)}
</Chip>
))
: tab === "group"
? groups.map((g) => (
<Chip key={g} active={g === selGroup} onClick={() => setSelGroup(g)}>
{lang === "en" ? `Group ${g}` : `${g}조`}
: effTab === "team"
? teams.map((tm) => (
<Chip key={tm.code} active={tm.code === selTeam} onClick={() => setSelTeam(tm.code)}>
<span className="flex items-center gap-1.5">
<TeamFlag team={tm} className="h-4 w-4 shrink-0" />
{teamShort(tm, lang)}
</span>
</Chip>
))
: rounds.map((r) => (
<Chip key={r} active={r === selRound} onClick={() => setSelRound(r)}>
{tRound(r, lang)}
</Chip>
))}
: effTab === "group"
? groups.map((g) => (
<Chip key={g} active={g === selGroup} onClick={() => setSelGroup(g)}>
{lang === "en" ? `Group ${g}` : `${g}조`}
</Chip>
))
: rounds.map((r) => (
<Chip key={r} active={r === selRound} onClick={() => setSelRound(r)}>
{tRound(r, lang)}
</Chip>
))}
</ChipScroller>
)}
{/* 경기 카드 */}
{effTab !== "rank" && (
<div className="flex flex-col gap-2.5">
{shown.length === 0 && (
<p className="py-6 text-center text-[13px] text-white/45">
{tab === "tournament"
{effTab === "tournament"
? lang === "en"
? "Bracket is set after the group stage."
: "토너먼트 대진은 조별리그 종료 후 확정됩니다"
@@ -184,9 +261,10 @@ export default function ScheduleBoard({
</p>
)}
{shown.map((m) => (
<MatchCard key={m.matchId} match={m} lang={lang} />
<MatchCard key={m.matchId} match={m} lang={lang} showDate={effTab === "team"} />
))}
</div>
)}
</section>
);
}
@@ -301,44 +379,99 @@ function Chip({
);
}
function MatchCard({ match, lang }: { match: Match; lang: Lang }) {
// 팀명 옆 순위 배지 (야구 — 순위 캐시 없으면 렌더 안 함)
function RankBadge({ rank, lang = "ko" }: { rank?: number | null; lang?: Lang }) {
if (!rank) return null;
return (
<span className="shrink-0 rounded border border-white/15 px-1 py-px text-[10px] font-bold text-white/45">
{lang === "en" ? `#${rank}` : `${rank}위`}
</span>
);
}
function MatchCard({
match,
lang,
showDate = false,
}: {
match: Match;
lang: Lang;
showDate?: boolean;
}) {
const t = dict(lang);
const phase = match.phase;
const finished = !!match.result;
const isBaseball = match.league === "kbo" || match.league === "mlb";
// 야구 진행 중: 회차·스코어 표시 (서버 15초 캐시라 부담 없음, 30초 폴링)
const [live, setLive] = useState<LiveData | null>(null);
useEffect(() => {
if (phase !== "live" || !isBaseball) return;
let alive = true;
const load = () =>
getLive(match.matchId)
.then((d) => {
if (alive && d.available) setLive(d);
})
.catch(() => {});
load();
const id = setInterval(load, 30_000);
return () => {
alive = false;
clearInterval(id);
};
}, [match.matchId, phase, isBaseball]);
// "6회초" / "Top 6"
const inning =
live?.inn != null
? lang === "en"
? `${live.half === "B" ? "Bot" : "Top"} ${live.inn}`
: `${live.inn}회${live.half === "B" ? "말" : "초"}`
: null;
// 한국을 항상 왼쪽에 표시(상세 페이지와 동일 규칙). 데이터는 원본 A/B 유지, 화면 좌우만 교체.
const flip = match.teamB.code === "KOR" && match.teamA.code !== "KOR";
const flip = !isBaseball && match.teamB.code === "KOR" && match.teamA.code !== "KOR";
const left = flip ? match.teamB : match.teamA;
const right = flip ? match.teamA : match.teamB;
const leftScore = flip ? match.result?.scoreB : match.result?.scoreA;
const rightScore = flip ? match.result?.scoreA : match.result?.scoreB;
const flagCls = isBaseball ? "h-7 w-7 shrink-0" : "h-6 w-9 shrink-0";
// 비투표(타 조)는 클릭 비활성, 투표 가능 조(A)는 상세로 이동
const inner = (
<>
<div className="flex items-center justify-between text-[11px]">
<span className="font-mono font-bold text-white/70">
{showDate && (
<span className="text-white/55">{shortDate(dateKey(match.kickoffKst), lang)} </span>
)}
{timeOnly(match.kickoffKst)} <span className="text-white/40">KST</span>
{/* 조별리그 seed 의 부가 라벨(예: 개막전)만 여기에. 녹아웃 라운드는 우측에 표시. */}
{match.group && match.roundLabel ? <> · {tRound(match.roundLabel, lang)}</> : null}
{isBaseball && match.venue ? (
<span className="text-white/40"> · {match.venue}</span>
) : match.group && match.roundLabel ? (
<> · {tRound(match.roundLabel, lang)}</>
) : null}
</span>
<span className="flex items-center gap-1.5">
<span className="text-[11px] font-bold text-white/45">
{match.group
? lang === "en"
? `Group ${match.group}`
: `${match.group}조`
: tRound(match.roundLabel, lang)}
</span>
{!isBaseball && (
<span className="text-[11px] font-bold text-white/45">
{match.group
? lang === "en"
? `Group ${match.group}`
: `${match.group}조`
: tRound(match.roundLabel, lang)}
</span>
)}
<span className={`rounded-md border px-2 py-0.5 font-semibold ${PHASE_CLS[phase]}`}>
{t.phase[phase]}
{phase === "live" && inning ? inning : t.phase[phase]}
</span>
</span>
</div>
<div className="mt-3 grid grid-cols-[1fr_auto_1fr] items-center gap-2">
<div className="flex items-center gap-2">
<TeamFlag team={left} className="h-6 w-9 shrink-0" />
<TeamFlag team={left} className={flagCls} />
<span className="truncate text-[15px] font-extrabold">{teamShort(left, lang)}</span>
{isBaseball && <RankBadge rank={match.extras?.standings?.a?.rank} lang={lang} />}
</div>
{match.result ? (
<span className="whitespace-nowrap font-mono text-[18px] font-extrabold tabular-nums text-white">
@@ -346,17 +479,35 @@ function MatchCard({ match, lang }: { match: Match; lang: Lang }) {
<span className="px-1.5 text-white/40">:</span>
{rightScore}
</span>
) : phase === "live" && live?.score ? (
// 진행 중 실시간 스코어 (A=원정, B=홈)
<span className="whitespace-nowrap font-mono text-[18px] font-extrabold tabular-nums text-white">
{live.score.away ?? 0}
<span className="px-1.5 text-[#FF5B5B]">:</span>
{live.score.home ?? 0}
</span>
) : (
<span className="font-impact text-[18px] italic text-[#94FBE0]">VS</span>
)}
<div className="flex items-center justify-end gap-2">
{isBaseball && <RankBadge rank={match.extras?.standings?.b?.rank} lang={lang} />}
<span className="truncate text-right text-[15px] font-extrabold">{teamShort(right, lang)}</span>
<TeamFlag team={right} className="h-6 w-9 shrink-0" />
<TeamFlag team={right} className={flagCls} />
</div>
</div>
{/* 투표 가능 조만: AI 픽 갈림 + 참여수 + 이동 화살표 */}
{match.votable && (
{/* 야구: 선발 매치업 (프리뷰 캐시 있을 때만) */}
{isBaseball && !match.result && (match.extras?.starterA || match.extras?.starterB) && (
<div className="mt-2 text-center text-[11px] font-semibold text-white/50">
<span className="text-white/35">{lang === "en" ? "SP" : "선발"}</span>{" "}
{match.extras?.starterA?.name ?? "?"}
<span className="px-1 text-white/30">vs</span>
{match.extras?.starterB?.name ?? "?"}
</div>
)}
{/* 투표 가능 조만: AI 픽 갈림 + 참여수 + 이동 화살표 (취소 경기는 숨김) */}
{match.votable && phase !== "cancelled" && (
<div className="mt-3 flex items-center justify-between text-[11px] font-bold text-[#F4F3FE]">
<span>
<span className="font-semibold text-white/55">{t.aiPicks}</span>{" "}
@@ -372,6 +523,10 @@ function MatchCard({ match, lang }: { match: Match; lang: Lang }) {
);
const base = "block rounded-2xl border-2 bg-[#171b21] p-4";
// 취소 경기: 클릭 불가·저채도 표시 전용
if (phase === "cancelled") {
return <div className={`${base} border-[var(--line-d)] opacity-60`}>{inner}</div>;
}
if (match.votable && !finished) {
return (
<Link
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useState } from "react";
import { getStandings } from "@/lib/api";
import { type Lang, teamShort } from "@/lib/i18n";
import type { StandingRow, StandingsOut } from "@/lib/types";
import TeamFlag from "./TeamFlag";
// 야구 리그 순위표 — KBO: 단일 테이블 · MLB: 디비전 6그룹.
// 데이터는 워커가 캐싱한 시즌 순위(/api/standings)로, 하루 수회 갱신된다.
const DIV_LABEL: Record<string, { ko: string; en: string }> = {
ALE: { ko: "AL 동부", en: "AL East" },
ALC: { ko: "AL 중부", en: "AL Central" },
ALW: { ko: "AL 서부", en: "AL West" },
NLE: { ko: "NL 동부", en: "NL East" },
NLC: { ko: "NL 중부", en: "NL Central" },
NLW: { ko: "NL 서부", en: "NL West" },
};
function fmtWra(v: StandingRow["wra"]): string {
if (v == null || v === "") return "-";
const n = typeof v === "number" ? v : parseFloat(v);
return Number.isNaN(n) ? String(v) : n.toFixed(3);
}
function fmtGb(v: StandingRow["gb"]): string {
if (v == null || v === "" || v === "-") return "-";
const n = Number(v);
return !Number.isNaN(n) && n === 0 ? "-" : String(v);
}
export default function StandingsTable({
league,
lang = "ko",
}: {
league: string;
lang?: Lang;
}) {
const [data, setData] = useState<StandingsOut | null>(null);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
let alive = true;
setLoaded(false);
getStandings(league)
.then((d) => {
if (!alive) return;
setData(d);
setLoaded(true);
})
.catch(() => {
if (!alive) return;
setData(null);
setLoaded(true);
});
return () => {
alive = false;
};
}, [league]);
if (!loaded) {
return (
<p className="py-6 text-center text-[13px] text-white/45">
{lang === "en" ? "Loading…" : "불러오는 중…"}
</p>
);
}
if (!data || data.groups.length === 0) {
return (
<p className="py-6 text-center text-[13px] text-white/45">
{lang === "en" ? "Standings not available yet" : "순위 정보가 아직 없습니다"}
</p>
);
}
const hasDraw = league === "kbo"; // KBO 만 무승부 존재
return (
<div className="flex flex-col gap-4">
{data.groups.map((g, gi) => (
<div key={g.key ?? gi} className="rounded-2xl border border-[var(--line-d)] bg-[#171b21] px-3 py-2.5">
{g.key && (
<div className="mb-1.5 px-1 text-[13px] font-extrabold text-[#94FBE0]">
{DIV_LABEL[g.key]?.[lang === "en" ? "en" : "ko"] ?? g.key}
</div>
)}
<table className="w-full text-[13px] tabular-nums">
<thead>
<tr className="text-[11px] font-bold text-white/40">
<th className="w-7 py-1 text-center font-bold">{lang === "en" ? "#" : "순위"}</th>
<th className="py-1 text-left font-bold">{lang === "en" ? "Team" : "팀"}</th>
<th className="w-8 py-1 text-center font-bold">{lang === "en" ? "W" : "승"}</th>
{hasDraw && (
<th className="w-8 py-1 text-center font-bold">{lang === "en" ? "D" : "무"}</th>
)}
<th className="w-8 py-1 text-center font-bold">{lang === "en" ? "L" : "패"}</th>
<th className="w-12 py-1 text-center font-bold">{lang === "en" ? "PCT" : "승률"}</th>
<th className="w-10 py-1 text-center font-bold">{lang === "en" ? "GB" : "게임차"}</th>
</tr>
</thead>
<tbody>
{g.rows.map((r) => (
<tr key={r.code} className="border-t border-white/[0.06]">
<td
className={`py-1.5 text-center font-mono font-extrabold ${
r.rank === 1 ? "text-[#94FBE0]" : "text-white/60"
}`}
>
{r.rank ?? "-"}
</td>
<td className="py-1.5">
<span className="flex items-center gap-1.5">
<TeamFlag team={r} className="h-[18px] w-[18px] shrink-0" />
<span className="truncate font-bold">{teamShort(r, lang)}</span>
</span>
</td>
<td className="py-1.5 text-center font-mono text-white/80">{r.w ?? "-"}</td>
{hasDraw && (
<td className="py-1.5 text-center font-mono text-white/50">{r.d ?? "-"}</td>
)}
<td className="py-1.5 text-center font-mono text-white/80">{r.l ?? "-"}</td>
<td className="py-1.5 text-center font-mono font-bold text-white">{fmtWra(r.wra)}</td>
<td className="py-1.5 text-center font-mono text-white/60">{fmtGb(r.gb)}</td>
</tr>
))}
</tbody>
</table>
</div>
))}
{data.updatedAt && (
<p className="-mt-1 text-right text-[11px] text-white/35">
{(() => {
const d = new Date(data.updatedAt);
const hh = String(d.getHours()).padStart(2, "0");
const mm = String(d.getMinutes()).padStart(2, "0");
return lang === "en"
? `As of ${d.getMonth() + 1}/${d.getDate()} ${hh}:${mm}`
: `${d.getMonth() + 1}.${d.getDate()} ${hh}:${mm} 기준`;
})()}
</p>
)}
</div>
);
}
+17 -3
View File
@@ -1,9 +1,10 @@
import { useState } from "react";
import type { Team } from "@/lib/types";
// 모든 경기에 일반화된 국기 렌더.
// 글로벌 축구 축전 출전 48개국 SVG 자산(/assets/flags/{fifa코드}.svg, 예: kor.svg)을 사용하고,
// 자산이 없는 코드는 이모지 폴백(컨테이너 높이에 비례, 안 잘림).
// 모든 경기에 일반화된 국기/팀로고 렌더.
// 야구(KBO/MLB): 백엔드가 flag 필드에 로고 경로/URL 을 실어줌 → 그대로 img.
// 축구(월드컵): 48개국 SVG 자산(/assets/flags/{fifa코드}.svg) 사용.
// 없으면 이모지 폴백(컨테이너 높이에 비례, 안 잘림).
export default function TeamFlag({
team,
className = "",
@@ -12,6 +13,19 @@ export default function TeamFlag({
className?: string;
}) {
const [failed, setFailed] = useState(false);
const isLogoUrl =
!!team.flag && (team.flag.startsWith("/") || team.flag.startsWith("http"));
if (!failed && isLogoUrl) {
return (
<img
src={team.flag}
alt={team.name}
onError={() => setFailed(true)}
className={`object-contain ${className}`}
/>
);
}
if (!failed && team.code) {
return (
+50 -13
View File
@@ -10,6 +10,7 @@ import type {
MyPrediction,
RankingEntry,
RankingTab,
StandingsOut,
} from "./types";
import type { Lang } from "./i18n";
@@ -42,14 +43,41 @@ export class ApiError extends Error {
}
}
export function listMatches(lang: Lang): Promise<Match[]> {
return http<Match[]>(`/matches?lang=${lang}`);
export function listMatches(lang: Lang, league = ""): Promise<Match[]> {
return http<Match[]>(`/matches?lang=${lang}${league ? `&league=${league}` : ""}`);
}
export function getMatch(matchId: string, lang: Lang): Promise<Match> {
return http<Match>(`/matches/${matchId}?lang=${lang}`);
}
// ── 야구 라이브 필드 뷰 ──────────────────────────────────────
export interface LiveBatter {
order?: number | null;
name: string;
pos?: string;
avg?: number | string | null;
sub?: boolean;
}
export interface LiveData {
available: boolean;
inn?: number;
half?: "T" | "B";
score?: { away?: number | string; home?: number | string };
bso?: { b?: number | string; s?: number | string; o?: number | string };
bases?: boolean[];
batter?: LiveBatter | null;
pitcher?: { name: string; ballCount?: number | string | null } | null;
vsRecord?: string;
defense?: { pos?: string; name: string }[];
offenseLineup?: LiveBatter[];
}
export function getLive(matchId: string): Promise<LiveData> {
return http<LiveData>(`/matches/${matchId}/live`);
}
export interface SubmitResult {
ok: boolean;
predictionId: string;
@@ -73,23 +101,28 @@ export function submitPrediction(body: {
});
}
export function getLeaderboard(): Promise<Leaderboard> {
return http<Leaderboard>(`/leaderboard`);
export function getLeaderboard(league = ""): Promise<Leaderboard> {
return http<Leaderboard>(`/leaderboard${league ? `?league=${league}` : ""}`);
}
// 리그 순위표 (야구 — 워커가 캐싱한 시즌 순위)
export function getStandings(league: string): Promise<StandingsOut> {
return http<StandingsOut>(`/standings?league=${league}`);
}
// AI 모델 누적 랭킹 (종료 경기 합산 — 서버가 매 조회 시 재계산)
export function getAILeaderboard(): Promise<AILeaderboard> {
return http<AILeaderboard>(`/leaderboard/ai`);
export function getAILeaderboard(league = ""): Promise<AILeaderboard> {
return http<AILeaderboard>(`/leaderboard/ai${league ? `?league=${league}` : ""}`);
}
// 랭킹 위젯 공용 — 탭에 맞춰 TOP 10 을 {label, points} 로 정규화해 반환.
// 경기 종료·채점 때마다 서버 값이 갱신되므로 호출 시점 최신 누적이 내려옴.
export async function fetchRanking(tab: RankingTab): Promise<RankingEntry[]> {
// league 를 주면 해당 리그 경기만 집계(빈 값 = 전체 통합).
export async function fetchRanking(tab: RankingTab, league = ""): Promise<RankingEntry[]> {
if (tab === "ai") {
const { standings } = await getAILeaderboard();
const { standings } = await getAILeaderboard(league);
return standings.map((s) => ({ label: s.model, points: s.totalPoints }));
}
const { standings } = await getLeaderboard();
const { standings } = await getLeaderboard(league);
return standings
.slice(0, 10)
.map((s) => ({ label: s.emailMasked, points: s.totalPoints }));
@@ -125,10 +158,14 @@ export function postComment(
// ── 세션 닉네임: 세션당 한 번 발급받아 sessionStorage 에 캐싱 ──
// 탭/창을 닫으면 비워지고(껐다 켜면 새 닉), 시크릿창은 별도 저장소라 새로 발급됨.
// 종목별(축구/야구) 캐시 분리 — 서버가 리그에 맞는 단어풀로 발급하므로
// 축구 닉이 야구 경기에 재사용되지 않게 키를 나눈다.
const SESSION_NICK_KEY = "tp_session_nick";
const nickKey = (matchId: string) =>
`${SESSION_NICK_KEY}.${/^(KBO|MLB)_/.test(matchId) ? "bb" : "wc"}`;
export async function getSessionNickname(matchId: string): Promise<string> {
try {
const cached = sessionStorage.getItem(SESSION_NICK_KEY);
const cached = sessionStorage.getItem(nickKey(matchId));
if (cached) return cached;
} catch {
/* sessionStorage 불가 환경은 매번 발급 */
@@ -137,7 +174,7 @@ export async function getSessionNickname(matchId: string): Promise<string> {
`/matches/${matchId}/comments/nickname`,
);
try {
sessionStorage.setItem(SESSION_NICK_KEY, nickname);
sessionStorage.setItem(nickKey(matchId), nickname);
} catch {
/* noop */
}
@@ -150,7 +187,7 @@ export async function rerollSessionNickname(matchId: string): Promise<string> {
`/matches/${matchId}/comments/nickname`,
);
try {
sessionStorage.setItem(SESSION_NICK_KEY, nickname);
sessionStorage.setItem(nickKey(matchId), nickname);
} catch {
/* noop */
}
+16 -3
View File
@@ -58,7 +58,14 @@ type Dict = {
prizeLine2: string;
schedTitle: string;
schedGuide: string;
phase: { open: string; scheduled: string; locked: string; live: string; finished: string };
phase: {
open: string;
scheduled: string;
locked: string;
live: string;
finished: string;
cancelled: string;
};
aiPicks: string;
draw: string;
joined: (n: string) => string;
@@ -90,8 +97,10 @@ type Dict = {
rulesCumulative: string;
rulesExact: string;
rulesCloseGrade: string;
rulesCloseGradeBB: string; // 야구: 득실차 ±1 허용
rulesOutcome: string;
rulesPartial: string;
rulesPartialBB: string; // 야구: 한 팀 득점 ±1 허용
rulesMiss: string;
rulesEmailRequired: string;
rulesCloseBtn: string;
@@ -163,7 +172,7 @@ export const DICT: Record<Lang, Dict> = {
prizeLine2: "최종 우승자에게 100만원 상금",
schedTitle: "전체 일정",
schedGuide: "투표하고 싶은 경기를 선택해주세요",
phase: { open: "투표 중", scheduled: "오픈 예정", locked: "투표 종료", live: "경기중", finished: "종료" },
phase: { open: "투표 중", scheduled: "오픈 예정", locked: "투표 종료", live: "경기중", finished: "종료", cancelled: "취소" },
aiPicks: "AI 픽",
draw: "무",
joined: (n) => `${n}명 참여`,
@@ -196,8 +205,10 @@ export const DICT: Record<Lang, Dict> = {
rulesCumulative: "경기마다 적중 포인트를 쌓아, 대회 누적 포인트 1위 한 분에게 최종 100만 원을 드립니다.",
rulesExact: "정확 스코어 적중",
rulesCloseGrade: "근접 (승패 + 득실차 일치)",
rulesCloseGradeBB: "근접 (승패 + 득실차 ±1)",
rulesOutcome: "승패만 적중",
rulesPartial: "부분 (한 팀 스코어만 일치)",
rulesPartialBB: "부분 (한 팀 득점 ±1)",
rulesMiss: "빗나감",
rulesEmailRequired:
"픽 제출 시 입력한 이메일로 챌린지에 참여됩니다. 같은 이메일의 모든 경기 포인트가 합산되어 누적 순위가 매겨집니다.",
@@ -266,7 +277,7 @@ export const DICT: Record<Lang, Dict> = {
prizeLine2: "overall winner takes ₩1,000,000",
schedTitle: "All Matches",
schedGuide: "Pick a match to predict",
phase: { open: "Voting", scheduled: "Opens soon", locked: "Closed", live: "Live", finished: "Ended" },
phase: { open: "Voting", scheduled: "Opens soon", locked: "Closed", live: "Live", finished: "Ended", cancelled: "Canceled" },
aiPicks: "AI picks",
draw: "Draw",
joined: (n) => `${n} joined`,
@@ -299,8 +310,10 @@ export const DICT: Record<Lang, Dict> = {
rulesCumulative: "Earn points each match — the player with the highest cumulative total wins ₩1,000,000.",
rulesExact: "Exact score",
rulesCloseGrade: "Close (result + goal difference)",
rulesCloseGradeBB: "Close (result + run diff ±1)",
rulesOutcome: "Correct result only",
rulesPartial: "Partial (one team's score)",
rulesPartialBB: "Partial (one team's runs ±1)",
rulesMiss: "Miss",
rulesEmailRequired:
"You enter the challenge with the email you provide when submitting a pick. Points from all matches under the same email are summed for the overall ranking.",
+50 -1
View File
@@ -2,7 +2,13 @@
export type Outcome = "TEAM_A_WIN" | "DRAW" | "TEAM_B_WIN";
export type ModelName = "GPT" | "Claude" | "Gemini";
export type MatchPhase = "scheduled" | "open" | "locked" | "live" | "finished";
export type MatchPhase =
| "scheduled"
| "open"
| "locked"
| "live"
| "finished"
| "cancelled";
export interface Team {
name: string;
@@ -36,8 +42,50 @@ export interface CrowdStats {
teamBWin: number;
}
// 리그: wc(월드컵 축구) | kbo | mlb
export type League = "wc" | "kbo" | "mlb";
// 야구 부가정보 (프리뷰·순위 캐시 — 없으면 undefined)
export interface StarterInfo {
name: string;
hitType?: string;
era?: string | number | null;
w?: number | null;
l?: number | null;
vsEra?: string | number | null;
}
export interface TeamStanding {
rank?: number | null;
w?: number;
d?: number;
l?: number;
wra?: string | number;
gb?: string | number;
last5?: string | null;
}
// /standings 응답 — 팀 정보(Team) + 시즌 성적 한 행
export interface StandingRow extends Team, TeamStanding {
div?: string | null; // MLB 디비전 키 (ALE/ALC/ALW/NLE/NLC/NLW)
}
export interface StandingsOut {
league: string;
updatedAt?: string | null;
groups: { key: string | null; rows: StandingRow[] }[];
}
export interface MatchExtras {
starterA?: StarterInfo | null;
starterB?: StarterInfo | null;
seasonVs?: { aWin?: number; draw?: number; bWin?: number } | null;
standings?: { a?: TeamStanding | null; b?: TeamStanding | null };
}
export interface Match {
matchId: string;
league: League;
roundLabel: string;
group: string;
teamA: Team;
@@ -54,6 +102,7 @@ export interface Match {
result?: MatchResult | null;
predictions: AIPrediction[];
crowd?: CrowdStats | null;
extras?: MatchExtras | null;
}
export interface UserPick {
+19
View File
@@ -0,0 +1,19 @@
import { useSearchParams } from "react-router-dom";
import type { League } from "./types";
// 리그 상태 — URL 쿼리(?league=)가 SSOT. 기본값은 KBO(메인 탭).
// 링크 공유 시에도 리그가 보존되도록 쿼리 파라미터를 쓴다.
export const DEFAULT_LEAGUE: League = "kbo";
export function useLeague(): [League, (l: League) => void] {
const [params, setParams] = useSearchParams();
const raw = params.get("league");
const league: League =
raw === "wc" || raw === "kbo" || raw === "mlb" ? raw : DEFAULT_LEAGUE;
const setLeague = (l: League) => {
const next = new URLSearchParams(params);
next.set("league", l);
setParams(next, { replace: false });
};
return [league, setLeague];
}
+7 -5
View File
@@ -5,12 +5,14 @@ import Ado2Ad from "@/components/Ado2Ad";
import Footer from "@/components/Footer";
import { dict } from "@/lib/i18n";
import { useLang } from "@/lib/useLang";
import { useLeague } from "@/lib/useLeague";
import { listMatches } from "@/lib/api";
import type { Match } from "@/lib/types";
// L1. 전체 일정 대시보드 (랜딩 진입)
// L1. 전체 일정 대시보드 (랜딩 진입) — 리그 탭(월드컵/KBO/MLB)별 경기 목록
export default function Dashboard() {
const lang = useLang();
const [league] = useLeague();
const t = dict(lang);
const [matches, setMatches] = useState<Match[] | null>(null);
const [error, setError] = useState(false);
@@ -19,17 +21,17 @@ export default function Dashboard() {
let alive = true;
setMatches(null);
setError(false);
listMatches(lang)
listMatches(lang, league)
.then((m) => alive && setMatches(m))
.catch(() => alive && setError(true));
return () => {
alive = false;
};
}, [lang]);
}, [lang, league]);
return (
<main className="shell">
<Hero lang={lang} />
<Hero lang={lang} league={league} />
{/* 기간 안내 + CTA 영역 */}
<div className="mt-5 rounded-2xl border border-[var(--line-d)] bg-[var(--bg2)] p-4 text-center">
@@ -48,7 +50,7 @@ export default function Dashboard() {
{lang === "en" ? "Failed to load matches." : "경기 정보를 불러오지 못했습니다."}
</p>
)}
{matches && <ScheduleBoard matches={matches} lang={lang} />}
{matches && <ScheduleBoard matches={matches} lang={lang} league={league} />}
<Ado2Ad lang={lang} />
<Footer lang={lang} />
+4 -2
View File
@@ -2,11 +2,13 @@ import Hero from "@/components/Hero";
import Footer from "@/components/Footer";
import RankingBoard from "@/components/RankingBoard";
import { useLang } from "@/lib/useLang";
import { useLeague } from "@/lib/useLeague";
// L3. 리더보드 — 누적 포인트 랭킹(참가자/AI 탭). 펼친 상태로 전체 표시.
// 빈 상태·AI 탭·TOP10 렌더는 RankingBoard 위젯이 일괄 처리(매치 페이지와 동일 UI).
// ?league= 쿼리에 따라 해당 리그 경기만 집계(기본 KBO).
export default function Leaderboard() {
const lang = useLang();
const [league] = useLeague();
return (
<main className="shell">
@@ -19,7 +21,7 @@ export default function Leaderboard() {
: "매 경기 누적 점수로 순위를 매기고, 끝까지 가장 잘 맞힌 한 분께 최종 100만원을 드립니다."}
</p>
{/* 전체 페이지: 펼친 상태(폴딩 토글 숨김) */}
<RankingBoard lang={lang} defaultOpen />
<RankingBoard lang={lang} defaultOpen league={league} />
</section>
<Footer lang={lang} />
</main>
+3
View File
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import Hero from "@/components/Hero";
import MatchupHUD from "@/components/MatchupHUD";
import LiveField from "@/components/LiveField";
import Arena from "@/components/Arena";
import Comments from "@/components/Comments";
import Footer from "@/components/Footer";
@@ -69,6 +70,7 @@ export default function MatchDetail() {
<Hero
back
lang={lang}
league={match.league}
share={{
url,
title: `${leftShort} vs ${rightShort} — TriplePick`,
@@ -87,6 +89,7 @@ export default function MatchDetail() {
</h1>
<MatchupHUD match={match} lang={lang} />
<LiveField match={match} lang={lang} />
<Arena
match={match}
predictions={match.predictions}