File size: 100,965 Bytes
14c58d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cricket data foundry review</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@500;600;700&family=Source+Sans+3:wght@400;600&display=swap" rel="stylesheet">
<style>
:root{--bg:#F1F5F0;--surface:#FFFFFF;--ink:#17231B;--muted:#56675B;--line:#D3DDD4;--field:#2E6A3E;--field-soft:#E2EEE4;
--pitch:#D2B47C;--pitch-ink:#5E4A22;--ball:#B2262B;--amber:#B5741A;--amber-soft:#F7EBD6;--fail-soft:#F6E1E1;--blue:#2F5F8A;--blue-soft:#E3ECF5;
--display:"Barlow Condensed","Arial Narrow",Arial,sans-serif;--body:"Source Sans 3","Segoe UI",Helvetica,Arial,sans-serif;--code:ui-monospace,Menlo,Consolas,monospace;color-scheme:light}
@media (prefers-color-scheme:dark){:root{--bg:#0E1611;--surface:#16211A;--ink:#E4ECE6;--muted:#93A598;--line:#2A3A30;--field:#62A876;--field-soft:#1D3024;
--pitch:#B39660;--pitch-ink:#2E220C;--ball:#E3585D;--amber:#E0A04A;--amber-soft:#33281A;--fail-soft:#3A1F21;--blue:#7FB0DD;--blue-soft:#1A2A38;color-scheme:dark}}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.5 var(--body)}
button,select,input,textarea{font:inherit;color:inherit}:focus-visible{outline:2px solid var(--field);outline-offset:2px}
header{padding:16px 28px 0;border-bottom:1px solid var(--line);background:var(--surface)}
.top{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap}
h1{font:700 32px/1 var(--display);margin:0}.sub{color:var(--muted);font-size:14px}
.who{display:flex;gap:8px;align-items:center;font-size:14px}.who input{width:140px;padding:4px 8px;border:1px solid var(--line);border-radius:6px;background:var(--bg)}
.mode{font-size:13px;padding:2px 10px;border-radius:12px;background:var(--amber-soft)}.mode.live{background:var(--field-soft)}
.stages{display:flex;margin:14px 0 0;padding:0;list-style:none;overflow-x:auto;counter-reset:st}
.stages li{flex:1 0 120px;padding:8px 12px 10px;border-left:1px solid var(--line);counter-increment:st}.stages li:first-child{border-left:0;padding-left:0}
.stages b{display:block;font:600 26px/1.05 var(--display)}.stages span{color:var(--muted);font-size:13px}.stages span::before{content:counter(st) ". "}
nav{display:flex;gap:2px;margin-top:8px;overflow-x:auto}
nav button{background:none;border:0;border-bottom:3px solid transparent;padding:9px 13px;cursor:pointer;color:var(--muted);font-weight:600;white-space:nowrap}
nav button[aria-selected=true]{color:var(--ink);border-color:var(--field)}
main{padding:20px 28px 80px}.view{display:none}.view.on{display:block}
.layout{display:grid;grid-template-columns:290px minmax(0,1fr);gap:24px;align-items:start}
.filters{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:10px}
select,input[type=text],input[type=search],textarea{background:var(--surface);border:1px solid var(--line);border-radius:6px;padding:5px 8px;min-width:0}
.filters select,.filters input{flex:1 1 45%}
td.acts{white-space:nowrap}
.list{max-height:calc(100vh - 260px);overflow:auto;border:1px solid var(--line);border-radius:8px;background:var(--surface)}
.item{display:grid;grid-template-columns:64px 1fr;gap:10px;padding:9px;border:0;border-bottom:1px solid var(--line);border-left:4px solid transparent;cursor:pointer;width:100%;text-align:left;background:none}
.item[aria-current=true]{background:var(--field-soft);border-left-color:var(--field)}
.item img,.item .noimg{width:64px;height:44px;object-fit:cover;border-radius:4px;background:var(--line)}
.item .id{font:600 16px/1.2 var(--display)}.meta{font-size:13px;color:var(--muted)}
.dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px;vertical-align:1px}
.dot.pass{background:var(--field)}.dot.warn{background:var(--amber)}.dot.fail{background:var(--ball)}
.pill{display:inline-block;font-size:12px;padding:1px 9px;border-radius:10px;background:var(--line);margin-right:6px;white-space:nowrap}
.pill.auto{background:var(--line)}.pill.human_verified{background:var(--blue-soft)}.pill.human_corrected{background:var(--amber-soft)}.pill.expert_gold{background:#F2C230;color:#2B2208}
.viewer{max-width:var(--vw,960px)}
.player{background:#000;border-radius:8px;overflow:hidden;aspect-ratio:16/9;display:grid;place-items:center}
.player video{width:100%;height:100%;object-fit:contain;display:block}.player .empty{color:#bbb;padding:20px;text-align:center}
.controls{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:10px 0}
.seg{display:inline-flex;border:1px solid var(--line);border-radius:6px;overflow:hidden}
.seg button{background:var(--surface);border:0;padding:4px 11px;cursor:pointer;border-left:1px solid var(--line)}.seg button:first-child{border-left:0}
.seg button[aria-pressed=true]{background:var(--field);color:#fff}
.clock{font:600 18px var(--display);min-width:170px}
.btn{background:var(--surface);border:1px solid var(--line);border-radius:6px;padding:4px 11px;cursor:pointer}
.btn.primary{background:var(--field);border-color:var(--field);color:#fff}.btn:disabled{opacity:.45;cursor:not-allowed}
.btn.small{padding:1px 8px;font-size:13px}
.title{font:600 28px/1.15 var(--display);margin:0}
/* signature element: the clip timeline as a 22-yard strip with creases */
.strip{position:relative;height:66px;margin:8px 0 4px;border-radius:4px;cursor:pointer;touch-action:none;
background:var(--pitch);box-shadow:inset 0 0 0 1px rgba(0,0,0,.08)}
.strip .head{position:absolute;top:-5px;bottom:-5px;width:2px;background:var(--ink);pointer-events:none}
.mark{position:absolute;transform:translate(-50%,0);border:0;padding:0;background:none;cursor:pointer;touch-action:none}
.mark i{display:block;width:16px;height:16px;border-radius:50%;border:2px solid #fff;box-shadow:0 1px 3px rgba(0,0,0,.35);margin:0 auto}
.mark span{display:block;white-space:nowrap;font-size:11px;font-weight:600;color:var(--pitch-ink);text-align:center}
.mark.up{top:3px}.mark.down{bottom:3px}.mark.down span{order:-1}
.mark.edit i{outline:2px dashed #fff;outline-offset:2px}.mark.dragging i{transform:scale(1.25)}
.scale{display:flex;justify-content:space-between;font-size:12px;color:var(--muted)}
.strip .tick{position:absolute;top:0;bottom:0;width:1px;background:rgba(0,0,0,.18);pointer-events:none}
.strip .hov{position:absolute;top:-24px;transform:translateX(-50%);background:var(--ink);color:var(--surface);font-size:12px;padding:1px 6px;border-radius:4px;pointer-events:none;white-space:nowrap;display:none}
.strip .hovline{position:absolute;top:0;bottom:0;width:1px;background:var(--ink);opacity:.5;pointer-events:none;display:none}
.ruler{position:relative;height:18px;font-size:12px;color:var(--muted)}.ruler span{position:absolute;transform:translateX(-50%);white-space:nowrap}
.phases{position:relative;height:26px;margin-top:3px;margin-left:0}
.phrow{display:grid;grid-template-columns:52px 1fr;align-items:center;gap:6px;margin-left:-58px}
.phrow>span{font-size:12px;color:var(--muted);text-align:right}
@media (max-width:900px){.phrow{margin-left:0;grid-template-columns:44px 1fr}}
.phase{position:absolute;top:0;height:24px;border:0;border-radius:4px;cursor:pointer;font-size:11px;font-weight:600;color:#fff;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;padding:0 4px;opacity:.9}
.phase:hover,.phase:focus-visible{opacity:1;outline:2px solid var(--ink);outline-offset:1px}
.chips{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0 4px}
.chip{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--surface);border-radius:14px;padding:2px 10px 2px 6px;cursor:pointer;font-size:13px}
.chip i{width:10px;height:10px;border-radius:50%;display:inline-block;border:1px solid rgba(0,0,0,.25)}
.chip b{font-weight:600}.chip:hover{border-color:var(--field)}
.ts{background:var(--field-soft);border:0;border-radius:4px;padding:0 5px;cursor:pointer;font:inherit;color:var(--ink);font-weight:600;white-space:nowrap}
.ts:hover{background:var(--field);color:#fff}
.playinfo{font-size:13px;color:var(--muted);min-height:18px}
.lab{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:20px;align-items:start}
.labimg{position:relative;max-width:1100px}.labimg img{width:100%;display:block;border-radius:6px}.labimg canvas{position:absolute;inset:0;width:100%;height:100%;cursor:crosshair}
.kbd{font:12px var(--code);border:1px solid var(--line);border-radius:4px;padding:0 5px;background:var(--surface)}
.vd{display:inline-block;font-size:12px;font-weight:700;padding:1px 8px;border-radius:10px;white-space:nowrap}
.vd.match{background:var(--field-soft);color:var(--field)}.vd.mismatch{background:var(--fail-soft);color:var(--ball)}
.vd.needs_label,.vd.not_measured{background:var(--amber-soft);color:var(--amber)}.vd.measured{background:var(--blue-soft);color:var(--blue)}
.rp{display:grid;grid-template-columns:repeat(auto-fit,minmax(380px,1fr));gap:20px;margin-top:18px}
.rp table td:nth-child(2),.rp table td:nth-child(3){width:34%}
.role{display:inline-block;font-size:12px;font-weight:600;color:#fff;border-radius:10px;padding:1px 9px;white-space:nowrap}
.seg-line{padding:8px 0;border-bottom:1px solid var(--line);line-height:1.9}
.w{cursor:pointer;border-radius:3px;padding:0 1px}.w:hover{background:var(--field-soft)}.w.now{background:#F2C230;color:#2B2208}
.voicebox{border:1px dashed var(--line);border-radius:8px;padding:12px;margin-top:10px}
.speechcard{border-left:4px solid var(--blue);background:var(--surface);border-radius:8px;padding:12px 16px;margin-top:18px}
.vwrap{position:relative;width:100%;height:100%}.vwrap canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
.mvgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
.mvcell{background:#000;border-radius:6px;overflow:hidden;position:relative;aspect-ratio:16/9}
.mvcell video{width:100%;height:100%;object-fit:contain;display:block}
.mvcell span{position:absolute;left:6px;top:6px;background:rgba(0,0,0,.65);color:#fff;font-size:12px;padding:1px 7px;border-radius:4px}
canvas.plot{width:100%;height:230px;display:block;background:var(--surface);border:1px solid var(--line);border-radius:8px}
.checkrow{display:grid;grid-template-columns:1fr 210px;gap:10px;padding:6px 0;border-bottom:1px solid var(--line);align-items:center}
@media (max-width:900px){.lab{grid-template-columns:1fr}}
.grid2{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:24px;margin-top:20px}
h2{font:600 22px/1.2 var(--display);margin:0 0 8px}h3{font:600 18px/1.2 var(--display);margin:14px 0 6px}
table{border-collapse:collapse;width:100%;font-size:14px}td,th{padding:5px 7px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}th{color:var(--muted);font-weight:600}
.bar{height:6px;background:var(--line);border-radius:3px;width:56px;display:inline-block;vertical-align:middle;margin-right:6px}.bar i{display:block;height:100%;border-radius:3px;background:var(--field)}
.state{font-size:12px;color:var(--muted)}.state.corrected{color:var(--amber)}.state.verified{color:var(--blue)}
.card{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:14px 16px}
.qc{border-radius:8px;padding:12px 14px;background:var(--field-soft)}.qc.warn{background:var(--amber-soft)}.qc.fail{background:var(--fail-soft)}.qc ul{margin:6px 0 0;padding-left:18px}
.why{background:var(--blue-soft);border-radius:8px;padding:8px 12px;font-size:14px;margin:8px 0}
.keys{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}.keys figure{margin:0;width:120px}.keys img{width:100%;border-radius:6px;display:block;cursor:pointer}.keys figcaption{font-size:12px;color:var(--muted)}
canvas.chart{width:100%;height:140px;display:block;background:var(--surface);border:1px solid var(--line);border-radius:8px}
.form{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px}.form label{font-size:13px;color:var(--muted);display:flex;flex-direction:column;gap:3px}
.form label.wide{grid-column:1/-1}textarea{min-height:52px;resize:vertical}
.err{color:var(--ball);font-size:13px;margin-top:4px}
.calib{position:relative;display:inline-block;max-width:100%}.calib img{max-width:100%;display:block;border-radius:6px}
.calib canvas{position:absolute;inset:0;width:100%;height:100%;cursor:crosshair}
.qa{border-top:1px solid var(--line);padding:10px 0;max-width:80ch}.qa .q{font-weight:600}.qa .a{margin:2px 0 6px}
.tag{display:inline-block;font-size:12px;padding:1px 8px;border-radius:10px;background:var(--field-soft);margin-right:6px}.tag.low{background:var(--amber-soft)}.tag.expert{background:var(--blue-soft)}
.linkish{background:none;border:0;color:var(--field);cursor:pointer;padding:0;font-weight:600;font-size:13px}
pre{background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:10px;overflow:auto;font:12px/1.45 var(--code);max-height:340px;white-space:pre-wrap;word-break:break-word}
.tablewrap{overflow-x:auto;background:var(--surface);border:1px solid var(--line);border-radius:8px}
.downloads a{display:inline-block;margin:0 14px 8px 0;color:var(--field);font-weight:600}
.note{color:var(--muted);font-size:15px;max-width:75ch}.empty-state{padding:40px;text-align:center;color:var(--muted)}
.hbar{display:grid;grid-template-columns:150px 1fr 100px;gap:8px;align-items:center;font-size:14px;margin:4px 0}.hbar .track{background:var(--line);height:12px;border-radius:6px;overflow:hidden}.hbar .track i{display:block;height:100%;background:var(--field)}
.check{display:grid;grid-template-columns:70px 1fr;gap:8px;padding:6px 0;border-bottom:1px solid var(--line);font-size:14px}
.st-ok{color:var(--field);font-weight:600}.st-warn{color:var(--amber);font-weight:600}.st-fail{color:var(--ball);font-weight:600}.st-manual{color:var(--muted);font-weight:600}
.savebar{position:fixed;left:0;right:0;bottom:0;background:var(--surface);border-top:1px solid var(--line);padding:10px 28px;display:none;align-items:center;gap:12px;z-index:5}
.savebar.on{display:flex}.toast{font-size:14px;color:var(--muted)}
.dl{display:grid;grid-template-columns:200px 1fr;gap:4px 14px;font-size:14px}.dl dt{color:var(--muted)}.dl dd{margin:0}
@media (max-width:900px){.layout{grid-template-columns:1fr}.list{max-height:260px}main,header{padding-left:14px;padding-right:14px}.hbar{grid-template-columns:110px 1fr 56px}}
</style>
</head>
<body>
<header>
  <div class="top">
    <div><h1>Cricket data foundry review</h1><div class="sub" id="gen"></div></div>
    <div class="who"><span id="mode" class="mode">Read-only</span><label for="annot">Reviewer ID</label><input id="annot" autocomplete="off" placeholder="e.g. reviewer_01"><span id="role" class="meta"></span></div>
  </div>
  <ol class="stages" id="stages" aria-label="Pipeline stages"></ol>
  <nav role="tablist" id="tabs">
    <button role="tab" data-v="deliveries" aria-selected="true">Deliveries</button>
    <button role="tab" data-v="mv" aria-selected="false">Multi-view</button>
    <button role="tab" data-v="queue" aria-selected="false">Review queue</button>
    <button role="tab" data-v="dash" aria-selected="false">Dashboard</button>
    <button role="tab" data-v="pairs" aria-selected="false">Training pairs</button>
    <button role="tab" data-v="release" aria-selected="false">Release</button>
    <button role="tab" data-v="balls" aria-selected="false">Ball labels</button>
    <button role="tab" data-v="bats" aria-selected="false">Bat labels</button>
    <button role="tab" data-v="check" aria-selected="false">Field checklist</button>
    <button role="tab" data-v="exp" aria-selected="false">Experiment and sources</button>
  </nav>
</header>
<main>
  <section class="view on" id="v-deliveries"><div class="layout">
    <aside>
      <div class="filters">
        <select id="f-cat" aria-label="Video type"></select>
        <select id="f-qc" aria-label="QC result"><option value="">All QC</option><option>pass</option><option>warn</option><option>fail</option></select>
        <select id="f-st" aria-label="Review status"><option value="">All statuses</option></select>
        <select id="f-sort" aria-label="Sort"><option value="priority">Needs review first</option><option value="id">By delivery ID</option></select>
      </div>
      <div class="list" id="list"></div>
    </aside>
    <div id="detail"></div>
  </div></section>
  <section class="view" id="v-mv"><div id="mvTab"></div></section>
  <section class="view" id="v-queue">
    <p class="note">Deliveries the pipeline is least sure about come first (section 9.2). The reason column says why each one was picked, so reviewers correct targeted errors instead of checking everything.</p>
    <div class="tablewrap"><table><thead><tr><th>Delivery</th><th>Video type</th><th>Priority</th><th>Why selected</th><th>Status</th><th></th></tr></thead><tbody id="q-rows"></tbody></table></div>
  </section>
  <section class="view" id="v-dash"><div class="grid2" id="dash"></div></section>
  <section class="view" id="v-pairs">
    <p class="note">One line per question about one delivery clip. Facts come from measurements, labels from reviewers, and interpretation, advice and counterfactuals from coaches; each answer type is kept separate (section 7.6).</p>
    <div class="downloads" id="downloads"></div>
    <div class="filters" style="max-width:820px">
      <select id="j-task" aria-label="Question type"></select><select id="j-type" aria-label="Answer type"></select>
      <select id="j-rs" aria-label="Review state"><option value="">All review states</option><option>unreviewed</option><option>verified</option><option>corrected</option></select>
      <input id="j-q" type="search" placeholder="Search questions and answers" aria-label="Search">
    </div>
    <div class="tablewrap"><table><thead><tr><th>Delivery</th><th>Question</th><th>Answer</th><th>Type</th><th>Review</th><th>Conf.</th></tr></thead><tbody id="j-rows"></tbody></table></div>
    <h2 style="margin-top:22px">Raw JSONL preview</h2><pre id="j-raw"></pre>
  </section>
  <section class="view" id="v-release"><div id="rel"></div></section>
  <section class="view" id="v-balls"><div id="balls"></div></section>
  <section class="view" id="v-bats"><div id="bats"></div></section>
  <section class="view" id="v-check"><div id="check"></div></section>
  <section class="view" id="v-exp"><div id="exp"></div></section>
</main>
<div class="savebar" id="savebar"><b id="pendN"></b><button class="btn primary" id="saveBtn">Save and rebuild</button><button class="btn" id="discardBtn">Discard</button><span class="toast" id="toast"></span><span class="err" id="saveErr"></span></div>
<script src="data.js"></script>
<script>
const D = window.FOUNDRY, O = D && D.ontology, EN = D && D.event_names;
const $ = s => document.querySelector(s), $$ = s => [...document.querySelectorAll(s)];
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"}[c]));
const linkTimes = (html, did) => html.replace(/(\d+\.\d{2,3}) s\b/g, (m, x) => `<button class="ts" data-t="${x}"${did ? ` data-d="${did}"` : ""} title="Play this moment">${x} s ▶</button>`);
const fmt = (v, d = 2) => v == null || isNaN(v) ? "–" : (+v).toFixed(d);
const CAT = {nets_uncut:"Nets session", slowmo_action:"Slow-motion action", batter_pov:"Batter's view"};
const catName = c => CAT[c] || c, shortId = id => id.split("_").slice(-2).join(" ");
const STATUS = {auto:"Automatic", human_verified:"Verified", human_corrected:"Corrected", expert_gold:"Expert gold"};
const EVC = {run_up_start:"#2E8C8C", back_foot_contact:"#43A7C7", front_foot_contact:"#FFFFFF", ball_release:"#B2262B", ball_bounce:"#F2C230", bat_ball_contact:"#7A4FB5", followthrough_end:"#6B7C70", batter_trigger_start:"#D9739B", shot_followthrough_end:"#8A6BC9"};
const SHORT = {run_up_start:"Run-up", back_foot_contact:"Back foot", front_foot_contact:"Front foot", ball_release:"Release", ball_bounce:"Bounce", bat_ball_contact:"Bat", followthrough_end:"Follow-through", batter_trigger_start:"Trigger", shot_followthrough_end:"Shot end"};
if (!D) { document.querySelector("main").innerHTML = '<div class="empty-state">No data.js next to this page. Run python code/run_all.py, then reload.</div>'; throw new Error("no data"); }

const VSIZE = {S: 640, M: 960, L: 1280};
let vsize = "M";
try { const v = localStorage.getItem("foundry_vsize"); if (VSIZE[v]) vsize = v; } catch (e) {}
const ON_LIVE = [];          // sections that re-render once editing is confirmed
let batOverlay = true;
let LIVE = false, current = null, mode = "annotated", pending = [], zoom = true, pendingPlay = null, keepTime = null;
const store = (() => { try { return window.localStorage; } catch (e) { return null; } })();
$("#annot").value = (store && store.getItem("foundry_annotator")) || D.annotator_default || "";
const showRole = () => { const r = (D.people || {})[$("#annot").value.trim()]; $("#role").textContent = r ? r : "not registered"; };
$("#annot").oninput = () => { try { store && store.setItem("foundry_annotator", $("#annot").value.trim()); } catch (e) {} showRole(); };
showRole();
fetch("/api/ping").then(r => r.ok && r.json()).then(j => { if (j && j.ok) { LIVE = true; $("#mode").textContent = "Editing on"; $("#mode").classList.add("live"); if (current) show(current.delivery_id); ON_LIVE.forEach(f => f()); } }).catch(() => {});

$("#gen").textContent = `Generated ${D.generated_at}, pipeline ${D.pipeline_version}, ${O.ontology_version}`;
const S = D.summary, Q = S.qc || {};
$("#stages").innerHTML = [[S.videos,"Videos ingested"],[S.windows,"Delivery windows"],[S.deliveries,"Deliveries analysed"],
  [`${Q.pass||0}/${Q.warn||0}/${Q.fail||0}`,"QC pass, warn, fail"],[S.reviewed,"Reviewed by people"],[S.sft_pairs,"Training pairs"],
  [D.release ? D.release.release_kind.replace("_"," ") : "–","Dataset release"]].map(([b,s]) => `<li><b>${b}</b><span>${s}</span></li>`).join("");
function tab(v) {
  $$("nav button").forEach(x => x.setAttribute("aria-selected", x.dataset.v === v));
  $$(".view").forEach(x => x.classList.toggle("on", x.id === "v-" + v));
}
$$("nav button").forEach(b => b.onclick = () => { tab(b.dataset.v); history.replaceState(null, "", "#" + b.dataset.v + (current ? ":" + current.delivery_id : "")); });

/* ---------------- deliveries ---------------- */
const sftBy = {}; D.sft.forEach(r => (sftBy[r.delivery_id] ||= []).push(r));
const cats = [...new Set(D.deliveries.map(d => d.category))];
$("#f-cat").innerHTML = `<option value="">All video types</option>` + cats.map(c => `<option value="${c}">${catName(c)}</option>`).join("");
$("#f-st").innerHTML += O.vocab.annotation_status.map(s => `<option value="${s}">${STATUS[s] || s}</option>`).join("");
const byId = Object.fromEntries(D.deliveries.map(d => [d.delivery_id, d]));

function renderList() {
  const fc = $("#f-cat").value, fq = $("#f-qc").value, fs = $("#f-st").value;
  let items = D.deliveries.filter(d => (!fc || d.category === fc) && (!fq || d.qc.status === fq) && (!fs || d.annotation_status === fs));
  if ($("#f-sort").value === "priority") items = [...items].sort((a, b) => b.review.priority - a.review.priority);
  if (!items.length) { $("#list").innerHTML = '<div class="empty-state">No deliveries match these filters.</div>'; return; }
  $("#list").innerHTML = items.map(d => `<button class="item" data-id="${d.delivery_id}" aria-current="${current && current.delivery_id === d.delivery_id}">
    ${d.media.thumbnail ? `<img src="${d.media.thumbnail}" alt="" loading="lazy">` : `<div class="noimg"></div>`}
    <div><div class="id"><span class="dot ${d.qc.status}"></span>${shortId(d.delivery_id)}</div>
    <div class="meta">${catName(d.category)}${d.bowler?.bowling_arm ? `, ${d.bowler.bowling_arm}-arm` : ""}</div>
    <div class="meta"><span class="pill ${d.annotation_status}">${STATUS[d.annotation_status]}</span>${Object.keys(d.events).length} events</div></div></button>`).join("");
  $$("#list .item").forEach(b => b.onclick = () => show(b.dataset.id));
  if (!current || !items.find(d => d.delivery_id === current.delivery_id)) show(items[0].delivery_id);
}

function evState(e) { const p = e.provenance || {}; return p.review_state || "unreviewed"; }
function addPending(rec) {
  if (!LIVE) return;
  pending = pending.filter(p => !(p.delivery_id === rec.delivery_id && p.kind === rec.kind && p.field === rec.field && p.source_id === rec.source_id));
  pending.push(rec); updateSaveBar();
}
function updateSaveBar() {
  $("#savebar").classList.toggle("on", pending.length > 0);
  $("#pendN").textContent = `${pending.length} unsaved change${pending.length === 1 ? "" : "s"}`;
}
$("#discardBtn").onclick = () => { pending = []; updateSaveBar(); show(current.delivery_id); };
$("#saveBtn").onclick = async () => {
  const who = $("#annot").value.trim();
  $("#saveErr").textContent = "";
  if (!/^[A-Za-z0-9_.-]{2,40}$/.test(who)) { $("#saveErr").textContent = "Enter a reviewer ID (letters, digits, _ . -) in the header first."; $("#annot").focus(); return; }
  $("#saveBtn").disabled = true; $("#toast").textContent = "Saving…";
  try {
    let r = await fetch("/api/review", {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({records: pending.map(p => ({...p, annotator_id: who}))})});
    let j = await r.json(); if (!r.ok) throw new Error(j.error || "save failed");
    $("#toast").textContent = `Saved ${j.saved}. Rebuilding outputs…`;
    r = await fetch("/api/rebuild", {method: "POST", body: "{}"}); j = await r.json(); if (!r.ok) throw new Error(j.error || "rebuild failed");
    const active = ($$("nav button").find(b => b.getAttribute("aria-selected") === "true") || {dataset: {v: "deliveries"}}).dataset.v;
    location.hash = active + (current ? ":" + current.delivery_id : ""); location.reload();
  } catch (e) { $("#saveErr").textContent = e.message; $("#toast").textContent = ""; $("#saveBtn").disabled = false; }
};

function show(id) {
  current = byId[id]; if (!current) return;
  $$(".item").forEach(b => b.setAttribute("aria-current", b.dataset.id === id));
  history.replaceState(null, "", "#deliveries:" + id);
  const d = current, w = d.window, ev = {...d.events}, po = d.posture || {}, fps = w.fps;
  pending.filter(p => p.delivery_id === id && p.kind === "event").forEach(p => {
    if (p.value === null) delete ev[p.field]; else ev[p.field] = {...(ev[p.field] || {}), t_clip: p.value.t_clip, confidence: 1, provenance: {review_state: "corrected"}};
  });
  const dur = w.duration_video_s || (w.end_s - w.start_s);
  const src = mode === "annotated" && d.media.annotated ? d.media.annotated : d.media.clip;
  const order = O.events.filter(e => ev[e]).sort((a, b) => ev[a].t_clip - ev[b].t_clip);
  const tsc = w.time_scale || 1;
  let v0 = 0, v1 = dur;
  const anchor = ["back_foot_contact", "front_foot_contact", "ball_release"].find(k => ev[k]) || order[0];
  if (zoom && order.length) {
    v0 = Math.max(0, ev[anchor].t_clip - 0.5 * tsc); v1 = Math.min(dur, ev[order[order.length - 1]].t_clip + 0.4 * tsc);
    if (v1 - v0 < 1) { const c = (v0 + v1) / 2; v0 = Math.max(0, c - 0.5); v1 = Math.min(dur, c + 0.5); }
  }
  const P = t => 100 * (t - v0) / (v1 - v0), inView = t => t >= v0 - 1e-6 && t <= v1 + 1e-6;
  const span = v1 - v0, step = [0.05, 0.1, 0.2, 0.25, 0.5, 1, 2, 5].find(x => span / x <= 10) || 10;
  const dec = step >= 1 ? 0 : step >= 0.5 || step === 0.2 || step === 0.1 ? 1 : 2;
  const tickT = []; for (let t = Math.ceil(v0 / step - 1e-9) * step; t <= v1 + 1e-9; t += step) tickT.push(+t.toFixed(4));
  const ticks = tickT.map(t => `<i class="tick" style="left:${P(t)}%"></i>`).join("");
  const ruler = tickT.map(t => `<span style="left:${P(t)}%">${t.toFixed(dec)} s</span>`).join("");
  const PHC = ["#2E8C8C", "#43A7C7", "#5B7F3A", "#B2262B", "#C0901A", "#7A4FB5", "#6B7C70"];
  const PHN = {"run_up_start>back_foot_contact": "Run-up", "back_foot_contact>front_foot_contact": "Delivery stride",
    "front_foot_contact>ball_release": "Front foot to release", "ball_release>ball_bounce": "Ball flight",
    "ball_bounce>bat_ball_contact": "Bounce to bat", "ball_release>followthrough_end": "Follow-through",
    "back_foot_contact>ball_release": "Stride to release", "ball_release>bat_ball_contact": "Ball flight",
    "batter_trigger_start>bat_ball_contact": "Trigger to contact", "bat_ball_contact>shot_followthrough_end": "Shot follow-through",
    "batter_trigger_start>shot_followthrough_end": "Batter movement",
    "run_up_start>front_foot_contact": "Run-up and stride", "run_up_start>ball_release": "Approach to release"};
  const track = keys => { const ks = keys.filter(k => ev[k]); return ks.slice(1).map((k2, i) => { const k1 = ks[i], ta = ev[k1].t_clip, tb = ev[k2].t_clip;
      if (tb <= ta || tb < v0 || ta > v1) return "";
      const L = Math.max(0, P(ta)), R = Math.min(100, P(tb)), name = PHN[k1 + ">" + k2] || `${SHORT[k1]} to ${SHORT[k2]}`, ms = (tb - ta) / tsc * 1000;
      return `<button class="phase" data-a="${ta}" data-b="${tb}" style="left:${L}%;width:${Math.max(0.8, R - L)}%;background:${EVC[k1] === "#FFFFFF" ? "#5B7F3A" : EVC[k1]}" title="${name}: ${ta.toFixed(3)} to ${tb.toFixed(3)} s, ${ms.toFixed(0)} ms in real time. Click to play.">${name} ${ms.toFixed(0)} ms</button>`; }).join(""); };
  const bodyPh = track(["run_up_start", "back_foot_contact", "front_foot_contact", "ball_release", "followthrough_end"]);
  const ballPh = track(["ball_release", "ball_bounce", "bat_ball_contact"]);
  const batPh = track(["batter_trigger_start", "bat_ball_contact", "shot_followthrough_end"]);
  const phases = (bodyPh ? `<div class="phrow"><span>Bowler</span><div class="phases">${bodyPh}</div></div>` : "") +
                 (ballPh ? `<div class="phrow"><span>Ball</span><div class="phases">${ballPh}</div></div>` : "") +
                 (batPh ? `<div class="phrow"><span>Batter</span><div class="phases">${batPh}</div></div>` : "");
  const chips = order.map(k => `<button class="chip" data-play="${ev[k].t_clip}" title="Play around ${EN[k]}"><i style="background:${EVC[k]}"></i>${EN[k]} <b>${fmt(ev[k].t_clip, 3)} s</b> ▶</button>`).join("");
  const marks = order.filter(k => inView(ev[k].t_clip)).map((k, i) => `<button class="mark ${i % 2 ? "down" : "up"} ${LIVE ? "edit" : ""}" data-ev="${k}" style="left:${P(ev[k].t_clip)}%" title="${EN[k]} ${fmt(ev[k].t_clip)} s${LIVE ? " (drag to correct)" : ""}"><i style="background:${EVC[k]}"></i><span>${SHORT[k]}</span></button>`).join("");
  const evRows = O.events.map(k => { const e = ev[k];
    const st = e ? evState(e) : "";
    return `<tr><td>${EN[k]}</td><td>${e ? `<button class="ts" data-t="${e.t_clip}" title="Play this moment">${fmt(e.t_clip, 3)} s ▶</button>` : "–"}</td>
      <td>${e ? `<span class="bar"><i style="width:${100 * e.confidence}%"></i></span>${fmt(e.confidence)}` : ""}</td>
      <td><span class="state ${st}">${e ? st : "not found"}</span>${e && e.auto_t_clip != null ? `<div class="meta">auto ${fmt(e.auto_t_clip, 3)} s</div>` : ""}${e && e.alternatives ? `<div class="err">${Object.entries(e.alternatives).map(([a, t]) => `${esc(a)}: ${t == null ? "absent" : fmt(t, 3) + " s"}`).join("; ")}</div>` : ""}${e && e.audio_t_clip != null ? `<div class="meta">${e.from_sound ? "from" : "confirmed by"} bat sound at ${fmt(e.audio_t_clip, 3)} s</div>` : ""}</td>
      <td class="acts">${LIVE ? (e ? `<button class="btn small" data-set="${k}" title="Move this event to the current video frame">Set here</button> <button class="btn small" data-ok="${k}" title="The automatic time is right">Confirm</button> <button class="btn small" data-rm="${k}" title="This event does not happen in the clip">Remove</button>`
                       : `<button class="btn small" data-set="${k}" title="Add this event at the current video frame">Add here</button>`) : ""}</td></tr>`; }).join("");
  const POSN = {elbow_angle_release_deg:"Elbow at release", front_knee_angle_release_deg:"Front knee at release", front_knee_angle_ffc_deg:"Front knee at front-foot contact",
    trunk_tilt_release_deg:"Trunk tilt at release", wrist_height_release_torso:"Wrist height at release (torso)", stride_length_ffc_torso:"Stride length (torso)", front_leg:"Front leg"};
  const posRows = Object.entries(po).map(([k, v]) => { const deg = k.endsWith("_deg");
    const val = typeof v.value === "number" ? fmt(v.value, deg ? 0 : 2) + (deg ? "°" : "") : (v.value ?? "–");
    return `<tr><td>${POSN[k] || k}</td><td>${esc(val)}</td><td><span class="bar"><i style="width:${100 * (v.confidence || 0)}%"></i></span>${fmt(v.confidence)}</td><td class="state">${v.provenance?.source_type || ""}</td></tr>`; }).join("");
  const keys = Object.entries(d.media.keyframes || {}).map(([k, p]) => `<figure><img src="${p}" alt="${EN[k]}" data-t="${d.events[k]?.t_clip}"><figcaption title="Play this moment" style="cursor:pointer">${SHORT[k]}, ${fmt(d.events[k]?.t_clip)} s ▶</figcaption></figure>`).join("");
  const lab = d.labels || {};
  const labelInput = (field, vocab) => { const cur = lab[field]?.value || ""; const auto = lab[field]?.provenance?.source_type === "deterministic_rule";
    return `<label>${field.replace(/_/g, " ")}${auto ? " (from calibration)" : ""}<select data-label="${field}" ${LIVE ? "" : "disabled"}><option value="">–</option>${O.vocab[vocab].map(v => `<option ${v === cur ? "selected" : ""}>${v}</option>`).join("")}</select></label>`; };
  const groups = Object.entries(O.labels).map(([g, fields]) => `<h3>${{intent:"Intent (what was asked)", actual:"Actual (what happened)", context:"Context", review:"Coach override for the batter's expected shot"}[g] || g}</h3><div class="form">${Object.entries(fields).map(([f, v]) => labelInput(f, v)).join("")}${g === "context" ? ["bowler_id", "batter_id"].map(f => `<label>${f.replace("_", " ")}<input type="text" data-label="${f}" placeholder="P0023" value="${esc(lab[f]?.value || "")}" ${LIVE ? "" : "disabled"}></label>`).join("") : ""}</div>`).join("");
  const derived = O.labels.actual.actual_length ? "" : ["actual_length", "actual_line"].filter(k => lab[k]).map(k => `<span class="pill">${k.replace("_", " ")}: ${lab[k].value}</span>`).join("");
  const c = d.coach || {};
  const coachForm = `<div class="form">
    ${["observation", "evidence", "consequence", "correction"].map(f => `<label class="wide">${f[0].toUpperCase() + f.slice(1)}<textarea data-coach="${f}" ${LIVE ? "" : "disabled"} placeholder="${{observation:"Front leg braced through release.", evidence:"Knee angle barely changes after landing.", consequence:"Energy transfers into the ball.", correction:"Drive the non-bowling arm down harder."}[f]}">${esc(c[f] || "")}</textarea></label>`).join("")}
    <label>Confidence<select data-coach="confidence" ${LIVE ? "" : "disabled"}>${O.vocab.confidence.map(v => `<option ${v === (c.confidence || "medium") ? "selected" : ""}>${v}</option>`).join("")}</select></label>
    <label class="wide">Counterfactual question (optional)<input type="text" data-coach="cf_question" value="${esc(c.cf_question || "")}" placeholder="If this ball were 40 cm fuller, what would a coach expect?" ${LIVE ? "" : "disabled"}></label>
    <label class="wide">Counterfactual answer<textarea data-coach="cf_answer" ${LIVE ? "" : "disabled"}>${esc(c.cf_answer || "")}</textarea></label></div>
    ${c.provenance ? `<div class="meta">Saved by ${esc(c.provenance.created_by)}</div>` : ""}${LIVE ? `<button class="btn" id="coachBtn" style="margin-top:8px">Add coach note to changes</button><div class="err" id="coachErr"></div>` : ""}`;
  const pitch = d.measurements?.pitch, cal = d.calibration;
  const calNote = !cal ? "" : cal.status === "invalid" ? `<p class="err">${esc(cal.reason)}. Calibrate this delivery on its own frame.</p>`
    : cal.status === "transferred" ? `<p class="meta">Camera moved ${fmt(cal.shift_px, 0)} px since the calibration frame; crease points were moved to match.</p>`
    : cal.status === "same" ? `<p class="meta">Camera unchanged since the calibration frame.</p>` : "";
  const G = d.measurements?.ground || {};
  const groundInfo = (G.bowler_front_foot || G.batter_movement) ? `<h3>Feet on the pitch</h3><table>
      ${G.bowler_front_foot ? `<tr><td>Bowler's front foot (ankle) at landing</td><td>${G.bowler_front_foot.behind_popping_crease_cm >= 0 ? fmt(G.bowler_front_foot.behind_popping_crease_cm, 0) + " cm behind the popping crease" : `<span class="err">${fmt(-G.bowler_front_foot.behind_popping_crease_cm, 0)} cm beyond the crease</span>`}</td></tr>` : ""}
      ${G.bowler_stride_m != null ? `<tr><td>Bowler's stride at front-foot contact</td><td>${fmt(G.bowler_stride_m)} m</td></tr>` : ""}
      ${G.batter_movement ? `<tr><td>Batter's feet, trigger to contact</td><td>${fmt(G.batter_feet_move_m)} m towards the bowler: ${G.batter_movement.replace("_", " ")}</td></tr>` : ""}</table>
      <p class="meta">Ankle keypoints mapped to the pitch: allow about 15 cm.</p>` : "";
  const pitchInfo = cal && cal.status === "invalid" ? calNote : cal ? `<p class="meta">Calibration ${esc(cal.calibration_id)} (camera behind ${cal.camera_end}), by ${esc(cal.created_by)}.</p>${calNote}${groundInfo}` +
    (pitch ? `<table><tr><td>Bounce from batter's stumps</td><td>${fmt(pitch.bounce_m.length_from_batter_stumps_m)} m</td></tr><tr><td>Length</td><td>${pitch.actual_length || "–"}</td></tr>
      <tr><td>Line</td><td>${pitch.actual_line || "needs batter handedness"}</td></tr>${pitch.valid ? "" : `<tr><td colspan="2" class="err">Bounce falls outside the pitch: check the clicks or the bounce time.</td></tr>`}</table>`
      : `<p class="meta">No bounce pixel to measure: add or correct the bounce on a frame where the ball is tracked.</p>`) : `<p class="meta">Not calibrated. Only fixed-camera views can be calibrated.</p>`;
  const why = d.review.priority > 0 ? `<div class="why"><b>Why review this:</b> ${d.review.why_selected.map(esc).join("; ")}</div>` : "";
  const pairs = (sftBy[d.delivery_id] || []).map((r, i) => `<div class="qa"><div class="q">${esc(r.question)}</div><div class="a">${linkTimes(esc(r.answer))}</div>
    <span class="tag ${/expert|counterfactual/.test(r.answer_type) ? "expert" : ""}">${r.answer_type.replace(/_/g, " ")}</span><span class="tag ${r.confidence < 0.6 ? "low" : ""}">conf ${fmt(r.confidence)}</span><span class="tag">${r.provenance.review_state}</span>
    <button class="linkish" data-i="${i}">Show record</button><pre hidden id="rec-${i}"></pre></div>`).join("") || `<p class="note">No training pairs for this delivery.</p>`;
  const slow = w.time_scale > 1 ? `, slow motion ×${w.time_scale}${w.time_scale_verified ? "" : " (unverified)"}` : "";

  $("#detail").innerHTML = `
    <div style="display:flex;gap:12px;align-items:baseline;flex-wrap:wrap"><p class="title">${d.delivery_id}</p><span class="pill ${d.annotation_status}">${STATUS[d.annotation_status]}</span>
      ${LIVE ? `<button class="btn small" data-status="human_verified">Mark verified</button><button class="btn small" data-status="expert_gold">Mark expert gold</button>` : ""}</div>
    ${d.multiview ? `<div class="why">Multi-view: this is camera <b>${esc(d.multiview.camera_id)}</b> of <b>${d.multiview.mv_delivery_id}</b> (${d.multiview.n_views} views, one delivery). <button class="linkish" data-openmv="${d.multiview.mv_delivery_id}">Open all views</button></div>` : ""}
    <p class="sub" style="margin:2px 0 8px">${esc(d.title)}. Seconds ${fmt(w.start_s, 1)}–${fmt(w.end_s, 1)} of the source${slow}. ${d.review.annotators.length ? "Reviewed by " + d.review.annotators.map(esc).join(", ") + "." : ""}</p>
    ${why}
    <div class="viewer" style="--vw:${VSIZE[vsize]}px">
    <div class="player">${src ? `<div class="vwrap"><video id="vid" src="${src}" controls playsinline preload="metadata"></video><canvas id="ovl"></canvas></div>` : `<div class="empty">Clip not exported. Install ffmpeg and rerun with --force.</div>`}</div>
    <div class="controls">
      <div class="seg" role="group" aria-label="Video version"><button data-m="annotated" aria-pressed="${mode === "annotated"}">Annotated</button><button data-m="clip" aria-pressed="${mode === "clip"}">Original</button></div>
      <div class="seg" role="group" aria-label="Speed">${[0.1, 0.25, 0.5, 1].map(s => `<button data-s="${s}" aria-pressed="${s === 1}">${s}×</button>`).join("")}</div>
      <div class="seg" role="group" aria-label="Step"><button data-step="-1" aria-label="Previous frame">◀ frame</button><button data-step="1" aria-label="Next frame">frame ▶</button></div>
      <div class="seg" role="group" aria-label="Timeline range"><button data-zoom="1" aria-pressed="${zoom}">Action</button><button data-zoom="0" aria-pressed="${!zoom}">Whole clip</button></div>
      <div class="seg" role="group" aria-label="Video size">${Object.keys(VSIZE).map(k => `<button data-vsize="${k}" aria-pressed="${k === vsize}" title="Video width ${VSIZE[k]} px">${k}</button>`).join("")}</div>
      ${d.bat ? `<div class="seg" role="group" aria-label="Bat overlay"><button data-batov aria-pressed="${batOverlay}" title="${d.bat.source === "model" ? "Detected bat" : "Bat estimated from the hands"}">Bat line</button></div>` : ""}
      <span class="clock" id="clock">0.000 s, frame 0</span>
    </div>
    <div class="playinfo" id="playinfo">Click any timestamp, event or phase to play that moment slowly.</div>
    <div class="chips">${chips || '<span class="meta">No events detected.</span>'}</div>
    <div class="strip" id="strip" title="Click to jump; hover to read the time">${ticks}${marks}<div class="hovline" id="hovline"></div><div class="hov" id="hov"></div><div class="head" id="head" style="left:0;display:none"></div></div>
    <div class="ruler">${ruler}</div>
    ${phases}
    </div>
    ${reviewPointsHtml(d)}
    ${batHtml(d)}
    ${speechHtml(d)}
    ${LIVE ? `<p class="meta">Drag a marker, or pause on the right frame (use the frame buttons) and press "Set here". Changes stay unsaved until you press Save.</p>` : `<p class="meta">Read-only. Run <b>python code/serve.py</b> and open the page it prints to correct events, add labels and calibrate.</p>`}
    <div class="grid2">
      <div style="grid-column:1/-1;overflow-x:auto"><h2>Events (section 7.3)</h2><table><tr><th>Event</th><th>Clip time</th><th>Confidence</th><th>State</th><th></th></tr>${evRows}</table></div>
      <div><h2>Quality check</h2><div class="qc ${d.qc.status}"><b>${{pass:"Passed", warn:"Passed with warnings", fail:"Failed"}[d.qc.status]}</b>
        ${d.qc.reasons.length ? `<ul>${d.qc.reasons.map(r => `<li>${esc(r)}</li>`).join("")}</ul>` : ""}
        <div class="meta">Sharpness ${fmt(d.qc.sharpness, 0)}, brightness ${fmt(d.qc.mean_brightness, 0)}. Bowler in ${d.bowler?.frames_tracked ?? 0} of ${w.frames} frames, ball in ${d.ball?.points?.length ?? 0}.</div></div>
        <h2 style="margin-top:16px">Bowling wrist and front ankle</h2><canvas class="chart" id="chart" width="800" height="280" role="img" aria-label="Wrist height and ankle speed"></canvas>
        <div class="keys">${keys}</div></div>
    </div>
    <div class="grid2">
      <div><h2>Posture, 2D estimates</h2><table><tr><th>Measure</th><th>Value</th><th>Confidence</th><th>Source</th></tr>${posRows || `<tr><td colspan="4">Bowler not tracked</td></tr>`}</table></div>
      <div><h2>Pitch calibration (section 8.2)</h2>${pitchInfo}
        ${d.media.calib_frame ? `<div class="calib" id="calibBox"><img id="calibImg" src="${d.media.calib_frame}" alt="Frame for calibration"><canvas id="calibCv"></canvas></div>` : ""}
        ${LIVE && d.media.calib_frame ? `<div class="form" style="margin-top:8px"><label>Camera is behind the<select id="calEnd">${O.vocab.camera_end.map(v => `<option>${v}</option>`).join("")}</select></label>
          <label>Apply to<select id="calScope"><option value="source">every delivery of this video</option><option value="delivery">this delivery only</option></select></label></div>
          <p class="meta" id="calHelp"></p>
          <button class="btn" id="calSkip">Skip this point</button> <button class="btn" id="calUndo">Undo</button> <button class="btn" id="calReset">Clear points</button> <button class="btn" id="calAdd" disabled>Add calibration to changes</button>
          <p class="meta">Click what you can see and skip the rest. Length needs 4 points on the ground. For 3D with several cameras, also click the stump base and top: at least 6 points including one stump top.</p>` : ""}
      </div>
    </div>
    <h2 style="margin-top:22px" id="labels">Cricket labels (sections 7.2 and 8.1)</h2>${groups}${derived}
    ${LIVE ? `<button class="btn" id="labelBtn" style="margin-top:10px">Add label changes</button>` : ""}
    <h2 style="margin-top:22px">Coach notes (section 7.5)</h2><p class="note">Kept apart from measurements. Becomes expert_interpretation, expert_advice and counterfactual training pairs.</p>${coachForm}
    <h2 style="margin-top:22px">Training pairs for this delivery</h2>${pairs}`;

  const vid = $("#vid"), strip = $("#strip");
  let stopAt = null, returnTo = null;
  const setRate = r => { if (vid) vid.playbackRate = r; $$("#detail [data-s]").forEach(x => x.setAttribute("aria-pressed", +x.dataset.s === r)); };
  const drawBat = t => { const c = $("#ovl"); if (!c || !vid) return; const x = c.getContext("2d");
    c.width = c.clientWidth; c.height = c.clientHeight; x.clearRect(0, 0, c.width, c.height);
    const S = d.bat && d.bat.series; if (!batOverlay || !S || !vid.videoWidth) return;
    let i = 0, best = 1e9; S.t_clip.forEach((tt, j) => { const dd = Math.abs(tt - t); if (dd < best) { best = dd; i = j; } });
    if (best > 0.08 * (w.time_scale || 1)) return;
    const sc = Math.min(c.width / vid.videoWidth, c.height / vid.videoHeight), ox = (c.width - vid.videoWidth * sc) / 2, oy = (c.height - vid.videoHeight * sc) / 2;
    const P_ = p => [ox + p[0] * sc, oy + p[1] * sc], h = P_(S.handle[i]), tp = P_(S.toe[i]);
    x.lineCap = "round"; x.strokeStyle = d.bat.source === "model" ? "#62E07A" : "rgba(242,194,48,.9)"; x.lineWidth = 6;
    if (d.bat.source !== "model") x.setLineDash([10, 6]);
    x.beginPath(); x.moveTo(...h); x.lineTo(...tp); x.stroke(); x.setLineDash([]);
    x.fillStyle = "#fff"; x.beginPath(); x.arc(...h, 4, 0, 7); x.fill(); };
  const setClock = () => { if (!vid) return; const t = vid.currentTime; drawBat(t);
    $("#clock").textContent = `${t.toFixed(3)} s, frame ${Math.round(t * fps)}`;
    const h = $("#head"); h.style.display = inView(t) ? "" : "none"; h.style.left = `${P(t)}%`; drawChart(d, t);
    if (stopAt != null && t >= stopAt - 1e-3) { vid.pause(); stopAt = null;
      if (returnTo != null) { vid.currentTime = returnTo; returnTo = null; }
      $("#playinfo").textContent += ". Done: paused on the moment (use the frame buttons to step)."; } };
  const playSegment = (a, b, rate, back) => { if (!vid) return; a = Math.max(0, a); b = Math.min(dur, b);
    stopAt = b; returnTo = back ?? null; setRate(rate); vid.currentTime = a; vid.play().catch(() => {});
    $("#playinfo").textContent = `Playing ${a.toFixed(2)}–${b.toFixed(2)} s at ${rate}×`; };
  const playAround = t => playSegment(t - 0.4 * tsc, t + 0.4 * tsc, 0.25, t);
  if (vid) {
    let raf = null;
    const tick = () => { setClock(); raf = vid.paused ? null : requestAnimationFrame(tick); };
    vid.onplay = () => { if (!raf) raf = requestAnimationFrame(tick); };
    vid.ontimeupdate = setClock; vid.onseeked = setClock;
    const ready = () => { if (keepTime != null) { vid.currentTime = keepTime; keepTime = null; }
      if (pendingPlay != null) { const t = pendingPlay; pendingPlay = null; playAround(t); } };
    vid.readyState >= 1 ? ready() : vid.addEventListener("loadedmetadata", ready, {once: true});
  }
  $$("#detail [data-m]").forEach(b => b.onclick = () => { keepTime = vid ? vid.currentTime : null; mode = b.dataset.m; show(id); });
  $$("#detail [data-zoom]").forEach(b => b.onclick = () => { keepTime = vid ? vid.currentTime : null; zoom = b.dataset.zoom === "1"; show(id); });
  $$("#detail [data-s]").forEach(b => b.onclick = () => setRate(+b.dataset.s));
  $$("#detail [data-openmv]").forEach(b => b.onclick = () => { tab("mv"); window.MV_OPEN && window.MV_OPEN(b.dataset.openmv); window.scrollTo(0, 0); });
  $$("#detail [data-batov]").forEach(b => b.onclick = () => { batOverlay = !batOverlay; b.setAttribute("aria-pressed", batOverlay); drawBat(vid ? vid.currentTime : 0); });
  $$("#detail [data-vsize]").forEach(b => b.onclick = () => { vsize = b.dataset.vsize; try { localStorage.setItem("foundry_vsize", vsize); } catch (e) {}
    $("#detail .viewer").style.setProperty("--vw", VSIZE[vsize] + "px"); $$("#detail [data-vsize]").forEach(x => x.setAttribute("aria-pressed", x === b)); });
  $$("#detail .ts, #detail [data-play]").forEach(b => b.onclick = () => playAround(+(b.dataset.t ?? b.dataset.play)));
  const playFrom = (t, e) => { if (!vid) return; stopAt = e ?? null; returnTo = null; setRate(1); vid.currentTime = Math.max(0, t); vid.play().catch(() => {});
    $("#playinfo").textContent = `Playing speech from ${t.toFixed(2)} s at 1× (sound on)`; };
  $$("#detail .w").forEach(w => w.onclick = () => playFrom(+w.dataset.t - 0.15, +w.dataset.e + 0.25));
  $$("#detail [data-seg]").forEach(b => b.onclick = () => playFrom(+b.dataset.seg, +b.dataset.end));
  $$("#detail .phase").forEach(b => b.onclick = () => playSegment(+b.dataset.a - 0.1 * tsc, +b.dataset.b + 0.1 * tsc, 0.25, +b.dataset.b));
  const tAt = x => { const r = strip.getBoundingClientRect(); return Math.max(v0, Math.min(v1, v0 + (v1 - v0) * (x - r.left) / r.width)); };
  strip.onmousemove = e => { const t = tAt(e.clientX), hv = $("#hov"), hl = $("#hovline");
    hv.style.display = hl.style.display = "block"; hv.style.left = hl.style.left = `${P(t)}%`;
    hv.textContent = `${t.toFixed(3)} s, frame ${Math.round(t * fps)}`; };
  strip.onmouseleave = () => { $("#hov").style.display = $("#hovline").style.display = "none"; };
  $$("#detail [data-step]").forEach(b => b.onclick = () => { if (!vid) return; vid.pause(); vid.currentTime = Math.max(0, Math.min(dur, (Math.round(vid.currentTime * fps) + +b.dataset.step) / fps + 1e-4)); });
  const seek = t => { if (vid && !isNaN(t)) { vid.pause(); vid.currentTime = t; } };
  strip.onclick = e => { if (e.target.closest(".mark")) return; seek(Math.round(tAt(e.clientX) * fps) / fps); };
  $$("#detail .keys img, #detail .keys figcaption").forEach(m => m.onclick = () => playAround(+(m.dataset.t ?? m.previousElementSibling.dataset.t)));
  $$("#detail .mark").forEach(m => {
    m.onclick = () => playAround(ev[m.dataset.ev].t_clip);
    if (!LIVE) return;
    m.onpointerdown = e => { e.preventDefault(); m.setPointerCapture(e.pointerId); m.classList.add("dragging"); let moved = false, t = ev[m.dataset.ev].t_clip;
      m.onpointermove = e2 => { moved = true; t = Math.round(tAt(e2.clientX) * fps) / fps; m.style.left = `${P(t)}%`; seek(t); };
      m.onpointerup = () => { m.classList.remove("dragging"); m.onpointermove = m.onpointerup = null; if (moved) { keepTime = t; addPending({kind: "event", delivery_id: id, field: m.dataset.ev, value: {t_clip: +t.toFixed(3)}}); show(id); } else playAround(ev[m.dataset.ev].t_clip); };
    };
  });
  const playhead = () => vid ? Math.round(vid.currentTime * fps) / fps : 0;
  $$("#detail [data-set]").forEach(b => b.onclick = () => { const t = playhead(); keepTime = t; addPending({kind: "event", delivery_id: id, field: b.dataset.set, value: {t_clip: +t.toFixed(3)}}); show(id); });
  $$("#detail [data-ok]").forEach(b => b.onclick = () => { addPending({kind: "event_verify", delivery_id: id, field: b.dataset.ok, value: true}); b.textContent = "Confirmed"; b.disabled = true; });
  $$("#detail [data-rm]").forEach(b => b.onclick = () => { addPending({kind: "event", delivery_id: id, field: b.dataset.rm, value: null}); show(id); });
  $$("#detail [data-status]").forEach(b => b.onclick = () => { addPending({kind: "status", delivery_id: id, field: "annotation_status", value: b.dataset.status}); b.textContent = "Added"; });
  const lb = $("#labelBtn"); if (lb) lb.onclick = () => { let n = 0;
    $$("#detail [data-label]").forEach(el => { const f = el.dataset.label, v = el.value.trim(), cur = (lab[f] && lab[f].provenance?.source_type !== "deterministic_rule") ? lab[f].value : "";
      if (v !== (cur || "")) { addPending({kind: "label", delivery_id: id, field: f, value: v || null}); n++; } });
    lb.textContent = n ? `${n} label change${n > 1 ? "s" : ""} added` : "No label changes"; };
  const cb = $("#coachBtn"); if (cb) cb.onclick = () => { const v = {}; $$("#detail [data-coach]").forEach(el => v[el.dataset.coach] = el.value.trim());
    if (!v.observation) { $("#coachErr").textContent = "Write at least an observation."; return; }
    $("#coachErr").textContent = ""; addPending({kind: "coach", delivery_id: id, field: "note", value: v}); cb.textContent = "Coach note added"; };
  $$("#detail .linkish").forEach(b => b.onclick = () => { const pre = $("#rec-" + b.dataset.i); pre.hidden = !pre.hidden; pre.textContent = JSON.stringify(sftBy[id][+b.dataset.i], null, 2); b.textContent = pre.hidden ? "Show record" : "Hide record"; });
  setupCalib(d); drawChart(d, 0);
}

const CAL_POINTS = [
  ["bowler_left", "Bowler end: popping crease meets the return crease on the LEFT (as seen in the image)"],
  ["bowler_right", "Bowler end: popping crease meets the return crease on the RIGHT"],
  ["batter_left", "Batter end: popping crease meets the return crease on the LEFT"],
  ["batter_right", "Batter end: popping crease meets the return crease on the RIGHT"],
  ["bowler_bc_left", "Bowler end: stump line (bowling crease) meets the return crease on the LEFT"],
  ["bowler_bc_right", "Bowler end: stump line meets the return crease on the RIGHT"],
  ["batter_bc_left", "Batter end: stump line meets the return crease on the LEFT"],
  ["batter_bc_right", "Batter end: stump line meets the return crease on the RIGHT"],
  ["bowler_stump_base", "Bowler end: bottom of the middle stump"],
  ["bowler_stump_top", "Bowler end: top of the middle stump (71.1 cm)"],
  ["batter_stump_base", "Batter end: bottom of the middle stump"],
  ["batter_stump_top", "Batter end: top of the middle stump (71.1 cm)"]];
function setupCalib(d) {
  const img = $("#calibImg"), cv = $("#calibCv"); if (!img || !cv) return;
  const [W, H] = d.media.calib_frame_size || [img.naturalWidth, img.naturalHeight];
  let named = {}, step = 0, dirty = false, hist = [];
  const pend = pending.find(p => p.kind === "calibration" && (p.delivery_id === d.delivery_id || p.source_id === d.source_id));
  const src = pend ? pend.value : d.calibration;
  if (src) { (src.points_px || []).forEach((p, i) => { if (p) named[CAL_POINTS[i][0]] = [...p]; });
    Object.entries(src.named_px || {}).forEach(([k, p]) => named[k] = [...p]); step = CAL_POINTS.length; }
  const ground = () => Object.keys(named).filter(k => !k.endsWith("_top")).length;
  const draw = () => { cv.width = img.clientWidth; cv.height = img.clientHeight; const x = cv.getContext("2d"), sx = cv.width / W, sy = cv.height / H;
    x.clearRect(0, 0, cv.width, cv.height); x.lineWidth = 2; x.strokeStyle = "#F2C230"; x.fillStyle = "#F2C230"; x.font = "bold 13px sans-serif";
    const q = ["bowler_left", "bowler_right", "batter_right", "batter_left"].map(k => named[k]);
    if (q.every(Boolean)) { x.beginPath(); q.forEach((p, i) => i ? x.lineTo(p[0] * sx, p[1] * sy) : x.moveTo(p[0] * sx, p[1] * sy)); x.closePath(); x.stroke(); }
    CAL_POINTS.forEach(([k], i) => { const p = named[k]; if (!p) return; x.beginPath(); x.arc(p[0] * sx, p[1] * sy, 5, 0, 7); x.fill(); x.fillText(String(i + 1), p[0] * sx + 7, p[1] * sy - 7); });
    const bp = d.events.ball_bounce?.xy_px; if (bp) { x.strokeStyle = "#B2262B"; x.beginPath(); x.arc(bp[0] * sx, bp[1] * sy, 8, 0, 7); x.stroke(); }
    const add = $("#calAdd"); if (add) add.disabled = !(dirty && ground() >= 4);
    const help = $("#calHelp"); if (help) help.textContent = step < CAL_POINTS.length ? `Point ${step + 1} of ${CAL_POINTS.length}: ${CAL_POINTS[step][1]}.` : `${Object.keys(named).length} points placed (${ground()} on the ground).`; };
  img.complete ? draw() : img.onload = draw;
  if (window.ResizeObserver) new ResizeObserver(draw).observe(img);
  if (!LIVE) return;
  if (!src) step = 0;
  cv.onclick = e => { if (step >= CAL_POINTS.length) return; dirty = true; const r = cv.getBoundingClientRect();
    named[CAL_POINTS[step][0]] = [Math.round((e.clientX - r.left) * W / r.width), Math.round((e.clientY - r.top) * H / r.height)]; hist.push(step); step++; draw(); };
  $("#calSkip").onclick = () => { if (step < CAL_POINTS.length) { hist.push(step); delete named[CAL_POINTS[step][0]]; step++; dirty = true; draw(); } };
  $("#calUndo").onclick = () => { if (hist.length) { step = hist.pop(); delete named[CAL_POINTS[step][0]]; draw(); } };
  $("#calReset").onclick = () => { named = {}; step = 0; hist = []; dirty = true; draw(); };
  $("#calAdd").onclick = () => { const scope = $("#calScope").value;
    const four = ["bowler_left", "bowler_right", "batter_left", "batter_right"];
    const value = {named_px: named, camera_end: $("#calEnd").value, frame_size: [W, H], ref_delivery_id: d.delivery_id};
    if (four.every(k => named[k])) value.points_px = four.map(k => named[k]);
    const rec = {kind: "calibration", value};
    if (scope === "source") rec.source_id = d.source_id; else rec.delivery_id = d.delivery_id;
    rec.field = "pitch"; addPending(rec); $("#calAdd").textContent = "Calibration added"; };
}

function drawChart(d, now) {
  const c = $("#chart"); if (!c) return;
  const x = c.getContext("2d"), W = c.width, H = c.height, s = d.series || {}, css = getComputedStyle(document.documentElement), col = v => css.getPropertyValue(v).trim();
  x.clearRect(0, 0, W, H); const t = s.t_clip || [], dur = d.window.duration_video_s || 1; x.font = "20px sans-serif";
  if (!t.length) { x.fillStyle = col("--muted"); x.fillText("Bowler not tracked in this clip", 20, 40); return; }
  const X = v => 40 + (W - 60) * v / dur;
  const line = (arr, lo, hi, color, dash) => { x.strokeStyle = color; x.lineWidth = 3; x.setLineDash(dash || []); x.beginPath(); let pen = false;
    arr.forEach((v, i) => { if (v == null) { pen = false; return; } const y = H - 34 - (H - 54) * (Math.max(lo, Math.min(hi, v)) - lo) / (hi - lo); pen ? x.lineTo(X(t[i]), y) : x.moveTo(X(t[i]), y); pen = true; });
    x.stroke(); x.setLineDash([]); };
  line(s.front_ankle_speed || [], 0, 20, col("--muted"), [6, 6]); line(s.wrist_height || [], -1.5, 1.8, col("--field"));
  Object.entries(d.events || {}).forEach(([k, e]) => { x.strokeStyle = EVC[k] === "#FFFFFF" ? col("--ink") : EVC[k]; x.lineWidth = 2; x.beginPath(); x.moveTo(X(e.t_clip), 10); x.lineTo(X(e.t_clip), H - 34); x.stroke(); });
  x.fillStyle = col("--ink"); x.fillRect(X(now) - 1, 10, 2, H - 44); x.fillStyle = col("--muted"); x.fillText("Solid: wrist height. Dashed: front-ankle speed.", 44, H - 8);
}
["#f-cat", "#f-qc", "#f-st", "#f-sort"].forEach(s => $(s).onchange = renderList);

/* ---------------- review queue ---------------- */
$("#q-rows").innerHTML = [...D.deliveries].sort((a, b) => b.review.priority - a.review.priority).map(d => `<tr><td>${shortId(d.delivery_id)}</td><td>${catName(d.category)}</td>
  <td><span class="bar"><i style="width:${Math.min(100, 100 * d.review.priority)}%"></i></span>${fmt(d.review.priority)}</td><td>${d.review.why_selected.map(esc).join("; ")}</td>
  <td><span class="pill ${d.annotation_status}">${STATUS[d.annotation_status]}</span></td><td><button class="btn small" data-open="${d.delivery_id}">Review</button></td></tr>`).join("") || `<tr><td colspan="6">No deliveries yet.</td></tr>`;
$$("[data-open]").forEach(b => b.onclick = () => { tab("deliveries"); show(b.dataset.open); window.scrollTo(0, 0); });

/* ---------------- dashboard ---------------- */
(function dash() {
  const ds = D.deliveries, n = ds.length || 1;
  const hb = (label, v, total, txt) => `<div class="hbar"><span>${label}</span><div class="track"><i style="width:${total ? 100 * v / total : 0}%"></i></div><span>${txt ?? v}</span></div>`;
  const evRate = O.events.map(e => { const have = ds.filter(d => d.events[e]); const conf = have.length ? have.reduce((a, d) => a + d.events[e].confidence, 0) / have.length : 0;
    return hb(EN[e], have.length, n, `${Math.round(100 * have.length / n)}%, conf ${fmt(conf)}`); }).join("");
  const corr = O.events.map(e => { const c = ds.filter(d => d.events[e]?.auto_t_clip != null); const ms = c.length ? c.reduce((a, d) => a + d.events[e].correction_ms_real, 0) / c.length : 0;
    const removed = ds.filter(d => d.removed_events && d.removed_events[e]).length;
    return `<tr><td>${EN[e]}</td><td>${c.length}</td><td>${c.length ? fmt(ms, 0) + " ms" : "–"}</td><td>${removed}</td></tr>`; }).join("");
  const qcBy = cats.map(c => { const g = ds.filter(d => d.category === c); const k = s => g.filter(d => d.qc.status === s).length;
    return `<tr><td>${catName(c)}</td><td>${g.length}</td><td>${k("pass")}</td><td>${k("warn")}</td><td>${k("fail")}</td></tr>`; }).join("");
  const st = O.vocab.annotation_status.map(s => hb(STATUS[s], ds.filter(d => d.annotation_status === s).length, n)).join("");
  const at = {}; D.sft.forEach(r => at[r.answer_type] = (at[r.answer_type] || 0) + 1);
  const atb = Object.entries(at).sort((a, b) => b[1] - a[1]).map(([k, v]) => hb(k.replace(/_/g, " "), v, D.sft.length)).join("");
  const arm = {}; ds.forEach(d => { const a = d.bowler?.bowling_arm || "unknown"; arm[a] = (arm[a] || 0) + 1; });
  const sch = D.schema || {};
  $("#dash").innerHTML = `<div class="card"><h2>Event detection</h2><p class="meta">Share of deliveries where each event was found, and mean confidence.</p>${evRate}</div>
    <div class="card"><h2>Review progress</h2>${st}<h3>Human corrections by event</h3><table><tr><th>Event</th><th>Corrected</th><th>Mean shift (real time)</th><th>Removed</th></tr>${corr}</table></div>
    <div class="card"><h2>Capture QC by video type</h2><table><tr><th>Type</th><th>Total</th><th>Pass</th><th>Warn</th><th>Fail</th></tr>${qcBy}</table>
      <h3>Bowling arm</h3>${Object.entries(arm).map(([k, v]) => hb(k, v, n)).join("")}</div>
    <div class="card"><h2>Training pairs by answer type</h2>${atb || "<p class='meta'>None yet.</p>"}
      <h3>Tier-1 table</h3><p class="meta">Schema ${sch.passed ? "valid" : (sch.n_errors || 0) + " errors"}; expected fields ${Math.round(100 * (sch.tier1_completeness || 0))}% complete.</p>
      ${(sch.errors || []).slice(0, 5).map(e => `<div class="err">${esc(e)}</div>`).join("")}</div>
    ${qualityCards()}
    <div class="card"><h2>Recent edits</h2>${(D.recent_edits || []).slice(0, 12).map(r => `<div class="meta">${esc(r.created_at.slice(0, 16).replace("T", " "))} ${esc(r.annotator_id)}: ${r.kind} ${esc(r.field || "")} ${r.delivery_id ? shortId(r.delivery_id) : esc(r.source_id || "")}</div>`).join("") || "<p class='meta'>No edits yet.</p>"}</div>`;
})();

function qualityCards() {
  const E = D.evaluation; if (!E) return "";
  const tm = Object.entries(E.timing).filter(([, v]) => v.reviewed).map(([k, v]) => `<tr><td>${EN[k]}</td><td>${v.scored}</td><td>${v.mae_ms ?? "–"}</td><td>${v.within_1_frame == null ? "–" : Math.round(100 * v.within_1_frame) + "%"}</td><td>${v.missed}</td><td>${v.false_positive}</td></tr>`).join("");
  const ag = Object.entries(E.agreement.labels).map(([k, v]) => `<tr><td>${k.replace(/_/g, " ")}</td><td>${v.pairs}</td><td>${Math.round(100 * v.percent_agree)}%</td><td class="${v.low_agreement ? "err" : ""}">${v.kappa ?? "–"}</td></tr>`).join("")
    + Object.entries(E.agreement.events).map(([k, v]) => `<tr><td>${EN[k] || k}</td><td>${v.pairs}</td><td colspan="2">mean difference ${v.mean_diff_ms} ms</td></tr>`).join("");
  const dims = Object.keys(E.slices);
  const sl = dim => `<table><tr><th>${dim.replace(/_/g, " ")}</th><th>n</th><th>QC pass</th><th>Front foot</th><th>Bounce</th><th>Bat</th><th>Release conf.</th><th>Corrections</th></tr>${Object.entries(E.slices[dim]).map(([g, r]) =>
    `<tr><td>${esc(catName(g))}</td><td>${r.n}</td><td>${Math.round(100 * r.qc_pass)}%</td><td>${Math.round(100 * r.has_front_foot_contact)}%</td><td>${Math.round(100 * r.has_ball_bounce)}%</td><td>${Math.round(100 * r.has_bat_ball_contact)}%</td><td>${fmt(r.mean_release_conf)}</td><td>${r.corrected_events}</td></tr>`).join("")}</table>`;
  const bd = E.ball_detector;
  const bdt = bd ? `<table><tr><th>Model</th><th>Recall</th><th>Precision</th><th>Centre error</th></tr>${["stock_coco", "finetuned"].filter(k => bd[k]).map(k => `<tr><td>${k.replace("_", " ")}</td><td>${Math.round(100 * bd[k].recall)}%</td><td>${Math.round(100 * bd[k].precision)}%</td><td>${bd[k].mean_center_error_px ?? "–"} px</td></tr>`).join("")}</table><p class="meta">${bd.frames} held-out labelled frames, ${bd.with_ball} with the ball visible.</p>`
    : `<p class="meta">Not evaluated yet. Label frames in the Ball labels tab, then run python code/train_ball.py export, train and eval.</p>`;
  return `<div class="card"><h2>Event timing accuracy (section 12)</h2><p class="meta">Reviewer-confirmed or corrected events are the reference. ${E.reviewed_deliveries} deliveries reviewed, ${E.gold_deliveries} expert gold.</p>
      ${tm ? `<table><tr><th>Event</th><th>Scored</th><th>Mean error (ms, real)</th><th>Within 1 frame</th><th>Missed</th><th>False</th></tr>${tm}</table>` : `<p class="meta">No reviewed events yet. Confirm or correct events in the Deliveries tab.</p>`}</div>
    <div class="card"><h2>Reviewer agreement</h2><p class="meta">Needs two reviewers on the same deliveries. Kappa below 0.6 means the label definition needs work (section 8). Reviewers so far: ${E.agreement.reviewers.map(esc).join(", ") || "none"}.</p>
      ${ag ? `<table><tr><th>Field</th><th>Pairs</th><th>Agree</th><th>Kappa</th></tr>${ag}</table>` : `<p class="meta">No double-reviewed fields yet.</p>`}</div>
    <div class="card" style="grid-column:span 2;min-width:0"><h2>Error by slice (section 9.2)</h2><div class="seg" role="group" aria-label="Slice">${dims.map((k, i) => `<button data-slice="${k}" aria-pressed="${i === 0}">${k.replace(/_/g, " ")}</button>`).join("")}</div><div id="sliceTbl" style="margin-top:8px;overflow-x:auto">${sl(dims[0])}</div></div>
    <div class="card"><h2>Ball detector</h2>${bdt}</div>`;
}
document.addEventListener("click", e => { const b = e.target.closest("[data-slice]"); if (!b || !D.evaluation) return;
  $$("[data-slice]").forEach(x => x.setAttribute("aria-pressed", x === b));
  const dim = b.dataset.slice, E = D.evaluation;
  $("#sliceTbl").innerHTML = `<table><tr><th>${dim.replace(/_/g, " ")}</th><th>n</th><th>QC pass</th><th>Front foot</th><th>Bounce</th><th>Bat</th><th>Release conf.</th><th>Corrections</th></tr>${Object.entries(E.slices[dim]).map(([g, r]) =>
    `<tr><td>${esc(catName(g))}</td><td>${r.n}</td><td>${Math.round(100 * r.qc_pass)}%</td><td>${Math.round(100 * r.has_front_foot_contact)}%</td><td>${Math.round(100 * r.has_ball_bounce)}%</td><td>${Math.round(100 * r.has_bat_ball_contact)}%</td><td>${fmt(r.mean_release_conf)}</td><td>${r.corrected_events}</td></tr>`).join("")}</table>`; });

/* ---------------- review points (expected vs performed) ---------------- */
function reviewPointsHtml(d) {
  const R = d.review_points; if (!R) return "";
  const V = {match: "✓ as expected", mismatch: "✗ not as expected", needs_label: "needs label", not_measured: "not measured", measured: "measured"};
  const card = (title, sub, rows, sum) => `<div class="card"><h2>${title}</h2><p class="meta">${sub}<br>${sum.match} as expected, ${sum.mismatch} not, ${sum.open} open.</p>
    <table><tr><th>Aspect</th><th>Expected action</th><th>Performed action</th><th></th></tr>${rows.map(r => `<tr><td><b>${esc(r.aspect)}</b></td>
      <td>${esc(r.expected ?? "–")}${r.expected_from ? `<div class="meta">${esc(r.expected_from)}</div>` : ""}</td>
      <td>${esc(r.performed ?? "–")}${r.performed_from ? `<div class="meta">${esc(r.performed_from)}</div>` : ""}</td>
      <td><span class="vd ${r.status}">${V[r.status]}</span>${r.note ? `<div class="meta">${esc(r.note)}</div>` : ""}</td></tr>`).join("")}</table></div>`;
  return `<div class="rp">${card("Bowler's review point", "Expected = the instruction. Performed = what was measured or labelled.", R.bowler, R.bowler_summary)}
    ${card("Batter's review point", "Expected = the recommended response to this delivery as bowled (provisional coaching rules, or a coach override). Performed = what the batter did.", R.batter, R.batter_summary)}</div>
    <p class="meta">Fill gaps in <a href="#labels" class="linkish">Cricket labels</a> (intent, shot type, contact, line and length) or calibrate the pitch.</p>`;
}

/* ---------------- transcribed speech in a delivery (optional) ---------------- */
function batHtml(d) {
  const b = d.bat; if (!b) return "";
  const est = b.source !== "model";
  const law = (D.equipment || {}).bat_law5_limits || {};
  const row = (k, v) => `<tr><td>${k}</td><td>${v}</td></tr>`;
  return `<div class="card" style="margin-top:18px"><h2>Bat (section 7.4)</h2>
    <p class="meta">${est ? "Estimated from the batter's hands and forearms with a standard bat length (no bat detector yet). Good for timing; angles are rough. The dashed yellow line on the video shows it." : "Detected by the bat keypoint model (green line on the video)."}
      Bat used for scaling: ${esc(b.bat_size)}, ${b.bat_length_cm} cm. Confidence ${fmt(b.confidence)}.</p>
    <table>${b.backlift_top ? row("Top of backlift", `<button class="ts" data-t="${b.backlift_top.t_clip}">${fmt(b.backlift_top.t_clip, 2)} s ▶</button> bat ${fmt(b.backlift_top.angle_deg, 0)}° from hanging down, toe ${fmt(b.backlift_top.height_torso, 2)} torso lengths above the hands`) : ""}
      ${b.peak_swing ? row("Fastest downswing", `<button class="ts" data-t="${b.peak_swing.t_clip}">${fmt(b.peak_swing.t_clip, 2)} s ▶</button> about ${fmt(b.peak_swing.angular_speed_deg_s, 0)}°/s in this view`) : ""}
      ${b.at_contact ? row("At bat contact", `<button class="ts" data-t="${b.at_contact.t_clip}">${fmt(b.at_contact.t_clip, 2)} s ▶</button> bat ${fmt(b.at_contact.angle_deg, 0)}° from vertical`) : ""}</table>
    <p class="meta" style="margin-top:8px">Law 5 limits: length ≤ ${law.overall_length_cm ?? "–"} cm, blade width ≤ ${law.blade_width_cm ?? "–"} cm, depth ≤ ${law.blade_depth_cm ?? "–"} cm, edge ≤ ${law.edge_thickness_cm ?? "–"} cm, handle ≤ ${Math.round(100 * (law.handle_max_fraction || 0))}% of length. Set each player's bat size in code/registry/equipment.yaml.
      To replace the estimate with a detector, click bats in the Bat labels tab, then run python code/train_bat.py.</p></div>`;
}

function speechHtml(d) {
  const sp = d.speech; if (!sp) return "";
  const words = x => x.words && x.words.length ? x.words.map(w => `<span class="w" data-t="${w.t}" data-e="${w.e}" title="${fmt(w.t, 2)} s">${esc(w.w)}</span>`).join(" ") : esc(x.text);
  return `<div class="speechcard"><h2>Speech in this clip (transcribed)</h2><p class="meta">Automatic transcript (${esc(sp.provenance.source_version || "")}); treat as unreviewed. Click a word to hear it.</p>
    ${sp.segments.map(x => `<div class="seg-line"><button class="ts" data-seg="${x.t_clip_start}" data-end="${x.t_clip_end}">${fmt(x.t_clip_start, 2)} s ▶</button> ${words(x)}</div>`).join("")}</div>`;
}

/* ---------------- multi-view ---------------- */
(function mvTab() {
  const M = D.multiview || [];
  if (!M.length) { $("#mvTab").innerHTML = `<div class="empty-state">No multi-view sessions. List the videos that film the same session under multiview.sessions in code/config.yaml (see README), calibrate each camera, then rerun.</div>`; return; }
  let cur = M[0], T = 0, playing = false, rate = 0.25, raf = null;
  const EVO = ["run_up_start", "back_foot_contact", "front_foot_contact", "ball_release", "followthrough_end", "ball_bounce", "batter_trigger_start", "bat_ball_contact", "shot_followthrough_end"];
  function render() {
    const r = cur, b = r.ball_3d, p = r.bowler_3d_release, pf = r.bowler_3d_ffc, cams = r.cameras || {};
    const ev = EVO.filter(e => r.events_fused[e]);
    const list = M.map(m => `<button class="item" data-mv="${m.mv_delivery_id}" aria-current="${m === r}"><div class="noimg"></div><div><div class="id">${m.mv_delivery_id.split("_").slice(-2).join(" ")}</div>
      <div class="meta">${m.n_views} views: ${m.views.map(v => v.camera_id).join(", ")}</div><div class="meta">${m.ball_3d?.speed_kmh ? m.ball_3d.speed_kmh.toFixed(0) + " km/h · " : ""}spread ${m.release_spread_ms.toFixed(0)} ms</div></div></button>`).join("");
    const evRows = ev.map(e => { const f = r.events_fused[e]; return `<tr><td>${EN[e]}</td><td><button class="ts" data-rel="${f.t_rel_release_s}">${(f.t_rel_release_s * 1000).toFixed(0)} ms ▶</button></td>
      <td>${Object.entries(f.per_view).map(([c, t]) => `${c} ${(t * 1000).toFixed(0)}`).join(", ")}</td><td class="${f.spread_ms > 70 ? "err" : ""}">${f.spread_ms.toFixed(0)} ms</td></tr>`; }).join("");
    const camRows = r.views.map(v => { const c = cams[v.camera_id] || {}, sy = (r.sync || {})[v.camera_id] || {};
      return `<tr><td><b>${v.camera_id}</b> ${esc(v.role)}</td><td>${(v.shift_s ?? 0).toFixed(3)} s<div class="meta">${esc(sy.method || "")}</div></td>
        <td>${c.focal_px ? `${c.focal_px} px, error ${c.reprojection_px} px<div class="meta">at (${c.position_m.join(", ")}) m from ${c.points_used} points</div>` : `<span class="meta">not calibrated in 3D</span>`}</td>
        <td><button class="linkish" data-openv="${v.delivery_id}">${shortId(v.delivery_id)}</button></td></tr>`; }).join("");
    const f3 = (v, d = 2) => v == null ? "–" : (+v).toFixed(d);
    $("#mvTab").innerHTML = `<div class="layout"><aside><div class="list">${list}</div></aside><div>
      <div style="display:flex;gap:12px;align-items:baseline;flex-wrap:wrap"><p class="title">${r.mv_delivery_id}</p><span class="pill">${r.n_views} synchronised views</span>
        <span class="meta">session ${esc(r.session_id)}, releases agree to ${r.release_spread_ms.toFixed(0)} ms</span></div>
      <p class="note">One delivery, several cameras: one training sample. Times are relative to the fused release moment.</p>
      <div class="mvgrid">${r.views.map(v => `<div class="mvcell">${v.clip ? `<video data-cam="${v.camera_id}" src="${v.annotated || v.clip}" muted playsinline preload="auto"></video>` : ""}<span>${v.camera_id}: ${esc(v.role)}</span></div>`).join("")}</div>
      <div class="controls"><button class="btn primary" id="mvPlay">▶ Play all</button>
        <div class="seg" role="group" aria-label="Speed">${[0.1, 0.25, 0.5, 1].map(x => `<button data-mvr="${x}" aria-pressed="${x === rate}">${x}×</button>`).join("")}</div>
        <input type="range" id="mvT" min="-2.5" max="1.5" step="0.005" value="${T}" style="flex:1;min-width:200px"><span class="clock" id="mvClock"></span></div>
      <div class="chips">${ev.map(e => `<button class="chip" data-rel="${r.events_fused[e].t_rel_release_s}"><i style="background:${EVC[e] || "#888"}"></i>${EN[e]} <b>${(r.events_fused[e].t_rel_release_s * 1000).toFixed(0)} ms</b></button>`).join("")}</div>
      <div class="grid2">
        <div class="card"><h2>3D ball (${b ? "triangulated" : "not available"})</h2>${b ? `<table>
          <tr><td>Speed out of the hand</td><td><b>${f3(b.speed_kmh, 1)} km/h</b></td></tr>
          <tr><td>Release point (x, y, z)</td><td>${b.release_xyz.map(v => f3(v)).join(", ")} m</td></tr>
          <tr><td>Bounce point (x, y)</td><td>${f3(b.bounce_xyz[0])}, ${f3(b.bounce_xyz[1])} m, ${f3(b.bounce_t_after_release_s, 3)} s after release</td></tr>
          <tr><td>Length</td><td>${f3(b.length_from_batter_stumps_m)} m from the batter's stumps</td></tr></table><p class="meta">${esc(b.fit || "")}. x = right as seen from behind the bowler, y = from the bowler's popping crease, z = up.</p>`
          : `<p class="meta">Needs the ball tracked in at least two views calibrated in 3D (6+ pitch points including a stump top).</p>`}</div>
        <div class="card"><h2>Bowler in 3D</h2>${p ? `<table><tr><th></th><th>Release</th><th>Front-foot contact</th></tr>
          <tr><td>Bowling elbow</td><td>${f3(p.elbow_angle_deg, 0)}°</td><td>${f3(pf?.elbow_angle_deg, 0)}°</td></tr>
          <tr><td>Front knee</td><td>${f3(p.front_knee_angle_deg, 0)}°</td><td>${f3(pf?.front_knee_angle_deg, 0)}°</td></tr>
          <tr><td>Trunk sideways lean</td><td>${f3(p.trunk_lateral_tilt_deg, 0)}°</td><td>${f3(pf?.trunk_lateral_tilt_deg, 0)}°</td></tr>
          <tr><td>Wrist height</td><td>${f3(p.wrist_height_m)} m</td><td>${f3(pf?.wrist_height_m)} m</td></tr></table>
          <p class="meta">${p.views} views, joint reprojection error ${f3(p.reproj_px, 1)} px. 3D video estimate, not a legality test.</p>` : `<p class="meta">Needs the bowler in at least two calibrated views.</p>`}</div>
        <div class="card"><h2>Top view</h2><canvas class="plot" id="mvTop" width="700" height="460"></canvas></div>
        <div class="card"><h2>Side view</h2><canvas class="plot" id="mvSide" width="700" height="460"></canvas></div>
      </div>
      <h2 style="margin-top:20px">Events across views</h2><div class="tablewrap"><table><tr><th>Event</th><th>Fused (vs release)</th><th>Per camera (ms)</th><th>Spread</th></tr>${evRows}</table></div>
      <h2 style="margin-top:20px">Cameras: sync and calibration</h2><div class="tablewrap"><table><tr><th>Camera</th><th>Time shift</th><th>3D calibration</th><th>Per-view delivery</th></tr>${camRows}</table></div>
    </div></div>`;
    $$("#mvTab [data-mv]").forEach(x => x.onclick = () => { cur = M.find(m => m.mv_delivery_id === x.dataset.mv); T = 0; stop(); render(); });
    $$("#mvTab [data-openv]").forEach(x => x.onclick = () => { tab("deliveries"); show(x.dataset.openv); window.scrollTo(0, 0); });
    $$("#mvTab [data-rel]").forEach(x => x.onclick = () => { stop(); seek(+x.dataset.rel - 0.3); play(+x.dataset.rel + 0.4); });
    $$("#mvTab [data-mvr]").forEach(x => x.onclick = () => { rate = +x.dataset.mvr; $$("#mvTab [data-mvr]").forEach(y => y.setAttribute("aria-pressed", y === x)); if (playing) { stop(); play(); } });
    $("#mvPlay").onclick = () => playing ? stop() : play();
    $("#mvT").oninput = e => { stop(); seek(+e.target.value); };
    plots(r); seek(T);
  }
  const vids = () => $$("#mvTab video[data-cam]");
  const clipT = (v, T_) => { const view = cur.views.find(x => x.camera_id === v.dataset.cam); return (cur.release_session_s + T_ - view.window_start_session_s) * (view.time_scale || 1); };
  function seek(T_) { T = T_; vids().forEach(v => { const t = clipT(v, T); if (t >= 0) v.currentTime = t; });
    $("#mvT").value = T; $("#mvClock").textContent = `${(T * 1000).toFixed(0)} ms from release`; plots(cur); }
  let stopAt = null;
  function play(until) { playing = true; stopAt = until ?? null; $("#mvPlay").textContent = "❚❚ Pause";
    vids().forEach(v => { const view = cur.views.find(x => x.camera_id === v.dataset.cam); v.playbackRate = rate * (view.time_scale || 1); v.play().catch(() => {}); });
    let last = performance.now();
    const tick = now => { if (!playing) return; T += (now - last) / 1000 * rate; last = now;
      vids().forEach(v => { const t = clipT(v, T); if (Math.abs(v.currentTime - t) > 0.08) v.currentTime = Math.max(0, t); });
      $("#mvT").value = T; $("#mvClock").textContent = `${(T * 1000).toFixed(0)} ms from release`;
      if ((stopAt != null && T >= stopAt) || T > 1.5) { stop(); return; } raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick); }
  function stop() { playing = false; if (raf) cancelAnimationFrame(raf); vids().forEach(v => v.pause()); const b = $("#mvPlay"); if (b) b.textContent = "▶ Play all"; }
  function plots(r) {
    const css = getComputedStyle(document.documentElement), col = v => css.getPropertyValue(v).trim();
    const draw = (id, fx, fy, rangeX, rangeY, labels) => { const c = $(id); if (!c) return; const x = c.getContext("2d"), W = c.width, H = c.height;
      x.clearRect(0, 0, W, H); const sx = (W - 60) / (rangeX[1] - rangeX[0]), sy = (H - 50) / (rangeY[1] - rangeY[0]), s_ = Math.min(sx, sy);
      const P = (a, b) => [30 + (a - rangeX[0]) * s_, H - 30 - (b - rangeY[0]) * s_];
      x.font = "15px sans-serif"; x.fillStyle = col("--muted"); x.fillText(labels, 30, 20); return {x, P}; };
    const b = r.ball_3d, cams = r.cameras || {};
    let g = draw("#mvTop", 0, 0, [-12, 36], [-14, 14], "Top view: x across, y along the pitch (m); cameras and ball path");
    if (g) { const {x, P} = g;
      const pt = (X, Y) => P(Y, X);                                   // draw the pitch lengthwise
      x.fillStyle = col("--pitch"); const a = pt(-1.52, -2), c2 = pt(1.52, 21); x.fillRect(a[0], c2[1], c2[0] - a[0], a[1] - c2[1]);
      x.strokeStyle = "#fff"; x.lineWidth = 2; [[0], [17.68]].forEach(([y]) => { const p1 = pt(-1.32, y), p2 = pt(1.32, y); x.beginPath(); x.moveTo(...p1); x.lineTo(...p2); x.stroke(); });
      Object.entries(cams).forEach(([k, v]) => { const p = pt(v.position_m[0], v.position_m[1]); x.fillStyle = col("--blue"); x.beginPath(); x.arc(...p, 6, 0, 7); x.fill(); x.fillStyle = col("--ink"); x.fillText(k, p[0] + 8, p[1] - 6); });
      if (b) { x.strokeStyle = "#F2C230"; x.lineWidth = 3; x.beginPath(); b.path.forEach((q, i) => { const p = pt(q.xyz[0], q.xyz[1]); i ? x.lineTo(...p) : x.moveTo(...p); }); x.stroke();
        x.fillStyle = col("--ball"); const bb = pt(b.bounce_xyz[0], b.bounce_xyz[1]); x.beginPath(); x.arc(...bb, 6, 0, 7); x.fill(); } }
    g = draw("#mvSide", 0, 0, [-3, 21], [-0.3, 3.2], "Side view: height (m) along the pitch; ball path, release and bounce");
    if (g) { const {x, P} = g;
      x.strokeStyle = col("--line"); x.beginPath(); x.moveTo(...P(-3, 0)); x.lineTo(...P(21, 0)); x.stroke();
      [[-1.22], [18.9]].forEach(([y]) => { x.strokeStyle = col("--ink"); x.lineWidth = 3; x.beginPath(); x.moveTo(...P(y, 0)); x.lineTo(...P(y, 0.711)); x.stroke(); });
      if (b) { x.strokeStyle = "#F2C230"; x.lineWidth = 3; x.beginPath(); b.path.forEach((q, i) => { const p = P(q.xyz[1], q.xyz[2]); i ? x.lineTo(...p) : x.moveTo(...p); }); x.stroke();
        x.fillStyle = col("--ball"); [b.release_xyz, b.bounce_xyz].forEach(q => { x.beginPath(); x.arc(...P(q[1], q[2]), 6, 0, 7); x.fill(); });
        const now = b.path.reduce((a, q) => Math.abs(q.t - T) < Math.abs(a.t - T) ? q : a, b.path[0]);
        if (T >= 0 && T <= b.path[b.path.length - 1].t + 0.05) { x.strokeStyle = col("--ink"); x.beginPath(); x.arc(...P(now.xyz[1], now.xyz[2]), 9, 0, 7); x.stroke(); } } }
  }
  window.MV_OPEN = id => { cur = M.find(m => m.mv_delivery_id === id) || cur; T = 0; render(); };
  render();
})();

/* ---------------- ball labels ---------------- */
(function balls() {
  const F = D.label_frames || [];
  if (!F.length) { $("#balls").innerHTML = `<div class="empty-state">No frames to label yet. Run python code/run_all.py (the label stage extracts frames).</div>`; return; }
  let onlyTodo = true, idx = 0;
  const local = {};                                   // labels added in this session (pending)
  const lab = f => local[f.id] || f.label;
  const list = () => F.filter(f => !onlyTodo || !lab(f));
  function render() {
    const L = list(); if (idx >= L.length) idx = Math.max(0, L.length - 1);
    const done = F.filter(f => lab(f)).length;
    if (!L.length) { $("#balls").innerHTML = `<div class="empty-state">All ${F.length} frames labelled. Save, then run python code/train_ball.py export and train.</div>`; return; }
    const f = L[idx], cur = lab(f);
    $("#balls").innerHTML = `<p class="note">Click the centre of the ball. Frames where the automatic tracker lost the ball come first (section 9.2). These clicks train a cricket-specific ball detector with <b>python code/train_ball.py</b>.</p>
      <div class="lab"><div><div class="labimg"><img id="limg" src="${f.image}" alt="Frame to label"><canvas id="lcv"></canvas></div></div>
      <div class="card"><h2>${shortId(f.delivery_id)}, ${fmt(f.t_clip, 2)} s</h2>
        <p class="meta">Frame ${idx + 1} of ${L.length} shown; ${done} of ${F.length} labelled.</p>
        <p>${cur ? (cur.visible === false ? "Labelled: no ball visible." : `Labelled at (${Math.round(cur.x)}, ${Math.round(cur.y)}).`) : f.proposal ? "Yellow circle: the tracker's guess." : "No automatic guess for this frame."}</p>
        <div style="display:flex;gap:6px;flex-wrap:wrap">
          <button class="btn" id="lAcc" ${f.proposal ? "" : "disabled"}>Guess is right <span class="kbd">A</span></button>
          <button class="btn" id="lNo">No ball visible <span class="kbd">N</span></button>
          <button class="btn" id="lPrev">Back <span class="kbd">←</span></button>
          <button class="btn" id="lNext">Skip <span class="kbd">→</span></button></div>
        <label class="meta" style="display:block;margin-top:10px"><input type="checkbox" id="lTodo" ${onlyTodo ? "checked" : ""}> Show unlabelled frames only</label>
        <p class="meta">${LIVE ? "Labels join the unsaved changes; press Save in the bar below." : "Read-only: start python code/serve.py to label."}</p></div></div>`;
    const img = $("#limg"), cv = $("#lcv"), [W, H] = f.size;
    const draw = () => { cv.width = img.clientWidth; cv.height = img.clientHeight; const x = cv.getContext("2d"), sx = cv.width / W, sy = cv.height / H; x.lineWidth = 2;
      if (f.proposal) { x.strokeStyle = "#F2C230"; x.beginPath(); x.arc(f.proposal.x * sx, f.proposal.y * sy, 12, 0, 7); x.stroke(); }
      if (cur && cur.visible !== false) { x.strokeStyle = "#62E07A"; x.beginPath(); x.arc(cur.x * sx, cur.y * sy, 9, 0, 7); x.stroke(); x.beginPath(); x.moveTo(cur.x * sx - 14, cur.y * sy); x.lineTo(cur.x * sx + 14, cur.y * sy); x.moveTo(cur.x * sx, cur.y * sy - 14); x.lineTo(cur.x * sx, cur.y * sy + 14); x.stroke(); } };
    img.complete ? draw() : img.onload = draw;
    if (window.ResizeObserver) new ResizeObserver(draw).observe(img);   // redraw when the tab becomes visible or resizes
    const set = v => { if (!LIVE) return; local[f.id] = v; addPending({kind: "ball_label", field: f.id, value: v, delivery_id: f.delivery_id}); if (!onlyTodo) idx++; render(); };
    cv.onclick = e => { const r = cv.getBoundingClientRect(); set({x: Math.round((e.clientX - r.left) * W / r.width), y: Math.round((e.clientY - r.top) * H / r.height)}); };
    $("#lAcc").onclick = () => f.proposal && set({x: f.proposal.x, y: f.proposal.y});
    $("#lNo").onclick = () => set({visible: false});
    $("#lPrev").onclick = () => { idx = Math.max(0, idx - 1); render(); };
    $("#lNext").onclick = () => { idx = Math.min(L.length - 1, idx + 1); render(); };
    $("#lTodo").onchange = e => { onlyTodo = e.target.checked; idx = 0; render(); };
  }
  ON_LIVE.push(render);
  document.addEventListener("keydown", e => { if (!$("#v-balls").classList.contains("on") || /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
    const k = e.key.toLowerCase(), b = {a: "#lAcc", n: "#lNo", arrowleft: "#lPrev", arrowright: "#lNext"}[k]; if (b && $(b) && !$(b).disabled) { e.preventDefault(); $(b).click(); } });
  render();
})();

/* ---------------- bat labels ---------------- */
(function batsTab() {
  const F = (D.label_frames || []);
  if (!F.length) { $("#bats").innerHTML = `<div class="empty-state">No frames yet. Run python code/run_all.py (the label stage extracts frames).</div>`; return; }
  let onlyTodo = true, idx = 0, clicks = [];
  const local = {}, lab = f => local[f.id] || f.bat;
  function render() {
    const L = F.filter(f => !onlyTodo || !lab(f)); if (idx >= L.length) idx = Math.max(0, L.length - 1);
    const done = F.filter(f => lab(f)).length;
    if (!L.length) { $("#bats").innerHTML = `<div class="empty-state">All ${F.length} frames have a bat label. Save, then run python code/train_bat.py export and train.</div>`; return; }
    const f = L[idx], cur = lab(f); clicks = [];
    $("#bats").innerHTML = `<p class="note">Click the <b>top of the handle</b>, then the <b>toe of the bat</b> (bottom of the blade). These clicks train a bat keypoint detector with <b>python code/train_bat.py</b>; until then the bat is estimated from the batter's hands.</p>
      <div class="lab"><div><div class="labimg"><img id="bimg" src="${f.image}" alt="Frame to label"><canvas id="bcv"></canvas></div></div>
      <div class="card"><h2>${shortId(f.delivery_id)}, ${fmt(f.t_clip, 2)} s</h2><p class="meta">Frame ${idx + 1} of ${L.length} shown; ${done} of ${F.length} have a bat label.</p>
        <p id="bmsg">${cur ? (cur.visible === false ? "Labelled: no bat visible." : "Labelled (green line).") : "Click 1: top of the handle."}</p>
        <div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn" id="bNo">No bat visible <span class="kbd">N</span></button>
          <button class="btn" id="bClr">Clear clicks <span class="kbd">C</span></button><button class="btn" id="bPrev">Back <span class="kbd">←</span></button><button class="btn" id="bNext">Skip <span class="kbd">→</span></button></div>
        <label class="meta" style="display:block;margin-top:10px"><input type="checkbox" id="bTodo" ${onlyTodo ? "checked" : ""}> Show unlabelled frames only</label>
        <p class="meta">${LIVE ? "Labels join the unsaved changes; press Save in the bar below." : "Read-only: start python code/serve.py to label."}</p></div></div>`;
    const img = $("#bimg"), cv = $("#bcv"), [W, H] = f.size;
    const draw = () => { cv.width = img.clientWidth; cv.height = img.clientHeight; const x = cv.getContext("2d"), sx = cv.width / W, sy = cv.height / H; x.lineWidth = 4; x.lineCap = "round";
      const line = (a, b, col) => { x.strokeStyle = col; x.beginPath(); x.moveTo(a[0] * sx, a[1] * sy); x.lineTo(b[0] * sx, b[1] * sy); x.stroke(); };
      if (cur && cur.visible !== false) line(cur.handle, cur.toe, "#62E07A");
      x.fillStyle = "#F2C230"; clicks.forEach(p => { x.beginPath(); x.arc(p[0] * sx, p[1] * sy, 6, 0, 7); x.fill(); });
      if (clicks.length === 2) line(clicks[0], clicks[1], "#F2C230"); };
    img.complete ? draw() : img.onload = draw;
    if (window.ResizeObserver) new ResizeObserver(draw).observe(img);
    const set = v => { if (!LIVE) return; local[f.id] = v; addPending({kind: "bat_label", field: f.id, value: v, delivery_id: f.delivery_id}); if (!onlyTodo) idx++; render(); };
    cv.onclick = e => { if (!LIVE) return; const r = cv.getBoundingClientRect();
      clicks.push([Math.round((e.clientX - r.left) * W / r.width), Math.round((e.clientY - r.top) * H / r.height)]); draw();
      if (clicks.length === 1) $("#bmsg").textContent = "Click 2: toe of the bat.";
      if (clicks.length === 2) set({handle: clicks[0], toe: clicks[1]}); };
    $("#bNo").onclick = () => set({visible: false});
    $("#bClr").onclick = () => { clicks = []; $("#bmsg").textContent = "Click 1: top of the handle."; draw(); };
    $("#bPrev").onclick = () => { idx = Math.max(0, idx - 1); render(); };
    $("#bNext").onclick = () => { idx = Math.min(L.length - 1, idx + 1); render(); };
    $("#bTodo").onchange = e => { onlyTodo = e.target.checked; idx = 0; render(); };
  }
  document.addEventListener("keydown", e => { if (!$("#v-bats").classList.contains("on") || /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
    const b = {n: "#bNo", c: "#bClr", arrowleft: "#bPrev", arrowright: "#bNext"}[e.key.toLowerCase()]; if (b && $(b)) { e.preventDefault(); $(b).click(); } });
  render(); ON_LIVE.push(render);
})();

/* ---------------- field checklist (Appendix A) ---------------- */
(function check() {
  const ITEMS = ["Experiment ID / protocol version confirmed", "Participant IDs and permissions confirmed", "Cameras powered, lens/focus/exposure checked",
    "Camera positions match config or new config recorded", "Calibration valid / new calibration captured", "Hardware/PTP sync green", "Radar alignment and device health checked",
    "Lighting/flicker check passed", "Storage throughput and free space passed", "Network links passed", "Session manifest created",
    "Technical test capture processed successfully", "Operator declares CAPTURE READY"];
  const C = D.checklists || {};
  $("#check").innerHTML = `<p class="note">Appendix A session readiness, recorded per session. For downloaded videos most items are "not applicable"; at Salem every item must be "yes" before capture starts.</p>
    <div class="filters" style="max-width:600px"><select id="ckSrc">${D.sources.map(s => `<option value="${s.source_id}">${s.source_id} ${esc(s.title.slice(0, 50))}</option>`).join("")}</select></div><div id="ckBody" class="card" style="max-width:900px"></div>`;
  const body = () => { const sid = $("#ckSrc").value, cur = C[sid] || {};
    const ready = ITEMS.every(i => cur[i] === "yes");
    $("#ckBody").innerHTML = `${cur.by ? `<p class="meta">Last saved by ${esc(cur.by)} at ${esc((cur.at || "").replace("T", " ").slice(0, 16))}. ${ready ? "<b>Capture ready.</b>" : "Not capture-ready."}</p>` : ""}
      ${ITEMS.map((it, i) => `<div class="checkrow"><span>${esc(it)}</span><select data-ck="${i}" ${LIVE ? "" : "disabled"}>${["", "yes", "no", "n/a"].map(v => `<option ${cur[it] === v ? "selected" : ""}>${v}</option>`).join("")}</select></div>`).join("")}
      <label class="meta" style="display:block;margin-top:10px">Notes<textarea id="ckNotes" style="width:100%" ${LIVE ? "" : "disabled"}>${esc(cur.notes || "")}</textarea></label>
      ${LIVE ? `<button class="btn" id="ckAdd" style="margin-top:8px">Add checklist to changes</button>` : ""}`;
    const b = $("#ckAdd"); if (b) b.onclick = () => { const v = {}; $$("[data-ck]").forEach(el => v[ITEMS[+el.dataset.ck]] = el.value || null); v.notes = $("#ckNotes").value;
      addPending({kind: "checklist", source_id: sid, field: "appendix_a", value: v}); b.textContent = "Checklist added"; }; };
  $("#ckSrc").onchange = body; body(); ON_LIVE.push(body);
})();

/* ---------------- training pairs ---------------- */
$("#downloads").innerHTML = Object.entries(D.files).map(([k, p]) => `<a href="${p}" download>${k}</a>`).join("");
const uniq = k => [...new Set(D.sft.map(r => r[k]))];
$("#j-task").innerHTML = `<option value="">All question types</option>` + uniq("task").map(t => `<option value="${t}">${t.replace(/_/g, " ")}</option>`).join("");
$("#j-type").innerHTML = `<option value="">All answer types</option>` + uniq("answer_type").map(t => `<option value="${t}">${t.replace(/_/g, " ")}</option>`).join("");
function renderPairs() {
  const tk = $("#j-task").value, ty = $("#j-type").value, rs = $("#j-rs").value, qq = $("#j-q").value.toLowerCase();
  const rows = D.sft.filter(r => (!tk || r.task === tk) && (!ty || r.answer_type === ty) && (!rs || r.provenance.review_state === rs) && (!qq || (r.question + " " + r.answer).toLowerCase().includes(qq)));
  $("#j-rows").innerHTML = rows.slice(0, 400).map(r => `<tr><td><button class="linkish" data-open-d="${r.delivery_id}">${shortId(r.delivery_id)}</button></td><td>${esc(r.question)}</td><td>${linkTimes(esc(r.answer), r.delivery_id)}</td><td>${r.answer_type.replace(/_/g, " ")}</td><td>${r.provenance.review_state}</td><td>${fmt(r.confidence)}</td></tr>`).join("") || `<tr><td colspan="6">No pairs match.</td></tr>`;
  $("#j-raw").textContent = rows.length ? rows.slice(0, 20).map(r => JSON.stringify(r)).join("\n") + (rows.length > 20 ? `\n… ${rows.length - 20} more` : "") : "No records.";
}
$("#j-rows").onclick = e => { const b = e.target.closest("[data-d],[data-open-d]"); if (!b) return;
  if (b.dataset.t) pendingPlay = +b.dataset.t;
  tab("deliveries"); show(b.dataset.d || b.dataset.openD); window.scrollTo(0, 0); };
["#j-task", "#j-type", "#j-rs"].forEach(s => $(s).onchange = renderPairs); $("#j-q").oninput = renderPairs; renderPairs();

/* ---------------- release ---------------- */
(function rel() {
  const r = D.release; if (!r) { $("#rel").innerHTML = `<div class="empty-state">No release built yet. Run python code/run_all.py.</div>`; return; }
  const ok = r.checklist.filter(c => c.status === "ok").length;
  $("#rel").innerHTML = `<div class="grid2" style="margin-top:0">
    <div class="card"><h2>${r.release_id}</h2>
      <p>${r.release_kind === "dev_only" ? "<b>Development only.</b> These sources are not cleared for model training, so this release is for testing training code and evaluation, not for a model you ship." : "Cleared for training within the recorded rights."}</p>
      <dl class="dl"><dt>Split by</dt><dd>source video (no video spans two splits)</dd><dt>Deliveries</dt><dd>train ${r.counts.train}, validation ${r.counts.val}, test ${r.counts.test}</dd>
      <dt>Training pairs</dt><dd>train ${r.sft_pairs.train}, validation ${r.sft_pairs.val}, test ${r.sft_pairs.test}</dd><dt>Expert-gold evaluation set</dt><dd>${r.gold.length} deliveries (their videos are held in test)</dd>
      <dt>Hash</dt><dd style="font-family:var(--code);font-size:12px;word-break:break-all">${r.hash}</dd></dl>
      <p class="downloads" style="margin-top:10px">${D.files["data_card.md"] ? `<a href="${D.files["data_card.md"]}" download>Download data card</a>` : ""}</p></div>
    <div class="card"><h2>Readiness checklist (Appendix D)</h2><p class="meta">${ok} of ${r.checklist.length} items pass automatically.</p>
      ${r.checklist.map(c => `<div class="check"><span class="st-${c.status}">${c.status}</span><span>${esc(c.item)}<div class="meta">${esc(c.detail)}</div></span></div>`).join("")}</div>
    <div class="card"><h2>Evaluation slices</h2>${Object.entries(r.slices).map(([k, v]) => `<h3>${k.replace(/_/g, " ")}</h3>` + Object.entries(v).map(([a, b]) => `<div class="meta">${esc(a)}: ${b}</div>`).join("")).join("")}</div>
  </div>`;
})();

/* ---------------- experiment and sources ---------------- */
(function exp() {
  const e = D.experiment || {}, fields = [["Experiment", e.experiment_id], ["Protocol version", e.protocol_version], ["Model question", e.model_question], ["Objective", e.model_objective],
    ["Population", e.population], ["Independent variables", e.independent_variables], ["Controlled variables", e.controlled_variables], ["Measured variables", (e.measured_variables || []).join("; ")],
    ["Cricket labels", (e.cricket_labels || []).join(", ")], ["Repetitions", e.repetitions], ["Gold subset", e.gold_subset], ["Acceptance", (e.acceptance || []).join("; ")]];
  $("#exp").innerHTML = `<div class="card" style="max-width:900px"><h2>Experiment specification (section 3)</h2><dl class="dl">${fields.map(([k, v]) => `<dt>${k}</dt><dd>${esc(v ?? "–")}</dd>`).join("")}</dl></div>
    <h2 style="margin-top:22px">Source registry (section 10.2)</h2><div class="tablewrap"><table><thead><tr><th>Source</th><th>Title</th><th>Type</th><th>Length</th><th>FPS</th><th>Slow-down</th><th>Deliveries</th><th>Category</th><th>Rights basis</th><th>Training</th></tr></thead><tbody>
    ${D.sources.map(s => `<tr><td>${s.source_id}</td><td>${esc(s.title)}</td><td>${catName(s.category)}</td><td>${fmt(s.duration_s, 0)} s</td><td>${fmt(s.fps, 0)}</td>
      <td>${s.time_scale > 1 ? `×${s.time_scale}${s.time_scale_verified ? "" : " (unverified)"}` : "real time"}</td><td>${s.deliveries}</td><td>${esc(s.rights.source_category)}</td><td>${esc(s.rights.rights_basis)}</td>
      <td>${s.rights.training_allowed ? "Allowed" : "Not allowed"}</td></tr>`).join("")}</tbody></table></div>
    <h2 style="margin-top:22px">Ontology ${O.ontology_version}</h2><div class="tablewrap"><table><thead><tr><th>Vocabulary</th><th>Values</th></tr></thead><tbody>
    ${Object.entries(O.vocab).map(([k, v]) => `<tr><td>${k}</td><td>${v.join(", ")}</td></tr>`).join("")}</tbody></table></div>
    <h2 style="margin-top:22px">Device registry (backlog #2)</h2><div class="tablewrap"><table><thead><tr><th>Device</th><th>Type</th><th>Model</th><th>Mode / role</th><th>Serial</th></tr></thead><tbody>
    ${Object.entries((D.devices || {}).devices || {}).map(([k, v]) => `<tr><td>${k}</td><td>${esc(v.type)}</td><td>${esc(v.model || "")}</td><td>${esc(v.mode || v.view || v.description || (v.measures || []).join(", "))}</td><td>${esc(v.serial || "")}</td></tr>`).join("")}</tbody></table></div>
    <h2 style="margin-top:22px">People and roles (section 11.3)</h2><p class="meta">${Object.entries(D.people || {}).map(([k, v]) => `${esc(k)}: ${v}`).join("; ")}. Edit code/registry/people.yaml to add reviewers.</p>
    <h3>Length thresholds (metres from the batter's stumps, provisional)</h3><p class="meta">${Object.entries(O.thresholds.length_from_batter_stumps_m).map(([k, [a, b]]) => `${k} ${a}–${b}`).join("; ")}</p>`;
})();

const h = location.hash.slice(1).split(":");
if (D.deliveries.length) { renderList(); if (h[1] && byId[h[1]]) show(h[1]); }
else $("#detail").innerHTML = `<div class="empty-state">No deliveries yet. Check results/segments/ or run python code/diagnose.py on a video.</div>`;
if (h[0] && $("#v-" + h[0])) tab(h[0]);
</script>
</body>
</html>