File size: 243,987 Bytes
cf9e1bd
 
 
 
 
 
 
95be3b8
 
 
 
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2990854
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
 
 
 
756f8b1
 
2990854
 
 
 
 
 
 
 
 
 
 
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f6242e
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756f8b1
2990854
 
 
756f8b1
 
2990854
756f8b1
 
 
2990854
 
756f8b1
 
 
 
 
 
 
 
 
 
 
2990854
 
 
 
756f8b1
 
 
 
2990854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95be3b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95be3b8
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756f8b1
00466c9
2990854
cf9e1bd
8f6242e
 
2990854
cf9e1bd
 
 
00466c9
8f6242e
cf9e1bd
 
 
 
 
 
 
 
2990854
cf9e1bd
 
2990854
 
 
 
 
 
 
 
 
cf9e1bd
 
 
 
 
 
00466c9
 
 
8f6242e
 
00466c9
 
 
 
 
 
 
 
 
 
8f6242e
 
95be3b8
00466c9
8f6242e
00466c9
8f6242e
 
 
00466c9
 
 
 
 
 
 
 
 
 
 
cf9e1bd
 
 
 
 
756f8b1
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f6242e
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f6242e
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2990854
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
cf9e1bd
 
 
00466c9
 
cf9e1bd
00466c9
cf9e1bd
 
 
756f8b1
8f6242e
cf9e1bd
 
 
 
 
 
 
756f8b1
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f6242e
cf9e1bd
 
 
 
 
 
 
 
 
 
756f8b1
2990854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f6242e
2990854
756f8b1
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2990854
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
 
 
 
 
 
 
 
 
 
 
 
2990854
 
 
 
 
 
 
00466c9
 
2990854
00466c9
 
 
 
 
95be3b8
 
 
2990854
95be3b8
 
00466c9
 
2990854
 
 
 
 
 
 
00466c9
 
 
 
 
 
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
8f6242e
 
 
 
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f6242e
 
 
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f6242e
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95be3b8
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00466c9
 
 
 
2990854
 
00466c9
2990854
8f6242e
 
 
 
 
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2990854
cf9e1bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="robots" content="noindex">
<title>StepWise Self-Checks</title>
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#2f5bd3">
<link rel="apple-touch-icon" href="icon-192.png">
<link rel="icon" type="image/png" href="icon-192.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:ital,wght@0,400;0,700;1,400&family=Familjen+Grotesk:wght@500;600;700&family=JetBrains+Mono:wght@400;600&display=swap">
<style>
html { -webkit-text-size-adjust: 100%; }
body { margin: 0; }
[hidden] { display: none !important; }
/* Layout: a squared exercise-book page. One column of work, a header strip with the
   student's name, results shown as marks in the margin. */
:root {
  --paper: #f3f5f2;
  --sheet: #ffffff;
  --grid: #e3e8e2;
  --ink: #1d2738;
  --ink-soft: #5b6577;
  --rule: #d5dbd3;
  --accent: #2f5bd3;
  --accent-ink: #ffffff;
  --accent-wash: #e6ecfb;
  --good: #1f7a4d;
  --good-wash: #e2f3ea;
  --warn: #9a6a00;
  --warn-wash: #fbf1d6;
  --bad: #b3332b;
  --bad-wash: #fbe5e3;
  --font-display: "Familjen Grotesk", "Segoe UI", system-ui, sans-serif;
  --font-body: "Atkinson Hyperlegible", "Segoe UI", system-ui, sans-serif;
  --font-data: "JetBrains Mono", ui-monospace, "Cascadia Mono", Consolas, monospace;
  --radius: 10px;
}
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --paper: #12161d; --sheet: #1a2029; --grid: #1f2630; --ink: #e6eaf1; --ink-soft: #9aa4b5;
    --rule: #2c3442; --accent: #7f9ff0; --accent-ink: #0f1420; --accent-wash: #222c44;
    --good: #5cc28f; --good-wash: #183326; --warn: #e2b54a; --warn-wash: #33290f;
    --bad: #f08a80; --bad-wash: #3a1d1b; color-scheme: dark;
  }
}
:root[data-theme="dark"] {
  --paper: #12161d; --sheet: #1a2029; --grid: #1f2630; --ink: #e6eaf1; --ink-soft: #9aa4b5;
  --rule: #2c3442; --accent: #7f9ff0; --accent-ink: #0f1420; --accent-wash: #222c44;
  --good: #5cc28f; --good-wash: #183326; --warn: #e2b54a; --warn-wash: #33290f;
  --bad: #f08a80; --bad-wash: #3a1d1b; color-scheme: dark;
}
* { box-sizing: border-box; }
body {
  background-color: var(--paper);
  background-image:
    linear-gradient(var(--grid) 1px, transparent 1px),
    linear-gradient(90deg, var(--grid) 1px, transparent 1px);
  background-size: 24px 24px;
  color: var(--ink);
  font-family: var(--font-body);
  font-size: 16px;
  line-height: 1.55;
  padding-inline: 16px;
  padding-block: 0 calc(var(--dock-h, 0px) + var(--calc-h, 0px) + 32px);
}
.wrap { max-width: 1120px; margin: 0 auto; }
h1, h2, h3 { font-family: var(--font-display); text-wrap: balance; margin: 0; line-height: 1.2; }
h1 { font-size: 1.35rem; font-weight: 700; letter-spacing: -0.01em; }
h2 { font-size: 1.25rem; font-weight: 600; }
h3 { font-size: 1.05rem; font-weight: 600; }
p { margin: 0; }
.muted { color: var(--ink-soft); }
.mono { font-family: var(--font-data); font-variant-numeric: tabular-nums; }
.label { font-family: var(--font-display); font-size: 0.75rem; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink-soft); }

header.top {
  position: sticky; top: env(safe-area-inset-top, 0px); z-index: 5;
  background: color-mix(in srgb, var(--paper) 92%, transparent);
  backdrop-filter: blur(6px);
  border-bottom: 1px solid var(--rule);
  margin-inline: -16px; padding: 12px 16px;
}
header.top .row { max-width: 1120px; margin: 0 auto; display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; }
@media (max-width: 720px) { .brand .tag { display: none; } }
.brand { display: flex; align-items: baseline; gap: 10px; margin-right: auto; }
.brand .tag { font-family: var(--font-data); font-size: 0.75rem; color: var(--ink-soft); }
nav.tabs { display: flex; gap: 4px; background: var(--sheet); border: 1px solid var(--rule); border-radius: 999px; padding: 3px; }
nav.tabs button { border: 0; background: transparent; color: var(--ink-soft); font: 600 0.9rem var(--font-display); padding: 6px 14px; border-radius: 999px; cursor: pointer; }
nav.tabs button[aria-pressed="true"] { background: var(--ink); color: var(--paper); }
nav.tabs button { display: inline-flex; align-items: center; gap: 6px; }
nav.tabs .ic { font-size: 1rem; line-height: 1; }
@media (max-width: 720px) {
  header.top { backdrop-filter: none; background: var(--paper); }   /* a blur would trap the fixed bar inside the header */
  nav#places { position: fixed; left: 0; right: 0; bottom: 0; z-index: 7; border-radius: 0; border: 0; border-top: 1px solid var(--rule);
    justify-content: space-around; padding: 6px 4px calc(6px + env(safe-area-inset-bottom, 0px)); background: var(--sheet); }
  nav#places button { flex: 1; flex-direction: column; gap: 2px; font-size: .72rem; padding: 6px 2px; border-radius: 12px; }
  nav#places .ic { font-size: 1.3rem; }
  body:not(.in-chat):not(.in-quiz) .wrap { padding-bottom: 76px; }
  body.in-chat nav#places, body.in-quiz nav#places { display: none; }
}
.prog-list { display: grid; gap: 6px; }
.prog-row { display: grid; grid-template-columns: 1fr auto; gap: 4px 10px; align-items: center; text-align: left; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 10px; background: var(--paper); color: var(--ink); font: inherit; cursor: pointer; }
.prog-row:hover { border-color: var(--accent); }
.prog-row .prog-bar { grid-column: 1 / -1; height: 6px; border-radius: 99px; background: var(--rule); overflow: hidden; }
.prog-row .prog-bar span { display: block; height: 100%; background: var(--accent); }
.chat-group { margin-top: 14px; }
.stat-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 8px 0 12px; }
@media (max-width: 520px) { .stat-grid { grid-template-columns: repeat(2, 1fr); } }
.stat { border: 1px solid var(--rule); border-radius: 10px; padding: 10px; display: grid; gap: 2px; text-align: center; background: var(--paper); }
.stat strong { font-size: 1.5rem; }
.trend { font-size: .75rem; font-weight: 600; }
.trend.up { color: var(--good); } .trend.down { color: var(--ink-soft); }
.chart { margin: 6px 0 12px; }
.day-bars { display: flex; align-items: flex-end; gap: 3px; height: 120px; padding-top: 16px; border-bottom: 1px solid var(--rule); }
.day-bars .day { flex: 1; height: 100%; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; position: relative; min-width: 0; }
.day-bars .bar { width: 100%; max-width: 28px; background: var(--accent); border-radius: 4px 4px 0 0; min-height: 2px; }
.day-bars .dot { position: absolute; top: -14px; font-size: .7rem; font-weight: 700; color: var(--good); }
.day-bars .lbl { position: absolute; bottom: -18px; font-size: .65rem; color: var(--ink-soft); white-space: nowrap; }
.chart { padding-bottom: 18px; }
.idea-list ul, .report-extra { margin: 4px 0 10px; padding-left: 20px; display: grid; gap: 4px; }
.period { flex-wrap: wrap; }
.period-box { display: grid; gap: 8px; margin-bottom: 8px; }
.coach .bubble { margin: 8px 0; }
.note { border-left: 4px solid var(--accent); padding: 4px 12px; margin: 6px 0; }
.note-text { font-size: 1.1rem; margin: 4px 0 8px; }
.note-form { display: grid; gap: 8px; margin: 8px 0; }
.note-form textarea { font: inherit; padding: 8px 10px; border: 1px solid var(--rule); border-radius: 8px; background: var(--sheet); color: var(--ink); }
.note-form .btn { justify-self: start; }
.kid-chips { margin: 4px 0 10px; }
.chat-log-row { display: block !important; border-top: 0 !important; }
.nudge { border: 2px solid var(--accent); border-radius: 12px; padding: 12px 14px; background: var(--sheet); display: grid; gap: 8px; animation: nudge-in .3s ease-out; }
.nudge p { margin: 0; }
@keyframes nudge-in { from { transform: translateY(6px); opacity: 0; } to { transform: none; opacity: 1; } }
.stay-hint { margin: 0 0 8px; }
.focus-bar { height: 8px; border-radius: 4px; background: var(--rule); overflow: hidden; margin: 4px 0 6px; }
.focus-bar span { display: block; height: 100%; background: var(--accent); }
.calc { position: fixed; right: 16px; bottom: calc(var(--dock-h, 64px) + 10px); z-index: 7; width: 300px; max-width: calc(100vw - 32px);
  background: var(--sheet); color: var(--ink); border: 1px solid var(--rule); border-radius: 14px; padding: 10px; box-shadow: 0 10px 30px rgba(0,0,0,.18); }
.calc-head { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.calc-head .hint { margin-right: auto; }
.calc-out { min-height: 1.3em; text-align: right; color: var(--ink-soft); font-size: 0.9rem; overflow-wrap: anywhere; }
.calc-out.err { color: var(--bad, #b3261e); }
.calc-in { width: 100%; box-sizing: border-box; font-size: 1.25rem; text-align: right; padding: 8px 10px; border: 1px solid var(--rule); border-radius: 8px; background: var(--paper); color: var(--ink); margin: 4px 0 8px; }
.calc-keys { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; }
.ck { font: inherit; font-size: 1rem; padding: 10px 0; border-radius: 8px; border: 1px solid var(--rule); background: var(--paper); color: var(--ink); cursor: pointer; }
.ck.op, .ck.fn { background: var(--rule); }
.ck.eq { background: var(--accent); color: #fff; border-color: var(--accent); }
@media (max-width: 560px) { .calc { left: 16px; right: 16px; width: auto; padding: 8px; } .ck { padding: 8px 0; } .calc-keys { gap: 5px; } }
.kid-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; margin: 0 0 12px; }
.kid-card { display: grid; gap: 4px; text-align: left; padding: 14px 16px; border: 2px solid var(--rule); border-radius: 12px; background: var(--sheet); color: var(--ink); font: inherit; cursor: pointer; }
.kid-card.on { border-color: var(--accent); }
.kid-card strong { font-size: 1.15rem; }
.chat-log { display: grid; gap: 8px; margin-top: 10px; max-height: 70vh; overflow: auto; padding: 4px; border-top: 1px solid var(--rule); }
.topic-fold > summary { list-style: none; display: flex; gap: 12px; align-items: center; cursor: pointer; padding: 4px 0; }
.topic-fold > summary::-webkit-details-marker { display: none; }
.topic-fold > summary::after { content: "▾"; margin-left: auto; color: var(--ink-soft); transition: transform 120ms; font-size: 1.4rem; padding: 0 6px; }
.topic-fold:not([open]) > summary::after { transform: rotate(-90deg); }
.topic-fold .topic-sum { display: grid; gap: 2px; }
.topic-fold .topic-body { margin: 8px 0 4px 0; display: grid; gap: 10px; }
.topic.current .topic-fold > summary strong { color: var(--accent); }
.parts-list li.next { background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; padding: 6px; }
details.more > summary { cursor: pointer; color: var(--ink-soft); font-size: .9rem; margin: 2px 0 6px; }
.btn.small { padding: 6px 12px; font-size: .85rem; }
.chat-strip { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; }
.chat-strip > span { margin-right: auto; font-weight: 600; }
.week-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; text-align: center; }
.week-stats strong { display: block; font-size: 1.4rem; }
.back-top { margin-bottom: 4px; }
.who { display: flex; align-items: center; gap: 8px; }
.who-chip { font: 600 0.9rem var(--font-display); padding: 6px 12px; border-radius: 999px; border: 1px dashed var(--rule); background: var(--sheet); color: var(--ink); cursor: pointer; }
.who-chip.set { border-style: solid; border-color: var(--accent); }

main { display: grid; gap: 20px; padding-top: 20px; }
.sheet { background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); padding: 20px; display: grid; gap: 14px; min-width: 0; }
.notice { border-left: 4px solid var(--warn); background: var(--warn-wash); padding: 12px 14px; border-radius: 6px; }
.notice.bad { border-color: var(--bad); background: var(--bad-wash); }
.notice.good { border-color: var(--good); background: var(--good-wash); }

button.btn, a.btn {
  display: inline-block; text-decoration: none;
  font: 600 0.95rem var(--font-display); border-radius: 8px; padding: 10px 16px; cursor: pointer;
  border: 1px solid var(--ink); background: var(--ink); color: var(--paper);
}
button.btn.ghost, a.btn.ghost { background: transparent; color: var(--ink); border-color: var(--rule); }
button.btn.accent { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
button.btn:disabled { opacity: 0.5; cursor: not-allowed; }
button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-visible, label.opt:focus-within { outline: 3px solid var(--accent); outline-offset: 2px; }

.students { display: flex; flex-wrap: wrap; gap: 10px; }
.student {
  font: 600 1rem var(--font-display); padding: 12px 18px; border-radius: 10px; cursor: pointer;
  border: 1px solid var(--rule); background: var(--sheet); color: var(--ink); min-width: 120px; text-align: left;
}
.student[aria-pressed="true"] { border-color: var(--accent); background: var(--accent-wash); }
.add-student { display: flex; flex-wrap: wrap; gap: 8px; }
.add-student input { flex: 1 1 180px; min-width: 0; }
input[type="text"], input[type="number"], textarea, select {
  font: 1rem var(--font-body); color: var(--ink); background: var(--paper);
  border: 1px solid var(--rule); border-radius: 8px; padding: 10px 12px;
}
textarea { width: 100%; min-height: 110px; resize: vertical; }

.sets { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 14px; }
.set-card {
  text-align: left; cursor: pointer; display: grid; gap: 8px; align-content: start;
  background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); padding: 16px; color: var(--ink); font: inherit;
}
.set-card:hover { border-color: var(--accent); }
.set-card .code { font-family: var(--font-data); font-size: 0.8rem; color: var(--ink-soft); }
.set-card .meta { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 0.85rem; color: var(--ink-soft); }
.pill { display: inline-flex; align-items: center; gap: 6px; font: 600 0.8rem var(--font-data); padding: 3px 9px; border-radius: 999px; background: var(--paper); border: 1px solid var(--rule); }
.pill.good { background: var(--good-wash); color: var(--good); border-color: transparent; }
.pill.warn { background: var(--warn-wash); color: var(--warn); border-color: transparent; }
.pill.bad { background: var(--bad-wash); color: var(--bad); border-color: transparent; }
.subject-head { display: flex; align-items: baseline; gap: 10px; margin-top: 4px; }

.test-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 18px; }
.test-bar .timer { font: 600 1.1rem var(--font-data); }
.q { display: grid; grid-template-columns: 52px 1fr; gap: 12px; padding-top: 16px; border-top: 1px solid var(--rule); }
.q:first-of-type { border-top: 0; padding-top: 0; }
.q .num { font: 700 1.05rem var(--font-data); color: var(--ink-soft); }
.q .body { display: grid; gap: 10px; min-width: 0; }
.q .prompt { white-space: pre-wrap; overflow-wrap: anywhere; }
.q .marks { font: 600 0.8rem var(--font-data); color: var(--ink-soft); }
.opts { display: grid; gap: 8px; }
label.opt { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 8px; cursor: pointer; background: var(--paper); }
label.opt input { margin-top: 4px; accent-color: var(--accent); }
label.opt.right { border-color: var(--good); background: var(--good-wash); }
label.opt.wrong { border-color: var(--bad); background: var(--bad-wash); }
.numeric { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.numeric input { width: 12rem; max-width: 100%; }
.hint { font-size: 0.85rem; color: var(--ink-soft); }
.verdict { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.scheme { background: var(--paper); border: 1px solid var(--rule); border-radius: 8px; padding: 10px 12px; display: grid; gap: 6px; font-size: 0.95rem; }
.selfmark { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.selfmark button { font: 600 0.9rem var(--font-data); min-width: 40px; padding: 6px 10px; border-radius: 6px; border: 1px solid var(--rule); background: var(--sheet); color: var(--ink); cursor: pointer; }
.selfmark button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }

.dock { position: fixed; left: 0; right: 0; bottom: 0; z-index: 6; padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px)); background: color-mix(in srgb, var(--paper) 94%, transparent); backdrop-filter: blur(6px); border-top: 1px solid var(--rule); }
.dock .row { max-width: 1120px; margin: 0 auto; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: flex-end; }
.dock .row .status { margin-right: auto; font-size: 0.9rem; color: var(--ink-soft); }

.score-big { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
.score-big .n { font: 700 2.4rem var(--font-data); }
.bar { height: 10px; border-radius: 999px; background: var(--paper); border: 1px solid var(--rule); overflow: hidden; }
.bar > span { display: block; height: 100%; background: var(--accent); }
.bar.good > span { background: var(--good); }
.bar.warn > span { background: var(--warn); }
.bar.bad > span { background: var(--bad); }

.table-wrap { overflow-x: auto; }
table { border-collapse: collapse; width: 100%; font-size: 0.92rem; }
th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--rule); vertical-align: top; }
th { font: 600 0.75rem var(--font-display); letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-soft); }
td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-numeric: tabular-nums; white-space: nowrap; }
.atom-row { display: grid; grid-template-columns: 1fr 120px 56px; gap: 10px; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--rule); }
.atom-row .stmt { min-width: 0; overflow-wrap: anywhere; }
.atom-row .id { font: 0.75rem var(--font-data); color: var(--ink-soft); }
@media (max-width: 520px) {
  .q { grid-template-columns: 1fr; }
  .atom-row { grid-template-columns: 1fr 64px; }
  .atom-row .bar { display: none; }
}
.toast { position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(84px + env(safe-area-inset-bottom, 0px)); background: var(--ink); color: var(--paper); padding: 10px 16px; border-radius: 8px; font: 600 0.95rem var(--font-display); z-index: 9; }
.empty { display: grid; gap: 8px; padding: 8px 0; }

/* tutor */
.lv-bar { display: flex; height: 10px; border-radius: 999px; overflow: hidden; border: 1px solid var(--rule); background: var(--paper); }
.lv { display: block; height: 100%; }
.lv0 { background: var(--rule); } .lv1 { background: #a9c4ef; } .lv2 { background: #6b98e0; }
.lv3 { background: var(--accent); } .lv4 { background: var(--good); }
.lv-dot { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 6px; vertical-align: -1px; }
.legend { display: flex; flex-wrap: wrap; gap: 6px 16px; font-size: 0.85rem; color: var(--ink-soft); }
.set-card .students { gap: 8px; }
.chat { gap: 12px; }
.bubble { max-width: 88%; padding: 10px 14px; border-radius: 12px; display: grid; gap: 6px; min-width: 0; }
.bubble p { white-space: pre-wrap; overflow-wrap: anywhere; }
.bubble.tutor { background: var(--paper); border: 1px solid var(--rule); justify-self: start; border-top-left-radius: 4px; }
.bubble.me { background: var(--accent-wash); justify-self: end; border-top-right-radius: 4px; }
.bubble.system { background: var(--bad-wash); justify-self: center; }
.chat.log { display: grid; gap: 10px; padding: 12px; background: var(--paper); border-radius: var(--radius); }
.chat-row { width: 100%; }
/* chat: header, its own scrolling message area, and the composer inside one panel */
body.in-chat { padding-block: 0; overflow: hidden; }
body.in-chat .wrap { height: calc(100dvh - var(--hdr-h, 64px)); }
body.in-chat main { height: 100%; padding-block: 12px; display: block; }
.chat-shell { display: flex; flex-direction: column; height: 100%; min-height: 0; background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); overflow: hidden; }
.chat-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; padding: 12px 16px; border-bottom: 1px solid var(--rule); }
.chat-head .title { margin-right: auto; min-width: 0; }
.chat-head h2 { font-size: 1.05rem; }
.chat-scroll { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 18px 16px; display: flex; flex-direction: column; gap: 14px; scroll-behavior: smooth; }
@media (prefers-reduced-motion: reduce) { .chat-scroll { scroll-behavior: auto; } }
.chat-scroll .bubble { max-width: min(760px, 88%); }
.chat-scroll .bubble.tutor { align-self: flex-start; }
.chat-scroll .bubble.me { align-self: flex-end; }
.chat-scroll .bubble.system { align-self: center; }
.chat-composer { border-top: 1px solid var(--rule); background: var(--paper); padding: 10px 16px calc(10px + env(safe-area-inset-bottom, 0px)); display: grid; gap: 8px; }
.chat-composer .input-row { display: flex; gap: 8px; align-items: flex-end; }
.chat-composer textarea { flex: 1; min-width: 0; min-height: 44px; max-height: 180px; resize: none; line-height: 1.45; background: var(--sheet); }
.chat-composer .meta-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
.chat-composer .meta-row .selfmark { margin-right: auto; }
.chat-composer .feel-row { margin: 6px 0 2px; }
.chat-composer .feel-row button { font: 600 0.8rem var(--font-body, inherit); }
.chat-composer .feel-row button.armed { outline: 2px solid var(--accent, #c2410c); outline-offset: 1px; }
.typing { display: inline-flex; gap: 4px; padding: 4px 0; }
.typing span { width: 6px; height: 6px; border-radius: 50%; background: var(--ink-soft); opacity: 0.4; }
@media (prefers-reduced-motion: no-preference) {
  .typing span { animation: blink 1.2s infinite; } .typing span:nth-child(2) { animation-delay: .2s; } .typing span:nth-child(3) { animation-delay: .4s; }
  @keyframes blink { 0%, 80%, 100% { opacity: .25; } 40% { opacity: .9; } }
}
.md { display: grid; gap: 8px; }
.md p { white-space: normal; }
.md ul, .md ol { margin: 0; padding-left: 1.3em; display: grid; gap: 3px; }
.md code { font-family: var(--font-data); font-size: 0.9em; background: var(--paper); padding: 0 4px; border-radius: 4px; }
.bubble-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; opacity: 0.6; }
.bubble:hover .bubble-actions, .bubble-actions:focus-within { opacity: 1; }
.react { font: 600 0.75rem var(--font-display); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--rule); background: var(--sheet); color: var(--ink-soft); cursor: pointer; }
.react[aria-pressed="true"] { border-color: var(--good); color: var(--good); }
.composer { display: grid; gap: 8px; width: 100%; }
.chapter-card .lv-bar { margin-top: 4px; }
.topic-path { list-style: none; margin: 0; padding: 0; display: grid; gap: 0; }
.topic { display: grid; grid-template-columns: 44px 1fr; gap: 14px; padding: 16px 0; border-top: 1px solid var(--rule); position: relative; }
.topic:first-child { border-top: 0; padding-top: 4px; }
.topic-num { width: 36px; height: 36px; border-radius: 50%; display: grid; place-items: center; font: 700 1rem var(--font-display); background: var(--paper); border: 2px solid var(--rule); color: var(--ink-soft); }
.topic.done .topic-num { background: var(--good); border-color: var(--good); color: #fff; }
.topic.final .topic-num { border-style: dashed; }
.topic-body { display: grid; gap: 8px; min-width: 0; }
.topic:has(> .topic-fold) { display: block; }
.topic-fold .topic-num { flex: 0 0 36px; }
.topic-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.steps { list-style: none; margin: 0; padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px 14px; border-bottom: 1px solid var(--rule); background: var(--paper); }
.step { display: inline-flex; align-items: center; gap: 6px; font: 600 0.82rem var(--font-display); color: var(--ink-soft); }
.step .dot { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-size: 0.75rem; border: 2px solid var(--rule); background: var(--sheet); }
.step.done .dot { background: var(--good); border-color: var(--good); color: #fff; }
.step.now { color: var(--ink); } .step.now .dot { border-color: var(--accent); color: var(--accent); }
.summary-card { align-self: stretch; border: 2px solid var(--good); background: var(--good-wash); border-radius: var(--radius); padding: 14px 16px; display: grid; gap: 8px; }
.summary-card ul { margin: 0; padding-left: 1.2em; }
.back-link { display: block; margin-bottom: 6px; }

/* quiz player */
.quizbar { position: sticky; top: var(--hdr-h, 64px); z-index: 4; background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); padding: 12px 16px; display: grid; gap: 10px; box-shadow: 0 6px 18px -14px rgba(0,0,0,.35); }
.quizbar-top { display: flex; align-items: center; gap: 12px; }
.quizbar-top .title { margin-right: auto; min-width: 0; }
.quizbar-top h2 { font-size: 1.1rem; }
.timer-box { display: grid; justify-items: end; line-height: 1.1; }
.timer-box .timer { font-size: 1.35rem; }
.timer.over { color: var(--warn); }
.timer.good { color: var(--good); } .timer.warn { color: var(--warn); } .timer.bad { color: var(--bad); }
.qnav { display: flex; gap: 6px; overflow-x: auto; padding-bottom: 2px; scrollbar-width: thin; }
.qchip { flex: 0 0 auto; min-width: 40px; height: 40px; border-radius: 10px; border: 2px solid var(--rule); background: var(--paper); color: var(--ink); font: 700 0.95rem var(--font-data); cursor: pointer; position: relative; }
.qchip.answered { background: var(--accent-wash); border-color: var(--accent-wash); }
.qchip.marked::after { content: ""; position: absolute; top: 3px; right: 3px; width: 8px; height: 8px; border-radius: 50%; background: var(--warn); }
.qchip.right { background: var(--good-wash); border-color: var(--good); color: var(--good); }
.qchip.part { background: var(--warn-wash); border-color: var(--warn); color: var(--warn); }
.qchip.wrong { background: var(--bad-wash); border-color: var(--bad); color: var(--bad); }
.qchip.pending { border-style: dashed; border-color: var(--ink-soft); }
.qchip.notlearnt { border-style: dotted; border-color: var(--ink-soft); color: var(--ink-soft); background: var(--paper); }
.notlearnt-btn { margin-top: 10px; }
.notlearnt-btn[aria-pressed="true"] { background: var(--warn-wash); color: var(--warn); border-color: var(--warn); }
/* learning in parts (CHUNK_MODEL.md) */
.parts-bar { padding: 8px 16px; border-bottom: 1px solid var(--rule); background: var(--paper); display: grid; gap: 6px; }
.parts-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
.part-dot { display: inline-flex; align-items: center; gap: 5px; font: 600 0.8rem var(--font-display); color: var(--ink-soft); }
.part-dot .dot { width: 20px; height: 20px; border-radius: 6px; display: grid; place-items: center; font-size: 0.72rem; border: 2px solid var(--rule); background: var(--sheet); }
.part-dot.learned .dot { background: var(--good); border-color: var(--good); color: #fff; }
.part-dot.now { color: var(--ink); } .part-dot.now .dot { border-color: var(--accent); color: var(--accent); }
.idea-chips { display: flex; flex-wrap: wrap; gap: 6px; }
.idea-chip { font: 500 0.78rem var(--font-data); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--rule); background: var(--sheet); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.idea-chip.learning { background: var(--warn-wash); color: var(--warn); border-color: transparent; }
.idea-chip.got { background: var(--good-wash); color: var(--good); border-color: transparent; }
.idea-chip.following { background: var(--accent-wash); color: var(--accent); border-color: transparent; }
.part-card { align-self: stretch; border: 2px solid var(--accent); background: var(--accent-wash); border-radius: var(--radius); padding: 14px 16px; display: grid; gap: 8px; }
.part-card ul { margin: 0; padding-left: 1.2em; }
.cheer { margin: 10px 0; padding: 14px 16px; border-radius: 12px; border: 1px solid var(--rule); border-left: 6px solid var(--accent); background: var(--sheet); }
.cheer strong { display: block; font-size: 1.1rem; margin-bottom: 4px; }
.cheer p { margin: 0; }
.cheer.good { border-left-color: #2e7d4f; }
.cheer.warn { border-left-color: #b7791f; }
.cheer.bad { border-left-color: var(--accent); }
.cheer-line { font-style: italic; margin: 4px 0 8px; }
.login { max-width: 460px; margin-inline: auto; }
.chat-composer.read-only { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: space-between; }
.login-form { display: grid; gap: 6px; margin: 12px 0; }
.login-form label { font-weight: 600; margin-top: 6px; }
.login-form input, .login-form select, .admin-user input[type=text] { font: inherit; padding: 8px 10px; border: 1px solid var(--rule); border-radius: 8px; background: var(--sheet); color: var(--ink); }
.login-form .btn { margin-top: 10px; justify-self: start; }
.admin-user { display: grid; gap: 8px; padding: 6px 0 12px; }
.admin-user .btn { justify-self: start; }
.chat-list { list-style: none; margin: 8px 0; padding: 0; display: grid; gap: 8px; }
.chat-list li { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: space-between; padding: 8px 0; border-top: 1px solid var(--rule); }
.parts-list { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 8px; }
.parts-list li { display: grid; grid-template-columns: 26px 1fr; gap: 10px; align-items: start; }
.parts-list .pnum { width: 24px; height: 24px; border-radius: 7px; display: grid; place-items: center; font: 700 0.75rem var(--font-data); border: 2px solid var(--rule); }
.parts-list li.learned .pnum { background: var(--good); border-color: var(--good); color: #fff; }
.parts-list .pbody { display: grid; gap: 4px; min-width: 0; }
.parts-list .pbody .topic-actions { gap: 6px; }
.qchip.current { outline: 3px solid var(--accent); outline-offset: 2px; }
.qchip.mini { display: inline-block; min-width: 14px; width: 14px; height: 14px; border-radius: 4px; vertical-align: -2px; margin-right: 6px; cursor: default; }
.qchip.mini.marked::after { top: 2px; right: 2px; width: 6px; height: 6px; }
.qcard { gap: 16px; }
.qcard-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
.qcard-head .marks { margin-right: auto; }
.qcard .prompt { font-size: 1.08rem; }
.qcard-nav { display: flex; justify-content: space-between; gap: 10px; padding-top: 8px; border-top: 1px solid var(--rule); }
.qflags { display: grid; gap: 8px; padding: 10px 12px; border-radius: 8px; background: var(--paper); }
.qflag-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
.qflag-row .hint { min-width: 150px; }
.select-n { font: 700 0.8rem var(--font-display); letter-spacing: 0.06em; text-transform: uppercase; color: var(--accent); }
.idea-ch { display: grid; gap: 8px; padding-top: 10px; border-top: 1px solid var(--rule); }
.idea-list { display: grid; gap: 4px; font-size: 0.92rem; }
.idea { display: flex; gap: 8px; align-items: baseline; }
.composer textarea { min-height: 56px; }
.composer-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; justify-content: flex-end; }
.composer-row .selfmark { margin-right: auto; }

/* feedback */
.fb { display: grid; gap: 8px; }
.fb-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.fb-toggle { justify-self: start; background: none; border: 0; padding: 2px 0; color: var(--accent); font: 600 0.85rem var(--font-display); cursor: pointer; text-decoration: underline; text-underline-offset: 3px; }
.fb textarea { min-height: 64px; }
.fb-actions { display: flex; justify-content: flex-end; gap: 8px; }
.fb-list { display: grid; gap: 8px; }
.fb-item { border: 1px solid var(--rule); border-left: 4px solid var(--warn); border-radius: 8px; padding: 10px 12px; display: grid; gap: 6px; background: var(--sheet); }
.fb-item.resolved { border-left-color: var(--good); opacity: 0.8; }
.fb-excerpt { font-size: 0.9rem; color: var(--ink-soft); border-left: 2px solid var(--rule); padding-left: 8px; white-space: pre-wrap; overflow-wrap: anywhere; }
.student.parent { border-style: dashed; }
.fb-chip { border-style: solid; color: var(--accent); }
.app-fb { border-color: var(--accent); }
.fb-chip .short { display: none; }
.timer { white-space: nowrap; }
@media (max-width: 560px) {
  .fb-chip .long { display: none; } .fb-chip .short { display: inline; }
  header.top .row { gap: 8px; }
  .brand h1 { font-size: 1.1rem; }
  .quizbar { padding: 10px 12px; }
  .quizbar-top .label { display: none; }
  .timer-box .timer { font-size: 1.05rem; }
  .qchip { min-width: 36px; height: 36px; }
}
.opts-list { margin: 0; padding-left: 1.4em; display: grid; gap: 4px; }
.opts-list li.right { color: var(--good); font-weight: 700; }
/* home: carry on, review, subjects; subject page: units with a path of chapters */
.student { display: grid; gap: 2px; }
.student .hint { font: 400 0.8rem var(--font-body); }
.home-hello { display: grid; gap: 4px; padding: 4px 2px 0; }
.home-hello h2 { font-size: 1.6rem; font-weight: 700; }
.section-title { font-size: 1.1rem; margin: 0 0 10px; }
.home-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 20px; }
.next-card { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
.next-card h3 { font-size: 1.3rem; }
.q-line { font-style: italic; }
.due-list { display: flex; flex-wrap: wrap; gap: 6px; }
.subject-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 260px), 1fr)); gap: 14px; }
.subject-card { text-align: left; cursor: pointer; display: grid; gap: 10px; align-content: start; background: var(--sheet); border: 1px solid var(--rule); border-radius: var(--radius); padding: 16px; color: var(--ink); font: inherit; min-width: 0; }
.subject-card:hover { border-color: var(--subj); }
.subject-card.soon { cursor: default; border-style: dashed; }
.subject-card .meta, .ch-card .meta { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 0.85rem; color: var(--ink-soft); align-items: center; }
.subject-top { display: flex; gap: 12px; align-items: center; min-width: 0; }
.subj-mark { width: 40px; height: 40px; border-radius: 10px; display: grid; place-items: center; font: 700 1.05rem var(--font-display); background: var(--subj); color: #fff; flex: none; }
.subject-card .code, .ch-card .code { font-family: var(--font-data); font-size: 0.78rem; color: var(--ink-soft); }
.unit-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
.unit-num { font: 600 0.75rem var(--font-display); letter-spacing: 0.08em; text-transform: uppercase; color: var(--accent); }
.ch-path { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; }
.ch-stop { display: grid; grid-template-columns: 28px minmax(0, 1fr); gap: 12px; position: relative; }
.ch-stop::before { content: ""; position: absolute; left: 13px; top: 42px; bottom: -26px; width: 2px; background: var(--rule); }
.ch-stop:last-child::before { display: none; }
.ch-dot { width: 28px; height: 28px; border-radius: 50%; margin-top: 14px; border: 2px solid var(--rule); background: var(--sheet); display: grid; place-items: center; font: 700 0.85rem var(--font-display); color: #fff; position: relative; z-index: 1; }
.ch-stop.doing .ch-dot { border-color: var(--accent); background: var(--accent-wash); }
.ch-stop.done .ch-dot { border-color: var(--good); background: var(--good); }
.ch-card { text-align: left; cursor: pointer; display: grid; gap: 8px; background: var(--paper); border: 1px solid var(--rule); border-radius: var(--radius); padding: 14px 16px; color: var(--ink); font: inherit; min-width: 0; }
.ch-card:hover { border-color: var(--accent); }
.ch-top { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 6px 10px; align-items: center; }
.ch-top .pill { font: 600 0.78rem var(--font-display); white-space: normal; }
.pill.accent { background: var(--accent-wash); color: var(--accent); border-color: transparent; }
.ch-links { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.kid-subjects { padding: 6px 4px 10px; display: grid; gap: 10px; margin: 0; min-width: 0; }
details.fold { border: 1px solid var(--rule); border-radius: 8px; margin: 6px 0; background: var(--sheet); }
details.fold > summary { cursor: pointer; padding: 10px 14px; list-style: none; display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; }
details.fold > summary::-webkit-details-marker { display: none; }
details.fold > summary::before { content: "▸"; color: var(--ink-soft); margin-right: 2px; }
details.fold[open] > summary::before { content: "▾"; }
details.fold > .fold-body, details.fold > .kid-subjects { padding: 0 12px 10px 22px; }
.fold-body { display: grid; gap: 6px; }
.quiz-row { display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; text-align: left; padding: 8px 12px; border: 1px solid var(--rule); border-radius: 6px; background: var(--paper); color: var(--ink); font: inherit; cursor: pointer; }
.quiz-row:hover { border-color: var(--accent); }
.board-head { margin: 14px 0 4px; font: 600 .9rem var(--font-display); color: var(--ink-soft); text-transform: uppercase; letter-spacing: .04em; }
.kid-subjects legend { font: 600 1rem var(--font-display); padding: 0 6px; }
.board-row { display: grid; gap: 4px; }
.subj-checks { display: flex; flex-wrap: wrap; gap: 6px 18px; }
.subj-check { display: inline-flex; gap: 6px; align-items: center; cursor: pointer; }
.subj-check input { accent-color: var(--accent); width: 18px; height: 18px; }
@media (prefers-reduced-motion: no-preference) {
  .set-card, .student, .subject-card, .ch-card { transition: border-color 120ms ease, background-color 120ms ease; }
}
</style>
</head>
<body>


<header class="top">
  <div class="row">
    <div class="brand"><h1>StepWise</h1><span class="tag" id="brand-tag"></span></div>
    <nav class="tabs" id="places" aria-label="Sections">
      <button id="tab-practise" aria-pressed="true"><span class="ic" aria-hidden="true">🏠</span><span>Today</span></button>
      <button id="tab-subjects" aria-pressed="false"><span class="ic" aria-hidden="true">📚</span><span>Subjects</span></button>
      <button id="tab-chats" aria-pressed="false"><span class="ic" aria-hidden="true">💬</span><span>Chats</span></button>
      <button id="tab-tutor" aria-pressed="false" hidden>Tutor</button>
      <button id="tab-progress" aria-pressed="false"><span class="ic" aria-hidden="true">📈</span><span>Report</span></button>
      <button id="tab-bank" aria-pressed="false" hidden><span class="ic" aria-hidden="true">👪</span><span>Parent</span></button>
    </nav>
    <div class="who"><button id="app-fb" class="who-chip fb-chip" type="button" aria-label="Feedback on the app"><span class="long">Feedback on the app</span><span class="short">Feedback</span></button><button id="who" class="who-chip">Choose your name</button></div>
  </div>
</header>

<div class="wrap">
  <main id="main">
    <section class="sheet">
      <h2>Loading your self-checks</h2>
      <p class="muted">Loading your self-checks and results.</p>
    </section>
  </main>
</div>
<div id="dock" class="dock" hidden><div class="row" id="dock-row"></div></div>
<div id="toast" class="toast" role="status" hidden></div>

<script type="module">
  import * as V from "./visuals/render.js";
  const st = document.createElement("style"); st.textContent = V.CSS; document.head.append(st);
  window.StepVis = V; document.dispatchEvent(new Event("stepvis"));
</script>
<script>
(() => {
  "use strict";

  // ---------- tiny DOM helper (text only, never innerHTML for data) ----------
  function h(tag, props, ...kids) {
    const el = document.createElement(tag);
    if (props) for (const [k, v] of Object.entries(props)) {
      if (v == null || v === false) continue;
      if (k === "class") el.className = v;
      else if (k === "text") el.textContent = v;
      else if (k.startsWith("on")) el.addEventListener(k.slice(2), v);
      else el.setAttribute(k, v === true ? "" : v);
    }
    for (const kid of kids.flat()) {
      if (kid == null || kid === false) continue;
      el.append(kid instanceof Node ? kid : document.createTextNode(String(kid)));
    }
    return el;
  }
  const $ = (id) => document.getElementById(id);
  const store = {
    get(k) { try { return localStorage.getItem(k); } catch { return null; } },
    set(k, v) { try { localStorage.setItem(k, v); } catch {} },
    del(k) { try { localStorage.removeItem(k); } catch {} },
  };
  // ---------- focus: counted while a quiz or tutor chat is open ----------
  // "active" = StepWise on screen and touched, scrolled or typed in within IDLE_MS; "idle" = on screen but no input
  // for longer than that; "away" = another app or tab, or the screen off. "switches" = times the page was hidden.
  // A rough guide only: it can't see a second device, and a calculator app or a phone call counts as away.
  const FT = (() => {
    const IDLE_MS = 3 * 60 * 1000;
    const open = new Map();   // key -> { active, idle, away, switches } in ms
    let lastTick = Date.now(), lastInput = Date.now(), wasHidden = document.hidden;
    function tick() {
      const t = Date.now(), dt = Math.max(0, t - lastTick); lastTick = t;
      const k = wasHidden ? "away" : t - lastInput > IDLE_MS ? "idle" : "active";
      for (const c of open.values()) c[k] += dt;
      wasHidden = document.hidden;
    }
    const touch = () => { tick(); lastInput = Date.now(); };
    for (const ev of ["pointerdown", "keydown", "wheel", "touchstart", "scroll", "pointermove"]) addEventListener(ev, touch, { passive: true, capture: true });
    document.addEventListener("visibilitychange", () => {
      tick();
      if (document.hidden) for (const c of open.values()) c.switches += 1;
      else lastInput = Date.now();
    });
    setInterval(tick, 5000);
    return {
      start(key, seed) { tick(); const s = seed || {}; open.set(key, { active: (s.activeSec || 0) * 1000, idle: (s.idleSec || 0) * 1000, away: (s.awaySec || 0) * 1000, switches: s.switches || 0 }); },
      peek(key) { tick(); const c = open.get(key); return c ? { activeSec: Math.round(c.active / 1000), idleSec: Math.round(c.idle / 1000), awaySec: Math.round(c.away / 1000), switches: c.switches } : null; },
      openSec(key) { const v = this.peek(key); return v ? v.activeSec + v.idleSec + v.awaySec : 0; },
      take(key) { const v = this.peek(key); if (open.has(key)) open.set(key, { active: 0, idle: 0, away: 0, switches: 0 }); return v; },
      stop(key) { const v = this.peek(key); open.delete(key); return v; },
    };
  })();

  // ---------- calculator (in the quiz, so she never needs to leave for the phone's calculator) ----------
  // Its own small parser, no eval. Angles in degrees, as in IGCSE. Ans = the last result.
  const CALC = (() => {
    let ans = 0, el = null, inp = null, out = null;
    const FN = { sin: (x) => Math.sin(x * Math.PI / 180), cos: (x) => Math.cos(x * Math.PI / 180), tan: (x) => Math.tan(x * Math.PI / 180),
      "√": Math.sqrt, sqrt: Math.sqrt, log: Math.log10, ln: Math.log };
    function tokens(s) {
      const out = []; const re = /\s*(\d+\.?\d*(?:e[+-]?\d+)?|\.\d+(?:e[+-]?\d+)?|sin|cos|tan|sqrt|log|ln|Ans|ans|pi|π|√|[-+*/×÷^()−])/y;
      let m; re.lastIndex = 0;
      while (re.lastIndex < s.length) { const at = re.lastIndex; m = re.exec(s); if (!m) { if (/^\s*$/.test(s.slice(at))) break; throw new Error("?"); } out.push(m[1]); }
      return out.map((t) => ({ "×": "*", "÷": "/", "−": "-", pi: "π", ans: "Ans" }[t] || t));
    }
    function evaluate(src) {
      const t = tokens(src); let i = 0;
      const isVal = (x) => x != null && (/^[\d.]/.test(x) || x === "π" || x === "Ans" || x === ")");
      const startsVal = (x) => x != null && (/^[\d.]/.test(x) || x === "π" || x === "Ans" || x === "(" || x in FN);
      for (let k = t.length - 1; k > 0; k--) if (isVal(t[k - 1]) && startsVal(t[k])) t.splice(k, 0, "*");   // 2π, 3(4), 2sin30
      const peek = () => t[i], next = () => t[i++];
      function expr() { let v = term(); while (peek() === "+" || peek() === "-") v = next() === "+" ? v + term() : v - term(); return v; }
      function term() { let v = unary(); while (peek() === "*" || peek() === "/") v = next() === "*" ? v * unary() : v / unary(); return v; }
      function unary() { if (peek() === "-") { next(); return -unary(); } if (peek() === "+") { next(); return unary(); } return power(); }
      function power() { const b = primary(); if (peek() === "^") { next(); return Math.pow(b, unary()); } return b; }
      function primary() {
        const x = next();
        if (x == null) throw new Error("?");
        if (/^[\d.]/.test(x)) return parseFloat(x);
        if (x === "π") return Math.PI;
        if (x === "Ans") return ans;
        if (x === "(") { const v = expr(); if (peek() === ")") next(); return v; }   // a missing ")" at the end is fine
        if (x in FN) { const v = FN[x](peek() === "(" ? primary() : power()); return Math.abs(v) < 1e-12 ? 0 : v; }
        throw new Error("?");
      }
      const v = expr(); if (i < t.length) throw new Error("?");
      if (!isFinite(v)) throw new Error("Can't do that (dividing by zero?)");
      return v;
    }
    function fmt(v) {
      if (v === 0) return "0";
      const a = Math.abs(v);
      if (a >= 1e10 || a < 1e-6) { const [m, e] = v.toExponential(6).split("e"); return `${String(parseFloat(m))} × 10^${parseInt(e, 10)}`; }
      return String(parseFloat(v.toPrecision(10)));
    }
    function preview() { try { const s = inp.value.trim(); out.textContent = s ? `= ${fmt(evaluate(s))}` : ""; out.classList.remove("err"); } catch { out.textContent = ""; } }
    function equals() {
      const s = inp.value.trim(); if (!s) return;
      try { const v = evaluate(s); ans = v; inp.value = fmt(v).replace(" × 10^", "e"); out.textContent = `${s} =`; out.classList.remove("err"); }
      catch (e) { out.textContent = e.message === "?" ? "Check the sum" : e.message; out.classList.add("err"); }
    }
    function put(text) {
      const a = inp.selectionStart ?? inp.value.length, b = inp.selectionEnd ?? inp.value.length;
      inp.value = inp.value.slice(0, a) + text + inp.value.slice(b); const p = a + text.length; inp.setSelectionRange(p, p); preview();
    }
    function key(label, act, cls) { return h("button", { type: "button", class: `ck ${cls || ""}`, text: label, onclick: () => { act(); if (!matchMedia("(pointer: coarse)").matches) inp.focus(); } }); }
    function build() {
      inp = h("input", { type: "text", class: "calc-in mono", "aria-label": "Calculation", autocomplete: "off", spellcheck: "false", inputmode: matchMedia("(pointer: coarse)").matches ? "none" : "text" });
      inp.addEventListener("input", preview);
      inp.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === "=") { e.preventDefault(); equals(); } if (e.key === "Escape") { S.calcOpen = false; render(); } e.stopPropagation(); });
      out = h("div", { class: "calc-out mono", "aria-live": "polite" });
      const p = (s) => () => put(s);
      const rows = [
        [["sin", p("sin(")], ["cos", p("cos(")], ["tan", p("tan(")], ["√", p("√(")], ["xʸ", p("^")]],
        [["(", p("(")], [")", p(")")], ["π", p("π")], ["x²", p("^2")], ["⌫", () => { const a = inp.selectionStart ?? inp.value.length; if (a > 0 && a === inp.selectionEnd) { inp.value = inp.value.slice(0, a - 1) + inp.value.slice(a); inp.setSelectionRange(a - 1, a - 1); } else put(""); preview(); }, "fn"]],
        [["7", p("7")], ["8", p("8")], ["9", p("9")], ["÷", p("÷"), "op"], ["C", () => { inp.value = ""; out.textContent = ""; }, "fn"]],
        [["4", p("4")], ["5", p("5")], ["6", p("6")], ["×", p("×"), "op"], ["Ans", p("Ans")]],
        [["1", p("1")], ["2", p("2")], ["3", p("3")], ["−", p("−"), "op"], ["×10ˣ", p("e")]],
        [["0", p("0")], [".", p(".")], ["log", p("log(")], ["+", p("+"), "op"], ["=", equals, "eq"]],
      ];
      el = h("div", { class: "calc", id: "calc", role: "dialog", "aria-label": "Calculator", hidden: true },
        h("div", { class: "calc-head" }, h("strong", { text: "🧮 Calculator" }), h("span", { class: "hint", text: "angles in degrees" }),
          h("button", { type: "button", class: "react", "aria-label": "Close calculator", text: "✕", onclick: () => { S.calcOpen = false; render(); } })),
        out, inp, h("div", { class: "calc-keys" }, ...rows.flat().map(([l, f, c]) => key(l, f, c))));
      document.body.append(el);
    }
    return {
      show(on) {   // while open, the page gets extra room at the bottom so the question can scroll clear of it
        if (!el) { if (!on) return; build(); }
        el.hidden = !on; document.documentElement.style.setProperty("--calc-h", on ? `${el.getBoundingClientRect().height + 10}px` : "0px");
      },
      focus() { if (inp && !matchMedia("(pointer: coarse)").matches) requestAnimationFrame(() => inp.focus()); },
      evaluate, fmt,
    };
  })();
  window.__calc = CALC;

  // ---------- alarm: two short beeps and a buzz on phones that support it ----------
  const ALARM = (() => {
    let ctx = null;
    const unlock = () => { try { ctx = ctx || new (window.AudioContext || window.webkitAudioContext)(); if (ctx.state === "suspended") ctx.resume(); } catch {} };
    addEventListener("pointerdown", unlock, { capture: true, passive: true });
    addEventListener("keydown", unlock, { capture: true });
    return {
      ring() {
        try { if (navigator.vibrate) navigator.vibrate([250, 120, 250]); } catch {}
        if (!ctx) return;
        try {
          for (const [at, f] of [[0, 880], [0.28, 660], [0.56, 880]]) {
            const o = ctx.createOscillator(), g = ctx.createGain();
            o.frequency.value = f; o.type = "sine"; o.connect(g); g.connect(ctx.destination);
            const t0 = ctx.currentTime + at;
            g.gain.setValueAtTime(0.0001, t0); g.gain.exponentialRampToValueAtTime(0.3, t0 + 0.02); g.gain.exponentialRampToValueAtTime(0.0001, t0 + 0.22);
            o.start(t0); o.stop(t0 + 0.25);
          }
        } catch {}
      },
    };
  })();
  const BASE_TITLE = document.title;

  // ---------- reminders (notifications) ----------
  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
  const isStandalone = matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
  const PUSHS = { key: null, on: false, checked: false, busy: false };
  let swReg = null;
  if ("serviceWorker" in navigator) navigator.serviceWorker.register("sw.js", { scope: "./" }).then((r) => { swReg = r; }).catch(() => {});
  function pushSupported() { return "serviceWorker" in navigator && "PushManager" in window && "Notification" in window; }
  function b64uToBytes(s) { const p = "=".repeat((4 - s.length % 4) % 4); const b = atob((s + p).replace(/-/g, "+").replace(/_/g, "/")); return Uint8Array.from(b, (c) => c.charCodeAt(0)); }
  async function pushCheck() {
    if (PUSHS.checked) return; PUSHS.checked = true;
    try { const r = await api("api/push/key"); PUSHS.key = r.key; PUSHS.on = r.on;
      if (pushSupported() && Notification.permission === "granted") {   // this device may be subscribed even if another isn't
        const reg = swReg || await navigator.serviceWorker.ready; const sub = await reg.pushManager.getSubscription();
        PUSHS.here = !!sub; if (sub) api("api/push/subscribe", { method: "POST", body: JSON.stringify(sub.toJSON()) }).catch(() => {});
      }
    } catch {}
    render();
  }
  async function pushEnable() {
    if (PUSHS.busy) return; PUSHS.busy = true; render();
    try {
      const perm = await Notification.requestPermission();
      if (perm !== "granted") { toast("Reminders need notifications allowed"); return; }
      const reg = swReg || await navigator.serviceWorker.ready;
      const sub = (await reg.pushManager.getSubscription()) || await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64uToBytes(PUSHS.key) });
      await api("api/push/subscribe", { method: "POST", body: JSON.stringify(sub.toJSON()) });
      PUSHS.on = true; PUSHS.here = true;
      await api("api/push/test", { method: "POST", body: "{}" }).catch(() => {});
      toast("Reminders are on");
    } catch (e) { toast(e.message || "Couldn't turn on reminders"); } finally { PUSHS.busy = false; render(); }
  }
  async function pushDisable() {
    try { const reg = swReg || await navigator.serviceWorker.ready; const sub = await reg.pushManager.getSubscription();
      if (sub) { await api("api/push/unsubscribe", { method: "POST", body: JSON.stringify(sub.toJSON()) }); await sub.unsubscribe(); }
      PUSHS.here = false; toast("Reminders are off on this device"); } catch (e) { toast(e.message); }
    render();
  }
  // compact: the Today card (only while not set up on this device); full: the Account page
  function remindersCard(full) {
    if (!S.me || S.me.role !== "child") return null;
    pushCheck();
    if (!PUSHS.checked || !PUSHS.key) return null;
    const here = !!PUSHS.here;   // subscribed on this device
    if (!full && here) return null;
    const box = h("section", { class: "sheet reminders" }, h("h3", { text: "🔔 Reminders" }));
    if (isIOS && !isStandalone) {
      box.append(h("p", { text: "On iPhone or iPad, reminders work once StepWise is on your home screen:" }),
        h("ol", null, h("li", { text: "Tap the Share button (the square with an arrow) in Safari." }), h("li", { text: "Choose “Add to Home Screen”." }),
          h("li", { text: "Open StepWise from the new home-screen icon and turn reminders on here." })));
    } else if (!pushSupported()) {
      box.append(h("p", { class: "muted", text: "This browser can't show reminders. Try Chrome, Edge or Safari." }));
    } else if (Notification.permission === "denied") {
      box.append(h("p", { class: "muted", text: "Notifications are blocked for StepWise. Allow them in your browser's site settings, then come back here." }));
    } else if (here) {
      box.append(h("p", { text: "On for this device. If you leave a quiz or the tutor is waiting for your reply, StepWise will send you a notification." }),
        h("div", { class: "topic-actions" }, h("button", { class: "btn ghost", text: "Send a test", onclick: () => api("api/push/test", { method: "POST", body: "{}" }).then(() => toast("Sent")).catch((e) => toast(e.message)) }),
          h("button", { class: "btn ghost", text: "Turn off on this device", onclick: pushDisable })));
    } else {
      box.append(h("p", { text: "Get a notification if you leave a quiz, or when the tutor is waiting for your reply." }),
        h("button", { class: "btn accent", disabled: PUSHS.busy, text: PUSHS.busy ? "Turning on…" : "🔔 Turn on reminders", onclick: pushEnable }));
    }
    return box;
  }
  function awayPing(body) {
    if (!S.me || S.me.role !== "child") return;
    const tok = store.get("sw.token"); if (!tok) return;
    try { fetch("api/away", { method: "POST", keepalive: true, headers: { "Content-Type": "application/json", Authorization: `Bearer ${tok}` }, body: JSON.stringify(body) }).catch(() => {}); } catch {}
  }

  let toastTimer = null;
  function toast(msg) {
    const t = $("toast"); t.textContent = msg; t.hidden = false;
    clearTimeout(toastTimer); toastTimer = setTimeout(() => { t.hidden = true; }, 2600);
  }

  // ---------- state ----------
  const S = {
    ready: false, feedback: [], readOnly: false, dbError: "", pinError: "",
    sets: new Map(), students: new Map(), attempts: [],
    view: "practise",           // practise | test | review | progress
    studentId: null,
    progressStudent: null,
    run: null,                  // active test or review
  };

  // ---------- marking ----------
  const SUP = { "⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁻":"-","⁺":"+" };
  function parseNumber(raw) {
    if (raw == null) return NaN;
    let s = String(raw).trim().replace(/^(₹|Rs\.?|INR|US\$|\$)\s*/i, "").replace(/\s+/g, "").replace(/,/g, "").replace(/−/g, "-");
    // superscript powers of ten only (10²³ -> 10^23); a unit like dm³ is left alone
    s = s.replace(/10([⁻⁺]?[⁰¹²³⁴⁵⁶⁷⁸⁹]+)/g, (m, g) => "10^" + [...g].map((c) => SUP[c]).join(""));
    // number, optional "x 10^n" or "e n", optional trailing unit starting with a letter, µ, ° or %
    const m = s.match(/^([-+]?(?:\d+\.?\d*|\.\d+))(?:[x×*X]10\^?([-+]?\d+)|[eE]([-+]?\d+))?(?:[a-zA-Zµ°%].*)?$/);
    if (!m) return NaN;
    const exp = m[2] != null ? m[2] : m[3];
    return parseFloat(m[1]) * (exp != null ? Math.pow(10, parseInt(exp, 10)) : 1);
  }
  // Significant figures in what the student typed (mantissa only; trailing zeros of a whole number don't count).
  function sigFigs(raw) {
    if (raw == null) return 0;
    let s = String(raw).replace(/\s+/g, "").replace(/,/g, "").replace(/−/g, "-");
    const m = s.match(/^[-+]?(\d*\.?\d+|\d+\.)/); if (!m) return 0;
    let t = m[1];
    if (t.includes(".")) { t = t.replace(".", "").replace(/^0+/, ""); return t.length; }
    t = t.replace(/^0+/, "").replace(/0+$/, ""); return t.length;
  }
  // Trailing zeros in a whole number are ambiguous: "20" may be 1 or 2 s.f. Returns every reading.
  function sigFigOptions(raw) {
    const lo = sigFigs(raw);
    const m = String(raw ?? "").replace(/\s+/g, "").replace(/,/g, "").replace(/−/g, "-").match(/^[-+]?(\d+)(?![.\d])/);
    const hi = m ? Math.max(lo, m[1].replace(/^0+/, "").length) : lo;
    const out = []; for (let k = lo; k <= hi; k++) out.push(k); return out;
  }
  function markQuestion(q, resp) {
    const max = Number(q.marks) || 1;
    if (q.type === "mcq") {
      if (resp == null) return { got: 0, max, auto: true, right: false };
      const right = Number(resp) === Number(q.answer);
      return { got: right ? max : 0, max, auto: true, right };
    }
    if (q.type === "multi") {
      const want = new Set((q.answer || []).map(Number));
      const picked = new Set((resp || []).map(Number));
      let hits = 0, wrong = 0;
      picked.forEach((i) => (want.has(i) ? hits++ : wrong++));
      // Cambridge "tick N boxes": more than N ticked scores 0; otherwise marks rise with each correct tick.
      const exact = hits === want.size && wrong === 0;
      const got = picked.size > want.size ? 0 : Math.floor(max * hits / Math.max(1, want.size));
      return { got, max, auto: true, right: exact, over: picked.size > want.size };
    }
    if (q.type === "numeric") {
      if (resp != null) resp = String(resp).replace(/^\s*[x×X]\s*(?=[\d.])/, "");   // magnification written "×1200"
      const v0 = parseNumber(resp);
      // sign_optional: Cambridge accepts PED/PES with or without the minus sign
      const v = q.sign_optional && Number.isFinite(v0) && Number(q.answer) !== 0 && Math.sign(v0) === -Math.sign(Number(q.answer)) ? -v0 : v0;
      const a = Number(q.answer);
      const tol = q.tolerance != null ? Number(q.tolerance) : 0.01;
      const within = Number.isFinite(v) && (a === 0 ? Math.abs(v) < 1e-9 : Math.abs(v - a) <= Math.abs(a) * tol + 1e-12);
      // Also right: the correct answer rounded to the precision the student used (at least 2 s.f.),
      // e.g. 25 for 24.5 N, or 10.0 for 10.048 cm³.
      // A question can insist on the precision it asks for: dp = decimal places, min_sf = significant figures.
      const dps = (() => { const m = String(resp ?? "").replace(/\s+/g, "").replace(/−/g, "-").match(/^[-+]?\d*\.(\d+)/); return m ? m[1].length : 0; })();
      const sfs = sigFigOptions(resp);
      const rounded = Number.isFinite(v) && a !== 0 && sfs.some((k) => k >= 2 && (q.min_sf == null || k >= q.min_sf)
        && Math.abs(Number(a.toPrecision(k)) - v) <= Math.abs(v) * 1e-9);
      let right = q.exact ? Number.isFinite(v) && Math.abs(v - a) < 1e-9 : within || rounded;   // accounts: the exact figure only
      // Exact precision asked ("give your answer to 2 s.f." / "to 1 d.p."): only the correctly rounded
      // value at exactly that precision is right, as in Cambridge marking.
      if (q.sf != null || q.dp != null) {
        const target = q.sf != null ? Number(a.toPrecision(q.sf)) : Number(a.toFixed(q.dp));
        const precOk = q.sf != null ? sfs.includes(q.sf) : dps === q.dp;
        right = Number.isFinite(v) && precOk && Math.abs(v - target) <= Math.abs(target) * 1e-9 + 1e-12;
      }
      return { got: right ? max : 0, max, auto: true, right, parsed: Number.isFinite(v) ? v : null };
    }
    return { got: null, max, auto: false, right: null }; // short: self-marked
  }
  function pct(got, max) { return max > 0 ? Math.round((100 * got) / max) : 0; }
  function band(p) { return p >= 75 ? "good" : p >= 50 ? "warn" : "bad"; }
  function fmtNum(x) {
    if (!Number.isFinite(x)) return String(x);
    const ax = Math.abs(x);
    if (ax !== 0 && (ax >= 1e5 || ax < 1e-3)) {
      const [m, e] = x.toExponential(3).split("e");
      return `${parseFloat(m)} × 10^${parseInt(e, 10)}`;
    }
    return String(Math.round(x * 1e6) / 1e6);
  }
  function fmtDate(iso) {
    try { return new Date(iso).toLocaleString(undefined, { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }); }
    catch { return iso || ""; }
  }

  // ---------- data access ----------
  function setTitle(set) { return `${set.subject || ""} · ${set.chapter || set.id}`; }
  function attemptsFor(studentId, setId) {
    return S.attempts.filter((a) => a.studentId === studentId && (!setId || a.setId === setId))
      .sort((a, b) => String(b.submittedAt).localeCompare(String(a.submittedAt)));
  }
  function latestPerSet(studentId) {
    const m = new Map();
    for (const a of attemptsFor(studentId)) if (!m.has(a.setId)) m.set(a.setId, a);
    return m;
  }

  async function api(path, opts) {
    const tok = store.get("sw.token");
    const res = await fetch(path, { ...(opts || {}), headers: { "Content-Type": "application/json", ...(tok ? { Authorization: `Bearer ${tok}` } : {}), ...((opts && opts.headers) || {}) } });
    let body = null; try { body = await res.json(); } catch {}
    if (res.status === 401 && path !== "api/login" && tok) { signOut("Please log in again."); }
    if (!res.ok) { const err = new Error((body && body.detail) || `Request failed (${res.status})`); err.status = res.status; throw err; }
    return body;
  }
  // ---------- logins ----------
  function signOut(msg) {
    store.del("sw.token"); store.del("sw.student");
    S.me = null; S.studentId = null; S.view = "practise"; S.picking = false; S.chapterId = null; S.subjectCode = null; S.run = null;
    S.students = new Map(); S.attempts = []; S.feedback = []; S.myChats = {}; S.activity = null; A.data = null;
    T.sessionId = null; T.msgs = []; T.mastery = null; document.body.classList.remove("in-chat");
    S.replaceRoute = true; render(); if (msg) toast(msg);
  }
  function renderLogin(main) {
    const user = h("input", { type: "text", id: "login-user", autocomplete: "username", autocapitalize: "none", spellcheck: "false", required: true });
    const pass = h("input", { type: "password", id: "login-pass", autocomplete: "current-password", required: true });
    const err = h("p", { class: "hint", role: "alert" });
    const btn = h("button", { class: "btn accent", type: "submit", text: "Log in" });
    main.append(h("section", { class: "sheet login" },
      h("h2", { text: "Log in to StepWise" }),
      h("p", { class: "muted", text: "Use the username and password you were given. You stay logged in on this device until you log out." }),
      h("form", { class: "login-form", onsubmit: async (e) => {
        e.preventDefault(); btn.disabled = true; err.textContent = "";
        try {
          const r = await api("api/login", { method: "POST", body: JSON.stringify({ username: user.value.trim(), password: pass.value }) });
          store.set("sw.token", r.token); S.me = r.me; S.ready = false; render(); await connect();
        } catch (x) { err.textContent = x.message; btn.disabled = false; pass.value = ""; pass.focus(); }
      } },
        h("label", { for: "login-user", text: "Username" }), user,
        h("label", { for: "login-pass", text: "Password" }), pass, err, btn)));
    requestAnimationFrame(() => user.focus());
  }
  function renderAccount(main) {
    const me = S.me; const forced = me.mustChange;
    const old = h("input", { type: "password", id: "pw-old", autocomplete: "current-password", required: true });
    const nw = h("input", { type: "password", id: "pw-new", autocomplete: "new-password", minlength: "6", required: true });
    const again = h("input", { type: "password", id: "pw-again", autocomplete: "new-password", minlength: "6", required: true });
    const err = h("p", { class: "hint", role: "alert" });
    const roleName = { admin: "Admin", parent: "Parent", child: "Student" }[me.role] || me.role;
    main.append(h("section", { class: `sheet ${forced ? "login" : "account"}` },
      h("h2", { text: forced ? `Welcome, ${me.name}! Choose your own password` : "👤 Your account" }),
      h("p", { class: "muted", text: forced ? "You logged in with a starter password. Pick one only you know (at least 6 characters)."
        : `${me.name} · ${roleName} · username ${me.username}` }),
      h("form", { class: "login-form", onsubmit: async (e) => {
        e.preventDefault(); err.textContent = "";
        if (nw.value !== again.value) { err.textContent = "The two new passwords don't match."; return; }
        try {
          const r = await api("api/me/password", { method: "POST", body: JSON.stringify({ old: old.value, new: nw.value }) });
          store.set("sw.token", r.token); S.me = r.me; S.view = me.role === "child" ? "practise" : "bank"; toast("Password changed");
          if (S.pendingRoute) { const to = S.pendingRoute; S.pendingRoute = null; return applyRoute(to); }
          render();
        } catch (x) { err.textContent = x.message; }
      } },
        h("label", { for: "pw-old", text: forced ? "Starter password" : "Current password" }), old,
        h("label", { for: "pw-new", text: "New password" }), nw,
        h("label", { for: "pw-again", text: "New password again" }), again, err,
        h("button", { class: "btn accent", type: "submit", text: "Save new password" })),
      !forced ? remindersCard(true) : null,
      h("div", { class: "students" },
        !forced ? h("button", { class: "btn ghost", text: "Back", onclick: () => { S.view = me.role === "child" ? "practise" : "bank"; render(); } }) : null,
        h("button", { class: "btn ghost", text: "Log out", onclick: () => signOut("Logged out") }))));
  }
  async function connect() {
    if (!store.get("sw.token")) { S.me = null; S.ready = true; render(); return; }
    try {
      const st = await api("api/state");
      S.me = st.me; S.notes = st.notes || []; S.family = st.family || {}; S.reportsUnread = st.reportsUnread || 0;
      S.sets = new Map(st.sets.map((s) => [s.id, s]));
      S.students = new Map(st.students.map((s) => [s.id, s]));
      S.attempts = st.attempts;
      S.feedback = st.feedback || [];
      S.catalog = st.catalog || { boards: [], subjects: [] };
      if (S.me.role === "child") S.studentId = S.me.studentId;
      else if (!S.studentId || (S.studentId !== "parent" && !S.students.has(S.studentId))) S.studentId = "parent";
      S.dbError = ""; S.pinError = "";
      try { S.tutorOn = (await api("api/tutor/status")).enabled; } catch { S.tutorOn = false; }
      try { S.topics = await api("api/topics"); } catch { S.topics = {}; }
    } catch (e) {
      if (e.status === 401) return;   // signOut has already shown the login
      S.dbError = "unavailable";
    }
    S.ready = true;
    if (S.me && !routeReady) {   // first load: open the screen in the address, if any
      routeReady = true;
      const deep = location.hash && !["#/login", "#/today", "#/account"].includes(location.hash);
      if (deep && S.me.mustChange) S.pendingRoute = location.hash;   // open it once they've chosen a password
      else if (deep) return applyRoute(location.hash);
      S.replaceRoute = true;
    }
    render();
  }
  async function addStudent(name, stay = false) {
    const clean = name.trim().replace(/\s+/g, " ").slice(0, 40);
    if (!clean) return;
    if ([...S.students.values()].some((s) => (s.name || "").toLowerCase() === clean.toLowerCase())) {
      toast(`${clean} is already on the list`); return;
    }
    try {
      const s = await api("api/students", { method: "POST", body: JSON.stringify({ name: clean }) });
      let st = s;
      if (stay) {   // added by the parent: start with no subjects ticked and open the child's panel to choose
        try { st = await api(`api/students/${encodeURIComponent(s.id)}/profile`, { method: "POST", body: JSON.stringify({ subjects: [] }) }); } catch { /* keep the default */ }
        B.open.add(`kid:${s.id}`);
      }
      S.students.set(s.id, st); if (!stay) { S.studentId = s.id; store.set("sw.student", s.id); } toast(stay ? `Added ${clean}: now tick ${clean}'s subjects` : `Added ${clean}`); render();
    } catch (e) { handleWriteError(e); }
  }
  function handleWriteError(e) {
    toast((e && e.message) || "Couldn't save just now. Check your connection and try again.");
  }

  // ---------- test flow ----------
  function startTest(setId) {
    const set = S.sets.get(setId);
    if (!set || !S.studentId) return;
    const key = `sw.draft.${S.studentId}.${setId}`;
    let draft = null; try { draft = JSON.parse(store.get(key) || "null"); } catch {}
    S.chapterId = set.chapterId || set.id;
    S.run = {
      setId, key, phase: "test",
      startedAt: draft && draft.startedAt ? draft.startedAt : new Date().toISOString(),
      responses: draft && draft.responses ? draft.responses : {},
      self: {}, results: null, saved: false, idx: 0, marked: new Set(),
      notLearnt: new Set(draft && draft.notLearnt ? draft.notLearnt : []),
    };
    FT.start("quiz", draft && draft.focus);
    S.run.leaves = (draft && draft.leaves) || 0;
    if (S.studentId !== "parent") api("api/quiz/start", { method: "POST", body: JSON.stringify({ studentId: S.studentId, setId, startedAt: S.run.startedAt }) }).catch(() => {});
    S.view = "test"; render(); window.scrollTo(0, 0); tickTimer();
    S.run.leaveLog = (draft && draft.leaveLog) || [];
    if (draft && draft.leftAt) quizReturned(draft.leftAt, true);   // she closed or reloaded the page mid-quiz
    else checkTimeUp();
  }
  function saveDraft() {
    const r = S.run; if (!r || r.phase !== "test") return;
    store.set(r.key, JSON.stringify({ startedAt: r.startedAt, responses: r.responses, notLearnt: [...r.notLearnt], focus: FT.peek("quiz"),
      leaves: r.leaves || 0, leftAt: r.leftAt || null, leaveLog: r.leaveLog || [] }));
  }
  let timerHandle = null;
  function tickTimer() {
    clearInterval(timerHandle);
    timerHandle = setInterval(() => {
      const el = $("timer"); if (!el || !S.run || S.run.phase !== "test") { clearInterval(timerHandle); return; }
      el.textContent = elapsedLabel();
      const set = S.sets.get(S.run.setId); el.classList.toggle("over", elapsedSec() > (Number(set && set.minutes) || 0) * 60);
      checkTimeUp();
    }, 1000);
  }
  // Open time (only while the quiz screen is open, so "Leave quiz" and carrying on later is fine) past twice the
  // quiz's minutes submits it, with a one-minute warning. Stops a quiz being left open with answers never submitted.
  function hardLimitSec() { const set = S.run && S.sets.get(S.run.setId); const m = Number(set && set.minutes) || 0; return m ? m * 120 : 0; }
  function checkTimeUp() {
    const r = S.run; const lim = hardLimitSec(); if (!r || r.phase !== "test" || !lim || !inQuiz()) return;
    const open = FT.openSec("quiz");
    if (open >= lim) { r.timeUp = true; submitTest(); return; }
    if (open >= lim - 60 && !r.timeWarned) { r.timeWarned = true; ALARM.ring(); render(); }
  }
  function elapsedSec() { return S.run ? Math.max(0, Math.round((Date.now() - Date.parse(S.run.startedAt)) / 1000)) : 0; }
  function elapsedLabel() {
    const s = elapsedSec(); const set = S.sets.get(S.run.setId); const lim = (Number(set && set.minutes) || 0) * 60;
    const mm = String(Math.floor(s / 60)).padStart(2, "0"), ss = String(s % 60).padStart(2, "0");
    return lim ? `${mm}:${ss} / ${String(lim / 60).padStart(2, "0")}:00` : `${mm}:${ss}`;
  }
  // Leaving the quiz screen (another app or tab, screen off, closing the page) submits the quiz.
  // A first, short slip (back within QUIZ_GRACE_MS) only warns; after that, leaving submits.
  const QUIZ_GRACE_MS = 15000;
  const QUIZ_BLIP_MS = 2000;           // hidden for less than this (a screen flicker, a system pop-up): not counted
  const PAGE_LOADED_AT = Date.now();   // after a reload, time away is counted up to here, not to when she reopens the quiz
  const inQuiz = () => S.run && S.run.phase === "test" && S.view === "test";
  let wakeLock = null;
  async function keepAwake(on) {   // stop the phone locking itself mid-quiz (that would count as leaving)
    try {
      if (on && !wakeLock && navigator.wakeLock && !document.hidden) { wakeLock = await navigator.wakeLock.request("screen"); wakeLock.addEventListener("release", () => { wakeLock = null; }); }
      if (!on && wakeLock) { await wakeLock.release(); wakeLock = null; }
    } catch { wakeLock = null; }
  }
  setInterval(() => keepAwake(inQuiz()), 5000);
  function quizLeft() {
    const r = S.run; if (r.leftAt) return;   // already away (e.g. the page then closes): keep the first time
    r.leftAt = Date.now(); r.leaves = (r.leaves || 0) + 1; saveDraft();
    if (r.leaves === 1) awayPing({ kind: "quiz" });
  }
  function quizReturned(leftAt, reloaded) {
    const r = S.run; if (!r || r.phase !== "test") return;
    const away = (reloaded ? Math.min(Date.now(), Math.max(leftAt, PAGE_LOADED_AT)) : Date.now()) - leftAt; r.leftAt = null;
    r.leaveLog = [...(r.leaveLog || []), { at: new Date(leftAt).toISOString(), sec: Math.round(away / 1000), reload: !!reloaded }].slice(-20);
    if (away < QUIZ_BLIP_MS) { r.leaves = Math.max(0, (r.leaves || 1) - 1); saveDraft(); return; }
    if (r.leaves <= 1 && away < QUIZ_GRACE_MS) {
      r.warning = true; saveDraft(); render(); ALARM.ring();
      return;
    }
    r.leftQuiz = true; submitTest();
  }
  document.addEventListener("visibilitychange", () => {
    if (!inQuiz()) return;
    if (document.hidden) quizLeft(); else { keepAwake(true); if (S.run.leftAt) quizReturned(S.run.leftAt); }
  });
  addEventListener("beforeunload", (e) => { if (inQuiz()) { e.preventDefault(); e.returnValue = ""; } });
  function submitTest() {
    const r = S.run; const set = S.sets.get(r.setId);
    r.results = {};
    for (const q of set.questions || []) r.results[q.id] = r.notLearnt.has(q.id)
      ? { got: 0, max: Number(q.marks) || 1, auto: true, right: false, notLearnt: true } : markQuestion(q, r.responses[q.id]);
    r.phase = "review"; r.submittedAt = new Date().toISOString(); r.durationSec = elapsedSec(); r.focus = FT.stop("quiz");
    clearInterval(timerHandle); S.view = "review";
    const firstShort = (set.questions || []).findIndex((q) => !r.results[q.id].auto);
    r.idx = firstShort >= 0 ? firstShort : 0;
    render(); window.scrollTo(0, 0);
    if (reviewTotals().pendingSelf === 0) saveAttempt();
  }
  // ---------- encouragement after a quiz or a learnt part, matched to how it went ----------
  const pick = (arr, seed) => arr[Math.abs([...String(seed)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) | 0, 7)) % arr.length];
  function firstName() { const st = S.students.get(S.studentId); return st ? String(st.name).split(" ")[0] : ""; }
  function quizCheer(r, t) {
    const p = pct(t.got, t.max); const n = firstName(); const seed = r.attemptId || r.submittedAt;
    const earlier = attemptsFor(S.studentId).filter((a) => a.setId === r.setId && a.id !== r.attemptId);
    const prevBest = earlier.length ? Math.max(...earlier.map((a) => pct(a.score, a.max))) : null;
    const nl = r.notLearnt.size; const mins = Math.max(1, Math.round((r.durationSec || 0) / 60));
    let title, lines;
    if (p === 100) {
      title = pick([`Full marks, ${n}!`, "Every single one right!", `Perfect score, ${n}!`], seed);
      lines = prevBest === null
        ? ["First try, and not one slip. That's real understanding, not luck.", "You clearly know this inside out. Time to take on something harder.", "Flawless on your first go. Bank this feeling for exam day."]
        : ["You came back and nailed it. That's exactly how mastery is built.", "From not quite there to perfect. That's what practice does.", "Practice paid off: every answer right this time."];
    } else if (p >= 85) {
      title = pick(["Excellent work!", `Brilliant, ${n}!`, "Really strong result!"], seed);
      lines = ["You're nearly there. Look at the one or two you missed, and you'll own this topic.",
        "This is exam-ready territory. A quick look at your slip-ups will make it rock solid.",
        "Strong work. The small mistakes are the most useful ones to learn from now."];
    } else if (p >= 60) {
      title = pick(["Good progress!", `Nice going, ${n}!`, "Solid effort!"], seed);
      lines = ["You've got the core of it. Fixing your mistakes now is the fastest way to lift this score.",
        "More right than wrong, and every mistake shows you exactly what to practise next.",
        "Good foundation. One more round on the tricky bits and you'll see the difference."];
    } else if (p >= 40) {
      title = pick(["You're on your way", `Keep at it, ${n}`, "Building up"], seed);
      lines = ["Half the battle is done. Go through the ones you missed with the tutor and try again tomorrow.",
        "Every expert started exactly here. Look at what tripped you up, and it'll stick much better next time.",
        "This is where the learning happens. Mistakes you understand are mistakes you won't repeat."];
    } else {
      title = pick(["Every try counts", `Don't give up, ${n}`, "A starting point"], seed);
      lines = ["Tough one! That just means this topic needs a little more time, and that's completely normal.",
        "Struggling with something is how your brain grows. Try learning it with the tutor, then come back to this quiz.",
        "This shows you exactly where to focus. Start with one idea at a time, and it'll come together."];
    }
    let line = pick(lines, seed + "l");
    if (prevBest !== null && p > prevBest && p < 100) line = `Up from ${prevBest}% to ${p}%. ${p - prevBest >= 20 ? "That's a big jump, and you earned it." : "Steady progress is still progress."} ` + line;
    else if (prevBest !== null && p < prevBest) {
      title = pick(["Not your best today", `Shake it off, ${n}`, "Off day? That's okay"], seed);
      line = `Your best here is ${prevBest}%, so you know this. ` + pick(["Slow down, read each question twice, and have another go.",
        "Check the ones you missed. Was it a slip or a gap? Either way, you'll catch it next time.",
        "Everyone has days like this. Take a short break and come back fresh."], seed + "d");
    }
    if (nl) line += ` You also found ${nl} idea${nl > 1 ? "s" : ""} you haven't learnt yet. Knowing that is useful, not a failure.`;
    if (mins >= 15 && p >= 60) line += ` ${mins} minutes of focused work. Well done for sticking with it.`;
    return { title, line, band: band(p) };
  }
  function partCheer(seed, misses) {
    return misses
      ? pick(["You worked through the tricky bits and got there. That's what real learning looks like.",
        "It took a second go on some ideas, and that's exactly how they stick.",
        "You didn't give up when it got hard. Those are the ideas you'll remember best."], seed)
      : pick(["Smooth! You picked up every idea first time.", "Nicely done. One more step towards the big question.",
        "Great focus. Each part you learn makes the next one easier."], seed);
  }
  function reviewTotals() {
    const r = S.run; const set = S.sets.get(r.setId);
    let got = 0, max = 0, pendingSelf = 0;
    for (const q of set.questions || []) {
      const res = r.results[q.id]; max += res.max;
      if (res.auto) got += res.got;
      else if (r.self[q.id] != null) got += r.self[q.id];
      else pendingSelf++;
    }
    return { got, max, pendingSelf };
  }
  async function saveAttempt() {
    const r = S.run; const set = S.sets.get(r.setId); const t = reviewTotals();
    if (t.pendingSelf > 0) { toast(`Mark your ${t.pendingSelf} written answer${t.pendingSelf > 1 ? "s" : ""} first`); return; }
    const answers = {}; const atoms = {};
    for (const q of set.questions || []) {
      const res = r.results[q.id];
      const got = res.auto ? res.got : r.self[q.id];
      const resp = r.responses[q.id];
      answers[q.id] = { response: resp == null || res.notLearnt ? null : resp, got, max: res.max, auto: res.auto, notLearnt: !!res.notLearnt };
      if (res.notLearnt) continue;
      for (const a of q.atom_ids || []) {
        const cur = atoms[a] || [0, 0]; atoms[a] = [cur[0] + got, cur[1] + res.max];
      }
    }
    const doc = {
      studentId: S.studentId, setId: r.setId, subject: set.subject || "", code: set.code || "",
      chapter: set.chapter || "", startedAt: r.startedAt, submittedAt: r.submittedAt,
      durationSec: r.durationSec, score: t.got, max: t.max, answers, atoms,
    };
    if (r.saving || r.saved) return;
    const btn = $("save-btn"); if (btn) btn.disabled = true;
    r.saving = true;
    try {
      const saved = await api("api/attempts", { method: "POST", body: JSON.stringify({
        studentId: doc.studentId, setId: doc.setId, startedAt: doc.startedAt, submittedAt: doc.submittedAt,
        durationSec: doc.durationSec, answers: doc.answers, focus: r.focus || undefined, leftQuiz: !!r.leftQuiz, timeUp: !!r.timeUp, leaveLog: (r.leaveLog || []).length ? r.leaveLog : undefined }) });
      S.attempts.push(saved); r.saved = true; r.attemptId = saved.id; store.del(r.key); toast("Result saved"); T.mastery = null; render();
    } catch (e) { if (btn) btn.disabled = false; handleWriteError(e); } finally { r.saving = false; }
  }

  // ---------- feedback ----------
  const FB_TAGS = ["wrong answer", "unclear", "too hard", "too easy", "typo", "great question", "helpful", "other"];
  const FB_TUTOR_TAGS = ["helpful", "unclear", "wrong answer", "too hard", "too easy", "off topic", "other"];
  const FB_APP_TAGS = ["confusing", "hard to find", "looks wrong", "too slow", "bug", "idea", "love it", "other"];
  const fbOpen = new Set();
  function feedbackFor(t) {
    return S.feedback.filter((f) => f.targetType === t.targetType && f.setId === t.setId
      && (f.questionId || null) === (t.questionId || null) && (f.sessionId || null) === (t.sessionId || null)
      && (t.targetType !== "tutor_message" || f.excerpt === t.excerpt));
  }
  function whoName(by) {
    if (by === "parent") return "Parent";
    if (by === "visitor") return "Visitor";
    const st = S.students.get(by) || {};
    return (st.name || "Someone") + (st.test ? " (test)" : "");
  }
  function screenName() {
    if (S.picking || (!S.studentId && S.view === "practise")) return "Name list";
    if (S.view === "practise" && !S.chapterId) return S.subjectCode ? `Subject ${S.subjectCode}` : "Home";
    return { practise: "Chapter page", test: "Taking a self-check", review: "Marked self-check", tutor: T.sessionId ? "Tutor chat" : "Tutor chapter list",
             progress: "Progress", bank: B.setId ? "Parent question review" : "Parent feedback inbox" }[S.view] || S.view;
  }
  function feedbackWidget(t, label) {
    const key = JSON.stringify(t);
    const existing = feedbackFor(t);
    const box = h("div", { class: "fb" });
    const mine = existing.filter((f) => f.by === S.studentId);
    const head = h("div", { class: "fb-head" },
      h("button", { type: "button", class: "fb-toggle", "aria-expanded": String(fbOpen.has(key)), text: fbOpen.has(key) ? "Close feedback" : (label || "Give feedback"),
        onclick: () => { fbOpen.has(key) ? fbOpen.delete(key) : fbOpen.add(key); render(); } }),
      mine.length ? h("span", { class: "pill good", text: `You sent ${mine.length}` }) : null,
      S.studentId === "parent" && existing.length ? h("span", { class: "pill warn", text: `${existing.filter((f) => f.status === "open").length} open of ${existing.length}` }) : null);
    box.append(head);
    if (!fbOpen.has(key)) return box;
    const picked = new Set();
    const tags = h("div", { class: "selfmark", role: "group", "aria-label": "What's the feedback about?" });
    for (const tag of (t.targetType === "app" ? FB_APP_TAGS : t.targetType.startsWith("tutor") ? FB_TUTOR_TAGS : FB_TAGS)) {
      const b = h("button", { type: "button", "aria-pressed": "false", text: tag });
      b.addEventListener("click", () => { picked.has(tag) ? picked.delete(tag) : picked.add(tag); b.setAttribute("aria-pressed", String(picked.has(tag))); });
      tags.append(b);
    }
    const ta = h("textarea", { rows: "2", placeholder: "What should change? (optional)", "aria-label": "Feedback comment" });
    const send = h("button", { type: "button", class: "btn ghost", text: "Send feedback" });
    send.addEventListener("click", async () => {
      if (!S.studentId && t.targetType !== "app") return toast("Pick your name first");
      if (!picked.size && !ta.value.trim()) return toast("Pick a reason or write a comment");
      send.disabled = true;
      try {
        const f = await api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId || "visitor", ...t, tags: [...picked], text: ta.value }) });
        S.feedback.push(f); fbOpen.delete(key); if (t.targetType === "app") S.appFb = false; toast("Thanks, feedback sent"); render();
      } catch (e) { send.disabled = false; toast(e.message); }
    });
    box.append(tags, ta, h("div", { class: "fb-actions" }, send));
    if (existing.length) box.append(feedbackList(existing, false));
    return box;
  }
  function feedbackList(items, withTarget) {
    const ul = h("div", { class: "fb-list" });
    for (const f of items.slice().sort((a, b) => String(b.created).localeCompare(String(a.created)))) {
      const set = S.sets.get(f.setId) || {};
      const row = h("div", { class: `fb-item ${f.status}` },
        h("div", { class: "meta" }, h("strong", { text: whoName(f.by) }), h("span", { class: "mono", text: fmtDate(f.created) }),
          ...f.tags.map((tg) => h("span", { class: `pill ${["wrong answer", "typo", "unclear"].includes(tg) ? "bad" : ["helpful", "great question", "got insight", "gaining confidence"].includes(tg) ? "good" : "warn"}`, text: tg })),
          h("span", { class: `pill ${f.status === "resolved" ? "good" : ""}`, text: f.status })),
        withTarget ? h("p", { class: "hint", text: f.targetType === "app" ? "The app itself" : `${set.subject || ""} · ${set.chapter || f.setId} · ${f.targetType.replace("_", " ")}${f.questionId ? " " + f.questionId : ""}` }) : null,
        f.excerpt ? h("p", { class: "fb-excerpt", text: f.excerpt }) : null,
        f.text ? h("p", { text: f.text }) : null,
        f.note ? h("p", { class: "hint", text: `Parent note: ${f.note}` }) : null);
      if (S.studentId === "parent") {
        row.append(h("div", { class: "fb-actions" }, h("button", { type: "button", class: "btn ghost", text: f.status === "open" ? "Mark resolved" : "Reopen",
          onclick: async () => {
            try { const u = await api(`api/feedback/${encodeURIComponent(f.id)}/status`, { method: "POST", body: JSON.stringify({ status: f.status === "open" ? "resolved" : "open" }) });
              Object.assign(f, u); render(); } catch (e) { toast(e.message); }
          } })));
      }
      ul.append(row);
    }
    return ul;
  }

  // ---------- parent page: Children · Questions · Feedback ----------
  const B = { setId: null, filter: "open", tab: "reports", open: new Set(), kid: null };
  function fold(key, summary, body, startOpen = false) {   // a collapsible block that remembers being opened
    const d = h("details", { class: "fold" }, h("summary", null, summary), body);
    d.open = B.open.has(key) || startOpen;
    d.addEventListener("toggle", () => { if (d.open) B.open.add(key); else B.open.delete(key); });
    return d;
  }
  // Parent: add children and choose which subjects each one sees.
  function childrenSettings() {
    const kids = [...S.students.values()].sort((a, b) => (a.name || "").localeCompare(b.name || ""));
    const sec = h("section", { class: "sheet" }, h("h2", { text: "Children" }),
      h("p", { class: "muted", text: "Each child sees the courses of their class (ticked and locked below). Tick any extra subjects they study; changes save straight away." }));
    if (!kids.length) sec.append(h("p", { class: "muted", text: "No children linked to your account yet. Ask the admin to link them." }));
    for (const k of kids) {
      const cur = new Set(k.ownSubjects || []); const fromClass = new Set(k.classCourses || []);
      const summaryText = () => [...new Set([...fromClass, ...cur])].map((c) => (catSubjects().find((x) => x.code === c) || {}).name).filter(Boolean).join(", ") || "no subjects ticked";
      const sumHint = h("span", { class: "hint", text: summaryText() });
      const box = h("div", { class: "kid-subjects" });
      for (const b of S.catalog.boards || []) {
        const subs = catSubjects().filter((s) => s.board === b.id); if (!subs.length) continue;
        box.append(h("div", { class: "board-row" }, h("span", { class: "label", text: b.name }),
          h("div", { class: "subj-checks" }, ...subs.map((s) => {
            const id = `subj-${k.id}-${s.code}`;
            const cb = h("input", { type: "checkbox", id }); cb.checked = cur.has(s.code) || fromClass.has(s.code); cb.disabled = fromClass.has(s.code);
            cb.addEventListener("change", async () => {
              if (cb.checked) cur.add(s.code); else cur.delete(s.code);
              try {
                const r = await api(`api/students/${encodeURIComponent(k.id)}/profile`, { method: "POST",
                  body: JSON.stringify({ subjects: catSubjects().map((x) => x.code).filter((c) => cur.has(c)) }) });
                S.students.set(k.id, r); sumHint.textContent = summaryText(); toast(`Saved ${k.name}'s subjects`);
              } catch (e) { cb.checked = !cb.checked; if (cb.checked) cur.add(s.code); else cur.delete(s.code); handleWriteError(e); }
            });
            return h("label", { class: "subj-check", for: id }, cb, h("span", { text: s.name + (fromClass.has(s.code) ? " (class)" : "") + (unitsOf(s).length ? "" : " (coming soon)") }));
          }))));
      }
      sec.append(fold(`kid:${k.id}`, [h("strong", { text: k.name + (k.test ? " (test)" : "") }), " ", sumHint], box));
    }
    return sec;
  }
  // ---------- admin: logins, families and classes ----------
  const A = { data: null, loading: false };
  function loadAdmin() {
    if (A.loading) return; A.loading = true;
    api("api/admin").then((d) => { A.data = d; }).catch((e) => toast(e.message)).finally(() => { A.loading = false; render(); });
  }
  function starterPassword() {
    const abc = "abcdefghjkmnpqrstuvwxyz23456789"; const r = new Uint32Array(8); crypto.getRandomValues(r);
    return [...r].map((x) => abc[x % abc.length]).join("");
  }
  function checkList(items, chosen, idp) {   // a row of checkboxes; returns [element, () => chosen ids]
    const set = new Set(chosen);
    const el = h("div", { class: "subj-checks" }, ...items.map((it) => {
      const id = `${idp}-${it.id}`; const cb = h("input", { type: "checkbox", id }); cb.checked = set.has(it.id);
      cb.addEventListener("change", () => { if (cb.checked) set.add(it.id); else set.delete(it.id); });
      return h("label", { class: "subj-check", for: id }, cb, h("span", { text: it.label }));
    }));
    return [el, () => items.map((x) => x.id).filter((x) => set.has(x))];
  }
  function adminPage() {
    const sec = h("section", { class: "sheet" }, h("h2", { text: "Admin" }));
    if (!A.data) { sec.append(h("p", { class: "muted", text: "Loading accounts…" })); loadAdmin(); return sec; }
    const d = A.data;
    const stName = new Map(d.students.map((x) => [x.id, x.name + (x.test ? " (test)" : "")]));
    const kidItems = d.students.map((x) => ({ id: x.id, label: stName.get(x.id) }));
    const post = async (path, body, ok) => {
      try { await api(path, { method: "POST", body: JSON.stringify(body) }); toast(ok); A.data = null; await connect(); }
      catch (e) { toast(e.message); }
    };
    const roleName = { admin: "Admin", parent: "Parent", child: "Student" };
    A.tab = A.tab || "people";
    sec.append(h("div", { class: "selfmark", role: "tablist" }, ...[["people", "👤 People"], ["classes", "🏫 Classes"], ["family", "👪 Family"]].map(([k, l]) =>
      h("button", { type: "button", role: "tab", "aria-selected": String(A.tab === k), "aria-pressed": String(A.tab === k), text: l, onclick: () => { A.tab = k; render(); } }))));
    if (A.tab === "family") {
      sec.append(h("h3", { text: "Who is Mom, Dad…" }), h("p", { class: "hint", text: "Children share reports with these people, and see their encouragement as \"From Mom\", \"From Dad\" and so on. Linking someone here also lets them see that child." }));
      const grown = d.users.filter((u) => u.role !== "child" && !u.disabled);
      for (const st of d.students.filter((x) => !x.test)) {
        const fam = (d.family && d.family[st.id]) || [];
        const who = h("select", { "aria-label": `Add someone for ${st.name}` }, ...grown.map((u) => h("option", { value: u.id, text: u.name })));
        const rel = h("input", { type: "text", value: "Mom", maxlength: "20", "aria-label": "Shown to the child as", list: "rel-list" });
        sec.append(h("div", { class: "admin-user" }, h("strong", { text: st.name }),
          fam.length ? h("ul", { class: "chat-list" }, ...fam.map((x) => h("li", null, h("span", { text: `${x.relation}: ${x.name}` }),
            h("button", { class: "react", text: "Remove", onclick: () => post("api/admin/family", { studentId: st.id, userId: x.id, relation: null }, `Removed ${x.name} for ${st.name}`) })))) : h("p", { class: "hint", text: "No one linked yet." }),
          h("div", { class: "add-student" }, who, h("span", { text: "as" }), rel,
            h("button", { class: "btn ghost", text: "Link", onclick: () => post("api/admin/family", { studentId: st.id, userId: who.value, relation: rel.value || "Parent" }, `Linked for ${st.name}`) }))));
      }
      sec.append(h("datalist", { id: "rel-list" }, ...["Mom", "Dad", "Grandma", "Grandpa", "Guardian", "Tutor"].map((x) => h("option", { value: x }))));
      return sec;
    }
    if (A.tab === "people") {
    sec.append(h("h3", { text: "Logins" }));
    for (const u of d.users) {
      const pw = h("input", { type: "text", value: starterPassword(), "aria-label": `New starter password for ${u.name}`, minlength: "6" });
      const body = h("div", { class: "admin-user" },
        h("p", { class: "hint", text: `Username ${u.username}${u.role === "child" && u.studentId ? ` · results of ${stName.get(u.studentId) || u.studentId}` : ""}${u.mustChange ? " · has not chosen a password yet" : ""}` }));
      if (u.role === "parent") {
        const [el, get] = checkList(kidItems, u.children, `kids-${u.id}`);
        body.append(h("p", { class: "label", text: "Children" }), el,
          h("button", { class: "btn ghost", text: "Save children", onclick: () => post(`api/admin/users/${u.id}`, { children: get() }, `Saved ${u.name}'s children`) }));
      }
      body.append(h("p", { class: "label", text: "Reset password" }),
        h("div", { class: "add-student" }, pw, h("button", { class: "btn ghost", text: "Reset", onclick: () => post(`api/admin/users/${u.id}`, { password: pw.value }, `New starter password for ${u.name}: ${pw.value}`) })),
        u.id !== S.me.id ? h("button", { class: "btn ghost", text: u.disabled ? "Switch login back on" : "Switch login off",
          onclick: () => post(`api/admin/users/${u.id}`, { disabled: !u.disabled }, u.disabled ? `${u.name} can log in again` : `${u.name} can no longer log in`) }) : null);
      const kids = u.role === "parent" ? (u.children || []).map((c) => stName.get(c) || c).join(", ") : "";
      sec.append(fold(`user:${u.id}`, [h("strong", { text: u.name }), " ", h("span", { class: `pill ${u.disabled ? "bad" : ""}`, text: u.disabled ? "off" : roleName[u.role] }),
        kids ? h("span", { class: "hint", text: ` · ${kids}` }) : null], body));
    }
    // add a login
    {
      const name = h("input", { type: "text", id: "nu-name", maxlength: "40", required: true });
      const uname = h("input", { type: "text", id: "nu-user", maxlength: "30", autocapitalize: "none", spellcheck: "false", required: true, pattern: "[a-z0-9][a-z0-9._\\-]{1,29}" });
      const pw = h("input", { type: "text", id: "nu-pw", minlength: "6", required: true, value: starterPassword() });
      const role = h("select", { id: "nu-role" }, ...["child", "parent", "admin"].map((r) => h("option", { value: r, text: roleName[r] })));
      const linked = new Set(d.users.filter((u) => u.studentId).map((u) => u.studentId));
      const link = h("select", { id: "nu-link" }, h("option", { value: "", text: "New student record" }),
        ...d.students.filter((x) => !linked.has(x.id)).map((x) => h("option", { value: x.id, text: `Existing: ${stName.get(x.id)}` })));
      const [kidsEl, getKids] = checkList(kidItems, [], "nu-kids");
      const childRow = h("div", null, h("label", { for: "nu-link", text: "Results" }), link);
      const parentRow = h("div", { hidden: true }, h("p", { class: "label", text: "Children" }), kidsEl);
      role.addEventListener("change", () => { childRow.hidden = role.value !== "child"; parentRow.hidden = role.value !== "parent"; });
      name.addEventListener("input", () => { if (!uname.dataset.touched) uname.value = name.value.toLowerCase().replace(/[^a-z0-9]+/g, ""); });
      uname.addEventListener("input", () => { uname.dataset.touched = "1"; });
      sec.append(h("h3", { text: "Add a login" }), h("form", { class: "login-form", onsubmit: (e) => {
        e.preventDefault();
        const body = { name: name.value.trim(), username: uname.value.trim().toLowerCase(), role: role.value, password: pw.value };
        if (role.value === "child" && link.value) body.studentId = link.value;
        if (role.value === "parent") body.children = getKids();
        post("api/admin/users", body, `Added ${body.name}: username ${body.username}, starter password ${body.password}`);
      } },
        h("label", { for: "nu-name", text: "Name" }), name, h("label", { for: "nu-user", text: "Username (lowercase letters and numbers)" }), uname,
        h("label", { for: "nu-role", text: "Role" }), role, childRow, parentRow,
        h("label", { for: "nu-pw", text: "Starter password (they choose their own when they first log in)" }), pw,
        h("button", { class: "btn accent", type: "submit", text: "Add login" })));
    }
    return sec;
    }
    // classes
    sec.append(h("h3", { text: "Classes" }), h("p", { class: "hint", text: "A class has courses and students. Each student sees the courses of all their classes." }));
    const courseItems = d.subjects.map((x) => ({ id: x.code, label: `${x.name} (${x.board.toUpperCase()} ${x.code})` }));
    for (const c of d.classes) {
      const nm = h("input", { type: "text", value: c.name, maxlength: "60", "aria-label": "Class name" });
      const [cEl, getC] = checkList(courseItems, c.courses, `cc-${c.id}`);
      const [sEl, getS] = checkList(kidItems, c.students, `cs-${c.id}`);
      sec.append(fold(`class:${c.id}`, [h("strong", { text: c.name }), h("span", { class: "hint", text: ` · ${c.courses.length} courses · ${c.students.map((x) => stName.get(x) || x).join(", ") || "no students"}` })],
        h("div", { class: "admin-user" }, h("p", { class: "label", text: "Name" }), nm, h("p", { class: "label", text: "Courses" }), cEl,
          h("p", { class: "label", text: "Students" }), sEl,
          h("div", { class: "students" },
            h("button", { class: "btn accent", text: "Save class", onclick: () => post(`api/admin/classes/${c.id}`, { name: nm.value, courses: getC(), students: getS() }, `Saved ${nm.value}`) }),
            h("button", { class: "btn ghost", text: "Delete class", onclick: async () => {
              try { await api(`api/admin/classes/${c.id}`, { method: "DELETE" }); toast(`Deleted ${c.name}`); A.data = null; await connect(); } catch (e) { toast(e.message); } } })))));
    }
    const cn = h("input", { type: "text", placeholder: "New class name, e.g. IGCSE Year 10", maxlength: "60", "aria-label": "New class name" });
    sec.append(h("form", { class: "add-student", onsubmit: (e) => { e.preventDefault(); if (cn.value.trim()) post("api/admin/classes", { name: cn.value.trim(), courses: [], students: [] }, "Class added: open it to add courses and students"); } },
      cn, h("button", { class: "btn ghost", type: "submit", text: "Add class" })));
    return sec;
  }
  // Parent: every quiz, organised board > subject > unit > chapter > quizzes (part quizzes folded away).
  function questionTree() {
    const open = S.feedback.filter((f) => f.status === "open");
    const nOpen = (ids) => open.filter((f) => ids.includes(f.setId)).length;
    const setsOf = (cid) => [...S.sets.values()].filter((x) => (x.chapterId || x.id) === cid).sort((a, b) => (a.order || 0) - (b.order || 0));
    const quizBtn = (z) => { const n = nOpen([z.id]);
      return h("button", { class: "quiz-row", type: "button", onclick: () => { B.setId = z.id; render(); window.scrollTo(0, 0); } },
        h("span", { text: z.title || z.chapter }), h("span", { class: "hint", text: `${(z.questions || []).length} Qs${n ? ` · ${n} open feedback` : ""}` })); };
    const sec = h("section", { class: "sheet" }, h("h2", { text: "Questions" }),
      h("p", { class: "muted", text: "Open a subject, then a chapter, then a quiz to see every question with its answer, mark scheme and explanation. Leave feedback on anything that needs fixing." }));
    const placed = new Set();
    for (const b of S.catalog.boards || []) {
      const subs = catSubjects().filter((s) => s.board === b.id && unitsOf(s).length); if (!subs.length) continue;
      sec.append(h("h3", { class: "board-head", text: b.name }));
      for (const subj of subs) {
        const chapters = unitsOf(subj).flatMap((u) => u.chapters.map((c) => ({ u, c })));
        const subjSets = chapters.flatMap(({ c }) => setsOf(c.id).map((z) => z.id));
        const body = h("div", { class: "fold-body" });
        for (const { u, c } of chapters) {
          placed.add(c.id);
          const all = setsOf(c.id); const main = all.filter((z) => z.kind !== "chunk"); const parts = all.filter((z) => z.kind === "chunk");
          const cBody = h("div", { class: "fold-body" }, ...main.map(quizBtn));
          if (parts.length) cBody.append(fold(`parts:${c.id}`, [h("span", { text: "Part quizzes" }), " ", h("span", { class: "hint", text: `${parts.length} short quizzes` })], h("div", { class: "fold-body" }, ...parts.map(quizBtn))));
          const n = nOpen(all.map((z) => z.id));
          body.append(fold(`ch:${c.id}`, [h("span", { text: `${u.num ? `Unit ${u.num} · ` : ""}${chapterTitle(c.id)}` }), " ",
            h("span", { class: "hint", text: `${main.length} quizzes${parts.length ? ` + ${parts.length} parts` : ""}${n ? ` · ${n} open feedback` : ""}` })], cBody));
        }
        const n = nOpen(subjSets);
        sec.append(fold(`subj:${subj.code}`, [h("strong", { text: subj.name }), " ", h("span", { class: "hint", text: `${chapters.length} chapter${chapters.length === 1 ? "" : "s"}${n ? ` · ${n} open feedback` : ""}` })], body));
      }
    }
    const rest = [...new Set([...S.sets.values()].map((z) => z.chapterId || z.id))].filter((cid) => !placed.has(cid));
    if (rest.length) sec.append(fold("subj:other", [h("strong", { text: "Other" }), " ", h("span", { class: "hint", text: `${rest.length} chapters not in the catalogue` })],
      h("div", { class: "fold-body" }, ...rest.map((cid) => fold(`ch:${cid}`, h("span", { text: chapterTitle(cid) }), h("div", { class: "fold-body" }, ...setsOf(cid).map(quizBtn)))))));
    return sec;
  }
  function renderBank(main) {
    const open = S.feedback.filter((f) => f.status === "open");
    if (!B.setId) {
      const isAdmin = S.me && S.me.role === "admin";
      const tabs = [["reports", `📈 Reports${S.reportsUnread ? ` (${S.reportsUnread} new)` : ""}`], ["children", "Children"],
        ...(isAdmin ? [["questions", "Questions"], ["feedback", `Feedback${open.length ? ` (${open.length})` : ""}`], ["admin", "Admin"]] : [])];
      if (!tabs.some(([k]) => k === B.tab)) B.tab = "reports";
      main.append(h("section", { class: "sheet parent-head" }, h("h2", { text: "Parent" }),
        h("div", { class: "selfmark", role: "tablist" }, ...tabs.map(([k, label]) => h("button", { type: "button", role: "tab", "aria-selected": String(B.tab === k), "aria-pressed": String(B.tab === k), text: label, onclick: () => { B.tab = k; render(); } })))));
      if (B.tab === "reports") { parentReports(main); return; }
      if (B.tab === "children") { if (S.catalog) main.append(childrenSettings()); return; }
      if (B.tab === "admin" && S.me.role === "admin") { main.append(adminPage()); return; }
      if (B.tab === "questions") { if (S.catalog) main.append(questionTree()); return; }
      const inbox = h("section", { class: "sheet" }, h("h2", { text: "Feedback inbox" }),
        h("div", { class: "selfmark" }, ...["open", "all"].map((k) => h("button", { type: "button", "aria-pressed": String(B.filter === k), text: k === "open" ? `Open (${open.length})` : `All (${S.feedback.length})`, onclick: () => { B.filter = k; render(); } }))));
      const items = B.filter === "open" ? open : S.feedback;
      inbox.append(items.length ? feedbackList(items, true) : h("p", { class: "muted", text: "No feedback yet. It appears here as soon as anyone sends some." }));
      main.append(inbox);
      return;
    }
    const set = S.sets.get(B.setId); const atoms = set.atoms || {};
    const sheet = h("section", { class: "sheet" },
      h("div", { class: "test-bar" }, h("div", null, h("span", { class: "label", text: `${set.subject} · ${set.code}` }), h("h2", { text: set.chapter })),
        h("button", { class: "btn ghost", text: "← Back to questions", onclick: () => { B.setId = null; B.tab = "questions"; render(); } })),
      feedbackWidget({ targetType: "set", setId: set.id }, "Feedback on this whole self-check"));
    (set.questions || []).forEach((q, i) => {
      const body = h("div", { class: "body" }, h("p", { class: "prompt", text: q.prompt }), q.figure ? figureEl(q.figure, true) : null);
      if (q.options) body.append(h("ol", { class: "opts-list", type: "A" }, ...q.options.map((o, k) => {
        const right = q.type === "mcq" ? Number(q.answer) === k : (q.answer || []).map(Number).includes(k);
        return h("li", { class: right ? "right" : "", text: o + (right ? "  ✓" : "") });
      })));
      if (q.type === "numeric") body.append(h("p", null, h("span", { class: "label", text: "Answer  " }), h("span", { class: "mono", text: (() => { const shown = q.sf != null ? (() => { const t = Number(q.answer).toPrecision(q.sf); return t.includes("e") ? String(Number(t)) : t; })() : q.dp != null ? Number(q.answer).toFixed(q.dp) : fmtNum(Number(q.answer));
        const tol = q.exact || q.sf != null || q.dp != null ? (q.exact ? " (exact)" : q.sf != null ? ` (${q.sf} s.f.)` : ` (${q.dp} d.p.)`) : ` (±${+((q.tolerance ?? 0.01) * 100).toFixed(1)}%)`;
        return `${shown}${q.unit ? " " + q.unit : ""}${tol}${q.sign_optional ? "; sign optional" : ""}`; })() })));
      const scheme = h("div", { class: "scheme" });
      if (q.mark_scheme) scheme.append(h("p", null, h("span", { class: "label", text: "Mark scheme  " }), q.mark_scheme));
      if (q.explanation) scheme.append(h("p", null, h("span", { class: "label", text: "Why  " }), q.explanation));
      scheme.append(h("p", { class: "hint", text: `${q.type} · difficulty ${q.difficulty || "?"} · template ${q.template_id || "none"}${q.misconception_id ? " · probes " + q.misconception_id : ""}` }));
      for (const a of q.atom_ids || []) scheme.append(h("p", { class: "hint", text: `${a}: ${atoms[a] || ""}` }));
      body.append(scheme, feedbackWidget({ targetType: "question", setId: set.id, questionId: q.id }));
      sheet.append(h("div", { class: "q" }, h("div", null, h("div", { class: "num", text: `Q${i + 1}` }), h("div", { class: "marks", text: `[${q.marks || 1}]` })), body));
    });
    main.append(sheet);
  }

  // ---------- rendering ----------
  // ---------- addresses: every screen has one, so Back and refresh work ----------
  let routeReady = false;
  function routeOf() {
    if (!S.me) return "#/login";
    if (S.view === "account" || S.me.mustChange) return "#/account";
    if (S.view === "tutor") return T.sessionId ? `#/chat/${T.sessionId}` : location.hash;   // opening: keep the address
    if ((S.view === "test" || S.view === "review") && S.run) return `#/quiz/${S.run.setId}`;
    if (S.view === "chats") return "#/chats";
    if (S.view === "progress") return "#/progress";
    if (S.view === "shared" && S.sharedId) return `#/report/${S.sharedId}`;
    if (S.picking) return "#/switch";
    if (S.studentId === "parent") return `#/parent/${B.tab}`;
    if (S.chapterId) return `#/chapter/${S.chapterId}`;
    if (S.subjectCode) return `#/subjects/${S.subjectCode}`;
    if (S.place === "subjects") return "#/subjects";
    return "#/today";
  }
  function syncUrl() {
    if (!S.ready || !routeReady) return;
    const r = routeOf(); if (r === location.hash) { S.replaceRoute = false; return; }
    try { if (S.replaceRoute) history.replaceState(null, "", r); else history.pushState(null, "", r); } catch {}
    S.replaceRoute = false;
  }
  function applyRoute(hash) {
    const [a, b] = String(hash || "").replace(/^#\/?/, "").split("/").map((x) => decodeURIComponent(x || ""));
    if (S.view === "test" && S.run && !(a === "quiz" && b === S.run.setId)) confirmLeave();
    if (a !== "quiz") S.run = null;
    if (T.sessionId && !(a === "chat" && b === T.sessionId)) endSession();
    S.picking = false; S.replaceRoute = true;
    const parentish = S.studentId === "parent";
    if (a === "account") S.view = "account";
    else if (a === "chats" && !parentish) S.view = "chats";
    else if (a === "progress") S.view = "progress";
    else if (a === "report" && b) { S.view = "shared"; S.sharedId = b; }
    else if (a === "parent" && parentish) { S.view = "bank"; B.setId = null; if (b) B.tab = b; }
    else if (a === "switch" && S.me && S.me.role !== "child") { S.view = "practise"; S.picking = true; }
    else if (a === "chapter" && b && !parentish) { const e = chapterEntry(b); S.view = "practise"; S.place = "subjects"; S.chapterId = b; S.subjectCode = e ? e.subject.code : null; }
    else if (a === "subjects" && !parentish) { S.view = "practise"; S.place = "subjects"; S.chapterId = null; S.subjectCode = b || null; }
    else if (a === "chat" && b && !parentish) { if (b !== T.sessionId) { reopenChat(b); return; } }
    else if (a === "quiz" && S.run && S.run.setId === b) { /* still in that quiz */ }
    else if (a === "quiz" && b && S.studentId && S.studentId !== "parent" && store.get(`sw.draft.${S.studentId}.${b}`) && S.sets.has(b)) { startTest(b); return; }   // reloaded mid-quiz: carry on
    else if (a === "quiz" && b) { const set = S.sets.get(b); S.view = "practise"; S.place = "subjects"; S.chapterId = set ? (set.chapterId || set.id) : null; }
    else { S.view = parentish ? "bank" : "practise"; S.place = "today"; S.chapterId = null; S.subjectCode = null; }
    render(); window.scrollTo(0, 0);
  }
  window.addEventListener("popstate", () => { if (S.me && routeReady) applyRoute(location.hash); });
  function goPlace(place) {
    if (place !== "chats") S.chatFilter = null;
    if (S.view === "test" && S.run) confirmLeave();
    if (T.sessionId) endSession();
    S.run = null; S.picking = false; S.chapterId = null; S.subjectCode = null;
    if (place === "today" || place === "subjects") { S.view = "practise"; S.place = place; } else S.view = place;
    render(); window.scrollTo(0, 0);
  }
  function render() { renderInner(); syncUrl(); }
  function renderInner() {
    const isParent = S.studentId === "parent";
    if (isParent && S.view === "practise" && !S.picking) S.view = "bank";   // the parent's home is Review
    $("tab-practise").hidden = isParent;                                    // parents don't take self-checks
    $("tab-subjects").hidden = isParent; $("tab-chats").hidden = isParent;
    const inSubjects = S.view === "practise" && !S.picking && (S.place === "subjects" || S.subjectCode || S.chapterId);
    $("tab-practise").setAttribute("aria-pressed", String(S.view === "practise" && !inSubjects));
    $("tab-subjects").setAttribute("aria-pressed", String(!!inSubjects || ["test", "review"].includes(S.view)));
    $("tab-chats").setAttribute("aria-pressed", String(S.view === "chats" || S.view === "tutor"));
    document.body.classList.toggle("in-quiz", ["test", "review"].includes(S.view));
    $("tab-tutor").setAttribute("aria-pressed", String(S.view === "tutor"));
    $("tab-progress").setAttribute("aria-pressed", String(S.view === "progress"));
    const who = $("who"); const st = S.studentId && S.students.get(S.studentId);
    who.textContent = isParent ? "Parent" : st ? `👤 ${st.name}` : "Choose your name"; who.classList.toggle("set", !!st || isParent);
    who.title = S.me && S.me.role === "child" ? "Your account: password and log out" : "Switch view, your account, log out";
    $("brand-tag").textContent = isParent ? "Parent" : st && S.catalog ? boardLine(subjectsFor(st)) : "";
    $("tab-bank").hidden = !isParent;
    $("tab-bank").setAttribute("aria-pressed", String(S.view === "bank"));
    $("tab-progress").replaceChildren(h("span", { class: "ic", "aria-hidden": "true", text: isParent ? "📊" : "📈" }), h("span", { text: isParent ? "Overview" : "Report" }));
    for (const id of ["tab-practise", "tab-subjects", "tab-chats", "tab-progress", "who", "app-fb"]) if (!S.me) $(id).hidden = true;
    if (S.me) { $("tab-progress").hidden = isParent && S.me.role !== "admin"; $("who").hidden = false; $("app-fb").hidden = false; }
    if (S.me && isParent) who.textContent = S.me.role === "admin" ? `👤 ${S.me.name} (admin)` : `👤 ${S.me.name} (parent)`;
    const main = $("main"); main.replaceChildren();
    if (!(S.view === "tutor" && (T.sessionId || T.busy))) document.body.classList.remove("in-chat");
    const dock = $("dock"); const dockRow = $("dock-row"); dock.hidden = true; dockRow.replaceChildren();
    CALC.show(!!S.calcOpen && inQuiz());

    if (!S.ready) { main.append(h("section", { class: "sheet" }, h("h2", { text: "Loading your self-checks" }), h("p", { class: "muted", text: "Loading your self-checks and results." }))); return; }
    if (!S.me) return renderLogin(main);
    if (S.me.mustChange || S.view === "account") return renderAccount(main);
    if (S.dbError) { main.append(connectionNotice()); }
    if (S.appFb) {
      const where = screenName(); const t = { targetType: "app", setId: "app", excerpt: `Screen: ${where}` };
      const k = JSON.stringify(t);
      if (S.appFbOpening) { fbOpen.add(k); S.appFbOpening = false; }
      if (!fbOpen.has(k)) S.appFb = false;
    }
    if (S.appFb) {
      const where = screenName(); const t = { targetType: "app", setId: "app", excerpt: `Screen: ${where}` };
      main.append(h("section", { class: "sheet app-fb" },
        h("div", { class: "test-bar" }, h("h2", { text: "Feedback on the app" }), h("button", { class: "btn ghost", text: "Close", onclick: () => { S.appFb = false; fbOpen.clear(); render(); } })),
        h("p", { class: "muted", text: `What's working, what's confusing, what you'd change. We'll note that you were on: ${where}.` }),
        feedbackWidget(t, "Feedback")));
    }

    if (S.view === "test" && S.run) return renderTest(main, dock, dockRow);
    if (S.view === "review" && S.run) return renderReview(main, dock, dockRow);
    if (S.view === "progress") return S.studentId && S.studentId !== "parent" ? renderMyProgress(main) : renderProgress(main);
    if (S.view === "chats") return renderChats(main);
    if (S.view === "shared" && S.sharedId) return renderSharedReport(main, S.sharedId);
    if (S.view === "tutor") return renderTutor(main, dock, dockRow);
    if (S.view === "bank" && isParent) return renderBank(main);
    if (isParent && !S.picking) return renderBank(main);
    renderPractise(main);
  }

  // ---------- light formatting for tutor replies ----------
  function inline(text) {
    const frag = document.createDocumentFragment();
    const re = /(\*\*[^*\n]+\*\*|__[^_\n]+__|\*[^*\s][^*\n]*\*|_[^_\s][^_\n]*_|`[^`\n]+`)/g;
    let last = 0, m;
    while ((m = re.exec(text))) {
      if (m.index > last) frag.append(text.slice(last, m.index));
      const t = m[0];
      if (t.startsWith("**") || t.startsWith("__")) frag.append(h("strong", { text: t.slice(2, -2) }));
      else if (t.startsWith("`")) frag.append(h("code", { text: t.slice(1, -1) }));
      else frag.append(h("em", { text: t.slice(1, -1) }));
      last = m.index + t.length;
    }
    if (last < text.length) frag.append(text.slice(last));
    return frag;
  }
  function md(text) {
    const box = h("div", { class: "md" });
    let para = [], list = null, listType = null;
    const flushPara = () => { if (para.length) { const p = h("p"); para.forEach((l, i) => { if (i) p.append(h("br")); p.append(inline(l)); }); box.append(p); para = []; } };
    const flushList = () => { if (list) { box.append(list); list = null; listType = null; } };
    for (const raw of String(text || "").split("\n")) {
      const line = raw.trimEnd();
      const ul = line.match(/^\s*[-•*]\s+(.*)$/), ol = line.match(/^\s*\d+[.)]\s+(.*)$/);
      if (ul || ol) {
        flushPara();
        const type = ul ? "ul" : "ol";
        if (listType !== type) { flushList(); list = h(type); listType = type; }
        list.append(h("li", null, inline((ul || ol)[1])));
      } else if (!line.trim()) { flushPara(); flushList(); }
      else { flushList(); para.push(line); }
    }
    flushPara(); flushList();
    return box;
  }

  // ---------- tutor ----------
  const T = { setId: null, sessionId: null, mode: null, msgs: [], busy: false, conf: null, mastery: null, draft: "",
              kind: null, chapterId: null, topicId: null, plan: [], step: 0, goal: "", complete: false, summary: null };
  async function loadMastery() {
    if (!S.studentId || T.loadingM) return;
    T.loadingM = true;
    try { T.mastery = await api(`api/mastery/${encodeURIComponent(S.studentId)}`); } catch { T.mastery = { chapters: {}, levels: {} }; }
    T.loadingM = false;
    if (S.view === "practise") render();
  }
  function applySession(r) {
    T.sessionId = r.sessionId; T.kind = r.kind; T.goal = r.goal; T.plan = r.plan || []; T.step = r.step || 0;
    T.complete = !!r.complete; T.summary = r.summary || null; T.parts = r.parts || null;
  }
  function carryOn() { const box = $("tutor-input"); if (box) box.value = "Carry on to the next part."; T.draft = "Carry on to the next part."; tutorSend(); }
  function partsBar(p) {
    const k = p.parts.findIndex((x) => x.status === "now");
    const cur = k >= 0 ? p.parts[k] : null;
    const bar = h("div", { class: "parts-bar", "aria-label": "Your progress in this topic" },
      h("div", { class: "parts-row" },
        h("span", { class: "label", text: cur ? `Part ${k + 1} of ${p.parts.length}: ${cur.title}` : `${p.parts.length} parts` }),
        h("span", { class: `pill ${p.learnt >= p.of ? "good" : ""}`, text: `${p.learnt} of ${p.of} ideas learnt` })),
      h("div", { class: "parts-row", role: "list" }, ...p.parts.map((x, i) =>
        h("span", { role: "listitem", class: `part-dot ${x.status}`, title: x.question, "aria-label": `Part ${i + 1}, ${x.title}: ${x.status === "learned" ? "learnt" : x.status === "now" ? "now" : x.status === "skipped" ? "skipped" : "to do"}` },
          h("span", { class: "dot", text: x.status === "learned" ? "✓" : x.status === "skipped" ? "–" : String(i + 1) }), h("span", { text: x.title })))));
    if (p.ideas && p.ideas.length) {
      bar.append(h("div", { class: "idea-chips", "aria-label": "Ideas in this part" }, ...p.ideas.map((d) =>
        h("span", { class: `idea-chip ${d.status === "got it" ? "got" : d.status === "following" ? "following" : d.status === "learning" ? "learning" : ""}`,
          title: `${d.idea} (${d.status === "got it" ? "checked: got it" : d.status === "following" ? "following so far; the check comes next" : d.status === "learning" ? "still learning" : "not yet"})`,
          text: `${d.status === "got it" ? "✓ " : d.status === "following" ? "→ " : d.status === "learning" ? "… " : ""}${d.idea.length > 48 ? d.idea.slice(0, 46) + "…" : d.idea}` }))));
    }
    return bar;
  }
  function partCard(p) {
    const d = p.chunkDone; const quiz = d.quizId && S.sets.get(d.quizId);
    const idx = p.parts.findIndex((x) => x.id === d.id); const next = p.parts.find((x, i) => i > idx && x.status !== "learned");
    const names = new Map(((CHAPTERS_INFO(T.chapterId) || {}).topics || []).flatMap((t) => Object.entries(t.atoms || {})));
    const card = h("div", { class: "part-card" }, h("h3", { text: d.status === "learned" ? `Part ${idx + 1} learnt: ${d.title}` : `Part ${idx + 1} skipped: ${d.title}` }),
      d.status === "learned" ? h("p", { class: "cheer-line", text: partCheer(`${T.sessionId}${d.id}`, (d.ideas || []).some((x) => x.misses)) }) : null);
    if (d.ideas && d.ideas.length) card.append(h("ul", null, ...d.ideas.map((x) =>
      h("li", { text: `${x.got ? "✓" : "○"} ${names.get(x.atom) || x.atom}${x.got && x.misses ? " (needed another go)" : ""}` }))));
    const acts = h("div", { class: "students" });
    if (quiz && !T.complete) acts.append(h("button", { class: "btn accent", text: `Take the part quiz · ${quiz.questions.length} Qs (recommended)`,
      onclick: () => { endSession(); startTest(quiz.id); } }));
    if (next && !T.complete) acts.append(h("button", { class: quiz ? "btn ghost" : "btn accent", text: `Carry on: ${next.title}`, disabled: T.busy, onclick: carryOn }));
    card.append(acts);
    return card;
  }
  async function tutorStart(opts) {
    T.readOnly = false;
    if (!S.tutorOn) return toast("The tutor isn't switched on yet");
    T.setId = opts.chapterId; T.chapterId = opts.chapterId; T.topicId = opts.topicId || null; T.kind = opts.kind;
    T.msgs = []; T.busy = true; T.sessionId = null; T.plan = []; T.goal = ""; T.complete = false; T.summary = null; T.parts = null;
    S.view = "tutor"; S.run = null; render();
    try {
      const r = await api("api/tutor/start", { method: "POST", body: JSON.stringify({ studentId: S.studentId, ...opts }) });
      applySession(r); T.msgs.push({ who: "tutor", text: r.reply }); FT.start("chat"); resetWait();
    } catch (e) { toast(e.message); T.busy = false; T.setId = null; S.view = "practise"; document.body.classList.remove("in-chat"); render(); return; }
    T.busy = false; render(); scrollChat();
  }
  async function tutorSend(preset) {
    const box = $("tutor-input"); const text = (typeof preset === "string" ? preset : (box ? box.value : T.draft)).trim();
    if (!text || T.busy) return;
    T.nudge = false; T.waitSince = null; document.title = BASE_TITLE;
    T.msgs.push({ who: "me", text, conf: T.conf }); T.draft = ""; T.busy = true;
    const conf = T.conf; T.conf = null; render(); scrollChat();
    try {
      const r = await api("api/tutor/message", { method: "POST", body: JSON.stringify({ sessionId: T.sessionId, text, confidence: conf, focus: FT.take("chat") || undefined }) });
      applySession(r); T.msgs.push({ who: "tutor", text: r.reply, changes: r.changes, marks: r.marks }); resetWait();
    } catch (e) { T.msgs.push({ who: "system", text: e.message }); }
    T.busy = false; render(); scrollChat();
    const nb = $("tutor-input"); if (nb) nb.focus();
  }
  function endSession() {
    if (T.chapterId) S.chapterId = T.chapterId;
    T.sessionId = null; T.setId = null; T.msgs = []; T.mastery = null; T.plan = []; T.complete = false; T.summary = null; T.parts = null;
    FT.stop("chat");
    S.activity = null; S.view = "practise"; document.body.classList.remove("in-chat");
    S.myChats = {};       // refresh "Your tutor chats" next time a chapter opens
  }
  // ---------- past chats: list them on the chapter page, reopen and carry on ----------
  function myChats(cid) {
    S.myChats = S.myChats || {};
    const k = `${S.studentId}|${cid || "*"}`;
    if (S.myChats[k] === undefined && S.studentId && S.tutorOn) {
      S.myChats[k] = null;   // loading
      api(`api/tutor/sessions/${encodeURIComponent(S.studentId)}${cid ? `?chapterId=${encodeURIComponent(cid)}` : ""}`)
        .then((r) => { S.myChats[k] = r; }).catch(() => { S.myChats[k] = []; })
        .finally(() => { if (["practise", "chats"].includes(S.view)) render(); });
    }
    return S.myChats[k] || [];
  }
  function resumableChat(cid, topicId) {
    return myChats(cid).find((c) => c.kind === "learn" && c.topicId === topicId && !c.complete && c.atChunk && !c.atPartLearnt);
  }
  async function reopenChat(id) {
    T.busy = true; S.view = "tutor"; S.run = null; T.msgs = []; render();
    try {
      const r = await api(`api/tutor/session/${encodeURIComponent(id)}?studentId=${encodeURIComponent(S.studentId)}`);
      T.setId = r.chapterId; T.chapterId = r.chapterId; T.topicId = r.topicId || null; T.draft = "";
      applySession(r); T.msgs = r.msgs; if (!T.readOnly) { FT.start("chat"); resetWait(); }
      const row = Object.values(S.myChats || {}).flat().find((c) => c && c.id === id);
      T.readOnly = !!(r.complete || (row && row.atPartLearnt));
    } catch (e) { toast(e.message); T.busy = false; endSession(); render(); return; }
    T.busy = false; render(); scrollChat();
  }
  const CHAT_KINDS = { learn: "Learn", ask: "Question", fix: "Fix mistakes", review: "Review" };
  function chatWhen(iso) { return new Date(iso).toLocaleString(undefined, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }); }
  function chatRow(c, withChapter) {
    const open = !c.complete && !c.atPartLearnt;
    return h("li", null,
      h("div", null, h("strong", { text: `${CHAT_KINDS[c.kind] || c.kind}: ${c.title}` }),
        h("span", { class: "hint", text: ` · ${withChapter ? chapterTitle(c.chapterId) + " · " : ""}${chatWhen(c.updated)} · ${c.messages} messages${c.complete ? " · finished" : c.atPart && !c.atPartLearnt ? ` · stopped at ${c.atPart}` : ""}` })),
      h("button", { class: open ? "btn accent" : "react", text: open ? "Carry on" : "Read", onclick: () => reopenChat(c.id) }));
  }
  function ensureActivity() {
    if (!S.activity && !S.loadingActivity) {
      S.loadingActivity = true;
      api("api/activity").then((a) => { S.activity = a; }).catch(() => { S.activity = {}; }).finally(() => { S.loadingActivity = false; if (["practise", "progress"].includes(S.view)) render(); });
    }
  }

  // ---------- 📈 Report: numbers for a period, the coach, sharing, encouragement ----------
  const R = { sid: null, period: "week", start: "", end: "", data: null, loading: false, err: "", coach: null, busy: false, draft: "", shared: null, key: "" };
  const PERIODS = [["today", "Today"], ["yesterday", "Yesterday"], ["week", "This week"], ["lastweek", "Last week"], ["month", "This month"], ["30d", "Last 30 days"], ["custom", "Pick dates"]];
  function reportQuery() { return { studentId: R.sid, period: R.period, start: R.period === "custom" ? R.start || null : null, end: R.period === "custom" ? R.end || null : null, tz: new Date().getTimezoneOffset() }; }
  function loadReport(sid) {
    const key = JSON.stringify([sid, R.period, R.start, R.end]);
    if (R.key === key && (R.data || R.loading || R.err)) return;   // never retry a failed load on every redraw
    if (R.sid !== sid || R.key !== key) {
      R.saved = R.saved || {};
      if (R.key) R.saved[R.key] = { coach: R.coach, sharedTo: R.sharedTo, shared: R.shared };
      const back = R.saved[key] || {};
      R.coach = back.coach || null; R.sharedTo = back.sharedTo || []; R.shared = back.shared || null; R.draft = "";
    }
    R.sid = sid; R.key = key; R.loading = true; R.err = "";
    api("api/report", { method: "POST", body: JSON.stringify(reportQuery()) })
      .then((d) => { if (R.key === key) R.data = d; }).catch((e) => { R.err = e.message; R.data = null; })
      .finally(() => { R.loading = false; render(); });
  }
  function trend(cur, prev, unit = "") {
    if (cur == null || prev == null || cur === prev) return null;
    const up = cur > prev;
    return h("span", { class: `trend ${up ? "up" : "down"}`, text: up ? `▲ up from ${prev}${unit}` : `${prev}${unit} before` });
  }
  function statsView(st) {
    const pv = st.previous || {};
    const card = (big, label, tr) => h("div", { class: "stat" }, h("strong", { text: big }), h("span", { class: "hint", text: label }), tr);
    const wrap = h("div", { class: "report-body" });
    wrap.append(h("div", { class: "stat-grid" },
      card(String(st.minutes), "minutes (about)", trend(st.minutes, pv.minutes)),
      card(String(st.activeDays), st.activeDays === 1 ? "day active" : "days active", trend(st.activeDays, pv.activeDays)),
      card(String(st.partsLearnt), st.partsLearnt === 1 ? "part learnt" : "parts learnt", trend(st.partsLearnt, pv.partsLearnt)),
      card(String(st.quizzes), st.quizzes === 1 ? "quiz" : "quizzes", trend(st.quizzes, pv.quizzes)),
      card(st.average != null ? `${st.average}%` : "–", `average score · best try of each quiz${st.firstTryAverage != null ? ` · first tries ${st.firstTryAverage}%` : ""}`, trend(st.average, pv.average, "%")),
      card(st.best != null ? `${st.best}%` : "–", st.fullMarks ? `best · ${st.fullMarks}× full marks` : "best score", null)));
    if (st.days && st.days.length > 1) {
      const max = Math.max(10, ...st.days.map((d) => d.minutes));
      const bars = h("div", { class: "day-bars", role: "img", "aria-label": st.days.map((d) => `${d.date}: ${d.minutes} minutes, ${d.quizzes} quizzes`).join("; ") },
        ...st.days.map((d) => h("div", { class: "day", title: `${d.date}: ${d.minutes} min, ${d.quizzes} quiz${d.quizzes === 1 ? "" : "zes"}${d.average != null ? `, average ${d.average}%` : ""}` },
          h("span", { class: "bar", style: `height:${Math.round(100 * d.minutes / max)}%` }),
          d.quizzes ? h("span", { class: "dot", text: String(d.quizzes) }) : null,
          st.days.length <= 14 ? h("span", { class: "lbl", text: new Date(d.date + "T12:00").toLocaleDateString(undefined, st.days.length <= 7 ? { weekday: "short" } : { day: "numeric" }) }) : null)));
      wrap.append(h("div", { class: "chart" }, h("p", { class: "label", text: `Minutes each day · tallest bar ${max} min · green numbers are quizzes` }), bars));
    }
    if (st.focus) {
      const f = st.focus, plural = (n, w) => `${n} ${w}${n === 1 ? "" : w === "quiz" ? "zes" : "s"}`;
      const on = f.onScreenMinutes ?? f.focusedMinutes, share = f.onScreenShare ?? f.focusedShare;
      const quizLines = [f.quizzesSubmittedByLeaving ? `${plural(f.quizzesSubmittedByLeaving, "quiz")} submitted because she left the screen` : null,
        f.quizzesSubmittedAtTimeLimit ? `${plural(f.quizzesSubmittedAtTimeLimit, "quiz")} submitted automatically at twice the time` : null,
        f.quizzesNotSubmitted && f.quizzesNotSubmitted.length ? `Started but not submitted: ${f.quizzesNotSubmitted.join(", ")}` : null].filter(Boolean);
      wrap.append(h("div", { class: "idea-list focus" }, h("p", { class: "label", text: "📱 Time on screen (a rough guide)" }),
        h("p", { text: [`${on} min on screen and in use`, f.idleMinutes != null ? `${f.idleMinutes} min on screen but idle` : null,
          `${f.awayMinutes} min in another app or with the screen off`, `left the screen ${plural(f.switchesAway, "time")}`].filter(Boolean).join(" · ") }),
        share != null ? h("div", { class: "focus-bar", role: "img", "aria-label": `${share}% of the time on screen and in use` }, h("span", { style: `width:${share}%` })) : null,
        ...quizLines.map((t) => h("p", { text: t })),
        h("p", { class: "hint", text: "Counted during quizzes and tutor chats. It shows whether StepWise was on screen, not whether she was paying attention. A calculator app, a phone call or the screen locking count as leaving. A second device, or another window beside the browser, can't be seen. Idle means 3 minutes with no tapping, scrolling or typing, which can also be reading or thinking." })));
    }
    if (st.replies) {
      const r = st.replies;
      wrap.append(h("div", { class: "idea-list" }, h("p", { class: "label", text: "💬 Replies to the tutor" }),
        h("p", { text: [`${r.total} repl${r.total === 1 ? "y" : "ies"}`, r.dontKnow ? `${r.dontKnow} “don't know”` : null,
          r.offTopic ? `${r.offTopic} flagged off-topic` : null, r.notRealTry ? `${r.notRealTry} flagged as not a real try` : null].filter(Boolean).join(" · ") }),
        r.checked ? h("p", { text: `${r.checked} answer${r.checked === 1 ? "" : "s"} double-checked by a second marker · ${r.corrected || 0} marked too generously and corrected` }) : null,
        h("p", { class: "hint", text: "A “don't know” is fine: the tutor then explains. Flags come from the tutor when replies were random or unrelated more than once." })));
    }
    const list = (title, items, fmt) => items && items.length ? h("div", { class: "idea-list" }, h("p", { class: "label", text: title }),
      h("ul", null, ...items.slice(0, 3).map((x) => h("li", null, ...fmt(x)))),
      items.length > 3 ? h("details", { class: "more" }, h("summary", { text: `Show ${items.length - 3} more` }), h("ul", null, ...items.slice(3).map((x) => h("li", null, ...fmt(x))))) : null) : null;
    const strongEl = list("🌟 Strong ideas (right every time)", st.strong, (x) => [h("span", { text: x.idea }), h("span", { class: "hint", text: ` · ${x.chapter} · ${x.right}/${x.of}` })]);
    const weakEl = list("🎯 Ideas to work on", st.weak, (x) => [h("span", { text: x.idea }), h("span", { class: "hint", text: ` · ${x.chapter} · ${x.right}/${x.of} right` })]);
    if (strongEl) wrap.append(strongEl);
    if (weakEl) wrap.append(weakEl);
    const extra = [];
    if (st.newChapters && st.newChapters.length) extra.push(`New this period: ${st.newChapters.join(", ")}`);
    if (st.bySubject && Object.keys(st.bySubject).length) extra.push("Quiz average by subject: " + Object.entries(st.bySubject).map(([k, v]) => `${k} ${v.average}% (${v.quizzes})`).join(" · "));
    const fl = st.feelings || {}; const fe = { "feeling lost": "😕", "feeling repetitive": "🔁", "got insight": "💡", "gaining confidence": "💪" };
    if (Object.keys(fl).length) extra.push("Feelings pressed: " + Object.entries(fl).map(([k, v]) => `${fe[k] || ""} ${k} ×${v}`).join(" · "));
    if (st.notLearntYet) extra.push(`${st.notLearntYet} quiz question${st.notLearntYet > 1 ? "s" : ""} marked "not learnt yet"`);
    if (extra.length) wrap.append(h("div", { class: "idea-list" }, h("p", { class: "label", text: "📋 Also this period" }), h("ul", { class: "report-extra" }, ...extra.map((t) => h("li", { text: t })))));
    if (!st.minutes && !st.quizzes && !st.partsLearnt) wrap.append(h("p", { class: "muted", text: "Nothing recorded in this period yet." }));
    return wrap;
  }
  async function coachSend(text) {
    if (R.busy) return;
    R.coach = R.coach || { id: null, msgs: [] };
    if (text) R.coach.msgs.push({ who: "me", text });
    R.busy = true; render();
    try {
      const r = await api("api/report/coach", { method: "POST", body: JSON.stringify({ ...reportQuery(), coachId: R.coach.id,
        history: R.coach.msgs.map((m) => ({ role: m.who === "me" ? "user" : "assistant", content: m.text })) }) });
      R.coach.id = r.coachId; R.coach.msgs.push({ who: "coach", text: r.reply });
    } catch (e) { R.coach.msgs.push({ who: "system", text: e.message }); }
    R.busy = false; render();
  }
  function coachView(forParent) {
    const box = h("section", { class: "sheet coach" }, h("h3", { text: forParent ? "✨ Coach: how is it going?" : "✨ Coach: how did I do?" }));
    if (!S.tutorOn) { box.append(h("p", { class: "muted", text: "The coach isn't switched on yet." })); return box; }
    if (!R.coach || !R.coach.msgs.length) {
      box.append(h("p", { class: "muted", text: forParent ? "Get feedback on this period: what went well, what to keep an eye on, and how you can help." : "Get feedback on this period: what went well, what to pay attention to, and what to do next." }),
        h("button", { class: "btn accent", disabled: R.busy || !R.data, text: R.busy ? "Thinking…" : "✨ Get feedback", onclick: () => coachSend("") }));
      return box;
    }
    for (const m of R.coach.msgs) box.append(h("div", { class: `bubble ${m.who === "me" ? "me" : m.who === "coach" ? "tutor" : "system"}` }, m.who === "coach" ? md(m.text) : h("p", { text: m.text })));
    if (R.busy) box.append(h("div", { class: "bubble tutor" }, h("div", { class: "typing" }, h("span"), h("span"), h("span"))));
    const inp = h("input", { type: "text", placeholder: forParent ? "Ask the coach, e.g. how can I help this week?" : "Ask the coach, e.g. what should I focus on tomorrow?", "aria-label": "Ask the coach", maxlength: "500" });
    inp.value = R.draft; inp.addEventListener("input", () => { R.draft = inp.value; });
    box.append(h("form", { class: "add-student", onsubmit: (e) => { e.preventDefault(); const t = inp.value.trim(); if (t) { R.draft = ""; coachSend(t); } } },
      inp, h("button", { class: "btn ghost", type: "submit", disabled: R.busy, text: "Ask" })));
    return box;
  }
  function shareView(st) {
    const fam = (S.family && S.family[R.sid]) || [];
    const box = h("section", { class: "sheet share" }, h("h3", { text: "📤 Share this report" }));
    if (!fam.length) { box.append(h("p", { class: "muted", text: "No parent is linked to your account yet." })); return box; }
    const commentary = R.coach && (R.coach.msgs.find((m) => m.who === "coach") || {}).text || "";
    box.append(h("p", { class: "muted", text: commentary ? "Your numbers and the feedback will be sent." : "Your numbers will be sent. Get feedback first if you'd like to include it." }));
    R.sharedTo = R.sharedTo || [];
    const send = async (ids) => {
      ids = ids.filter((x) => !R.sharedTo.includes(x)); if (!ids.length || R.sharing) return;
      R.sharing = true;
      try {
        const r = await api("api/report/share", { method: "POST", body: JSON.stringify({ ...reportQuery(), to: ids, commentary }) });
        R.sharedTo.push(...ids); R.shared = { id: r.id, names: [...((R.shared && R.shared.names) || []), ...r.sharedWith] };
      } catch (e) { toast(e.message); } finally { R.sharing = false; render(); }
    };
    const icon = (p) => (p.relation === "Mom" ? "👩" : p.relation === "Dad" ? "👨" : "👤");
    const row = h("div", { class: "topic-actions" }, ...fam.map((p) => R.sharedTo.includes(p.id)
      ? h("button", { class: "btn ghost", disabled: true, text: `✓ Sent to ${p.relation}` })
      : h("button", { class: "btn ghost", text: `${icon(p)} ${p.relation}`, onclick: () => send([p.id]) })));
    const left = fam.filter((p) => !R.sharedTo.includes(p.id));
    if (fam.length > 1 && left.length > 1) row.append(h("button", { class: "btn ghost", text: left.length === 2 ? "👪 Both" : "👪 Everyone", onclick: () => send(left.map((p) => p.id)) }));
    box.append(row);
    if (R.shared) {
      const url = `${location.origin}${location.pathname}#/report/${R.shared.id}`;
      box.append(h("div", { class: "notice good" }, h("p", { text: `Sent to ${R.shared.names.join(" and ")}. They'll see it in their app. You can also send them this link:` }),
        h("div", { class: "add-student" }, h("input", { type: "text", value: url, readonly: true, "aria-label": "Report link" }),
          h("button", { class: "btn ghost", text: navigator.share ? "Send link…" : "Copy link", onclick: async () => {
            try { if (navigator.share) await navigator.share({ title: "My StepWise report", text: "Here's my StepWise report:", url }); else { await navigator.clipboard.writeText(url); toast("Link copied"); } } catch {}
          } }))));
    }
    return box;
  }
  function periodPicker() {
    const chips = h("div", { class: "selfmark period" }, ...PERIODS.map(([k, label]) => h("button", { type: "button", "aria-pressed": String(R.period === k), text: label,
      onclick: () => { R.period = k; R.data = null; R.key = ""; render(); } })));
    const box = h("div", { class: "period-box" }, chips);
    if (R.period === "custom") {
      const st = R.data && R.data.stats; const dflt = (iso) => (iso ? iso.slice(0, 10) : "");
      const a = h("input", { type: "date", value: R.start || dflt(st && st.from), "aria-label": "From" });
      const b = h("input", { type: "date", value: R.end || (st ? new Date(new Date(st.to).getTime() - 864e5).toISOString().slice(0, 10) : ""), "aria-label": "To" });
      box.append(h("form", { class: "add-student", onsubmit: (e) => { e.preventDefault(); R.start = a.value; R.end = b.value; R.data = null; R.key = ""; render(); } },
        h("span", { text: "From" }), a, h("span", { text: "to" }), b, h("button", { class: "btn ghost", type: "submit", text: "Show" })));
    }
    return box;
  }
  function renderReportFor(main, sid, forParent) {
    const st = S.students.get(sid); if (!st) return;
    loadReport(sid);
    const first = st.name.split(" ")[0];
    main.append(h("section", { class: "home-hello" }, h("h2", { text: forParent ? `📈 ${first}'s report` : "📈 Your report" }),
      h("p", { class: "muted", text: forParent ? "How the chosen period went, compared with the period before." : "How you did, compared with the period before. Pick a period, get feedback, and share it with your parents." }),
      !forParent && ((S.family && S.family[sid]) || []).length ? h("p", { class: "hint", text: `👀 ${((S.family && S.family[sid]) || []).map((x) => x.relation).join(" and ")} can always see this page and read your tutor chats. Sharing sends them this period with the feedback, and lets them know.` }) : null));
    main.append(h("section", { class: "sheet" }, periodPicker(),
      R.loading && !R.data ? h("p", { class: "muted", text: "Counting…" }) : R.err ? h("p", { class: "muted", text: R.err }) : R.data ? h("div", null, h("p", { class: "label", text: R.data.label }), statsView(R.data.stats)) : null));
    if (R.data) main.append(coachView(forParent));
    if (R.data && !forParent) main.append(shareView(R.data.stats));
  }
  function noteBox(sid, reportId) {
    const st = S.students.get(sid); const first = st ? st.name.split(" ")[0] : "";
    const inp = h("textarea", { rows: "2", maxlength: "500", placeholder: `A few words for ${first}…`, "aria-label": `Encouragement for ${first}` });
    const send = async (text) => {
      if (!text.trim()) return;
      try { const n = await api("api/notes", { method: "POST", body: JSON.stringify({ studentId: sid, text, reportId: reportId || null }) }); S.notes.push(n); toast(`Sent to ${first} 💌`); render(); }
      catch (e) { toast(e.message); }
    };
    const quick = ["So proud of you! 🌟", "Great effort this week 💪", "Keep going, you've got this! 🚀", "Loved seeing you stick with the hard bits ❤️"];
    const sent = (S.notes || []).filter((n) => n.studentId === sid && n.fromUser === S.me.id).slice(-3).reverse();
    return h("section", { class: "sheet" }, h("h3", { text: `💌 Send ${first} some encouragement` }),
      h("div", { class: "due-list" }, ...quick.map((q) => h("button", { class: "react", text: q, onclick: () => { inp.value = q; inp.focus(); } }))),
      h("form", { class: "note-form", onsubmit: (e) => { e.preventDefault(); send(inp.value); } }, inp, h("button", { class: "btn accent", type: "submit", text: "Send" })),
      sent.length ? h("div", null, h("p", { class: "label", text: "You sent" }), h("ul", { class: "hint" }, ...sent.map((n) => h("li", { text: `${chatWhen(n.created)} · ${n.text}${n.heart ? " · ❤️ back" : n.seen ? " · seen" : " · not seen yet"}` })))) : null);
  }
  async function renderSharedReport(main, rid) {
    if (!S.sharedReport || S.sharedReport.id !== rid) {
      main.append(h("section", { class: "sheet" }, h("p", { class: "muted", text: "Opening the report…" })));
      if (!S.sharedLoading) {
        S.sharedLoading = true;
        api(`api/reports/${encodeURIComponent(rid)}`).then((r) => { S.sharedReport = r; S.reportsList = null; })
          .catch((e) => { S.sharedReport = { id: rid, error: e.message }; }).finally(() => { S.sharedLoading = false; render(); });
      }
      return;
    }
    const r = S.sharedReport;
    main.append(h("div", null, backLink("← Back", () => { history.length > 1 ? history.back() : goPlace(S.studentId === "parent" ? "bank" : "today"); })));
    if (r.error) { main.append(h("section", { class: "sheet" }, h("p", { class: "muted", text: r.error }))); return; }
    main.append(h("section", { class: "home-hello" }, h("h2", { text: `📈 ${r.student.split(" ")[0]}'s report · ${r.label}` }),
      h("p", { class: "muted", text: `Shared ${chatWhen(r.created)} with ${r.sharedWithNames.join(" and ")}` })));
    main.append(h("section", { class: "sheet" }, statsView(r.stats)));
    if (r.commentary) main.append(h("section", { class: "sheet coach" }, h("h3", { text: "✨ What the coach said" }), h("div", { class: "bubble tutor" }, md(r.commentary))));
    if (S.me.role !== "child") main.append(noteBox(r.studentId, r.id));
  }
  function notesCard(sid) {
    S.heartedNow = S.heartedNow || new Set();
    const mine = (S.notes || []).filter((n) => n.studentId === sid && (!n.seen || S.heartedNow.has(n.id)));
    const groups = new Map();   // the same words from the same person show once
    for (const n of mine) { const k = `${n.fromUser}|${n.text}`; if (!groups.has(k)) groups.set(k, []); groups.get(k).push(n); }
    if (!groups.size) return null;
    const mark = async (items, heart) => {
      try { for (const n of items) { Object.assign(n, await api(`api/notes/${n.id}/seen${heart ? "?heart=true" : ""}`, { method: "POST" })); if (heart) S.heartedNow.add(n.id); } render(); }
      catch (e) { toast(e.message); }
    };
    return h("section", { class: "sheet notes" }, ...[...groups.values()].slice(-3).map((items) => {
      const n = items[items.length - 1]; const hearted = items.every((x) => x.heart);
      return h("div", { class: "note" },
        h("p", { class: "label", text: `💌 From ${n.relation === "Parent" ? n.fromName : n.relation} · ${chatWhen(n.created)}${items.length > 1 ? ` · ×${items.length}` : ""}` }),
        h("p", { class: "note-text", text: n.text }),
        h("div", { class: "topic-actions" }, hearted
          ? h("span", { class: "pill good", text: "❤️ sent" })
          : h("button", { class: "btn accent small", text: "❤️ Thanks!", onclick: () => mark(items, true) }),
          h("button", { class: "react", text: hearted ? "Close" : "Got it", onclick: () => { items.forEach((x) => S.heartedNow.delete(x.id)); if (hearted) render(); else mark(items, false); } })));
    }));
  }
  function kidWeek(sid) {
    S.kidWeek = S.kidWeek || {};
    if (S.kidWeek[sid] === undefined) {
      S.kidWeek[sid] = null;
      api("api/report", { method: "POST", body: JSON.stringify({ studentId: sid, period: "week", tz: new Date().getTimezoneOffset() }) })
        .then((r) => { S.kidWeek[sid] = r.stats; }).catch(() => { S.kidWeek[sid] = false; }).finally(() => render());
    }
    return S.kidWeek[sid];
  }
  function parentReports(main) {
    const kids = [...S.students.values()].filter((k) => !k.test).sort((a, b) => (a.name || "").localeCompare(b.name || ""));
    if (!kids.length) { main.append(h("section", { class: "sheet" }, h("p", { class: "muted", text: "No children linked to your account yet." }))); return; }
    if (!B.kid || !S.students.has(B.kid)) B.kid = kids[0].id;
    const unreadBy = {}; for (const r of S.reportsList || []) if (r.unread) unreadBy[r.studentId] = (unreadBy[r.studentId] || 0) + 1;
    main.append(h("div", { class: "kid-cards" }, ...kids.map((k) => {
      const w = kidWeek(k.id); const lost = w && w.feelings ? w.feelings["feeling lost"] || 0 : 0;
      return h("button", { class: `kid-card ${B.kid === k.id ? "on" : ""}`, "aria-pressed": String(B.kid === k.id), onclick: () => { B.kid = k.id; B.chatOpen = null; render(); } },
        h("strong", { text: k.name.split(" ")[0] }), h("span", { class: "hint", text: "This week" }),
        w ? h("span", { text: `${w.minutes} min · ${w.quizzes} quiz${w.quizzes === 1 ? "" : "zes"}${w.average != null ? ` · avg ${w.average}%` : ""} · ${w.partsLearnt} part${w.partsLearnt === 1 ? "" : "s"} learnt${w.focus && (w.focus.onScreenShare ?? w.focus.focusedShare) != null ? ` · ${w.focus.onScreenShare ?? w.focus.focusedShare}% on screen` : ""}` })
          : h("span", { class: "hint", text: w === false ? "Couldn't load" : "Loading…" }),
        h("span", null, unreadBy[k.id] ? h("span", { class: "pill warn", text: `📬 ${unreadBy[k.id]} new report${unreadBy[k.id] > 1 ? "s" : ""}` }) : null,
          lost ? h("span", { class: "pill", text: `😕 felt lost ×${lost}` }) : null));
    })));
    if (!S.reportsList && !S.reportsLoading) {
      S.reportsLoading = true;
      api("api/reports").then((r) => { S.reportsList = r; }).catch(() => { S.reportsList = []; }).finally(() => { S.reportsLoading = false; render(); });
    }
    const shared = (S.reportsList || []).filter((r) => r.studentId === B.kid);
    if (shared.length) main.append(h("section", { class: "sheet" }, h("h3", { text: "📬 Reports shared with you" }),
      h("ul", { class: "chat-list" }, ...shared.slice(0, 8).map((r) => h("li", null,
        h("div", null, h("strong", { text: `${(S.students.get(r.studentId) || { name: "" }).name.split(" ")[0]} · ${r.label}` }), h("span", { class: "hint", text: ` · ${chatWhen(r.created)}` }), r.unread ? h("span", { class: "pill warn", text: "new" }) : null),
        h("button", { class: r.unread ? "btn accent small" : "react", text: "Open", onclick: () => { location.hash = `#/report/${r.id}`; } }))))));
    renderReportFor(main, B.kid, true);
    main.append(noteBox(B.kid, null));
    main.append(kidChats(B.kid));
  }
  function kidChats(sid) {
    if (!P.chats && !P.loadingChats) {
      P.loadingChats = true;
      api("api/parent/chats").then((r) => { P.chats = r; }).catch(() => { P.chats = []; }).finally(() => { P.loadingChats = false; render(); });
    }
    const first = (S.students.get(sid) || { name: "" }).name.split(" ")[0];
    const list = (P.chats || []).filter((c) => c.studentId === sid).slice(0, 6);
    const sec = h("section", { class: "sheet" }, h("h3", { text: `💬 ${first}'s recent tutor chats` }),
      h("p", { class: "hint", text: "Read-only. The newest first." }));
    if (!list.length) { sec.append(h("p", { class: "muted", text: P.chats ? "No chats yet." : "Loading…" })); return sec; }
    const ul = h("ul", { class: "chat-list" });
    for (const c of list) {
      const isOpen = B.chatOpen && B.chatOpen.id === c.id;
      ul.append(h("li", { id: `pchat-${c.id}` },
        h("div", null, h("strong", { text: `${c.subject} · ${c.chapter}` }), h("span", { class: "hint", text: ` · ${chatWhen(c.updated)} · ${c.messages} messages${c.flags && c.flags.length ? ` · ⚠️ ${c.flags.length} flag${c.flags.length > 1 ? "s" : ""}` : ""}` })),
        h("button", { class: "react", text: isOpen ? "Close" : "Read", onclick: async () => {
          if (isOpen) { B.chatOpen = null; return render(); }
          try { B.chatOpen = await api(`api/parent/chats/${encodeURIComponent(c.id)}`); } catch (e) { toast(e.message); }
          render(); requestAnimationFrame(() => { const el = $(`pchat-${c.id}`); if (el) el.scrollIntoView({ block: "start", behavior: "smooth" }); }); } })));
      if (isOpen) {
        const log = h("li", { class: "chat-log-row" }, h("div", { class: "chat-log" }, h("p", { class: "label", text: `${c.subject} · ${c.chapter} · ${chatWhen(c.updated)}` })));
        const box = log.firstChild;
        for (const f of B.chatOpen.flags || []) box.append(h("div", { class: `notice ${f.kind === "distress" ? "bad" : ""}` }, h("p", { text: `Flag (${f.kind.replace("_", " ")}): ${f.note}` })));
        for (const m of B.chatOpen.transcript) box.append(h("div", { class: `bubble ${m.role === "student" ? "me" : "tutor"}` }, m.role === "student" ? h("p", { text: m.text }) : md(m.text)));
        box.append(h("button", { class: "react", text: "Close this chat", onclick: () => { B.chatOpen = null; render(); } }));
        ul.append(log);
      }
    }
    sec.append(ul);
    return sec;
  }
  function renderMyProgress(main) {
    const st = S.studentId && S.students.get(S.studentId);
    if (!st) { main.append(studentPicker(false)); return; }
    if (!T.mastery && !T.loadingM) loadMastery();
    ensureActivity();
    renderReportFor(main, st.id, false);
    main.append(h("h2", { class: "section-title", text: "📚 All your subjects" }));
    for (const s of subjectsFor(st)) {
      const rows = [];
      for (const u of unitsOf(s)) for (const c of u.chapters) {
        const pr = chapterProgress(c.id, st.id); if (pr.state === "new") continue;
        const best = quizzesOf(c.id).map((z) => bestOf(st.id, z.id)).filter(Boolean);
        const avg = best.length ? Math.round(best.reduce((t, a) => t + pct(a.score, a.max), 0) / best.length) : null;
        rows.push(h("button", { class: "prog-row", onclick: () => openChapter(c.id) },
          h("strong", { text: chapterTitle(c.id) }),
          avg !== null ? h("span", { class: `pill ${band(avg)}`, text: `quizzes ${avg}%` }) : h("span"),
          h("span", { class: "prog-bar", "aria-hidden": "true" }, h("span", { style: `width:${pr.of ? Math.round(100 * pr.done / pr.of) : 0}%` })),
          h("span", { class: "hint", text: `${pr.done} of ${pr.of} ${pr.unit}${pr.quizDone ? ` · ${pr.quizDone} of ${pr.quizzes} quizzes done` : ""}` })));
      }
      main.append(h("section", { class: "sheet" }, h("h3", { text: s.name }),
        rows.length ? h("div", { class: "prog-list" }, ...rows) : h("p", { class: "muted", text: "Not started yet." })));
    }
    const recent = attemptsFor(st.id).slice(0, 8);
    if (recent.length) main.append(h("section", { class: "sheet" }, h("h3", { text: "Latest quizzes" }),
      h("ul", { class: "chat-list" }, ...recent.map((a) => {
        const set = S.sets.get(a.setId); const p = pct(a.score, a.max);
        return h("li", null, h("div", null, h("strong", { text: set ? (set.title || set.chapter) : a.chapter }),
          h("span", { class: "hint", text: ` · ${a.subject} · ${new Date(a.submittedAt).toLocaleDateString(undefined, { day: "numeric", month: "short" })}` })),
          h("span", { class: `pill ${band(p)}`, text: `${p}%` }));
      }))));
  }
  function renderChats(main) {
    const st = S.studentId && S.students.get(S.studentId);
    if (!st) { main.append(studentPicker(false)); return; }
    const list = myChats(null); const loading = S.myChats[`${S.studentId}|*`] === null;
    const fam = ((S.family && S.family[S.studentId]) || []).map((x) => x.relation);
    const sec = h("section", { class: "sheet" }, h("h2", { text: "💬 Your tutor chats" }),
      h("p", { class: "muted", text: "Every chat you've had with the tutor, newest first. Open one to read it again or carry on where you stopped." }),
      fam.length ? h("p", { class: "hint", text: `👀 ${fam.join(" and ")} can read these chats.` }) : null);
    if (!S.tutorOn) sec.append(h("p", { class: "muted", text: "The tutor isn't switched on yet." }));
    else if (loading) sec.append(h("p", { class: "muted", text: "Loading your chats…" }));
    else if (!list.length) sec.append(h("p", { class: "muted", text: "No chats yet. Open a topic in 📚 Subjects and press “Learn with the tutor”." }));
    const shown = S.chatFilter ? list.filter((c) => c.chapterId === S.chatFilter) : list;
    if (S.chatFilter) sec.append(h("div", { class: "selfmark" }, h("span", { class: "hint", text: `Only: ${chapterTitle(S.chatFilter)}` }),
      h("button", { type: "button", text: "Show all chats ✕", onclick: () => { S.chatFilter = null; render(); } })));
    const groups = new Map();
    for (const c of shown) { const subj = (CHAPTERS_INFO(c.chapterId) || {}).subject || "Other"; if (!groups.has(subj)) groups.set(subj, []); groups.get(subj).push(c); }
    for (const [subj, items] of groups) sec.append(h("div", { class: "chat-group" }, h("h3", { text: subj }), h("ul", { class: "chat-list" }, ...items.map((c) => chatRow(c, true)))));
    main.append(sec);
  }
  function chatsSection(cid) {
    const list = myChats(cid);
    if (!list.length) return null;
    const when = (iso) => new Date(iso).toLocaleString(undefined, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" });
    const kinds = { learn: "Learn", ask: "Question", fix: "Fix mistakes", review: "Review" };
    const shown = S.allChats === cid ? list : list.slice(0, 4);
    return h("section", { class: "sheet" },
      h("h3", { text: "Your tutor chats" }),
      h("p", { class: "hint", text: "Open any chat to read it again or carry on where you stopped." }),
      h("ul", { class: "chat-list" }, ...shown.map((c) => h("li", null,
        h("div", null, h("strong", { text: `${kinds[c.kind] || c.kind}: ${c.title}` }),
          h("span", { class: "hint", text: ` · ${when(c.updated)} · ${c.messages} messages${c.complete ? " · finished" : c.atPart && !c.atPartLearnt ? ` · stopped at ${c.atPart}` : ""}` })),
        h("button", { class: "react", text: c.complete || c.atPartLearnt ? "Read" : "Open and carry on", onclick: () => reopenChat(c.id) })))),
      list.length > 4 ? h("button", { class: "react", text: S.allChats === cid ? "Show fewer" : `Show all ${list.length}`,
        onclick: () => { S.allChats = S.allChats === cid ? null : cid; render(); } }) : null);
  }
  function CHAPTERS_INFO(cid) {
    const t = (S.topics || {})[cid]; if (t) return t;
    const anySet = [...S.sets.values()].find((x) => (x.chapterId || x.id) === cid);
    return anySet ? { subject: anySet.subject, code: anySet.code, chapter: anySet.chapter } : null;
  }
  // Expected reply time: time to read the tutor's last message plus time to think, 2 to 6 minutes.
  // After that, ring once, show a nudge with help options; ring once more 3 minutes later, then stay quiet.
  const NUDGE_AGAIN_MS = 3 * 60 * 1000;
  function expectedReplyMs() {
    const last = [...T.msgs].reverse().find((m) => m.who === "tutor");
    const words = last ? String(last.text).split(/\s+/).length : 60;
    return Math.min(6 * 60, Math.max(2 * 60, Math.round(words / 3) + 90)) * 1000;
  }
  function chatWaiting() {
    return S.view === "tutor" && T.sessionId && !T.readOnly && !T.busy && !T.complete && T.waitSince;
  }
  function resetWait() { T.waitSince = Date.now(); T.nudges = 0; T.nudge = false; document.title = BASE_TITLE; }
  // Typing holds the nudge back only while she is actually typing (30 s after the last key), and never past twice
  // the expected time: typing something and leaving it unsent doesn't silence the tutor.
  function nudgeDueAt() {
    const exp = expectedReplyMs(), extra = (T.nudges || 0) * NUDGE_AGAIN_MS;
    const due = T.waitSince + exp + extra;
    return Math.max(due, Math.min((T.lastTyped || 0) + 30000, T.waitSince + 2 * exp + extra));
  }
  function checkNudge() {
    if (!chatWaiting()) { if (document.title !== BASE_TITLE && !T.nudge) document.title = BASE_TITLE; return; }
    if (Date.now() < nudgeDueAt() || (T.nudges || 0) >= 2) return;
    T.nudges = (T.nudges || 0) + 1; T.nudge = true;
    if (document.hidden) document.title = "⏰ Your tutor is waiting";
    ALARM.ring(); render(); scrollChat();
  }
  setInterval(checkNudge, 5000);
  document.addEventListener("visibilitychange", () => {
    if (!document.hidden) { awayPing({ kind: "back" }); document.title = BASE_TITLE; checkNudge(); return; }
    if (chatWaiting() && (T.nudges || 0) < 2) {
      awayPing({ kind: "chat", sessionId: T.sessionId, dueInMs: Math.max(0, nudgeDueAt() - Date.now()) });
    }
  });
  function nudgeCard() {
    const say = (text) => { T.draft = ""; const box = $("tutor-input"); if (box) box.value = text; else T.draft = text; resetWait(); tutorSend(text); };
    const typed = ($("tutor-input") ? $("tutor-input").value : T.draft || "").trim();
    if (typed) return h("div", { class: "nudge", role: "alert" },
      h("p", null, h("strong", { text: "⏰ Ready to send? " }), h("span", { text: "You've typed an answer but haven't sent it. Send what you have, even if you're not sure. The tutor will help from there." })),
      h("div", { class: "topic-actions" },
        h("button", { class: "btn accent", text: "📨 Send it", onclick: () => { resetWait(); tutorSend(); } }),
        h("button", { class: "btn ghost", text: "🔁 Ask me again, more simply", onclick: () => say("I'm finding this hard to answer. Can you ask me again in a simpler way?") }),
        h("button", { class: "btn ghost", text: "💡 Give me a hint", onclick: () => say("Can I have a hint?") })));
    return h("div", { class: "nudge", role: "alert" },
      h("p", null, h("strong", { text: "⏰ Still there? " }), h("span", { text: "The tutor is waiting for your answer. If it's hard to answer, that's fine. Pick one:" })),
      h("div", { class: "topic-actions" },
        h("button", { class: "btn accent", text: "🔁 Ask me again, more simply", onclick: () => say("I'm finding this hard to answer. Can you ask me again in a simpler way?") }),
        h("button", { class: "btn ghost", text: "💡 Give me a hint", onclick: () => say("Can I have a hint?") }),
        h("button", { class: "btn ghost", text: "✋ I'm here, still thinking", onclick: () => { resetWait(); render(); const b = $("tutor-input"); if (b) b.focus(); } })));
  }
  function scrollChat() { T.stick = true; requestAnimationFrame(() => { const el = $("chat-scroll"); if (el) el.scrollTop = el.scrollHeight; }); }
  // How the session feels. Every press is saved as session feedback for the parent; "lost" and "repetitive"
  // also tell the tutor at once so it changes course.
  const FEELINGS = [
    { tag: "feeling lost", label: "😕 Feeling lost", say: "I'm feeling lost." },
    { tag: "feeling repetitive", label: "🔁 Feeling repetitive", say: "This feels repetitive." },
    { tag: "got insight", label: "💡 Got an insight", say: null },
    { tag: "gaining confidence", label: "💪 Gaining confidence", say: null },
  ];
  async function feel(f) {
    if (!T.sessionId || T.busy) return;
    if (f.say && T.feelArm !== f.tag) {   // these change the lesson, so a stray tap shouldn't send them
      T.feelArm = f.tag; render(); clearTimeout(T.feelTimer);
      T.feelTimer = setTimeout(() => { T.feelArm = null; render(); }, 4000); return;
    }
    T.feelArm = null; clearTimeout(T.feelTimer);
    const last = [...T.msgs].reverse().find((m) => m.who === "tutor");
    api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId, targetType: "tutor_session", setId: T.setId, sessionId: T.sessionId,
      excerpt: last ? last.text.slice(0, 600) : null, tags: [f.tag], text: "" }) })
      .then((x) => S.feedback.push(x)).catch((e) => toast(e.message));
    if (!f.say) return toast(f.tag === "got insight" ? "Nice! Noted." : "Great, noted.");
    const box = $("tutor-input"); const typed = (box ? box.value : T.draft).trim();
    T.draft = `[${f.tag}] ${f.say}${typed ? " " + typed : ""}`; if (box) box.value = T.draft;
    tutorSend();
  }
  async function react(m, up) {
    if (up) {
      m.rated = "up";
      try { const f = await api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId, targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600), tags: ["helpful"], text: "" }) }); S.feedback.push(f); toast("Thanks"); }
      catch (e) { m.rated = null; toast(e.message); }
    } else {
      m.open = !m.open;
      const k = JSON.stringify({ targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600) });
      m.open ? fbOpen.add(k) : fbOpen.delete(k);
    }
    render();
  }
  function levelBar(byLevel, total) {
    const bar = h("div", { class: "lv-bar", role: "img", "aria-label": `Idea levels: ${byLevel.map((n, i) => `${n} at level ${i}`).join(", ")}` });
    byLevel.forEach((n, i) => { if (n) bar.append(h("span", { class: `lv lv${i}`, style: `flex:${n}` })); });
    if (!total) bar.append(h("span", { class: "lv lv0", style: "flex:1" }));
    return bar;
  }
  function renderTutor(main, dock, dockRow) {
    const st = S.studentId && S.students.get(S.studentId);
    if (S.studentId === "parent") {
      main.append(h("section", { class: "sheet" }, h("h2", { text: "The tutor is for the girls" }),
        h("p", { class: "muted", text: "Read every tutor chat, and the feedback on it, in the Progress tab." })));
      return;
    }
    if (!st) { main.append(studentPicker(false)); return; }
    if (!S.tutorOn) {
      main.append(h("section", { class: "sheet" }, h("h2", { text: "The tutor isn't switched on yet" }),
        h("p", { class: "muted", text: "Your parent needs to finish setting it up. Self-checks work as normal." })));
      return;
    }
    if (!T.sessionId && !T.busy) { S.view = "practise"; document.body.classList.remove("in-chat"); return render(); }
    if (false) {
      main.append(h("section", { class: "sheet" }, h("h2", { text: `${st.name}, pick a chapter` }),
        h("p", { class: "muted", text: "Today's practice is a short planned session: a few quick reviews, one or two new ideas, a stretch question and an exit ticket. Ask questions is free chat about the chapter. Your parent can read these chats." }),
        h("div", { class: "legend" }, ...[0, 1, 2, 3, 4].map((i) => h("span", null, h("span", { class: `lv-dot lv${i}` }), ["not met", "recall", "apply", "combine", "exam-ready"][i])))));
      const grid = h("div", { class: "sets" });
      const sets = [...S.sets.values()].sort((a, b) => (a.subject || "").localeCompare(b.subject || ""));
      for (const s of sets) {
        const ms = T.mastery && T.mastery[s.id];
        grid.append(h("div", { class: "set-card" },
          h("span", { class: "code", text: `${s.subject} · ${s.code}` }), h("h3", { text: s.chapter }),
          ms ? levelBar(ms.byLevel, ms.atoms) : h("div", { class: "lv-bar" }, h("span", { class: "lv lv0", style: "flex:1" })),
          ms ? h("span", { class: "hint", text: `${ms.byLevel.slice(2).reduce((a, b) => a + b, 0)} of ${ms.atoms} ideas at apply level or above` }) : null,
          h("div", { class: "students" },
            h("button", { class: "btn accent", text: "Today's practice", onclick: () => tutorStart(s.id, "practice") }),
            h("button", { class: "btn ghost", text: "Ask questions", onclick: () => tutorStart(s.id, "chat") }))));
      }
      main.append(grid);
      return;
    }
    const set = S.sets.get(T.setId) || {};
    document.body.classList.add("in-chat");
    const scroller = h("div", { class: "chat-scroll", id: "chat-scroll", role: "log", "aria-live": "polite", "aria-label": "Tutor conversation" });
    for (const m of T.msgs) {
      const b = h("div", { class: `bubble ${m.who}` }, m.who === "tutor" ? md(m.text) : h("p", { text: m.text }));
      if (m.conf) b.append(h("span", { class: "hint", text: `You said: ${m.conf}` }));
      if (m.marks && m.marks.length) {
        const MARK = { right: ["good", "✓ Recorded: right"], partly: ["warn", "◐ Recorded: partly right"], wrong: ["bad", "✗ Recorded: not yet"], no_attempt: ["bad", "– Recorded: not tried"] };
        for (const k of m.marks) { const [cls, label] = MARK[k.outcome] || MARK.wrong; b.append(h("span", { class: `pill ${cls}`, title: k.question || "", text: label })); }
      }
      if (m.changes && m.changes.length) {
        const ups = m.changes.filter((c) => c.to > c.from).length, downs = m.changes.filter((c) => c.to < c.from).length;
        if (ups || downs) b.append(h("span", { class: `pill ${ups && !downs ? "good" : downs && !ups ? "bad" : "warn"}`, text: [ups ? `${ups} idea${ups > 1 ? "s" : ""} up a level` : "", downs ? `${downs} idea${downs > 1 ? "s" : ""} to revisit` : ""].filter(Boolean).join(" · ") }));
      }
      const ft = { targetType: "tutor_message", setId: T.setId, sessionId: T.sessionId, excerpt: m.text.slice(0, 600) };
      if (m.open && !fbOpen.has(JSON.stringify(ft))) m.open = false;
      if (m.who === "tutor" && T.sessionId && !T.readOnly) {
        b.append(h("div", { class: "bubble-actions" },
          h("button", { type: "button", class: "react", "aria-pressed": String(m.rated === "up"), disabled: m.rated === "up", text: m.rated === "up" ? "Marked helpful" : "Helpful", onclick: () => react(m, true) }),
          h("button", { type: "button", class: "react", "aria-pressed": String(!!m.open), text: "Not quite…", onclick: () => react(m, false) })));
        if (m.open) b.append(feedbackWidget(ft, "Tell us what was wrong"));
      }
      scroller.append(b);
    }
    if (T.busy) scroller.append(h("div", { class: "bubble tutor", "aria-label": "Tutor is thinking" }, h("div", { class: "typing" }, h("span"), h("span"), h("span"))));
    if (!T.busy && T.parts && T.parts.chunkDone && !T.complete) scroller.append(partCard(T.parts));
    if (T.nudge && chatWaiting()) scroller.append(nudgeCard());
    if (T.complete && T.summary) {
      const sm = T.summary;
      const card = h("div", { class: "summary-card" }, h("h3", { text: T.parts ? "Topic learnt" : "Session complete" }),
        h("p", { class: "cheer-line", text: T.parts
          ? pick([`You've learnt the whole topic, ${firstName()}! Every part, one step at a time. That's real work.`,
            "Topic complete! You answered the big question piece by piece. That's how experts learn.",
            "That's the whole topic done. The quiz is your chance to show what you now know."], T.sessionId)
          : pick(["Well done for putting the time in today.", "Session done. Every one of these makes the next one easier.", "Nice work. Steady practice is what builds confidence."], T.sessionId) }),
        h("p", { class: "muted", text: T.parts ? `${T.parts.learnt} of ${T.parts.of} ideas learnt${sm.answered ? ` · ${sm.right} of ${sm.answered} answers right` : ""}`
          : `${sm.steps} of ${sm.of} steps done${sm.answered ? ` · ${sm.right} of ${sm.answered} answers right` : ""}` }));
      if (sm.up && sm.up.length) card.append(h("p", { class: "label", text: "Ideas that moved up" }), h("ul", null, ...sm.up.slice(0, 6).map((u) => h("li", { text: u.idea || u.atom }))));
      if (sm.down && sm.down.length) card.append(h("p", { class: "label", text: "Ideas to revisit" }), h("ul", null, ...sm.down.slice(0, 6).map((u) => h("li", { text: u.idea || u.atom }))));
      const acts = h("div", { class: "students" });
      const lastPart = T.parts && T.parts.chunkDone && T.parts.chunkDone.quizId && S.sets.get(T.parts.chunkDone.quizId);
      if (lastPart) acts.append(h("button", { class: "btn ghost", text: `Part quiz: ${T.parts.chunkDone.title} · ${lastPart.questions.length} Qs`, onclick: () => { endSession(); startTest(lastPart.id); } }));
      if (sm.next && sm.next.kind === "quiz" && S.sets.has(sm.next.id)) acts.append(h("button", { class: "btn accent", text: sm.next.label, onclick: () => { endSession(); startTest(sm.next.id); } }));
      if (sm.next && sm.next.kind === "learn") { const cid = T.chapterId; acts.append(h("button", { class: "btn accent", text: sm.next.label, onclick: () => { endSession(); tutorStart({ chapterId: cid, kind: "learn", topicId: sm.next.topicId, chunkId: sm.next.chunkId }); } })); }
      acts.append(h("button", { class: "btn ghost", text: "Back to the chapter", onclick: () => { endSession(); render(); } }));
      card.append(acts);
      scroller.append(card);
    }
    const ta = h("textarea", { id: "tutor-input", rows: "1", placeholder: T.busy ? "The tutor is thinking…" : "Type your answer or question (Enter to send, Shift+Enter for a new line)", "aria-label": "Your message", disabled: T.busy });
    ta.value = T.draft;
    const grow = () => { ta.style.height = "auto"; ta.style.height = Math.min(ta.scrollHeight, 180) + "px"; };
    ta.addEventListener("input", () => { T.draft = ta.value; T.lastTyped = Date.now(); if (T.nudge) { T.nudge = false; document.title = BASE_TITLE; } grow(); });
    ta.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); tutorSend(); } });
    const confRow = h("div", { class: "selfmark", role: "group", "aria-label": "How sure are you?" },
      h("span", { class: "hint", text: "How sure?" }),
      ...["guess", "think so", "sure"].map((c) => h("button", { type: "button", "aria-pressed": String(T.conf === c), text: c,
        onclick: () => { T.conf = T.conf === c ? null : c; T.draft = ta.value; render(); } })));
    const sessionFbKey = JSON.stringify({ targetType: "tutor_session", setId: T.setId, sessionId: T.sessionId });
    const shell = h("section", { class: "chat-shell" },
      h("div", { class: "chat-head" },
        h("div", { class: "title" },
          backLink("← Back", () => { const ro = T.readOnly; if (history.length > 1) history.back(); else { endSession(); render(); }
            if (!ro && T.msgs.length > 1) toast("Saved. Carry on any time from 💬 Chats."); }),
          h("span", { class: "label", text: `${(CHAPTERS_INFO(T.chapterId) || {}).subject || ""} · ${(CHAPTERS_INFO(T.chapterId) || {}).chapter || ""}` }), h("h2", { text: T.goal || "Starting…" })),
        T.sessionId ? h("button", { type: "button", class: "react", text: fbOpen.has(sessionFbKey) ? "Close feedback" : "Feedback on session",
          onclick: () => { fbOpen.has(sessionFbKey) ? fbOpen.delete(sessionFbKey) : fbOpen.add(sessionFbKey); render(); } }) : null),
      T.parts && T.parts.parts && !T.readOnly ? partsBar(T.parts) : null,
      T.plan.length && !(T.parts && T.complete) ? h("ol", { class: "steps", "aria-label": "Session steps" }, ...T.plan.map((p, i) =>
        h("li", { class: `step ${p.status !== "todo" ? "done" : i === T.step ? "now" : ""}`, "aria-current": i === T.step && !T.complete ? "step" : null },
          h("span", { class: "dot", text: p.status === "done" ? "✓" : p.status === "skipped" ? "–" : String(i + 1) }), h("span", { text: p.label })))) : null,
      T.sessionId && fbOpen.has(sessionFbKey) ? h("div", { class: "chat-head" }, feedbackWidget({ targetType: "tutor_session", setId: T.setId, sessionId: T.sessionId }, "Feedback on this session")) : null,
      scroller,
      T.readOnly ? h("div", { class: "chat-composer read-only" }, h("p", { class: "muted", text: T.complete ? "This chat is finished. You can read it here any time." : "You've learnt this part since this chat, so it's here to read." }),
        h("button", { class: "btn ghost", text: "← Back", onclick: () => { if (history.length > 1) history.back(); else { endSession(); render(); } } })) :
      h("div", { class: "chat-composer" },
        h("div", { class: "input-row" }, ta, h("button", { class: "btn accent", text: "Send", disabled: T.busy, onclick: tutorSend })),
        T.sessionId ? h("div", { class: "selfmark feel-row", role: "group", "aria-label": "How is this going?" },
          h("span", { class: "hint", text: "🙂 How's it going?" }),
          ...FEELINGS.map((f) => h("button", { type: "button", disabled: T.busy, class: T.feelArm === f.tag ? "armed" : null, text: T.feelArm === f.tag ? `${f.label.split(" ")[0]} Tap again to send` : f.label, onclick: () => feel(f) }))) : null,
        h("div", { class: "meta-row" }, confRow, h("span", { class: "hint", text: "Your parent can read these chats." }))));
    main.append(shell);
    requestAnimationFrame(() => {
      grow();
      if (T.stick || T.scrollPos == null) scroller.scrollTop = scroller.scrollHeight; else scroller.scrollTop = T.scrollPos;
      T.stick = false;
      scroller.addEventListener("scroll", () => {
        const nearBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 60;
        T.scrollPos = nearBottom ? null : scroller.scrollTop;
      }, { passive: true });
      if (!T.busy && !T.readOnly && document.activeElement === document.body && window.innerWidth > 720) ta.focus({ preventScroll: true });
    });
  }

  // ---------- parent area ----------
  const P = { chats: null, open: null };
  const papi = (path) => api(path);
  async function loadParent() {
    try {
      [P.chats, P.settings, P.costs] = await Promise.all([papi("api/parent/chats"), papi("api/settings"), papi("api/costs")]);
      P.err = "";
    }
    catch (e) { P.chats = []; toast(e.message); }
    render();
  }
  async function openChat(id) {
    if (P.open && P.open.id === id) { P.open = null; return render(); }
    try { P.open = await papi(`api/parent/chats/${encodeURIComponent(id)}`); } catch (e) { toast(e.message); }
    render();
  }
  function parentArea() {
    const sec = h("section", { class: "sheet" }, h("h2", { text: "Parent area" }));
    if (S.studentId !== "parent") { sec.append(h("p", { class: "muted", text: "Choose \"I'm the parent\" from the name list to read tutor chats and download results." })); return sec; }
    if (P.chats == null) { loadParent(); sec.append(h("p", { class: "muted", text: "Loading chats…" })); return sec; }
    sec.append(h("div", { class: "students" },
      h("a", { class: "btn ghost", href: `api/export/attempts.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "Attempts (CSV)" }),
      h("a", { class: "btn ghost", href: `api/export/answers.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "Every answer (CSV)" }),
      h("a", { class: "btn ghost", href: `api/export/atoms.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "Ideas by student (CSV)" }),
      h("a", { class: "btn ghost", href: `api/export/chats.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "All tutor chats (CSV)" }),
      h("a", { class: "btn ghost", href: `api/export/feedback.csv?t=${encodeURIComponent(store.get("sw.token") || "")}`, text: "All feedback (CSV)" })));

    // tutor model routing and running costs
    const modeLabels = { auto: "Auto (by question)", opus: "Always Opus 5.5", fable: "Always Fable 5.1" };
    const current = (P.settings && P.settings.tutorRouting) || "auto";
    sec.append(h("h3", { text: "Tutor model" }),
      h("p", { class: "muted", text: "Auto sends quick replies to Opus 5.5 at low effort and sends 'why' questions, multi-step working and replies after a wrong answer to Fable 5.1. Pick a fixed model to compare them." }),
      h("div", { class: "selfmark", role: "group", "aria-label": "Tutor model" }, ...Object.entries(modeLabels).map(([k, label]) =>
        h("button", { type: "button", "aria-pressed": String(current === k), text: label, onclick: async () => {
          try { P.settings = await api("api/settings", { method: "POST", body: JSON.stringify({ tutorRouting: k }) }); toast(`Tutor now uses: ${label}`); render(); }
          catch (e) { toast(e.message); }
        } }))));
    const bm = (P.costs && P.costs.byModel) || {};
    if (Object.keys(bm).length) {
      const t = h("table"); t.append(h("thead", null, h("tr", null, h("th", { text: "Model" }), h("th", { class: "num", text: "Replies" }),
        h("th", { class: "num", text: "Avg time" }), h("th", { class: "num", text: "Avg cost" }), h("th", { class: "num", text: "Total" }))));
      const tb = h("tbody");
      for (const v of Object.values(bm)) tb.append(h("tr", null, h("td", { text: v.label }), h("td", { class: "num", text: String(v.turns) }),
        h("td", { class: "num", text: `${v.avgSeconds}s` }), h("td", { class: "num", text: `$${v.avgCost.toFixed(3)}` }), h("td", { class: "num", text: `$${v.cost.toFixed(2)}` })));
      tb.append(h("tr", null, h("td", { text: "All tutor use" }), h("td"), h("td"), h("td"), h("td", { class: "num", text: `$${(P.costs.total || 0).toFixed(2)}` })));
      t.append(tb); sec.append(h("div", { class: "table-wrap" }, t));
    } else sec.append(h("p", { class: "hint", text: "Costs appear here after the first tutor session." }));

    sec.append(h("h3", { text: "Tutor chats" }));
    if (!P.chats.length) sec.append(h("p", { class: "muted", text: "No tutor chats yet." }));
    for (const c of P.chats) {
      const flags = c.flags || [];
      const row = h("button", { class: "set-card chat-row", onclick: () => openChat(c.id) },
        h("div", { class: "meta" }, h("strong", { text: c.student }), h("span", { text: `${c.subject} · ${c.chapter}` }), h("span", { text: c.mode === "practice" ? "practice" : "questions" }), h("span", { class: "mono", text: fmtDate(c.updated) })),
        h("div", { class: "meta" }, h("span", { text: `${c.messages} messages` }), h("span", { text: `${c.correct}/${c.attempts} answers right` }),
          h("span", { class: "mono", text: `$${(c.cost || 0).toFixed(2)}` }), h("span", { text: (c.models || []).join(" + ") }),
          ...flags.map((f) => h("span", { class: `pill ${f.kind === "distress" ? "bad" : "warn"}`, text: f.kind.replace("_", " ") }))));
      sec.append(row);
      if (P.open && P.open.id === c.id) {
        const log = h("div", { class: "chat log" });
        const sessFb = S.feedback.filter((f) => f.sessionId === c.id);
        if (sessFb.length) log.append(h("p", { class: "label", text: "Feedback on this session" }), feedbackList(sessFb, false));
        for (const f of P.open.flags || []) log.append(h("div", { class: `notice ${f.kind === "distress" ? "bad" : ""}` }, h("p", { text: `Flag (${f.kind.replace("_", " ")}): ${f.note}` })));
        for (const m of P.open.transcript) log.append(h("div", { class: `bubble ${m.role === "student" ? "me" : "tutor"}` },
          h("span", { class: "hint", text: `${m.role === "student" ? c.student : "Tutor"} · ${fmtDate(m.t)}${m.confidence ? " · " + m.confidence : ""}`
            + (m.model ? ` · ${m.model.includes("fable") ? "Fable 5.1" : m.model.includes("opus-5-5") ? "Opus 5.5" : m.model} ${m.effort || ""} · ${m.seconds}s · $${(m.cost || 0).toFixed(3)} · ${m.why || ""}` : "") }),
          h("p", { text: m.text })));
        sec.append(log);
      }
    }
    return sec;
  }
  function connectionNotice() {
    return h("div", { class: "notice bad" }, h("p", { text: "The results store isn't answering. Check the internet connection and reload the page." }));
  }

  function studentPicker(compact) {
    const wrap = h("section", { class: "sheet" });
    wrap.append(h("div", null, h("h2", { text: compact ? "Switch student" : "Who is practising?" }),
      h("p", { class: "muted", text: "Open a child's view to practise or look around as them, or go back to the parent view." })));
    const list = h("div", { class: "students" });
    const names = [...S.students.values()].sort((a, b) => (a.name || "").localeCompare(b.name || ""));
    if (!names.length) list.append(h("p", { class: "muted", text: "No students yet. Add the first name below." }));
    for (const s of names) {
      const subs = subjectsFor(s).map((x) => x.name);
      list.append(h("button", { class: "student", "aria-pressed": String(s.id === S.studentId),
        onclick: () => { S.studentId = s.id; store.set("sw.student", s.id); S.picking = false; S.subjectCode = null; S.chapterId = null; T.mastery = null; S.activity = null; render(); } },
        h("span", { text: s.name + (s.test ? " (test)" : "") }),
        subs.length ? h("span", { class: "hint", text: subs.length > 4 ? `${subs.slice(0, 4).join(", ")} +${subs.length - 4}` : subs.join(", ") }) : null));
    }
    list.append(h("button", { class: "student parent", "aria-pressed": String(S.studentId === "parent"), text: S.me && S.me.role === "admin" ? "Admin and parent view" : "Parent view",
      onclick: () => { S.studentId = "parent"; store.set("sw.student", "parent"); S.picking = false; S.view = "bank"; render(); } }));
    wrap.append(list);
    wrap.append(h("div", { class: "students" },
      h("button", { class: "btn ghost", text: "My account", onclick: () => { S.picking = false; S.view = "account"; render(); } }),
      h("button", { class: "btn ghost", text: "Log out", onclick: () => signOut("Logged out") })));
    return wrap;
  }

  function chapterIds() {
    const ids = new Set(Object.keys(S.topics || {}));
    for (const x of S.sets.values()) ids.add(x.chapterId || x.id);
    return [...ids].sort((a, b) => ((CHAPTERS_INFO(a) || {}).subject || "").localeCompare((CHAPTERS_INFO(b) || {}).subject || "") || a.localeCompare(b));
  }
  function quizzesOf(cid) { return [...S.sets.values()].filter((x) => (x.chapterId || x.id) === cid && x.active !== false && x.kind !== "chunk").sort((a, b) => (a.order || 0) - (b.order || 0)); }
  function partStatus(cid, chunkId) { const c = (T.mastery && T.mastery.chunks) || {}; return (c[`${cid}/${chunkId}`] || {}).status || "todo"; }
  // Where to learn the ideas a student marked "not learnt yet": the earliest part (or topic) that teaches any of them.
  function learnTargetFor(cid, atomIds) {
    const tdoc = (S.topics || {})[cid]; if (!tdoc || !atomIds.length) return null;
    const want = new Set(atomIds);
    for (const t of tdoc.topics) {
      for (const c of t.chunks || []) if ((c.atom_ids || []).some((a) => want.has(a))) return { chapterId: cid, kind: "learn", topicId: t.id, chunkId: c.id, label: c.title };
      if (!(t.chunks || []).length && (t.atom_ids || []).some((a) => want.has(a))) return { chapterId: cid, kind: "learn", topicId: t.id, label: t.title };
    }
    return null;
  }
  function bestOf(studentId, quizId) {
    const xs = attemptsFor(studentId, quizId); if (!xs.length) return null;
    return xs.reduce((m, a) => (pct(a.score, a.max) > pct(m.score, m.max) ? a : m));
  }
  function learnedTopics(cid) {
    const act = (S.activity && S.activity[S.studentId]) || { sessions: [] };
    const out = new Set(act.sessions.filter((x) => x.chapterId === cid && x.kind === "learn" && x.complete).map((x) => x.topicId));
    for (const t of ((S.topics || {})[cid] || {}).topics || []) {   // a topic in parts is learnt only when every part is
      if ((t.chunks || []).length) { if (t.chunks.every((c) => partStatus(cid, c.id) === "learned")) out.add(t.id); else out.delete(t.id); }
    }
    return out;
  }
  function renderPractise(main) {
    const st = S.studentId && S.students.get(S.studentId);
    if (!st || S.picking) { main.append(studentPicker(!!st)); if (!st) return; }
    if (!T.mastery && !T.loadingM) loadMastery();
    if (!S.activity && !S.loadingActivity) {
      S.loadingActivity = true;
      api("api/activity").then((a) => { S.activity = a; }).catch(() => { S.activity = {}; }).finally(() => { S.loadingActivity = false; if (["practise", "progress"].includes(S.view)) render(); });
    }
    if (S.chapterId && chapterIds().includes(S.chapterId)) return renderChapter(main, st);
    const subj = S.subjectCode && catSubjects().find((x) => x.code === S.subjectCode);
    if (subj) return renderSubject(main, st, subj);
    if (S.place === "subjects") return renderSubjectList(main, st);
    renderHome(main, st);
  }

  // ---------- catalogue: board → subject → syllabus unit → chapter (data/catalog.json) ----------
  function catSubjects() { return (S.catalog && S.catalog.subjects) || []; }
  function boardName(id) { const b = ((S.catalog && S.catalog.boards) || []).find((x) => x.id === id); return b ? b.name : ""; }
  function boardLine(subjects) { return [...new Set(subjects.map((s) => boardName(s.board)))].filter(Boolean).join(" · "); }
  function hasContent(cid) { return !!((S.topics || {})[cid] || quizzesOf(cid).length); }
  // A subject's units with their published chapters; chapters the catalogue doesn't place yet go last.
  function unitsOf(subj) {
    const placed = new Set(subj.units.flatMap((u) => u.chapters.map((c) => c.id)));
    const units = subj.units.map((u) => ({ ...u, chapters: u.chapters.filter((c) => hasContent(c.id)) })).filter((u) => u.chapters.length);
    const extra = chapterIds().filter((cid) => !placed.has(cid) && (CHAPTERS_INFO(cid) || {}).code === subj.code).map((id) => ({ id }));
    if (extra.length) units.push({ num: "", title: "More chapters", chapters: extra });
    return units;
  }
  function chapterEntry(cid) {
    for (const s of catSubjects()) for (const u of s.units) for (const c of u.chapters) if (c.id === cid) return { subject: s, unit: u, ch: c };
    const s = catSubjects().find((x) => x.code === (CHAPTERS_INFO(cid) || {}).code);
    return s ? { subject: s, unit: null, ch: { id: cid } } : null;
  }
  // The subjects a child sees. Not set up yet: every IGCSE subject that has chapters (the old behaviour).
  function subjectsFor(st) {
    const all = catSubjects();
    if (st && Array.isArray(st.subjects)) return all.filter((s) => st.subjects.includes(s.code));
    return all.filter((s) => s.board === "igcse" && unitsOf(s).length);
  }
  function chapterTitle(cid) { return (CHAPTERS_INFO(cid) || {}).chapter || cid; }
  function openChapter(cid) {
    const e = chapterEntry(cid); if (e) S.subjectCode = e.subject.code;
    S.chapterId = cid; S.view = "practise"; S.run = null; render(); window.scrollTo(0, 0);
  }
  // How far a child is through a chapter: parts learnt if it has parts, else topics learnt, else quizzes done.
  function chapterProgress(cid, sid) {
    const tdoc = (S.topics || {})[cid];
    const parts = tdoc ? tdoc.topics.flatMap((t) => (t.chunks || []).map((c) => c.id)) : [];
    const qz = quizzesOf(cid); const quizDone = qz.filter((z) => bestOf(sid, z.id)).length;
    let done, of, unit;
    if (parts.length) { done = parts.filter((p) => partStatus(cid, p) === "learned").length; of = parts.length; unit = "parts"; }
    else if (tdoc) { const L = learnedTopics(cid); done = tdoc.topics.filter((t) => L.has(t.id)).length; of = tdoc.topics.length; unit = "topics"; }
    else { done = quizDone; of = qz.length; unit = "quizzes"; }
    const ms = T.mastery && T.mastery.chapters && T.mastery.chapters[cid];
    const touched = done > 0 || quizDone > 0 || !!(ms && ms.seen);
    return { done, of, unit, quizDone, quizzes: qz.length, ms, state: of && done >= of ? "done" : touched ? "doing" : "new" };
  }
  // The next thing to learn in a chapter: its first part (or topic) not learnt yet.
  function nextInChapter(cid) {
    const tdoc = (S.topics || {})[cid]; if (!tdoc) return null;
    const learned = learnedTopics(cid);
    for (const t of tdoc.topics) {
      const chunks = t.chunks || [];
      if (chunks.length) {
        const c = chunks.find((x) => partStatus(cid, x.id) !== "learned");
        if (c) return { chapterId: cid, topicId: t.id, chunkId: c.id, title: c.title, topic: t.title, question: c.question };
      } else if (!learned.has(t.id)) return { chapterId: cid, topicId: t.id, title: t.title, topic: t.title, question: t.goal };
    }
    return null;
  }
  // Carry on from the last Learn session; otherwise the first chapter in progress; otherwise the first not done.
  function carryOnTarget(st, subjects) {
    const order = subjects.flatMap((s) => unitsOf(s).flatMap((u) => u.chapters.map((c) => c.id)));
    const act = (S.activity && S.activity[st.id]) || { sessions: [] };
    const last = act.sessions.find((x) => x.kind === "learn" && order.includes(x.chapterId));
    if (last) { const n = nextInChapter(last.chapterId); if (n) return { ...n, resume: true }; }
    for (const want of ["doing", "new"]) for (const cid of order) {
      if (chapterProgress(cid, st.id).state !== want) continue;
      const n = nextInChapter(cid); if (n) return { ...n, resume: want === "doing" };
    }
    return null;
  }
  function backLink(text, fn) { return h("button", { type: "button", class: "fb-toggle back-link", text, onclick: fn }); }
  function renderHome(main, st) {
    const subjects = subjectsFor(st);
    main.append(h("section", { class: "home-hello" }, h("h2", { text: `Hello ${st.name}` }),
      h("p", { class: "muted", text: subjects.length ? `${boardLine(subjects)} · ${subjects.map((s) => s.name).join(", ")}` : "No subjects chosen yet." })));
    const nc = notesCard(st.id); if (nc) main.append(nc);
    const rc = remindersCard(false); if (rc) main.append(rc);
    const row = h("div", { class: "home-row" });
    const next = carryOnTarget(st, subjects);
    if (next) {
      const e = chapterEntry(next.chapterId);
      row.append(h("section", { class: "sheet next-card" },
        h("p", { class: "label", text: next.resume ? "Carry on" : "Start here" }),
        h("h3", { text: next.title }),
        h("p", { class: "muted", text: [e && e.subject.name, chapterTitle(next.chapterId), next.topic !== next.title ? next.topic : ""].filter(Boolean).join(" · ") }),
        next.question && next.question !== next.title ? h("p", { class: "q-line", text: next.question }) : null,
        h("div", { class: "topic-actions" },
          S.tutorOn ? h("button", { class: "btn accent", text: next.chunkId ? "Learn this part" : "Learn this topic",
            onclick: () => tutorStart({ chapterId: next.chapterId, kind: "learn", topicId: next.topicId, chunkId: next.chunkId }) }) : null,
          h("button", { class: "btn ghost", text: "Open the chapter", onclick: () => openChapter(next.chapterId) }))));
    }
    const due = [];
    for (const s of subjects) for (const u of unitsOf(s)) for (const c of u.chapters) {
      const ms = T.mastery && T.mastery.chapters && T.mastery.chapters[c.id];
      if (ms && ms.due) due.push({ cid: c.id, n: ms.due, subject: s.name });
    }
    if (due.length && S.tutorOn) {
      due.sort((a, b) => b.n - a.n); const top = due[0];
      row.append(h("section", { class: "sheet" },
        h("p", { class: "label", text: "🔁 Quick review" }),
        h("h3", { text: `${top.subject} · ${chapterTitle(top.cid)}` }),
        h("p", { class: "muted", text: "A few quick questions on ideas you met a while ago, so they don't fade. About 5 minutes." }),
        h("div", { class: "topic-actions" }, h("button", { class: "btn ghost", text: "Start a quick review", onclick: () => tutorStart({ chapterId: top.cid, kind: "review" }) })),
        due.length > 1 ? h("details", { class: "more" }, h("summary", { text: `Other chapters to review (${due.length - 1})` }),
          h("div", { class: "due-list" }, ...due.slice(1, 8).map((d) => h("button", { class: "react", text: `${d.subject} · ${chapterTitle(d.cid)}`,
            onclick: () => tutorStart({ chapterId: d.cid, kind: "review" }) })))) : null));
    }
    const wk0 = weekSummary(st.id); const ws = kidWeek(st.id);
    const wk = ws ? { minutes: ws.minutes, quizzes: ws.quizzes, best: ws.best, parts: ws.partsLearnt } : wk0;
    row.append(h("section", { class: "sheet week" }, h("p", { class: "label", text: "📅 This week" }),
      h("div", { class: "week-stats" },
        h("div", null, h("strong", { text: String(wk.minutes) }), h("span", { class: "hint", text: "minutes (about)" })),
        h("div", null, h("strong", { text: String(wk.quizzes) }), h("span", { class: "hint", text: wk.quizzes === 1 ? "quiz" : "quizzes" })),
        h("div", null, h("strong", { text: wk.best !== null ? `${wk.best}%` : "–" }), h("span", { class: "hint", text: "best score" })),
        h("div", null, h("strong", { text: String(wk.parts) }), h("span", { class: "hint", text: wk.parts === 1 ? "part learnt" : "parts learnt" })))));
    const open = S.tutorOn ? myChats(null).filter((c) => !c.complete && !c.atPartLearnt).slice(0, 2) : [];
    if (open.length) row.append(h("section", { class: "sheet" }, h("p", { class: "label", text: "💬 Chats you can carry on" }),
      h("ul", { class: "chat-list" }, ...open.map((c) => chatRow(c, true)))));
    if (row.children.length) main.append(row);
    main.append(h("div", { class: "students" }, h("button", { class: "btn ghost", text: "📚 See all your subjects", onclick: () => goPlace("subjects") })));
  }
  // Monday-to-now totals for the Today card
  function weekSummary(sid) {
    const d = new Date(); const day = (d.getDay() + 6) % 7; d.setHours(0, 0, 0, 0); d.setDate(d.getDate() - day);
    const since = d.toISOString();
    const qs = S.attempts.filter((a) => a.studentId === sid && a.submittedAt >= since);
    const sess = ((S.activity && S.activity[sid]) || { sessions: [] }).sessions.filter((x) => x.updated >= since);
    const chunks = (T.mastery && T.mastery.chunks) || {};
    return { quizzes: qs.length, best: qs.length ? Math.max(...qs.map((a) => pct(a.score, a.max))) : null,
      minutes: sess.reduce((t, x) => t + Math.min(45, x.minutes || 0), 0) + Math.round(qs.reduce((t, a) => t + Math.min(1800, a.durationSec || 0), 0) / 60),   // a chat or quiz left open counts at most 45 / 30 min
      parts: Object.values(chunks).filter((c) => c.status === "learned" && c.at >= since).length };
  }
  function renderSubjectList(main, st) {
    const subjects = subjectsFor(st);
    const grid = h("div", { class: "subject-grid" }, ...subjects.map((s) => subjectCard(s, st)));
    main.append(h("section", { class: "home-subjects" }, h("h2", { class: "section-title", text: "📚 Your subjects" }),
      subjects.length ? grid : h("div", { class: "sheet" }, h("p", { class: "muted", text: "No subjects yet. Ask a parent or the admin to add you to a class." }))));
  }
  function subjectCard(s, st) {
    const units = unitsOf(s); const style = `--subj: hsl(${s.hue || 220} 55% 45%)`;
    const top = h("div", { class: "subject-top" }, h("span", { class: "subj-mark", "aria-hidden": "true", text: s.mark || s.name[0] }),
      h("div", null, h("h3", { text: s.name }), h("span", { class: "code", text: `${boardName(s.board)} · ${s.code}` })));
    if (!units.length) return h("div", { class: "subject-card soon", style }, top, h("p", { class: "muted", text: "Chapters are being written. They'll appear here when they're ready." }));
    const byL = [0, 0, 0, 0, 0]; let atoms = 0, chapters = 0, started = 0, done = 0;
    for (const u of units) for (const c of u.chapters) {
      const p = chapterProgress(c.id, st.id); chapters++;
      if (p.state !== "new") started++; if (p.state === "done") done++;
      if (p.ms) { p.ms.byLevel.forEach((n, i) => { byL[i] += n; }); atoms += p.ms.atoms; }
    }
    const solid = byL[2] + byL[3] + byL[4];
    return h("button", { class: "subject-card", style, onclick: () => { S.subjectCode = s.code; S.chapterId = null; render(); window.scrollTo(0, 0); } },
      top,
      h("div", { class: "meta" }, h("span", { text: `${units.length} unit${units.length > 1 ? "s" : ""} · ${chapters} chapter${chapters > 1 ? "s" : ""}` }),
        h("span", { text: done ? `${done} done · ${started - done} in progress` : started ? `${started} in progress` : "Not started" })),
      levelBar(byL, atoms),
      h("span", { class: "hint", text: atoms ? `${solid} of ${atoms} ideas solid` : "" }));
  }
  function renderSubject(main, st, s) {
    main.append(h("section", { class: "sheet" },
      h("div", null, backLink("← Subjects", () => { S.subjectCode = null; S.place = "subjects"; render(); window.scrollTo(0, 0); }),
        h("span", { class: "label", text: `${boardName(s.board)} · ${s.code}` }), h("h2", { text: s.name })),
      h("p", { class: "muted", text: "Chapters grouped by syllabus unit. “Best after” means a chapter builds on an earlier one; you can still open any chapter." })));
    const units = unitsOf(s);
    if (!units.length) { main.append(h("section", { class: "sheet" }, h("p", { class: "muted", text: "Chapters for this subject are being written. They'll appear here as soon as they're ready." }))); return; }
    for (const u of units) {
      main.append(h("section", { class: "sheet unit" },
        h("div", { class: "unit-head" }, u.num ? h("span", { class: "unit-num", text: `Unit ${u.num}` }) : null, h("h3", { text: u.title })),
        h("ol", { class: "ch-path" }, ...u.chapters.map((c) => chapterStop(c, st)))));
    }
  }
  function chapterStop(c, st) {
    const p = chapterProgress(c.id, st.id);
    const before = (c.buildsOn || []).filter((b) => hasContent(b) && chapterProgress(b, st.id).state !== "done");
    const [cls, label] = p.state === "done" ? ["good", "Done"] : p.state === "doing" ? ["warn", "In progress"]
      : before.length ? ["", `Best after: ${before.map(chapterTitle).join(", ")}`] : ["accent", "Ready to start"];
    const where = [c.ref ? `Syllabus ${c.ref}` : "", c.book ? `Book ${c.book}` : ""].filter(Boolean).join(" · ");
    return h("li", { class: `ch-stop ${p.state}` },
      h("span", { class: "ch-dot", "aria-hidden": "true", text: p.state === "done" ? "✓" : "" }),
      h("button", { class: "ch-card", onclick: () => openChapter(c.id) },
        h("div", { class: "ch-top" }, h("span", { class: "code", text: where }), h("span", { class: `pill ${cls}`, text: label })),
        h("h3", { text: chapterTitle(c.id) }),
        h("div", { class: "meta" },
          p.of ? h("span", { text: `${p.done} of ${p.of} ${p.unit} learnt` }) : null,
          p.quizzes && p.unit !== "quizzes" ? h("span", { text: `${p.quizDone} of ${p.quizzes} quizzes done` }) : null,
          p.ms && p.ms.due ? h("span", { class: "pill warn", text: `${p.ms.due} to review` }) : null),
        p.ms ? levelBar(p.ms.byLevel, p.ms.atoms) : null));
  }
  function chapterLinks(cid) {
    const e = chapterEntry(cid); if (!e) return null;
    const before = (e.ch.buildsOn || []).filter(hasContent);
    const after = catSubjects().flatMap((s) => s.units.flatMap((u) => u.chapters)).filter((c) => (c.buildsOn || []).includes(cid) && hasContent(c.id)).map((c) => c.id);
    if (!before.length && !after.length) return null;
    const chip = (x) => h("button", { class: "react", text: chapterTitle(x), onclick: () => openChapter(x) });
    return h("div", { class: "ch-links" },
      before.length ? h("span", { class: "hint", text: "Builds on" }) : null, ...before.map(chip),
      after.length ? h("span", { class: "hint", text: before.length ? " · Leads to" : "Leads to" }) : null, ...after.map(chip));
  }
  function renderChapter(main, st) {
    const cid = S.chapterId; const info = CHAPTERS_INFO(cid) || {}; const tdoc = (S.topics || {})[cid];
    const ms = T.mastery && T.mastery.chapters && T.mastery.chapters[cid]; const lv = (T.mastery && T.mastery.levels) || {};
    const ent = chapterEntry(cid);
    const where = ent ? [ent.subject.name, ent.unit && ent.unit.num ? `Unit ${ent.unit.num}` : "", ent.ch.ref ? `Syllabus ${ent.ch.ref}` : "", ent.ch.book ? `Book ${ent.ch.book}` : ""].filter(Boolean).join(" · ")
      : `${info.subject || ""} · ${info.code || ""}`;
    const head = h("section", { class: "sheet" },
      h("div", { class: "test-bar" },
        h("div", null, backLink(ent ? `← ${ent.subject.name}` : "← Home", () => { S.chapterId = null; if (ent) S.subjectCode = ent.subject.code; render(); }),
          h("span", { class: "label", text: where }), h("h2", { text: info.chapter || cid })),
        S.tutorOn && ms && (ms.due || ms.seen) ? h("button", { class: "btn ghost", text: ms.due ? `Review ${ms.due} due idea${ms.due > 1 ? "s" : ""} with the tutor` : "Quick review with the tutor",
          onclick: () => tutorStart({ chapterId: cid, kind: "review" }) }) : null),
      chapterLinks(cid),
      ms ? levelBar(ms.byLevel, ms.atoms) : null,
      ms ? h("details", { class: "more" }, h("summary", { text: "What do the colours mean?" }),
        h("div", { class: "legend" }, ...[0, 1, 2, 3, 4].map((i) => h("span", null, h("span", { class: `lv-dot lv${i}` }), ["not met", "recall", "apply", "combine", "exam-ready"][i])))) : null);
    main.append(head);
    if (S.tutorOn) {
      const list = myChats(cid);
      if (list.length) {
        const open = list.find((c) => !c.complete && !c.atPartLearnt);
        main.append(h("section", { class: "sheet chat-strip" },
          h("span", { text: `💬 ${list.length} chat${list.length > 1 ? "s" : ""} in this chapter` }),
          open ? h("button", { class: "btn accent small", text: `Carry on: ${open.atPart || open.title}`, onclick: () => reopenChat(open.id) }) : null,
          h("button", { class: "react", text: "See this chapter's chats", onclick: () => { S.chatFilter = cid; goPlace("chats"); } })));
      }
    }
    if (!tdoc) {   // chapter not split into topics yet: list its quizzes
      const list = h("section", { class: "sheet" }, h("p", { class: "muted", text: "Topics for this chapter are on their way. For now, here is its quiz." }));
      for (const z of quizzesOf(cid)) list.append(quizButton(st, z));
      main.append(list); return;
    }
    const learned = learnedTopics(cid);
    const path = h("ol", { class: "topic-path" });
    const topicDone = (t) => learned.has(t.id) || ((t.chunks || []).length && (t.chunks || []).every((c) => partStatus(cid, c.id) === "learned"));
    const current = tdoc.topics.find((t) => !topicDone(t)) || tdoc.topics.find((t) => { const q = S.sets.get(t.quizId); return q && !bestOf(st.id, q.id); });
    S.openTopics = S.openTopics || new Set();
    tdoc.topics.forEach((t, i) => {
      const quiz = S.sets.get(t.quizId); const best = quiz && bestOf(st.id, quiz.id);
      const ids = t.atom_ids || []; const byL = [0, 0, 0, 0, 0]; ids.forEach((a) => { byL[Math.min(4, lv[a] || 0)]++; });
      const chunks = t.chunks || [];
      const nLearnt = chunks.filter((c) => partStatus(cid, c.id) === "learned").length;
      const nextPart = chunks.find((c) => partStatus(cid, c.id) !== "learned");
      const isDone = topicDone(t);
      const resume = S.tutorOn && !isDone ? resumableChat(cid, t.id) : null;
      const status = isDone ? `✓ learnt${best ? ` · quiz ${pct(best.score, best.max)}%` : quiz ? " · quiz not taken yet" : ""}`
        : chunks.length ? (nLearnt ? `${nLearnt} of ${chunks.length} parts learnt` : `${chunks.length} parts`) : "Not started";
      let partsEl = null;
      if (chunks.length) {
        partsEl = h("ol", { class: "parts-list", "aria-label": `Parts of ${t.title}` }, ...chunks.map((c, j) => {
          const stt = partStatus(cid, c.id); const pq = S.sets.get(c.quizId); const pb = pq && bestOf(st.id, pq.id);
          const isNext = nextPart && c.id === nextPart.id;
          const act = stt === "learned"
            ? (pq ? h("button", { class: "react", text: pb ? `Part quiz · best ${pct(pb.score, pb.max)}%` : `Part quiz · ${pq.questions.length} Qs`, onclick: () => startTest(pq.id) }) : null)
            : S.tutorOn ? h("button", { class: "react", text: "Learn this part", onclick: () => tutorStart({ chapterId: cid, kind: "learn", topicId: t.id, chunkId: c.id }) }) : null;
          return h("li", { class: `${stt}${isNext ? " next" : ""}` },
            h("span", { class: "pnum", text: stt === "learned" ? "✓" : stt === "skipped" ? "–" : String(j + 1) }),
            h("div", { class: "pbody" }, h("strong", { text: c.title }), isNext ? h("span", { class: "hint", text: c.question }) : null,
              h("div", { class: "topic-actions" }, act)));
        }));
      }
      // one main action, one quiz button, everything else under "More"
      const main1 = S.tutorOn && !isDone ? h("button", { class: "btn accent", text: resume ? `Carry on your chat: ${resume.atPart}` : nextPart && nLearnt ? `Continue: ${nextPart.title}` : "Learn with the tutor",
        onclick: () => (resume ? reopenChat(resume.id) : tutorStart({ chapterId: cid, kind: "learn", topicId: t.id })) }) : null;
      const quizBtn = quiz ? h("button", { class: isDone && !best ? "btn accent" : "btn ghost", text: best ? `Quiz again · best ${pct(best.score, best.max)}%` : `Take the ${chunks.length ? "topic " : ""}quiz · ${quiz.questions.length} Qs`,
        onclick: () => startTest(quiz.id) }) : null;
      const more = [
        S.tutorOn && isDone ? h("button", { class: "react", text: "Learn again", onclick: () => tutorStart({ chapterId: cid, kind: "learn", topicId: t.id }) }) : null,
        S.tutorOn ? h("button", { class: "react", text: "Ask the tutor a question", onclick: () => tutorStart({ chapterId: cid, kind: "ask", topicId: t.id }) }) : null,
        t.visualQuizId && S.sets.get(t.visualQuizId) ? (() => { const vz = S.sets.get(t.visualQuizId); const vb = bestOf(st.id, vz.id);
          return h("button", { class: "react", text: vb ? `Diagram quiz · best ${pct(vb.score, vb.max)}%` : `Diagram quiz · ${vz.questions.length} Qs`, onclick: () => startTest(vz.id) }); })() : null,
        t.visual ? h("button", { class: "react", "aria-expanded": String(S.explore === `${cid}/${t.id}`), text: S.explore === `${cid}/${t.id}` ? "Hide the diagram" : "Explore the diagram",
          onclick: () => { S.explore = S.explore === `${cid}/${t.id}` ? null : `${cid}/${t.id}`; S.openTopics.add(`${cid}/${t.id}`); render(); } }) : null].filter(Boolean);
      const moreEl = more.length ? h("details", { class: "more" }, h("summary", { text: "More" }), h("div", { class: "topic-actions" }, ...more)) : null;
      const key = `${cid}/${t.id}`;
      const det = h("details", { class: "topic-fold" },
        h("summary", null, h("span", { class: "topic-num", text: isDone ? "✓" : String(i + 1) }),
          h("span", { class: "topic-sum" }, h("strong", { text: t.title }), h("span", { class: "hint", text: status }))),
        h("div", { class: "topic-body" },
          h("p", { class: "muted", text: t.goal }), levelBar(byL, ids.length),
          partsEl,
          h("div", { class: "topic-actions" }, main1, quizBtn), moreEl,
          t.visual && S.explore === key ? explorerEl(t.visual, key) : null));
      det.open = S.openTopics.has(key) || (!S.closedTopics || !S.closedTopics.has(key)) && current && current.id === t.id;
      // remember the choice the moment it's tapped, so a redraw straight after can't undo it
      det.querySelector("summary").addEventListener("click", () => { S.closedTopics = S.closedTopics || new Set();
        if (!det.open) { S.openTopics.add(key); S.closedTopics.delete(key); } else { S.openTopics.delete(key); S.closedTopics.add(key); } });
      path.append(h("li", { class: `topic ${isDone ? "done" : ""}${current && current.id === t.id ? " current" : ""}` }, det));
    });
    const mixed = S.sets.get(tdoc.mixedQuizId);
    if (mixed) {
      const best = bestOf(st.id, mixed.id);
      path.append(h("li", { class: `topic final ${best ? "done" : ""}` }, h("div", { class: "topic-num", text: best ? "✓" : "★" }),
        h("div", { class: "topic-body" }, h("h3", { text: mixed.title }), h("p", { class: "muted", text: mixed.intro || "A mixed review across the whole chapter." }),
          h("div", { class: "topic-actions" }, h("button", { class: "btn ghost", text: best ? `Again · best ${pct(best.score, best.max)}%` : `Take the review · ${mixed.questions.length} Qs`, onclick: () => startTest(mixed.id) })))));
    }
    main.append(h("section", { class: "sheet" }, path));
  }
  function quizButton(st, z) {
    const best = bestOf(st.id, z.id); const marks = (z.questions || []).reduce((t, q) => t + (Number(q.marks) || 1), 0);
    return h("button", { class: "set-card", onclick: () => startTest(z.id) }, h("h3", { text: z.title || z.chapter }),
      h("div", { class: "meta" }, h("span", { text: `${(z.questions || []).length} questions` }), h("span", { text: `${marks} marks` }), h("span", { text: `${z.minutes || 10} min` })),
      best ? h("span", { class: `pill ${band(pct(best.score, best.max))}`, text: `Best ${pct(best.score, best.max)}%` }) : h("span", { class: "pill", text: "Not tried yet" }));
  }

  // Diagrams come from static/visuals (an ES module loaded beside this script); until it arrives, show a placeholder.
  function figureEl(fig, reveal) {
    if (window.StepVis) return window.StepVis.renderFigure(fig, { reveal }) || h("span");
    const ph = h("p", { class: "muted", text: "Loading the diagram…" });
    document.addEventListener("stepvis", () => ph.replaceWith(window.StepVis.renderFigure(fig, { reveal }) || h("span")), { once: true });
    return ph;
  }
  const exploreSeeds = {};
  function explorerEl(v, key) {
    const wrap = h("div", { class: "explore" });
    const scen = v.scenarios || [v.scenario];
    const build = () => {
      if (!window.StepVis) { wrap.replaceChildren(h("p", { class: "muted", text: "Loading the diagram…" })); document.addEventListener("stepvis", build, { once: true }); return; }
      const seed = exploreSeeds[key] || 1; const sc = scen[(seed - 1) % scen.length];
      const inst = window.StepVis.sampleFor(v.cls, sc, seed * 7919);
      wrap.replaceChildren(inst ? window.StepVis.explorer(v.cls, inst) : h("p", { class: "muted", text: "No example could be made." }),
        h("button", { class: "react", type: "button", text: "Try a new example", onclick: () => { exploreSeeds[key] = seed + 1; build(); } }));
    };
    build(); return wrap;
  }
  function questionBody(q, idx, mode) {
    const r = S.run; const resp = r.responses[q.id]; const res = r.results && r.results[q.id];
    const body = h("div", { class: "body" });
    body.append(h("p", { class: "prompt", text: q.prompt || "" }));
    if (q.figure) body.append(figureEl(q.figure, mode === "review"));
    const name = `q-${q.id}`;
    if (q.type === "mcq" || q.type === "multi") {
      if (q.type === "multi") body.append(h("p", { class: "select-n", text: `Select ${(q.answer || []).length}` }));
      const opts = h("div", { class: "opts", role: q.type === "mcq" ? "radiogroup" : "group" });
      (q.options || []).forEach((opt, i) => {
        const checked = q.type === "mcq" ? Number(resp) === i && resp != null : (resp || []).map(Number).includes(i);
        const input = h("input", { type: q.type === "mcq" ? "radio" : "checkbox", name, id: `${name}-${i}`, value: String(i), disabled: mode !== "test" });
        input.checked = checked;
        input.addEventListener("change", () => {
          r.notLearnt.delete(q.id);
          if (q.type === "mcq") r.responses[q.id] = i;
          else {
            const cur = new Set((r.responses[q.id] || []).map(Number)); const n = (q.answer || []).length;
            if (input.checked && cur.size >= n) toast(`This question asks for ${n}. Ticking more than ${n} scores 0, so untick one first if you change your mind.`);
            input.checked ? cur.add(i) : cur.delete(i); r.responses[q.id] = [...cur].sort();
          }
          saveDraft(); updateDock(); updateNav();
        });
        let cls = "opt";
        if (mode === "review") {
          const isAns = q.type === "mcq" ? Number(q.answer) === i : (q.answer || []).map(Number).includes(i);
          if (isAns) cls += " right"; else if (checked) cls += " wrong";
        }
        opts.append(h("label", { class: cls, for: `${name}-${i}` }, input, h("span", null, h("span", { class: "mono muted", text: String.fromCharCode(65 + i) + "  " }), opt)));
      });
      body.append(opts);
    } else if (q.type === "numeric") {
      const input = h("input", { type: "text", inputmode: "decimal", id: name, autocomplete: "off", disabled: mode !== "test", "aria-label": `Answer to question ${idx + 1}` });
      input.value = resp == null ? "" : String(resp);
      input.addEventListener("input", () => { r.responses[q.id] = input.value; r.notLearnt.delete(q.id); saveDraft(); updateDock(); updateNav(); });
      body.append(h("div", { class: "numeric" }, input, q.unit ? h("span", { class: "mono", text: q.unit }) : null));
      if (mode === "test") body.append(h("p", { class: "hint", text: "Numbers only. Standard form can be typed as 6.02 x 10^23." }));
    } else {
      const ta = h("textarea", { id: name, disabled: mode !== "test", "aria-label": `Answer to question ${idx + 1}` });
      ta.value = resp == null ? "" : String(resp);
      ta.addEventListener("input", () => { r.responses[q.id] = ta.value; r.notLearnt.delete(q.id); saveDraft(); updateDock(); updateNav(); });
      body.append(ta);
    }
    if (mode === "test") {
      const on = r.notLearnt.has(q.id);
      body.append(h("button", { type: "button", class: "react notlearnt-btn", "aria-pressed": String(on),
        text: on ? "Marked: I haven't learnt this yet (tap to undo)" : "I haven't learnt this yet",
        onclick: () => { if (on) r.notLearnt.delete(q.id); else { r.notLearnt.add(q.id); delete r.responses[q.id]; } saveDraft(); render(); } }));
      if (on) body.append(h("p", { class: "hint", text: "That's fine. It scores 0 but isn't counted as a mistake, and after the quiz you can learn it with the tutor." }));
    }
    if (mode === "review") body.append(reviewBlock(q, res), questionFlags(S.run.setId, q),
      feedbackWidget({ targetType: "question", setId: S.run.setId, questionId: q.id }, "Something's wrong with this question"));
    return body;
  }
  function reviewBlock(q, res) {
    const r = S.run; const box = h("div", { class: "scheme" });
    if (res.notLearnt) {
      box.append(h("div", { class: "verdict" }, h("span", { class: "pill", text: `0/${res.max}` }),
        h("span", { text: "Not learnt yet: not counted as a mistake. Learn it with the tutor, then try again." })));
    } else if (res.auto) {
      const v = h("div", { class: "verdict" },
        h("span", { class: `pill ${res.right ? "good" : res.got > 0 ? "warn" : "bad"}`, text: `${res.got}/${res.max}` }),
        h("span", { text: res.right ? "Correct" : res.got > 0 ? "Partly correct" : res.over ? `Not correct: more than ${(q.answer || []).length} options were selected` : "Not correct" }));
      box.append(v);
      if (q.type === "numeric") {
        const sfText = (x, n) => { const t = Number(x).toPrecision(n); return t.includes("e") ? String(Number(t)) : t; };
        const shown = q.sf != null ? sfText(q.answer, q.sf) : q.dp != null ? Number(q.answer).toFixed(q.dp) : fmtNum(Number(q.answer));
        box.append(h("p", null, h("span", { class: "label", text: "Answer  " }), h("span", { class: "mono", text: `${shown}${q.unit ? " " + q.unit : ""}` }),
          q.sf != null ? h("span", { class: "hint", text: `  (to ${q.sf} significant figures)` }) : q.dp != null ? h("span", { class: "hint", text: `  (to ${q.dp} decimal place${q.dp > 1 ? "s" : ""})` }) : null));
        if (res.parsed == null && r.responses[q.id]) box.append(h("p", { class: "hint", text: "Your answer couldn't be read as a number. Type digits only, for example 0.25 or 2.5 x 10^-3." }));
      }
    } else {
      box.append(h("p", { class: "label", text: "Mark your own answer" }));
      const row = h("div", { class: "selfmark", role: "group", "aria-label": "Marks you award yourself" });
      for (let m = 0; m <= res.max; m++) {
        row.append(h("button", { type: "button", "aria-pressed": String(r.self[q.id] === m), text: String(m),
          onclick: () => { r.self[q.id] = m; render(); if (!r.saved && reviewTotals().pendingSelf === 0) saveAttempt(); } }));
      }
      box.append(row, h("span", { class: "hint", text: `out of ${res.max}. Give yourself a mark only for each point you clearly made.` }));
    }
    if (q.mark_scheme) box.append(h("p", null, h("span", { class: "label", text: "Mark scheme  " }), q.mark_scheme));
    if (q.explanation) box.append(h("p", null, h("span", { class: "label", text: "Why  " }), q.explanation));
    return box;
  }

  function answeredCount() {
    const set = S.sets.get(S.run.setId);
    return (set.questions || []).filter((q) => isAnswered(q)).length;
  }
  function updateDock() {
    const s = $("dock-status"); if (!s || !S.run) return;
    const set = S.sets.get(S.run.setId); s.textContent = `${answeredCount()} of ${(set.questions || []).length} answered`;
  }

  // ---------- quiz player: one question at a time ----------
  const FLAG_GROUPS = [
    { label: "Is this in your syllabus?", tags: ["in syllabus", "not taught yet", "not in syllabus"] },
    { label: "For you, this was", tags: ["too easy", "just right", "too hard"] },
  ];
  function questionFlags(setId, q) {
    if (!S.studentId || S.studentId === "parent") return null;
    const mine = S.feedback.filter((f) => f.by === S.studentId && f.targetType === "question" && f.setId === setId && f.questionId === q.id)
      .sort((x, y) => String(x.created).localeCompare(String(y.created)));
    const box = h("div", { class: "qflags" });
    for (const g of FLAG_GROUPS) {
      const latest = [...mine].reverse().find((f) => f.tags.some((t) => g.tags.includes(t)));
      const current = latest && latest.tags.find((t) => g.tags.includes(t));
      box.append(h("div", { class: "qflag-row" }, h("span", { class: "hint", text: g.label }),
        h("div", { class: "selfmark", role: "group", "aria-label": g.label }, ...g.tags.map((t) =>
          h("button", { type: "button", "aria-pressed": String(current === t), text: t, onclick: async () => {
            try {
              const f = await api("api/feedback", { method: "POST", body: JSON.stringify({ by: S.studentId, targetType: "question", setId, questionId: q.id, tags: [t], text: "" }) });
              S.feedback.push(f); render();
            } catch (e) { toast(e.message); }
          } })))));
    }
    return box;
  }
  function isAnswered(q) { if (S.run.notLearnt && S.run.notLearnt.has(q.id)) return true; const v = S.run.responses[q.id]; return v != null && v !== "" && !(Array.isArray(v) && !v.length); }
  function goTo(i) {
    const set = S.sets.get(S.run.setId); const n = (set.questions || []).length;
    S.run.idx = Math.max(0, Math.min(n - 1, i)); render();
    const card = $("qcard"); if (card) card.scrollIntoView({ block: "nearest" });
  }
  function navChip(q, i) {
    const r = S.run; const cls = ["qchip"];
    if (i === r.idx) cls.push("current");
    if (r.phase === "test") {
      if (isAnswered(q)) cls.push("answered");
      if (r.marked.has(q.id)) cls.push("marked");
    } else {
      const res = r.results[q.id];
      const got = res.auto ? res.got : r.self[q.id];
      cls.push(res.notLearnt ? "notlearnt" : got == null ? "pending" : got >= res.max ? "right" : got > 0 ? "part" : "wrong");
    }
    const state = r.phase === "test" ? (isAnswered(q) ? "answered" : "not answered") + (r.marked.has(q.id) ? ", marked to come back to" : "")
      : cls.includes("notlearnt") ? "not learnt yet" : cls.includes("pending") ? "needs self-marking" : cls.includes("right") ? "correct" : cls.includes("part") ? "partly correct" : "not correct";
    return h("button", { type: "button", class: cls.join(" "), "aria-current": i === r.idx ? "step" : null,
      "aria-label": `Question ${i + 1}, ${state}`, text: String(i + 1), onclick: () => goTo(i) });
  }
  function updateNav() {
    const nav = $("qnav"); if (!nav || !S.run) return;
    const set = S.sets.get(S.run.setId);
    nav.replaceChildren(...(set.questions || []).map(navChip));
    const c = $("answered-count"); if (c) c.textContent = `${answeredCount()} of ${(set.questions || []).length} answered`;
  }
  function renderPlayer(main, dock, dockRow, mode) {
    const r = S.run; const set = S.sets.get(r.setId);
    if (!set) { S.view = "practise"; S.run = null; return render(); }
    const qs = set.questions || []; const n = qs.length; const q = qs[r.idx];
    const title = set.title ? `${set.title}` : (set.chapter || set.id);
    const t = mode === "review" ? reviewTotals() : null;
    // sticky bar: title, timer or score, question numbers
    const bar = h("div", { class: "quizbar" },
      h("div", { class: "quizbar-top" },
        h("div", { class: "title" }, backLink(mode === "test" ? "← Leave quiz" : "← Back to the chapter", () => {
            if (mode === "test") { saveDraft(); clearInterval(timerHandle); toast("Your answers are kept on this device. Open the quiz again to carry on."); }
            S.chapterId = set.chapterId || set.id; S.view = "practise"; S.place = "subjects"; S.run = null; render(); window.scrollTo(0, 0); }),
          h("span", { class: "label", text: `${set.subject || ""} · ${set.chapter || ""}` }), h("h2", { text: title })),
        mode === "test"
          ? h("div", { class: "timer-box", role: "timer", "aria-label": "Time" }, h("span", { class: "hint", text: "Time" }), h("span", { class: "timer mono", id: "timer", text: elapsedLabel() }))
          : h("div", { class: "timer-box" }, h("span", { class: "hint", text: "Score" }), h("span", { class: `timer mono ${band(pct(t.got, t.max))}`, text: `${t.got}/${t.max}` }))),
      h("nav", { class: "qnav", id: "qnav", "aria-label": "Questions" }, ...qs.map(navChip)),
      h("div", { class: "legend" }, ...(mode === "test"
        ? [h("span", null, h("span", { class: "qchip mini answered" }), "answered"), h("span", null, h("span", { class: "qchip mini marked" }), "come back to"), h("span", { class: "hint", id: "answered-count", text: `${answeredCount()} of ${n} answered` })]
        : [h("span", null, h("span", { class: "qchip mini right" }), "correct"), h("span", null, h("span", { class: "qchip mini part" }), "partly"), h("span", null, h("span", { class: "qchip mini wrong" }), "not correct"),
           r.notLearnt.size ? h("span", null, h("span", { class: "qchip mini notlearnt" }), "not learnt yet") : null,
           t.pendingSelf ? h("span", null, h("span", { class: "qchip mini pending" }), `${t.pendingSelf} to mark yourself`) : null])));
    main.append(bar);
    if (mode === "test") {
      main.append(r.warning
        ? h("div", { class: "notice bad", role: "alert" }, h("p", { text: "⚠️ You left the quiz. That was your one warning: if you switch to another app or tab again, the quiz will be submitted as it is." }),
            h("button", { class: "btn ghost", text: "OK, I'll stay", onclick: () => { r.warning = false; render(); } }))
        : h("p", { class: "hint stay-hint", text: `🔒 Stay on this screen until you submit. Switching to another app or tab submits the quiz.${hardLimitSec() ? ` So does going past ${hardLimitSec() / 60} minutes (twice its time).` : ""} Need a calculator? Use the 🧮 button below or your own calculator.` }));
      if (r.timeWarned) main.append(h("div", { class: "notice bad", role: "alert" }, h("p", { text: "⏳ About one minute left. The quiz will submit itself then, so press Submit when you're ready." })));
    }
    if (mode === "review" && r.timeUp) main.append(h("div", { class: "notice bad" }, h("p", { text: `This quiz was submitted automatically after ${hardLimitSec() / 60} minutes, twice its time. Unanswered questions count as wrong.` })));
    if (mode === "review" && r.leftQuiz) {
      const when = (r.leaveLog || []).filter((l) => l.sec >= QUIZ_BLIP_MS / 1000).map((l) => `${new Date(l.at).toLocaleTimeString([], { hour: "numeric", minute: "2-digit", second: "2-digit" })} for ${l.sec} s${l.reload ? " (the page was reloaded or closed)" : ""}`);
      main.append(h("div", { class: "notice bad" }, h("p", { text: "This quiz was submitted because you left the quiz screen. Unanswered questions count as wrong. Next time, stay on the quiz until you press Submit." }),
        when.length ? h("p", { class: "hint", text: `StepWise was hidden at ${when.join("; ")}. Another app or window covering the browser, or the screen turning off, also counts.` }) : null));
    }
    if (mode === "review") {
      const p = pct(t.got, t.max);
      main.append(h("div", { class: `notice ${r.saved ? "good" : ""}` }, h("p", { text: r.saved
        ? `Saved: ${t.got}/${t.max} (${p}%) in ${Math.max(1, Math.round((r.durationSec || 0) / 60))} min. Tap any number to see that question.`
        : t.pendingSelf ? `Mark your written answer${t.pendingSelf > 1 ? "s" : ""} (dashed numbers) and your result saves automatically.` : "Saving your result…" })));
      if (r.saved && S.studentId !== "parent") {
        r.cheer = r.cheer || quizCheer(r, t);
        main.append(h("div", { class: `cheer ${r.cheer.band}`, role: "status" }, h("strong", { text: r.cheer.title }), h("p", { text: r.cheer.line })));
      }
      if (r.notLearnt.size) {
        const cid = set.chapterId || set.id;
        const atomIds = qs.filter((x) => r.notLearnt.has(x.id)).flatMap((x) => x.atom_ids || []);
        const target = set.kind === "chunk" && set.chunkId ? { chapterId: cid, kind: "learn", topicId: set.topicId, chunkId: set.chunkId, label: set.chunkTitle } : learnTargetFor(cid, atomIds);
        main.append(h("div", { class: "notice" },
          h("p", { text: `You marked ${r.notLearnt.size} question${r.notLearnt.size > 1 ? "s" : ""} as not learnt yet. That's not counted as a mistake.` }),
          target && S.tutorOn ? h("div", { class: "students" }, h("button", { class: "btn accent", text: `Learn ${r.notLearnt.size > 1 ? "them" : "it"} now: ${target.label}`,
            onclick: () => { const { label, ...opts } = target; tutorStart(opts); } })) : null));
      }
    }
    // the question card
    const card = h("section", { class: "sheet qcard", id: "qcard" },
      h("div", { class: "qcard-head" }, h("span", { class: "label", text: `Question ${r.idx + 1} of ${n}` }), h("span", { class: "marks", text: `${q.marks || 1} mark${(q.marks || 1) > 1 ? "s" : ""}` }),
        mode === "test" ? h("button", { type: "button", class: "react", "aria-pressed": String(r.marked.has(q.id)), text: r.marked.has(q.id) ? "Marked to come back to" : "Mark to come back to",
          onclick: () => { r.marked.has(q.id) ? r.marked.delete(q.id) : r.marked.add(q.id); render(); } }) : null),
      questionBody(q, r.idx, mode),
      h("div", { class: "qcard-nav" },
        h("button", { type: "button", class: "btn ghost", disabled: r.idx === 0, "aria-label": "Previous question", text: "← Previous", onclick: () => goTo(r.idx - 1) }),
        r.idx < n - 1
          ? h("button", { type: "button", class: "btn accent", "aria-label": "Next question", text: "Next →", onclick: () => goTo(r.idx + 1) })
          : mode === "test" ? h("button", { type: "button", class: "btn accent", text: "Submit and mark", onclick: confirmSubmit }) : null));
    main.append(card);
    if (mode === "review") main.append(h("section", { class: "sheet" }, feedbackWidget({ targetType: "set", setId: r.setId }, "Feedback on this whole quiz")));
    // bottom dock: leave / submit, or after review: where next
    dock.hidden = false;
    if (mode === "test") {
      dockRow.append(h("span", { class: "status", id: "dock-status" }),
        h("button", { class: "btn ghost", type: "button", "aria-pressed": String(!!S.calcOpen), text: "🧮 Calculator", onclick: () => { S.calcOpen = !S.calcOpen; render(); if (S.calcOpen) CALC.focus(); } }),
        h("button", { class: "btn accent", text: "Submit and mark", onclick: confirmSubmit }));
      updateDock();
    } else {
      dockRow.append(h("span", { class: "status", text: r.saved ? "Result saved" : t.pendingSelf ? `${t.pendingSelf} to mark yourself` : "Saving…" }),
        h("button", { class: "btn ghost", text: "Back to the chapter", onclick: () => { if (!r.saved && t.pendingSelf) toast("Mark your written answers first, or this result won't be saved"); S.chapterId = set.chapterId || set.id; S.view = "practise"; S.run = null; render(); } }),
        r.saved && S.tutorOn && qs.some((x) => { const res = r.results[x.id]; const g = res.auto ? res.got : r.self[x.id]; return !res.notLearnt && g != null && g < res.max; }) ? h("button", { class: "btn accent", text: `Fix my mistakes with the tutor`,
          onclick: () => tutorStart({ chapterId: set.chapterId || set.id, kind: "fix", attemptId: r.attemptId }) }) : null);
    }
    if (r.confirming) {
      const left = n - answeredCount();
      main.append(h("div", { class: "notice", role: "alertdialog", "aria-label": "Submit the quiz?" },
        h("p", { text: left ? `${left} question${left > 1 ? "s are" : " is"} not answered yet. Submit anyway?` : "Submit your answers for marking?" }),
        h("div", { class: "students" },
          h("button", { class: "btn ghost", text: "Keep working", onclick: () => { r.confirming = false; render(); } }),
          h("button", { class: "btn accent", text: "Submit", onclick: () => { r.confirming = false; submitTest(); } }))));
      requestAnimationFrame(() => window.scrollTo(0, document.body.scrollHeight));
    }
  }
  function confirmSubmit() { S.run.confirming = true; render(); }
  function renderTest(main, dock, dockRow) { renderPlayer(main, dock, dockRow, "test"); }
  function renderReview(main, dock, dockRow) { renderPlayer(main, dock, dockRow, "review"); }
  document.addEventListener("keydown", (e) => {
    if (!S.run || !["test", "review"].includes(S.view)) return;
    const tag = (e.target && e.target.tagName) || "";
    if (["INPUT", "TEXTAREA", "SELECT"].includes(tag) && e.target.type !== "radio" && e.target.type !== "checkbox") return;
    if (e.key === "ArrowRight") { e.preventDefault(); goTo(S.run.idx + 1); }
    if (e.key === "ArrowLeft") { e.preventDefault(); goTo(S.run.idx - 1); }
  });

  function renderProgress(main) {
    const students = [...S.students.values()].sort((a, b) => (a.name || "").localeCompare(b.name || ""));
    if (!students.length) { main.append(studentPicker(false)); return; }
    const sid = S.progressStudent && S.students.has(S.progressStudent) ? S.progressStudent : (S.studentId && S.students.has(S.studentId) ? S.studentId : students[0].id);
    S.progressStudent = sid;
    const codes = new Set(students.flatMap((s) => subjectsFor(s).map((x) => x.code)));   // only the shown children's courses
    const sets = [...S.sets.values()].filter((x) => codes.has(x.code))
      .sort((a, b) => (a.subject || "").localeCompare(b.subject || "") || (a.order || 0) - (b.order || 0));

    // overview matrix: students × sets, latest %
    const ov = h("section", { class: "sheet" }, h("h2", { text: "Everyone at a glance" }),
      h("p", { class: "muted", text: "Latest score on each self-check. Pick a name to see which ideas need more practice." }));
    const tw = h("div", { class: "table-wrap" }); const table = h("table");
    table.append(h("thead", null, h("tr", null, h("th", { text: "Self-check" }), ...students.map((s) =>
      h("th", { class: "num" }, h("button", { class: "student", style: "min-width:0;padding:4px 10px;font-size:.85rem", "aria-pressed": String(s.id === sid), text: s.name, onclick: () => { S.progressStudent = s.id; render(); } }))))));
    const tb = h("tbody");
    if (!sets.length) tb.append(h("tr", null, h("td", { colspan: String(students.length + 1), class: "muted", text: "No self-checks published yet." })));
    const latestByStudent = new Map(students.map((s) => [s.id, latestPerSet(s.id)]));
    for (const set of sets) {
      tb.append(h("tr", null, h("td", null, h("div", { text: set.chapter || set.id }), h("div", { class: "mono muted", style: "font-size:.75rem", text: `${set.subject || ""} ${set.code || ""}` })),
        ...students.map((s) => { const a = latestByStudent.get(s.id).get(set.id); if (!a) return h("td", { class: "num muted", text: "—" });
          const p = pct(a.score, a.max); return h("td", { class: "num" }, h("span", { class: `pill ${band(p)}`, text: `${p}%` })); })));
    }
    table.append(tb); tw.append(table); ov.append(tw); main.append(ov);

    // weak ideas for the chosen student, from the latest attempt of each set
    const st = S.students.get(sid);
    const latest = latestByStudent.get(sid);
    const atomAgg = new Map();
    for (const a of latest.values()) {
      const set = S.sets.get(a.setId); const names = (set && set.atoms) || {};
      for (const [atom, gm] of Object.entries(a.atoms || {})) {
        const cur = atomAgg.get(atom) || { got: 0, max: 0, text: names[atom] || "", subject: a.subject, code: a.code };
        cur.got += Number(gm[0]) || 0; cur.max += Number(gm[1]) || 0; atomAgg.set(atom, cur);
      }
    }
    const weak = [...atomAgg.entries()].filter(([, v]) => v.max > 0)
      .map(([id, v]) => ({ id, ...v, p: pct(v.got, v.max) })).sort((a, b) => a.p - b.p || b.max - a.max);
    const ws = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: ideas to work on` }),
      h("p", { class: "muted", text: "Each idea is scored across the questions that test it, using the latest attempt of each self-check. Lowest first." }));
    if (!weak.length) ws.append(h("p", { class: "muted", text: `No saved attempts for ${st.name} yet. Results appear here after the first self-check is saved.` }));
    for (const w of weak.slice(0, 25)) {
      ws.append(h("div", { class: "atom-row" },
        h("div", { class: "stmt" }, h("div", { text: w.text || w.id }), h("div", { class: "id", text: `${w.subject || ""} · ${w.id}` })),
        h("div", { class: `bar ${band(w.p)}` }, h("span", { style: `width:${w.p}%` })),
        h("span", { class: `pill ${band(w.p)}`, text: `${w.p}%` })));
    }
    main.append(ws);

    // tutor activity and idea levels (counts only; the parent area has the full chats)
    if (!S.activity && !S.loadingActivity) {
      S.loadingActivity = true;
      api("api/activity").then((a) => { S.activity = a; }).catch(() => { S.activity = {}; }).finally(() => { S.loadingActivity = false; if (S.view === "progress") render(); });
    }
    const act = (S.activity && S.activity[sid]) || { sessions: [], ideas: {} };
    const ts = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: tutor sessions` }));
    if (!S.activity) ts.append(h("p", { class: "muted", text: "Loading…" }));
    else if (!act.sessions.length) ts.append(h("p", { class: "muted", text: "No tutor sessions yet." }));
    else {
      const mins = act.sessions.reduce((a, x) => a + (x.minutes || 0), 0);
      const right = act.sessions.reduce((a, x) => a + x.correct, 0), tried = act.sessions.reduce((a, x) => a + x.attempts, 0);
      ts.append(h("p", { class: "muted", text: `${act.sessions.length} session${act.sessions.length > 1 ? "s" : ""}, about ${mins} min, ${right} of ${tried} tutor questions answered correctly.` }));
      const tt = h("table"); tt.append(h("thead", null, h("tr", null, h("th", { text: "When" }), h("th", { text: "Chapter" }), h("th", { class: "num", text: "Messages" }), h("th", { class: "num", text: "Right" }), h("th", { class: "num", text: "Time" }))));
      const tb2 = h("tbody");
      for (const x of act.sessions.slice(0, 30)) tb2.append(h("tr", null, h("td", { class: "mono", text: fmtDate(x.updated) }),
        h("td", { text: `${x.subject} · ${x.chapter}${x.mode === "practice" ? " (practice)" : ""}` }), h("td", { class: "num", text: String(Math.max(0, x.messages)) }),
        h("td", { class: "num", text: `${x.correct}/${x.attempts}` }), h("td", { class: "num", text: `${x.minutes} min` })));
      tt.append(tb2); ts.append(h("div", { class: "table-wrap" }, tt));
    }
    main.append(ts);
    const ideaCh = Object.entries(act.ideas || {});
    if (ideaCh.length) {
      const is = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: idea levels` }),
        h("p", { class: "muted", text: "From the tutor and quizzes together. Levels: not met, recall, apply, combine, exam-ready." }),
        h("div", { class: "legend" }, ...[0, 1, 2, 3, 4].map((i) => h("span", null, h("span", { class: `lv-dot lv${i}` }), ["not met", "recall", "apply", "combine", "exam-ready"][i]))));
      for (const [, ch] of ideaCh) {
        const total = ch.byLevel.reduce((a, b) => a + b, 0);
        is.append(h("div", { class: "idea-ch" }, h("h3", { text: `${ch.subject} · ${ch.chapter}` }), levelBar(ch.byLevel, total),
          h("div", { class: "idea-list" }, ...ch.atoms.slice().sort((a, b) => a.level - b.level).slice(0, 8).map((a) =>
            h("div", { class: "idea" }, h("span", { class: `lv-dot lv${a.level}` }), h("span", { text: a.statement }))))));
      }
      main.append(is);
    }

    // attempt history
    const hist = attemptsFor(sid);
    const hs = h("section", { class: "sheet" }, h("h2", { text: `${st.name}: attempts` }));
    if (!hist.length) hs.append(h("p", { class: "muted", text: "Nothing saved yet." }));
    else {
      const t2 = h("table"); t2.append(h("thead", null, h("tr", null, h("th", { text: "When" }), h("th", { text: "Self-check" }), h("th", { class: "num", text: "Score" }), h("th", { class: "num", text: "Time" }))));
      const b2 = h("tbody");
      for (const a of hist.slice(0, 50)) {
        const p = pct(a.score, a.max);
        b2.append(h("tr", null, h("td", { class: "mono", text: fmtDate(a.submittedAt) }), h("td", { text: `${a.subject || ""} · ${a.chapter || a.setId}` }),
          h("td", { class: "num" }, h("span", { class: `pill ${band(p)}`, text: `${a.score}/${a.max}` })), h("td", { class: "num", text: `${Math.round((a.durationSec || 0) / 60)} min` })));
      }
      t2.append(b2); hs.append(h("div", { class: "table-wrap" }, t2));
    }
    main.append(hs);

    main.append(parentArea());
  }

  // ---------- chrome ----------
  $("tab-practise").addEventListener("click", () => goPlace("today"));
  $("tab-subjects").addEventListener("click", () => goPlace("subjects"));
  $("tab-chats").addEventListener("click", () => goPlace("chats"));
  $("tab-progress").addEventListener("click", () => goPlace("progress"));
  $("app-fb").addEventListener("click", () => { S.appFb = !S.appFb; S.appFbOpening = S.appFb; render(); window.scrollTo(0, 0); });
  $("tab-bank").addEventListener("click", () => { S.view = "bank"; S.run = null; render(); });
  $("tab-tutor").addEventListener("click", () => { if (S.view === "test" && !confirmLeave()) return; S.view = "tutor"; S.run = null; T.mastery = null; render(); });
  $("who").addEventListener("click", () => {
    if (S.view === "test") return toast("Submit or leave the self-check first");
    if (S.me && S.me.role === "child") { S.view = "account"; return render(); }
    S.view = "practise"; S.picking = true; render();
  });
  function confirmLeave() { saveDraft(); toast("Your answers are kept on this device. Open the self-check again to carry on."); clearInterval(timerHandle); return true; }

  try {
    const ro = new ResizeObserver(() => {
      const hd = document.querySelector("header.top"), dk = $("dock");
      document.documentElement.style.setProperty("--hdr-h", `${hd ? hd.getBoundingClientRect().height : 64}px`);
      document.documentElement.style.setProperty("--dock-h", `${dk && !dk.hidden ? dk.getBoundingClientRect().height : 0}px`);
    });
    ro.observe(document.querySelector("header.top")); ro.observe($("dock"));
  } catch {}
  render();
  connect().catch(() => { S.dbError = "unavailable"; S.ready = true; render(); });
})();
</script>

</body>
</html>