File size: 36,401 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Tests for src/lib/achievements.ts
 *
 * Covers:
 *   - computeAchievements: returns expected achievement IDs
 *   - milestone helper: earned=true when current >= target, progress capped at 100
 *   - Level achievements: bronze/silver/gold/platinum thresholds
 *   - XP achievements
 *   - Streak achievements (longestStreak used, not current)
 *   - Daily goal achievements
 *   - Active day achievements (dedup by date)
 *   - Volume (total exercises) achievements
 *   - Category mastery achievements
 *   - Category count achievements (per-category exercise counts)
 *   - Critical hit achievements
 *   - Quality/score achievements (score >= 0.9, score >= 1.0)
 *   - Variety achievements (unique categories used)
 *   - Logic puzzle type variety
 *   - Feynman-specific: taught / review count from metadata
 *   - Reading: custom content from metadata
 *   - Unlock achievements
 *   - achievementSummary: total, earned, byTier counts
 *   - earnedAt: null when not earned, populated when earned
 *   - progress: 0–99 for unearned, 100 for earned
 *   - No duplicate IDs across the full list
 */

import { describe, it, expect } from "vitest";
import {
  computeAchievements,
  achievementSummary,
  type AchievementInput,
} from "../achievements";

// ─── Helpers ──────────────────────────────────────────────────────────────

const DAY = 24 * 60 * 60 * 1000;
const NOW = new Date("2026-01-15T12:00:00Z");

function daysAgo(n: number): Date {
  return new Date(NOW.getTime() - n * DAY);
}

function baseInput(overrides: Partial<AchievementInput> = {}): AchievementInput {
  return {
    user: {
      level: 1,
      totalXp: 0,
      streak: 0,
      longestStreak: 0,
      createdAt: daysAgo(1),
    },
    categorySkills: [],
    activities: [],
    dailyLogs: [],
    unlocks: [],
    ...overrides,
  };
}

function makeActivity(
  overrides: Partial<AchievementInput["activities"][number]> = {}
): AchievementInput["activities"][number] {
  return {
    category: "logic",
    exerciseType: "sudoku",
    isCriticalHit: false,
    score: 0.8,
    durationSecs: 120,
    createdAt: daysAgo(1),
    metadata: null,
    ...overrides,
  };
}

function makeActivities(count: number, overrides: Partial<AchievementInput["activities"][number]> = {}): AchievementInput["activities"] {
  return Array.from({ length: count }, (_, i) =>
    makeActivity({ createdAt: daysAgo(count - i), ...overrides })
  );
}

// ─── computeAchievements: structure ────────────────────────────────────────

describe("computeAchievements", () => {
  it("returns an array of achievements", () => {
    const result = computeAchievements(baseInput());
    expect(Array.isArray(result)).toBe(true);
    expect(result.length).toBeGreaterThan(0);
  });

  it("every achievement has required fields", () => {
    const result = computeAchievements(baseInput());
    for (const a of result) {
      expect(typeof a.id).toBe("string");
      expect(typeof a.name).toBe("string");
      expect(typeof a.description).toBe("string");
      expect(["bronze", "silver", "gold", "platinum"]).toContain(a.tier);
      expect(typeof a.icon).toBe("string");
      expect(typeof a.earned).toBe("boolean");
      expect(a.earnedAt === null || typeof a.earnedAt === "string").toBe(true);
      expect(typeof a.progress).toBe("number");
      expect(a.progress).toBeGreaterThanOrEqual(0);
      expect(a.progress).toBeLessThanOrEqual(100);
    }
  });

  it("no duplicate achievement IDs", () => {
    const result = computeAchievements(baseInput());
    const ids = result.map((a) => a.id);
    const unique = new Set(ids);
    expect(unique.size).toBe(ids.length);
  });

  it("includes expected milestone IDs", () => {
    const result = computeAchievements(baseInput());
    const ids = new Set(result.map((a) => a.id));
    expect(ids.has("level-5")).toBe(true);
    expect(ids.has("level-50")).toBe(true);
    expect(ids.has("streak-7")).toBe(true);
    expect(ids.has("xp-1000")).toBe(true);
    expect(ids.has("exercises-10")).toBe(true);
    expect(ids.has("variety-6")).toBe(true);
    expect(ids.has("crit-1")).toBe(true);
  });
});

// ─── Level achievements ─────────────────────────────────────────────────────

describe("level achievements", () => {
  it("level-5 is earned at level 5", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, level: 5 } }));
    const a = result.find((x) => x.id === "level-5")!;
    expect(a.earned).toBe(true);
    expect(a.progress).toBe(100);
  });

  it("level-5 is not earned at level 4", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, level: 4 } }));
    const a = result.find((x) => x.id === "level-5")!;
    expect(a.earned).toBe(false);
    expect(a.progress).toBe(80); // 4/5 * 100
  });

  it("level-50 not earned at level 25", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, level: 25 } }));
    const a = result.find((x) => x.id === "level-50")!;
    expect(a.earned).toBe(false);
    expect(a.progress).toBe(50);
  });

  it("all level achievements earned at level 50", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, level: 50 } }));
    for (const id of ["level-5", "level-10", "level-25", "level-50"]) {
      expect(result.find((x) => x.id === id)!.earned).toBe(true);
    }
  });
});

// ─── XP achievements ────────────────────────────────────────────────────────

describe("XP achievements", () => {
  it("xp-1000 earned at exactly 1000", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, totalXp: 1000 } }));
    expect(result.find((x) => x.id === "xp-1000")!.earned).toBe(true);
  });

  it("xp-1000 not earned at 999", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, totalXp: 999 } }));
    expect(result.find((x) => x.id === "xp-1000")!.earned).toBe(false);
  });

  it("xp-1000 progress is 50 at 500 XP", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, totalXp: 500 } }));
    expect(result.find((x) => x.id === "xp-1000")!.progress).toBe(50);
  });
});

// ─── Streak achievements ─────────────────────────────────────────────────────

describe("streak achievements", () => {
  it("streak-7 earned when longestStreak >= 7", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, longestStreak: 7 } }));
    expect(result.find((x) => x.id === "streak-7")!.earned).toBe(true);
  });

  it("streak-7 not earned when longestStreak = 6", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, longestStreak: 6 } }));
    expect(result.find((x) => x.id === "streak-7")!.earned).toBe(false);
  });

  it("streak-100 earned at longestStreak = 100", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, longestStreak: 100 } }));
    expect(result.find((x) => x.id === "streak-100")!.earned).toBe(true);
  });
});

// ─── Daily goal achievements ─────────────────────────────────────────────────

describe("daily goal achievements", () => {
  it("goals-7 earned when 7 days have goalMet=true", () => {
    const logs = Array.from({ length: 7 }, (_, i) => ({
      date: daysAgo(i + 1),
      goalMet: true,
      activityCount: 3,
    }));
    const result = computeAchievements(baseInput({ dailyLogs: logs }));
    expect(result.find((x) => x.id === "goals-7")!.earned).toBe(true);
  });

  it("goals-7 not earned with only 6 goal days", () => {
    const logs = Array.from({ length: 6 }, (_, i) => ({
      date: daysAgo(i + 1),
      goalMet: true,
      activityCount: 3,
    }));
    const result = computeAchievements(baseInput({ dailyLogs: logs }));
    expect(result.find((x) => x.id === "goals-7")!.earned).toBe(false);
  });

  it("non-goalMet logs do not count", () => {
    const logs = Array.from({ length: 10 }, (_, i) => ({
      date: daysAgo(i + 1),
      goalMet: false,
      activityCount: 2,
    }));
    const result = computeAchievements(baseInput({ dailyLogs: logs }));
    expect(result.find((x) => x.id === "goals-7")!.earned).toBe(false);
  });
});

// ─── Active days achievements ─────────────────────────────────────────────────

describe("active days achievements", () => {
  it("active-30 earned with 30 logs having activityCount > 0", () => {
    const logs = Array.from({ length: 30 }, (_, i) => ({
      date: daysAgo(i + 1),
      goalMet: false,
      activityCount: 1,
    }));
    const result = computeAchievements(baseInput({ dailyLogs: logs }));
    expect(result.find((x) => x.id === "active-30")!.earned).toBe(true);
  });

  it("duplicate dates count as one active day", () => {
    const date = daysAgo(1);
    const logs = Array.from({ length: 5 }, () => ({
      date,
      goalMet: false,
      activityCount: 1,
    }));
    const result = computeAchievements(baseInput({ dailyLogs: logs }));
    expect(result.find((x) => x.id === "active-30")!.earned).toBe(false);
    expect(result.find((x) => x.id === "active-30")!.progress).toBe(3); // 1/30*100 rounded
  });

  it("logs with activityCount=0 do not count", () => {
    const logs = Array.from({ length: 30 }, (_, i) => ({
      date: daysAgo(i + 1),
      goalMet: true,
      activityCount: 0,
    }));
    const result = computeAchievements(baseInput({ dailyLogs: logs }));
    expect(result.find((x) => x.id === "active-30")!.earned).toBe(false);
  });
});

// ─── Volume achievements ─────────────────────────────────────────────────────

describe("volume achievements", () => {
  it("exercises-10 earned with 10 activities", () => {
    const acts = makeActivities(10);
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "exercises-10")!.earned).toBe(true);
  });

  it("exercises-10 not earned with 9 activities", () => {
    const acts = makeActivities(9);
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "exercises-10")!.earned).toBe(false);
  });

  it("exercises-50 progress is correct at 25 activities", () => {
    const acts = makeActivities(25);
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "exercises-50")!.progress).toBe(50);
  });

  it("exercises-200 earned with 200 activities", () => {
    const acts = makeActivities(200);
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "exercises-200")!.earned).toBe(true);
  });
});

// ─── Category mastery achievements ────────────────────────────────────────────

describe("category mastery achievements", () => {
  it("chess-level-5 earned at chess skill level 5", () => {
    const input = baseInput({
      categorySkills: [{ category: "chess", level: 5, totalXp: 500 }],
    });
    const result = computeAchievements(input);
    expect(result.find((x) => x.id === "chess-level-5")!.earned).toBe(true);
  });

  it("chess-level-10 not earned at chess skill level 5", () => {
    const input = baseInput({
      categorySkills: [{ category: "chess", level: 5, totalXp: 500 }],
    });
    const result = computeAchievements(input);
    expect(result.find((x) => x.id === "chess-level-10")!.earned).toBe(false);
    expect(result.find((x) => x.id === "chess-level-10")!.progress).toBe(50);
  });

  it("missing category skill defaults to level 1", () => {
    const result = computeAchievements(baseInput());
    expect(result.find((x) => x.id === "reading-level-5")!.progress).toBe(20);
  });
});

// ─── Category count achievements ─────────────────────────────────────────────

describe("category count achievements", () => {
  it("chess-10 earned with 10 chess activities", () => {
    const acts = makeActivities(10, { category: "chess" });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "chess-10")!.earned).toBe(true);
  });

  it("chess-10 not earned with only 9 chess activities", () => {
    const acts = makeActivities(9, { category: "chess" });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "chess-10")!.earned).toBe(false);
  });

  it("chess-50 progress correct with 25 chess activities", () => {
    const acts = makeActivities(25, { category: "chess" });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "chess-50")!.progress).toBe(50);
  });
});

// ─── Critical hit achievements ────────────────────────────────────────────────

describe("critical hit achievements", () => {
  it("crit-1 earned on first critical hit", () => {
    const acts = [makeActivity({ isCriticalHit: true })];
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "crit-1")!.earned).toBe(true);
  });

  it("crit-1 not earned with no critical hits", () => {
    const result = computeAchievements(baseInput());
    expect(result.find((x) => x.id === "crit-1")!.earned).toBe(false);
    expect(result.find((x) => x.id === "crit-1")!.progress).toBe(0);
  });

  it("crit-10 earned with 10 critical hits", () => {
    const acts = Array.from({ length: 10 }, () => makeActivity({ isCriticalHit: true }));
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "crit-10")!.earned).toBe(true);
  });

  it("crit-10 progress correct with 5 critical hits", () => {
    const acts = Array.from({ length: 5 }, () => makeActivity({ isCriticalHit: true }));
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "crit-10")!.progress).toBe(50);
  });
});

// ─── Quality achievements ─────────────────────────────────────────────────────

describe("quality achievements", () => {
  it("highscore-10 earned with 10 exercises scoring >= 0.9", () => {
    const acts = makeActivities(10, { score: 0.95 });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "highscore-10")!.earned).toBe(true);
  });

  it("highscore-10 not earned when scores are 0.89", () => {
    const acts = makeActivities(10, { score: 0.89 });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "highscore-10")!.earned).toBe(false);
  });

  it("perfect-5 earned with 5 score=1.0 exercises", () => {
    const acts = makeActivities(5, { score: 1.0 });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "perfect-5")!.earned).toBe(true);
  });

  it("perfect-5 not earned with 4 perfect exercises", () => {
    const acts = makeActivities(4, { score: 1.0 });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "perfect-5")!.earned).toBe(false);
  });

  it("null score exercises are excluded from highscore count", () => {
    const acts = makeActivities(10, { score: null });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "highscore-10")!.earned).toBe(false);
  });
});

// ─── Variety achievements ─────────────────────────────────────────────────────

describe("variety achievements", () => {
  it("variety-3 earned with 3 distinct categories", () => {
    const acts = [
      makeActivity({ category: "chess" }),
      makeActivity({ category: "reading" }),
      makeActivity({ category: "feynman" }),
    ];
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "variety-3")!.earned).toBe(true);
  });

  it("variety-3 not earned with only 2 categories", () => {
    const acts = [
      makeActivity({ category: "chess" }),
      makeActivity({ category: "reading" }),
    ];
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "variety-3")!.earned).toBe(false);
  });

  it("variety-6 earned with all 6 categories", () => {
    const acts = [
      makeActivity({ category: "chess" }),
      makeActivity({ category: "reading" }),
      makeActivity({ category: "feynman" }),
      makeActivity({ category: "logic" }),
      makeActivity({ category: "critical-thinking" }),
      makeActivity({ category: "quests" }),
    ];
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "variety-6")!.earned).toBe(true);
  });

  it("multiple activities in same category count as 1 toward variety", () => {
    const acts = makeActivities(10, { category: "chess" });
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "variety-3")!.progress).toBe(33);
  });
});

// ─── Logic puzzle type variety ────────────────────────────────────────────────

describe("logic puzzle type variety", () => {
  it("logic-types-3 earned with 3 distinct logic exerciseTypes", () => {
    const acts = [
      makeActivity({ category: "logic", exerciseType: "sudoku" }),
      makeActivity({ category: "logic", exerciseType: "sequence" }),
      makeActivity({ category: "logic", exerciseType: "pattern" }),
    ];
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "logic-types-3")!.earned).toBe(true);
  });

  it("logic-types-6 earned with all 6 logic types", () => {
    const types = ["sudoku", "sequence", "pattern", "wordscramble", "constraint", "mathequation"];
    const acts = types.map((t) => makeActivity({ category: "logic", exerciseType: t }));
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "logic-types-6")!.earned).toBe(true);
  });

  it("non-logic activities do not count toward logic type variety", () => {
    const acts = [
      makeActivity({ category: "chess", exerciseType: "puzzle" }),
      makeActivity({ category: "reading", exerciseType: "comprehension" }),
      makeActivity({ category: "feynman", exerciseType: "explain" }),
    ];
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "logic-types-3")!.earned).toBe(false);
  });
});

// ─── Feynman achievements ─────────────────────────────────────────────────────

describe("feynman achievements", () => {
  it("feynman-taught-5 earned with 5 wasTaught=true feynman activities", () => {
    const acts = Array.from({ length: 5 }, () =>
      makeActivity({
        category: "feynman",
        metadata: JSON.stringify({ wasTaught: true }),
      })
    );
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "feynman-taught-5")!.earned).toBe(true);
  });

  it("feynman-taught-5 not earned with only 4 wasTaught activities", () => {
    const acts = Array.from({ length: 4 }, () =>
      makeActivity({
        category: "feynman",
        metadata: JSON.stringify({ wasTaught: true }),
      })
    );
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "feynman-taught-5")!.earned).toBe(false);
  });

  it("feynman-review-10 earned with 10 isReview=true feynman activities", () => {
    const acts = Array.from({ length: 10 }, () =>
      makeActivity({
        category: "feynman",
        metadata: JSON.stringify({ isReview: true }),
      })
    );
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "feynman-review-10")!.earned).toBe(true);
  });

  it("invalid metadata JSON does not throw and is treated as non-taught", () => {
    const acts = [
      makeActivity({ category: "feynman", metadata: "INVALID JSON {" }),
    ];
    expect(() => computeAchievements(baseInput({ activities: acts }))).not.toThrow();
  });

  it("null metadata treated as non-taught", () => {
    const acts = [makeActivity({ category: "feynman", metadata: null })];
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "feynman-taught-5")!.earned).toBe(false);
  });
});

// ─── Reading custom content achievements ──────────────────────────────────────

describe("reading custom content achievements", () => {
  it("reading-custom-3 earned with 3 custom=true reading activities", () => {
    const acts = Array.from({ length: 3 }, () =>
      makeActivity({
        category: "reading",
        metadata: JSON.stringify({ custom: true }),
      })
    );
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "reading-custom-3")!.earned).toBe(true);
  });

  it("reading-custom-3 not earned with custom=false", () => {
    const acts = Array.from({ length: 3 }, () =>
      makeActivity({
        category: "reading",
        metadata: JSON.stringify({ custom: false }),
      })
    );
    const result = computeAchievements(baseInput({ activities: acts }));
    expect(result.find((x) => x.id === "reading-custom-3")!.earned).toBe(false);
  });
});

// ─── Unlock achievements ──────────────────────────────────────────────────────

describe("unlock achievements", () => {
  it("unlock-1 earned with 1 unlock", () => {
    const unlocks = [{ unlockedAt: daysAgo(1) }];
    const result = computeAchievements(baseInput({ unlocks }));
    expect(result.find((x) => x.id === "unlock-1")!.earned).toBe(true);
  });

  it("unlock-1 not earned with 0 unlocks", () => {
    const result = computeAchievements(baseInput());
    expect(result.find((x) => x.id === "unlock-1")!.earned).toBe(false);
  });

  it("unlock-10 earned with 10 unlocks", () => {
    const unlocks = Array.from({ length: 10 }, (_, i) => ({ unlockedAt: daysAgo(i + 1) }));
    const result = computeAchievements(baseInput({ unlocks }));
    expect(result.find((x) => x.id === "unlock-10")!.earned).toBe(true);
  });

  it("unlock-25 not earned with 24 unlocks", () => {
    const unlocks = Array.from({ length: 24 }, (_, i) => ({ unlockedAt: daysAgo(i + 1) }));
    const result = computeAchievements(baseInput({ unlocks }));
    expect(result.find((x) => x.id === "unlock-25")!.earned).toBe(false);
  });
});

// ─── earnedAt ────────────────────────────────────────────────────────────────

describe("earnedAt field", () => {
  it("is null when achievement is not earned", () => {
    const result = computeAchievements(baseInput());
    expect(result.find((x) => x.id === "level-5")!.earnedAt).toBeNull();
  });

  it("unlock-1 earnedAt is ISO string of first unlock date", () => {
    const unlockDate = daysAgo(3);
    const result = computeAchievements(baseInput({ unlocks: [{ unlockedAt: unlockDate }] }));
    const a = result.find((x) => x.id === "unlock-1")!;
    expect(a.earned).toBe(true);
    expect(a.earnedAt).toBe(unlockDate.toISOString());
  });

  it("crit-1 earnedAt is ISO string of first critical hit activity", () => {
    const critDate = daysAgo(2);
    const acts = [makeActivity({ isCriticalHit: true, createdAt: critDate })];
    const result = computeAchievements(baseInput({ activities: acts }));
    const a = result.find((x) => x.id === "crit-1")!;
    expect(a.earned).toBe(true);
    expect(a.earnedAt).toBe(critDate.toISOString());
  });
});

// ─── progress bounds ─────────────────────────────────────────────────────────

describe("progress bounds", () => {
  it("progress is exactly 100 when earned", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, level: 5 } }));
    expect(result.find((x) => x.id === "level-5")!.progress).toBe(100);
  });

  it("progress is at most 99 when not yet earned", () => {
    const result = computeAchievements(baseInput({ user: { ...baseInput().user, level: 4 } }));
    const a = result.find((x) => x.id === "level-5")!;
    expect(a.earned).toBe(false);
    expect(a.progress).toBeLessThanOrEqual(99);
  });

  it("progress is 0 when no data", () => {
    const result = computeAchievements(baseInput());
    expect(result.find((x) => x.id === "crit-1")!.progress).toBe(0);
  });
});

// ─── Debate Arena achievements ───────────────────────────────────────────────

function makeDebateActivity(
  winner: "user" | "opponent" | "tie" = "user",
  overrides: {
    opponentDifficulty?: string;
    roundCount?: number;
    userSide?: string;
    createdAt?: Date;
  } = {}
): AchievementInput["activities"][number] {
  return makeActivity({
    category: "critical-thinking",
    exerciseType: "debate",
    score: winner === "user" ? 0.8 : 0.4,
    metadata: JSON.stringify({
      exerciseType: "debate",
      winner,
      opponentDifficulty: overrides.opponentDifficulty ?? "medium",
      roundCount: overrides.roundCount ?? 3,
      userSide: overrides.userSide ?? "pro",
      topic: "Universal Basic Income",
      opponentId: "balanced",
      opponentName: "The Balanced Debater",
    }),
    createdAt: overrides.createdAt ?? daysAgo(1),
  });
}

describe("Debate Arena achievements", () => {
  it("no debate achievements earned with no activities", () => {
    const result = computeAchievements(baseInput());
    const debateAchs = result.filter((a) => a.id.startsWith("debate-"));
    expect(debateAchs.every((a) => !a.earned)).toBe(true);
  });

  it("debate-first earned after 1 debate", () => {
    const input = baseInput({ activities: [makeDebateActivity()] });
    const result = computeAchievements(input);
    expect(result.find((a) => a.id === "debate-first")!.earned).toBe(true);
  });

  it("debate-5 earned after 5 debates", () => {
    const activities = Array.from({ length: 5 }, (_, i) =>
      makeDebateActivity("opponent", { createdAt: daysAgo(5 - i) })
    );
    const input = baseInput({ activities });
    const result = computeAchievements(input);
    expect(result.find((a) => a.id === "debate-5")!.earned).toBe(true);
  });

  it("debate-5 not earned after 4 debates", () => {
    const activities = Array.from({ length: 4 }, () => makeDebateActivity("tie"));
    const input = baseInput({ activities });
    expect(computeAchievements(input).find((a) => a.id === "debate-5")!.earned).toBe(false);
  });

  it("debate-25 earned after 25 debates", () => {
    const activities = Array.from({ length: 25 }, (_, i) =>
      makeDebateActivity("user", { createdAt: daysAgo(25 - i) })
    );
    const input = baseInput({ activities });
    expect(computeAchievements(input).find((a) => a.id === "debate-25")!.earned).toBe(true);
  });

  it("debate-win-1 earned after winning 1 debate", () => {
    const input = baseInput({ activities: [makeDebateActivity("user")] });
    expect(computeAchievements(input).find((a) => a.id === "debate-win-1")!.earned).toBe(true);
  });

  it("debate-win-1 not earned when all debates are losses", () => {
    const input = baseInput({ activities: [makeDebateActivity("opponent")] });
    expect(computeAchievements(input).find((a) => a.id === "debate-win-1")!.earned).toBe(false);
  });

  it("debate-win-10 earned after winning 10 debates", () => {
    const activities = Array.from({ length: 10 }, (_, i) =>
      makeDebateActivity("user", { createdAt: daysAgo(10 - i) })
    );
    const input = baseInput({ activities });
    expect(computeAchievements(input).find((a) => a.id === "debate-win-10")!.earned).toBe(true);
  });

  it("debate-win-25 earned after winning 25 debates", () => {
    const activities = Array.from({ length: 25 }, (_, i) =>
      makeDebateActivity("user", { createdAt: daysAgo(25 - i) })
    );
    const input = baseInput({ activities });
    expect(computeAchievements(input).find((a) => a.id === "debate-win-25")!.earned).toBe(true);
  });

  it("debate-hard-1 earned after defeating a hard opponent", () => {
    const input = baseInput({
      activities: [makeDebateActivity("user", { opponentDifficulty: "hard" })],
    });
    expect(computeAchievements(input).find((a) => a.id === "debate-hard-1")!.earned).toBe(true);
  });

  it("debate-hard-1 not earned when hard opponent wins", () => {
    const input = baseInput({
      activities: [makeDebateActivity("opponent", { opponentDifficulty: "hard" })],
    });
    expect(computeAchievements(input).find((a) => a.id === "debate-hard-1")!.earned).toBe(false);
  });

  it("debate-hard-1 not earned when winning against medium opponent", () => {
    const input = baseInput({
      activities: [makeDebateActivity("user", { opponentDifficulty: "medium" })],
    });
    expect(computeAchievements(input).find((a) => a.id === "debate-hard-1")!.earned).toBe(false);
  });

  it("debate-hard-5 earned after defeating 5 hard opponents", () => {
    const activities = Array.from({ length: 5 }, (_, i) =>
      makeDebateActivity("user", { opponentDifficulty: "hard", createdAt: daysAgo(5 - i) })
    );
    const input = baseInput({ activities });
    expect(computeAchievements(input).find((a) => a.id === "debate-hard-5")!.earned).toBe(true);
  });

  it("debate-5-rounds earned after completing a 5-round debate", () => {
    const input = baseInput({
      activities: [makeDebateActivity("user", { roundCount: 5 })],
    });
    expect(computeAchievements(input).find((a) => a.id === "debate-5-rounds")!.earned).toBe(true);
  });

  it("debate-5-rounds not earned after only 3-round debates", () => {
    const input = baseInput({
      activities: [makeDebateActivity("user", { roundCount: 3 })],
    });
    expect(computeAchievements(input).find((a) => a.id === "debate-5-rounds")!.earned).toBe(false);
  });

  it("debate-all-sides earned after arguing both pro and con", () => {
    const activities = [
      makeDebateActivity("user", { userSide: "pro", createdAt: daysAgo(2) }),
      makeDebateActivity("opponent", { userSide: "con", createdAt: daysAgo(1) }),
    ];
    const input = baseInput({ activities });
    expect(computeAchievements(input).find((a) => a.id === "debate-all-sides")!.earned).toBe(true);
  });

  it("debate-all-sides not earned after only pro debates", () => {
    const activities = Array.from({ length: 3 }, () =>
      makeDebateActivity("user", { userSide: "pro" })
    );
    const input = baseInput({ activities });
    expect(computeAchievements(input).find((a) => a.id === "debate-all-sides")!.earned).toBe(false);
  });

  it("debate achievements have unique IDs with no duplicates vs global set", () => {
    const result = computeAchievements(baseInput());
    const ids = result.map((a) => a.id);
    const uniqueIds = new Set(ids);
    expect(uniqueIds.size).toBe(ids.length);
  });

  it("debate progress is 0 with no debates", () => {
    const result = computeAchievements(baseInput());
    expect(result.find((a) => a.id === "debate-first")!.progress).toBe(0);
  });

  it("debate-all-sides progress is 50 after one side only", () => {
    const input = baseInput({
      activities: [makeDebateActivity("user", { userSide: "pro" })],
    });
    const result = computeAchievements(input);
    expect(result.find((a) => a.id === "debate-all-sides")!.progress).toBe(50);
  });

  it("non-debate critical-thinking activities do not count as debates", () => {
    const input = baseInput({
      activities: [
        makeActivity({
          category: "critical-thinking",
          exerciseType: "flaw-finder",
          metadata: null,
        }),
      ],
    });
    const result = computeAchievements(input);
    expect(result.find((a) => a.id === "debate-first")!.earned).toBe(false);
  });

  it("debate activity with malformed metadata does not crash and is not a win", () => {
    const input = baseInput({
      activities: [
        makeActivity({
          category: "critical-thinking",
          exerciseType: "debate",
          metadata: "NOT_VALID_JSON",
        }),
      ],
    });
    // Should not throw, debate-first should be earned (1 activity exists), but win should not
    const result = computeAchievements(input);
    expect(result.find((a) => a.id === "debate-first")!.earned).toBe(true);
    expect(result.find((a) => a.id === "debate-win-1")!.earned).toBe(false);
  });
});

// ─── achievementSummary ───────────────────────────────────────────────────────

describe("achievementSummary", () => {
  it("total equals number of achievements in the list", () => {
    const result = computeAchievements(baseInput());
    const summary = achievementSummary(result);
    expect(summary.total).toBe(result.length);
  });

  it("earned is 0 when nothing is earned", () => {
    const result = computeAchievements(baseInput());
    const summary = achievementSummary(result);
    expect(summary.earned).toBe(0);
  });

  it("earned count matches actual earned achievements", () => {
    const input = baseInput({ user: { ...baseInput().user, level: 50, totalXp: 1000 } });
    const result = computeAchievements(input);
    const expected = result.filter((a) => a.earned).length;
    const summary = achievementSummary(result);
    expect(summary.earned).toBe(expected);
  });

  it("byTier sums to total", () => {
    const result = computeAchievements(baseInput());
    const summary = achievementSummary(result);
    const tierTotal = Object.values(summary.byTier).reduce((s, v) => s + v.total, 0);
    expect(tierTotal).toBe(summary.total);
  });

  it("byTier earned sums to overall earned", () => {
    const input = baseInput({ user: { ...baseInput().user, level: 10, totalXp: 5000 } });
    const result = computeAchievements(input);
    const summary = achievementSummary(result);
    const tierEarned = Object.values(summary.byTier).reduce((s, v) => s + v.earned, 0);
    expect(tierEarned).toBe(summary.earned);
  });

  it("has all 4 tier keys", () => {
    const result = computeAchievements(baseInput());
    const summary = achievementSummary(result);
    expect(summary.byTier.bronze).toBeDefined();
    expect(summary.byTier.silver).toBeDefined();
    expect(summary.byTier.gold).toBeDefined();
    expect(summary.byTier.platinum).toBeDefined();
  });
});