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

const API_BASE = '/api';
let currentTaskId = null;
let currentAnalysis = null;
// manual-flow / upload-first state
let selectedFile = null;
let uploadTaskId = null;
let uploadPages = 0;
let scheduleRegions = [];   // [{page, x0, y0, x1, y1}] hand-drawn schedule tables
let scheduleGroups = [];    // [{page, region, units:[{tag,type,qty,model,...}]}] from read
let floorPages = [];        // [{page_num, name}] hand-picked floor plans

// DOM Elements
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');
const analyzeBtn = document.getElementById('analyzeBtn');
const loadingSection = document.getElementById('loadingSection');
const resultsSection = document.getElementById('resultsSection');
const errorSection = document.getElementById('errorSection');
const tabs = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');

// ===== FILE UPLOAD =====
uploadArea.addEventListener('click', () => fileInput.click());

// Note under the file info when this exact file already has results on disk
// (content-hash match) — Analyze will reuse them free instead of re-paying.
function showReuseNote(prev) {
    let el = document.getElementById('reuseNote');
    if (!el) {
        el = document.createElement('div');
        el.id = 'reuseNote';
        el.style.cssText = 'margin:6px 0 0;font-size:0.85em;';
        document.getElementById('fileInfo')?.appendChild(el);
    }
    if (prev && prev.found && prev.reusable) {
        el.style.color = '#15803d';
        el.textContent = `✓ Previous results found (${prev.floors} floor(s)) — ` +
            `Analyze will reuse them free. Tick "force re-detect" to re-run instead.`;
    } else if (prev && prev.found) {
        el.style.color = '#92400e';
        el.textContent = 'A different version of this file was analyzed before — ' +
            'Analyze will re-detect fresh.';
    } else {
        el.textContent = '';
    }
}

// Free text-layer scan: point the user at likely schedule pages so step ①
// isn't a 29-page hunt (round-1 focus group: Sal bounced right here).
async function loadScheduleHints() {
    if (!uploadTaskId) return;
    try {
        const res = await fetch(`${API_BASE}/schedule-hints/${uploadTaskId}`);
        const d = await res.json();
        let el = document.getElementById('scheduleHints');
        if (!el) {
            el = document.createElement('div');
            el.id = 'scheduleHints';
            el.style.cssText = 'margin-top:4px;font-size:0.85em;color:#4338ca;';
            document.getElementById('addScheduleBtn')?.parentElement?.appendChild(el);
        }
        el.textContent = (d.schedule_pages || []).length
            ? `💡 Pages ${d.schedule_pages.join(', ')} look like schedule sheets — start there.`
            : '';
    } catch (e) { /* advisory */ }
}

// ===== RECENT BUILDINGS (reopen results after a restart / new session) =====
async function loadRecentBuildings() {
    try {
        const res = await fetch(`${API_BASE}/recent`);
        const data = await res.json();
        const items = data.recent || [];
        if (!items.length) return;
        let box = document.getElementById('recentBuildings');
        if (!box) {
            box = document.createElement('div');
            box.id = 'recentBuildings';
            box.style.cssText = 'margin-top:14px;padding:10px 12px;background:#f8fafc;'
                + 'border:1px solid #e2e8f0;border-radius:8px;font-size:0.9em;';
            uploadArea.parentElement.insertBefore(box, uploadArea.nextSibling);
        }
        box.innerHTML = '<b>Recent buildings</b> — click to reopen previous results (free):<br>';
        items.forEach(it => {
            const a = document.createElement('a');
            a.href = '#';
            a.textContent = `${it.name} (${it.floors} floor(s), ${it.updated})`;
            a.style.cssText = 'display:inline-block;margin:4px 12px 0 0;color:#4338ca;';
            a.addEventListener('click', async e => {
                e.preventDefault();
                a.textContent += ' …';
                try {
                    const r = await fetch(`${API_BASE}/reopen`, {
                        method: 'POST', headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ name: it.name })
                    });
                    const d = await r.json();
                    if (d.task_id) {
                        currentTaskId = uploadTaskId = d.task_id;
                        uploadPages = d.pages || 0;
                        currentAnalysis = d.result;
                        // Enable the step ① pickers — a reopened building skips the
                        // upload path that normally turns these on, so "Add schedule
                        // region" / "Add floor page" were dead after a reopen (the
                        // flag's call-to-action then did nothing).
                        ['addScheduleBtn', 'addFloorBtn'].forEach(id => {
                            const b = document.getElementById(id); if (b) b.disabled = false;
                        });
                        loadScheduleHints(); updateReadBtn();
                        displayResults(d.result);
                        resultsSection.style.display = 'block';
                        loadReview(currentTaskId);
                        resultsSection.scrollIntoView({ behavior: 'smooth' });
                    } else {
                        showError(d.message || d.error || 'Could not reopen — re-upload the PDF (results reload free).');
                    }
                } catch (err) { showError('Reopen failed: ' + err.message); }
                a.textContent = a.textContent.replace(' …', '');
            });
            box.appendChild(a);
        });
    } catch (e) { /* advisory only — never block the landing page */ }
}
loadRecentBuildings();

// ===== PRODUCT MODE (hide developer surfaces from end users) =====
async function applyGuiConfig() {
    try {
        const res = await fetch(`${API_BASE}/config`);
        const cfg = await res.json();
        if (cfg.product_mode) {
            // The Symbol Bank tab is a developer tool full of internal
            // training data (other buildings' crops) — never show it to
            // an end user (round-1 focus group: "somebody else's building?").
            document.querySelectorAll('[data-tab="bank"], #bank-tab').forEach(el => {
                el.style.display = 'none';
            });
            [...document.querySelectorAll('.tab-btn')].forEach(b => {
                if (/bank/i.test(b.textContent)) b.style.display = 'none';
            });
        }
    } catch (e) { /* config is advisory */ }
}
applyGuiConfig();

uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('dragover');
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('dragover');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    handleFiles(e.dataTransfer.files);
});

fileInput.addEventListener('change', (e) => {
    handleFiles(e.target.files);
});

// Third way in: paste a PDF from the clipboard (Ctrl/⌘+V). Copy a PDF file in
// the OS file manager (or copy a PDF out of another app), then paste anywhere
// on the page. Chromium exposes the copied file via clipboardData.files /
// .items. A plain-text paste (into the tag/floor-name inputs) carries no file,
// so we return early WITHOUT preventDefault — normal text pasting is untouched.
document.addEventListener('paste', (e) => {
    const dt = e.clipboardData;
    if (!dt) return;
    let file = (dt.files && dt.files.length) ? dt.files[0] : null;
    if (!file && dt.items) {
        for (const it of dt.items) {
            if (it.kind === 'file') { file = it.getAsFile(); break; }
        }
    }
    if (!file) return;                       // no file on the clipboard — ignore
    e.preventDefault();
    const isPdf = /\.pdf$/i.test(file.name || '') || file.type === 'application/pdf';
    if (!isPdf) {
        showError('That clipboard item isn’t a PDF — copy a PDF file, then paste.');
        return;
    }
    // Brief green flash so the user sees the paste landed.
    uploadArea.classList.add('pasted');
    setTimeout(() => uploadArea.classList.remove('pasted'), 700);
    handleFiles([file]);
});

// Make the NATIVE right-click ▸ Paste work too. Browsers only put "Paste" in
// the context menu — and only hand a copied FILE to the paste event — on an
// editable element. So mark the drop zone contenteditable, but block every real
// edit (typing, text paste, deletes). A right-click Paste of a PDF then arrives
// as an ordinary paste event and is handled above; nothing is ever typed into
// the box. caret-color:transparent + clearing the selection keep it from
// looking or behaving like a text field.
uploadArea.setAttribute('contenteditable', 'true');
uploadArea.setAttribute('spellcheck', 'false');
uploadArea.setAttribute('aria-label', 'Upload area — drag, click, right-click ▸ Paste, or Ctrl/⌘+V a PDF');
uploadArea.addEventListener('beforeinput', (e) => e.preventDefault());   // no text/edit ever enters
uploadArea.addEventListener('mouseup', () => {
    const s = window.getSelection && window.getSelection();
    if (s) s.removeAllRanges();                 // don't leave a caret/selection after a click
});

function handleFiles(files) {
    const file = files[0];
    if (!file) return;

    if (!/\.pdf$/i.test(file.name || '') && file.type !== 'application/pdf') {
        showError('Please upload a PDF file');
        return;
    }

    // Show file info
    fileInfo.style.display = 'block';
    document.getElementById('fileName').textContent = file.name;
    document.getElementById('fileSize').textContent = `(${(file.size / 1024 / 1024).toFixed(2)} MB)`;

    // Reset the manual-flow state for a new file.
    selectedFile = file;
    uploadTaskId = null;
    scheduleRegions = []; scheduleGroups = []; floorPages = [];
    renderScheduleChips(); renderUnitGroups(); renderFloorChips();
    document.getElementById('unitsSection').style.display = 'none';
    analyzeBtn.disabled = true;
    analyzeBtn.onclick = () => analyzeBlueprint(file);

    // Pre-upload so the pickers can render pages before analysis runs.
    uploadPdf(file);
}

async function uploadPdf(file) {
    const fd = new FormData();
    fd.append('file', file);
    try {
        const res = await fetch(`${API_BASE}/upload`, { method: 'POST', body: fd });
        const data = await res.json();
        uploadTaskId = data.task_id;
        uploadPages = data.pages || 0;
        ['addScheduleBtn', 'addFloorBtn'].forEach(id => {
            const b = document.getElementById(id); if (b) b.disabled = false;
        });
        // Same file analyzed before (content-hash match) → Analyze reuses the
        // cached detections for free; tell the user before they worry about cost.
        showReuseNote(data.previous_results);
        loadScheduleHints();
        updateReadBtn(); updateAnalyzeBtn(); updateFindUnitBtn();
        // If this PDF was analyzed before (cached outputs/<name>/ results),
        // surface the saved boxes in the Review tab immediately — the user
        // shouldn't need to re-run analysis just to review existing floors.
        currentTaskId = uploadTaskId;
        loadReview(uploadTaskId);
    } catch (e) { showError('Upload failed: ' + e.message); }
}

// Enable "Read schedules" once at least one region has been added.
function updateReadBtn() {
    const b = document.getElementById('readSchedulesBtn');
    if (b) b.disabled = !(uploadTaskId && scheduleRegions.length);
}

// Enable "Analyze" once we have ≥1 floor page. A confirmed schedule is
// OPTIONAL — with no confirmed tags the engine detects every unit tag it finds
// on the drawings (the schedule is a hint/filter, not a prerequisite). Reading
// a schedule first still improves capacity + tag accuracy.
function updateAnalyzeBtn() {
    analyzeBtn.disabled = !(uploadTaskId && floorPages.length);
    const hint = document.getElementById('analyzeHint');
    if (hint) {
        const haveTags = getConfirmedTags().length;
        hint.textContent = haveTags
            ? 'Looking for the units you confirmed above.'
            : 'No schedule needed — with no units confirmed above, this finds every unit tag on the floors you added. Reading a schedule first improves capacity & tag accuracy.';
    }
}

// ===== SCHEDULE REGIONS (chips) =====
function renderScheduleChips() {
    const wrap = document.getElementById('scheduleChips');
    if (!wrap) return;
    wrap.innerHTML = '';
    scheduleRegions.forEach((r, i) => {
        const whole = (r.x1 - r.x0 > 0.98 && r.y1 - r.y0 > 0.98);
        const chip = document.createElement('span');
        chip.style.cssText = 'display:inline-flex;align-items:center;gap:6px;background:#e0e7ff;'
            + 'color:#3730a3;border-radius:14px;padding:3px 10px;font-size:0.85em;';
        chip.innerHTML = `📐 p${r.page}${whole ? ' (whole)' : ''} `
            + `<a href="#" data-i="${i}" class="chip-x" style="color:#3730a3;text-decoration:none;font-weight:bold;">✕</a>`;
        wrap.appendChild(chip);
    });
    wrap.querySelectorAll('.chip-x').forEach(a => a.addEventListener('click', e => {
        e.preventDefault();
        scheduleRegions.splice(+a.dataset.i, 1);
        renderScheduleChips(); updateReadBtn();
    }));
    updateReadBtn();
}

// ===== READ SCHEDULES → confirm units =====
async function readSchedules() {
    if (!uploadTaskId || !scheduleRegions.length) return;
    const btn = document.getElementById('readSchedulesBtn');
    const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Reading…';
    resultsSection.style.display = 'none';
    errorSection.style.display = 'none';
    loadingSection.style.display = 'block';
    const lt = document.getElementById('loadingText');
    if (lt) lt.textContent = 'Reading the selected schedule region(s)…';
    setProgress(5, 'Starting…');
    try {
        const res = await fetch(`${API_BASE}/read-schedules`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ task_id: uploadTaskId, regions: scheduleRegions })
        });
        if (!res.ok) throw new Error((await res.json()).detail || 'Could not read schedules');
        scheduleGroups = await pollUntilPrepared(uploadTaskId);
        loadingSection.style.display = 'none';
        renderUnitGroups();
        document.getElementById('unitsSection').style.display =
            scheduleGroups.length ? 'block' : 'none';
        if (!scheduleGroups.some(g => (g.units || []).length))
            showError('No units were read from the selected region(s). Try drawing the box '
                + 'tighter around the table, or add another region.');
        // Post-run schedule add: if results already exist (e.g. the flags said
        // "AH units aren't in your schedule — it's on p15"), rebuild them from
        // the enlarged schedule so capacities update — NO re-detection cost.
        if (currentAnalysis && currentTaskId) {
            try {
                const rr = await fetch(`${API_BASE}/refresh-result`, {
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ task_id: currentTaskId })
                });
                if (rr.ok) {
                    currentAnalysis = await rr.json();
                    displayResults(currentAnalysis);
                    resultsSection.style.display = 'block';
                }
            } catch (e) { /* advisory */ }
        }
    } catch (e) {
        loadingSection.style.display = 'none';
        showError('Read schedules failed: ' + e.message);
    } finally { btn.disabled = false; btn.textContent = orig; }
}

async function pollUntilPrepared(taskId) {
    while (true) {
        await new Promise(r => setTimeout(r, 2000));
        const res = await fetch(`${API_BASE}/status/${taskId}`);
        if (!res.ok) throw new Error('Lost track of the schedule task');
        const job = await res.json();
        setProgress(job.percent || 0, `${(job.phase || '').toUpperCase()} — ${job.message || ''}`);
        if (job.status === 'prepared') return job.schedule_groups || [];
        if (job.status === 'error') throw new Error(job.error || 'Schedule read failed');
    }
}

// ===== UNIT CONFIRM LIST (neat table, grouped per schedule region) =====
function renderUnitGroups() {
    const wrap = document.getElementById('unitGroups');
    if (!wrap) return;
    let html = '<table class="units-table" style="width:100%;max-width:560px;border-collapse:collapse;font-size:0.88em;text-align:left;">'
        + '<thead><tr style="border-bottom:2px solid #e2e8f0;color:#475569;">'
        + '<th style="padding:4px 8px;width:36px;text-align:center;">✓</th>'
        + '<th style="padding:4px 8px;">Tag</th>'
        + '<th style="padding:4px 8px;">Type</th>'
        + '<th style="padding:4px 8px;width:48px;text-align:right;">Qty</th>'
        + '<th style="padding:4px 8px;">Model</th></tr></thead><tbody>';
    scheduleGroups.forEach((g, gi) => {
        const units = g.units || [];
        html += `<tr style="background:#f8fafc;"><td colspan="5" style="padding:4px 8px;font-weight:600;color:#334155;">`
            + `Schedule p${g.page} — ${units.length} unit(s)</td></tr>`;
        if (!units.length) {
            html += '<tr><td colspan="5" style="padding:4px 8px;color:#94a3b8;">No units read from this region.</td></tr>';
        }
        units.forEach((u, ui) => {
            // Word-fragment junk (OCR reads "AIR CONDI-TIONING" as a tag
            // "AC-TION" with a huge qty) arrives with no type, no model, and an
            // implausible count — default it UNTICKED with a warning so the
            // user opts IN instead of having to spot it (round-1 focus group).
            const suspicious = looksLikeJunkTag(u);
            const cb = `<input type="checkbox" class="unit-cb" data-tag="${u.tag}" id="u_${gi}_${ui}" ${suspicious ? '' : 'checked'}>`;
            const warn = suspicious
                ? ` <span title="No type, no model, and an implausible quantity — usually a text fragment misread as a tag. Tick it only if it's a real unit." style="color:#b45309;">⚠ looks like a text fragment</span>`
                : '';
            html += `<tr style="border-bottom:1px solid #f1f5f9;${suspicious ? 'opacity:0.65;' : ''}">`
                + `<td style="padding:3px 8px;text-align:center;">${cb}</td>`
                + `<td style="padding:3px 8px;font-weight:600;">${u.tag}${warn}</td>`
                + `<td style="padding:3px 8px;color:#64748b;">${u.type || ''}</td>`
                + `<td style="padding:3px 8px;text-align:right;color:#64748b;">${u.qty != null ? u.qty : ''}</td>`
                + `<td style="padding:3px 8px;color:#64748b;">${u.model || ''}</td></tr>`;
        });
    });
    html += '</tbody></table>';
    wrap.innerHTML = html;
    wrap.querySelectorAll('.unit-cb').forEach(cb => cb.addEventListener('change', updateAnalyzeBtn));
    updateAnalyzeBtn();
}

// Junk heuristic for schedule reads: real units carry a type or a model or a
// sane quantity; hyphenation fragments ("AC-TION" from "AIR CONDI-TIONING")
// carry none and often absurd counts. Conservative on purpose — a real bare
// tag with qty 4 (AH-1) is NOT flagged.
function looksLikeJunkTag(u) {
    const bare = !(u.type || '').trim() && !(u.model || '').trim();
    if (!bare) return false;
    const qty = +u.qty || 0;
    const tail = (u.tag || '').split('-').slice(1).join('-');
    const fragment = /^(TION|TIONS|MENT|NING|CESS|SION|ANCE|ABLE)$/i.test(tail);
    return fragment || qty >= 15;
}

// Unique set of ticked tags across all groups.
function getConfirmedTags() {
    const tags = new Set();
    document.querySelectorAll('.unit-cb:checked').forEach(cb => tags.add(cb.dataset.tag));
    return [...tags];
}

// ===== FLOOR PAGES (chips) =====
function renderFloorChips() {
    const wrap = document.getElementById('floorChips');
    if (!wrap) return;
    wrap.innerHTML = '';
    floorPages.forEach((f, i) => {
        const chip = document.createElement('span');
        chip.style.cssText = 'display:inline-flex;align-items:center;gap:6px;background:#dcfce7;'
            + 'color:#166534;border-radius:14px;padding:3px 10px;font-size:0.85em;';
        chip.innerHTML = `🏗️ p${f.page_num} — ${f.name || ('Page ' + f.page_num)} `
            + `<a href="#" data-i="${i}" class="fchip-x" style="color:#166534;text-decoration:none;font-weight:bold;">✕</a>`;
        wrap.appendChild(chip);
    });
    wrap.querySelectorAll('.fchip-x').forEach(a => a.addEventListener('click', e => {
        e.preventDefault();
        floorPages.splice(+a.dataset.i, 1);
        renderFloorChips(); updateAnalyzeBtn();
    }));
    renderCustomScope();
    updateAnalyzeBtn();
}

// ===== FIND A CUSTOM UNIT (not in the schedule) =====
// Scope dropdown: "all selected floors" or one specific floor page.
function renderCustomScope() {
    const sel = document.getElementById('customScope');
    if (!sel) return;
    const prev = sel.value;
    sel.innerHTML = '<option value="all">all selected floors</option>'
        + floorPages.map(f => `<option value="${f.page_num}">p${f.page_num} — ${f.name || ('Page ' + f.page_num)}</option>`).join('');
    if ([...sel.options].some(o => o.value === prev)) sel.value = prev;
    updateFindUnitBtn();
}

function updateFindUnitBtn() {
    const tag = (document.getElementById('customTagInput')?.value || '').trim();
    const b = document.getElementById('findUnitBtn');
    if (b) b.disabled = !(uploadTaskId && floorPages.length && tag);
}

async function findUnit() {
    const tag = (document.getElementById('customTagInput')?.value || '').trim();
    if (!tag) { showError('Type a unit tag to find.'); return; }
    if (!floorPages.length) { showError('Add at least one floor page first (step ③).'); return; }
    const scope = document.getElementById('customScope').value;
    const scopePages = scope === 'all'
        ? floorPages
        : floorPages.filter(f => String(f.page_num) === String(scope));
    const modelChoice = document.querySelector('input[name="model"]:checked').value;

    resultsSection.style.display = 'none';
    errorSection.style.display = 'none';
    loadingSection.style.display = 'block';
    const lt = document.getElementById('loadingText');
    if (lt) lt.textContent = `Searching for ${tag}…`;
    setProgress(2, 'Starting…');
    const btn = document.getElementById('findUnitBtn');
    const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Searching…';
    try {
        const res = await fetch(`${API_BASE}/find-unit`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                task_id: uploadTaskId, tags: tag, floor_pages: scopePages,
                model_choice: modelChoice
            })
        });
        if (!res.ok) throw new Error((await res.json()).detail || 'Find unit failed');
        currentTaskId = (await res.json()).task_id;
        const result = await pollUntilDone(currentTaskId);
        currentAnalysis = result;
        loadingSection.style.display = 'none';
        displayResults(result);
        resultsSection.style.display = 'block';
        loadReview(currentTaskId);
    } catch (e) {
        loadingSection.style.display = 'none';
        showError('Find unit failed: ' + e.message);
    } finally { btn.disabled = false; btn.textContent = orig; updateFindUnitBtn(); }
}

document.getElementById('findUnitBtn')?.addEventListener('click', findUnit);
document.getElementById('customTagInput')?.addEventListener('input', updateFindUnitBtn);

// ===== "What to look for" — multi-select checkbox dropdown =====
// Pick one or more categories. Only "indoor" has an active detector today; the
// rest are selectable but flagged "coming soon". The chosen list is sent to the
// backend as look_for so the plumbing is ready as detectors ship.
const LOOKFOR_LABELS = {
    indoor: 'Indoor units', diffusers: 'Diffusers', fans: 'Fans',
    electric_heaters: 'Electric heaters', dampers: 'Dampers', cav: 'CAV',
    rooftop: 'Rooftop units', ptac: 'PTAC', branch_boxes: 'Branch boxes',
    condensers: 'Condensers', erv: 'ERVs'
};
// Every category is now wired to the engine. "indoor" is fully tuned; the rest
// are basic (beta) first-pass detectors, flagged so the user knows they're rough.
const LOOKFOR_TUNED = new Set(['indoor']);

function getLookFor() {
    return [...document.querySelectorAll('.lookfor-cb:checked')].map(cb => cb.value);
}

function updateLookForUI() {
    const sel = getLookFor();
    const summary = document.getElementById('lookForSummary');
    if (summary) {
        summary.textContent = sel.length
            ? sel.map(v => LOOKFOR_LABELS[v] || v).join(', ')
            : 'Choose what to look for…';
    }
    const note = document.getElementById('lookForNote');
    if (note) {
        const beta = sel.filter(v => !LOOKFOR_TUNED.has(v));
        if (!sel.length) {
            note.textContent = 'Pick at least one category to look for.';
            note.style.color = '#b45309';
        } else if (!beta.length) {
            note.textContent = 'Indoor units is fully tuned.';
            note.style.color = '#64748b';
        } else {
            const names = beta.map(v => LOOKFOR_LABELS[v] || v).join(', ');
            note.textContent = `${names} ${beta.length > 1 ? 'are' : 'is'} beta (basic detectors) — `
                + `they’ll find symbols to review, but may miss or over-detect until refined.`;
            note.style.color = '#b45309';
        }
    }
}

(function initLookForMulti() {
    const multi = document.getElementById('lookForMulti');
    const toggle = document.getElementById('lookForToggle');
    const panel = document.getElementById('lookForPanel');
    if (!multi || !toggle || !panel) return;
    const open = () => { panel.hidden = false; multi.classList.add('open'); toggle.setAttribute('aria-expanded', 'true'); };
    const close = () => { panel.hidden = true; multi.classList.remove('open'); toggle.setAttribute('aria-expanded', 'false'); };
    toggle.addEventListener('click', (e) => {
        e.stopPropagation();
        panel.hidden ? open() : close();
    });
    // Ticking a box shouldn't close the panel — let users pick several at once.
    panel.addEventListener('click', (e) => e.stopPropagation());
    panel.querySelectorAll('.lookfor-cb').forEach(cb => cb.addEventListener('change', updateLookForUI));
    document.addEventListener('click', close);          // click outside closes
    document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close(); });
    updateLookForUI();
})();

function formatDuration(totalSeconds) {
    const s = Math.max(0, Math.round(totalSeconds || 0));
    if (s < 60) return `${s}s`;
    const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
    if (h) return `${h}h ${m}m ${sec}s`;
    return `${m}m ${sec}s`;
}

document.getElementById('readSchedulesBtn')?.addEventListener('click', readSchedules);

// ===== ANALYSIS =====
async function analyzeBlueprint(file) {
    const modelChoice = document.querySelector('input[name="model"]:checked').value;
    const g = id => document.getElementById(id);
    // A confirmed schedule is optional. Require only ≥1 floor page; with no
    // confirmed tags the engine detects every tag it finds (all-tags mode).
    const confirmedTags = getConfirmedTags();
    if (!floorPages.length) { showError('Add at least one floor page to analyze.'); return; }

    const tagPrefixes = (g('rTagPrefixes')?.value || '').trim();
    const recipe = g('rRuns') ? {
        runs: +g('rRuns').value, tile: +g('rTile').value, consensus: +g('rConsensus').value,
        all_tags: g('rAllTags').checked, fp_filter: g('rFp').checked, force: g('rForce').checked,
        ...(tagPrefixes ? { tag_prefixes: tagPrefixes } : {})
    } : {};
    // No schedule confirmed → make sure we sweep for every tag, not a filtered set.
    if (!confirmedTags.length) recipe.all_tags = true;

    // Show loading
    resultsSection.style.display = 'none';
    errorSection.style.display = 'none';
    loadingSection.style.display = 'block';
    const lt2 = document.getElementById('loadingText');
    if (lt2) lt2.textContent = 'Detecting units…';
    setProgress(2, 'Starting…');

    try {
        const res = await fetch(`${API_BASE}/detect`, {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                task_id: uploadTaskId, model_choice: modelChoice, recipe,
                floor_pages: floorPages, confirmed_tags: confirmedTags,
                look_for: getLookFor()
            })
        });
        if (!res.ok) throw new Error((await res.json()).detail || 'Analysis failed');
        const started = await res.json();
        currentTaskId = started.task_id;

        // Poll status until done/error (real detection is minutes per page)
        const result = await pollUntilDone(currentTaskId);
        currentAnalysis = result;
        loadingSection.style.display = 'none';
        displayResults(result);
        resultsSection.style.display = 'block';
        loadReview(currentTaskId);
    } catch (error) {
        loadingSection.style.display = 'none';
        showError(error.message);
    }
}

function setProgress(percent, message) {
    const fill = document.getElementById('progressFill');
    if (fill) fill.style.width = (percent || 0) + '%';
    const msg = document.getElementById('progressMessage');
    if (msg && message) msg.textContent = message;
}

async function pollUntilDone(taskId) {
    while (true) {
        await new Promise(r => setTimeout(r, 2000));
        const res = await fetch(`${API_BASE}/status/${taskId}`);
        if (!res.ok) throw new Error('Lost track of the analysis task');
        const job = await res.json();
        setProgress(job.percent || 0,
            `${(job.phase || '').toUpperCase()} — ${job.message || ''}`);
        if (job.status === 'done') {
            if (!job.result) throw new Error(
                'Finished but no result returned — restart the server and hard-refresh (Ctrl+F5).');
            return job.result;
        }
        if (job.status === 'error') throw new Error(job.error || 'Analysis failed');
    }
}

// ===== DISPLAY RESULTS =====
function displayResults(result) {
    if (!result || !result.summary) {
        showError('No result to display (the analysis returned nothing — restart the '
            + 'server and hard-refresh the page with Ctrl+F5).');
        return;
    }
    // Summary tab
    document.getElementById('totalFloors').textContent = result.summary.total_floors;
    // Verified (green/orange) is THE headline number a bid can use. Yellows are
    // shown as "to review", gray noise as "rejected" — never mixed into one count.
    const vu = result.summary.verified_units;
    document.getElementById('totalUnits').textContent =
        (vu !== undefined) ? vu : result.summary.total_units;
    const bd = document.getElementById('unitsBreakdown');
    if (bd) {
        const eq = result.summary.equipment_units || 0;
        bd.textContent = (vu !== undefined)
            ? `+${result.summary.review_units || 0} to review · ${result.summary.noise_units || 0} rejected`
              + (eq ? ` · ${eq} equipment (ERV/MUA…)` : '')
            : '';
    }
    // Capacity comes from the schedule (BTU per unit tag). With no schedule
    // read, there's no capacity to total — show "—" + a nudge instead of a bare
    // "0k BTU" (which reads like "OK" and looks like a real zero).
    const btu = result.summary.total_capacity_btu || 0;
    const capNote = document.getElementById('capacityNote');
    if (btu > 0) {
        document.getElementById('totalCapacity').textContent = `${(btu / 1000).toFixed(0)}k BTU`;
        if (capNote) capNote.textContent = '';
    } else {
        document.getElementById('totalCapacity').textContent = '—';
        if (capNote) capNote.textContent = 'Add a schedule to see total BTU';
    }
    document.getElementById('processingTime').textContent =
        formatDuration(result.processing_time_seconds);
    document.getElementById('modelUsed').textContent = result.model_used;
    document.getElementById('fileName2').textContent = result.file_name;
    document.getElementById('costUsed').textContent = `$${result.cost_usd.toFixed(4)}`;

    // Floors table
    populateFloorsTable(result.floors);

    // Flags / reconciliation
    renderFlags(result.reconciliation);

    // Floor Plan tab — real annotated PNGs (colored boxes) from the engine
    loadAnnotated(currentTaskId);

    // Download buttons
    setupDownloadButtons(result.csv_files);
}

function populateFloorsTable(floors) {
    const tbody = document.getElementById('floorsTableBody');
    tbody.innerHTML = '';

    floors.forEach(floor => {
        // Show the REAL floor name ("Cellar", "3rd Floor") from the PDF text
        // layer, not the raw page ordinal. The multi-floor case carries a
        // verbose "(sheet pN: …)" provenance suffix — keep it on hover only.
        const fullName = floor.floor_name || `Floor ${floor.floor_number}`;
        const floorLabel = fullName.split('  (sheet ')[0];
        floor.units.forEach(unit => {
            const row = tbody.insertRow();
            // ERV/MUA/EF/CU… are real equipment but NOT indoor units — shown
            // muted with a badge, excluded from the verified count/capacity.
            const isEquip = unit.scope === 'equipment';
            if (isEquip) row.style.opacity = '0.6';
            row.innerHTML = `

                <td title="${fullName.replace(/"/g, '&quot;')}">${floorLabel}</td>

                <td><strong>${unit.tag}</strong>${isEquip ? ' <span style="font-size:0.78em;color:#b45309;">equipment</span>' : ''}</td>

                <td>${unit.type || '-'}</td>

                <td>${unit.model || '-'}</td>

                <td>${unit.quantity}</td>

                <td>${unit.capacity_btu || '-'}</td>

                <td>${unit.capacity_kw || '-'}</td>

                <td>${unit.location || '-'}</td>

            `;

        });

    });

}



// Load the engine's annotated floor PNGs (colored bounding boxes) into the

// Floor Plan tab, with a per-floor selector and a download link.

async function loadAnnotated(taskId) {

    const sel = document.getElementById('annotatedSelect');

    const img = document.getElementById('annotatedImg');

    const ctrls = document.getElementById('annotatedControls');

    const empty = document.getElementById('annotatedEmpty');

    const dl = document.getElementById('annotatedDownload');

    if (!sel || !img) return;

    try {

        const res = await fetch(`${API_BASE}/annotated/${taskId}`);

        const data = await res.json();

        const floors = (data.floors || []).filter(f => f.url);

        if (!floors.length) {

            ctrls.style.display = 'none'; img.style.display = 'none';

            empty.style.display = 'block';

            empty.textContent = 'No annotated images yet for this run.';

            return;

        }

        sel.innerHTML = '';

        floors.forEach(f => {

            const o = document.createElement('option');

            o.value = f.url; o.textContent = `p${f.page_num} — ${f.floor_name}`;

            o.dataset.page = f.page_num;

            sel.appendChild(o);

        });

        const show = () => {

            const opt = sel.options[sel.selectedIndex];

            // cache-bust so re-runs / re-reviews refresh the image

            const bust = `?t=${Date.now()}`;

            img.src = opt.value + bust;

            img.style.display = 'block';

            // cache-bust the download too, so re-downloading after a re-review

            // fetches the freshly redrawn PNG (kept boxes only) not a cached copy

            if (dl) { dl.href = opt.value + bust; dl.setAttribute('download', `floor_${opt.dataset.page}_annotated.png`); }

        };

        sel.onchange = show;

        ctrls.style.display = 'flex';

        empty.style.display = 'none';

        show();

    } catch (e) {

        ctrls.style.display = 'none';

        empty.style.display = 'block';

        empty.textContent = 'Could not load annotated images.';

    }

}



function drawFloorPlan(floors) {

    const canvas = document.getElementById('floorCanvas');

    const ctx = canvas.getContext('2d');



    // Clear canvas

    ctx.fillStyle = '#ffffff';

    ctx.fillRect(0, 0, canvas.width, canvas.height);



    // Draw background

    ctx.strokeStyle = '#e2e8f0';

    ctx.lineWidth = 1;

    for (let i = 0; i < canvas.width; i += 50) {

        ctx.beginPath();

        ctx.moveTo(i, 0);

        ctx.lineTo(i, canvas.height);

        ctx.stroke();

    }



    // Draw floors

    const floorHeight = canvas.height / (floors.length + 1);

    floors.forEach((floor, floorIndex) => {

        const y = 50 + floorIndex * floorHeight;



        // Floor label

        ctx.fillStyle = '#1e293b';

        ctx.font = 'bold 16px Arial';

        ctx.fillText(`Floor ${floor.floor_number}`, 20, y);



        // Units

        let unitX = 150;

        floor.units.forEach(unit => {

            drawUnit(ctx, unitX, y, unit);

            unitX += 120;

        });



        // Floor line

        ctx.strokeStyle = '#cbd5e1';

        ctx.lineWidth = 2;

        ctx.beginPath();

        ctx.moveTo(0, y + 40);

        ctx.lineTo(canvas.width, y + 40);

        ctx.stroke();

    });

}



function drawUnit(ctx, x, y, unit) {

    // Unit box

    ctx.fillStyle = '#dbeafe';

    ctx.fillRect(x, y, 100, 30);



    ctx.strokeStyle = '#2563eb';

    ctx.lineWidth = 2;

    ctx.strokeRect(x, y, 100, 30);



    // Unit text

    ctx.fillStyle = '#1e293b';

    ctx.font = 'bold 12px Arial';

    ctx.textAlign = 'center';

    ctx.fillText(unit.tag, x + 50, y + 20);



    // Capacity below

    ctx.font = '10px Arial';

    ctx.fillStyle = '#64748b';

    ctx.fillText(`${unit.quantity}x${Math.round(unit.capacity_btu / 1000)}k`, x + 50, y + 35);

}



function setupDownloadButtons(csvFiles) {

    csvFiles = csvFiles || {};

    // Fall back to building the URL from the task id if csv_files is missing.

    const csvUrl = (name) => csvFiles[name] || `${API_BASE}/download/csv/${currentTaskId}/${name}`;

    document.getElementById('downloadFloors').onclick = () =>

        downloadFile(csvUrl('floors_units'), 'hvac_floors_units.csv');

    document.getElementById('downloadSchedule').onclick = () =>

        downloadFile(csvUrl('equipment_schedule'), 'hvac_equipment_schedule.csv');

    document.getElementById('downloadReconciliation').onclick = () =>

        downloadFile(csvUrl('reconciliation'), 'hvac_reconciliation.csv');

    document.getElementById('downloadZip').onclick = () =>

        downloadFile(`${API_BASE}/download/zip/${currentTaskId}`, 'hvac_analysis.zip');

}



function downloadFile(url, filename) {

    // The anchor MUST be in the DOM for the download to fire in several browsers.

    const a = document.createElement('a');

    a.href = url;

    a.download = filename || '';

    a.style.display = 'none';

    document.body.appendChild(a);

    a.click();

    setTimeout(() => a.remove(), 0);

}



// ===== TABS =====

tabs.forEach(tab => {

    tab.addEventListener('click', () => {

        // Remove active from all

        tabs.forEach(t => t.classList.remove('active'));

        tabContents.forEach(c => c.classList.remove('active'));



        // Add active to clicked

        tab.classList.add('active');

        const tabId = tab.dataset.tab + '-tab';

        document.getElementById(tabId).classList.add('active');

    });

});



// ===== ERROR HANDLING =====

function showError(message) {

    loadingSection.style.display = 'none';

    resultsSection.style.display = 'none';

    errorSection.style.display = 'block';

    document.getElementById('errorMessage').textContent = message;

}



// ===== FLAGS / RECONCILIATION =====

// Flags tab — one plain-English card per flag: a friendly severity badge, a

// "what's going on" title, the specifics, and a highlighted "what to do" step.

const FLAG_META = {

    high:   { color: '#dc2626', bg: '#fef2f2', label: 'NEEDS ATTENTION', icon: '⚠️' },

    medium: { color: '#ca8a04', bg: '#fefce8', label: 'WORTH A LOOK',    icon: '🔎' },

    low:    { color: '#64748b', bg: '#f8fafc', label: 'FYI',             icon: 'ℹ️' },

};

const FLAG_RANK = { high: 0, medium: 1, low: 2 };

function esc(s) { const p = document.createElement('div'); p.textContent = s == null ? '' : String(s); return p.innerHTML; }



function renderFlags(rec) {

    rec = rec || { issues: [] };

    const issues = (rec.issues || []).slice()

        .sort((a, b) => (FLAG_RANK[a.severity] ?? 9) - (FLAG_RANK[b.severity] ?? 9));

    const hi = rec.high_severity || 0, me = rec.medium_severity || 0, lo = rec.low_severity || 0;

    const sum = document.getElementById('flagsSummary');

    if (sum) sum.textContent = issues.length

        ? `${issues.length} thing${issues.length > 1 ? 's' : ''} to check — ${hi} need attention, ${me} worth a look, ${lo} FYI.`

        : '';

    const list = document.getElementById('flagsList');

    if (!list) return;

    if (!issues.length) {

        list.innerHTML = '<p style="color:#16a34a;font-weight:600;padding:8px 0;">✓ All clear — the counts add up and nothing looks missing.</p>';

        return;

    }

    list.innerHTML = issues.map(i => {

        const m = FLAG_META[i.severity] || FLAG_META.low;

        const title = esc(i.title || (i.type || 'Flag').replace(/_/g, ' '));

        const body = i.message ? `<div style="color:#475569;font-size:0.92em;line-height:1.45;margin-top:3px;">${esc(i.message)}</div>` : '';

        const action = i.action ? `<div style="margin-top:9px;padding:8px 11px;background:#fff;border-radius:5px;font-size:0.92em;color:#0f172a;line-height:1.45;"><strong style="color:${m.color};">→ What to do:</strong> ${esc(i.action)}</div>` : '';

        // Room-gap flags carry crop PNGs of the exact spot — show them so the

        // user sees WHERE, not just which floor. Click to open full-size.

        let crops = '';

        if (Array.isArray(i.crops) && i.crops.length && currentTaskId) {

            const thumbs = i.crops.slice(0, 6).map(c => {

                const u = `${API_BASE}/roomgap-crop/${currentTaskId}/${encodeURIComponent(c)}`;

                return `<a href="${u}" target="_blank" rel="noopener" title="Open this spot full-size">`

                    + `<img src="${u}" loading="lazy" style="width:130px;height:130px;object-fit:cover;`

                    + `border:2px solid ${m.color}66;border-radius:6px;background:#fff;"></a>`;

            }).join('');

            const more = i.crops.length > 6 ? `<span style="align-self:center;color:#64748b;font-size:0.85em;">+${i.crops.length - 6} more</span>` : '';

            crops = `<div style="margin-top:10px;display:flex;flex-wrap:wrap;gap:8px;">${thumbs}${more}</div>`

                + `<div style="font-size:0.8em;color:#64748b;margin-top:4px;">👆 The exact spot on the plan — the flagged room is at the center of each. Click to enlarge.</div>`;

        }

        return `<div style="padding:12px 14px;margin:10px 0;background:${m.bg};border:1px solid ${m.color}33;border-left:4px solid ${m.color};border-radius:6px;">`

            + `<div style="font-size:0.66em;font-weight:700;letter-spacing:.05em;color:${m.color};margin-bottom:5px;">${m.icon} ${m.label}</div>`

            + `<div style="font-weight:650;color:#0f172a;">${title}</div>`

            + body + action + crops + `</div>`;

    }).join('');

}



// ===== REVIEW — VISUAL BOX EDITOR (approve / move / resize / relabel / add / delete) =====

const STATE_COLOR = { green: '#16a34a', orange: '#ea580c', yellow: '#ca8a04', purple: '#9333ea', gray: '#9ca3af', blue: '#2563eb' };

let reviewFloors = [];        // [{file,floor_name,page_num,width,height,boxes:[...]}]

let edFloorIdx = 0;           // index into reviewFloors of the floor being edited

let edBoxes = [];             // working copy of the current floor's boxes

let edImg = null;             // loaded page Image

let edScale = 1;              // canvas px per 300-dpi source px

let edSel = -1;              // selected box index (-1 = none)

let edDrag = null;            // {mode:'move'|'nw'|..|'new'|'pan', sx, sy, box0}

let edAdd = false;           // "add unit" mode armed

let edZoom = 1;              // wheel zoom (1 = fit width)

let edPanX = 0, edPanY = 0;  // pan offset in canvas px

const ED_MAXW = 1000;         // canvas display width cap

const HANDLE = 6;



// combined source(300-dpi)px → canvas px scale, and the inverse mapping

function edS() { return edScale * edZoom; }

function screenToSrc(mx, my) { const s = edS(); return [(mx - edPanX) / s, (my - edPanY) / s]; }

function edClampPan() {

    const canvas = document.getElementById('editorCanvas');

    if (!canvas) return;

    const dw = canvas.width * edZoom, dh = canvas.height * edZoom;

    edPanX = Math.min(0, Math.max(canvas.width - dw, edPanX));

    edPanY = Math.min(0, Math.max(canvas.height - dh, edPanY));

}



async function loadReview(taskId) {

    try {

        const res = await fetch(`${API_BASE}/review/${taskId}`);

        if (!res.ok) return;

        const data = await res.json();

        reviewFloors = data.floors || [];

        const sel = document.getElementById('reviewFloorSelect');

        if (sel) {

            sel.innerHTML = reviewFloors.map((f, i) =>

                `<option value="${i}">p${f.page_num} — ${f.floor_name || ''} (${(f.boxes || []).length})</option>`).join('');

            if (edFloorIdx >= reviewFloors.length) edFloorIdx = 0;

            sel.value = edFloorIdx;

        }

        // Cached results reconnected on upload (no analysis this session):

        // the tabs live inside resultsSection which starts hidden, so unhide

        // it and land on Review — otherwise the cached floors are unreachable.

        if (reviewFloors.length && resultsSection.style.display === 'none') {

            resultsSection.style.display = 'block';

            document.querySelector('.tab-btn[data-tab="review"]')?.click();

        }

        loadEditorFloor(edFloorIdx);

    } catch (e) { /* review panel is optional */ }

}



function loadEditorFloor(idx) {

    edFloorIdx = idx; edSel = -1; edAdd = false; edDrag = null;

    edZoom = 1; edPanX = 0; edPanY = 0;

    const fl = reviewFloors[idx];

    const canvas = document.getElementById('editorCanvas');

    if (!fl || !canvas) return;

    // deep-copy boxes so edits aren't committed until Save

    edBoxes = (fl.boxes || []).map(b => ({ ...b }));

    edImg = new Image();

    edImg.onload = () => {

        edScale = ED_MAXW / (fl.width || edImg.naturalWidth || ED_MAXW);

        canvas.width = Math.round((fl.width || edImg.naturalWidth) * edScale);

        canvas.height = Math.round((fl.height || edImg.naturalHeight) * edScale);

        drawEditor();

    };

    edImg.src = `${API_BASE}/page-image/${currentTaskId}/${fl.page_num}?dpi=150&max=3000`;

    updateSelToolbar(); updateNoiseCount();

}



// ── rotated-box geometry (b.angle = degrees, rotated about the box center) ──

function boxCenterScreen(b) {

    const s = edS();

    return [(b.x + b.w / 2) * s + edPanX, (b.y + b.h / 2) * s + edPanY];

}

// corner + rotation-handle positions in SCREEN px, honouring b.angle

function boxPtsScreen(b) {

    const s = edS();

    const cx = b.x + b.w / 2, cy = b.y + b.h / 2;

    const rad = (b.angle || 0) * Math.PI / 180, cos = Math.cos(rad), sin = Math.sin(rad);

    const local = {

        nw: [b.x, b.y], ne: [b.x + b.w, b.y],

        sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h],

        rot: [cx, b.y - 22 / s],   // 22 screen-px above top-centre

    };

    const out = {};

    for (const k in local) {

        const dx = local[k][0] - cx, dy = local[k][1] - cy;

        out[k] = [(cx + dx * cos - dy * sin) * s + edPanX,

                  (cy + dx * sin + dy * cos) * s + edPanY];

    }

    return out;

}

// map a source-space point into a box's LOCAL (unrotated) frame

function toBoxLocal(b, ix, iy) {

    const cx = b.x + b.w / 2, cy = b.y + b.h / 2;

    const rad = -(b.angle || 0) * Math.PI / 180, cos = Math.cos(rad), sin = Math.sin(rad);

    const dx = ix - cx, dy = iy - cy;

    return [cx + dx * cos - dy * sin, cy + dx * sin + dy * cos];

}



function drawEditor() {

    const canvas = document.getElementById('editorCanvas');

    if (!canvas) return;

    const ctx = canvas.getContext('2d');

    const s = edS();

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    if (edImg) ctx.drawImage(edImg, edPanX, edPanY, canvas.width * edZoom, canvas.height * edZoom);

    edBoxes.forEach((b, i) => {

        if (b.deleted) return;

        const col = STATE_COLOR[b.color] || (b.status === 'added' ? STATE_COLOR.purple : '#ef4444');

        const w = b.w * s, h = b.h * s;

        const [ccx, ccy] = boxCenterScreen(b);

        ctx.save();

        ctx.translate(ccx, ccy);

        ctx.rotate((b.angle || 0) * Math.PI / 180);

        ctx.lineWidth = i === edSel ? 3 : 2;

        ctx.strokeStyle = col;

        ctx.setLineDash(b.color === 'gray' ? [5, 4] : []);

        ctx.strokeRect(-w / 2, -h / 2, w, h);

        ctx.setLineDash([]);

        ctx.fillStyle = col;

        ctx.font = 'bold 13px sans-serif';

        ctx.fillText(b.tag || '?', -w / 2 + 2, -h / 2 - 3);

        ctx.restore();

        if (i === edSel) {

            const pts = boxPtsScreen(b);

            ['nw', 'ne', 'sw', 'se'].forEach(k => {

                const [hx, hy] = pts[k];

                ctx.fillStyle = '#000'; ctx.fillRect(hx - HANDLE, hy - HANDLE, HANDLE * 2, HANDLE * 2);

                ctx.strokeStyle = col; ctx.strokeRect(hx - HANDLE, hy - HANDLE, HANDLE * 2, HANDLE * 2);

            });

            // rotation handle: stem from top-centre up to a small circle

            const [rx, ry] = pts.rot;

            const tx = (pts.nw[0] + pts.ne[0]) / 2, ty = (pts.nw[1] + pts.ne[1]) / 2;

            ctx.strokeStyle = col; ctx.lineWidth = 2;

            ctx.beginPath(); ctx.moveTo(tx, ty); ctx.lineTo(rx, ry); ctx.stroke();

            ctx.beginPath(); ctx.arc(rx, ry, HANDLE, 0, 2 * Math.PI);

            ctx.fillStyle = '#fff'; ctx.fill(); ctx.strokeStyle = col; ctx.stroke();

        }

    });

}



// hit-test the selected box's handles; returns 'nw'|'ne'|'sw'|'se'|'rotate'|null

function hitHandle(mx, my) {

    if (edSel < 0) return null;

    const pts = boxPtsScreen(edBoxes[edSel]);

    if (Math.hypot(mx - pts.rot[0], my - pts.rot[1]) <= HANDLE + 3) return 'rotate';

    for (const name of ['nw', 'ne', 'sw', 'se'])

        if (Math.abs(mx - pts[name][0]) <= HANDLE && Math.abs(my - pts[name][1]) <= HANDLE) return name;

    return null;

}



function boxAt(mx, my) {

    const [ix, iy] = screenToSrc(mx, my);

    for (let i = edBoxes.length - 1; i >= 0; i--) {

        const b = edBoxes[i];

        if (b.deleted) continue;

        const [lx, ly] = toBoxLocal(b, ix, iy);   // into box-local frame for rotated boxes

        if (lx >= b.x && lx <= b.x + b.w && ly >= b.y && ly <= b.y + b.h) return i;

    }

    return -1;

}



function canvasXY(e) {

    const canvas = document.getElementById('editorCanvas');

    const r = canvas.getBoundingClientRect();

    return [(e.clientX - r.left) * (canvas.width / r.width),

            (e.clientY - r.top) * (canvas.height / r.height)];

}



function initEditorCanvas() {

    const canvas = document.getElementById('editorCanvas');

    if (!canvas || canvas._wired) return;

    canvas._wired = true;

    canvas.addEventListener('wheel', e => {

        e.preventDefault();

        const [mx, my] = canvasXY(e);

        const [sx, sy] = screenToSrc(mx, my);

        edZoom = Math.min(10, Math.max(1, edZoom * (e.deltaY < 0 ? 1.2 : 1 / 1.2)));

        // keep the source point under the cursor fixed

        edPanX = mx - sx * edS(); edPanY = my - sy * edS();

        edClampPan(); drawEditor();

    }, { passive: false });

    canvas.addEventListener('mousedown', e => {

        const [mx, my] = canvasXY(e);

        if (edAdd) { const [sx, sy] = screenToSrc(mx, my); edDrag = { mode: 'new', sx, sy }; return; }

        const handle = hitHandle(mx, my);

        if (handle) { edDrag = { mode: handle, box0: { ...edBoxes[edSel] } }; return; }

        const hit = boxAt(mx, my);

        if (hit >= 0) {

            edSel = hit; updateSelToolbar();

            const [sx, sy] = screenToSrc(mx, my);

            edDrag = { mode: 'move', sx, sy, box0: { ...edBoxes[hit] } };

        } else {

            edSel = -1; updateSelToolbar();

            edDrag = { mode: 'pan', lastx: mx, lasty: my };   // drag empty space to pan

        }

        drawEditor();

    });

    canvas.addEventListener('mousemove', e => {

        if (!edDrag) return;

        const [mx, my] = canvasXY(e);

        if (edDrag.mode === 'pan') {

            edPanX += mx - edDrag.lastx; edPanY += my - edDrag.lasty;

            edDrag.lastx = mx; edDrag.lasty = my; edClampPan(); drawEditor(); return;

        }

        const [ix, iy] = screenToSrc(mx, my);

        if (edDrag.mode === 'new') {

            edDrag.cx = ix; edDrag.cy = iy;

            drawEditor();

            const ctx = canvas.getContext('2d'); const s = edS();

            ctx.strokeStyle = STATE_COLOR.purple; ctx.lineWidth = 2;

            ctx.strokeRect(Math.min(edDrag.sx, ix) * s + edPanX, Math.min(edDrag.sy, iy) * s + edPanY,

                Math.abs(ix - edDrag.sx) * s, Math.abs(iy - edDrag.sy) * s);

            return;

        }

        const b = edBoxes[edSel]; const b0 = edDrag.box0;

        if (edDrag.mode === 'rotate') {

            const cx = b.x + b.w / 2, cy = b.y + b.h / 2;

            let deg = Math.atan2(iy - cy, ix - cx) * 180 / Math.PI + 90;  // handle sits above centre

            if (e.shiftKey) deg = Math.round(deg / 15) * 15;             // Shift = snap to 15°

            b.angle = ((Math.round(deg * 10) / 10) % 360 + 360) % 360;

        } else if (edDrag.mode === 'move') {

            b.x = Math.round(b0.x + (ix - edDrag.sx)); b.y = Math.round(b0.y + (iy - edDrag.sy));

        } else {

            // resize in the box's LOCAL (unrotated) frame so it works when rotated

            const [lx, ly] = toBoxLocal(b0, ix, iy);

            let x0 = b0.x, y0 = b0.y, x1 = b0.x + b0.w, y1 = b0.y + b0.h;

            if (edDrag.mode.includes('w')) x0 = lx; if (edDrag.mode.includes('e')) x1 = lx;

            if (edDrag.mode.includes('n')) y0 = ly; if (edDrag.mode.includes('s')) y1 = ly;

            b.x = Math.round(Math.min(x0, x1)); b.y = Math.round(Math.min(y0, y1));

            b.w = Math.max(4, Math.round(Math.abs(x1 - x0))); b.h = Math.max(4, Math.round(Math.abs(y1 - y0)));

        }

        drawEditor();

    });

    window.addEventListener('mouseup', () => {

        if (!edDrag) return;

        if (edDrag.mode === 'new' && edDrag.cx != null) {

            const x = Math.round(Math.min(edDrag.sx, edDrag.cx)), y = Math.round(Math.min(edDrag.sy, edDrag.cy));

            const w = Math.round(Math.abs(edDrag.cx - edDrag.sx)), h = Math.round(Math.abs(edDrag.cy - edDrag.sy));

            edDrag = null; edAdd = false;

            // Reset the button fully — label AND highlight — so a second add

            // works and the toolbar doesn't lie ("drawing…" while edAdd=false).

            const addBtn = document.getElementById('addUnitBtn');

            if (addBtn) { addBtn.classList.remove('btn-primary'); addBtn.textContent = '➕ Add unit'; }

            if (w > 5 && h > 5) {

                const tag = (prompt('Tag for the new unit (e.g. AC-D):') || '').trim().toUpperCase();

                if (tag) {

                    edBoxes.push({ id: '', tag, status: 'added', color: 'purple', action: 'keep', x, y, w, h, angle: 0 });

                    edSel = edBoxes.length - 1; updateSelToolbar();

                }

            }

            drawEditor();

            return;

        }

        edDrag = null;

    });

}



function updateSelToolbar() {

    const bar = document.getElementById('selToolbar');

    if (!bar) return;

    if (edSel < 0) { bar.style.display = 'none'; return; }

    bar.style.display = 'flex';

    const b = edBoxes[edSel];

    document.getElementById('selTagInput').value = b.tag || '';

    document.getElementById('selState').textContent = b.status || '';

}



function loadAnnotatedRefresh() {

    if (typeof loadAnnotated === 'function') loadAnnotated(currentTaskId);

}



// ── toolbar wiring ──

document.getElementById('reviewFloorSelect')?.addEventListener('change', e =>

    loadEditorFloor(+e.target.value));

document.getElementById('addUnitBtn')?.addEventListener('click', e => {

    edAdd = !edAdd;

    e.target.classList.toggle('btn-primary', edAdd);

    e.target.textContent = edAdd ? '✏️ drawing… (drag a box)' : '➕ Add unit';

});

document.getElementById('approveSelBtn')?.addEventListener('click', () => {

    if (edSel < 0) return;

    edBoxes[edSel].status = 'confirmed'; edBoxes[edSel].color = 'green'; edBoxes[edSel].action = 'keep';

    drawEditor(); updateSelToolbar();

});

document.getElementById('deleteSelBtn')?.addEventListener('click', () => {

    if (edSel < 0) return;

    edBoxes[edSel].action = 'delete'; edBoxes[edSel].deleted = true;

    edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();

});

document.getElementById('relabelSelBtn')?.addEventListener('click', () => {

    if (edSel < 0) return;

    const v = (document.getElementById('selTagInput').value || '').trim().toUpperCase();

    if (v) { edBoxes[edSel].tag = v; drawEditor(); }

});

document.getElementById('approveAllBtn')?.addEventListener('click', () => {

    // Skip gray noise: the engine judged those NOT-a-unit; approving them

    // blindly would turn verify-rejects into confirmed units. Skip deleted

    // boxes too — they're marked for removal, not for approval.

    edBoxes.forEach(b => {

        if (b.color === 'gray' || b.deleted) return;

        b.status = 'confirmed'; b.color = 'green'; b.action = 'keep';

    });

    drawEditor();

});

document.getElementById('deleteNoiseBtn')?.addEventListener('click', () => {

    edBoxes.forEach(b => {

        if (b.color === 'gray' && !b.deleted) { b.action = 'delete'; b.deleted = true; }

    });

    edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();

});

// Same idiom for yellows (user feedback: on clean buildings every yellow was

// junk — Mac cellar review). Confirm first: on some buildings real units hide

// in yellow (Queens fl28 had 7), so this is a glance-then-sweep, never blind.

document.getElementById('deleteYellowsBtn')?.addEventListener('click', () => {

    const n = edBoxes.filter(b => b.color === 'yellow' && !b.deleted).length;

    if (!n) return;

    if (!confirm(`Delete all ${n} yellow (unconfirmed) box(es) on this floor?\n`

                 + `Make sure none of them is a real unit first.`)) return;

    edBoxes.forEach(b => {

        if (b.color === 'yellow' && !b.deleted) { b.action = 'delete'; b.deleted = true; }

    });

    edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();

});

// Blue = auto-suggested extras (gap-hunt / template-sweep). Separate from the

// engine's own yellow "uncertain" reads, so they get their own sweep button.

document.getElementById('deleteSuggestedBtn')?.addEventListener('click', () => {

    const n = edBoxes.filter(b => b.color === 'blue' && !b.deleted).length;

    if (!n) return;

    if (!confirm(`Delete all ${n} blue (auto-suggested) box(es) on this floor?\n`

                 + `These are extra candidates the finder proposed — glance first in case a real unit is among them.`)) return;

    edBoxes.forEach(b => {

        if (b.color === 'blue' && !b.deleted) { b.action = 'delete'; b.deleted = true; }

    });

    edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();

});

function updateNoiseCount() {

    const el = document.getElementById('noiseCount');

    if (el) el.textContent = edBoxes.filter(b => b.color === 'gray' && !b.deleted).length;

    const yl = document.getElementById('yellowCount');

    if (yl) yl.textContent = edBoxes.filter(b => b.color === 'yellow' && !b.deleted).length;

    const sg = document.getElementById('suggestedCount');

    if (sg) sg.textContent = edBoxes.filter(b => b.color === 'blue' && !b.deleted).length;

}

document.addEventListener('keydown', e => {

    if (document.getElementById('review-tab')?.classList.contains('active') !== true) return;

    if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;

    if (edSel < 0) return;

    if (e.key === 'Delete' || e.key === 'd') {

        edBoxes[edSel].action = 'delete'; edBoxes[edSel].deleted = true;

        edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();

    }

    else if (e.key === 'Enter' || e.key === 'c') {

        edBoxes[edSel].status = 'confirmed'; edBoxes[edSel].color = 'green'; drawEditor(); updateSelToolbar();

    }

    // rotate the selected box: [ / ] = ±1°, Shift = ±15°

    else if (e.key === '[' || e.key === ']') {

        const step = (e.key === ']' ? 1 : -1) * (e.shiftKey ? 15 : 1);

        const b = edBoxes[edSel];

        b.angle = (((b.angle || 0) + step) % 360 + 360) % 360;

        drawEditor();

    }

});



document.getElementById('saveFloorBtn')?.addEventListener('click', async () => {

    const fl = reviewFloors[edFloorIdx];

    if (!fl) return;

    const btn = document.getElementById('saveFloorBtn');

    btn.disabled = true; const orig = btn.textContent; btn.textContent = 'Saving…';

    try {

        const res = await fetch(`${API_BASE}/save-review`, {

            method: 'POST', headers: { 'Content-Type': 'application/json' },

            body: JSON.stringify({ task_id: currentTaskId,

                floors: [{ file: fl.file, boxes: edBoxes }] })

        });

        if (!res.ok) throw new Error((await res.json()).detail || 'Save failed');

        const result = await pollUntilDone(currentTaskId);

        currentAnalysis = result; displayResults(result);

        await loadReview(currentTaskId);   // resync ids/colors after re-render

        loadAnnotatedRefresh();

    } catch (e) {

        showError('Save failed: ' + e.message);

    } finally { btn.disabled = false; btn.textContent = orig; }

});



initEditorCanvas();



// ===== Wheel-zoom for the schedule / floor picker images (scroll/drag to pan) =====

function enableImageZoom(wrapId, imgId, dragPan) {

    const wrap = document.getElementById(wrapId), img = document.getElementById(imgId);

    if (!wrap || !img || wrap._zoom) return;

    wrap._zoom = true;

    let z = 1;

    img.addEventListener('load', () => { z = 1; img.style.width = ''; img.style.maxWidth = '100%'; });

    if (dragPan) {

        let pan = null;

        wrap.addEventListener('mousedown', e => {

            pan = { x: e.clientX, y: e.clientY, sl: wrap.scrollLeft, st: wrap.scrollTop };

            wrap.style.cursor = 'grabbing'; e.preventDefault();

        });

        window.addEventListener('mousemove', e => {

            if (!pan) return;

            wrap.scrollLeft = pan.sl - (e.clientX - pan.x);

            wrap.scrollTop = pan.st - (e.clientY - pan.y);

        });

        window.addEventListener('mouseup', () => { pan = null; wrap.style.cursor = ''; });

    }

    wrap.addEventListener('wheel', e => {

        const rect = img.getBoundingClientRect();

        if (!rect.width) return;

        e.preventDefault();

        const relX = (e.clientX - rect.left) / rect.width;

        const relY = (e.clientY - rect.top) / rect.height;

        z = Math.min(8, Math.max(1, z * (e.deltaY < 0 ? 1.2 : 1 / 1.2)));

        const newW = wrap.clientWidth * z;

        img.style.maxWidth = 'none';

        img.style.width = newW + 'px';

        const wrapRect = wrap.getBoundingClientRect();

        const newH = img.getBoundingClientRect().height;

        wrap.scrollLeft = relX * newW - (e.clientX - wrapRect.left);

        wrap.scrollTop = relY * newH - (e.clientY - wrapRect.top);

    }, { passive: false });

}

enableImageZoom('schedImgWrap', 'schedImg', false);

enableImageZoom('floorImgWrap', 'floorImg', true);



// ===== SCHEDULE REGION PICKER =====

(function () {

    const modal = document.getElementById('schedModal');

    if (!modal) return;

    const img = document.getElementById('schedImg');

    const boxEl = document.getElementById('schedBox');

    const pageNum = document.getElementById('schedPageNum');

    let page = 1, drag = null, region = null;   // region in 0-1 fractions of the page



    function loadPage(n) {

        page = Math.max(1, uploadPages ? Math.min(n, uploadPages) : n);

        pageNum.value = page;

        boxEl.style.display = 'none'; region = null;

        img.src = `${API_BASE}/page-image/${uploadTaskId}/${page}?dpi=130&max=2000`;

    }

    function openModal() {

        if (!uploadTaskId) return;

        document.getElementById('schedPageTotal').textContent = uploadPages || '?';

        loadPage(1);

        modal.style.display = 'block';

    }

    function close() { modal.style.display = 'none'; }



    document.getElementById('addScheduleBtn')?.addEventListener('click', openModal);

    document.getElementById('schedPrev')?.addEventListener('click', () => loadPage(page - 1));

    document.getElementById('schedNext')?.addEventListener('click', () => loadPage(page + 1));

    pageNum.addEventListener('change', () => loadPage(parseInt(pageNum.value) || 1));

    document.getElementById('schedCancel')?.addEventListener('click', close);

    document.getElementById('schedClear')?.addEventListener('click', () => {

        boxEl.style.display = 'none'; region = null;

    });



    img.addEventListener('mousedown', e => {

        e.preventDefault();

        const r = img.getBoundingClientRect();

        drag = { x: e.clientX - r.left, y: e.clientY - r.top };

    });

    window.addEventListener('mousemove', e => {

        if (!drag) return;

        const r = img.getBoundingClientRect();

        const cx = Math.max(0, Math.min(e.clientX - r.left, r.width));

        const cy = Math.max(0, Math.min(e.clientY - r.top, r.height));

        const x0 = Math.min(drag.x, cx), y0 = Math.min(drag.y, cy);

        const w = Math.abs(cx - drag.x), h = Math.abs(cy - drag.y);

        boxEl.style.display = 'block';

        boxEl.style.left = (img.offsetLeft + x0) + 'px';

        boxEl.style.top = (img.offsetTop + y0) + 'px';

        boxEl.style.width = w + 'px';

        boxEl.style.height = h + 'px';

        region = { x0: x0 / r.width, y0: y0 / r.height,

                   x1: (x0 + w) / r.width, y1: (y0 + h) / r.height };

    });

    window.addEventListener('mouseup', () => { drag = null; });



    function addRegion(reg) {

        scheduleRegions.push({ page, x0: +reg.x0.toFixed(4), y0: +reg.y0.toFixed(4),

                               x1: +reg.x1.toFixed(4), y1: +reg.y1.toFixed(4) });

        renderScheduleChips();

        boxEl.style.display = 'none'; region = null;   // ready to add another

    }

    document.getElementById('schedUseRegion')?.addEventListener('click', () => {

        if (!region || (region.x1 - region.x0) < 0.01 || (region.y1 - region.y0) < 0.01) {

            alert('Draw a box around the schedule table first.'); return;

        }

        addRegion(region);

    });

    document.getElementById('schedWhole')?.addEventListener('click', () => {

        addRegion({ x0: 0, y0: 0, x1: 1, y1: 1 });

    });

})();



// ===== 🏦 SYMBOL BANK TAB (approve unit-body crops into the bank) =====

// One exemplar at a time: crop image + adjustable green box (drag body to

// move, corners to resize, nudge buttons / arrows), unit-type dropdown,

// Approve / Reject / Skip (keys a / r / s). Decisions persist server-side.

const BANK_MAXW = 560, BANK_MAXH = 440, BANK_HANDLE = 7;

let bankItems = [];            // pending exemplars from /api/bank/queue

let bankPos = 0;               // index of the item being shown

let bankImg = null;            // loaded crop Image

let bankScale = 1;             // canvas px per crop-image px

let bankBox = null;            // working {x,y,w,h} in crop-image px

let bankDrag = null;           // {mode:'move'|'nw'|'ne'|'sw'|'se', sx, sy, box0}

let bankSession = { approve: 0, reject: 0, skip: 0 };



function bankTabActive() {

    return document.getElementById('bank-tab')?.classList.contains('active') === true;

}



let bankTypesLoaded = false;



async function bankLoadTypes() {

    const sel = document.getElementById('bankType');

    if (!sel) return;

    try {

        const res = await fetch(`${API_BASE}/bank/types`);

        if (!res.ok) throw new Error('types unavailable');

        const data = await res.json();

        const opts = ['<option value="">— choose type —</option>'];

        (data.base || []).forEach(t => {

            opts.push(`<option value="${t.id}">${t.label}</option>`);

        });

        if ((data.custom || []).length) {

            opts.push('<optgroup label="Custom">');

            data.custom.forEach(t => {

                opts.push(`<option value="${t.id}">${t.label}</option>`);

            });

            opts.push('</optgroup>');

        }

        sel.innerHTML = opts.join('');

        bankTypesLoaded = true;

    } catch (e) {

        // leave whatever options exist; approve will just fail server-side

    }

}



document.getElementById('bankType')?.addEventListener('change', () => {

    const sel = document.getElementById('bankType');

    const customInput = document.getElementById('bankCustomType');

    if (!customInput) return;

    customInput.style.display = (sel.value === 'other') ? 'block' : 'none';

    if (sel.value !== 'other') customInput.value = '';

});



async function bankLoadQueue(autoShow) {

    const empty = document.getElementById('bankEmpty');

    try {

        const res = await fetch(`${API_BASE}/bank/queue`);

        if (!res.ok) throw new Error((await res.json()).detail || 'queue unavailable');

        const data = await res.json();

        bankItems = data.items || [];

        bankPos = 0;

        bankSession = { approve: 0, reject: 0, skip: 0 };

        bankCounts = data.counts || {};

        if (autoShow && bankItems.length) {

            // Make the Bank tab reachable without running an analysis first.

            resultsSection.style.display = 'block';

            document.querySelector('.tab-btn[data-tab="bank"]')?.click();

        }

        bankShow();

    } catch (e) {

        if (empty) empty.textContent = 'Bank queue unavailable: ' + e.message;

    }

}

let bankCounts = {};



function bankProgressText() {

    const total = bankCounts.exemplars || bankItems.length;

    const done = (bankCounts.approved || 0) + (bankCounts.rejected || 0)

        + bankSession.approve + bankSession.reject;

    return `Exemplar ${Math.min(bankPos + 1, bankItems.length)} of ${bankItems.length} pending`

        + ` · ${done}/${total} decided (bank total)`

        + ` · this session: ✓${bankSession.approve} ✗${bankSession.reject} ↷${bankSession.skip}`;

}



function bankShow() {

    const empty = document.getElementById('bankEmpty');

    const work = document.getElementById('bankWork');

    const summary = document.getElementById('bankSummary');

    const prog = document.getElementById('bankProgress');

    if (!work) return;

    document.getElementById('bankMsg').textContent = '';

    if (!bankItems.length || bankPos >= bankItems.length) {

        work.style.display = 'none';

        empty.style.display = 'none';

        summary.style.display = 'block';

        prog.textContent = '';

        const banked = (bankCounts.approved || 0) + bankSession.approve;

        summary.innerHTML = '<div style="padding:14px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;">'

            + '<h4 style="margin:0 0 6px;">🎉 Bank queue done</h4>'

            + `<p style="margin:0 0 4px;">This session: <b>${bankSession.approve}</b> approved, `

            + `<b>${bankSession.reject}</b> rejected, <b>${bankSession.skip}</b> skipped.</p>`

            + `<p style="margin:0 0 10px;color:#64748b;">${banked} crop(s) total in the bank `

            + '(analyzer_b/symbol_crops/). Approved crops are registered in symbol_library.json.</p>'

            + '<button class="btn btn-secondary" id="bankReload">↻ Reload queue</button></div>';

        document.getElementById('bankReload')?.addEventListener('click', () => bankLoadQueue(false));

        return;

    }

    summary.style.display = 'none';

    empty.style.display = 'none';

    work.style.display = 'block';

    prog.textContent = bankProgressText();



    const item = bankItems[bankPos];

    document.getElementById('bankMeta').innerHTML =

        `<b>${item.tag || '?'}</b> — ${item.building || ''}, page ${item.page}`

        + `<br>confidence ${item.confidence != null ? item.confidence : '?'}`

        + ` · cluster of ${item.cluster_size || 1}`

        + (item.skipped ? ' · <span style="color:#ca8a04;">previously skipped</span>' : '');

    document.getElementById('bankType').value = '';

    const customInput = document.getElementById('bankCustomType');

    if (customInput) { customInput.value = ''; customInput.style.display = 'none'; }



    // angle (degrees, clockwise) — rotate the box over a diagonal unit; the

    // backend de-rotates the saved crop so the body comes out upright.

    bankBox = Object.assign({ x: 0, y: 0, w: 10, h: 10, angle: 0 }, item.proposed_box || {});

    bankImg = new Image();

    bankImg.onload = () => {

        const canvas = document.getElementById('bankCanvas');

        if (!canvas) return;

        // Fit within the work area; upscale small crops (cap 3x) so the box

        // is comfortable to adjust.

        bankScale = Math.min(BANK_MAXW / bankImg.naturalWidth,

                             BANK_MAXH / bankImg.naturalHeight, 3);

        canvas.width = Math.round(bankImg.naturalWidth * bankScale);

        canvas.height = Math.round(bankImg.naturalHeight * bankScale);

        bankDraw();

    };

    bankImg.src = item.image_url + `?t=${Date.now()}`;

}



function bankClampBox() {

    if (!bankBox || !bankImg) return;

    const W = bankImg.naturalWidth, H = bankImg.naturalHeight;

    bankBox.w = Math.max(4, Math.min(Math.round(bankBox.w), W));

    bankBox.h = Math.max(4, Math.min(Math.round(bankBox.h), H));

    bankBox.x = Math.max(0, Math.min(Math.round(bankBox.x), W - bankBox.w));

    bankBox.y = Math.max(0, Math.min(Math.round(bankBox.y), H - bankBox.h));

}



function bankDraw() {

    const canvas = document.getElementById('bankCanvas');

    if (!canvas || !bankImg) return;

    const ctx = canvas.getContext('2d');

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.drawImage(bankImg, 0, 0, canvas.width, canvas.height);

    if (!bankBox) return;

    bankClampBox();

    const s = bankScale;

    const x = bankBox.x * s, y = bankBox.y * s, w = bankBox.w * s, h = bankBox.h * s;

    const cx = x + w / 2, cy = y + h / 2;

    const a = (bankBox.angle || 0) * Math.PI / 180;

    // dim everything outside the (possibly rotated) box so "body only" is

    // easy to judge — canvas rect + rotated inner rect, even-odd fill

    ctx.beginPath();

    ctx.rect(0, 0, canvas.width, canvas.height);

    ctx.save();

    ctx.translate(cx, cy); ctx.rotate(a);

    ctx.rect(-w / 2, -h / 2, w, h);

    ctx.restore();

    ctx.fillStyle = 'rgba(255,255,255,0.55)';

    ctx.fill('evenodd');

    // rotated green box + corner handles (drawn in box-local space)

    ctx.save();

    ctx.translate(cx, cy); ctx.rotate(a);

    ctx.strokeStyle = '#16a34a'; ctx.lineWidth = 2;

    ctx.strokeRect(-w / 2, -h / 2, w, h);

    [[-w / 2, -h / 2], [w / 2, -h / 2], [-w / 2, h / 2], [w / 2, h / 2]].forEach(([hx, hy]) => {

        ctx.fillStyle = '#16a34a';

        ctx.fillRect(hx - BANK_HANDLE, hy - BANK_HANDLE, BANK_HANDLE * 2, BANK_HANDLE * 2);

        ctx.strokeStyle = '#fff'; ctx.lineWidth = 1;

        ctx.strokeRect(hx - BANK_HANDLE, hy - BANK_HANDLE, BANK_HANDLE * 2, BANK_HANDLE * 2);

    });

    ctx.restore();

    const angleEl = document.getElementById('bankAngle');

    if (angleEl) angleEl.textContent = bankBox.angle ? `${bankBox.angle}°` : '';

}



// Mouse (image px) -> box-local coords (rotation-aware hit testing).

function bankToLocal(ix, iy) {

    const b = bankBox;

    const cx = b.x + b.w / 2, cy = b.y + b.h / 2;

    const a = -(b.angle || 0) * Math.PI / 180;

    const dx = ix - cx, dy = iy - cy;

    return [dx * Math.cos(a) - dy * Math.sin(a),

            dx * Math.sin(a) + dy * Math.cos(a)];

}



function bankCanvasXY(e) {

    const canvas = document.getElementById('bankCanvas');

    const r = canvas.getBoundingClientRect();

    return [(e.clientX - r.left) * (canvas.width / r.width),

            (e.clientY - r.top) * (canvas.height / r.height)];

}



function bankHitHandle(mx, my) {

    if (!bankBox) return null;

    const b = bankBox;

    // Compare in box-local space so handles stay grabbable at any rotation.

    const [lx, ly] = bankToLocal(mx / bankScale, my / bankScale);

    const tol = (BANK_HANDLE + 2) / bankScale;

    const corners = {

        nw: [-b.w / 2, -b.h / 2], ne: [b.w / 2, -b.h / 2],

        sw: [-b.w / 2, b.h / 2], se: [b.w / 2, b.h / 2],

    };

    for (const [name, [hx, hy]] of Object.entries(corners))

        if (Math.abs(lx - hx) <= tol && Math.abs(ly - hy) <= tol) return name;

    return null;

}



function initBankCanvas() {

    const canvas = document.getElementById('bankCanvas');

    if (!canvas || canvas._wired) return;

    canvas._wired = true;

    canvas.addEventListener('mousedown', e => {

        if (!bankBox) return;

        e.preventDefault();

        const [mx, my] = bankCanvasXY(e);

        const handle = bankHitHandle(mx, my);

        if (handle) { bankDrag = { mode: handle, box0: { ...bankBox } }; return; }

        const ix = mx / bankScale, iy = my / bankScale;

        const [lx, ly] = bankToLocal(ix, iy);   // inside-test in rotated space

        if (Math.abs(lx) <= bankBox.w / 2 && Math.abs(ly) <= bankBox.h / 2) {

            bankDrag = { mode: 'move', sx: ix, sy: iy, box0: { ...bankBox } };

        }

    });

    window.addEventListener('mousemove', e => {

        if (!bankDrag || !bankBox) return;

        const [mx, my] = bankCanvasXY(e);

        const ix = mx / bankScale, iy = my / bankScale;

        const b0 = bankDrag.box0;

        if (bankDrag.mode === 'move') {

            bankBox.x = b0.x + (ix - bankDrag.sx);

            bankBox.y = b0.y + (iy - bankDrag.sy);

        } else if (!bankBox.angle) {

            // unrotated: classic corner drag (opposite corner stays put)

            let x0 = b0.x, y0 = b0.y, x1 = b0.x + b0.w, y1 = b0.y + b0.h;

            if (bankDrag.mode.includes('w')) x0 = ix; if (bankDrag.mode.includes('e')) x1 = ix;

            if (bankDrag.mode.includes('n')) y0 = iy; if (bankDrag.mode.includes('s')) y1 = iy;

            bankBox.x = Math.min(x0, x1); bankBox.y = Math.min(y0, y1);

            bankBox.w = Math.abs(x1 - x0); bankBox.h = Math.abs(y1 - y0);

        } else {

            // rotated: center-anchored resize — the dragged corner tracks the

            // mouse in box-local space, the center stays put (keeps the math

            // sane at any angle; nudge buttons still fine-tune afterwards)

            const cx = b0.x + b0.w / 2, cy = b0.y + b0.h / 2;

            const [lx, ly] = bankToLocal(ix, iy);

            bankBox.w = Math.max(4, Math.abs(lx) * 2);

            bankBox.h = Math.max(4, Math.abs(ly) * 2);

            bankBox.x = cx - bankBox.w / 2;

            bankBox.y = cy - bankBox.h / 2;

        }

        bankDraw();

    });

    window.addEventListener('mouseup', () => { bankDrag = null; });

}



async function bankDecide(action) {

    if (bankPos >= bankItems.length) return;

    const item = bankItems[bankPos];

    const msg = document.getElementById('bankMsg');

    msg.textContent = '';

    const body = { id: item.id, action };

    if (action === 'approve') {

        const unitType = document.getElementById('bankType').value;

        if (!unitType) { msg.textContent = 'Pick a unit type before approving.'; return; }

        if (unitType === 'other') {

            const customType = (document.getElementById('bankCustomType')?.value || '').trim();

            if (!customType) { msg.textContent = 'Type a custom unit name before approving.'; return; }

            body.custom_type = customType;

        }

        bankClampBox();

        body.unit_type = unitType;

        body.box = { x: bankBox.x, y: bankBox.y, w: bankBox.w, h: bankBox.h,

                     angle: bankBox.angle || 0 };

    }

    ['bankApprove', 'bankReject', 'bankSkip'].forEach(id => {

        const b = document.getElementById(id); if (b) b.disabled = true;

    });

    try {

        const res = await fetch(`${API_BASE}/bank/decide`, {

            method: 'POST', headers: { 'Content-Type': 'application/json' },

            body: JSON.stringify(body)

        });

        if (!res.ok) throw new Error((await res.json()).detail || 'decide failed');

        bankSession[action]++;

        bankPos++;

        bankShow();

    } catch (e) {

        msg.textContent = e.message;

    } finally {

        ['bankApprove', 'bankReject', 'bankSkip'].forEach(id => {

            const b = document.getElementById(id); if (b) b.disabled = false;

        });

    }

}



document.getElementById('bankApprove')?.addEventListener('click', () => bankDecide('approve'));

document.getElementById('bankReject')?.addEventListener('click', () => bankDecide('reject'));

document.getElementById('bankSkip')?.addEventListener('click', () => bankDecide('skip'));

document.querySelectorAll('.bank-nudge').forEach(btn => btn.addEventListener('click', () => {

    if (!bankBox) return;

    bankBox[btn.dataset.k] += +btn.dataset.d;

    bankDraw();

}));

// Rotate over a diagonal unit (Shift = 15° steps, matching the Review editor).

function bankRotate(deg) {

    if (!bankBox) return;

    let a = (bankBox.angle || 0) + deg;

    a = ((a + 180) % 360 + 360) % 360 - 180;   // normalize to (-180, 180]

    bankBox.angle = Math.round(a * 10) / 10;

    bankDraw();

}

document.querySelectorAll('.bank-rot').forEach(btn => btn.addEventListener('click', e => {

    bankRotate(+btn.dataset.d * (e.shiftKey ? 7.5 : 1));

}));

document.getElementById('bankRotReset')?.addEventListener('click', () => {

    if (!bankBox) return;

    bankBox.angle = 0;

    bankDraw();

});



// keyboard: a=approve r=reject s=skip · arrows move · Shift+arrows resize

document.addEventListener('keydown', e => {

    if (!bankTabActive()) return;

    if (['INPUT', 'SELECT', 'TEXTAREA'].includes(e.target.tagName)) return;

    if (e.key === 'a') { bankDecide('approve'); }

    else if (e.key === 'r') { bankDecide('reject'); }

    else if (e.key === 's') { bankDecide('skip'); }

    else if (e.key === '[' || e.key === '{') { bankRotate(e.shiftKey ? -15 : -2); }

    else if (e.key === ']' || e.key === '}') { bankRotate(e.shiftKey ? 15 : 2); }

    else if (e.key.startsWith('Arrow') && bankBox) {

        e.preventDefault();

        const d = 2;

        if (e.shiftKey) {

            if (e.key === 'ArrowRight') bankBox.w += d;

            else if (e.key === 'ArrowLeft') bankBox.w -= d;

            else if (e.key === 'ArrowDown') bankBox.h += d;

            else if (e.key === 'ArrowUp') bankBox.h -= d;

        } else {

            if (e.key === 'ArrowRight') bankBox.x += d;

            else if (e.key === 'ArrowLeft') bankBox.x -= d;

            else if (e.key === 'ArrowDown') bankBox.y += d;

            else if (e.key === 'ArrowUp') bankBox.y -= d;

        }

        bankDraw();

    }

});



initBankCanvas();

// Load the type dropdown + queue on page open; if there is pending work,

// surface the Bank tab so it is reachable without running an analysis first.

bankLoadTypes();

bankLoadQueue(true);



// ===== FLOOR PAGE PICKER (page-by-page; add each floor plan) =====

(function () {

    const modal = document.getElementById('floorModal');

    if (!modal) return;

    const img = document.getElementById('floorImg');

    const pageNum = document.getElementById('floorPageNum');

    const nameInput = document.getElementById('floorNameInput');

    let page = 1;



    function loadPage(n) {

        page = Math.max(1, uploadPages ? Math.min(n, uploadPages) : n);

        pageNum.value = page;

        img.src = `${API_BASE}/page-image/${uploadTaskId}/${page}?dpi=130&max=2000`;

    }

    function openModal() {

        if (!uploadTaskId) return;

        document.getElementById('floorPageTotal').textContent = uploadPages || '?';

        loadPage(1);

        modal.style.display = 'block';

    }

    function close() { modal.style.display = 'none'; }



    document.getElementById('addFloorBtn')?.addEventListener('click', openModal);

    document.getElementById('floorPrev')?.addEventListener('click', () => loadPage(page - 1));

    document.getElementById('floorNext')?.addEventListener('click', () => loadPage(page + 1));

    pageNum.addEventListener('change', () => loadPage(parseInt(pageNum.value) || 1));

    document.getElementById('floorDone')?.addEventListener('click', close);

    document.getElementById('floorAdd')?.addEventListener('click', () => {

        if (floorPages.some(f => f.page_num === page)) {

            alert(`Page ${page} is already added.`); return;

        }

        floorPages.push({ page_num: page, name: (nameInput.value || '').trim() });

        nameInput.value = '';

        renderFloorChips();

    });

})();