BlueGit

projects-timfalken-com microchess

Files

microchess / web / assets / app.js

app.js

feat: scaffold Synhex hex tactics on the Microchess lobby shell
timfa project_86226080_bot_b6e0858ac0a12dc6d49a8d25b3b0be9b · pushed by timfa · 2 months ago
24f20754 History
app.js 53.7 KiB Download Raw
1'use strict';
2const $ = (s, root = document) => root.querySelector(s);
3const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
4const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || '';
5const withAssetVersion = url => {
6 if (!assetVersion) return url;
7 return url + (url.includes('?') ? '&' : '?') + 'v=' + encodeURIComponent(assetVersion);
8};
9(() => {
10 if (!assetVersion) return;
11 const key = 'synhex-asset-version';
12 const prev = localStorage.getItem(key);
13 if (prev === assetVersion) return;
14 localStorage.setItem(key, assetVersion);
15 if (prev) location.reload();
16})();
17const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow'];
18const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']);
19const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
20const HEX_DIRS = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]];
21const HEX_SIZE = 12;
22function customColoursDisabled () { return !!(state?.user?.disableCustomColours); }
23const classicPieceUrl = p => withAssetVersion(`assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`);
24const pieceUrl = (p, skin) =>
25{
26 if (!skin || customColoursDisabled() || !CUSTOM_PIECE_SKINS.has(skin)) return classicPieceUrl(p);
27 return withAssetVersion(`assets/avatars/${skin.toLowerCase()}-${pieceFileNames[p.toLowerCase()]}.png`);
28};
29function unitLetter (u)
30{
31 if (u.role === 'vip') return 'k';
32 if (u.weapon === 'shotgun') return 'r';
33 return 'n';
34}
35function unitPiece (u) { const g = unitLetter(u); return u.team === 'w' ? g.toUpperCase() : g; }
36function unitLabel (u)
37{
38 if (u.role === 'vip') return 'VIP (pistol)';
39 if (u.weapon === 'shotgun') return 'Soldier (shotgun)';
40 return 'Soldier (SMG)';
41}
42function skinForUnit (g, u)
43{
44 if (!g) return null;
45 return u.team === 'w' ? (g.pieceSkinWhite || 'White') : (g.pieceSkinBlack || 'Black');
46}
47function displayColorFor (g)
48{
49 if (!g) return 'White';
50 if (customColoursDisabled()) return g.color === 'w' ? 'White' : 'Black';
51 return g.displayColor || (g.color === 'w' ? (g.pieceSkinWhite || 'White') : (g.pieceSkinBlack || 'Black'));
52}
53function rulesColorLabel (g) { return g.color === 'w' ? 'White' : 'Black'; }
54function colorTagMarkup (g)
55{
56 const display = displayColorFor(g);
57 const rules = rulesColorLabel(g);
58 const tip = !customColoursDisabled() && display !== rules ? `Playing as ${display} (${rules})` : `Playing as ${display}`;
59 return `<span class="color-tag" title="${esc(tip)}"><span class="color-disc ${esc(display.toLowerCase())}"></span>${esc(display)}</span>`;
60}
61function kingAvatarUrl (color) { return withAssetVersion(`assets/avatars/${color.toLowerCase()}-king.png`); }
62function nextColorSkipping (current, skip)
63{
64 let i = PIECE_COLOR_ORDER.indexOf(current);
65 if (i < 0) i = 0;
66 for (let n = 0; n < PIECE_COLOR_ORDER.length; n++)
67 {
68 i = (i + 1) % PIECE_COLOR_ORDER.length;
69 if (PIECE_COLOR_ORDER[i] !== skip) return PIECE_COLOR_ORDER[i];
70 }
71 return current;
72}
73const initials = name => esc(name.slice(0, 2).toUpperCase());
74const avatarUrl = id => withAssetVersion(`assets/avatars/${encodeURIComponent(id)}.png`);
75function avatarMarkup (name, id, editable = false)
76{
77 const content = id ? `<img src="${avatarUrl(id)}" alt="" draggable="false">` : initials(name);
78 return editable ? `<button id="avatar-button" class="avatar" aria-label="Choose your avatar" title="Choose your avatar">${content}</button>` : `<span class="avatar">${content}</span>`;
79}
80let avatarOptions = null, avatarGroup = 'all', avatarColor = 'all';
81async function chooseAvatar ()
82{
83 if (!state) return;
84 showModal('<h2 id="modal-title">Choose your avatar</h2><p>Loading the pieces…</p>');
85 modal.classList.add('avatar-picker');
86 try
87 {
88 if (!avatarOptions) { const response = await fetch(withAssetVersion('assets/avatars/catalog.json')); if (!response.ok) throw new Error('Unable to load avatars. Please try again.'); avatarOptions = await response.json(); }
89 if (!modal.open || !modal.classList.contains('avatar-picker')) return;
90 avatarGroup = 'all'; avatarColor = 'all';
91 $('#modal-content').innerHTML = `<span class="eyebrow">MAKE IT YOURS</span><h2 id="modal-title">Choose your avatar</h2><p>A little character for your next rivalry. Select a piece to save it.</p><div class="avatar-filters"><div class="avatar-tabs" aria-label="Piece family">${[['all', 'All pieces'], ['standard', 'Chess'], ['fairy', 'Fairy chess']].map(([id, label]) => `<button class="secondary" data-avatar-group="${id}" aria-pressed="${id === 'all'}">${label}</button>`).join('')}</div><select id="avatar-color" aria-label="Filter avatars by color"><option value="all">All colors</option>${[...new Set(avatarOptions.map(a => a.color))].sort().map(c => `<option value="${esc(c)}">${esc(c)}</option>`).join('')}</select></div><div id="avatar-choices" class="avatar-choices" aria-label="Available avatars"></div><div class="avatar-picker-footer"><button class="text-button" data-avatar-choice="">Choose randomly</button><span id="avatar-option-count" class="inline-note" role="status"></span></div><p class="avatar-credits">Pieces by Wikimedia Commons contributors. <a href="${withAssetVersion('assets/avatars/CREDITS.md')}" target="_blank" rel="noopener">Sources &amp; licenses ↗</a></p>`;
92 renderAvatarChoices();
93 } catch (e) { toast(e.message); if (modal.classList.contains('avatar-picker')) closeModal(); }
94}
95function renderAvatarChoices ()
96{
97 const options = avatarOptions.filter(a => (avatarGroup === 'all' || a.group === avatarGroup) && (avatarColor === 'all' || a.color === avatarColor));
98 $('#avatar-choices').innerHTML = options.map(a => `<button class="avatar-choice" data-avatar-choice="${esc(a.id)}" aria-label="${esc(a.name)}" aria-pressed="${state.user.avatar === a.id}"><img src="${avatarUrl(a.id)}" alt="" loading="lazy"><span>${esc(a.name)}</span></button>`).join('') || '<p class="avatar-no-results">No pieces in this color. Try another color.</p>';
99 $('#avatar-option-count').textContent = `${options.length} pieces`;
100 document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup)));
101}
102function openColorPreferences ()
103{
104 if (!state) return;
105 const pref = {
106 mode: state.user.colorMode === 'custom' ? 'custom' : 'default',
107 preferred: state.user.preferredColor || 'White',
108 alternative: state.user.alternativeColor || 'Black'
109 };
110 if (pref.preferred === pref.alternative) pref.alternative = nextColorSkipping(pref.alternative, pref.preferred);
111 const paint = () =>
112 {
113 showModal(`<span class="eyebrow">YOUR SIDE</span><h2 id="modal-title">Piece colours</h2><p>Choose how your operatives look in new games. Opponents may use a different colour when both prefer the same one.</p><div class="color-mode-options" role="radiogroup" aria-label="Colour mode"><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-default" value="default" ${pref.mode !== 'custom' ? 'checked' : ''}> <span><strong>Default Colours</strong><small>Play as White or Black by the rules side, as usual.</small></span></label><label class="color-mode-option"><input type="radio" name="color-mode" id="color-mode-custom" value="custom" ${pref.mode === 'custom' ? 'checked' : ''}> <span><strong>Custom Colour</strong><small>Pick a preferred colour and an alternative if both players clash.</small></span></label></div><div id="custom-color-pickers" class="custom-color-pickers"${pref.mode === 'custom' ? '' : ' hidden'}><button type="button" class="color-king-choice" data-color-role="preferred" aria-label="Preferred colour ${esc(pref.preferred)}"><img src="${kingAvatarUrl(pref.preferred)}" alt=""><span>Preferred</span><strong>${esc(pref.preferred)}</strong></button><button type="button" class="color-king-choice" data-color-role="alternative" aria-label="Alternative colour ${esc(pref.alternative)}"><img src="${kingAvatarUrl(pref.alternative)}" alt=""><span>Alternative</span><strong>${esc(pref.alternative)}</strong></button></div><div class="actions"><button class="primary" id="save-color-prefs">Save</button><button class="secondary" data-modal-action="close">Cancel</button></div>`);
114 $('#color-mode-default').onchange = () => { pref.mode = 'default'; paint(); };
115 $('#color-mode-custom').onchange = () => { pref.mode = 'custom'; paint(); };
116 document.querySelectorAll('[data-color-role]').forEach(btn =>
117 {
118 btn.onclick = () =>
119 {
120 if (btn.dataset.colorRole === 'preferred') pref.preferred = nextColorSkipping(pref.preferred, pref.alternative);
121 else pref.alternative = nextColorSkipping(pref.alternative, pref.preferred);
122 paint();
123 };
124 });
125 $('#save-color-prefs').onclick = async () =>
126 {
127 await action({ action: 'set_piece_colors', colorMode: pref.mode, preferredColor: pref.preferred, alternativeColor: pref.alternative }, () =>
128 {
129 closeModal();
130 toast('Colour preference saved.');
131 });
132 };
133 };
134 paint();
135}
136
137let state, selected = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false;
138const playback = new Map();
139let inviteToken = new URLSearchParams(location.search).get('invite');
140const modal = $('#modal');
141function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); }
142function showModal (html) { delete $('#modal-content').dataset.rivalry; stopReplay(); modal.classList.remove('avatar-picker', 'replay-modal'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); }
143function clearReplay () { stopReplay(); if (modal?.classList.contains('replay-modal')) { $('#modal-content').innerHTML = ''; modal.classList.remove('replay-modal'); } }
144function closeModal () { if (!modal) return; clearReplay(); modal.close(); }
145if ($('#modal-close')) $('#modal-close').onclick = closeModal;
146modal?.addEventListener('click', e => { if (e.target === modal) { const r = modal.getBoundingClientRect(); if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) closeModal(); } });
147function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); }
148modal?.addEventListener('close', () => { if (!modal.open) clearReplay(); if (inviteShown) dismissInvite(); });
149const mobileLayout = matchMedia('(max-width: 760px)');
150function showSidebar (open)
151{
152 const sidebar = $('#sidebar'); if (!sidebar) return;
153 sidebar.classList.toggle('open', open);
154 sidebar.inert = mobileLayout.matches && !open;
155 $('#sidebar-backdrop').hidden = !open;
156 $('#friends-toggle').setAttribute('aria-expanded', String(open));
157 $('#main').inert = mobileLayout.matches && open;
158 document.body.classList.toggle('sidebar-open', mobileLayout.matches && open);
159 if (open) { $('#friends-close').focus(); animateSavedGames(); }
160 else if (mobileLayout.matches) $('#friends-toggle').focus();
161}
162mobileLayout.addEventListener('change', () => showSidebar(false));
163if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches;
164if ($('#friends-toggle')) $('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open'));
165if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false);
166if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false);
167document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; renderGames(); } });
168async function api (data)
169{
170 const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) });
171 const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Request failed.'); return result;
172}
173async function action (data, success)
174{
175 if (busy) return; busy = true;
176 try
177 {
178 const result = await api(data);
179 selected = null; if (success) await success(result); await refresh(true);
180 }
181 catch (e) { toast(e.message); await refresh(true); }
182 finally { busy = false; }
183}
184async function refresh (force = false)
185{
186 if (!$('#your-games') || (busy && !force) || drag) return;
187 try
188 {
189 const response = await fetch('api.php' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : ''));
190 const data = await response.json();
191 if (response.status === 401) { showModal('<h2>Sign in to continue</h2><p>Your session has expired. Your games are saved.</p><a class="button primary" href="auth.php' + esc(location.search || '') + '">Sign in</a>'); return; }
192 if (!response.ok) throw new Error(data.error || 'Unable to load games.');
193 state = data;
194 window.synhexPwa?.sync();
195 if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version || g.state?.phase !== 'planning') selected = null; }
196 const signature = JSON.stringify(data);
197 if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); }
198 if (data.invite && !inviteShown)
199 {
200 inviteShown = true; const i = data.invite;
201 if (i.error) showModal(`<h2>Invitation</h2><p>${esc(i.error)}</p><button class="primary" data-modal-action="close">Got it</button>`);
202 else showModal(`<span class="eyebrow">${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}</span><h2>${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}</h2><p>${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'Lock your plan. The act plays when you both commit.'}</p><div class="actions"><button class="primary" data-modal-action="accept-invite">Accept</button><button class="secondary" data-modal-action="close">Reject</button></div>`);
203 }
204 window.synhexPwa?.intro();
205 } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); }
206}
207function empty (yours) { return `<div class="empty"><span class="empty-icon">⬡</span><h3>${yours ? 'Your next rivalry starts here.' : 'All caught up.'}</h3><p>${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is planning or watching playback.'}</p>${yours ? '<button class="text-button" data-create-link="match">Invite someone to play ↗</button>' : ''}</div>`; }
208function renderGames ()
209{
210 if (!state) return;
211 const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' && !g.rematch || g.status === 'pending' && g.incoming).sort((a, b) => a.turnOrder - b.turnOrder || a.id - b.id);
212 const waiting = state.games.filter(g => !yours.includes(g));
213 $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0);
214 $('#your-games').innerHTML = yours.map(card).join('') || empty(true);
215 $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false);
216 for (const el of document.querySelectorAll('#main .material-bar'))
217 {
218 const fill = $('.material-white', el), share = Number(el.dataset.share);
219 fill.animate([{ transform: `scaleX(${share})` }], { duration: 0, fill: 'forwards' });
220 }
221 window.synhexPwa?.highlight();
222}
223function card (g)
224{
225 let content = '';
226 if (g.replay) content = board(g);
227 else if (g.status === 'pending') content = `<div class="pending-content"><span class="big-icon">⬡</span><h3>${g.incoming ? 'A little challenge?' : 'Challenge sent.'}</h3><p>${g.incoming ? `${esc(g.opponent)} invited you to play.<br>Your board is waiting.` : `Waiting for ${esc(g.opponent)}<br>to accept your challenge.`}</p>${g.incoming ? `<div class="actions"><button class="primary" data-game-action="accept">Accept</button><button class="secondary" data-game-action="reject">Reject</button></div>` : '<span class="inline-note"></span>'}</div>`;
228 else if (g.status === 'ended') content = `<div class="ended-board">${board(g)}<div class="end-content"><div class="end-status"><h3>${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}</h3><small>${esc(g.reason)}</small>${g.opponentRematch && g.canRematch ? `<small>${esc(g.opponent)} wants a rematch.</small>` : ''}</div><div class="actions">${g.canRematch ? `<button class="primary" data-game-action="rematch" ${g.rematch ? 'disabled' : ''}>${g.rematch ? 'Requested' : 'Rematch'}</button>` : ''}<button class="secondary" data-game-action="exit">Exit</button></div></div></div>`;
229 else content = board(g) + footer(g);
230 return `<article class="game-card ${!g.yourTurn && g.status === 'active' ? 'waiting' : ''}" data-game="${g.id}" aria-label="Game with ${esc(g.opponent)}"><div class="card-header">${avatarMarkup(g.opponent, g.opponentAvatar)}<div class="opponent-info"><strong><button class="opponent-name" data-opponent="${esc(g.opponentId)}">${esc(g.opponent)}</button> <small class="rating" aria-label="${g.opponentRating} Elo">${g.opponentRating}</small></strong>${g.status !== 'pending' ? materialBar(g) : ''}</div>${g.status !== 'pending' ? colorTagMarkup(g) : ''}${g.inactiveDays >= 7 ? '<button class="stop-inactive" data-game-action="stop-confirm" aria-label="Stop inactive game" title="Stop inactive game">×</button>' : ''}</div>${content}</article>`;
231}
232function footer (g)
233{
234 const phase = g.state?.phase;
235 let status = 'Waiting';
236 let extra = '';
237 if (phase === 'planning')
238 {
239 status = g.state.committed ? 'Plan locked' : (g.yourTurn ? 'Plan your act' : 'Waiting for a plan');
240 if (g.yourTurn && !g.state.committed) extra = `<button class="primary" data-game-action="commit">Lock plan</button>`;
241 else extra = `<span>Act ${g.state.act + 1}</span>`;
242 }
243 else if (phase === 'playback')
244 {
245 status = g.state.acked ? 'Waiting for opponent' : 'Act ready';
246 if (g.yourTurn && !g.state.acked) extra = `<button class="primary" data-game-action="play">Play</button>`;
247 else extra = `<span>Act ${g.state.act}</span>`;
248 }
249 return `<div class="card-footer"><span class="${g.yourTurn ? 'turn-label' : ''}">${status}</span>${g.yourTurn ? `<span class="footer-actions">${extra}<button class="text-button" data-game-action="options" aria-label="Game options">${g.drawOffer === 'opponent' ? 'Draw offered · ' : ''}•••</button></span>` : extra}</div>`;
250}
251function materialBarSkinName (name, fallback) { return PIECE_COLOR_ORDER.includes(name) ? name : fallback; }
252function materialBarSkins (g)
253{
254 if (customColoursDisabled()) return { left: 'White', right: 'Black' };
255 return { left: materialBarSkinName(g.pieceSkinWhite, 'White'), right: materialBarSkinName(g.pieceSkinBlack, 'Black') };
256}
257function materialBar (g)
258{
259 const totals = g.strength || { w: 0, b: 0 };
260 const total = totals.w + totals.b, share = total ? totals.w / total : .5;
261 const { left, right } = materialBarSkins(g);
262 const you = g.color === 'w' ? left : right;
263 const label = `${left}: ${totals.w} strength. ${right}: ${totals.b} strength. You play ${you}. VIP 3 · Soldier 1.`;
264 return `<div class="material-bar material-right-${right.toLowerCase()}" data-share="${share}" role="meter" aria-label="Team strength" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(share * 100)}" aria-valuetext="${esc(label)}" title="${esc(label)}" tabindex="0"><span class="material-white material-left-${left.toLowerCase()}"></span></div>`;
265}
266function hexKey (q, r) { return q + ',' + r; }
267function offsetOf (q, r) { return { col: q + Math.floor(r / 2), row: r }; }
268function axialOf (col, row) { return { q: col - Math.floor(row / 2), r: row }; }
269function hexDist (a, b) { return (Math.abs(a.q - b.q) + Math.abs(a.q + a.r - b.q - b.r) + Math.abs(a.r - b.r)) / 2; }
270function hexNeighbors (q, r) { return HEX_DIRS.map(([dq, dr]) => ({ q: q + dq, r: r + dr })); }
271function hexPixel (col, row, size)
272{
273 const w = Math.sqrt(3) * size;
274 return { x: w * (col + 0.5 * (row & 1)) + size * Math.sqrt(3), y: size * 1.5 * row + size * 1.2, w };
275}
276function hexPoints (cx, cy, size)
277{
278 const pts = [];
279 for (let i = 0; i < 6; i++)
280 {
281 const a = Math.PI / 180 * (60 * i - 30);
282 pts.push(`${cx + size * Math.cos(a)},${cy + size * Math.sin(a)}`);
283 }
284 return pts.join(' ');
285}
286function walkableSet (g)
287{
288 const walls = new Set(g.state.walls || []);
289 const set = new Set();
290 const cols = g.state.grid.cols, rows = g.state.grid.rows;
291 for (let row = 0; row < rows; row++) for (let col = 0; col < cols; col++)
292 {
293 const { q, r } = axialOf(col, row);
294 const k = hexKey(q, r);
295 if (!walls.has(k)) set.add(k);
296 }
297 return set;
298}
299function hexPath (from, to, walkable)
300{
301 const start = hexKey(from.q, from.r), goal = hexKey(to.q, to.r);
302 if (!walkable.has(start) || !walkable.has(goal)) return null;
303 if (start === goal) return [from];
304 const open = new Map([[start, 0]]), came = new Map(), gScore = new Map([[start, 0]]);
305 while (open.size)
306 {
307 let current = null, best = Infinity;
308 for (const [k, f] of open) if (f < best) { best = f; current = k; }
309 open.delete(current);
310 if (current === goal)
311 {
312 const path = [];
313 while (current !== start) { const [q, r] = current.split(',').map(Number); path.push({ q, r }); current = came.get(current); }
314 path.push(from);
315 return path.reverse();
316 }
317 const [cq, cr] = current.split(',').map(Number);
318 for (const n of hexNeighbors(cq, cr))
319 {
320 const nk = hexKey(n.q, n.r);
321 if (!walkable.has(nk)) continue;
322 const tg = gScore.get(current) + 1;
323 if (!gScore.has(nk) || tg < gScore.get(nk))
324 {
325 came.set(nk, current); gScore.set(nk, tg); open.set(nk, tg + hexDist(n, to));
326 }
327 }
328 }
329 return null;
330}
331function currentUnits (g)
332{
333 const play = playback.get(g.id);
334 if (play?.units) return play.units;
335 return g.state?.units || [];
336}
337function board (g)
338{
339 if (!g.state?.grid) return '<div class="board-wrap"><p class="inline-note">Loading board…</p></div>';
340 const cols = g.state.grid.cols, rows = g.state.grid.rows;
341 const size = HEX_SIZE;
342 const width = Math.sqrt(3) * size * (cols + 1.2);
343 const height = size * 1.5 * rows + size * 2.2;
344 const walls = new Set(g.state.walls || []);
345 const units = currentUnits(g);
346 const mine = selected?.game === g.id ? selected : null;
347 const pathKeys = new Set((mine?.path || []).map(p => hexKey(p.q, p.r)));
348 const holo = hologramOf(g, mine);
349 const play = playback.get(g.id);
350 let hexes = '';
351 for (let row = 0; row < rows; row++)
352 {
353 for (let col = 0; col < cols; col++)
354 {
355 const { q, r } = axialOf(col, row);
356 const { x, y } = hexPixel(col, row, size);
357 const k = hexKey(q, r);
358 const wall = walls.has(k);
359 const classes = ['hex-cell', (col + row) % 2 ? 'odd' : '', wall ? 'wall' : '', pathKeys.has(k) ? 'path' : '', holo && holo.q === q && holo.r === r ? 'hologram-hex' : ''].filter(Boolean).join(' ');
360 hexes += `<polygon class="${classes}" data-hex="${k}" points="${hexPoints(x, y, size)}"></polygon>`;
361 }
362 }
363 let sprites = '';
364 for (const u of units)
365 {
366 const { col, row } = offsetOf(u.q, u.r);
367 const { x, y } = hexPixel(col, row, size);
368 const p = unitPiece(u);
369 const src = pieceUrl(p, skinForUnit(g, u));
370 const cls = u.hologram ? 'hex-unit hologram' : 'hex-unit';
371 sprites += `<image class="${cls}" data-unit="${esc(u.id)}" href="${src}" xlink:href="${src}" x="${x - size * 0.72}" y="${y - size * 0.72}" width="${size * 1.44}" height="${size * 1.44}"></image>`;
372 const [dq, dr] = HEX_DIRS[u.facing ?? 0];
373 const fx = x + dq * size * 0.55, fy = y + dr * size * 0.48;
374 sprites += `<polygon class="hex-facing" points="${fx},${fy - 2.2} ${fx + 2.4},${fy + 1.6} ${fx - 2.4},${fy + 1.6}" transform="rotate(${(u.facing ?? 0) * 60} ${fx} ${fy})"></polygon>`;
375 if (u.role === 'vip') sprites += `<text class="hex-label" x="${x}" y="${y + size * 0.92}" text-anchor="middle">VIP</text>`;
376 }
377 if (holo && mine)
378 {
379 const unit = units.find(u => u.id === mine.unitId);
380 if (unit)
381 {
382 const { col, row } = offsetOf(holo.q, holo.r);
383 const { x, y } = hexPixel(col, row, size);
384 const p = unitPiece(unit);
385 sprites += `<image class="hex-unit hologram" href="${pieceUrl(p, skinForUnit(g, unit))}" x="${x - size * 0.72}" y="${y - size * 0.72}" width="${size * 1.44}" height="${size * 1.44}"></image>`;
386 const facing = holo.facing ?? unit.facing ?? 0;
387 const front = hexNeighbors(holo.q, holo.r)[facing];
388 if (front)
389 {
390 const fo = offsetOf(front.q, front.r);
391 const fp = hexPixel(fo.col, fo.row, size);
392 sprites += `<polygon class="hex-cell hologram-hex" data-facing-handle="${mine.unitId}" data-hex="${hexKey(front.q, front.r)}" points="${hexPoints(fp.x, fp.y, size * 0.72)}"></polygon>`;
393 }
394 }
395 }
396 let shots = '';
397 if (play?.shots)
398 {
399 for (const sh of play.shots)
400 {
401 const a = units.find(u => u.id === sh.id), b = units.find(u => u.id === (sh.victim || sh.target));
402 if (!a) continue;
403 const ao = offsetOf(a.q, a.r), ap = hexPixel(ao.col, ao.row, size);
404 const aim = sh.aim || b;
405 if (!aim) continue;
406 const bo = offsetOf(aim.q, aim.r), bp = hexPixel(bo.col, bo.row, size);
407 shots += `<line class="hex-shot" x1="${ap.x}" y1="${ap.y}" x2="${bp.x}" y2="${bp.y}"></line>`;
408 }
409 }
410 const planning = g.yourTurn && g.state.phase === 'planning' && !g.state.committed;
411 return `<div class="board-wrap"><svg class="hex-board board" viewBox="0 0 ${width} ${height}" role="group" aria-label="Synhex hex board" ${planning ? '' : 'data-inert="1"'}>${hexes}${shots}${sprites}</svg></div>`;
412}
413function hologramOf (g, mine)
414{
415 if (!mine?.path?.length) return null;
416 const idx = mine.hologramAt == null ? mine.path.length - 1 : mine.hologramAt;
417 return mine.path[Math.max(0, Math.min(mine.path.length - 1, idx))];
418}
419function draftPlan (g)
420{
421 const units = {};
422 if (selected?.game === g.id && selected.unitId)
423 {
424 const rest = g.state.draft?.units || {};
425 Object.assign(units, rest);
426 units[selected.unitId] = { path: selected.path || [], facing: selected.facing };
427 }
428 else Object.assign(units, g.state.draft?.units || {});
429 return { units };
430}
431function chooseHex (g, q, r)
432{
433 if (!g.yourTurn || busy || g.state.phase !== 'planning' || g.state.committed) return;
434 const units = currentUnits(g);
435 const unit = units.find(u => u.q === q && u.r === r && u.team === g.color && u.alive && !u.hologram);
436 if (unit)
437 {
438 if (selected?.game === g.id && selected.unitId === unit.id) selected = null;
439 else selected = { game: g.id, unitId: unit.id, path: [], version: g.version, hologramAt: null };
440 renderGames();
441 return;
442 }
443 if (!selected || selected.game !== g.id) return;
444 const me = units.find(u => u.id === selected.unitId); if (!me) return;
445 const walkable = walkableSet(g);
446 const last = selected.path.length ? selected.path[selected.path.length - 1] : { q: me.q, r: me.r };
447 if (hexDist(last, { q, r }) === 1 && walkable.has(hexKey(q, r)))
448 {
449 selected.path = [...selected.path, { q, r }];
450 selected.hologramAt = selected.path.length - 1;
451 }
452 else
453 {
454 const found = hexPath(last, { q, r }, walkable);
455 if (!found || found.length < 2) { renderGames(); return; }
456 selected.path = selected.path.concat(found.slice(1));
457 selected.hologramAt = selected.path.length - 1;
458 }
459 renderGames();
460}
461function setFacing (g, q, r)
462{
463 if (!selected || selected.game !== g.id || !selected.path.length) return;
464 const idx = selected.hologramAt == null ? selected.path.length - 1 : selected.hologramAt;
465 const wp = selected.path[idx];
466 const dir = HEX_DIRS.findIndex(([dq, dr]) => wp.q + dq === q && wp.r + dr === r);
467 if (dir < 0)
468 {
469 let best = 0, bestD = Infinity;
470 HEX_DIRS.forEach(([dq, dr], i) =>
471 {
472 const d = hexDist({ q: wp.q + dq, r: wp.r + dr }, { q, r });
473 if (d < bestD) { bestD = d; best = i; }
474 });
475 selected.path[idx] = { ...wp, facing: best };
476 }
477 else selected.path[idx] = { ...wp, facing: dir };
478 renderGames();
479}
480function clickPathHex (g, q, r)
481{
482 if (!selected || selected.game !== g.id) return false;
483 const i = selected.path.findIndex(p => p.q === q && p.r === r);
484 if (i < 0) return false;
485 selected.hologramAt = i;
486 renderGames();
487 return true;
488}
489function matchmakingCard ()
490{
491 const searching = state.matchmaking.status === 'searching';
492 return `<article class="game-card"><div class="pending-content"><span class="big-icon">⬡</span><h3>${searching ? 'Finding an opponent…' : 'No opponent found'}</h3><div class="actions">${searching ? '' : '<button class="primary" data-matchmaking="join_matchmaking">Try again</button>'}<button class="secondary" data-matchmaking="cancel_matchmaking">${searching ? 'Cancel search' : 'Dismiss'}</button></div></div></article>`;
493}
494function renderMatchmaking ()
495{
496 const target = $('#matchmaking-actions');
497 if (!target || !state) return;
498 target.innerHTML = state.matchmaking?.status === 'searching'
499 ? '<p role="status">Finding an opponent…</p><button class="secondary" data-matchmaking="cancel_matchmaking">Cancel search</button>'
500 : '<button class="secondary" data-matchmaking="join_matchmaking">Challenge a random player</button>';
501}
502function renderFriends ()
503{
504 $('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length;
505 $('#friend-list').innerHTML = state.friends.map(f => `<button class="friend" data-friend="${esc(f.id)}">${avatarMarkup(f.name, f.avatar)}<span><strong>${esc(f.name)}</strong><small>${f.rating} Elo · ${f.wins} wins · ${f.losses} losses · ${f.ties} ties</small></span><span>↗</span></button>`).join('') || '<p class="inline-note">Your friends will appear here.<br>Send an invitation to get started.</p>';
506 const incoming = state.friendRequests.filter(r => r.incoming);
507 $('#friend-requests').innerHTML = incoming.length ? '<div class="friends-label">PENDING REQUESTS</div>' + incoming.map(r => `<div class="friend-request">${avatarMarkup(r.name, r.avatar)}<div><strong>${esc(r.name)}</strong><div class="actions"><button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(r.id)}">Accept</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(r.id)}">Reject</button></div></div></div>`).join('') : '';
508 $('#friend-count').textContent = state.friends.length + incoming.length;
509 $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}<button type="button" id="color-pref-button" class="account-name-button" title="Piece colours"><span>${esc(state.user.name)}</span><small>${state.user.rating} Elo</small></button><button id="history-button" class="text-button" aria-label="Game history" title="Game history">⌛</button>`;
510}
511function showRivalry (id)
512{
513 const friend = state.friends.find(f => f.id === id);
514 const game = state.games.find(g => g.opponentId === id);
515 const f = friend || (game && { id, name: game.opponent, ...game.rivalry });
516 if (!f) return;
517 const request = state.friendRequests.find(r => r.id === id);
518 const actions = friend
519 ? '<button class="primary" data-friend-action="challenge">Challenge to a game ↗</button><button class="text-button" data-friend-action="remove">Remove friend…</button>'
520 : request?.incoming
521 ? `<button class="primary" data-request-action="accept_friend_request" data-request-user="${esc(id)}">Accept friend request</button><button class="secondary" data-request-action="reject_friend_request" data-request-user="${esc(id)}">Reject</button>`
522 : request
523 ? '<button class="secondary" disabled>Friend request sent</button>'
524 : `<button class="primary" data-request-action="send_friend_request" data-request-user="${esc(id)}">Send friend request</button>`;
525 showModal(`<span class="eyebrow">YOUR FRIENDLY RIVALRY</span><h2>${esc(f.name)}</h2><div class="stats"><div><strong>${f.wins}</strong><span>Wins</span></div><div><strong>${f.losses}</strong><span>Losses</span></div><div><strong>${f.ties}</strong><span>Ties</span></div></div><div class="settings-actions">${actions}</div>`);
526 $('#modal-content').dataset.friend = id;
527 $('#modal-content').dataset.rivalry = id;
528}
529function refreshRivalry () { const id = $('#modal-content').dataset.rivalry; if (modal.open && id) showRivalry(id); }
530function options (g) { showModal(`<h2>Your game with ${esc(g.opponent)}</h2><p>${g.state?.phase === 'planning' ? 'Plan paths for your four operatives, then lock the plan. The act runs when both of you commit.' : 'Watch the same server-computed act, then plan again.'}</p><div class="settings-actions">${g.drawOffer === 'opponent' ? '<button class="primary" data-option="accept_draw">Accept draw</button>' : g.drawOffer === 'you' ? '<p>Draw offered.</p>' : '<button class="secondary" data-option="offer_draw">Offer a draw</button>'}<button class="danger" data-option="resign-confirm">Resign…</button></div>`); $('#modal-content').dataset.game = g.id; }
531async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`<span class="eyebrow">${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}</span><h2>${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}</h2><p>Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.</p><input aria-label="Invitation link" id="share-url" readonly value="${esc(r.url)}"><div class="actions"><button class="primary" data-modal-action="copy">Copy link ↗</button></div>${kind === 'match' ? '<div id="matchmaking-actions" class="settings-actions"></div>' : ''}`); renderMatchmaking(); }); }
532if ($('#match-link')) $('#match-link').onclick = () => createLink('match');
533if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend');
534if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`<h2>Your account</h2><p>Signed in as ${esc(state.user.name)}.</p><p>${state.user.rating} Elo</p><label class="settings-check"><input type="checkbox" id="disable-custom-colours" ${customColoursDisabled() ? 'checked' : ''}> Disable custom colours</label><div id="notification-settings"></div><div class="settings-actions"><button class="secondary" data-install-app>Add to home screen</button><p id="install-help" hidden></p>${state.local ? `<button class="secondary" data-modal-action="switch">Switch to ${state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1'}</button>` : ''}<a class="button secondary" href="api.php?action=export" download>Export my data (JSON)</a><button class="secondary" data-modal-action="logout">Sign out</button></div>`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.synhexPwa?.settings(); };
535if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`<span class="eyebrow">SYNHEX</span><h2>Plan together. Fire together.</h2><p>Simultaneous-turn hex tactics. Both players plan, then the server simulates a 3-second act.</p><ul class="rules-list"><li>The board is a 17 × 14 pointy-top hex grid (odd-r), with random walls. Each side has a VIP (pistol), two SMG soldiers and a shotgun soldier.</li><li>If your VIP dies, you lose.</li><li>Click a unit, then click hexes or drag a path. The path end is a hologram. Click a waypoint to place the hologram there; drag the facing hex in front of it to set look direction.</li><li>Re-click a unit to clear its path. Lock your plan; when both players lock, the act runs.</li><li>Press Play to watch the same server-computed result, then plan the next act.</li><li>Units walk up to 5 hexes per act. They shoot enemies in a forward 120° cone with line of sight. Hits are instant kills. Friendly fire is possible.</li><li>Accuracy starts at 15% plus bonuses for standing still, aiming dead-ahead, close range, focus fire, and more — see <code>lib/game-config.php</code>.</li><li>Enemies are visible at match start, when in your cone and LoS, or when they fire; otherwise a hologram marks their last known position.</li></ul>`);
536function playTimeline (g)
537{
538 const tl = g.state?.timeline; if (!tl) { action({ action: 'ack_playback', game: g.id, version: g.version }); return; }
539 const snaps = tl.snapshots || [];
540 if (!snaps.length || matchMedia('(prefers-reduced-motion: reduce)').matches)
541 {
542 playback.set(g.id, { units: tl.endUnits || snaps.at(-1)?.units, shots: tl.shots || [] });
543 renderGames();
544 action({ action: 'ack_playback', game: g.id, version: g.version });
545 return;
546 }
547 let i = 0;
548 const play = { timer: null };
549 const step = () =>
550 {
551 const snap = snaps[Math.min(i, snaps.length - 1)];
552 const shots = (tl.shots || []).filter(s => s.t === snap.t);
553 playback.set(g.id, { units: snap.units, shots, timer: play.timer });
554 renderGames();
555 i++;
556 if (i >= snaps.length)
557 {
558 clearInterval(play.timer);
559 playback.set(g.id, { units: tl.endUnits || snap.units, shots: [] });
560 renderGames();
561 action({ action: 'ack_playback', game: g.id, version: g.version }, () => playback.delete(g.id));
562 }
563 };
564 step();
565 play.timer = setInterval(step, Math.max(30, Math.min(120, Math.floor((tl.durationMs || 3000) / Math.max(1, snaps.length)))));
566}
567document.addEventListener('click', e =>
568{
569 const el = e.target.closest('button, polygon, image'); if (!el) return;
570 const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game));
571 if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); });
572 if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); });
573 if (el.id === 'history-button') showHistory();
574 if (el.id === 'avatar-button') chooseAvatar();
575 if (el.id === 'color-pref-button') openColorPreferences();
576 if (el.dataset.createLink) createLink(el.dataset.createLink);
577 if (el.dataset.hex && g)
578 {
579 if (suppressClick) { suppressClick = false; return; }
580 const [q, r] = el.dataset.hex.split(',').map(Number);
581 if (el.hasAttribute('data-facing-handle')) { setFacing(g, q, r); return; }
582 if (clickPathHex(g, q, r)) return;
583 chooseHex(g, q, r);
584 }
585 if (el.dataset.unit && g)
586 {
587 const u = currentUnits(g).find(u => u.id === el.dataset.unit);
588 if (u) chooseHex(g, u.q, u.r);
589 }
590 if (el.dataset.gameAction && g)
591 {
592 if (el.dataset.gameAction === 'stop-confirm') showModal(`<h2 id="modal-title">Stop this game?</h2><p>This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?</p><div class="actions"><button class="danger" data-stop-game="${g.id}" data-version="${g.version}">Stop game</button><button class="secondary" data-modal-action="close">Cancel</button></div>`);
593 else if (el.dataset.gameAction === 'options') options(g);
594 else if (el.dataset.gameAction === 'commit') action({ action: 'commit_plan', game: g.id, version: g.version, plan: draftPlan(g) });
595 else if (el.dataset.gameAction === 'play') playTimeline(g);
596 else action({ action: el.dataset.gameAction, game: g.id, version: g.version });
597 }
598 if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent);
599});
600$('#modal-content').addEventListener('click', async e =>
601{
602 const b = e.target.closest('button'); if (!b) return;
603 if (b.dataset.stopGame) { await action({ action: 'stop_inactive', game: Number(b.dataset.stopGame), version: Number(b.dataset.version) }, () => closeModal()); return; }
604 if (b.dataset.avatarGroup) { avatarGroup = b.dataset.avatarGroup; renderAvatarChoices(); return; }
605 if (b.hasAttribute('data-avatar-choice')) { await action({ action: 'set_avatar', avatar: b.dataset.avatarChoice || null }, () => { closeModal(); toast('Avatar updated.'); }); return; }
606 if (b.dataset.modalAction === 'close') closeModal();
607 if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); });
608 if (b.dataset.modalAction === 'copy') { const input = $('#share-url'); try { await navigator.clipboard.writeText(input.value); b.textContent = 'Copied ✓'; } catch { input.focus(); input.select(); toast('Select and copy the link.'); } }
609 if (b.dataset.modalAction === 'switch') await action({ endpoint: await window.synhexPwa?.endpoint(), action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); });
610 if (b.dataset.modalAction === 'logout') await action({ action: 'logout', endpoint: await window.synhexPwa?.endpoint() }, () => location.reload());
611 if (b.dataset.friendAction)
612 {
613 const id = $('#modal-content').dataset.friend;
614 if (b.dataset.friendAction === 'remove') { showModal('<h2>Remove this friend?</h2><p>You will both be removed from each other’s friends list. Your game history is kept.</p><div class="actions"><button class="danger" data-friend-action="confirm-remove">Remove friend</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); }
615 else await action({ action: b.dataset.friendAction === 'challenge' ? 'challenge' : 'remove_friend', friend: id }, () => { closeModal(); toast(b.dataset.friendAction === 'challenge' ? 'Challenge sent.' : 'Friend removed.'); });
616 }
617 if (b.dataset.option)
618 {
619 const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return;
620 if (b.dataset.option === 'resign-confirm') { showModal('<h2>Resign this game?</h2><p>Your opponent will win this game. You can request a rematch afterwards.</p><div class="actions"><button class="danger" data-option="resign">Resign</button><button class="secondary" data-modal-action="close">Cancel</button></div>'); return; }
621 await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal());
622 }
623});
624$('#modal-content').addEventListener('change', e => { if (e.target.id === 'avatar-color') { avatarColor = e.target.value; renderAvatarChoices(); } });
625let suppressClick = false;
626document.addEventListener('pointerdown', e =>
627{
628 const cell = e.target.closest('[data-hex], [data-unit]'); if (!cell || e.button !== 0 || busy) return;
629 const g = state?.games.find(g => g.id === Number(cell.closest('[data-game]').dataset.game)); if (!g?.yourTurn || g.state?.phase !== 'planning' || g.state.committed) return;
630 if (cell.hasAttribute('data-facing-handle'))
631 {
632 drag = { kind: 'facing', game: g.id, id: e.pointerId };
633 return;
634 }
635 const unitId = cell.dataset.unit || currentUnits(g).find(u => hexKey(u.q, u.r) === cell.dataset.hex && u.team === g.color && u.alive && !u.hologram)?.id;
636 if (!unitId) return;
637 const unit = currentUnits(g).find(u => u.id === unitId);
638 selected = { game: g.id, unitId, path: [], version: g.version, hologramAt: null };
639 drag = { kind: 'path', game: g.id, unitId, last: { q: unit.q, r: unit.r }, id: e.pointerId, moving: false };
640 renderGames();
641});
642document.addEventListener('pointermove', e =>
643{
644 if (!drag || e.pointerId !== drag.id) return;
645 const g = state.games.find(g => g.id === drag.game); if (!g) return;
646 const el = document.elementFromPoint(e.clientX, e.clientY)?.closest('[data-hex]');
647 if (!el) return;
648 const [q, r] = el.dataset.hex.split(',').map(Number);
649 if (drag.kind === 'facing') { setFacing(g, q, r); return; }
650 if (hexDist(drag.last, { q, r }) !== 1) return;
651 if (!walkableSet(g).has(hexKey(q, r))) return;
652 drag.moving = true;
653 selected.path = [...(selected.path || []), { q, r }];
654 selected.hologramAt = selected.path.length - 1;
655 drag.last = { q, r };
656 renderGames();
657}, { passive: false });
658document.addEventListener('pointerup', e =>
659{
660 if (!drag || e.pointerId !== drag.id) return;
661 if (drag.moving) { suppressClick = true; setTimeout(() => suppressClick = false, 100); }
662 drag = null;
663});
664document.addEventListener('pointercancel', () => { drag = null; });
665refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });
666
667let replay = null, replayTimer = null, historyRequest = 0;
668function stopReplay () { clearInterval(replayTimer); replayTimer = null; }
669async function historyFetch (query)
670{
671 const response = await fetch('api.php?action=' + query);
672 const data = await response.json();
673 if (!response.ok) throw new Error(data.error || 'Unable to load saved games.');
674 return data;
675}
676async function showHistory ()
677{
678 const request = ++historyRequest;
679 showModal('<h2 id="modal-title">Game history</h2><p>Loading saved games…</p>');
680 try {
681 const games = await historyFetch('history');
682 if (request !== historyRequest || !modal.open || $('#modal-title')?.textContent !== 'Game history') return;
683 $('#modal-content').innerHTML = `<h2 id="modal-title">Game history</h2><div class="history-list">${games.map(g => `<button class="secondary history-entry" data-replay-id="${g.id}"><strong>${esc(g.opponent)}</strong><span>${g.outcome === 'win' ? 'Won' : g.outcome === 'loss' ? 'Lost' : 'Draw'}</span><time datetime="${new Date(g.ended * 1000).toISOString()}">${esc(new Date(g.ended * 1000).toLocaleDateString())}</time></button>`).join('') || '<p>No saved games yet.</p>'}</div>`;
684 } catch (e) { toast(e.message); }
685}
686async function openReplay (id)
687{
688 const source = $('#modal-content').firstElementChild;
689 const request = ++historyRequest;
690 try {
691 const game = await historyFetch('replay&id=' + id);
692 if (request !== historyRequest || !modal.open || source !== $('#modal-content').firstElementChild) return;
693 showReplay(game);
694 } catch (e) { toast(e.message); }
695}
696function showReplay (game)
697{
698 const content = '<div id="replay-card"></div><div class="replay-controls"><button class="secondary" data-replay-control="start" aria-label="Jump to start" title="Jump to start">⏮</button><button class="secondary" data-replay-control="back" aria-label="Step back" title="Step back">⏪</button><button class="primary" data-replay-control="play" aria-label="Play">▶</button><button class="secondary" data-replay-control="next" aria-label="Step forward" title="Step forward">⏩</button><button class="secondary" data-replay-control="end" aria-label="Jump to end" title="Jump to end">⏭</button></div><p id="replay-progress" aria-live="polite"></p><div class="replay-bottom">' + (game.shared ? '<a class="text-button" href="./">Synhex ↗</a>' : '<button class="text-button" id="history-return">← Game history</button>') + '<button class="text-button" id="replay-share" aria-label="Copy game link" title="Copy game link">🔗</button></div>';
699 if ($('#replay-page')) { stopReplay(); $('#modal-content').innerHTML = content; }
700 else { showModal(content); modal.classList.add('replay-modal'); }
701 replay = { ...game, index: 0 };
702 renderReplay();
703}
704async function copyReplayLink ()
705{
706 const url = new URL('./', location.href); url.searchParams.set('replay', replay.shareToken);
707 try { await navigator.clipboard.writeText(url.href); toast('Game link copied.'); }
708 catch {
709 const input = document.createElement('input'); input.value = url.href; input.readOnly = true; input.setAttribute('aria-label', 'Game link');
710 $('.replay-bottom').append(input); input.select(); toast('Select and copy the game link.');
711 }
712}
713function renderReplay ()
714{
715 if (!replay || !$('#replay-card')) return;
716 const frame = replay.positions[replay.index] || { units: [], walls: [], grid: { cols: 17, rows: 14 } };
717 const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], state: { phase: 'replay', grid: frame.grid, walls: frame.walls, units: (frame.units || []).map(u => ({ ...u, hologram: false })), act: frame.act } };
718 const whiteTip = !customColoursDisabled() && (replay.pieceSkinWhite || 'White') !== 'White' ? `Playing as ${replay.pieceSkinWhite} (White)` : 'Playing as White';
719 const blackTip = !customColoursDisabled() && (replay.pieceSkinBlack || 'Black') !== 'Black' ? `Playing as ${replay.pieceSkinBlack} (Black)` : 'Playing as Black';
720 $('#replay-card').innerHTML = `<article class="game-card" data-game="replay"><div class="card-header replay-players" id="modal-title"><span title="${esc(whiteTip)}"><img src="${pieceUrl('K', replay.pieceSkinWhite || 'White')}" alt="${esc(replay.pieceSkinWhite || 'White')}">${esc(replay.whiteName)}</span><span aria-hidden="true">–</span><span title="${esc(blackTip)}"><img src="${pieceUrl('k', replay.pieceSkinBlack || 'Black')}" alt="${esc(replay.pieceSkinBlack || 'Black')}">${esc(replay.blackName)}</span></div>${board(g)}</article>`;
721 $('#replay-progress').textContent = `${replay.index} / ${Math.max(0, replay.positions.length - 1)} · ${replay.shared ? replay.outcome : replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`;
722 const last = Math.max(0, replay.positions.length - 1);
723 $('[data-replay-control="play"]').textContent = replayTimer ? '⏸' : '▶';
724 $('[data-replay-control="play"]').setAttribute('aria-label', replayTimer ? 'Pause' : 'Play');
725 $('[data-replay-control="play"]').disabled = last < 1;
726 $('[data-replay-control="start"]').disabled = $('[data-replay-control="back"]').disabled = replay.index === 0;
727 $('[data-replay-control="next"]').disabled = $('[data-replay-control="end"]').disabled = replay.index === last;
728}
729$('#modal-content').addEventListener('click', e => {
730 const b = e.target.closest('button'); if (!b) return;
731 if (b.dataset.replayId) openReplay(b.dataset.replayId);
732 if (b.id === 'history-return') showHistory();
733 if (b.id === 'replay-share') copyReplayLink();
734 const control = b.dataset.replayControl;
735 if (!control || !replay) return;
736 if (control === 'play') {
737 if (replayTimer) stopReplay();
738 else {
739 if (replay.index === replay.positions.length - 1) replay.index = 0;
740 replayTimer = setInterval(() => {
741 replay.index++;
742 if (replay.index >= replay.positions.length - 1) stopReplay();
743 renderReplay();
744 }, 500);
745 }
746 } else {
747 stopReplay();
748 const last = Math.max(0, replay.positions.length - 1);
749 replay.index = control === 'start' ? 0 : control === 'end' ? last : Math.max(0, Math.min(last, replay.index + (control === 'back' ? -1 : 1)));
750 }
751 renderReplay();
752});
753const savedAnimations = new Set();
754function animateSavedGames ()
755{
756 if (!state?.games) return;
757 for (const g of state.games) {
758 if (!g.replayId) continue;
759 const key = `synhex-saved:${state.user.id}:${g.replayId}`;
760 let seen = savedAnimations.has(key);
761 try { seen ||= localStorage.getItem(key) === '1'; } catch {}
762 const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button');
763 if (seen || !tile || !target || !target.getBoundingClientRect().width) continue;
764 savedAnimations.add(key);
765 try { localStorage.setItem(key, '1'); } catch {}
766 if (matchMedia('(prefers-reduced-motion: reduce)').matches) continue;
767 const start = tile.getBoundingClientRect(), end = target.getBoundingClientRect();
768 const icon = document.createElement('span'); icon.className = 'saved-hourglass'; icon.textContent = '⌛'; icon.setAttribute('aria-hidden', 'true');
769 icon.style.left = `${start.left + start.width / 2 - 12}px`; icon.style.top = `${start.top + 45}px`; document.body.append(icon);
770 const flight = icon.animate([{ opacity: 0, transform: 'translate(0,0) scale(.5)' }, { opacity: 1, transform: 'translate(0,0) scale(1)', offset: .2 }, { opacity: 0, transform: `translate(${end.left + end.width / 2 - start.left - start.width / 2}px,${end.top + end.height / 2 - start.top - 57}px) scale(.5)` }], { duration: 1100, easing: 'cubic-bezier(.4,0,.2,1)' });
771 flight.onfinish = () => { icon.remove(); $('#history-button')?.animate([{ transform: 'translateY(0)' }, { transform: 'translateY(-9px)' }, { transform: 'translateY(0)' }], { duration: 360, easing: 'ease-out' }); };
772 }
773}
774
775if (new URLSearchParams(location.search).has('replay')) {
776 const token = new URLSearchParams(location.search).get('replay');
777 fetch('api.php?action=shared_replay&token=' + encodeURIComponent(token), { credentials: 'omit' }).then(async response => {
778 const data = await response.json();
779 if (!response.ok) throw new Error(data.error || 'Unable to load saved games.');
780 showReplay(data);
781 }).catch(e => {
782 $('#modal-content').innerHTML = `<h1>Game unavailable</h1><p>${esc(e.message)}</p>`;
783 });
784}