-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.js
More file actions
464 lines (417 loc) · 21 KB
/
Copy pathanalytics.js
File metadata and controls
464 lines (417 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Brain Arcade — shared analytics, leaderboard, streaks & badges
// Requires: firebase-config.js + Firebase compat CDN loaded before this file
(function () {
'use strict';
// ── Game config ───────────────────────────────────────────────────────────────
const GAMES = {
'2048': { label: '2048', icon: '🔷', unit: 'pts', lower: false },
'wordle': { label: 'Wordle', icon: '🟩', unit: 'tries', lower: true },
'grid': { label: 'Grid', icon: '🔢', unit: '/ 49', lower: false },
'chain': { label: 'Chain', icon: '⛓️', unit: 'links', lower: false },
'letterlock': { label: 'LetterLock', icon: '🔒', unit: 'pts', lower: false },
};
// ── Badge definitions ─────────────────────────────────────────────────────────
// check(game, score, meta, { streak, maxStreak, gamesPlayed }) => boolean
const BADGES = [
// Universal
{ id:'first_game', icon:'🎮', label:'First Game', desc:'Play your first Brain Arcade game', game:'any', check:(_g,_s,_m,x) => x.gamesPlayed >= 1 },
{ id:'streak_3', icon:'🔥', label:'On Fire', desc:'Play 3 days in a row', game:'any', check:(_g,_s,_m,x) => x.streak >= 3 },
{ id:'streak_7', icon:'⚡', label:'Week Warrior', desc:'Play 7 days in a row', game:'any', check:(_g,_s,_m,x) => x.streak >= 7 },
{ id:'streak_30', icon:'💥', label:'Unstoppable', desc:'Play 30 days in a row', game:'any', check:(_g,_s,_m,x) => x.streak >= 30 },
// 2048
{ id:'tile_2048', icon:'🔷', label:'Reached 2048', desc:'Merge tiles to reach 2048', game:'2048', check:(_g,_s,m) => (m.bestTile||0) >= 2048 },
{ id:'tile_4096', icon:'💎', label:'Beyond 2048', desc:'Reach the 4096 tile', game:'2048', check:(_g,_s,m) => (m.bestTile||0) >= 4096 },
{ id:'score_10k', icon:'🌟', label:'10K Club', desc:'Score 10,000+ points in 2048', game:'2048', check:(_g,s) => s >= 10000 },
// Wordle
{ id:'wordle_win', icon:'🟩', label:'Word Solver', desc:'Win your first Wordle', game:'wordle', check:(_g,_s,m) => !!m.won },
{ id:'wordle_2', icon:'🎯', label:'Sharp Mind', desc:'Solve Wordle in 2 tries or fewer', game:'wordle', check:(_g,_s,m) => m.won && m.guesses <= 2 },
{ id:'wordle_genius', icon:'🧠', label:'Genius', desc:'Solve Wordle in 1 try', game:'wordle', check:(_g,_s,m) => m.won && m.guesses === 1 },
// Grid
{ id:'grid_25', icon:'🔢', label:'Halfway There', desc:'Find 25+ numbers in Grid', game:'grid', check:(_g,s) => s >= 25 },
{ id:'grid_perfect', icon:'🎯', label:'Perfect Grid', desc:'Find all 49 numbers', game:'grid', check:(_g,s) => s === 49 },
{ id:'grid_clean', icon:'✅', label:'No Mistakes', desc:'Complete Grid without a wrong tap', game:'grid', check:(_g,s,m) => m.reason !== 'wrong' && s > 0 },
// Chain
{ id:'chain_10', icon:'⛓️', label:'Chain Starter', desc:'Link 10+ words in Chain', game:'chain', check:(_g,s) => s >= 10 },
{ id:'chain_20', icon:'👑', label:'Chain Master', desc:'Link 20+ words in Chain', game:'chain', check:(_g,s) => s >= 20 },
{ id:'chain_mythic', icon:'🌌', label:'Mythic', desc:'Achieve Mythic rank (30+ links)', game:'chain', check:(_g,_s,m) => m.rank === 'Mythic' },
// LetterLock
{ id:'ll_lock', icon:'🔒', label:'Letter Locked', desc:'Find a 7+ letter word in LetterLock', game:'letterlock', check:(_g,_s,m) => m.bestWord && m.bestWord.length >= 7 },
{ id:'ll_30', icon:'📖', label:'Letter Legend', desc:'Score 30+ points in LetterLock', game:'letterlock', check:(_g,s) => s >= 30 },
{ id:'ll_10words', icon:'📚', label:'Vocab King', desc:'Find 10+ words in LetterLock', game:'letterlock', check:(_g,_s,m) => (m.wordsFound||0) >= 10 },
];
// ── Styles ────────────────────────────────────────────────────────────────────
const PANEL_CSS = `
#ba-sheet {
position: fixed; bottom: 0; left: 50%;
transform: translateX(-50%) translateY(110%);
width: min(480px, 100vw); z-index: 9999;
background: #0f172a;
border: 1px solid rgba(99,102,241,.35); border-bottom: none;
border-radius: 16px 16px 0 0;
box-shadow: 0 -12px 48px rgba(0,0,0,.6);
transition: transform .35s cubic-bezier(.32,1.02,.68,1);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
color: #e2e8f0; font-size: 14px;
}
#ba-sheet.ba-open { transform: translateX(-50%) translateY(0); }
#ba-inner { padding: 18px 20px 24px; }
#ba-header {
display: flex; justify-content: space-between; align-items: center;
font-weight: 700; font-size: 15px; margin-bottom: 8px; color: #a5b4fc;
}
#ba-close {
background: none; border: none; color: #64748b; cursor: pointer;
font-size: 16px; padding: 2px 6px; border-radius: 4px; line-height: 1;
}
#ba-close:hover { color: #e2e8f0; background: rgba(255,255,255,.07); }
#ba-streak-row {
display: flex; gap: 14px; align-items: center;
font-size: 12px; color: #94a3b8; margin-bottom: 14px;
}
#ba-streak-row .ba-fire { color: #f97316; font-weight: 700; }
#ba-submit-row { display: flex; gap: 8px; margin-bottom: 8px; }
#ba-name {
flex: 1; background: #1e293b; border: 1px solid rgba(99,102,241,.3);
border-radius: 8px; color: #e2e8f0; padding: 8px 12px;
font-size: 14px; outline: none;
}
#ba-name:focus { border-color: #6366f1; }
#ba-btn {
background: #6366f1; border: none; border-radius: 8px; color: #fff;
cursor: pointer; font-size: 14px; font-weight: 700;
padding: 8px 18px; transition: background .15s; white-space: nowrap;
}
#ba-btn:hover:not(:disabled) { background: #4f46e5; }
#ba-btn:disabled { opacity: .5; cursor: default; }
#ba-status { font-size: 12px; min-height: 18px; margin-bottom: 10px; }
.ba-section-title {
font-size: 11px; font-weight: 700; letter-spacing: .08em;
text-transform: uppercase; color: #64748b; margin-bottom: 8px;
}
.ba-row {
display: flex; align-items: center; gap: 10px;
padding: 7px 0; border-bottom: 1px solid rgba(255,255,255,.05);
}
.ba-row:last-child { border-bottom: none; }
.ba-rank { width: 28px; font-size: 15px; flex-shrink: 0; }
.ba-pname { flex: 1; color: #cbd5e1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ba-score { color: #a5b4fc; font-weight: 700; flex-shrink: 0; }
.ba-msg { color: #64748b; font-size: 13px; padding: 8px 0; }
#ba-badges-wrap { margin-top: 16px; padding-top: 14px; border-top: 1px solid rgba(255,255,255,.06); }
.ba-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
.ba-chip {
font-size: 18px; padding: 5px 7px; border-radius: 8px;
background: rgba(255,255,255,.05); border: 1px solid rgba(255,255,255,.08);
cursor: default; transition: transform .1s; line-height: 1;
}
.ba-chip:hover { transform: scale(1.2); }
.ba-chip-new { border-color: rgba(99,102,241,.6); background: rgba(99,102,241,.12); }
#ba-full-link {
display: block; text-align: center; margin-top: 16px;
color: #6366f1; text-decoration: none; font-size: 13px;
}
#ba-full-link:hover { text-decoration: underline; }
/* Badge toast */
.ba-toast {
position: fixed; top: -90px; left: 50%;
transform: translateX(-50%);
background: #1e293b; border: 1px solid rgba(99,102,241,.5);
border-radius: 14px; padding: 12px 18px;
display: flex; align-items: center; gap: 12px;
box-shadow: 0 8px 32px rgba(0,0,0,.6);
z-index: 10001; min-width: 240px; max-width: 340px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
transition: top .4s cubic-bezier(.32,1.02,.68,1);
pointer-events: none;
}
.ba-toast.ba-toast-in { top: 16px; }
.ba-toast-icon { font-size: 2rem; flex-shrink: 0; line-height: 1; }
.ba-toast-eyebrow { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .1em; color: #6366f1; }
.ba-toast-name { font-size: 14px; font-weight: 700; color: #e2e8f0; }
.ba-toast-desc { font-size: 11px; color: #94a3b8; margin-top: 2px; }
`;
// ── Firebase ──────────────────────────────────────────────────────────────────
let db = null;
function initFirebase() {
const cfg = window.FIREBASE_CONFIG;
if (!cfg || cfg.apiKey === 'YOUR_API_KEY') return;
try {
if (!firebase.apps.length) firebase.initializeApp(cfg);
db = firebase.firestore();
} catch (e) {
console.warn('[BA] Firebase init failed:', e);
}
}
// ── GA4 ───────────────────────────────────────────────────────────────────────
function initGA4() {
const mid = (window.GA_MEASUREMENT_ID && window.GA_MEASUREMENT_ID !== 'G-XXXXXXXXXX')
? window.GA_MEASUREMENT_ID
: (window.FIREBASE_CONFIG && window.FIREBASE_CONFIG.measurementId) || null;
if (!mid) return;
window.dataLayer = window.dataLayer || [];
window.gtag = function () { dataLayer.push(arguments); };
gtag('js', new Date());
gtag('config', mid);
const s = document.createElement('script');
s.async = true;
s.src = 'https://www.googletagmanager.com/gtag/js?id=' + mid;
document.head.appendChild(s);
}
function sendEvent(name, params) {
if (typeof window.gtag === 'function') gtag('event', name, params);
}
// ── Firestore helpers ─────────────────────────────────────────────────────────
function colRef(game) {
return db.collection('leaderboards').doc(game).collection('scores');
}
async function submitScore(game, playerName, score, meta) {
await colRef(game).add({
playerName: escHtml(playerName.trim().slice(0, 20)) || 'Anonymous',
score,
game,
metadata: meta || {},
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
sendEvent('score_submitted', { game_name: game, score });
}
async function fetchTop(game, limit) {
const cfg = GAMES[game] || {};
let q = colRef(game).orderBy('score', cfg.lower ? 'asc' : 'desc').limit(limit || 5);
if (game === 'wordle') q = colRef(game).where('score', '<', 99).orderBy('score', 'asc').limit(limit || 5);
const snap = await q.get();
return snap.docs.map(d => d.data());
}
// ── Streak ────────────────────────────────────────────────────────────────────
function getStreakData() {
return {
streak: parseInt(localStorage.getItem('ba_streak_count') || '0'),
maxStreak: parseInt(localStorage.getItem('ba_streak_max') || '0'),
lastDate: localStorage.getItem('ba_streak_last') || '',
gamesPlayed: parseInt(localStorage.getItem('ba_games_played') || '0'),
};
}
function updateStreak() {
const today = new Date().toISOString().slice(0, 10);
const data = getStreakData();
const newPlayed = data.gamesPlayed + 1;
localStorage.setItem('ba_games_played', newPlayed);
if (data.lastDate === today) {
return { ...data, gamesPlayed: newPlayed };
}
const prev = new Date();
prev.setDate(prev.getDate() - 1);
const yesterday = prev.toISOString().slice(0, 10);
const newStreak = data.lastDate === yesterday ? data.streak + 1 : 1;
const newMax = Math.max(data.maxStreak, newStreak);
localStorage.setItem('ba_streak_last', today);
localStorage.setItem('ba_streak_count', newStreak);
localStorage.setItem('ba_streak_max', newMax);
return { streak: newStreak, maxStreak: newMax, lastDate: today, gamesPlayed: newPlayed };
}
// ── Badges ────────────────────────────────────────────────────────────────────
function getEarnedIds() {
return new Set(JSON.parse(localStorage.getItem('ba_badges') || '[]'));
}
function awardBadges(game, score, meta, streakData) {
const earned = getEarnedIds();
const newOnes = [];
for (const b of BADGES) {
if (earned.has(b.id)) continue;
if (b.game !== 'any' && b.game !== game) continue;
if (b.check(game, score, meta, streakData)) {
earned.add(b.id);
newOnes.push(b);
}
}
if (newOnes.length) {
localStorage.setItem('ba_badges', JSON.stringify([...earned]));
}
return newOnes;
}
// ── Badge toast ───────────────────────────────────────────────────────────────
let toastQueue = [];
let toastBusy = false;
function showNextToast() {
if (toastBusy || !toastQueue.length) return;
toastBusy = true;
const b = toastQueue.shift();
const el = document.createElement('div');
el.className = 'ba-toast';
el.innerHTML = `
<div class="ba-toast-icon">${b.icon}</div>
<div>
<div class="ba-toast-eyebrow">Badge Unlocked!</div>
<div class="ba-toast-name">${b.label}</div>
<div class="ba-toast-desc">${b.desc}</div>
</div>
`;
document.body.appendChild(el);
requestAnimationFrame(() => el.classList.add('ba-toast-in'));
setTimeout(() => {
el.classList.remove('ba-toast-in');
setTimeout(() => {
el.remove();
toastBusy = false;
showNextToast();
}, 450);
}, 3000);
}
function queueBadgeToasts(badges) {
toastQueue.push(...badges);
showNextToast();
}
// ── Helpers ───────────────────────────────────────────────────────────────────
function fmtScore(game, score) {
if (game === 'wordle') return score < 99 ? score + ' tries' : 'DNF';
if (game === '2048') return Number(score).toLocaleString() + ' pts';
if (game === 'grid') return score + ' / 49';
if (game === 'chain') return score + ' links';
return score + ' pts';
}
function escHtml(s) {
return String(s).replace(/[&<>"']/g, c =>
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])
);
}
function rankBadge(i) {
return i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `#${i + 1}`;
}
// ── Panel UI ──────────────────────────────────────────────────────────────────
function injectStyles() {
if (document.getElementById('ba-styles')) return;
const el = document.createElement('style');
el.id = 'ba-styles';
el.textContent = PANEL_CSS;
document.head.appendChild(el);
}
async function renderLeaderboard(game) {
const list = document.getElementById('ba-lb-list');
if (!list) return;
if (!db) {
list.innerHTML = '<div class="ba-msg">Configure Firebase in firebase-config.js to enable leaderboards.</div>';
return;
}
list.innerHTML = '<div class="ba-msg">Loading…</div>';
try {
const rows = await fetchTop(game, 5);
if (!rows.length) {
list.innerHTML = '<div class="ba-msg">No scores yet — be the first!</div>';
return;
}
list.innerHTML = rows.map((r, i) => `
<div class="ba-row">
<span class="ba-rank">${rankBadge(i)}</span>
<span class="ba-pname">${escHtml(r.playerName)}</span>
<span class="ba-score">${fmtScore(game, r.score)}</span>
</div>
`).join('');
} catch (e) {
list.innerHTML = '<div class="ba-msg">Could not load scores.</div>';
}
}
function renderBadgesSection(newIds) {
const wrap = document.getElementById('ba-badges-wrap');
if (!wrap) return;
const earned = [...getEarnedIds()];
if (!earned.length) { wrap.style.display = 'none'; return; }
const earnedBadges = BADGES.filter(b => earned.includes(b.id));
wrap.style.display = '';
wrap.innerHTML = `
<div class="ba-section-title">Your Badges (${earnedBadges.length}/${BADGES.length})</div>
<div class="ba-chips">
${earnedBadges.map(b => `
<span class="ba-chip${newIds.has(b.id) ? ' ba-chip-new' : ''}" title="${b.label}: ${b.desc}">${b.icon}</span>
`).join('')}
</div>
`;
}
function showPanel(game, score, meta, streakData, newBadges) {
injectStyles();
const existing = document.getElementById('ba-sheet');
if (existing) existing.remove();
const cfg = GAMES[game] || { label: game, icon: '🎮' };
const newIds = new Set(newBadges.map(b => b.id));
const streakTxt = streakData.streak > 0
? `<span class="ba-fire">🔥 ${streakData.streak}-day streak</span><span>Best: ${streakData.maxStreak}</span>`
: '';
const sheet = document.createElement('div');
sheet.id = 'ba-sheet';
sheet.innerHTML = `
<div id="ba-inner">
<div id="ba-header">
<span>${cfg.icon} ${cfg.label} — ${fmtScore(game, score)}</span>
<button id="ba-close" aria-label="Close">✕</button>
</div>
${streakTxt ? `<div id="ba-streak-row">${streakTxt}</div>` : ''}
<div id="ba-submit-row">
<input id="ba-name" type="text" placeholder="Your name" maxlength="20" autocomplete="off" spellcheck="false">
<button id="ba-btn">Submit</button>
</div>
<div id="ba-status"></div>
<div class="ba-section-title">Top 5</div>
<div id="ba-lb-list"></div>
<div id="ba-badges-wrap"></div>
<a href="leaderboard.html" id="ba-full-link">View full leaderboard →</a>
</div>
`;
document.body.appendChild(sheet);
const nameEl = document.getElementById('ba-name');
const btnEl = document.getElementById('ba-btn');
const statusEl = document.getElementById('ba-status');
nameEl.value = localStorage.getItem('ba_player_name') || '';
document.getElementById('ba-close').onclick = () => sheet.remove();
btnEl.onclick = async () => {
if (!db) {
statusEl.style.color = '#f43f5e';
statusEl.textContent = 'Firebase not configured yet.';
return;
}
const name = nameEl.value.trim() || 'Anonymous';
btnEl.disabled = true;
btnEl.textContent = '…';
try {
await submitScore(game, name, score, meta);
localStorage.setItem('ba_player_name', name);
statusEl.style.color = '#10b981';
statusEl.textContent = '✓ Score submitted!';
renderLeaderboard(game);
} catch (e) {
statusEl.style.color = '#f43f5e';
statusEl.textContent = 'Submission failed — try again.';
btnEl.disabled = false;
btnEl.textContent = 'Submit';
}
};
requestAnimationFrame(() => sheet.classList.add('ba-open'));
renderLeaderboard(game);
renderBadgesSection(newIds);
}
// ── Public API ────────────────────────────────────────────────────────────────
window.Analytics = {
trackGameEnd(game, score, meta) {
const streakData = updateStreak();
const newBadges = awardBadges(game, score, meta || {}, streakData);
sendEvent('game_end', { game_name: game, score, ...(meta || {}), streak: streakData.streak });
// Show badge toasts first, then panel after a short delay
if (newBadges.length) {
setTimeout(() => queueBadgeToasts(newBadges), 400);
}
setTimeout(() => {
injectStyles();
showPanel(game, score, meta || {}, streakData, newBadges);
}, 1200);
},
// Exposed for leaderboard.html
fetchTop,
fmtScore,
escHtml,
rankBadge,
GAMES,
BADGES,
getStreakData,
getEarnedIds,
getDb() { return db; },
};
initFirebase();
initGA4();
})();