CyberMax-tools commited on
Commit
43f07b6
·
verified ·
1 Parent(s): 542744a

Deploy shelfpop to the hub

Browse files
.gitattributes CHANGED
@@ -1205,3 +1205,5 @@ brand/streamwren/image-2-shot.png filter=lfs diff=lfs merge=lfs -text
1205
  brand/streamwren/image-3-shot.png filter=lfs diff=lfs merge=lfs -text
1206
  brand/streamwren/image-4-inside.png filter=lfs diff=lfs merge=lfs -text
1207
  brand/streamwren/image-5-savings.png filter=lfs diff=lfs merge=lfs -text
 
 
 
1205
  brand/streamwren/image-3-shot.png filter=lfs diff=lfs merge=lfs -text
1206
  brand/streamwren/image-4-inside.png filter=lfs diff=lfs merge=lfs -text
1207
  brand/streamwren/image-5-savings.png filter=lfs diff=lfs merge=lfs -text
1208
+ shelfpop/og.png filter=lfs diff=lfs merge=lfs -text
1209
+ shelfpop/shot-phone.png filter=lfs diff=lfs merge=lfs -text
shelfpop/arena.js ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CyberMax Arena: the cheap social layer of the CyberMax games (31 Oct 2026). Copied into each game by
2
+ // scripts/games/sync_kit.py (web/arena.js, or src/arena.js for bundled games), so every game stays self-contained.
3
+ // Goal: a game can go viral without breaking anything or running up Worker requests (docs/ceo/games-scale-2026-10-31.md).
4
+ // * counts: summed on the device, ONE beacon per session (on hide/close), sampled 1-in-w in high-traffic modes
5
+ // with the weight sent along, so the totals stay right
6
+ // * boards: read at most once per 5/15/60 minutes per device (normal/high/surge), else from this device's copy,
7
+ // else from the static snapshot on cybermaxtools.com (free), else "offline"; the game never waits on it
8
+ // * posts: skipped on the device when the score can't reach the top 20 (and no friend group needs it), queued on the
9
+ // device in surge mode or when the board is busy, and sent later by drain(); never an error for the player
10
+ // * friend groups (6-letter code, no accounts), weekly cups (ISO week, the week's Monday course), head-to-head records
11
+ // Nothing personal: a random device tag (for friend boards), the name the player typed, scores. (c) 2026 CyberMax.
12
+
13
+ export const ARENA_API = 'https://toys.cybermaxtools.com';
14
+ export const POLICY = {
15
+ normal: { w: 1, board: 5 * 60e3 },
16
+ high: { w: 10, board: 15 * 60e3 },
17
+ surge: { w: 100, board: 60 * 60e3 },
18
+ };
19
+ export const BOARD_SIZE = 20;
20
+ const G = globalThis;
21
+ const CODE_RX = /^[A-HJ-NP-Z2-9]{6}$/;
22
+ const CODE_ABC = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
23
+
24
+ // ------------------------------------------------------------------ storage (never throws: private mode, blocked storage)
25
+ export function ls(key, val) {
26
+ try {
27
+ if (val === undefined) return JSON.parse(G.localStorage.getItem(key) || 'null');
28
+ if (val === null) G.localStorage.removeItem(key); else G.localStorage.setItem(key, JSON.stringify(val));
29
+ } catch { /* private mode */ }
30
+ return val;
31
+ }
32
+ const now = () => Date.now();
33
+ const host = () => { try { return G.location.hostname || ''; } catch { return ''; } };
34
+ /** Our own test runs and local copies send nothing (tests opt in with window.__cmxBeaconTest). */
35
+ export function quiet() {
36
+ if (G.__cmxBeaconTest) return false;
37
+ if (G.__cmxNoBeacon) return true; // portals that allow no outside analytics (set by the platform adapter)
38
+ return /^(localhost|127\.|0\.0\.0\.0|\[::1\])/.test(host()) || !!(G.navigator && G.navigator.webdriver);
39
+ }
40
+
41
+ // ------------------------------------------------------------------ traffic mode hint
42
+ /** The mode this device last heard (from a board answer or the static /games/traffic.json), else normal. */
43
+ export function traffic() {
44
+ const h = ls('cmx-traffic');
45
+ return h && h.until > now() && POLICY[h.mode] ? h.mode : 'normal';
46
+ }
47
+ export function noteMode(mode, ttl = 30 * 60e3) {
48
+ if (!POLICY[mode]) return;
49
+ const h = ls('cmx-traffic');
50
+ if (h && h.forced && h.until > now()) return; // a forced mode from the static file wins until it expires
51
+ ls('cmx-traffic', { mode, until: now() + ttl });
52
+ }
53
+ /** Reads /games/traffic.json at most every 6 hours (a free static file; the owner or an agent can force a mode there). */
54
+ export async function loadTraffic(base = '') {
55
+ try {
56
+ if (!G.__cmxTrafficBase && !/(^|\.)cybermaxtools\.com$/.test(host())) return traffic();
57
+ const seen = ls('cmx-traffic-file');
58
+ if (seen && now() - seen < 6 * 3600e3) return traffic();
59
+ ls('cmx-traffic-file', now());
60
+ const r = await G.fetch(`${G.__cmxTrafficBase || base || ''}/games/traffic.json`, { cache: 'no-cache', signal: timeout(3000) });
61
+ const j = r.ok ? await r.json() : null;
62
+ if (j && POLICY[j.mode]) ls('cmx-traffic', { mode: j.mode, until: now() + 6 * 3600e3, forced: true });
63
+ } catch { /* offline: keep what we had */ }
64
+ return traffic();
65
+ }
66
+ const timeout = (ms) => (G.AbortSignal && G.AbortSignal.timeout ? G.AbortSignal.timeout(ms) : undefined);
67
+
68
+ // ------------------------------------------------------------------ counts: one beacon per session
69
+ const pend = new Map(); // game -> { "ev:ch": n }
70
+ let pendN = 0, hooked = false;
71
+ export const sent = []; // beacons sent by this page (tests read it)
72
+ const cleanCh = (c) => String(c || '').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 40);
73
+ /** Count one event. Free: nothing leaves the device until the page is hidden or closed (or 60 events pile up). */
74
+ export function tally(game, ev, ch = '') {
75
+ const c = cleanCh(ch);
76
+ try { G.dispatchEvent && G.dispatchEvent(new G.CustomEvent('cmx:count', { detail: { game, ev, ch: c } })); } catch { /* old browser */ }
77
+ if (quiet()) return;
78
+ const k = `${ev}:${cleanCh((G.__cmxChPrefix || '') + c)}`;
79
+ const m = pend.get(game) || {};
80
+ m[k] = (m[k] || 0) + 1;
81
+ pend.set(game, m);
82
+ pendN++;
83
+ if (!hooked && G.addEventListener) {
84
+ hooked = true;
85
+ G.addEventListener('pagehide', () => flush('pagehide'));
86
+ if (G.document) G.document.addEventListener('visibilitychange', () => { if (G.document.visibilityState === 'hidden') flush('hidden'); });
87
+ }
88
+ if (pendN >= 60) flush('full');
89
+ }
90
+ export const pending = () => Object.fromEntries([...pend].map(([g, m]) => [g, { ...m }]));
91
+ /** Send what is pending: one beacon per game, kept with probability 1/w and weighted by w (unbiased totals). */
92
+ export function flush(why = '') {
93
+ let n = 0;
94
+ const w = POLICY[traffic()].w;
95
+ for (const [game, m] of pend) {
96
+ if (!Object.keys(m).length) continue;
97
+ if ((G.__cmxRandom || Math.random)() * w < 1) {
98
+ const body = JSON.stringify({ t: game, n: m, w });
99
+ try {
100
+ const ok = G.navigator && G.navigator.sendBeacon && G.navigator.sendBeacon(`${ARENA_API}/eb`, new G.Blob([body], { type: 'text/plain' }));
101
+ if (!ok) G.fetch(`${ARENA_API}/eb`, { method: 'POST', body, keepalive: true, mode: 'no-cors', headers: { 'content-type': 'text/plain' } }).catch(() => {});
102
+ } catch { /* never break the game */ }
103
+ sent.push({ game, n: { ...m }, w, why });
104
+ n++;
105
+ }
106
+ }
107
+ pend.clear();
108
+ pendN = 0;
109
+ return n;
110
+ }
111
+
112
+ // ------------------------------------------------------------------ weeks (same maths as the toys Worker, social.js)
113
+ export function weekOf(iso) {
114
+ const [y, m, d] = iso.split('-').map(Number);
115
+ const t = new Date(Date.UTC(y, m - 1, d));
116
+ t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);
117
+ const wy = t.getUTCFullYear();
118
+ return `${wy}-W${String(Math.floor((t - Date.UTC(wy, 0, 1)) / 864e5 / 7) + 1).padStart(2, '0')}`;
119
+ }
120
+ export function mondayOf(wk) {
121
+ const y = +wk.slice(0, 4), w = +wk.slice(6);
122
+ const jan4 = Date.UTC(y, 0, 4), dow = (new Date(jan4).getUTCDay() + 6) % 7;
123
+ return new Date(jan4 - dow * 864e5 + (w - 1) * 7 * 864e5).toISOString().slice(0, 10);
124
+ }
125
+ /** Cup number: #1 = the week of 2 Nov 2026 (the first full week after launch). */
126
+ export const cupNumber = (wk) => Math.round((Date.parse(mondayOf(wk)) - Date.parse('2026-11-02')) / (7 * 864e5)) + 1;
127
+ function stillOpen(d, today) {
128
+ const t = Date.parse(today);
129
+ if (/^\d{4}-\d{2}-\d{2}$/.test(d)) return Math.abs(Date.parse(d) - t) <= 864e5;
130
+ const day = (o) => new Date(t + o * 864e5).toISOString().slice(0, 10);
131
+ return [day(-1), day(0), day(1)].some((x) => weekOf(x) === d);
132
+ }
133
+
134
+ // ------------------------------------------------------------------ boards (read through this device's copy)
135
+ const slim = (j) => ({ top: (j.top || []).slice(0, BOARD_SIZE).map((e) => ({ name: e.name, score: e.score })), cut: j.cut || 0,
136
+ ghost: j.ghost && typeof j.ghost.taps === 'string' && j.ghost.taps.length <= 12000 ? j.ghost : null, mode: j.mode || '' });
137
+ const cutOf = (j) => (j && j.top && j.top.length >= BOARD_SIZE ? (j.cut || j.top[j.top.length - 1].score) : 0);
138
+ export function cachedBoard(game, d) { const c = ls(`cmx-board:${game}:${d}`); return c ? { ...c.j, at: c.at } : null; }
139
+ function keepBoard(game, d, j) {
140
+ ls(`cmx-board:${game}:${d}`, { at: now(), j: slim(j) });
141
+ // keep at most 8 board copies on the device
142
+ try {
143
+ const keys = []; for (let i = 0; i < G.localStorage.length; i++) { const k = G.localStorage.key(i); if (k && k.startsWith('cmx-board:')) keys.push(k); }
144
+ if (keys.length > 8) keys.map((k) => [k, (ls(k) || {}).at || 0]).sort((a, b) => a[1] - b[1]).slice(0, keys.length - 8).forEach(([k]) => ls(k, null));
145
+ } catch { /* storage blocked */ }
146
+ }
147
+ /** A board: { top, cut, ghost, mode, src: live|cache|snapshot|stale } or null when nothing is reachable. */
148
+ export async function board(game, d, { fresh = false, wait = 4500 } = {}) {
149
+ const c = ls(`cmx-board:${game}:${d}`);
150
+ if (!fresh && c && now() - c.at < POLICY[traffic()].board) return { ...c.j, src: 'cache' };
151
+ try {
152
+ const r = await G.fetch(`${ARENA_API}/api/board?g=${encodeURIComponent(game)}&d=${encodeURIComponent(d)}`, { signal: timeout(wait) });
153
+ if (r.ok) {
154
+ const j = await r.json();
155
+ if (j.mode) noteMode(j.mode);
156
+ keepBoard(game, d, j);
157
+ return { ...slim(j), src: 'live' };
158
+ }
159
+ } catch { /* offline or capped: fall through */ }
160
+ const snap = await snapshot(game, d);
161
+ if (snap) return { ...snap, src: 'snapshot' };
162
+ return c ? { ...c.j, src: 'stale' } : null;
163
+ }
164
+ /** The static board snapshot written at site build (scripts/games/board_snapshot.py), free to read. */
165
+ async function snapshot(game, d) {
166
+ try {
167
+ if (!G.__cmxSnapshotBase && !/(^|\.)cybermaxtools\.com$/.test(host())) return null;
168
+ const r = await G.fetch(`${G.__cmxSnapshotBase || ''}/games/boards/${game}.json`, { signal: timeout(3000) });
169
+ const j = r.ok ? await r.json() : null;
170
+ const b = j && j.boards && j.boards[d];
171
+ return b ? slim(b) : null;
172
+ } catch { return null; }
173
+ }
174
+
175
+ // ------------------------------------------------------------------ device tag, friend groups
176
+ export function tag() {
177
+ let p = ls('cmx-p');
178
+ if (!/^[a-z0-9]{8}$/.test(p || '')) { p = ''; for (let i = 0; i < 8; i++) p += 'abcdefghijkmnpqrstuvwxyz23456789'[Math.floor(Math.random() * 32)]; ls('cmx-p', p); }
179
+ return p;
180
+ }
181
+ export const cleanNick = (n) => String(n || '').replace(/[^A-Za-z0-9 ]/g, '').replace(/\s+/g, ' ').trim().slice(0, 10);
182
+ export const myGroups = () => (Array.isArray(ls('cmx-groups')) ? ls('cmx-groups').filter((g) => CODE_RX.test(g.code)) : []);
183
+ export function joinGroup(code) {
184
+ code = String(code || '').toUpperCase();
185
+ if (!CODE_RX.test(code)) return false;
186
+ const gs = myGroups().filter((g) => g.code !== code);
187
+ gs.unshift({ code, at: now() });
188
+ ls('cmx-groups', gs.slice(0, 3)); // at most 3 groups per device
189
+ return true;
190
+ }
191
+ export function leaveGroup(code) { ls('cmx-groups', myGroups().filter((g) => g.code !== code)); }
192
+ export function newGroup() {
193
+ let c = ''; for (let i = 0; i < 6; i++) c += CODE_ABC[Math.floor(Math.random() * CODE_ABC.length)];
194
+ joinGroup(c);
195
+ return c;
196
+ }
197
+ /** ?fg=CODE in the link joins that group (returns the code, or ''). */
198
+ export function groupFromUrl(search) {
199
+ try { const c = new URLSearchParams(search ?? G.location.search).get('fg'); return c && joinGroup(c) ? c.toUpperCase() : ''; } catch { return ''; }
200
+ }
201
+ export function groupLink(url, code) { const u = new URL(url); u.searchParams.set('fg', code); return u.toString(); }
202
+ export async function groupBoard(game, code, d, { fresh = false } = {}) {
203
+ const key = `cmx-group:${game}:${code}:${d}`, c = ls(key);
204
+ if (!fresh && c && now() - c.at < POLICY[traffic()].board) return { ...c.j, src: 'cache' };
205
+ try {
206
+ const r = await G.fetch(`${ARENA_API}/api/group?g=${encodeURIComponent(game)}&d=${encodeURIComponent(d)}&code=${code}`, { signal: timeout(4500) });
207
+ if (r.ok) { const j = await r.json(); if (j.mode) noteMode(j.mode); const v = { top: (j.top || []).slice(0, 50) }; ls(key, { at: now(), j: v }); return { ...v, src: 'live' }; }
208
+ } catch { /* offline */ }
209
+ return c ? { ...c.j, src: 'stale' } : null;
210
+ }
211
+ const gbestKey = (game, code, d) => `${game}|${code}|${d}`;
212
+ function gbest(game, code, d, score) {
213
+ const m = ls('cmx-gbest') || {};
214
+ if (score === undefined) return m[gbestKey(game, code, d)] || 0;
215
+ m[gbestKey(game, code, d)] = score;
216
+ const ks = Object.keys(m); if (ks.length > 60) for (const k of ks.slice(0, ks.length - 60)) delete m[k];
217
+ ls('cmx-gbest', m);
218
+ return score;
219
+ }
220
+
221
+ // ------------------------------------------------------------------ posting (gated, queued, never an error)
222
+ /**
223
+ * Post a run to the daily (d = YYYY-MM-DD) or weekly (d = YYYY-Www) board and the player's friend groups.
224
+ * Returns { state: posted|skipped|queued|refused, rank, score, message, groups }.
225
+ */
226
+ export async function post(game, d, { name, taps, score, nick = '', groups = true, today = '' } = {}) {
227
+ const gs = groups ? myGroups().map((g) => g.code).filter((code) => score > gbest(game, code, d)) : [];
228
+ const c = cachedBoard(game, d);
229
+ const cut = cutOf(c);
230
+ if (cut && score <= cut && !gs.length) return { state: 'skipped', rank: 0, score, cut, message: `Saved on this device. The top 20 starts at ${cut.toLocaleString('en-US')}.` };
231
+ const item = { game, d, name, taps, score, nick: cleanNick(nick) || name, gs, at: now(), today };
232
+ if (traffic() === 'surge') return queue(item, 'Busy moment on the board: saved, and it posts on its own later.');
233
+ return send(item);
234
+ }
235
+ async function send(item) {
236
+ let r;
237
+ try {
238
+ r = await G.fetch(`${ARENA_API}/api/board`, { method: 'POST', headers: { 'content-type': 'application/json' }, signal: timeout(8000),
239
+ body: JSON.stringify({ g: item.game, d: item.d, name: item.name, taps: item.taps, s: item.score, groups: item.gs, p: item.gs.length ? tag() : undefined, nick: item.nick }) });
240
+ } catch { return queue(item, 'Offline for now: saved, and it posts on its own later.'); }
241
+ let j = null; try { j = await r.json(); } catch { /* not JSON */ }
242
+ if (r.ok && j && j.ok) {
243
+ if (j.mode) noteMode(j.mode);
244
+ if (Array.isArray(j.top)) keepBoard(item.game, item.d, j);
245
+ for (const g of j.groups || []) if (g && g.best) gbest(item.game, g.code, item.d, g.best);
246
+ return { state: 'posted', rank: j.rank || 0, score: j.score ?? item.score, groups: j.groups || [], checked: j.checked !== false,
247
+ message: j.rank ? `Posted! You're #${j.rank}.` : 'Posted! Not in the top 20 yet. Keep going.' };
248
+ }
249
+ if (r.status === 422 || r.status === 400) return { state: 'refused', rank: 0, score: item.score, message: (j && j.message) || 'That run could not be posted.' };
250
+ return queue(item, 'The board is busy: saved, and it posts on its own later.');
251
+ }
252
+ function queue(item, message) {
253
+ const q = (ls('cmx-q') || []).filter((x) => !(x.game === item.game && x.d === item.d && x.score >= item.score));
254
+ if (!q.some((x) => x.game === item.game && x.d === item.d)) q.push(item);
255
+ else for (let i = 0; i < q.length; i++) if (q[i].game === item.game && q[i].d === item.d) q[i] = item;
256
+ ls('cmx-q', q.slice(-10));
257
+ return { state: 'queued', rank: 0, score: item.score, message };
258
+ }
259
+ export const queued = (game) => (ls('cmx-q') || []).filter((x) => !game || x.game === game);
260
+ /** Send at most ONE queued post for this game (call once at boot); drops posts whose day or week has closed. */
261
+ export async function drain(game, today) {
262
+ if (traffic() === 'surge') return null;
263
+ const q = ls('cmx-q') || [];
264
+ const keep = q.filter((x) => stillOpen(x.d, today || new Date().toISOString().slice(0, 10)));
265
+ const i = keep.findIndex((x) => x.game === game);
266
+ if (i < 0) { ls('cmx-q', keep); return null; }
267
+ const [item] = keep.splice(i, 1);
268
+ ls('cmx-q', keep);
269
+ return send(item);
270
+ }
271
+
272
+ // ------------------------------------------------------------------ head-to-head records (challenge links, on the device)
273
+ /** Record one finished challenge (id = the challenge link's run id); returns the record against that rival. */
274
+ export function h2hRecord(game, rival, id, mine, theirs) {
275
+ const all = ls('cmx-h2h') || {};
276
+ const g = all[game] || (all[game] = {});
277
+ const key = cleanNick(rival).toLowerCase() || 'friend';
278
+ const r = g[key] || (g[key] = { name: cleanNick(rival) || 'Friend', c: {} });
279
+ const prev = r.c[id];
280
+ if (!prev || mine > prev.mine) r.c[id] = { mine, theirs };
281
+ const ids = Object.keys(r.c); if (ids.length > 50) for (const k of ids.slice(0, ids.length - 50)) delete r.c[k];
282
+ ls('cmx-h2h', all);
283
+ return h2h(game, rival);
284
+ }
285
+ export function h2h(game, rival) {
286
+ const r = ((ls('cmx-h2h') || {})[game] || {})[cleanNick(rival).toLowerCase() || 'friend'];
287
+ const out = { name: r ? r.name : cleanNick(rival), w: 0, l: 0, t: 0 };
288
+ if (r) for (const { mine, theirs } of Object.values(r.c)) { if (mine > theirs) out.w++; else if (mine < theirs) out.l++; else out.t++; }
289
+ return out;
290
+ }
shelfpop/cmx.js ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CyberMax Fun kit: shared browser helpers for the CyberMax games (copied into each game's web/ folder by
2
+ // scripts/games/sync_kit.py, so every game stays self-contained and sellable on its own).
3
+ // Counter beacon (game + event + channel only: no cookies, no IDs, nothing personal), daily seed, share, PWA install.
4
+ // (c) 2026 CyberMax. All rights reserved.
5
+ import { tally } from './arena.js';
6
+
7
+ export const SITE = 'https://cybermaxtools.com';
8
+ export const API = 'https://toys.cybermaxtools.com';
9
+ export const EPOCH = Date.UTC(2026, 9, 2); // 2 Oct 2026 = puzzle #1 for every CyberMax daily game
10
+
11
+ /** Today's date in the player's own time zone as YYYY-MM-DD (everyone gets a new puzzle at their local midnight). */
12
+ export function today(d = new Date()) {
13
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
14
+ }
15
+ /** Puzzle number for a YYYY-MM-DD date (#1 = 2026-10-02). */
16
+ export function dayNumber(iso) {
17
+ const [y, m, d] = iso.split('-').map(Number);
18
+ return Math.round((Date.UTC(y, m - 1, d) - EPOCH) / 864e5) + 1;
19
+ }
20
+ export function dateOf(n) {
21
+ const t = new Date(EPOCH + (n - 1) * 864e5);
22
+ return t.toISOString().slice(0, 10);
23
+ }
24
+
25
+ /** 32-bit string hash (FNV-1a) and a small fast PRNG (mulberry32): the same seed gives the same game everywhere. */
26
+ export function hash(str) {
27
+ let h = 0x811c9dc5;
28
+ for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 0x01000193); }
29
+ return h >>> 0;
30
+ }
31
+ export function rng(seed) {
32
+ let a = typeof seed === 'string' ? hash(seed) : seed >>> 0;
33
+ return function () {
34
+ a = (a + 0x6d2b79f5) >>> 0;
35
+ let t = a;
36
+ t = Math.imul(t ^ (t >>> 15), t | 1);
37
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
38
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Count one event (play, win, share, install, pro, cta). Never breaks the page; skipped on localhost and in tests.
44
+ * 31 Oct 2026 (scale fix): events are summed on the device and sent as ONE beacon per session (arena.js tally), sampled
45
+ * with a weight in high-traffic modes, instead of one Worker request per event. It still fires a "cmx:count" event.
46
+ */
47
+ export function count(game, ev, ch = '') {
48
+ try { tally(game, ev, ch); } catch { /* never break the game */ }
49
+ }
50
+
51
+ export function store(key, val) {
52
+ try {
53
+ if (val === undefined) return JSON.parse(localStorage.getItem(key) || 'null');
54
+ localStorage.setItem(key, JSON.stringify(val));
55
+ } catch { /* private mode */ }
56
+ return val;
57
+ }
58
+
59
+ export function toast(msg, ms = 2400) {
60
+ let t = document.getElementById('toast');
61
+ if (!t) { t = document.createElement('div'); t.id = 'toast'; t.setAttribute('role', 'status'); document.body.appendChild(t); }
62
+ t.textContent = msg;
63
+ t.classList.add('on');
64
+ clearTimeout(t._h);
65
+ t._h = setTimeout(() => t.classList.remove('on'), ms);
66
+ }
67
+
68
+ /** The link people share: the canonical game page with UTM tags the site view counter reads. */
69
+ export function shareLink(path, channel, game) {
70
+ const u = new URL(SITE + path);
71
+ u.searchParams.set('utm_source', channel);
72
+ u.searchParams.set('utm_medium', 'share');
73
+ u.searchParams.set('utm_campaign', `game-${game}`);
74
+ return u.toString();
75
+ }
76
+
77
+ /**
78
+ * Share a result: native share sheet on phones (text + optional PNG card), else copy to clipboard.
79
+ * text = Wordle-style text block; path = the game's path on the CyberMax site; blob = optional PNG card.
80
+ */
81
+ export async function share(game, text, path, blob, filename) {
82
+ const url = shareLink(path, 'share', game);
83
+ const full = `${text}\n${url}`;
84
+ if (navigator.share) {
85
+ try {
86
+ const file = blob ? new File([blob], filename || `${game}.png`, { type: 'image/png' }) : null;
87
+ const data = file && navigator.canShare && navigator.canShare({ files: [file] }) ? { files: [file], text: full } : { text: full };
88
+ await navigator.share(data);
89
+ count(game, 'share', 'native');
90
+ return 'shared';
91
+ } catch (e) {
92
+ if (e && e.name === 'AbortError') return 'cancelled';
93
+ }
94
+ }
95
+ try { await navigator.clipboard.writeText(full); toast('Result copied. Paste it anywhere.'); } catch { prompt('Copy your result:', full); }
96
+ count(game, 'share', 'copy');
97
+ return 'copied';
98
+ }
99
+
100
+ export function intents(game, text, path) {
101
+ const u = (ch) => shareLink(path, ch, game);
102
+ return {
103
+ x: `https://x.com/intent/post?text=${encodeURIComponent(text)}&url=${encodeURIComponent(u('x'))}`,
104
+ bsky: `https://bsky.app/intent/compose?text=${encodeURIComponent(`${text}\n${u('bsky')}`)}`,
105
+ whatsapp: `https://wa.me/?text=${encodeURIComponent(`${text}\n${u('whatsapp')}`)}`,
106
+ };
107
+ }
108
+
109
+ export function download(blob, filename) {
110
+ const a = document.createElement('a');
111
+ a.href = URL.createObjectURL(blob);
112
+ a.download = filename;
113
+ document.body.appendChild(a);
114
+ a.click();
115
+ setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 1500);
116
+ }
117
+
118
+ /**
119
+ * Installable app: registers the service worker (offline play) and shows an "Add to Home Screen" button.
120
+ * Chrome/Edge/Android: the real install prompt. iPhone/iPad Safari: a short Share → Add to Home Screen hint.
121
+ * The button only appears after the first finished round (offer(): never on first load) and never once installed.
122
+ */
123
+ export function pwa(game, btn) {
124
+ if ('serviceWorker' in navigator && (location.protocol === 'https:' || location.hostname === 'localhost')) {
125
+ navigator.serviceWorker.register('sw.js').catch(() => {});
126
+ }
127
+ const standalone = matchMedia('(display-mode: standalone)').matches || navigator.standalone;
128
+ if (standalone) { count(game, 'play', 'app'); return { offer() {} }; }
129
+ let deferred = null;
130
+ let wanted = false;
131
+ const ios = /iphone|ipad|ipod/i.test(navigator.userAgent) && !/crios|fxios/i.test(navigator.userAgent);
132
+ window.addEventListener('beforeinstallprompt', (e) => { e.preventDefault(); deferred = e; if (wanted && btn && !store(`cmx-install-no:${game}`)) btn.hidden = false; });
133
+ window.addEventListener('appinstalled', () => { count(game, 'install', 'prompt'); if (btn) btn.hidden = true; });
134
+ if (btn) {
135
+ btn.addEventListener('click', async () => {
136
+ if (deferred) {
137
+ deferred.prompt();
138
+ const r = await deferred.userChoice.catch(() => null);
139
+ if (r && r.outcome === 'accepted') btn.hidden = true;
140
+ else if (r && r.outcome === 'dismissed') { store(`cmx-install-no:${game}`, 1); btn.hidden = true; } // "Not now" is remembered
141
+ deferred = null;
142
+ } else if (ios) {
143
+ toast('Tap the Share button, then "Add to Home Screen".', 5000);
144
+ count(game, 'install', 'ios-hint');
145
+ store(`cmx-install-no:${game}`, 1);
146
+ }
147
+ });
148
+ }
149
+ return {
150
+ offer() {
151
+ wanted = true;
152
+ if (btn && (deferred || ios) && !store(`cmx-install-no:${game}`)) btn.hidden = false;
153
+ },
154
+ };
155
+ }
156
+
157
+ /** Rounded rectangle path for canvas cards. */
158
+ export function rr(ctx, x, y, w, h, r) {
159
+ ctx.beginPath();
160
+ ctx.moveTo(x + r, y);
161
+ ctx.arcTo(x + w, y, x + w, y + h, r);
162
+ ctx.arcTo(x + w, y + h, x, y + h, r);
163
+ ctx.arcTo(x, y + h, x, y, r);
164
+ ctx.arcTo(x, y, x + w, y, r);
165
+ ctx.closePath();
166
+ }
167
+
168
+ export const canvasBlob = (canvas) => new Promise((res) => canvas.toBlob(res, 'image/png'));
169
+
170
+ /** Theme toggle shared by every page (light/dark, remembered). */
171
+ export function themeToggle(btn) {
172
+ if (!btn) return;
173
+ btn.addEventListener('click', () => {
174
+ const r = document.documentElement;
175
+ const c = r.dataset.theme || 'dark'; // games default to the dark arcade look (fun.css)
176
+ const n = c === 'dark' ? 'light' : 'dark';
177
+ r.dataset.theme = n;
178
+ store('cm-theme-v', n);
179
+ try { localStorage.setItem('cm-theme', n); } catch { /* private mode */ }
180
+ });
181
+ }
182
+
183
+ // ------------------------------------------------------------------ first-touch attribution on buy links
184
+ // First-sale review (29 Oct 2026, docs/ceo/first-sale-2026-10-27.md): the first paid order could be traced to the page
185
+ // that sold it but not to where the buyer came from. So the first time this browser opens a CyberMax page, one short tag
186
+ // is kept in localStorage (no cookie, no id, never sent on its own): where it came from (utm_source + utm_campaign, s=,
187
+ // the referrer's host or "direct") and the landing page, e.g. "ft-youtube-brimbloom-at-games-brimbloom". A Buy click
188
+ // carries it: s=<source>--<tag> on data.cybermaxtools.com/buy links (the Worker copies s into client_reference_id
189
+ // "data_<s>"), client_reference_id=<id>--<tag> on buy.stripe.com links. No extra request, page view or Worker call.
190
+ // The same code is in shared/convert-kit/convert.js (site pages), so the tag is shared across cybermaxtools.com.
191
+ const FT_KEY = 'cmx-ft';
192
+ const FT_DAYS = 90;
193
+ const ftSlug = (x, n) => String(x || '').toLowerCase().replace(/^www\./, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, n).replace(/-+$/, '');
194
+ // words collect.py reads as "our own test" (TEST_MARK) never appear in a buyer's tag
195
+ const ftClean = (t) => t.replace(/(^|-)(test|e2e|check|probe|audit|lane\d*|internal)(?=-|$)/g, '$1x');
196
+ export function ftCompute(loc, referrer) {
197
+ const q = new URLSearchParams(loc.search || '');
198
+ const us = q.get('utm_source'), uc = q.get('utm_campaign'), s = q.get('s');
199
+ let ch;
200
+ if (us) ch = ftSlug(us, 14) + (uc ? `-${ftSlug(String(uc).replace(/^\d{4}-\d{2}-\d{2}-(\d+-)?/, ''), 18)}` : ''); // post ids start with a date
201
+ else if (s) ch = `s-${ftSlug(s, 24)}`;
202
+ else {
203
+ let host = '';
204
+ try { host = referrer ? new URL(referrer).hostname.toLowerCase() : ''; } catch { host = 'other'; }
205
+ ch = !host ? 'direct' : /(^|\.)cybermaxtools\.com$|cybermax-tools/.test(host) ? `site-${ftSlug(host.split('.')[0], 12)}` : `r-${ftSlug(host, 24)}`;
206
+ }
207
+ const segs = String(loc.pathname || '/').toLowerCase().split('/').filter((x) => x && !/^index\.html?$/.test(x));
208
+ const land = ftSlug(segs.slice(-2).join('-'), 18) || 'home';
209
+ return ftClean(`ft-${ch || 'direct'}-at-${land}`).slice(0, 48).replace(/-+$/, '');
210
+ }
211
+ /** The first-touch tag of this browser ('' when storage is blocked). Recorded once, kept FT_DAYS days. */
212
+ export function firstTouch() {
213
+ try {
214
+ const old = JSON.parse(localStorage.getItem(FT_KEY) || 'null');
215
+ if (old && old.t && Date.now() - old.at < FT_DAYS * 864e5) return old.t;
216
+ const t = ftCompute(location, document.referrer);
217
+ localStorage.setItem(FT_KEY, JSON.stringify({ t, at: Date.now() }));
218
+ return t;
219
+ } catch { return ''; }
220
+ }
221
+ /** href with the first-touch tag added (data /buy links: s; Stripe links: client_reference_id). Pure, for tests too. */
222
+ export function ftTagUrl(href, t) {
223
+ if (!t) return href;
224
+ try {
225
+ const u = new URL(href);
226
+ if (u.hostname === 'data.cybermaxtools.com' && u.pathname.startsWith('/buy/')) {
227
+ const s = (u.searchParams.get('s') || 'unknown').toLowerCase().replace(/[^a-z0-9-]/g, '');
228
+ if (s.includes('--ft-')) return href;
229
+ u.searchParams.set('s', `${s}--${t}`.slice(0, 80).replace(/-+$/, '')); // the Worker keeps s to 80 chars of [a-z0-9-]
230
+ return u.toString();
231
+ }
232
+ if (u.hostname === 'buy.stripe.com') {
233
+ const c = u.searchParams.get('client_reference_id') || 'data_unknown';
234
+ if (c.includes('--ft-')) return href;
235
+ u.searchParams.set('client_reference_id', `${c}--${t}`.slice(0, 200)); // Stripe: 200 chars of letters, digits, - and _
236
+ return u.toString();
237
+ }
238
+ } catch { /* not a URL */ }
239
+ return href;
240
+ }
241
+ if (typeof document !== 'undefined' && typeof location !== 'undefined' && !window.__cmxFt) {
242
+ window.__cmxFt = 1;
243
+ firstTouch();
244
+ // capture phase, registered before funpass.js/skins.js add their direct-checkout handler (they import this module)
245
+ document.addEventListener('click', (e) => {
246
+ const a = e.target && e.target.closest && e.target.closest('a[href*="data.cybermaxtools.com/buy/"],a[href*="buy.stripe.com/"]');
247
+ if (a) { const t = firstTouch(); if (t) a.href = ftTagUrl(a.href, t); }
248
+ }, true);
249
+ }
250
+
251
+ // ------------------------------------------------------------------ calm play focus (7 Nov 2026 quality pass)
252
+ // "Calm screens in every game": on a phone, a touch on the board (the stage canvas or board inside section.game) sets
253
+ // html.cmx-focus, and fun.css then hides the shop/skin/pass buttons, the swatches and the "Get more" row until the round
254
+ // ends. A results panel appearing (#over, #win, #done, .win, .over) or a touch outside the game clears it; a touch on the board sets it again even if old results stay on screen. Pure CSS
255
+ // hooks: a game without section.game is untouched.
256
+ export const FOCUS_END = '#over,#win,#done,.win,.over,[data-cmx-end]';
257
+ export function focusWatch(doc = document) {
258
+ const game = doc.querySelector('section.game');
259
+ if (!game || doc.documentElement.dataset.cmxFocus === 'off') return null;
260
+ const root = doc.documentElement;
261
+ const stage = (t) => t && t.closest && t.closest('canvas,#board,#arena,.board-wrap,.stage,#stage,[class$="-wrap"]') && game.contains(t);
262
+ const shown = () => new Set([...game.querySelectorAll(FOCUS_END)].filter((e) => !e.hidden && e.offsetParent !== null));
263
+ const set = (on) => root.classList.toggle('cmx-focus', !!on);
264
+ let was = shown();
265
+ // a touch on the board starts (or keeps) the focus, even when last round's results stay on screen below it
266
+ doc.addEventListener('pointerdown', (e) => { if (stage(e.target)) { set(true); was = shown(); } else if (!game.contains(e.target)) set(false); }, true);
267
+ // a results panel that newly appears ends it
268
+ new MutationObserver(() => { const now = shown(); if ([...now].some((x) => !was.has(x))) set(false); was = now; })
269
+ .observe(game, { subtree: true, attributes: true, attributeFilter: ['hidden', 'class'] });
270
+ return { set, shown };
271
+ }
272
+ if (typeof document !== 'undefined' && !window.__cmxFocus) {
273
+ window.__cmxFocus = 1;
274
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => focusWatch(), { once: true });
275
+ else focusWatch();
276
+ }
shelfpop/core.js ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Shelf Pop rules (no DOM, unit-tested): shelves of goods, three slots in front and more rows behind. Move a front item
2
+ // to a free slot; three of a kind on one shelf pop, and the row behind slides forward. Clear every shelf before the
3
+ // clock runs out. Every board is checked solvable by a solver before anyone plays it. (c) 2026 CyberMax. All rights reserved.
4
+
5
+ export const GOODS = [
6
+ { id: 'apple', e: '🍎', c: '#FF5A5A' }, { id: 'lemon', e: '🍋', c: '#FFD23F' }, { id: 'grape', e: '🍇', c: '#9B6BFF' },
7
+ { id: 'carrot', e: '🥕', c: '#FF9F1C' }, { id: 'donut', e: '🍩', c: '#FF8FC8' }, { id: 'milk', e: '🥛', c: '#7FC8FF' },
8
+ { id: 'melon', e: '🍉', c: '#4CCB7A' }, { id: 'cookie', e: '🍪', c: '#C98A5A' }, { id: 'egg', e: '🥚', c: '#F2E6CC' },
9
+ { id: 'berry', e: '🫐', c: '#4D6BFF' }, { id: 'cheese', e: '🧀', c: '#FFB627' }, { id: 'mint', e: '🍬', c: '#2FD3C0' },
10
+ ];
11
+
12
+ export function hash(str) { let h = 0x811c9dc5; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 0x01000193); } return h >>> 0; }
13
+ export function rng(seed) {
14
+ let a = typeof seed === 'string' ? hash(seed) : seed >>> 0;
15
+ return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
16
+ }
17
+
18
+ /** Board size for a level (1, 2, … ) or the daily ('daily'). shelves × depth rows × 3 slots, `empty` free slots in front. */
19
+ export function specOf(level) {
20
+ if (level === 'daily') return { shelves: 6, depth: 3, empty: 6, kinds: 9 };
21
+ const n = Math.max(1, level | 0);
22
+ if (n === 1) return { shelves: 3, depth: 1, empty: 3, kinds: 2 };
23
+ if (n === 2) return { shelves: 4, depth: 1, empty: 3, kinds: 3 };
24
+ if (n === 3) return { shelves: 4, depth: 2, empty: 3, kinds: 5 };
25
+ // at most 6 shelves (2 columns x 3, big targets on a phone) and 3 rows deep: rounds stay around two minutes
26
+ const shelves = Math.min(6, 4 + Math.floor((n - 4) / 3)), depth = Math.min(3, 2 + Math.floor((n - 4) / 5));
27
+ return { shelves, depth, empty: n % 2 ? 3 : 6, kinds: Math.min(GOODS.length, 4 + Math.floor(n / 2)) };
28
+ }
29
+ export const triplesOf = (sp) => (sp.shelves * sp.depth * 3 - sp.empty) / 3;
30
+ /** Seconds on the clock: generous early, tighter later. */
31
+ export const timeOf = (sp) => Math.round(20 + triplesOf(sp) * (sp.depth >= 3 ? 6.5 : 7.5));
32
+
33
+ // ------------------------------------------------------------------ board state: shelves[i] = rows (front first), row = [a,b,c] (null = free)
34
+ export const clone = (b) => b.map((s) => s.map((r) => r.slice()));
35
+ export const front = (b, i) => b[i][0] || [null, null, null];
36
+ export const isEmpty = (b) => b.every((s) => s.length === 0 || (s.length === 1 && s[0].every((x) => x === null)));
37
+ const full3 = (r) => r[0] !== null && r[0] === r[1] && r[1] === r[2];
38
+
39
+ /** Apply one move in place: item at shelf a slot i → shelf c slot j (or the first free slot). Returns events or null if illegal. */
40
+ export function move(b, a, i, c, j = -1) {
41
+ if (a === c) return null;
42
+ const fa = b[a][0], fc = b[c][0] || (b[c][0] = [null, null, null]);
43
+ if (!fa || fa[i] == null) return null;
44
+ if (j < 0 || fc[j] != null) j = fc.indexOf(null);
45
+ if (j < 0) return null;
46
+ const item = fa[i]; fa[i] = null; fc[j] = item;
47
+ const ev = { item, from: [a, i], to: [c, j], pop: null, slid: [] };
48
+ if (full3(fc)) { ev.pop = { shelf: c, item }; b[c][0] = [null, null, null]; }
49
+ for (const s of [a, c]) settle(b, s, ev);
50
+ return ev;
51
+ }
52
+ function settle(b, s, ev) {
53
+ const sh = b[s];
54
+ while (sh.length > 1 && sh[0].every((x) => x === null)) { sh.shift(); ev.slid.push(s); if (full3(sh[0])) { ev.pop2 = (ev.pop2 || []).concat({ shelf: s, item: sh[0][0] }); sh[0] = [null, null, null]; } }
55
+ }
56
+ /** All legal moves (front item → a shelf with a free front slot). */
57
+ export function moves(b) {
58
+ const out = [];
59
+ for (let a = 0; a < b.length; a++) {
60
+ const fa = b[a][0]; if (!fa) continue;
61
+ for (let i = 0; i < 3; i++) {
62
+ if (fa[i] == null) continue;
63
+ for (let c = 0; c < b.length; c++) if (c !== a && (!b[c][0] || b[c][0].includes(null))) out.push([a, i, c]);
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+ export const stuck = (b) => !isEmpty(b) && moves(b).length === 0;
69
+ const key = (b) => b.map((s) => s.map((r) => r.map((x) => (x == null ? '.' : x.toString(36))).sort().join('')).join('/')).sort().join('|');
70
+
71
+ /** Depth-first solver with a move order a person would use (finish a triple, then join a pair, then free a row). */
72
+ export function solve(b0, limit = 40000) {
73
+ const seen = new Set(); let nodes = 0;
74
+ const score = (b, [a, i, c]) => {
75
+ const it = b[a][0][i], fc = b[c][0] || [], same = fc.filter((x) => x === it).length, left = b[a][0].filter((x) => x != null).length;
76
+ return same * 10 + (left === 1 ? 3 : 0) - (fc.every((x) => x == null) ? 2 : 0);
77
+ };
78
+ const path = [], items = b0.flat(2).filter((x) => x != null).length, maxDepth = items * 2 + 6;
79
+ const go = (b, last) => {
80
+ if (isEmpty(b)) return true;
81
+ if (++nodes > limit || path.length > maxDepth) return false;
82
+ const k = key(b); if (seen.has(k)) return false; seen.add(k);
83
+ const ms = moves(b).filter((m) => !(last && m[0] === last[2] && m[2] === last[0])).map((m) => [score(b, m), m]).sort((x, y) => y[0] - x[0]);
84
+ for (const [, m] of ms) {
85
+ const n = clone(b); move(n, m[0], m[1], m[2]); path.push(m);
86
+ if (go(n, m)) return true;
87
+ path.pop();
88
+ }
89
+ return false;
90
+ };
91
+ const ok = go(clone(b0), null);
92
+ return { ok, nodes, path: ok ? path.slice() : null };
93
+ }
94
+
95
+ /** A solvable board for a seed: triples dealt into the rows, free slots only in front, no ready-made triple anywhere. */
96
+ export function makeBoard(seed, sp) {
97
+ for (let attempt = 0; attempt < 400; attempt++) {
98
+ const r = rng(`${seed}#${attempt}`), T = triplesOf(sp);
99
+ const pool = [];
100
+ for (let t = 0; t < T; t++) { const k = t % sp.kinds; pool.push(k, k, k); }
101
+ for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
102
+ const holes = new Set();
103
+ while (holes.size < sp.empty) holes.add(Math.floor(r() * sp.shelves) * 3 + Math.floor(r() * 3));
104
+ const b = []; let p = 0, bad = false;
105
+ for (let s = 0; s < sp.shelves; s++) {
106
+ const rows = [];
107
+ for (let d = 0; d < sp.depth; d++) rows.push([0, 1, 2].map((k) => (d === 0 && holes.has(s * 3 + k) ? null : pool[p++])));
108
+ if (rows.some((row) => full3(row))) bad = true;
109
+ while (rows.length > 1 && rows[0].every((x) => x === null)) rows.shift();
110
+ b.push(rows);
111
+ }
112
+ if (bad || p !== pool.length) continue;
113
+ if (moves(b).length < 2) continue;
114
+ const s = solve(b, 5000);
115
+ if (s.ok) return { board: b, attempt, solution: s.path };
116
+ }
117
+ throw new Error('no solvable board');
118
+ }
119
+
120
+ /** A whole round: the board, the clock, scoring. */
121
+ export function makeGame(seed, level) {
122
+ const sp = specOf(level), { board, solution } = makeBoard(seed, sp);
123
+ const g = { seed, level, sp, board, total: triplesOf(sp), popped: 0, moves: 0, time: timeOf(sp), t: 0, score: 0, combo: 0, bestCombo: 0, lastPop: -99, state: 'run', solution, popsBy: {} };
124
+ g.tick = (dt) => { if (g.state !== 'run') return; g.t += dt; if (g.t >= g.time) { g.t = g.time; g.state = 'over'; } };
125
+ g.left = () => Math.max(0, g.time - g.t);
126
+ g.play = (a, i, c, j = -1) => {
127
+ if (g.state !== 'run') return null;
128
+ const ev = move(g.board, a, i, c, j); if (!ev) return null;
129
+ g.moves++;
130
+ for (const p of [ev.pop, ...(ev.pop2 || [])].filter(Boolean)) {
131
+ g.combo = g.t - g.lastPop <= 4 ? g.combo + 1 : 1; g.lastPop = g.t; g.bestCombo = Math.max(g.bestCombo, g.combo);
132
+ const pts = 30 * Math.min(5, g.combo); g.score += pts; p.pts = pts; p.combo = g.combo; g.popped++;
133
+ g.popsBy[p.item] = (g.popsBy[p.item] || 0) + 1;
134
+ }
135
+ if (isEmpty(g.board)) { g.state = 'done'; g.bonus = Math.round(g.left()) * 5; g.score += g.bonus; }
136
+ else if (stuck(g.board)) g.state = 'stuck';
137
+ return ev;
138
+ };
139
+ g.stars = () => (g.state !== 'done' ? 0 : g.left() >= g.time * 0.4 ? 3 : g.left() >= g.time * 0.2 ? 2 : 1);
140
+ return g;
141
+ }
142
+
143
+ export const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
144
+ /** Share line: the goods you popped, in order of the shelf, and the time. */
145
+ export function shareText(g, label) {
146
+ const ems = Object.keys(g.popsBy).map(Number).sort((a, b) => a - b).map((k) => GOODS[k].e).join('');
147
+ const head = g.state === 'done' ? `cleared in ${fmt(g.t)} ${'⭐'.repeat(g.stars())}` : `${g.popped}/${g.total} popped`;
148
+ return `Shelf Pop ${label} 🛒 ${g.score.toLocaleString('en-US')}\n${ems || '🛒'} ${head}\nbest combo x${g.bestCombo}`;
149
+ }
shelfpop/fun.css ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* CyberMax Fun kit: shared look for CyberMax games (copied into each game). Mobile first. 2026 look: soft dusk by default (7 Nov 2026: lifted from near-black after "too dark"),
2
+ dark arcade (glass panels, a glow in each game's own colours behind the stage), light on request. (c) 2026 CyberMax. */
3
+ :root{--bg:#161B2E;--bg2:#1E2440;--card:rgba(40,47,74,.72);--card-solid:#252B45;--ink:#F4F2FA;--muted:#B7BCD0;--line:rgba(255,255,255,.14);--chip:rgba(255,255,255,.08);--acc:#FF6A3D;--acc-ink:#11141B;--ok:#2FD3A0;--bad:#FF7A5C;--game:#5CF2FF;--game2:#FF4D9A;--shadow:0 1px 0 rgba(255,255,255,.04) inset,0 18px 50px rgba(0,0,0,.45);color-scheme:dark}
4
+ :root[data-theme=light]{--bg:#F6F3EC;--bg2:#EFEADF;--card:#fff;--card-solid:#fff;--ink:#11141B;--muted:#565C6B;--line:#E2DCD0;--chip:#ECE6DA;--ok:#0B7F5E;--bad:#C2361B;--shadow:0 1px 2px rgba(17,20,27,.06),0 10px 30px rgba(17,20,27,.08);color-scheme:light}
5
+ *{box-sizing:border-box}[hidden]{display:none!important}html{-webkit-text-size-adjust:100%}
6
+ body{margin:0;background:radial-gradient(1100px 620px at 50% -12%,color-mix(in srgb,var(--game) 26%,transparent),transparent 70%),radial-gradient(800px 520px at 105% 38%,color-mix(in srgb,var(--game2) 16%,transparent),transparent 70%),radial-gradient(700px 500px at -8% 70%,color-mix(in srgb,var(--game) 9%,transparent),transparent 70%),linear-gradient(180deg,var(--bg),var(--bg2));background-attachment:fixed;color:var(--ink);font:16px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;overflow-x:hidden;min-height:100vh}
7
+ :root[data-theme=light] body{background:var(--bg)}
8
+ a{color:inherit}img,canvas{max-width:100%}
9
+ .wrap{max-width:760px;margin:0 auto;padding:0 16px}
10
+ .top{display:flex;align-items:center;gap:6px;padding:12px 0}
11
+ .top .brand{display:flex;align-items:center;gap:8px;font-weight:800;text-decoration:none;font-size:18px;margin-right:auto}.top .brand svg{width:28px;height:28px}
12
+ .top nav a,.top .icon{color:var(--muted);text-decoration:none;padding:8px 10px;border-radius:10px;font-size:15px;background:none;border:0;font-family:inherit;cursor:pointer;min-height:40px}
13
+ .top nav a:hover,.top .icon:hover{color:var(--ink);background:var(--chip)}
14
+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:48px;padding:10px 18px;border-radius:12px;border:0;background:var(--acc);color:var(--acc-ink);font:inherit;font-weight:800;font-size:16px;cursor:pointer;text-decoration:none;touch-action:manipulation}
15
+ .btn:hover{filter:brightness(1.08)}.btn:not(.ghost){box-shadow:0 6px 22px color-mix(in srgb,var(--acc) 35%,transparent)}.btn.ghost{background:transparent;color:var(--ink);border:1.5px solid var(--line)}.btn.sm{min-height:40px;padding:6px 14px;font-size:15px}
16
+ .btn.pass{background:linear-gradient(135deg,#FFB547,#FF6A3D);color:#11141B}
17
+ .row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
18
+ .chips{display:flex;gap:6px;flex-wrap:wrap}
19
+ .chip{border:1.5px solid var(--line);background:var(--chip);color:var(--ink);border-radius:999px;padding:6px 12px;font:inherit;font-size:14px;font-weight:700;cursor:pointer;min-height:36px}
20
+ .chip[aria-pressed=true]{background:var(--ink);color:var(--bg);border-color:var(--ink)}.chip .lock{opacity:.7;font-size:12px}
21
+ .panel{background:var(--card);border:1px solid var(--line);border-radius:20px;padding:16px;box-shadow:var(--shadow)}
22
+ .muted{color:var(--muted)}.small{font-size:14px}
23
+ h1{font-size:clamp(28px,6.4vw,46px);font-weight:900;line-height:1.05;letter-spacing:-.025em;margin:0 0 6px;text-wrap:balance}
24
+ h2{font-size:21px;letter-spacing:-.01em;margin:30px 0 8px}
25
+ .seo h3{font-size:17px;margin:18px 0 4px}.seo p,.seo li{color:var(--muted)}
26
+ .more{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:10px;margin:12px 0}
27
+ .more a{display:block;padding:12px 14px;border:1px solid var(--line);border-radius:14px;background:var(--card);text-decoration:none;transition:transform .15s,border-color .15s}.more a:hover{transform:translateY(-2px);border-color:color-mix(in srgb,var(--game) 50%,var(--line))}.more a b{display:block}.more a span{color:var(--muted);font-size:14px}
28
+ footer{color:var(--muted);font-size:14px;padding:26px 0 40px;border-top:1px solid var(--line);margin-top:36px}
29
+ #toast{position:fixed;left:50%;bottom:22px;transform:translate(-50%,40px);opacity:0;background:var(--ink);color:var(--bg);padding:12px 16px;border-radius:12px;font-weight:700;transition:.25s;z-index:99;max-width:calc(100% - 32px);text-align:center;pointer-events:none}
30
+ #toast.on{transform:translate(-50%,0);opacity:1}
31
+ .nudge{display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap;border:1.5px dashed var(--line);border-radius:14px;padding:10px 12px;margin-top:12px;font-size:15px}
32
+ html.cmx-pro .nudge{display:none}
33
+ .pro-badge{display:none;font-size:12px;font-weight:800;background:linear-gradient(135deg,#FFB547,#FF6A3D);color:#11141B;border-radius:999px;padding:2px 8px;vertical-align:middle}
34
+ html.cmx-pro .pro-badge{display:inline-block}
35
+ dialog.funpass{border:0;padding:0;border-radius:20px;max-width:min(520px,calc(100% - 24px));width:100%;background:var(--card-solid);color:var(--ink);box-shadow:0 20px 60px rgba(0,0,0,.35)}
36
+ dialog.funpass::backdrop{background:rgba(10,12,18,.55)}
37
+ .fp{padding:22px 20px 18px;position:relative}.fp h2{margin:2px 0 10px;font-size:24px}
38
+ .fp-x{position:absolute;right:10px;top:8px;border:0;background:none;color:var(--muted);font-size:28px;cursor:pointer;width:44px;height:44px}
39
+ .fp-kick{margin:0;color:var(--acc);font-weight:800;font-size:13px;letter-spacing:.06em;text-transform:uppercase}
40
+ .fp-perks{margin:0 0 14px;padding-left:20px}.fp-perks li{margin:2px 0}
41
+ .fp-plans{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}
42
+ .fp-plan{position:relative;display:flex;flex-direction:column;gap:2px;padding:14px 10px 12px;border:1.5px solid var(--line);border-radius:14px;text-decoration:none;text-align:center;background:var(--bg2)}
43
+ .fp-plan:hover{border-color:var(--acc)}.fp-plan.best{border-color:var(--acc);box-shadow:0 0 0 2px var(--acc) inset}
44
+ .fp-plan i{position:absolute;top:-10px;left:50%;transform:translateX(-50%);background:var(--acc);color:#11141B;font-style:normal;font-size:11px;font-weight:800;padding:2px 8px;border-radius:999px;white-space:nowrap}
45
+ .fp-plan b{font-size:14px}.fp-price{font-size:22px;font-weight:900}.fp-price small{font-size:12px;font-weight:600;color:var(--muted)}.fp-note{font-size:12px;color:var(--muted)}
46
+ .fp-small{font-size:13px;color:var(--muted);margin:10px 0 4px}
47
+ .fp-code{display:block;user-select:all;word-break:break-all;background:var(--chip);padding:8px;border-radius:8px;font-size:12px}
48
+ .fp details{margin-top:6px;font-size:14px}.fp-form{display:flex;gap:6px;margin-top:8px}.fp-form input{flex:1;min-width:0;font:inherit;font-size:14px;padding:8px 10px;border-radius:10px;border:1.5px solid var(--line);background:var(--bg);color:var(--ink)}
49
+ @media (max-width:420px){.fp-plans{grid-template-columns:1fr}.fp-plan{flex-direction:row;align-items:center;justify-content:space-between;text-align:left;padding:12px}.fp-plan i{left:auto;right:10px;transform:none}}
50
+ @media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
51
+ @media (max-width:560px){.chips{flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none;margin:0 -16px;padding:2px 16px 4px}.chips::-webkit-scrollbar{display:none}.chip{flex:0 0 auto}}
52
+ @media (min-width:760px){dialog.funpass{max-width:720px}.fp-perks{columns:2;column-gap:28px}}
53
+ .fp-after{margin:14px 0 0;padding:12px 14px;border:1px solid var(--line, rgba(127,127,127,.35));border-radius:14px;text-align:left}.fp-after p{margin:0 0 8px}.fp-after .fp-row{display:flex;gap:8px;flex-wrap:wrap}.fp-after .fp-pv{font-size:13px;opacity:.85}
54
+ .fp-game{border-color:var(--acc);display:grid;grid-template-columns:1fr auto;align-items:center;text-align:left;gap:2px 12px;padding:14px 14px 12px;margin:0 0 6px}.fp-game b{font-size:16px}.fp-game .fp-price{grid-row:span 2}.fp-game .fp-note{grid-column:1}
55
+ .fp-or{margin:12px 0 8px;font-size:14px}
56
+
57
+ .top{position:relative;z-index:2}.top .brand{letter-spacing:-.01em}
58
+ /* 3D games on wide screens: a bigger stage, centred header (2026 upgrade) */
59
+ @media (min-width:1100px){.wrap:has(.cmx3d-wrap){max-width:1080px}.wrap:has(.cmx3d-wrap) .seo,.wrap:has(.cmx3d-wrap) footer{max-width:760px;margin-left:auto;margin-right:auto}
60
+ .wrap:has(.cmx3d-wrap) section.game>.headline{text-align:center}.wrap:has(.cmx3d-wrap) section.game>.headline .tag{margin-left:auto;margin-right:auto;max-width:640px}
61
+ .wrap:has(.cmx3d-wrap) section.game>.chips{justify-content:center}.wrap:has(.cmx3d-wrap) section.game>.lv-goal,.wrap:has(.cmx3d-wrap) section.game>#goal{text-align:center;justify-content:center}
62
+ .wrap:has(.cmx3d-wrap) section.game>.panel{max-width:760px;margin-left:auto;margin-right:auto}}
63
+ /* living background: two slow glows in the game's colours drift behind the page (dark theme; off for reduced motion) */
64
+ body::before,body::after{content:"";position:fixed;z-index:-1;width:60vmax;height:60vmax;border-radius:50%;opacity:.16;pointer-events:none;animation:cmx-drift 26s ease-in-out infinite alternate}
65
+ body::before{left:-20vmax;top:-25vmax;background:radial-gradient(closest-side,var(--game),transparent)}body::after{right:-25vmax;bottom:-30vmax;background:radial-gradient(closest-side,var(--game2),transparent);animation-duration:34s;animation-direction:alternate-reverse}
66
+ :root[data-theme=light] body::before,:root[data-theme=light] body::after{display:none}
67
+ @keyframes cmx-drift{from{transform:translate(0,0) scale(1)}to{transform:translate(12vmax,8vmax) scale(1.15)}}
68
+ .panel{transition:border-color .2s,box-shadow .2s}.panel:hover{border-color:color-mix(in srgb,var(--game) 28%,var(--line))}
69
+ .fp-rbx{font-size:13px;color:var(--muted);margin:10px 0 0;text-align:center}.fp-rbx a{color:inherit;font-weight:700}
70
+ /* Shop (29 Oct 2026): one Shop button on the title/menu screen, one quiet one on results, one sheet with every item */
71
+ .cmx-shopbtn{background:linear-gradient(135deg,#FFD15C,#FF8A3D)!important;color:#11141B!important;font-weight:900;letter-spacing:.01em;gap:8px;border:0}
72
+ .cmx-shopbtn small{font-size:.78em;font-weight:700;opacity:.8;white-space:nowrap}.cmx-shopres small{font-size:.85em;opacity:.8}
73
+ html.cmx-noshop [data-cmx-shop]:not([data-cmx-keep]){display:none!important}
74
+ .cmxshop .sh-list{list-style:none;margin:10px 0 6px;padding:0;display:grid;gap:8px}
75
+ .cmxshop .sh-i{display:grid;grid-template-columns:56px 1fr auto;gap:12px;align-items:center;padding:10px;border:1.5px solid var(--line);border-radius:14px;background:var(--bg2)}
76
+ .cmxshop .sh-own{font-weight:800;color:var(--ok);font-size:14px;white-space:nowrap}
77
+ .cmxshop .sh-pv{position:relative;width:56px;height:56px;border-radius:12px;overflow:hidden;display:grid;place-items:center;font-size:26px}
78
+ .cmxshop .sh-pv i{font-style:normal}.cmxshop .sh-pv img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
79
+ .cmxshop .sh-t{min-width:0;display:flex;flex-direction:column;gap:2px}.cmxshop .sh-t b{font-size:16px}
80
+ .cmxshop .sh-w{font-size:13px;color:var(--muted);line-height:1.35}.cmxshop .sh-w em{font-style:normal;font-weight:700;color:var(--ink)}
81
+ .cmxshop .sh-alt{font-size:13px;color:var(--muted)}.cmxshop .sh-alt a{color:var(--ink);font-weight:700}
82
+ .cmxshop .sh-buy{min-width:84px;white-space:nowrap}.cmxshop .sh-buy small{font-size:11px;font-weight:600}
83
+ .cmxshop .sh-code{border:0;background:none;color:var(--ink);font:inherit;font-weight:700;text-decoration:underline;cursor:pointer;padding:0}
84
+ @media (max-width:460px){.cmxshop .sh-i{grid-template-columns:44px 1fr;gap:8px 10px}.cmxshop .sh-pv{width:44px;height:44px;font-size:20px}.cmxshop .sh-buy,.cmxshop .sh-own{grid-column:2;justify-self:start}}
85
+ dialog.cmxshop{max-height:calc(100dvh - 16px);overflow:auto}
86
+ .cmx-shop-top{min-height:38px;padding:5px 12px;font-size:14px;border-radius:999px;margin:0 4px;white-space:nowrap;flex:0 0 auto;gap:6px}
87
+ @media (max-width:430px){header.top:has(.cmx-shop-top:not([hidden])) nav{display:none}header.top:has(.cmx-shop-top:not([hidden])) .brand{font-size:0;gap:0}.cmx-shop-top{padding:5px 10px;font-size:13px;margin:0 2px}.cmx-shop-top small{font-size:11px}}
88
+ /* Calm play focus (7 Nov 2026 quality pass, "Calm screens in every game"): on a phone, once the player touches the board,
89
+ the shop, skin and pass buttons, the theme swatches, the stats/theme icons and the "Get more" row step aside until the
90
+ round ends (cmx.js adds html.cmx-focus; a results panel or a tap outside the game brings them back). Above the board
91
+ only visibility changes, so nothing moves under the player's finger. */
92
+ @media (max-width:560px){
93
+ html.cmx-focus header.top .cmx-shop-top,html.cmx-focus header.top #stats-btn,html.cmx-focus header.top #theme,html.cmx-focus header.top nav{visibility:hidden}
94
+ html.cmx-focus section.game .row.skins,html.cmx-focus section.game #skins-btn,html.cmx-focus section.game #pass-btn,html.cmx-focus section.game #install,
95
+ html.cmx-focus section.game .row [data-cmx-shop],html.cmx-focus section.game>.nudge,html.cmx-focus .cmx-gm{display:none!important}}
shelfpop/funpass.js ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CyberMax games checkout: the per-game "full game" unlock + the Fun Pass (every game), copied into each game's web/ folder.
2
+ // Model (games lane GM, 9 Oct 2026; evidence docs/ceo/games-monetization-2026-10-09.md):
3
+ // - Free demo: every game's daily challenge stays free for everyone, plus the first levels (OFFER.demo once the per-game
4
+ // unlock is live; levels 1-20 until then). A level the player has opened is never locked again.
5
+ // - Full game: ONE payment per game (OFFER.price, Stripe pack revenue/packs/stripe/<game>-full) unlocks every level,
6
+ // mode, the daily archive and themes in that game, for good. Shown only when OFFER.live is true (owner-approved).
7
+ // - Fun Pass = the all-games bundle: Monthly $2.99 · Yearly $19 · Lifetime $29.99 (pack revenue/packs/stripe/fun-pass).
8
+ // - Portal builds (scripts/games/portals.py) never show a checkout; where the portal SDK offers rewarded ads, the player
9
+ // may watch one to open the full game for an hour (shared/portal-adapter/cmx-portal.js CMXPortal.rewarded()).
10
+ // Buy: counted redirect https://data.cybermaxtools.com/buy/st-<pack>-<plan>?s=game-<id> -> Stripe checkout.
11
+ // After checkout the data Worker (/unlock/fun-pass or /unlock/<game>-full) checks the Checkout Session and returns with
12
+ // #cmx-pro=<code> (the full-game return adds ?unlock=full). The code on the receipt page unlocks any other device.
13
+ // No account, no cookies, nothing personal stored. (c) 2026 CyberMax. All rights reserved.
14
+ import { count, store, toast } from './cmx.js';
15
+ import { OFFER } from './offer.js'; // written by scripts/games/sync_kit.py from products/fun-pass/games.json
16
+ export { OFFER };
17
+
18
+ const DATA = 'https://data.cybermaxtools.com';
19
+ const KEY = 'cmx-pro:fun-pass';
20
+ const SID = /^(cmxk1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|cs_(live|test)_[A-Za-z0-9]{10,200}|[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})$/i; // Stripe order code or Gumroad licence key
21
+ const RECHECK = 3 * 864e5; // subscriptions are re-checked every 3 days; a cancelled pass turns off by itself
22
+ export const PLANS = [
23
+ { id: 'monthly', label: 'Monthly', price: '$2.99', per: '/month', note: 'Cancel any time' },
24
+ { id: 'yearly', label: 'Yearly', price: '$19', per: '/year', note: 'Save 47%', best: true },
25
+ { id: 'unlock', label: 'Lifetime', price: '$29.99', per: ' once', note: 'Pay once, keep forever' },
26
+ ];
27
+ export const COMMON_PERKS = ['Every paid level, chapter and mode in every CyberMax game', 'The full archive of past dailies', 'New games and new chapters included as they launch', 'Custom colour themes'];
28
+ const FULL_KEY = `cmx-full:${OFFER.game}`;
29
+ const REWARD_KEY = `cmx-reward:${OFFER.game}`;
30
+ const REWARD_MS = 60 * 60 * 1000; // one rewarded ad on a portal build opens the full game for an hour
31
+
32
+ let state = store(KEY);
33
+ let full = store(FULL_KEY);
34
+ const listeners = [];
35
+ let cfg = { game: 'games', name: 'CyberMax games', perks: [] };
36
+ // Per-game offer naming (17 Oct 2026 conversion fix): games whose one-time unlock is not a "full game" (no levels, every
37
+ // mode free) pass init({ title: 'Stoop Dice Crew Pass', exact: true, free: '...' }): the sheet then names the offer exactly
38
+ // as the Stripe product, lists only its own perks and states what stays free, instead of "every level / bonus mode".
39
+ const fullTitle = () => cfg.title || `Full ${OFFER.name}`;
40
+
41
+ const passOn = () => !!(state && state.code);
42
+ export const ownsGame = () => !!(full && full.code);
43
+ const rewardOn = () => { const r = store(REWARD_KEY); return !!(r && Date.now() - r.at < REWARD_MS); };
44
+ /** True when this player may use everything in this game: Fun Pass, this game's full unlock, or a portal reward hour. */
45
+ export const isPro = () => passOn() || ownsGame() || rewardOn();
46
+ /** Free levels in this game's demo: OFFER.demo once the per-game unlock is live, else the game's current number. */
47
+ export const freeLevels = (current = 20) => (OFFER.live && OFFER.demo ? Math.min(current, OFFER.demo) : current);
48
+ const portal = () => (typeof window !== 'undefined' && window.CMXPortal && window.CMXPortal.portal) || '';
49
+ export function onChange(fn) { listeners.push(fn); fn(isPro()); }
50
+ // The header pass button names the real price (convert lane, 15 Oct 2026): "Full game $2.99" where this game sells its
51
+ // own unlock, else the Fun Pass monthly price. Pass holders see the button's own label.
52
+ function priceButton() {
53
+ const btn = typeof document !== 'undefined' && document.getElementById('pass-btn');
54
+ if (!btn) return;
55
+ if (!btn.dataset.label) btn.dataset.label = btn.textContent;
56
+ btn.textContent = isPro() || portal() ? btn.dataset.label : sellsGame() ? `✨ ${cfg.title ? cfg.short || cfg.title : 'Full game'} ${OFFER.price}` : `✨ Fun Pass ${PLANS[0].price}/mo`;
57
+ }
58
+ function emit() {
59
+ document.documentElement.classList.toggle('cmx-pro', isPro());
60
+ priceButton();
61
+ paintShop();
62
+ listeners.forEach((fn) => { try { fn(isPro()); } catch { /* game hook */ } });
63
+ }
64
+
65
+ // Offline Pro keys (17 Oct 2026): "cmxk1.<payload>.<Ed25519 signature>" from data.cybermaxtools.com/unlock is verified here
66
+ // with WebCrypto and this public key, so an unlock needs no Worker call. Expired, foreign-signed or unverifiable keys fall
67
+ // back to the online check of the order code inside them, as before.
68
+ const CMX_PUB = 'u0FDxbu0d9B9Sz5-yLT6AuL5IagyTlFcbBgEDqZxWtk';
69
+ const b64d = (s) => { s = s.replace(/-/g, '+').replace(/_/g, '/'); while (s.length % 4) s += '='; return Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); };
70
+ async function cmxKeyOk(k, app, online) {
71
+ const [tag, body, sig] = k.split('.');
72
+ let p;
73
+ try { p = JSON.parse(new TextDecoder().decode(b64d(body))); } catch { return false; }
74
+ if (!p || p.a !== app) return false;
75
+ try {
76
+ const key = await crypto.subtle.importKey('raw', b64d(CMX_PUB), { name: 'Ed25519' }, false, ['verify']);
77
+ if (await crypto.subtle.verify({ name: 'Ed25519' }, key, b64d(sig), new TextEncoder().encode(tag + '.' + body)) && (!p.x || p.x * 1000 > Date.now())) return true;
78
+ } catch { /* no Ed25519 here: online check below */ }
79
+ return p.c ? online(p.c) : false;
80
+ }
81
+ async function check(code, what = 'fun-pass') {
82
+ if (/^cmxk1\./.test(code)) return cmxKeyOk(code, what, (c) => checkOnline(c, what));
83
+ return checkOnline(code, what);
84
+ }
85
+ async function checkOnline(code, what = 'fun-pass') {
86
+ try {
87
+ const r = await fetch(`${DATA}/unlock/${what}?json=1&session_id=${encodeURIComponent(code)}`);
88
+ const j = await r.json();
89
+ return j && typeof j.pro === 'boolean' ? j.pro : null;
90
+ } catch { return null; }
91
+ }
92
+
93
+ /** Turn on a full-game code for this game (receipt code of the <game>-full Payment Link). */
94
+ export async function unlockGame(code) {
95
+ const ok = await check(code, `${OFFER.game}-full`);
96
+ if (ok) {
97
+ full = store(FULL_KEY, { code, at: new Date().toISOString() });
98
+ count(cfg.game, 'pro', 'full-unlocked');
99
+ toast(cfg.title ? `${cfg.title} is on. Thank you for supporting CyberMax games!` : `${OFFER.name}: the full game is on. Thank you for supporting CyberMax games!`, 3500);
100
+ emit(); render();
101
+ } else if (ok === false) toast('That code is not a full-game order for this game.', 3500);
102
+ else toast('Could not reach the unlock check. Try again in a minute.', 3500);
103
+ return ok;
104
+ }
105
+
106
+ /** Turn on a pasted or returned code: a Fun Pass code, or (where this game sells its own unlock) a full-game code. */
107
+ export async function unlock(code) {
108
+ const ok = await check(code);
109
+ if (ok) {
110
+ state = store(KEY, { code, at: new Date().toISOString(), checked: Date.now() });
111
+ count(cfg.game, 'pro', 'unlocked');
112
+ toast('Fun Pass is on. Thank you for supporting CyberMax games!', 3500);
113
+ emit();
114
+ render();
115
+ return ok;
116
+ }
117
+ if (sellsGame() && (await check(code, `${OFFER.game}-full`))) return unlockGame(code);
118
+ if (ok === false) toast('That code is not an active Fun Pass.', 3500);
119
+ else toast('Could not reach the pass check. Try again in a minute.', 3500);
120
+ return ok;
121
+ }
122
+
123
+ async function recheck() {
124
+ if (!passOn() || Date.now() - (state.checked || 0) < RECHECK) return; // only a Fun Pass is re-checked (a full-game or Founder owner has no pass state)
125
+ const ok = await check(state.code);
126
+ if (ok === false) { state = null; try { localStorage.removeItem(KEY); } catch { /* */ } emit(); render(); toast('Your Fun Pass has ended. Everything free is still here.', 4000); }
127
+ else if (ok) state = store(KEY, { ...state, checked: Date.now() });
128
+ }
129
+
130
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
131
+ const buyUrl = (plan) => `${DATA}/buy/st-fun-pass-${plan}?s=game-${cfg.game}`;
132
+ const gameUrl = (from = '') => `${DATA}/buy/st-${OFFER.game}-full-unlock?s=game-${cfg.game}${from ? `-${from}` : ''}`;
133
+ const sellsGame = () => !!(OFFER.live && OFFER.price && OFFER.game !== 'games');
134
+
135
+ function dialog() {
136
+ let d = document.getElementById('funpass');
137
+ if (!d) {
138
+ d = document.createElement('dialog');
139
+ d.id = 'funpass';
140
+ d.className = 'funpass';
141
+ document.body.appendChild(d);
142
+ d.addEventListener('click', (e) => { if (e.target === d || e.target.closest('[data-close]')) d.close(); });
143
+ }
144
+ return d;
145
+ }
146
+
147
+ const planHtml = () => PLANS.map((p) => `<a class="fp-plan${p.best ? ' best' : ''}" href="${buyUrl(p.id)}" rel="nofollow" data-plan="${p.id}">${p.best ? '<i>Best value</i>' : ''}<b>${p.label}</b><span class="fp-price">${p.price}<small>${p.per}</small></span><span class="fp-note">${p.note}</span></a>`).join('');
148
+ const codeForm = `<details><summary>Already bought?</summary><form class="fp-form"><input aria-label="Order code" autocomplete="off" placeholder="Receipt code (cs_live_…) or Gumroad licence key"><button class="btn sm" type="submit">Turn on</button></form></details>`;
149
+
150
+ function render() {
151
+ const d = dialog();
152
+ const perks = [...(cfg.perks || []), ...COMMON_PERKS.filter((p) => !(cfg.perks || []).some((q) => q.split(' ')[0] === p.split(' ')[0]))].slice(0, 6);
153
+ if (isPro()) {
154
+ const what = passOn() ? 'The Fun Pass is on in this browser for every CyberMax game' : ownsGame() ? (cfg.title ? `You own the ${esc(cfg.title)}` : `You own the full ${esc(OFFER.name)}`) : 'The full game is open for the next hour (rewarded ad)';
155
+ const code = passOn() ? state.code : ownsGame() ? full.code : '';
156
+ d.innerHTML = `<div class="fp"><button class="fp-x" data-close aria-label="Close">×</button><p class="fp-kick">${passOn() ? 'CyberMax Fun Pass' : esc(OFFER.name)}</p><h2>Everything is open. Thank you!</h2>
157
+ <p>${what}: ${perks.map(esc).join(' · ')}.</p>
158
+ ${code ? `<p class="fp-small">Your code (paste it on another device to turn it on there):</p><code class="fp-code">${esc(code)}</code>` : ''}
159
+ ${passOn() ? '<p class="fp-small">Manage or cancel a subscription any time from the link in your Stripe receipt email.</p>' : ''}</div>`;
160
+ return;
161
+ }
162
+ if (portal()) { // portal build: no outside checkout; a rewarded ad (when the portal offers one) opens the game for an hour
163
+ d.innerHTML = `<div class="fp"><button class="fp-x" data-close aria-label="Close">×</button><p class="fp-kick">${esc(OFFER.name || 'Full game')}</p>
164
+ <h2>Open the full game for an hour</h2><ul class="fp-perks">${perks.slice(0, 4).map((p) => `<li>${esc(p)}</li>`).join('')}</ul>
165
+ <p><button class="btn" type="button" data-reward>▶ Watch a short ad</button></p>
166
+ <p class="fp-small">Optional. The daily challenge and the free levels stay free without ads.</p></div>`;
167
+ d.querySelector('[data-reward]').addEventListener('click', async () => {
168
+ count(cfg.game, 'cta', 'reward-ad');
169
+ const ok = await window.CMXPortal.rewarded().catch(() => false);
170
+ if (ok) { store(REWARD_KEY, { at: Date.now() }); count(cfg.game, 'pro', 'reward-hour'); toast('Everything is open for the next hour. Have fun!', 3000); emit(); d.close(); }
171
+ else toast('No ad is available right now. Try again later.', 3000);
172
+ });
173
+ return;
174
+ }
175
+ const allGames = `${OFFER.games || 'every'} CyberMax games`;
176
+ const own = cfg.perks || [];
177
+ const gamePerks = cfg.exact ? own.slice(0, 6) : [...own, ...(own.some((p) => /archive/i.test(p)) ? [] : ['The full archive of past dailies']), 'Every bonus mode in this game'].slice(0, 6);
178
+ const freeLine = cfg.free || `The daily challenge and ${OFFER.levels === false ? 'the free modes stay' : `the first ${OFFER.demo || ''} levels stay`} free for everyone.`;
179
+ d.innerHTML = sellsGame()
180
+ ? `<div class="fp"><button class="fp-x" data-close aria-label="Close">×</button><p class="fp-kick">${esc(OFFER.name)} · ${cfg.title ? 'one payment' : 'full game'}</p>
181
+ <h2>${cfg.title ? `Get the ${esc(cfg.title)}` : `Unlock the full ${esc(OFFER.name)}`}</h2>
182
+ <ul class="fp-perks">${gamePerks.map((p) => `<li>${esc(p)}</li>`).join('')}</ul>
183
+ <a class="fp-plan fp-game" href="${gameUrl()}" rel="nofollow" data-game><i>This game only</i><b>${esc(fullTitle())}</b><span class="fp-price">${esc(OFFER.price)}<small> once</small></span><span class="fp-note">Pay once, keep it forever. No subscription.</span></a>
184
+ <p class="fp-or"><b>Or get all ${esc(allGames)}</b> with the Fun Pass (a separate pass for every game):</p>
185
+ <div class="fp-plans">${planHtml()}</div>
186
+ <p class="fp-small">Secure checkout by Stripe (shown as Link) · turns on as soon as you pay · your code works on any device · 14-day fix-or-refund if it doesn't work as described (<a href="https://cybermaxtools.com/terms#payments" target="_blank" rel="noopener">terms</a>). ${esc(freeLine)} Prices in USD; tax for your country is added at checkout.</p>
187
+ ${codeForm}</div>`
188
+ : `<div class="fp"><button class="fp-x" data-close aria-label="Close">×</button><p class="fp-kick">CyberMax Fun Pass</p>
189
+ <h2>One pass. Every game. More to play.</h2>
190
+ <ul class="fp-perks">${perks.map((p) => `<li>${esc(p)}</li>`).join('')}</ul>
191
+ <div class="fp-plans">${planHtml()}</div>
192
+ <p class="fp-small">Secure checkout by Stripe (shown as Link; card, Apple Pay, Google Pay) · turns on as soon as you pay · cancel any time from your receipt email · 14-day fix-or-refund if it doesn't work as described (<a href="https://cybermaxtools.com/terms#payments" target="_blank" rel="noopener">terms</a>). Prices in USD, + tax where applicable. Works in every CyberMax game. The daily challenges and the free levels stay free for everyone.</p>
193
+ ${codeForm}</div>`;
194
+ d.querySelector('.fp-form').addEventListener('submit', (e) => {
195
+ e.preventDefault();
196
+ const c = e.target.querySelector('input').value.trim();
197
+ if (SID.test(c)) unlock(c); else toast('Paste the code from your receipt page (cs_live_…) or your Gumroad licence key.', 3500);
198
+ });
199
+ d.querySelectorAll('[data-plan]').forEach((a) => a.addEventListener('click', () => count(cfg.game, 'cta', `pass-${a.dataset.plan}`)));
200
+ d.querySelector('[data-game]')?.addEventListener('click', () => count(cfg.game, 'cta', 'full-game'));
201
+ }
202
+
203
+ /** Open the pass sheet; `from` names the button that opened it (counted as cta). */
204
+ export function open(from = 'button') {
205
+ render();
206
+ const d = dialog();
207
+ if (d.showModal) d.showModal(); else d.setAttribute('open', '');
208
+ count(cfg.game, 'cta', `pass-open-${from}`);
209
+ }
210
+
211
+ /** After a finished round (the value moment): one small inline card under the result, never a pop-up. Shows the
212
+ * pass price, the honest trust line and an optional "email me" weekly reminder (double opt-in).
213
+ * `host` is the result panel; the card is added once and removed for pass holders. */
214
+ // One quiet line under the result: CyberMax's free Roblox games (24 Oct 2026). Not on game portals (their rules ban
215
+ // outside links), never a pop-up; links carry the game id so clicks can be told apart.
216
+ const ROBLOX = [['Skyline Flight Circuit', 'https://www.roblox.com/games/89786604994377'], ['Hatchlume', 'https://www.roblox.com/games/80122923062327'],
217
+ ['Sled Volt', 'https://www.roblox.com/games/134881648422275']];
218
+ function robloxRow(host) {
219
+ if (portal() || host.querySelector('.fp-rbx')) return;
220
+ const p = document.createElement('p'); p.className = 'fp-rbx';
221
+ const tag = `?utm_source=cybermax&utm_medium=game&utm_campaign=${encodeURIComponent(cfg.game || 'games')}-end`;
222
+ p.innerHTML = 'Play our Roblox games: ' + ROBLOX.map(([n, u]) => `<a href="${u}${tag}" target="_blank" rel="noopener">${esc(n)}</a>`).join(' · ');
223
+ p.querySelectorAll('a').forEach((a) => a.addEventListener('click', () => count(cfg.game, 'cta', 'roblox-end')));
224
+ host.appendChild(p);
225
+ }
226
+
227
+ // The paywall moment (owner, 31 Oct 2026: "charge for more levels"; docs/ceo/game-content-monetization-2026-10-31.md):
228
+ // the unlock card is shown at a NATURAL point only: the first result after the free chapter is cleared (init({ ready }) ->
229
+ // true), else from the 3rd finished round in this browser, and then at most once a day. Never on the first round, never
230
+ // during play (results screens only), never stacked: the game's own result stays the headline. init({ preview: [...] })
231
+ // lists what the paid content holds (chapter names), shown as one quiet line in the card.
232
+ const ROUNDS_KEY = () => `cmx-rounds:${cfg.game || OFFER.game}`;
233
+ export function paywallDue() {
234
+ const r = store(ROUNDS_KEY()) || { n: 0, day: '', end: 0 };
235
+ r.n = (r.n || 0) + 1;
236
+ const day = new Date().toISOString().slice(0, 10);
237
+ let due = false, why = '';
238
+ let ready = false;
239
+ try { ready = !!(cfg.ready && cfg.ready()); } catch { /* game hook */ }
240
+ if (ready && !r.end) { due = true; why = 'chapter-end'; r.end = 1; } // the end of the free chapter: always the first time
241
+ else if (r.n >= 3 && r.day !== day) { due = true; why = ready ? 'chapter-end-again' : 'rounds'; }
242
+ if (due) r.day = day;
243
+ store(ROUNDS_KEY(), r);
244
+ return due ? why : '';
245
+ }
246
+
247
+ export function afterWin(host, from = 'win') {
248
+ if (!host) return;
249
+ robloxRow(host);
250
+ if (isPro() || portal()) { host.querySelector('.fp-after')?.remove(); return; }
251
+ const why = paywallDue();
252
+ const nudges = host.querySelectorAll('.nudge'); // a result never carries two upsells: the content card wins over a looks nudge
253
+ nudges.forEach((n) => { n.hidden = !!why; });
254
+ if (!why) { host.querySelector('.fp-after')?.remove(); return; }
255
+ from = `${from}-${why}`;
256
+ let el = host.querySelector('.fp-after');
257
+ if (!el) { el = document.createElement('div'); el.className = 'fp-after'; host.appendChild(el); }
258
+ const best = PLANS.find((p) => p.best) || PLANS[0];
259
+ const game = sellsGame();
260
+ const href = game ? gameUrl('after') : `${buyUrl(best.id)}-after`;
261
+ const label = game ? (cfg.title ? `Get the ${cfg.title}: ${OFFER.price} once` : `Get the full ${OFFER.name}: ${OFFER.price} once`) : `Get the Fun Pass: ${best.price}${best.per}`;
262
+ const line = game ? (cfg.extra || `The full game opens every level, mode, the daily archive and themes in ${OFFER.name}.`)
263
+ : (cfg.extra || 'The Fun Pass opens every level, mode, the full archive and themes in every CyberMax game.');
264
+ const pv = Array.isArray(cfg.preview) && cfg.preview.length && game ? `<p class="fp-pv">Inside: ${cfg.preview.slice(0, 4).map(esc).join(' · ')}</p>` : '';
265
+ el.innerHTML = `<p><b>${game && from.includes('chapter-end') ? 'You cleared the free levels.' : 'Want more today?'}</b> ${esc(line)}</p>${pv}
266
+ <p class="fp-row"><a class="btn sm" href="${href}" rel="nofollow" data-after>${esc(label)}</a> <button class="btn sm ghost" type="button" data-plans>${game ? 'All games pass' : 'See all plans'}</button></p>
267
+ <p class="fp-small">Secure checkout by Stripe (shown as Link) · turns on as soon as you pay · ${game ? 'one payment, no subscription' : 'cancel any time from your receipt email'} · 14-day fix-or-refund if it doesn't work as described (<a href="https://cybermaxtools.com/terms#payments" target="_blank" rel="noopener">terms</a>). Prices in USD, + tax where applicable. Today's daily challenge stays free.</p>
268
+ <div class="fp-cap"></div>`;
269
+ el.querySelector('[data-after]').addEventListener('click', () => { count(cfg.game, 'cta', game ? 'full-game-after' : `pass-${best.id}-after`); kit((K) => K.event('upgrade-click', cfg.game)); });
270
+ el.querySelector('[data-plans]').addEventListener('click', () => open(`after-${from}`));
271
+ kit((K) => {
272
+ K.event('result', cfg.game); K.event('upgrade-view', cfg.game);
273
+ K.capture(el.querySelector('.fp-cap'), { list: `weekly-${cfg.game}`, src: `game-${cfg.game}`, label: cfg.remind || 'Email me a weekly reminder with new puzzles (free)', button: 'Remind me' });
274
+ });
275
+ }
276
+
277
+ // Convert kit (funnel beacons + email capture) from the CyberMax site; optional, the game works without it.
278
+ let kitQ = null;
279
+ function kit(fn) {
280
+ if (window.CMXConvert) return fn(window.CMXConvert);
281
+ if (kitQ) return kitQ.push(fn);
282
+ kitQ = [fn];
283
+ const sc = document.createElement('script');
284
+ sc.src = 'https://cybermaxtools.com/store/convert.js'; sc.async = true;
285
+ sc.onload = () => kitQ.splice(0).forEach((f) => { try { f(window.CMXConvert); } catch { /* optional */ } });
286
+ document.head.appendChild(sc);
287
+ }
288
+
289
+ // ------------------------------------------------------------------ the Shop (owner, 29 Oct 2026: "there's nothing to buy")
290
+ // One clear Shop button on the title/menu screen and one quiet button on the results screen open ONE sheet that lists
291
+ // everything this game sells, cheapest first (OFFER.shop, written by scripts/games/sync_kit.py from products/fun-pass/shop.json;
292
+ // prices come from the Stripe packs): coin packs, Skin/Look/Founder Packs, the full game, the Fun Pass and the Arcade
293
+ // Lifetime. Buttons are plain markup with data-cmx-shop="<where>" (menu, title, results); this file labels them, opens
294
+ // the sheet and hides them on portal and Telegram builds (no outside checkout there). Never shown during play: the
295
+ // buttons live on menu/results screens or above the game, so the play HUD is unchanged. Buy links carry
296
+ // s=game-<id>-shop-<where>; cmx.js adds the first-touch tag on click. Nothing pops up by itself.
297
+ const SHOP = Array.isArray(OFFER.shop) ? OFFER.shop : [];
298
+ const TG = typeof location !== 'undefined' && (/[?&]tg(=|&|$)/.test(location.search) || /tgWebAppData=/.test(location.hash));
299
+ /** True where no web checkout may show: portal builds and the Telegram Mini App (Stars only). */
300
+ export const noShop = () => !!portal() || TG || !SHOP.length;
301
+ const slug = (s) => String(s || 'shop').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 24) || 'shop';
302
+ const shopHref = (offer, from) => `${DATA}/buy/${offer}?s=game-${OFFER.game}-shop-${slug(from)}`;
303
+ const ownedKind = (it) => {
304
+ if (it.kind === 'pass') return passOn();
305
+ if (it.kind === 'full') return ownsGame();
306
+ if (it.kind === 'skins') return !!store(`cmx-skins:${OFFER.game}`) || !!store(`cmx-founder:${OFFER.game}`);
307
+ if (it.kind === 'founder') return !!store(`cmx-founder:${OFFER.game}`);
308
+ if (it.kind === 'collector') return !!store(`cmx-collector:${OFFER.game}`); // looks Collector Packs (skins.js v2)
309
+ return false; // coin packs, looks packs and the Arcade Lifetime can always be bought
310
+ };
311
+ /** The Shop items with an owned flag: the game's content unlock (more levels, chapters, modes) on top, then cheapest first. */
312
+ const CONTENT = (it) => (it.kind === 'full' || it.kind === 'campaign' ? 0 : 1);
313
+ export const shopItems = () => SHOP.slice().sort((a, b) => CONTENT(a) - CONTENT(b) || a.cents - b.cents).map((it) => ({ ...it, owned: ownedKind(it) }));
314
+ /** Label for a Shop button: the menu/title one names the lowest price, the results one the most relevant offer. */
315
+ export function shopLabel(where = 'menu') {
316
+ if (where === 'results') return esc(OFFER.shopResults || '🛍️ See the shop →');
317
+ return `🛍️ Shop${OFFER.shopFrom ? ` <small>from ${esc(OFFER.shopFrom)}</small>` : ''}`;
318
+ }
319
+ /** Markup for a Shop button in screens a game draws itself ('' where no checkout may show). */
320
+ export function shopButtonHtml(where = 'menu', cls = '') {
321
+ if (noShop()) return '';
322
+ const c = where === 'results' ? 'btn ghost sm cmx-shopres' : 'btn cmx-shopbtn';
323
+ return `<button class="${c}${cls ? ` ${cls}` : ''}" type="button" data-cmx-shop="${esc(where)}">${shopLabel(where)}</button>`;
324
+ }
325
+ function paintShop() {
326
+ if (typeof document === 'undefined') return;
327
+ const off = noShop();
328
+ document.documentElement.classList.toggle('cmx-noshop', off);
329
+ for (const b of document.querySelectorAll('[data-cmx-shop]')) {
330
+ if (off) { if (!b.hasAttribute('data-cmx-keep')) b.hidden = true; continue; } // data-cmx-keep: the game's own button, its own handler
331
+ const where = b.dataset.cmxShop || 'menu';
332
+ const html = shopLabel(where === 'results' ? 'results' : 'menu');
333
+ if (b.dataset.cmxLabel !== html) { b.innerHTML = html; b.dataset.cmxLabel = html; }
334
+ if (b.hasAttribute('data-cmx-hidden')) continue; // the game shows/hides this one itself
335
+ b.hidden = false;
336
+ }
337
+ }
338
+ const swatch = (it) => `background:${it.sw && it.sw.length > 1 ? `linear-gradient(135deg,${it.sw.map(esc).join(',')})` : esc((it.sw || ['#FF6A3D'])[0])}`;
339
+ function shopDialog() {
340
+ let d = document.getElementById('cmxshop');
341
+ if (!d) {
342
+ d = document.createElement('dialog');
343
+ d.id = 'cmxshop';
344
+ d.className = 'funpass cmxshop';
345
+ d.setAttribute('aria-label', `${OFFER.name} shop`);
346
+ document.body.appendChild(d);
347
+ d.addEventListener('click', (e) => { if (e.target === d || e.target.closest('[data-close]')) d.close(); });
348
+ }
349
+ return d;
350
+ }
351
+ function renderShop(from) {
352
+ const d = shopDialog();
353
+ const rows = shopItems().map((it) => {
354
+ const img = it.img ? `<img src="${esc(it.img)}" alt="" loading="lazy" onerror="this.remove()">` : '';
355
+ const buy = it.owned ? '<span class="sh-own">Owned ✓</span>'
356
+ : `<a class="btn sm pass sh-buy" href="${shopHref(it.offer, from)}" rel="nofollow" data-offer="${esc(it.offer)}">${esc(it.price)}<small>${esc(it.per)}</small></a>`;
357
+ const alt = !it.owned && it.alt ? `<span class="sh-alt">or ${it.alt.map((a) => `<a href="${shopHref(a.offer, from)}" rel="nofollow" data-offer="${esc(a.offer)}">${esc(a.label)}</a>`).join(' · ')}</span>` : '';
358
+ return `<li class="sh-i sh-${esc(it.kind)}"><span class="sh-pv" style="${swatch(it)}" aria-hidden="true"><i>${esc(it.icon || '🛍️')}</i>${img}</span>`
359
+ + `<span class="sh-t"><b>${esc(it.name)}</b><span class="sh-w"><em>What you get:</em> ${esc(it.what)}</span>${alt}</span>${buy}</li>`;
360
+ }).join('');
361
+ const store = OFFER.shopStore ? ` · <a href="${esc(OFFER.shopStore)}" target="_blank" rel="noopener">details in the store</a>` : '';
362
+ d.innerHTML = `<div class="fp"><button class="fp-x" data-close aria-label="Close">×</button><p class="fp-kick">${esc(OFFER.name)} shop</p>
363
+ <h2>Looks, packs and more</h2><ul class="sh-list">${rows}</ul>
364
+ <p class="fp-small">One-time prices unless marked /month or /year. Secure checkout by Stripe (shown as Link) · turns on as soon as you pay · your receipt code works on any device · 14-day fix-or-refund if it doesn't work as described (<a href="https://cybermaxtools.com/terms#payments" target="_blank" rel="noopener">terms</a>). Prices in USD, + tax where applicable. Looks never change scores or the daily board; the daily challenge stays free for everyone${store}.</p>
365
+ <p class="fp-small"><button class="sh-code" type="button" data-code>Already bought? Turn on your code</button></p></div>`;
366
+ d.querySelectorAll('a[data-offer]').forEach((a) => a.addEventListener('click', () => count(cfg.game, 'cta', `shop-buy-${a.dataset.offer.replace(/^st-/, '')}`.slice(0, 40))));
367
+ d.querySelector('[data-code]').addEventListener('click', () => { d.close(); open('shop-code'); });
368
+ }
369
+ /** Open the Shop sheet; `from` names the button that opened it (counted, and in the buy tag). */
370
+ export function openShop(from = 'button') {
371
+ if (noShop()) { if (portal()) open(from); return; } // a portal build keeps its rewarded-ad sheet
372
+ renderShop(from);
373
+ const d = shopDialog();
374
+ if (d.showModal) { if (!d.open) d.showModal(); } else d.setAttribute('open', '');
375
+ count(cfg.game, 'cta', `shop-open-${slug(from)}`);
376
+ }
377
+ if (typeof document !== 'undefined' && !window.__cmxShop) {
378
+ window.__cmxShop = 1;
379
+ // capture phase on the document: runs before the game's own handlers on that button, and stops them
380
+ document.addEventListener('click', (e) => {
381
+ const b = e.target && e.target.closest && e.target.closest('[data-cmx-shop]');
382
+ if (!b || noShop()) return; // portal / Telegram: the game's own handler (if any) runs as before
383
+ e.preventDefault(); e.stopPropagation();
384
+ openShop(b.dataset.cmxShop || 'menu');
385
+ }, true);
386
+ for (const ev of ['pointerdown', 'mousedown', 'touchstart']) { // tap-to-retry overlays never see a Shop tap
387
+ document.addEventListener(ev, (e) => { if (!noShop() && e.target && e.target.closest && e.target.closest('[data-cmx-shop]')) e.stopPropagation(); }, true);
388
+ }
389
+ paintShop();
390
+ }
391
+
392
+ /** Call once per page: game id, display name and the game's own perks (listed first). Reads #cmx-pro=<code> after
393
+ * checkout (?unlock=full marks this game's full-game return). Skin-pack codes are taken first by skins.js capture(). */
394
+ export function init(options) {
395
+ cfg = { ...cfg, ...options };
396
+ const m = /[#&]cmx-key=([^&]+)/.exec(location.hash || '') || /[#&]cmx-pro=([^&]+)/.exec(location.hash || '');
397
+ if (m && SID.test(decodeURIComponent(m[1]))) {
398
+ const q = new URLSearchParams(location.search);
399
+ const fullReturn = q.get('unlock') === 'full';
400
+ q.delete('unlock');
401
+ history.replaceState(null, '', location.pathname + (q.toString() ? `?${q}` : ''));
402
+ if (fullReturn) unlockGame(decodeURIComponent(m[1])); else unlock(decodeURIComponent(m[1]));
403
+ } else recheck();
404
+ emit();
405
+ }
406
+
407
+ // Direct checkout (17 Oct 2026, Workers cap fix): a click on a data.cybermaxtools.com/buy/<offer> link goes straight to the
408
+ // Stripe/Polar checkout (static map https://cybermaxtools.com/store/buy-direct.json); the click is counted by a beacon.
409
+ (() => {
410
+ if (typeof document === 'undefined' || window.__cmxBd) return;
411
+ window.__cmxBd = 1;
412
+ let MAP = null;
413
+ try { MAP = JSON.parse(sessionStorage.getItem('cmx-bd') || 'null'); } catch { /* none */ }
414
+ if (!MAP) fetch('https://cybermaxtools.com/store/buy-direct.json').then((r) => r.json()).then((j) => { MAP = j; try { sessionStorage.setItem('cmx-bd', JSON.stringify(j)); } catch { /* full */ } }).catch(() => {});
415
+ document.addEventListener('click', (e) => {
416
+ const a = e.target && e.target.closest && e.target.closest('a[href*="data.cybermaxtools.com/buy/"]');
417
+ if (!a || !MAP || !MAP.offers) return;
418
+ try {
419
+ const u = new URL(a.href);
420
+ const k = /^\/buy\/([a-z0-9-]+)\/?$/.exec(u.pathname);
421
+ const t = k && MAP.offers[k[1]];
422
+ if (!t) return;
423
+ const s = String(u.searchParams.get('s') || 'unknown').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 80) || 'unknown';
424
+ a.href = t.split(MAP.ph).join(s);
425
+ if (!navigator.webdriver) navigator.sendBeacon(u.href + (u.search ? '&' : '?') + 'b=1');
426
+ } catch { /* keep the counted link */ }
427
+ }, true);
428
+ })();
shelfpop/game.js ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Shelf Pop: game screen (crisp canvas, drag or tap to move goods, pops, slide-forward rows, hint hand, sound, daily +
2
+ // levels + archive, share line + card, Fun Pass). Rules: core.js. (c) 2026 CyberMax. All rights reserved.
3
+ import { GOODS, makeGame, moves as allMoves, fmt, shareText as coreShare, specOf } from './core.js';
4
+ import { dayNumber, dateOf, count, store, share, intents, download, canvasBlob, pwa, themeToggle, rr } from './cmx.js';
5
+ import * as pass from './funpass.js';
6
+
7
+ const GAME = 'shelfpop', PATH = '/games/shelfpop/';
8
+ const $ = (id) => document.getElementById(id);
9
+ const cv = $('c'), ctx = cv.getContext('2d'), TAU = Math.PI * 2;
10
+ const W = 360, H = 540, TOP = 70;
11
+ const LOOKS = {
12
+ market: { name: 'Market', tier: 'free', top: '#FFF1D6', bot: '#FFE0EC', wall: 'rgba(255,255,255,.55)', wood: '#E9A86B', wood2: '#C9824A', ink: '#3A2A1E', acc: '#FF6A8A' },
13
+ mint: { name: 'Mint', tier: 'pass', top: '#DDFBEF', bot: '#E9F6FF', wall: 'rgba(255,255,255,.55)', wood: '#9ED9C0', wood2: '#5FB596', ink: '#173A33', acc: '#FF7A59' },
14
+ peach: { name: 'Peach', tier: 'pass', top: '#FFE6DA', bot: '#FFF8D9', wall: 'rgba(255,255,255,.55)', wood: '#F2B48C', wood2: '#D88A5E', ink: '#3E2418', acc: '#E2477A' },
15
+ };
16
+ const todayIso = new Date().toISOString().slice(0, 10), todayNum = dayNumber(todayIso);
17
+ pass.init({ game: GAME, name: 'Shelf Pop', perks: ['Every past Daily Shelf in the archive', 'Mint and Peach shop themes'],
18
+ free: 'The Daily Shelf and every level stay free for everyone.', extra: 'The Fun Pass adds every past Daily Shelf and 2 shop themes.', preview: ['past daily shelves', '2 themes'] });
19
+ const canUse = (s) => s.tier === 'free' || pass.isPro();
20
+ let look = LOOKS[store('shelfpop:look')] && canUse(LOOKS[store('shelfpop:look')]) ? store('shelfpop:look') : 'market';
21
+ let muted = !!store('shelfpop:mute');
22
+ let level = Math.max(1, store('shelfpop:level') || 1);
23
+ let mode = store('shelfpop:played') ? { kind: 'daily', date: todayIso } : { kind: 'level', n: level }; // a first visit starts on the tiny level 1
24
+ let game, last = performance.now(), endShown = false, idle = 0, fx = [], texts = [], anims = new Map(), drag = null, sel = null, shake = 0, autoBot = false, botT = 0;
25
+ const install = pwa(GAME, $('install'));
26
+ themeToggle($('theme'));
27
+
28
+ // ------------------------------------------------------------------ sound + haptics
29
+ let ac;
30
+ function tone(f, d = 0.08, type = 'sine', vol = 0.07, to = 1, delay = 0) {
31
+ if (muted) return;
32
+ try {
33
+ ac = ac || new (window.AudioContext || window.webkitAudioContext)();
34
+ const s = ac.currentTime + delay, o = ac.createOscillator(), v = ac.createGain();
35
+ o.type = type; o.frequency.setValueAtTime(f, s); o.frequency.exponentialRampToValueAtTime(Math.max(40, f * to), s + d);
36
+ v.gain.setValueAtTime(0.0001, s); v.gain.exponentialRampToValueAtTime(vol, s + 0.008); v.gain.exponentialRampToValueAtTime(0.0001, s + d);
37
+ o.connect(v); v.connect(ac.destination); o.start(s); o.stop(s + d + 0.03);
38
+ } catch { /* no audio */ }
39
+ }
40
+ const NOTES = [523, 587, 659, 784, 880, 1047];
41
+ const buzz = (ms) => { try { if (navigator.vibrate) navigator.vibrate(ms); } catch { /* */ } };
42
+ const setMute = () => { $('mute').textContent = muted ? '🔇' : '🔊'; };
43
+ setMute(); $('mute').onclick = () => { muted = !muted; store('shelfpop:mute', muted); setMute(); };
44
+
45
+ // ------------------------------------------------------------------ crisp canvas
46
+ let scale = 1;
47
+ function fit() {
48
+ const r = cv.getBoundingClientRect(), dpr = Math.min(3, window.devicePixelRatio || 1);
49
+ const w = Math.max(1, Math.round(r.width * dpr)), h = Math.max(1, Math.round(r.height * dpr));
50
+ if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
51
+ scale = cv.width / W;
52
+ }
53
+ new ResizeObserver(fit).observe(cv); fit();
54
+
55
+ // ------------------------------------------------------------------ layout: 2 columns of shelves, each with 3 front slots
56
+ function layout(n, depth) {
57
+ const rows = Math.ceil(n / 2), ch = Math.min(96 + 30 * Math.min(2, depth - 1), (H - TOP - 10) / rows), cw = 168, gap = (H - TOP - 10 - ch * rows) / 2;
58
+ return Array.from({ length: n }, (_, i) => {
59
+ const col = i % 2, row = Math.floor(i / 2), lone = n % 2 === 1 && i === n - 1;
60
+ const x = lone ? (W - cw) / 2 : 8 + col * (cw + 8), y = TOP + gap + row * ch;
61
+ return { x, y, w: cw, h: ch, base: y + ch - 22, slot: (k) => x + 30 + k * 54 };
62
+ });
63
+ }
64
+ let L = [];
65
+
66
+ // ------------------------------------------------------------------ goods (code-drawn, bright, readable at a glance)
67
+ function good(g, k, x, y, s = 1, a = 1) {
68
+ const G = GOODS[k]; g.save(); g.translate(x, y); g.scale(s, s); g.globalAlpha *= a;
69
+ const ink = 'rgba(40,25,20,.35)'; g.lineWidth = 2; g.strokeStyle = ink;
70
+ const circ = (cx, cy, r, c) => { g.fillStyle = c; g.beginPath(); g.arc(cx, cy, r, 0, TAU); g.fill(); g.stroke(); };
71
+ const shine = (cx, cy, r) => { g.fillStyle = 'rgba(255,255,255,.7)'; g.beginPath(); g.ellipse(cx, cy, r, r * 0.55, -0.6, 0, TAU); g.fill(); };
72
+ switch (G.id) {
73
+ case 'apple': circ(0, 2, 17, G.c); g.fillStyle = '#7A4A22'; g.fillRect(-1.5, -20, 3, 8); g.fillStyle = '#4CCB7A'; g.beginPath(); g.ellipse(7, -16, 7, 3.5, -0.5, 0, TAU); g.fill(); shine(-7, -5, 5); break;
74
+ case 'lemon': g.fillStyle = G.c; g.beginPath(); g.ellipse(0, 0, 20, 14, 0, 0, TAU); g.fill(); g.stroke(); g.beginPath(); g.arc(20, 0, 3, 0, TAU); g.arc(-20, 0, 3, 0, TAU); g.fill(); shine(-6, -5, 5); break;
75
+ case 'grape': for (const [dx, dy] of [[-8, -8], [8, -8], [0, -8], [-4, 0], [4, 0], [-8, 0], [8, 0], [0, 8], [-4, 8], [4, 8], [0, 15]]) circ(dx, dy, 6, G.c); g.fillStyle = '#4CCB7A'; g.beginPath(); g.ellipse(4, -17, 7, 3.5, 0.3, 0, TAU); g.fill(); break;
76
+ case 'carrot': g.fillStyle = G.c; g.beginPath(); g.moveTo(-9, -10); g.lineTo(9, -10); g.lineTo(0, 20); g.closePath(); g.fill(); g.stroke(); g.fillStyle = '#4CCB7A'; for (const a of [-0.5, 0, 0.5]) { g.save(); g.translate(0, -11); g.rotate(a); g.beginPath(); g.ellipse(0, -7, 3, 8, 0, 0, TAU); g.fill(); g.restore(); } break;
77
+ case 'donut': g.fillStyle = '#E8B070'; g.beginPath(); g.arc(0, 0, 19, 0, TAU); g.fill(); g.stroke(); g.fillStyle = G.c; g.beginPath(); g.arc(0, -1, 16, 0, TAU); g.fill(); g.fillStyle = '#FFF5E8'; g.beginPath(); g.arc(0, 0, 6, 0, TAU); g.fill(); g.stroke(); for (const [dx, dy, c] of [[-9, -6, '#4D6BFF'], [8, -8, '#FFD23F'], [10, 4, '#4CCB7A'], [-8, 7, '#FFFFFF']]) { g.fillStyle = c; g.fillRect(dx - 2, dy - 1, 4, 2); } break;
78
+ case 'milk': g.fillStyle = '#FFFFFF'; g.beginPath(); g.moveTo(-12, -8); g.lineTo(0, -20); g.lineTo(12, -8); g.lineTo(12, 18); g.lineTo(-12, 18); g.closePath(); g.fill(); g.stroke(); g.fillStyle = G.c; g.fillRect(-12, 0, 24, 10); break;
79
+ case 'melon': g.fillStyle = '#4CCB7A'; g.beginPath(); g.arc(0, -6, 21, 0, Math.PI); g.closePath(); g.fill(); g.stroke(); g.fillStyle = '#FF5A6E'; g.beginPath(); g.arc(0, -6, 16, 0, Math.PI); g.closePath(); g.fill(); g.fillStyle = '#2B2340'; for (const dx of [-8, 0, 8]) { g.beginPath(); g.ellipse(dx, 0, 1.6, 2.4, 0, 0, TAU); g.fill(); } break;
80
+ case 'cookie': circ(0, 0, 18, G.c); g.fillStyle = '#5A3420'; for (const [dx, dy] of [[-7, -6], [6, -8], [8, 5], [-5, 7], [0, 0]]) { g.beginPath(); g.arc(dx, dy, 2.6, 0, TAU); g.fill(); } break;
81
+ case 'egg': g.fillStyle = '#FFF9EC'; g.beginPath(); g.ellipse(0, 1, 14, 18, 0, 0, TAU); g.fill(); g.stroke(); shine(-5, -7, 4); break;
82
+ case 'berry': circ(0, 2, 16, G.c); g.fillStyle = '#2E3F9E'; g.beginPath(); for (let i = 0; i < 5; i++) { const a = -Math.PI / 2 + i * TAU / 5; g.lineTo(Math.cos(a) * 6, -10 + Math.sin(a) * 6); g.lineTo(Math.cos(a + 0.6) * 3, -10 + Math.sin(a + 0.6) * 3); } g.fill(); shine(-6, -3, 4); break;
83
+ case 'cheese': g.fillStyle = G.c; g.beginPath(); g.moveTo(-19, 14); g.lineTo(19, 14); g.lineTo(19, -6); g.lineTo(-19, 4); g.closePath(); g.fill(); g.stroke(); g.fillStyle = '#E09A10'; for (const [dx, dy, r] of [[-8, 9, 3], [6, 6, 4], [12, 11, 2]]) { g.beginPath(); g.arc(dx, dy, r, 0, TAU); g.fill(); } break;
84
+ case 'mint': g.fillStyle = G.c; g.beginPath(); g.moveTo(-12, 0); g.lineTo(-22, -8); g.lineTo(-22, 8); g.closePath(); g.moveTo(12, 0); g.lineTo(22, -8); g.lineTo(22, 8); g.closePath(); g.fill(); circ(0, 0, 13, '#FFFFFF'); g.strokeStyle = G.c; g.lineWidth = 4; g.beginPath(); g.arc(0, 0, 7, 0, 4.5); g.stroke(); break;
85
+ default: circ(0, 0, 16, G.c);
86
+ }
87
+ g.restore();
88
+ }
89
+
90
+ // ------------------------------------------------------------------ modes + stats (one small menu)
91
+ const seedOf = (m) => (m.kind === 'daily' ? `daily:${m.date}` : `level:${m.n}`);
92
+ const dayKey = (m) => `shelfpop:day:${m.date}`;
93
+ const dayStats = (m) => store(dayKey(m)) || { best: 0, tries: 0, done: false };
94
+ function renderModes() {
95
+ const el = $('modes'); el.innerHTML = '';
96
+ const items = [
97
+ { t: `Daily Shelf #${todayNum}`, on: mode.kind === 'daily' && mode.date === todayIso, go: () => setMode({ kind: 'daily', date: todayIso }) },
98
+ { t: `Level ${level}`, on: mode.kind === 'level', go: () => setMode({ kind: 'level', n: level }) },
99
+ { t: 'Archive', on: mode.kind === 'daily' && mode.date !== todayIso, lock: !pass.isPro(), go: archive },
100
+ ];
101
+ for (const it of items) {
102
+ const b = document.createElement('button'); b.className = 'chip'; b.type = 'button'; b.setAttribute('aria-pressed', String(it.on));
103
+ b.innerHTML = `${it.t}${it.lock ? ' <span class="lock">🔒</span>' : ''}`; b.onclick = it.go; el.appendChild(b);
104
+ }
105
+ }
106
+ function archive() {
107
+ if (!pass.isPro()) { pass.open('archive'); return; }
108
+ const n = todayNum - 1, k = Number(prompt(`Play a past Daily Shelf: enter a number from 1 to ${n}`, String(n)));
109
+ if (k >= 1 && k <= n) setMode({ kind: 'daily', date: dateOf(k) });
110
+ }
111
+ function setMode(m) { mode = m; $('menu').open = false; renderModes(); start(); }
112
+ const label = () => (mode.kind === 'daily' ? `#${dayNumber(mode.date)}` : `level ${mode.n}`);
113
+ function hud() {
114
+ $('num').textContent = label();
115
+ const s = mode.kind === 'daily' ? dayStats(mode) : { best: store(`shelfpop:lv:${mode.n}`) || 0 };
116
+ $('best').textContent = (s.best || 0).toLocaleString('en-US'); $('lvl').textContent = level;
117
+ }
118
+ const shopVis = (on) => { const b = $('shop-btn'); if (b) b.hidden = !on || pass.noShop(); };
119
+
120
+ // ------------------------------------------------------------------ run
121
+ function start() {
122
+ if (mode.kind === 'level') mode.n = level;
123
+ game = makeGame(seedOf(mode), mode.kind === 'daily' ? 'daily' : mode.n);
124
+ L = layout(game.board.length, game.sp.depth);
125
+ fx = []; texts = []; anims = new Map(); drag = sel = null; endShown = false; idle = 0; shake = 0; last = performance.now();
126
+ for (let s = 0; s < game.board.length; s++) for (let k = 0; k < 3; k++) anims.set(`${s}:${k}`, { kind: 'in', t: -0.03 * (s * 3 + k) });
127
+ $('over').hidden = true; shopVis(false); hud();
128
+ count(GAME, 'play', mode.kind === 'daily' ? (mode.date === todayIso ? 'daily' : 'archive') : 'level');
129
+ }
130
+ function finish() {
131
+ endShown = true;
132
+ const done = game.state === 'done';
133
+ if (done) { tone(784, 0.15, 'triangle', 0.08); tone(1047, 0.25, 'triangle', 0.08, 1, 0.12); tone(1319, 0.3, 'triangle', 0.07, 1, 0.24); }
134
+ else { tone(300, 0.35, 'sawtooth', 0.05, 0.4); buzz([30, 40, 30]); shake = 8; }
135
+ let newBest = false;
136
+ if (mode.kind === 'daily') {
137
+ const s = dayStats(mode); s.tries = (s.tries || 0) + 1;
138
+ if (game.score > (s.best || 0)) { s.best = game.score; newBest = game.score > 0; }
139
+ s.done = s.done || done; store(dayKey(mode), s); store('shelfpop:played', true);
140
+ } else {
141
+ const k = `shelfpop:lv:${mode.n}`; if (game.score > (store(k) || 0)) { store(k, game.score); newBest = true; }
142
+ if (done && mode.n === level) { level++; store('shelfpop:level', level); }
143
+ }
144
+ hud(); renderModes();
145
+ setTimeout(() => showOver(newBest, done), done ? 600 : 900);
146
+ if (done) install.offer();
147
+ }
148
+ function play(a, i, c, j = -1, fromXY = null) {
149
+ const ev = game.play(a, i, c, j);
150
+ if (!ev) { tone(200, 0.06, 'sine', 0.03); return false; }
151
+ idle = 0; sel = null;
152
+ const [ts, tj] = ev.to, p = L[c];
153
+ anims.set(`${ts}:${tj}`, { kind: 'fly', t: 0, fx: fromXY ? fromXY[0] : L[a].slot(i), fy: fromXY ? fromXY[1] : L[a].base - 24 });
154
+ tone(440 + (ev.item % 6) * 40, 0.05, 'triangle', 0.05, 1.2);
155
+ for (const pp of [ev.pop, ...(ev.pop2 || [])].filter(Boolean)) {
156
+ const q = L[pp.shelf], col = GOODS[pp.item].c;
157
+ for (let k = 0; k < 3; k++) burst(q.slot(k), q.base - 24, col, 12);
158
+ texts.push({ x: q.x + q.w / 2, y: q.base - 60, t: `+${pp.pts}`, big: pp.combo >= 2 ? `${pp.combo}x combo!` : '', life: 1 });
159
+ tone(NOTES[Math.min(5, pp.combo - 1)], 0.14, 'triangle', 0.09, 1.02, 0.04); tone(NOTES[Math.min(5, pp.combo)] * 2, 0.12, 'sine', 0.05, 1, 0.1);
160
+ buzz(pp.combo >= 3 ? 25 : 12); shake = Math.max(shake, pp.combo >= 3 ? 3 : 1.5);
161
+ }
162
+ for (const s of new Set(ev.slid)) for (let k = 0; k < 3; k++) anims.set(`${s}:${k}`, { kind: 'in', t: 0 });
163
+ if (p && !ev.pop) { /* placed */ }
164
+ if (game.state !== 'run' && !endShown) finish();
165
+ return true;
166
+ }
167
+ function burst(x, y, c, n) {
168
+ for (let i = 0; i < n; i++) { const a = Math.random() * TAU, v = 60 + Math.random() * 160; fx.push({ x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v - 70, life: 1, r: 2 + Math.random() * 3, c: i % 4 === 0 ? '#FFFFFF' : c }); }
169
+ }
170
+ // a good next move for the hint hand (cheap: finish a triple, else join a pair, else anything)
171
+ function hintMove() {
172
+ const b = game.board; let best = null, bs = -1;
173
+ for (const m of allMoves(b)) {
174
+ const it = b[m[0]][0][m[1]], fc = b[m[2]][0] || [], same = fc.filter((x) => x === it).length, srcSame = b[m[0]][0].filter((x) => x === it).length;
175
+ const sc = same * 10 - srcSame * 4 + (fc.every((x) => x == null) ? -3 : 0);
176
+ if (sc > bs) { bs = sc; best = m; }
177
+ }
178
+ return best;
179
+ }
180
+
181
+ // ------------------------------------------------------------------ loop
182
+ function frame(now) {
183
+ requestAnimationFrame(frame);
184
+ const dt = Math.min(0.1, (now - last) / 1000); last = now;
185
+ if (game) {
186
+ const was = game.state; game.tick(dt);
187
+ if (was === 'run' && game.state !== 'run' && !endShown) finish();
188
+ if (game.state === 'run') { idle += dt; if (autoBot && (botT += dt) > 0.35) { botT = 0; const m = (game.solution && game.solution[game.moves]) || hintMove(); if (m) play(m[0], m[1], m[2]); } }
189
+ }
190
+ for (const a of anims.values()) a.t += dt;
191
+ for (const [k, a] of anims) if (a.t > 0.5) anims.delete(k);
192
+ for (const p of fx) { p.x += p.vx * dt; p.y += p.vy * dt; p.vy += 600 * dt; p.life -= dt * 1.5; }
193
+ fx = fx.filter((p) => p.life > 0);
194
+ for (const t of texts) { t.y -= 36 * dt; t.life -= dt * 0.9; }
195
+ texts = texts.filter((t) => t.life > 0);
196
+ shake *= Math.pow(0.02, dt); if (shake < 0.2) shake = 0;
197
+ draw(now);
198
+ }
199
+ const ease = (t) => 1 - Math.pow(1 - Math.min(1, Math.max(0, t)), 3);
200
+ function draw(now) {
201
+ const S = LOOKS[look];
202
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, cv.width, cv.height); ctx.setTransform(scale, 0, 0, scale, 0, 0);
203
+ const gr = ctx.createLinearGradient(0, 0, 0, H); gr.addColorStop(0, S.top); gr.addColorStop(1, S.bot); ctx.fillStyle = gr; ctx.fillRect(0, 0, W, H);
204
+ ctx.fillStyle = 'rgba(255,255,255,.35)'; for (let i = 0; i < 9; i++) ctx.fillRect(0, 70 + i * 54, W, 2);
205
+ if (shake) ctx.translate((Math.random() - 0.5) * shake, (Math.random() - 0.5) * shake);
206
+ if (!game) return;
207
+ const hm = game.state === 'run' && (idle > 5 || (mode.kind === 'level' && mode.n === 1 && game.moves < 4 && idle > 0.6)) ? hintMove() : null;
208
+ game.board.forEach((rows, s) => {
209
+ const p = L[s];
210
+ ctx.fillStyle = S.wall; rr(ctx, p.x, p.y + 4, p.w, p.h - 8, 18); ctx.fill();
211
+ if (sel && sel[0] !== s && (!rows[0] || rows[0].includes(null))) { ctx.strokeStyle = S.acc; ctx.lineWidth = 2; ctx.setLineDash([6, 6]); rr(ctx, p.x + 2, p.y + 6, p.w - 4, p.h - 12, 16); ctx.stroke(); ctx.setLineDash([]); }
212
+ // back rows: smaller and softer, peeking above the front row
213
+ for (let d = Math.min(rows.length - 1, 2); d >= 1; d--) {
214
+ const y = p.base - 24 - (d === 1 ? 42 : 68), sc = d === 1 ? 0.62 : 0.45, al = d === 1 ? 0.6 : 0.38;
215
+ rows[d].forEach((it, k) => { if (it != null) good(ctx, it, p.slot(k), y, sc, al); });
216
+ }
217
+ // the plank
218
+ ctx.fillStyle = S.wood; rr(ctx, p.x + 4, p.base, p.w - 8, 12, 5); ctx.fill(); ctx.fillStyle = S.wood2; ctx.fillRect(p.x + 8, p.base + 10, p.w - 16, 3);
219
+ if (rows.length > 1) { ctx.fillStyle = S.ink; ctx.globalAlpha = 0.45; ctx.font = '800 11px system-ui,sans-serif'; ctx.textAlign = 'right'; ctx.fillText(`+${rows.length - 1}`, p.x + p.w - 10, p.y + 20); ctx.globalAlpha = 1; }
220
+ const fr = rows[0] || [];
221
+ fr.forEach((it, k) => {
222
+ if (it == null) return;
223
+ if (drag && drag.a === s && drag.i === k) return;
224
+ let x = p.slot(k), y = p.base - 24, sc = 1;
225
+ const an = anims.get(`${s}:${k}`);
226
+ if (an && an.kind === 'in') { const e = ease(an.t / 0.28); sc = an.t < 0 ? 0 : 0.4 + 0.6 * e + Math.sin(Math.min(1, an.t / 0.28) * Math.PI) * 0.12; }
227
+ if (an && an.kind === 'fly') { const e = ease(an.t / 0.18); x = an.fx + (x - an.fx) * e; y = an.fy + (y - an.fy) * e; }
228
+ const lifted = sel && sel[0] === s && sel[1] === k;
229
+ if (hm && hm[0] === s && hm[1] === k) { ctx.strokeStyle = S.acc; ctx.lineWidth = 3; ctx.globalAlpha = 0.5 + 0.5 * Math.sin(now / 160); ctx.beginPath(); ctx.arc(x, y, 25, 0, TAU); ctx.stroke(); ctx.globalAlpha = 1; }
230
+ ctx.fillStyle = 'rgba(60,30,10,.12)'; ctx.beginPath(); ctx.ellipse(x, p.base - 1, 16, 3.5, 0, 0, TAU); ctx.fill();
231
+ good(ctx, it, x, y - (lifted ? 8 : 0), sc * (lifted ? 1.24 : 1.12));
232
+ });
233
+ });
234
+ // hint hand (moves from the item to the target shelf)
235
+ if (hm) {
236
+ const a = L[hm[0]], c = L[hm[2]], u = ((now / 1300) % 1), e = ease(u * 1.4);
237
+ const x = a.slot(hm[1]) + (c.x + c.w / 2 - a.slot(hm[1])) * e, y = a.base - 10 + (c.base - 10 - (a.base - 10)) * e;
238
+ ctx.globalAlpha = u > 0.85 ? (1 - u) / 0.15 : 1; ctx.font = '30px system-ui,sans-serif'; ctx.textAlign = 'center'; ctx.fillText('👆', x + 6, y + 18); ctx.globalAlpha = 1;
239
+ }
240
+ if (drag) good(ctx, drag.it, drag.x, drag.y - 14, 1.3);
241
+ for (const q of fx) { ctx.globalAlpha = Math.max(0, Math.min(1, q.life * 1.3)); ctx.fillStyle = q.c; ctx.beginPath(); ctx.arc(q.x, q.y, q.r, 0, TAU); ctx.fill(); }
242
+ ctx.globalAlpha = 1; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
243
+ for (const t of texts) {
244
+ ctx.globalAlpha = Math.min(1, t.life * 1.5); ctx.font = '900 22px system-ui,-apple-system,sans-serif'; ctx.lineWidth = 5; ctx.strokeStyle = '#FFFFFF'; ctx.fillStyle = S.ink;
245
+ ctx.strokeText(t.t, t.x, t.y); ctx.fillText(t.t, t.x, t.y);
246
+ if (t.big) { ctx.font = '900 16px system-ui,sans-serif'; ctx.fillStyle = S.acc; ctx.strokeText(t.big, t.x, t.y - 22); ctx.fillText(t.big, t.x, t.y - 22); }
247
+ }
248
+ ctx.globalAlpha = 1;
249
+ // HUD: score chip (left), progress dots (middle), clock (right)
250
+ ctx.fillStyle = 'rgba(255,255,255,.9)'; rr(ctx, 10, 12, 112, 40, 20); ctx.fill();
251
+ ctx.fillStyle = S.ink; ctx.textAlign = 'left'; ctx.font = '900 22px system-ui,-apple-system,sans-serif'; ctx.fillText(game.score.toLocaleString('en-US'), 24, 33);
252
+ const left = game.left(), low = left <= 10 && game.state === 'run';
253
+ ctx.fillStyle = 'rgba(255,255,255,.9)'; rr(ctx, W - 82, 12, 72, 40, 20); ctx.fill();
254
+ ctx.fillStyle = low ? '#E2477A' : S.ink; ctx.textAlign = 'center'; ctx.font = '900 20px system-ui,sans-serif'; ctx.fillText(fmt(Math.ceil(left)), W - 46, 33);
255
+ const prog = game.popped / game.total; ctx.fillStyle = 'rgba(255,255,255,.9)'; rr(ctx, 132, 26, 136, 12, 6); ctx.fill();
256
+ ctx.fillStyle = S.acc; rr(ctx, 132, 26, Math.max(12, 136 * prog), 12, 6); ctx.fill();
257
+ if (game.moves === 0 && game.state === 'run' && !(mode.kind === 'level' && mode.n === 1)) {
258
+ ctx.globalAlpha = Math.max(0, 1 - game.t / 3); ctx.fillStyle = S.ink; ctx.font = '800 15px system-ui,sans-serif'; ctx.fillText('Drag goods to a free spot · 3 alike pop', W / 2, 60); ctx.globalAlpha = 1;
259
+ }
260
+ }
261
+
262
+ // ------------------------------------------------------------------ input: drag an item to a shelf, or tap item then tap shelf
263
+ const toWorld = (e) => { const r = cv.getBoundingClientRect(); return [((e.clientX - r.left) / r.width) * W, ((e.clientY - r.top) / r.height) * H]; };
264
+ function itemAt(x, y) {
265
+ for (let s = 0; s < L.length; s++) { const p = L[s], fr = game.board[s][0]; if (!fr) continue; for (let k = 0; k < 3; k++) if (fr[k] != null && Math.hypot(x - p.slot(k), y - (p.base - 24)) < 27) return [s, k]; }
266
+ return null;
267
+ }
268
+ function shelfAt(x, y) { for (let s = 0; s < L.length; s++) { const p = L[s]; if (x >= p.x && x <= p.x + p.w && y >= p.y && y <= p.y + p.h) return s; } return -1; }
269
+ function slotNear(s, x) { const fr = game.board[s][0] || [null, null, null]; let best = -1, bd = 1e9; for (let k = 0; k < 3; k++) if (fr[k] == null) { const d = Math.abs(L[s].slot(k) - x); if (d < bd) { bd = d; best = k; } } return best; }
270
+ cv.addEventListener('pointerdown', (e) => {
271
+ e.preventDefault();
272
+ if (!game || game.state !== 'run') { if (endShown) start(); return; }
273
+ const [x, y] = toWorld(e), hit = itemAt(x, y);
274
+ if (hit) { drag = { a: hit[0], i: hit[1], it: game.board[hit[0]][0][hit[1]], x, y, sx: x, sy: y, moved: false }; try { cv.setPointerCapture(e.pointerId); } catch { /* */ } tone(660, 0.03, 'sine', 0.03); return; }
275
+ if (sel) { const s = shelfAt(x, y); if (s >= 0 && s !== sel[0]) play(sel[0], sel[1], s, slotNear(s, x)); else sel = null; }
276
+ });
277
+ cv.addEventListener('pointermove', (e) => { if (!drag) return; const [x, y] = toWorld(e); drag.x = x; drag.y = y; if (Math.hypot(x - drag.sx, y - drag.sy) > 10) drag.moved = true; });
278
+ cv.addEventListener('pointerup', (e) => {
279
+ if (!drag) return;
280
+ const [x, y] = toWorld(e), d = drag; drag = null;
281
+ const s = shelfAt(x, y);
282
+ if (!d.moved || s === d.a) { // a tap: select it (tap again to drop), or move the selection here
283
+ if (sel && sel[0] !== d.a) { play(sel[0], sel[1], d.a, slotNear(d.a, x)); return; }
284
+ sel = sel && sel[0] === d.a && sel[1] === d.i ? null : [d.a, d.i]; return;
285
+ }
286
+ if (s >= 0) play(d.a, d.i, s, slotNear(s, x), [x, y - 14]);
287
+ });
288
+ cv.addEventListener('pointercancel', () => { drag = null; });
289
+ document.addEventListener('keydown', (e) => {
290
+ if (/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement && document.activeElement.tagName)) return;
291
+ if (e.key === 'r' || e.key === 'R') { e.preventDefault(); start(); }
292
+ else if (e.key === 'm' || e.key === 'M') $('mute').click();
293
+ else if (e.key === 'h' || e.key === 'H') idle = 99;
294
+ else if ((e.key === ' ' || e.key === 'Enter') && endShown && document.activeElement && document.activeElement.tagName !== 'BUTTON') { e.preventDefault(); start(); }
295
+ });
296
+
297
+ // ------------------------------------------------------------------ results, share, card
298
+ function shareText() { return `${coreShare(game, label())}\nCan you clear today's shelves?`; }
299
+ function showOver(newBest, done) {
300
+ $('over-title').textContent = done ? (newBest ? 'New best!' : 'Shelves clear!') : game.state === 'stuck' ? 'No free spot!' : 'Time!';
301
+ $('over-score').textContent = game.score.toLocaleString('en-US');
302
+ $('over-line').textContent = done ? `Cleared in ${fmt(game.t)} ${'⭐'.repeat(game.stars())}` : `${game.popped}/${game.total} popped · best combo x${game.bestCombo}`;
303
+ $('again').textContent = done && mode.kind === 'level' ? `Level ${level} ▶` : 'Play again';
304
+ $('over-grid').textContent = coreShare(game, label());
305
+ const it = intents(GAME, shareText(), PATH); $('sx').href = it.x; $('sb').href = it.bsky; $('sw').href = it.whatsapp;
306
+ $('over').hidden = false; shopVis(true);
307
+ pass.afterWin($('over'), 'over');
308
+ }
309
+ function card() {
310
+ const S = LOOKS[look], c = document.createElement('canvas'); c.width = 1080; c.height = 1350; const x = c.getContext('2d');
311
+ const gr = x.createLinearGradient(0, 0, 0, 1350); gr.addColorStop(0, S.top); gr.addColorStop(1, S.bot); x.fillStyle = gr; x.fillRect(0, 0, 1080, 1350);
312
+ const kinds = Object.keys(game.popsBy).map(Number); const show = kinds.length ? kinds : [0, 1, 2];
313
+ x.save(); x.scale(3, 3); show.slice(0, 12).forEach((k, i) => good(x, k, 50 + (i % 6) * 48, 190 + Math.floor(i / 6) * 50)); x.restore();
314
+ x.fillStyle = S.wood; x.fillRect(80, 650, 920, 24);
315
+ x.fillStyle = S.ink; x.textAlign = 'left'; x.font = '900 80px system-ui,sans-serif'; x.fillText('SHELF POP', 80, 150);
316
+ x.globalAlpha = 0.75; x.font = '700 40px system-ui,sans-serif'; x.fillText(mode.kind === 'daily' ? `Daily Shelf #${dayNumber(mode.date)} · ${mode.date}` : `Level ${mode.n}`, 80, 210); x.globalAlpha = 1;
317
+ x.font = '900 170px system-ui,sans-serif'; x.fillText(game.score.toLocaleString('en-US'), 80, 900);
318
+ x.font = '700 48px system-ui,sans-serif'; x.fillText(game.state === 'done' ? `cleared in ${fmt(game.t)} ${'⭐'.repeat(game.stars())}` : `${game.popped}/${game.total} popped`, 80, 980);
319
+ x.font = '800 44px system-ui,sans-serif'; x.fillText("Can you clear today's shelves?", 80, 1200);
320
+ x.globalAlpha = 0.7; x.font = '600 32px system-ui,sans-serif'; x.fillText('Play free: cybermaxtools.com/games/shelfpop', 80, 1270);
321
+ return c;
322
+ }
323
+ const fname = () => `shelfpop-${mode.kind === 'daily' ? mode.date : `level-${mode.n}`}.png`;
324
+ $('share').onclick = async () => share(GAME, shareText(), PATH, await canvasBlob(card()), fname());
325
+ ['sx', 'sb', 'sw'].forEach((id) => $(id).addEventListener('click', () => count(GAME, 'share', { sx: 'x', sb: 'bsky', sw: 'whatsapp' }[id])));
326
+ $('card').onclick = async () => { download(await canvasBlob(card()), fname()); count(GAME, 'share', 'png'); };
327
+ $('pass-btn').onclick = () => pass.open('header');
328
+ $('again').onclick = () => { if (mode.kind === 'level') mode.n = level; start(); cv.focus(); };
329
+ document.addEventListener('visibilitychange', () => { last = performance.now(); });
330
+ function renderLooks() {
331
+ const el = $('looks'); el.innerHTML = '';
332
+ for (const [id, s] of Object.entries(LOOKS)) {
333
+ const b = document.createElement('button'), lock = !canUse(s);
334
+ b.type = 'button'; b.title = `${s.name}${s.tier === 'pass' ? ' (Fun Pass)' : ''}`; b.setAttribute('aria-label', b.title);
335
+ b.style.background = `linear-gradient(135deg, ${s.top} 50%, ${s.wood} 50%)`; b.setAttribute('aria-pressed', String(id === look));
336
+ if (lock) b.classList.add('locked');
337
+ b.onclick = () => { if (lock) { pass.open('theme'); return; } look = id; store('shelfpop:look', id); renderLooks(); };
338
+ el.appendChild(b);
339
+ }
340
+ }
341
+ pass.onChange(() => { if (!canUse(LOOKS[look])) { look = 'market'; store('shelfpop:look', 'market'); } renderLooks(); renderModes(); });
342
+
343
+ // test + screenshot hooks (no effect on normal play)
344
+ window.__shelfpop = {
345
+ state: () => ({ state: game.state, score: game.score, popped: game.popped, total: game.total, moves: game.moves, left: game.left(), mode: mode.kind, level, endShown, shelves: game.board.length }),
346
+ bot: (on = true) => { autoBot = on; },
347
+ solve: () => { for (const m of game.solution.slice(game.moves)) play(m[0], m[1], m[2]); },
348
+ // canvas CSS pixel positions for a move (for real drag tests)
349
+ where: (s, k) => { const r = cv.getBoundingClientRect(), p = L[s]; return { x: r.left + (p.slot(k) / W) * r.width, y: r.top + ((p.base - 24) / H) * r.height, sx: r.left + ((p.x + p.w / 2) / W) * r.width, sy: r.top + ((p.base - 24) / H) * r.height }; },
350
+ next: () => game.solution[game.moves],
351
+ free: (c) => (game.board[c][0] || [null, null, null]).indexOf(null),
352
+ hint: hintMove,
353
+ timeout: () => { game.t = game.time - 0.01; },
354
+ shareText,
355
+ };
356
+ window.__cmxShot = async () => { mode = { kind: 'daily', date: todayIso }; start(); for (const m of game.solution.slice(0, 9)) play(m[0], m[1], m[2]); fx = []; texts = []; anims = new Map(); idle = 0; };
357
+
358
+ renderModes(); renderLooks();
359
+ start();
360
+ requestAnimationFrame(frame);
shelfpop/icon-192.png ADDED
shelfpop/icon-512.png ADDED
shelfpop/icon-maskable.png ADDED
shelfpop/icon.svg ADDED
shelfpop/index.html ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en" data-theme="light"><head><meta charset="utf-8"><!-- cmx:sound --><script>(()=>{let on=false;const W=window,L=[];try{if(navigator.audioSession)navigator.audioSession.type='playback'}catch(e){}const kick=c=>{if(c.state==='closed')return;if(c.state!=='running')c.resume().catch(()=>{});try{const b=c.createBuffer(1,1,22050),s=c.createBufferSource();s.buffer=b;s.connect(c.destination);s.start(0)}catch(e){}};for(const K of['AudioContext','webkitAudioContext']){const O=W[K];if(!O||O.__cmx)continue;const C=class extends O{constructor(...a){super(...a);L.push(this);if(on)kick(this)}};C.__cmx=1;W[K]=C}const go=()=>{on=true;L.forEach(kick)};for(const e of['pointerdown','touchend','keydown','click'])addEventListener(e,go,{capture:true,passive:true});document.addEventListener('visibilitychange',()=>{if(!document.hidden&&on)go()})})();</script><!-- /cmx:sound -->
3
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
4
+ <title>Shelf Pop: Free Goods Sort Puzzle Game Online, Daily Shelf</title>
5
+ <meta name="description" content="Play Shelf Pop free: drag the goods between shelves, line up three alike and they pop. Clear every shelf before the clock runs out. A new Daily Shelf every day. No download.">
6
+ <link rel="canonical" href="https://cybermaxtools.com/games/shelfpop/">
7
+ <meta property="og:type" content="website"><meta property="og:site_name" content="CyberMax">
8
+ <meta property="og:title" content="Shelf Pop: Free Goods Sort Puzzle Game Online">
9
+ <meta property="og:description" content="Play Shelf Pop free: drag the goods between shelves, line up three alike and they pop. Clear every shelf before the clock runs out. A new Daily Shelf every day. No download.">
10
+ <meta property="og:url" content="https://cybermaxtools.com/games/shelfpop/">
11
+ <meta property="og:image" content="https://cybermaxtools.com/games/shelfpop/og.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630">
12
+ <meta name="twitter:card" content="summary_large_image"><meta name="twitter:image" content="https://cybermaxtools.com/games/shelfpop/og.png">
13
+ <meta name="twitter:title" content="Shelf Pop: Free Goods Sort Puzzle Game Online">
14
+ <meta name="twitter:description" content="Play Shelf Pop free: drag the goods between shelves, line up three alike and they pop. Clear every shelf before the clock runs out. A new Daily Shelf every day. No download.">
15
+ <meta name="theme-color" content="#FFF1D6">
16
+ <link rel="manifest" href="manifest.webmanifest">
17
+ <link rel="icon" href="icon.svg" type="image/svg+xml"><link rel="apple-touch-icon" href="icon-192.png">
18
+ <meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-title" content="Shelf Pop">
19
+ <link rel="stylesheet" href="fun.css"><link rel="stylesheet" href="style.css">
20
+ <script>try{var t=localStorage.getItem('cm-theme');document.documentElement.dataset.theme=t||'light'}catch(e){}</script>
21
+ <style>.h1kw{display:block;font-size:.42em;font-weight:600;opacity:.75;letter-spacing:.01em;margin-top:.15em}.seo ol,.seo ul{padding-left:1.2em}.seo li{margin:.25em 0}</style>
22
+ <script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "VideoGame", "@id": "https://cybermaxtools.com/games/shelfpop/#game", "name": "Shelf Pop", "alternateName": "Goods sort puzzle game online free", "url": "https://cybermaxtools.com/games/shelfpop/", "image": "https://cybermaxtools.com/games/shelfpop/og.png", "description": "Shelf Pop is a free goods sort puzzle for your browser. Every shelf shows three spots in front and more goods waiting behind. Drag an apple, a donut or a carton of milk to a free spot on another shelf; when three of the same sit together on one shelf, they pop and the row behind slides forward. Pop several in a row for a combo. Clear every shelf before the clock runs out. The Daily Shelf gives everyone the same board each day, and every board is checked solvable before you see it.", "genre": ["Puzzle", "Casual", "Sorting", "Match 3"], "gamePlatform": ["Web browser", "Android", "iOS", "Windows", "macOS", "ChromeOS"], "applicationCategory": "Game", "operatingSystem": "Any (web browser)", "playMode": "SinglePlayer", "inLanguage": "en", "isAccessibleForFree": true, "offers": [{"@type": "Offer", "name": "Free to play (daily challenge + free modes)", "price": "0", "priceCurrency": "USD"}], "author": {"@type": "Organization", "name": "CyberMax", "url": "https://cybermaxtools.com/"}, "publisher": {"@type": "Organization", "name": "CyberMax"}, "datePublished": "2026-11-08", "keywords": "Goods sort puzzle game online free, free goods sort puzzle game, unblocked, no download, browser game"}, {"@type": "FAQPage", "@id": "https://cybermaxtools.com/games/shelfpop/#faq", "mainEntity": [{"@type": "Question", "name": "Is Shelf Pop free?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. The Daily Shelf and every level are free, with no ads and no sign-up. The optional CyberMax Fun Pass adds every past Daily Shelf and two shop themes."}}, {"@type": "Question", "name": "Can every board be solved?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. A solver plays every board through before it is shown, so there is always a way to clear it."}}, {"@type": "Question", "name": "How does the score work?", "acceptedAnswer": {"@type": "Answer", "text": "Each pop is 30 points times your combo (up to 5x). Clearing every shelf adds 5 points for every second left on the clock."}}, {"@type": "Question", "name": "Is the daily the same for everyone?", "acceptedAnswer": {"@type": "Answer", "text": "Yes. Everyone gets the same shelves in the same order each day, so scores compare fairly."}}, {"@type": "Question", "name": "Can I play offline?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, after the first visit, and you can add it to your home screen like an app."}}]}]}</script>
23
+ </head><body>
24
+ <div class="wrap">
25
+ <header class="top"><a class="brand" href="https://cybermaxtools.com/games/"><svg viewBox="0 0 512 512" aria-hidden="true"><clipPath id="lg"><rect width="512" height="512" rx="116"/></clipPath><g clip-path="url(#lg)"><rect width="512" height="512" fill="#FF6A3D"/><path d="M512 250V512H250Z" fill="#D9481F"/></g><g transform="translate(86 86) scale(3.4)"><path d="M66 27 A27 27 0 1 0 66 73" fill="none" stroke="#11141B" stroke-width="17" stroke-linecap="round"/><rect x="66" y="41" width="20" height="18" rx="4" fill="#11141B"/></g></svg>CyberMax</a>
26
+ <nav><a href="https://cybermaxtools.com/games/">Games</a></nav><button class="btn sm cmx-shopbtn cmx-shop-top" id="shop-btn" type="button" data-cmx-shop="title" data-cmx-hidden>🛍️ Shop</button><button class="icon" id="mute" type="button" aria-label="Sound on or off">🔊</button><button class="icon" id="theme" type="button" aria-label="Switch light or dark">◐</button></header>
27
+ <main>
28
+ <section class="game">
29
+ <div class="headline"><h1>Shelf Pop <span id="num" class="num"></span> <span class="pro-badge">PASS</span> <small class="h1kw">Free goods sort puzzle game</small></h1></div>
30
+ <div class="stage"><canvas id="c" width="360" height="540" aria-label="Shelf Pop game. Drag an item from the front of a shelf to a free spot on another shelf. Three alike on one shelf pop." tabindex="0"></canvas>
31
+ <section class="panel over" id="over" hidden aria-live="polite">
32
+ <h2 id="over-title"></h2>
33
+ <p class="big-num" id="over-score">0</p>
34
+ <p id="over-line" class="muted"></p>
35
+ <button class="btn big" id="again" type="button">Play again</button>
36
+ <p><button class="btn ghost sm cmx-shopres" type="button" data-cmx-shop="results">See the shop →</button></p>
37
+ <details class="more-res"><summary>Your shelves and sharing</summary>
38
+ <p id="over-grid" class="grid"></p>
39
+ <div class="row"><button class="btn sm" id="share" type="button">Share score</button><a class="btn ghost sm" id="sx" target="_blank" rel="noopener">X</a><a class="btn ghost sm" id="sb" target="_blank" rel="noopener">Bluesky</a><a class="btn ghost sm" id="sw" target="_blank" rel="noopener">WhatsApp</a><button class="btn ghost sm" id="card" type="button">Save card</button></div>
40
+ </details>
41
+ </section>
42
+ </div>
43
+ <div class="row under"><span class="muted small">Best <b id="best">0</b> · level <b id="lvl">1</b></span>
44
+ <details class="menu" id="menu"><summary class="btn ghost sm">☰ Menu</summary>
45
+ <div class="menu-body">
46
+ <div class="chips" id="modes" role="group" aria-label="Mode"></div>
47
+ <div class="row looks" id="looks" aria-label="Theme"></div>
48
+ <div class="row"><button class="btn pass sm" id="pass-btn" type="button">✨ Fun Pass</button><button class="btn ghost sm" id="install" type="button" hidden>📲 Add to Home Screen</button></div>
49
+ </div>
50
+ </details>
51
+ </div>
52
+ </section>
53
+ <section class="seo" id="guide">
54
+ <h2>Shelf Pop: goods sort puzzle game online free</h2>
55
+ <p>Shelf Pop is a free goods sort puzzle for your browser. Every shelf shows three spots in front and more goods waiting behind. Drag an apple, a donut or a carton of milk to a free spot on another shelf; when three of the same sit together on one shelf, they pop and the row behind slides forward. Pop several in a row for a combo. Clear every shelf before the clock runs out. The Daily Shelf gives everyone the same board each day, and every board is checked solvable before you see it.</p>
56
+ <h2>How to play Shelf Pop</h2>
57
+ <ol><li>Drag an item from the front of a shelf and drop it on another shelf with a free spot.</li><li>Three of the same item on one shelf pop.</li><li>When a shelf&#x27;s front row is empty, the goods behind it slide forward.</li><li>Pop again within four seconds to build a combo (up to 5x).</li><li>Clear every shelf before the clock runs out; time left is bonus points.</li><li>Stuck? Tap H or wait a moment and a hand shows a good move.</li></ol>
58
+ <h3>Controls</h3>
59
+ <p><b>Phone and tablet:</b> Drag an item to another shelf, or tap an item and then tap the shelf.</p>
60
+ <p><b>Desktop, laptop and Chromebook:</b> Drag with the mouse, or click an item and then a shelf. R restarts, M mutes, H shows a hint.</p>
61
+ <h2>Shelf Pop tips and strategy</h2>
62
+ <ul><li>Look at the faded goods behind each shelf: they come forward next.</li><li>Keep one shelf as a free parking spot for awkward items.</li><li>Finish a pair before you start a new one.</li><li>Quick pops in a row multiply your score.</li></ul>
63
+ <h2>Game modes</h2>
64
+ <ul><li>Daily Shelf: the same board for everyone today, with a shareable result.</li><li>Levels: from a tiny three-shelf warm-up to six deep shelves.</li><li>Fun Pass: every past Daily Shelf and the Mint and Peach shop themes.</li></ul>
65
+ <p>The daily challenge and the main modes are free to play, with no ads and no sign-up. Bonus modes, the daily archive and colour themes come with the optional <a href="https://cybermaxtools.com/games/#pass">CyberMax Fun Pass</a> ($2.99/month, $19/year or $29.99 for life), which opens everything in every CyberMax game.</p>
66
+ <h2>Shelf Pop FAQ</h2>
67
+ <h3>Is Shelf Pop free?</h3><p>Yes. The Daily Shelf and every level are free, with no ads and no sign-up. The optional CyberMax Fun Pass adds every past Daily Shelf and two shop themes.</p>
68
+ <h3>Can every board be solved?</h3><p>Yes. A solver plays every board through before it is shown, so there is always a way to clear it.</p>
69
+ <h3>How does the score work?</h3><p>Each pop is 30 points times your combo (up to 5x). Clearing every shelf adds 5 points for every second left on the clock.</p>
70
+ <h3>Is the daily the same for everyone?</h3><p>Yes. Everyone gets the same shelves in the same order each day, so scores compare fairly.</p>
71
+ <h3>Can I play offline?</h3><p>Yes, after the first visit, and you can add it to your home screen like an app.</p>
72
+ <h2>Similar free games</h2>
73
+ <div class="more"><a href="https://cybermaxtools.com/games/gummy-jar/"><b>Gummy Jar</b><span>Drop gummies, match two, plop them bigger</span></a><a href="https://cybermaxtools.com/games/dig-drone/"><b>Dig Drone</b><span>Hold to dig, slide to steer, upgrade and dig deeper</span></a><a href="https://cybermaxtools.com/games/stone-paths/"><b>Stone Paths</b><span>Turn the 3D stones until every path glows</span></a><a href="https://cybermaxtools.com/games/"><b>All CyberMax games</b><span>Free browser games, no download</span></a></div>
74
+ </section>
75
+ </main>
76
+ <footer>© 2026 CyberMax · <a href="https://cybermaxtools.com/games/">Games</a> · <a href="https://cybermaxtools.com/store/">Store</a> · <a href="https://cybermaxtools.com/privacy">Privacy</a> · <a href="https://cybermaxtools.com/terms">Terms</a></footer>
77
+ </div>
78
+ <script type="module" src="game.js"></script>
79
+ </body></html>
shelfpop/manifest.webmanifest ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Shelf Pop",
3
+ "short_name": "Shelf Pop",
4
+ "description": "Drag the goods, line up three alike, pop the shelves clear. Free daily game by CyberMax, works offline.",
5
+ "id": "index.html",
6
+ "start_url": "index.html?utm_source=pwa-hf",
7
+ "scope": "./",
8
+ "display": "standalone",
9
+ "orientation": "portrait",
10
+ "background_color": "#FFF1D6",
11
+ "theme_color": "#FFF1D6",
12
+ "categories": [
13
+ "games",
14
+ "entertainment"
15
+ ],
16
+ "icons": [
17
+ {
18
+ "src": "icon-192.png",
19
+ "sizes": "192x192",
20
+ "type": "image/png"
21
+ },
22
+ {
23
+ "src": "icon-512.png",
24
+ "sizes": "512x512",
25
+ "type": "image/png"
26
+ },
27
+ {
28
+ "src": "icon-maskable.png",
29
+ "sizes": "512x512",
30
+ "type": "image/png",
31
+ "purpose": "maskable"
32
+ },
33
+ {
34
+ "src": "icon.svg",
35
+ "sizes": "any",
36
+ "type": "image/svg+xml"
37
+ }
38
+ ],
39
+ "screenshots": [
40
+ {
41
+ "src": "shot-phone.png",
42
+ "sizes": "780x1688",
43
+ "type": "image/png",
44
+ "form_factor": "narrow"
45
+ }
46
+ ]
47
+ }
shelfpop/offer.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ // Written by scripts/games/sync_kit.py from products/fun-pass/games.json; do not edit by hand. (c) 2026 CyberMax.
2
+ export const OFFER = {"game": "shelfpop", "name": "Shelf Pop", "price": null, "live": false, "demo": 20, "games": 26, "levels": false, "shop": [{"offer": "st-fun-pass-monthly", "kind": "pass", "name": "Fun Pass", "what": "Every paid level, chapter and mode in every CyberMax game (Campaign+, Prism+, every full game), plus every past daily and theme. Cancel any time.", "cents": 299, "price": "$2.99", "per": "/month", "icon": "✨", "sw": ["#FFB547", "#FF6A3D"], "store": "https://cybermaxtools.com/store/fun-pass/", "img": "https://cybermaxtools.com/store/img/fun-pass-icon.webp", "alt": [{"offer": "st-fun-pass-yearly", "label": "$19/year"}, {"offer": "st-fun-pass-unlock", "label": "$29.99 for life"}]}, {"offer": "st-arcade-lifetime-lifetime", "kind": "arcade", "name": "Arcade Lifetime", "what": "One payment for every content unlock in every CyberMax game, now and later (every full game, Campaign+, Prism+ and new chapters), plus the Fun Pass for life and every Skin, Look and Founder Pack. Coin and crown packs not included.", "cents": 3999, "price": "$39.99", "per": "", "icon": "🕹️", "sw": ["#5CF2FF", "#B26BFF"], "store": "https://cybermaxtools.com/store/arcade-lifetime/", "img": "https://cybermaxtools.com/store/img/arcade-lifetime-icon.webp"}], "shopFrom": "$2.99", "shopResults": "✨ See the Fun Pass →", "shopStore": null, "shopPass": true};
shelfpop/og.png ADDED

Git LFS Details

  • SHA256: edd8f8dd85aee67d92bb24b5007968cc96fe1a6623c5bd10d0fbf6bd54977473
  • Pointer size: 131 Bytes
  • Size of remote file: 132 kB
shelfpop/shot-phone.png ADDED

Git LFS Details

  • SHA256: 56004c0bb2325af2dad146c41e31d887d9c12974e973e2f691700357ef69cf77
  • Pointer size: 131 Bytes
  • Size of remote file: 217 kB
shelfpop/style.css ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Shelf Pop layout. Game colours live in game.js (LOOKS, GOODS). Calm screen: the shelves (score, progress, clock drawn in it), one menu. (c) 2026 CyberMax. */
2
+ .headline h1{margin:4px 0 0}.headline h1 .num{color:var(--muted);font-weight:700;font-size:.62em}
3
+ .stage{position:relative;display:flex;justify-content:center;margin-top:8px}
4
+ #c{display:block;width:min(100%,calc((100svh - 190px) * 2 / 3),480px);min-width:240px;aspect-ratio:2/3;height:auto;border-radius:24px;touch-action:none;user-select:none;-webkit-user-select:none;-webkit-tap-highlight-color:transparent;cursor:grab;box-shadow:0 2px 6px rgba(17,20,27,.08),0 14px 40px rgba(17,20,27,.12);background:#FFF1D6}
5
+ .under{justify-content:center;align-items:flex-start;margin:10px 0;gap:10px}
6
+ .menu{position:relative}.menu>summary{list-style:none;cursor:pointer;min-height:44px}.menu>summary::-webkit-details-marker{display:none}
7
+ .menu-body{display:flex;flex-direction:column;gap:10px;margin-top:8px;padding:12px;border:1px solid var(--line);border-radius:14px;background:var(--card,transparent)}
8
+ .over{margin:12px auto;text-align:center;max-width:520px}.over h2{margin:0;font-size:1.5em}
9
+ .big-num{font-size:3.2em;font-weight:900;margin:0;line-height:1.1;letter-spacing:-.02em}
10
+ .btn.big{font-size:1.15em;padding:14px 34px;min-height:52px;margin:8px 0}
11
+ .more-res{margin-top:6px;text-align:left}.more-res summary{cursor:pointer;color:var(--muted)}
12
+ .looks{justify-content:center;margin:0;flex-wrap:wrap}
13
+ .looks button{width:38px;height:38px;border-radius:50%;border:3px solid var(--line);cursor:pointer;position:relative}
14
+ .looks button[aria-pressed=true]{border-color:var(--ink)}
15
+ .looks button.locked::after{content:"🔒";position:absolute;right:-6px;bottom:-6px;font-size:12px}
16
+ .grid{font-size:20px;letter-spacing:1px;margin:4px 0 10px;white-space:pre-line;line-height:1.4}
17
+ .seo ol,.seo ul{padding-left:1.2em}.seo li{margin:.25em 0}
18
+ @media (max-width:520px){.wrap{padding-left:10px;padding-right:10px}header.top{margin-bottom:2px}.headline h1{font-size:1.5em}}
19
+ .stage>.panel{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(90%,420px);max-height:92%;overflow:auto;margin:0;z-index:5;background:var(--card-solid,#fff);border-radius:22px;box-shadow:0 10px 40px rgba(17,20,27,.22);animation:pin .22s ease-out}
20
+ @keyframes pin{from{opacity:0;transform:translate(-50%,-46%) scale(.96)}}
21
+ @media (prefers-reduced-motion:reduce){.stage>.panel{animation:none}}
shelfpop/sw.js ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CyberMax game service worker: the game works offline after the first visit. Cache-first for the game's own files,
2
+ // network-first for the page itself (so updates arrive), never caches API calls or other sites. (c) 2026 CyberMax.
3
+ const GAME = 'shelfpop';
4
+ const CACHE = `cmx-${GAME}-2664f3b0d6`;
5
+ const FILES = ["index.html", "arena.js", "cmx.js", "core.js", "fun.css", "funpass.js", "game.js", "icon-192.png", "icon-512.png", "icon-maskable.png", "icon.svg", "index.html", "manifest.webmanifest", "offer.js", "style.css"];
6
+
7
+ self.addEventListener('install', (e) => {
8
+ e.waitUntil(caches.open(CACHE).then((c) => c.addAll(FILES)).then(() => self.skipWaiting()));
9
+ });
10
+ self.addEventListener('activate', (e) => {
11
+ e.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter((k) => k.startsWith(`cmx-${GAME}-`) && k !== CACHE).map((k) => caches.delete(k)))).then(() => self.clients.claim()));
12
+ });
13
+ self.addEventListener('fetch', (e) => {
14
+ const u = new URL(e.request.url);
15
+ if (e.request.method !== 'GET' || u.origin !== location.origin || !u.pathname.startsWith(new URL(self.registration.scope).pathname)) return;
16
+ if (e.request.mode === 'navigate') {
17
+ e.respondWith(fetch(e.request).then((r) => { const c = r.clone(); caches.open(CACHE).then((x) => x.put(u.pathname, c)); return r; })
18
+ .catch(() => caches.match(u.pathname).then((r) => r || caches.match('index.html'))));
19
+ return;
20
+ }
21
+ e.respondWith(caches.match(e.request, { ignoreSearch: true }).then((r) => r || fetch(e.request).then((res) => {
22
+ if (res.ok) { const c = res.clone(); caches.open(CACHE).then((x) => x.put(e.request, c)); }
23
+ return res;
24
+ })));
25
+ });