File size: 103,312 Bytes
4e6a175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frame-Pair Aligner — RGB/IR overlay</title>

<!--
  ============================================================================
   FRAME-PAIR ALIGNER   (Piece 1 of 4:  folder load + display + IR overlay)
  ============================================================================
   Goal: register the IR (thermal, 640x360) camera to the RGB (2688x1512)
   camera for a wildfire dataset folder. The RGB<->IR geometry is USUALLY fixed for
   a given Pair-ID folder, so one homography aligns every frame — but when the drone
   altitude changes a lot the RGB<->IR parallax shifts, so a folder can be split into
   SUBSETS (contiguous frame ranges), each fit to its own homography (see the tab bar).

   This app fuses two earlier tools:
     - sync-video-player.html  -> the "look": full RGB with a draggable,
                                   resizable, adjustable-opacity IR overlay.
     - align_manual.html       -> the math: point-pair homography + overlays.

   Folder layout it understands (matching by filename across rgb/ & ir/):
        <Pair-ID>/rgb/f00300.png
        <Pair-ID>/ir /f00300.png
   Selecting a parent (e.g. "Canopy/") yields several Pair-ID groups; each
   group gets its own homography.

   PIECE 1 (this file) only LOADS and DISPLAYS. Picking / fitting / overlays
   come in pieces 2-4. Everything here is plain <canvas> + <img> (no WebCodecs,
   no mp4box), so it runs straight from file:// — no localhost needed.
  ============================================================================
-->

<style>
  :root {
    --bg: #0e0f13; --panel: #191b22; --panel-2: #21242d; --border: #2c303b;
    --text: #e6e8ee; --muted: #9aa0ac; --accent: #4f8cff; --accent-2: #3a6fd8; --danger: #ff5a5a;
    color-scheme: dark;
  }
  * { box-sizing: border-box; }
  html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text);
    font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; height: 100%; }
  body { display: flex; flex-direction: column; height: 100vh; }

  header { padding: 10px 16px; background: var(--panel); border-bottom: 1px solid var(--border);
    display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
  header h1 { font-size: 15px; margin: 0; font-weight: 600; letter-spacing: .2px; }

  .loaders { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
  .file-btn { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
    padding: 6px 10px; border-radius: 7px; cursor: pointer; font-size: 12px; }
  .file-btn:hover { border-color: var(--accent); }
  input[type=file] { display: none; }
  select#groupSel { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
    border-radius: 7px; padding: 6px 8px; font-size: 12px; max-width: 260px; }

  .filepaths { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; }
  .filepath { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--muted); min-width: 0; }
  .fp-tag { color: var(--accent); font-weight: 600; flex: none; width: 30px; }
  .fp-path { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; direction: rtl; text-align: left; }

  .error { display: none; margin: 8px 16px 0; padding: 10px 14px; background: #2a1416;
    border: 1px solid #6b2b30; border-radius: 8px; color: #ffd7da; font-size: 12px; white-space: pre-wrap; }
  .error.show { display: block; }

  /* --- SUBSET TABS: split a folder's frames into contiguous "altitude bands",
     each fit to its OWN homography. Thin bar between the header and the stage. --- */
  .subset-bar { display: none; align-items: center; gap: 10px; flex-wrap: wrap;
    padding: 6px 16px; background: var(--panel-2); border-bottom: 1px solid var(--border); }
  .subset-bar.show { display: flex; }
  .sb-label { font-size: 12px; color: var(--muted); font-weight: 600; flex: none; }
  .sb-tabs { display: flex; gap: 4px; flex-wrap: wrap; }
  .sb-tab { display: inline-flex; align-items: center; gap: 6px; background: var(--panel);
    border: 1px solid var(--border); color: var(--text); padding: 5px 10px; border-radius: 7px;
    cursor: pointer; font-size: 12px; line-height: 1.2; white-space: nowrap; }
  .sb-tab:hover { border-color: var(--accent); }
  .sb-tab.active { border-color: var(--accent); background: #262a34; box-shadow: inset 0 -2px 0 var(--accent); }
  .sb-tab .sb-no { font-weight: 700; color: var(--accent); }
  .sb-tab .sb-rng { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
  .sb-tab .sb-cnt { color: var(--muted); font-variant-numeric: tabular-nums; }
  .sb-tab .sb-fit { color: var(--muted); }
  .sb-tab.fitted .sb-fit { color: #57c97a; }         /* ✓ once this subset has a homography */
  .sb-tab.thin { color: var(--muted); }              /* < 4 pts: can't fit yet */
  .sb-hint { font-size: 11px; color: var(--muted); margin-left: auto; }

  main { flex: 1; display: flex; padding: 8px; min-height: 0; }

  .stage { position: relative; flex: 1; width: 100%; background: #000; border: 1px solid var(--border);
    border-radius: 8px; overflow: hidden; display: flex; align-items: center; justify-content: center; min-height: 0; }
  /* #scene wraps the RGB canvas + IR panel; scroll-zoom / right-drag-pan apply a
     single transform here so the IR overlay stays locked to the RGB underneath. */
  #scene { position: absolute; inset: 0; transform-origin: 0 0; will-change: transform; }
  #scene > canvas#canvasA { width: 100%; height: 100%; object-fit: contain; background: #000; display: block; }
  .stage .badge, .rstage .badge { position: absolute; top: 8px; left: 8px; background: rgba(0,0,0,.6); color: #fff;
    padding: 3px 8px; border-radius: 6px; font-size: 11px; pointer-events: none; z-index: 2; }
  .ftime { font-variant-numeric: tabular-nums; color: var(--accent); margin-left: 4px; }
  .ir-panel .geom { left: auto; right: 8px; font-size: 10px; font-variant-numeric: tabular-nums; }
  .geo { display: inline-flex; align-items: center; gap: 3px; }
  .geolab { font-size: 11px; color: var(--muted); }
  input[type=number].geoinput { width: 54px; }

  .loading { position: absolute; inset: 0; z-index: 10; display: none; pointer-events: none;
    flex-direction: column; align-items: center; justify-content: center; gap: 12px;
    background: rgba(14,15,19,.55); color: var(--text); font-size: 13px; }
  .loading.show { display: flex; }
  .loading .spinner { width: 34px; height: 34px; border-radius: 50%;
    border: 3px solid var(--panel-2); border-top-color: var(--accent); animation: spin .8s linear infinite; }
  @keyframes spin { to { transform: rotate(360deg); } }
  .stage .empty, .rstage .empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
    color: var(--muted); font-size: 13px; text-align: center; padding: 20px; pointer-events: none; }

  /* IR overlay panel (sits on top of the full-size RGB) */
  .ir-panel { position: absolute; left: 0; top: 0; width: 320px; height: 240px;
    outline: 2px solid var(--accent); border-radius: 6px; overflow: hidden; background: transparent;
    box-shadow: 0 6px 24px rgba(0,0,0,.55); cursor: move; touch-action: none; z-index: 5; }
  .ir-panel.ir-hidden { opacity: 0; pointer-events: none; transform: translateX(calc(-100vw - 100% - 32px)); }
  .ir-panel > canvas { width: 100%; height: 100%; object-fit: contain; display: block; background: #000;
    opacity: var(--ir-opacity, 1); }
  .ir-resize { position: absolute; right: 0; bottom: 0; width: 18px; height: 18px; background: var(--accent);
    border-top-left-radius: 6px; cursor: nwse-resize; touch-action: none; z-index: 6; }
  .ir-resize::before { content: ""; position: absolute; right: 3px; bottom: 3px; width: 6px; height: 6px;
    border-right: 2px solid #fff; border-bottom: 2px solid #fff; }
  /* Counter-scale the IR panel's chrome so it stays a constant on-screen size
     while the scene is zoomed (--zoom is set on #scene by applyView()). */
  /* The accent ring is an OUTLINE, not a border: with box-sizing:border-box a
     border would eat 2px into the panel and inset the IR canvas inside ir.w×ir.h,
     while auto-place and the warp use the FULL box — so a border made the picked
     overlay land ~2px off the fitted one. Outline sits outside the box and doesn't
     affect layout, so the IR image fills ir.x..ir.x+ir.w exactly (matches the fit). */
  .ir-panel { outline-width: calc(2px / var(--zoom, 1)); }
  .ir-panel .badge { transform: scale(calc(1 / var(--zoom, 1))); transform-origin: top left; }
  .ir-panel .geom  { transform-origin: top right; }
  .ir-resize { transform: scale(calc(1 / var(--zoom, 1))); transform-origin: bottom right; }

  footer { background: var(--panel); border-top: 1px solid var(--border); padding: 10px 16px 14px;
    display: flex; flex-direction: column; gap: 10px; }
  .scrubber-row { display: flex; align-items: center; gap: 12px; }
  .frameLabel { font-variant-numeric: tabular-nums; font-size: 12px; color: var(--muted); min-width: 220px; }
  input[type=range].seek { flex: 1; height: 6px; -webkit-appearance: none; appearance: none;
    background: var(--panel-2); border-radius: 4px; outline: none; cursor: pointer; }
  input[type=range].seek::-webkit-slider-thumb { -webkit-appearance: none; appearance: none;
    width: 15px; height: 15px; border-radius: 50%; background: var(--accent); cursor: pointer; border: 2px solid #fff; }
  input[type=range].seek::-moz-range-thumb { width: 15px; height: 15px; border-radius: 50%;
    background: var(--accent); cursor: pointer; border: 2px solid #fff; }

  .controls { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
  button.ctrl { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
    padding: 8px 12px; border-radius: 8px; cursor: pointer; font-size: 13px; min-width: 40px;
    display: inline-flex; align-items: center; justify-content: center; gap: 6px; }
  button.ctrl:hover:not(:disabled) { border-color: var(--accent); background: #262a34; }
  button.ctrl:disabled { opacity: .4; cursor: not-allowed; }
  button.ctrl.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }
  button.ctrl.primary:hover:not(:disabled) { background: var(--accent-2); }

  .group { display: flex; align-items: center; gap: 8px; padding-left: 12px; margin-left: 4px; border-left: 1px solid var(--border); }
  .group:first-child { border-left: none; padding-left: 0; margin-left: 0; }
  .group label { font-size: 12px; color: var(--muted); }
  input[type=number] { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
    border-radius: 7px; padding: 6px 8px; font-size: 12px; width: 76px; }
  input[type=range].ir-opacity { width: 110px; height: 6px; -webkit-appearance: none; appearance: none;
    background: var(--panel-2); border-radius: 4px; outline: none; cursor: pointer; }
  input[type=range].ir-opacity::-webkit-slider-thumb { -webkit-appearance: none; appearance: none;
    width: 14px; height: 14px; border-radius: 50%; background: var(--accent); cursor: pointer; border: 2px solid #fff; }
  input[type=range].ir-opacity::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%;
    background: var(--accent); cursor: pointer; border: 2px solid #fff; }
  input[type=range].ir-opacity:disabled { opacity: .45; cursor: not-allowed; }
  .opacity-badge { font-size: 12px; color: var(--accent); font-variant-numeric: tabular-nums; min-width: 38px; text-align: right; }
  .spacer { flex: 1; }

  /* Point-picking: marker canvas (HUD over the stage) + the status pills. */
  #marks { position: absolute; inset: 0; pointer-events: none; z-index: 8; }
  .pill { background: var(--panel-2); border: 1px solid var(--border); padding: 5px 11px;
    border-radius: 999px; font-size: 12px; color: var(--muted); white-space: nowrap; }
  .pill b { color: var(--text); font-weight: 600; }
  .pill.turn-ir  { border-color: var(--accent); color: var(--accent); }
  .pill.turn-ir b  { color: var(--accent); }
  .pill.turn-rgb { border-color: #57c97a; color: #57c97a; }
  .pill.turn-rgb b { color: #57c97a; }
  .pill.warn { border-color: #6b5a2b; color: #f2b84b; }

  /* Fit-results screen — a full-screen overlay PLAYER (RGB base + warped-IR),
     built to mirror the main picking stage: scroll-zoom, right-drag-pan, ← → nav. */
  #results { position: fixed; inset: 0; z-index: 50; background: var(--bg); display: none; flex-direction: column; }
  #results.show { display: flex; }
  .rheader { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 10px 16px;
    background: var(--panel); border-bottom: 1px solid var(--border); }
  .rheader h2 { font-size: 15px; margin: 0; font-weight: 600; }
  .rspacer { flex: 1; }
  .rstage { position: relative; flex: 1; min-height: 0; background: #000; overflow: hidden;
    display: flex; align-items: center; justify-content: center; }
  #ovScene { position: absolute; inset: 0; transform-origin: 0 0; will-change: transform; }
  #ovScene img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain;
    -webkit-user-drag: none; user-select: none; }
  #ovScene .ov-ir { opacity: var(--ov-alpha, .8); }   /* IR layer opacity, live */
  .rfooter { background: var(--panel); border-top: 1px solid var(--border); padding: 10px 16px 12px;
    display: flex; flex-direction: column; gap: 8px; }
  .rrow { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
  /* Fitted matrices / stats — slide-over drawer on the right of the stage. */
  #fitDetails { position: absolute; top: 0; right: 0; bottom: 0; width: min(560px, 92vw); z-index: 4;
    background: var(--bg); border-left: 1px solid var(--border); box-shadow: -8px 0 30px rgba(0,0,0,.5);
    overflow: auto; padding: 6px 18px 28px; transform: translateX(100%); transition: transform .18s ease; }
  #fitDetails.show { transform: none; }
  .fit-card { border: 1px solid var(--border); border-radius: 10px; padding: 12px 16px; margin: 12px 0; background: var(--panel); }
  .fit-card.bad { border-color: #6b2b30; }
  .fit-card h3 { margin: 0 0 8px; font-size: 14px; }
  .stat { font-size: 13px; color: var(--muted); margin: 4px 0; }
  .stat b { color: var(--text); }
  pre.mat { background: var(--panel-2); padding: 10px 12px; border-radius: 8px; font-size: 12px; overflow-x: auto;
    margin: 6px 0 0; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: pre; }
  .ok { color: #57c97a; } .err { color: #ff5a5a; }
  .fld { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); }
  .sect { font-size: 14px; font-weight: 600; color: var(--accent); margin: 18px 0 2px; }
  select#ovModel { background: var(--panel-2); border: 1px solid var(--border); color: var(--text);
    border-radius: 7px; padding: 6px 8px; font-size: 12px; max-width: 240px; }
  kbd { background: var(--panel-2); border: 1px solid var(--border); border-bottom-width: 2px; border-radius: 4px;
    padding: 1px 5px; font-size: 11px; font-family: inherit; color: var(--text); }
  #saveHint { font-size: 12px; }
  #saveHint code { background: var(--panel-2); border: 1px solid var(--border); border-radius: 5px;
    padding: 1px 6px; color: var(--accent); font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
</style>
</head>
<body>
  <header>
    <h1>🎯 Frame-Pair Aligner</h1>
    <div class="loaders">
      <!-- webkitdirectory: lets the user pick a whole Pair-ID folder (or a parent). -->
      <label><span class="file-btn">📁 Load folder</span><input type="file" id="dirInput" webkitdirectory></label>
      <select id="groupSel" style="display:none" title="Pair-ID folder to align"></select>
      <button class="ctrl" id="btnRestart" title="Discard all picked points and restart from the first frame" disabled>↺ Restart</button>
    </div>
    <div class="filepaths">
      <div class="filepath"><span class="fp-tag">RGB</span><span class="fp-path" id="pathA" title="No folder loaded">—</span></div>
      <div class="filepath"><span class="fp-tag">IR</span><span class="fp-path" id="pathB" title="No folder loaded">—</span></div>
    </div>
  </header>

  <div id="error" class="error"></div>

  <!-- SUBSET TABS: split the folder's frames into contiguous ranges ("altitude
       bands"); each range is fit to its OWN homography. Hidden until a folder loads. -->
  <div id="subsetBar" class="subset-bar">
    <span class="sb-label" title="Split the video into ranges when the altitude changes so much that one homography no longer fits every frame">Subsets</span>
    <div class="sb-tabs" id="sbTabs"></div>
    <button class="ctrl" id="btnSplit" title="Start a NEW subset at the current frame (use it where the altitude jumps)" disabled>✂ Split here</button>
    <button class="ctrl" id="btnMergeSubset" title="Merge the current subset back into the previous one" disabled>↤ Merge</button>
    <span class="sb-hint">each gets its own homography · <kbd>Alt</kbd>+<kbd>1</kbd>…<kbd>9</kbd> to switch · double-click a tab to rename</span>
  </div>

  <main id="main">
    <div class="stage" id="stageRGB">
      <span class="badge">RGB<span class="ftime" id="tA">—</span></span>

      <!-- Everything inside #scene zooms/pans together (RGB + IR overlay). -->
      <div id="scene">
        <canvas id="canvasA"></canvas>

        <!-- IR overlay: a draggable/resizable panel floating over the RGB. -->
        <div class="ir-panel" id="irPanel">
          <span class="badge">IR<span class="ftime" id="tB">—</span></span>
          <span class="badge geom" id="irGeom">—</span>
          <canvas id="canvasB"></canvas>
          <div class="ir-resize" id="irResize" title="Drag to resize (keeps aspect ratio)"></div>
        </div>
      </div>

      <!-- Picked-point markers (HUD, drawn in screen space so they stay crisp). -->
      <canvas id="marks"></canvas>

      <div class="empty" id="emptyA">Click “📁 Load folder” and choose a Pair-ID folder<br>(one that contains <code>rgb/</code> and <code>ir/</code> sub-folders)</div>

      <div class="loading" id="loading"><div class="spinner"></div><div>Loading…</div></div>
    </div>
  </main>

  <footer>
    <!-- Frame navigation: discrete step through the sampled frames in the group. -->
    <div class="scrubber-row">
      <span class="frameLabel" id="frameLabel">No folder loaded</span>
      <input type="range" class="seek" id="seek" min="0" max="1" value="0" step="1" disabled>
    </div>

    <div class="controls">
      <div class="group">
        <button class="ctrl" id="btnFirst" title="First frame (Home)" disabled>⏮</button>
        <button class="ctrl" id="btnPrev"  title="Previous frame (←)"  disabled>◀ Prev</button>
        <button class="ctrl" id="btnNext"  title="Next frame (→)"      disabled>Next ▶</button>
        <button class="ctrl" id="btnLast"  title="Last frame (End)"    disabled>⏭</button>
      </div>
      <!-- Picking status + controls sit in the controls row's empty middle gap, so
           the footer height (and thus the fixed IR default alignment) is unchanged. -->
      <div class="group" id="pickGroup">
        <span class="pill" id="pickStatus">Load a folder to start picking</span>
        <span class="pill" id="pickCount">—</span>
        <button class="ctrl" id="btnUndo" title="Undo last point (u)" disabled>↶ Undo</button>
        <button class="ctrl" id="btnClearFrame" title="Clear this frame's points" disabled>Clear frame</button>
        <button class="ctrl" id="btnAutoPoints" title="Drop a grid of correspondences that reproduce the CURRENT IR-overlay placement (scale + position). Adjust the box until it looks right, then Auto-place → Fit. Replaces this frame's points." disabled>⊞ Auto-place</button>
        <button class="ctrl primary" id="btnFit" title="Fit EVERY subset that has ≥4 points, each to its own homography" disabled>✓ Fit</button>
      </div>
      <div class="spacer"></div>
      <div class="group">
        <label for="irOpacity">IR opacity</label>
        <input type="range" class="ir-opacity" id="irOpacity" min="0" max="100" value="70" step="1" disabled>
        <span class="opacity-badge" id="irOpacityValue">70%</span>
        <button class="ctrl" id="btnToggleIR" title="Hide / Show IR overlay (I)" disabled>Hide IR</button>
        <button class="ctrl" id="btnCenterIR" title="Center IR over RGB" disabled>⊹ Center</button>
        <button class="ctrl" id="btnResetIR"  title="Reset IR to default size, centered" disabled>↺ Reset</button>
      </div>
      <div class="group">
        <label title="IR panel size &amp; position in stage pixels">IR box</label>
        <span class="geo"><span class="geolab">W</span><input type="number" class="geoinput" id="irW" title="width (px)"></span>
        <span class="geo"><span class="geolab">H</span><input type="number" class="geoinput" id="irH" title="height (px)"></span>
        <span class="geo"><span class="geolab">X</span><input type="number" class="geoinput" id="irX" title="left (px)"></span>
        <span class="geo"><span class="geolab">Y</span><input type="number" class="geoinput" id="irY" title="top (px)"></span>
      </div>
    </div>

    <div class="hint" style="font-size:11px;color:var(--muted)">
      Shortcuts: <kbd>←</kbd>/<kbd>→</kbd> prev/next frame · <kbd>Home</kbd>/<kbd>End</kbd> first/last · <kbd>I</kbd> hide/show IR ·
      <kbd>scroll</kbd> zoom · <kbd>right-drag</kbd> pan · <kbd>0</kbd> reset view · <kbd>U</kbd> undo pick · <kbd>middle-click</kbd> a point to remove it ·
      drag the <span style="color:var(--accent)">IR</span> panel to move it, drag its corner to resize
    </div>
  </footer>

  <!-- Fit-results screen: a full-screen overlay player (RGB + warped-IR). -->
  <div id="results">
    <div class="rheader">
      <button class="ctrl" id="btnBackPick">← Back to picking</button>
      <h2 id="resultsTitle">Fit results</h2>
      <!-- Jump between already-fitted subsets without leaving this screen; shown by
           renderSubsetSwitch() only when ≥2 subsets are fitted. -->
      <label class="fld" id="subsetSwitchWrap" style="display:none">Subset <select id="subsetSwitch" title="Show another fitted subset's results"></select></label>
      <label class="fld">Model <select id="ovModel" disabled></select></label>
      <label class="fld">RANSAC px <input type="number" id="ransacThresh" value="6" step="1" min="1" style="width:56px"></label>
      <button class="ctrl" id="btnRefit" title="Re-run the fit with the current threshold">↻ Re-fit</button>
      <button class="ctrl" id="btnFitDetails" title="Show the fitted matrices & stats">ⓘ Fit details</button>
      <span class="rspacer"></span>
      <button class="ctrl primary" id="btnGenOverlays" disabled>Generate overlays</button>
      <button class="ctrl" id="btnSaveH" title="Save homography.json + points.json" disabled>Save H + points</button>
      <button class="ctrl" id="btnSaveAll" title="Save homography.json + points.json + overlay images for EVERY fitted subset (warps any not yet generated)" disabled>💾 Save all…</button>
      <!-- Reminder of WHERE to save so the folder's own homography/ files update in place. -->
      <span class="stat" id="saveHint" title="The load dialog can't grant write access, so Save opens a folder picker — choose this folder to overwrite its existing files"></span>
    </div>

    <div class="rstage" id="ovStage">
      <span class="badge" id="ovBadge">—</span>
      <div id="ovScene">
        <img class="ov-base" id="ovBase" alt="RGB">
        <img class="ov-ir"   id="ovIr"   alt="warped IR">
      </div>
      <div class="empty" id="ovEmpty">Pick a model above, then “Generate overlays”.</div>
      <div class="loading" id="ovLoading"><div class="spinner"></div><div id="ovProgress">Warping…</div></div>
      <!-- Fitted matrices / stats — slide-over drawer. -->
      <div id="fitDetails"><div id="resultsBody"></div></div>
    </div>

    <div class="rfooter">
      <div class="rrow">
        <button class="ctrl" id="ovFirst" title="First (Home)" disabled>⏮</button>
        <button class="ctrl" id="ovPrev"  title="Previous (←)" disabled>◀ Prev</button>
        <span class="frameLabel" id="ovFrameLabel">—</span>
        <input type="range" class="seek" id="ovSeek" min="0" max="1" value="0" step="1" disabled>
        <button class="ctrl" id="ovNext"  title="Next (→)" disabled>Next ▶</button>
        <button class="ctrl" id="ovLast"  title="Last (End)" disabled>⏭</button>
        <span class="rspacer"></span>
        <label class="fld">IR opacity
          <input type="range" class="ir-opacity" id="ovAlpha" min="0" max="100" value="70" step="1" style="width:130px">
          <span class="opacity-badge" id="ovAlphaVal">70%</span></label>
        <span id="saveStatus" class="stat"></span>
      </div>
      <div class="hint" style="font-size:11px;color:var(--muted)">
        <kbd>←</kbd>/<kbd>→</kbd> prev/next overlay · <kbd>I</kbd> hide/show IR · <kbd>scroll</kbd> zoom · <kbd>right-drag</kbd> pan · <kbd>0</kbd> reset view · <kbd>Esc</kbd> back to picking
      </div>
    </div>
  </div>

<script>
"use strict";
// ============================================================================
//  Small helpers
// ============================================================================
const $ = (id) => document.getElementById(id);
const clamp = (x, lo, hi) => x < lo ? lo : (x > hi ? hi : x);
const errorEl = $("error");
const showError = (m) => { errorEl.textContent = m; errorEl.classList.add("show"); };
const clearError = () => { errorEl.textContent = ""; errorEl.classList.remove("show"); };

// Reference frame number from a name like "f00300.png" -> 300 (first run of
// digits; falls back to Infinity so unnamed files sort last).
const frameNo = (name) => { const m = name.match(/\d+/); return m ? +m[0] : Infinity; };
// Short display label: last path segment ("Canopy/Canopy-01" -> "Canopy-01").
const shortLabel = (key) => key.split("/").filter(Boolean).pop() || key;

// Per-point colour palette (from align_manual.html) — the i-th correspondence
// gets colour col(i) in both the IR and RGB marker.
const COLORS = [
  [0,220,0],[255,100,0],[0,60,255],[210,210,0],[210,0,210],[0,200,200],
  [0,140,255],[255,180,0],[150,255,100],[150,100,255],[255,100,150],[80,230,230],
].map(([r,g,b]) => `rgb(${r},${g},${b})`);
const col = (i) => COLORS[((i % COLORS.length) + COLORS.length) % COLORS.length];
const DRAG_PX = 4;   // pointer travel (screen px) that separates a click from a drag

// ============================================================================
//  DATA MODEL
//  GROUPS = [ { key, pairs: [ {name, rgbFile, irFile} ] } ]
//  One group == one Pair-ID folder == one (future) homography.
// ============================================================================
let GROUPS = [];
let gi = 0;            // active group index
let fi = 0;            // active frame index within the active group
let imgRGB = null, imgIR = null;   // decoded Image objects for the current frame

// PICKING state. framePicks maps a frame index (within the active group) to the
// point pairs picked on it, in IMAGE-pixel coords. The homography is fit from ALL
// frames' pairs pooled together (the RGB<->IR geometry is constant per folder).
//   framePicks: Map(frameIndex -> { ir: [[ix,iy],...], rgb: [[rx,ry],...] })
// `waiting` is which side the NEXT click records ("ir" then "rgb", alternating).
let framePicks = new Map();
let waiting = "ir";
let lastFit = null;   // { src, dst, frames, ls, ransac, thresh } from the most recent Fit

// ============================================================================
//  SUBSETS  (the "groups" from the request)
//  A Pair-ID folder's frames can be split into contiguous ranges — "altitude
//  bands" — because the RGB↔IR parallax changes with altitude, so ONE homography
//  may not fit a whole flight. Subsets PARTITION the frame-index space: subset k
//  covers frames [subsets[k].start .. subsets[k+1].start-1] (the last runs to the
//  end); subsets[0].start is always 0. Picks stay keyed by GLOBAL frame index
//  (framePicks), so a frame's picks belong to whichever subset contains it and the
//  picking code is untouched. Each subset is fit to its own homography, remembered
//  in subset.fit so switching tabs — and exporting the whole video — just works.
//     subsets: [ { start, name|null, fit|null } ]
//     si     : active subset (the one Fit / overlays / save act on); it follows the
//              current frame, so the highlighted tab is always the one you're in.
// ============================================================================
let subsets = [{ start: 0, name: null, fit: null }];
let si = 0;
const escapeHtml = (s) => String(s).replace(/[&<>"]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));

const nPairs = () => (GROUPS[gi] ? GROUPS[gi].pairs.length : 0);
// [firstFrame, lastFrame] inclusive for subset k.
function subsetRange(k) {
  const start = subsets[k].start;
  const end = (k + 1 < subsets.length ? subsets[k + 1].start : nPairs()) - 1;
  return [start, end];
}
// Which subset owns global frame index f (the last boundary at or before f).
function subsetOfFrame(f) { let k = 0; for (let i = 0; i < subsets.length; i++) { if (subsets[i].start <= f) k = i; else break; } return k; }
// Frame stem for index i ("f00300.png" -> "f00300"); falls back to a 1-based number.
function frameStem(i) { const p = GROUPS[gi] && GROUPS[gi].pairs[i]; return p ? p.name.replace(/\.\w+$/, "") : String(i + 1); }
// Frame-name range label for subset k, e.g. "f00300–f01200".
function subsetLabel(k) { const [a, b] = subsetRange(k); return a === b ? frameStem(a) : `${frameStem(a)}–${frameStem(b)}`; }
// Completed pairs (min ir/rgb per frame) pooled over the frames in subset k.
function subsetPairs(k) {
  const g = GROUPS[gi], [a, b] = subsetRange(k), list = [], frames = new Set();
  for (let f = a; f <= b; f++) {
    const fp = framePicks.get(f); if (!fp) continue;
    const n = Math.min(fp.ir.length, fp.rgb.length), name = (g && g.pairs[f]) ? g.pairs[f].name : String(f);
    for (let i = 0; i < n; i++) list.push({ frame: name, ir: fp.ir[i], rgb: fp.rgb[i] });
    if (n > 0) frames.add(f);
  }
  return { list, frames: frames.size };
}
function subsetPairCount(k) { const [a, b] = subsetRange(k); let n = 0; for (let f = a; f <= b; f++) { const fp = framePicks.get(f); if (fp) n += Math.min(fp.ir.length, fp.rgb.length); } return n; }
function resetSubsets() { subsets = [{ start: 0, name: null, fit: null }]; si = 0; renderSubsetTabs(); }
// A pick edit on the current frame invalidates its subset's stored fit (the point
// pool changed); refresh the tabs so the ✓ / count follow.
function touchPicks() { if (subsets[si]) subsets[si].fit = null; renderSubsetTabs(); }

// ---- subset tab bar --------------------------------------------------------
const sbTabs = $("sbTabs");
function renderSubsetTabs() {
  const bar = $("subsetBar");
  bar.classList.toggle("show", GROUPS.length > 0);
  if (!GROUPS.length) return;
  sbTabs.innerHTML = "";
  subsets.forEach((s, k) => {
    const [a, b] = subsetRange(k), cnt = subsetPairCount(k), thin = cnt < 4;
    const t = document.createElement("button");
    t.className = "sb-tab" + (k === si ? " active" : "") + (s.fit ? " fitted" : "") + (thin ? " thin" : "");
    t.title = `Subset ${k + 1}: frames ${a + 1}–${b + 1} (${b - a + 1} frame${b - a ? "s" : ""}), ${cnt} point pair${cnt === 1 ? "" : "s"}` +
      `${s.fit ? " · fitted ✓" : ""}\nAlt+${k + 1} to switch · double-click to rename`;
    t.innerHTML = `<span class="sb-no">${k + 1}</span>` +
      `<span class="sb-rng">${s.name ? escapeHtml(s.name) : escapeHtml(subsetLabel(k))}</span>` +
      `<span class="sb-cnt">${cnt} pt${cnt === 1 ? "" : "s"}</span>` +
      `<span class="sb-fit">${s.fit ? "✓" : "○"}</span>`;
    t.addEventListener("click", () => selectSubset(k));
    t.addEventListener("dblclick", (e) => { e.preventDefault(); renameSubset(k); });
    sbTabs.appendChild(t);
  });
  $("btnMergeSubset").disabled = (si === 0);
}
// Click a tab / Alt+n → jump to that subset's first frame (navigation sets si).
function selectSubset(k) { if (k >= 0 && k < subsets.length && GROUPS.length) gotoFrame(subsets[k].start); }
// Split the CURRENT subset in two at the current frame (a new boundary at fi).
function splitHere() {
  if (!GROUPS.length) return;
  const owner = subsetOfFrame(fi);
  if (subsets[owner].start === fi) {          // fi is already a boundary
    showError(fi === 0 ? "Move to the frame where the altitude changes, then Split — subset 1 already starts at the first frame."
                       : "This frame already starts a subset.");
    setTimeout(clearError, 3500); return;
  }
  subsets.splice(owner + 1, 0, { start: fi, name: null, fit: null });
  subsets[owner].fit = null;                  // the split shrank subset `owner`'s pool → its fit is stale
  si = owner + 1;
  clearError(); renderSubsetTabs(); updatePickUI();
}
// Merge the active subset back into the previous one (remove its boundary).
function mergeSubset() {
  if (si === 0) return;
  subsets[si - 1].fit = null;                 // merged pool → previous subset's fit is stale
  subsets.splice(si, 1);
  si = subsetOfFrame(fi);
  renderSubsetTabs(); updatePickUI();
}
function renameSubset(k) {
  const v = prompt(`Name for subset ${k + 1} (blank = auto range label):`, subsets[k].name || "");
  if (v === null) return;
  subsets[k].name = v.trim() || null; renderSubsetTabs();
}
$("btnSplit").addEventListener("click", splitHere);
$("btnMergeSubset").addEventListener("click", mergeSubset);

// Discover groups from a webkitdirectory file list. A file at path
// ".../<key>/rgb/<name>.png" contributes to group <key> under role "rgb"; the
// matching ".../<key>/ir/<name>.png" is its IR partner. Pairs are the names
// present in BOTH rgb/ and ir/, ordered by frame number.
//
// A THIRD sub-folder, ".../<key>/homography/", is optional: if present it holds a
// PRIOR save (homography.json + points.json + <stem>_overlay.jpg images). We collect
// it here into group.saved so selectGroup() can re-import that work — see importSaved().
function discoverGroups(files) {
  const map = new Map();   // key -> { rgb:Map, ir:Map, homography:Map } (name -> file)
  for (const f of files) {
    const path = f.webkitRelativePath || f.name;
    const m = /^(.*)\/(rgb|ir|homography)\/([^\/]+)$/i.exec(path);   // key / role / name
    if (!m) continue;
    const key = m[1], role = m[2].toLowerCase(), name = m[3];
    // rgb/ & ir/ hold only PNG frames; homography/ holds the two JSONs + overlay images.
    if ((role === "rgb" || role === "ir") && !/\.png$/i.test(name)) continue;
    if (role === "homography" && !/\.(json|jpe?g|png)$/i.test(name)) continue;
    if (!map.has(key)) map.set(key, { rgb: new Map(), ir: new Map(), homography: new Map() });
    map.get(key)[role].set(name, f);
  }
  const out = [];
  for (const [key, g] of map) {
    const pairs = [];
    for (const [name, rgbFile] of g.rgb) {
      const irFile = g.ir.get(name);
      if (irFile) pairs.push({ name, rgbFile, irFile });
    }
    pairs.sort((a, b) => frameNo(a.name) - frameNo(b.name));
    if (!pairs.length) continue;
    // Bundle any saved homography/ folder for re-import (null when there's none).
    const H = g.homography;
    const saved = H.size ? {
      homographyJson: H.get("homography.json") || null,
      pointsJson:     H.get("points.json") || null,
      overlays:       new Map([...H].filter(([n]) => /_overlay\.(jpe?g|png)$/i.test(n))),
    } : null;
    out.push({ key, pairs, saved });
  }
  out.sort((a, b) => a.key.localeCompare(b.key));
  return out;
}

// ============================================================================
//  IMPORT: restore a prior save from the folder's homography/ sub-folder
//  When a Pair-ID folder carries a homography/ sub-folder (see discoverGroups),
//  we rebuild the full picking/fit state from it so the work can be reviewed,
//  EDITED and re-saved — the inverse of the homographyDoc()/pointsDoc() writers.
//  Any later point edit clears that subset's fit (touchPicks), so a re-Fit + Save
//  overwrites homography.json / points.json / the overlay jpegs with the new state.
// ============================================================================
async function readJSONFile(file) { try { return JSON.parse(await file.text()); } catch { return null; } }
// frame name ("f00300.png") -> its index in the CURRENT group's pairs.
function nameIndexMap() { const g = GROUPS[gi], m = new Map(); if (g) g.pairs.forEach((p, i) => m.set(p.name, i)); return m; }
// Rebuild one server-style model object from a saved homography.json subset row.
// The row carries the label + matrix + stats but NOT which of the 4 model slots it
// was; we recover the slot key from its shape: scale => similarity (s_*), else full
// homography (h_*); n_inliers present => RANSAC variant (*_rn), else least-squares (*_ls).
function modelFromRow(row) {
  const key = (row.scale != null ? "s" : "h") + "_" + (row.n_inliers != null ? "rn" : "ls");
  const m = { matrix: row.matrix, rmse: row.rmse_px, n: row.n_pairs, label: row.model || key };
  if (row.n_inliers != null) m.inliers = row.n_inliers;
  if (row.scale != null) { m.scale = row.scale; m.rotation_deg = row.rotation_deg; m.translation = row.translation_px; }
  return { key, model: m };
}
// Restore subsets + framePicks + fitted matrices for the active group from its saved
// homography/ folder. Returns true if anything was imported. Leaves state untouched
// (returns false) when there's no save or the JSON can't be read.
async function importSaved(group) {
  if (!group || !group.saved) return false;
  const hDoc = group.saved.homographyJson ? await readJSONFile(group.saved.homographyJson) : null;
  const pDoc = group.saved.pointsJson     ? await readJSONFile(group.saved.pointsJson)     : null;
  const hSubs = (hDoc && hDoc.subsets) || [], pSubs = (pDoc && pDoc.subsets) || [];
  const nSub = Math.max(hSubs.length, pSubs.length);
  if (!nSub) return false;

  const nameIdx = nameIndexMap();
  // A saved subset's start frame INDEX in THIS group: prefer the saved frame NAME
  // (robust if indices shifted), fall back to the saved index, else 0.
  const startIndexOf = (row) => {
    if (row && row.frame_start != null && nameIdx.has(row.frame_start)) return nameIdx.get(row.frame_start);
    if (row && row.frame_index_start != null) return clamp(row.frame_index_start, 0, nPairs() - 1);
    return 0;
  };

  const newSubsets = [], picks = new Map();
  for (let k = 0; k < nSub; k++) {
    const hRow = hSubs[k], pRow = pSubs[k];
    const corr = (pRow && pRow.correspondences) || [];
    // Re-load this subset's picked points (keyed by frame index) from points.json.
    for (const c of corr) {
      const idx = nameIdx.get(c.frame);
      if (idx == null || !c.ir || !c.rgb) continue;
      let fp = picks.get(idx); if (!fp) { fp = { ir: [], rgb: [] }; picks.set(idx, fp); }
      fp.ir.push([c.ir[0], c.ir[1]]); fp.rgb.push([c.rgb[0], c.rgb[1]]);
    }
    // Rebuild the fit (one model slot) from homography.json, matching subsetPairs()/
    // fitSubset()'s shape so loadFit()/renderResults() and the writers work unchanged.
    let fit = null;
    if (hRow && hRow.matrix) {
      const { key, model } = modelFromRow(hRow);
      fit = { models: { [key]: model }, imported: true,   // only the saved model slot is known
        thresh: (pRow && pRow.ransac_threshold_px) != null ? pRow.ransac_threshold_px : (hRow.ransac_threshold_px || 6),
        n_pairs: hRow.n_pairs != null ? hRow.n_pairs : corr.length,
        list: corr, frames: new Set(corr.map(c => c.frame)).size,
        ir_size:  (hDoc && hDoc.ir_size)  || (pDoc && pDoc.ir_size)  || null,
        rgb_size: (hDoc && hDoc.rgb_size) || (pDoc && pDoc.rgb_size) || null };
    }
    newSubsets.push({ start: startIndexOf(hRow || pRow), name: (hRow && hRow.name) || (pRow && pRow.name) || null, fit });
  }
  // Subsets partition frame space in order, first always starting at 0.
  newSubsets.sort((a, b) => a.start - b.start);
  newSubsets[0].start = 0;

  subsets = newSubsets; framePicks = picks; si = 0;
  return true;
}

// ============================================================================
//  FRAME LOADING + DRAW
// ============================================================================
const stageRGB = $("stageRGB"), canvasA = $("canvasA"), canvasB = $("canvasB");
const ctxA = canvasA.getContext("2d", { alpha: false });
const ctxB = canvasB.getContext("2d", { alpha: false });
const marks = $("marks"), marksCtx = marks.getContext("2d");   // picked-point overlay (HUD)
const loadingEl = $("loading");
const showLoading = () => loadingEl.classList.add("show");
const hideLoading = () => loadingEl.classList.remove("show");

// Object URLs for the frame currently on screen; revoked when we move on so we
// never hold more than one frame's worth of blobs.
let curURLs = [];
function revokeURLs() { for (const u of curURLs) URL.revokeObjectURL(u); curURLs = []; }
function loadImage(file) {
  return new Promise((res, rej) => {
    const url = URL.createObjectURL(file); curURLs.push(url);
    const im = new Image();
    im.onload = () => res(im);
    im.onerror = () => rej(new Error("could not read " + (file.webkitRelativePath || file.name)));
    im.src = url;
  });
}

let loadToken = 0;   // guards against out-of-order loads when stepping fast
async function gotoFrame(i) {
  const g = GROUPS[gi]; if (!g) return;
  fi = clamp(i, 0, g.pairs.length - 1);
  si = subsetOfFrame(fi);          // the active subset follows the current frame
  const p = g.pairs[fi];
  const myToken = ++loadToken;
  showLoading();
  let rgb, ir;
  try { [rgb, ir] = await Promise.all([loadImage(p.rgbFile), loadImage(p.irFile)]); }
  catch (e) { if (myToken === loadToken) { showError(e.message); hideLoading(); } return; }
  if (myToken !== loadToken) return;         // superseded by a newer step — bail
  // Only now that both decoded, drop the previous frame's URLs (keep-then-swap
  // avoids a flicker of black between frames).
  const stale = curURLs.slice(0, curURLs.length - 2); // all but the two we just added
  for (const u of stale) URL.revokeObjectURL(u);
  curURLs = curURLs.slice(curURLs.length - 2);

  imgRGB = rgb; imgIR = ir;
  canvasA.width = rgb.naturalWidth; canvasA.height = rgb.naturalHeight; ctxA.drawImage(rgb, 0, 0);
  canvasB.width = ir.naturalWidth;  canvasB.height = ir.naturalHeight;  ctxB.drawImage(ir, 0, 0);
  hideLoading();
  updateFrameUI(p);
  if (!irUserMoved) initIR();     // fit the overlay to the (16:9) IR aspect
  else { clampIR(); applyIR(); }
  syncWaiting();                  // this frame may already have picks — resume where it left off
  drawMarks(); updatePickUI(); renderSubsetTabs();
}

function updateFrameUI(p) {
  const g = GROUPS[gi];
  $("frameLabel").textContent = `${shortLabel(g.key)} · frame ${fi + 1}/${g.pairs.length} · ${p.name}`;
  $("tA").textContent = p.name; $("tB").textContent = p.name;
  $("pathA").textContent = p.rgbFile.webkitRelativePath || p.name; $("pathA").title = $("pathA").textContent;
  $("pathB").textContent = p.irFile.webkitRelativePath || p.name;  $("pathB").title = $("pathB").textContent;
  const seek = $("seek");
  seek.max = String(g.pairs.length - 1); seek.value = String(fi);
}

// ============================================================================
//  FOLDER LOAD WIRING
// ============================================================================
async function selectGroup(index) {
  gi = clamp(index, 0, GROUPS.length - 1);
  irUserMoved = false;            // a fresh group re-fits the default overlay
  resetView();                    // ...and starts back at fit (1×, no pan)
  resetPicks();                   // ...and starts a fresh correspondence set
  resetSubsets();                 // ...as one subset covering the whole folder
  clearOverlays(); clearOverlayCache(); lastFit = null;   // ...and drops any overlays/fit from the previous folder
  ["btnGenOverlays","btnSaveH","btnSaveAll"].forEach(id => $(id).disabled = true);   // no fit yet in the new folder
  setControlsEnabled(true);
  // If this Pair-ID folder carries a homography/ save, restore it (points, subsets,
  // fitted matrices) so it can be reviewed / edited / re-saved. Overrides the resets above.
  await importSaved(GROUPS[gi]);
  await gotoFrame(0);             // gotoFrame renders the (imported) subset tabs + pick UI
}
// Start over: discard every picked point and go back to the first frame of the
// first group (folder stays loaded). Also closes the results/overlay screen.
function restart() {
  if (!GROUPS.length) return;
  if (totalPairs() > 0 && !confirm("Discard all picked points and restart from the first frame?")) return;
  hideResults(); clearOverlays(); lastFit = null;
  $("groupSel").value = "0";
  selectGroup(0);
}
$("btnRestart").addEventListener("click", restart);

$("dirInput").addEventListener("change", (e) => {
  clearError();
  const files = e.target.files;
  if (!files || !files.length) return;
  GROUPS = discoverGroups(files);
  if (!GROUPS.length) {
    showError("No rgb/ir frame pairs found.\nPick a folder that contains a Pair-ID folder with rgb/ and ir/ sub-folders\n(e.g. SampledFrames/Canopy/Canopy-01), or a parent of several.");
    return;
  }
  // Populate the group selector (shown only when there is more than one).
  const sel = $("groupSel");
  sel.innerHTML = "";
  GROUPS.forEach((g, i) => {
    const o = document.createElement("option");
    o.value = String(i);
    o.textContent = `${shortLabel(g.key)}  (${g.pairs.length})`;
    sel.appendChild(o);
  });
  sel.style.display = GROUPS.length > 1 ? "" : "none";
  sel.value = "0";
  $("emptyA").style.display = "none";
  selectGroup(0);
});
$("groupSel").addEventListener("change", (e) => selectGroup(+e.target.value));

function setControlsEnabled(on) {
  ["btnFirst","btnPrev","btnNext","btnLast","btnToggleIR","btnCenterIR","btnResetIR","btnUndo","btnClearFrame","btnAutoPoints","btnRestart","btnSplit","btnMergeSubset"].forEach(id => $(id).disabled = !on);
  $("seek").disabled = !on; $("irOpacity").disabled = !on;
}

// ---- frame transport --------------------------------------------------------
$("btnFirst").addEventListener("click", () => gotoFrame(0));
$("btnPrev").addEventListener("click",  () => gotoFrame(fi - 1));
$("btnNext").addEventListener("click",  () => gotoFrame(fi + 1));
$("btnLast").addEventListener("click",  () => { const g = GROUPS[gi]; if (g) gotoFrame(g.pairs.length - 1); });
$("seek").addEventListener("input", (e) => gotoFrame(+e.target.value));

// ============================================================================
//  IR OVERLAY: move / resize (aspect-locked) / opacity / hide
//  (Lifted from sync-video-player.html; geometry is in STAGE pixels.)
// ============================================================================
const irPanel = $("irPanel"), irResize = $("irResize");
const irGeom = $("irGeom"), irW = $("irW"), irH = $("irH"), irX = $("irX"), irY = $("irY");
const irOpacityInput = $("irOpacity"), irOpacityValue = $("irOpacityValue"), btnToggleIR = $("btnToggleIR");
const IR_MIN = 60;
// Default IR→RGB transform in IMAGE pixels. The dual-camera rig geometry is fixed
// (same drone, same 640×360 IR / 2688×1512 RGB everywhere), so this one transform
// is a good default overlay placement for every folder. It's a pure scale+translate
// (no rotation/perspective) — IR maps to the box x=312, y=202, W=2040, H=1148 in RGB
// image pixels. initIR() PROJECTS it into the current stage, so the default lands on
// the RGB correctly at ANY window/stage size (image space is screen-independent).
const DEFAULT_H = [ 3.18782,  0.0,      311.82,
                    0.0,      3.18880,  202.07,
                    0.0,      0.0,      1.0 ];
// Stage-pixel fallback used only before any image is loaded (empty panel).
const IR_DEFAULT = { x: 536, y: 144, w: 1452, h: 817 };
let ir = { x: IR_DEFAULT.x, y: IR_DEFAULT.y, w: IR_DEFAULT.w, h: IR_DEFAULT.h };
let irUserMoved = false, irVisible = true;

// ---- VIEW: scroll = zoom (about cursor), right-drag = pan --------------------
// Zoom/pan the whole #scene (RGB canvas + IR panel together) so the overlay
// stays aligned — invaluable for precise point-picking on the low-res IR.
// `view` is in STAGE pixels: screen = pan + zoom * sceneCoord.
const scene = $("scene");
const view = { zoom: 1, panX: 0, panY: 0 };
const ZOOM_MIN = 1, ZOOM_MAX = 20;
function clampView() {
  const sw = stageRGB.clientWidth, sh = stageRGB.clientHeight;
  view.zoom = clamp(view.zoom, ZOOM_MIN, ZOOM_MAX);
  // Keep the scaled scene covering the stage (no black gaps from over-panning).
  view.panX = clamp(view.panX, sw * (1 - view.zoom), 0);
  view.panY = clamp(view.panY, sh * (1 - view.zoom), 0);
}
function applyView() {
  clampView();
  scene.style.transform = `translate(${view.panX}px, ${view.panY}px) scale(${view.zoom})`;
  scene.style.setProperty("--zoom", view.zoom);
  drawMarks();   // markers are a HUD in screen space — re-place them for the new view
}
function resetView() { view.zoom = 1; view.panX = 0; view.panY = 0; applyView(); }
// Zoom about the cursor: the scene point under the pointer stays put.
function zoomAt(clientX, clientY, factor) {
  const r = stageRGB.getBoundingClientRect();
  const cx = clientX - r.left, cy = clientY - r.top;
  const sx = (cx - view.panX) / view.zoom, sy = (cy - view.panY) / view.zoom;
  view.zoom = clamp(view.zoom * factor, ZOOM_MIN, ZOOM_MAX);
  view.panX = cx - sx * view.zoom; view.panY = cy - sy * view.zoom;
  applyView();
}
stageRGB.addEventListener("wheel", e => {
  if (!imgRGB) return;
  e.preventDefault();
  zoomAt(e.clientX, e.clientY, e.deltaY < 0 ? 1.15 : 1 / 1.15);
}, { passive: false });
// Right-button drag = pan (captured on the stage so it keeps tracking off-panel).
let panDrag = null;
stageRGB.addEventListener("pointerdown", e => {
  if (e.button !== 2 || !imgRGB) return;
  e.preventDefault();
  panDrag = { sx: e.clientX, sy: e.clientY, px: view.panX, py: view.panY };
  try { stageRGB.setPointerCapture(e.pointerId); } catch {}
});
stageRGB.addEventListener("pointermove", e => {
  if (!panDrag) return;
  view.panX = panDrag.px + (e.clientX - panDrag.sx);
  view.panY = panDrag.py + (e.clientY - panDrag.sy);
  applyView();
});
function endPan(e) { if (panDrag) { try { stageRGB.releasePointerCapture(e.pointerId); } catch {} panDrag = null; } }
stageRGB.addEventListener("pointerup", endPan);
stageRGB.addEventListener("pointercancel", endPan);
stageRGB.addEventListener("contextmenu", e => e.preventDefault());   // right-drag would else pop the menu

// IR aspect from the decoded IR frame (640/360 here); fall back to box/4:3.
function irAspect() { if (imgIR && imgIR.naturalWidth && imgIR.naturalHeight) return imgIR.naturalWidth / imgIR.naturalHeight; return ir.w / ir.h || 4 / 3; }
// Where the RGB image actually sits inside the stage (object-fit: contain box).
function rgbBox() {
  const sw = stageRGB.clientWidth, sh = stageRGB.clientHeight;
  const vw = imgRGB ? imgRGB.naturalWidth : 0, vh = imgRGB ? imgRGB.naturalHeight : 0;
  if (imgRGB && vw && vh) { const scale = Math.min(sw / vw, sh / vh), w = vw * scale, h = vh * scale;
    return { left: (sw - w) / 2, top: (sh - h) / 2, width: w, height: h }; }
  return { left: 0, top: 0, width: sw, height: sh };
}
function applyIR() {
  irPanel.style.left = ir.x + "px"; irPanel.style.top = ir.y + "px"; irPanel.style.width = ir.w + "px"; irPanel.style.height = ir.h + "px";
  irGeom.textContent = Math.round(ir.w) + "×" + Math.round(ir.h) + " @ (" + Math.round(ir.x) + ", " + Math.round(ir.y) + ")";
  syncGeoInputs();
  drawMarks();   // IR markers are mapped through the panel geometry — follow it as it moves
}
function syncGeoInputs() {
  const set = (el, v) => { if (el !== document.activeElement) el.value = Math.round(v); };
  set(irW, ir.w); set(irH, ir.h); set(irX, ir.x); set(irY, ir.y);
}
function setIRW(w) { irUserMoved = true; if (isFinite(w)) { ir.w = Math.max(IR_MIN, w); ir.h = ir.w / irAspect(); } clampIR(); applyIR(); }
function setIRH(h) { irUserMoved = true; if (isFinite(h)) { ir.h = Math.max(IR_MIN, h); ir.w = ir.h * irAspect(); } clampIR(); applyIR(); }
function setIRX(x) { irUserMoved = true; if (isFinite(x)) ir.x = x; clampIR(); applyIR(); }
function setIRY(y) { irUserMoved = true; if (isFinite(y)) ir.y = y; clampIR(); applyIR(); }
[[irW, setIRW], [irH, setIRH], [irX, setIRX], [irY, setIRY]].forEach(([el, fn]) => {
  const run = () => fn(parseFloat(el.value));
  el.addEventListener("input", run); el.addEventListener("change", run);
  el.addEventListener("keydown", e => { if (e.key === "Enter") el.blur(); });
});
function applyIROpacity() { const o = clamp(parseFloat(irOpacityInput.value) / 100 || 0, 0, 1);
  irPanel.style.setProperty("--ir-opacity", o); irOpacityValue.textContent = Math.round(o * 100) + "%"; }
function setIRVisible(on) { irVisible = on; irPanel.classList.toggle("ir-hidden", !irVisible);
  btnToggleIR.textContent = irVisible ? "Hide IR" : "Show IR";
  btnToggleIR.title = irVisible ? "Hide IR overlay (I)" : "Show IR overlay (I)"; if (irVisible) { clampIR(); applyIR(); }
  updatePickUI(); }
function toggleIR() { setIRVisible(!irVisible); }
function clampIR() { const sw = stageRGB.clientWidth, sh = stageRGB.clientHeight;
  if (sw && sh) { ir.w = Math.min(ir.w, sw); ir.h = Math.min(ir.h, sh);
    ir.x = Math.max(0, Math.min(ir.x, sw - ir.w)); ir.y = Math.max(0, Math.min(ir.y, sh - ir.h)); } }
// Default alignment: project DEFAULT_H's IR footprint onto the CURRENT stage as an
// axis-aligned box, so the default overlay lands in the same spot on the RGB scene
// at any window/stage size (instead of a box frozen in stage pixels). Falls back to
// the fixed IR_DEFAULT before an image is loaded. Clamped so it can't spill off.
function initIR() {
  if (imgIR && imgRGB) {
    const Sw = imgIR.naturalWidth, Sh = imgIR.naturalHeight;
    let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
    for (const [x, y] of [[0,0],[Sw,0],[Sw,Sh],[0,Sh]]) {            // IR corners → RGB pixels via DEFAULT_H
      const w = DEFAULT_H[6]*x + DEFAULT_H[7]*y + DEFAULT_H[8];
      const X = (DEFAULT_H[0]*x + DEFAULT_H[1]*y + DEFAULT_H[2]) / w;
      const Y = (DEFAULT_H[3]*x + DEFAULT_H[4]*y + DEFAULT_H[5]) / w;
      minX = Math.min(minX, X); maxX = Math.max(maxX, X); minY = Math.min(minY, Y); maxY = Math.max(maxY, Y);
    }
    const b = rgbBox(), RW = imgRGB.naturalWidth, RH = imgRGB.naturalHeight;   // RGB pixels → stage pixels
    ir.x = b.left + (minX / RW) * b.width;
    ir.y = b.top  + (minY / RH) * b.height;
    ir.w = ((maxX - minX) / RW) * b.width;
    ir.h = ((maxY - minY) / RH) * b.height;
  } else {
    ir.x = IR_DEFAULT.x; ir.y = IR_DEFAULT.y; ir.w = IR_DEFAULT.w; ir.h = IR_DEFAULT.h;
  }
  clampIR(); applyIR();
}
function centerIR() { const box = rgbBox(); ir.x = box.left + (box.width - ir.w) / 2; ir.y = box.top + (box.height - ir.h) / 2; clampIR(); applyIR(); }
// Pointer -> SCENE coordinates (undo the zoom/pan transform), so IR drag/resize
// keep working at any zoom. ir.x/y/w/h all live in this (untransformed) space.
function stagePoint(e) { const r = stageRGB.getBoundingClientRect();
  return { x: (e.clientX - r.left - view.panX) / view.zoom, y: (e.clientY - r.top - view.panY) / view.zoom }; }

// Left click on the IR panel = pick an IR point; left DRAG = move the panel.
// (They're told apart by a small screen-space travel threshold, so a pick never
// nudges the box.) Right button falls through to the stage's pan handler.
irPanel.addEventListener("pointerdown", e => {
  if (e.target === irResize || e.button !== 0) return;
  e.preventDefault(); irPanel.setPointerCapture(e.pointerId);
  const p0 = stagePoint(e), grabX = p0.x - ir.x, grabY = p0.y - ir.y;
  let moved = false;
  function move(ev) {
    const q = stagePoint(ev);
    if (!moved && Math.hypot((q.x - p0.x) * view.zoom, (q.y - p0.y) * view.zoom) > DRAG_PX) moved = true;
    if (moved) { irUserMoved = true; ir.x = q.x - grabX; ir.y = q.y - grabY; clampIR(); applyIR(); }
  }
  function up(ev) {
    irPanel.releasePointerCapture(e.pointerId);
    irPanel.removeEventListener("pointermove", move); irPanel.removeEventListener("pointerup", up);
    if (!moved) pickIR(stagePoint(ev));   // it was a click, not a drag → record an IR point
  }
  irPanel.addEventListener("pointermove", move); irPanel.addEventListener("pointerup", up);
});
// Drag corner to resize (aspect-locked).
irResize.addEventListener("pointerdown", e => {
  if (e.button !== 0) return;   // right button falls through to pan
  e.preventDefault(); e.stopPropagation(); irUserMoved = true; irResize.setPointerCapture(e.pointerId);
  const start = stagePoint(e), startW = ir.w, a = irAspect(), sw = stageRGB.clientWidth, sh = stageRGB.clientHeight;
  function move(ev) { const q = stagePoint(ev); let w = Math.max(IR_MIN, startW + (q.x - start.x)), h = w / a;
    if (ir.x + w > sw) { w = sw - ir.x; h = w / a; } if (ir.y + h > sh) { h = sh - ir.y; w = h * a; } ir.w = w; ir.h = h; applyIR(); }
  function up() { irResize.releasePointerCapture(e.pointerId); irResize.removeEventListener("pointermove", move); irResize.removeEventListener("pointerup", up); }
  irResize.addEventListener("pointermove", move); irResize.addEventListener("pointerup", up);
});
$("btnCenterIR").addEventListener("click", () => { irUserMoved = true; centerIR(); });
$("btnResetIR").addEventListener("click", () => { irUserMoved = false; initIR(); });
btnToggleIR.addEventListener("click", toggleIR);
irOpacityInput.addEventListener("input", applyIROpacity);
new ResizeObserver(() => { applyView(); if (!imgRGB) return; if (!irUserMoved) initIR(); else { clampIR(); applyIR(); } }).observe(stageRGB);
initIR(); applyIROpacity(); resetView();   // place the (empty) IR panel at its default box + opacity, view at fit

// ============================================================================
//  POINT-PAIR PICKING
//  Flow: click a landmark on the IR overlay → (press I to hide IR) → click the
//  same landmark on the RGB = one match. Points accumulate per frame; the fit
//  (Piece 3) pools every frame's pairs into one homography for the folder.
// ============================================================================
function curFrame() { let f = framePicks.get(fi); if (!f) { f = { ir: [], rgb: [] }; framePicks.set(fi, f); } return f; }
function totalPairs() { let n = 0; for (const f of framePicks.values()) n += Math.min(f.ir.length, f.rgb.length); return n; }
// Resume the alternation state for the frame we're now on (it may already hold
// picks): if an IR point is dangling (no RGB partner yet), the next click is RGB.
function syncWaiting() { const f = curFrame(); waiting = (f.ir.length > f.rgb.length) ? "rgb" : "ir"; }
function resetPicks() { framePicks = new Map(); waiting = "ir"; drawMarks(); updatePickUI(); }

// --- coordinate maps (all go through the CURRENT geometry, so markers track the
//     IR panel / window size, and picks are correct at any zoom) ---------------
function irPixToScene(ix, iy) { return [ ir.x + (ix / imgIR.naturalWidth) * ir.w,  ir.y + (iy / imgIR.naturalHeight) * ir.h ]; }
function sceneToIrPix(sx, sy) { return [ (sx - ir.x) / ir.w * imgIR.naturalWidth,  (sy - ir.y) / ir.h * imgIR.naturalHeight ]; }
function rgbPixToScene(rx, ry) { const b = rgbBox(); return [ b.left + rx / imgRGB.naturalWidth * b.width, b.top + ry / imgRGB.naturalHeight * b.height ]; }
function sceneToRgbPix(sx, sy) { const b = rgbBox(); return [ (sx - b.left) / b.width * imgRGB.naturalWidth, (sy - b.top) / b.height * imgRGB.naturalHeight ]; }
function sceneToScreen(sx, sy) { return [ view.panX + sx * view.zoom, view.panY + sy * view.zoom ]; }

function pickIR(sp) {
  if (!imgIR || waiting !== "ir") return;
  const [ix, iy] = sceneToIrPix(sp.x, sp.y);
  if (ix < 0 || iy < 0 || ix >= imgIR.naturalWidth || iy >= imgIR.naturalHeight) return;   // clicked outside the IR image
  curFrame().ir.push([ix, iy]); waiting = "rgb"; drawMarks(); updatePickUI(); touchPicks();
}
function pickRGB(sp) {
  if (!imgRGB || waiting !== "rgb") return;
  const [rx, ry] = sceneToRgbPix(sp.x, sp.y);
  if (rx < 0 || ry < 0 || rx >= imgRGB.naturalWidth || ry >= imgRGB.naturalHeight) return;  // clicked off the RGB (letterbox)
  curFrame().rgb.push([rx, ry]); waiting = "ir"; drawMarks(); updatePickUI(); touchPicks();
}
function undo() {
  if (!imgRGB) return;
  const f = curFrame();
  if (f.ir.length > f.rgb.length) { f.ir.pop(); }                 // drop the dangling IR point
  else if (f.ir.length) { f.ir.pop(); f.rgb.pop(); }              // drop the last completed pair
  waiting = "ir"; drawMarks(); updatePickUI(); touchPicks();
}
function clearFrame() { if (!imgRGB) return; framePicks.set(fi, { ir: [], rgb: [] }); waiting = "ir"; drawMarks(); updatePickUI(); touchPicks(); }

// AUTO-PLACE: turn the CURRENT IR-overlay placement into correspondences. For each
// node of a grid over the IR image we take the IR pixel and pair it with the RGB
// pixel sitting at the SAME on-screen spot under the present box (drag = translate,
// resize = scale). Fitting these reproduces that scale+translate — a fast way to
// convert a hand-adjusted overlay into a homography without clicking points by hand.
// (Both halves land at the same screen location, so the fit's RMSE ≈ 0 by design;
// the 8-DOF homography model reproduces the box most faithfully.) Replaces this
// frame's points with the fresh grid.
const GRID_COLS = 6, GRID_ROWS = 4, GRID_INSET = 0.08;   // inset so matches stay off the very edge
function autoPlacePoints() {
  if (!imgIR || !imgRGB) return;
  const RW = imgRGB.naturalWidth, RH = imgRGB.naturalHeight, IW = imgIR.naturalWidth, IH = imgIR.naturalHeight;
  const irPts = [], rgbPts = [];
  for (let r = 0; r < GRID_ROWS; r++) for (let c = 0; c < GRID_COLS; c++) {
    const fx = GRID_INSET + (c / (GRID_COLS - 1)) * (1 - 2 * GRID_INSET);
    const fy = GRID_INSET + (r / (GRID_ROWS - 1)) * (1 - 2 * GRID_INSET);
    const ix = fx * IW, iy = fy * IH;                       // IR image pixel
    const [sx, sy] = irPixToScene(ix, iy);                  // → scene (on-screen) point via the box
    const [rx, ry] = sceneToRgbPix(sx, sy);                 // → RGB pixel at that same spot
    if (rx < 0 || ry < 0 || rx >= RW || ry >= RH) continue; // RGB match fell off the image → skip
    irPts.push([ix, iy]); rgbPts.push([rx, ry]);
  }
  if (!irPts.length) { showError("The IR overlay isn't over the RGB image — move/resize it onto the RGB, then Auto-place."); setTimeout(clearError, 3500); return; }
  framePicks.set(fi, { ir: irPts, rgb: rgbPts });           // replace this frame's points with the grid
  waiting = "ir";
  drawMarks(); updatePickUI(); touchPicks();
}

// Which pair index is nearest the given SCENE point (within ~12 screen px), by
// testing both its IR marker and its RGB marker. -1 if none is close enough.
function hitPair(sp) {
  const f = curFrame(), thr = 12 / view.zoom;   // 12 px on screen, at any zoom
  let best = -1, bestD = thr;
  const test = (sx, sy, i) => { const d = Math.hypot(sx - sp.x, sy - sp.y); if (d < bestD) { bestD = d; best = i; } };
  for (let i = 0; i < f.ir.length; i++)  { const [sx, sy] = irPixToScene(f.ir[i][0], f.ir[i][1]);  test(sx, sy, i); }
  for (let i = 0; i < f.rgb.length; i++) { const [sx, sy] = rgbPixToScene(f.rgb[i][0], f.rgb[i][1]); test(sx, sy, i); }
  return best;
}
// Remove correspondence i (both halves if it's a completed pair; the dangling IR
// alone if its RGB half isn't placed yet). Remaining points renumber.
function removePair(i) {
  const f = curFrame();
  if (i < f.rgb.length) f.rgb.splice(i, 1);
  if (i < f.ir.length)  f.ir.splice(i, 1);
  syncWaiting(); drawMarks(); updatePickUI(); touchPicks();
}
// Middle-click on a point deletes it. Middle-clicks on the IR panel bubble here
// (the panel only handles the left button).
stageRGB.addEventListener("pointerdown", e => {
  if (e.button !== 1 || !imgRGB) return;
  e.preventDefault();
  const i = hitPair(stagePoint(e));
  if (i >= 0) removePair(i);
});

// Left click anywhere on the stage (with IR hidden / off the panel) = pick RGB.
// A drag (or right-drag pan) is excluded by the travel threshold; clicks that
// land on a visible IR panel are left for the panel's own handler.
stageRGB.addEventListener("pointerdown", e => {
  if (e.button !== 0 || !imgRGB) return;
  if (irVisible && irPanel.contains(e.target)) return;
  const x0 = e.clientX, y0 = e.clientY;
  function up(ev) {
    window.removeEventListener("pointerup", up);
    if (Math.hypot(ev.clientX - x0, ev.clientY - y0) <= DRAG_PX) pickRGB(stagePoint(ev));
  }
  window.addEventListener("pointerup", up);
});
$("btnUndo").addEventListener("click", undo);
$("btnClearFrame").addEventListener("click", clearFrame);
$("btnAutoPoints").addEventListener("click", autoPlacePoints);

function updatePickUI() {
  const st = $("pickStatus"), cnt = $("pickCount");
  // Fit is enabled if ANY subset has ≥4 pairs (the button fits them all at once).
  let canFit = false; for (let k = 0; k < subsets.length; k++) if (subsetPairCount(k) >= 4) { canFit = true; break; }
  $("btnFit").disabled = !(imgRGB && canFit);
  $("btnFit").textContent = subsets.length > 1 ? "✓ Fit all" : "✓ Fit";
  st.classList.remove("turn-ir", "turn-rgb"); cnt.classList.remove("warn");
  if (!imgRGB) { st.textContent = "Load a folder to start picking"; cnt.textContent = "—"; return; }
  if (waiting === "ir") {
    st.innerHTML = irVisible ? "① Click the landmark on the <b>IR</b>"
                             : "① Press <b>I</b> to show IR, then click it";
    st.classList.add("turn-ir");
  } else {
    st.innerHTML = irVisible ? "② Press <b>I</b> to hide IR, then click it on <b>RGB</b>"
                             : "② Click the matching point on <b>RGB</b>";
    st.classList.add("turn-rgb");
  }
  const f = curFrame(), done = Math.min(f.ir.length, f.rgb.length), pend = f.ir.length > f.rgb.length;
  const subTot = subsetPairCount(si), multi = subsets.length > 1;
  cnt.innerHTML = `<b>${done}</b> here${pend ? "+1" : ""} · <b>${subTot}</b> ${multi ? `in subset ${si + 1}` : "total"}`;
  if (subTot < 4) { cnt.innerHTML += " · need ≥4"; cnt.classList.add("warn"); }
}

// Markers are drawn on a stage-sized HUD canvas in SCREEN space (crisp, constant
// size at any zoom); their scene positions come from the current geometry.
function drawMarks() {
  const c = marks, ctx = marksCtx;
  const w = stageRGB.clientWidth, h = stageRGB.clientHeight, dpr = window.devicePixelRatio || 1;
  if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) { c.width = Math.round(w * dpr); c.height = Math.round(h * dpr); }
  c.style.width = w + "px"; c.style.height = h + "px";
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.clearRect(0, 0, w, h);
  if (!imgRGB) return;
  const f = framePicks.get(fi); if (!f) return;
  // connect each matched IR↔RGB pair with a faint coloured line
  const n = Math.min(f.ir.length, f.rgb.length);
  for (let i = 0; i < n; i++) {
    const [ax, ay] = sceneToScreen(...irPixToScene(f.ir[i][0], f.ir[i][1]));
    const [bx, by] = sceneToScreen(...rgbPixToScene(f.rgb[i][0], f.rgb[i][1]));
    ctx.strokeStyle = col(i); ctx.globalAlpha = .45; ctx.lineWidth = 1.5;
    ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx, by); ctx.stroke(); ctx.globalAlpha = 1;
  }
  // IR picks are labelled 1, 2, 3…; their RGB matches 1', 2', 3' (same colour).
  const dot = (sx, sy, i, label) => {
    const [X, Y] = sceneToScreen(sx, sy);
    ctx.beginPath(); ctx.arc(X, Y, 7, 0, 7); ctx.fillStyle = "#fff"; ctx.fill();
    ctx.beginPath(); ctx.arc(X, Y, 5, 0, 7); ctx.fillStyle = col(i); ctx.fill();
    ctx.font = "bold 12px sans-serif"; ctx.lineWidth = 3; ctx.strokeStyle = "rgba(0,0,0,.7)";
    ctx.strokeText(label, X + 9, Y + 4); ctx.fillStyle = "#fff"; ctx.fillText(label, X + 9, Y + 4);
  };
  for (let i = 0; i < f.ir.length; i++)  { const [sx, sy] = irPixToScene(f.ir[i][0], f.ir[i][1]);  dot(sx, sy, i, String(i + 1)); }
  for (let i = 0; i < f.rgb.length; i++) { const [sx, sy] = rgbPixToScene(f.rgb[i][0], f.rgb[i][1]); dot(sx, sy, i, (i + 1) + "'"); }
}

// ============================================================================
//  FITTING + OVERLAYS  — the OpenCV "machinery" lives in fit_server.py. This side
//  only sends the picked correspondences / IR images and shows what comes back;
//  the UI and flow are exactly as before.
// ============================================================================
// Where the OpenCV server is. If this page is served BY fit_server.py
// (http://localhost:8000/) requests are same-origin; opened from file:// they go
// to localhost:8000.
const SERVER = (location.protocol === "http:" || location.protocol === "https:") ? "" : "http://localhost:8000";
async function postJSON(path, body) {
  const r = await fetch(SERVER + path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
  let j = null; try { j = await r.json(); } catch {}
  if (!r.ok || !j || j.ok === false) throw new Error((j && j.error) || ("HTTP " + r.status));
  return j;
}
const fileToDataURL = (file) => new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = rej; r.readAsDataURL(file); });

function showResults() { $("results").classList.add("show"); }
function hideResults() { $("results").classList.remove("show"); }

// Fit the ACTIVE subset: pool the completed pairs of the frames in its range and
// send them to OpenCV. (subsetPairs() tags each correspondence with its frame name.)
// Fit ONE subset: pool its frames' pairs, POST to OpenCV, remember the result.
async function fitSubset(k, thresh) {
  const g = subsetPairs(k);
  const resp = await postJSON("/fit", { correspondences: g.list, ransac_thresh: thresh });
  subsets[k].fit = { models: resp.models, thresh, n_pairs: resp.n_pairs, list: g.list, frames: g.frames,
    ir_size: imgIR ? [imgIR.naturalWidth, imgIR.naturalHeight] : null,
    rgb_size: imgRGB ? [imgRGB.naturalWidth, imgRGB.naturalHeight] : null };
  return subsets[k].fit;
}
// Point the results screen at subset k's stored fit (no network) + make it active.
function loadFit(k) {
  const fit = subsets[k] && subsets[k].fit; if (!fit) return;
  si = k;
  lastFit = { list: fit.list, frames: fit.frames, n_pairs: fit.n_pairs, subset: k,
    ir_size: fit.ir_size, rgb_size: fit.rgb_size, thresh: fit.thresh, models: fit.models, imported: fit.imported };
  $("ransacThresh").value = fit.thresh;
}
const fitFailHTML = (e) => `<div class="fit-card bad"><h3>Couldn’t reach the OpenCV server</h3>` +
  `<p class="err">${e && e.message || e}</p>` +
  `<p class="stat">Start it in this folder:  <code>python fit_server.py</code>, open <code>http://localhost:8000/</code>, then Fit again.</p></div>`;
// FIT ALL: one click fits EVERY subset that has ≥4 pooled pairs, each to its own
// homography. Then it shows the active subset's results (or the first fitted one) —
// use the Subset ▾ switcher to review the rest.
async function fitAll() {
  const targets = [];
  for (let k = 0; k < subsets.length; k++) if (subsetPairCount(k) >= 4) targets.push(k);
  if (!targets.length) return;
  const thresh = clamp(parseFloat($("ransacThresh").value) || 6, 0.1, 1e4), multi = subsets.length > 1;
  showResults();
  $("fitDetails").classList.add("show");   // open the matrices drawer while/after fitting
  try {
    for (let i = 0; i < targets.length; i++) {
      const k = targets[i];
      if (subsets[k].fit) continue;   // already fitted (imported, or fit earlier & unedited) — keep it, no server call
      $("resultsBody").innerHTML = `<p class="stat">Fitting ${multi ? `subset ${k + 1} — ${i + 1}/${targets.length} ` : ""}with OpenCV…</p>`;
      await fitSubset(k, thresh);
    }
    loadFit(targets.includes(si) ? si : targets[0]);
    renderResults(); refreshOverlayControls(); renderSubsetTabs();
  } catch (e) {
    refreshOverlayControls();
    $("resultsBody").innerHTML = fitFailHTML(e);
  }
}
// RE-FIT: re-run ONLY the subset currently shown (e.g. after changing the RANSAC
// threshold). Bound to the Re-fit button and Enter in the threshold box.
async function callFit() {
  const k = lastFit ? lastFit.subset : si;
  if (subsetPairCount(k) < 4) return;
  const thresh = clamp(parseFloat($("ransacThresh").value) || 6, 0.1, 1e4);
  showResults();
  $("fitDetails").classList.add("show");
  $("resultsBody").innerHTML = `<p class="stat">Fitting with OpenCV…</p>`;
  try {
    await fitSubset(k, thresh);
    loadFit(k);
    renderResults(); refreshOverlayControls(); renderSubsetTabs();
  } catch (e) {
    refreshOverlayControls();
    $("resultsBody").innerHTML = fitFailHTML(e);
  }
}

function prettyMat(m) { return m.map(r => "[ " + r.map(v => v.toExponential(6).padStart(15)).join("  ") + " ]").join("\n"); }
// One result card from a server model object (matrix + rmse + optional inliers / sim decode).
function fitCard(m, title) {
  if (!m) return `<div class="fit-card bad"><h3>${title}</h3><p class="err">Fit failed — degenerate points.</p></div>`;
  let stat;
  if (m.inliers != null) { const out = m.n - m.inliers;
    stat = `Inliers: <b class="ok">${m.inliers}/${m.n}</b>${out ? ` · <b class="err">${out} rejected</b>` : ""} · inlier RMSE: <b>${m.rmse.toFixed(2)} px</b>`;
  } else stat = `Reprojection RMSE: <b>${m.rmse.toFixed(2)} px</b> (over all ${m.n})`;
  let extra = "";
  if (m.scale != null) extra = `<div class="stat">scale <b>${m.scale.toFixed(4)}</b> · translation <b>(${m.translation[0].toFixed(1)}, ${m.translation[1].toFixed(1)})</b> px</div>`;
  return `<div class="fit-card"><h3>${title}</h3><div class="stat">${stat}</div>${extra}<pre class="mat">H =\n${prettyMat(m.matrix)}</pre></div>`;
}
function renderResults() {
  const g = GROUPS[gi], M = lastFit.models || {};
  const sub = subsets.length > 1 ? ` · subset ${lastFit.subset + 1} (${subsetLabel(lastFit.subset)})` : "";
  $("resultsTitle").textContent = "Fit results — " + (g ? shortLabel(g.key) : "") + sub;
  let html = `<p class="stat"><b>${lastFit.n_pairs}</b> point pair(s) pooled from <b>${lastFit.frames}</b> frame(s) · RANSAC threshold <b>${lastFit.thresh} px</b> · ${lastFit.imported ? "imported from a saved fit" : "fit by OpenCV"}.</p>`;
  // An imported fit only carries the ONE model it was saved with, so we render just the
  // present slots (no phantom "Fit failed" cards). A live fit keeps all four, showing a
  // failed card for any degenerate slot.
  const card = (key, title) => M[key] ? fitCard(M[key], title) : (lastFit.imported ? "" : fitCard(null, title));
  const hCards = card("h_ls", "Least-squares · all pairs") + card("h_rn", "RANSAC + LS refit on inliers");
  if (hCards) html += `<div class="sect">Full projective homography — 8 DOF</div>` + hCards;
  const sCards = card("s_ls", "Least-squares · all pairs") + card("s_rn", "RANSAC + LS refit on inliers");
  if (sCards) html += `<div class="sect">Scale + translation (no rotation) — 3 DOF</div>` + sCards;
  if (lastFit.imported) html += `<p class="stat">Only the model chosen at save time was stored. Re-Fit (needs the OpenCV server) to recompute all four models.</p>`;
  $("resultsBody").innerHTML = html;
  renderSubsetSwitch();
}
$("btnFit").addEventListener("click", fitAll);
$("subsetSwitch").addEventListener("change", e => reviewSubset(+e.target.value));
$("btnBackPick").addEventListener("click", hideResults);
$("btnRefit").addEventListener("click", callFit);
$("ransacThresh").addEventListener("keydown", e => { if (e.key === "Enter") callFit(); });

// ---- OVERLAYS + SAVE (player) ----------------------------------------------
// The warp (IR→RGB) is done by OpenCV on the server; here we layer the returned
// warped-IR PNG over the RGB in a full-screen player (opacity live, zoom/pan,
// ← → to step frames) and blend into a flat composite only at save time.
let OVERLAYS = [];   // the set currently on screen — [{ name, rgbUrl, warpUrl }]
let ovIdx = 0, ovIrShown = true;
let overlaySig = null;   // signature (frames + matrix) of OVERLAYS
// Cache of warped sets keyed by signature, so switching between subsets (or leaving
// the player and coming back) reuses whatever's already warped instead of redoing it.
// Bounded to CACHE_MAX sets (oldest evicted) as a safety net; a folder switch clears
// it. Since subsets partition the frames, all bands together hold no more overlays
// than one whole-video set would.
const overlayCache = new Map();
const CACHE_MAX = 16;
function cachePut(sig, set) {
  overlayCache.set(sig, set);
  while (overlayCache.size > CACHE_MAX) {
    let victim = null;                                 // evict the oldest entry that ISN'T on screen
    for (const key of overlayCache.keys()) { if (key !== overlaySig) { victim = key; break; } }
    if (victim === null) break;
    const gone = overlayCache.get(victim); overlayCache.delete(victim);
    for (const o of gone) { try { URL.revokeObjectURL(o.rgbUrl); } catch {} try { URL.revokeObjectURL(o.warpUrl); } catch {} }
  }
}
// Drop the whole cache (folder switch / restart) — revoke every set's blob URLs.
function clearOverlayCache() {
  for (const set of overlayCache.values()) for (const o of set) { try { URL.revokeObjectURL(o.rgbUrl); } catch {} try { URL.revokeObjectURL(o.warpUrl); } catch {} }
  overlayCache.clear();
}
function loadImageFile(file) {
  return new Promise((res, rej) => { const url = URL.createObjectURL(file); const im = new Image();
    im.onload = () => res({ img: im, url }); im.onerror = () => { URL.revokeObjectURL(url); rej(new Error("read " + file.name)); }; im.src = url; });
}
function loadImg(url) { return new Promise((res, rej) => { const im = new Image(); im.onload = () => res(im); im.onerror = rej; im.src = url; }); }
const curAlpha = () => clamp(parseFloat($("ovAlpha").value) / 100 || 0, 0, 1);
function applyOvAlpha() { document.documentElement.style.setProperty("--ov-alpha", curAlpha()); $("ovAlphaVal").textContent = $("ovAlpha").value + "%"; ovSetIR(true); }
// Hide / show the warped-IR layer (I). Hiding wins over the opacity var via an
// inline opacity:0; moving the slider (applyOvAlpha) brings it back.
function ovSetIR(show) { ovIrShown = show; $("ovIr").style.opacity = show ? "" : "0"; }
// A flat imported composite has no separate IR layer to hide/show — ignore I on it.
function ovToggleIR() { const o = OVERLAYS[ovIdx]; if (o && o.composite) return; ovSetIR(!ovIrShown); }
function availableModels() {
  const M = lastFit && lastFit.models; if (!M) return [];
  return ["h_rn", "h_ls", "s_rn", "s_ls"].filter(k => M[k]).map(k => ({ key: k, label: M[k].label, matrix: M[k].matrix }));
}
function chosenModel() { const m = availableModels(); return m.find(x => x.key === $("ovModel").value) || m[0] || null; }
function refreshOverlayControls() {
  const sel = $("ovModel"), models = availableModels(), prev = sel.value;
  sel.innerHTML = "";
  for (const m of models) { const o = document.createElement("option"); o.value = m.key; o.textContent = m.label; sel.appendChild(o); }
  if (models.some(m => m.key === prev)) sel.value = prev;
  const has = models.length > 0;
  sel.disabled = !has; $("btnGenOverlays").disabled = !has; $("btnSaveH").disabled = !has;
  $("btnSaveAll").disabled = !has;   // Save all exports every fitted band, so it only needs a fit
  updateSaveHint();    // remind the user which folder to pick so files update in place
  syncOverlayView();   // point the player at THIS band's cached overlays (or empty)
}
// The results-header subset switcher: lists ALL subsets (shown once there are ≥2),
// so you can hop between bands without leaving this screen. Fitted bands are marked
// ✓; picking a not-yet-fitted band drops you back onto it in the picking view.
function renderSubsetSwitch() {
  const wrap = $("subsetSwitchWrap"), sel = $("subsetSwitch");
  wrap.style.display = subsets.length > 1 ? "" : "none";
  if (subsets.length <= 1) return;
  const cur = lastFit ? lastFit.subset : si;
  sel.innerHTML = "";
  subsets.forEach((s, k) => { const o = document.createElement("option"); o.value = String(k);
    o.textContent = `${k + 1}: ${subsetLabel(k)} ${s.fit ? "✓" : "· not fit"}`; sel.appendChild(o); });
  sel.value = String(cur);
}
// Jump the results screen to another subset (from the switcher). Fitted → load its
// stored fit and re-render in place (no Back-and-refit). Not fitted → leave the
// results screen and drop onto that band in the picking view so you can fit it.
function reviewSubset(k) {
  if (k < 0 || k >= subsets.length) return;
  if (!subsets[k].fit) { hideResults(); selectSubset(k); return; }   // not fit → go pick it
  loadFit(k);                               // fitted → load its stored result in place
  renderResults(); refreshOverlayControls();
}

// ---- overlay player: scroll = zoom (about cursor), right-drag = pan ---------
const ovStage = $("ovStage"), ovScene = $("ovScene");
const ovView = { zoom: 1, panX: 0, panY: 0 };
function ovClampView() {
  const sw = ovStage.clientWidth, sh = ovStage.clientHeight;
  ovView.zoom = clamp(ovView.zoom, 1, 20);
  ovView.panX = clamp(ovView.panX, sw * (1 - ovView.zoom), 0);
  ovView.panY = clamp(ovView.panY, sh * (1 - ovView.zoom), 0);
}
function ovApplyView() { ovClampView(); ovScene.style.transform = `translate(${ovView.panX}px, ${ovView.panY}px) scale(${ovView.zoom})`; }
function ovResetView() { ovView.zoom = 1; ovView.panX = 0; ovView.panY = 0; ovApplyView(); }
function ovZoomAt(clientX, clientY, f) {
  const r = ovStage.getBoundingClientRect(), cx = clientX - r.left, cy = clientY - r.top;
  const sx = (cx - ovView.panX) / ovView.zoom, sy = (cy - ovView.panY) / ovView.zoom;
  ovView.zoom = clamp(ovView.zoom * f, 1, 20);
  ovView.panX = cx - sx * ovView.zoom; ovView.panY = cy - sy * ovView.zoom; ovApplyView();
}
ovStage.addEventListener("wheel", e => { if (!OVERLAYS.length) return; e.preventDefault(); ovZoomAt(e.clientX, e.clientY, e.deltaY < 0 ? 1.15 : 1 / 1.15); }, { passive: false });
let ovPan = null;
ovStage.addEventListener("pointerdown", e => { if (e.button !== 2 || !OVERLAYS.length) return; e.preventDefault();
  ovPan = { sx: e.clientX, sy: e.clientY, px: ovView.panX, py: ovView.panY }; try { ovStage.setPointerCapture(e.pointerId); } catch {} });
ovStage.addEventListener("pointermove", e => { if (!ovPan) return; ovView.panX = ovPan.px + (e.clientX - ovPan.sx); ovView.panY = ovPan.py + (e.clientY - ovPan.sy); ovApplyView(); });
function ovEndPan(e) { if (ovPan) { try { ovStage.releasePointerCapture(e.pointerId); } catch {} ovPan = null; } }
ovStage.addEventListener("pointerup", ovEndPan);
ovStage.addEventListener("pointercancel", ovEndPan);
ovStage.addEventListener("contextmenu", e => e.preventDefault());
new ResizeObserver(() => ovApplyView()).observe(ovStage);

// ---- overlay player: frame navigation --------------------------------------
function ovShow(i) {
  if (!OVERLAYS.length) return;
  ovIdx = clamp(i, 0, OVERLAYS.length - 1);
  const o = OVERLAYS[ovIdx], stem = o.name.replace(/_overlay\.\w+$/, ""), flat = !!o.composite;
  // Imported composites are already flat (RGB+IR blended at save time), so we show the
  // single image and hide the (empty) IR layer. The opacity slider / hide-IR can't act
  // on a baked image, so we DISABLE them (rather than let them fail silently) and point
  // the user at "Generate overlays" for a live, adjustable IR layer.
  if (flat) { $("ovBase").src = o.compositeUrl; $("ovIr").removeAttribute("src"); }
  else { $("ovBase").src = o.rgbUrl; $("ovIr").src = o.warpUrl; }
  $("ovAlpha").disabled = flat;
  $("ovAlpha").title = flat ? "This is a saved, already-flattened overlay — click “Generate overlays” for a live IR layer you can fade with this slider or toggle with I" : "";
  $("ovAlphaVal").textContent = flat ? "baked" : ($("ovAlpha").value + "%");
  $("ovBadge").textContent = stem + (flat ? " · saved overlay — Generate for live opacity" : "");
  $("ovFrameLabel").textContent = `overlay ${ovIdx + 1}/${OVERLAYS.length} · ${stem}`;
  $("ovSeek").value = String(ovIdx);
}
function ovStep(d) { ovShow(ovIdx + d); }
function ovNavEnabled(on) {
  ["ovFirst", "ovPrev", "ovNext", "ovLast"].forEach(id => $(id).disabled = !on);
  $("ovSeek").disabled = !on; $("ovSeek").max = String(Math.max(1, OVERLAYS.length - 1));
}
$("ovFirst").addEventListener("click", () => ovShow(0));
$("ovPrev").addEventListener("click", () => ovStep(-1));
$("ovNext").addEventListener("click", () => ovStep(1));
$("ovLast").addEventListener("click", () => ovShow(OVERLAYS.length - 1));
$("ovSeek").addEventListener("input", e => ovShow(+e.target.value));

// Detach the on-screen set + reset the player UI. Does NOT revoke blob URLs — the
// cache owns them (freed by eviction / clearOverlayCache).
function clearOverlays() {
  // Imported-composite entries own their blob URL (they're NOT in overlayCache, which
  // owns the rgbUrl/warpUrl of the server-warped sets) — free them here as we detach.
  for (const o of OVERLAYS) if (o.composite && o.compositeUrl) { try { URL.revokeObjectURL(o.compositeUrl); } catch {} }
  OVERLAYS = []; overlaySig = null; ovNavEnabled(false);
  $("ovBase").removeAttribute("src"); $("ovIr").removeAttribute("src");
  $("ovBadge").textContent = "—"; $("ovFrameLabel").textContent = "—";
  $("ovEmpty").style.display = ""; ovResetView();
}
// The warp list for the CURRENT band: its frames, each warped by the chosen model.
function overlayWorkList() {
  const group = GROUPS[gi]; if (!group) return { work: [] };
  const model = chosenModel(); if (!model) return { work: [] };
  const k = lastFit ? lastFit.subset : si, [a, b] = subsetRange(k), work = [];
  for (let f = a; f <= b; f++) work.push({ pair: group.pairs[f], matrix: model.matrix });
  return { work };
}
// A fingerprint of what this band's overlays WOULD be (frames + matrix): the cache
// key, and the test for whether the set on screen still matches the band.
const workSig = (work) => JSON.stringify(work.map(w => [w.pair.name, w.matrix]));
function overlaySignature() { return workSig(overlayWorkList().work); }
// Point the player at the current band's overlays: reuse the cached set if we've
// warped it, else show it empty (Generate will warp). Keeps the player + Save button
// in step with the band on screen after a fit / band switch / model change.
function syncOverlayView() {
  const sig = overlaySignature();
  if (overlayCache.has(sig)) {
    OVERLAYS = overlayCache.get(sig); overlaySig = sig;
    ovNavEnabled(true);
    if (!$("fitDetails").classList.contains("show")) { $("ovEmpty").style.display = "none"; ovShow(clamp(ovIdx, 0, OVERLAYS.length - 1)); }
    return;
  }
  // No live (server-warped) set yet — fall back to the IMPORTED overlay jpegs, but ONLY
  // for a still-imported (un-re-fitted) subset: once you re-fit, the saved composites
  // are stale for the new geometry, so we show the empty "Generate overlays" prompt
  // instead. "Generate overlays" re-warps live (and overwrites the saved ones).
  const imp = (lastFit && lastFit.imported) ? importedOverlaysForBand(lastFit.subset) : [];
  clearOverlays();
  if (imp.length) {
    OVERLAYS = imp; overlaySig = null; ovNavEnabled(true);
    if (!$("fitDetails").classList.contains("show")) { $("ovEmpty").style.display = "none"; ovShow(0); }
  }
}
// Build an OVERLAYS-style list from the imported <stem>_overlay.jpg files covering band
// k's frames (flat composites — flagged .composite so ovShow renders them directly).
function importedOverlaysForBand(k) {
  const g = GROUPS[gi]; if (!g || !g.saved || !g.saved.overlays.size) return [];
  const [a, b] = subsetRange(k), out = [];
  for (let f = a; f <= b; f++) {
    const stem = frameStem(f);
    let file = null;
    for (const ext of ["jpg", "jpeg", "png"]) { const c = g.saved.overlays.get(`${stem}_overlay.${ext}`); if (c) { file = c; break; } }
    if (file) out.push({ name: `${stem}_overlay.jpg`, compositeUrl: URL.createObjectURL(file), composite: true });
  }
  return out;
}
function revealPlayer() { $("fitDetails").classList.remove("show"); $("ovEmpty").style.display = "none"; ovNavEnabled(true); }
// Frames + matrix for a specific fitted subset k under model `modelKey`.
function bandWorkList(k, modelKey) {
  const group = GROUPS[gi], fit = subsets[k] && subsets[k].fit; if (!group || !fit || !fit.models[modelKey]) return [];
  const [a, b] = subsetRange(k), matrix = fit.models[modelKey].matrix, work = [];
  for (let f = a; f <= b; f++) work.push({ pair: group.pairs[f], matrix });
  return work;
}
// Warp a work list into an overlays array (throws on failure after cleaning up the
// partial set). Pure: the caller decides whether to cache / display / save.
async function buildOverlays(work, onProgress) {
  const built = [];
  for (let i = 0; i < work.length; i++) {
    if (onProgress) onProgress(i, work.length);
    let rgb, irDataUrl;
    try { rgb = await loadImageFile(work[i].pair.rgbFile); irDataUrl = await fileToDataURL(work[i].pair.irFile); }
    catch { if (rgb) URL.revokeObjectURL(rgb.url); continue; }
    let warpUrl;
    try {
      const resp = await postJSON("/warp", { matrix: work[i].matrix, ir_png_b64: irDataUrl.split(",")[1],
        rgb_w: rgb.img.naturalWidth, rgb_h: rgb.img.naturalHeight });
      warpUrl = URL.createObjectURL(await (await fetch("data:image/png;base64," + resp.warp_png_b64)).blob());
    } catch (e) {
      URL.revokeObjectURL(rgb.url);
      for (const o of built) { try { URL.revokeObjectURL(o.rgbUrl); } catch {} try { URL.revokeObjectURL(o.warpUrl); } catch {} }   // drop the partial set
      throw e;
    }
    built.push({ name: `${work[i].pair.name.replace(/\.png$/i, "")}_overlay.jpg`, rgbUrl: rgb.url, warpUrl });
    await new Promise(r => setTimeout(r, 0));   // yield so the UI stays responsive
  }
  return built;
}
async function generateOverlays() {
  const { work } = overlayWorkList();
  if (!work.length) { $("ovEmpty").innerHTML = "Fit this subset, then “Generate overlays”."; $("ovEmpty").style.display = ""; return; }
  const sig = workSig(work);
  if (overlayCache.has(sig)) {                    // already warped this band — reuse instantly
    OVERLAYS = overlayCache.get(sig); overlaySig = sig; applyOvAlpha();
    revealPlayer(); ovResetView(); ovShow(clamp(ovIdx, 0, OVERLAYS.length - 1));
    return;
  }
  clearOverlays(); applyOvAlpha();
  revealPlayer(); $("btnGenOverlays").disabled = true; $("ovLoading").classList.add("show");
  const prog = $("ovProgress");
  let built;
  try { built = await buildOverlays(work, (i, n) => { prog.textContent = `Warping ${i + 1}/${n}… (OpenCV)`; }); }
  catch (e) { $("ovLoading").classList.remove("show"); prog.innerHTML = `<span class="err">Warp failed — is the server running? ${e && e.message || e}</span>`; $("btnGenOverlays").disabled = false; $("ovEmpty").style.display = ""; return; }
  $("ovLoading").classList.remove("show");
  $("btnGenOverlays").disabled = false;
  if (built.length) { OVERLAYS = built; overlaySig = sig; cachePut(sig, built); $("ovEmpty").style.display = "none"; ovNavEnabled(true); ovResetView(); ovShow(0); }
  else { $("ovEmpty").style.display = ""; }
}
// ── Serialisation — everything goes into just TWO files ─────────────────────
// A subset's frame span, embedded in the saved JSON.
function subsetInfo(k) {
  const g = GROUPS[gi], [a, b] = subsetRange(k);
  return { index: k, name: subsets[k].name || null, label: subsetLabel(k),
    frame_start: g && g.pairs[a] ? g.pairs[a].name : null, frame_end: g && g.pairs[b] ? g.pairs[b].name : null,
    frame_index_start: a, frame_index_end: b, n_frames: b - a + 1 };
}
// One subset's row for the homography file: matrix + stats + which frames it covers.
function subsetMatrixRow(k, modelKey) {
  const fit = subsets[k].fit, m = fit.models[modelKey];
  const row = Object.assign(subsetInfo(k), { model: m.label, matrix: m.matrix,
    n_pairs: m.n, rmse_px: +m.rmse.toFixed(4), ransac_threshold_px: fit.thresh });
  if (m.inliers != null) row.n_inliers = m.inliers;
  if (m.scale != null) { row.scale = +m.scale.toFixed(6); row.rotation_deg = +m.rotation_deg.toFixed(4); row.translation_px = [+m.translation[0].toFixed(2), +m.translation[1].toFixed(2)]; }
  return row;
}
// homography.json content — ONE file, ALWAYS the same schema: { …, n_subsets, subsets:[ row… ] }
// holding every fitted band's matrix + frame span. A single un-split folder is just the
// n_subsets:1 case (one row spanning the whole video), so downstream code has exactly one
// shape to read — it picks the band by frame index regardless of how many there are.
function homographyDoc(keys, modelKey) {
  const g = GROUPS[gi];
  const any = subsets[keys[0]].fit;
  return { group: g ? shortLabel(g.key) : "",
    ir_size: any ? any.ir_size : null, rgb_size: any ? any.rgb_size : null,
    maps: "IR_pixel -> RGB_pixel", note: "each subset's matrix covers frames [frame_index_start..frame_index_end]",
    n_subsets: keys.length, subsets: keys.map(k => subsetMatrixRow(k, modelKey)) };
}
// points.json content — ONE file, ALWAYS the same schema: { …, n_subsets, subsets:[ {span,
// correspondences} ] } for every fitted band. A single un-split folder is just the n_subsets:1
// case. Re-POST a subset's `correspondences` to /fit to reproduce its matrix.
function pointsDoc(keys) {
  const g = GROUPS[gi];
  const any = subsets[keys[0]].fit;
  return { group: g ? shortLabel(g.key) : "",
    ir_size: any ? any.ir_size : null, rgb_size: any ? any.rgb_size : null,
    units: "image pixels", maps: "IR_pixel -> RGB_pixel", n_subsets: keys.length,
    subsets: keys.map(k => { const fit = subsets[k].fit;
      return Object.assign(subsetInfo(k), { ransac_threshold_px: fit.thresh,
        n_pairs: fit.list.length, correspondences: fit.list }); }) };
}
const blobOf = (obj) => new Blob([JSON.stringify(obj, null, 2)], { type: "application/json" });
// EVERY fitted subset that holds the chosen model key, plus the model KEY to use.
// Save writes them ALL in one click (not just the active subset).
function subsetsToSave() {
  const models = availableModels();
  const key = $("ovModel").value || (models[0] && models[0].key) || "h_rn";
  const keys = [];
  for (let k = 0; k < subsets.length; k++) { const f = subsets[k].fit; if (f && f.models && f.models[key]) keys.push(k); }
  return { keys, modelKey: key };
}
// Ask for the output folder. MUST run straight off the click (before any long
// compositing), because showDirectoryPicker needs a live user gesture — if we
// call it after several seconds of encoding, the activation has expired and it
// throws. Returns a dir handle, the string "download" (no File System Access), or
// null (user cancelled).
async function pickSaveDir() {
  if (!window.showDirectoryPicker) return "download";
  // `id` makes the browser reopen the picker where you last saved (per origin), so
  // after the first time you land right on the <Pair-ID>/homography/ folder again.
  try { return await window.showDirectoryPicker({ mode: "readwrite", id: "framePairHomographyOut" }); }
  catch { return null; }
}
// Show which folder to pick so Save overwrites this Pair-ID's own homography/ files.
function updateSaveHint() {
  const el = $("saveHint"); if (!el) return;
  const g = GROUPS[gi];
  el.innerHTML = g ? `→ Save into <code>${escapeHtml(shortLabel(g.key))}/homography/</code> to update this folder` : "";
}
async function putFile(dir, name, blob) {
  if (dir === "download") { const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = name; a.click(); return; }
  const fh = await dir.getFileHandle(name, { create: true });
  const w = await fh.createWritable(); await w.write(blob); await w.close();
}
// Write exactly TWO files — homography.json + points.json — flat in `dir`. Both hold
// every fitted subset (split folder) or the single fit (un-split). No subfolders, no
// per-band files, no manifest.
async function writeHAndPoints(dir, keys, modelKey) {
  await putFile(dir, "homography.json", blobOf(homographyDoc(keys, modelKey)));
  await putFile(dir, "points.json", blobOf(pointsDoc(keys)));
}
function saveSummary(dir, nSub, nOv) {
  const where = dir === "download" ? "Downloaded" : `Saved to “${dir.name}”:`;
  const span = nSub > 1 ? ` (${nSub} subsets)` : "";
  const what = nOv ? `homography.json + points.json${span} + ${nOv} overlay(s)` : `homography.json + points.json${span}`;
  // Nudge if they saved somewhere other than a homography/ folder — re-import only
  // picks up files that live in the Pair-ID's own homography/ sub-folder.
  const tip = (dir !== "download" && dir.name && dir.name.toLowerCase() !== "homography")
    ? `  Tip: to have this auto-import next time, save into the folder's homography/ sub-folder.` : "";
  return `${where} ${2 + nOv} file(s) — ${what}.${tip}`;
}
async function saveHOnly() {
  const { keys, modelKey } = subsetsToSave();
  if (!keys.length) { $("saveStatus").innerHTML = `<span class="err">Nothing to save — Fit the subset first.</span>`; return; }
  const dir = await pickSaveDir(); if (dir === null) return;
  try {
    await writeHAndPoints(dir, keys, modelKey);
    $("saveStatus").textContent = saveSummary(dir, keys.length, 0);
  } catch (e) { $("saveStatus").innerHTML = `<span class="err">Save failed: ${e && e.message || e}</span>`; }
}
// Bake the CURRENT opacity into a flat composite (RGB + warped IR at alpha) per frame.
async function compositeBlob(o, alpha) {
  const [rgb, warp] = await Promise.all([loadImg(o.rgbUrl), loadImg(o.warpUrl)]);
  const c = document.createElement("canvas"); c.width = rgb.naturalWidth; c.height = rgb.naturalHeight;
  const cx = c.getContext("2d"); cx.drawImage(rgb, 0, 0); cx.globalAlpha = alpha; cx.drawImage(warp, 0, 0); cx.globalAlpha = 1;
  // JPEG: the composite is opaque (RGB base) and just a visualization, so lossy is
  // fine — encodes ~5-10× faster and files are ~5× smaller than PNG.
  return await new Promise(r => c.toBlob(r, "image/jpeg", 0.92));
}
// Save the two JSON files + the overlays for EVERY fitted band (warping any that
// aren't cached yet, reusing those that are). Frame names are unique across bands
// (they partition the video), so everything lands flat with no collisions.
async function saveAll() {
  const { keys, modelKey } = subsetsToSave();
  if (!keys.length) { $("saveStatus").innerHTML = `<span class="err">Nothing to save — Fit the subset(s) first.</span>`; return; }
  const dir = await pickSaveDir(); if (dir === null) return;   // pick FIRST, then composite + write into it
  const alpha = curAlpha(), status = $("saveStatus");
  $("btnSaveAll").disabled = true;
  try {
    await writeHAndPoints(dir, keys, modelKey);
    // Gather each band's overlays (cache hit, or warp now) and tally the total.
    const bands = keys.map(k => { const work = bandWorkList(k, modelKey); return { k, work, sig: workSig(work) }; });
    const total = bands.reduce((n, b) => n + b.work.length, 0);
    let saved = 0;
    for (const { k, work, sig } of bands) {
      let set = overlayCache.get(sig);
      if (!set) { status.textContent = `Warping subset ${k + 1}…`; set = await buildOverlays(work, (i, n) => { status.textContent = `Warping subset ${k + 1}: ${i + 1}/${n}…`; }); cachePut(sig, set); }
      for (const o of set) { status.textContent = `Saving overlay ${++saved}/${total} @ ${Math.round(alpha * 100)}%…`; await putFile(dir, o.name, await compositeBlob(o, alpha)); }
    }
    status.textContent = saveSummary(dir, keys.length, total);
  } catch (e) {
    status.innerHTML = `<span class="err">Save failed — is the server running? ${e && e.message || e}</span>`;
  } finally {
    $("btnSaveAll").disabled = false;
  }
}
$("btnFitDetails").addEventListener("click", () => {
  const open = $("fitDetails").classList.toggle("show");
  // Closing the matrices drawer reveals the player; if overlays are already loaded
  // (e.g. imported composites), show the current one instead of the empty prompt.
  if (!open && OVERLAYS.length) { $("ovEmpty").style.display = "none"; ovShow(clamp(ovIdx, 0, OVERLAYS.length - 1)); }
});
$("ovAlpha").addEventListener("input", applyOvAlpha);     // live opacity (grid removed → player + save)
$("ovModel").addEventListener("change", syncOverlayView);   // model changed → show that model's overlays (or empty)
$("btnGenOverlays").addEventListener("click", generateOverlays);
$("btnSaveH").addEventListener("click", saveHOnly);
$("btnSaveAll").addEventListener("click", saveAll);
applyOvAlpha();   // initialise --ov-alpha from the slider default

// ============================================================================
//  KEYBOARD
// ============================================================================
document.addEventListener("keydown", e => {
  // While the overlay player is open, drive it with the keyboard.
  if ($("results").classList.contains("show")) {
    if (e.target.tagName === "INPUT") return;   // let the threshold / opacity inputs keep their keys
    switch (e.key) {
      case "Escape": e.preventDefault(); hideResults(); break;
      case "ArrowLeft": e.preventDefault(); ovStep(-1); break;
      case "ArrowRight": e.preventDefault(); ovStep(1); break;
      case "Home": e.preventDefault(); ovShow(0); break;
      case "End": e.preventDefault(); ovShow(OVERLAYS.length - 1); break;
      case "i": case "I": e.preventDefault(); ovToggleIR(); break;
      case "0": e.preventDefault(); ovResetView(); break;
    }
    return;
  }
  const el = e.target;
  if (el.tagName === "INPUT" && el.type !== "range") return;
  if (el.tagName === "INPUT" && el.type === "range" && e.key.indexOf("Arrow") === 0) return;
  if (!GROUPS.length) return;
  // Alt+1…9 → jump to that subset (e.code is layout-independent: Digit1…Digit9).
  if (e.altKey && /^Digit[1-9]$/.test(e.code)) { e.preventDefault(); selectSubset(+e.code.slice(5) - 1); return; }
  switch (e.key) {
    case "ArrowLeft":  e.preventDefault(); gotoFrame(fi - 1); break;
    case "ArrowRight": e.preventDefault(); gotoFrame(fi + 1); break;
    case "Home": e.preventDefault(); gotoFrame(0); break;
    case "End":  e.preventDefault(); { const g = GROUPS[gi]; if (g) gotoFrame(g.pairs.length - 1); } break;
    case "i": case "I": e.preventDefault(); toggleIR(); break;
    case "u": case "U": e.preventDefault(); undo(); break;   // undo last pick
    case "0": e.preventDefault(); resetView(); break;   // reset zoom/pan to fit
  }
});
</script>
</body>
</html>