/**
* Chess client — runs in sandboxed iframe.
*/
import "./style.css";
import { connectHost, type InitMsg } from "@3miz/game-client/iframe";
let S: any = null;
let init: InitMsg | null = null;
const L = (fa: string, en: string) => (init?.locale === "en" ? en : fa);
const host = connectHost({
onInit(m) {
init = m;
document.documentElement.lang = m.locale;
document.documentElement.dir = m.dir;
render();
},
onState(env) {
if (env.t === "snap") {
S = env.body;
// Drop any half-finished local selection once the turn moves on (e.g. timeout auto-move).
if (S.turn !== S.me) { selectedSquare = ""; pendingPromo = null; }
render();
}
},
onAck(a) {
if (a.status === "rejected") host.toast("حرکت پذیرفته نشد", "Move not accepted", "warn");
},
});
function render() {
const app = document.getElementById("app")!;
if (!S) {
app.innerHTML = `
${L("در حال بارگذاری…", "Loading…")}
`;
return;
}
const me = S.me;
const myColor = me !== null && me !== undefined ? S.players[me]?.color : null;
// Orientation: your own back rank is always at the bottom.
// White (and observers) see rank 8 at the top, files a→h; Black sees rank 1 at the top, files h→a.
const flipped = myColor === "b";
const bySquare: Record = {};
for (const cell of S.board) bySquare[cell.square] = cell;
const files = flipped ? [7, 6, 5, 4, 3, 2, 1, 0] : [0, 1, 2, 3, 4, 5, 6, 7];
const ranks = flipped ? [0, 1, 2, 3, 4, 5, 6, 7] : [7, 6, 5, 4, 3, 2, 1, 0];
const isMyTurn = S.phase === "play" && S.turn === me;
const boardHtml = ranks.map((r) => files.map((f) => {
const sq = String.fromCharCode(97 + f) + (r + 1);
const cell = bySquare[sq] || { square: sq, type: null, color: null };
const piece = cell.color ? `${pieceChar(cell.type, cell.color)}` : "";
const selectable = isMyTurn && !!myColor && cell.color === myColor;
const isSelected = selectedSquare === sq;
const enabled = !selectedSquare ? selectable : isMyTurn;
// Standard colouring: a1 is dark; shade = parity of (file + rank).
const shade = (f + r) % 2 === 0 ? "dark" : "light";
return ``;
}).join("")).join("");
const selHint = selectedSquare
? `
${L("مبدا", "From")}: ${selectedSquare} — ${L("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)", "click a target square (click it again to cancel)")}