import { Chess } from "/static/vendor/chess.min.js";
import { Chessground } from "/static/vendor/chessground.min.js";
const $ = (id) => document.getElementById(id);
let cg = null;
let replay = { history: [], evals: new Map(), ply: 0 };
function fenKey(fen) { return fen.split(" ").slice(0, 3).join(" "); }
// ---------- gating ----------
async function checkBlocked() {
try {
const r = await fetch("/api/state");
const s = await r.json();
return !!(s.game && !s.game.status?.result);
} catch (e) { return false; }
}
// ---------- leaderboard ----------
function renderLeaderboard(stats) {
$("games-count").textContent = `${stats.total_games} games`;
const tb = document.querySelector("#leaderboard tbody");
tb.innerHTML = "";
for (const p of stats.players) {
const wr = p.games ? Math.round(100 * (p.wins + 0.5 * p.draws) / p.games) : 0;
const tr = document.createElement("tr");
tr.innerHTML = `
${p.agent} / ${p.model} |
${p.games} |
${p.wins} |
${p.draws} |
${p.losses} |
${p.score.toFixed(1)} |
${wr}% | `;
tb.appendChild(tr);
}
const tp = document.querySelector("#leaderboard-prompts tbody");
tp.innerHTML = "";
for (const p of stats.prompts) {
const tr = document.createElement("tr");
tr.innerHTML = `
${p.prompt} |
${p.games} |
${p.wins} |
${p.draws} |
${p.losses} |
${p.score.toFixed(1)} | `;
tp.appendChild(tr);
}
}
// ---------- games list ----------
function renderGames(games) {
const tb = document.querySelector("#games-table tbody");
tb.innerHTML = "";
for (const g of games) {
const w = g.agents?.white || {};
const b = g.agents?.black || {};
const tr = document.createElement("tr");
const result = g.result || "*";
tr.innerHTML = `
${(g.id || "?").slice(0, 10)}… |
${w.agent || "?"}/${w.model || "?"} ${w.prompt || ""} |
${b.agent || "?"}/${b.model || "?"} ${b.prompt || ""} |
${result} |
${g.termination || ""} |
${g.moves_count ?? 0} |
pgn | `;
tr.querySelector("a[data-id]").addEventListener("click", (e) => {
e.preventDefault();
openReplay(g.id);
});
tb.appendChild(tr);
}
}
// ---------- replay ----------
async function openReplay(id) {
const data = await (await fetch(`/api/games/${id}`)).json();
const meta = data.meta;
const w = meta.agents?.white || {};
const b = meta.agents?.black || {};
$("replay-title").textContent =
`${id.slice(0,10)}… — ${w.agent||"?"}/${w.model||"?"} (${w.prompt||"?"}) vs ${b.agent||"?"}/${b.model||"?"} (${b.prompt||"?"}) → ${meta.result || "*"}`;
// Prefer saved history (with comments) if present in meta
let history = [];
if (Array.isArray(meta.history) && meta.history.length) {
history = meta.history.filter(h => h.san);
} else {
// fallback to PGN parse
const c = new Chess();
c.load_pgn(data.pgn);
history = c.history({ verbose: true }).map(m => ({
san: m.san, uci: m.from + m.to + (m.promotion || ""), comment: null, side: m.color === "w" ? "white" : "black",
}));
}
replay.history = history;
replay.evals.clear();
for (const e of (meta.evals || [])) {
const sideToMove = (e.fen || "").split(" ")[1] || "w";
const flip = sideToMove === "b";
replay.evals.set(fenKey(e.fen), {
cp: e.cp == null ? null : (flip ? -e.cp : e.cp),
mate: e.mate == null ? null : (flip ? -e.mate : e.mate),
best_uci: e.best_uci,
pv: e.pv,
});
}
replay.ply = 0;
if (!cg) {
cg = Chessground($("replay-board"), { viewOnly: true, fen: "start" });
}
$("replay-wrap").hidden = false;
renderReplay();
$("replay-wrap").scrollIntoView({ behavior: "smooth", block: "nearest" });
}
function renderReplay() {
const c = new Chess();
for (let i = 0; i < replay.ply; i++) c.move(replay.history[i].san);
const fen = c.fen();
const e = replay.evals.get(fenKey(fen));
const shapes = (e?.best_uci && e.best_uci.length >= 4)
? [{ orig: e.best_uci.slice(0,2), dest: e.best_uci.slice(2,4), brush: "green" }] : [];
cg.set({ fen, drawable: { autoShapes: shapes } });
$("replay-ply").textContent = `ply ${replay.ply}/${replay.history.length}`;
$("replay-eval").textContent = e
? (e.mate != null ? `#${e.mate}` : (e.cp != null ? ((e.cp/100).toFixed(2)) : "—"))
: "—";
const ol = $("replay-history");
ol.innerHTML = "";
replay.history.forEach((h, i) => {
const li = document.createElement("li");
li.className = `replay-row bubble bubble-${h.side}`;
if (i === replay.ply - 1) li.classList.add("active");
const meta = document.createElement("div");
meta.className = "bubble-meta";
meta.innerHTML = `${h.side}${Math.floor(i/2)+1}${h.side==="white"?".":"..."} ${h.san}`;
const body = document.createElement("div");
body.className = "bubble-body" + (h.comment ? "" : " bubble-empty");
body.textContent = h.comment || "—";
li.append(meta, body);
li.addEventListener("click", () => { replay.ply = i + 1; renderReplay(); });
ol.appendChild(li);
});
const activeRow = ol.querySelector(".replay-row.active");
if (activeRow) activeRow.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
$("replay-first").addEventListener("click", () => { replay.ply = 0; renderReplay(); });
$("replay-prev").addEventListener("click", () => { if (replay.ply > 0) { replay.ply--; renderReplay(); } });
$("replay-next").addEventListener("click", () => { if (replay.ply < replay.history.length) { replay.ply++; renderReplay(); } });
$("replay-last").addEventListener("click", () => { replay.ply = replay.history.length; renderReplay(); });
$("replay-close").addEventListener("click", () => { $("replay-wrap").hidden = true; });
window.addEventListener("keydown", (e) => {
if ($("replay-wrap").hidden) return;
if (e.key === "ArrowLeft" && replay.ply > 0) { replay.ply--; renderReplay(); }
else if (e.key === "ArrowRight" && replay.ply < replay.history.length) { replay.ply++; renderReplay(); }
});
// ---------- bootstrap ----------
async function main() {
const blocked = await checkBlocked();
if (blocked) {
$("blocked-banner").hidden = false;
document.getElementById("page-grid").style.opacity = "0.4";
document.getElementById("page-grid").style.pointerEvents = "none";
// refresh every 5s — when game finishes, unblock
const intv = setInterval(async () => {
if (!(await checkBlocked())) {
clearInterval(intv);
location.reload();
}
}, 5000);
return;
}
const [games, stats] = await Promise.all([
fetch("/api/games").then(r => r.json()),
fetch("/api/stats").then(r => r.json()),
]);
renderGames(games);
renderLeaderboard(stats);
}
main();