BREP_plm 0.26.0

The next.BREP.io PLM server for the Rust B-rep CAD kernel: parts, revisions, lifecycle, checkout, BOMs and configurable workflows over an embedded SQLite store, with a browser UI and the document API the CAD app stores through.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
// The PLM page. Vanilla, hash-routed, one fetch helper.
//
// The page never decides what a user may do — it asks the server (`/api/me`
// resolves the group rules into `can_author` / `can_checkin` / `is_admin`) and
// only DISABLES what the server would refuse. A button the page enables and
// the server rejects is a bug in one place; two copies of the rules would be a
// bug in two.

'use strict';

const $ = (id) => document.getElementById(id);
let me = null;
let currentPart = null;
let lifecycleOptions = [];
const statusName = state => lifecycleOptions.find(s => s.state === state)?.name || state;
const statusEnabled = state => lifecycleOptions.find(s => s.state === state)?.enabled !== false;

// ---------------------------------------------------------------- transport

// The session's CSRF token, from /api/login and /api/me. Every request that
// changes anything sends it back; the server refuses one that does not.
let csrfToken = '';

// The last few API calls, for the long-task record below: a long task with
// no script in it is the browser laying out what a response just drew.
const recentApi = [];

async function api(method, path, body) {
  const call = { method, path: path.split('?')[0], at: Math.round(performance.now()), ms: null, bytes: null };
  recentApi.push(call); if (recentApi.length > 8) recentApi.shift();
  try { return (await apiCall(method, path, body, call)).payload; } finally { call.ms = Math.round(performance.now() - call.at); }
}

// A GET that sends back the ETag it was last answered with: `{payload, tag}`,
// or `{notModified: true, tag}` when the server says nothing moved.
async function apiTagged(path, tag) {
  const call = { method: 'GET', path: path.split('?')[0], at: Math.round(performance.now()), ms: null, bytes: null };
  recentApi.push(call); if (recentApi.length > 8) recentApi.shift();
  try { return await apiCall('GET', path, undefined, call, tag ? { 'If-None-Match': tag } : {}); } finally { call.ms = Math.round(performance.now() - call.at); }
}

async function apiCall(method, path, body, call, headers = {}) {
  const options = { method, headers: { ...headers }, credentials: 'same-origin' };
  if (method !== 'GET' && csrfToken) options.headers['X-CSRF-Token'] = csrfToken;
  if (body !== undefined) {
    if (typeof body === 'string') {
      options.headers['Content-Type'] = 'application/json';
      options.body = body;
    } else {
      options.headers['Content-Type'] = 'application/json';
      options.body = JSON.stringify(body);
    }
  }
  const response = await fetch(path, options);
  const tag = response.headers.get('ETag') || '';
  if (response.status === 304) return { notModified: true, tag };
  if (response.status === 204) return { payload: null, tag };
  const text = await response.text();
  call.bytes = text.length;
  let payload = null;
  if (text) {
    try { payload = JSON.parse(text); } catch { payload = text; }
  }
  if (!response.ok) {
    const message = payload && payload.error ? payload.error : `${response.status} ${response.statusText}`;
    throw new Error(message);
  }
  return { payload, tag };
}

// A main-thread task of a second or more names itself: what it overlapped, and
// what was on screen. Kept in `window.__plmLongTasks` (newest last) and
// written to the console, so the next one is a record, not a guess.
const LONG_TASK_RECORD_MS = 1000;
window.__plmLongTasks = [];
try {
  new PerformanceObserver((list) => {
    for (const task of list.getEntries()) {
      if (task.duration < LONG_TASK_RECORD_MS) continue;
      const record = {
        ms: Math.round(task.duration),
        at: Math.round(task.startTime),
        attribution: (task.attribution || []).map((a) => [a.containerType, a.containerName, a.containerSrc, a.name].filter(Boolean).join(' ')),
        route: location.hash,
        tab: typeof objectTab === 'undefined' ? '' : objectTab,
        structureTab: typeof structure === 'undefined' ? '' : structure.tab,
        bomRows: document.querySelectorAll('#bom-rows tr').length,
        nodes: document.getElementsByTagName('*').length,
        hidden: document.hidden,
        dialog: document.querySelector('dialog[open]')?.id || '',
        api: recentApi.filter((c) => c.at <= task.startTime + task.duration).map((c) => `${c.method} ${c.path} at ${c.at} ${c.ms ?? '…'} ms ${c.bytes ?? '?'} B`),
      };
      window.__plmLongTasks.push(record);
      if (window.__plmLongTasks.length > 20) window.__plmLongTasks.shift();
      console.warn(`[plm long task] ${record.ms} ms on ${record.route} (${record.tab}/${record.structureTab}, ${record.bomRows} BOM rows, ${record.nodes} elements)`, record);
    }
  }).observe({ type: 'longtask', buffered: true });
} catch { /* no Long Tasks API: nothing to record */ }

function banner(message) {
  const el = $('banner');
  el.textContent = message || '';
  el.hidden = !message;
  // A modal dialog covers the page banner, so a refusal of what the dialog
  // just sent is also written inside the dialog, above its buttons.
  for (const old of document.querySelectorAll('p.dialog-error')) old.remove();
  const open = document.querySelector('dialog[open] form');
  if (message && open) {
    const line = document.createElement('p');
    line.className = 'error dialog-error';
    line.setAttribute('role', 'alert');
    line.textContent = message;
    open.insertBefore(line, open.querySelector('menu'));
  } else if (message) {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
}

// A refusal belongs to the dialog that caused it: closing the dialog, by
// saving or by cancelling, clears it.
for (const dialog of document.querySelectorAll('dialog')) {
  dialog.addEventListener('close', () => banner(''));
}

// Run an action, show any refusal, and refresh. Every mutating button goes
// through this so a server message always reaches the user.
async function act(fn) {
  banner('');
  try {
    await fn();
  } catch (error) {
    banner(error.message);
  }
}

const escape = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => (
  { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
));

const CLASS_NAMES = { normal: 'normal', family: 'family', template: 'template' };
const classBadge = (cls) => `<span class="badge badge-${escape(cls)}">${escape(CLASS_NAMES[cls] || cls)}</span>`;

// How a part type numbers, in words.
function modeText(mode) {
  switch (mode && mode.kind) {
    case 'free': return 'free text';
    case 'pattern': return `pattern <code>${escape(mode.regex)}</code>`;
    case 'script': return `script <code>${escape(mode.script)}</code>`;
    default: return 'counter';
  }
}

// A part's or revision's thumbnail (P9), from the URL the server hands out
// (versioned by the picture, so the browser keeps it). No picture — none
// made yet, stale after a save, or one that fails to load — is a neutral
// placeholder box, never a broken image.
const thumb = (url, size = 'sm', title = '') => (url
  ? `<img class="thumb thumb-${size}" src="${escape(url)}" alt="" loading="lazy" decoding="async"${title ? ` title="${escape(title)}"` : ''}>`
  : `<span class="thumb thumb-${size} thumb-none"${title ? ` title="${escape(title)}"` : ''} aria-hidden="true"></span>`);
document.addEventListener('error', (event) => {
  const img = event.target;
  if (!(img instanceof HTMLImageElement) || !img.classList.contains('thumb')) return;
  const box = document.createElement('span');
  box.className = `${img.className} thumb-none`;
  box.setAttribute('aria-hidden', 'true');
  img.replaceWith(box);
}, true);

const when = (seconds) => (seconds ? new Date(seconds * 1000).toLocaleString() : '—');
const bytes = (n) => (n ? `${n.toLocaleString()} B` : '—');

// ------------------------------------------------------------------- routing

const VIEWS = ['workflows', 'workflow-editor', 'workflow-run', 'setup', 'file', 'empty', 'native-import', 'parts', 'workspace', 'part', 'reviews', 'catalog', 'sourcing', 'tools', 'jobs', 'bake', 'bom-columns', 'occurrence-fields', 'types', 'users', 'scripts', 'settings', 'account', 'security', 'audit', 'backups'];

let visiblePage = null;
function show(view) {
  const names = { workflows: 'Workflows', 'workflow-editor': 'Workflow editor', 'workflow-run': 'Workflow process', setup: 'Server setup', 'native-import': 'Import native files', tools: 'Tools library', jobs: 'Jobs', parts: 'Parts', part: currentPart?.number || 'Part', workspace: 'Home', reviews: 'Review inbox', catalog: 'Classification', sourcing: 'Sourcing', bake: 'Bake queue', 'bom-columns':'BOM column configurations', 'occurrence-fields':'Occurrence fields', types: 'Part types', users: 'Users', scripts: 'Scripts', settings: 'Settings', account: 'My account', security: 'Security', audit: 'Audit', backups: 'Backups' };
  visiblePage = {view, title:names[view] || view};
  for(const menu of document.querySelectorAll('.top-nav details[open]'))menu.open=false;
  $('shell-status').textContent = names[view] || 'Ready';
  for (const name of VIEWS) $(`view-${name}`).hidden = name !== view;
  for (const link of document.querySelectorAll('.top-nav a')) {
    const current = link.getAttribute('href') === `#/${view === 'part' ? 'parts' : view}`;
    link.classList.toggle('current', current);
    if (current) link.setAttribute('aria-current', 'page');
    else link.removeAttribute('aria-current');
  }
}

let routeQueue = Promise.resolve();
function route() {
  for (const menu of document.querySelectorAll('.command-menu[open]')) menu.open = false;
  const hash=location.hash || '#/workspace';
  routeQueue=routeQueue.catch(()=>{}).then(async()=>{
    if(!me)return;
    OpenPages.capture();
    document.querySelector('.work-area').inert=true;
    try { await renderRoute(hash); }
    finally { document.querySelector('.work-area').inert=false; }
  });
  return routeQueue;
}
async function renderRoute(hash) {
  if (!me) return;
  banner('');
  const [, section, rawId, rawRevision, objectView] = hash.split('/');
  const id = rawId && decodeURIComponent(rawId);
  const revision = rawRevision && decodeURIComponent(rawRevision);
  try {
    await OpenPages.beforeRender(hash);
    const cached=OpenPages.resume(hash);
    if(cached){show(cached.view);}
    else if(section==='attachment'||section==='file'){const title=await FileDocuments.open(hash);show('file');visiblePage.title=title;}
    else if (section === 'empty') { show('empty');
    } else if (section === 'part' && id) {
      await renderPart(id, revision, OBJECT_TABS.some(([tab]) => tab === objectView) ? objectView : OpenPages.partView(hash));
      show('part');
    } else if (section === 'native-import') {
      if (!me.can_author) { location.hash = '#/parts'; return; }
      await openNativeImport();
      show('native-import');
    } else if (section === 'workspace') {
      Workbench.restore(OpenPages.workspace(hash));
      show('workspace');
      await Workbench.home(id);
      show('workspace');
    } else if (section === 'reviews') {
      await renderReviews();
      show('reviews');
    } else if (section === 'catalog') {
      await renderCatalog(id ? decodeURIComponent(id) : null);
      show('catalog');
    } else if (section === 'sourcing') {
      await renderCompanies();
      show('sourcing');
    } else if (section === 'tools') {
      await renderTools();
      show('tools');
    } else if (section === 'jobs') {
      await renderJobs(id ? decodeURIComponent(id) : null);
      show('jobs');
    } else if (section === 'bake') {
      await renderBake();
      show('bake');
    } else if(section==='bom-columns'){await renderBomConfigurations();show('bom-columns');
    } else if(section==='occurrence-fields'){await renderOccurrenceFields();show('occurrence-fields');
    } else if (section === 'types') {
      await renderTypes();
      show('types');
    } else if (section === 'scripts') {
      if (!me.is_admin) { location.hash = '#/parts'; return; }
      if(id) {
        const path=[rawId,rawRevision,objectView].filter(Boolean).map(decodeURIComponent).join('/');
        const draft=OpenPages.scriptDraft(hash);
        scriptPath=null;scriptSaved='';
        await openScript(path, draft?.text, true);
        if(draft){scriptSaved=draft.saved;syncScriptButtons();}
      } else {scriptPath=null;scriptSaved='';$('script-text').value='';$('script-path').textContent='No file open';await renderScripts();}
      show('scripts');
    } else if (section === 'workflows') {
      await WorkflowUI.list(id, revision); show('workflows');
    } else if (section === 'workflow-editor') {
      if (!me.is_admin) { location.hash = '#/workflows'; return; }
      await WorkflowUI.editor(id || 'new'); show('workflow-editor');
    } else if (section === 'workflow-run' && id) {
      await WorkflowUI.detail(id); show('workflow-run');
    } else if (section === 'setup') {
      if (!me.is_admin) { location.hash = '#/workspace'; return; }
      await SetupWizard.open();
      show('setup');
    } else if (section === 'settings') {
      if (!me.is_admin) { location.hash = '#/parts'; return; }
      await renderSettings();
      show('settings');
    } else if (section === 'audit') {
      if (!me.is_admin) { location.hash = '#/parts'; return; }
      await renderAudit();
      show('audit');
    } else if (section === 'account') {
      await renderAccount();
      show('account');
      if (id === 'password') {
        $('password-form').scrollIntoView({ block: 'start' });
        $('pw-current').focus({ preventScroll: true });
      }
    } else if (section === 'backups') {
      if (!me.is_admin) { location.hash = '#/parts'; return; }
      await renderBackups();
      show('backups');
    } else if (section === 'security') {
      if (!me.is_admin) { location.hash = '#/parts'; return; }
      await renderSecurity();
      show('security');
    } else if (section === 'users') {
      if (!me.is_admin) { location.hash = '#/parts'; return; }
      await renderUsers();
      show('users');
    } else {
      // `#/parts/<category id>` opens the list filtered to that category.
      if (section === 'parts' && id) {
        await loadCategories();
        fillCategoryFilter();
        $('filter-category').value = decodeURIComponent(id);
      }
      // Re-read on every visit: companies are added on another page, or by
      // another user.
      await loadCompanies();
      await renderParts();
      show('parts');
    }
    let title=visiblePage.title;
    if(visiblePage.view==='part')title=currentPart.number+(revision?'/'+(currentPart.revisions.find(r=>r.id===revision||r.label===revision)?.label || revision):'');
    if(visiblePage.view==='workspace'&&id)title=$('home-detail').querySelector('h2')?.textContent || 'Folder';
    if(visiblePage.view==='scripts'&&id)title=scriptPath;
    if(visiblePage.view==='catalog'&&id)title=$('cat-title').textContent || title;
    await OpenPages.afterRender(hash);
    OpenPages.activate(hash,visiblePage.view,title);
  } catch (error) {
    banner(error.message);
  }
  // The badge follows every page change: a review may have arrived since.
  refreshInbox();
}

// -------------------------------------------------------------- open in CAD

// Where this server hosts the CAD app (`/cad/config`'s `app`), or null when it
// hosts none: then no "Open in CAD" button is shown anywhere.
let cadApp = null;

async function loadCadConfig() {
  try {
    const config = await api('GET', '/cad/config');
    cadApp = config && config.app ? config.app : null;
  } catch {
    cadApp = null;
  }
}

// An "Open in CAD" button for one revision, as HTML, or '' when no CAD app is
// hosted. Any view may drop it into its markup: the one listener below opens
// every such button in a new tab. Every document class (.nbrep, .fbrep, .tbrep)
// opens in the CAD app, and a revision with no document yet opens as a new one.
const idSegment = value => encodeURIComponent(value).replace(/[.!'()*~]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase());
const documentKey = (part, revision) => `part/${idSegment(part)}/rev/${idSegment(revision)}`;

function openInCadButton(partId, revisionId, label = 'Open in CAD') {
  if (!cadApp || !partId || !revisionId) return '';
  const key = documentKey(partId, revisionId);
  return `<button type="button" data-open-cad="${escape(key)}" title="Open this revision in the CAD app, in a new tab">${escape(label)}</button>`;
}

document.addEventListener('click', (event) => {
  const button = event.target.closest && event.target.closest('[data-open-cad]');
  if (!button || !cadApp) return;
  event.preventDefault();
  // A new tab on this origin: the CAD app signs in with this page's session.
  window.open(`${cadApp}?open=${encodeURIComponent(button.dataset.openCad)}`, '_blank');
});

// -------------------------------------------------------------------- signin

// The desktop app's browser sign-in: BREP opened /desktop-link?token=…. The
// token is taken out of the address bar at once (kept for this tab only, so a
// sign-in or a reload keeps it), and nothing is approved until the person
// clicks Approve: a link someone else sent must not connect their app.
const DESKTOP_LINK_KEY = 'brep-desktop-link';
const desktopLinking = location.pathname === '/desktop-link';
const desktopLinkToken = (() => {
  if (!desktopLinking) return '';
  const fromUrl = new URLSearchParams(location.search).get('token') || '';
  try {
    if (fromUrl) sessionStorage.setItem(DESKTOP_LINK_KEY, fromUrl);
    else return sessionStorage.getItem(DESKTOP_LINK_KEY) || '';
  } catch { /* No storage: the token lives in this page only. */ }
  if (fromUrl) history.replaceState(null, '', '/desktop-link');
  return fromUrl;
})();

function desktopLinkDone(message, ok) {
  try { sessionStorage.removeItem(DESKTOP_LINK_KEY); } catch { /* Nothing kept. */ }
  $('desktop-link-ask').hidden = true;
  $('desktop-link-result').textContent = message;
  $('desktop-link-result').className = ok ? 'ok' : 'error';
}

async function showDesktopLink() {
  $('desktop-link').hidden = false;
  $('desktop-link-ask').hidden = true;
  $('desktop-link-result').textContent = '';
  if (!desktopLinkToken) {
    desktopLinkDone('This page needs the link BREP opened. Start the sign-in again from BREP.', false);
    return;
  }
  let link;
  try {
    link = await api('POST', '/api/desktop/link/inspect', { token: desktopLinkToken });
  } catch (error) {
    desktopLinkDone(error.message, false);
    return;
  }
  const machine = [link.host || 'a computer', link.os && `(${link.os})`].filter(Boolean).join(' ');
  $('desktop-link-text').textContent = `Connect BREP desktop on ${machine} as ${me.username}?`;
  $('desktop-link-code').textContent = link.code;
  $('desktop-link-origin').textContent = link.ip ? `Asked from ${link.ip}.` : '';
  $('desktop-link-ask').hidden = false;
}

async function decideDesktopLink(approve) {
  for (const id of ['desktop-link-approve', 'desktop-link-deny']) $(id).disabled = true;
  try {
    await api('POST', `/api/desktop/link/${approve ? 'approve' : 'deny'}`, { token: desktopLinkToken });
    desktopLinkDone(approve
      ? 'BREP desktop is connected. You can return to BREP.'
      : 'Refused: BREP desktop was not connected. You can close this page.', approve);
  } catch (error) {
    desktopLinkDone(error.message, false);
  } finally {
    for (const id of ['desktop-link-approve', 'desktop-link-deny']) $(id).disabled = false;
  }
}

$('desktop-link-approve').addEventListener('click', () => decideDesktopLink(true));
$('desktop-link-deny').addEventListener('click', () => decideDesktopLink(false));

async function boot() {
  try {
    me = await api('GET', '/api/me');
    csrfToken = me.csrf || '';
  } catch {
    me = null;
    csrfToken = '';
  }
  $('login-purpose').hidden = !desktopLinking;
  $('signin').hidden = !!me;
  $('shell').hidden = !me || desktopLinking;
  if (!me) return;
  if (desktopLinking) {
    await showDesktopLink();
    return;
  }

  const cadReturn = new URLSearchParams(location.search).get('cad');
  if (cadReturn) {
    let target;
    try { target = new URL(cadReturn, location.origin); } catch { /* Ignore malformed return paths. */ }
    if (target && target.origin === location.origin && target.pathname.startsWith('/cad/app/')) {
      location.replace(target.href);
      return;
    }
  }

  $('user-display-name').textContent = me.display_name || me.username;
  $('whoami').textContent = `${me.username} · ${me.groups.join(', ') || 'no groups'}`;
  $('user-menu-trigger').setAttribute('aria-label', `User account menu for ${me.display_name || me.username}`);
  for (const el of document.querySelectorAll('.admin-only')) el.hidden = !me.is_admin;
  for (const el of document.querySelectorAll('.author-only')) el.hidden = !me.can_author;
  const setupSettings = await api('GET', '/api/settings');
  lifecycleOptions = setupSettings.status_options;
  if (me.is_admin && !setupSettings.setup_completed && !location.hash) location.hash = '#/setup';
  await loadCadConfig();
  OpenPages.restoreSession();
  await route();
}

$('login-form').addEventListener('submit', async (event) => {
  event.preventDefault();
  $('login-error').textContent = '';
  try {
    const signedIn = await api('POST', '/api/login', {
      username: $('login-user').value,
      password: $('login-pass').value,
    });
    csrfToken = signedIn.csrf || '';
    $('login-pass').value = '';
    await boot();
  } catch (error) {
    $('login-error').textContent = error.message;
  }
});

$('signout').addEventListener('click', () => act(async () => {
  await api('POST', '/api/logout');
  me = null;
  location.hash = '';
  location.reload();
}));

// --------------------------------------------------------------- parts list

// A page replaces the previous rows, keeping DOM size bounded.
const PARTS_PAGE = 100; // Chunk size for explicitly selecting all matching parts.
let partsCursors = [null], partsPageIndex = 0, partsPageBusy = false, partsRestorePage = null;
// Bumped by every fresh render, so a slow page for an older search cannot
// land in the list after a newer one.
let partsGeneration = 0;
let partsNext = null;
let partsQuery = '';
let listedParts = [];
let selectedPartId = null;
const selectedParts = new Map();
let partsSelectionAnchor = null, partsBatchRunning = false, partsSelecting = false;
let partsBatchReport = null, partsBatchUser = null, partsBatchPolling = false, partsBatchOffset = 0;

async function renderParts() {
  if (!categoriesLoaded) {
    await loadCategories();
    fillCategoryFilter();
  }
  if (!companiesLoaded) await loadCompanies();
  // `m:<id>` or `s:<id>`: a manufacturer or a supplier.
  const [kind, company] = ($('filter-company').value || ':').split(':');
  const params = new URLSearchParams({
    q: $('search').value.trim(),
    category: $('filter-category').value,
    tag: $('filter-tag').value.trim(),
    manufacturer: kind === 'm' ? company : '',
    supplier: kind === 's' ? company : '',
  });
  if ($('filter-geometry').value) params.set('attr.has_geometry', $('filter-geometry').value);
  if ($('filter-thumbnail').value) params.set('attr.has_thumbnail', $('filter-thumbnail').value);
  partsQuery = params.toString();
  partsCursors = partsRestorePage?.cursors || [null];
  partsPageIndex = partsRestorePage?.index || 0;
  partsRestorePage = null;
  partsSelectionAnchor = null;
  await loadPartsPage(partsPageIndex);
}

function updatePartsPager() {
  $('parts-prev').disabled = partsPageBusy || partsPageIndex === 0;
  $('parts-more').disabled = partsPageBusy || !partsNext;
  $('parts-page-size').disabled = partsPageBusy;
  $('parts-page-status').textContent = `Page ${partsPageIndex + 1}`;
}

async function loadPartsPage(index) {
  const generation = ++partsGeneration;
  const cursor = partsCursors[index];
  const size = Number($('parts-page-size').value);
  partsPageBusy = true; updatePartsPager();
  try {
  const page = await api('GET', `/api/parts?${partsQuery}&limit=${size}${cursor ? `&after=${encodeURIComponent(cursor)}` : ''}`);
  if (generation !== partsGeneration) return;
  $('parts-empty').hidden = page.parts.length > 0;
  $('parts-empty').textContent = 'No parts match.';
  partsPageIndex = index; partsSelectionAnchor = null;
  listedParts = page.parts;
  $('parts-rows').innerHTML = page.parts.map(partRow).join('');
  partsNext = page.next;
  partsCursors[index + 1] = page.next;
  updatePartsSummary();
  } finally { if (generation === partsGeneration) { partsPageBusy = false; updatePartsPager(); updatePartSelection(); } }
}

async function moreParts() {
  if (!partsNext || partsPageBusy) return;
  await loadPartsPage(partsPageIndex + 1);
}

$('parts-more').addEventListener('click', () => act(moreParts));
$('parts-prev').addEventListener('click', () => act(() => loadPartsPage(partsPageIndex - 1)));
$('parts-page-size').addEventListener('change', () => act(renderParts));

function partRow(part) {
  return `
    <tr data-part-id="${escape(part.id)}" data-copy-kind="part" data-copy-part="${escape(part.id)}" data-copy-label="${escape(part.number)}">
      <td><input type="checkbox" class="part-select" aria-label="Select ${escape(part.number)}"${selectedParts.has(part.id)?' checked':''}></td>
      <td class="thumb-cell"><span class="part-tile-preview"><a href="#/part/${encodeURIComponent(part.id)}" tabindex="-1">${thumb(part.thumbnail_url)}</a>${part.locked ? `<span class="part-tile-lock" role="img" aria-label="Checked out" title="Checked out">${PART_ATTRIBUTE_LOCK_ICON}</span>` : ''}</span></td>
      <td class="number"><div class="part-tile-identity"><a href="#/part/${encodeURIComponent(part.id)}">${escape(part.number)}/${escape(part.latest_label)}</a><span class="state state-${escape(part.latest_state)}">${escape(statusName(part.latest_state))}</span></div></td>
      <td><span class="part-tile-name">${escape(part.name)}</span>${part.document_class && part.document_class !== 'normal' ? classBadge(part.document_class) : ''}${part.tags.length ? tagChips(part.tags) : ''}</td>
      <td>${escape(part.part_type)}</td>
      <td>${categoryText(part)}</td>
      <td class="mono">${escape(part.mpn) || '<span class="muted">—</span>'}</td>
      <td>${escape(part.latest_label)}</td>
      <td><span class="state state-${escape(part.latest_state)}">${escape(statusName(part.latest_state))}</span></td>
      <td class="actions"><button class="link inspect-part" aria-label="Inspect ${escape(part.number)}" aria-pressed="false">Properties</button></td>
    </tr>`;
}

function updatePartsSummary() {
  const first = partsPageIndex * Number($('parts-page-size').value) + 1;
  $('parts-count').textContent = listedParts.length ? `Showing ${first}–${first + listedParts.length - 1}` : '0 parts';
  refreshPartsBatch();
  updatePartSelection();
  selectPartSummary(selectedPartId);
}

function selectPartSummary(id, reveal = false) {
  const part = listedParts.find(p => p.id === id);
  selectedPartId = part ? id : null;
  for (const row of $('parts-rows').rows) {
    const selected = row.dataset.partId === selectedPartId;
    row.classList.toggle('selected', selectedParts.has(row.dataset.partId));
    row.querySelector('.inspect-part').setAttribute('aria-pressed', String(selected));
  }
  if (!part) {
    $('selection-content').innerHTML = '<p class="selection-empty">Select a row to inspect its properties. Open a part number to work with its revisions.</p>';
    return;
  }
  return Workbench.catalog(part.id, reveal);
}

$('parts-rows').addEventListener('click', event => {
  if (event.target.closest('button.tag')) return;
  const row = event.target.closest('tr[data-part-id]');
  if(!row)return;
  const id=row.dataset.partId,index=listedParts.findIndex(part=>part.id===id);
  const checkbox=event.target.closest('.part-select');
  if(partsBatchRunning||partsSelecting){if(checkbox)event.preventDefault();return;}
  if(event.shiftKey&&partsSelectionAnchor!==null) {
    for(const part of listedParts.slice(Math.min(index,partsSelectionAnchor),Math.max(index,partsSelectionAnchor)+1))selectedParts.set(part.id,part.number);
  } else if(checkbox||event.ctrlKey||event.metaKey) {
    if(selectedParts.has(id))selectedParts.delete(id);else selectedParts.set(id,listedParts[index].number);
  }
  partsSelectionAnchor=index;updatePartSelection();
  if(!checkbox){event.preventDefault();selectPartSummary(id,true);}
});


$('parts-rows').addEventListener('dblclick', event => {
  if (partsBatchRunning || partsSelecting || event.ctrlKey || event.metaKey || event.shiftKey
      || event.target.closest('input, select, textarea, button, label')) return;
  const row = event.target.closest('tr[data-part-id]');
  const part = listedParts.find(part => part.id === row?.dataset.partId);
  if (!part) return;
  event.preventDefault();
  location.hash = `#/part/${encodeURIComponent(part.id)}/${encodeURIComponent(part.latest_revision_id)}/summary`;
});

function updatePartSelection() {
  const busy=partsBatchRunning||partsSelecting||partsPageBusy;
  $('parts-selection-count').textContent=`${selectedParts.size} selected`;
  let loadedSelected=0;
  for(const row of $('parts-rows').rows) {
    const selected=selectedParts.has(row.dataset.partId);
    row.classList.toggle('selected',selected);
    const checkbox=row.querySelector('.part-select');checkbox.checked=selected;checkbox.disabled=busy;
    if(selected)loadedSelected++;
  }
  $('parts-select-all').checked=listedParts.length>0&&loadedSelected===listedParts.length;
  $('parts-select-all').indeterminate=loadedSelected>0&&loadedSelected<listedParts.length;
  $('parts-select-all').disabled=busy||!listedParts.length;
  $('parts-select-matching').disabled=busy;
  $('parts-clear-selection').disabled=busy||!selectedParts.size;
  $('parts-force-resave').disabled=busy||!selectedParts.size||!me?.can_author;
}
$('parts-select-all').addEventListener('change',()=>{
  for(const part of listedParts)if($('parts-select-all').checked)selectedParts.set(part.id,part.number);else selectedParts.delete(part.id);
  updatePartSelection();
});
$('parts-clear-selection').addEventListener('click',()=>{selectedParts.clear();partsSelectionAnchor=null;updatePartSelection();});
$('parts-select-matching').addEventListener('click',()=>act(async()=>{
  partsSelecting=true;updatePartSelection();
  const query=partsQuery,generation=partsGeneration;let next=null;
  try {
    selectedParts.clear();
    do {
      const page=await api('GET',`/api/parts?${query}&limit=${PARTS_PAGE}${next?`&after=${encodeURIComponent(next)}`:''}`);
      if(generation!==partsGeneration)return;
      for(const part of page.parts)selectedParts.set(part.id,part.number);
      next=page.next;updatePartSelection();
    } while(next);
  } finally {partsSelecting=false;updatePartSelection();}
}));
$('parts-force-resave').addEventListener('click',()=>act(forceResaveSelectedParts));
function restorePartBatch() {
  if(partsBatchUser===me.id)return;
  partsBatchUser=me.id;partsBatchReport=null;partsBatchOffset=0;
  try {partsBatchReport=JSON.parse(localStorage.getItem(`plm.parts.resave:${me.id}`));}catch {}
}
async function forceResaveSelectedParts() {
  if(partsBatchRunning||!selectedParts.size)return;
  partsBatchRunning=true;updatePartSelection();
  $('parts-batch-status').textContent='Adding selected parts to the bake queue…';
  const labels=new Map(selectedParts);
  try {
    const report=await api('POST','/api/bake/resave',{parts:[...labels.keys()]});
    partsBatchOffset=0;
    partsBatchReport={...report,jobs:report.jobs.map(job=>({id:job.id})),failures:report.failures.map(f=>({...f,number:labels.get(f.part_id)||f.part_id}))};
    partsBatchUser=me.id;
    try {localStorage.setItem(`plm.parts.resave:${me.id}`,JSON.stringify(partsBatchReport));}catch {}
    const counts={pending:0,claimed:0,done:0,failed:0,waiting:0};
    for(const job of report.jobs){counts[job.status]++;if(job.status==='pending'&&job.waiting_on_checkout)counts.waiting++;}
    drawPartsBatch({jobs:report.jobs.slice(0,50),total:report.jobs.length,counts});
  } finally {partsBatchRunning=false;updatePartSelection();}
}
function drawPartsBatch(page) {
  if(!partsBatchReport)return;
  const {counts}=page,failures=partsBatchReport.failures;
  const total=page.total+failures.length;
  partsBatchOffset=Math.min(partsBatchOffset,Math.floor(Math.max(0,total-1)/50)*50);
  const tracked=partsBatchOffset<page.total?page.jobs:[];
  const shownFailures=failures.slice(Math.max(0,partsBatchOffset-page.total),Math.max(0,partsBatchOffset+50-page.total));
  $('parts-batch-status').textContent=`${counts.pending} queued, ${counts.claimed} running, ${counts.done} completed, ${counts.failed+failures.length} failed${counts.waiting?`, ${counts.waiting} waiting for checkout`:''}.`;
  $('parts-batch-results').hidden=false;
  $('parts-batch-result-list').innerHTML=tracked.map(job=>`<li${job.status==='failed'?' class="error"':''}>${escape(job.number)}: ${escape(job.status==='done'?(job.error||'Resaved model and thumbnail'):job.status==='claimed'?'Baking…':job.status==='failed'?job.error:job.waiting_on_checkout?`Waiting for ${job.locked_by} to check in`:'Queued for bake worker')}</li>`).join('')
    +shownFailures.map(f=>`<li class="error">${escape(f.number)}: ${escape(f.error)}</li>`).join('');
  $('parts-batch-page-status').textContent=`Page ${Math.floor(partsBatchOffset/50)+1} of ${Math.max(1,Math.ceil(total/50))} · ${total} results`;
  $('parts-batch-prev').disabled=partsBatchPolling||partsBatchOffset===0;
  $('parts-batch-next').disabled=partsBatchPolling||partsBatchOffset+50>=total;
}
async function refreshPartsBatch() {
  if(!me||document.hidden||partsBatchRunning||partsBatchPolling||$('view-parts').hidden)return;
  restorePartBatch();if(!partsBatchReport)return;
  partsBatchPolling=true;
  $('parts-batch-prev').disabled=true;$('parts-batch-next').disabled=true;
  const batch=partsBatchReport;
  try {
    const page=await api('POST','/api/bake/jobs/progress',{ids:batch.jobs.map(job=>job.id),offset:partsBatchOffset,limit:50});
    if(batch!==partsBatchReport)return;
    partsBatchPolling=false;drawPartsBatch(page);
  }catch {} finally {partsBatchPolling=false;}
}
for(const [id,step] of [['parts-batch-prev',-50],['parts-batch-next',50]]) {
  $(id).addEventListener('click',()=>{if(partsBatchPolling)return;partsBatchOffset+=step;refreshPartsBatch();});
}
setInterval(refreshPartsBatch,5000);

const OBJECT_TABS = [['summary', 'Summary'], ['revisions', 'Revisions'], ['structure', 'Structure'], ['instructions', 'Instructions'], ['review', 'Review'], ['attachments', 'Attachments'], ['sourcing', 'Sourcing'], ['history', 'History']];
let objectTab = 'summary';
$('object-tabs').innerHTML = OBJECT_TABS.map(([id, label]) => `<button type="button" role="tab" id="object-tab-${id}" data-object-tab="${id}" aria-controls="object-panel-${id}" aria-selected="false">${label}</button>`).join('');
for (const [id] of OBJECT_TABS) {
  const panel = document.querySelector(`[data-object-panel="${id}"]`);
  panel.id = panel.id || `object-panel-${id}`;
  $(`object-tab-${id}`).setAttribute('aria-controls', panel.id);
  panel.setAttribute('role', 'tabpanel');
  panel.setAttribute('aria-labelledby', `object-tab-${id}`);
}
function selectObjectTab(id, {load=true}={}) {
  objectTab = id;
  for (const button of $('object-tabs').querySelectorAll('button')) {
    const active = button.dataset.objectTab === id;
    button.setAttribute('aria-selected', String(active));
    button.tabIndex = active ? 0 : -1;
  }
  for (const panel of document.querySelectorAll('[data-object-panel]')) panel.classList.toggle('active', panel.dataset.objectPanel === id);
  if(load && currentPart && !$('view-part').hidden && partPanels && !partPanels.loaded.has(id)) {
    const state=partPanels;
    // Use the navigation queue so a loader's global helpers cannot write
    // another part's panels if the user switches pages during a request.
    routeQueue=routeQueue.catch(()=>{}).then(async()=>{
      if(partPanels!==state || $('view-part').hidden || objectTab!==id)return;
      await act(async()=>{await loadPartPanel(id,state);OpenPages.partPanelReady(id);});
    });
  }
}
$('object-tabs').addEventListener('click', event => {
  const tab = event.target.closest('[data-object-tab]');
  if (tab) selectObjectTab(tab.dataset.objectTab);
});
$('object-tabs').addEventListener('keydown', event => {
  if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
  event.preventDefault();
  const index = OBJECT_TABS.findIndex(([id]) => id === objectTab);
  const next = event.key === 'Home' ? 0 : event.key === 'End' ? OBJECT_TABS.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : -1) + OBJECT_TABS.length) % OBJECT_TABS.length;
  selectObjectTab(OBJECT_TABS[next][0]);
  $(`object-tab-${objectTab}`).focus();
});
selectObjectTab('summary');

$('menu-change-password').addEventListener('click', () => {
  if (location.hash === '#/account/password') act(route);
});
$('shell-back').addEventListener('click', () => history.back());
$('shell-refresh').addEventListener('click', () => act(route));
$('menu-new-part').addEventListener('click', () => $('new-part').click());
for (const menu of document.querySelectorAll('.command-menu')) {
  menu.addEventListener('toggle', () => {
    if (menu.open) for (const other of document.querySelectorAll('.command-menu')) if (other !== menu) other.open = false;
  });
  menu.addEventListener('click', event => { if (event.target.closest('a, button')) menu.open = false; });
}
document.addEventListener('click', event => {
  if (!event.target.closest('.command-menu')) for (const menu of document.querySelectorAll('.command-menu')) menu.open = false;
});
document.addEventListener('keydown', event => {
  if (event.key === 'Escape') for (const menu of document.querySelectorAll('.command-menu[open]')) { menu.open = false; menu.querySelector('summary').focus(); }
});

let searchTimer = null;
for (const id of ['search', 'filter-tag']) {
  $(id).addEventListener('input', () => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => act(renderParts), 150);
  });
}
$('filter-geometry').addEventListener('change', () => act(renderParts));
$('filter-thumbnail').addEventListener('change', () => act(renderParts));
$('filter-category').addEventListener('change', () => act(renderParts));
$('filter-company').addEventListener('change', () => act(renderParts));

// A tag chip anywhere filters the parts list to that tag.
document.addEventListener('click', (event) => {
  const chip = event.target.closest('button.tag');
  if (!chip) return;
  event.preventDefault();
  $('filter-tag').value = chip.dataset.tag;
  if (location.hash.startsWith('#/parts')) act(renderParts);
  else location.hash = '#/parts';
});

// ----------------------------------------------------------------- one part

let partPanels = null;
async function loadPartPanel(tab, state=partPanels) {
  if(!state || state.loaded.has(tab))return;
  const detail=state.detail;
  const panels=[...document.querySelectorAll(`[data-object-panel="${tab}"]`)];
  for(const panel of panels){
    panel.inert=true;panel.dataset.partLoading='true';panel.setAttribute('aria-busy','true');
    if(!panel.querySelector(':scope > .part-load-status')){
      const status=document.createElement('p');status.className='part-load-status';status.textContent='Loading…';panel.prepend(status);
    }
  }
  try {
    switch(tab) {
      case 'summary': await Promise.all([renderDetails(detail),renderSeed(detail),loadSummaryFields(detail,state.revision)]);break;
      case 'revisions': await loadRevisionFields(detail);break;
      case 'structure': await renderStructure(detail);break;
      case 'attachments': await renderAttachments(detail);break;
      case 'review': await renderReview(detail);break;
      case 'history': await renderHistory(detail);break;
      case 'instructions': await renderInstructions(detail);break;
      case 'sourcing': renderSourcing(detail);break;
    }
    state.loaded.add(tab);
    for(const panel of panels)delete panel.dataset.partPending;
  } catch(error) {
    for(const panel of panels)panel.querySelector(':scope > .part-load-status').textContent=`Could not load this view: ${error.message}. Select the view again to retry.`;
    throw error;
  } finally {
    for(const panel of panels){panel.inert=false;delete panel.dataset.partLoading;panel.removeAttribute('aria-busy');if(state.loaded.has(tab))panel.querySelector(':scope > .part-load-status')?.remove();}
  }
}
async function renderPart(id, selectedRevision, requestedTab) {
  const detail = await api('GET', `/api/parts/${encodeURIComponent(id)}`);
  // The editor belongs to one part's document; opening another part closes it
  // rather than leaving the last part's text under this part's heading.
  if (editorKey && !editorKey.startsWith(`part/${idSegment(detail.id)}/`)) {
    $('editor').hidden = true;
    editorKey = null;
  }
  const targetTab=requestedTab || (currentPart?.id===detail.id ? objectTab : 'summary');
  currentPart = detail;
  if (selectedRevision && detail.revision_views.some(r => r.id === selectedRevision)) {
    structure.part = detail.id; structure.revision = selectedRevision;
    attaching.part = detail.id; attaching.revision = selectedRevision; reviewRevision = selectedRevision;
  }
  const cadRevision = detail.revision_views.find(r => r.id === selectedRevision) || detail.revision_views.at(-1);
  $('part-open-cad').innerHTML = cadRevision ? openInCadButton(detail.id, cadRevision.id, cadRevision.editable ? 'Edit in CAD' : 'Open in CAD') : '';
  $('part-thumb').innerHTML = thumb(detail.thumbnail_url, 'lg');
  $('part-start-workflow').onclick = () => {
    const revision = $('summary-revision').value || partPanels.revision;
    location.hash = `#/workflows/${encodeURIComponent(detail.id)}/${encodeURIComponent(revision)}`;
  };
  $('part-number').textContent = detail.number;
  // Right-click the heading to copy the part (Workbench's context menu).
  Object.assign($('part-number').closest('h1').dataset, { copyKind: 'part', copyPart: detail.id, copyRevision: '', copyLabel: detail.number });
  $('part-name').textContent = detail.name;
  $('part-meta').innerHTML =
    `${escape(detail.part_type)}${detail.document_class && detail.document_class !== 'normal' ? ` · ${classBadge(detail.document_class)}` : ''} · created ${escape(when(detail.created_at))}`
    + (detail.description ? ` · ${escape(detail.description)}` : '');
  partPanels={detail,revision:selectedRevision || defaultRevision(detail),loaded:new Set()};
  revisionOptions($('revision-field-revision'),detail,partPanels.revision);
  for(const panel of document.querySelectorAll('[data-object-panel]'))panel.dataset.partPending='true';
  $('family-panel').hidden=detail.document_class!=='family';
  $('template-panel').hidden=detail.document_class!=='template';

  const openDraft = detail.revision_views.some((r) => r.editable);
  const blocked = openDraft && !detail.multiple_open_drafts;
  $('new-rev').disabled = blocked;
  $('new-rev-label').disabled = blocked;
  $('new-rev-label').placeholder = detail.suggested_label;
  $('new-rev-note').textContent = blocked
    ? 'A revision is still open, and this server allows one at a time. Use a workflow to release it, or delete it first.'
    : `Labels are free text. Leave it empty to use ${detail.suggested_label}.`
      + (openDraft ? ' The new revision starts from the released document, not from the open one.' : '');

  $('rev-rows').innerHTML = detail.revision_views.map((rev) => {
    const held = rev.locked_by
      ? `${escape(rev.locked_by)}${rev.locked_by_me ? ' (you)' : ''}<br><span class="muted">${when(rev.locked_at)}</span>`
      : '—';
    return `
      <tr data-revision-id="${escape(rev.id)}" data-copy-kind="part" data-copy-part="${escape(currentPart.id)}" data-copy-revision="${escape(rev.id)}" data-copy-label="${escape(`${currentPart.number} rev ${rev.label}`)}">
        <td><span class="rev-label">${revThumb(rev)}<strong>${escape(rev.label)}</strong></span>${revisionContext(rev)}</td>
        <td><span class="state state-${escape(rev.lifecycle)}">${escape(statusName(rev.lifecycle))}</span></td>
        <td>${reviewCell(rev)}</td>
        <td>${held}</td>
        <td class="actions">${actions(rev)}</td>
      </tr>`;
  }).join('');

  for (const button of $('rev-rows').querySelectorAll('button[data-do]')) {
    button.addEventListener('click', () => onRevisionAction(button.dataset.do, button.dataset.rev));
  }
  selectObjectTab(targetTab,{load:false});
  show('part');
  await loadPartPanel(targetTab);
  Workbench.partChanged(detail);
}

function revThumb(rev) {
  const t = rev.thumbnail;
  if (!t) return thumb('', 'xs', 'No picture yet');
  if (!t.current) return thumb('', 'xs', 'The picture is of an older save; the next save from CAD makes a new one');
  return thumb(t.url, 'xs', `Revision ${rev.label} preview`);
}

function actions(rev) {
  const out = [];
  const advanced = [];
  const rid = escape(rev.id);
  const cad = openInCadButton(currentPart.id, rev.id);
  if (cad) out.push(cad);
  // An ordinary part's motion study, published at a save from the CAD app:
  // the player page the PLM serves (instructions have their own section).
  const full = (currentPart.revisions || []).find((r) => r.id === rev.id);
  if (full?.player && currentPart.document_class !== 'instructions') {
    out.push(`<a class="button link" href="/motion/${encodeURIComponent(currentPart.number)}/${encodeURIComponent(rev.id)}" target="_blank" rel="noopener">Open motion player</a>`);
  }
  out.push(`<a class="button link" href="#/workflows/${encodeURIComponent(currentPart.id)}/${encodeURIComponent(rev.id)}">Start workflow</a>`);
  if (rev.editable) {
    if (!rev.locked_by && me.can_author) out.push(`<button class="link" data-do="checkout" data-rev="${rid}">Check out</button>`);
    if (rev.locked_by_me) {
      advanced.push(`<button class="link" data-do="edit" data-rev="${rid}">Edit model JSON</button>`);
      out.push(`<button class="link" data-do="checkin" data-rev="${rid}">Check in</button>`);
    } else if (rev.locked_by && me.can_checkin) {
      out.push(`<button class="link danger" data-do="break" data-rev="${rid}">Break lock</button>`);
    }
    if (rev.lifecycle === 'draft' && me.can_author && statusEnabled('inreview')) out.push(`<button class="link" data-do="submit" data-rev="${rid}">Submit for review</button>`);
    if (rev.lifecycle === 'inreview' && me.can_author) out.push(`<button class="link" data-do="withdraw" data-rev="${rid}">Withdraw</button>`);

    if (me.can_author) out.push(`<button class="link" data-do="delete" data-rev="${rid}">Delete</button>`);
  } else {
    advanced.push(`<button class="link" data-do="view" data-rev="${rid}">View model JSON</button>`);
    if (rev.lifecycle === 'released' && me.can_checkin && statusEnabled('obsolete')) {
      out.push(`<button class="link" data-do="obsolete" data-rev="${rid}">Obsolete</button>`);
    }
  }
  if (advanced.length) out.push(`<details class="revision-advanced"><summary>Advanced</summary>${advanced.join(' ')}</details>`);
  return out.join(' ');
}

// A revision of the part on the page, as people read it.
function revisionLabel(revisionId) {
  return currentPart.revisions.find((r) => r.id === revisionId)?.label || revisionId;
}

function onRevisionAction(action, revisionId) {
  const part = currentPart.id;
  const base = `/api/parts/${encodeURIComponent(part)}/revisions/${encodeURIComponent(revisionId)}`;
  act(async () => {
    switch (action) {
      case 'checkout':
        await api('POST', `${base}/checkout`, { client_id: 'web' });
        break;
      case 'checkin':
        await api('POST', `${base}/checkin`, { force: false });
        break;
      case 'break':
        if (!confirm('Break this lock? The holder may have unsaved work — their edit stays in their app and is NOT written here.')) return;
        await api('POST', `${base}/checkin`, { force: true });
        break;
      case 'submit':
        await openSubmit(revisionId);
        return;
      case 'withdraw':
        if (!confirm('Withdraw this revision from review? Its review ends, and it goes back to Draft.')) return;
        showWarnings(await api('POST', `${base}/state`, { to: 'draft' }));
        break;
      case 'obsolete':
        if (!confirm(await UsedBy.ask(api, part, revisionId, revisionLabel(revisionId), 'obsolete'))) return;
        showWarnings(await api('POST', `${base}/state`, { to: 'obsolete' }));
        break;
      case 'delete':
        if (!confirm(await UsedBy.ask(api, part, revisionId, revisionLabel(revisionId), 'delete'))) return;
        await api('DELETE', base);
        break;
      case 'edit':
      case 'view':
        await openEditor(revisionId, action === 'edit');
        return;
    }
    await renderPart(part);
  });
}

// ------------------------------------------------------------------ editor

let editorKey = null;

async function openEditor(revisionId, writable) {
  const rev = currentPart.revision_views.find((r) => r.id === revisionId);
  editorKey = rev.document_key;
  const body = await api('GET', `/api/store/doc/${rev.document_key.replaceAll('%', '%25')}`);
  $('editor').hidden = false;
  $('editor-key').textContent = `${currentPart.number}/${rev.label}`;
  $('editor-body').value = body === null ? '' : (typeof body === 'string' ? body : JSON.stringify(body, null, 2));
  $('editor-body').readOnly = !writable;
  $('editor-save').hidden = !writable;
  $('editor-note').textContent = writable
    ? 'Advanced model editing. Use Edit in CAD for normal design changes.'
    : `Revision ${rev.label} is shown read-only${rev.locked_by ? `; checked out by ${rev.locked_by}` : ''}. Saved changes remain visible.`;
  $('editor-status').textContent = '';
  $('editor').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

$('editor-save').addEventListener('click', () => act(async () => {
  await api('PUT', `/api/store/doc/${editorKey.replaceAll('%', '%25')}`, $('editor-body').value);
  $('editor-status').textContent = 'Saved.';
  OpenPages.saved();
  await renderPart(currentPart.id);
}));

// Load a CAD file (.fbrep, .tbrep, .nbrep) from disk into the editor: how a
// family or a template made in the file-based CAD app comes into the PLM
// before the CAD app is wired to it.
$('editor-file').addEventListener('change', () => act(async () => {
  const file = $('editor-file').files[0];
  if (!file) return;
  const text = await file.text();
  JSON.parse(text); // refuse a file that is not a document before it reaches the box
  $('editor-body').value = text;
  $('editor-status').textContent = `loaded ${file.name} — not saved yet`;
  $('editor-file').value = '';
}));

// The import rewrote a document the editor may be showing. Saving the stale
// text would silently undo the import, so the editor re-reads it.
async function reloadEditor(key) {
  if ($('editor').hidden || editorKey !== key) return;
  const body = await api('GET', `/api/store/doc/${key.replaceAll('%', '%25')}`);
  $('editor-body').value = body === null ? '' : (typeof body === 'string' ? body : JSON.stringify(body, null, 2));
  $('editor-status').textContent = 'reloaded: the import changed this document';
}

$('editor-close').addEventListener('click', () => {
  $('editor').hidden = true;
  editorKey = null;
});

// --------------------------------------------------------------- new part

let partTypes = [];

// The number field follows the chosen type's mode: a counter owns its numbers,
// free text and pattern types need one typed, a script may take one or not.
function syncNumberField() {
  const kind = partTypes.find((t) => t.id === $('np-type').value);
  const mode = kind ? kind.mode : { kind: 'counter' };
  const input = $('np-number');
  input.disabled = mode.kind === 'counter';
  input.required = mode.kind === 'free' || mode.kind === 'pattern';
  if (mode.kind === 'counter') input.value = '';
  input.placeholder = mode.kind === 'counter' ? kind.next_number
    : mode.kind === 'pattern' ? mode.regex
    : mode.kind === 'script' ? 'optional — the script decides'
    : 'e.g. the ERP number';
  $('np-number-note').innerHTML = {
    counter: `Allocated by the counter. The next is <span class="mono">${escape(kind ? kind.next_number : '')}</span>.`,
    free: 'Type any number. It must not already be in use.',
    pattern: `Must match <code>${escape(mode.regex)}</code> in full.`,
    script: `<code>${escape(mode.script)}</code> decides. It sees what you type here, if anything.`,
  }[mode.kind] || '';
}

$('new-part').addEventListener('click', () => act(async () => {
  partTypes = await api('GET', '/api/part-types');
  $('np-type').innerHTML = partTypes
    .map((t) => `<option value="${escape(t.id)}">${escape(t.name)} (${escape(modeText(t.mode).replace(/<[^>]+>/g, ''))})</option>`)
    .join('');
  syncNumberField();
  await loadCategories();
  // Start in the category the list is filtered to, if it is one.
  const filtered = $('filter-category').value;
  categoryOptions($('np-category'), { blank: '— none —' });
  $('np-category').value = categories.some((c) => c.id === filtered) ? filtered : '';
  await syncAttrForm($('np-category').value, $('np-attrs'), {});
  $('new-part-dialog').showModal();
}));

$('np-category').addEventListener('change', () => act(() => syncAttrForm($('np-category').value, $('np-attrs'), readAttrForm($('np-attrs')))));

$('np-type').addEventListener('change', syncNumberField);

$('new-part-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'create') return;
  event.preventDefault();
  act(async () => {
    const part = await api('POST', '/api/parts', {
      part_type: $('np-type').value,
      number: $('np-number').value,
      name: $('np-name').value,
      document_class: $('np-class').value,
      category: $('np-category').value,
      description: $('np-description').value,
      label: $('np-label').value,
      tags: splitTags($('np-tags').value),
      attributes: readAttrForm($('np-attrs')),
    });
    $('new-part-dialog').close();
    for (const id of ['np-number', 'np-name', 'np-category', 'np-tags', 'np-description', 'np-label']) $(id).value = '';
    $('np-attrs').innerHTML = '';
    $('np-class').value = 'normal';
    location.hash = `#/part/${encodeURIComponent(part.id)}`;
  });
});

$('new-rev-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    await api('POST', `/api/parts/${encodeURIComponent(currentPart.id)}/revisions`, {
      label: $('new-rev-label').value,
    });
    $('new-rev-label').value = '';
    await renderPart(currentPart.id);
  });
});

// ------------------------------------------------------------------ catalog

let categories = [];
let categoriesLoaded = false;
let categoriesEtag = '', categoriesUser = null, categoriesRequest = null;

async function loadCategories() {
  if(categoriesUser!==me.id){categoriesUser=me.id;categoriesEtag='';categoriesLoaded=false;categories=[];}
  if(categoriesRequest)return categoriesRequest;
  const user=me.id;
  categoriesRequest=(async()=>{
    const response=await fetch('/api/categories',{credentials:'same-origin',headers:categoriesEtag?{'If-None-Match':categoriesEtag}:{}});
    if(response.status===304)return categories;
    const payload=await response.json();
    if(!response.ok)throw new Error(payload.error || 'Could not load categories.');
    if(me?.id!==user)return categories;
    categories=payload;categoriesEtag=response.headers.get('ETag') || '';categoriesLoaded=true;
    return categories;
  })();
  try{return await categoriesRequest;}finally{categoriesRequest=null;}
}

const indent = (depth) => '\u00a0\u00a0\u00a0'.repeat(depth);

// Fill a <select> with the tree, indented. `blank` adds a first option with
// value '' and that text; `exclude` drops those ids.
function categoryOptions(select, { blank, exclude } = {}) {
  const skip = exclude || new Set();
  select.innerHTML = (blank !== undefined ? `<option value="">${escape(blank)}</option>` : '')
    + categories
      .filter((c) => !skip.has(c.id))
      .map((c) => `<option value="${escape(c.id)}">${indent(c.depth)}${escape(c.name)}</option>`)
      .join('');
}

function fillCategoryFilter() {
  const select = $('filter-category');
  const current = select.value;
  categoryOptions(select, { blank: 'All categories' });
  select.insertAdjacentHTML('beforeend', '<option value="_none">Uncategorized</option>');
  select.value = [...select.options].some((o) => o.value === current) ? current : '';
}

// A category and every category beneath it, by id.
function subtree(id) {
  const out = new Set([id]);
  let grew = true;
  while (grew) {
    grew = false;
    for (const c of categories) {
      if (c.parent && out.has(c.parent) && !out.has(c.id)) { out.add(c.id); grew = true; }
    }
  }
  return out;
}

// How a part's category reads in a list: its path, or the old free text that
// names no category, marked as such.
function categoryText(part) {
  if (part.category_path) return escape(part.category_path);
  if (part.category) return `<span class="muted" title="Not a catalog category">${escape(part.category)} ?</span>`;
  return '<span class="muted">—</span>';
}

const tagChips = (tags) => tags.map((t) => `<button class="tag" data-tag="${escape(t)}" title="Show parts tagged ${escape(t)}">${escape(t)}</button>`).join('');
const splitTags = (text) => text.split(',').map((t) => t.trim()).filter(Boolean);

function typeText(def) {
  switch (def.type) {
    case 'number': return def.unit ? `number (${escape(def.unit)})` : 'number';
    case 'bool': return 'yes / no';
    case 'enum': return `one of ${def.values.map(escape).join(', ')}`;
    default: return 'text';
  }
}

function valueText(def, value) {
  if (value === undefined || value === null || value === '') return '';
  if (def && def.type === 'bool') return value ? 'yes' : 'no';
  if (def && def.type === 'number' && def.unit) return `${escape(value)} ${escape(def.unit)}`;
  return escape(value);
}

// The input for one attribute of a schema, holding `value`.
function attrInput(def, value) {
  const key = escape(def.key);
  const v = value === undefined || value === null ? '' : value;
  const req = def.required ? ' <span class="req" title="Needed before a release">*</span>' : '';
  let control;
  if (def.type === 'number') {
    control = `<span class="unit"><input type="number" step="any" data-attr="${key}" value="${escape(v)}">${def.unit ? `<span>${escape(def.unit)}</span>` : ''}</span>`;
  } else if (def.type === 'bool') {
    control = `<select data-attr="${key}">
      <option value="">—</option>
      <option value="true" ${v === true ? 'selected' : ''}>yes</option>
      <option value="false" ${v === false ? 'selected' : ''}>no</option></select>`;
  } else if (def.type === 'enum') {
    control = `<select data-attr="${key}"><option value="">—</option>${def.values
      .map((option) => `<option ${option === v ? 'selected' : ''}>${escape(option)}</option>`).join('')}</select>`;
  } else {
    control = `<input data-attr="${key}" value="${escape(v)}">`;
  }
  return `<label><span>${escape(def.name)}${req}</span>${control}</label>`;
}

// Draw the attribute inputs for `categoryId`'s schema into `container`.
async function syncAttrForm(categoryId, container, values) {
  if (!categoryId || !categories.some((c) => c.id === categoryId)) {
    container.innerHTML = '';
    return [];
  }
  const schema = await api('GET', `/api/categories/${encodeURIComponent(categoryId)}/schema`);
  container.innerHTML = schema.attributes.map((def) => attrInput(def, values[def.key])).join('');
  return schema.attributes;
}

// The form's values: `{ key: text }`. An empty field is `null` when
// `clearEmpty` (an edit clears it) and left out otherwise (a new part).
function readAttrForm(container, clearEmpty = false) {
  const out = {};
  for (const el of container.querySelectorAll('[data-attr]')) {
    const value = el.value.trim();
    if (value !== '') out[el.dataset.attr] = value;
    else if (clearEmpty) out[el.dataset.attr] = null;
  }
  return out;
}

// -- the part's catalog panel and its edit dialog

const PART_ATTRIBUTE_LOCK_ICON = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="5" y="10" width="14" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>';
function partAttributeEditor(field, value, editable, attributes = '') {
  const lock = editable ? '' : PART_ATTRIBUTE_LOCK_ICON;
  return `<div class="part-attribute-input${editable ? '' : ' is-read-only'}"><span class="attribute-lock" aria-hidden="true"${editable ? '' : ' title="Read-only"'}>${lock}</span>${fieldValueEditor(field, value, !editable, attributes)}</div>`;
}

async function renderDetails(detail) {
  await loadCategories();
  const catalogEditable = me.can_author && !detail.catalog_locked;
  $('part-locked').hidden = !detail.catalog_locked;
  const options = categories.map(c => ({value: c.id, label: c.path || c.name}));
  if (detail.category && !options.some(o => o.value === detail.category)) {
    options.push({value: detail.category, label: `${detail.category} (not in the catalog)`});
  }
  const metadata = [
    {key: 'has_geometry', name: 'Contains 3D geometry', type: 'bool', editable: false},
    {key: 'has_thumbnail', name: 'Has thumbnail', type: 'bool', editable: false},
    {key: 'category', name: 'Category', type: 'enum', options, empty_label: 'Uncategorized', editable: catalogEditable},
    {key: 'tags', name: 'Tags', type: 'text', encoding: 'comma-list', editable: me.can_author},
  ];
  const rows = metadata.map(f => `<dt>${escape(f.name)}</dt><dd>${partAttributeEditor(f, detail[f.key], f.editable, `data-summary-metadata="${escape(f.key)}"`)}</dd>`);
  rows.push(...detail.schema.map(def => {
    const value = detail.attributes[def.key];
    const cell = partAttributeEditor(def, value, catalogEditable, `data-summary-catalog="${escape(def.key)}"`);
    return `<dt>${escape(def.name)}${def.required ? ' <span class="req">*</span>' : ''}</dt><dd>${cell}${def.required && value == null ? '<span class="missing">missing — needed before release</span>' : ''}</dd>`;
  }));
  for (const key of detail.inert) {
    rows.push(`<dt class="muted">${escape(key)}</dt><dd>${partAttributeEditor({name: key, type: 'text'}, detail.attributes[key], false)}
      <span class="muted">Not an attribute of this category; kept, no effect.</span>
      <button type="button" class="ghost" data-summary-clear="${escape(key)}"${catalogEditable ? '' : ' disabled'}>Clear value</button></dd>`);
  }
  $('part-attrs').innerHTML = rows.join('');
  $('part-attrs').hidden = false;
  for (const input of $('part-attrs').querySelectorAll('[data-summary-metadata]')) input.onchange = () => act(async () => {
    const field = metadata.find(f => f.key === input.dataset.summaryMetadata);
    input.disabled = true;
    try { await api('PATCH', `/api/parts/${encodeURIComponent(detail.id)}`, {[field.key]: editedFieldValue(field, input)}); }
    finally { await renderPart(detail.id, $('summary-revision').value); }
  });
  for (const input of $('part-attrs').querySelectorAll('[data-summary-catalog]')) input.onchange = () => act(async () => {
    const def = detail.schema.find(f => f.key === input.dataset.summaryCatalog);
    input.disabled = true;
    try { await api('PATCH', `/api/parts/${encodeURIComponent(detail.id)}`, {attributes: {[def.key]: editedFieldValue(def, input)}}); }
    finally { await renderPart(detail.id, $('summary-revision').value); }
  });
  for (const button of $('part-attrs').querySelectorAll('[data-summary-clear]')) button.onclick = () => act(async () => {
    button.disabled = true;
    try { await api('PATCH', `/api/parts/${encodeURIComponent(detail.id)}`, {attributes: {[button.dataset.summaryClear]: null}}); }
    finally { await renderPart(detail.id, $('summary-revision').value); }
  });
}

// -- the catalog view

let selectedCategory = null;

async function renderCatalog(id) {
  await loadCategories();
  fillCategoryFilter();
  selectedCategory = categories.find((c) => c.id === id) || null;
  $('category-tree').innerHTML = categories.length
    ? categories.map((c) => `
      <li><button class="${selectedCategory && c.id === selectedCategory.id ? 'current' : ''}" data-cat="${escape(c.id)}"
        data-depth="${c.depth}">${escape(c.name)}<span class="count" title="${c.parts} here, ${c.parts_within} including sub-categories">${c.parts_within}</span></button></li>`).join('')
    : '<li class="empty">No categories yet.</li>';
  for (const button of $('category-tree').querySelectorAll('button[data-cat]')) {
    // Set through the CSSOM, not an inline style attribute: the page's CSP allows
    // no inline style.
    button.style.paddingLeft = `${8 + Number(button.dataset.depth) * 16}px`;
    button.addEventListener('click', () => { location.hash = `#/catalog/${encodeURIComponent(button.dataset.cat)}`; });
  }
  categoryOptions($('cn-parent'), { blank: '(top level)' });
  if (selectedCategory) $('cn-parent').value = selectedCategory.id;

  $('category-none').hidden = !!selectedCategory;
  $('category-body').hidden = !selectedCategory;
  if (!selectedCategory) return;
  const c = selectedCategory;
  const schema = await api('GET', `/api/categories/${encodeURIComponent(c.id)}/schema`);
  $('cat-title').textContent = c.path;
  $('cat-parts').href = `#/parts/${encodeURIComponent(c.id)}`;
  $('cat-parts').textContent = `Show parts (${c.parts_within})`;
  $('cat-meta').innerHTML = `${c.parts} part${c.parts === 1 ? '' : 's'} filed here, ${c.parts_within} including sub-categories`;

  const inherited = schema.attributes.filter((a) => a.from !== c.id);
  const nameOf = (id) => (categories.find((x) => x.id === id) || { name: id }).name;
  $('cat-inherited-none').hidden = inherited.length > 0;
  $('cat-inherited-none').textContent = c.parent ? 'No inherited fields are defined by this category’s ancestors.' : 'None. This is a top-level category.';
  $('cat-inherited-table').hidden = inherited.length === 0;
  $('cat-inherited').innerHTML = inherited.map((a) => `
    <tr><td class="mono">${escape(a.key)}</td><td>${escape(a.name)}</td><td>${typeText(a)}</td>
    <td>${a.required ? 'yes' : ''}</td><td><a href="#/catalog/${encodeURIComponent(a.from)}">${escape(nameOf(a.from))}</a></td></tr>`).join('');

  $('cat-name').value = c.name;
  categoryOptions($('cat-parent'), { blank: '(top level)', exclude: subtree(c.id) });
  $('cat-parent').value = c.parent || '';
  $('cat-own').innerHTML = '';
  for (const def of c.attributes) addAttrRow(def);
  syncOwnEmpty();
  for (const el of $('cat-form').querySelectorAll('input, select, button')) el.disabled = !me.is_admin;
}

function syncOwnEmpty() {
  $('cat-own-none').hidden = $('cat-own').children.length > 0;
}

// One editable row of the category's own attributes.
function addAttrRow(def = { key: '', name: '', type: 'text', required: false }) {
  const row = document.createElement('tr');
  const extra = def.type === 'number' ? (def.unit || '') : def.type === 'enum' ? def.values.join(', ') : '';
  row.innerHTML = `
    <td><input class="mono" data-f="key" value="${escape(def.key)}" placeholder="length" aria-label="Key"></td>
    <td><input data-f="name" value="${escape(def.name)}" placeholder="Length" aria-label="Name"></td>
    <td><select data-f="type" aria-label="Type">
      ${['text', 'number', 'bool', 'enum'].map((t) => `<option value="${t}" ${t === def.type ? 'selected' : ''}>${{ text: 'text', number: 'number', bool: 'yes / no', enum: 'list' }[t]}</option>`).join('')}
    </select></td>
    <td><input data-f="extra" value="${escape(extra)}" aria-label="Unit or values"></td>
    <td><input type="checkbox" data-f="required" ${def.required ? 'checked' : ''} aria-label="Required"></td>
    <td class="actions"><button type="button" class="link danger" data-f="remove">Remove</button></td>`;
  const sync = () => {
    const type = row.querySelector('[data-f=type]').value;
    const extraInput = row.querySelector('[data-f=extra]');
    extraInput.disabled = !me.is_admin || (type !== 'number' && type !== 'enum');
    extraInput.placeholder = type === 'number' ? 'unit, e.g. mm' : type === 'enum' ? 'M3, M4, M5' : '';
    if (type !== 'number' && type !== 'enum') extraInput.value = '';
  };
  row.querySelector('[data-f=type]').addEventListener('change', sync);
  row.querySelector('[data-f=remove]').addEventListener('click', () => { row.remove(); syncOwnEmpty(); });
  $('cat-own').appendChild(row);
  sync();
  syncOwnEmpty();
}

function readAttrRows() {
  return [...$('cat-own').children].map((row) => {
    const f = (name) => row.querySelector(`[data-f=${name}]`);
    const type = f('type').value;
    const def = { key: f('key').value.trim(), name: f('name').value.trim(), type, required: f('required').checked };
    if (type === 'number') def.unit = f('extra').value.trim();
    if (type === 'enum') def.values = splitTags(f('extra').value);
    return def;
  });
}

$('cat-add-attr').addEventListener('click', () => addAttrRow());

$('cat-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    const id = selectedCategory.id;
    await api('PATCH', `/api/categories/${encodeURIComponent(id)}`, {
      name: $('cat-name').value,
      parent: $('cat-parent').value,
      attributes: readAttrRows(),
    });
    await renderCatalog(id);
  });
});

$('cat-delete').addEventListener('click', () => act(async () => {
  if (!confirm(`Delete the category ${selectedCategory.path}?`)) return;
  await api('DELETE', `/api/categories/${encodeURIComponent(selectedCategory.id)}`);
  location.hash = '#/catalog';
}));

$('category-new').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    const created = await api('POST', '/api/categories', {
      id: $('cn-id').value,
      name: $('cn-name').value,
      parent: $('cn-parent').value,
    });
    $('cn-id').value = '';
    $('cn-name').value = '';
    location.hash = `#/catalog/${encodeURIComponent(created.id)}`;
  });
});

// -------------------------------------------------------------- part types

async function renderTypes() {
  partTypes = await api('GET', '/api/part-types');
  $('type-rows').innerHTML = partTypes.map((t) => `
    <tr>
      <td class="mono">${escape(t.id)}</td>
      <td>${escape(t.name)}</td>
      <td>${t.mode.kind === 'counter'
        ? `counter <span class="mono">${escape(t.prefix)}</span> + ${t.digits} digits`
        : modeText(t.mode)}</td>
      <td class="mono">${t.mode.kind === 'counter' ? escape(t.next_number) : '<span class="muted">typed or scripted</span>'}</td>
      <td class="actions">${me.is_admin ? `<button class="link" data-type="${escape(t.id)}">Edit</button> <button class="link" data-type-fields="${escape(t.id)}">Fields…</button>` : ''}</td>
    </tr>`).join('');
  for(const button of $('type-rows').querySelectorAll('[data-type-fields]'))button.addEventListener('click',()=>act(()=>openFieldDefinitions(button.dataset.typeFields)));
  for (const button of $('type-rows').querySelectorAll('button[data-type]')) {
    button.addEventListener('click', () => openTypeEditor(button.dataset.type));
  }
}

function previewNumber() {
  const prefix = $('type-prefix').value;
  const digits = Math.min(Math.max(parseInt($('type-digits').value, 10) || 1, 1), 18);
  const start = Math.max(parseInt($('type-start').value, 10) || 1, 1);
  $('type-preview').textContent = prefix + String(start).padStart(digits, '0');
}
for (const id of ['type-prefix', 'type-digits', 'type-start']) {
  $(id).addEventListener('input', previewNumber);
}
previewNumber();

function syncModeFields() {
  const kind = $('type-mode').value;
  for (const el of document.querySelectorAll('#type-form .mode-fields')) el.hidden = el.dataset.mode !== kind;
}
$('type-mode').addEventListener('change', syncModeFields);
syncModeFields();

// The mode object the API takes, from a select and its two fields.
function modeFrom(kind, regex, script) {
  if (kind === 'pattern') return { kind, regex };
  if (kind === 'script') return { kind, script: script || 'part-number.js' };
  return { kind };
}

$('type-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    const kind = $('type-mode').value;
    await api('POST', '/api/part-types', {
      id: $('type-id').value,
      name: $('type-name').value,
      prefix: $('type-prefix').value,
      digits: parseInt($('type-digits').value, 10) || 9,
      start: parseInt($('type-start').value, 10) || 1,
      mode: modeFrom(kind, $('type-regex').value, $('type-script').value),
    });
    for (const id of ['type-id', 'type-name', 'type-prefix', 'type-regex', 'type-script']) $(id).value = '';
    await renderTypes();
  });
});

let editingType = null;

function syncEditFields() {
  for (const el of document.querySelectorAll('#type-edit-form .te-field')) el.hidden = el.dataset.mode !== $('te-mode').value;
}
$('te-mode').addEventListener('change', syncEditFields);

function openTypeEditor(id) {
  editingType = partTypes.find((t) => t.id === id);
  $('te-id').textContent = editingType.id;
  $('te-name').value = editingType.name;
  $('te-mode').value = editingType.mode.kind;
  $('te-regex').value = editingType.mode.regex || '';
  $('te-script').value = editingType.mode.script || '';
  syncEditFields();
  $('type-dialog').showModal();
}

$('type-edit-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'save') return;
  event.preventDefault();
  act(async () => {
    await api('PATCH', `/api/part-types/${encodeURIComponent(editingType.id)}`, {
      name: $('te-name').value,
      mode: modeFrom($('te-mode').value, $('te-regex').value, $('te-script').value),
    });
    $('type-dialog').close();
    await renderTypes();
  });
});

// ------------------------------------------------------------------- users

async function renderUsers() {
  const users = await api('GET', '/api/users');
  $('user-rows').innerHTML = users.map((u) => `
    <tr>
      <td class="mono">${escape(u.username)}</td>
      <td>${escape(u.display_name)}</td>
      <td class="muted">${escape(u.email)}</td>
      <td>${escape(u.groups.join(', '))}</td>
      <td>${u.active ? 'yes' : '<span class="muted">disabled</span>'}</td>
      <td class="actions">
        <button class="link" data-user="${escape(u.id)}" data-do="groups">Groups</button>
        <button class="link" data-user="${escape(u.id)}" data-do="password">Password</button>
        <button class="link" data-user="${escape(u.id)}" data-do="toggle">${u.active ? 'Disable' : 'Enable'}</button>
        <button class="link" data-user="${escape(u.id)}" data-do="sign-out" title="End every browser session of this user">Sign out</button>
      </td>
    </tr>`).join('');

  for (const button of $('user-rows').querySelectorAll('button[data-user]')) {
    button.addEventListener('click', () => onUserAction(button.dataset.do, button.dataset.user, users));
  }
}

function onUserAction(action, id, users) {
  const user = users.find((u) => u.id === id);
  act(async () => {
    if (action === 'groups') {
      const entered = prompt(`Groups for ${user.username} (comma separated)`, user.groups.join(', '));
      if (entered === null) return;
      await api('PATCH', `/api/users/${id}`, {
        groups: entered.split(',').map((g) => g.trim()).filter(Boolean),
      });
    } else if (action === 'password') {
      const entered = prompt(`New password for ${user.username} (at least 8 characters)`);
      if (!entered) return;
      await api('PATCH', `/api/users/${id}`, { password: entered });
    } else if (action === 'toggle') {
      await api('PATCH', `/api/users/${id}`, { active: !user.active });
    } else if (action === 'sign-out') {
      if (!confirm(`Sign ${user.username} out of every browser?`)) return;
      const done = await api('POST', `/api/users/${id}/sign-out`);
      banner('');
      alert(`${user.username}: ${done.sessions_ended} session${done.sessions_ended === 1 ? '' : 's'} ended.`);
    }
    await renderUsers();
  });
}

$('user-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    const groups = [...$('user-form').querySelectorAll('input[type=checkbox]:checked')].map((c) => c.value);
    await api('POST', '/api/users', {
      username: $('user-name').value,
      display_name: $('user-display').value,
      email: $('user-email').value,
      password: $('user-pass').value,
      groups,
    });
    $('user-name').value = '';
    $('user-display').value = '';
    $('user-email').value = '';
    $('user-pass').value = '';
    await renderUsers();
  });
});

// ------------------------------------------------------------------ sourcing

let companies = { manufacturers: [], suppliers: [] };
let companiesLoaded = false;

async function loadCompanies() {
  const [manufacturers, suppliers] = await Promise.all([
    api('GET', '/api/manufacturers'),
    api('GET', '/api/suppliers'),
  ]);
  companies = { manufacturers, suppliers };
  companiesLoaded = true;
  // Whoever loads the lists keeps the parts filter current with them.
  fillCompanyFilter();
}

function fillCompanyFilter() {
  const select = $('filter-company');
  const keep = select.value;
  const group = (label, prefix, list) => list.length
    ? `<optgroup label="${label}">${list.map((c) => `<option value="${prefix}:${escape(c.id)}">${escape(c.name)}</option>`).join('')}</optgroup>`
    : '';
  select.innerHTML = '<option value="">Any maker or supplier</option>'
    + group('Manufacturers', 'm', companies.manufacturers)
    + group('Suppliers', 's', companies.suppliers);
  select.value = [...select.options].some((o) => o.value === keep) ? keep : '';
}

const STATUS_NAMES = { active: 'active', nrnd: 'NRND', obsolete: 'obsolete' };
const link = (url, text) => (url
  ? `<a href="${escape(url)}" target="_blank" rel="noopener noreferrer">${escape(text || url)}</a>`
  : escape(text || ''));
const price = (n) => Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 6 });

function breaksText(offer) {
  if (!offer.price_breaks.length) return '<span class="muted">no price</span>';
  const currency = offer.currency ? ` ${escape(offer.currency)}` : '';
  return offer.price_breaks
    .map((b) => `<span class="break">${b.qty.toLocaleString()}+ <strong>${price(b.unit_price)}</strong></span>`)
    .join(' ') + currency;
}

function renderSourcing(detail) {
  const list = detail.sourcing_view;
  $('sourcing-empty').hidden = list.length > 0;
  const author = me.can_author;
  $('sourcing-list').innerHTML = list.map((mp) => {
    const offers = mp.offers.map((o) => `
      <tr>
        <td>${escape(o.supplier_name)}</td>
        <td class="mono">${link(o.url, o.spn || (o.url ? 'page' : '—'))}</td>
        <td>${breaksText(o)}</td>
        <td>${o.lead_time_days == null ? '—' : `${o.lead_time_days} d`}</td>
        <td>${o.moq == null ? '—' : o.moq.toLocaleString()}</td>
        <td>${o.stock == null ? '—' : o.stock.toLocaleString()}</td>
        <td class="muted">${escape(when(o.updated_at))}</td>
        <td class="actions">${author ? `
          <button class="link" data-src="edit-offer" data-mp="${escape(mp.id)}" data-offer="${escape(o.id)}">Edit</button>
          <button class="link" data-src="delete-offer" data-mp="${escape(mp.id)}" data-offer="${escape(o.id)}">Delete</button>` : ''}</td>
      </tr>`).join('');
    return `
      <div class="mp${mp.preferred ? ' preferred' : ''}">
        <div class="toolbar">
          <strong>${escape(mp.manufacturer_name)}</strong>
          <span class="mono">${escape(mp.mpn)}</span>
          ${mp.preferred ? '<span class="badge badge-preferred">preferred</span>' : ''}
          <span class="badge badge-${escape(mp.status)}">${escape(STATUS_NAMES[mp.status] || mp.status)}</span>
          ${mp.datasheet ? link(mp.datasheet, 'datasheet') : ''}
          <span class="spacer"></span>
          ${author ? `
            <button class="link" data-src="add-offer" data-mp="${escape(mp.id)}">Add offer</button>
            <button class="link" data-src="edit-mp" data-mp="${escape(mp.id)}">Edit</button>
            <button class="link" data-src="delete-mp" data-mp="${escape(mp.id)}">Delete</button>` : ''}
        </div>
        ${mp.notes ? `<p class="muted">${escape(mp.notes)}</p>` : ''}
        ${mp.offers.length ? `
          <div class="table-wrap">
            <table class="offers">
              <thead><tr><th>Supplier</th><th>SPN</th><th>Price each</th><th>Lead</th><th>MOQ</th><th>Stock</th><th>Updated</th><th></th></tr></thead>
              <tbody>${offers}</tbody>
            </table>
          </div>` : '<p class="muted">No supplier offers.</p>'}
      </div>`;
  }).join('');
}

const partBase = () => `/api/parts/${encodeURIComponent(currentPart.id)}/sourcing`;
const findMp = (id) => currentPart.sourcing.find((m) => m.id === id);

function companyOptions(select, list, value) {
  select.innerHTML = list.map((c) => `<option value="${escape(c.id)}">${escape(c.name)}</option>`).join('');
  if (value) select.value = value;
}

let editingMp = null;

async function openMpDialog(mp) {
  await loadCompanies();
  editingMp = mp ? mp.id : null;
  $('mp-title').textContent = mp ? `Edit ${mp.mpn}` : 'Add manufacturer part';
  companyOptions($('mp-manufacturer'), companies.manufacturers, mp && mp.manufacturer);
  $('mp-no-makers').hidden = companies.manufacturers.length > 0;
  $('mp-mpn').value = mp ? mp.mpn : '';
  $('mp-status').value = mp ? mp.status : 'active';
  $('mp-preferred').checked = mp ? mp.preferred : currentPart.sourcing.length === 0;
  $('mp-datasheet').value = mp ? mp.datasheet : '';
  $('mp-notes').value = mp ? mp.notes : '';
  $('mp-dialog').showModal();
}

$('add-mp').addEventListener('click', () => act(() => openMpDialog(null)));

$('mp-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'save') return;
  event.preventDefault();
  act(async () => {
    const body = {
      manufacturer: $('mp-manufacturer').value,
      mpn: $('mp-mpn').value,
      status: $('mp-status').value,
      preferred: $('mp-preferred').checked,
      datasheet: $('mp-datasheet').value,
      notes: $('mp-notes').value,
    };
    if (editingMp) await api('PATCH', `${partBase()}/${encodeURIComponent(editingMp)}`, body);
    else await api('POST', partBase(), body);
    $('mp-dialog').close();
    await renderPart(currentPart.id);
  });
});

let editingOffer = null;

function addBreakRow(qty = '', unitPrice = '') {
  const row = document.createElement('div');
  row.className = 'break-row';
  row.innerHTML = `
    <label>Quantity <input type="number" min="1" step="1" data-f="qty" value="${escape(qty)}"></label>
    <label>Unit price <input type="number" min="0" step="any" data-f="price" value="${escape(unitPrice)}"></label>
    <button type="button" class="link" data-f="remove" aria-label="Remove this price break">Remove</button>`;
  row.querySelector('[data-f=remove]').addEventListener('click', () => row.remove());
  $('of-breaks').appendChild(row);
}

$('of-add-break').addEventListener('click', () => addBreakRow());

async function openOfferDialog(mpId, offer) {
  await loadCompanies();
  editingOffer = { mp: mpId, id: offer ? offer.id : null };
  const mp = findMp(mpId);
  $('of-title').textContent = offer ? `Edit offer for ${mp.mpn}` : `Add an offer for ${mp.mpn}`;
  companyOptions($('of-supplier'), companies.suppliers, offer && offer.supplier);
  $('of-no-suppliers').hidden = companies.suppliers.length > 0;
  $('of-spn').value = offer ? offer.spn : '';
  $('of-url').value = offer ? offer.url : '';
  $('of-currency').value = offer ? offer.currency : 'USD';
  $('of-breaks').innerHTML = '';
  for (const b of (offer ? offer.price_breaks : [])) addBreakRow(b.qty, b.unit_price);
  if (!offer || !offer.price_breaks.length) addBreakRow(1, '');
  $('of-lead').value = offer && offer.lead_time_days != null ? offer.lead_time_days : '';
  $('of-moq').value = offer && offer.moq != null ? offer.moq : '';
  $('of-stock').value = offer && offer.stock != null ? offer.stock : '';
  $('of-notes').value = offer ? offer.notes : '';
  $('offer-dialog').showModal();
}

$('offer-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'save') return;
  event.preventDefault();
  act(async () => {
    // A row with no price is a row nobody filled in, not a free part.
    const price_breaks = [...$('of-breaks').querySelectorAll('.break-row')]
      .map((row) => ({ qty: row.querySelector('[data-f=qty]').value, unit_price: row.querySelector('[data-f=price]').value }))
      .filter((b) => String(b.unit_price).trim() !== '');
    const body = {
      supplier: $('of-supplier').value,
      spn: $('of-spn').value,
      url: $('of-url').value,
      currency: $('of-currency').value,
      price_breaks,
      lead_time_days: $('of-lead').value,
      moq: $('of-moq').value,
      stock: $('of-stock').value,
      notes: $('of-notes').value,
    };
    const base = `${partBase()}/${encodeURIComponent(editingOffer.mp)}/offers`;
    if (editingOffer.id) await api('PATCH', `${base}/${encodeURIComponent(editingOffer.id)}`, body);
    else await api('POST', base, body);
    $('offer-dialog').close();
    await renderPart(currentPart.id);
  });
});

$('sourcing-list').addEventListener('click', (event) => {
  const button = event.target.closest('button[data-src]');
  if (!button) return;
  const { src, mp, offer } = button.dataset;
  act(async () => {
    const found = findMp(mp);
    switch (src) {
      case 'edit-mp':
        return openMpDialog(found);
      case 'add-offer':
        return openOfferDialog(mp, null);
      case 'edit-offer':
        return openOfferDialog(mp, found.offers.find((o) => o.id === offer));
      case 'delete-mp':
        if (!confirm(`Remove ${found.mpn} and its ${found.offers.length} offer(s) from this part?`)) return;
        await api('DELETE', `${partBase()}/${encodeURIComponent(mp)}`);
        break;
      case 'delete-offer':
        if (!confirm('Remove this offer?')) return;
        await api('DELETE', `${partBase()}/${encodeURIComponent(mp)}/offers/${encodeURIComponent(offer)}`);
        break;
    }
    await renderPart(currentPart.id);
  });
});

// -- the manufacturers and suppliers page

function companyRows(list, key) {
  const prefix = key === 'manufacturers' ? 'm' : 's';
  return list.map((c) => `
    <tr>
      <td><strong>${escape(c.name)}</strong>${c.notes ? `<br><span class="muted">${escape(c.notes)}</span>` : ''}</td>
      <td>${c.website ? link(c.website, c.website.replace(/^https?:\/\//, '')) : '<span class="muted">—</span>'}</td>
      <td>${c.parts ? `<button class="link" data-show="${prefix}:${escape(c.id)}" title="Show the parts sourced from ${escape(c.name)}">${c.parts}</button>` : '0'}</td>
      <td class="actions">
        ${me.can_author ? `<button class="link" data-co="edit" data-list="${key}" data-id="${escape(c.id)}">Edit</button>` : ''}
        ${me.is_admin ? `<button class="link" data-co="delete" data-list="${key}" data-id="${escape(c.id)}"
          ${c.uses ? `disabled title="Named by ${c.uses} ${key === 'manufacturers' ? 'manufacturer part' : 'offer'}${c.uses === 1 ? '' : 's'}"` : ''}>Delete</button>` : ''}
      </td>
    </tr>`).join('');
}

// ----------------------------------------------------------------- tools

async function renderTools() {
  const tools = await api('GET', `/api/tools${$('tools-retired').checked ? '?retired=true' : ''}`);
  $('tools-empty').hidden = tools.length > 0;
  $('tools-rows').innerHTML = tools.map((tool) => `<tr data-tool="${escape(tool.id)}"${tool.retired ? ' class="muted"' : ''}>
    <td>${tool.picture_url ? `<img class="tool-picture" src="${escape(tool.picture_url)}" alt="" loading="lazy">` : ''}</td>
    <td>${escape(tool.name)}<span class="attrs-line">${escape(tool.id)}${tool.retired ? ' · retired' : ''}</span></td>
    <td>${escape(tool.kind)}</td><td>${escape(tool.spec)}</td>
    <td class="author-only"><button type="button" class="link" data-tool-edit>Edit</button>
      <button type="button" class="link" data-tool-retire>${tool.retired ? 'Restore' : 'Retire'}</button>
      <label class="link">Picture<input type="file" accept="image/png,image/jpeg,image/webp" data-tool-picture hidden></label></td></tr>`).join('');
  for (const row of $('tools-rows').querySelectorAll('tr')) {
    const id = row.dataset.tool, tool = tools.find((t) => t.id === id);
    row.querySelector('[data-tool-retire]').onclick = () => act(async () => { await api('PATCH', `/api/tools/${id}`, { retired: !tool.retired }); await renderTools(); });
    row.querySelector('[data-tool-edit]').onclick = () => act(async () => {
      const name = prompt('Tool name', tool.name); if (name === null) return;
      const spec = prompt('Spec', tool.spec); if (spec === null) return;
      await api('PATCH', `/api/tools/${id}`, { name, spec }); await renderTools();
    });
    row.querySelector('[data-tool-picture]').onchange = (event) => act(async () => {
      const file = event.target.files[0]; if (!file) return;
      const response = await fetch(`/api/tools/${id}/picture`, { method: 'PUT', body: file, credentials: 'same-origin', headers: { 'Content-Type': file.type, 'X-CSRF-Token': csrfToken } });
      if (!response.ok) throw new Error(await response.text());
      await renderTools();
    });
  }
}
$('tools-retired').addEventListener('change', () => act(renderTools));
$('tool-add').addEventListener('submit', (event) => {
  event.preventDefault();
  const form = event.target;
  act(async () => {
    await api('POST', '/api/tools', { name: form.elements.name.value, kind: form.elements.kind.value, spec: form.elements.spec.value });
    form.reset(); await renderTools();
  });
});

// ----------------------------------------------------------------- jobs floor queue

// The queue polls what moved since its last answer, so a tablet on the
// floor sees another's sign-off without reloading.
const jobsView = { jobs: new Map(), seq: 0, open: null, timer: null };
const canSign = () => (me?.groups || []).some((g) => ['operator', 'author', 'admin'].includes(g));

async function renderJobs(open) {
  const queue = await api('GET', '/api/jobs');
  jobsView.jobs = new Map(queue.jobs.map((job) => [job.id, job]));
  jobsView.seq = queue.seq;
  jobsView.open = open;
  if (open && !jobsView.jobs.has(open)) jobsView.jobs.set(open, await api('GET', `/api/jobs/${encodeURIComponent(open)}`));
  paintJobs();
  clearInterval(jobsView.timer);
  jobsView.timer = setInterval(pollJobs, 5000);
}

async function pollJobs() {
  if (visiblePage?.view !== 'jobs' || document.hidden) return;
  try {
    const moved = await api('GET', `/api/jobs?since=${jobsView.seq}`);
    if (!moved.jobs.length) return;
    for (const job of moved.jobs) jobsView.jobs.set(job.id, job);
    jobsView.seq = moved.seq;
    paintJobs();
  } catch {}
}

function signedCount(job) { return job.steps.filter((s) => s.signed_at).length; }

// A step's field (what its instructions ask to be recorded) as an input of
// the sign-off form: a tick, a dropdown (boxes when several may be picked),
// a line or a box of text, a measurement with its unit and limits, a serial.
// The server reads the values against the same definitions and refuses what
// is missing or out of limits.
function jobFieldLimits(field) {
  const show = (v) => (field.decimals === undefined || field.decimals === null ? String(v) : Number(v).toFixed(field.decimals));
  const has = (v) => typeof v === 'number';
  const unit = (field.unit || '').trim();
  const range = has(field.min) && has(field.max) ? `${show(field.min)}–${show(field.max)}` : has(field.min) ? `min ${show(field.min)}` : has(field.max) ? `max ${show(field.max)}` : '';
  const nominal = has(field.nominal) ? `${show(field.nominal)}${unit ? ` ${unit}` : ''}` : '';
  return nominal && range ? `${nominal}, ${range}` : nominal || (range ? `${range}${unit ? ` ${unit}` : ''}` : '');
}
function jobFieldInput(field) {
  const id = escape(field.id);
  const name = `${escape(field.label || field.id)}${field.required ? ' *' : ''}`;
  const options = [...new Set((field.options || []).map((o) => String(o).trim()).filter(Boolean))];
  const hint = field.hint ? ` <span class="attrs-line">${escape(field.hint)}</span>` : '';
  if (field.kind === 'check') return `<label><input type="checkbox" data-field="${id}" data-kind="check"> ${name}</label>${hint}`;
  if (field.kind === 'choice' && field.multiple) {
    return `<fieldset data-field="${id}" data-kind="multiple"><legend>${name} (mark all that apply)</legend>${options.map((o) => `<label><input type="checkbox" value="${escape(o)}"> ${escape(o)}</label>`).join('')}${field.other ? '<label>Other <input data-other autocomplete="off"></label>' : ''}</fieldset>${hint}`;
  }
  if (field.kind === 'choice') {
    return `<label>${name} <select data-field="${id}" data-kind="choice"><option value="">—</option>${options.map((o) => `<option value="${escape(o)}">${escape(o)}</option>`).join('')}</select></label>${field.other ? `<label>Other <input data-other-of="${id}" autocomplete="off"></label>` : ''}${hint}`;
  }
  if (field.kind === 'text' && field.lines > 1) return `<label>${name} <textarea data-field="${id}" data-kind="text" rows="${Math.min(20, field.lines)}"></textarea></label>${hint}`;
  if (field.kind === 'number') {
    const limits = jobFieldLimits(field);
    return `<label>${name} <input data-field="${id}" data-kind="number" inputmode="decimal" autocomplete="off"> ${escape((field.unit || '').trim())}${limits ? ` <span class="attrs-line">(${escape(limits)})</span>` : ''}</label>${hint}`;
  }
  return `<label>${name} <input data-field="${id}" data-kind="text" autocomplete="off"></label>${hint}`;
}
// The values of a step's field inputs, as the sign-off sends them: only the
// fields that were filled in.
function jobFieldValues(li) {
  const out = [];
  for (const input of li.querySelectorAll('[data-field]')) {
    const id = input.dataset.field;
    let value;
    if (input.dataset.kind === 'check') value = input.checked || undefined;
    else if (input.dataset.kind === 'multiple') {
      const picked = [...input.querySelectorAll('input[type=checkbox]:checked')].map((box) => box.value);
      const other = input.querySelector('[data-other]')?.value.trim();
      if (other) picked.push(other);
      value = picked.length ? picked : undefined;
    } else if (input.dataset.kind === 'choice') {
      value = li.querySelector(`[data-other-of="${CSS.escape(id)}"]`)?.value.trim() || input.value || undefined;
    } else value = input.value.trim() || undefined;
    if (value !== undefined) out.push({ id, value });
  }
  return out;
}
function jobFieldText(entry) {
  const value = entry.value === true ? 'yes' : Array.isArray(entry.value) ? entry.value.join('; ') : String(entry.value);
  return `${value}${entry.unit ? ` ${entry.unit}` : ''}${entry.in_limits === false ? ' (out of limits)' : ''}`;
}

function paintJobs() {
  const live = [...jobsView.jobs.values()].filter((j) => j.status === 'queued' || j.status === 'in_progress').sort((a, b) => a.position - b.position || a.id.localeCompare(b.id));
  $('jobs-empty').hidden = live.length > 0;
  $('jobs-list').innerHTML = live.map((job) => {
    const next = job.steps.find((s) => !s.signed_at);
    return `<button type="button" class="job-card" data-job="${escape(job.id)}"><strong>${escape(job.id)}</strong> ${escape(job.instructions.part)} rev ${escape(job.instructions.revision)}${job.serial ? ` · ${escape(job.serial)}` : ''}
      <span class="attrs-line">${escape(job.status.replace('_', ' '))} · ${signedCount(job)} of ${job.steps.length} steps${next ? ` · next: ${escape(next.title || next.step)}` : ''}</span></button>`;
  }).join('');
  for (const card of $('jobs-list').querySelectorAll('[data-job]')) card.onclick = () => { location.hash = `#/jobs/${encodeURIComponent(card.dataset.job)}`; };
  const job = jobsView.open && jobsView.jobs.get(jobsView.open);
  $('job-detail').hidden = !job;
  $('jobs-list').hidden = !!job;
  $('job-add').hidden = !!job || !me?.can_author;
  if (!job) return;
  $('job-title').textContent = `${job.id}${job.serial ? ` · ${job.serial}` : ''}`;
  $('job-meta').textContent = `${job.instructions.part} rev ${job.instructions.revision} for ${job.assembly.part} rev ${job.assembly.revision} · ${job.status.replace('_', ' ')} · ${signedCount(job)} of ${job.steps.length} steps signed`;
  const next = job.steps.findIndex((s) => !s.signed_at);
  // The queue's poll repaints this list every time any job moves: what is
  // typed into the current step's sign-off form (serials, fields, the note)
  // is carried over the repaint when the same step is still the current one.
  const typedKey = `${job.id}/${job.steps[next]?.step ?? ''}`;
  const typed = [...$('job-steps').querySelectorAll('li.current .job-sign input, li.current .job-sign select, li.current .job-sign textarea')].map((input) => ({ value: input.value, checked: input.checked }));
  const typedFor = $('job-steps').dataset.typedKey;
  $('job-steps').dataset.typedKey = typedKey;
  $('job-steps').innerHTML = job.steps.map((step, i) => {
    const inputs = i === next && canSign() && job.status !== 'cancelled'
      ? step.adds.filter((a) => a.serial_tracked).flatMap((add) => add.occurrences.map((occurrence) => `<label>Serial of ${escape(add.part)} at ${escape(occurrence)} <input data-serial="${escape(occurrence)}" required autocomplete="off"></label>`)).join('')
        + (step.field_defs || []).map(jobFieldInput).join('')
        + `<label>Note <input data-note autocomplete="off"></label><button type="button" data-sign>Sign step</button>`
      : '';
    const signed = step.signed_at ? `<span class="attrs-line">Signed ${new Date(step.signed_at * 1000).toLocaleString()}${step.serials.length ? ` · serials ${step.serials.map((s) => escape(s.serial)).join(', ')}` : ''}${(step.fields || []).map((f) => ` · ${escape(f.label || f.id)}: ${escape(jobFieldText(f))}`).join('')}${step.note ? ` · ${escape(step.note)}` : ''}</span>${me?.can_checkin ? '<button type="button" class="link" data-reopen>Reopen</button>' : ''}` : (step.note ? `<span class="attrs-line">${escape(step.note)}</span>` : '');
    return `<li data-step="${escape(step.step)}" class="${step.signed_at ? 'signed' : i === next ? 'current' : ''}"><strong>${escape(step.title || step.step)}</strong>${signed}${inputs ? `<div class="job-sign">${inputs}</div>` : ''}</li>`;
  }).join('');
  const inputsNow = [...$('job-steps').querySelectorAll('li.current .job-sign input, li.current .job-sign select, li.current .job-sign textarea')];
  if (typedFor === typedKey && inputsNow.length === typed.length) {
    inputsNow.forEach((input, i) => {
      if (input.type === 'checkbox') input.checked = typed[i].checked;
      else input.value = typed[i].value;
    });
  }
  for (const li of $('job-steps').querySelectorAll('li')) {
    const step = li.dataset.step;
    li.querySelector('[data-sign]')?.addEventListener('click', () => act(async () => {
      const serials = [...li.querySelectorAll('[data-serial]')].map((input) => ({ occurrence: input.dataset.serial, serial: input.value }));
      const fields = jobFieldValues(li);
      await api('POST', `/api/jobs/${encodeURIComponent(job.id)}/steps/${encodeURIComponent(step)}/signoff`, { serials, fields, note: li.querySelector('[data-note]').value });
      jobsView.jobs.set(job.id, await api('GET', `/api/jobs/${encodeURIComponent(job.id)}`));
      paintJobs();
    }));
    li.querySelector('[data-reopen]')?.addEventListener('click', () => act(async () => {
      const reason = prompt('Why is this step reopened? It and every later step are signed again.'); if (!reason) return;
      jobsView.jobs.set(job.id, await api('POST', `/api/jobs/${encodeURIComponent(job.id)}/steps/${encodeURIComponent(step)}/reopen`, { reason }));
      paintJobs();
    }));
  }
}
$('job-close').addEventListener('click', () => { location.hash = '#/jobs'; });
$('job-add').addEventListener('submit', (event) => {
  event.preventDefault();
  const form = event.target;
  act(async () => {
    await api('POST', '/api/jobs', { instructions: form.elements.instructions.value.trim(), revision: form.elements.revision.value.trim(), serial: form.elements.serial.value.trim(), quantity: Number(form.elements.quantity.value) || 1 });
    form.reset(); await renderJobs(null);
  });
});

async function renderCompanies() {
  await loadCompanies();
  $('manufacturer-rows').innerHTML = companyRows(companies.manufacturers, 'manufacturers');
  $('supplier-rows').innerHTML = companyRows(companies.suppliers, 'suppliers');
  $('manufacturers-empty').hidden = companies.manufacturers.length > 0;
  $('suppliers-empty').hidden = companies.suppliers.length > 0;
}

for (const form of document.querySelectorAll('form.company-add')) {
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    act(async () => {
      await api('POST', `/api/${form.dataset.list}`, { name: form.elements.name.value });
      form.reset();
      await renderCompanies();
    });
  });
}

let editingCompany = null;

$('view-sourcing').addEventListener('click', (event) => {
  const show = event.target.closest('button[data-show]');
  if (show) {
    $('filter-company').value = show.dataset.show;
    location.hash = '#/parts';
    return;
  }
  const button = event.target.closest('button[data-co]');
  if (!button) return;
  const list = button.dataset.list;
  const company = companies[list].find((c) => c.id === button.dataset.id);
  act(async () => {
    if (button.dataset.co === 'edit') {
      editingCompany = { list, id: company.id };
      $('co-title').textContent = `Edit ${company.name}`;
      $('co-name').value = company.name;
      $('co-website').value = company.website;
      $('co-notes').value = company.notes;
      $('company-dialog').showModal();
    } else if (button.dataset.co === 'delete') {
      if (!confirm(`Delete ${company.name}?`)) return;
      await api('DELETE', `/api/${list}/${encodeURIComponent(company.id)}`);
      await renderCompanies();
    }
  });
});

$('company-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'save') return;
  event.preventDefault();
  act(async () => {
    await api('PATCH', `/api/${editingCompany.list}/${encodeURIComponent(editingCompany.id)}`, {
      name: $('co-name').value,
      website: $('co-website').value,
      notes: $('co-notes').value,
    });
    $('company-dialog').close();
    await renderCompanies();
  });
});

// ----------------------------------------------------------------- settings

async function renderSettings() {
  const settings = await api('GET', '/api/settings');
  $('set-multiple-drafts').checked = settings.allow_multiple_open_drafts;
  $('set-lock-attributes').checked = settings.lock_released_attributes;
  $('set-released-children').checked = settings.require_released_children;
  $('set-idle').value = settings.session_idle_minutes;
  $('set-max-hours').value = settings.session_max_hours;
  $('set-script-editor').checked = settings.script_editor_enabled;
  $('set-workspaces-browsable').checked = settings.workspaces_browsable;
  $('set-script-locked').hidden = !settings.script_editor_locked;
  await renderReviewSettings(settings);
  $('settings-status').textContent = '';
}

$('settings-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    await api('PATCH', '/api/settings', {
      allow_multiple_open_drafts: $('set-multiple-drafts').checked,
      lock_released_attributes: $('set-lock-attributes').checked,
      require_released_children: $('set-released-children').checked,
      session_idle_minutes: Number($('set-idle').value),
      session_max_hours: Number($('set-max-hours').value),
      script_editor_enabled: $('set-script-editor').checked,
      workspaces_browsable: $('set-workspaces-browsable').checked,
      review_rule: readRule({
        required: $('set-rv-required'), due: $('set-rv-due'), reviewers: $('set-rv-reviewers'), self: $('set-rv-self'),
      }),
      review_overrides: readOverrides(),
    });
    await renderSettings();
    $('settings-status').textContent = 'Saved.';
    OpenPages.saved();
  });
});

// ------------------------------------------------------------------ scripts

// Example inputs for the test run: the shape each hook really receives, so an
// admin can edit rather than guess.
const SAMPLE_INPUT = {
  partNumber: {
    requested: '',
    partType: { id: 'made', name: 'Made', mode: { kind: 'script', script: 'part-number.js' } },
    part: { name: 'Motor mount bracket', description: '', category: 'brackets', document_class: 'normal' },
    user: { username: 'admin', groups: ['admin'] },
  },
  revisionLabel: {
    requested: '', suggested: 'B', existing: ['A'],
    part: { number: 'CPART000000001', name: 'Motor mount bracket' },
    user: { username: 'admin', groups: ['admin'] },
  },
  beforeRelease: {
    part: { number: 'CPART000000001', name: 'Motor mount bracket', description: '' },
    revision: { label: 'A', lifecycle: 'draft' },
    user: { username: 'admin', groups: ['admin'] },
  },
  afterRelease: {
    part: { number: 'CPART000000001', name: 'Motor mount bracket' },
    revision: { label: 'A', lifecycle: 'released' },
    user: { username: 'admin', groups: ['admin'] },
  },
};

// A starting point for each hook file, so "New" opens something that runs.
const STARTER = {
  'revision-label.js': `// Decide the label of every new revision.
// Return the label, return null to accept what was typed (or the suggestion),
// or throw to refuse.
function revisionLabel(input) {
  return input.requested || input.suggested;
}
`,
  'before-release.js': `// Throw to refuse a release. The message is shown to the user.
function beforeRelease(input) {
  if (!input.part.description) throw new Error('A released part needs a description.');
}
`,
  'after-release.js': `// Runs after a release is committed. It cannot undo it; a throw is shown as a warning.
function afterRelease(input) {
  console.log('released', input.part.number, input.revision.label);
}
`,
};
const PART_NUMBER_STARTER = `// Validate or allocate the number of a part of a Script-mode part type.
// input.requested is what the user typed ('' if nothing). Return the number,
// or throw to refuse.
function partNumber(input) {
  if (input.requested) return input.requested;
  throw new Error('Type a number for this part type.');
}
`;

let scriptPath = null;
let scriptSaved = '';

function scriptDirty() {
  return scriptPath !== null && $('script-text').value !== scriptSaved;
}

// Whether the server lets this admin edit and test-run scripts here.
let scriptEditorOn = true;

function syncScriptButtons() {
  const open = scriptPath !== null;
  $('script-text').disabled = !open;
  $('script-text').readOnly = !scriptEditorOn;
  $('script-save').disabled = !scriptEditorOn || !open || !scriptDirty();
  $('script-delete').disabled = !scriptEditorOn || !open;
  $('run-go').disabled = !scriptEditorOn || !open;
  for (const el of $('script-new').elements) el.disabled = !scriptEditorOn;
  $('script-dirty').textContent = scriptDirty() ? '· unsaved' : '';
}

async function renderScripts() {
  const [listing, settings] = await Promise.all([api('GET', '/api/scripts'), api('GET', '/api/settings')]);
  scriptEditorOn = settings.script_editor_enabled && !settings.script_editor_locked;
  $('scripts-readonly').hidden = scriptEditorOn;
  $('scripts-readonly').textContent = settings.script_editor_locked
    ? 'Read-only: this server was started with --lock-script-editor. Edit the scripts directory on the host.'
    : 'Read-only: editing scripts in the browser is turned off in Settings. Edit the scripts directory on the host, or turn it back on.';
  $('scripts-dir').textContent = listing.dir;
  $('hook-rows').innerHTML = listing.hooks.map((h) => `
    <tr><td class="mono">${escape(h.file)}</td><td class="mono">${escape(h.function)}()</td><td>${escape(h.when)}</td></tr>`).join('');
  $('script-list').innerHTML = listing.files.length
    ? listing.files.map((f) => `
      <li><button class="${f.path === scriptPath ? 'current' : ''}" data-path="${escape(f.path)}" title="${f.size} bytes · ${escape(when(f.modified))}">${escape(f.path)}</button></li>`).join('')
    : '<li class="empty">No scripts yet.</li>';
  for (const button of $('script-list').querySelectorAll('button[data-path]')) {
    button.addEventListener('click', () => act(() => openScript(button.dataset.path)));
  }
  if (!$('run-input').value) setSampleInput();
  syncScriptButtons();
}

function setSampleInput() {
  $('run-input').value = JSON.stringify(SAMPLE_INPUT[$('run-function').value] || {}, null, 2);
}

// Pick the function a file most likely defines, from its name or its text.
function guessFunction(path, text) {
  for (const name of Object.keys(SAMPLE_INPUT)) {
    if (new RegExp(`function\\s+${name}\\b`).test(text)) return name;
  }
  if (path.includes('label')) return 'revisionLabel';
  if (path.includes('before')) return 'beforeRelease';
  if (path.includes('after')) return 'afterRelease';
  return 'partNumber';
}

async function openScript(path, starter, routed = false) {
  if(!routed && (starter===undefined || OpenPages.scriptDraft(`#/scripts/${encodeURIComponent(path)}`))){location.hash=`#/scripts/${encodeURIComponent(path)}`;return;}
  if(!routed)OpenPages.capture();
  let text = starter;
  if (text === undefined) {
    text = (await api('GET', `/api/scripts/file/${path}`)).text;
    scriptSaved = text;
  } else {
    scriptSaved = '';
  }
  scriptPath = path;
  $('script-path').textContent = path;
  $('script-text').value = text;
  const guess = guessFunction(path, text);
  if ($('run-function').value !== guess) {
    $('run-function').value = guess;
    setSampleInput();
  }
  $('run-output').hidden = true;
  $('run-status').textContent = '';
  await renderScripts();
  if(!routed){const hash=`#/scripts/${encodeURIComponent(path)}`;history.replaceState(null,'',hash);OpenPages.activate(hash,'scripts',path);OpenPages.capture();}
}

$('script-text').addEventListener('input', syncScriptButtons);
$('run-function').addEventListener('change', setSampleInput);

$('script-new').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    let path = $('script-new-path').value.trim();
    if (!path) return;
    if (!path.endsWith('.js')) path += '.js';
    const base = path.split('/').pop();
    await openScript(path, STARTER[base] || PART_NUMBER_STARTER);
    $('script-new-path').value = '';
  });
});

$('script-save').addEventListener('click', () => act(async () => {
  await api('PUT', `/api/scripts/file/${scriptPath}`, $('script-text').value);
  scriptSaved = $('script-text').value;
  OpenPages.saved();
  await renderScripts();
}));

$('script-delete').addEventListener('click', () => act(async () => {
  if (!confirm(`Delete ${scriptPath} from the scripts directory?`)) return;
  await api('DELETE', `/api/scripts/file/${scriptPath}`);
  OpenPages.closeTab(OpenPages.keyOf(location.hash),true);
  scriptPath = null;
  scriptSaved = '';
  $('script-path').textContent = 'No file open';
  $('script-text').value = '';
  await renderScripts();
}));

$('run-go').addEventListener('click', () => act(async () => {
  let input;
  try {
    input = JSON.parse($('run-input').value || 'null');
  } catch (error) {
    throw new Error(`The input is not JSON: ${error.message}`);
  }
  $('run-status').textContent = 'running…';
  const result = await api('POST', '/api/scripts/run', {
    path: scriptPath,
    source: $('script-text').value,
    function: $('run-function').value,
    input,
  });
  $('run-status').textContent = `${result.ok ? 'returned' : 'refused'} in ${result.millis} ms`;
  const out = $('run-output');
  out.hidden = false;
  out.classList.toggle('bad', !result.ok);
  const lines = [];
  if (result.ok) lines.push(`returned: ${JSON.stringify(result.value, null, 2)}`);
  else lines.push(`refused: ${result.error}`);
  if (result.logs.length) lines.push('', 'console:', ...result.logs);
  out.textContent = lines.join('\n');
}));

// OpenPages owns unload warnings for active and background script drafts.

// ---------------------------------------------------------------------- go



// ------------------------------------------------- families and templates

// Surface build failures and regeneration risks; ancestry is useful on demand.
function revisionContext(rev) {
  const notices = [];
  if (rev.hand_edited) notices.push('<span class="st st-stale">Edited after generation</span>');
  if (rev.bake && rev.bake !== 'done') {
    const label = { pending: 'Build queued', claimed: 'Building', failed: 'Build failed' }[rev.bake] || `Build ${rev.bake}`;
    notices.push(`<span class="st st-${escape(rev.bake)}">${escape(label)}</span>${rev.bake_error ? `<div class="error">${escape(rev.bake_error)}</div>` : ''}`);
  }
  const parents = [];
  const link = p => `<a href="#/part/${encodeURIComponent(p.part_id)}/${encodeURIComponent(p.revision_label)}/summary">${escape(p.number)}/${escape(p.revision_label)}</a>`;
  if (rev.family) parents.push(`Family ${link(rev.family)}`);
  if (rev.template) parents.push(`Template ${link(rev.template)}`);
  if (parents.length) notices.push(`<details><summary>Generated from</summary>${parents.join('<br>')}</details>`);
  return notices.length ? `<div class="revision-context">${notices.join(' ')}</div>` : '';
}

const STATUS_WORDS = {
  new: 'new', current: 'current', stale: 'stale', unstamped: 'not from family', blocked: 'blocked',
};

let familyRevision = '';

async function renderSeed(detail) {
  $('family-panel').hidden = detail.document_class !== 'family';
  $('template-panel').hidden = detail.document_class !== 'template';
  if (detail.document_class === 'family') await renderFamily(detail);
  if (detail.document_class === 'template') await renderTemplate(detail);
}

async function memberTypeOptions(select, current) {
  partTypes = await api('GET', '/api/part-types');
  select.innerHTML = partTypes
    .map((t) => `<option value="${escape(t.id)}">${escape(t.name)} (${escape(modeText(t.mode).replace(/<[^>]+>/g, ''))})</option>`)
    .join('');
  select.value = current;
}

async function renderFamily(detail) {
  if (familyRevision && !detail.revisions.some((r) => r.id === familyRevision)) familyRevision = '';
  const q = familyRevision ? `?revision=${encodeURIComponent(familyRevision)}` : '';
  const view = await api('GET', `/api/parts/${encodeURIComponent(detail.id)}/family${q}`);
  $('fam-revision').innerHTML = view.revisions
    .map((r) => `<option value="${escape(r.id)}">${escape(r.label)} (${escape(statusName(r.lifecycle))})</option>`)
    .join('');
  $('fam-revision').value = view.revision_id;
  await memberTypeOptions($('fam-member-type'), view.member_part_type);
  $('fam-member-type').disabled = !me.can_author;
  $('fam-member-note').textContent = view.member_part_type_mode === 'counter'
    ? 'A counter type allocates its own numbers, so rows naming new parts will fail. Choose a free-text, pattern or script type.'
    : '';
  $('fam-nodoc').hidden = view.has_document;
  $('fam-generate').disabled = !view.has_document || !view.rows.length;
  $('fam-import').disabled = !view.has_document;

  const columns = view.columns.map((c) => c.label || c.name);
  $('fam-head').innerHTML = `<tr><th>Part number</th><th>Rev</th><th>Description</th>${
    columns.map((c) => `<th class="mono">${escape(c)}</th>`).join('')}<th>Member</th><th>Status</th><th></th></tr>`;
  $('fam-empty').hidden = view.rows.length > 0;
  $('fam-rows').innerHTML = view.rows.map((row) => {
    const m = row.member;
    const member = m
      ? `<a href="#/part/${encodeURIComponent(m.part_id)}">${escape(m.number)}</a>`
        + (m.revision_label ? ` rev ${escape(m.revision_label)} <span class="state state-${escape(m.lifecycle)}">${escape(statusName(m.lifecycle))}</span>` : '')
        + (m.bake && m.bake !== 'done' ? ` <span class="st st-${escape(m.bake)}" title="${escape(m.bake_error)}">bake ${escape(m.bake)}</span>` : '')
      : '<span class="muted">not yet</span>';
    const cells = view.columns.map((c) => `<td class="mono">${escape(row.values[c.name] ?? '')}</td>`).join('');
    const one = me.can_author && view.has_document && row.status !== 'current' && row.status !== 'blocked'
      ? `<button class="link" data-one="${escape(row.part_number)}">Generate</button>` : '';
    return `<tr>
      <td class="mono">${escape(row.part_number)}</td>
      <td>${escape(row.revision) || '<span class="muted">newest</span>'}</td>
      <td>${escape(row.description)}</td>
      ${cells}
      <td>${member}</td>
      <td><span class="st st-${escape(row.status)}">${escape(STATUS_WORDS[row.status] || row.status)}</span></td>
      <td class="note-cell">${escape(row.note)} ${one}</td>
    </tr>`;
  }).join('');
  for (const button of $('fam-rows').querySelectorAll('button[data-one]')) {
    button.addEventListener('click', () => generateFamily([button.dataset.one]));
  }
  $('fam-orphans').hidden = !view.orphans.length;
  $('fam-orphan-list').innerHTML = view.orphans.map((o) =>
    `<li><a href="#/part/${encodeURIComponent(o.part_id)}">${escape(o.number)}</a> ${escape(o.name)}
      <span class="muted">rev ${escape(o.revision_label)}, generated from family rev ${escape(o.generated_from || '?')}</span></li>`).join('');
  currentFamily = view;
}

let currentFamily = null;

function showReport(report) {
  const box = $('fam-report');
  const failed = report.rows.filter((r) => r.status === 'failed');
  const baking = report.rows.filter((r) => r.bake).length;
  box.className = failed.length ? 'report bad' : 'report';
  box.innerHTML = `<strong>Generated from revision ${escape(report.family_revision)}:</strong>
    ${report.written} written, ${report.skipped} unchanged, ${report.failed} failed`
    + (baking ? ` · ${baking} waiting for a bake` : '')
    + (failed.length ? `<ul>${failed.map((r) => `<li><span class="mono">${escape(r.number)}</span>${
      r.revision ? ` rev ${escape(r.revision)}` : ''}: ${escape(r.reason)}</li>`).join('')}</ul>` : '');
  box.hidden = false;
}

function generateFamily(only) {
  act(async () => {
    const report = await api('POST', `/api/parts/${encodeURIComponent(currentPart.id)}/generate`, {
      family_revision: $('fam-revision').value,
      only: only || [],
    });
    await renderPart(currentPart.id);
    showReport(report);
  });
}

$('fam-generate').addEventListener('click', () => generateFamily());

$('fam-revision').addEventListener('change', () => act(async () => {
  familyRevision = $('fam-revision').value;
  $('fam-report').hidden = true;
  await renderFamily(currentPart);
}));

$('fam-member-type').addEventListener('change', () => act(async () => {
  await api('PATCH', `/api/parts/${encodeURIComponent(currentPart.id)}`, { member_part_type: $('fam-member-type').value });
  await renderPart(currentPart.id);
}));

$('fam-import').addEventListener('click', () => {
  const draft = currentFamily && currentFamily.revision_writeable;
  $('import-target').textContent = draft
    ? `Rows go into the table of revision ${currentFamily.revision_label}, which is ${currentFamily.revision_state}.`
    : `Revision ${currentFamily ? currentFamily.revision_label : ''} cannot be changed, so rows go into the newest family revision still in work, if there is one.`;
  $('import-dialog').showModal();
});

$('import-file').addEventListener('change', () => act(async () => {
  const file = $('import-file').files[0];
  if (file) $('import-csv').value = await file.text();
  $('import-file').value = '';
}));

$('import-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'import') return;
  event.preventDefault();
  act(async () => {
    const result = await api('POST', `/api/parts/${encodeURIComponent(currentPart.id)}/family/import`, {
      csv: $('import-csv').value,
      revision: currentFamily && currentFamily.revision_writeable ? currentFamily.revision_id : '',
      generate: $('import-generate').checked,
    });
    $('import-dialog').close();
    $('import-csv').value = '';
    familyRevision = result.import.revision_id;
    await renderPart(currentPart.id);
    await reloadEditor(documentKey(currentPart.id, result.import.revision_id));
    const i = result.import;
    const box = $('fam-report');
    if (result.generate) {
      showReport(result.generate);
      box.insertAdjacentHTML('afterbegin', `Imported ${i.added} new and ${i.updated} updated rows into revision ${escape(i.revision_label)}. `);
    } else {
      box.className = 'report';
      box.innerHTML = `Imported ${i.added} new and ${i.updated} updated rows into revision ${escape(i.revision_label)}`
        + (i.columns_added.length ? `, adding columns ${i.columns_added.map((c) => `<span class="mono">${escape(c)}</span>`).join(', ')}` : '')
        + '. Press Generate to write the members.';
      box.hidden = false;
    }
  });
});

let currentTemplate = null;

function syncSpinNumber() {
  const kind = partTypes.find((t) => t.id === $('spin-type').value);
  const mode = kind ? kind.mode : { kind: 'counter' };
  const input = $('spin-number');
  input.disabled = mode.kind === 'counter';
  input.required = mode.kind === 'free' || mode.kind === 'pattern';
  if (mode.kind === 'counter') input.value = '';
  input.placeholder = mode.kind === 'counter' ? (kind ? kind.next_number : '') : mode.kind === 'pattern' ? mode.regex : '';
  $('spin-number-note').textContent = mode.kind === 'counter'
    ? `The ${kind ? kind.name : ''} counter numbers it.` : mode.kind === 'script' ? 'The script decides; it sees what you type.' : '';
}

async function renderTemplate(detail) {
  const view = await api('GET', `/api/parts/${encodeURIComponent(detail.id)}/template`);
  currentTemplate = view;
  $('tpl-revision').textContent = `inputs from revision ${view.revision_label}`;
  $('tpl-nodoc').hidden = view.has_document;
  $('spin-form').hidden = !me.can_author || !view.has_document;
  await memberTypeOptions($('spin-type'), view.member_part_type);
  syncSpinNumber();
  $('spin-none').hidden = view.inputs.length > 0;
  $('spin-inputs').innerHTML = view.inputs.map((input) => {
    const label = escape(input.label || input.name);
    const limits = [input.min != null ? `min ${input.min}` : '', input.max != null ? `max ${input.max}` : ''].filter(Boolean).join(', ');
    const field = input.choices && input.choices.length
      ? `<select data-input="${escape(input.name)}">${input.choices.map((c) =>
        `<option${c.trim() === input.default ? ' selected' : ''}>${escape(c)}</option>`).join('')}</select>`
      : `<input class="mono" data-input="${escape(input.name)}" value="${escape(input.default)}">`;
    return `<label><span title="${escape(input.name)}">${label}${limits ? ` <span class="muted">(${escape(limits)})</span>` : ''}</span>${field}</label>`;
  }).join('');
  $('tpl-copies-none').hidden = view.copies.length > 0;
  $('tpl-copies').innerHTML = view.copies.map((c) =>
    `<li><a href="#/part/${encodeURIComponent(c.part_id)}">${escape(c.number)}</a> ${escape(c.name)}
      <span class="muted mono">${escape(Object.entries(c.values).map(([k, v]) => `${k} = ${v}`).join(', '))}</span>
      ${c.bake && c.bake !== 'done' ? `<span class="st st-${escape(c.bake)}">bake ${escape(c.bake)}</span>` : ''}</li>`).join('');
}

$('spin-type').addEventListener('change', syncSpinNumber);

$('spin-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    const values = {};
    for (const field of $('spin-inputs').querySelectorAll('[data-input]')) values[field.dataset.input] = field.value;
    const part = await api('POST', `/api/parts/${encodeURIComponent(currentPart.id)}/spin-out`, {
      name: $('spin-name').value,
      number: $('spin-number').value,
      part_type: $('spin-type').value,
      template_revision: currentTemplate ? currentTemplate.revision_id : '',
      values,
    });
    $('spin-name').value = '';
    $('spin-number').value = '';
    location.hash = `#/part/${encodeURIComponent(part.id)}`;
  });
});

// ----------------------------------------------------------- the bake queue

let bakeWorkerBusy = false, bakeOffset = 0, bakeGeneration = 0, bakeLoading = false, bakeNext = null;
async function renderBakeWorker() {
  $('bake-worker-controls').hidden = !me.is_admin;
  if (!me.is_admin || bakeWorkerBusy) return;
  const worker = await api('GET', '/api/bake/worker');
  if (bakeWorkerBusy) return;
  $('bake-worker-status').textContent = worker.running ? `Running (PID ${worker.pid})` : 'Stopped';
  $('bake-worker-message').textContent = worker.error || (worker.configured
    ? (worker.running ? 'The worker is processing queued jobs.' : 'Start the worker to process queued jobs.')
    : 'The server operator must configure the native worker executable, token file and server URL before it can be started here.');
  $('bake-worker-start').disabled = !worker.configured || worker.running;
  $('bake-worker-stop').disabled = !worker.running;
}
for (const action of ['start', 'stop']) {
  $(`bake-worker-${action}`).addEventListener('click', () => act(async () => {
    if (bakeWorkerBusy) return;
    bakeWorkerBusy = true;
    $('bake-worker-start').disabled = true;
    $('bake-worker-stop').disabled = true;
    try {
      await api('POST', `/api/bake/worker/${action}`);
    } finally {
      bakeWorkerBusy = false;
      await renderBakeWorker();
    }
  }));
}
async function renderBake() {
  const generation=++bakeGeneration;
  bakeLoading=true;$('bake-prev').disabled=true;$('bake-next').disabled=true;
  try {
  await renderBakeWorker();
  const filter = $('bake-filter').value;
  const size=Number($('bake-page-size').value);
  const page = await api('GET', `/api/bake/jobs?${new URLSearchParams({status:filter,limit:size,offset:bakeOffset})}`);
  if(generation!==bakeGeneration)return;
  const jobs=page.jobs;
  bakeOffset=page.offset;bakeNext=page.next;
  $('bake-page-status').textContent=`Page ${Math.floor(bakeOffset/size)+1} of ${Math.max(1,Math.ceil(page.total/size))} · ${page.total} jobs`;
  $('bake-empty').hidden = jobs.length > 0;
  $('bake-empty').textContent = filter ? 'No jobs.' : 'Nothing waiting.';
  $('bake-rows').innerHTML = jobs.map((job) => {
    const worker = job.claimed_by
      ? `${escape(job.claimed_by)}${job.status === 'claimed' && job.lease_expires_at
        ? `<br><span class="muted">until ${escape(when(job.lease_expires_at))}</span>` : ''}`
      : '—';
    const retry = me.can_author && (job.status === 'failed' || job.status === 'claimed')
      ? `<button class="link" data-retry="${escape(job.id)}">${job.status === 'failed' ? 'Retry' : 'Take back'}</button>` : '';
    return `<tr>
      <td><a href="#/part/${encodeURIComponent(job.part_id)}">${escape(job.number)}</a><br><span class="muted">${escape(job.name)}</span></td>
      <td>${escape(job.revision_label)}</td>
      <td><span class="st st-${escape(job.status)}">${escape(job.status)}</span>${
        job.error ? `<br><span class="muted">${escape(job.error)}</span>` : ''}</td>
      <td>${escape(job.reason)}</td>
      <td>${escape(when(job.requested_at))}<br><span class="muted">${escape(job.requested_by)}</span></td>
      <td>${worker}${job.waiting_on_checkout && job.status === 'pending'
        ? `<br><span class="muted">waits: checked out by ${escape(job.locked_by)}</span>` : ''}</td>
      <td>${job.attempts}</td>
      <td class="actions">${retry}</td>
    </tr>`;
  }).join('');
  for (const button of $('bake-rows').querySelectorAll('button[data-retry]')) {
    button.addEventListener('click', () => act(async () => {
      await api('POST', `/api/bake/jobs/${encodeURIComponent(button.dataset.retry)}/retry`);
      await renderBake();
    }));
  }
  } finally {
    if(generation===bakeGeneration){bakeLoading=false;$('bake-prev').disabled=bakeOffset===0;$('bake-next').disabled=bakeNext===null;}
  }
}

$('bake-filter').addEventListener('change', () => act(async()=>{bakeOffset=0;await renderBake();}));
$('bake-page-size').addEventListener('change', () => act(async()=>{bakeOffset=0;await renderBake();}));
$('bake-prev').addEventListener('click', () => act(async()=>{bakeOffset=Math.max(0,bakeOffset-Number($('bake-page-size').value));await renderBake();}));
$('bake-next').addEventListener('click', () => act(async()=>{if(bakeNext===null)return;bakeOffset=bakeNext;await renderBake();}));
$('bake-refresh').addEventListener('click', () => act(renderBake));
setInterval(()=>{if(me&&!bakeLoading&&!document.hidden&&!$('view-bake').hidden)renderBake().catch(()=>{});},5000);

window.addEventListener('hashchange', route);
boot();

// ---------------------------------------------------------------- structure
//
// A revision's uses list is the assembly structure; the BOM, the diff and
// where-used are all read from the server, which computes them. The page
// only edits the list, and only while the viewer holds the revision's lock —
// the server refuses otherwise, and the page says why before anyone tries.

const structure = { part: null, revision: '', tab: 'bom', lines: [], saved: '' };
const partUrl = () => `/api/parts/${encodeURIComponent(currentPart.id)}`;
const revUrl = (rev) => `${partUrl()}/revisions/${encodeURIComponent(rev)}`;
const qtyText = (n) => (Number.isInteger(n) ? String(n) : String(Number(n.toFixed(6))));
const money = (n) => Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 4 });
const stateChip = (state) => (state ? `<span class="state state-${escape(state)}">${escape(state)}</span>` : '—');

// The revision a structure view opens on: the current release, else the
// newest.
function defaultRevision(detail) {
  const views = detail.revision_views;
  const released = [...views].reverse().find((r) => r.lifecycle === 'released');
  return (released || views[views.length - 1]).id;
}

function revisionOptions(select, detail, value, { any = false } = {}) {
  const rows = [...detail.revision_views].reverse()
    .map((r) => `<option value="${escape(r.id)}">${escape(r.label)} · ${escape(statusName(r.lifecycle))}</option>`);
  select.innerHTML = (any ? '<option value="">any revision</option>' : '') + rows.join('');
  select.value = value;
}

async function renderStructure(detail) {
  const views = detail.revision_views;
  if (structure.part !== detail.id || !views.some((r) => r.id === structure.revision)) {
    // Another part opens on its BOM, not on whichever tab the last one was left.
    if (structure.part !== detail.id) structure.tab = 'bom';
    structure.part = detail.id;
    structure.revision = defaultRevision(detail);
    const newest = views[views.length - 1].id;
    const before = views.length > 1 ? views[views.length - 2].id : newest;
    revisionOptions($('diff-from'), detail, before);
    revisionOptions($('diff-to'), detail, newest);
    revisionOptions($('wu-revision'), detail, '', { any: true });
  } else {
    revisionOptions($('diff-from'), detail, $('diff-from').value || views[0].id);
    revisionOptions($('diff-to'), detail, $('diff-to').value || views[views.length - 1].id);
    revisionOptions($('wu-revision'), detail, $('wu-revision').value, { any: true });
  }
  revisionOptions($('bom-revision'), detail, structure.revision);
  showTab(structure.tab);
  await Promise.all([loadBom(), loadUses(), loadDiff(), loadWhereUsed(), loadRevisionFields(detail)]);
}

function showTab(tab) {
  structure.tab = tab;
  for (const button of document.querySelectorAll('#bom-panel .tab')) {
    button.setAttribute('aria-selected', String(button.dataset.tab === tab));
  }
  for (const name of ['bom', 'uses', 'diff']) $(`tab-${name}`).hidden = name !== tab;
  if (tab === 'uses' && structure.usesUnpainted) paintUsesRows();
}

for (const button of document.querySelectorAll('#bom-panel .tab')) {
  button.addEventListener('click', () => showTab(button.dataset.tab));
}

$('bom-revision').addEventListener('change', () => act(async () => {
  structure.revision = $('bom-revision').value;
  await Promise.all([loadBom(), loadUses()]);
}));
$('bom-view').addEventListener('change', () => act(loadBom));

let bomReadSerial=0;
// The last BOM read by loadBom: its URL, ETag and body, for the poll's 304.
let bomTagged={url:'',tag:'',bom:null};
async function loadBom({background=false}={}) {
  const serial=++bomReadSerial;
  const flat = $('bom-view').value === 'flat';
  const query = `levels=0&flat=${flat}&occurrences=true`;
  const base = `${revUrl(structure.revision)}/bom`;
  // The poll sends back the ETag of the BOM it drew: an unchanged BOM is a
  // 304 with no body, not megabytes to fetch, parse and compare.
  const url = `${base}?${query}`;
  const kept = background && bomTagged.url === url && bomTagged.bom ? bomTagged : null;
  const answer = await apiTagged(url, kept?.tag);
  let bom, tag;
  if (answer.notModified && kept) ({ bom, tag } = kept);
  else if (answer.notModified) throw new Error('The BOM could not be read again.');
  else { bom = answer.payload; tag = answer.tag; bomTagged = { url, tag, bom }; }
  if(serial!==bomReadSerial)return;
  $('bom-csv').href = `${base}?${query}&format=csv`;
  const empty = bom.lines.length === 0;
  $('bom-empty').hidden = !empty;
  $('bom-wrap').hidden = empty;
  $('bom-csv').hidden = empty;
  $('bom-totals').hidden = empty;

  await drawConfiguredBom(bom,serial,background,tag);
  if(serial!==bomReadSerial)return;
  const totals = bom.totals.map((t) => `${escape(t.currency || '(no currency)')} ${money(t.total)}`).join(' · ');
  $('bom-totals').innerHTML = `Total: ${totals || '—'}`
    + (bom.unpriced ? ` <span class="muted">· ${bom.unpriced} line${bom.unpriced === 1 ? '' : 's'} with no price</span>` : '');
}

// -- the uses list editor

function usesRevision() {
  return currentPart.revision_views.find((r) => r.id === structure.revision);
}

const usesEditable = () => {
  const rev = usesRevision();
  return Boolean(rev && rev.editable && rev.locked_by_me);
};

const usesBody = () => structure.lines.map((l) => ({
  part: l.part,
  revision: l.revision.trim(),
  quantity: String(l.quantity).trim(),
  unit: l.unit.trim(),
  find_number: l.find_number.trim(),
  reference: l.reference.trim(),
}));

async function loadUses() {
  const answer = await api('GET', `${revUrl(structure.revision)}/uses`);
  structure.lines = answer.uses.map((u) => ({
    part: u.part,
    number: u.number,
    name: u.name,
    revision: u.floating ? '' : u.revision_label,
    resolved: u.revision_label,
    state: u.state,
    quantity: qtyText(u.quantity),
    unit: u.unit,
    find_number: u.find_number,
    reference: u.reference,
  }));
  structure.saved = JSON.stringify(usesBody());
  $('uses-status').textContent = '';
  $('uses-search').value = '';
  $('uses-results').innerHTML = '';
  renderUses();
}

function renderUses() {
  const rev = usesRevision();
  const editable = usesEditable();
  let note = '';
  if (rev && !rev.editable) {
    note = `Rev ${rev.label} is ${rev.lifecycle}: its uses list is frozen with it. Start a new revision to change it.`;
  } else if (rev && !rev.locked_by) {
    note = me.can_author ? `Check out rev ${rev.label} to edit its uses list.` : '';
  } else if (rev && !rev.locked_by_me) {
    note = `Rev ${rev.label} is checked out by ${rev.locked_by}.`;
  }
  $('uses-locked').hidden = !note;
  $('uses-locked').textContent = note;
  $('uses-add').hidden = !editable;
  $('uses-save').hidden = !editable;
  $('uses-revert').hidden = !editable;
  $('uses-empty').hidden = structure.lines.length > 0;
  // The rows wait for their tab: a 2,000-line list is 10,000 inputs the
  // Structure view would otherwise build behind the BOM it opens on.
  if ($('tab-uses').hidden) structure.usesUnpainted = true;
  else paintUsesRows();
  syncUsesStatus();
}

function paintUsesRows() {
  structure.usesUnpainted = false;
  const editable = usesEditable();
  const off = editable ? '' : ' disabled';
  $('uses-rows').innerHTML = structure.lines.map((l, i) => `
    <tr>
      <td><a href="#/part/${encodeURIComponent(l.part)}">${escape(l.number)}</a> <span class="muted">${escape(l.name)}</span></td>
      <td><input class="rev" data-i="${i}" data-f="revision" value="${escape(l.revision)}" placeholder="${escape(l.resolved ? `(${l.resolved})` : 'current')}"
        aria-label="Revision of ${escape(l.number)}, empty follows the current release"${off}></td>
      <td><input class="qty" data-i="${i}" data-f="quantity" value="${escape(l.quantity)}" inputmode="decimal" aria-label="Quantity of ${escape(l.number)}"${off}></td>
      <td><input class="unit" data-i="${i}" data-f="unit" value="${escape(l.unit)}" aria-label="Unit"${off}></td>
      <td><input class="find" data-i="${i}" data-f="find_number" value="${escape(l.find_number)}" aria-label="Find number"${off}></td>
      <td><input class="ref" data-i="${i}" data-f="reference" value="${escape(l.reference)}" aria-label="Reference designators"${off}></td>
      <td class="actions">${editable ? `<button type="button" class="link" data-remove="${i}">Remove</button>` : ''}</td>
    </tr>`).join('');
}

function syncUsesStatus() {
  if (!usesEditable()) return;
  const changed = JSON.stringify(usesBody()) !== structure.saved;
  $('uses-save').disabled = !changed;
  $('uses-revert').disabled = !changed;
  $('uses-status').textContent = changed ? 'Unsaved changes.' : '';
}

$('uses-rows').addEventListener('input', (event) => {
  const input = event.target.closest('input[data-f]');
  if (!input) return;
  structure.lines[Number(input.dataset.i)][input.dataset.f] = input.value;
  syncUsesStatus();
});

$('uses-rows').addEventListener('click', (event) => {
  const button = event.target.closest('button[data-remove]');
  if (!button) return;
  structure.lines.splice(Number(button.dataset.remove), 1);
  renderUses();
});

let usesTimer = null;
$('uses-search').addEventListener('input', () => {
  clearTimeout(usesTimer);
  usesTimer = setTimeout(() => act(searchUses), 200);
});

async function searchUses() {
  const q = $('uses-search').value.trim();
  if (!q) { $('uses-results').innerHTML = ''; return; }
  const found = (await api('GET', `/api/parts?q=${encodeURIComponent(q)}&limit=9`)).parts
    .filter((p) => p.id !== currentPart.id)
    .slice(0, 8);
  $('uses-results').innerHTML = found.length
    ? found.map((p) => `<li><button type="button" data-add="${escape(p.id)}" data-number="${escape(p.number)}" data-name="${escape(p.name)}">
        ${thumb(p.thumbnail_url, 'xs')}<strong class="mono">${escape(p.number)}</strong> ${escape(p.name)}
        <span class="muted">· rev ${escape(p.latest_label)} ${escape(statusName(p.latest_state))}</span></button></li>`).join('')
    : '<li class="muted">No part matches.</li>';
}

$('uses-results').addEventListener('click', (event) => {
  const button = event.target.closest('button[data-add]');
  if (!button) return;
  structure.lines.push({
    part: button.dataset.add,
    number: button.dataset.number,
    name: button.dataset.name,
    revision: '',
    resolved: '',
    state: '',
    quantity: '1',
    unit: 'each',
    find_number: String(structure.lines.length + 1),
    reference: '',
  });
  $('uses-search').value = '';
  $('uses-results').innerHTML = '';
  renderUses();
});

$('uses-save').addEventListener('click', () => act(async () => {
  await api('PUT', `${revUrl(structure.revision)}/uses`, { uses: usesBody() });
  await renderPart(currentPart.id);
  $('uses-status').textContent = 'Saved.';
}));

$('uses-revert').addEventListener('click', () => act(loadUses));

// -- comparing two revisions

$('diff-from').addEventListener('change', () => act(loadDiff));
$('diff-to').addEventListener('change', () => act(loadDiff));

async function loadDiff() {
  const from = $('diff-from').value;
  const to = $('diff-to').value;
  $('diff-wrap').hidden = !from || !to || from === to;
  if (!from || !to || from === to) {
    $('diff-rows').innerHTML = '';
    $('diff-summary').textContent = currentPart.revision_views.length < 2
      ? 'This part has one revision; there is nothing to compare yet.'
      : 'Pick two different revisions.';
    return;
  }
  const diff = await api('GET', `${partUrl()}/bom/diff?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`);
  $('diff-rows').innerHTML = diff.lines.map((l) => `
    <tr>
      <td class="number"><a href="#/part/${encodeURIComponent(l.part_id)}">${escape(l.number)}</a></td>
      <td>${escape(l.name)}</td>
      <td class="change-${escape(l.change)}">${escape(l.change)}</td>
      <td>${l.details.map(escape).join('<br>')}</td>
    </tr>`).join('');
  $('diff-wrap').hidden = diff.lines.length === 0;
  $('diff-summary').textContent = `From rev ${diff.from_revision} to rev ${diff.to_revision}: `
    + `${diff.lines.length} change${diff.lines.length === 1 ? '' : 's'}, ${diff.unchanged} part${diff.unchanged === 1 ? '' : 's'} unchanged.`;
}

// -- where-used

$('wu-revision').addEventListener('change', () => act(loadWhereUsed));
$('wu-levels').addEventListener('change', () => act(loadWhereUsed));

// Where-used draws its first rows when a part is used everywhere, as the BOM
// does (BOM_SHOWN_FIRST): 2,000 lines took the browser close to a second.
const whereUsedView = { key: '', showAll: false, used: null };

$('wu-show-all').addEventListener('click', () => { whereUsedView.showAll = true; paintWhereUsed(); });

async function loadWhereUsed() {
  const revision = $('wu-revision').value;
  const levels = $('wu-levels').value;
  const used = await api('GET', `${partUrl()}/where-used?revision=${encodeURIComponent(revision)}&levels=${encodeURIComponent(levels)}`);
  $('wu-empty').hidden = used.lines.length > 0;
  $('wu-empty').textContent = revision
    ? `Nothing uses rev ${used.revision_label} of this part.`
    : 'Nothing uses this part.';
  $('wu-wrap').hidden = used.lines.length === 0;
  const key = `${currentPart.id}/${revision}/${levels}`;
  if (whereUsedView.key !== key) { whereUsedView.key = key; whereUsedView.showAll = false; }
  whereUsedView.used = used;
  paintWhereUsed();
}

function paintWhereUsed() {
  const used = whereUsedView.used;
  const capped = !whereUsedView.showAll && used.lines.length > BOM_COLLAPSED_OVER;
  const lines = capped ? used.lines.slice(0, BOM_SHOWN_FIRST) : used.lines;
  $('wu-limit').hidden = !capped;
  $('wu-limit-note').textContent = capped ? `Showing the first ${BOM_SHOWN_FIRST.toLocaleString()} of ${used.lines.length.toLocaleString()} lines: drawing them all is slow.` : '';
  $('wu-show-all').textContent = `Show all ${used.lines.length.toLocaleString()} lines`;
  $('wu-rows').innerHTML = lines.map((l) => `
    <tr class="${l.current ? '' : 'muted'}">
      <td>${'\u00a0\u00a0\u00a0'.repeat(l.level - 1)}<a href="#/part/${encodeURIComponent(l.part_id)}">${escape(l.number)}</a>
        <span class="muted">${escape(l.name)}</span>${l.top ? ' <span class="badge">top</span>' : ''}</td>
      <td>${escape(l.revision_label)}</td>
      <td>${stateChip(l.state)}</td>
      <td>${escape(l.uses_revision)}</td>
      <td class="num">${qtyText(l.quantity)}${l.unit === 'each' ? '' : ` ${escape(l.unit)}`}</td>
      <td>${escape(l.find_number)}</td>
    </tr>`).join('');
}


// -- replace everywhere
//
// The server plans and writes (crate::replace); this dialog asks it for a dry
// run, lets the user leave parents out, and applies what is ticked.

const replacing = { to: null, report: null };

$('replace-open').addEventListener('click', () => act(openReplace));

async function openReplace() {
  replacing.to = null;
  replacing.report = null;
  $('rp-title').textContent = currentPart.number;
  $('rp-from').innerHTML = '<option value="">Any revision (the whole part)</option>'
    + currentPart.revision_views.map((r) => `<option value="${escape(r.id)}">Rev ${escape(r.label)} (${escape(statusName(r.lifecycle))})</option>`).join('');
  $('rp-from').value = $('wu-revision').value || '';
  $('rp-search').value = '';
  $('rp-results').innerHTML = '';
  chooseReplacement(currentPart.id, currentPart.number, currentPart.name, currentPart.revision_views);
  $('replace-dialog').showModal();
}


// Any change to the question makes the previous preview stale.
function staleReplace() {
  replacing.report = null;
  $('rp-apply').disabled = true;
  $('rp-wrap').hidden = true;
  $('rp-summary').textContent = '';
}
for (const id of ['rp-from', 'rp-to-rev']) $(id).addEventListener('change', staleReplace);

function chooseReplacement(id, number, name, revisions) {
  replacing.to = { id, number };
  $('rp-chosen').textContent = `Replacement: ${number} ${name}`;
  $('rp-to-rev').innerHTML = '<option value="">Follow its current release (floating)</option>'
    + revisions.map((r) => `<option value="${escape(r.id)}">Rev ${escape(r.label)} (${escape(statusName(r.lifecycle))})</option>`).join('');
  const released = revisions.find((r) => r.lifecycle === 'released');
  if (id === currentPart.id) {
    // A revision swap needs a revision; default to the current release.
    $('rp-to-rev').value = released ? released.id : (revisions[revisions.length - 1] || {}).id || '';
  } else {
    $('rp-to-rev').value = released ? released.id : '';
  }
  staleReplace();
}

let replaceTimer = null;
$('rp-search').addEventListener('input', () => {
  clearTimeout(replaceTimer);
  replaceTimer = setTimeout(() => act(searchReplacement), 200);
});

async function searchReplacement() {
  const q = $('rp-search').value.trim();
  if (!q) { $('rp-results').innerHTML = ''; return; }
  const found = (await api('GET', `/api/parts?q=${encodeURIComponent(q)}&limit=8`)).parts;
  $('rp-results').innerHTML = found.length
    ? found.map((p) => `<li><button type="button" data-pick="${escape(p.id)}">
        ${thumb(p.thumbnail_url, 'xs')}<strong class="mono">${escape(p.number)}</strong> ${escape(p.name)}
        <span class="muted">· rev ${escape(p.latest_label)} ${escape(statusName(p.latest_state))}</span></button></li>`).join('')
    : '<li class="muted">No part matches.</li>';
}

$('rp-results').addEventListener('click', (event) => {
  const button = event.target.closest('button[data-pick]');
  if (!button) return;
  act(async () => {
    const detail = await api('GET', `/api/parts/${encodeURIComponent(button.dataset.pick)}`);
    chooseReplacement(detail.id, detail.number, detail.name, detail.revision_views);
    $('rp-results').innerHTML = '';
    $('rp-search').value = '';
  });
});

function replaceRequest(dryRun) {
  const body = {
    from_revision: $('rp-from').value,
    to_part: replacing.to ? replacing.to.id : '',
    to_revision: $('rp-to-rev').value,
    dry_run: dryRun,
  };
  if (!dryRun) {
    body.parents = [...$('rp-rows').querySelectorAll('input[data-parent]:checked')].map((c) => c.dataset.parent);
  }
  return body;
}

const REPLACE_STATUS = {
  'would-write': 'will edit', 'would-create': 'will start a new revision',
  written: 'edited', created: 'new revision', skipped: 'skipped', refused: 'refused',
};

function renderReplace(report, preview) {
  $('rp-wrap').hidden = report.rows.length === 0;
  $('rp-rows').innerHTML = report.rows.map((r) => {
    const doable = r.status === 'would-write' || r.status === 'would-create';
    const writes = r.plan === 'edit' ? `rev ${escape(r.revision)} in place`
      : r.plan === 'new-revision' ? `new rev ${escape(r.revision)}` : '—';
    const lines = r.lines.map((l) => `${escape(l.from)} → ${escape(l.to)} <span class="muted">×${qtyText(l.quantity)}${l.find_number ? ` · find ${escape(l.find_number)}` : ''}</span>`).join('<br>');
    const result = `${escape(REPLACE_STATUS[r.status] || r.status)}${r.reason ? `: ${escape(r.reason)}` : ''}`;
    return `
      <tr>
        <td>${preview && doable ? `<input type="checkbox" data-parent="${escape(documentKey(r.part_id, r.parent_revision_id))}" checked aria-label="Include ${escape(r.number)} rev ${escape(r.parent_revision)}">` : ''}</td>
        <td><a href="#/part/${encodeURIComponent(r.part_id)}">${escape(r.number)}</a> <span class="muted">${escape(r.name)}</span></td>
        <td>${escape(r.parent_revision)} ${stateChip(r.parent_state)}</td>
        <td>${writes}</td>
        <td>${lines || '<span class="muted">nothing</span>'}</td>
        <td class="result-${escape(r.status)}">${result}</td>
      </tr>`;
  }).join('');
  const doable = report.rows.filter((r) => r.status === 'would-write' || r.status === 'would-create').length;
  $('rp-summary').textContent = preview
    ? (report.rows.length ? `${doable} of ${report.rows.length} assemblies can be changed. Untick any to leave out.` : 'No current assembly uses it.')
    : `${report.written} changed, ${report.skipped} skipped, ${report.refused} refused.`;
  $('rp-apply').disabled = !preview || doable === 0;
}

$('rp-rows').addEventListener('change', () => {
  const ticked = $('rp-rows').querySelectorAll('input[data-parent]:checked').length;
  $('rp-apply').disabled = !replacing.report || ticked === 0;
});

$('rp-preview').addEventListener('click', () => act(async () => {
  const report = await api('POST', `${partUrl()}/replace`, replaceRequest(true));
  replacing.report = report;
  renderReplace(report, true);
}));

$('rp-apply').addEventListener('click', () => act(async () => {
  const body = replaceRequest(false);
  if (!body.parents.length) return;
  const report = await api('POST', `${partUrl()}/replace`, body);
  replacing.report = null;
  renderReplace(report, false);
  await loadWhereUsed();
}));


// -- attachments
//
// The bytes go up as the request body (crate::api::attachments), so a
// 100 MB file is never read into the page or the server's memory whole.

const attaching = { part: null, revision: null };

async function renderAttachments(detail) {
  if (attaching.part !== detail.id || !detail.revision_views.some((r) => r.id === attaching.revision)) {
    attaching.part = detail.id;
    attaching.revision = defaultRevision(detail);
    $('att-preview').hidden = true;
  }
  revisionOptions($('att-revision'), detail, attaching.revision);
  await loadAttachments();
}

$('att-revision').addEventListener('change', () => {
  attaching.revision = $('att-revision').value;
  act(loadAttachments);
});

// The largest image attachment drawn as its own thumbnail in the list.
const ATTACHMENT_THUMB_MAX = 256 * 1024;

const fileSize = (n) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`);

async function loadAttachments() {
  const list = await api('GET', `${partUrl()}/attachments?revision=${encodeURIComponent(attaching.revision)}`);
  const rev = currentPart.revision_views.find((r) => r.id === attaching.revision);
  const revisionOpen = list.revision_editable;
  $('att-target').querySelector('option[value=revision]').textContent = `rev ${list.revision_label}`
    + (revisionOpen ? '' : ` (${rev ? rev.lifecycle : 'frozen'} — frozen)`);
  $('att-target').querySelector('option[value=revision]').disabled = !revisionOpen;
  if (!revisionOpen) $('att-target').value = 'part';
  const rows = [
    ...list.part.map((a) => ({ ...a, on: 'part', removable: true })),
    ...list.revision.map((a) => ({ ...a, on: `rev ${list.revision_label}`, removable: revisionOpen })),
  ];
  $('att-empty').hidden = rows.length > 0;
  $('att-wrap').hidden = rows.length === 0;
  $('att-rows').innerHTML = rows.map((a) => {
    const href = `/api/attachments/${encodeURIComponent(a.id)}`;
    // The thumbnail IS the file: a small image is drawn (when it scrolls
    // into view), a large one waits for Preview. Forty photos were 97 MB
    // fetched every time the tab opened.
    const thumb = a.inline && a.media_type.startsWith('image/') && a.size <= ATTACHMENT_THUMB_MAX
      ? `<img class="thumb" src="${href}?inline=true" alt="" loading="lazy" decoding="async">` : '';
    const view = a.inline
      ? (a.media_type.startsWith('image/')
        ? `<button type="button" class="link" data-preview="${escape(a.id)}">Preview</button>`
        : `<a href="${FileDocuments.route('attachment',a.id,currentPart.id,a.on==='part'?'':attaching.revision)}">Open</a>`)
      : '';
    return `
      <tr data-copy-kind="attachment" data-copy-id="${escape(a.id)}" data-copy-part="${escape(currentPart.id)}" data-copy-revision="${escape(a.on==='part'?'':attaching.revision)}" data-copy-label="${escape(a.name)}">
        <td>${thumb}${FileDocuments.documentLink(a,currentPart.id,a.on==='part'?'':attaching.revision)}
          <span class="muted mono">${escape(a.media_type)}</span></td>
        <td>${escape(a.on)}</td>
        <td>${escape(a.kind)}</td>
        <td class="num">${fileSize(a.size)}</td>
        <td>${escape(a.uploaded_by_name || '')}<br><span class="muted">${escape(when(a.uploaded_at))}</span></td>
        <td class="actions">${view}
          ${a.removable && me.can_author ? `<button type="button" class="link danger" data-remove-file="${escape(a.id)}" data-name="${escape(a.name)}">Remove</button>` : ''}</td>
      </tr>`;
  }).join('');
}

$('att-rows').addEventListener('click', (event) => {
  const preview = event.target.closest('button[data-preview]');
  if (preview) {
    const box = $('att-preview');
    const same = !box.hidden && box.dataset.id === preview.dataset.preview;
    box.hidden = same;
    box.dataset.id = preview.dataset.preview;
    box.innerHTML = same ? '' : `<img src="/api/attachments/${encodeURIComponent(preview.dataset.preview)}?inline=true" alt="Preview">`;
    return;
  }
  const remove = event.target.closest('button[data-remove-file]');
  if (!remove) return;
  if (!confirm(`Remove ${remove.dataset.name}?`)) return;
  act(async () => {
    await api('DELETE', `/api/attachments/${encodeURIComponent(remove.dataset.removeFile)}`);
    if ($('att-preview').dataset.id === remove.dataset.removeFile) $('att-preview').hidden = true;
    await loadAttachments();
  });
});

async function uploadFiles(files) {
  const target = $('att-target').value === 'revision'
    ? `${partUrl()}/revisions/${encodeURIComponent(attaching.revision)}/attachments`
    : `${partUrl()}/attachments`;
  let done = 0;
  for (const file of files) {
    $('att-status').textContent = `Uploading ${file.name} (${fileSize(file.size)})…`;
    const query = new URLSearchParams({ name: file.name, kind: $('att-kind').value });
    const response = await fetch(`${target}?${query}`, {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': file.type || 'application/octet-stream', 'X-CSRF-Token': csrfToken || '' },
      body: file,
    });
    if (!response.ok) {
      let message = `${response.status} ${response.statusText}`;
      try { message = (await response.json()).error || message; } catch { /* not JSON */ }
      $('att-status').textContent = '';
      await loadAttachments();
      throw new Error(`${file.name}: ${message}`);
    }
    done += 1;
  }
  $('att-status').textContent = done ? `Added ${done} file${done === 1 ? '' : 's'}.` : '';
  await loadAttachments();
}

$('att-file').addEventListener('change', () => {
  const files = [...$('att-file').files];
  $('att-file').value = '';
  if (files.length) act(() => uploadFiles(files));
});

for (const name of ['dragenter', 'dragover']) {
  $('att-drop').addEventListener(name, (event) => {
    event.preventDefault();
    $('att-drop').classList.add('over');
  });
}
for (const name of ['dragleave', 'drop']) {
  $('att-drop').addEventListener(name, () => $('att-drop').classList.remove('over'));
}
$('att-drop').addEventListener('drop', (event) => {
  event.preventDefault();
  const files = [...event.dataTransfer.files];
  if (files.length) act(() => uploadFiles(files));
});


// ----------------------------------------------------------------- backups

async function renderBackups() {
  const b = await api('GET', '/api/admin/backups');
  $('bk-config').innerHTML = b.dir
    ? `Saved to <code>${escape(b.dir)}</code>, the newest ${b.keep} kept`
      + (b.every_minutes ? `, one every ${b.every_minutes} minute${b.every_minutes === 1 ? '' : 's'}.` : '. No schedule (<code>--backup-every</code>).')
    : 'No backup directory is set (<code>--backup-dir</code>), so backups are downloaded, not saved on the server.';
  $('bk-now').hidden = !b.dir;
  $('bk-now').disabled = b.running;
  $('bk-status').textContent = b.running ? 'A backup is running…' : '';
  const last = b.last;
  $('bk-last').innerHTML = !last ? 'None since the server started.'
    : last.ok
      ? `${escape(when(last.at))} · ${escape(last.trigger)} · ${last.files} files, ${fileSize(last.size)}`
        + `${last.file ? ` · <code>${escape(last.file)}</code>` : ''}`
        + `${last.attempts > 1 ? ` · ${last.attempts} tries` : ''}`
      : `<span class="error">${escape(when(last.at))} · ${escape(last.trigger)} failed: ${escape(last.error)}</span>`;
  $('bk-empty').hidden = b.saved.length > 0;
  $('bk-wrap').hidden = b.saved.length === 0;
  $('bk-rows').innerHTML = b.saved.map((f) => `
    <tr>
      <td><a href="/api/admin/backups/file/${encodeURIComponent(f.name)}" download>${escape(f.name)}</a></td>
      <td class="num">${fileSize(f.size)}</td>
      <td>${escape(when(f.modified))}</td>
    </tr>`).join('');
}

$('bk-now').addEventListener('click', () => act(async () => {
  $('bk-now').disabled = true;
  $('bk-status').textContent = 'Backing up…';
  try {
    await api('POST', '/api/admin/backups');
  } finally {
    await renderBackups();
  }
}));

$('bk-download').addEventListener('click', () => {
  $('bk-status').textContent = 'Preparing the download…';
  setTimeout(() => act(renderBackups), 1500);
});


// ----------------------------------------------------------------- account

const SCOPE_NAMES = { full: 'Full', read: 'Read only', worker: 'Worker' };

function tokenRow(t, showOwner) {
  const expires = t.expires_at ? (t.expired ? `<span class="error">expired ${escape(when(t.expires_at))}</span>` : escape(when(t.expires_at))) : 'never';
  return `
    <tr>
      ${showOwner ? `<td class="mono">${escape(t.username)}</td>` : ''}
      <td>${escape(t.name)}</td>
      <td>${escape(SCOPE_NAMES[t.scope] || t.scope)}</td>
      <td class="mono">${escape(t.prefix)}…</td>
      <td>${escape(when(t.created_at))}</td>
      <td>${escape(when(t.last_used_at))}</td>
      <td>${expires}</td>
      <td class="actions"><button class="link danger" data-token="${escape(t.id)}" data-name="${escape(t.name)}">Revoke</button></td>
    </tr>`;
}

// A Linked desktop: an API token a browser sign-in made for a desktop app
// (`desktop` names the computer that asked).
function desktopRow(t, showOwner) {
  const d = t.desktop || {};
  return `
    <tr>
      ${showOwner ? `<td class="mono">${escape(t.username)}</td>` : ''}
      <td>${escape(d.host || 'unnamed computer')}</td>
      <td>${escape(d.os || '')}</td>
      <td class="mono">${escape(d.app_version || '')}</td>
      <td>${escape(when(t.created_at))}</td>
      <td>${escape(when(t.last_used_at))}</td>
      <td class="actions"><button class="link danger" data-token="${escape(t.id)}" data-desktop="${escape(d.host || 'this desktop app')}">Revoke</button></td>
    </tr>`;
}

function wireRevoke(container, after) {
  for (const button of container.querySelectorAll('button[data-token]')) {
    button.addEventListener('click', () => act(async () => {
      const question = button.dataset.desktop
        ? `Sign out the BREP desktop app on ${button.dataset.desktop}? It asks to sign in again at its next request.`
        : `Revoke the token "${button.dataset.name}"? Anything using it stops working at once.`;
      if (!confirm(question)) return;
      await api('DELETE', `/api/tokens/${button.dataset.token}`);
      await after();
    }));
  }
}

// Install the desktop app (My account): one card per platform for which the
// `--cad-app` directory holds BOTH the native app and its install script
// (`/cad/config`'s `native` and `installers`) — a script with no app to fetch
// would only fail. The command names this page's own origin, which is the
// address the workstation reaches the server by.
const INSTALL_PLATFORMS = [
  { id: 'linux', native: 'linux-x86_64', script: 'linux', command: (url, script) => `curl -fsSL ${script} | sh -s -- ${url}` },
  { id: 'windows', native: 'windows-x86_64', script: 'windows', command: (url, script) => `& ([scriptblock]::Create((Invoke-WebRequest -UseBasicParsing ${script}).Content)) -Url ${url}` },
];

const megabytes = (size) => `${(size / 1048576).toFixed(1)} MB`;

async function renderInstall() {
  let config = null;
  try {
    config = await api('GET', '/cad/config');
  } catch {
    config = null;
  }
  const url = location.origin;
  let offered = 0;
  for (const platform of INSTALL_PLATFORMS) {
    const app = config && config.native ? config.native[platform.native] : null;
    const script = config && config.installers ? config.installers[platform.script] : null;
    const card = $(`install-${platform.id}`);
    card.hidden = !(app && script);
    if (card.hidden) continue;
    offered += 1;
    const scriptUrl = new URL(script.path, url + '/').href;
    $(`install-${platform.id}-command`).textContent = platform.command(url, scriptUrl);
    $(`install-${platform.id}-script`).href = scriptUrl;
    $(`install-${platform.id}-app`).href = new URL(app.path, url + '/').href;
    $(`install-${platform.id}-app`).textContent = `Download the app (${megabytes(app.size)})`;
    $(`install-${platform.id}-hash`).textContent = `SHA-256 ${app.sha256}`;
  }
  $('install-none').hidden = offered > 0;
}

for (const platform of INSTALL_PLATFORMS) {
  const copy = $(`install-${platform.id}-copy`);
  copy.addEventListener('click', () => act(async () => {
    await navigator.clipboard.writeText($(`install-${platform.id}-command`).textContent);
    copy.textContent = 'Copied';
  }));
}

async function renderAccount() {
  $('account-who').textContent = `Signed in as ${me.username}${me.display_name ? ` (${me.display_name})` : ''}.`;
  await renderInstall();
  const all = await api('GET', '/api/tokens');
  const desktops = all.filter((t) => t.desktop);
  const tokens = all.filter((t) => !t.desktop);
  $('desktop-rows').innerHTML = desktops.map((t) => desktopRow(t, false)).join('');
  $('desktops-empty').hidden = desktops.length > 0;
  wireRevoke($('desktop-rows'), renderAccount);
  $('token-rows').innerHTML = tokens.map((t) => tokenRow(t, false)).join('');
  $('tokens-empty').hidden = tokens.length > 0;
  wireRevoke($('token-rows'), renderAccount);
  if (me.is_admin) {
    const users = await api('GET', '/api/users');
    const current = $('tk-user').value || me.id;
    $('tk-user').innerHTML = users
      .map((u) => `<option value="${escape(u.id)}">${escape(u.username)}${u.id === me.id ? ' (you)' : ''}</option>`)
      .join('');
    $('tk-user').value = current;
  }
}

$('password-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    if ($('pw-new').value !== $('pw-again').value) throw new Error('The two new passwords are not the same.');
    const done = await api('POST', '/api/me/password', { current: $('pw-current').value, new: $('pw-new').value });
    for (const id of ['pw-current', 'pw-new', 'pw-again']) $(id).value = '';
    $('pw-status').textContent = `Changed. ${done.other_sessions_ended} other session${done.other_sessions_ended === 1 ? '' : 's'} signed out.`;
  });
});

$('logout-all').addEventListener('click', () => act(async () => {
  if (!confirm('Sign out of every browser, this one included?')) return;
  await api('POST', '/api/logout-all');
  me = null;
  location.hash = '';
  location.reload();
}));

$('token-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    const body = { name: $('tk-name').value.trim(), scope: $('tk-scope').value };
    const days = Number($('tk-days').value);
    if (days > 0) body.expires_days = days;
    if (me.is_admin && $('tk-user').value) body.user_id = $('tk-user').value;
    const created = await api('POST', '/api/tokens', body);
    $('tk-name').value = '';
    $('tk-days').value = '';
    $('token-secret-text').textContent = created.token;
    $('token-secret').hidden = false;
    await renderAccount();
  });
});

$('token-copy').addEventListener('click', () => act(async () => {
  await navigator.clipboard.writeText($('token-secret-text').textContent);
  $('token-copy').textContent = 'Copied';
}));

$('token-done').addEventListener('click', () => {
  $('token-secret-text').textContent = '';
  $('token-secret').hidden = true;
  $('token-copy').textContent = 'Copy';
});

// ---------------------------------------------------------------- security

async function renderSecurity() {
  const [lockouts, all] = await Promise.all([
    api('GET', '/api/security/lockouts'),
    api('GET', '/api/tokens?all=true'),
  ]);
  const desktops = all.filter((t) => t.desktop);
  const tokens = all.filter((t) => !t.desktop);
  $('all-desktop-rows').innerHTML = desktops.map((t) => desktopRow(t, true)).join('');
  $('all-desktops-empty').hidden = desktops.length > 0;
  wireRevoke($('all-desktop-rows'), renderSecurity);
  $('lockout-rows').innerHTML = lockouts.map((l) => `
    <tr>
      <td>${l.kind === 'user' ? 'Username' : 'Address'}</td>
      <td class="mono">${escape(l.key)}</td>
      <td>${l.failures}</td>
      <td>${escape(when(l.last_failure))}</td>
      <td>${l.locked ? `<span class="error">${escape(when(l.locked_until))}</span>` : '<span class="muted">not locked</span>'}</td>
      <td class="actions"><button class="link" data-kind="${escape(l.kind)}" data-key="${escape(l.key)}">Clear</button></td>
    </tr>`).join('');
  $('lockouts-empty').hidden = lockouts.length > 0;
  $('lockouts-clear').disabled = lockouts.length === 0;
  for (const button of $('lockout-rows').querySelectorAll('button[data-key]')) {
    button.addEventListener('click', () => act(async () => {
      const params = new URLSearchParams({ kind: button.dataset.kind, key: button.dataset.key });
      await api('DELETE', `/api/security/lockouts?${params}`);
      await renderSecurity();
    }));
  }
  $('all-token-rows').innerHTML = tokens.map((t) => tokenRow(t, true)).join('');
  $('all-tokens-empty').hidden = tokens.length > 0;
  wireRevoke($('all-token-rows'), renderSecurity);
}

$('lockouts-clear').addEventListener('click', () => act(async () => {
  if (!confirm('Clear every sign-in lockout?')) return;
  await api('DELETE', '/api/security/lockouts');
  await renderSecurity();
}));

// ---------------------------------------------------------------- audit log

const AUDIT_PAGE = 50;

// One value, short enough for a table cell; the full text is in the title.
function auditValue(value) {
  if (value === null || value === undefined) return '—';
  const text = typeof value === 'string' ? value : JSON.stringify(value);
  return text.length > 80 ? `${text.slice(0, 77)}…` : text;
}

// A review's rounds and a discussion are whole lists in the log; a cell says
// what they amount to — the last round's status, the newest comment.
function auditSummary(field, value) {
  if (!Array.isArray(value)) return value;
  const last = value[value.length - 1];
  if (!last) return value.length ? value : 'none';
  if (field === 'reviews') {
    const d = last.decisions || [];
    const said = d.length ? `, last: ${d[d.length - 1].verdict}` : '';
    return `${value.length} round${value.length === 1 ? '' : 's'}; current ${last.status}${said}`;
  }
  if (field === 'comments') return `${value.length} comment${value.length === 1 ? '' : 's'}; newest "${last.body}"`;
  if (field === 'items') return `${value.length} item${value.length === 1 ? '' : 's'}`;
  return value;
}

function auditChanges(event) {
  const lines = Object.entries(event.changes || {}).flatMap(([field, raw]) => {
    if (field === 'content_hash') return '<div>Model document updated</div>';
    if (field === 'thumbnail') return '<div>Preview updated</div>';
    if (field === 'size' && event.changes.content_hash) return [];
    const change = { before: raw.before === null ? null : auditSummary(field, raw.before), after: auditSummary(field, raw.after) };
    const before = change.before === null ? '' : `${escape(auditValue(change.before))}<span class="arrow">→</span>`;
    const full = `${field}: ${JSON.stringify(raw.before)} → ${JSON.stringify(raw.after)}`;
    return `<div title="${escape(full)}"><span class="field">${escape(field)}</span> ${before}${escape(auditValue(change.after))}</div>`;
  });
  if (event.detail) lines.push(`<div>${escape(event.detail)}</div>`);
  return lines.join('');
}

function auditTarget(event) {
  const e = event.entity;
  const label = escape(e.label || e.id);
  if (e.kind === 'part') return `<a href="#/part/${encodeURIComponent(e.id)}">${label}</a>`;
  if (e.kind === 'revision' && e.part_id) return `<a href="#/part/${encodeURIComponent(e.part_id)}">${label}</a>`;
  return `<span class="muted">${escape(e.kind)}</span> ${label}`;
}

function auditRow(event, showTarget) {
  const who = event.actor.username || '(server)';
  const via = [event.actor.via, event.actor.ip].filter(Boolean).join(' · ');
  return `
    <tr>
      <td class="when">${escape(when(event.at))}</td>
      <td>${escape(who)}<div class="via">${escape(via)}</div></td>
      <td class="action">${escape(event.action)}</td>
      <td>${showTarget ? auditTarget(event) : escape(event.entity.kind === 'revision' ? `rev ${event.entity.label.split(' rev ').pop()}` : 'part')}</td>
      <td class="changes">${auditChanges(event)}</td>
    </tr>`;
}

// A list that pages backwards with "Older": the rows so far, the query, and
// the oldest id shown.
async function pageAudit({ base, params, rows, empty, more, showTarget, append }) {
  const query = new URLSearchParams(params);
  query.set('limit', String(AUDIT_PAGE));
  if (append && rows.dataset.oldest) query.set('before', rows.dataset.oldest);
  const events = await api('GET', `${base}?${query}`);
  const html = events.map((e) => auditRow(e, showTarget)).join('');
  rows.innerHTML = append ? rows.innerHTML + html : html;
  if (events.length) rows.dataset.oldest = String(events[events.length - 1].id);
  else if (!append) delete rows.dataset.oldest;
  empty.hidden = rows.children.length > 0;
  more.hidden = events.length < AUDIT_PAGE;
}

// The part page's History panel.
let historyPart = null;

// Manufacturing instructions: on instructions, the assembly each revision
// instructs; on anything else, the instructions that instruct it (stale once
// the assembly has a newer revision than the one instructed).
async function renderInstructions(detail) {
  const own = detail.document_class === 'instructions';
  $('instructions-own').hidden = !own;
  $('instructions-by').hidden = own;
  if (own) {
    const rows = detail.revision_views.map((revision) => {
      const full = detail.revisions.find((r) => r.id === revision.id);
      const target = full?.instructs;
      const player = `/instructions/${encodeURIComponent(detail.number)}/${encodeURIComponent(revision.id)}`;
      const share = full?.lifecycle === 'released' && me?.can_author ? ` <button type="button" class="link" data-share="${escape(revision.id)}">Customer link</button>` : '';
      return `<tr><td>${escape(revision.label)}</td><td>${target ? `<a href="#/part/${encodeURIComponent(target.part)}">${escape(target.part)}</a> rev ${escape(target.revision)}` : '<span class="muted">No PLM assembly</span>'}</td>
        <td>${full?.player ? `<a href="${player}" target="_blank" rel="noopener">Open player</a> · <a href="${player}?mode=customer" target="_blank" rel="noopener">customer view</a>${share}` : '<span class="muted">Saved from the CAD app, the player follows</span>'}<span class="attrs-line" data-share-out="${escape(revision.id)}"></span>${share ? `<ul class="plain share-list" data-share-list="${escape(revision.id)}"></ul>` : ''}</td></tr>`;
    });
    $('instructions-own-rows').innerHTML = rows.join('');
    const sharesUrl = (rev) => `/api/parts/${encodeURIComponent(detail.id)}/revisions/${encodeURIComponent(rev)}/shares`;
    // Each released revision's customer links, each revocable. The token is
    // never listed: only the label and who made it.
    const paintShares = async (rev) => {
      const out = $('instructions-own-rows').querySelector(`[data-share-list="${CSS.escape(rev)}"]`);
      if (!out) return;
      const shares = await api('GET', sharesUrl(rev));
      out.innerHTML = shares.map((share) => `<li data-share-id="${escape(share.id)}">${escape(share.label || 'Customer link')} <span class="muted">by ${escape(share.created_by)}, ${new Date(share.created_at * 1000).toLocaleDateString()}</span> <button type="button" class="link" data-revoke>Revoke</button></li>`).join('');
      for (const item of out.querySelectorAll('[data-share-id]')) item.querySelector('[data-revoke]').onclick = () => act(async () => {
        if (!confirm(`Revoke "${item.firstChild.textContent.trim()}"? The link stops working at once.`)) return;
        await api('DELETE', `${sharesUrl(rev)}/${encodeURIComponent(item.dataset.shareId)}`);
        await paintShares(rev);
      });
    };
    for (const button of $('instructions-own-rows').querySelectorAll('[data-share]')) {
      button.onclick = () => act(async () => {
        const label = prompt('Who is this customer link for? (shown in the list, not to them)'); if (label === null) return;
        const made = await api('POST', sharesUrl(button.dataset.share), { label });
        $('instructions-own-rows').querySelector(`[data-share-out="${CSS.escape(button.dataset.share)}"]`).textContent = `Link (shown once): ${location.origin}${made.url}`;
        await paintShares(button.dataset.share);
      });
      await paintShares(button.dataset.share);
    }
    return;
  }
  const rows = await api('GET', `/api/parts/${encodeURIComponent(detail.id)}/instructions`);
  $('instructions-empty').hidden = rows.length > 0;
  $('instructions-rows').innerHTML = rows.map((row) => `<tr><td><a href="#/part/${encodeURIComponent(row.part)}">${escape(row.number)}</a> ${escape(row.name)}</td><td>${escape(row.label)}</td><td>${escape(row.state)}</td><td>${escape(row.target_label)}${row.stale ? ' <span class="flag-chip">newer assembly revision</span>' : ''}</td></tr>`).join('');
}

async function renderHistory(detail, append = false) {
  historyPart = detail.id;
  const base = `/api/parts/${encodeURIComponent(detail.id)}/history`;
  $('history-csv').href = `${base}?format=csv&limit=5000`;
  await pageAudit({
    base, params: {}, rows: $('history-rows'), empty: $('history-empty'), more: $('history-more'),
    showTarget: false, append,
  });
}

$('history-more').addEventListener('click', () => act(async () => {
  if (currentPart && currentPart.id === historyPart) await renderHistory(currentPart, true);
}));

// The admin's Audit page.
function auditParams() {
  const params = {};
  const user = $('af-user').value.trim();
  if (user) params.user = user;
  if ($('af-action').value) params.action = $('af-action').value;
  if ($('af-kind').value) params.kind = $('af-kind').value;
  // Dates are the viewer's local days: from the start of one to the end of the other.
  if ($('af-since').value) params.since = String(Math.floor(new Date(`${$('af-since').value}T00:00:00`).getTime() / 1000));
  if ($('af-until').value) params.until = String(Math.floor(new Date(`${$('af-until').value}T23:59:59`).getTime() / 1000));
  return params;
}

async function renderAudit(append = false) {
  const params = auditParams();
  $('audit-csv').href = `/api/audit?${new URLSearchParams({ ...params, format: 'csv', limit: '5000' })}`;
  await pageAudit({
    base: '/api/audit', params, rows: $('audit-rows'), empty: $('audit-empty'), more: $('audit-more'),
    showTarget: true, append,
  });
}

$('audit-filter').addEventListener('submit', (event) => {
  event.preventDefault();
  act(() => renderAudit());
});

$('af-clear').addEventListener('click', () => {
  for (const id of ['af-user', 'af-since', 'af-until']) $(id).value = '';
  $('af-action').value = '';
  $('af-kind').value = '';
  act(() => renderAudit());
});

$('audit-more').addEventListener('click', () => act(() => renderAudit(true)));

// ------------------------------------------------------------------ reviews

// A due date typed as a local day means the end of that day.
const dayToSeconds = (day) => (day ? Math.floor(new Date(`${day}T23:59:59`).getTime() / 1000) : 0);
const secondsToDay = (seconds) => {
  if (!seconds) return '';
  const d = new Date(seconds * 1000);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};
const splitList = (text) => text.split(',').map((t) => t.trim()).filter(Boolean);
const reviewChip = (status) => `<span class="state review-${escape(status)}">${escape(status)}</span>`;

// Show a `review-event` hook's failure: the event itself stood.
function showWarnings(result) {
  if (result && result.warnings && result.warnings.length) banner(result.warnings.join('\n'));
}

// The badge in the header: how many reviews wait on the person signed in.
async function refreshInbox() {
  if (!me) return;
  try {
    const inbox = await api('GET', '/api/inbox');
    $('inbox-badge').textContent = inbox.count;
    $('inbox-badge').hidden = inbox.count === 0;
  } catch {
    // The badge is a convenience; the page it links to says what is wrong.
  }
}

function reviewCell(rev) {
  const parts = [];
  if (rev.review) {
    const r = rev.review;
    parts.push(reviewChip(r.status));
    if (r.live && r.required_approvals) parts.push(`<span class="muted">${r.approvals}/${r.required_approvals}</span>`);
  }
  if (rev.comments) parts.push(`<span class="muted" title="Comments">💬 ${rev.comments}</span>`);
  return parts.length ? parts.join(' ') : '<span class="muted">—</span>';
}

// -- the reviews page

async function renderReviews() { await Workbench.inbox(); }

// -- one revision's review, on the part page

let reviewRevision = '';
let replyTo = '';

// The revision the panel opens on: one in review if any, else the newest.
function defaultReviewRevision(detail) {
  const views = detail.revision_views;
  const inReview = [...views].reverse().find((r) => r.lifecycle === 'inreview');
  return (inReview || views[views.length - 1] || {}).id || '';
}

function roundHtml(round, current, prefix = 'rv') {
  const due = round.due
    ? ` · due ${escape(when(round.due))}${round.overdue ? ' <span class="state review-rejected">overdue</span>' : ''}`
    : '';
  const reviewers = round.reviewers.length
    ? round.reviewers.map((r) => {
      if (r.kind === 'group') {
        const who = r.approved_by.length ? ` — approved by ${escape(r.approved_by.join(', '))}` : '';
        return `<li><span class="badge">group</span> ${escape(r.name)}${who}</li>`;
      }
      const said = r.verdict ? ` ${reviewChip(r.verdict === 'approve' ? 'approved' : 'rejected')}` : ' <span class="muted">waiting</span>';
      return `<li>${escape(r.name)}${said}</li>`;
    }).join('')
    : '<li class="muted">Anyone in the check-in group may decide.</li>';
  const decisions = round.decisions.map((d) => `
    <li>${reviewChip(d.verdict === 'approve' ? 'approved' : 'rejected')} <strong>${escape(d.name)}</strong>
      <span class="muted">${escape(when(d.at))}</span>${d.comment ? `<div class="comment-body">${escape(d.comment)}</div>` : ''}</li>`).join('');
  const closed = round.closed_at
    ? `<p class="muted">Ended ${escape(when(round.closed_at))}${round.closed_by ? ` by ${escape(round.closed_by)}` : ''}.</p>`
    : '';
  const decide = current && round.can_decide ? `
    <div class="decide">
      <textarea id="${prefix}-decision-comment" rows="2" placeholder="Comment — required to reject" aria-label="Decision comment"></textarea>
      <div class="toolbar">
        <button type="button" data-verdict="approve">Approve</button>
        <button type="button" class="danger" data-verdict="reject">Reject</button>
      </div>
    </div>` : '';
  const change = current && round.can_change ? `<button type="button" class="ghost" id="${prefix}-change">Change</button>` : '';
  return `
    <div class="round">
      <div class="toolbar">
        ${reviewChip(round.status)}
        <strong>${round.approvals} of ${round.required_approvals} approval${round.required_approvals === 1 ? '' : 's'}</strong>
        <span class="muted">submitted by ${escape(round.opened_by)} ${escape(when(round.opened_at))}${due}
          · rule from ${escape(round.rule_source)}</span>
        <span class="spacer"></span>
        ${change}
      </div>
      <ul class="plain reviewers">${reviewers}</ul>
      ${decisions ? `<ul class="plain decisions">${decisions}</ul>` : ''}
      ${closed}
      ${decide}
    </div>`;
}

function threadHtml(comments, canComment) {
  const children = new Map();
  for (const c of comments) {
    const key = c.parent || '';
    if (!children.has(key)) children.set(key, []);
    children.get(key).push(c);
  }
  const known = new Set(comments.map((c) => c.id));
  const render = (parent) => (children.get(parent) || []).map((c) => `
    <li>
      <div class="comment-head"><strong>${escape(c.author)}</strong> <span class="muted">${escape(when(c.at))}</span>
        ${canComment ? `<button type="button" class="link" data-reply="${escape(c.id)}" data-author="${escape(c.author)}">Reply</button>` : ''}</div>
      <div class="comment-body">${escape(c.body)}</div>
      ${children.has(c.id) ? `<ul class="plain thread">${render(c.id)}</ul>` : ''}
    </li>`).join('');
  // A reply whose parent is unknown still shows, at the top level.
  const orphans = comments.filter((c) => c.parent && !known.has(c.parent)).map((c) => c.id);
  for (const id of orphans) {
    const c = comments.find((x) => x.id === id);
    children.set('', [...(children.get('') || []), { ...c, parent: '' }]);
  }
  return `<ul class="plain thread">${render('')}</ul>`;
}

async function renderReview(detail) {
  const views = detail.revision_views;
  if (!views.some((r) => r.id === reviewRevision)) reviewRevision = defaultReviewRevision(detail);
  $('rv-revision').innerHTML = views.map((r) => `<option value="${escape(r.id)}">${escape(r.label)} — ${escape(statusName(r.lifecycle))}</option>`).join('');
  $('rv-revision').value = reviewRevision;
  if (!reviewRevision) return;
  const panel = await api('GET', `${revUrl(reviewRevision)}/review`);
  $('rv-current').innerHTML = panel.current ? roundHtml(panel.current, true) : '';
  $('rv-none').hidden = !!panel.current;
  const rule = panel.rule;
  $('rv-none').textContent = rule.required_approvals
    ? `Not submitted for review yet. It needs ${rule.required_approvals} approval${rule.required_approvals === 1 ? '' : 's'} before it can release (rule from ${panel.rule_source}).`
    : `Not submitted for review. No approval is needed to release it (rule from ${panel.rule_source}); submitting asks for one anyway.`;
  $('rv-history').hidden = panel.history.length === 0;
  $('rv-history-list').innerHTML = panel.history.map((r) => roundHtml(r, false)).join('');
  $('rv-comments').innerHTML = panel.comments.length ? threadHtml(panel.comments, panel.can_comment) : '';
  $('rv-comments-empty').hidden = panel.comments.length > 0;
  $('rv-comment-form').hidden = !panel.can_comment;
  setReplyTo('', '');

  for (const button of $('rv-current').querySelectorAll('button[data-verdict]')) {
    button.addEventListener('click', () => act(async () => {
      const verdict = button.dataset.verdict;
      const comment = $('rv-decision-comment').value;
      if (verdict === 'reject' && !confirm('Reject this revision? It goes back to Draft, and the review ends.')) return;
      showWarnings(await api('POST', `${revUrl(reviewRevision)}/review/decision`, { verdict, comment }));
      await renderPart(currentPart.id);
    }));
  }
  const change = $('rv-change');
  if (change) change.addEventListener('click', () => { roundTarget = null; openRoundDialog(panel.current); });
  for (const button of $('rv-comments').querySelectorAll('button[data-reply]')) {
    button.addEventListener('click', () => {
      setReplyTo(button.dataset.reply, button.dataset.author);
      $('rv-comment').focus();
    });
  }
}

function setReplyTo(id, author) {
  replyTo = id;
  $('rv-reply-to').hidden = !id;
  $('rv-reply-to').textContent = id ? `Replying to ${author}` : '';
  $('rv-reply-cancel').hidden = !id;
}

$('rv-revision').addEventListener('change', () => act(async () => {
  reviewRevision = $('rv-revision').value;
  await renderReview(currentPart);
}));
$('rv-reply-cancel').addEventListener('click', () => setReplyTo('', ''));
$('rv-comment-form').addEventListener('submit', (event) => {
  event.preventDefault();
  act(async () => {
    const body = $('rv-comment').value;
    showWarnings(await api('POST', `${revUrl(reviewRevision)}/comments`, { body, parent: replyTo }));
    $('rv-comment').value = '';
    await renderPart(currentPart.id);
  });
});

// Reviewers as the server reports them, as the text the inputs take.
function reviewersText(refs, names = {}) {
  return refs.map((r) => `${r.kind}:${r.kind === 'user' ? (names[r.id] || r.id) : r.id}`).join(', ');
}

// -- submitting

let submitting = null;

async function openSubmit(revisionId) {
  submitting = revisionId;
  const rev = currentPart.revision_views.find((r) => r.id === revisionId);
  const panel = await api('GET', `${revUrl(revisionId)}/review`);
  $('sb-title').textContent = `${currentPart.number} rev ${rev ? rev.label : ''}`;
  const n = panel.rule.required_approvals;
  $('sb-rule').textContent = `${n ? `It needs ${n} approval${n === 1 ? '' : 's'}` : 'No approval is needed'} by the rule from ${panel.rule_source}.`
    + (panel.rule.reviewers.length ? ' The rule names its reviewers; you can add more.' : ' Anyone in the check-in group may decide, unless you name reviewers.');
  $('sb-reviewers').value = '';
  $('sb-due').value = '';
  $('sb-note').value = '';
  $('submit-dialog').showModal();
}

$('submit-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'submit') return;
  event.preventDefault();
  act(async () => {
    const body = { note: $('sb-note').value };
    const extra = splitList($('sb-reviewers').value);
    if (extra.length) body.reviewers = extra;
    if ($('sb-due').value) body.due = dayToSeconds($('sb-due').value);
    const result = await api('POST', `${revUrl(submitting)}/submit`, body);
    $('submit-dialog').close();
    reviewRevision = submitting;
    await renderPart(currentPart.id);
    showWarnings(result);
  });
});

// -- changing a round

function openRoundDialog(round) {
  $('rd-reviewers').value = round.reviewers.map((r) => `${r.kind}:${r.kind === 'user' ? r.name : r.id}`).join(', ');
  $('rd-due').value = secondsToDay(round.due);
  $('rd-required').value = round.required_approvals;
  $('rd-required-label').hidden = !me.can_checkin;
  $('round-dialog').showModal();
}

// Where the round dialog saves, and what it refreshes: a revision's round or
// a revision's.
let roundTarget = null;

$('round-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'save') return;
  event.preventDefault();
  act(async () => {
    const body = { reviewers: splitList($('rd-reviewers').value), due: dayToSeconds($('rd-due').value) };
    if (me.can_checkin) body.required_approvals = Number($('rd-required').value);
    const target = roundTarget || { url: `${revUrl(reviewRevision)}/review`, refresh: () => renderPart(currentPart.id) };
    const result = await api('PATCH', target.url, body);
    $('round-dialog').close();
    await target.refresh();
    showWarnings(result);
  });
});

// -- the rule, on the settings page

let reviewNames = {};

function readRule({ required, due, reviewers, self }) {
  return {
    required_approvals: Number(required.value) || 0,
    due_days: Number(due.value) || 0,
    reviewers: splitList(reviewers.value),
    allow_self_approval: self.checked,
  };
}

async function overrideOptions(select, scope, value) {
  if (scope === 'category') {
    await loadCategories();
    categoryOptions(select);
  } else {
    const types = await api('GET', '/api/part-types');
    select.innerHTML = types.map((t) => `<option value="${escape(t.id)}">${escape(t.name)} (${escape(t.id)})</option>`).join('');
  }
  if (value) select.value = value;
}

async function addOverrideRow(o = { scope: 'part_type', id: '', rule: { required_approvals: 1, due_days: 0, reviewers: [], allow_self_approval: false } }) {
  const row = document.createElement('tr');
  row.innerHTML = `
    <td><select data-f="scope" aria-label="Override for">
      <option value="part_type">Part type</option><option value="category">Category</option></select></td>
    <td><select data-f="id" aria-label="Which"></select></td>
    <td><input data-f="required" type="number" min="0" max="50" class="tiny" aria-label="Approvals" value="${o.rule.required_approvals}"></td>
    <td><input data-f="due" type="number" min="0" class="tiny" aria-label="Due days" value="${o.rule.due_days}"></td>
    <td><input data-f="reviewers" aria-label="Reviewers" placeholder="user:grace, group:quality" value="${escape(reviewersText(o.rule.reviewers, reviewNames))}"></td>
    <td><input data-f="self" type="checkbox" aria-label="The submitter's own approval counts" ${o.rule.allow_self_approval ? 'checked' : ''}></td>
    <td><button type="button" class="link danger" data-f="remove">Remove</button></td>`;
  const scope = row.querySelector('[data-f=scope]');
  scope.value = o.scope;
  await overrideOptions(row.querySelector('[data-f=id]'), o.scope, o.id);
  scope.addEventListener('change', () => act(() => overrideOptions(row.querySelector('[data-f=id]'), scope.value, '')));
  row.querySelector('[data-f=remove]').addEventListener('click', () => row.remove());
  $('set-rv-overrides').appendChild(row);
}

function readOverrides() {
  return [...$('set-rv-overrides').querySelectorAll('tr')].map((row) => {
    const f = (name) => row.querySelector(`[data-f=${name}]`);
    return {
      scope: f('scope').value,
      id: f('id').value,
      rule: readRule({ required: f('required'), due: f('due'), reviewers: f('reviewers'), self: f('self') }),
    };
  });
}

async function renderReviewSettings(settings) {
  try {
    const users = await api('GET', '/api/users');
    reviewNames = Object.fromEntries(users.map((u) => [u.id, u.username]));
  } catch {
    reviewNames = {};
  }
  const rule = settings.review_rule;
  $('set-rv-required').value = rule.required_approvals;
  $('set-rv-due').value = rule.due_days;
  $('set-rv-reviewers').value = reviewersText(rule.reviewers, reviewNames);
  $('set-rv-self').checked = rule.allow_self_approval;
  $('set-rv-overrides').innerHTML = '';
  for (const o of settings.review_overrides) await addOverrideRow(o);
}

$('set-rv-add').addEventListener('click', () => act(() => addOverrideRow()));


// --------------------------------------------------------------- workspace
//
// A user's folders of links and files (D12, the server's P6). The CAD app's File > Open
// shows the same workspace. Delete removes a link or a file, never a part (D9).

async function renderWorkspace() { await Workbench.home(); }

// "Add to workspace…" on a part's page: pick one of your folders, and follow the newest
// revision or pin one.
const wsPick = { path: [], purpose: null };

async function wsPickLoad() {
  const parent = wsPick.path.length ? wsPick.path[wsPick.path.length - 1].id : '';
  const folder = await api('GET', `/api/workspace/entries?${new URLSearchParams({ parent })}`);
  $('ws-pick-crumbs').innerHTML = [`<button type="button" class="link" data-ws-pick-crumb="0">My workspace</button>`]
    .concat(wsPick.path.map((p, i) => `<button type="button" class="link" data-ws-pick-crumb="${i + 1}">${escape(p.name)}</button>`))
    .join(' / ');
  const folders = folder.entries.filter((e) => e.kind === 'folder');
  $('ws-pick-list').innerHTML = folders.length
    ? folders.map((f) => `<li><button type="button" class="link" data-ws-pick="${escape(f.id)}" data-name="${escape(f.name)}">${escape(f.name)}/</button></li>`).join('')
    : '<li class="muted">No folders here.</li>';
}

$('ws-pick-crumbs').addEventListener('click', (event) => {
  const crumb = event.target.closest('button[data-ws-pick-crumb]');
  if (!crumb) return;
  wsPick.path = wsPick.path.slice(0, Number(crumb.dataset.wsPickCrumb));
  act(wsPickLoad);
});

$('ws-pick-list').addEventListener('click', (event) => {
  const folder = event.target.closest('button[data-ws-pick]');
  if (!folder) return;
  wsPick.path.push({ id: folder.dataset.wsPick, name: folder.dataset.name });
  act(wsPickLoad);
});

$('part-add-ws').addEventListener('click', () => act(async () => {
  if (!currentPart) return;
  wsPick.path = [];
  $('part-ws-status').textContent = '';
  $('ws-pick-title').textContent = `Add ${currentPart.number} to your workspace`;
  $('ws-pick-rev').innerHTML = ['<option value="">follow the newest revision</option>']
    .concat(currentPart.revision_views.slice().reverse().map((r) => `<option value="${escape(r.id)}">pin to ${escape(r.label)} (${escape(statusName(r.lifecycle))})</option>`))
    .join('');
  await wsPickLoad();
  $('ws-pick-dialog').showModal();
}));

$('ws-pick-form').addEventListener('submit', (event) => {
  if (event.submitter && event.submitter.value !== 'choose') return;
  event.preventDefault();
  act(async () => {
    const parent = wsPick.path.length ? wsPick.path[wsPick.path.length - 1].id : '';
    await api('POST', '/api/workspace/links', { parent, part: currentPart.id, revision: $('ws-pick-rev').value, name: $('ws-pick-name').value.trim() });
    $('ws-pick-dialog').close();
    $('ws-pick-name').value = '';
    const where = wsPick.path.length ? wsPick.path.map((p) => p.name).join(' / ') : 'the top of your workspace';
    $('part-ws-status').textContent = `Added to ${where}.`;
  });
});

// ------------------------------------------------ native model import wizard
let nativeWizard = { rows: [], types: [], job: null, running: false, stop: false, owner: null, busy: false };
const niError = error => { $('ni-error').textContent = error?.message || String(error || ''); $('ni-error').hidden = !error; };
async function niAct(fn) {
  if (nativeWizard.busy || nativeWizard.running) return;
  nativeWizard.busy = true; niError(null);
  $('ni-files-step').disabled = true; $('ni-mapping-fields').disabled = true;
  try { await fn(); } catch (error) { niError(error); }
  finally {
    nativeWizard.busy = false;
    const frozen = Boolean(nativeWizard.job) || !$('ni-review-step').hidden;
    $('ni-files-step').disabled = frozen; $('ni-mapping-fields').disabled = frozen;
  }
}
function importDatabase() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('brep-plm-native-import', 1);
    request.onupgradeneeded = () => request.result.createObjectStore('jobs');
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(new Error('Cannot save import progress in this browser. Enable browser storage before importing.'));
  });
}
async function importStorage(operation, value) {
  const db = await importDatabase();
  try {
    return await new Promise((resolve, reject) => {
      const transaction = db.transaction('jobs', operation === 'get' ? 'readonly' : 'readwrite');
      const store = transaction.objectStore('jobs');
      const key = nativeWizard.owner;
      const request = operation === 'get' ? store.get(key) : operation === 'delete' ? store.delete(key) : store.put(value, key);
      transaction.oncomplete = () => resolve(request.result);
      transaction.onerror = transaction.onabort = () => reject(new Error('Import progress could not be saved. Free browser storage before resuming.'));
    });
  } finally { db.close(); }
}
async function openNativeImport() {
  if (nativeWizard.owner === me.id) return;
  nativeWizard = { rows: [], types: await api('GET', '/api/part-types'), job: null, running: false, stop: false, owner: me.id, busy: false };
  $('ni-default-type').innerHTML = nativeWizard.types.map(t => `<option value="${escape(t.id)}">${escape(t.name)}</option>`).join('');
  nativeWizard.job = await importStorage('get');
  if (nativeWizard.job) niProgress(nativeWizard.job);
}
function niType(row) { return nativeWizard.types.find(t => t.id === row.part_type); }
function niNumbering(row) {
  const type = niType(row);
  if (!type) return 'Choose a part type';
  if (type.mode.kind === 'counter') {
    const before = nativeWizard.rows.slice(0, nativeWizard.rows.indexOf(row)).filter(r => r.action === 'create' && r.part_type === row.part_type).length;
    return `Estimated ${type.prefix}${String(type.next + before).padStart(type.digits, '0')}`;
  }
  return type.mode.kind === 'pattern' ? `Pattern: ${type.mode.regex}` : type.mode.kind === 'script' ? `Server script: ${type.mode.script}` : 'Enter a unique part number';
}
function niRenderRows() {
  $('ni-mapping-step').hidden = false;
  $('ni-rows').innerHTML = nativeWizard.rows.map((row, i) => {
    const creating = row.action === 'create', counter = niType(row)?.mode.kind === 'counter';
    return `<tr data-import-row="${i}"><td><input data-field="name" aria-label="Name for ${escape(row.name)}" value="${escape(row.name)}"><small>${row.assembly ? 'Assembly' : 'Part'} · ${escape(row.id)}${row.root ? ' · uploaded file' : ' · embedded'}${row.unchanged ? ' · unchanged' : ''}${row.note ? ` · ${escape(row.note)}` : ''}</small></td>
      <td><select data-field="action" aria-label="Action for ${escape(row.name)}">${[['create','Create part'],['revise','Create new revision'],['replace','Replace editable draft'],['reuse','Reuse existing revision']].map(([v,t]) => `<option value="${v}" ${row.action === v ? 'selected' : ''}>${t}</option>`).join('')}</select></td>
      <td><select data-field="part_type" aria-label="Part type for ${escape(row.name)}" ${creating ? '' : 'disabled'}>${nativeWizard.types.map(t => `<option value="${escape(t.id)}" ${row.part_type === t.id ? 'selected' : ''}>${escape(t.name)}</option>`).join('')}</select><small>${creating ? escape(niNumbering(row)) : 'Existing part keeps its type and number'}</small></td>
      <td><input data-field="${creating ? 'number' : 'part'}" aria-label="${creating ? 'Number' : 'Existing part'} for ${escape(row.name)}" value="${escape(creating ? row.number : row.part)}" ${creating && counter ? 'disabled placeholder="Assigned on import"' : ''}>${creating ? '' : '<button type="button" data-target-lookup class="ghost">Load revisions</button>'}</td>
      <td>${creating ? 'First revision' : row.action === 'revise' ? 'Next revision' : `<select data-field="revision" aria-label="Revision for ${escape(row.name)}"><option value="">Newest (load to choose)</option>${(row.available || []).map(r => `<option value="${escape(r.id)}" ${r.id === row.revision ? 'selected' : ''}>${escape(r.label)} · ${escape(statusName(r.lifecycle))}${r.locked_by ? ' · checked out' : ''}</option>`).join('')}</select>`}</td></tr>`;
  }).join('');
}
async function niReadFiles(list) {
  if (nativeWizard.job) throw new Error('Finish the current import or choose Start another import before choosing files.');
  const files = [...list].filter(f => /\.nbrep$/i.test(f.name));
  if (!files.length) throw new Error('Choose at least one .nbrep file.');
  $('ni-review-step').hidden = true;
  $('ni-mapping-step').hidden = true;
  nativeWizard.rows = [];
  $('ni-rows').replaceChildren();
  $('ni-file-summary').textContent = 'Reading native models…';
  const documents = [];
  for (const file of files) {
    try { documents.push({ name: file.webkitRelativePath || file.name, document: JSON.parse(await file.text()) }); }
    catch { throw new Error(`${file.name}: this is not valid native JSON`); }
  }
  nativeWizard.documents = documents; nativeWizard.choices = {};
  await niPlan();
}
// Plan the chosen files and propose an action per item from what the server
// already holds. Re-run when a conflict answer or the import set changes.
async function niPlan() {
  const documents = nativeWizard.documents;
  const plan = NativeImport.plan(documents, nativeWizard.choices);
  if (plan.errors.length) { $('ni-file-summary').textContent = 'Files need attention.'; throw new Error(plan.errors.join('\n')); }
  const types = nativeWizard.types;
  if (!types.length) throw new Error('Create a part type before importing models.');
  // The root assembly names the set by default, so a file and its folder import alike.
  if (!$('ni-namespace').value.trim()) $('ni-namespace').value = plan.tree[0]?.name || NativeImport.path(documents[0].name).split('/').pop();
  const namespace = $('ni-namespace').value;
  for (const row of plan.rows) {
    row.action = 'create'; row.number = ''; row.part = ''; row.revision = '';
    row.part_type = (types.find(t => t.id === (row.assembly ? 'assembly' : 'component')) || types[0]).id;
    row.external_ref = NativeImport.externalRef(namespace, row.id);
  }
  await NativeImport.propose(plan.rows, api);
  nativeWizard.rows = plan.rows; nativeWizard.plan = plan;
  const unchanged = plan.rows.filter(r => r.unchanged).length;
  $('ni-file-summary').textContent = `${documents.length} file(s), ${plan.rows.length} distinct parts and assemblies, ${plan.rows.reduce((n,r) => n + Object.keys(r.dependencies).length, 0)} component links${unchanged ? `, ${unchanged} unchanged since the last import` : ''}.`;
  niRenderPlan(plan);
  niRenderRows();
}
function niRenderPlan(plan) {
  const branch = (node, trail) => {
    const here = trail ? `${trail}/${node.name}` : node.name;
    const label = trail ? `${node.name} ×${node.quantity}` : node.name;
    return `<li data-tree-node="${escape(trail ? `${here} ×${node.quantity}` : here)}">${escape(label)}${node.existing ? ' <small>existing PLM revision</small>' : ''}${node.children.length ? `<ul>${node.children.map(c => branch(c, here)).join('')}</ul>` : ''}</li>`;
  };
  $('ni-tree').innerHTML = plan.tree.map(node => branch(node, '')).join('');
  $('ni-conflicts').hidden = !plan.conflicts.length;
  $('ni-conflict-rows').innerHTML = plan.conflicts.map(c => `<li data-conflict="${escape(c.id)}">${escape(c.message)} <label class="inline">Use <select data-conflict-choice aria-label="Copy of ${escape(c.name)} to import">${c.options.map(o => `<option value="${escape(o.value)}" ${o.value === c.choice ? 'selected' : ''}>${escape(o.label)}</option>`).join('')}</select></label></li>`).join('');
}
$('ni-conflict-rows').addEventListener('change', event => {
  const item = event.target.closest('[data-conflict]');
  if (!item || nativeWizard.running || nativeWizard.busy) return;
  nativeWizard.choices[item.dataset.conflict] = event.target.value;
  niAct(niPlan);
});
$('ni-namespace').addEventListener('change', () => {
  if (nativeWizard.documents?.length && !nativeWizard.job && $('ni-review-step').hidden) niAct(niPlan);
});
for (const id of ['ni-files', 'ni-folder']) $(id).addEventListener('change', event => niAct(() => niReadFiles(event.target.files)));
$('ni-rows').addEventListener('change', event => {
  const tr = event.target.closest('[data-import-row]'), field = event.target.dataset.field;
  if (!tr || !field || nativeWizard.running || nativeWizard.busy) return;
  const row = nativeWizard.rows[Number(tr.dataset.importRow)];
  row[field] = event.target.value;
  if (field === 'part') { row.available = []; row.revision = ''; }
  if (field === 'part_type') row.number = '';
  if (field === 'action') row.userAction = true;
  if (['action','part_type'].includes(field)) niRenderRows();
  // What this row now places changes what its parents would write.
  if (['action','revision','part'].includes(field)) niAct(async () => { await NativeImport.repropose(nativeWizard.rows, api, row.id); niRenderRows(); });
});
$('ni-rows').addEventListener('click', event => {
  if (!event.target.closest('[data-target-lookup]')) return;
  const row = nativeWizard.rows[Number(event.target.closest('[data-import-row]').dataset.importRow)];
  niAct(async () => {
    const p = await api('GET', `/api/parts/${encodeURIComponent(row.part.trim())}`);
    row.part = p.number; row.part_type = p.part_type; row.available = p.revision_views; row.revision = p.revision_views.at(-1)?.id || '';
    niRenderRows();
  });
});
$('ni-apply-type').addEventListener('click', () => {
  for (const row of nativeWizard.rows.filter(r => r.action === 'create')) { row.part_type = $('ni-default-type').value; row.number = ''; }
  niRenderRows();
});
$('ni-review').addEventListener('click', () => niAct(async () => {
  const namespace = $('ni-namespace').value.trim();
  if (!namespace) throw new Error('Give this import set a name.');
  if (!nativeWizard.rows.length) throw new Error('Choose native files first.');
  for (const row of nativeWizard.rows) {
    if (!row.name.trim()) throw new Error('Every part needs a name.');
    delete row.reviewed;
    row.external_ref = NativeImport.externalRef(namespace, row.id);
    if (row.action !== 'create') continue;
    const type = niType(row);
    if (!type) throw new Error(`${row.name}: select a part type`);
    if (['free','pattern'].includes(type.mode.kind) && !row.number.trim()) throw new Error(`${row.name}: enter a number for ${type.name}`);
    if (row.number.trim()) {
      const matches = (await api('GET', `/api/parts?q=${encodeURIComponent(row.number.trim())}&limit=50`)).parts;
      if (matches.some(p => p.number.toLowerCase() === row.number.trim().toLowerCase())) throw new Error(`${row.number}: already exists; choose an update action for this row`);
    }
    const matches = (await api('GET', `/api/parts?external_ref=${encodeURIComponent(row.external_ref)}&part_type=${encodeURIComponent(row.part_type)}&limit=2`)).parts;
    if (matches.length) throw new Error(`${row.name}: already imported as ${matches[0].number}; choose an update action`);
  }
  const numbers = nativeWizard.rows.filter(r => r.action === 'create' && r.number.trim()).map(r => r.number.trim().toLowerCase());
  if (new Set(numbers).size !== numbers.length) throw new Error('Two new parts have the same number.');
  await api('POST', '/api/import/validate', nativeWizard.rows.filter(r => r.action === 'create').map(r => ({part_type: r.part_type, number: r.number})));
  await NativeImport.inspect(nativeWizard.rows, api);
  $('ni-review-rows').innerHTML = nativeWizard.rows.map(row => `<tr><td>${escape(row.name)}<br><small>${escape(row.id)}</small></td><td>${escape({create:'Create part',revise:'Create new revision',replace:'REPLACE draft document and BOM',reuse:'Reuse without changes'}[row.action])}${row.unchanged ? ' (unchanged)' : ''}${row.note ? `<br><small>${escape(row.note)}</small>` : ''}</td><td>${escape(row.reviewed?.number || row.number || niNumbering(row))}</td><td>${escape(row.action === 'create' ? 'First revision' : row.action === 'revise' ? 'New revision' : row.reviewed.label)}</td></tr>`).join('');
  $('ni-review-summary').textContent = `${nativeWizard.rows.length} items: ${nativeWizard.rows.filter(r=>r.action==='create').length} new parts, ${nativeWizard.rows.filter(r=>r.action==='revise').length} new revisions, ${nativeWizard.rows.filter(r=>r.action==='replace').length} draft replacements, ${nativeWizard.rows.filter(r=>r.action==='reuse').length} reused revisions.`;
  $('ni-review-step').hidden = false; $('ni-files-step').disabled = true; $('ni-mapping-fields').disabled = true;
  $('ni-confirm').checked = false; $('ni-run').disabled = true;
  $('ni-review-step').scrollIntoView({ block: 'start' });
}));
$('ni-confirm').addEventListener('change', () => { $('ni-run').disabled = !$('ni-confirm').checked; });
$('ni-back').addEventListener('click', () => {
  $('ni-review-step').hidden = true; $('ni-files-step').disabled = false; $('ni-mapping-fields').disabled = false;
});
function niProgress(job) {
  $('ni-results').hidden = false; $('ni-status').textContent = job.current || 'Ready to resume';
  $('ni-files-step').disabled = true; $('ni-mapping-fields').disabled = true;
  $('ni-result-rows').innerHTML = job.rows.map(row => {
    const target = job.targets[row.id];
    return `<li>${escape(row.name)} — ${target ? `<a href="#/part/${encodeURIComponent(target.part)}">${escape(target.number)} / ${escape(target.label)}</a> · ${target.done ? row.action === 'reuse' ? 'reused' : 'imported' : target.written ? 'saved, awaiting check-in' : 'allocated, awaiting document'}` : row.allocating ? 'allocation outcome unconfirmed — inspect the server before retrying' : 'not started'}</li>`;
  }).join('');
  $('ni-resume').hidden = Boolean(job.complete); $('ni-resume').disabled = nativeWizard.running;
  $('ni-reset').disabled = nativeWizard.running; $('ni-stop').hidden = !nativeWizard.running;
}
async function niExecute() {
  nativeWizard.running = true; nativeWizard.stop = false; niError(null);
  $('ni-review-step').hidden = true;
  $('ni-run').disabled = true;
  try { await NativeImport.run(nativeWizard.job, api, job => importStorage('put', job), niProgress, () => nativeWizard.stop); }
  catch (error) { niError(error); }
  finally { nativeWizard.running = false; niProgress(nativeWizard.job); }
}
$('ni-run').addEventListener('click', () => niAct(async () => {
  if (!$('ni-confirm').checked) return;
  nativeWizard.job = { rows: JSON.parse(JSON.stringify(nativeWizard.rows)), targets: {}, complete: false, current: 'Ready to import' };
  await importStorage('put', nativeWizard.job);
  await niExecute();
}));
$('ni-resume').addEventListener('click', () => niAct(niExecute));
$('ni-stop').addEventListener('click', () => { nativeWizard.stop = true; });
$('ni-receipt').addEventListener('click', () => {
  const job = nativeWizard.job;
  const receipt = { complete: job.complete, current: job.current, items: job.rows.map(row => ({ source: row.id, action: row.action, allocationPending: Boolean(row.allocating && !job.targets[row.id]), reviewed: row.reviewed, target: job.targets[row.id] && { ...job.targets[row.id], reusedDocument: undefined } })) };
  const url = URL.createObjectURL(new Blob([JSON.stringify(receipt,null,2)], {type:'application/json'}));
  const a = document.createElement('a'); a.href = url; a.download = 'native-import-receipt.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
});
$('ni-reset').addEventListener('click', () => niAct(async () => {
  if (!nativeWizard.job?.complete && !confirm('Keep existing parts and discard this import’s saved progress? Download its receipt first if you need to reconcile it.')) return;
  await importStorage('delete'); nativeWizard.job = null; nativeWizard.rows = [];
  for (const id of ['ni-results','ni-mapping-step','ni-review-step']) $(id).hidden = true;
  $('ni-files-step').disabled = false; $('ni-mapping-fields').disabled = false;
  $('ni-rows').replaceChildren(); $('ni-tree').replaceChildren(); $('ni-conflict-rows').replaceChildren(); $('ni-conflicts').hidden = true;
  nativeWizard.documents = null; nativeWizard.choices = {};
  $('ni-files').value = ''; $('ni-folder').value = ''; $('ni-file-summary').textContent = 'No files selected.'; $('ni-status').textContent = '';
}));
window.addEventListener('beforeunload', event => { if (nativeWizard.running) { event.preventDefault(); event.returnValue = ''; } });

Workbench.init();

// Checkout protects writes. Keep readers up to date with every accepted save
// and its later thumbnail upload, without replacing forms or local drafts.
let modelChangeSeq = 0, modelChangeBusy = false;
async function refreshSavedModels() {
  if(!me || document.hidden || modelChangeBusy || document.querySelector('.work-area').inert)return;
  modelChangeBusy=true;
  const hash=location.hash,user=me.id;
  try {
    const changes=await api('GET',`/api/store/changes?since=${modelChangeSeq}`);
    if(me?.id!==user || location.hash!==hash)return;
    const changed=new Set(changes.keys.map(key=>decodeURIComponent(key.split('/')[1])));
    if(!changes.stale&&!changed.size){modelChangeSeq=changes.seq;return;}
    if(!$('view-parts').hidden) {
      const generation=partsGeneration;
      for(const part of listedParts) {
        if(!changes.stale&&!changed.has(part.id))continue;
        const detail=await api('GET',`/api/parts/${encodeURIComponent(part.id)}`);
        if(location.hash!==hash || generation!==partsGeneration)return;
        part.thumbnail_url=detail.thumbnail_url;
        const row=[...$('parts-rows').rows].find(row=>row.dataset.partId===part.id);
        const preview=row?.querySelector('.thumb-cell a');
        if(preview)preview.innerHTML=thumb(detail.thumbnail_url);
      }
    }
    if(!$('view-part').hidden&&currentPart&&(changes.stale||changed.has(currentPart.id))) {
      const id=currentPart.id;
      const detail=await api('GET',`/api/parts/${encodeURIComponent(id)}`);
      if(location.hash!==hash || currentPart?.id!==id)return;
      currentPart=detail;
      $('part-thumb').innerHTML=thumb(detail.thumbnail_url,'lg');
      for(const row of $('rev-rows').rows) {
        const revision=detail.revision_views.find(revision=>revision.id===row.dataset.revisionId);
        const preview=row.querySelector('.rev-label .thumb');
        if(revision&&preview)preview.outerHTML=revThumb(revision);
      }
      if(editorKey&&!$('editor').hidden&&$('editor-body').readOnly) {
        const key=editorKey;
        const body=await api('GET',`/api/store/doc/${key.replaceAll('%','%25')}`);
        if(location.hash===hash&&editorKey===key&&$('editor-body').readOnly)$('editor-body').value=body===null?'':typeof body==='string'?body:JSON.stringify(body,null,2);
      }
    }
    if(location.hash!==hash)return;
    await Workbench.savedModels(changed,changes.stale);
    modelChangeSeq=changes.seq;
  } catch {
    // Retry after a temporary outage; background refresh must not erase work.
  } finally { modelChangeBusy=false; }
}
setInterval(refreshSavedModels,2000);
window.addEventListener('focus',refreshSavedModels);
document.addEventListener('visibilitychange',refreshSavedModels);

// Field definitions and the BOM layouts are shared with the CAD application.
let fieldDefinitionTarget=null, fieldDefinitions=[];
function drawFieldDefinitions(){
  $('fields-editor').innerHTML=fieldDefinitions.map((d,i)=>`<fieldset data-index="${i}"><label>Key <input data-def="key" value="${escape(d.key)}" required></label><label>Name <input data-def="name" value="${escape(d.name)}" required></label><label>Type <select data-def="type">${['text','number','bool','enum'].map(t=>`<option${d.type===t?' selected':''}>${t}</option>`).join('')}</select></label><label>Units <input data-def="unit" value="${escape(d.unit||'')}" ${d.type==='number'?'':'disabled'}></label><label>Choices (one per line) <textarea data-def="values" ${d.type==='enum'?'':'disabled'}>${escape((d.values||[]).join('\n'))}</textarea></label><label><input type="checkbox" data-def="required" ${d.required?'checked':''}> Required</label><button type="button" data-remove="${i}" class="ghost">Remove field</button></fieldset>`).join('');
  for(const row of $('fields-editor').querySelectorAll('fieldset')){
    for(const input of row.querySelectorAll('[data-def]'))input.addEventListener(input.matches('select,input[type=checkbox]')?'change':'input',()=>{
      const d=fieldDefinitions[Number(row.dataset.index)],key=input.dataset.def;
      d[key]=key==='required'?input.checked:key==='values'?input.value.split('\n').map(v=>v.trim()).filter(Boolean):input.value;
      if(key==='type')drawFieldDefinitions();
    });
  }
  for(const button of $('fields-editor').querySelectorAll('[data-remove]'))button.addEventListener('click',()=>{fieldDefinitions.splice(Number(button.dataset.remove),1);drawFieldDefinitions();});
}
async function openFieldDefinitions(type){
  fieldDefinitionTarget=type;
  const data=type?await api('GET',`/api/part-types/${encodeURIComponent(type)}/fields`):await api('GET','/api/bom/configuration');
  fieldDefinitions=structuredClone(type?data.fields:data.occurrence_fields);
  $('fields-title').textContent=type?`Fields for ${partTypes.find(t=>t.id===type)?.name||type}`:'Occurrence fields';
  drawFieldDefinitions();$('fields-dialog').showModal();
}
$('fields-add').addEventListener('click',()=>{fieldDefinitions.push({key:'',name:'',type:'text',required:false});drawFieldDefinitions();});
$('fields-cancel').addEventListener('click',()=>$('fields-dialog').close());
$('fields-form').addEventListener('submit',e=>{e.preventDefault();act(async()=>{
  const fields=fieldDefinitions.map(d=>({key:d.key.trim(),name:d.name.trim(),type:d.type,required:d.required,...(d.type==='number'?{unit:d.unit||''}:{}),...(d.type==='enum'?{values:d.values||[]}: {})}));
  await api('PUT',fieldDefinitionTarget?`/api/part-types/${encodeURIComponent(fieldDefinitionTarget)}/fields`:'/api/bom/occurrence-fields',{fields});
  $('fields-dialog').close();if(!fieldDefinitionTarget)await renderOccurrenceFields();
});});
$('occurrence-fields-edit').addEventListener('click',()=>act(()=>openFieldDefinitions(null)));
async function renderOccurrenceFields(){
  const config=await api('GET','/api/bom/configuration');
  $('occurrence-fields-list').innerHTML='<p>Callout / find number, reference designator, and installation notes are built-in occurrence fields.</p>'+config.occurrence_fields.map(d=>`<p><strong>${escape(d.name)}</strong> — ${escape(d.type)}${d.unit?` (${escape(d.unit)})`:''}</p>`).join('');
}
let bomConfiguration=null, bomLayoutEditing='', bomLayoutColumns=[];
const DEFAULT_BOM_COLUMNS=['builtin.number','builtin.name','builtin.revision_label','builtin.quantity','builtin.total'];
async function renderBomConfigurations(){
  bomConfiguration=await api('GET','/api/bom/configuration');
  $('bc-layout').innerHTML='<option value="">New configuration</option>'+bomConfiguration.layouts.map(l=>`<option value="${escape(l.id)}">${escape(l.name)} (${l.owner?'Personal':'Shared'})</option>`).join('');
  const target=bomConfiguration.layouts.find(l=>l.id===bomLayoutEditing)||bomConfiguration.layouts.find(l=>l.id===bomConfiguration.selected);
  chooseBomConfiguration(target?.id||'');
}
function chooseBomConfiguration(id){
  bomLayoutEditing=id;const l=bomConfiguration.layouts.find(l=>l.id===id);
  bomLayoutColumns=[...(l?.columns||DEFAULT_BOM_COLUMNS)];
  $('bc-layout').value=id;$('bc-name').value=l?.name||'';$('bc-shared').checked=Boolean(l&&!l.owner);
  const editable=!l||Boolean(l.owner)||me.is_admin;
  $('bc-name').disabled=!editable;$('bc-shared').disabled=!editable;$('bc-delete').disabled=!l||!editable;
  $('bc-form').querySelector('[type=submit]').disabled=!editable;
  $('bc-use').disabled=!l;$('bc-status').textContent='';drawBomConfigurationFields(editable);
}
let bomLayoutCanEdit=true;
const selectedColumns=element=>new Set([...element.selectedOptions].map(option=>option.value));
function drawBomConfigurationFields(editable=true,selectedRight=new Set(),selectedLeft=new Set()){
  bomLayoutCanEdit=editable;
  const label=field=>`${field.name} — ${field.scope==='part'?'Part revision':field.scope==='occurrence'?'Occurrence':field.edit?.resource==='part'?'Part':'Built-in'}${field.unit?` (${field.unit})`:''}`;
  const available=bomConfiguration.fields.filter(field=>!bomLayoutColumns.includes(field.id)).sort((a,b)=>a.name.localeCompare(b.name));
  $('bc-available').innerHTML=available.map(field=>`<option value="${escape(field.id)}" ${selectedLeft.has(field.id)?'selected':''}>${escape(label(field))}</option>`).join('');
  $('bc-configured').innerHTML=bomLayoutColumns.map(id=>{const field=bomConfiguration.fields.find(field=>field.id===id);return `<option value="${escape(id)}" ${selectedRight.has(id)?'selected':''}>${escape(field?label(field):`${id} (Unavailable field)`)}</option>`;}).join('');
  $('bc-available').disabled=!editable;$('bc-configured').disabled=!editable;refreshBomColumnButtons();
}
function refreshBomColumnButtons(){
  const selected=selectedColumns($('bc-configured'));
  $('bc-add').disabled=!bomLayoutCanEdit||!$('bc-available').selectedOptions.length;
  $('bc-remove').disabled=!bomLayoutCanEdit||!selected.size;
  $('bc-up').disabled=!bomLayoutCanEdit||!bomLayoutColumns.some((id,i)=>selected.has(id)&&i>0&&!selected.has(bomLayoutColumns[i-1]));
  $('bc-down').disabled=!bomLayoutCanEdit||!bomLayoutColumns.some((id,i)=>selected.has(id)&&i+1<bomLayoutColumns.length&&!selected.has(bomLayoutColumns[i+1]));
}
$('bc-available').addEventListener('change',refreshBomColumnButtons);
$('bc-configured').addEventListener('change',refreshBomColumnButtons);
$('bc-add').addEventListener('click',()=>{
  if(!bomLayoutCanEdit)return;
  const selected=selectedColumns($('bc-available'));
  for(const id of selected)if(!bomLayoutColumns.includes(id))bomLayoutColumns.push(id);
  drawBomConfigurationFields(true,selected);
});
$('bc-remove').addEventListener('click',()=>{
  if(!bomLayoutCanEdit)return;
  const selected=selectedColumns($('bc-configured'));
  bomLayoutColumns=bomLayoutColumns.filter(id=>!selected.has(id));drawBomConfigurationFields(true,new Set(),selected);
});
function moveBomColumns(direction){
  if(!bomLayoutCanEdit)return;
  const selected=selectedColumns($('bc-configured'));
  const indices=Array.from({length:bomLayoutColumns.length},(_,i)=>i);if(direction>0)indices.reverse();
  for(const i of indices){const to=i+direction;if(to>=0&&to<bomLayoutColumns.length&&selected.has(bomLayoutColumns[i])&&!selected.has(bomLayoutColumns[to]))[bomLayoutColumns[i],bomLayoutColumns[to]]=[bomLayoutColumns[to],bomLayoutColumns[i]];}
  drawBomConfigurationFields(true,selected);
}
$('bc-up').addEventListener('click',()=>moveBomColumns(-1));
$('bc-down').addEventListener('click',()=>moveBomColumns(1));
$('bc-layout').addEventListener('change',()=>chooseBomConfiguration($('bc-layout').value));
$('bc-new').addEventListener('click',()=>chooseBomConfiguration(''));
$('bc-copy').addEventListener('click',()=>{const columns=[...bomLayoutColumns],name=$('bc-name').value;chooseBomConfiguration('');bomLayoutColumns=columns;$('bc-name').value=name?`${name} copy`:'';drawBomConfigurationFields();});
$('bc-form').addEventListener('submit',e=>{e.preventDefault();act(async()=>{const saved=await api('POST','/api/bom/layouts',{id:bomLayoutEditing,name:$('bc-name').value,columns:bomLayoutColumns,shared:me.is_admin&&$('bc-shared').checked});bomLayoutEditing=saved.id;await renderBomConfigurations();$('bc-status').textContent='Saved';});});
$('bc-use').addEventListener('click',()=>act(async()=>{await api('PUT','/api/bom/selection',{id:bomLayoutEditing});$('bc-status').textContent='Selected for CAD and PLM';}));
$('bc-delete').addEventListener('click',()=>act(async()=>{await api('DELETE',`/api/bom/layouts/${encodeURIComponent(bomLayoutEditing)}`);bomLayoutEditing='';await renderBomConfigurations();}));

function fieldValueEditor(field,value,disabled,attributes=''){
  if(field.encoding==='comma-list'&&Array.isArray(value))value=value.join(', ');
  const common=`${attributes} ${disabled?'disabled':''} aria-label="${escape(field.name)}"`;
  if(field.type==='bool')return `<input type="checkbox" ${common} ${value===true?'checked':''}>`;
  if(field.type==='enum')return `<select ${common}><option value="">${escape(field.empty_label||'')}</option>${(field.options||(field.values||[]).map(v=>({value:v,label:v}))).map(o=>`<option value="${escape(o.value)}" ${o.value===value?'selected':''}>${escape(o.label)}</option>`).join('')}</select>`;
  return `<input type="${field.type==='number'?'number':'text'}" ${field.type==='number'?'step="any"':''} ${common} value="${escape(value==null?'':String(value))}">`;
}
function editedFieldValue(field,input){if(field.encoding==='comma-list')return splitTags(input.value);if(field.type==='bool')return input.checked;if(input.value==='')return null;return field.type==='number'?Number(input.value):input.value;}
// Summary always shows the complete part schema, independent of BOM layouts.
let summaryReadSerial = 0;
async function loadSummaryFields(detail=currentPart, selectedRevision=$('summary-revision').value, {background=false}={}) {
  if (!detail || !detail.revision_views.length) return;
  const serial = ++summaryReadSerial;
  const revision = detail.revision_views.some(r => r.id === selectedRevision) ? selectedRevision : defaultRevision(detail);
  const revisionSelect = $('summary-revision');
  const optionsSignature = JSON.stringify(detail.revision_views.map(r => [r.id, r.label, r.lifecycle]));
  if (revisionSelect._summaryOptions !== optionsSignature) {
    revisionOptions(revisionSelect, detail, revision);
    revisionSelect._summaryOptions = optionsSignature;
  } else if (revisionSelect.value !== revision) revisionSelect.value = revision;
  const path = `/api/parts/${encodeURIComponent(detail.id)}`;
  const data = await api('GET', `${path}/revisions/${encodeURIComponent(revision)}/attributes`);
  if (serial !== summaryReadSerial || currentPart?.id !== detail.id) return;
  if (background && document.activeElement?.closest('.summary-attributes')) return;
  const draw = (container, fields, values, resource) => {
    // Keep input nodes stable during background reads and after value saves.
    // Rebuild only when the configured field definitions actually change.
    const schema = JSON.stringify(fields.map(({value, editable, ...definition}) => definition));
    if (container._partAttributeSchema !== schema) {
      container.innerHTML = fields.map(f => `<dt>${escape(f.name)}${f.unit ? ` (${escape(f.unit)})` : ''}</dt><dd>${partAttributeEditor(f, values[f.key], f.editable, `data-summary-field="${escape(f.key)}"`)}</dd>`).join('');
      container._partAttributeSchema = schema;
    }
    for (const input of container.querySelectorAll('[data-summary-field]')) {
      const field = fields.find(f => f.key === input.dataset.summaryField);
      const value = values[field.key];
      if (input.disabled !== !field.editable) input.disabled = !field.editable;
      const wrapper = input.closest('.part-attribute-input');
      if (wrapper.classList.contains('is-read-only') !== !field.editable) {
        wrapper.classList.toggle('is-read-only', !field.editable);
        const lock = wrapper.querySelector('.attribute-lock');
        lock.innerHTML = field.editable ? '' : PART_ATTRIBUTE_LOCK_ICON;
        if (field.editable) lock.removeAttribute('title'); else lock.title = 'Read-only';
      }
      if (field.type === 'bool') {
        if (input.checked !== (value === true)) input.checked = value === true;
      } else {
        const shown = field.encoding === 'comma-list' && Array.isArray(value) ? value.join(', ') : value == null ? '' : String(value);
        if (input.value !== shown) input.value = shown;
      }
      input.onchange = () => act(async () => {
        const value = editedFieldValue(field, input);
        input.disabled = true;
        try {
          await api('PATCH', resource === 'part' ? path : `${path}/revisions/${encodeURIComponent(revision)}/attributes`, resource === 'part' ? {[field.key]: value ?? ''} : {attributes: {[field.key]: value}});
          $('summary-field-status').textContent = 'Saved';
          if (resource === 'part') {
            const fresh = await api('GET', path);
            if (currentPart?.id === detail.id) { currentPart = fresh; $('part-name').textContent = fresh.name; }
          }
        } finally { await loadSummaryFields(currentPart, revision); }
      });
    }
  };
  draw($('summary-record-fields'), data.record_fields, Object.fromEntries(data.record_fields.map(f => [f.key, f.value])), 'part');
  draw($('summary-revision-fields'), data.fields.map(f => ({...f, editable: data.editable})), data.attributes, 'revision');
  const status = data.editable ? 'Revision fields are editable' : 'Revision fields are read-only';
  if ($('summary-field-status').textContent !== status) $('summary-field-status').textContent = status;
}
$('summary-revision').addEventListener('change', () => act(() => loadSummaryFields()));
async function loadRevisionFields(detail=currentPart){
  if(!detail)return;
  const revision=$('revision-field-revision').value;
  revisionOptions($('revision-field-revision'),detail,detail.revision_views.some(r=>r.id===revision)?revision:defaultRevision(detail));
  const rev=$('revision-field-revision').value;
  const data=await api('GET',`/api/parts/${encodeURIComponent(detail.id)}/revisions/${encodeURIComponent(rev)}/attributes`);
  const editable=data.editable;
  $('revision-field-values').innerHTML=data.fields.length?data.fields.map(f=>`<label>${escape(f.name)}${f.unit?` (${escape(f.unit)})`:''}${fieldValueEditor(f,data.attributes[f.key],!editable,`data-revision-field="${escape(f.key)}"`)}</label>`).join(''):'<p class="muted">No revision fields configured for this part type.</p>';
  for(const input of $('revision-field-values').querySelectorAll('[data-revision-field]'))input.addEventListener('change',()=>act(async()=>{
    const field=data.fields.find(f=>f.key===input.dataset.revisionField);input.disabled=true;
    try{await api('PATCH',`/api/parts/${encodeURIComponent(detail.id)}/revisions/${encodeURIComponent(rev)}/attributes`,{attributes:{[field.key]:editedFieldValue(field,input)}});}finally{await loadRevisionFields(detail);}
  }));
}
$('revision-field-revision').addEventListener('change',()=>act(()=>loadRevisionFields()));
const bomAttributeView={show:false};
// An indented BOM with more lines than this opens collapsed to its first level.
const BOM_COLLAPSED_OVER=1000;
// ... and draws this many of its rows until Show all.
const BOM_SHOWN_FIRST=500;
async function drawConfiguredBom(bom,serial,background=false,tag=''){
  await drawBomAttributes({background,bom,tag,head:$('bom-head'),rows:$('bom-rows'),selection:$('bom-layout'),editButton:$('bom-edit-attributes'),status:$('bom-edit-status'),treeControls:$('bom-tree-controls'),view:bomAttributeView,reload:loadBom,isCurrent:()=>serial===bomReadSerial});
}
// Every PLM BOM uses this editor, including Home, Parts and review detail panes.
// Edits whose PATCH is still in flight (every pane). The 5 s metadata poll
// waits for them: its loadBom() moves bomReadSerial, which told the edit
// handler below the table it drew for was stale, so a save that took longer
// than the poll interval never wrote 'Attributes saved.' (the server had the
// value; the user only saw the hint).
let bomEditsInFlight=0;
async function drawBomAttributes({bom,tag='',head,rows,selection,editButton,status,treeControls,view,reload,isCurrent,background=false}){
  const config=await api('GET','/api/bom/configuration');
  if(!isCurrent())return;
  // The 5 s poll redraws only what moved: repainting an unchanged 4,000-line
  // BOM froze the page for half a second every poll.
  // With the server's ETag the BOM is named by it: no stringify of megabytes.
  const drawn=JSON.stringify([tag?`${bom.part_id}/${bom.revision_id} ${tag}`:bom,config,view.show,me.can_author]);
  if(background&&view.drawn===drawn&&rows.isConnected)return;
  view.drawn=drawn;
  selection.innerHTML='<option value="">Default</option>'+config.layouts.map(l=>`<option value="${escape(l.id)}">${escape(l.name)} (${l.owner?'Personal':'Shared'})</option>`).join('');
  selection.value=config.selected||'';
  selection.onchange=()=>act(async()=>{await api('PUT','/api/bom/selection',{id:selection.value});view.show=false;await reload();});
  editButton.hidden=!me.can_author;
  editButton.textContent=view.show?'Hide extra attribute columns':'Edit attributes';
  editButton.setAttribute('aria-pressed',String(view.show));
  editButton.onclick=()=>act(async()=>{view.show=!view.show;await reload();});
  const layout=config.layouts.find(l=>l.id===config.selected),ids=[...(layout?.columns||DEFAULT_BOM_COLUMNS)];
  if(view.show)for(const field of config.fields){
    if(field.editable&&!ids.includes(field.id)&&(field.scope!=='part'||bom.lines.some(line=>line.part_type===field.part_type)))ids.push(field.id);
  }
  const fields=ids.map(id=>config.fields.find(f=>f.id===id)).filter(f=>f&&(bom.flat||f.id!=='builtin.number'));
  const treeKey=`${bom.part_id}/${bom.revision_id}`;
  if(view.treeKey!==treeKey){view.treeKey=treeKey;view.collapsed=new Set();}
  const branches=new Set(),lastSibling=new Set(),siblings=new Map();
  for(const line of bom.lines){
    const parent=line.position.split('.').slice(0,-1).join('.');
    if(parent)branches.add(parent);
    if(!siblings.has(parent))siblings.set(parent,[]);siblings.get(parent).push(line.position);
  }
  for(const children of siblings.values())lastSibling.add(children.at(-1));
  // A large indented BOM opens on its first level: drawing all of a 4,000-line
  // tree took the browser over 3 s of layout. Expand all still draws every line.
  if(!bom.flat&&view.collapseFor!==treeKey){
    view.collapseFor=treeKey;
    view.autoCollapsed=bom.lines.length>BOM_COLLAPSED_OVER;
    if(view.autoCollapsed)view.collapsed=new Set(branches);
  }
  // And whatever it shows, a BOM over that size draws its first rows only
  // (a single level of 2,000 has nothing to collapse): Show all, or Expand
  // all, draws the rest. The poll's repaints keep the choice.
  if(view.capFor!==treeKey){view.capFor=treeKey;view.showAll=bom.lines.length<=BOM_COLLAPSED_OVER;}
  rows.closest('table').setAttribute('role',bom.flat?'table':'treegrid');
  treeControls.hidden=bom.flat;
  const maxDepth=bom.lines.reduce((depth,line)=>Math.max(depth,line.level),1);
  treeControls.innerHTML=`<button type="button" class="ghost" data-bom-expand-all>Expand all</button><button type="button" class="ghost" data-bom-collapse-all>Collapse all</button><label class="inline-select">Depth <select data-bom-expand-depth>${Array.from({length:maxDepth},(_,i)=>`<option value="${i+1}" ${Number(view.expandDepth||1)===i+1?'selected':''}>${i+1}</option>`).join('')}</select></label><button type="button" class="ghost" data-bom-expand-to>Expand to depth</button>`;
  // The note and Show all sit beside the tree controls, not in them: the flat
  // view hides the tree controls and is capped too.
  let limit=treeControls.nextElementSibling;
  if(!limit?.matches('[data-bom-limit]')){limit=document.createElement('div');limit.className='toolbar bom-limit';limit.dataset.bomLimit='';treeControls.after(limit);}
  const lines=bom.lines.length.toLocaleString();
  limit.innerHTML=`<span class="muted" data-bom-collapsed-note hidden>Opened collapsed to the first level: this BOM has ${lines} lines, and drawing them all is slow. Expand all shows every line.</span><span class="muted" data-bom-capped-note hidden></span><button type="button" class="ghost" data-bom-show-all hidden></button>`;
  limit.querySelector('[data-bom-show-all]').onclick=()=>{view.showAll=true;paint();};
  treeControls.querySelector('[data-bom-expand-all]').onclick=()=>{view.collapsed.clear();view.showAll=true;paint();};
  treeControls.querySelector('[data-bom-collapse-all]').onclick=()=>{view.collapsed=new Set(branches);paint();};
  treeControls.querySelector('[data-bom-expand-depth]').onchange=event=>{view.expandDepth=Number(event.target.value);};
  treeControls.querySelector('[data-bom-expand-to]').onclick=()=>{
    const depth=Number(treeControls.querySelector('[data-bom-expand-depth]').value);view.expandDepth=depth;
    view.collapsed=new Set(bom.lines.filter(line=>branches.has(line.position)&&line.level>=depth).map(line=>line.position));paint();
  };
  const treeCell=line=>{
    const segments=line.position.split('.');
    const guides=segments.slice(0,-1).map((_,i)=>`<span class="bom-tree-guide ${lastSibling.has(segments.slice(0,i+1).join('.'))?'':'continues'}" data-bom-guide-index="${i}"></span>`).join('');
    const expanded=!view.collapsed.has(line.position),branch=branches.has(line.position);
    return `<td class="bom-tree-cell"><div class="bom-tree-entry">${guides}<span class="bom-tree-guide elbow ${lastSibling.has(line.position)?'last':''}" data-bom-guide-index="${segments.length-1}"></span>${branch?`<button type="button" class="bom-tree-toggle" data-bom-toggle="${escape(line.position)}" aria-expanded="${expanded}" aria-label="${expanded?'Collapse':'Expand'} ${escape(line.number)} at ${escape(line.position)}">${expanded?'▾':'▸'}</button>`:'<span class="bom-tree-spacer"></span>'}<svg class="bom-tree-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">${line.assembly?'<path d="M3 6h7l2 3h9v12H3z"/>':'<path d="M5 3h9l5 5v13H5zM14 3v6h5"/>'}</svg><a href="#/part/${encodeURIComponent(line.part_id)}" title="Position ${escape(line.position)}">${escape(line.number)}</a></div></td>`;
  };
  const hasWarnings=bom.lines.some(line=>line.warnings?.length);
  head.innerHTML=`<tr>${hasWarnings?'<th class="bom-warning-column" aria-label="Warnings"></th>':''}${bom.flat?'':'<th>Part</th>'}${fields.map(f=>`<th>${escape(f.name)}${f.unit?` (${escape(f.unit)})`:''}</th>`).join('')}</tr>`;
  const valueOf=(line,f)=>f.scope==='part'?(f.part_type===line.part_type?line.part_values[f.key]:null):f.scope==='occurrence'?(f.id.startsWith('builtin.')?line[f.key]:line.occurrence_attributes[f.key]):line[f.key];
  function paint(){
  // `i` stays the index into bom.lines: a row left out by the collapse or the
  // cap is an empty string, as a collapsed one always was.
  let shown=0,visible=0;
  const hidden=line=>!bom.flat&&line.position.split('.').slice(0,-1).some((_,j,parts)=>view.collapsed.has(line.position.split('.').slice(0,j+1).join('.')));
  for(const line of bom.lines)if(!hidden(line))visible++;
  const capped=!view.showAll&&visible>BOM_SHOWN_FIRST;
  limit.querySelector('[data-bom-collapsed-note]').hidden=bom.flat||!(view.autoCollapsed&&view.collapsed.size>0);
  limit.querySelector('[data-bom-capped-note]').hidden=!capped;
  limit.querySelector('[data-bom-capped-note]').textContent=capped?`Showing the first ${BOM_SHOWN_FIRST.toLocaleString()} of ${visible.toLocaleString()} rows: this BOM has ${lines} lines, and drawing them all is slow.`:'';
  limit.querySelector('[data-bom-show-all]').hidden=!capped;
  limit.querySelector('[data-bom-show-all]').textContent=`Show all ${visible.toLocaleString()} rows`;
  rows.innerHTML=bom.lines.map((line,i)=>{
    if(hidden(line))return '';
    if(capped&&++shown>BOM_SHOWN_FIRST)return '';
    return `<tr data-bom-position="${escape(line.position)}" data-copy-kind="part" data-copy-part="${escape(line.part_id)}" data-copy-revision="${escape(line.revision_id||'')}" data-copy-label="${escape(line.number)}" ${bom.flat?'':`aria-level="${line.level}" ${branches.has(line.position)?`aria-expanded="${!view.collapsed.has(line.position)}"`:''}`}>${hasWarnings?`<td class="bom-warning-column">${line.warnings?.length?`<button type="button" class="bom-warning-icon" data-bom-warning="${i}" title="${escape(line.warnings.join('\n'))}" aria-label="Warnings for ${escape(line.number)} rev ${escape(line.revision_label)}">⚠</button>`:''}</td>`:''}${bom.flat?'':treeCell(line)}${fields.map(f=>{
    const value=valueOf(line,f),applicable=f.edit?.resource==='part'||(f.scope==='part'?f.part_type===line.part_type:line.occurrence_ids.length>0);
    if(f.editable&&applicable&&me.can_author)return `<td>${fieldValueEditor(f,value,false,`data-bom-row="${i}" data-bom-field="${escape(f.id)}"`)}</td>`;
    if(f.id==='builtin.number')return `<td><a href="#/part/${encodeURIComponent(line.part_id)}">${escape(line.number)}</a></td>`;
    return `<td>${escape(value==null?'—':String(value))}</td>`;
  }).join('')}</tr>`;}).join('');
  // The guide column offset is a custom property; set on the element, not written inline (the CSP allows no style attribute).
  for(const guide of rows.querySelectorAll('.bom-tree-guide[data-bom-guide-index]'))guide.style.setProperty('--bom-guide-index',guide.dataset.bomGuideIndex);
  for(const button of rows.querySelectorAll('[data-bom-toggle]')){
    const toggle=()=>{const position=button.dataset.bomToggle;if(view.collapsed.has(position))view.collapsed.delete(position);else view.collapsed.add(position);paint();rows.querySelector(`[data-bom-toggle="${CSS.escape(position)}"]`)?.focus();};
    button.onclick=toggle;button.onkeydown=event=>{if((event.key==='ArrowRight'&&view.collapsed.has(button.dataset.bomToggle))||(event.key==='ArrowLeft'&&!view.collapsed.has(button.dataset.bomToggle))){event.preventDefault();toggle();}};
  }
  for(const button of rows.querySelectorAll('[data-bom-warning]'))button.onclick=()=>{
    const line=bom.lines[Number(button.dataset.bomWarning)];
    let dialog=$('bom-warning-dialog');
    if(!dialog){dialog=document.createElement('dialog');dialog.id='bom-warning-dialog';document.body.append(dialog);}
    dialog.innerHTML=`<form method="dialog"><h2>${escape(line.number)} rev ${escape(line.revision_label)}</h2><ul>${line.warnings.map(w=>`<li>${escape(w)}</li>`).join('')}</ul><button type="submit">Close</button></form>`;
    dialog.showModal();
  };
  // A background refresh keeps the status the user last caused ('Attributes
  // saved.' or a refusal); only a foreground draw resets it to the hint.
  if(!background)status.textContent=me.can_author?'Edit attribute values in the table. Changes save automatically.':'';
  for(const input of rows.querySelectorAll('[data-bom-field]'))input.addEventListener('change',()=>act(async()=>{
    const line=bom.lines[Number(input.dataset.bomRow)],field=fields.find(f=>f.id===input.dataset.bomField);input.disabled=true;
    const value=editedFieldValue(field,input);
    const target=field.edit;
    const part=target.resource==='occurrence'?line.owner_part:line.part_id,revision=target.resource==='occurrence'?line.owner_revision:line.revision_id;
    const base=`/api/parts/${encodeURIComponent(part)}`;
    const path=target.resource==='part'?base:`${base}/revisions/${encodeURIComponent(revision)}/${target.resource==='revision'?'attributes':'occurrences'}`;
    const payload=target.resource==='part'?{[target.key]:value??''}:{...(target.resource==='occurrence'?{ids:line.occurrence_ids}:{}),attributes:{[target.key]:value}};
    bomEditsInFlight++;
    try{
      await api('PATCH',path,payload);
      if(isCurrent()){await reload();status.textContent='Attributes saved.';}
    }catch(error){
      if(isCurrent()){await reload();status.textContent=error.message;}
      throw error;
    }finally{bomEditsInFlight--;}
  }));
  }
  paint();
}

let bomMetadataPolling=false;
setInterval(async()=>{
  if(!me||!currentPart||document.hidden||$('view-part').hidden||bomMetadataPolling||bomEditsInFlight>0||document.querySelector('.work-area').inert)return;
  if(document.activeElement?.closest('#bom-rows,#revision-field-values,[data-object-panel="summary"]'))return;
  bomMetadataPolling=true;
  try{if(objectTab==='structure'&&structure.tab==='bom')await loadBom({background:true});else if(objectTab==='revisions')await loadRevisionFields();else if(objectTab==='summary')await loadSummaryFields(currentPart,$('summary-revision').value,{background:true});}catch{}finally{bomMetadataPolling=false;}
},5000);