-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
4786 lines (4569 loc) · 218 KB
/
Copy pathapp.js
File metadata and controls
4786 lines (4569 loc) · 218 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// A+ Study — single-file PWA logic
// Modules: State, DB, Study, Quiz, Reading, Stats, ScratchPad, Router
import {
MIN,
defaultProgress, migrateProgress, schedule,
escapeHtml, normalizeOption, formatExplanation, formatQuestion,
orderDeck, nextIntervalLabel, /* recommendedRating no longer used in UI; kept in lib.mjs + tests */
shuffleOptionsForCard, isSafeImageSrc, isSafeLearnMoreUrl,
} from './lib.mjs';
import {
randomSaltB64, deriveKey, encryptJSON, decryptJSON, isEncryptedBlob,
makeVerificationBlob, verifyPin, CRYPTO_DEFAULTS,
} from './crypto.mjs';
import {
state, $, $$, pref, setPref, applyPrefs,
isDue, haptic, toast, lsSet, announce,
trapFocus, setAppInert, restoreFocusAfterRender,
} from './core.mjs';
import { celebrate } from './confetti.mjs';
import { setSound } from './focus-sound.mjs';
import { installImageZoom } from './image-zoom.mjs';
import { acquireWakeLock, releaseWakeLock, installWakeLock } from './wake-lock.mjs';
import { initReadAloud, stopSpeaking, installListenButton } from './read-aloud.mjs';
import { initShake, enableShake, disableShake } from './shake.mjs';
import {
STORE, OSTORE, DSTORE, RSTORE,
openDB, idbGet, idbPut,
loadProgress, saveProgress, clearProgress,
loadOverrides, saveOverrides, loadExamEvents, saveExamEvents,
} from './storage.mjs';
import { renderScratchpadHTML, attachScratchpadEvents } from './scratchpad.mjs';
import { initSync, scheduleAutoSync, syncStatusLine, showSync, updateSyncBadge } from './sync.mjs';
// PINs set before the iteration count was raised to 600k stored (or implied)
// 310k. Derive existing setups at their recorded count so a bump never locks
// anyone out; new setups below are saved at the current default.
const LEGACY_PBKDF2_ITERATIONS = 310_000;
//─── EXAMS (multi-dataset support) ──────────────────────────
// Each exam has its own questions + concept-fixes file, and its own
// progress/overrides rows in IndexedDB, keyed by id. Adding a new exam
// is just: drop files in data/<id>/ and add an entry here.
const EXAMS = {
core2: {
id: 'core2',
label: 'Core 2 (220-1202)',
questions: 'data/core2/questions.json',
fixes: 'data/core2/concept-fixes.json',
},
};
const EXAM_IDS = Object.keys(EXAMS);
function examDef(id) { return EXAMS[id] || EXAMS.core2; }
// Exam target date (ISO yyyy-mm-dd) per exam. Used to drive the header
// countdown and the urgency styling on the welcome screen.
function getExamDate(examId) {
return localStorage.getItem(`exam.${examId}.date`) || '';
}
function setExamDate(examId, iso) {
if (!iso) localStorage.removeItem(`exam.${examId}.date`);
else lsSet(`exam.${examId}.date`, iso);
}
function daysUntilExam(examId = state?.exam) {
const iso = getExamDate(examId);
if (!iso) return null;
const [y, m, d] = iso.split('-').map(Number);
if (!y || !m || !d) return null;
const target = new Date(y, m - 1, d);
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
return Math.round((target - today) / (24 * 60 * 60 * 1000));
}
//─── DAILY ACTIVITY (heatmap source) ─────────────────────────
function bumpActivity() {
try {
const a = getActivity();
const k = todayKey();
a[k] = (a[k] || 0) + 1;
// Prune anything older than 180 days — the heatmap only shows 90
const cutoff = new Date(); cutoff.setDate(cutoff.getDate() - 180);
const cutoffKey = `${cutoff.getFullYear()}-${String(cutoff.getMonth()+1).padStart(2,'0')}-${String(cutoff.getDate()).padStart(2,'0')}`;
for (const key of Object.keys(a)) if (key < cutoffKey) delete a[key];
lsSet('activity', JSON.stringify(a));
} catch {}
}
function getActivity() {
try { return JSON.parse(localStorage.getItem('activity') || '{}'); }
catch { return {}; }
}
//─── CELEBRATION TRIGGERS (objective mastery + streak milestones) ───
const STREAK_MILESTONES = [3, 7, 14, 30, 60, 100];
function celebratedFlag(key) {
try { return !!JSON.parse(localStorage.getItem('celebrated') || '{}')[key]; }
catch { return false; }
}
function markCelebrated(key) {
try {
const c = JSON.parse(localStorage.getItem('celebrated') || '{}');
c[key] = true;
lsSet('celebrated', JSON.stringify(c));
} catch {}
}
function checkObjectiveMastered(obj) {
if (!obj || obj === '?') return false;
const qs = state.questions.filter(q => q.obj === obj);
if (qs.length === 0) return false;
return qs.every(q => state.progress[q.id]?.status === 'good');
}
function maybeFireObjectiveCelebration(obj) {
if (!obj) return;
const key = `obj:${state.exam}:${obj}`;
if (celebratedFlag(key)) return;
if (!checkObjectiveMastered(obj)) return;
markCelebrated(key);
celebrate({ intensity: 45, duration: 1700 });
toast(`🎉 Objective ${obj} mastered — every card rated Good.`, 'success', 5000);
}
function maybeFireStreakCelebration(newCount) {
for (const n of STREAK_MILESTONES) {
if (newCount !== n) continue;
const key = `streak:${n}`;
if (celebratedFlag(key)) return;
markCelebrated(key);
celebrate({ intensity: 50, duration: 1800 });
toast(`🔥 ${n}-day streak. You keep showing up.`, 'success', 5500);
return;
}
}
// GitHub-style heatmap of daily cards-rated for the last 90 days. Columns
// are weeks; rows are days of the week. Color intensity bands mirror the
// GitHub scale so it feels familiar.
// Quiz history chart: small inline SVG line/dot of scores per session.
// Rendered into Stats so users see whether they're trending up. Empty state
// (no sessions yet) returns '' — no UI noise until there's data to show.
function renderQuizHistoryHTML() {
const history = loadQuizHistory();
if (history.length === 0) return '';
const W = 300, H = 110, PAD_L = 28, PAD_R = 8, PAD_T = 10, PAD_B = 22;
const innerW = W - PAD_L - PAD_R;
const innerH = H - PAD_T - PAD_B;
const n = history.length;
const x = (i) => n === 1 ? PAD_L + innerW / 2 : PAD_L + (i / (n - 1)) * innerW;
const y = (score) => PAD_T + (1 - score / 100) * innerH;
const points = history.map((e, i) => `${x(i).toFixed(1)},${y(e.score).toFixed(1)}`).join(' ');
const dots = history.map((e, i) =>
`<circle cx="${x(i).toFixed(1)}" cy="${y(e.score).toFixed(1)}" r="3.5" fill="${e.score >= 75 ? 'var(--good)' : 'var(--bad)'}" />`
).join('');
// 75% pass-line
const passY = y(75).toFixed(1);
const best = Math.max(...history.map(e => e.score));
const avg = Math.round(history.reduce((s, e) => s + e.score, 0) / history.length);
const last = history[history.length - 1];
return `
<h3 class="stats-h numeric-ui">Quiz history</h3>
<div class="quiz-history numeric-ui">
<div class="qh-meta">
<div class="qh-stat"><span class="qh-num">${history.length}</span><span class="qh-label">sessions</span></div>
<div class="qh-stat"><span class="qh-num">${best}%</span><span class="qh-label">best</span></div>
<div class="qh-stat"><span class="qh-num">${avg}%</span><span class="qh-label">avg</span></div>
<div class="qh-stat"><span class="qh-num">${last.score}%</span><span class="qh-label">last</span></div>
</div>
<svg class="qh-chart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="Quiz score history">
<line x1="${PAD_L}" y1="${passY}" x2="${W - PAD_R}" y2="${passY}" stroke="var(--good)" stroke-width="1" stroke-dasharray="4 3" opacity="0.5" />
<text x="${W - PAD_R - 2}" y="${(parseFloat(passY) - 3).toFixed(1)}" font-size="9" fill="var(--text-dim)" text-anchor="end">75% pass</text>
<text x="${PAD_L - 4}" y="${(PAD_T + 6).toFixed(1)}" font-size="9" fill="var(--text-dim)" text-anchor="end">100</text>
<text x="${PAD_L - 4}" y="${(PAD_T + innerH + 3).toFixed(1)}" font-size="9" fill="var(--text-dim)" text-anchor="end">0</text>
${n > 1 ? `<polyline points="${points}" fill="none" stroke="var(--accent)" stroke-width="1.5" />` : ''}
${dots}
</svg>
</div>`;
}
function renderHeatmapHTML() {
const activity = getActivity();
const DAYS = 90;
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// Align the last column to today; walk backwards by `DAYS` days, padding
// with blank cells so the first column is a full Sun–Sat.
const cells = [];
for (let i = DAYS - 1; i >= 0; i--) {
const d = new Date(today);
d.setDate(today.getDate() - i);
const key = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const count = activity[key] || 0;
cells.push({ key, count, d });
}
// Pad at the start so the first cell lands on a Sunday column
const firstDow = cells[0].d.getDay();
const padded = Array.from({ length: firstDow }, () => null).concat(cells);
// Break into columns of 7
const cols = [];
for (let i = 0; i < padded.length; i += 7) cols.push(padded.slice(i, i + 7));
const level = (n) =>
n === 0 ? 0 :
n < 3 ? 1 :
n < 8 ? 2 :
n < 20 ? 3 : 4;
const total = Object.values(activity).reduce((s, n) => s + n, 0);
const activeDays = Object.values(activity).filter(n => n > 0).length;
return `
<div class="heatmap">
<div class="heatmap-grid" role="img" aria-label="${total} cards rated across ${activeDays} active days in the last 90 days">
${cols.map(col => `
<div class="heatmap-col">
${col.map(cell => cell
? `<div class="heatmap-cell" data-lvl="${level(cell.count)}" title="${cell.key} · ${cell.count} card${cell.count === 1 ? '' : 's'}"></div>`
: `<div class="heatmap-cell heatmap-cell-empty" aria-hidden="true"></div>`
).join('')}
</div>
`).join('')}
</div>
<div class="heatmap-legend">
<span>${total} cards · ${activeDays} active day${activeDays === 1 ? '' : 's'}</span>
<span class="heatmap-scale">
less
<span class="heatmap-cell" data-lvl="0"></span>
<span class="heatmap-cell" data-lvl="1"></span>
<span class="heatmap-cell" data-lvl="2"></span>
<span class="heatmap-cell" data-lvl="3"></span>
<span class="heatmap-cell" data-lvl="4"></span>
more
</span>
</div>
</div>`;
}
//─── SESSION (Pomodoro or card-count micro-goal) ─────────────
// Cram session: walks through every card in the current filter once, then
// loops anything you rated Again/Hard back through the queue until cleared.
// Designed for crunch-time studying when you have a deadline and can't trust
// the spaced-repetition queue to surface unseen cards.
function startCram() {
const qs = state.questions.slice();
// Shuffle once for variety
const seed = (Date.now() & 0x7fffffff) || 1;
const rng = (function (s) { let t = s >>> 0; return () => { t += 0x6D2B79F5; let r = t; r = Math.imul(r ^ (r >>> 15), r | 1); r ^= r + Math.imul(r ^ (r >>> 7), r | 61); return ((r ^ (r >>> 14)) >>> 0) / 4294967296; }; })(seed);
const queue = qs.map(q => q.id);
for (let i = queue.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[queue[i], queue[j]] = [queue[j], queue[i]];
}
state.cram = {
active: true,
startedAt: Date.now(),
queue,
originalCount: queue.length,
cleared: 0,
};
// Cram clears all filters and uses sequential order so the queue is the
// single source of truth for what's shown.
state.filter = { obj: null, due: false, weakest: false, hard: false, search: '' };
state.currentIndex = 0;
state.history = [];
state._orderCache = null;
setMode('study');
toast(`Cram started — ${queue.length} cards. Rate Good/Easy to clear; Again/Hard loops them back.`, 'info', 4500);
}
function endCram(announce = true) {
if (!state.cram) return;
const { cleared, originalCount } = state.cram;
state.cram = null;
state.currentIndex = 0;
state._orderCache = null;
if (announce) toast(`Cram ended — cleared ${cleared} of ${originalCount}.`, 'success');
if (state.mode === 'study') renderStudy();
}
// Called from recordRating when cram is active. Updates the queue based on
// the user's rating: Good/Easy clears the card, Again/Hard sends it to the
// back. When the queue empties, we celebrate and end the session.
function onCramRated(qid, rate) {
if (!state.cram || !state.cram.active) return;
const q = state.cram.queue;
const idx = q.indexOf(qid);
if (idx === -1) return; // already cleared on a previous pass
q.splice(idx, 1);
if (rate === 'good' || rate === 'easy') {
state.cram.cleared++;
} else {
q.push(qid);
}
if (q.length === 0) {
// Capture count + cram-instance reference before the timer fires.
// state.cram may be null'd by an end-now tap or a switchExam in the
// 200 ms window (which would throw on .originalCount), OR replaced
// with a NEW cram if the user restarts immediately — which would
// have us endCram() the wrong instance. Compare identity at fire
// time and bail if it doesn't match.
const total = state.cram.originalCount;
const cramRef = state.cram;
celebrate({ intensity: 80, duration: 2200 });
setTimeout(() => {
if (state.cram !== cramRef) return; // user already moved on
toast(`🎉 Cram complete — all ${total} cards cleared!`, 'success', 5000);
endCram(false);
}, 200);
}
}
function startSession({ minutes = 0, targetCards = 0, rapid = false } = {}) {
state.session = {
endsAt: minutes > 0 ? Date.now() + minutes * MIN : null,
targetCards: targetCards > 0 ? targetCards : null,
ratedIds: new Set(),
length: minutes,
rapid,
targetDesc: rapid
? '⚡ 60s rapid fire'
: targetCards > 0 ? `${targetCards} card${targetCards === 1 ? '' : 's'}` : `${minutes} min`,
};
if (state._sessionTick) clearInterval(state._sessionTick);
if (minutes > 0) {
state._sessionTick = setInterval(() => {
if (!state.session) return;
if (Date.now() >= state.session.endsAt) endSession(true);
else updateHUD();
}, 1000);
}
updateHUD();
}
function endSession(triggerSummary) {
if (state._sessionTick) { clearInterval(state._sessionTick); state._sessionTick = null; }
const sess = state.session;
state.session = null;
updateHUD();
if (triggerSummary && sess) {
const reviewed = sess.ratedIds.size;
const msg = reviewed === 0
? `Session done. No cards rated this time — that's OK, sometimes just showing up is the win.`
: sess.rapid
? `⚡ ${reviewed} card${reviewed === 1 ? '' : 's'} in 60 seconds. Nice sprint.`
: `Session done. ${reviewed} card${reviewed === 1 ? '' : 's'} reviewed. 🎉`;
haptic([80, 60, 80]);
if (reviewed > 0) celebrate({ intensity: sess.rapid ? 50 : 36, duration: 1600 });
toast(msg, 'success', 5000);
}
}
function onCardRated(qid) {
if (state.session) {
state.session.ratedIds.add(qid);
// Card-count micro-goal reached → end naturally
if (state.session.targetCards && state.session.ratedIds.size >= state.session.targetCards) {
endSession(true);
}
}
bumpStreak();
bumpActivity();
// Celebrate when this rating just pushed an objective to full mastery
const q = state.questions.find(x => x.id === qid);
if (q) maybeFireObjectiveCelebration(q.obj);
scheduleAutoSync();
}
//─── DAILY STREAK ────────────────────────────────────────────
function todayKey() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}
// Minimum cards rated before today counts as a streak day. Tying the
// streak to real retrieval — not a single "tap to keep the flame" —
// makes the habit signal more honest. 3 is small enough to feel
// achievable, big enough to require actual recall practice.
const STREAK_MIN_CARDS = 3;
function bumpStreak() {
const today = todayKey();
const lastEarned = localStorage.getItem('streak.lastDay');
// Reset today's counter if the calendar day rolled over since it was set.
const cardsDay = localStorage.getItem('streak.cardsDay');
let cardsToday = Number(localStorage.getItem('streak.todayCards') || '0');
if (cardsDay !== today) {
cardsToday = 0;
lsSet('streak.cardsDay', today);
}
cardsToday += 1;
lsSet('streak.todayCards', String(cardsToday));
if (cardsToday < STREAK_MIN_CARDS) return; // threshold not met
if (lastEarned === today) return; // already earned today
// Earn today: compute new count from prior earned day.
let count = Number(localStorage.getItem('streak.count') || '0');
if (lastEarned) {
const [ly, lm, ld] = lastEarned.split('-').map(Number);
const lastDate = new Date(ly, lm - 1, ld);
const now = new Date();
const y = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const diffDays = Math.round((y - lastDate) / (24*60*60*1000));
if (diffDays === 1) {
count = count + 1; // streak continues
} else if (diffDays === 0 || diffDays === -1) {
// diffDays=0: edge case (today === lastEarned but lastEarned !==
// today check passed before reaching here — possible during a clock
// adjustment); preserve count.
// diffDays=-1: user crossed an international date line backwards
// OR system clock just adjusted backward by ~24h. Preserve count
// rather than punish a traveler / NTP-correcting device.
count = Math.max(1, count);
} else {
// diffDays >= 2: real gap, reset.
// diffDays <= -2: clock jumped backwards by multiple days — likely
// wrong-clock state, also reset to 1 so we don't double-credit.
count = 1;
}
} else {
count = 1;
}
lsSet('streak.lastDay', today);
lsSet('streak.count', String(count));
// Subtle celebration the first time the threshold is crossed today.
toast(`🔥 ${count}-day streak — today's earned.`, 'success', 2500);
maybeFireStreakCelebration(count);
}
function getStreak() {
const last = localStorage.getItem('streak.lastDay');
const count = Number(localStorage.getItem('streak.count') || '0');
const today = todayKey();
// If last day wasn't yesterday or today, streak is effectively 0 now
if (!last) return { count: 0, today: 0 };
const [ly, lm, ld] = last.split('-').map(Number);
const lastDate = new Date(ly, lm - 1, ld);
const now = new Date();
const y = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const diffDays = Math.round((y - lastDate) / (24*60*60*1000));
const active = diffDays <= 1;
return {
count: active ? count : 0,
today: last === today ? Number(localStorage.getItem('streak.todayCards') || '0') : 0,
};
}
function cardsRatedToday() {
return getStreak().today;
}
//─── PIN LOCK (AES-GCM at-rest encryption) ───────────────────
// Setup metadata lives in localStorage under `pin.setup` as
// { v: 1, salt: b64, iterations: N, verification: { v, iv, ct } }
// The derived key is held in memory only (state._cryptoKey) for the
// current session; closing the app drops it and requires re-unlock.
const PIN_SETUP_KEY = 'pin.setup';
function getPinSetup() {
try {
const raw = localStorage.getItem(PIN_SETUP_KEY);
return raw ? JSON.parse(raw) : null;
} catch { return null; }
}
function savePinSetup(setup) { lsSet(PIN_SETUP_KEY, JSON.stringify(setup)); }
function clearPinSetup() { localStorage.removeItem(PIN_SETUP_KEY); }
function isPinSet() { return !!getPinSetup(); }
//─── EXAM-OUTCOME LOG (PR #67) ───────────────────────────────
// load/saveExamEvents live in storage.mjs (with the full ExamEvent shape
// doc). The value stored per exam is an ARRAY of events; calibration metrics
// only compute meaningfully at n >= 3 per the WWC SCED standard surfaced by
// the metacognition research, below which the UI labels the data 'anecdotal'.
async function appendExamEvent(event) {
const list = await loadExamEvents();
list.push(event);
await saveExamEvents(list);
return list;
}
// Compute calibration metrics on the events that have both pre.predictedReadinessPct
// and post.actualScorePct. Returns null when n < 3 — the threshold the
// metacognition research flagged as the WWC single-case-design floor
// for "without reservations."
function computeCalibrationMetrics(events) {
const ws = events.filter(e => e?.pre?.predictedReadinessPct != null && e?.post?.actualScorePct != null);
if (ws.length < 3) return null;
const diffs = ws.map(e => e.pre.predictedReadinessPct - e.post.actualScorePct);
const signedBias = diffs.reduce((s, d) => s + d, 0) / diffs.length;
const mae = diffs.reduce((s, d) => s + Math.abs(d), 0) / diffs.length;
// Brier-style component for the "are they expected to pass?" prediction.
// Treats predicted probability of pass as predicted/100, outcome as 0/1.
const brierItems = ws.filter(e => e.post.passed !== undefined);
const brier = brierItems.length === 0 ? null
: brierItems.reduce((s, e) => {
const p = (e.pre.predictedReadinessPct || 0) / 100;
const o = e.post.passed ? 1 : 0;
return s + (p - o) * (p - o);
}, 0) / brierItems.length;
return { n: ws.length, signedBias, mae, brier };
}
async function hydrateOutcomesPanel() {
const host = $('#outcomes-panel');
if (!host) return;
let events;
try { events = await loadExamEvents(); }
catch (e) { if (e.message === 'locked') { host.innerHTML = '<p class="outcomes-empty">Unlock with your PIN to view the outcome log.</p>'; return; } events = []; }
// Compute calibration stats only when we have ≥3 attempts. Below that
// threshold, the metacognition research's punchline applies: anything
// we'd display is anecdotal, so just say so honestly.
const metrics = computeCalibrationMetrics(events);
const n = events.length;
// Calibration scatter — a tiny SVG showing predicted vs actual %.
// Diagonal = perfect calibration. Above = under-confident; below =
// over-confident. One dot per attempt; pass/fail tints the dot.
const SVG_SIZE = 240, PAD = 24;
const dots = events.map(e => {
const p = e?.pre?.predictedReadinessPct;
const a = e?.post?.actualScorePct;
if (p == null || a == null) return '';
const x = PAD + (p / 100) * (SVG_SIZE - 2 * PAD);
const y = SVG_SIZE - PAD - (a / 100) * (SVG_SIZE - 2 * PAD);
const tint = e.post.passed ? 'var(--good)' : 'var(--bad)';
return `<circle cx="${x}" cy="${y}" r="5" fill="${tint}" stroke="var(--surface)" stroke-width="2"></circle>`;
}).join('');
const scatter = `
<svg viewBox="0 0 ${SVG_SIZE} ${SVG_SIZE}" class="outcome-scatter" role="img" aria-label="Predicted vs actual exam scores">
<rect x="${PAD}" y="${PAD}" width="${SVG_SIZE-2*PAD}" height="${SVG_SIZE-2*PAD}" fill="var(--surface-2)" stroke="var(--border)" />
<line x1="${PAD}" y1="${SVG_SIZE-PAD}" x2="${SVG_SIZE-PAD}" y2="${PAD}" stroke="var(--border)" stroke-dasharray="3,3" />
<text x="${SVG_SIZE/2}" y="${SVG_SIZE-4}" text-anchor="middle" font-size="10" fill="var(--text-dim)">predicted readiness %</text>
<text x="6" y="${SVG_SIZE/2}" text-anchor="middle" font-size="10" fill="var(--text-dim)" transform="rotate(-90, 6, ${SVG_SIZE/2})">actual score %</text>
${dots}
</svg>`;
const metricsHTML = metrics ? `
<div class="outcome-metrics">
<div class="outcome-metric"><div class="outcome-metric-label">Mean signed bias</div><div class="outcome-metric-value ${metrics.signedBias > 5 ? 'over' : metrics.signedBias < -5 ? 'under' : ''}">${metrics.signedBias > 0 ? '+' : ''}${metrics.signedBias.toFixed(1)}%</div><div class="outcome-metric-help">${metrics.signedBias > 5 ? 'overconfident' : metrics.signedBias < -5 ? 'underconfident' : 'well-calibrated'}</div></div>
<div class="outcome-metric"><div class="outcome-metric-label">Mean absolute error</div><div class="outcome-metric-value">${metrics.mae.toFixed(1)}%</div><div class="outcome-metric-help">avg |pred − actual|</div></div>
${metrics.brier != null ? `<div class="outcome-metric"><div class="outcome-metric-label">Brier (pass)</div><div class="outcome-metric-value">${metrics.brier.toFixed(3)}</div><div class="outcome-metric-help">lower = better</div></div>` : ''}
</div>` : '';
const anecdoteBanner = n < 3 ? `
<div class="outcome-anecdote">
<strong>Anecdotal until ${3 - n} more attempt${3 - n === 1 ? '' : 's'}.</strong>
Calibration metrics need ≥3 exam events per the WWC single-case-design
standard. Until then, the dots are just dots.
</div>` : '';
const list = events.length === 0 ? '' : `
<details class="outcome-list">
<summary>${events.length} attempt${events.length === 1 ? '' : 's'} logged</summary>
<ul>
${events.slice().reverse().map(e => `
<li>
<strong>${escapeHtml(e.examDateISO || new Date(e.loggedAtMs).toISOString().slice(0,10))}</strong>
${e.post?.actualScorePct != null ? `· ${e.post.actualScorePct}% ${e.post.passed ? '✓' : '✗'}` : '· result pending'}
${e.pre?.predictedReadinessPct != null ? `· predicted ${e.pre.predictedReadinessPct}%` : ''}
</li>`).join('')}
</ul>
</details>`;
host.innerHTML = `
<p class="outcomes-blurb">
Log every real exam attempt — even one. Future attempts get compared
against your predicted readiness so you can see whether the app's
number is trustworthy. Local only; not synced.
</p>
${anecdoteBanner}
${n > 0 ? `<div class="outcome-scatter-wrap">${scatter}</div>` : ''}
${metricsHTML}
${list}
<div class="settings-actions" style="margin-top: 12px;">
<button class="action" id="outcome-log-btn">📊 Log an exam attempt</button>
</div>
`;
$('#outcome-log-btn')?.addEventListener('click', () => openOutcomeLogDialog());
}
// Single dialog that captures the full ExamEvent in one form. Skip
// fields don't break anything — predictedReadiness is auto-filled from
// the current readiness number; everything else is optional but
// strongly suggested in the prompt copy.
function openOutcomeLogDialog() {
// Snapshot the current app-predicted readiness so we capture what
// the user actually saw at log time, not at form-submit time.
const currentReadiness = (() => {
const history = loadQuizHistory(state.exam).slice(-5);
const totalQ = history.reduce((n, e) => n + (e.total || 0), 0);
const correctQ = history.reduce((n, e) => n + (e.correct || 0), 0);
return totalQ >= 40 ? Math.round((correctQ / totalQ) * 100) : null;
})();
const today = new Date().toISOString().slice(0,10);
const overlay = document.createElement('div');
overlay.id = 'outcome-overlay';
overlay.setAttribute('role', 'dialog');
overlay.setAttribute('aria-modal', 'true');
overlay.setAttribute('aria-labelledby', 'outcome-title');
overlay.innerHTML = `
<div class="outcome-card">
<button class="welcome-close" id="outcome-close" aria-label="Cancel">✕</button>
<h2 id="outcome-title">Log an exam attempt</h2>
<p class="outcome-intro">
Capture what the app predicted, what you guessed, and what you actually scored.
After 3+ attempts the calibration view starts to mean something.
</p>
<form id="outcome-form">
<label class="outcome-field">
<span class="outcome-label">Exam date</span>
<input type="date" id="outcome-date" value="${today}" required>
</label>
<fieldset class="outcome-group">
<legend>Before the exam</legend>
<label class="outcome-field">
<span class="outcome-label">App's predicted readiness % <span class="outcome-meta">(auto)</span></span>
<input type="number" id="outcome-app-pred" min="0" max="100" step="1" value="${currentReadiness ?? ''}" placeholder="e.g. 78">
</label>
<label class="outcome-field">
<span class="outcome-label">Your own prediction %</span>
<input type="number" id="outcome-self-pred" min="0" max="100" step="1" placeholder="What did you guess you'd score?">
</label>
<label class="outcome-field">
<span class="outcome-label">Your confidence (0–100)</span>
<input type="number" id="outcome-confidence" min="0" max="100" step="1" placeholder="How sure were you?">
</label>
</fieldset>
<fieldset class="outcome-group">
<legend>After the exam</legend>
<label class="outcome-field">
<span class="outcome-label">Actual score % (from CompTIA score report)</span>
<input type="number" id="outcome-actual" min="0" max="100" step="0.1" placeholder="e.g. 82" required>
</label>
<label class="outcome-field">
<span class="outcome-label">Postdiction % <span class="outcome-meta">(your guess right after — before seeing the score)</span></span>
<input type="number" id="outcome-postdict" min="0" max="100" step="1">
</label>
</fieldset>
<fieldset class="outcome-group">
<legend>Reflection (Lovett wrapper)</legend>
<label class="outcome-field">
<span class="outcome-label">One sentence on the prediction-vs-actual gap</span>
<textarea id="outcome-gap" rows="2" placeholder="e.g. I overestimated my OBJ 2.x readiness — I'd skipped a domain."></textarea>
</label>
<span class="outcome-label">Which study activities did you use?</span>
<div class="outcome-strategies">
${['Study cards', 'Practice quizzes', 'Reading sheets', 'Timed mocks', 'Reference book'].map(s =>
`<label class="outcome-strategy"><input type="checkbox" value="${escapeHtml(s)}"> ${escapeHtml(s)}</label>`
).join('')}
</div>
<label class="outcome-field" style="margin-top: 10px;">
<span class="outcome-label">One concrete change for next cycle</span>
<textarea id="outcome-forward" rows="2" placeholder="e.g. Take a timed 90-Q mock under exam conditions every Sunday."></textarea>
</label>
</fieldset>
<div class="outcome-actions">
<button type="button" class="action" id="outcome-cancel">Cancel</button>
<button type="submit" class="action primary" id="outcome-save">Save attempt</button>
</div>
</form>
</div>`;
document.body.appendChild(overlay);
const previouslyFocused = document.activeElement;
setAppInert(true);
const releaseTrap = trapFocus(overlay);
const close = () => {
releaseTrap();
setAppInert(false);
document.removeEventListener('keydown', onKey);
overlay.remove();
if (previouslyFocused && typeof previouslyFocused.focus === 'function') previouslyFocused.focus();
};
const onKey = (e) => { if (e.key === 'Escape') close(); };
document.addEventListener('keydown', onKey);
$('#outcome-close').addEventListener('click', close);
$('#outcome-cancel').addEventListener('click', close);
$('#outcome-form').addEventListener('submit', async (e) => {
e.preventDefault();
const intField = (id) => {
const v = $(`#${id}`)?.value?.trim();
if (v === '' || v == null) return null;
const n = Number(v);
return Number.isFinite(n) ? n : null;
};
const actual = intField('outcome-actual');
if (actual == null) { toast('Actual score is required.', 'error'); return; }
const strategies = [...overlay.querySelectorAll('.outcome-strategy input:checked')].map(c => c.value);
const event = {
id: 'evt-' + Date.now(),
exam: state.exam,
examDateISO: $('#outcome-date').value || today,
loggedAtMs: Date.now(),
pre: {
predictedReadinessPct: intField('outcome-app-pred'),
selfPredictedPct: intField('outcome-self-pred'),
confidencePct: intField('outcome-confidence'),
},
post: {
actualScorePct: actual,
postdictionPct: intField('outcome-postdict'),
passed: actual >= MOCK_EXAM_PASS_PCT,
lovettGap: $('#outcome-gap').value.trim(),
lovettStrategies: strategies,
lovettForward: $('#outcome-forward').value.trim(),
},
};
await appendExamEvent(event);
close();
toast('Logged. The calibration view will sharpen as you add more attempts.', 'success', 4500);
hydrateOutcomesPanel();
});
}
//─── DATA LOAD ───────────────────────────────────────────────
// Critical-path: questions.json blocks first paint (the Study tab is
// the default landing). concept-fixes.json is deferred — only Reading
// uses it, and renderReading awaits state._conceptFixesPromise if the
// data hasn't landed yet. Saves ~275ms off cold mobile boot.
async function loadData() {
const def = examDef(state.exam);
// Kick off the concept-fixes fetch in parallel but don't await it.
// Cached on state for renderReading + the renderReading-side wait.
state._conceptFixesPromise = fetch(def.fixes)
.then(r => r.ok ? r.json() : {})
.then(j => { state.conceptFixes = j; return j; })
.catch(() => { state.conceptFixes = {}; return {}; });
const questionsRes = await fetch(def.questions);
state.questions = questionsRes.ok ? await questionsRes.json() : [];
state.progress = await loadProgress();
state.overrides = await loadOverrides();
// Initialize progress for any new question; migrate older saves
let migrated = false;
// 1. Dedupe migration: old per-pretest IDs → canonical IDs via q.sources
const validIds = new Set(state.questions.map(q => q.id));
const orphans = Object.keys(state.progress).filter(id => !validIds.has(id));
for (const oldId of orphans) {
const m = oldId.match(/^p(\d+)q(\d+)$/);
if (!m) { delete state.progress[oldId]; migrated = true; continue; }
const pretest = Number(m[1]), qnum = Number(m[2]);
const canon = state.questions.find(q =>
(q.sources || []).some(s => s.pretest === pretest && s.qnum === qnum)
);
if (canon) {
const old = state.progress[oldId];
const tgt = state.progress[canon.id];
if (!tgt) {
state.progress[canon.id] = old;
} else {
// Merge by taking the more-advanced progress across both
tgt.seen = (tgt.seen || 0) + (old.seen || 0);
tgt.correct = (tgt.correct || 0) + (old.correct || 0);
tgt.lastSeen = Math.max(tgt.lastSeen || 0, old.lastSeen || 0);
tgt.updated_at = Math.max(tgt.updated_at || 0, old.updated_at || 0);
tgt.interval = Math.max(tgt.interval || 0, old.interval || 0);
tgt.ease = Math.max(tgt.ease ?? 2.5, old.ease ?? 2.5);
tgt.due = Math.max(tgt.due || 0, old.due || 0);
const rank = { new: 0, learning: 1, good: 2 };
if ((rank[old.status] ?? 0) > (rank[tgt.status] ?? 0)) tgt.status = old.status;
}
}
delete state.progress[oldId];
migrated = true;
}
// 2. Fill defaults + migrate SRS fields for every current question
for (const q of state.questions) {
const p = state.progress[q.id];
if (!p) {
state.progress[q.id] = defaultProgress();
migrated = true;
} else if (p.ease === undefined || p.interval === undefined || p.due === undefined) {
migrateProgress(p);
migrated = true;
}
}
if (migrated) saveProgress();
}
//─── UTILITIES ───────────────────────────────────────────────
function uniqueObjs() {
const objs = [...new Set(state.questions.map(q => q.obj))].filter(o => o !== '?');
// Sort numerically (1.1, 1.2, 2.1, ..., 5.6)
objs.sort((a, b) => {
const [am, an] = a.split('.').map(Number);
const [bm, bn] = b.split('.').map(Number);
return am - bm || an - bn;
});
return objs;
}
// Merge a base question with any user-added override (options, image, images)
function getQuestion(q) {
const o = state.overrides[q.id];
return o ? { ...q, ...o } : q;
}
// Weakest-N list: cards with at least one attempt, ranked by lowest accuracy
// then by highest seen-count (to break ties toward "cards you keep missing").
// Unseen cards don't count — they're not weak, they're unread.
const WEAKEST_LIMIT = 10;
function weakestIdSet() {
const withAttempts = state.questions
.map(q => {
const p = state.progress[q.id] || {};
const seen = p.seen || 0;
const acc = seen > 0 ? (p.correct || 0) / seen : 1;
return { id: q.id, seen, acc };
})
.filter(x => x.seen > 0);
withAttempts.sort((a, b) => a.acc - b.acc || b.seen - a.seen);
return new Set(withAttempts.slice(0, WEAKEST_LIMIT).map(x => x.id));
}
function filteredQuestions() {
// Cram session: queue is the source of truth, ignore filters + cache
if (state.cram?.active) {
const byId = Object.fromEntries(state.questions.map(q => [q.id, q]));
return state.cram.queue.map(id => byId[id]).filter(Boolean);
}
let qs = state.questions.slice();
if (state.filter.obj) qs = qs.filter(q => q.obj === state.filter.obj);
if (state.filter.due) qs = qs.filter(isDue);
if (state.filter.weakest) {
const ids = weakestIdSet();
qs = qs.filter(q => ids.has(q.id));
}
if (state.filter.hard) {
qs = qs.filter(q => {
const r = state.progress[q.id]?.lastRating;
return r === 'hard' || r === 'again';
});
}
if (state.filter.search) {
const q = state.filter.search.toLowerCase();
qs = qs.filter(x =>
x.question.toLowerCase().includes(q) ||
(x.explanation || '').toLowerCase().includes(q)
);
}
// Order the deck via orderDeck() unless explicitly sequential. Cached per
// (filter × order × deck-identity) so Prev/Next don't reshuffle mid-session.
if (state._orderSeed === null) state._orderSeed = (Date.now() & 0x7fffffff) || 1;
// Cheap rolling-hash of the full id list. Previously we sliced to 40 chars
// which collided when filter membership changed but length + the first ~5
// IDs stayed identical (e.g. rating a mid-deck Hard card Good while another
// entered the Hard set) — returning stale order with cards no longer in
// the filter. Hashing the full list catches every membership change.
let _idHash = 0;
for (const x of qs) for (let i = 0; i < x.id.length; i++) _idHash = ((_idHash * 31 + x.id.charCodeAt(i)) | 0);
const key = `${state.order}|${state.filter.obj}|${state.filter.due}|${state.filter.weakest}|${state.filter.hard}|${state.filter.search}|${qs.length}|${_idHash}`;
if (!state._orderCache || state._orderCache.key !== key) {
const list = orderDeck(qs, state.progress, { mode: state.order, seed: state._orderSeed });
state._orderCache = { key, list };
}
return state._orderCache.list;
}
function dueCount() {
return state.questions.filter(isDue).length;
}
function weakestCount() {
return weakestIdSet().size;
}
// Cards the user most recently rated Hard or Again — the "still shaky" set.
function hardCount() {
return state.questions.filter(q => {
const r = state.progress[q.id]?.lastRating;
return r === 'hard' || r === 'again';
}).length;
}
function formatRemaining(ms) {
const total = Math.max(0, Math.ceil(ms / 1000));
const m = Math.floor(total / 60);
const s = total % 60;
return `${m}:${String(s).padStart(2, '0')}`;
}
function updateHUD() {
const hud = $('#progress-hud');
if (!hud) return;
const parts = [];
// Exam countdown is always visible so the deadline stays top-of-mind.
// Urgency class kicks in when ≤7 days remain; hidden in Anxiety Mode
// along with other numeric progress feedback.
const days = daysUntilExam(state.exam);
hud.classList.remove('hud-urgent', 'hud-soon', 'hud-past');
if (days !== null && pref('anxiety') !== 'on') {
const short = examDef(state.exam).label.replace(/\s*\(.*\)$/, '');
let label;
if (days < 0) { label = `${short} exam was ${-days}d ago`; hud.classList.add('hud-past'); }
else if (days === 0){ label = `${short} · TODAY`; hud.classList.add('hud-urgent'); }
else if (days <= 7) { label = `${short} · ${days}d`; hud.classList.add('hud-urgent'); }
else if (days <= 30){ label = `${short} · ${days}d`; hud.classList.add('hud-soon'); }
else { label = `${short} · ${days}d`; }
parts.push(`⏳ ${label}`);
}
if (state.cram?.active) {
const remaining = state.cram.queue.length;
parts.push(`🔥 Cram ${state.cram.cleared}/${state.cram.originalCount}` + (remaining ? ` · ${remaining} to go` : ''));
}
if (state.session) {
if (state.session.endsAt) parts.push(`⏱ ${formatRemaining(state.session.endsAt - Date.now())}`);
if (state.session.targetCards) {
const done = state.session.ratedIds.size;
parts.push(`🎯 ${done}/${state.session.targetCards}`);
}
}
if (pref('anxiety') !== 'on' && (state.mode === 'study' || state.mode === 'quiz')) {
const qs = filteredQuestions();
const total = qs.length;
const idx = state.currentIndex + 1;
parts.push(total > 0 ? `${Math.min(idx, total)} / ${total}` : `0 / 0`);
// Skip the "X due" counter when X equals the total questions — fresh
// users see everything as due, so the number duplicates the deck size
// and (per the QA pass) overwhelms a beginner. Once they rate even one
// card, the count diverges and re-appears.
if (!state.filter.due) {
const due = dueCount();
if (due > 0 && due < state.questions.length) parts.push(`${due} due`);
}
}
hud.textContent = parts.join(' · ');
updateDueBadge();
}
// Spaced-repetition "due" pill on the Study tab. Mirrors the HUD's
// anxiety-mode suppression so the count stays consistent.
function updateDueBadge() {
const badge = $('#study-due-badge');
if (!badge) return;
// "Review backlog": cards already SEEN that have come due again. New
// unseen cards are deliberately excluded — counting them would just
// mirror the deck size on a fresh install and never feel like a backlog.
// Suppressed in Anxiety Mode (hides numeric pressure cues).
const due = pref('anxiety') === 'on' ? 0
: state.questions.filter(q => (state.progress[q.id]?.seen || 0) > 0 && isDue(q)).length;
if (due > 0) {
badge.textContent = due > 99 ? '99+' : String(due);
badge.hidden = false;
badge.setAttribute('aria-hidden', 'false');
badge.setAttribute('aria-label', `${due} cards due for review`);
} else {
badge.hidden = true;
badge.setAttribute('aria-hidden', 'true');
}
}
//─── MODE: STUDY (flashcards with self-rating) ──────────────
function renderStudy() {
$('#mode-title').textContent = 'Study';
document.documentElement.toggleAttribute('data-revealed', !!state.revealed);
const qs = filteredQuestions();
if (qs.length === 0) {
const msg = state.filter.weakest
? ['Nothing weak yet', 'Weakest shows cards you\'ve missed before. Rate a few cards and come back — that list builds itself.']
: state.filter.due
? ['✨ All caught up!', 'No cards due right now — come back later, or tap Due again to turn it off and study anything.']
: state.filter.search
? ['Hmm, nothing matches', `Nothing for "${escapeHtml(state.filter.search)}". Try a different word or clear the search.`]
: ['No questions', 'Pick an objective below or clear the filter.'];
$('#main').innerHTML = filterBarHTML() + emptyHTML(msg[0], msg[1]);
renderFilterBar();
return;
}
if (state.currentIndex >= qs.length) state.currentIndex = 0;
const baseQ = qs[state.currentIndex];
const q = getQuestion(baseQ);
const prog = state.progress[q.id];
if (state.editing) {
$('#main').innerHTML = `${filterBarHTML()}${renderEditFormHTML(q)}`;
renderFilterBar();
updateHUD();
attachEditEvents(q);
return;
}
const edited = !!state.overrides[q.id];
const sources = q.sources || [{ pretest: q.pretest, qnum: q.qnum }];
// Only animate the card on question change, not on reveal-toggle rerenders
const sameCard = state._lastRenderedCard === q.id;
let cardClass = sameCard ? 'card' : 'card card-fresh';
state._lastRenderedCard = q.id;
// Preserve the scroll position across SAME-CARD re-renders. Picking an
// option and revealing both rebuild #main via innerHTML, which resets
// scrollTop to 0 — that mid-card jump-to-top is the "the screen resizes
// when I tap an answer" report. We restore it after the swap. On a real
// card *change* we intentionally start at the top (prevScroll stays 0).
const prevScroll = sameCard ? ($('#main')?.scrollTop || 0) : 0;
// If we're in the first 500ms after reveal, paint the whole card with
// pointer-events: none. Every other guard (rate-row arming, JS timestamp
// checks in nextQuestion/prevQuestion, swipe target check) catches a
// specific path; this is the catch-all that makes ANY accidental click
// on the card during the reveal-transition window impossible.
const sinceReveal = Date.now() - (state._revealedAt || 0);
if (state.revealed && sinceReveal < 800) cardClass += ' card-just-revealed';
$('#main').innerHTML = `
${filterBarHTML()}