Dashboard Temp Share Shortlinks Frames API

HTMLify

CrashCartInvProg.html
Views: 19 | Author: deweyduck6116
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Crash Cart Drawer Inventory</title>
<style>
@page { margin: 0.2in 0.3in 0.2in 0.3in; }
@media print {
  .no-print { display: none !important; }
  .sheet { box-shadow: none; border: none; margin: 0; page-break-after: auto; }
  .print-scale-wrap { page-break-after: always; overflow: hidden; }
  .print-scale-wrap:last-child { page-break-after: auto; }
}
:root { --font: "Segoe UI", Arial, Helvetica, sans-serif; --nav-h: 42px; }
body { font-family: var(--font); margin: 0; background: #f2f2f2; color: #111; }

/* ---------------- PRINT BUNDLE ---------------- */
.print-bundle { display: none; }
body.printing #pages, body.printing .nav-strip, body.printing .toolbar, body.printing .print-all-wrap, body.printing .cart-banner, body.printing #statusBoardContainer {
  display: none !important;
}
body.printing .print-bundle { display: block !important; }
@media print {
  #statusBoardContainer { display: none !important; }
}

/* ---------------- NAV STRIP ---------------- */
.nav-strip {
  position: sticky; top: 0; z-index: 30;
  height: var(--nav-h); box-sizing: border-box;
  background: #1f2937; color: #fff;
  display: flex; align-items: center; gap: 10px;
  padding: 0 15px;
}
.no-cart-placeholder-img {
  display: block; margin: 10px auto 0; width: 160px; height: 160px; border: 1px solid #ccc;
  border-radius: 4px; background: #fff; padding: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.08);
  box-sizing: border-box;
}
.no-cart-placeholder-img img, .no-cart-placeholder-img canvas { width: 100%; height: 100%; display: block; }
.nav-strip button.toggle-menu {
  background: #374151; color: #fff; border: 1px solid #4b5563; border-radius: 4px;
  padding: 6px 12px; font-size: 12px; font-weight: bold; cursor: pointer;
}
.nav-strip button.toggle-menu:hover { background: #4b5563; }
.nav-strip .jump-label { font-size: 11px; text-transform: uppercase; color: #9ca3af; font-weight: bold; }
.nav-strip select {
  background: #fff; color: #111; border: 1px solid #4b5563; border-radius: 4px;
  padding: 5px 8px; font-size: 12px; font-family: var(--font);
}
.nav-strip .spacer { flex: 1; }
.nav-strip .status-text { font-size: 11px; color: #9ca3af; }

/* ---------------- COMMAND / TOOLBAR PANEL ---------------- */
.toolbar {
  display: grid;
  grid-template-columns: 150px 2fr 1.8fr 2fr;
  gap: 12px;
  background: #fff; border-bottom: 2px solid #ccc;
  padding: 14px 15px;
  box-sizing: border-box;
  position: fixed; top: var(--nav-h); left: 0; right: 0; z-index: 20;
  overflow: hidden;
  max-height: 950px;
  box-shadow: 0 4px 10px rgba(0,0,0,0.15);
  transition: max-height 0.2s ease, padding 0.2s ease, border-width 0.2s ease;
}
.toolbar.hidden { max-height: 0; padding-top: 0; padding-bottom: 0; border-bottom-width: 0; }

/* ---- iPhone-friendly single-column mode (toggled via "Desktop Layout" checkbox) ---- */
.toolbar.mobile-friendly {
  grid-template-columns: 1fr;
  max-height: 90vh;
  overflow-y: auto;
}
.toolbar.mobile-friendly .two-col,
.toolbar.mobile-friendly .list-actions {
  grid-template-columns: 1fr;
  gap: 8px;
}
.toolbar.mobile-friendly button,
.toolbar.mobile-friendly input,
.toolbar.mobile-friendly select,
.toolbar.mobile-friendly textarea {
  font-size: 15px;
  padding: 11px 10px;
}
.toolbar.mobile-friendly .list-panel {
  height: auto;
  max-height: 180px;
}
.toolbar.mobile-friendly .toolbar-group {
  border-bottom: 1px solid #eee;
  padding-bottom: 12px;
  margin-bottom: 4px;
}
.toolbar.mobile-friendly .toolbar-group:last-of-type {
  border-bottom: none;
}

.toolbar label { font-size: 10px; font-weight: bold; text-transform: uppercase; color: #444; display: block; margin-bottom: 3px; }
.toolbar input, .toolbar select, .toolbar textarea, .toolbar button {
  width: 100%; border: 1px solid #bbb; border-radius: 4px;
  font-family: var(--font); font-size: 12px; box-sizing: border-box; background: #fff;
  padding: 6px 8px;
}
.toolbar input[readonly] { background: #f0f0f0; color: #333; cursor: not-allowed; }

.date-field { margin-bottom: 10px; }
.lock-field { margin-top: 4px; margin-bottom: 10px; }
.chk-inline {
  display: flex; align-items: center; gap: 6px;
  font-size: 11px; font-weight: bold; text-transform: none; color: #444; cursor: pointer;
}
.chk-inline input { width: auto; }

.section-label { font-size: 10px; font-weight: bold; text-transform: uppercase; color: #007bff; margin: 8px 0 4px; border-top: 1px solid #eee; padding-top: 8px; }
.section-label:first-child { margin-top: 0; border-top: none; padding-top: 0; }

.toolbar-group { display: flex; flex-direction: column; height: 100%; }
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
.two-col button { padding: 6px; font-size: 11px; cursor: pointer; }
.two-col button.danger { border-color: #dc3545; color: #842029; background: #fff5f5; }

.list-panel {
  border: 1px solid #ccc; border-radius: 4px; padding: 4px;
  height: 108px; min-height: 60px; overflow-y: auto; background: #fafafa;
}
.list-panel .chk {
  display: grid; grid-template-columns: 16px auto; column-gap: 4px;
  align-items: center; font-size: 11px; margin-bottom: 2px; cursor: pointer;
}
.list-panel .empty-msg { font-size: 11px; color: #888; padding: 6px; }
.list-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; margin-top: 6px; }
.list-actions button { padding: 5px; font-size: 11px; cursor: pointer; }

.actions { display: flex; flex-direction: column; gap: 6px; justify-content: flex-start; }
.actions button { padding: 8px; font-weight: bold; cursor: pointer; font-size: 11px; }
#btnLoadWorkbook { background: #eefbff; border: 1px solid #007bff; color: #004085; }
#btnLoadWorkbook:disabled { opacity: 0.6; cursor: not-allowed; }
#btnSaveCartJson { background: #eef7ff; border: 1px solid #007bff; color: #004085; }
#btnExportCsv { background: #fff9ee; border: 1px solid #d99b00; color: #6b4e00; }
#btnPrintSelected { background: #f0fff0; border: 1px solid #28a745; color: #155724; }
#btnChooseFolder { background: #f4eeff; border: 1px solid #6f42c1; color: #3d1f75; }
label.file-label {
  display: block; text-align: center; padding: 8px; font-weight: bold; cursor: pointer;
  border: 1px solid #bbb; border-radius: 4px; background: #f7f7f7; font-size: 11px;
}

.wb-status {
  font-size: 11px; border: 1px dashed #bbb; border-radius: 4px; background: #fafafa;
  padding: 6px; min-height: 30px; color: #333; line-height: 1.4; white-space: pre-wrap;
}
.wb-status.loaded { border-color: #28a745; background: #f0fff4; color: #155724; }
.wb-status.error { border-color: #dc3545; background: #fff5f5; color: #842029; }
.wb-status.none { border-color: #dc3545; background: #fff5f5; color: #842029; }

.list-panel.status-red { border-color: #dc3545; background: #fff5f5; }
.list-panel.status-green { border-color: #28a745; background: #f0fff4; }
#selCartSwitcher.status-red { border-color: #dc3545; background: #fff5f5; color: #842029; }
#selCartSwitcher.status-green { border-color: #28a745; background: #f0fff4; color: #155724; }

.print-all-wrap { max-width: 8.5in; margin: 10px auto 0; padding: 0 8px; }
.print-all-wrap button {
  padding: 10px 16px; font-weight: bold; border-radius: 4px; cursor: pointer;
  border: 1px solid #6c757d; background: #f8f9fa; color: #333;
}

.cart-banner {
  max-width: 8.5in; margin: 10px auto 0; padding: 8px 14px;
  background: #eef7ff; border: 1px solid #b6dcff; border-radius: 4px;
  font-size: 12px; color: #004085; font-weight: 600;
}
.cart-banner.dirty { background: #fff3cd; border-color: #ffc107; color: #664d03; }

.legend {
  max-width: 8.5in; margin: 6px auto 0; padding: 0 14px;
  font-size: 11px; color: #555; display: flex; gap: 16px; align-items: center;
}
.legend .swatch { display: inline-block; width: 12px; height: 12px; border-radius: 2px; margin-right: 4px; vertical-align: middle; border: 1px solid #999; }
.legend .sw-past { background: #f5c2c7; }
.legend .sw-soon { background: #ffe69c; }

.empty-state {
  max-width: 8.5in; margin: 40px auto; padding: 40px;
  border: 2px dashed #bbb; border-radius: 8px; text-align: center; color: #888;
}

.data-loss-warning {
  max-width: 8.5in; margin: 10px auto 0; padding: 10px 16px;
  background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px;
  font-size: 12px; color: #664d03; font-weight: 600;
  display: flex; align-items: center; gap: 8px;
}
.data-loss-warning svg { width: 18px; height: 18px; flex-shrink: 0; }

/* ---------------- FORM SHEETS ---------------- */
.sheet {
  width: 8.5in; min-height: 11in;
  margin: 16px auto;
  background: #fff;
  box-shadow: 0 0 0 1px #ddd, 0 8px 24px rgba(0,0,0,.08);
  box-sizing: border-box;
  padding: 0.3in 0.35in;
  scroll-margin-top: calc(var(--nav-h) + 520px);
}

.cover-box { border: 2px solid #111; }
.cover-row { border-bottom: 2px solid #111; padding: 10px 12px; }
.cover-row:last-child { border-bottom: none; }
.cover-header {
  text-align: center; font-size: 20px; font-weight: 700; letter-spacing: 1px;
  display: flex; align-items: center; justify-content: center; gap: 6px; flex-wrap: wrap;
}
.cover-header input { border: none; border-bottom: 1px solid #111; width: 70px; text-align: center; font-size: 16px; font-family: var(--font); }
.auto-filled { background: #f0f0f0 !important; color: #333; cursor: not-allowed; }

.cover-label { text-align: center; font-size: 22px; font-weight: 700; margin-bottom: 8px; }
.cover-blank { min-height: 90px; }
.cover-blank textarea, .cover-blank input.auto-filled {
  width: 100%; height: 100%; border: none; outline: none; resize: none;
  font-family: var(--font); text-align: center; box-sizing: border-box;
  font-size: 60px; line-height: 1; padding-top: 14px;
}
.cover-blank.small textarea, .cover-blank.small input.auto-filled {
  font-size: 38px; padding-top: 10px;
}

.supply-row { display: flex; gap: 24px; align-items: center; font-size: 13px; }
.supply-row .field { display: flex; align-items: center; gap: 6px; flex: 1; }
.supply-row input { flex: 1; border: none; border-bottom: 1px solid #111; font-family: var(--font); font-size: 13px; padding: 2px; }

table.checkoff { width: 100%; border-collapse: collapse; margin-top: 0; }
table.checkoff th, table.checkoff td { border: 1px solid #111; padding: 6px 4px; text-align: center; font-size: 11px; }
table.checkoff th { font-weight: 700; }
table.checkoff td { height: 40px; }
table.checkoff td input { width: 100%; height: 100%; border: none; text-align: center; font-family: var(--font); font-size: 12px; background: transparent; }

.inv-title-bar { border: 2px solid #111; }
.inv-title-bar .top { text-align: center; font-size: 11px; font-weight: 700; border-bottom: 1px solid #111; padding: 3px; letter-spacing: .5px; }
.inv-title-bar .main { text-align: center; font-size: 30px; font-weight: 700; padding: 8px; }

.inv-meta { display: grid; grid-template-columns: 1fr 1fr; border: 1px solid #111; border-top: none; font-size: 12px; }
.inv-meta > div { padding: 5px 8px; border-bottom: 1px solid #111; display: flex; align-items: center; gap: 6px; }
.inv-meta > div:nth-child(odd) { border-right: 1px solid #111; }
.inv-meta input { flex: 1; border: none; border-bottom: 1px solid #999; font-family: var(--font); font-size: 12px; padding: 2px; min-width: 0; background: transparent; }
.inv-meta label { font-weight: 700; white-space: nowrap; }

table.inv { width: 100%; border-collapse: collapse; margin-top: 6px; font-size: 11.5px; }
table.inv th, table.inv td { border: 1px solid #111; padding: 3px 5px; text-align: center; vertical-align: middle; }
table.inv th { font-weight: 700; background: #fafafa; }
table.inv td.desc { text-align: left; }
table.inv td input {
  width: 100%; border: none; outline: none; font-family: var(--font); font-size: 11.5px;
  text-align: center; box-sizing: border-box; background: transparent;
}
table.inv td.desc input { text-align: left; }
.locked-field { background: #eee !important; color: #555; cursor: not-allowed; }
col.qty { width: 7%; } col.desc { width: 34%; } col.ref { width: 15%; }
col.msd { width: 14%; } col.ifcap { width: 10%; } col.exp { width: 14%; }

.date-past { background-color: #f5c2c7 !important; }
.date-soon { background-color: #ffe69c !important; }
.msd-stale { outline: 2px dashed #0d6efd !important; outline-offset: -2px; background-color: #eaf2ff !important; }
@media print {
  .msd-stale { outline: none !important; background-color: transparent !important; }
}

.row-actions { margin-top: 6px; display: flex; gap: 8px; }
.row-actions button {
  padding: 5px 10px; font-size: 11px; border: 1px solid #888; border-radius: 4px;
  background: #f7f7f7; cursor: pointer;
}
.row-actions button.remove { border-color: #dc3545; color: #842029; background: #fff5f5; }

.drawer-photo-wrap { display: flex; justify-content: center; margin-top: 16px; }
.drawer-photo {
  width: 3.2in; height: 2.2in;
  border: 1px solid #999; border-radius: 4px;
  background: repeating-linear-gradient(45deg, #f4f4f4, #f4f4f4 10px, #ececec 10px, #ececec 20px);
  display: flex; align-items: center; justify-content: center; flex-direction: column;
  color: #888; font-size: 11px; text-align: center; gap: 4px;
}
.drawer-photo svg { width: 40px; height: 40px; opacity: 0.5; }
.drawer-photo img { width: 100%; height: 100%; object-fit: contain; display: block; border-radius: 3px; }

/* ---------------- STATUS BOARD ---------------- */
.board-title-bar { border: 2px solid #111; }
.board-title-bar .top { text-align: center; font-size: 11px; font-weight: 700; border-bottom: 1px solid #111; padding: 3px; letter-spacing: .5px; }
.board-title-bar .main { text-align: center; font-size: 22px; font-weight: 700; padding: 6px; }

table.board { width: 100%; border-collapse: collapse; margin-top: 6px; font-size: 13px; table-layout: fixed; }
table.board th, table.board td { border: 1px solid #333; padding: 6px 8px; text-align: center; vertical-align: middle; word-wrap: break-word; line-height: 1.3; }
table.board thead th { font-weight: 700; background: #dfe4ea; font-size: 12.5px; text-transform: uppercase; letter-spacing: 0.3px; padding: 7px 8px; }
table.board td.loc, table.board td.drawer-cell, table.board td.tech-cell { text-align: left; }
table.board tbody tr:nth-child(even) td { background: #f7f8fa; }
table.board tr { page-break-inside: avoid; }
table.board col.col-cart { width: 8%; }
table.board col.col-loc { width: 11%; }
table.board col.col-due { width: 10%; }
table.board col.col-suction { width: 10%; }
table.board col.col-drawer { width: 31%; }
table.board col.col-room { width: 10%; }
table.board col.col-tech { width: 20%; }

.board-legend { margin-top: 10px; font-size: 11px; }
.board-legend div { display: flex; align-items: center; gap: 6px; margin-bottom: 3px; }
.board-legend .swatch { width: 16px; height: 12px; border: 1px solid #999; display: inline-block; }
.board-empty { padding: 30px; text-align: center; color: #888; border: 2px dashed #bbb; border-radius: 8px; }
.board-sheet { width: 8in; min-height: 10in; }
.board-page-indicator { text-align: right; font-size: 11px; color: #555; font-weight: 600; margin: 4px 0 8px; }

/* ---------------- EMERGENCY PICK LIST (plain spreadsheet-style, not part of the official form) ---------------- */
.picklist-heading { text-align: center; font-size: 20px; font-weight: 700; letter-spacing: 0.5px; margin-bottom: 4px; }
.picklist-sub { text-align: center; font-size: 11px; color: #666; margin-bottom: 14px; }
table.picklist { width: 100%; border-collapse: collapse; font-size: 11.5px; }
table.picklist th, table.picklist td { border: 1px solid #111; padding: 4px 6px; text-align: center; vertical-align: middle; }
table.picklist th { font-weight: 700; background: #fafafa; }
table.picklist td.desc { text-align: left; }
/* Row colors reflect a common (though not formally standardized) crash-cart drawer
   color convention: blue = Airway, yellow = IV Supplies. Drawer 5 (Procedure Supplies)
   and Top Shelf (Resuscitation Equipment) don't map to that original two-color scheme,
   so green/gray were chosen as reasonable extensions — adjust freely if your facility
   already has its own documented convention. */
table.picklist tr.picklist-row-airway td { background: #cfe2ff; }
table.picklist tr.picklist-row-iv td { background: #fff3cd; }
table.picklist tr.picklist-row-procedure td { background: #d1e7dd; }
table.picklist tr.picklist-row-equipment td { background: #e2e3e5; }
table.picklist tr.picklist-row-breathing td { background: #e0cffc; }
.picklist-legend { margin-top: 12px; font-size: 11px; display: flex; flex-wrap: wrap; gap: 14px; }
.picklist-legend div { display: flex; align-items: center; gap: 6px; }
.picklist-legend .swatch { width: 16px; height: 12px; border: 1px solid #999; display: inline-block; }

/* ---------------- DUPLICATE RESOLUTION MODAL ---------------- */
.modal-overlay {
  position: fixed; inset: 0; background: rgba(0,0,0,0.5);
  display: flex; align-items: center; justify-content: center; z-index: 1000;
}
.modal-box {
  background: #fff; border-radius: 8px; padding: 20px 24px;
  max-width: 560px; width: 90%; max-height: 80vh; overflow-y: auto;
  box-shadow: 0 12px 32px rgba(0,0,0,0.25);
}
.modal-box h3 { margin: 0 0 4px; font-size: 16px; }
.modal-box .modal-sub { font-size: 12px; color: #666; margin-bottom: 14px; }
.modal-option {
  border: 1px solid #ddd; border-radius: 6px; padding: 10px 12px; margin-bottom: 8px;
  cursor: pointer; font-size: 12px; display: flex; gap: 10px; align-items: flex-start;
}
.modal-option:hover { background: #f7f9ff; border-color: #99b8ff; }
.modal-option input[type="radio"] { margin-top: 3px; }
.modal-option .opt-detail { color: #444; line-height: 1.5; }
.modal-option .opt-detail b { color: #111; }
.modal-remember { display: flex; align-items: center; gap: 6px; font-size: 12px; margin: 14px 0; }
.modal-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 8px; }
.modal-actions button { padding: 8px 16px; border-radius: 4px; font-size: 12px; cursor: pointer; }
.modal-actions .btn-cancel { border: 1px solid #ccc; background: #f7f7f7; }
.modal-actions .btn-confirm { border: 1px solid #007bff; background: #007bff; color: #fff; font-weight: bold; }
.modal-actions .btn-confirm:disabled { background: #9cc3ef; border-color: #9cc3ef; cursor: not-allowed; }
.modal-actions .btn-discard { border: 1px solid #dc3545; color: #842029; background: #fff5f5; font-weight: bold; }

.modal-box.wide { max-width: 900px; }
.help-content h4 { margin: 16px 0 6px; font-size: 13px; color: #007bff; }
.help-content h4:first-child { margin-top: 0; }
.help-content p, .help-content li { font-size: 12.5px; line-height: 1.6; color: #333; }
.help-content ul { margin: 4px 0 4px 18px; padding: 0; }
.help-content .kbd { background: #eee; border: 1px solid #ccc; border-radius: 3px; padding: 1px 6px; font-family: monospace; font-size: 11px; }

.autogen-controls { display: flex; gap: 10px; align-items: center; margin-bottom: 12px; }
.autogen-controls select { padding: 6px 8px; font-size: 12px; border: 1px solid #bbb; border-radius: 4px; }
.autogen-controls button { padding: 7px 14px; font-size: 12px; font-weight: bold; border-radius: 4px; cursor: pointer; border: 1px solid #28a745; background: #f0fff0; color: #155724; }
.autogen-controls button.copied { background: #28a745; color: #fff; }
.autogen-table-wrap { max-height: 50vh; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; }
table.autogen { width: 100%; border-collapse: collapse; font-size: 11px; }
table.autogen th, table.autogen td { border: 1px solid #ddd; padding: 4px 6px; text-align: left; white-space: nowrap; }
table.autogen thead th { position: sticky; top: 0; background: #f7f7f7; font-weight: 700; }
table.autogen td.num { text-align: right; }

.nav-strip .right-actions { display: flex; gap: 8px; }
.nav-strip .right-actions button {
  background: #374151; color: #fff; border: 1px solid #4b5563; border-radius: 4px;
  padding: 6px 12px; font-size: 12px; font-weight: bold; cursor: pointer;
}
.nav-strip .right-actions button:hover { background: #4b5563; }
.nav-strip .right-actions button.autogen-btn { background: #0d6efd; border-color: #0a58ca; }
.nav-strip .right-actions button.autogen-btn:hover { background: #0a58ca; }
.dev-trigger {
  background: none; border: none; padding: 0 0 0 4px; font-size: 10px;
  color: #fff; vertical-align: super; cursor: default; outline: none;
}
.dev-trigger:hover, .dev-trigger:focus, .dev-trigger:active {
  background: none; color: #fff; box-shadow: none; text-decoration: none;
}
.nav-qr {
  width: 32px; height: 32px; background: #fff; border-radius: 4px;
  padding: 2px; box-sizing: border-box; display: flex; align-items: center; justify-content: center;
  flex-shrink: 0; cursor: pointer;
}
.nav-qr:hover { outline: 2px solid #6c8fff; }
.nav-qr img, .nav-qr canvas { width: 100%; height: 100%; display: block; }
.nav-strip .nav-title {
  font-size: 14px; font-weight: 700; color: #fff; letter-spacing: 0.3px;
  white-space: nowrap;
}
.devtool-log {
  font-size: 11px; font-family: monospace; background: #1e1e1e; color: #d4d4d4;
  border-radius: 4px; padding: 10px; max-height: 240px; overflow-y: auto;
  white-space: pre-wrap; margin-top: 10px;
}
.devtool-row { margin-bottom: 10px; }
.devtool-row label { display: block; font-size: 11px; font-weight: bold; text-transform: uppercase; color: #444; margin-bottom: 4px; }
</style>
</head>
<body>

<div class="nav-strip no-print">
  <button id="btnToggleMenu" class="toggle-menu">Show Command Menu</button>
  <span class="jump-label">Jump to:</span>
  <select id="selJumpPage"></select>
  <div class="spacer"></div>
  <span class="nav-title">Crash Cart Inventory Tool<button id="btnDevTool" class="dev-trigger" title="">v1</button></span>
  <div class="spacer"></div>
  <span class="status-text" id="navStatus"></span>
  <div class="nav-qr no-print" id="navQrCode" title="https://htmlify.me/deweyduck6116/Inventory/CrashCartInvProg.html"></div>
  <div class="right-actions">
    <button id="btnAutoGen" class="autogen-btn">Auto-Gen</button>
    <button id="btnHelp">Help ?</button>
  </div>
</div>

<div id="noCartPlaceholderImg" class="no-cart-placeholder-img no-print" style="display:none;"></div>

<div class="toolbar no-print hidden" id="toolbarPanel">
  <div class="toolbar-group">
    <div class="date-field">
      <label>Fiscal Year</label>
      <input id="inpFY" readonly />
    </div>
    <div class="date-field">
      <label>Month</label>
      <input id="inpMonth" readonly />
    </div>
    <div class="date-field">
      <label>Day</label>
      <input id="inpDay" readonly />
    </div>
    <div class="lock-field">
      <label class="chk-inline"><input type="checkbox" id="chkLockFields" checked /> Lock Fields</label>
    </div>
    <div class="lock-field">
      <label class="chk-inline"><input type="checkbox" id="chkDesktopLayout" checked /> Desktop Layout</label>
    </div>
    <div class="lock-field">
      <label class="chk-inline"><input type="checkbox" id="chkHideEmergencyList" checked /> Hide Emergency Pick List</label>
    </div>
    <div class="lock-field">
      <label class="chk-inline"><input type="checkbox" id="chkHideEmergencyAutoGenBoxes" checked /> Hide Emergency Auto Gen Boxes</label>
    </div>
  </div>

  <div class="toolbar-group">
    <div class="section-label">Active Cart Info</div>
    <div class="date-field">
      <label>Supply Technician</label>
      <input id="inpSupplyTech" type="text" placeholder="Enter name" />
    </div>
    <div class="date-field">
      <label>Secondary Location</label>
      <input id="inpCaseCartNum" type="text" placeholder="Free text" />
    </div>
    <div class="date-field">
      <label>Room Location</label>
      <input id="inpRoomLocation" type="text" placeholder="Free text" />
    </div>
    <div class="section-label">Active Cart</div>
    <select id="selCartSwitcher"></select>
    <div class="date-field" style="margin-top:6px;">
      <label>New Cart Number</label>
      <select id="selNewCartNumber"></select>
    </div>
    <div class="two-col">
      <button id="btnNewCart">+ New Cart</button>
      <button id="btnDeleteCart" class="danger">Delete Cart</button>
    </div>
  </div>

  <div class="toolbar-group">
    <label>Carts to Print</label>
    <div id="printChecklist" class="list-panel status-red"><div class="empty-msg">No carts loaded yet.</div></div>
    <div class="list-actions">
      <button id="btnSelectAllPrint">Select All</button>
      <button id="btnUnselectAllPrint">Clear Selection</button>
    </div>
  </div>

  <div class="actions">
    <button id="btnLoadWorkbook">Load Book1-C-DIST.xlsx</button>
    <div id="wbStatus" class="wb-status none">No workbook loaded.</div>
    <input type="file" id="fileInputWorkbook" accept=".xlsx" style="display:none" />
    <button id="btnCheckUpdates" disabled title="Load Book1-C-DIST.xlsx first">Check for Updates</button>
    <div class="section-label">Save / Load / Export</div>
    <button id="btnChooseFolder">Choose Save Folder (This Session)</button>
    <div id="folderStatus" class="wb-status none">No folder selected — files will download to your default Downloads folder.</div>
    <button id="btnSaveCartJson">Save Active Cart (JSON)</button>
    <label class="file-label" for="fileInputCartJson">Load Cart(s) (JSON)</label>
    <input type="file" id="fileInputCartJson" accept=".json" multiple style="display:none" />
    <label class="file-label" for="fileInputCartFolder">Load All from Folder (JSON)</label>
    <input type="file" id="fileInputCartFolder" webkitdirectory directory multiple style="display:none" />
    <button id="btnExportCsv">Export CSV (Checked Carts)</button>
    <button id="btnPrintSelected">Print Selected Carts</button>
    <button id="btnPrintStatusBoard">Print Status Board</button>
  </div>
</div>

<div class="no-print print-all-wrap">
  <button id="btnPrintForms">Print Active Cart Only</button>
</div>

<div class="data-loss-warning no-print">
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M12 9v4M12 17h.01M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
  </svg>
  <span>Your work is not saved automatically. Closing or refreshing this page will lose all cart data. Use "Save Active Cart (JSON)" to export your work before leaving.</span>
</div>

<div class="cart-banner no-print" id="cartBanner"></div>
<div class="legend no-print">
  <span><span class="swatch sw-past"></span>Past due</span>
  <span><span class="swatch sw-soon"></span>Due within 30 days / soonest of the 7 checkoff dates</span>
</div>

<div id="pages"></div>
<div id="statusBoardContainer"></div>
<div id="printBundle" class="print-bundle"></div>
<div id="modalRoot"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
/* ================= NAV STRIP ================= */
const toolbarPanel = document.getElementById('toolbarPanel');
const btnToggleMenu = document.getElementById('btnToggleMenu');
btnToggleMenu.addEventListener('click', () => {
  const isHidden = toolbarPanel.classList.toggle('hidden');
  btnToggleMenu.textContent = isHidden ? 'Show Command Menu' : 'Hide Command Menu';
});

/* ================= NAV QR CODE ================= */
const CRASH_CART_TOOL_URL = 'https://htmlify.me/deweyduck6116/Inventory/CrashCartInvProg.html';

try {
  new QRCode(document.getElementById('navQrCode'), {
    text: CRASH_CART_TOOL_URL, width: 120, height: 120,
    colorDark: '#000000', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.M
  });
} catch (err) { console.warn('QR code generation failed:', err.message); }

try {
  new QRCode(document.getElementById('noCartPlaceholderImg'), {
    text: CRASH_CART_TOOL_URL, width: 144, height: 144,
    colorDark: '#000000', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.M
  });
} catch (err) { console.warn('Placeholder QR code generation failed:', err.message); }

function renderQrModal(){
  const root = document.getElementById('modalRoot');
  root.innerHTML = `
    <div class="modal-overlay">
      <div class="modal-box" style="text-align:center;">
        <h3>Scan to Open This Tool</h3>
        <div class="modal-sub">The nav bar icon is too small for most phone cameras to focus on — use this larger version instead.</div>
        <div id="qrModalCode" style="display:flex; justify-content:center; margin: 12px 0;"></div>
        <div style="font-size:11px; color:#555; word-break:break-all; margin-bottom:14px;">${esc(CRASH_CART_TOOL_URL)}</div>
        <div class="modal-actions" style="justify-content:center;">
          <button id="btnQrModalCopy">Copy Link</button>
          <button class="btn-cancel" id="btnQrModalClose">Close</button>
        </div>
      </div>
    </div>
  `;
  try {
    new QRCode(document.getElementById('qrModalCode'), {
      text: CRASH_CART_TOOL_URL, width: 260, height: 260,
      colorDark: '#000000', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.M
    });
  } catch (err) {
    document.getElementById('qrModalCode').textContent = 'QR code failed to generate.';
  }
  const closeModal = () => { root.innerHTML = ''; root._onEscape = null; };
  root._onEscape = closeModal;
  document.getElementById('btnQrModalClose').addEventListener('click', closeModal);
  document.getElementById('btnQrModalCopy').addEventListener('click', async () => {
    const btn = document.getElementById('btnQrModalCopy');
    try {
      await navigator.clipboard.writeText(CRASH_CART_TOOL_URL);
      btn.textContent = 'Copied!';
      setTimeout(() => { btn.textContent = 'Copy Link'; }, 1500);
    } catch (err) {
      alert('Could not access the clipboard. Link:\n\n' + CRASH_CART_TOOL_URL);
    }
  });
}

document.getElementById('navQrCode').addEventListener('click', renderQrModal);

/* ================= DATE FIELDS ================= */
const now = new Date();
const monthAbbrevs = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
document.getElementById('inpFY').value = now.getFullYear();
document.getElementById('inpMonth').value = monthAbbrevs[now.getMonth()];
document.getElementById('inpDay').value = now.getDate();
const todayFormatted = `${String(now.getMonth()+1).padStart(2,'0')}/${String(now.getDate()).padStart(2,'0')}/${now.getFullYear()}`;
['inpFY','inpMonth','inpDay'].forEach(id => {
  document.getElementById(id).addEventListener('input', () => { if (activeCartUid) renderActiveCart(); });
});

/* ================= SESSION SAVE FOLDER ================= */
let sessionDirHandle = null;
const supportsFSAccess = typeof window.showDirectoryPicker === 'function';

function updateFolderStatus(){
  const el = document.getElementById('folderStatus');
  if (!el) return;
  if (!supportsFSAccess){
    el.className = 'wb-status error';
    el.textContent = 'This browser doesn\'t support folder selection (needs Chrome, Edge, or another Chromium-based browser). Files will download normally.';
  } else if (sessionDirHandle){
    el.className = 'wb-status loaded';
    el.textContent = `Saving to: "${sessionDirHandle.name}" (for this session — pick again after a page reload).`;
  } else {
    el.className = 'wb-status none';
    el.textContent = 'No folder selected — files will download to your default Downloads folder.';
  }
}

async function chooseSaveFolder(){
  if (!supportsFSAccess){
    alert('This browser doesn\'t support the folder-picker feature. Try Chrome or Edge, or continue using regular downloads.');
    return;
  }
  try {
    const handle = await window.showDirectoryPicker({ mode: 'readwrite' });
    sessionDirHandle = handle;
    updateFolderStatus();
  } catch (err){
    if (err.name !== 'AbortError'){
      alert(`Could not select a folder: ${err.message}`);
    }
  }
}

async function verifyFolderPermission(handle){
  const opts = { mode: 'readwrite' };
  try {
    if ((await handle.queryPermission(opts)) === 'granted') return true;
    if ((await handle.requestPermission(opts)) === 'granted') return true;
  } catch (err){
    console.warn('Permission check failed:', err.message);
  }
  return false;
}

async function saveFileSmart(content, filename, mime){
  if (sessionDirHandle){
    try {
      const ok = await verifyFolderPermission(sessionDirHandle);
      if (!ok) throw new Error('Permission to write to the selected folder was denied or revoked.');
      const fileHandle = await sessionDirHandle.getFileHandle(filename, { create: true });
      const writable = await fileHandle.createWritable();
      await writable.write(content);
      await writable.close();
      return { method: 'folder', filename, folder: sessionDirHandle.name };
    } catch (err){
      console.warn(`Direct folder save failed for "${filename}", falling back to a normal download: ${err.message}`);
      downloadBlob(content, filename, mime);
      return { method: 'download-fallback', filename, error: err.message };
    }
  }
  downloadBlob(content, filename, mime);
  return { method: 'download', filename };
}

document.getElementById('btnChooseFolder').addEventListener('click', chooseSaveFolder);
updateFolderStatus();

/* ================= WORKBOOK LOADER ================= */
let loadedWorkbook = null;
const btnLoadWorkbook = document.getElementById('btnLoadWorkbook');
const fileInputWorkbook = document.getElementById('fileInputWorkbook');
const wbStatus = document.getElementById('wbStatus');
btnLoadWorkbook.addEventListener('click', () => fileInputWorkbook.click());
fileInputWorkbook.addEventListener('change', async (e) => {
  const file = e.target.files[0];
  if (!file) return;
  wbStatus.className = 'wb-status';
  wbStatus.textContent = `Reading "${file.name}"...`;
  btnLoadWorkbook.disabled = true;
  try {
    const arrayBuffer = await file.arrayBuffer();
    const workbook = XLSX.read(arrayBuffer, { cellStyles:true, cellFormulas:true, cellDates:true, cellNF:true, sheetStubs:true });
    loadedWorkbook = workbook;
    const summaries = workbook.SheetNames.map(name => {
      const sheet = workbook.Sheets[name];
      const ref = sheet['!ref'];
      let rc = 0;
      if (ref) { const r = XLSX.utils.decode_range(ref); rc = r.e.r - r.s.r + 1; }
      return `  • ${name} (${rc} rows)`;
    }).join('\n');
    wbStatus.className = 'wb-status loaded';
    wbStatus.textContent = `Loaded "${file.name}"\n${summaries}`;
    document.getElementById('btnCheckUpdates').disabled = false;
    document.getElementById('btnCheckUpdates').title = '';
  } catch (err) {
    loadedWorkbook = null;
    wbStatus.className = 'wb-status error';
    wbStatus.textContent = `Failed: ${err.message}`;
    document.getElementById('btnCheckUpdates').disabled = true;
    document.getElementById('btnCheckUpdates').title = 'Load Book1-C-DIST.xlsx first';
  } finally {
    btnLoadWorkbook.disabled = false;
    fileInputWorkbook.value = '';
  }
});

/* ================= DATE PARSING / COLOR LOGIC ================= */
function parseFlexibleDate(raw){
  if (!raw) return null;
  const s = String(raw).trim();
  if (!s) return null;
  let m = s.match(/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2,4})$/);
  if (m){
    let month = parseInt(m[1],10), day = parseInt(m[2],10), year = parseInt(m[3],10);
    if (year < 100) year += 2000;
    if (month>=1 && month<=12 && day>=1 && day<=31) return {year, month, day};
  }
  m = s.match(/^(\d{1,2})[\/\-](\d{2,4})$/);
  if (m){
    let month = parseInt(m[1],10), year = parseInt(m[2],10);
    if (year < 100) year += 2000;
    if (month>=1 && month<=12) return {year, month, day:null};
  }
  return null;
}
function daysUntil(parsed){
  const today = new Date(); today.setHours(0,0,0,0);
  const target = new Date(parsed.year, parsed.month-1, parsed.day || 1); target.setHours(0,0,0,0);
  return Math.round((target - today) / 86400000);
}
function daysSince(dateStr){
  const parsed = parseFlexibleDate(dateStr);
  if (!parsed) return Infinity;
  const today = new Date(); today.setHours(0,0,0,0);
  const target = new Date(parsed.year, parsed.month-1, parsed.day || 1); target.setHours(0,0,0,0);
  return Math.round((today - target) / 86400000);
}
function isStaleVerification(lastVerified){
  if (!lastVerified) return true;
  return daysSince(lastVerified) > 30;
}
function isPlaceholderIfcap(ifcap){
  return /^n[\\/]a$/i.test(String(ifcap || '').trim());
}
function dateColorClass(raw){
  const parsed = parseFlexibleDate(raw);
  if (!parsed) return '';
  const diff = daysUntil(parsed);
  if (diff < 0) return 'date-past';
  if (diff <= 30) return 'date-soon';
  return '';
}
function isItemAutoExpiring(it){
  const cls = dateColorClass(it.exp);
  return cls === 'date-past' || cls === 'date-soon';
}
function isItemCustomPicked(it){
  if (it.customPick === true) return true;
  if (it.customPick === false) return false;
  return isItemAutoExpiring(it);
}
function findEarliestFormatted(rawList){
  let soonestKey = null, label = '';
  rawList.forEach(raw => {
    const parsed = parseFlexibleDate(raw);
    if (parsed){
      const key = parsed.year*12 + parsed.month;
      if (soonestKey === null || key < soonestKey){
        soonestKey = key;
        label = `${String(parsed.month).padStart(2,'0')}/${parsed.year}`;
      }
    }
  });
  return label;
}
function computeEarliestExp(items){
  return findEarliestFormatted(items.map(it => it.exp));
}
function updateStandardDateColors(){
  pagesEl.querySelectorAll('[data-field="exp"], [data-earlyout], [data-cover="suctionMachineDate"], [data-cover="msdOutDate"], [data-checkoff-computed], [data-cover="checkoff6"]').forEach(inp => {
    inp.classList.remove('date-past','date-soon');
    const cls = dateColorClass(inp.value);
    if (cls) inp.classList.add(cls);
  });
}
function updateAllDateColors(){
  updateStandardDateColors();
  updateStaleMsdIndicators();
}
function updateStaleMsdIndicators(){
  pagesEl.querySelectorAll('[data-field="msd"]').forEach(inp => {
    inp.classList.remove('msd-stale');
    const sheet = inp.dataset.sheet, idx = +inp.dataset.idx;
    const cart = carts[activeCartUid];
    if (!cart) return;
    const item = cart.items[sheet][idx];
    if (!item.ifcap) return;
    if (isStaleVerification(item.lastVerified)) inp.classList.add('msd-stale');
  });
}
function recomputeAndSetMsdOut(cart){
  const checkoffSheetMap = ['drawer2','drawer3','drawer4','drawer5','topShelf','sideDrawers'];
  const drawerValues = checkoffSheetMap.map(key => {
    const inp = pagesEl.querySelector(`[data-checkoff-computed="${key}"]`);
    return inp ? inp.value : '';
  });
  const suctionInput = pagesEl.querySelector('[data-cover="checkoff6"]');
  const suctionVal = suctionInput ? suctionInput.value : '';
  const msdOutInput = pagesEl.querySelector('[data-cover="msdOutDate"]');
  if (msdOutInput) msdOutInput.value = findEarliestFormatted([...drawerValues, suctionVal]);
}

/* ================= STATUS BOARD ================= */
const drawerDisplayLabels = { drawer2:'2', drawer3:'3', drawer4:'4', drawer5:'5', topShelf:'TOP', sideDrawers:'Side' };

function computeCartBoardRow(cart){
  const checkoffSheetMap = ['drawer2','drawer3','drawer4','drawer5','topShelf','sideDrawers'];
  const drawerValues = {};
  checkoffSheetMap.forEach(key => { drawerValues[key] = computeEarliestExp(cart.items[key]); });
  const suctionFormatted = findEarliestFormatted([cart.cover.suctionMachineDate]);
  const allValues = [...checkoffSheetMap.map(k => drawerValues[k]), suctionFormatted];
  const dueDate = findEarliestFormatted(allValues);

  let soonestKey = null;
  const keyed = {};
  checkoffSheetMap.forEach(key => {
    const parsed = parseFlexibleDate(drawerValues[key]);
    if (parsed){
      const k = parsed.year*12 + parsed.month;
      keyed[key] = k;
      if (soonestKey === null || k < soonestKey) soonestKey = k;
    }
  });
  const suctionParsed = parseFlexibleDate(suctionFormatted);
  let suctionKey = null;
  if (suctionParsed){
    suctionKey = suctionParsed.year*12 + suctionParsed.month;
    if (soonestKey === null || suctionKey < soonestKey) soonestKey = suctionKey;
  }
  const tiedLabels = [];
  checkoffSheetMap.forEach(key => { if (keyed[key] === soonestKey) tiedLabels.push(drawerDisplayLabels[key]); });
  if (suctionKey === soonestKey && suctionKey !== null) tiedLabels.push('Suct');

  return {
    cartNum: cart.serialNo || '(unset)',
    location: cart.secondaryLocation || '',
    dueDate: dueDate,
    suctionDue: suctionFormatted,
    drawer: tiedLabels.join(' & '),
    room: cart.roomLocation || '',
    poc: cart.supplyTechnician || ''
  };
}

function renderStatusBoard(){
  const container = document.getElementById('statusBoardContainer');
  const uids = Object.keys(carts);
  if (!uids.length){
    container.innerHTML = `<div class="sheet board-sheet" id="page-status-board"><div class="board-empty">No carts loaded yet. The Status Board will populate once carts are created or loaded.</div></div>`;
    return;
  }
  const rows = uids.map(uid => computeCartBoardRow(carts[uid]));
  rows.sort((a,b) => a.cartNum.localeCompare(b.cartNum, undefined, {numeric:true}));

  const MAX_ROWS_PER_PAGE = 25;
  const pages = [];
  for (let i = 0; i < rows.length; i += MAX_ROWS_PER_PAGE){
    pages.push(rows.slice(i, i + MAX_ROWS_PER_PAGE));
  }
  const totalPages = pages.length;

  const pagesHtml = pages.map((pageRows, pageIdx) => {
    const pageNum = pageIdx + 1;
    const isLastPage = pageNum === totalPages;
    const pageId = pageNum === 1 ? 'page-status-board' : `page-status-board-${pageNum}`;

    const rowsHtml = pageRows.map(r => `
      <tr>
        <td>${esc(r.cartNum)}</td>
        <td class="loc">${esc(r.location)}</td>
        <td class="board-due" data-boarddate="${esc(r.dueDate)}">${esc(r.dueDate)}</td>
        <td class="board-suction" data-boarddate="${esc(r.suctionDue)}">${esc(r.suctionDue)}</td>
        <td class="drawer-cell">${esc(r.drawer)}</td>
        <td>${esc(r.room)}</td>
        <td class="tech-cell">${esc(r.poc)}</td>
      </tr>`).join('');

    const legendHtml = isLastPage ? `
      <div class="board-legend">
        <div><span class="swatch" style="background:#f5c2c7;"></span> Expired or Expiring Soon (past due)</div>
        <div><span class="swatch" style="background:#ffe69c;"></span> Caution (due within 30 days)</div>
        <div><span class="swatch" style="background:#fff;"></span> No Issue</div>
      </div>` : '';

    return `
    <div class="sheet board-sheet" id="${pageId}" data-board-page="${pageNum}">
      <div class="board-title-bar">
        <div class="top">CRASH CART DRAWER INVENTORY</div>
        <div class="main">CODE ARREST CARTS CURRENT STATUS</div>
      </div>
      <div class="board-page-indicator">Page ${pageNum} of ${totalPages}</div>
      <table class="board">
        <colgroup>
          <col class="col-cart"><col class="col-loc"><col class="col-due"><col class="col-suction"><col class="col-drawer"><col class="col-room"><col class="col-tech">
        </colgroup>
        <thead><tr><th>CART #</th><th>LOCATION</th><th>DUE DATE</th><th>SUCTION DUE</th><th>DRAWER</th><th>ROOM</th><th>TECH</th></tr></thead>
        <tbody>${rowsHtml}</tbody>
      </table>
      ${legendHtml}
    </div>`;
  }).join('');

  container.innerHTML = pagesHtml;

  container.querySelectorAll('[data-boarddate]').forEach(td => {
    td.classList.remove('date-past','date-soon');
    const cls = dateColorClass(td.dataset.boarddate);
    if (cls) td.classList.add(cls);
  });
}

/* ================= SHEET METADATA + DEFAULT TEMPLATES ================= */
const sheetOrder = ['topShelf','sideDrawers','drawer2','drawer3','drawer4','drawer5'];

const drawerPhotoUrls = {
  drawer2: 'https://htmlify.me/deweyduck6116/Inventory/Drawer2.png',
  drawer3: 'https://htmlify.me/deweyduck6116/Inventory/Drawer3.png',
  drawer4: 'https://htmlify.me/deweyduck6116/Inventory/Drawer4.png',
  drawer5: 'https://htmlify.me/deweyduck6116/Inventory/Drawer5.png',
  sideDrawers: 'https://htmlify.me/deweyduck6116/Inventory/Side.png'
};

const sheetMeta = {
  topShelf: { title:'Top Shelf - Resuscitation Equipment', navLabel:'Top Shelf - Resuscitation Equipment', qtyLabel:'QTY', photo:false, blankRows:0, template:[
    [1,'Ambu bag','N/A','B59D01','98010'],
    [1,'Recording paper','8000-000877-01','B01E02','27104'],
    [2,'Defibilatar','8900-0214-01','B01B02','33996'],
    [1,'Adapter Airway','N/A','B34A03','50168'],
    [2,'Package Electrode','N/A','B01F05','23924'],
    [1,'Suction Unit','N/A','Equipment RM','N/A'],
  ]},
  sideDrawers: { title:'Side Drawers - Breathing\\Support', navLabel:'Side Drawers - Breathing\\Support', qtyLabel:'STOCK LEVEL', photo:true, blankRows:0, template:[
    [1,'Suction Tubing','8888301622','B56B01','177'],
    [1,'Yankuer Suction Tip','K86','B86A07','1972'],
    [2,'Nasal Cannula','1365','B35B04','41595'],
    [2,'Non-Rebreather Mask','154532','B35D01','1627'],
    [5,'Gloves/SM','72-50901','B46B01','32527'],
    [5,'Gloves/MEDIUM','72-50902','B46C01','32528'],
    [5,'Gloves/LARGE','72-50903','B46D01','32529'],
    [5,'GLOVES/XLARGE','72-50904','B46E01','32530'],
    [2,'VENTI/MASK','HUD1940','B61B07','1625'],
  ]},
  drawer2: { title:'DRAWER 2 - IV Supplies', navLabel:'Drawer 2 - IV Supplies', qtyLabel:'STOCK LEVEL', photo:true, blankRows:0, template:[
    [20,'Alcohol Pads','6818','B104A02','9295'],
    [2,'1" Transpost','','B45B05','39021'],
    [4,'IV Start Kits','74464','B44C01','13310'],
    [3,'16 GA IV Cath','6530-01-039-5888','B06B05','19671'],
    [3,'18 GA IV Cath','3065','B06B06','19676'],
    [3,'20 GA IV Cath','3066','B06B07','19677'],
    [3,'22 GA IV Cath','3060','B06B08','19678'],
    [3,'Needle 18 X 1-1/2 Gauge','8881850815','B04A01','22138'],
    [2,'Cath-Stabilization','IV0563P','B84A02','31896'],
    [5,'20 GA x 1.5" Needle','SYR100207','B06A10','9423'],
    [3,'3cc Lure Lock Syringe','','B32A03','9427'],
    [5,'6cc Lure Lock Syringe','SS-05L','B32B01','10934'],
    [5,'10cc Lure Lock Syringe','','B86C01','1994'],
    [1,'60cc Cath Tip Syringe','309620','B86F02','9436'],
    [3,'Primary IV Tubing','2420-0007','B12B01','50617'],
    [3,'Stopcock, 4 - Way','D500','B08D04','14774'],
    [10,'Saline Flush Syringe','306546','B10A02','35486'],
    [1,'Solution, Intravenous, DSW, 250ml, Flex Bag, Ster, Disp','2B0062Q','SOL RM','5010'],
    [2,'Solution, Intravenous, IN 0.9% NACL, 250ml, Flex Bag, Ster.','2B1322Q','SOL RM','5070'],
    [1,'Solution, Intravenous, IN 0.9% NACL, 500ml, Ster.','2B1323Q','SOL RM','5038'],
    [2,'Solution, Intravenous, IN 1000ml, Flex Bag, Ster.','2B1324X','SOL RM','5039'],
    [2,'Solution, Intravenous, LR 1000ml, Flex Bag, Ster.','2B2324X','SOL RM','5042'],
    [2,'Dextrose, Injection, 5% PVC Free, 500ml Bag','L5101','SOL RM','20659'],
  ]},
  drawer3: { title:'DRAWER 3 - Airway', navLabel:'Drawer 3 - Airway', qtyLabel:'STOCK LEVEL', photo:true, blankRows:0, template:[
    [1,'Size 6DCT Trach Tube','6CN75H1','B82D04','2058'],
    [1,'Size 8DCT Trach Tube','8CN85A','B58A04','2059'],
    [2,'CO2 Dector','EASYCAP','B33E03','7722'],
    [1,'Endotracheal Tube 6.0FR','86109','B82B01','1747'],
    [1,'Endotracheal Tube 7.0FR','DYNJ18870','B82B06','35398'],
    [1,'Endotracheal Tube 7.5FR','18875','B82B07','35399'],
    [1,'Endotracheal Tube 8.0FR','','B82B08','35400'],
    [1,'Endotracheal Tube 8.5FR','18885','C101A01','19768'],
    [2,'30cc Slip Tip Syringe','1183500777','B32D01','9434'],
    [1,'McGill Forceps','SS30-2601','A33E05','38897'],
    [1,'Disp. Laryngoscope, MIL3','1033.C','B80E07','35243'],
    [1,'Disp. Laryngoscope, MIL4','','B02C08','35244'],
    [1,'Disp. Laryngoscope, MAC3','1023.C','B80E03','35241'],
    [1,'Disp. Laryngoscope, MAC4','1024.C','B80E05','35242'],
    [1,'Portex Nasopharyngeal','','A37D05','1964'],
    [1,'Oropharyngeal (Berman) 100mm','N/A','B33A02','2086'],
    [2,'Oropharyngeal (Berman) 90mm','N/A','B33A01','2254'],
    [2,'Endotracheal Tube Guide (Bougie)','','B33C06','32148'],
    [2,'Endotracheal Tube Guide (Sylet)','85865','B82E01','1753'],
    [2,'Endotracheal Tube Holders','11010','B33B06','1569'],
    [5,'Surgical Mask w/Face Shield','15330','B26C04','6086'],
    [3,'Kit ABG, 3ml syr dry','','B02E01','50261'],
    [1,'Laryngeal Mask Airway 4 - ANES','8204000','B82C01','20492'],
    [1,'Laryngeal Mask Airway 5 - ANES','','B82C02','20493'],
    [6,'Surgi-Lube Special Order - IV Therapy','281020545A','B36C06','35511'],
    [1,'Laryngoscope Handle (Stubby)','2017.C','B80E01','37033'],
    [1,'Laryngoscop Handle (Medium)','2015.C','B80E02','37035'],
    [1,'Trach Holder','240','B82E02','18827'],
    [1,'Adapter, Airway','','B21B01','33997'],
  ]},
  drawer4: { title:'DRAWER 4 - Airway', navLabel:'Drawer 4 - Airway', qtyLabel:'STOCK LEVEL', photo:true, blankRows:0, template:[
    [1,'14FR Suction Cath Kit','37424','B82E03','9299'],
    [1,'Yankauer Suction Tip','K86','B86A07','1972'],
    [1,'Suction Tubing 1/4" x 12\'','8888301622','B68B01','177'],
    [1,'5 in 1 Connector','501','A36C05','2014'],
    [1,'18 FR Salem Sump Tube','8888266148','B86A03','14528'],
    [2,'Xmas Tree (02)','N/A','B35C01','1624'],
    [1,'Suction Meter','N/A','N/A','N/A'],
    [1,'Suction Liner','N/A','B65A01','32038'],
    [2,'Suction Tubing','9342','B34D03','9414'],
  ]},
  drawer5: { title:'Drawer 5 - Procedure Supplies', navLabel:'Drawer 5 - Procedure Supplies', qtyLabel:'STOCK LEVEL', photo:true, blankRows:0, template:[
    [1,'Triple Lumen Cath Tray 7FR','N/A','B81B02','1958'],
    [2,'Sterile 4 x 4 Gauze','8045','B03C02','434'],
    [3,'Sterile Barrier Towels','3520','A09B01','9625'],
    [2,'Chlorohhexidine','N/A','A36E04','19113'],
    [2,'Sterile Gloves Size 6.5','41165','A35C01','1913'],
    [2,'Sterile Gloves Size 7.0','41170','A28B01','5595'],
    [2,'Sterile Gloves Size 7.5','41175','A28B02','1914'],
    [2,'Sterile Gloves Size 8.0','41180','A35D01','1915'],
    [2,'Sterile Gloves Size 8.5','41185','A35D02','2800'],
    [1,'Stethescope','6515-00-NIB-0115','B43A05','2016'],
    [1,'Bandage Scissors','65945','B15B02','23695'],
    [1,'Wrist Restraints','MDT829020C','B51A05','39218'],
    [1,'C Fuser 50 ml Pressure Bag','DYNJPI500C','A33E03','12478'],
  ]},
};

function esc(v){ return String(v==null?'':v).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

/* ================= CART DATA MODEL ================= */
let cartUidCounter = 0;
const carts = {};
let activeCartUid = null;
const checkedForPrint = new Set();

const dirtyCarts = new Set();
function markDirty(uid){ if (uid) dirtyCarts.add(uid); }
function clearDirty(uid){ dirtyCarts.delete(uid); }
function isDirty(uid){ return !!uid && dirtyCarts.has(uid); }

window.addEventListener('beforeunload', (e) => {
  if (dirtyCarts.size > 0){
    e.preventDefault();
    e.returnValue = '';
    return '';
  }
});

function renderUnsavedChangesModal(cartLabel, onSaveAndContinue, onDiscardAndContinue, onCancel){
  const root = document.getElementById('modalRoot');
  root.innerHTML = `
    <div class="modal-overlay">
      <div class="modal-box">
        <h3>Unsaved Changes</h3>
        <div class="modal-sub">Cart <b>${esc(cartLabel)}</b> has changes that haven't been saved yet. What would you like to do before continuing?</div>
        <div class="modal-actions" style="justify-content:space-between;">
          <button class="btn-cancel" id="btnUnsavedCancel">Cancel</button>
          <div style="display:flex; gap:8px;">
            <button class="btn-discard" id="btnUnsavedDiscard">Discard Changes</button>
            <button class="btn-confirm" id="btnUnsavedSave">Save &amp; Continue</button>
          </div>
        </div>
      </div>
    </div>
  `;
  const cleanup = () => { root.innerHTML = ''; root._onEscape = null; };
  const cancel = () => { cleanup(); onCancel && onCancel(); };
  root._onEscape = cancel;
  document.getElementById('btnUnsavedCancel').addEventListener('click', cancel);
  document.getElementById('btnUnsavedDiscard').addEventListener('click', () => {
    cleanup();
    onDiscardAndContinue && onDiscardAndContinue();
  });
  document.getElementById('btnUnsavedSave').addEventListener('click', async () => {
    cleanup();
    await onSaveAndContinue();
  });
}

function guardLeavingActiveCart(proceedCallback, cancelCallback){
  const uid = activeCartUid;
  if (!isDirty(uid)){
    proceedCallback();
    return;
  }
  const label = (carts[uid] && carts[uid].serialNo) ? carts[uid].serialNo : uid;
  renderUnsavedChangesModal(
    label,
    async () => {
      const saved = await saveActiveCartToFile();
      if (saved) proceedCallback();
      else cancelCallback && cancelCallback();
    },
    () => {
      clearDirty(uid);
      proceedCallback();
    },
    () => { cancelCallback && cancelCallback(); }
  );
}

function makeBlankItem(){ return {qty:'',desc:'',ref:'',msd:'',ifcap:'',exp:'',lastVerified:null,customPick:null}; }

function createNewCart(){
  const numberSel = document.getElementById('selNewCartNumber');
  const chosenNumber = numberSel.value;
  if (!chosenNumber){ alert('No cart numbers available — all 001–100 are in use.'); return; }
  const alreadyUsed = Object.values(carts).some(c => c.serialNo === chosenNumber);
  if (alreadyUsed){ alert(`Cart ${chosenNumber} is already in use.`); return; }

  cartUidCounter++;
  const uid = 'cart_' + cartUidCounter;
  const defaultTech = document.getElementById('inpSupplyTech').value || '';
  const defaultLoc = document.getElementById('inpCaseCartNum').value || '';
  const cart = {
    uid,
    serialNo: chosenNumber,
    supplyTechnician: defaultTech,
    secondaryLocation: defaultLoc,
    roomLocation: document.getElementById('inpRoomLocation').value || '',
    cover: { suctionMachineDate:'' },
    items: {}
  };
  sheetOrder.forEach(key => {
    const meta = sheetMeta[key];
    const items = meta.template.map(([qty,desc,ref,msd,ifcap]) => ({qty,desc,ref,msd,ifcap,exp:'',lastVerified:null,customPick:null}));
    for (let i=0;i<meta.blankRows;i++) items.push(makeBlankItem());
    cart.items[key] = items;
  });
  carts[uid] = cart;
  activeCartUid = uid;
  checkedForPrint.add(uid);
  refreshCartSwitcher();
  refreshPrintChecklist();
  refreshNewCartNumberOptions();
  syncToolbarFromActiveCart();
  renderActiveCart();
}

function deleteActiveCart(){
  if(!activeCartUid || !carts[activeCartUid]) { alert('No active cart to delete.'); return; }
  const label = carts[activeCartUid].serialNo || '(unnamed cart)';
  if(!confirm(`Delete cart "${label}"? This cannot be undone.`)) return;
  clearDirty(activeCartUid);
  delete carts[activeCartUid];
  checkedForPrint.delete(activeCartUid);
  const remaining = Object.keys(carts);
  activeCartUid = remaining.length ? remaining[0] : null;
  refreshCartSwitcher();
  refreshPrintChecklist();
  refreshNewCartNumberOptions();
  syncToolbarFromActiveCart();
  renderActiveCart();
}

function refreshCartSwitcher(){
  const sel = document.getElementById('selCartSwitcher');
  const uids = Object.keys(carts);
  sel.classList.remove('status-red','status-green');
  sel.classList.add(uids.length ? 'status-green' : 'status-red');
  if(!uids.length){ sel.innerHTML = '<option value="">(no carts loaded)</option>'; return; }
  sel.innerHTML = uids.map(uid => {
    const label = carts[uid].serialNo ? esc(carts[uid].serialNo) : `(unnamed – ${uid})`;
    return `<option value="${uid}" ${uid===activeCartUid?'selected':''}>${label}</option>`;
  }).join('');
}

function refreshCartLabel(uid){
  const sel = document.getElementById('selCartSwitcher');
  const opt = sel.querySelector(`option[value="${uid}"]`);
  const label = carts[uid].serialNo ? carts[uid].serialNo : `(unnamed – ${uid})`;
  if(opt) opt.textContent = label;
  const chkLabel = document.querySelector(`#printChecklist span[data-uid-label="${uid}"]`);
  if(chkLabel) chkLabel.textContent = label;
  updateCartBanner();
}

function syncToolbarFromActiveCart(){
  const cart = carts[activeCartUid];
  const techInput = document.getElementById('inpSupplyTech');
  const locInput = document.getElementById('inpCaseCartNum');
  if (cart){
    techInput.value = cart.supplyTechnician || '';
    locInput.value = cart.secondaryLocation || '';
    document.getElementById('inpRoomLocation').value = cart.roomLocation || '';
  } else {
    techInput.value = '';
    locInput.value = '';
    document.getElementById('inpRoomLocation').value = '';
  }
}

function refreshPrintChecklist(){
  const panel = document.getElementById('printChecklist');
  const uids = Object.keys(carts);
  panel.classList.remove('status-red','status-green');
  panel.classList.add(uids.length ? 'status-green' : 'status-red');
  if(!uids.length){ panel.innerHTML = '<div class="empty-msg">No carts loaded yet.</div>'; return; }
  panel.innerHTML = uids.map(uid => {
    const label = carts[uid].serialNo ? esc(carts[uid].serialNo) : `(unnamed – ${uid})`;
    const checked = checkedForPrint.has(uid);
    return `<label class="chk"><input type="checkbox" data-uid="${uid}" ${checked?'checked':''}><span data-uid-label="${uid}">${label}</span></label>`;
  }).join('');
}

function updateCartBanner(){
  const banner = document.getElementById('cartBanner');
  const placeholderImg = document.getElementById('noCartPlaceholderImg');
  if (placeholderImg) placeholderImg.style.display = Object.keys(carts).length === 0 ? 'block' : 'none';
  if(!activeCartUid || !carts[activeCartUid]){
    banner.classList.remove('dirty');
    banner.textContent = 'No active cart.';
    return;
  }
  const c = carts[activeCartUid];
  const dirty = isDirty(activeCartUid);
  banner.classList.toggle('dirty', dirty);
  banner.textContent = `Editing Cart: ${c.serialNo || '(no serial number entered yet)'}${dirty ? '  •  Unsaved changes' : ''}`;
}

function refreshNewCartNumberOptions(){
  const sel = document.getElementById('selNewCartNumber');
  const usedNumbers = new Set(Object.values(carts).map(c => c.serialNo).filter(Boolean));
  const prevValue = sel.value;
  const options = [];
  for (let i = 1; i <= 100; i++){
    const num = String(i).padStart(3, '0');
    const inUse = usedNumbers.has(num);
    options.push(`<option value="${num}" ${inUse ? 'disabled' : ''}>${num}${inUse ? ' (in use)' : ''}</option>`);
  }
  sel.innerHTML = options.join('');
  if (prevValue && !usedNumbers.has(prevValue)){
    sel.value = prevValue;
  } else {
    const firstFree = sel.querySelector('option:not([disabled])');
    if (firstFree) sel.value = firstFree.value;
  }
}

document.getElementById('btnNewCart').addEventListener('click', () => {
  guardLeavingActiveCart(createNewCart, () => {});
});
document.getElementById('btnDeleteCart').addEventListener('click', deleteActiveCart);
document.getElementById('inpSupplyTech').addEventListener('input', (e) => {
  const cart = carts[activeCartUid];
  if (!cart) return;
  cart.supplyTechnician = e.target.value;
  markDirty(cart.uid);
  renderActiveCart();
});
document.getElementById('inpCaseCartNum').addEventListener('input', (e) => {
  const cart = carts[activeCartUid];
  if (!cart) return;
  cart.secondaryLocation = e.target.value;
  markDirty(cart.uid);
  renderActiveCart();
});
document.getElementById('inpRoomLocation').addEventListener('input', (e) => {
  const cart = carts[activeCartUid];
  if (!cart) return;
  cart.roomLocation = e.target.value;
  markDirty(cart.uid);
  renderStatusBoard();
  updateCartBanner();
});
document.getElementById('chkLockFields').addEventListener('change', () => {
  if (activeCartUid) renderActiveCart();
});
document.getElementById('chkDesktopLayout').addEventListener('change', (e) => {
  toolbarPanel.classList.toggle('mobile-friendly', !e.target.checked);
});
document.getElementById('chkHideEmergencyList').addEventListener('change', () => {
  if (activeCartUid) renderActiveCart();
  else if (typeof updateJumpMenuPickListState === 'function') updateJumpMenuPickListState();
});
document.getElementById('chkHideEmergencyAutoGenBoxes').addEventListener('change', () => {
  if (activeCartUid) renderActiveCart();
  else if (typeof updateJumpMenuPickListState === 'function') updateJumpMenuPickListState();
});
document.getElementById('selCartSwitcher').addEventListener('change', (e) => {
  const sel = e.target;
  const newUid = sel.value || null;
  const previousUid = activeCartUid;
  if (newUid === previousUid) return;
  guardLeavingActiveCart(
    () => {
      activeCartUid = newUid;
      syncToolbarFromActiveCart();
      renderActiveCart();
    },
    () => {
      sel.value = previousUid || '';
    }
  );
});
document.getElementById('printChecklist').addEventListener('change', (e) => {
  if(e.target.matches('input[type=checkbox]')){
    const uid = e.target.dataset.uid;
    if(e.target.checked) checkedForPrint.add(uid); else checkedForPrint.delete(uid);
  }
});
document.getElementById('btnSelectAllPrint').addEventListener('click', () => {
  document.querySelectorAll('#printChecklist input[type=checkbox]').forEach(b => { b.checked = true; checkedForPrint.add(b.dataset.uid); });
});
document.getElementById('btnUnselectAllPrint').addEventListener('click', () => {
  document.querySelectorAll('#printChecklist input[type=checkbox]').forEach(b => { b.checked = false; checkedForPrint.delete(b.dataset.uid); });
});

/* ================= RENDERING ================= */
function handleDrawerPhotoError(imgEl){
  const title = imgEl.dataset.title || '';
  const wrap = imgEl.closest('.drawer-photo');
  if (!wrap) return;
  wrap.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10.5" r="1.5"/><path d="M21 15l-5-5-4 4-3-3-6 6"/></svg><span>Photo unavailable — ${esc(title)}</span>`;
}

function photoPlaceholder(key, title){
  const imageUrl = drawerPhotoUrls[key] || '';
  if (imageUrl){
    return `<div class="drawer-photo-wrap">
      <div class="drawer-photo">
        <img src="${esc(imageUrl)}" alt="${esc(title)}" data-title="${esc(title)}"
          onerror="handleDrawerPhotoError(this)">
      </div>
    </div>`;
  }
  return `<div class="drawer-photo-wrap">
    <div class="drawer-photo">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
        <rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10.5" r="1.5"/><path d="M21 15l-5-5-4 4-3-3-6 6"/>
      </svg>
      <span>Photo placeholder — ${esc(title)}</span>
    </div>
  </div>`;
}

function getCommandMonthDayYear(){
  return {
    month: document.getElementById('inpMonth').value || '',
    day: document.getElementById('inpDay').value || '',
    year: document.getElementById('inpFY').value || ''
  };
}

function renderCoverSheetHTML(cart, idAttr){
  const { month, day, year } = getCommandMonthDayYear();
  const codeCartNum = cart.secondaryLocation ? `Cart ${cart.serialNo || ''} in ${cart.secondaryLocation}` : (cart.serialNo ? `Cart ${cart.serialNo}` : '');
  const supplyTech = cart.supplyTechnician || '';
  const dateStr = (month || day || year) ? `${month} ${day}, ${year}`.trim() : '';
  const checkoffSheetMap = ['drawer2','drawer3','drawer4','drawer5','topShelf','sideDrawers'];
  const drawerValues = checkoffSheetMap.map(key => computeEarliestExp(cart.items[key]));
  const suctionFormatted = findEarliestFormatted([cart.cover.suctionMachineDate]);
  const msdOutComputed = findEarliestFormatted([...drawerValues, suctionFormatted]);
  const checkoffCells = checkoffSheetMap.map((key,i) =>
    `<td><input type="text" readonly tabindex="-1" class="auto-filled" data-checkoff-computed="${key}" value="${esc(drawerValues[i])}"></td>`
  ).join('') + `<td><input type="text" readonly tabindex="-1" class="auto-filled" data-cover="checkoff6" value="${esc(suctionFormatted)}"></td>`;
  return `<div class="sheet" ${idAttr||''}>
    <div class="cover-box">
      <div class="cover-row cover-header">
        CODE CART <input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(month)}"> / <input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(day)}"> / <input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(year)}">
      </div>
      <div class="cover-row">
        <div class="cover-label">CODE CART #</div>
        <div class="cover-blank"><input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(codeCartNum)}"></div>
      </div>
      <div class="cover-row">
        <div class="cover-label">SUCTION MACHINE DATE:</div>
        <div class="cover-blank small"><textarea data-cover="suctionMachineDate">${esc(cart.cover.suctionMachineDate)}</textarea></div>
      </div>
      <div class="cover-row">
        <div class="cover-label">MSD -OUT DATE:</div>
        <div class="cover-blank small"><input type="text" readonly tabindex="-1" class="auto-filled" data-cover="msdOutDate" value="${esc(msdOutComputed)}"></div>
      </div>
      <div class="cover-row">
        <div class="supply-row">
          <div class="field"><label>SUPPLY TECH:</label><input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(supplyTech)}"></div>
          <div class="field"><label>DATE:</label><input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(dateStr)}"></div>
        </div>
      </div>
      <div class="cover-row" style="padding:0;">
        <table class="checkoff">
          <thead><tr><th>DRAWER 2</th><th>DRAWER 3</th><th>DRAWER 4</th><th>DRAWER 5</th><th>TOP</th><th>SIDE</th><th>SUCTION MACHINE</th></tr></thead>
          <tbody><tr>${checkoffCells}</tr></tbody>
        </table>
      </div>
    </div>
  </div>`;
}

function renderInventorySheetHTML(key, cart, idAttr){
  const meta = sheetMeta[key];
  const items = cart.items[key];
  const locked = document.getElementById('chkLockFields').checked;
  const lockAttr = locked ? 'readonly tabindex="-1" class="locked-field"' : '';
  const showPickBoxes = !document.getElementById('chkHideEmergencyAutoGenBoxes').checked;
  const pickColGroup = showPickBoxes ? '<col style="width:5%">' : '';
  const pickHeaderCell = showPickBoxes ? '<th class="no-print">Pick</th>' : '';
  const rows = items.map((it, idx) => {
    let pickCell = '';
    if (showPickBoxes){
      const isChecked = isItemCustomPicked(it) ? 'checked' : '';
      pickCell = '<td class="no-print" style="text-align:center;"><input type="checkbox" class="custom-pick-cb" data-sheet="' + key + '" data-idx="' + idx + '" ' + isChecked + '></td>';
    }
    return `
    <tr>
      <td><input data-sheet="${key}" data-idx="${idx}" data-field="qty" value="${esc(it.qty)}" ${lockAttr}></td>
      <td class="desc"><input data-sheet="${key}" data-idx="${idx}" data-field="desc" value="${esc(it.desc)}" ${lockAttr}></td>
      <td><input data-sheet="${key}" data-idx="${idx}" data-field="ref" value="${esc(it.ref)}" ${lockAttr}></td>
      <td><input data-sheet="${key}" data-idx="${idx}" data-field="msd" value="${esc(it.msd)}" ${lockAttr}></td>
      <td><input data-sheet="${key}" data-idx="${idx}" data-field="ifcap" value="${esc(it.ifcap)}" ${lockAttr}></td>
      <td><input data-sheet="${key}" data-idx="${idx}" data-field="exp" value="${esc(it.exp)}"></td>
      ${pickCell}
    </tr>`;
  }).join('');

  return `<div class="sheet" ${idAttr||''}>
    <div class="inv-title-bar">
      <div class="top">CRASH CART DRAWER INVENTORY</div>
      <div class="main">${esc(meta.title)}</div>
    </div>
    <div class="inv-meta">
      <div><label>CART SERIAL NO.</label><input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(cart.serialNo)}"></div>
      <div><label>COMPLETION DATE:</label><input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(todayFormatted)}"></div>
      <div><label>Supply Technician:</label><input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(cart.supplyTechnician)}"></div>
      <div><label>EARLY OUT DATE (M/Y):</label><input type="text" readonly tabindex="-1" class="auto-filled" data-earlyout="${key}" value="${esc(computeEarliestExp(items))}"></div>
      <div style="grid-column: 1 / -1;"><label>Secondary Location:</label><input type="text" readonly tabindex="-1" class="auto-filled" value="${esc(cart.secondaryLocation)}"></div>
    </div>
    <table class="inv">
      <colgroup><col class="qty"><col class="desc"><col class="ref"><col class="msd"><col class="ifcap"><col class="exp">${pickColGroup}</colgroup>
      <thead><tr><th>${esc(meta.qtyLabel)}</th><th>ITEM DESCRIPTION</th><th>REF NO</th><th>MSD LOCATION</th><th>IFCAP</th><th>EXPIRATION (MO/YR)</th>${pickHeaderCell}</tr></thead>
      <tbody>${rows}</tbody>
    </table>
    <div class="row-actions no-print">
      <button class="btnAddRow" data-sheet="${key}">+ Add Row</button>
      <button class="btnRemoveRow remove" data-sheet="${key}">− Remove Row</button>
    </div>
    ${meta.photo ? photoPlaceholder(key, meta.title) : ''}
  </div>`;
}

/* Maps a drawer/sheet key to the row-color class used only on the emergency pick lists.
   Airway = blue, IV Supplies = yellow, Procedure Supplies = green, Resuscitation
   Equipment = gray, Breathing/Support (Side Drawers: O2 delivery, suction, gloves) = purple. */
function pickListRowColorClass(sheetKey){
  if (sheetKey === 'drawer2') return 'picklist-row-iv';
  if (sheetKey === 'drawer3' || sheetKey === 'drawer4') return 'picklist-row-airway';
  if (sheetKey === 'sideDrawers') return 'picklist-row-breathing';
  if (sheetKey === 'drawer5') return 'picklist-row-procedure';
  if (sheetKey === 'topShelf') return 'picklist-row-equipment';
  return '';
}

/* Gathers every non-blank item across all six drawer/shelf sheets for one cart, optionally
   filtered, sorted by MSD Location ascending (alphanumeric, "smallest to largest"). Shared
   by both the general Emergency Pick List and the per-item Custom Emergency Pick Sheet. */
function computeItemRowsForList(cart, filterFn){
  const rows = [];
  sheetOrder.forEach(key => {
    const meta = sheetMeta[key];
    (cart.items[key] || []).forEach(it => {
      if (!it.desc && !it.qty && !it.ref) return;
      if (filterFn && !filterFn(it)) return;
      rows.push({
        sheetKey: key,
        drawer: meta.navLabel,
        msd: it.msd || '',
        desc: it.desc || '',
        qty: it.qty,
        ref: it.ref || '',
        ifcap: it.ifcap || ''
      });
    });
  });
  rows.sort((a, b) => {
    const am = a.msd ? a.msd : '\uffff';
    const bm = b.msd ? b.msd : '\uffff';
    return am.localeCompare(bm, undefined, { numeric: true, sensitivity: 'base' });
  });
  return rows;
}
function computeEmergencyPickListRows(cart){
  return computeItemRowsForList(cart, null);
}
function computeCustomPickListRows(cart){
  return computeItemRowsForList(cart, isItemCustomPicked);
}

const EMERGENCY_LIST_ROWS_PER_PAGE = 45;

/* Shared renderer for both plain spreadsheet-style pick lists — no cover box or form
   styling, just a heading and a table. idPrefix controls whether page ids are added:
   pass an id for the live single-cart view (so Jump-to can find it), or null when
   bundling multiple carts for "Print Selected Carts" to avoid duplicate ids. */
function renderPickListPagesHTML(rows, idPrefix, headingText, subLabelBase){
  const legendHtml = `
    <div class="picklist-legend">
      <div><span class="swatch" style="background:#cfe2ff;"></span> Airway</div>
      <div><span class="swatch" style="background:#fff3cd;"></span> IV Supplies</div>
      <div><span class="swatch" style="background:#e0cffc;"></span> Breathing\\Support</div>
      <div><span class="swatch" style="background:#d1e7dd;"></span> Procedure Supplies</div>
      <div><span class="swatch" style="background:#e2e3e5;"></span> Resuscitation Equipment</div>
    </div>`;

  if (!rows.length){
    const idAttr = idPrefix ? ` id="${idPrefix}"` : '';
    return `<div class="sheet"${idAttr}>
      <div class="picklist-heading">${esc(headingText)}</div>
      <div class="picklist-sub">${subLabelBase}</div>
      <div class="board-empty">No items to list.</div>
    </div>`;
  }

  const pages = [];
  for (let i = 0; i < rows.length; i += EMERGENCY_LIST_ROWS_PER_PAGE){
    pages.push(rows.slice(i, i + EMERGENCY_LIST_ROWS_PER_PAGE));
  }
  const totalPages = pages.length;

  return pages.map((pageRows, idx) => {
    const pageNum = idx + 1;
    const isLastPage = pageNum === totalPages;
    const idAttr = idPrefix ? ` id="${pageNum === 1 ? idPrefix : idPrefix + '-' + pageNum}"` : '';
    const rowsHtml = pageRows.map(r => `
      <tr class="${pickListRowColorClass(r.sheetKey)}">
        <td>${esc(r.msd)}</td>
        <td>${esc(r.drawer)}</td>
        <td class="desc">${esc(r.desc)}</td>
        <td>${esc(r.qty)}</td>
        <td>${esc(r.ref)}</td>
        <td>${esc(r.ifcap)}</td>
      </tr>`).join('');
    return `<div class="sheet"${idAttr}>
      <div class="picklist-heading">${esc(headingText)}</div>
      <div class="picklist-sub">${subLabelBase}${totalPages > 1 ? ` — Page ${pageNum} of ${totalPages}` : ''}</div>
      <table class="picklist">
        <thead><tr><th>MSD LOCATION</th><th>DRAWER</th><th>ITEM DESCRIPTION</th><th>QTY</th><th>REF NO</th><th>IFCAP</th></tr></thead>
        <tbody>${rowsHtml}</tbody>
      </table>
      ${isLastPage ? legendHtml : ''}
    </div>`;
  }).join('');
}

function renderEmergencyPickListHTML(cart, idPrefix){
  const rows = computeEmergencyPickListRows(cart);
  const subLabel = `Cart ${esc(cart.serialNo || '(unset)')} — sorted by MSD Location, smallest to largest`;
  return renderPickListPagesHTML(rows, idPrefix, 'EMERGENCY / UNOFFICIAL PICK LIST', subLabel);
}

function renderCustomPickSheetHTML(cart, idPrefix){
  const rows = computeCustomPickListRows(cart);
  const subLabel = `Cart ${esc(cart.serialNo || '(unset)')} — items selected via drawer checkboxes, sorted by MSD Location, smallest to largest`;
  return renderPickListPagesHTML(rows, idPrefix, 'CUSTOM EMERGENCY PICK SHEET', subLabel);
}

const pagesEl = document.getElementById('pages');

function renderActiveCart(){
  pagesEl.innerHTML = '';
  updateCartBanner();
  const cart = carts[activeCartUid];
  if(!cart){
    pagesEl.innerHTML = `<div class="empty-state">No carts loaded. Click "Show Command Menu" above, then "+ New Cart" or "Load Cart(s) (JSON)" to get started.</div>`;
    renderStatusBoard();
    updateJumpMenuPickListState();
    return;
  }
  pagesEl.insertAdjacentHTML('beforeend', renderCoverSheetHTML(cart, 'id="page-0"'));
  sheetOrder.forEach((key, i) => {
    pagesEl.insertAdjacentHTML('beforeend', renderInventorySheetHTML(key, cart, `id="page-${i+1}"`));
  });
  if (!document.getElementById('chkHideEmergencyList').checked){
    pagesEl.insertAdjacentHTML('beforeend', renderEmergencyPickListHTML(cart, 'page-picklist'));
  }
  if (!document.getElementById('chkHideEmergencyAutoGenBoxes').checked){
    pagesEl.insertAdjacentHTML('beforeend', renderCustomPickSheetHTML(cart, 'page-custompicklist'));
  }
  updateAllDateColors();
  renderStatusBoard();
  updateJumpMenuPickListState();
}

pagesEl.addEventListener('input', (e) => {
  const t = e.target;
  const cart = carts[activeCartUid];
  if(!cart) return;
  markDirty(cart.uid);
  if (t.dataset.sheet && t.dataset.field){
    cart.items[t.dataset.sheet][+t.dataset.idx][t.dataset.field] = t.value;
    if (t.dataset.field === 'exp'){
      const earliest = computeEarliestExp(cart.items[t.dataset.sheet]);
      const earlyOutInput = pagesEl.querySelector(`[data-earlyout="${t.dataset.sheet}"]`);
      if (earlyOutInput) earlyOutInput.value = earliest;
      const checkoffInput = pagesEl.querySelector(`[data-checkoff-computed="${t.dataset.sheet}"]`);
      if (checkoffInput) checkoffInput.value = earliest;
      recomputeAndSetMsdOut(cart);
      const editedItem = cart.items[t.dataset.sheet][+t.dataset.idx];
      if (editedItem.customPick == null){
        const pickCb = pagesEl.querySelector(`.custom-pick-cb[data-sheet="${t.dataset.sheet}"][data-idx="${t.dataset.idx}"]`);
        if (pickCb) pickCb.checked = isItemAutoExpiring(editedItem);
      }
    }
  } else if (t.dataset.shared){
    cart[t.dataset.shared] = t.value;
    pagesEl.querySelectorAll(`[data-shared="${t.dataset.shared}"]`).forEach(el => { if (el !== t) el.value = t.value; });
    if (t.dataset.shared === 'serialNo') refreshCartLabel(cart.uid);
    if (t.dataset.shared === 'supplyTechnician') {
      const coverInput = pagesEl.querySelector('.cover-box .supply-row .field input.auto-filled');
      if (coverInput) coverInput.value = t.value;
    }
    if (t.dataset.shared === 'serialNo' || t.dataset.shared === 'secondaryLocation') {
      const codeCartInput = pagesEl.querySelector('.cover-box .cover-blank input.auto-filled');
      if (codeCartInput) {
        codeCartInput.value = cart.secondaryLocation ? `Cart ${cart.serialNo || ''} in ${cart.secondaryLocation}` : (cart.serialNo ? `Cart ${cart.serialNo}` : '');
      }
    }
  } else if (t.dataset.cover){
    const key = t.dataset.cover;
    cart.cover[key] = t.value;
    if (key === 'suctionMachineDate'){
      const suctionFormatted = findEarliestFormatted([t.value]);
      const checkoffSuctionInput = pagesEl.querySelector('[data-cover="checkoff6"]');
      if (checkoffSuctionInput) checkoffSuctionInput.value = suctionFormatted;
    }
    recomputeAndSetMsdOut(cart);
  }
  updateAllDateColors();
  renderStatusBoard();
  updateCartBanner();
});

pagesEl.addEventListener('change', (e) => {
  const cb = e.target.closest('.custom-pick-cb');
  if (!cb) return;
  const cart = carts[activeCartUid];
  if(!cart) return;
  const sheet = cb.dataset.sheet, idx = +cb.dataset.idx;
  if (!cart.items[sheet] || !cart.items[sheet][idx]) return;
  cart.items[sheet][idx].customPick = cb.checked;
  markDirty(cart.uid);
  renderActiveCart();
});

pagesEl.addEventListener('click', (e) => {
  const addBtn = e.target.closest('.btnAddRow');
  const remBtn = e.target.closest('.btnRemoveRow');
  const cart = carts[activeCartUid];
  if(!cart) return;
  if (addBtn){
    markDirty(cart.uid);
    cart.items[addBtn.dataset.sheet].push(makeBlankItem());
    renderActiveCart();
  } else if (remBtn){
    const arr = cart.items[remBtn.dataset.sheet];
    if (arr.length > 0){
      markDirty(cart.uid);
      arr.pop();
    }
    renderActiveCart();
  }
});

/* ================= JUMP-TO MENU ================= */
const selJumpPage = document.getElementById('selJumpPage');
const jumpOptions = [['page-0','Code Cart Cover'], ...sheetOrder.map((k,i)=>[`page-${i+1}`, sheetMeta[k].navLabel]), ['page-picklist','Emergency Pick List'], ['page-custompicklist','Custom Emergency Pick Sheet'], ['page-status-board','Cart Status Board (All Carts)']];
selJumpPage.innerHTML = jumpOptions.map(([id,label]) => `<option value="${id}">${esc(label)}</option>`).join('');
function updateJumpMenuPickListState(){
  const opt = selJumpPage.querySelector('option[value="page-picklist"]');
  if (opt) opt.disabled = document.getElementById('chkHideEmergencyList').checked;
  const optCustom = selJumpPage.querySelector('option[value="page-custompicklist"]');
  if (optCustom) optCustom.disabled = document.getElementById('chkHideEmergencyAutoGenBoxes').checked;
}
selJumpPage.addEventListener('change', () => {
  const target = document.getElementById(selJumpPage.value);
  if (!target) return;
  const navH = 42;
  const toolbarH = toolbarPanel.classList.contains('hidden') ? 0 : toolbarPanel.getBoundingClientRect().height;
  const bannerH = document.getElementById('cartBanner').getBoundingClientRect().height;
  const targetTop = target.getBoundingClientRect().top + window.pageYOffset - navH - toolbarH - bannerH - 20;
  window.scrollTo({ top: targetTop, behavior: 'smooth' });
});

/* ================= DOWNLOAD HELPER ================= */
function downloadBlob(content, filename, mime){
  const blob = new Blob([content], {type: mime});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = filename;
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function csvField(v){
  v = (v===undefined||v===null) ? '' : String(v);
  if (/[",\n]/.test(v)) v = '"' + v.replace(/"/g,'""') + '"';
  return v;
}

/* ================= PRINT: FIT EACH SHEET TO ONE PAGE, NO TRAILING BLANK PAGE ================= */
const PX_PER_INCH = 96;
const PAGE_HEIGHT_IN = 11 - 0.2 - 0.2;
const AVAILABLE_PAGE_HEIGHT_PX = PAGE_HEIGHT_IN * PX_PER_INCH;

function waitForPrintImages(container){
  const images = [...container.querySelectorAll('.drawer-photo img')];
  if (!images.length) return Promise.resolve();
  return Promise.all(images.map(img => {
    if (img.complete && img.naturalWidth > 0) return Promise.resolve();
    return new Promise(resolve => {
      const done = () => resolve();
      img.addEventListener('load', done, { once:true });
      img.addEventListener('error', done, { once:true });
    });
  }));
}

function prepareSheetsForPrint(container){
  const sheets = [...container.querySelectorAll('.sheet')];
  sheets.forEach(sheet => {
    const wrap = document.createElement('div');
    wrap.className = 'print-scale-wrap';
    sheet.parentNode.insertBefore(wrap, sheet);
    wrap.appendChild(sheet);

    sheet.style.transform = 'none';
    sheet.style.width = '';
    wrap.style.height = '';
    wrap.style.width = '';

    const naturalHeight = sheet.offsetHeight;
    const naturalWidth = sheet.offsetWidth;
    const scale = Math.min(1, AVAILABLE_PAGE_HEIGHT_PX / naturalHeight);

    if (scale < 1){
      sheet.style.transformOrigin = 'top left';
      sheet.style.transform = `scale(${scale})`;
      sheet.style.width = `${100 / scale}%`;
    }

    wrap.style.height = `${Math.ceil(naturalHeight * scale)}px`;
    wrap.style.width = `${Math.ceil(naturalWidth * scale)}px`;
  });
}

function cleanupSheetsAfterPrint(container){
  container.querySelectorAll('.print-scale-wrap').forEach(wrap => {
    const sheet = wrap.querySelector('.sheet');
    if (sheet){
      sheet.style.transform = '';
      sheet.style.transformOrigin = '';
      sheet.style.width = '';
      wrap.style.height = '';
      wrap.style.width = '';
      wrap.parentNode.insertBefore(sheet, wrap);
    }
    wrap.remove();
  });
}

/* ================= SAVE / LOAD / EXPORT / PRINT ================= */
async function saveActiveCartToFile(){
  const cart = carts[activeCartUid];
  if(!cart){ alert('No active cart to save.'); return false; }
  const safeName = (cart.serialNo || cart.uid).replace(/[^a-zA-Z0-9_-]/g, '_');
  const result = await saveFileSmart(JSON.stringify(cart, null, 2), `cart-${safeName}.json`, 'application/json');

  const rememberedCount = Object.keys(rememberedDuplicateChoices).length;
  if (rememberedCount > 0){
    const payload = {
      version: 1,
      exportedOn: todayFormatted,
      choices: rememberedDuplicateChoices
    };
    await saveFileSmart(JSON.stringify(payload, null, 2), 'LastUpdate.json', 'application/json');
  }

  if (result.method === 'folder'){
    console.log(`Saved cart-${safeName}.json directly to "${result.folder}".`);
  }
  clearDirty(cart.uid);
  updateCartBanner();
  return true;
}

document.getElementById('btnSaveCartJson').addEventListener('click', () => { saveActiveCartToFile(); });

document.getElementById('fileInputCartJson').addEventListener('change', async (e) => {
  const files = [...e.target.files];
  e.target.value = '';
  if (!files.length) return;
  guardLeavingActiveCart(
    () => { loadCartJsonFiles(files); },
    () => {}
  );
});

document.getElementById('fileInputCartFolder').addEventListener('change', async (e) => {
  const jsonFiles = [...e.target.files].filter(f => f.name.toLowerCase().endsWith('.json'));
  e.target.value = '';
  if (!jsonFiles.length){ alert('No .json files were found in that folder.'); return; }
  guardLeavingActiveCart(
    () => { loadCartJsonFiles(jsonFiles); },
    () => {}
  );
});

function findExistingCartUidBySerial(serialNo){
  if (!serialNo) return null;
  const found = Object.entries(carts).find(([, c]) => c.serialNo === serialNo);
  return found ? found[0] : null;
}

function renderCartConflictModal(serialNo, existingCart, incomingData, fileName){
  return new Promise((resolve) => {
    const root = document.getElementById('modalRoot');
    const hasUnsaved = isDirty(existingCart.uid);
    const infoRow = (label, val) => `<div><span style="color:#666;">${esc(label)}:</span> ${esc(val || '—')}</div>`;
    root.innerHTML = `
      <div class="modal-overlay">
        <div class="modal-box">
          <h3>Cart ${esc(serialNo)} Is Already Loaded</h3>
          <div class="modal-sub">A cart with this number is already open in this session. Choose which version to keep — the other will be discarded. This choice only affects cart ${esc(serialNo)}; the rest of your import will continue either way.</div>
          <div style="display:flex; gap:10px; margin-bottom:16px;">
            <div style="flex:1; border:1px solid #ddd; border-radius:6px; padding:10px; font-size:12px; line-height:1.6;">
              <div style="font-weight:700; margin-bottom:4px;">Currently in Memory</div>
              ${infoRow('Supply Tech', existingCart.supplyTechnician)}
              ${infoRow('Secondary Location', existingCart.secondaryLocation)}
              ${infoRow('Room', existingCart.roomLocation)}
              ${hasUnsaved ? '<div style="color:#dc3545; font-weight:700; margin-top:4px;">Has unsaved changes</div>' : ''}
            </div>
            <div style="flex:1; border:1px solid #ddd; border-radius:6px; padding:10px; font-size:12px; line-height:1.6;">
              <div style="font-weight:700; margin-bottom:4px;">Importing: ${esc(fileName)}</div>
              ${infoRow('Supply Tech', incomingData.supplyTechnician)}
              ${infoRow('Secondary Location', incomingData.secondaryLocation)}
              ${infoRow('Room', incomingData.roomLocation)}
            </div>
          </div>
          <div class="modal-actions" style="justify-content:space-between;">
            <button class="btn-cancel" id="btnConflictKeepMemory">Keep Current (In-Memory)</button>
            <button class="btn-confirm" id="btnConflictUseImported">Use Imported File</button>
          </div>
        </div>
      </div>
    `;
    const cleanup = () => { root.innerHTML = ''; root._onEscape = null; };
    root._onEscape = () => { cleanup(); resolve('memory'); };
    document.getElementById('btnConflictKeepMemory').addEventListener('click', () => { cleanup(); resolve('memory'); });
    document.getElementById('btnConflictUseImported').addEventListener('click', () => { cleanup(); resolve('imported'); });
  });
}

async function loadCartJsonFiles(files){
  let loadedCount = 0, overwrittenCount = 0, keptMemoryCount = 0, restoredChoicesCount = 0;

  const lastUpdateFiles = files.filter(f => f.name.toLowerCase() === 'lastupdate.json');
  const cartFiles = files.filter(f => f.name.toLowerCase() !== 'lastupdate.json');

  const parsedCarts = [];
  const parseFailures = [];
  for (const file of cartFiles){
    try {
      const text = await file.text();
      const data = JSON.parse(text);
      if (!data || !data.items) throw new Error('missing items');
      parsedCarts.push({ fileName: file.name, data });
    } catch (err){
      parseFailures.push(file.name);
      console.warn(`Failed to load "${file.name}": ${err.message}`);
    }
  }

  for (const file of lastUpdateFiles){
    try {
      const text = await file.text();
      const data = JSON.parse(text);
      if (data && data.choices){
        Object.entries(data.choices).forEach(([ifcap, entry]) => {
          if (entry && entry.decidedOn && daysSince(entry.decidedOn) <= 30){
            rememberedDuplicateChoices[ifcap] = entry;
            restoredChoicesCount++;
          }
        });
      }
    } catch (err){
      console.warn(`Failed to read LastUpdate.json: ${err.message}`);
    }
  }

  const serialToUid = new Map();
  Object.entries(carts).forEach(([uid, c]) => { if (c.serialNo) serialToUid.set(c.serialNo, uid); });

  for (const pc of parsedCarts){
    const data = pc.data;
    if (data.roomLocation === undefined) data.roomLocation = '';
    sheetOrder.forEach(key => {
      if (Array.isArray(data.items[key])){
        data.items[key].forEach(it => {
          if (it.lastVerified === undefined) it.lastVerified = null;
          if (it.customPick === undefined) it.customPick = null;
        });
      }
    });

    const serial = data.serialNo;
    const existingUid = serial ? serialToUid.get(serial) : null;

    if (existingUid){
      const choice = await renderCartConflictModal(serial, carts[existingUid], data, pc.fileName);
      if (choice === 'imported'){
        data.uid = existingUid;
        carts[existingUid] = data;
        checkedForPrint.add(existingUid);
        clearDirty(existingUid);
        activeCartUid = existingUid;
        overwrittenCount++;
      } else {
        keptMemoryCount++;
        activeCartUid = existingUid;
      }
    } else {
      cartUidCounter++;
      const uid = 'cart_' + cartUidCounter;
      data.uid = uid;
      carts[uid] = data;
      checkedForPrint.add(uid);
      activeCartUid = uid;
      if (serial) serialToUid.set(serial, uid);
      loadedCount++;
    }
  }

  refreshCartSwitcher();
  refreshPrintChecklist();
  refreshNewCartNumberOptions();
  syncToolbarFromActiveCart();
  renderActiveCart();

  const messages = [];
  if (loadedCount) messages.push(`Loaded ${loadedCount} new cart(s).`);
  if (overwrittenCount) messages.push(`Replaced ${overwrittenCount} in-memory cart(s) with the imported version.`);
  if (keptMemoryCount) messages.push(`Kept ${keptMemoryCount} in-memory cart(s) as-is (imported version discarded).`);
  if (restoredChoicesCount) messages.push(`Restored ${restoredChoicesCount} remembered duplicate-resolution choice(s) from LastUpdate.json.`);
  if (parseFailures.length) messages.push(`${parseFailures.length} file(s) could not be read (not valid cart JSON).`);
  if (messages.length) alert(messages.join('\n'));
}

document.getElementById('btnExportCsv').addEventListener('click', async () => {
  const uids = [...document.querySelectorAll('#printChecklist input:checked')].map(i => i.dataset.uid);
  if (!uids.length){ alert('Check at least one cart in "Carts to Print" to export.'); return; }
  const header = ['Cart Serial No','Sheet','Qty/Stock Level','Item Description','Ref No','MSD Location','IFCAP','Expiration (Mo/Yr)'];
  const rows = [header];
  uids.forEach(uid => {
    const cart = carts[uid];
    sheetOrder.forEach(key => {
      cart.items[key].forEach(it => {
        if (!it.desc && !it.qty && !it.ref) return;
        rows.push([cart.serialNo || uid, sheetMeta[key].title, it.qty, it.desc, it.ref, it.msd, it.ifcap, it.exp]);
      });
    });
  });
  const csv = rows.map(r => r.map(csvField).join(',')).join('\n');
  await saveFileSmart(csv, 'crash-cart-export.csv', 'text/csv');
});

document.getElementById('btnPrintSelected').addEventListener('click', async () => {
  const uids = [...document.querySelectorAll('#printChecklist input:checked')].map(i => i.dataset.uid);
  if (!uids.length){ alert('Check at least one cart in "Carts to Print".'); return; }
  const includePickList = !document.getElementById('chkHideEmergencyList').checked;
  const includeCustomPickSheet = !document.getElementById('chkHideEmergencyAutoGenBoxes').checked;
  const bundle = document.getElementById('printBundle');
  bundle.innerHTML = uids.map(uid => {
    const cart = carts[uid];
    let html = renderCoverSheetHTML(cart, '');
    sheetOrder.forEach(key => { html += renderInventorySheetHTML(key, cart, ''); });
    if (includePickList) html += renderEmergencyPickListHTML(cart, null);
    if (includeCustomPickSheet) html += renderCustomPickSheetHTML(cart, null);
    return html;
  }).join('');
  document.body.classList.add('printing');
  await waitForPrintImages(bundle);
  prepareSheetsForPrint(bundle);
  window.print();
  cleanupSheetsAfterPrint(bundle);
  document.body.classList.remove('printing');
  bundle.innerHTML = '';
});

document.getElementById('btnPrintForms').addEventListener('click', async () => {
  await waitForPrintImages(pagesEl);
  prepareSheetsForPrint(pagesEl);
  window.print();
  cleanupSheetsAfterPrint(pagesEl);
});

document.getElementById('btnPrintStatusBoard').addEventListener('click', () => {
  const uids = Object.keys(carts);
  if (!uids.length){ alert('No carts are loaded — nothing to print on the Status Board.'); return; }
  const bundle = document.getElementById('printBundle');
  const boardSheets = [...document.querySelectorAll('#statusBoardContainer .board-sheet')];
  if (!boardSheets.length){ alert('Status Board is not currently available.'); return; }
  bundle.innerHTML = boardSheets.map(s => s.outerHTML).join('');
  document.body.classList.add('printing');
  prepareSheetsForPrint(bundle);
  window.print();
  cleanupSheetsAfterPrint(bundle);
  document.body.classList.remove('printing');
  bundle.innerHTML = '';
});

/* ================= AUTO-GEN REFERENCE DATA ================= */
const autoGenColumns = ['ALL @ PAR','Order ALL Drawers','Top Drawer','Side Drawer','Drawer 2','Drawer 3','Drawer 4','Drawer 5'];
const autoGenData = [
  ['PRCPH','PRCPH','PRCPH','PRCPH','PRCPH','PRCPH','PRCPH','PRCPH'],
  ['ID CC','ID CC','ID CC','ID CC','ID CC','ID CC','ID CC','ID CC'],
  ['IE317 177 1','IE317 177 0','IE317 177 1','IE317 177 1','IE317 177 1','IE317 177 1','IE317 177 0','IE317 177 1'],
  ['IE317 434 2','IE317 434 0','IE317 434 2','IE317 434 2','IE317 434 2','IE317 434 2','IE317 434 2','IE317 434 0'],
  ['IE317 1569 2','IE317 1569 0','IE317 1569 2','IE317 1569 2','IE317 1569 2','IE317 1569 0','IE317 1569 2','IE317 1569 2'],
  ['IE317 1624 2','IE317 1624 0','IE317 1624 2','IE317 1624 2','IE317 1624 2','IE317 1624 2','IE317 1624 0','IE317 1624 2'],
  ['IE317 1625 2','IE317 1625 0','IE317 1625 2','IE317 1625 0','IE317 1625 2','IE317 1625 2','IE317 1625 2','IE317 1625 2'],
  ['IE317 1627 2','IE317 1627 0','IE317 1627 2','IE317 1627 0','IE317 1627 2','IE317 1627 2','IE317 1627 2','IE317 1627 2'],
  ['IE317 1747 1','IE317 1747 0','IE317 1747 1','IE317 1747 1','IE317 1747 1','IE317 1747 0','IE317 1747 1','IE317 1747 1'],
  ['IE317 1753 2','IE317 1753 0','IE317 1753 2','IE317 1753 2','IE317 1753 2','IE317 1753 0','IE317 1753 2','IE317 1753 2'],
  ['IE317 1913 2','IE317 1913 0','IE317 1913 2','IE317 1913 2','IE317 1913 2','IE317 1913 2','IE317 1913 2','IE317 1913 0'],
  ['IE317 1914 2','IE317 1914 0','IE317 1914 2','IE317 1914 2','IE317 1914 2','IE317 1914 2','IE317 1914 2','IE317 1914 0'],
  ['IE317 1915 2','IE317 1915 0','IE317 1915 2','IE317 1915 2','IE317 1915 2','IE317 1915 2','IE317 1915 2','IE317 1915 0'],
  ['IE317 1958 1','IE317 1958 0','IE317 1958 1','IE317 1958 1','IE317 1958 1','IE317 1958 1','IE317 1958 1','IE317 1958 0'],
  ['IE317 1964 1','IE317 1964 0','IE317 1964 1','IE317 1964 1','IE317 1964 1','IE317 1964 0','IE317 1964 1','IE317 1964 1'],
  ['IE317 1972 1','IE317 1972 0','IE317 1972 1','IE317 1972 1','IE317 1972 1','IE317 1972 1','IE317 1972 0','IE317 1972 1'],
  ['IE317 1994 5','IE317 1994 0','IE317 1994 5','IE317 1994 5','IE317 1994 0','IE317 1994 5','IE317 1994 5','IE317 1994 5'],
  ['IE317 2014 1','IE317 2014 0','IE317 2014 1','IE317 2014 1','IE317 2014 1','IE317 2014 1','IE317 2014 0','IE317 2014 1'],
  ['IE317 2016 1','IE317 2016 0','IE317 2016 1','IE317 2016 1','IE317 2016 1','IE317 2016 1','IE317 2016 1','IE317 2016 0'],
  ['IE317 2058 1','IE317 2058 0','IE317 2058 1','IE317 2058 1','IE317 2058 1','IE317 2058 0','IE317 2058 1','IE317 2058 1'],
  ['IE317 2059 1','IE317 2059 0','IE317 2059 1','IE317 2059 1','IE317 2059 1','IE317 2059 0','IE317 2059 1','IE317 2059 1'],
  ['IE317 2086 1','IE317 2086 0','IE317 2086 1','IE317 2086 1','IE317 2086 1','IE317 2086 0','IE317 2086 1','IE317 2086 1'],
  ['IE317 2254 2','IE317 2254 0','IE317 2254 2','IE317 2254 2','IE317 2254 2','IE317 2254 0','IE317 2254 2','IE317 2254 2'],
  ['IE317 2800 2','IE317 2800 0','IE317 2800 2','IE317 2800 2','IE317 2800 2','IE317 2800 2','IE317 2800 2','IE317 2800 0'],
  ['IE317 5010 1','IE317 5010 0','IE317 5010 1','IE317 5010 1','IE317 5010 0','IE317 5010 1','IE317 5010 1','IE317 5010 1'],
  ['IE317 5038 1','IE317 5038 0','IE317 5038 1','IE317 5038 1','IE317 5038 0','IE317 5038 1','IE317 5038 1','IE317 5038 1'],
  ['IE317 5039 2','IE317 5039 0','IE317 5039 2','IE317 5039 2','IE317 5039 0','IE317 5039 2','IE317 5039 2','IE317 5039 2'],
  ['IE317 5042 2','IE317 5042 0','IE317 5042 2','IE317 5042 2','IE317 5042 0','IE317 5042 2','IE317 5042 2','IE317 5042 2'],
  ['IE317 5070 2','IE317 5070 0','IE317 5070 2','IE317 5070 2','IE317 5070 0','IE317 5070 2','IE317 5070 2','IE317 5070 2'],
  ['IE317 5595 2','IE317 5595 0','IE317 5595 2','IE317 5595 2','IE317 5595 2','IE317 5595 2','IE317 5595 2','IE317 5595 0'],
  ['IE317 6086 5','IE317 6086 0','IE317 6086 5','IE317 6086 5','IE317 6086 5','IE317 6086 0','IE317 6086 5','IE317 6086 5'],
  ['IE317 7722 2','IE317 7722 0','IE317 7722 2','IE317 7722 2','IE317 7722 2','IE317 7722 0','IE317 7722 2','IE317 7722 2'],
  ['IE317 9295 20','IE317 9295 0','IE317 9295 20','IE317 9295 20','IE317 9295 0','IE317 9295 20','IE317 9295 20','IE317 9295 20'],
  ['IE317 9299 1','IE317 9299 0','IE317 9299 1','IE317 9299 1','IE317 9299 1','IE317 9299 1','IE317 9299 0','IE317 9299 1'],
  ['IE317 9414 2','IE317 9414 0','IE317 9414 2','IE317 9414 2','IE317 9414 2','IE317 9414 2','IE317 9414 0','IE317 9414 2'],
  ['IE317 9423 5','IE317 9423 0','IE317 9423 5','IE317 9423 5','IE317 9423 0','IE317 9423 5','IE317 9423 5','IE317 9423 5'],
  ['IE317 9427 3','IE317 9427 0','IE317 9427 3','IE317 9427 3','IE317 9427 0','IE317 9427 3','IE317 9427 3','IE317 9427 3'],
  ['IE317 9436 1','IE317 9436 0','IE317 9436 1','IE317 9436 1','IE317 9436 0','IE317 9436 1','IE317 9436 1','IE317 9436 1'],
  ['IE317 9625 3','IE317 9625 0','IE317 9625 3','IE317 9625 3','IE317 9625 3','IE317 9625 3','IE317 9625 3','IE317 9625 0'],
  ['IE317 10934 5','IE317 10934 0','IE317 10934 5','IE317 10934 5','IE317 10934 0','IE317 10934 5','IE317 10934 5','IE317 10934 5'],
  ['IE317 13310 4','IE317 13310 0','IE317 13310 4','IE317 13310 4','IE317 13310 0','IE317 13310 4','IE317 13310 4','IE317 13310 4'],
  ['IE317 14528 1','IE317 14528 0','IE317 14528 1','IE317 14528 1','IE317 14528 1','IE317 14528 1','IE317 14528 0','IE317 14528 1'],
  ['IE317 14774 3','IE317 14774 0','IE317 14774 3','IE317 14774 3','IE317 14774 0','IE317 14774 3','IE317 14774 3','IE317 14774 3'],
  ['IE317 18827 1','IE317 18827 0','IE317 18827 1','IE317 18827 1','IE317 18827 1','IE317 18827 0','IE317 18827 1','IE317 18827 1'],
  ['IE317 19113 2','IE317 19113 0','IE317 19113 2','IE317 19113 2','IE317 19113 2','IE317 19113 2','IE317 19113 2','IE317 19113 0'],
  ['IE317 19671 3','IE317 19671 0','IE317 19671 3','IE317 19671 3','IE317 19671 0','IE317 19671 3','IE317 19671 3','IE317 19671 3'],
  ['IE317 19676 3','IE317 19676 0','IE317 19676 3','IE317 19676 3','IE317 19676 0','IE317 19676 3','IE317 19676 3','IE317 19676 3'],
  ['IE317 19677 3','IE317 19677 0','IE317 19677 3','IE317 19677 3','IE317 19677 0','IE317 19677 3','IE317 19677 3','IE317 19677 3'],
  ['IE317 19678 3','IE317 19678 0','IE317 19678 3','IE317 19678 3','IE317 19678 0','IE317 19678 3','IE317 19678 3','IE317 19678 3'],
  ['IE317 19768 1','IE317 19768 0','IE317 19768 1','IE317 19768 1','IE317 19768 1','IE317 19768 0','IE317 19768 1','IE317 19768 1'],
  ['IE317 20492 1','IE317 20492 0','IE317 20492 1','IE317 20492 1','IE317 20492 1','IE317 20492 0','IE317 20492 1','IE317 20492 1'],
  ['IE317 20493 1','IE317 20493 0','IE317 20493 1','IE317 20493 1','IE317 20493 1','IE317 20493 0','IE317 20493 1','IE317 20493 1'],
  ['IE317 20659 2','IE317 20659 0','IE317 20659 2','IE317 20659 2','IE317 20659 0','IE317 20659 2','IE317 20659 2','IE317 20659 2'],
  ['IE317 22138 3','IE317 22138 0','IE317 22138 3','IE317 22138 3','IE317 22138 0','IE317 22138 3','IE317 22138 3','IE317 22138 3'],
  ['IE317 23695 1','IE317 23695 0','IE317 23695 1','IE317 23695 1','IE317 23695 1','IE317 23695 1','IE317 23695 1','IE317 23695 0'],
  ['IE317 23924 2','IE317 23924 0','IE317 23924 0','IE317 23924 2','IE317 23924 2','IE317 23924 2','IE317 23924 2','IE317 23924 2'],
  ['IE317 27104 1','IE317 27104 0','IE317 27104 0','IE317 27104 1','IE317 27104 1','IE317 27104 1','IE317 27104 1','IE317 27104 1'],
  ['IE317 31896 2','IE317 31896 0','IE317 31896 2','IE317 31896 2','IE317 31896 0','IE317 31896 2','IE317 31896 2','IE317 31896 2'],
  ['IE317 32038 1','IE317 32038 0','IE317 32038 1','IE317 32038 1','IE317 32038 1','IE317 32038 1','IE317 32038 0','IE317 32038 1'],
  ['IE317 32148 2','IE317 32148 0','IE317 32148 2','IE317 32148 2','IE317 32148 2','IE317 32148 0','IE317 32148 2','IE317 32148 2'],
  ['IE317 32527 5','IE317 32527 0','IE317 32527 5','IE317 32527 0','IE317 32527 5','IE317 32527 5','IE317 32527 5','IE317 32527 5'],
  ['IE317 32528 5','IE317 32528 0','IE317 32528 5','IE317 32528 0','IE317 32528 5','IE317 32528 5','IE317 32528 5','IE317 32528 5'],
  ['IE317 32529 5','IE317 32529 0','IE317 32529 5','IE317 32529 0','IE317 32529 5','IE317 32529 5','IE317 32529 5','IE317 32529 5'],
  ['IE317 32530 5','IE317 32530 0','IE317 32530 5','IE317 32530 0','IE317 32530 5','IE317 32530 5','IE317 32530 5','IE317 32530 5'],
  ['IE317 33996 2','IE317 33996 0','IE317 33996 0','IE317 33996 2','IE317 33996 2','IE317 33996 2','IE317 33996 2','IE317 33996 2'],
  ['IE317 33997 1','IE317 33997 0','IE317 33997 1','IE317 33997 1','IE317 33997 1','IE317 33997 0','IE317 33997 1','IE317 33997 1'],
  ['IE317 35241 1','IE317 35241 0','IE317 35241 1','IE317 35241 1','IE317 35241 1','IE317 35241 0','IE317 35241 1','IE317 35241 1'],
  ['IE317 35242 1','IE317 35242 0','IE317 35242 1','IE317 35242 1','IE317 35242 1','IE317 35242 0','IE317 35242 1','IE317 35242 1'],
  ['IE317 35243 1','IE317 35243 0','IE317 35243 1','IE317 35243 1','IE317 35243 1','IE317 35243 0','IE317 35243 1','IE317 35243 1'],
  ['IE317 35244 1','IE317 35244 0','IE317 35244 1','IE317 35244 1','IE317 35244 1','IE317 35244 0','IE317 35244 1','IE317 35244 1'],
  ['IE317 35398 1','IE317 35398 0','IE317 35398 1','IE317 35398 1','IE317 35398 1','IE317 35398 0','IE317 35398 1','IE317 35398 1'],
  ['IE317 35399 1','IE317 35399 0','IE317 35399 1','IE317 35399 1','IE317 35399 1','IE317 35399 0','IE317 35399 1','IE317 35399 1'],
  ['IE317 35400 1','IE317 35400 0','IE317 35400 1','IE317 35400 1','IE317 35400 1','IE317 35400 0','IE317 35400 1','IE317 35400 1'],
  ['IE317 35486 10','IE317 35486 0','IE317 35486 10','IE317 35486 10','IE317 35486 0','IE317 35486 10','IE317 35486 10','IE317 35486 10'],
  ['IE317 35511 6','IE317 35511 0','IE317 35511 6','IE317 35511 6','IE317 35511 6','IE317 35511 0','IE317 35511 6','IE317 35511 6'],
  ['IE317 37033 1','IE317 37033 0','IE317 37033 1','IE317 37033 1','IE317 37033 1','IE317 37033 0','IE317 37033 1','IE317 37033 1'],
  ['IE317 37035 1','IE317 37035 0','IE317 37035 1','IE317 37035 1','IE317 37035 1','IE317 37035 0','IE317 37035 1','IE317 37035 1'],
  ['IE317 38897 1','IE317 38897 0','IE317 38897 1','IE317 38897 1','IE317 38897 1','IE317 38897 0','IE317 38897 1','IE317 38897 1'],
  ['IE317 39021 2','IE317 39021 0','IE317 39021 2','IE317 39021 2','IE317 39021 0','IE317 39021 2','IE317 39021 2','IE317 39021 2'],
  ['IE317 39218 1','IE317 39218 0','IE317 39218 1','IE317 39218 1','IE317 39218 1','IE317 39218 1','IE317 39218 1','IE317 39218 0'],
  ['IE317 41595 2','IE317 41595 0','IE317 41595 2','IE317 41595 0','IE317 41595 2','IE317 41595 2','IE317 41595 2','IE317 41595 2'],
  ['IE317 50168 1','IE317 50168 0','IE317 50168 0','IE317 50168 1','IE317 50168 1','IE317 50168 1','IE317 50168 1','IE317 50168 1'],
  ['IE317 50261 3','IE317 50261 0','IE317 50261 3','IE317 50261 3','IE317 50261 3','IE317 50261 0','IE317 50261 3','IE317 50261 3'],
  ['IE317 50617 3','IE317 50617 0','IE317 50617 3','IE317 50617 3','IE317 50617 0','IE317 50617 3','IE317 50617 3','IE317 50617 3'],
  ['IE317 98010 1','IE317 98010 0','IE317 98010 0','IE317 98010 1','IE317 98010 1','IE317 98010 1','IE317 98010 1','IE317 98010 1'],
  ['***END***^89','***END***^89','***END***^89','***END***^89','***END***^89','***END***^89','***END***^89','***END***^89'],
];

/* Computes the CUSTOM column value for one Auto-Gen row, reflecting only the ACTIVE
   cart's currently checked (via per-item pick checkboxes) items. Recomputed fresh
   every time the Auto-Gen modal is opened. */
function computeCustomAutoGenValue(row){
  const ref = row[0];
  if (ref === 'PRCPH' || ref === 'ID CC' || ref === '***END***^89') return ref;
  const m = String(ref).match(/^IE317 (\S+) (\S+)$/);
  if (!m) return ref;
  const ifcapNum = m[1];
  const parQty = m[2];
  const cart = carts[activeCartUid];
  let picked = false;
  if (cart){
    for (const key of sheetOrder){
      if ((cart.items[key] || []).some(it => String(it.ifcap || '').trim() === ifcapNum && isItemCustomPicked(it))){
        picked = true;
        break;
      }
    }
  }
  return `IE317 ${ifcapNum} ${picked ? parQty : 0}`;
}

function renderAutoGenModal(){
  const root = document.getElementById('modalRoot');
  const columns = [...autoGenColumns, 'CUSTOM'];
  const dataRows = autoGenData.map(row => [...row, computeCustomAutoGenValue(row)]);

  const rowsHtml = dataRows.map(row => `
    <tr>${row.map(v => `<td>${esc(v)}</td>`).join('')}</tr>
  `).join('');
  const colOptionsHtml = columns.map((c,i) => `<option value="${i}">${esc(c)}</option>`).join('');

  root.innerHTML = `
    <div class="modal-overlay">
      <div class="modal-box wide">
        <h3>Auto-Gen (Supply Order Reference)</h3>
        <div class="modal-sub">Pick a column and copy it to your clipboard in order to Auto-Gen a drawer in Vista. <b>CUSTOM</b> reflects the items currently checked (via the per-item pick checkboxes) on the active cart only.</div>
        <div class="autogen-controls">
          <label style="font-size:11px; font-weight:bold; text-transform:uppercase; color:#444;">Column to copy:</label>
          <select id="selAutoGenColumn">${colOptionsHtml}</select>
          <button id="btnAutoGenCopy">Copy Column to Clipboard</button>
        </div>
        <div class="autogen-table-wrap">
          <table class="autogen">
            <thead><tr>${columns.map(c => `<th>${esc(c)}</th>`).join('')}</tr></thead>
            <tbody>${rowsHtml}</tbody>
          </table>
        </div>
        <div class="modal-actions">
          <button class="btn-cancel" id="btnAutoGenClose">Close</button>
        </div>
      </div>
    </div>
  `;

  document.getElementById('btnAutoGenClose').addEventListener('click', () => { root.innerHTML = ''; root._onEscape = null; });

  document.getElementById('btnAutoGenCopy').addEventListener('click', async () => {
    const colIdx = +document.getElementById('selAutoGenColumn').value;
    const values = dataRows.map(row => row[colIdx]).join('\n');
    const btn = document.getElementById('btnAutoGenCopy');
    try {
      await navigator.clipboard.writeText(values);
      btn.textContent = 'Copied!';
      btn.classList.add('copied');
      setTimeout(() => { btn.textContent = 'Copy Column to Clipboard'; btn.classList.remove('copied'); }, 1500);
    } catch (err) {
      alert('Could not access the clipboard automatically. Select and copy this manually:\n\n' + values);
    }
  });
}

document.getElementById('btnAutoGen').addEventListener('click', renderAutoGenModal);

/* ================= HELP MODAL ================= */
function renderHelpModal(){
  const root = document.getElementById('modalRoot');
  root.innerHTML = `
    <div class="modal-overlay">
      <div class="modal-box wide">
        <h3>How to Use This Page</h3>
        <div class="help-content">
          <h4>Top Navigation Bar</h4>
          <ul>
            <li><b>Show/Hide Command Menu</b> — expands or collapses the toolbar below. Collapsed by default on page load.</li>
            <li><b>Jump to</b> — instantly scrolls to any page of the active cart (cover sheet, any drawer, the Emergency Pick List when visible, the Custom Emergency Pick Sheet when visible, or the Status Board).</li>
            <li><b>Auto-Gen</b> — opens a reference table of supply-ordering data with a column-copy tool. A <b>CUSTOM</b> column reflects the items currently checked (via the per-item pick checkboxes) on the active cart only.</li>
            <li><b>Help</b> — this window.</li>
          </ul>

          <h4>Command Menu</h4>
          <ul>
            <li><b>Fiscal Year / Month / Day</b> — read-only, always reflects today's system date.</li>
            <li><b>Lock Fields</b> — checked by default. While checked, QTY, Description, Ref No., MSD Location, and IFCAP cannot be manually edited on any drawer sheet (Expiration remains editable). Uncheck to allow manual edits to those fields.</li>
            <li><b>Desktop Layout</b> — checked by default, showing the command menu as a 4-column grid suited to a laptop or desktop screen. Uncheck to switch to a single stacked column with larger buttons and fields — better suited to a phone screen like an iPhone, with the whole menu scrollable in place if it runs taller than the screen.</li>
            <li><b>Hide Emergency Pick List</b> — checked by default (list hidden). Uncheck to append an unofficial, spreadsheet-style pick list to the bottom of the active cart's pages — and to prints of that cart — listing every stocked item across all drawers/shelves, sorted by MSD Location from smallest to largest, so its physical location can be found quickly. It's a plain table only (no form styling) and is not part of the official inventory form.</li>
            <li><b>Hide Emergency Auto Gen Boxes</b> — checked by default (checkboxes hidden). Uncheck to show a selection checkbox on the right side of every item row on each drawer/shelf sheet (non-printable). Items currently expiring soon (yellow) or already past due (red) are checked automatically; checking or unchecking any item manually overrides the automatic rule for that item going forward, and your choice is saved with the cart. A <b>Custom Emergency Pick Sheet</b> page then appears — using the same MSD-Location sort and drawer color-coding as the general Emergency Pick List — showing only the items you've checked.</li>
            <li><b>Active Cart</b> dropdown — switches which cart's 7 pages are shown. Turns red when no carts exist, green once at least one does. If the current cart has unsaved changes, you'll be asked to save or discard them before switching.</li>
            <li><b>New Cart Number</b> — pick an unused number (001–100), then click <b>+ New Cart</b>. Numbers already in use are grayed out.</li>
            <li><b>Delete Cart</b> — permanently removes the active cart (with confirmation).</li>
            <li><b>Carts to Print</b> — check which loaded carts should be included when using <b>Print Selected Carts</b>.</li>
          </ul>

          <h4>Unsaved Changes Protection</h4>
          <ul>
            <li>Once you edit anything in the active cart, the cart banner shows <b>"Unsaved changes"</b> in yellow.</li>
            <li>If you then try to <b>switch carts</b>, click <b>+ New Cart</b>, or <b>load cart file(s)</b> while the active cart has unsaved changes, you'll be prompted to <b>Save &amp; Continue</b>, <b>Discard Changes</b>, or <b>Cancel</b> and stay on the current cart.</li>
            <li>If the active cart has no unsaved changes, none of these actions interrupt you — they proceed immediately as before.</li>
          </ul>

          <h4>Workbook Tools</h4>
          <ul>
            <li><b>Load Book1-C-DIST.xlsx</b> — loads the master supply file into memory.</li>
            <li><b>Check for Updates</b> — cross-references every loaded cart's items (by IFCAP number) against the loaded workbook, updating Ref No. and MSD Location if they've changed, and marking items as verified. Items with a placeholder IFCAP of "N/A" are never reported as needing verification. If Book1 has more than one row for the same IFCAP number, you'll be asked which row to trust — you can optionally remember that choice for 30 days.</li>
          </ul>

          <h4>Save / Load / Export</h4>
          <ul>
            <li><b>Choose Save Folder (This Session)</b> — uses your browser's folder picker (Chrome/Edge) to grant this page write access to a folder of your choice, such as a OneDrive-synced folder. Once chosen, all downstream save actions in this list write directly into that folder for the rest of this browser tab session — no more repeated "Save As" dialogs. If the folder isn't set, or access is later revoked, saves automatically fall back to a normal browser download.</li>
            <li><b>Save Active Cart (JSON)</b> — saves the active cart's full data (including your custom pick checkbox selections) and clears its "unsaved changes" flag. If you have any "remembered" duplicate-resolution choices, a second file, <b>LastUpdate.json</b>, is also saved — keep it in the same folder as your cart files.</li>
            <li><b>Load Cart(s) (JSON)</b> / <b>Load All from Folder (JSON)</b> — reload previously saved carts. If a loaded file's Cart Serial No. matches a cart already in memory (including another file in the same batch), you'll be asked — per cart number — whether to <b>keep the version currently in memory</b> or <b>use the imported file instead</b>. Either choice only affects that one cart; the rest of the files in the batch keep loading normally. If a <b>LastUpdate.json</b> is included, its remembered choices are restored automatically (as long as they're not older than 30 days).</li>
            <li><b>Export CSV</b> — exports a flat spreadsheet of every item across the checked carts in "Carts to Print."</li>
          </ul>

          <h4>Printing</h4>
          <ul>
            <li><b>Print Active Cart Only</b> — prints just what's currently on screen, including the Emergency Pick List and/or Custom Emergency Pick Sheet if either is currently shown.</li>
            <li><b>Print Selected Carts</b> — prints the full 7-page set for every cart checked in "Carts to Print," plus each cart's Emergency Pick List and/or Custom Emergency Pick Sheet if either is currently shown.</li>
            <li><b>Print Status Board</b> — prints only the fleet-wide status board, listing every loaded cart.</li>
          </ul>

          <h4>Color Coding</h4>
          <ul>
            <li><span class="kbd" style="background:#f5c2c7;">&nbsp;&nbsp;</span> Red — a date has already passed.</li>
            <li><span class="kbd" style="background:#ffe69c;">&nbsp;&nbsp;</span> Yellow — a date is due within the next 30 days.</li>
            <li><span class="kbd" style="background:#eaf2ff; outline:2px dashed #0d6efd;">&nbsp;&nbsp;</span> Blue dashed — an item's storage location hasn't been verified against Book1 in the last 30 days.</li>
          </ul>

          <h4>Keyboard Navigation</h4>
          <ul>
            <li><span class="kbd">Tab</span> — moves only between fields that are currently editable (locked/computed fields are skipped).</li>
            <li><span class="kbd">↑ / ↓</span> — inside a drawer table, moves to the same column in the row above/below.</li>
            <li><span class="kbd">← / →</span> — moves the cursor within the current field's text first; once at the very start/end, jumps to the previous/next editable field.</li>
          </ul>

          <h4>Important</h4>
          <p><b>Nothing is saved automatically.</b> Closing or refreshing this page will lose all cart data, including any cart(s) whose changes you haven't explicitly saved. Always use <b>Save Active Cart (JSON)</b> before leaving.</p>
          <p><b>Note:</b> "Check for Updates" only corrects data for carts currently open in this browser tab — it does not change what a brand-new cart starts with. Fixing that permanently is a separate, developer-level action.</p>
        </div>
        <div class="modal-actions">
          <button class="btn-cancel" id="btnHelpClose">Close</button>
        </div>
      </div>
    </div>
  `;
  document.getElementById('btnHelpClose').addEventListener('click', () => { root.innerHTML = ''; root._onEscape = null; });
}

document.getElementById('btnHelp').addEventListener('click', renderHelpModal);

/* ================= ARROW KEY NAVIGATION BETWEEN EDITABLE FIELDS ================= */
function isFieldEditable(el){
  if (!el || !(el.tagName === 'INPUT' || el.tagName === 'TEXTAREA')) return false;
  if (el.disabled || el.readOnly) return false;
  if (el.tabIndex === -1) return false;
  return true;
}
function getAllEditableFieldsInOrder(){
  return [...document.querySelectorAll('input, textarea')].filter(isFieldEditable);
}
function focusAndSelect(el){
  if (!el) return;
  el.focus();
  if (typeof el.select === 'function') el.select();
}
function isCaretAtStart(el){
  return el.selectionStart === 0 && el.selectionEnd === 0;
}
function isCaretAtEnd(el){
  const len = el.value.length;
  return el.selectionStart === len && el.selectionEnd === len;
}

function handleArrowKeyNavigation(e){
  const el = e.target;
  if (!isFieldEditable(el)) return;
  const key = e.key;
  if (!['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(key)) return;

  if (key === 'ArrowUp' || key === 'ArrowDown'){
    const td = el.closest('td');
    const tr = td ? td.closest('tr') : null;
    if (td && tr && tr.parentElement && tr.parentElement.tagName === 'TBODY'){
      const cellIndex = td.cellIndex;
      let sibling = key === 'ArrowUp' ? tr.previousElementSibling : tr.nextElementSibling;
      while (sibling){
        const candidateCell = sibling.children[cellIndex];
        const candidateInput = candidateCell ? candidateCell.querySelector('input, textarea') : null;
        if (isFieldEditable(candidateInput)){
          e.preventDefault();
          focusAndSelect(candidateInput);
          return;
        }
        sibling = key === 'ArrowUp' ? sibling.previousElementSibling : sibling.nextElementSibling;
      }
      return;
    }
    const fields = getAllEditableFieldsInOrder();
    const idx = fields.indexOf(el);
    if (idx === -1) return;
    const nextIdx = key === 'ArrowUp' ? idx - 1 : idx + 1;
    if (fields[nextIdx]){
      e.preventDefault();
      focusAndSelect(fields[nextIdx]);
    }
    return;
  }

  if (key === 'ArrowLeft' || key === 'ArrowRight'){
    const atBoundary = key === 'ArrowLeft' ? isCaretAtStart(el) : isCaretAtEnd(el);
    if (!atBoundary) return;
    const fields = getAllEditableFieldsInOrder();
    const idx = fields.indexOf(el);
    if (idx === -1) return;
    const nextIdx = key === 'ArrowLeft' ? idx - 1 : idx + 1;
    if (fields[nextIdx]){
      e.preventDefault();
      focusAndSelect(fields[nextIdx]);
    }
  }
}

document.addEventListener('keydown', handleArrowKeyNavigation);

/* ================= GLOBAL ESCAPE KEY: CLOSE WHICHEVER MODAL IS OPEN ================= */
document.addEventListener('keydown', (e) => {
  if (e.key !== 'Escape') return;
  const root = document.getElementById('modalRoot');
  if (!root.hasChildNodes()) return;
  if (typeof root._onEscape === 'function'){
    root._onEscape();
  } else {
    root.innerHTML = '';
  }
});

/* ================= DUPLICATE RESOLUTION MODAL ================= */
const rememberedDuplicateChoices = {};

function showDuplicateResolutionModal(ifcap, entries){
  return new Promise((resolve) => {
    const root = document.getElementById('modalRoot');
    const optionsHtml = entries.map((e, idx) => `
      <label class="modal-option">
        <input type="radio" name="dupChoice" value="${idx}">
        <span class="opt-detail">
          <b>Row ${e.rowNum}:</b> ${esc(e.desc)}<br>
          Main Storage Location: <b>${esc(e.msd)}</b> &nbsp;|&nbsp; Manufacturer Part Number: <b>${esc(e.ref)}</b>
        </span>
      </label>
    `).join('');

    root.innerHTML = `
      <div class="modal-overlay">
        <div class="modal-box">
          <h3>IFCAP ${esc(ifcap)} has ${entries.length} matching rows</h3>
          <div class="modal-sub">Choose which row's data should be used to update this item.</div>
          ${optionsHtml}
          <label class="modal-remember">
            <input type="checkbox" id="chkRememberChoice">
            Remember this choice for IFCAP ${esc(ifcap)} for 30 days
          </label>
          <div class="modal-actions">
            <button class="btn-cancel" id="btnDupCancel">Skip This Item</button>
            <button class="btn-confirm" id="btnDupConfirm" disabled>Use Selected Row</button>
          </div>
        </div>
      </div>
    `;

    const confirmBtn = root.querySelector('#btnDupConfirm');
    root.querySelectorAll('input[name="dupChoice"]').forEach(radio => {
      radio.addEventListener('change', () => { confirmBtn.disabled = false; });
    });

    const cancelAndResolveNull = () => {
      root.innerHTML = '';
      root._onEscape = null;
      resolve(null);
    };
    root._onEscape = cancelAndResolveNull;

    root.querySelector('#btnDupCancel').addEventListener('click', cancelAndResolveNull);

    confirmBtn.addEventListener('click', () => {
      const selected = root.querySelector('input[name="dupChoice"]:checked');
      const remember = root.querySelector('#chkRememberChoice').checked;
      root.innerHTML = '';
      root._onEscape = null;
      if (!selected){ resolve(null); return; }
      resolve({ index: +selected.value, remember });
    });
  });
}

/* ================= SHARED: BUILD IFCAP LOOKUP FROM A LOADED WORKBOOK ================= */
async function buildIfcapLookupFromWorkbook(workbook){
  const firstSheetName = workbook.SheetNames[0];
  const sheet = workbook.Sheets[firstSheetName];
  const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: '', raw: false });

  const groupedByIfcap = {};
  for (let i = 1; i < rows.length; i++){
    const row = rows[i];
    const ifcap = String(row[0] ?? '').trim();
    if (!ifcap) continue;
    if (!groupedByIfcap[ifcap]) groupedByIfcap[ifcap] = [];
    groupedByIfcap[ifcap].push({
      rowNum: i + 1,
      ref: String(row[17] ?? '').trim(),
      msd: String(row[14] ?? '').trim(),
      desc: String(row[1] ?? '').trim()
    });
  }

  const lookup = {};
  const skippedAmbiguous = [];
  const usedRememberedChoice = [];

  for (const [ifcap, entries] of Object.entries(groupedByIfcap)){
    if (entries.length === 1){
      lookup[ifcap] = entries[0];
      continue;
    }

    const remembered = rememberedDuplicateChoices[ifcap];
    if (remembered && daysSince(remembered.decidedOn) <= 30){
      lookup[ifcap] = remembered.entry;
      usedRememberedChoice.push(ifcap);
      continue;
    } else if (remembered){
      delete rememberedDuplicateChoices[ifcap];
    }

    const result = await showDuplicateResolutionModal(ifcap, entries);
    if (result){
      const chosenEntry = entries[result.index];
      lookup[ifcap] = chosenEntry;
      if (result.remember){
        rememberedDuplicateChoices[ifcap] = { entry: chosenEntry, decidedOn: todayFormatted };
      }
    } else {
      skippedAmbiguous.push(ifcap);
    }
  }

  return { lookup, skippedAmbiguous, usedRememberedChoice };
}

/* ================= CHECK FOR UPDATES (cross-reference vs Book1-C-DIST.xlsx) ================= */
document.getElementById('btnCheckUpdates').addEventListener('click', async () => {
  if (!loadedWorkbook){ alert('Load Book1-C-DIST.xlsx first.'); return; }
  if (Object.keys(carts).length === 0){ alert('No active cart. Please create or load a cart before checking for updates.'); return; }

  const { lookup, skippedAmbiguous, usedRememberedChoice } = await buildIfcapLookupFromWorkbook(loadedWorkbook);

  const todayStr = todayFormatted;
  const updated = [];
  const stale = [];

  Object.values(carts).forEach(cart => {
    const cartLabel = cart.serialNo || cart.uid;
    sheetOrder.forEach(key => {
      cart.items[key].forEach(item => {
        const ifcap = String(item.ifcap || '').trim();
        if (!ifcap) return;
        const match = lookup[ifcap];
        if (!match) return;
        const refChanged = match.ref && match.ref !== item.ref;
        const msdChanged = match.msd && match.msd !== item.msd;
        if (refChanged || msdChanged){
          updated.push({
            cart: cartLabel, ifcap, desc: item.desc,
            oldRef: item.ref, newRef: match.ref,
            oldMsd: item.msd, newMsd: match.msd
          });
          if (refChanged) item.ref = match.ref;
          if (msdChanged) item.msd = match.msd;
        }
        item.lastVerified = todayStr;
      });
    });
  });

  Object.values(carts).forEach(cart => {
    const cartLabel = cart.serialNo || cart.uid;
    sheetOrder.forEach(key => {
      cart.items[key].forEach(item => {
        const ifcap = String(item.ifcap || '').trim();
        if (!ifcap) return;
        if (isPlaceholderIfcap(ifcap)) return;
        if (isStaleVerification(item.lastVerified)){
          stale.push({ cart: cartLabel, ifcap, desc: item.desc });
        }
      });
    });
  });

  renderActiveCart();

  let msg = 'Check for Updates complete.\n\n';
  if (updated.length){
    msg += `UPDATED (${updated.length}):\n`;
    updated.forEach(u => {
      msg += `  Cart ${u.cart} — IFCAP ${u.ifcap} (${u.desc || 'no description'})\n`;
      if (u.oldRef !== u.newRef) msg += `      Ref: "${u.oldRef}" → "${u.newRef}"\n`;
      if (u.oldMsd !== u.newMsd) msg += `      MSD Location: "${u.oldMsd}" → "${u.newMsd}"\n`;
    });
    msg += '\n';
  } else {
    msg += 'No REF/MSD Location changes found.\n\n';
  }
  if (stale.length){
    msg += `STILL NEEDS VERIFICATION — no IFCAP match found in Book1-C-DIST.xlsx (${stale.length}):\n`;
    stale.forEach(s => { msg += `  Cart ${s.cart} — IFCAP ${s.ifcap} (${s.desc || 'no description'})\n`; });
    msg += '\n';
  }
  if (skippedAmbiguous.length){
    msg += `SKIPPED — duplicate rows in Book1 not resolved (${skippedAmbiguous.length}):\n`;
    msg += `  IFCAP: ${skippedAmbiguous.join(', ')}\n`;
    msg += `  These were not updated or verified this run. Click "Check for Updates" again to resolve them.\n\n`;
  }
  if (usedRememberedChoice.length){
    msg += `Used remembered choice (still within 30 days) for IFCAP: ${usedRememberedChoice.join(', ')}\n`;
  }
  alert(msg);
});

/* ================= DEV TOOL: PATCH sheetMeta DIRECTLY IN AN UPLOADED HTML FILE ================= */
function extractSheetMetaBlock(sourceText){
  const startMarker = 'const sheetMeta = {';
  const startIdx = sourceText.indexOf(startMarker);
  if (startIdx === -1) return null;
  let depth = 0, i = startIdx + startMarker.length - 1;
  const braceStart = i;
  for (; i < sourceText.length; i++){
    if (sourceText[i] === '{') depth++;
    else if (sourceText[i] === '}'){
      depth--;
      if (depth === 0) break;
    }
  }
  if (depth !== 0) return null;
  return { start: braceStart, end: i + 1 };
}

function patchSheetMetaInSource(sourceText, lookup){
  const block = extractSheetMetaBlock(sourceText);
  if (!block) return { patchedText: sourceText, updates: [], error: 'Could not locate the sheetMeta block in this file. It may not be a compatible version of this page.' };

  const blockText = sourceText.slice(block.start, block.end);
  const itemRegex = /\[\s*\d+\s*,\s*'((?:[^'\\]|\\.)*)'\s*,\s*'((?:[^'\\]|\\.)*)'\s*,\s*'((?:[^'\\]|\\.)*)'\s*,\s*'((?:[^'\\]|\\.)*)'\s*\]/g;

  const updates = [];
  const replacements = [];

  let m;
  while ((m = itemRegex.exec(blockText)) !== null){
    const [fullMatch, desc, ref, msd, ifcap] = m;
    const match = lookup[ifcap];
    if (!match) continue;
    const refChanged = match.ref && match.ref !== ref;
    const msdChanged = match.msd && match.msd !== msd;
    if (!refChanged && !msdChanged) continue;

    const newRef = refChanged ? match.ref : ref;
    const newMsd = msdChanged ? match.msd : msd;
    const newFullMatch = fullMatch
      .replace(`'${ref}'`, `'${newRef}'`)
      .replace(`'${msd}'`, `'${newMsd}'`);

    replacements.push({ start: m.index, end: m.index + fullMatch.length, newText: newFullMatch });
    updates.push({ ifcap, desc, oldRef: ref, newRef, oldMsd: msd, newMsd });
  }

  let patchedBlockText = blockText;
  replacements.sort((a,b) => b.start - a.start).forEach(r => {
    patchedBlockText = patchedBlockText.slice(0, r.start) + r.newText + patchedBlockText.slice(r.end);
  });

  const patchedText = sourceText.slice(0, block.start) + patchedBlockText + sourceText.slice(block.end);
  return { patchedText, updates, error: null };
}

function renderDevToolModal(){
  document.getElementById('chkLockFields').checked = true;
  if (activeCartUid) renderActiveCart();
  const root = document.getElementById('modalRoot');
  root.innerHTML = `
    <div class="modal-overlay">
      <div class="modal-box wide">
        <h3>Developer Tool — Patch Template Source Code</h3>
        <div class="modal-sub">
          This does NOT affect your currently loaded carts. It reads a copy of this page's HTML file plus
          Book1-C-DIST.xlsx, permanently updates the built-in Ref No. / MSD Location values in that file's
          source code, and gives you a fresh copy to save/replace the original with.
        </div>
        <div class="devtool-row">
          <label>Step 1: Select the HTML file to patch (this page's saved .html file)</label>
          <input type="file" id="devHtmlFile" accept=".html" />
        </div>
        <div class="devtool-row">
          <label>Step 2: Select Book1-C-DIST.xlsx</label>
          <input type="file" id="devWorkbookFile" accept=".xlsx" />
        </div>
        <div class="autogen-controls">
          <button id="btnDevGenerate">Generate Patched Copy</button>
        </div>
        <div id="devToolLog" class="devtool-log" style="display:none;"></div>
        <div class="modal-actions">
          <button class="btn-cancel" id="btnDevToolClose">Close</button>
        </div>
      </div>
    </div>
  `;

  const closeModal = () => { root.innerHTML = ''; root._onEscape = null; };
  root._onEscape = closeModal;
  document.getElementById('btnDevToolClose').addEventListener('click', closeModal);

  document.getElementById('btnDevGenerate').addEventListener('click', async () => {
    const htmlFile = document.getElementById('devHtmlFile').files[0];
    const wbFile = document.getElementById('devWorkbookFile').files[0];
    const log = document.getElementById('devToolLog');
    log.style.display = 'block';
    log.textContent = '';

    if (!htmlFile){ alert('Select the HTML file to patch first.'); return; }
    if (!wbFile){ alert('Select Book1-C-DIST.xlsx first.'); return; }

    log.textContent += `Reading "${htmlFile.name}"...\n`;
    const sourceText = await htmlFile.text();

    log.textContent += `Reading "${wbFile.name}"...\n`;
    const arrayBuffer = await wbFile.arrayBuffer();
    const workbook = XLSX.read(arrayBuffer, { cellDates:true });

    log.textContent += `Building IFCAP lookup (you may be asked to resolve duplicate rows)...\n`;
    const { lookup, skippedAmbiguous, usedRememberedChoice } = await buildIfcapLookupFromWorkbook(workbook);

    log.textContent += `Scanning template source for items that need updating...\n`;
    const { patchedText, updates, error } = patchSheetMetaInSource(sourceText, lookup);

    if (error){
      log.textContent += `\nERROR: ${error}\n`;
      return;
    }

    if (updates.length === 0){
      log.textContent += `\nNo changes needed — all template Ref No. / MSD Location values already match Book1-C-DIST.xlsx.\n`;
    } else {
      log.textContent += `\nUpdated ${updates.length} item(s):\n`;
      updates.forEach(u => {
        log.textContent += `  IFCAP ${u.ifcap} (${u.desc || 'no description'})\n`;
        if (u.oldRef !== u.newRef) log.textContent += `      Ref: "${u.oldRef}" → "${u.newRef}"\n`;
        if (u.oldMsd !== u.newMsd) log.textContent += `      MSD Location: "${u.oldMsd}" → "${u.newMsd}"\n`;
      });
    }
    if (skippedAmbiguous.length){
      log.textContent += `\nSkipped (unresolved duplicate rows in Book1): ${skippedAmbiguous.join(', ')}\n`;
    }
    if (usedRememberedChoice.length){
      log.textContent += `\nUsed remembered choice for: ${usedRememberedChoice.join(', ')}\n`;
    }

    if (updates.length > 0){
      const safeName = htmlFile.name.replace(/\.html$/i, '');
      const dateTag = todayFormatted.replace(/\//g, '-');
      const newFilename = `${safeName} - Patched ${dateTag}.html`;
      await saveFileSmart(patchedText, newFilename, 'text/html');
      log.textContent += `\nSaved: ${newFilename}\nReplace your working copy of this page with this file.\n`;
    }
  });
}

document.getElementById('btnDevTool').addEventListener('click', renderDevToolModal);

/* ================= INIT ================= */
refreshNewCartNumberOptions();
refreshCartSwitcher();
refreshPrintChecklist();
syncToolbarFromActiveCart();
renderActiveCart();
</script>
</body>
</html>