summaryrefslogtreecommitdiff
path: root/web/app.js
blob: b22d3527e4eb9e70039cb6a23aaa61ed556dab93 (plain)
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
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
const BASE_PATH = (typeof document !== 'undefined') ? document.querySelector('meta[name="base-path"]')?.content ?? '' : '';
const API_BASE = (typeof window !== 'undefined') ? window.location.origin + BASE_PATH : '';

// ── Fetch ─────────────────────────────────────────────────────────────────────

async function fetchTasks(since = null) {
  let url = `${API_BASE}/api/tasks`;
  if (since) {
    url += `?since=${encodeURIComponent(since)}`;
  }
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// Fetches recent executions (last 24h) from /api/executions?since=24h.
// fetchFn defaults to window.fetch; injectable for tests.
async function fetchRecentExecutions(basePath = BASE_PATH, fetchFn = fetch) {
  const res = await fetchFn(`${basePath}/api/executions?since=24h`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// Returns only tasks currently in state RUNNING.
function filterRunningTasks(tasks) {
  return tasks.filter(t => t.state === 'RUNNING');
}

// Returns human-readable elapsed time from an ISO timestamp to now.
function formatElapsed(startISO) {
  if (startISO == null) return '';
  const elapsed = Math.floor((Date.now() - new Date(startISO).getTime()) / 1000);
  if (elapsed < 0) return '0s';
  const h = Math.floor(elapsed / 3600);
  const m = Math.floor((elapsed % 3600) / 60);
  const s = elapsed % 60;
  if (h > 0) return `${h}h ${m}m`;
  if (m > 0) return `${m}m ${s}s`;
  return `${s}s`;
}

// Returns human-readable duration between two ISO timestamps.
// If endISO is null, uses now (for in-progress tasks).
// If startISO is null, returns '--'.
function formatDuration(startISO, endISO) {
  if (startISO == null) return '--';
  const start = new Date(startISO).getTime();
  const end = endISO != null ? new Date(endISO).getTime() : Date.now();
  const elapsed = Math.max(0, Math.floor((end - start) / 1000));
  const h = Math.floor(elapsed / 3600);
  const m = Math.floor((elapsed % 3600) / 60);
  const s = elapsed % 60;
  if (h > 0) return `${h}h ${m}m`;
  if (m > 0) return `${m}m ${s}s`;
  return `${s}s`;
}

// Returns last max lines from array (for testability).
function extractLogLines(lines, max = 500) {
  if (lines.length <= max) return lines;
  return lines.slice(lines.length - max);
}

// Returns a new array of executions sorted by started_at descending.
function sortExecutionsDesc(executions) {
  return [...executions].sort((a, b) =>
    new Date(b.started_at).getTime() - new Date(a.started_at).getTime(),
  );
}

// ── Render ────────────────────────────────────────────────────────────────────

function formatDate(iso) {
  if (!iso) return '';
  return new Date(iso).toLocaleString(undefined, {
    month: 'short', day: 'numeric',
    hour: '2-digit', minute: '2-digit',
  });
}

// Returns formatted string for changestats, e.g. "5 files, +127 -43".
// Returns empty string for null/undefined input.
export function formatChangestats(stats) {
  if (stats == null) return '';
  return `${stats.files_changed} files, +${stats.lines_added} -${stats.lines_removed}`;
}

// Returns a <span class="changestats-badge"> element for the given stats,
// or null if stats is null/undefined.
// Accepts an optional doc parameter for testability (defaults to document).
export function renderChangestatsBadge(stats, doc = (typeof document !== 'undefined' ? document : null)) {
  if (stats == null || doc == null) return null;
  const span = doc.createElement('span');
  span.className = 'changestats-badge';
  span.textContent = formatChangestats(stats);
  return span;
}

// Returns a <span class="deployment-badge"> element indicating whether the
// currently-deployed server includes the task's fix commits.
// Returns null if status is null/undefined or doc is null.
// Accepts an optional doc parameter for testability (defaults to document).
export function renderDeploymentBadge(status, doc = (typeof document !== 'undefined' ? document : null)) {
  if (status == null || doc == null) return null;
  const span = doc.createElement('span');
  if (status.includes_fix) {
    span.className = 'deployment-badge deployment-badge--deployed';
    span.textContent = '✓ Deployed';
  } else {
    return null;
  }
  if (status.deployed_commit) {
    span.title = `Deployed commit: ${status.deployed_commit.slice(0, 8)}`;
  }
  return span;
}

// ── Event timeline ──────────────────────────────────────────────────────────
// The observability event stream (GET /api/tasks/{id}/events) replaces the
// ad-hoc question/summary panels. formatEventText turns one event into a human
// line; renderEventTimeline builds the list element.

// formatEventText returns a one-line human description of a task event.
export function formatEventText(event) {
  if (!event) return '';
  const p = event.payload || {};
  switch (event.kind) {
    case 'state_change':
      return `State: ${p.from || '?'} → ${p.to || '?'}`;
    case 'summary':
      return `Summary: ${p.text || p.summary || ''}`;
    case 'clarification_request':
      return `Question: ${p.text || ''}`;
    case 'clarification_answer':
      return `Answer: ${p.answer || ''}`;
    case 'subtask_spawned':
      return `Spawned subtask: ${p.name || p.subtask_id || ''}`;
    case 'commit_made':
      return `Commit: ${p.message || p.hash || ''}`;
    case 'cost_report':
      return `Cost: $${p.cost_usd != null ? p.cost_usd : 0}`;
    case 'agent_message':
    case 'human_message':
      return p.text || p.message || '';
    case 'execution_started':
      return 'Execution started';
    case 'execution_ended':
      return p.status ? `Execution ended (${p.status})` : 'Execution ended';
    case 'eval_verdict':
      return `Eval verdict (${p.role || '?'}): ${p.summary || ''}`;
    case 'arbitration_decided':
      return `Arbitration decided: ${p.summary || ''}`;
    case 'human_accepted':
      return `Accepted: ${p.from || '?'} → ${p.to || '?'}`;
    case 'retro_captured': {
      const n = (p.proposals || []).length;
      return `Retro captured (${n} config proposal${n === 1 ? '' : 's'}): ${p.summary || ''}`;
    }
    case 'epic_proposed':
      return `Epic proposed: ${p.name || ''} (${(p.story_ids || []).length} stories)`;
    case 'discovery_proposed':
      return 'Discovery proposed';
    case 'framing_decided':
      return 'Framing decided';
    case 'groomed':
      return 'Groomed';
    case 'prioritized':
      return 'Prioritized';
    case 'escalated':
      return `Escalated: rung ${p.from_rung ?? '?'} → ${p.to_rung ?? '?'}${p.final ? ' (final)' : ''}`;
    case 'role_config_proposed':
      return `Role config proposed: ${p.role || '?'} v${p.version ?? '?'}`;
    default:
      return event.kind || '';
  }
}

// renderEventTimeline builds a <ul class="event-timeline"> from an events array.
// Accepts an optional doc parameter for testability (defaults to document).
export function renderEventTimeline(events, doc = (typeof document !== 'undefined' ? document : null)) {
  if (doc == null) return null;
  const ul = doc.createElement('ul');
  ul.className = 'event-timeline';
  if (!events || events.length === 0) {
    const empty = doc.createElement('li');
    empty.className = 'event-timeline__empty';
    empty.textContent = 'No events yet.';
    ul.appendChild(empty);
    return ul;
  }
  for (const event of events) {
    const li = doc.createElement('li');
    li.className = `event-timeline__item event-timeline__item--${event.kind || 'unknown'}`;

    const actor = doc.createElement('span');
    actor.className = 'event-timeline__actor';
    actor.textContent = event.actor || '';
    li.appendChild(actor);

    const text = doc.createElement('span');
    text.className = 'event-timeline__text';
    text.textContent = formatEventText(event);
    li.appendChild(text);

    ul.appendChild(li);
  }
  return ul;
}

// fetchTaskEvents loads a task's event stream. fetchImpl defaults to the global
// fetch; pass a stub in tests. Returns [] on any error so the UI degrades
// gracefully.
export async function fetchTaskEvents(taskId, fetchImpl = (typeof fetch !== 'undefined' ? fetch : null)) {
  if (!fetchImpl) return [];
  try {
    const resp = await fetchImpl(`/api/tasks/${taskId}/events`);
    if (!resp.ok) return [];
    const data = await resp.json();
    return Array.isArray(data) ? data : [];
  } catch {
    return [];
  }
}

// ── Budget headroom ─────────────────────────────────────────────────────────
// Renders the per-provider rolling-window spend headroom from GET /api/budget.

// formatBudgetHeadroom turns one provider's headroom into a short label.
// Returns '' for unlimited providers (nothing to show).
export function formatBudgetHeadroom(h) {
  if (!h || !h.limited) return '';
  const pct = Math.round((h.fraction_remaining || 0) * 100);
  const remaining = (h.remaining_usd || 0).toFixed(2);
  const limit = (h.limit_usd || 0).toFixed(2);
  const name = h.provider ? h.provider.charAt(0).toUpperCase() + h.provider.slice(1) : '?';
  return `${name}: ${pct}% left ($${remaining} of $${limit})`;
}

// renderBudgetHeadroom builds a <span> chip per limited provider, flagging
// providers under 20% remaining with a --low modifier. Returns the container.
export function renderBudgetHeadroom(headrooms, doc = (typeof document !== 'undefined' ? document : null)) {
  if (doc == null) return null;
  const wrap = doc.createElement('div');
  wrap.className = 'budget-bar';
  for (const h of headrooms || []) {
    if (!h || !h.limited) continue;
    const chip = doc.createElement('span');
    chip.className = 'budget-chip' + ((h.fraction_remaining || 0) < 0.2 ? ' budget-chip--low' : '');
    chip.textContent = formatBudgetHeadroom(h);
    wrap.appendChild(chip);
  }
  return wrap;
}

// loadBudget fetches headroom and injects chips into #budget-bar. Best-effort.
async function loadBudget(fetchImpl = (typeof fetch !== 'undefined' ? fetch : null)) {
  if (!fetchImpl || typeof document === 'undefined') return;
  const slot = document.getElementById('budget-bar');
  if (!slot) return;
  try {
    const resp = await fetchImpl(`${BASE_PATH}/api/budget`);
    if (!resp.ok) return;
    const headrooms = await resp.json();
    const rendered = renderBudgetHeadroom(headrooms);
    slot.innerHTML = '';
    if (rendered) for (const c of rendered.children) slot.appendChild(c);
  } catch {
    // budget display is non-critical; ignore.
  }
}

function truncateToWordBoundary(text, maxLen = 120) {
  if (!text || text.length <= maxLen) return text;
  const cut = text.lastIndexOf(' ', maxLen);
  return (cut > 0 ? text.slice(0, cut) : text.slice(0, maxLen)) + '…';
}

export function createTaskCard(task, doc = document) {
  const card = doc.createElement('div');
  card.className = 'task-card';
  card.dataset.taskId = task.id;

  // Header: name + state badge
  const header = doc.createElement('div');
  header.className = 'task-card-header';

  const name = doc.createElement('span');
  name.className = 'task-name';
  name.textContent = task.name;

  const badge = doc.createElement('span');
  badge.className = 'state-badge';
  badge.dataset.state = task.state;
  badge.textContent = task.state.replace(/_/g, ' ');

  header.append(name, badge);
  card.appendChild(header);

  // Meta: priority + created_at
  const meta = doc.createElement('div');
  meta.className = 'task-meta';
  if (task.priority) {
    const prio = doc.createElement('span');
    prio.textContent = task.priority;
    meta.appendChild(prio);
  }
  if (task.created_at) {
    const when = doc.createElement('span');
    when.textContent = formatDate(task.created_at);
    meta.appendChild(when);
  }
  if (task.project) {
    const proj = doc.createElement('span');
    proj.className = 'task-project';
    proj.textContent = task.project;
    meta.appendChild(proj);
  }
  if (meta.children.length) card.appendChild(meta);

  // Elapsed timer for RUNNING tasks (no separate ticking interval — updated
  // on each poll tick alongside the rest of the board, same convention the
  // old Running-tab card used).
  if (task.state === 'RUNNING') {
    const elapsed = doc.createElement('span');
    elapsed.className = 'task-elapsed running-elapsed';
    elapsed.dataset.startedAt = task.updated_at ?? '';
    elapsed.textContent = formatElapsed(task.updated_at);
    card.appendChild(elapsed);
  }

  // Description (truncated via CSS)
  if (task.description) {
    const desc = doc.createElement('div');
    desc.className = 'task-description';
    desc.textContent = task.description;
    card.appendChild(desc);
  }

  // Error message for failed tasks
  const FAILED_STATES = new Set(['FAILED', 'BUDGET_EXCEEDED', 'TIMED_OUT']);
  if (FAILED_STATES.has(task.state) && task.error_msg) {
    const errEl = doc.createElement('div');
    errEl.className = 'task-error-msg';
    errEl.textContent = task.error_msg;
    errEl.title = task.error_msg;
    card.appendChild(errEl);
  }

  // Checker report for READY tasks where the checker flagged a problem.
  if (task.state === 'READY' && task.checker_report) {
    const reportEl = doc.createElement('div');
    reportEl.className = 'task-checker-report';
    const label = doc.createElement('span');
    label.className = 'task-checker-report-label';
    label.textContent = '⚠ Checker flagged:';
    const text = doc.createElement('span');
    text.textContent = task.checker_report;
    reportEl.appendChild(label);
    reportEl.appendChild(text);
    card.appendChild(reportEl);
  }

  // Changestats badge for COMPLETED/READY tasks
  const CHANGESTATS_STATES = new Set(['COMPLETED', 'READY']);
  if (CHANGESTATS_STATES.has(task.state) && task.changestats != null) {
    const csBadge = renderChangestatsBadge(task.changestats);
    if (csBadge) card.appendChild(csBadge);
  }

  // Deployment status badge for READY tasks — only when there are tracked commits to check.
  if (task.state === 'READY' && task.deployment_status != null &&
      task.deployment_status.fix_commits && task.deployment_status.fix_commits.length > 0) {
    const depBadge = renderDeploymentBadge(task.deployment_status);
    if (depBadge) card.appendChild(depBadge);
  }

  // Inline log tail (no click required) — see docs/superpowers/specs/2026-07-06-tasks-board-design.md
  // section 4. PENDING/QUEUED tasks have no execution row yet, so there is
  // nothing to tail; every other state gets a .task-log-tail element that
  // Task 6's ensureTaskLogStream() attaches an SSE stream to.
  if (task.state === 'PENDING' || task.state === 'QUEUED') {
    const placeholder = doc.createElement('div');
    placeholder.className = 'task-log-tail-placeholder';
    placeholder.textContent = 'Waiting to start…';
    card.appendChild(placeholder);
  } else {
    const logTail = doc.createElement('div');
    logTail.className = task.state === 'RUNNING' || task.state === 'BLOCKED'
      ? 'task-log-tail running-log'
      : 'task-log-tail';
    logTail.dataset.logTarget = task.id;
    card.appendChild(logTail);
  }

  // Footer: action buttons based on state
  // Interrupted states (CANCELLED, FAILED, BUDGET_EXCEEDED) show both Resume and Restart.
  // TIMED_OUT shows Resume only. Others show a single action.
  const RESUME_STATES  = new Set(['TIMED_OUT', 'CANCELLED', 'FAILED', 'BUDGET_EXCEEDED']);
  const RESTART_STATES = new Set(['CANCELLED', 'FAILED', 'BUDGET_EXCEEDED']);
  if (task.state === 'PENDING' || task.state === 'RUNNING' || task.state === 'READY' || task.state === 'BLOCKED' || RESUME_STATES.has(task.state)) {
    const footer = doc.createElement('div');
    footer.className = 'task-card-footer';

    if (task.state === 'PENDING') {
      const btn = doc.createElement('button');
      btn.className = 'btn-run';
      btn.textContent = 'Run';
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        handleRun(task.id, btn, footer);
      });
      footer.appendChild(btn);
    } else if (task.state === 'RUNNING') {
      const btn = doc.createElement('button');
      btn.className = 'btn-cancel';
      btn.textContent = 'Cancel';
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        handleCancel(task.id, btn, footer);
      });
      footer.appendChild(btn);
    } else if (task.state === 'READY') {
      renderSubtaskRollup(task, footer, doc);
      const acceptBtn = doc.createElement('button');
      acceptBtn.className = 'btn-accept';
      acceptBtn.textContent = 'Accept';
      acceptBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        handleAccept(task.id, acceptBtn, footer);
      });
      const rejectBtn = doc.createElement('button');
      rejectBtn.className = 'btn-reject';
      rejectBtn.textContent = 'Reject';
      rejectBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        handleReject(task.id, rejectBtn, footer);
      });
      footer.appendChild(acceptBtn);
      footer.appendChild(rejectBtn);
    } else if (task.state === 'BLOCKED') {
      if (task.question) {
        renderQuestionFooter(task, footer, doc);
      } else {
        renderSubtaskRollup(task, footer, doc);
      }
      const cancelBtn = doc.createElement('button');
      cancelBtn.className = 'btn-cancel';
      cancelBtn.textContent = 'Cancel';
      cancelBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        handleCancel(task.id, cancelBtn, footer);
      });
      footer.appendChild(cancelBtn);
    } else if (RESUME_STATES.has(task.state)) {
      const resumeBtn = doc.createElement('button');
      resumeBtn.className = 'btn-resume';
      resumeBtn.textContent = 'Resume';
      resumeBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        handleResume(task.id, resumeBtn, footer);
      });
      footer.appendChild(resumeBtn);
      if (RESTART_STATES.has(task.state)) {
        const restartBtn = doc.createElement('button');
        restartBtn.className = 'btn-restart';
        restartBtn.textContent = 'Restart';
        restartBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          handleRestart(task.id, restartBtn, footer);
        });
        footer.appendChild(restartBtn);
      }
    }

    card.appendChild(footer);
  }

  if (!NON_DELETABLE_STATES.has(task.state)) {
    const delBtn = doc.createElement('button');
    delBtn.className = 'btn-delete-task';
    delBtn.title = 'Delete task';
    delBtn.textContent = '✕';
    delBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      handleDelete(task.id, card);
    });
    card.appendChild(delBtn);
  }

  if (EDITABLE_STATES.has(task.state)) {
    card.classList.add('task-card--editable');
    const editForm = createEditForm(task, doc);
    editForm.hidden = true;
    card.appendChild(editForm);
    card.addEventListener('click', () => { editForm.hidden = !editForm.hidden; });
  } else {
    card.addEventListener('click', () => openTaskPanel(task.id));
  }

  return card;
}

/**
 * Returns true if the user is currently editing a text field or has a modal open.
 * Used to avoid destructive DOM refreshes during polling.
 */
export function isUserEditing(activeEl = (typeof document !== 'undefined' ? document.activeElement : null)) {
  if (!activeEl) return false;
  const tag = activeEl.tagName;
  if (tag === 'INPUT' || tag === 'TEXTAREA') return true;
  if (activeEl.isContentEditable) return true;
  if (activeEl.closest('[role="dialog"]') || activeEl.closest('dialog')) return true;
  // Also block re-renders when any modal/panel is open, even without focus.
  if (typeof document !== 'undefined') {
    if (document.querySelector('dialog[open]')) return true;
    if (document.getElementById('task-panel')?.classList.contains('open')) return true;
  }
  return false;
}

/**
 * Partitions tasks into 'running' and 'ready' arrays for the Active tab view.
 * Both arrays are sorted by created_at ascending (oldest first).
 */
export function partitionActivePaneTasks(tasks) {
  const running = tasks
    .filter(t => t.state === 'RUNNING')
    .sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
  
  const ready = tasks
    .filter(t => t.state === 'READY')
    .sort((a, b) => new Date(a.created_at) - new Date(b.created_at));

  return { running, ready };
}

// ── Sort ──────────────────────────────────────────────────────────────────────

function sortTasksByDate(tasks, descend = false) {
  return [...tasks].sort((a, b) => {
    if (!a.created_at && !b.created_at) return 0;
    if (!a.created_at) return 1;
    if (!b.created_at) return -1;
    const diff = new Date(a.created_at) - new Date(b.created_at);
    return descend ? -diff : diff;
  });
}

// ── Filter ────────────────────────────────────────────────────────────────────

const HIDE_STATES        = new Set(['COMPLETED', 'FAILED']);
const ACTIVE_STATES      = new Set(['PENDING', 'QUEUED', 'RUNNING', 'READY']);
const INTERRUPTED_STATES = new Set(['CANCELLED', 'FAILED', 'BUDGET_EXCEEDED', 'BLOCKED']);
const DONE_STATES        = new Set(['COMPLETED', 'TIMED_OUT']);

// filterActiveTasks uses its own set (excludes PENDING — tasks "in-flight" only)
const _PANEL_ACTIVE_STATES = new Set(['RUNNING', 'READY', 'QUEUED', 'BLOCKED']);

export function filterTasks(tasks, hideCompletedFailed = false) {
  if (!hideCompletedFailed) return tasks;
  return tasks.filter(t => !HIDE_STATES.has(t.state));
}

export function filterActiveTasks(tasks) {
  return tasks.filter(t => _PANEL_ACTIVE_STATES.has(t.state));
}

export function filterTasksByTab(tasks, tab) {
  if (tab === 'active')      return tasks.filter(t => ACTIVE_STATES.has(t.state));
  if (tab === 'interrupted') return tasks.filter(t => INTERRUPTED_STATES.has(t.state));
  if (tab === 'done') {
    const now = new Date();
    const twentyFourHoursAgo = new Date(now.getTime() - (24 * 60 * 60 * 1000));
    return tasks.filter(t => {
      if (!DONE_STATES.has(t.state)) return false;
      if (!t.created_at) return true; // keep if no date
      return new Date(t.created_at) > twentyFourHoursAgo;
    });
  }
  return tasks;
}

// Returns tasks with state QUEUED or PENDING.
export function filterQueueTasks(tasks) {
  return tasks.filter(t => t.state === 'QUEUED' || t.state === 'PENDING');
}

// Returns tasks with state READY.
export function filterReadyTasks(tasks) {
  return tasks.filter(t => t.state === 'READY');
}

// Returns COMPLETED, TIMED_OUT, BUDGET_EXCEEDED tasks from last 24h.
// Pass since24h=false to disable the time filter.
export function filterAllDoneTasks(tasks, since24h = true) {
  const DONE_TAB_STATES = new Set(['COMPLETED', 'TIMED_OUT', 'BUDGET_EXCEEDED']);
  return tasks.filter(t => {
    if (!DONE_TAB_STATES.has(t.state)) return false;
    if (!since24h) return true;
    if (!t.created_at) return true; // defensive: keep if no date
    const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
    return new Date(t.created_at) > twentyFourHoursAgo;
  });
}

export function getTaskFilterTab() {
  return localStorage.getItem('taskFilterTab') ?? 'active';
}

export function setTaskFilterTab(tab) {
  localStorage.setItem('taskFilterTab', tab);
}

export function getActiveMainTab() {
  return localStorage.getItem('activeMainTab') ?? 'stories';
}

export function setActiveMainTab(tab) {
  localStorage.setItem('activeMainTab', tab);
}

// ── Tab badge counts ───────────────────────────────────────────────────────────

/**
 * Computes badge counts for the 'interrupted', 'ready', and 'running' tabs.
 * Returns { interrupted: N, ready: N, running: N }.
 */
export function computeTabBadgeCounts(tasks) {
  let interrupted = 0;
  let ready = 0;
  let running = 0;

  for (const t of tasks) {
    if (INTERRUPTED_STATES.has(t.state)) interrupted++;
    if (t.state === 'READY') ready++;
    if (t.state === 'RUNNING') running++;
  }
  return { interrupted, ready, running };
}

/**
 * Updates the badge count spans inside the tab buttons for
 * 'interrupted', 'ready', 'running', and 'all'.
 * Badge is hidden (display:none) when count is zero.
 */
export function updateTabBadges(tasks, doc = (typeof document !== 'undefined' ? document : null)) {
  if (!doc) return;
  const counts = computeTabBadgeCounts(tasks);
  for (const [tab, count] of Object.entries(counts)) {
    const btn = doc.querySelector(`.tab[data-tab="${tab}"]`);
    if (!btn) continue;
    let badge = btn.querySelector('.tab-count-badge');
    if (!badge) {
      badge = doc.createElement('span');
      badge.className = 'tab-count-badge';
      btn.appendChild(badge);
    }
    badge.textContent = String(count);
    badge.hidden = count === 0;
  }
}

// ── Stats computations ─────────────────────────────────────────────────────────

/**
 * Computes task state distribution from a task array.
 * Returns { byState: { [state]: count } } — only states with tasks are included.
 */
export function computeTaskStats(tasks) {
  const byState = {};
  for (const t of tasks) {
    byState[t.state] = (byState[t.state] || 0) + 1;
  }
  return { byState };
}

/**
 * Computes execution health metrics from a RecentExecution array.
 * Returns:
 *   { total, successRate, totalCostUSD, avgDurationMs, byOutcome }
 * where successRate is a fraction (0–1), avgDurationMs is null if no durations.
 */
export function computeExecutionStats(executions) {
  if (executions.length === 0) {
    return { total: 0, successRate: 0, totalCostUSD: 0, avgDurationMs: null, byOutcome: {} };
  }

  let completed = 0;
  let totalCost = 0;
  let durationSum = 0;
  let durationCount = 0;
  const byOutcome = {};

  for (const e of executions) {
    const outcome = e.state || 'unknown';
    byOutcome[outcome] = (byOutcome[outcome] || 0) + 1;
    // Executions carry the task state machine's uppercase values (see
    // internal/executor.handleRunResult): a top-level task (no parent) that
    // succeeds lands its execution at READY, not COMPLETED — COMPLETED is
    // only set for subtask executions. Both represent a successful run from
    // the executor's perspective; only the human/chatbot accept step (a
    // separate, later transition) turns READY into COMPLETED.
    const normalized = outcome.toUpperCase();
    if (normalized === 'COMPLETED' || normalized === 'READY') completed++;
    totalCost += e.cost_usd || 0;
    if (e.duration_ms != null) {
      durationSum += e.duration_ms;
      durationCount++;
    }
  }

  return {
    total: executions.length,
    successRate: executions.length > 0 ? completed / executions.length : 0,
    totalCostUSD: totalCost,
    avgDurationMs: durationCount > 0 ? Math.round(durationSum / durationCount) : null,
    byOutcome,
  };
}

export function updateFilterTabs() {
  const current = getTaskFilterTab();
  document.querySelectorAll('.filter-tab[data-filter]').forEach(el => {
    el.classList.toggle('active', el.dataset.filter === current);
  });
}

function getHideCompletedFailed() {
  const stored = localStorage.getItem('hideCompletedFailed');
  return stored === null ? true : stored === 'true';
}

function setHideCompletedFailed(val) {
  localStorage.setItem('hideCompletedFailed', String(val));
}

function updateToggleButton() {
  const btn = document.getElementById('btn-toggle-completed');
  if (!btn) return;
  btn.textContent = getHideCompletedFailed()
    ? 'Show completed/failed'
    : 'Hide completed/failed';
}

// Shared helper: renders an array of tasks as cards into a container element.
// Now updated to be non-destructive by reusing/updating existing task-card elements.
// cardContentSignature returns a structural fingerprint of a task card,
// excluding any .task-log-tail/.running-log subtree — live-streamed log
// content must never cause renderTasksIntoContainer to think the card
// "changed" and tear it down (see Task 5 of the tasks-board plan).
export function cardContentSignature(cardEl) {
  function walk(el) {
    if (!el) return '';
    const isLogTail = el.className && (
      el.className.split(' ').includes('task-log-tail') ||
      el.className.split(' ').includes('running-log')
    );
    if (isLogTail) return `<logtail:${el.dataset && el.dataset.logTarget || ''}>`;
    const childSig = (el.children || []).map(walk).join('');
    return `<${el.tag || ''} class="${el.className || ''}" data-state="${(el.dataset && el.dataset.state) || ''}">${el.textContent || ''}${childSig}`;
  }
  return walk(cardEl);
}

function renderTasksIntoContainer(tasks, container, emptyMsg) {
  if (!tasks || tasks.length === 0) {
    container.innerHTML = `<div class="task-empty">${emptyMsg}</div>`;
    return;
  }

  // Remove empty message if it exists
  const empty = container.querySelector('.task-empty');
  if (empty) empty.remove();

  const existingCards = new Map();
  container.querySelectorAll('.task-card').forEach(card => {
    existingCards.set(card.dataset.taskId, card);
  });

  const taskIds = new Set(tasks.map(t => t.id));

  // Remove cards for tasks no longer in this list
  for (const [id, card] of existingCards.entries()) {
    if (!taskIds.has(id)) {
      card.remove();
      existingCards.delete(id);
    }
  }

  // Create or update cards and maintain order
  tasks.forEach((task, index) => {
    let card = existingCards.get(task.id);
    const newCard = createTaskCard(task);
    
    if (card) {
      // Compare everything except live-streamed log content (see
      // cardContentSignature) so an appending .task-log-tail never triggers
      // a teardown-and-rebuild of the whole card on its own.
      if (cardContentSignature(card) !== cardContentSignature(newCard)) {
        // Preserve the existing (potentially already-streaming) log-tail
        // element across the swap so its EventSource's target node stays
        // attached and its accumulated content survives.
        const oldLogTail = card.querySelector('.task-log-tail');
        const newLogTail = newCard.querySelector('.task-log-tail');
        if (oldLogTail && newLogTail) newLogTail.replaceWith(oldLogTail);
        container.replaceChild(newCard, card);
      }
    } else {
      // Append new card
      container.appendChild(newCard);
    }
  });

  // Re-sort cards in DOM to match task list order if they were out of sync
  const currentCards = Array.from(container.querySelectorAll('.task-card'));
  tasks.forEach((task, index) => {
    const card = container.querySelector(`[data-task-id="${task.id}"]`);
    if (container.children[index] !== card) {
      container.insertBefore(card, container.children[index]);
    }
  });
}

function renderQueuePanel(tasks) {
  const container = document.querySelector('[data-panel="queue"] .panel-task-list');
  if (!container) return;
  const visible = sortTasksByDate(filterQueueTasks(tasks));
  renderTasksIntoContainer(visible, container, 'No tasks queued.');
}

function renderInterruptedPanel(tasks) {
  const container = document.querySelector('[data-panel="interrupted"] .panel-task-list');
  if (!container) return;
  const visible = sortTasksByDate(tasks.filter(t => INTERRUPTED_STATES.has(t.state)), true);
  renderTasksIntoContainer(visible, container, 'No interrupted tasks.');
}

function renderReadyPanel(tasks) {
  const container = document.querySelector('[data-panel="ready"] .panel-task-list');
  if (!container) return;
  const visible = sortTasksByDate(filterReadyTasks(tasks));
  renderTasksIntoContainer(visible, container, 'No tasks awaiting review.');

  const completedContainer = document.querySelector('[data-panel="ready"] .ready-completed-history');
  if (!completedContainer) return;
  const done = sortTasksByDate(filterAllDoneTasks(tasks), true);
  if (!completedContainer.querySelector('.ready-completed-label')) {
    const label = document.createElement('h2');
    label.className = 'ready-completed-label';
    label.textContent = 'Completed (24h)';
    completedContainer.prepend(label);
  }
  const list = completedContainer.querySelector('.ready-completed-list') || (() => {
    const el = document.createElement('div');
    el.className = 'ready-completed-list';
    completedContainer.appendChild(el);
    return el;
  })();
  renderTasksIntoContainer(done, list, 'No completed tasks in the last 24h.');
}

// ── Run action ────────────────────────────────────────────────────────────────

async function runTask(taskId, agent) {
  const url = agent && agent !== 'auto'
    ? `${API_BASE}/api/tasks/${taskId}/run?agent=${agent}`
    : `${API_BASE}/api/tasks/${taskId}/run`;
  const res = await fetch(url, { method: 'POST' });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

async function handleRun(taskId, btn, footer) {
  const agentSelector = document.getElementById('select-agent');
  const agent = agentSelector ? agentSelector.value : 'auto';
  btn.disabled = true;
  btn.textContent = 'Queuing…';

  // Remove any previous error
  const prev = footer.querySelector('.task-error');
  if (prev) prev.remove();

  try {
    await runTask(taskId, agent);
    // Refresh active panel so state flips to QUEUED
    await poll();
  } catch (err) {
    btn.disabled = false;
    btn.textContent = 'Run';

    const errEl = document.createElement('span');
    errEl.className = 'task-error';
    errEl.textContent = `Failed to queue: ${err.message}`;
    footer.appendChild(errEl);
  }
}

// ── Cancel / Restart actions ──────────────────────────────────────────────────

async function cancelTask(taskId) {
  const res = await fetch(`${API_BASE}/api/tasks/${taskId}/cancel`, { method: 'POST' });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

async function restartTask(taskId) {
  const res = await fetch(`${API_BASE}/api/tasks/${taskId}/run`, { method: 'POST' });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

async function resumeTask(taskId) {
  const res = await fetch(`${API_BASE}/api/tasks/${taskId}/resume`, { method: 'POST' });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

const NON_DELETABLE_STATES = new Set(['RUNNING', 'QUEUED']);
const EDITABLE_STATES = new Set(['PENDING', 'FAILED', 'CANCELLED', 'TIMED_OUT', 'BUDGET_EXCEEDED']);

// Convert Duration JSON {"Duration": <ns>} to a human string for a text input (e.g. "15m").
function formatDurationForInput(timeout) {
  const ns = timeout && timeout.Duration;
  if (!ns) return '';
  const secs = Math.round(ns / 1e9);
  if (secs < 60) return `${secs}s`;
  const mins = Math.floor(secs / 60);
  const remSecs = secs % 60;
  if (mins < 60) return remSecs > 0 ? `${mins}m${remSecs}s` : `${mins}m`;
  const hrs = Math.floor(mins / 60);
  const remMins = mins % 60;
  return remMins > 0 ? `${hrs}h${remMins}m` : `${hrs}h`;
}

async function deleteTask(taskId) {
  const res = await fetch(`${API_BASE}/api/tasks/${taskId}`, { method: 'DELETE' });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
    throw new Error(msg);
  }
}

async function handleDelete(taskId, card) {
  if (!confirm('Delete this task? This cannot be undone.')) return;
  try {
    await deleteTask(taskId);
    card.remove();
  } catch (err) {
    alert(`Failed to delete: ${err.message}`);
  }
}

// ── Inline task editor ────────────────────────────────────────────────────────

async function updateTask(taskId, body) {
  const res = await fetch(`${API_BASE}/api/tasks/${taskId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const b = await res.json(); msg = b.error || b.message || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

function createEditForm(task, doc = document) {
  const a = task.agent || {};

  const form = doc.createElement('div');
  form.className = 'task-inline-edit';
  // Prevent card-level click from toggling this form while user interacts inside it.
  form.addEventListener('click', (e) => e.stopPropagation());

  function makeField(labelText, tag, attrs) {
    const label = doc.createElement('label');
    label.textContent = labelText;
    const el = doc.createElement(tag);
    for (const [k, v] of Object.entries(attrs)) {
      el[k] = v;
    }
    label.appendChild(el);
    return label;
  }

  form.appendChild(makeField('Name', 'input', { type: 'text', name: 'name', value: task.name || '' }));
  form.appendChild(makeField('Description', 'textarea', { name: 'description', rows: '2', value: task.description || '' }));
  form.appendChild(makeField('Instructions', 'textarea', { name: 'instructions', rows: '4', value: a.instructions || '' }));

  form.appendChild(makeField('Project Directory', 'input', { type: 'text', name: 'project_dir', value: a.project_dir || a.working_dir || '', placeholder: '/path/to/repo' }));
  form.appendChild(makeField('Max Budget (USD)', 'input', { type: 'number', name: 'max_budget_usd', step: '0.01', value: a.max_budget_usd != null ? String(a.max_budget_usd) : '1.00' }));
  form.appendChild(makeField('Timeout', 'input', { type: 'text', name: 'timeout', value: formatDurationForInput(task.timeout) || '15m', placeholder: '15m' }));

  const prioLabel = doc.createElement('label');
  prioLabel.textContent = 'Priority';
  const prioSel = doc.createElement('select');
  prioSel.name = 'priority';
  for (const val of ['high', 'normal', 'low']) {
    const opt = doc.createElement('option');
    opt.value = val;
    opt.textContent = val.charAt(0).toUpperCase() + val.slice(1);
    if (val === (task.priority || 'normal')) opt.selected = true;
    prioSel.appendChild(opt);
  }
  prioLabel.appendChild(prioSel);
  form.appendChild(prioLabel);

  const errEl = doc.createElement('div');
  errEl.className = 'inline-edit-error';
  errEl.hidden = true;
  form.appendChild(errEl);

  const actions = doc.createElement('div');
  actions.className = 'inline-edit-actions';

  const cancelBtn = doc.createElement('button');
  cancelBtn.type = 'button';
  cancelBtn.textContent = 'Cancel';
  cancelBtn.addEventListener('click', () => { form.hidden = true; });

  const saveBtn = doc.createElement('button');
  saveBtn.type = 'button';
  saveBtn.className = 'btn-primary btn-sm';
  saveBtn.textContent = 'Save';
  saveBtn.addEventListener('click', () => handleEditSave(task.id, form, saveBtn));

  actions.append(cancelBtn, saveBtn);
  form.appendChild(actions);

  return form;
}

async function handleEditSave(taskId, form, saveBtn) {
  const get = name => form.querySelector(`[name="${name}"]`)?.value ?? '';

  const body = {
    name: get('name'),
    description: get('description'),
    agent: {
      instructions: get('instructions'),
      project_dir: get('project_dir'),
      max_budget_usd: parseFloat(get('max_budget_usd')),
    },
    timeout: get('timeout'),
    priority: get('priority'),
  };

  const errEl = form.querySelector('.inline-edit-error');
  errEl.hidden = true;
  saveBtn.disabled = true;
  saveBtn.textContent = 'Saving…';

  try {
    await updateTask(taskId, body);
    form.hidden = true;

    // Brief success flash on the card
    const card = form.closest('.task-card');
    const flash = document.createElement('div');
    flash.className = 'inline-edit-success';
    flash.textContent = 'Saved';
    card.appendChild(flash);
    setTimeout(() => flash.remove(), 2000);

    await poll();
  } catch (err) {
    errEl.textContent = `Failed to save: ${err.message}`;
    errEl.hidden = false;
  } finally {
    saveBtn.disabled = false;
    saveBtn.textContent = 'Save';
  }
}

function renderQuestionFooter(task, footer, doc = document) {
  // Prevent any tap inside the question footer from opening the detail panel.
  footer.addEventListener('click', (e) => e.stopPropagation());

  let question = { text: 'Waiting for your input.', options: [] };
  if (task.question) {
    try { question = JSON.parse(task.question); } catch {}
  }

  const questionEl = doc.createElement('p');
  questionEl.className = 'task-question-text';
  questionEl.textContent = question.text;
  footer.appendChild(questionEl);

  if (question.options && question.options.length > 0) {
    question.options.forEach(opt => {
      const btn = doc.createElement('button');
      btn.className = 'btn-answer';
      btn.textContent = opt;
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        handleAnswer(task.id, opt, footer);
      });
      footer.appendChild(btn);
    });
  } else {
    const row = doc.createElement('div');
    row.className = 'task-answer-row';
    const input = doc.createElement('input');
    input.type = 'text';
    input.className = 'task-answer-input';
    input.placeholder = 'Your answer…';
    const btn = doc.createElement('button');
    btn.className = 'btn-answer';
    btn.textContent = 'Submit';
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      if (input.value.trim()) handleAnswer(task.id, input.value.trim(), footer);
    });
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && input.value.trim()) {
        e.stopPropagation();
        handleAnswer(task.id, input.value.trim(), footer);
      }
    });
    row.append(input, btn);
    footer.appendChild(row);
  }
}

const STATE_EMOJI = {
  PENDING: '⏳', QUEUED: '🕐', RUNNING: '⚡', COMPLETED: '✅',
  FAILED: '❌', CANCELLED: '🚫', TIMED_OUT: '⏱', BUDGET_EXCEEDED: '💸',
  READY: '👀', BLOCKED: '⏸',
};

async function renderSubtaskRollup(task, footer, doc = document) {
  footer.addEventListener('click', (e) => e.stopPropagation());
  const container = doc.createElement('div');
  container.className = 'subtask-rollup';
  footer.prepend(container);

  try {
    const res = await fetch(`${API_BASE}/api/tasks/${task.id}/subtasks`);
    const subtasks = await res.json();
    if (!subtasks || subtasks.length === 0) {
      const blurb = task.elaboration_input || task.description || task.name;
      container.textContent = blurb ? truncateToWordBoundary(blurb) : 'Waiting for subtasks…';
      return;
    }
    const ul = doc.createElement('ul');
    ul.className = 'subtask-list';
    for (const st of subtasks) {
      const li = doc.createElement('li');
      li.className = `subtask-item subtask-${st.state.toLowerCase()}`;
      li.textContent = `${STATE_EMOJI[st.state] || '•'} ${st.name}`;
      ul.appendChild(li);
    }
    container.appendChild(ul);
  } catch {
    container.textContent = 'Could not load subtasks.';
  }
}

async function handleAnswer(taskId, answer, footer) {
  const btns = footer.querySelectorAll('button, input');
  btns.forEach(el => { el.disabled = true; });
  const prev = footer.querySelector('.task-error');
  if (prev) prev.remove();

  try {
    const res = await fetch(`${API_BASE}/api/tasks/${taskId}/answer`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ answer }),
    });
    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      throw new Error(body.error || `HTTP ${res.status}`);
    }
    await poll();
  } catch (err) {
    btns.forEach(el => { el.disabled = false; });
    const errEl = document.createElement('span');
    errEl.className = 'task-error';
    errEl.textContent = `Failed: ${err.message}`;
    footer.appendChild(errEl);
  }
}

async function handleCancel(taskId, btn, footer) {
  btn.disabled = true;
  btn.textContent = 'Cancelling…';
  const prev = footer.querySelector('.task-error');
  if (prev) prev.remove();

  try {
    await cancelTask(taskId);
    await poll();
  } catch (err) {
    btn.disabled = false;
    btn.textContent = 'Cancel';
    const errEl = document.createElement('span');
    errEl.className = 'task-error';
    errEl.textContent = `Failed: ${err.message}`;
    footer.appendChild(errEl);
  }
}

async function handleRestart(taskId, btn, footer) {
  btn.disabled = true;
  btn.textContent = 'Restarting…';
  const prev = footer.querySelector('.task-error');
  if (prev) prev.remove();

  try {
    await restartTask(taskId);
    await poll();
  } catch (err) {
    btn.disabled = false;
    btn.textContent = 'Restart';
    const errEl = document.createElement('span');
    errEl.className = 'task-error';
    errEl.textContent = `Failed: ${err.message}`;
    footer.appendChild(errEl);
  }
}

async function handleResume(taskId, btn, footer) {
  btn.disabled = true;
  btn.textContent = 'Resuming…';
  const prev = footer.querySelector('.task-error');
  if (prev) prev.remove();

  try {
    await resumeTask(taskId);
    await poll();
  } catch (err) {
    btn.disabled = false;
    btn.textContent = 'Resume';
    const errEl = document.createElement('span');
    errEl.className = 'task-error';
    errEl.textContent = `Failed: ${err.message}`;
    footer.appendChild(errEl);
  }
}

// ── Accept / Reject actions ────────────────────────────────────────────────────

async function acceptTask(taskId) {
  const res = await fetch(`${API_BASE}/api/tasks/${taskId}/accept`, { method: 'POST' });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const body = await res.json(); msg = body.error || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

async function rejectTask(taskId, comment) {
  const res = await fetch(`${API_BASE}/api/tasks/${taskId}/reject`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ comment: comment || '' }),
  });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const body = await res.json(); msg = body.error || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

async function handleAccept(taskId, btn, footer) {
  btn.disabled = true;
  btn.textContent = 'Accepting…';
  const prev = footer.querySelector('.task-error');
  if (prev) prev.remove();

  try {
    await acceptTask(taskId);
    await poll();
  } catch (err) {
    btn.disabled = false;
    btn.textContent = 'Accept';
    const errEl = document.createElement('span');
    errEl.className = 'task-error';
    errEl.textContent = `Failed: ${err.message}`;
    footer.appendChild(errEl);
  }
}

async function handleReject(taskId, btn, footer) {
  const comment = prompt('Reason for rejection (optional):', '');
  if (comment === null) return; // User cancelled prompt

  btn.disabled = true;
  btn.textContent = 'Rejecting…';
  const prev = footer.querySelector('.task-error');
  if (prev) prev.remove();

  try {
    await rejectTask(taskId, comment);
    await poll();
  } catch (err) {
    btn.disabled = false;
    btn.textContent = 'Reject';
    const errEl = document.createElement('span');
    errEl.className = 'task-error';
    errEl.textContent = `Failed: ${err.message}`;
    footer.appendChild(errEl);
  }
}

// ── Start-next-task ─────────────────────────────────────────────────────────────

async function startNextTask(agent) {
  const url = agent && agent !== 'auto'
    ? `${API_BASE}/api/scripts/start-next-task?agent=${agent}`
    : `${API_BASE}/api/scripts/start-next-task`;
  const res = await fetch(url, { method: 'POST' });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const body = await res.json(); msg = body.error || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

async function handleStartNextTask(btn) {
  const agentSelector = document.getElementById('select-agent');
  const agent = agentSelector ? agentSelector.value : 'auto';
  btn.disabled = true;
  btn.textContent = 'Starting…';
  try {
    const result = await startNextTask(agent);
    const output = (result.output || '').trim();
    btn.textContent = output || 'No task to start';
    setTimeout(() => { btn.textContent = 'Start Next'; btn.disabled = false; }, 3000);
    if (output && output !== 'No task to start.') await poll();
  } catch (err) {
    btn.textContent = `Error: ${err.message}`;
    setTimeout(() => { btn.textContent = 'Start Next'; btn.disabled = false; }, 3000);
  }
}

// ── Polling ───────────────────────────────────────────────────────────────────

let taskCache = new Map();
let lastServerUpdate = null;
let pollTimeout = null;
let lastUserInteraction = Date.now();
let lastHistoryFetch = 0;

function getActiveTab() {
  const active = document.querySelector('.tab.active');
  return active ? active.dataset.tab : 'stories';
}

function getRefreshInterval() {
  const stored = localStorage.getItem('refreshInterval');
  return stored ? parseInt(stored, 10) : 10_000;
}

async function fetchHealth() {
  const res = await fetch(`${API_BASE}/api/health`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

function renderActiveTab(allTasks) {
  const activeTab = getActiveTab();
  switch (activeTab) {
    case 'stories':
      // Guard against yanking the board out from under an in-progress
      // HTML5 drag (see draggingStoryId) — the next poll tick after the
      // drag ends will pick up any server-side change.
      if (!draggingStoryId) renderStoriesPanel();
      break;
    case 'stats':
      Promise.all([
        fetchRecentExecutions(BASE_PATH, fetch),
        fetch(`${BASE_PATH}/api/agents/status?since=${encodeURIComponent(new Date(Date.now() - 24*60*60*1000).toISOString())}`).then(r => r.ok ? r.json() : { agents: [], events: [] }),
        fetch(`${BASE_PATH}/api/stats?window=7d`).then(r => r.ok ? r.json() : { throughput: [], billing: [], failures: [] }),
      ])
        .then(([execs, agentData, dashStats]) => renderStatsPanel(allTasks, execs, agentData, dashStats))
        .catch(() => {});
      break;
    case 'drops':
      renderDropsPanel();
      break;
    case 'settings':
      renderSettingsPanel();
      break;
  }
}

async function poll() {
  try {
    loadBudget(); // fire-and-forget; budget can change independently of tasks
    const health = await fetchHealth();
    const serverUpdate = health.last_updated;

    // If server says nothing changed, skip fetching but still render (e.g. tab was just switched).
    if (lastServerUpdate && serverUpdate <= lastServerUpdate && taskCache.size > 0) {
      renderActiveTab(Array.from(taskCache.values()));
      return;
    }

    const tasks = await fetchTasks(lastServerUpdate);
    lastServerUpdate = serverUpdate;

    // Update cache with new/changed tasks
    for (const t of tasks) {
      taskCache.set(t.id, t);
    }

    if (isUserEditing()) return;

    const allTasks = Array.from(taskCache.values());
    updateTabBadges(allTasks);
    renderActiveTab(allTasks);
  } catch (err) {
    console.error('Polling failed:', err);
    const panel = document.querySelector('[data-panel="queue"] .panel-task-list');
    if (panel && taskCache.size === 0) {
      panel.innerHTML = '<div class="task-empty">Could not reach server.</div>';
    }
  }
}

function startPolling() {
  if (pollTimeout) clearTimeout(pollTimeout);

  const runPoll = async () => {
    const interval = getRefreshInterval();
    if (interval > 0) {
      const now = Date.now();
      const timeSinceInteraction = now - lastUserInteraction;
      
      // If user is active, we might want to delay polling slightly,
      // but for now we just follow the interval if not editing.
      if (!isUserEditing()) {
        await poll();
      }
    }
    pollTimeout = setTimeout(runPoll, getRefreshInterval() || 10_000);
  };

  runPoll();
}

// Reset timer on interaction
if (typeof window !== 'undefined') {
  ['mousedown', 'keydown', 'touchstart', 'mousemove'].forEach(evt => {
    window.addEventListener(evt, () => {
      lastUserInteraction = Date.now();
    }, { passive: true });
  });
}



async function renderSettingsPanel() {
  const panel = document.querySelector('[data-panel="settings"]');
  if (!panel) return;

  panel.innerHTML = '';

  // ── General settings ──
  const section = document.createElement('div');
  section.className = 'stats-section';
  section.style.padding = '1rem';

  const heading = document.createElement('h2');
  heading.textContent = 'Settings';
  section.appendChild(heading);

  const refreshLabel = document.createElement('label');
  refreshLabel.style.display = 'block';
  refreshLabel.style.marginBottom = '0.5rem';
  refreshLabel.textContent = 'Auto-Refresh Interval';

  const refreshSelect = document.createElement('select');
  refreshSelect.className = 'agent-selector';
  refreshSelect.style.width = '100%';

  const options = [
    { label: '5 seconds', value: '5000' },
    { label: '10 seconds (default)', value: '10000' },
    { label: '30 seconds', value: '30000' },
    { label: '1 minute', value: '60000' },
    { label: 'Manual only', value: '0' },
  ];

  const current = String(getRefreshInterval());
  options.forEach(opt => {
    const o = document.createElement('option');
    o.value = opt.value;
    o.textContent = opt.label;
    if (opt.value === current) o.selected = true;
    refreshSelect.appendChild(o);
  });

  refreshSelect.addEventListener('change', () => {
    localStorage.setItem('refreshInterval', refreshSelect.value);
    startPolling();
  });

  refreshLabel.appendChild(refreshSelect);
  section.appendChild(refreshLabel);
  panel.appendChild(section);

  // ── Role Configuration ──
  const rolesSection = document.createElement('div');
  rolesSection.className = 'stats-section';
  rolesSection.style.padding = '1rem';
  const rolesHeading = document.createElement('h2');
  rolesHeading.textContent = 'Role Configuration';
  rolesSection.appendChild(rolesHeading);
  panel.appendChild(rolesSection);
  await renderRolesPanel(rolesSection);
}

// ── WebSocket (real-time events) ──────────────────────────────────────────────

let ws = null;
let activeLogSource = null;

function connectWebSocket() {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const url = `${protocol}//${window.location.host}${BASE_PATH}/api/ws`;
  ws = new WebSocket(url);

  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      handleWsEvent(data);
    } catch { /* ignore parse errors */ }
  };

  ws.onclose = () => {
    // Reconnect after 3 seconds.
    setTimeout(connectWebSocket, 3000);
  };

  ws.onerror = () => {
    ws.close();
  };
}

function handleWsEvent(data) {
  switch (data.type) {
    case 'task_started':
    case 'task_completed':
      // Force a poll immediately regardless of interval
      poll();
      break;
    case 'task_question':
      showQuestionBanner(data);
      break;
  }
}

// ── Question UI ───────────────────────────────────────────────────────────────

function showQuestionBanner(data) {
  const taskId = data.task_id;
  const questionId = data.question_id;
  const questionData = data.data || {};
  const questions = questionData.questions || [];

  // Find the task card for this task.
  const card = document.querySelector(`.task-card[data-task-id="${taskId}"]`);
  if (!card) return;

  // Remove any existing question banner on this card.
  const existing = card.querySelector('.question-banner');
  if (existing) existing.remove();

  const banner = document.createElement('div');
  banner.className = 'question-banner';

  for (const q of questions) {
    const qDiv = document.createElement('div');
    qDiv.className = 'question-item';

    const label = document.createElement('div');
    label.className = 'question-text';
    label.textContent = q.question || 'The agent has a question';
    qDiv.appendChild(label);

    const options = q.options || [];
    if (options.length > 0) {
      const btnGroup = document.createElement('div');
      btnGroup.className = 'question-options';
      for (const opt of options) {
        const btn = document.createElement('button');
        btn.className = 'btn-question-option';
        btn.textContent = opt.label;
        if (opt.description) btn.title = opt.description;
        btn.addEventListener('click', () => {
          submitAnswer(taskId, questionId, opt.label, banner);
        });
        btnGroup.appendChild(btn);
      }
      qDiv.appendChild(btnGroup);
    }

    // Always show a free-text input as fallback.
    const inputRow = document.createElement('div');
    inputRow.className = 'question-input-row';
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'question-input';
    input.placeholder = 'Type an answer…';
    const sendBtn = document.createElement('button');
    sendBtn.className = 'btn-question-send';
    sendBtn.textContent = 'Send';
    sendBtn.addEventListener('click', () => {
      const val = input.value.trim();
      if (val) submitAnswer(taskId, questionId, val, banner);
    });
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        const val = input.value.trim();
        if (val) submitAnswer(taskId, questionId, val, banner);
      }
    });
    inputRow.append(input, sendBtn);
    qDiv.appendChild(inputRow);

    banner.appendChild(qDiv);
  }

  card.appendChild(banner);
}

async function submitAnswer(taskId, questionId, answer, banner) {
  // Disable all buttons in the banner.
  banner.querySelectorAll('button').forEach(b => { b.disabled = true; });
  banner.querySelector('.question-input')?.setAttribute('disabled', '');

  try {
    const res = await fetch(`${API_BASE}/api/tasks/${taskId}/answer`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ question_id: questionId, answer }),
    });
    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      throw new Error(body.error || `HTTP ${res.status}`);
    }
    banner.remove();
  } catch (err) {
    const errEl = document.createElement('div');
    errEl.className = 'question-error';
    errEl.textContent = `Failed: ${err.message}`;
    banner.appendChild(errEl);
    // Re-enable buttons.
    banner.querySelectorAll('button').forEach(b => { b.disabled = false; });
    banner.querySelector('.question-input')?.removeAttribute('disabled');
  }
}

// ── Elaborate (Draft with AI) ─────────────────────────────────────────────────

// ── Task side panel ───────────────────────────────────────────────────────────

// Format Go's task.Duration JSON value {"Duration": <nanoseconds>} to human string.
function formatDurationNs(timeout) {
  const ns = timeout && timeout.Duration;
  if (!ns) return '—';
  const secs = ns / 1e9;
  if (secs < 60) return `${secs.toFixed(1)}s`;
  const mins = Math.floor(secs / 60);
  const remSecs = Math.floor(secs % 60);
  if (mins < 60) return remSecs > 0 ? `${mins}m ${remSecs}s` : `${mins}m`;
  const hrs = Math.floor(mins / 60);
  const remMins = mins % 60;
  return remMins > 0 ? `${hrs}h ${remMins}m` : `${hrs}h`;
}

function formatDateLong(iso) {
  if (!iso) return '—';
  return new Date(iso).toLocaleString(undefined, {
    year: 'numeric', month: 'short', day: 'numeric',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
  });
}

function openTaskPanel(taskId) {
  const panel = document.getElementById('task-panel');
  const backdrop = document.getElementById('task-panel-backdrop');
  const content = document.getElementById('task-panel-content');
  document.getElementById('task-panel-title').textContent = 'Task Details';

  content.innerHTML = '';
  const loading = document.createElement('div');
  loading.className = 'panel-loading';
  loading.textContent = 'Loading…';
  content.appendChild(loading);

  backdrop.hidden = false;
  panel.classList.add('open');

  Promise.all([
    fetch(`${API_BASE}/api/tasks/${taskId}`).then(r => {
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return r.json();
    }),
    fetch(`${API_BASE}/api/tasks/${taskId}/executions`).then(r => {
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return r.json();
    }),
  ]).then(([task, executions]) => {
    renderTaskPanel(task, executions);
  }).catch(err => {
    content.innerHTML = '';
    const errEl = document.createElement('div');
    errEl.className = 'panel-fetch-error';
    errEl.textContent = `Failed to load: ${err.message}`;
    content.appendChild(errEl);
  });
}

function closeTaskPanel() {
  closeLogViewer();
  document.getElementById('task-panel').classList.remove('open');
  document.getElementById('task-panel-backdrop').hidden = true;
}

function makeSection(title) {
  const section = document.createElement('div');
  section.className = 'panel-section';
  const hdr = document.createElement('div');
  hdr.className = 'panel-section-title';
  hdr.textContent = title;
  section.appendChild(hdr);
  return section;
}

function makeMetaItem(label, valueText, opts = {}) {
  const item = document.createElement('div');
  item.className = 'meta-item' + (opts.fullWidth ? ' full-width' : '');

  const lbl = document.createElement('div');
  lbl.className = 'meta-label';
  lbl.textContent = label;
  item.appendChild(lbl);

  if (opts.badge) {
    const badge = document.createElement('span');
    badge.className = 'state-badge';
    badge.dataset.state = valueText;
    badge.textContent = valueText.replace(/_/g, ' ');
    item.appendChild(badge);
  } else if (opts.code) {
    const pre = document.createElement('pre');
    pre.className = 'panel-code';
    pre.textContent = valueText;
    item.appendChild(pre);
  } else if (opts.tags) {
    const wrap = document.createElement('div');
    if (opts.tags.length > 0) {
      wrap.className = 'panel-tags';
      for (const tag of opts.tags) {
        const chip = document.createElement('span');
        chip.className = 'tag-chip';
        chip.textContent = tag;
        wrap.appendChild(chip);
      }
    } else {
      wrap.className = 'meta-value muted';
      wrap.textContent = '—';
    }
    item.appendChild(wrap);
  } else {
    const val = document.createElement('div');
    val.className = 'meta-value' + (opts.mono ? ' mono' : '') + (opts.muted ? ' muted' : '');
    val.textContent = valueText || '—';
    item.appendChild(val);
  }
  return item;
}

export function renderTaskPanel(task, executions) {
  document.getElementById('task-panel-title').textContent = task.name;
  const content = document.getElementById('task-panel-content');
  content.innerHTML = '';

  // ── Summary ──
  if (task.summary) {
    const summarySection = makeSection('Summary');
    const summaryEl = document.createElement('p');
    summaryEl.className = 'task-summary';
    summaryEl.textContent = task.summary;
    summarySection.appendChild(summaryEl);
    content.appendChild(summarySection);
  }

  // ── Q&A History ──
  if (task.interactions && task.interactions.length > 0) {
    const qaSection = makeSection('Q&A History');
    const qaList = document.createElement('div');
    qaList.className = 'qa-list';
    for (const interaction of task.interactions) {
      const qaItem = document.createElement('div');
      qaItem.className = 'qa-item';

      const qEl = document.createElement('div');
      qEl.className = 'qa-question';
      qEl.textContent = interaction.question_text || '(question)';
      qaItem.appendChild(qEl);

      if (interaction.options && interaction.options.length > 0) {
        const opts = document.createElement('div');
        opts.className = 'qa-options';
        opts.textContent = 'Options: ' + interaction.options.join(', ');
        qaItem.appendChild(opts);
      }

      if (interaction.answer) {
        const aEl = document.createElement('div');
        aEl.className = 'qa-answer';
        aEl.textContent = interaction.answer;
        qaItem.appendChild(aEl);
      }

      qaList.appendChild(qaItem);
    }
    qaSection.appendChild(qaList);
    content.appendChild(qaSection);
  }

  // ── Overview ──
  const overview = makeSection('Overview');
  const overviewGrid = document.createElement('div');
  overviewGrid.className = 'meta-grid';
  overviewGrid.append(
    makeMetaItem('State', task.state, { badge: true }),
    makeMetaItem('Priority', task.priority),
    makeMetaItem('Created', formatDateLong(task.created_at)),
    makeMetaItem('Updated', formatDateLong(task.updated_at)),
    makeMetaItem('ID', task.id, { fullWidth: true, mono: true }),
  );
  if (task.parent_task_id) {
    overviewGrid.append(makeMetaItem('Parent Task', task.parent_task_id, { fullWidth: true, mono: true }));
  }
  if (task.tags && task.tags.length >= 0) {
    overviewGrid.append(makeMetaItem('Tags', '', { fullWidth: true, tags: task.tags || [] }));
  }
  if (task.project) {
    overviewGrid.append(makeMetaItem('Project', task.project));
  }
  if (task.description) {
    overviewGrid.append(makeMetaItem('Description', task.description, { fullWidth: true }));
  }
  overview.appendChild(overviewGrid);
  content.appendChild(overview);

  // ── Agent Config ──
  const a = task.agent || {};
  const agentSection = makeSection('Agent Config');
  const agentGrid = document.createElement('div');
  agentGrid.className = 'meta-grid';
  agentGrid.append(
    makeMetaItem('Type', a.type || 'claude'),
    makeMetaItem('Model', a.model),
    makeMetaItem('Max Budget', a.max_budget_usd != null ? `$${a.max_budget_usd.toFixed(2)}` : '—'),
    makeMetaItem('Project Dir', a.project_dir || a.working_dir),
    makeMetaItem('Permission Mode', a.permission_mode || 'default'),
  );
  if (a.allowed_tools && a.allowed_tools.length > 0) {
    agentGrid.append(makeMetaItem('Allowed Tools', a.allowed_tools.join(', '), { fullWidth: true }));
  }
  if (a.disallowed_tools && a.disallowed_tools.length > 0) {
    agentGrid.append(makeMetaItem('Disallowed Tools', a.disallowed_tools.join(', '), { fullWidth: true }));
  }
  if (a.instructions) {
    agentGrid.append(makeMetaItem('Instructions', a.instructions, { fullWidth: true, code: true }));
  }
  if (a.system_prompt_append) {
    agentGrid.append(makeMetaItem('System Prompt Append', a.system_prompt_append, { fullWidth: true, code: true }));
  }
  agentSection.appendChild(agentGrid);
  content.appendChild(agentSection);

  // ── Q&A History ──
  let interactions = [];
  if (task.interactions) {
    try { interactions = JSON.parse(task.interactions); } catch {}
  }
  if (interactions.length > 0) {
    const qaSection = makeSection("Q&A History");
    const timeline = document.createElement("div");
    timeline.className = "qa-timeline";
    for (const item of interactions) {
      const entry = document.createElement("div");
      entry.className = `qa-item qa-${item.type}`;
      const label = document.createElement("span");
      label.className = "qa-label";
      label.textContent = item.type === "question" ? "Agent asked:" : "User answered:";
      const text = document.createElement("div");
      text.className = "qa-content";
      text.textContent = item.content;
      const ts = document.createElement("span");
      ts.className = "qa-timestamp";
      ts.textContent = item.timestamp ? formatDate(item.timestamp) : "";
      entry.append(label, text, ts);
      timeline.appendChild(entry);
    }
    qaSection.appendChild(timeline);
    content.appendChild(qaSection);
  }

  // ── Execution Settings ──
  const settingsSection = makeSection('Execution Settings');
  const settingsGrid = document.createElement('div');
  settingsGrid.className = 'meta-grid';
  settingsGrid.append(
    makeMetaItem('Timeout', formatDurationNs(task.timeout)),
    makeMetaItem('Retry Attempts', String(task.retry ? task.retry.max_attempts : 1)),
    makeMetaItem('Backoff', task.retry ? task.retry.backoff : '—'),
  );
  if (task.depends_on && task.depends_on.length > 0) {
    settingsGrid.append(makeMetaItem('Depends On', task.depends_on.join(', '), { fullWidth: true, mono: true }));
  }
  settingsSection.appendChild(settingsGrid);
  content.appendChild(settingsSection);

  // ── Executions ──
  const execSection = makeSection('Executions');
  if (!executions || executions.length === 0) {
    const none = document.createElement('div');
    none.className = 'meta-value muted';
    none.textContent = 'No executions yet.';
    execSection.appendChild(none);
  } else {
    const list = document.createElement('div');
    list.className = 'executions-list';
    // Newest first
    for (const exec of [...executions].reverse()) {
      const row = document.createElement('div');
      row.className = 'execution-row';

      const shortId = document.createElement('span');
      shortId.className = 'execution-id';
      shortId.textContent = exec.ID ? exec.ID.slice(0, 8) : '—';
      row.appendChild(shortId);

      const badge = document.createElement('span');
      badge.className = 'state-badge';
      badge.dataset.state = exec.Status || '';
      badge.textContent = (exec.Status || '—').replace(/_/g, ' ');
      row.appendChild(badge);

      const times = document.createElement('span');
      times.className = 'execution-times';
      const start = exec.StartTime ? formatDate(exec.StartTime) : '?';
      const end = exec.EndTime && exec.EndTime !== '0001-01-01T00:00:00Z' ? formatDate(exec.EndTime) : '…';
      times.textContent = `${start} → ${end}`;
      row.appendChild(times);

      if (exec.CostUSD != null && exec.CostUSD > 0) {
        const cost = document.createElement('span');
        cost.className = 'execution-cost';
        cost.textContent = `$${exec.CostUSD.toFixed(4)}`;
        row.appendChild(cost);
      }

      const exitEl = document.createElement('span');
      exitEl.className = 'execution-exit';
      exitEl.textContent = `exit: ${exec.ExitCode ?? '—'}`;
      row.appendChild(exitEl);

      if (exec.Changestats != null) {
        const csBadge = renderChangestatsBadge(exec.Changestats);
        if (csBadge) row.appendChild(csBadge);
      }

      if (exec.Commits && exec.Commits.length > 0) {
        const commitList = document.createElement('div');
        commitList.className = 'execution-commits';
        for (const commit of exec.Commits) {
          const item = document.createElement('div');
          item.className = 'commit-item';
          
          const hash = document.createElement('span');
          hash.className = 'commit-hash';
          hash.textContent = commit.hash.slice(0, 7);
          item.appendChild(hash);
          
          const msg = document.createElement('span');
          msg.className = 'commit-msg';
          msg.textContent = commit.message;
          item.appendChild(msg);
          
          commitList.appendChild(item);
        }
        row.appendChild(commitList);
      }

      row.style.cursor = 'pointer';
      row.addEventListener('click', () => openExecutionDetail(exec.ID));

      list.appendChild(row);
    }
    execSection.appendChild(list);
  }
  content.appendChild(execSection);

  // ── Timeline ──
  // Observability event stream, loaded asynchronously. Guarded so the sync
  // panel render (and its unit tests, which have no fetch) is unaffected.
  const timelineSection = makeSection('Timeline');
  const timelineContainer = document.createElement('div');
  timelineContainer.className = 'event-timeline-container';
  timelineSection.appendChild(timelineContainer);
  content.appendChild(timelineSection);
  if (typeof fetch !== 'undefined') {
    fetchTaskEvents(task.id).then(events => {
      timelineContainer.innerHTML = '';
      timelineContainer.appendChild(renderEventTimeline(events));
    });
  }
}

async function openExecutionDetail(execId) {
  const modal = document.getElementById('logs-modal');
  const body = document.getElementById('logs-modal-body');
  document.getElementById('logs-modal-title').textContent = `Execution ${execId.slice(0, 8)}`;
  body.innerHTML = '<div class="panel-loading">Loading…</div>';
  modal.showModal();

  let detailLogSource = null;

  const onClose = () => {
    detailLogSource?.close();
    detailLogSource = null;
    modal.removeEventListener('close', onClose);
  };
  modal.addEventListener('close', onClose);

  try {
    const res = await fetch(`${API_BASE}/api/executions/${execId}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const exec = await res.json();

    body.innerHTML = '';

    // Metadata grid
    const grid = document.createElement('div');
    grid.className = 'meta-grid';
    const entries = [
      ['ID',        exec.ID,        { fullWidth: true, mono: true }],
      ['Status',    exec.Status,    { badge: true }],
      ['Agent',     exec.Agent || '—', {}],
      ['Exit Code', String(exec.ExitCode ?? '—'), {}],
      ['Cost',      exec.CostUSD > 0 ? `$${exec.CostUSD.toFixed(4)}` : '—', {}],
      ['Start',     formatDateLong(exec.StartTime), {}],
      ['End',       exec.EndTime && !exec.EndTime.startsWith('0001-') ? formatDateLong(exec.EndTime) : '—', {}],
      ['Error',     exec.ErrorMsg || '—', { fullWidth: true }],
      ['Stdout',    exec.StdoutPath || '—', { fullWidth: true, mono: true }],
      ['Stderr',    exec.StderrPath || '—', { fullWidth: true, mono: true }],
    ];
    for (const [label, value, opts] of entries) {
      grid.appendChild(makeMetaItem(label, value, opts));
    }
    body.appendChild(grid);

    // Log stream
    const logHeader = document.createElement('div');
    logHeader.style.cssText = 'margin: 1rem 0 0.5rem; font-size: 0.75rem; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em;';
    logHeader.textContent = 'Log';
    body.appendChild(logHeader);

    const statusEl = document.createElement('div');
    statusEl.className = 'log-status-indicator';
    statusEl.textContent = 'Streaming...';
    body.appendChild(statusEl);

    const logOutput = document.createElement('div');
    logOutput.className = 'log-output';
    logOutput.style.fontFamily = 'monospace';
    logOutput.style.overflowY = 'auto';
    logOutput.style.maxHeight = '400px';
    body.appendChild(logOutput);

    let userScrolled = false;
    logOutput.addEventListener('scroll', () => {
      const nearBottom = logOutput.scrollHeight - logOutput.scrollTop - logOutput.clientHeight < 50;
      userScrolled = !nearBottom;
    });

    const source = new EventSource(`${API_BASE}/api/executions/${execId}/logs/stream`);
    detailLogSource = source;

    source.onmessage = (event) => {
      let data;
      try { data = JSON.parse(event.data); } catch { return; }

      const line = document.createElement('div');
      line.className = 'log-line';

      switch (data.type) {
        case 'text': {
          line.classList.add('log-text');
          line.textContent = data.text ?? data.content ?? '';
          break;
        }
        case 'tool_use': {
          line.classList.add('log-tool-use');
          const toolName = document.createElement('span');
          toolName.className = 'tool-name';
          toolName.textContent = `[${data.name ?? 'Tool'}]`;
          line.appendChild(toolName);
          const inputStr = data.input ? JSON.stringify(data.input) : '';
          const inputPreview = document.createElement('span');
          inputPreview.textContent = ' ' + inputStr.slice(0, 120);
          line.appendChild(inputPreview);
          break;
        }
        case 'tool_result': {
          line.classList.add('log-tool-result');
          line.style.opacity = '0.6';
          const content = Array.isArray(data.content)
            ? data.content.map(c => c.text ?? '').join(' ')
            : (data.content ?? '');
          line.textContent = String(content).slice(0, 120);
          break;
        }
        case 'cost': {
          line.classList.add('log-cost');
          const cost = data.total_cost ?? data.cost ?? 0;
          line.textContent = `Cost: $${Number(cost).toFixed(3)}`;
          break;
        }
        default:
          return;
      }

      logOutput.appendChild(line);
      if (!userScrolled) {
        logOutput.scrollTop = logOutput.scrollHeight;
      }
    };

    source.addEventListener('done', () => {
      source.close();
      detailLogSource = null;
      userScrolled = false;
      statusEl.classList.remove('log-status-indicator');
      statusEl.textContent = 'Stream complete';
    });

    source.onerror = () => {
      source.close();
      detailLogSource = null;
      statusEl.hidden = true;
      const errEl = document.createElement('div');
      errEl.className = 'log-line log-error';
      errEl.textContent = 'Connection error. Stream closed.';
      logOutput.appendChild(errEl);
    };

  } catch (err) {
    body.innerHTML = `<div class="panel-fetch-error">Failed to load: ${err.message}</div>`;
  }
}

// ── Log viewer ────────────────────────────────────────────────────────────────

function openLogViewer(execId, containerEl) {
  // Save original children so Back can restore them (with event listeners intact)
  const originalChildren = [...containerEl.childNodes];

  containerEl.innerHTML = '';

  const viewer = document.createElement('div');
  viewer.className = 'log-viewer';

  // Back button
  const backBtn = document.createElement('button');
  backBtn.className = 'log-back-btn';
  backBtn.textContent = '← Back';
  backBtn.addEventListener('click', () => {
    closeLogViewer();
    containerEl.innerHTML = '';
    for (const node of originalChildren) containerEl.appendChild(node);
  });
  viewer.appendChild(backBtn);

  // Pulsing status indicator
  const statusEl = document.createElement('div');
  statusEl.className = 'log-status-indicator';
  statusEl.textContent = 'Streaming...';
  viewer.appendChild(statusEl);

  // Log output area
  const logOutput = document.createElement('div');
  logOutput.className = 'log-output';
  logOutput.style.fontFamily = 'monospace';
  logOutput.style.overflowY = 'auto';
  logOutput.style.maxHeight = '400px';
  viewer.appendChild(logOutput);

  containerEl.appendChild(viewer);

  let userScrolled = false;
  logOutput.addEventListener('scroll', () => {
    const nearBottom = logOutput.scrollHeight - logOutput.scrollTop - logOutput.clientHeight < 50;
    userScrolled = !nearBottom;
  });

  const source = new EventSource(`${API_BASE}/api/executions/${execId}/logs/stream`);
  activeLogSource = source;

  source.onmessage = (event) => {
    let data;
    try { data = JSON.parse(event.data); } catch { return; }

    const line = document.createElement('div');
    line.className = 'log-line';

    switch (data.type) {
      case 'text': {
        line.classList.add('log-text');
        line.textContent = data.text ?? data.content ?? '';
        break;
      }
      case 'tool_use': {
        line.classList.add('log-tool-use');
        const toolName = document.createElement('span');
        toolName.className = 'tool-name';
        toolName.textContent = `[${data.name ?? 'Tool'}]`;
        line.appendChild(toolName);
        const inputStr = data.input ? JSON.stringify(data.input) : '';
        const inputPreview = document.createElement('span');
        inputPreview.textContent = ' ' + inputStr.slice(0, 120);
        line.appendChild(inputPreview);
        break;
      }
      case 'tool_result': {
        line.classList.add('log-tool-result');
        line.style.opacity = '0.6';
        const content = Array.isArray(data.content)
          ? data.content.map(c => c.text ?? '').join(' ')
          : (data.content ?? '');
        line.textContent = String(content).slice(0, 120);
        break;
      }
      case 'cost': {
        line.classList.add('log-cost');
        const cost = data.total_cost ?? data.cost ?? 0;
        line.textContent = `Cost: $${Number(cost).toFixed(3)}`;
        break;
      }
      default:
        return;
    }

    logOutput.appendChild(line);
    if (!userScrolled) {
      logOutput.scrollTop = logOutput.scrollHeight;
    }
  };

  source.addEventListener('done', () => {
    source.close();
    activeLogSource = null;
    userScrolled = false;
    statusEl.classList.remove('log-status-indicator');
    statusEl.textContent = 'Stream complete';
  });

  source.onerror = () => {
    source.close();
    activeLogSource = null;
    statusEl.hidden = true;
    const errEl = document.createElement('div');
    errEl.className = 'log-line log-error';
    errEl.textContent = 'Connection error. Stream closed.';
    logOutput.appendChild(errEl);
  };
}

function closeLogViewer() {
  activeLogSource?.close();
  activeLogSource = null;
}

// ── Running view ───────────────────────────────────────────────────────────────

// Map of taskId → EventSource for live log streams in the Running tab.
const runningViewLogSources = {};

function renderRunningView(tasks) {
  const currentEl = document.querySelector('.running-current');
  if (!currentEl) return;

  const running = filterRunningTasks(tasks);

  // Close SSE streams for tasks that are no longer RUNNING.
  for (const [id, src] of Object.entries(runningViewLogSources)) {
    if (!running.find(t => t.id === id)) {
      src.close();
      delete runningViewLogSources[id];
    }
  }

  // Update elapsed spans in place if the same tasks are still running.
  const existingCards = currentEl.querySelectorAll('[data-task-id]');
  const existingIds = new Set([...existingCards].map(c => c.dataset.taskId));
  const unchanged = running.length > 0 &&
    running.length === existingCards.length &&
    running.every(t => existingIds.has(t.id));

  if (unchanged) {
    updateRunningElapsed();
    return;
  }

  // Full re-render.
  currentEl.innerHTML = '';

  const h2 = document.createElement('h2');
  h2.textContent = 'Currently Running';
  currentEl.appendChild(h2);

  if (running.length === 0) {
    const empty = document.createElement('p');
    empty.className = 'task-meta';
    empty.textContent = 'No tasks are currently running.';
    currentEl.appendChild(empty);
    return;
  }

  for (const task of running) {
    const card = document.createElement('div');
    card.className = 'running-task-card task-card';
    card.dataset.taskId = task.id;

    const header = document.createElement('div');
    header.className = 'task-card-header';

    const name = document.createElement('span');
    name.className = 'task-name';
    name.textContent = task.name;

    const badge = document.createElement('span');
    badge.className = 'state-badge';
    badge.dataset.state = task.state;
    badge.textContent = task.state;

    const elapsed = document.createElement('span');
    elapsed.className = 'running-elapsed';
    elapsed.dataset.startedAt = task.updated_at ?? '';
    elapsed.textContent = formatElapsed(task.updated_at);

    header.append(name, badge, elapsed);
    card.appendChild(header);

    // Parent context (async fetch)
    if (task.parent_task_id) {
      const parentEl = document.createElement('div');
      parentEl.className = 'task-meta';
      parentEl.textContent = 'Subtask of: …';
      card.appendChild(parentEl);
      fetch(`${API_BASE}/api/tasks/${task.parent_task_id}`)
        .then(r => r.ok ? r.json() : null)
        .then(parent => {
          if (parent) parentEl.textContent = `Subtask of: ${parent.name}`;
        })
        .catch(() => { parentEl.textContent = ''; });
    }

    // Meta row: agent type + model + execution ID (exec ID filled in async)
    const metaRow = document.createElement('div');
    metaRow.className = 'task-meta running-exec-meta';
    const agentType = (task.agent && task.agent.type) ? task.agent.type : 'claude';
    const agentModel = (task.agent && task.agent.model) ? task.agent.model : '';
    const agentSpan = document.createElement('span');
    agentSpan.textContent = agentModel ? `${agentType} (${agentModel})` : `Agent: ${agentType}`;
    const execIdSpan = document.createElement('span');
    execIdSpan.className = 'execution-id running-exec-id';
    execIdSpan.textContent = 'exec: …';
    metaRow.append(agentSpan, execIdSpan);
    card.appendChild(metaRow);

    // Log area
    const logArea = document.createElement('div');
    logArea.className = 'running-log';
    logArea.dataset.logTarget = task.id;
    card.appendChild(logArea);

    // Footer with Cancel button
    const footer = document.createElement('div');
    footer.className = 'task-card-footer';
    const cancelBtn = document.createElement('button');
    cancelBtn.className = 'btn-cancel';
    cancelBtn.textContent = 'Cancel';
    cancelBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      handleCancel(task.id, cancelBtn, footer);
    });
    footer.appendChild(cancelBtn);
    card.appendChild(footer);

    currentEl.appendChild(card);

    // Open SSE stream if not already streaming for this task.
    if (!runningViewLogSources[task.id]) {
      startRunningLogStream(task.id, logArea);
    }
  }
}

// taskId -> { source: EventSource, execId: string } — tracks which execution
// each visible task's inline log-tail is currently attached to, so a poll-
// driven re-render never reopens a stream for the same execution twice, and
// correctly reopens when a Resume/Restart produces a fresh execution.
export const taskLogStreams = {};

// ensureTaskLogStream attaches (or leaves alone) a log stream for a task's
// most recent execution into logAreaEl. Every column's card uses this same
// mechanism — see docs/superpowers/specs/2026-07-06-tasks-board-design.md
// section 4: the /api/executions/{id}/logs/stream endpoint already replays-
// then-closes for a terminal execution and live-tails for a RUNNING one, so
// there is no separate "static" vs. "live" code path.
export async function ensureTaskLogStream(taskId, logAreaEl, {
  fetchFn = fetch,
  EventSourceImpl = (typeof EventSource !== 'undefined' ? EventSource : undefined),
  apiBase = API_BASE,
} = {}) {
  let execs;
  try {
    const res = await fetchFn(`${apiBase}/api/executions?task_id=${taskId}&limit=1`);
    execs = res.ok ? await res.json() : [];
  } catch {
    return;
  }
  if (!execs || execs.length === 0) return; // no execution yet (Queue)

  const execId = execs[0].id;
  const existing = taskLogStreams[taskId];
  if (existing && existing.execId === execId) return; // already attached to this execution

  if (existing) existing.source.close();
  // .children is a read-only live collection on a real DOM element — the
  // only correct way to clear it is innerHTML (the fake log-area mock in
  // web/test/tasks-board.test.mjs mirrors this via an innerHTML setter).
  logAreaEl.innerHTML = '';

  const src = new EventSourceImpl(`${apiBase}/api/executions/${execId}/logs/stream`);
  taskLogStreams[taskId] = { source: src, execId };

  let userScrolled = false;
  if (logAreaEl.addEventListener) {
    logAreaEl.addEventListener('scroll', () => {
      const nearBottom = logAreaEl.scrollHeight - logAreaEl.scrollTop - logAreaEl.clientHeight < 50;
      userScrolled = !nearBottom;
    });
  }

  src.onmessage = (event) => {
    let data;
    try { data = JSON.parse(event.data); } catch { return; }

    const doc = (typeof document !== 'undefined') ? document : { createElement: (t) => ({ tag: t, className: '', textContent: '', children: [], appendChild(c) { this.children.push(c); } }) };
    const line = doc.createElement('div');
    line.className = 'log-line';

    switch (data.type) {
      case 'text':
        line.classList.add('log-text');
        line.textContent = data.text ?? data.content ?? '';
        break;
      case 'tool_use': {
        line.classList.add('log-tool-use');
        const toolName = doc.createElement('span');
        toolName.className = 'tool-name';
        toolName.textContent = `[${data.name ?? 'Tool'}]`;
        line.appendChild(toolName);
        const inputStr = data.input ? JSON.stringify(data.input) : '';
        const inputPreview = doc.createElement('span');
        inputPreview.textContent = ' ' + inputStr.slice(0, 120);
        line.appendChild(inputPreview);
        break;
      }
      case 'cost':
        line.classList.add('log-cost');
        line.textContent = `Cost: $${Number(data.total_cost ?? data.cost ?? 0).toFixed(3)}`;
        break;
      default:
        return;
    }

    logAreaEl.appendChild(line);
    while (logAreaEl.childElementCount > 200) {
      logAreaEl.removeChild(logAreaEl.firstElementChild);
    }
    if (!userScrolled) logAreaEl.scrollTop = logAreaEl.scrollHeight;
  };

  src.addEventListener('done', () => {
    src.close();
    if (taskLogStreams[taskId] && taskLogStreams[taskId].source === src) delete taskLogStreams[taskId];
  });

  src.onerror = () => {
    src.close();
    if (taskLogStreams[taskId] && taskLogStreams[taskId].source === src) delete taskLogStreams[taskId];
  };
}

function startRunningLogStream(taskId, logArea) {
  fetch(`${API_BASE}/api/executions?task_id=${taskId}&limit=1`)
    .then(r => r.ok ? r.json() : [])
    .then(execs => {
      if (!execs || execs.length === 0) return;
      const execId = execs[0].id;

      // Update the exec ID shown in the running card.
      const card = document.querySelector(`[data-task-id="${taskId}"]`);
      if (card) {
        const execIdEl = card.querySelector('.running-exec-id');
        if (execIdEl) execIdEl.textContent = `exec: ${execId.slice(0, 8)}`;
      }

      let userScrolled = false;
      logArea.addEventListener('scroll', () => {
        const nearBottom = logArea.scrollHeight - logArea.scrollTop - logArea.clientHeight < 50;
        userScrolled = !nearBottom;
      });

      const src = new EventSource(`${API_BASE}/api/executions/${execId}/logs/stream`);
      runningViewLogSources[taskId] = src;

      src.onmessage = (event) => {
        let data;
        try { data = JSON.parse(event.data); } catch { return; }

        const line = document.createElement('div');
        line.className = 'log-line';

        switch (data.type) {
          case 'text': {
            line.classList.add('log-text');
            line.textContent = data.text ?? data.content ?? '';
            break;
          }
          case 'tool_use': {
            line.classList.add('log-tool-use');
            const toolName = document.createElement('span');
            toolName.className = 'tool-name';
            toolName.textContent = `[${data.name ?? 'Tool'}]`;
            line.appendChild(toolName);
            const inputStr = data.input ? JSON.stringify(data.input) : '';
            const inputPreview = document.createElement('span');
            inputPreview.textContent = ' ' + inputStr.slice(0, 120);
            line.appendChild(inputPreview);
            break;
          }
          case 'cost': {
            line.classList.add('log-cost');
            const cost = data.total_cost ?? data.cost ?? 0;
            line.textContent = `Cost: $${Number(cost).toFixed(3)}`;
            break;
          }
          default:
            return;
        }

        logArea.appendChild(line);
        // Trim to last 500 lines.
        while (logArea.childElementCount > 500) {
          logArea.removeChild(logArea.firstElementChild);
        }
        if (!userScrolled) logArea.scrollTop = logArea.scrollHeight;
      };

      src.addEventListener('done', () => {
        src.close();
        delete runningViewLogSources[taskId];
      });

      src.onerror = () => {
        src.close();
        delete runningViewLogSources[taskId];
        const errEl = document.createElement('div');
        errEl.className = 'log-line log-error';
        errEl.textContent = 'Stream closed.';
        logArea.appendChild(errEl);
      };
    })
    .catch(() => {});
}

function updateRunningElapsed() {
  document.querySelectorAll('.running-elapsed[data-started-at]').forEach(el => {
    el.textContent = formatElapsed(el.dataset.startedAt || null);
  });
}

function isRunningTabActive() {
  const panel = document.querySelector('[data-panel="running"]');
  return panel && !panel.hasAttribute('hidden');
}

function sortExecutionsByDate(executions) {
  return sortExecutionsDesc(executions);
}

function renderRunningHistory(executions) {
  const histEl = document.querySelector('.running-history');
  if (!histEl) return;

  histEl.innerHTML = '';

  const h2 = document.createElement('h2');
  h2.textContent = 'Execution History (Last 24h)';
  histEl.appendChild(h2);

  if (!executions || executions.length === 0) {
    const empty = document.createElement('p');
    empty.className = 'task-meta';
    empty.textContent = 'No executions in the last 24h';
    histEl.appendChild(empty);
    return;
  }

  const sorted = sortExecutionsDesc(executions);

  const table = document.createElement('table');
  table.className = 'history-table';

  const thead = document.createElement('thead');
  const headerRow = document.createElement('tr');
  for (const col of ['Date', 'Task', 'Status', 'Duration', 'Cost', 'Exit', 'Logs']) {
    const th = document.createElement('th');
    th.textContent = col;
    headerRow.appendChild(th);
  }
  thead.appendChild(headerRow);
  table.appendChild(thead);

  const tbody = document.createElement('tbody');
  for (const exec of sorted) {
    const tr = document.createElement('tr');

    const tdDate = document.createElement('td');
    tdDate.textContent = formatDate(exec.started_at);
    tr.appendChild(tdDate);

    const tdTask = document.createElement('td');
    tdTask.textContent = exec.task_name || exec.task_id || '—';
    tr.appendChild(tdTask);

    const tdStatus = document.createElement('td');
    const stateBadge = document.createElement('span');
    stateBadge.className = 'state-badge';
    stateBadge.dataset.state = exec.state || '';
    stateBadge.textContent = exec.state || '—';
    tdStatus.appendChild(stateBadge);
    tr.appendChild(tdStatus);

    const tdDur = document.createElement('td');
    tdDur.textContent = formatDuration(exec.started_at, exec.finished_at ?? null);
    tr.appendChild(tdDur);

    const tdCost = document.createElement('td');
    tdCost.textContent = exec.cost_usd > 0 ? `$${exec.cost_usd.toFixed(4)}` : '—';
    tr.appendChild(tdCost);

    const tdExit = document.createElement('td');
    tdExit.textContent = exec.exit_code != null ? String(exec.exit_code) : '—';
    tr.appendChild(tdExit);

    const tdLogs = document.createElement('td');
    const viewBtn = document.createElement('button');
    viewBtn.className = 'btn-sm';
    viewBtn.textContent = 'View Logs';
    viewBtn.addEventListener('click', () => openLogViewer(exec.id, histEl));
    tdLogs.appendChild(viewBtn);
    tr.appendChild(tdLogs);

    tbody.appendChild(tr);
  }
  table.appendChild(tbody);
  histEl.appendChild(table);
}

// ── Stats rendering ───────────────────────────────────────────────────────────

// State display order for the task overview grid.
const STATS_STATE_ORDER = [
  'RUNNING', 'QUEUED', 'READY', 'BLOCKED',
  'PENDING', 'COMPLETED', 'FAILED', 'TIMED_OUT', 'CANCELLED', 'BUDGET_EXCEEDED',
];

function formatDurationMs(ms) {
  if (ms == null) return '—';
  const s = Math.round(ms / 1000);
  if (s < 60) return `${s}s`;
  const m = Math.floor(s / 60);
  const rs = s % 60;
  if (m < 60) return rs > 0 ? `${m}m ${rs}s` : `${m}m`;
  const h = Math.floor(m / 60);
  const rm = m % 60;
  return rm > 0 ? `${h}h ${rm}m` : `${h}h`;
}

function renderStatsPanel(tasks, executions, agentData = { agents: [], events: [] }, dashStats = { throughput: [], billing: [], failures: [] }) {
  const panel = document.querySelector('[data-panel="stats"]');
  if (!panel) return;

  const taskStats = computeTaskStats(tasks);
  const execStats = computeExecutionStats(executions);

  panel.innerHTML = '';

  // ── Task Overview ──────────────────────────────────────────────────────────
  const taskSection = document.createElement('div');
  taskSection.className = 'stats-section';

  const taskHeading = document.createElement('h2');
  taskHeading.textContent = 'Task Overview';
  taskSection.appendChild(taskHeading);

  const countsGrid = document.createElement('div');
  countsGrid.className = 'stats-counts';

  const orderedStates = STATS_STATE_ORDER.filter(s => taskStats.byState[s] > 0);
  const otherStates = Object.keys(taskStats.byState).filter(s => !STATS_STATE_ORDER.includes(s));

  for (const state of [...orderedStates, ...otherStates]) {
    const count = taskStats.byState[state] || 0;
    if (count === 0) continue;
    const box = document.createElement('div');
    box.className = 'stats-count-box';
    box.dataset.state = state;

    const num = document.createElement('span');
    num.className = 'stats-count-number';
    num.textContent = String(count);

    const label = document.createElement('span');
    label.className = 'stats-count-label';
    label.textContent = state.replace(/_/g, ' ');

    box.appendChild(num);
    box.appendChild(label);
    countsGrid.appendChild(box);
  }

  if (orderedStates.length === 0 && otherStates.length === 0) {
    const empty = document.createElement('p');
    empty.className = 'task-meta';
    empty.textContent = 'No tasks yet.';
    countsGrid.appendChild(empty);
  }

  taskSection.appendChild(countsGrid);
  panel.appendChild(taskSection);

  // ── Execution Health ───────────────────────────────────────────────────────
  const execSection = document.createElement('div');
  execSection.className = 'stats-section';

  const execHeading = document.createElement('h2');
  execHeading.textContent = 'Executions (Last 24h)';
  execSection.appendChild(execHeading);

  const kpisRow = document.createElement('div');
  kpisRow.className = 'stats-kpis';

  const kpis = [
    { label: 'Total Runs', value: String(execStats.total) },
    { label: 'Success Rate', value: execStats.total > 0 ? `${Math.round(execStats.successRate * 100)}%` : '—' },
    { label: 'Total Cost', value: execStats.totalCostUSD > 0 ? `$${execStats.totalCostUSD.toFixed(2)}` : '$0.00' },
    { label: 'Avg Duration', value: formatDurationMs(execStats.avgDurationMs) },
  ];

  for (const kpi of kpis) {
    const box = document.createElement('div');
    box.className = 'stats-kpi-box';

    const val = document.createElement('span');
    val.className = 'stats-kpi-value';
    val.textContent = kpi.value;

    const lbl = document.createElement('span');
    lbl.className = 'stats-kpi-label';
    lbl.textContent = kpi.label;

    box.appendChild(val);
    box.appendChild(lbl);
    kpisRow.appendChild(box);
  }
  execSection.appendChild(kpisRow);

  // Bar chart of outcome distribution.
  if (execStats.total > 0) {
    const chartSection = document.createElement('div');
    chartSection.className = 'stats-bar-chart';

    const chartLabel = document.createElement('p');
    chartLabel.className = 'stats-bar-chart-label';
    chartLabel.textContent = 'Outcome breakdown';
    chartSection.appendChild(chartLabel);

    const bars = document.createElement('div');
    bars.className = 'stats-bars';

    for (const [outcome, count] of Object.entries(execStats.byOutcome)) {
      const pct = (count / execStats.total) * 100;
      const row = document.createElement('div');
      row.className = 'stats-bar-row';

      const barLabel = document.createElement('span');
      barLabel.className = 'stats-bar-row-label';
      barLabel.textContent = outcome.replace(/_/g, ' ');

      const barTrack = document.createElement('div');
      barTrack.className = 'stats-bar-track';

      const barFill = document.createElement('div');
      barFill.className = 'stats-bar-fill';
      barFill.dataset.state = outcome.toUpperCase();
      barFill.style.width = `${pct.toFixed(1)}%`;

      const barCount = document.createElement('span');
      barCount.className = 'stats-bar-count';
      barCount.textContent = `${count} (${Math.round(pct)}%)`;

      barTrack.appendChild(barFill);
      row.appendChild(barLabel);
      row.appendChild(barTrack);
      row.appendChild(barCount);
      bars.appendChild(row);
    }

    chartSection.appendChild(bars);
    execSection.appendChild(chartSection);
  }

  // ── Per-execution detail table ─────────────────────────────────────────────
  if (executions.length > 0) {
    const tableWrap = document.createElement('div');
    tableWrap.className = 'stats-exec-table-wrap';

    const tableLabel = document.createElement('p');
    tableLabel.className = 'stats-bar-chart-label';
    tableLabel.textContent = 'Recent runs';
    tableWrap.appendChild(tableLabel);

    const table = document.createElement('table');
    table.className = 'stats-exec-table';
    table.innerHTML = '<thead><tr><th>Task</th><th>Outcome</th><th>Cost</th><th>Duration</th><th>Started</th></tr></thead>';
    const tbody = document.createElement('tbody');
    for (const ex of executions.slice(0, 20)) {
      const tr = document.createElement('tr');
      const durationMs = ex.duration_ms != null ? formatDurationMs(ex.duration_ms) : '—';
      const cost = ex.cost_usd > 0 ? `$${ex.cost_usd.toFixed(3)}` : '—';
      const started = ex.started_at ? new Date(ex.started_at).toLocaleTimeString() : '—';
      const state = (ex.state || '').toUpperCase();
      tr.innerHTML = `<td class="stats-exec-name">${ex.task_name || ex.task_id}</td><td><span class="state-badge" data-state="${state}">${state.replace(/_/g,' ')}</span></td><td>${cost}</td><td>${durationMs}</td><td>${started}</td>`;
      tbody.appendChild(tr);
    }
    table.appendChild(tbody);
    tableWrap.appendChild(table);
    execSection.appendChild(tableWrap);
  }

  panel.appendChild(execSection);

  // ── Errors ────────────────────────────────────────────────────────────────
  const failures = dashStats.failures || [];
  const errSection = document.createElement('div');
  errSection.className = 'stats-section';

  const errHeading = document.createElement('h2');
  errHeading.textContent = 'Errors (Last 7d)';
  errSection.appendChild(errHeading);

  if (failures.length === 0) {
    const none = document.createElement('p');
    none.className = 'task-meta';
    none.textContent = 'No failures in the last 7 days.';
    errSection.appendChild(none);
  } else {
    // Category summary bar
    const cats = {};
    for (const f of failures) cats[f.category] = (cats[f.category] || 0) + 1;
    const catOrder = ['quota', 'rate_limit', 'timeout', 'git', 'failed'];
    const catLabels = { quota: 'Quota', rate_limit: 'Rate limit', timeout: 'Timeout', git: 'Git', failed: 'Failed' };
    const catColors = { quota: 'var(--state-budget-exceeded)', rate_limit: 'var(--state-failed)', timeout: 'var(--state-timed-out)', git: 'var(--state-cancelled)', failed: 'var(--state-failed)' };

    const catRow = document.createElement('div');
    catRow.className = 'stats-kpis';
    const allCats = [...catOrder, ...Object.keys(cats).filter(c => !catOrder.includes(c))];
    for (const cat of allCats) {
      if (!cats[cat]) continue;
      const box = document.createElement('div');
      box.className = 'stats-kpi-box stats-err-cat';
      box.style.setProperty('--cat-color', catColors[cat] || 'var(--state-failed)');
      const val = document.createElement('span');
      val.className = 'stats-kpi-value';
      val.textContent = String(cats[cat]);
      const lbl = document.createElement('span');
      lbl.className = 'stats-kpi-label';
      lbl.textContent = catLabels[cat] || cat;
      box.appendChild(val);
      box.appendChild(lbl);
      catRow.appendChild(box);
    }
    errSection.appendChild(catRow);

    // Failure table
    const errTable = document.createElement('table');
    errTable.className = 'stats-exec-table';
    errTable.style.marginTop = '0.75rem';
    errTable.innerHTML = '<thead><tr><th>Task</th><th>Category</th><th>Error</th><th>Time</th></tr></thead>';
    const errTbody = document.createElement('tbody');
    for (const f of failures.slice(0, 25)) {
      const tr = document.createElement('tr');
      const ts = new Date(f.started_at).toLocaleString();
      const short = f.error_msg.length > 80 ? f.error_msg.slice(0, 80) + '…' : f.error_msg;
      const catColor = catColors[f.category] || 'var(--state-failed)';
      tr.innerHTML = `<td class="stats-exec-name">${f.task_name}</td><td><span class="stats-err-badge" style="background:${catColor}">${catLabels[f.category] || f.category}</span></td><td class="stats-err-msg" title="${f.error_msg.replace(/"/g,'&quot;')}">${short}</td><td style="white-space:nowrap">${ts}</td>`;
      errTbody.appendChild(tr);
    }
    errTable.appendChild(errTbody);
    errSection.appendChild(errTable);
  }

  panel.appendChild(errSection);

  // ── Throughput ────────────────────────────────────────────────────────────
  const throughput = dashStats.throughput || [];
  const tpSection = document.createElement('div');
  tpSection.className = 'stats-section';

  const tpHeading = document.createElement('h2');
  tpHeading.textContent = 'Throughput (Last 7d)';
  tpSection.appendChild(tpHeading);

  if (throughput.length === 0) {
    const none = document.createElement('p');
    none.className = 'task-meta';
    none.textContent = 'No execution data yet.';
    tpSection.appendChild(none);
  } else {
    const maxTotal = Math.max(...throughput.map(b => b.completed + b.failed + b.other), 1);
    const chart = document.createElement('div');
    chart.className = 'stats-tp-chart';

    for (const bucket of throughput) {
      const total = bucket.completed + bucket.failed + bucket.other;
      const col = document.createElement('div');
      col.className = 'stats-tp-col';
      const heightPct = (total / maxTotal) * 100;
      const label = new Date(bucket.hour).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit' });
      col.title = `${label}\n✓ ${bucket.completed}  ✗ ${bucket.failed}  ○ ${bucket.other}`;

      if (total > 0) {
        const bar = document.createElement('div');
        bar.className = 'stats-tp-bar';
        bar.style.height = `${heightPct.toFixed(1)}%`;

        const cPct = (bucket.completed / total) * 100;
        const fPct = (bucket.failed / total) * 100;
        const oPct = 100 - cPct - fPct;

        bar.style.background = `linear-gradient(to top,
          var(--state-failed) 0% ${fPct.toFixed(1)}%,
          var(--state-timed-out) ${fPct.toFixed(1)}% ${(fPct+oPct).toFixed(1)}%,
          var(--state-completed) ${(fPct+oPct).toFixed(1)}% 100%)`;

        col.appendChild(bar);
      }

      chart.appendChild(col);
    }
    tpSection.appendChild(chart);

    const tpLegend = document.createElement('div');
    tpLegend.className = 'stats-tp-legend';
    tpLegend.innerHTML = `
      <span class="stats-tp-legend-item"><span class="stats-tp-swatch" style="background:var(--state-completed)"></span>Completed</span>
      <span class="stats-tp-legend-item"><span class="stats-tp-swatch" style="background:var(--state-failed)"></span>Failed</span>
      <span class="stats-tp-legend-item"><span class="stats-tp-swatch" style="background:var(--state-timed-out)"></span>Other</span>
    `;
    tpSection.appendChild(tpLegend);
  }

  panel.appendChild(tpSection);

  // ── Billing ───────────────────────────────────────────────────────────────
  const billing = dashStats.billing || [];
  const billSection = document.createElement('div');
  billSection.className = 'stats-section';

  const billHeading = document.createElement('h2');
  billHeading.textContent = 'Cost (Last 7d)';
  billSection.appendChild(billHeading);

  if (billing.length === 0) {
    const none = document.createElement('p');
    none.className = 'task-meta';
    none.textContent = 'No cost data yet.';
    billSection.appendChild(none);
  } else {
    const totalCost = billing.reduce((s, d) => s + d.cost_usd, 0);
    const totalRuns = billing.reduce((s, d) => s + d.runs, 0);

    const billKpis = document.createElement('div');
    billKpis.className = 'stats-kpis';
    for (const kpi of [
      { label: '7d Total', value: `$${totalCost.toFixed(2)}` },
      { label: 'Avg/Day', value: billing.length > 0 ? `$${(totalCost / billing.length).toFixed(2)}` : '—' },
      { label: 'Cost/Run', value: totalRuns > 0 ? `$${(totalCost / totalRuns).toFixed(3)}` : '—' },
      { label: 'Total Runs', value: String(totalRuns) },
    ]) {
      const box = document.createElement('div');
      box.className = 'stats-kpi-box';
      const val = document.createElement('span');
      val.className = 'stats-kpi-value';
      val.textContent = kpi.value;
      const lbl = document.createElement('span');
      lbl.className = 'stats-kpi-label';
      lbl.textContent = kpi.label;
      box.appendChild(val);
      box.appendChild(lbl);
      billKpis.appendChild(box);
    }
    billSection.appendChild(billKpis);

    // Daily cost bar chart
    const maxCost = Math.max(...billing.map(d => d.cost_usd), 0.001);
    const billChart = document.createElement('div');
    billChart.className = 'stats-bill-chart';

    for (const day of billing) {
      const col = document.createElement('div');
      col.className = 'stats-bill-col';
      col.title = `${day.day}\n$${day.cost_usd.toFixed(3)}  (${day.runs} runs)`;

      const bar = document.createElement('div');
      bar.className = 'stats-bill-bar';
      bar.style.height = `${((day.cost_usd / maxCost) * 100).toFixed(1)}%`;

      const dayLabel = document.createElement('span');
      dayLabel.className = 'stats-bill-day-label';
      const d = new Date(day.day + 'T12:00:00Z');
      dayLabel.textContent = d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });

      col.appendChild(bar);
      col.appendChild(dayLabel);
      billChart.appendChild(col);
    }
    billSection.appendChild(billChart);
  }

  panel.appendChild(billSection);

  // ── Agent Status ───────────────────────────────────────────────────────────
  const agentSection = document.createElement('div');
  agentSection.className = 'stats-section';

  const agentHeading = document.createElement('h2');
  agentHeading.textContent = 'Agent Status';
  agentSection.appendChild(agentHeading);

  const agents = agentData.agents || [];
  const agentEvents = agentData.events || [];

  if (agents.length === 0) {
    const none = document.createElement('p');
    none.className = 'task-meta';
    none.textContent = 'No agents registered.';
    agentSection.appendChild(none);
  } else {
    // Status cards row
    const cardsRow = document.createElement('div');
    cardsRow.className = 'stats-agent-cards';
    for (const ag of agents) {
      const card = document.createElement('div');
      card.className = 'stats-agent-card';
      const statusClass = ag.drained ? 'agent-drained' : ag.rate_limited ? 'agent-rate-limited' : 'agent-available';
      card.classList.add(statusClass);

      const nameEl = document.createElement('span');
      nameEl.className = 'stats-agent-name';
      nameEl.textContent = ag.agent;

      const statusEl = document.createElement('span');
      statusEl.className = 'stats-agent-status';
      if (ag.drained) {
        statusEl.textContent = 'Drain locked — needs manual undrain';
      } else if (ag.rate_limited && ag.until) {
        const untilDate = new Date(ag.until);
        const minsLeft = Math.max(0, Math.round((untilDate - Date.now()) / 60000));
        statusEl.textContent = `Rate limited — ${minsLeft}m remaining`;
      } else {
        statusEl.textContent = ag.active_tasks > 0 ? `Active (${ag.active_tasks} running)` : 'Available';
      }

      card.appendChild(nameEl);
      card.appendChild(statusEl);
      cardsRow.appendChild(card);
    }
    agentSection.appendChild(cardsRow);

    // Availability timeline (last 24h)
    const now = Date.now();
    const windowMs = 24 * 60 * 60 * 1000;
    const windowStart = now - windowMs;

    const timelineHeading = document.createElement('p');
    timelineHeading.className = 'stats-bar-chart-label';
    timelineHeading.textContent = 'Availability last 24h';
    agentSection.appendChild(timelineHeading);

    // Group events by agent
    const eventsByAgent = {};
    for (const ev of agentEvents) {
      if (!eventsByAgent[ev.agent]) eventsByAgent[ev.agent] = [];
      eventsByAgent[ev.agent].push(ev);
    }

    for (const ag of agents) {
      const evs = (eventsByAgent[ag.agent] || []).slice().sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

      const row = document.createElement('div');
      row.className = 'stats-timeline-row';

      const label = document.createElement('span');
      label.className = 'stats-timeline-label';
      label.textContent = ag.agent;
      row.appendChild(label);

      const track = document.createElement('div');
      track.className = 'stats-timeline-track';

      // Build segments: walk events and produce [start, end, state] intervals
      const segments = [];
      let cursor = windowStart;
      // Reconstruct: before first event, assume available unless currently rate-limited with an until before window
      let inRateLimit = false;

      for (const ev of evs) {
        const evTime = Math.max(windowStart, new Date(ev.timestamp).getTime());
        if (evTime > cursor) {
          segments.push({ start: cursor, end: evTime, limited: inRateLimit });
        }
        cursor = evTime;
        if (ev.event === 'rate_limited') {
          inRateLimit = true;
        } else if (ev.event === 'available') {
          inRateLimit = false;
        }
      }
      // Tail to now
      if (cursor < now) {
        // If currently rate limited use current agent state
        segments.push({ start: cursor, end: now, limited: ag.rate_limited || inRateLimit });
      }

      for (const seg of segments) {
        const pct = ((seg.end - seg.start) / windowMs) * 100;
        if (pct < 0.01) continue;
        const span = document.createElement('div');
        span.className = 'stats-timeline-seg';
        span.classList.add(seg.limited ? 'seg-limited' : 'seg-available');
        span.style.width = `${pct.toFixed(2)}%`;
        const mins = Math.round((seg.end - seg.start) / 60000);
        span.title = `${seg.limited ? 'Rate limited' : 'Available'} — ${mins}m`;
        track.appendChild(span);
      }

      row.appendChild(track);

      // Legend labels
      const timeLabels = document.createElement('div');
      timeLabels.className = 'stats-timeline-timelabels';
      timeLabels.innerHTML = '<span>24h ago</span><span>now</span>';
      row.appendChild(timeLabels);

      agentSection.appendChild(row);
    }

    // Rate-limit event log
    if (agentEvents.length > 0) {
      const evLogLabel = document.createElement('p');
      evLogLabel.className = 'stats-bar-chart-label';
      evLogLabel.textContent = 'Rate-limit events (last 24h)';
      agentSection.appendChild(evLogLabel);

      const evTable = document.createElement('table');
      evTable.className = 'stats-exec-table';
      evTable.innerHTML = '<thead><tr><th>Agent</th><th>Event</th><th>Reason</th><th>Until</th><th>Time</th></tr></thead>';
      const evTbody = document.createElement('tbody');
      for (const ev of agentEvents.slice(0, 30)) {
        const tr = document.createElement('tr');
        const until = ev.until ? new Date(ev.until).toLocaleTimeString() : '—';
        const ts = new Date(ev.timestamp).toLocaleTimeString();
        const eventClass = ev.event === 'rate_limited' ? 'state-badge" data-state="FAILED' : 'state-badge" data-state="COMPLETED';
        tr.innerHTML = `<td>${ev.agent}</td><td><span class="${eventClass}">${ev.event.replace(/_/g,' ')}</span></td><td>${ev.reason || '—'}</td><td>${until}</td><td>${ts}</td>`;
        evTbody.appendChild(tr);
      }
      evTable.appendChild(evTbody);
      agentSection.appendChild(evTable);
    }
  }

  panel.appendChild(agentSection);
}

// ── Web Push Notifications ────────────────────────────────────────────────────

async function registerServiceWorker() {
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) return null;
  return navigator.serviceWorker.register(BASE_PATH + '/api/push/sw.js', { scope: BASE_PATH + '/' });
}

function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = window.atob(base64);
  return Uint8Array.from([...rawData].map(c => c.charCodeAt(0)));
}

async function enableNotifications(btn) {
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
    alert('Push notifications are not supported in this browser.');
    return;
  }
  try {
    const permission = await Notification.requestPermission();
    if (permission !== 'granted') {
      alert('Notification permission denied.');
      return;
    }

    // Fetch VAPID public key.
    const keyRes = await fetch(`${API_BASE}/api/push/vapid-key`);
    if (!keyRes.ok) throw new Error(`Failed to get VAPID key: HTTP ${keyRes.status}`);
    const { public_key: vapidKey } = await keyRes.json();

    // Register service worker and wait for it to become active.
    await registerServiceWorker();
    const registration = await navigator.serviceWorker.ready;

    // Unsubscribe any stale subscription (e.g. from a VAPID key rotation).
    // PushManager.subscribe() throws "applicationServerKey is not valid" if the
    // existing subscription was created with a different key.
    const existingSub = await registration.pushManager.getSubscription();
    if (existingSub) {
      await existingSub.unsubscribe();
    }

    // Subscribe via PushManager.
    const subscription = await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: urlBase64ToUint8Array(vapidKey),
    });

    const subJSON = subscription.toJSON();
    // POST subscription to server.
    const res = await fetch(`${API_BASE}/api/push/subscribe`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        endpoint: subJSON.endpoint,
        keys: { p256dh: subJSON.keys.p256dh, auth: subJSON.keys.auth },
      }),
    });
    if (!res.ok) throw new Error(`Subscribe failed: HTTP ${res.status}`);

    if (btn) {
      btn.textContent = '🔔';
      btn.disabled = true;
    }
  } catch (err) {
    alert(`Notification setup failed: ${err.message}`);
  }
}

// ── File Drops ─────────────────────────────────────────────────────────────────

async function fetchDrops() {
  const res = await fetch(`${API_BASE}/api/drops`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// ── Drops panel ───────────────────────────────────────────────────────────────

async function renderDropsPanel() {
  const panel = document.querySelector('[data-panel="drops"] .drops-panel');
  if (!panel) return;
  panel.innerHTML = '<p class="task-meta">Loading drops…</p>';

  try {
    const files = await fetchDrops();
    panel.innerHTML = '';

    const heading = document.createElement('h3');
    heading.style.padding = '1rem 1rem 0.5rem';
    heading.textContent = 'Dropped Files';
    panel.appendChild(heading);

    if (files.length === 0) {
      const empty = document.createElement('p');
      empty.className = 'task-meta';
      empty.style.padding = '0 1rem';
      empty.textContent = 'No files dropped yet. Agents can write files to the drops directory to share them here.';
      panel.appendChild(empty);
    } else {
      const list = document.createElement('ul');
      list.style.cssText = 'list-style:none;padding:0 1rem;margin:0';
      for (const f of files) {
        const li = document.createElement('li');
        li.style.cssText = 'padding:0.5rem 0;border-bottom:1px solid var(--border,#e5e7eb)';
        const a = document.createElement('a');
        a.href = `${API_BASE}/api/drops/${encodeURIComponent(f.name)}`;
        a.textContent = f.name;
        a.download = f.name;
        a.style.cssText = 'color:var(--accent,#2563eb);text-decoration:none';
        const meta = document.createElement('span');
        meta.className = 'task-meta';
        meta.style.cssText = 'margin-left:1rem';
        meta.textContent = `${(f.size / 1024).toFixed(1)} KB`;
        li.append(a, meta);
        list.appendChild(li);
      }
      panel.appendChild(list);
    }
  } catch (err) {
    panel.innerHTML = `<p class="task-meta" style="padding:1rem">Failed to load drops: ${err.message}</p>`;
  }
}

// ── Stories tab: data fetch ──────────────────────────────────────────────────
// Phase 9a: consumes the existing, unchanged epics/stories REST surface
// (internal/api/stories.go, internal/api/epics.go) — no backend changes.

async function fetchStories(fetchImpl = fetch) {
  const res = await fetchImpl(`${API_BASE}/api/stories`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

async function fetchEpics(fetchImpl = fetch) {
  const res = await fetchImpl(`${API_BASE}/api/epics`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

async function fetchEpic(epicId, fetchImpl = fetch) {
  const res = await fetchImpl(`${API_BASE}/api/epics/${epicId}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

async function fetchStory(id, fetchImpl = fetch) {
  const res = await fetchImpl(`${API_BASE}/api/stories/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// fetchStoryEvents loads a story's event stream. Mirrors fetchTaskEvents:
// returns [] on any error so the board/modal degrade gracefully rather than
// throwing.
export async function fetchStoryEvents(storyId, fetchImpl = (typeof fetch !== 'undefined' ? fetch : null)) {
  if (!fetchImpl) return [];
  try {
    const resp = await fetchImpl(`${API_BASE}/api/stories/${storyId}/events`);
    if (!resp.ok) return [];
    const data = await resp.json();
    return Array.isArray(data) ? data : [];
  } catch {
    return [];
  }
}

async function fetchStoryTaskTree(storyId, fetchImpl = fetch) {
  const res = await fetchImpl(`${API_BASE}/api/stories/${storyId}/task-tree`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// updateStory issues a partial PUT — handleUpdateStory (internal/api/stories.go)
// decodes the request body onto the already-fetched existing row, so fields
// omitted from `body` are left untouched. Used here to write only `priority`
// on drag-and-drop reorder without clobbering the rest of the story.
async function updateStory(id, body) {
  const res = await fetch(`${API_BASE}/api/stories/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const b = await res.json(); msg = b.error || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

async function acceptStory(id) {
  const res = await fetch(`${API_BASE}/api/stories/${id}/accept`, { method: 'POST' });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try { const b = await res.json(); msg = b.error || msg; } catch {}
    throw new Error(msg);
  }
  return res.json();
}

// ── Stories tab: board/column model (pure — unit-tested in web/test) ───────
//
// Columns collapse the full story.Status lifecycle (DISCOVERY|FRAMING|
// BACKLOG|PRIORITIZED|IN_PROGRESS|SHIPPABLE|DEPLOYED|VALIDATING|
// REVIEW_READY|NEEDS_FIX|DONE|CANCELLED — internal/story/story.go) into 7
// columns. SHIPPABLE/DEPLOYED fold into "In Progress" (deploy-gating isn't
// built yet, so there's nothing actionable to show separately for them);
// VALIDATING/REVIEW_READY fold into one "Validating" column; NEEDS_FIX/
// CANCELLED get their own small side column rather than a hidden filter
// toggle, per the phase's "your judgment" call, so a story that needs
// attention is never one click away from invisible.
export const STORY_COLUMNS = [
  { key: 'discovery',   label: 'Discovery',    statuses: ['DISCOVERY', 'FRAMING'] },
  { key: 'backlog',     label: 'Backlog',      statuses: ['BACKLOG'] },
  { key: 'prioritized', label: 'Prioritized',  statuses: ['PRIORITIZED'] },
  { key: 'in_progress', label: 'In Progress',  statuses: ['IN_PROGRESS', 'SHIPPABLE', 'DEPLOYED'] },
  { key: 'validating',  label: 'Validating',   statuses: ['VALIDATING', 'REVIEW_READY'] },
  { key: 'done',        label: 'Done',         statuses: ['DONE'] },
  { key: 'issues',      label: 'Needs Fix / Cancelled', statuses: ['NEEDS_FIX', 'CANCELLED'] },
];

// columnForStatus returns the column key for a given story status, falling
// back to 'backlog' for an empty/unrecognized status so a story is never
// dropped off the board entirely.
export function columnForStatus(status) {
  const col = STORY_COLUMNS.find(c => c.statuses.includes(status));
  return col ? col.key : 'backlog';
}

function priorityRank(p) {
  // Number('') === 0 and Number(null) === 0, so both would otherwise sort
  // as the highest priority — treat "no priority set" as missing, not zero.
  if (p === null || p === undefined || p === '') return Number.POSITIVE_INFINITY;
  const n = Number(p);
  return Number.isFinite(n) ? n : Number.POSITIVE_INFINITY;
}

// storyPriorityComparator sorts ascending by numeric priority (this phase's
// convention: drag-and-drop reorder writes the story's rank as a stringified
// integer — story.Priority is a freeform string with no enum, so there's no
// existing convention to collide with). Non-numeric/missing priority sorts
// last; ties break by created_at ascending (oldest first).
export function storyPriorityComparator(a, b) {
  const ra = priorityRank(a.priority);
  const rb = priorityRank(b.priority);
  if (ra !== rb) return ra - rb;
  return new Date(a.created_at || 0) - new Date(b.created_at || 0);
}

// groupStoriesByColumn returns { [columnKey]: story[] }, each sub-array
// sorted by storyPriorityComparator.
export function groupStoriesByColumn(stories) {
  const groups = {};
  for (const col of STORY_COLUMNS) groups[col.key] = [];
  for (const s of stories || []) {
    const key = columnForStatus(s.status);
    if (!groups[key]) groups[key] = [];
    groups[key].push(s);
  }
  for (const key of Object.keys(groups)) {
    groups[key].sort(storyPriorityComparator);
  }
  return groups;
}

// ---------------------------------------------------------------------------
// Tasks board — column model
// ---------------------------------------------------------------------------

export const TASK_COLUMNS = [
  { key: 'queue',       label: 'Queue',       states: ['PENDING', 'QUEUED'] },
  { key: 'running',     label: 'Running',     states: ['RUNNING', 'BLOCKED'] },
  { key: 'ready',       label: 'Ready',       states: ['READY'] },
  { key: 'interrupted', label: 'Interrupted', states: ['FAILED', 'TIMED_OUT', 'CANCELLED', 'BUDGET_EXCEEDED'] },
  { key: 'done',        label: 'Done',        states: ['COMPLETED'] },
];

// columnForTaskState returns the column key for a given task state, falling
// back to 'queue' for an empty/unrecognized state so a task is never dropped
// off the board entirely.
export function columnForTaskState(state) {
  const col = TASK_COLUMNS.find(c => c.states.includes(state));
  return col ? col.key : 'queue';
}

// Sort directions are per-column, matching the semantics the old (removed)
// panels used:
//   queue      — oldest-first (FIFO)
//   ready      — oldest-first (longest-waiting surfaces first)
//   interrupted — newest-first (most recent failure is most urgent)
//   done       — newest-first (most recently completed is most relevant)
//   running    — newest-first (new-but-inconsequential default)
// Tasks with a missing created_at sort LAST in any direction (per sortTasksByDate).
const TASK_COLUMN_DESCEND = {
  queue:       false,
  running:     true,
  ready:       false,
  interrupted: true,
  done:        true,
};

// groupTasksByColumn returns { [columnKey]: task[] }, each sub-array sorted
// per the per-column sort direction above via the shared sortTasksByDate helper.
export function groupTasksByColumn(tasks) {
  const groups = {};
  for (const col of TASK_COLUMNS) groups[col.key] = [];
  for (const t of tasks || []) {
    const key = columnForTaskState(t.state);
    if (!groups[key]) groups[key] = [];
    groups[key].push(t);
  }
  for (const col of TASK_COLUMNS) {
    groups[col.key] = sortTasksByDate(groups[col.key], TASK_COLUMN_DESCEND[col.key] ?? false);
  }
  return groups;
}

// ---------------------------------------------------------------------------

// A story "has reached validation" once evaluator verdicts could plausibly
// exist for it — VALIDATING or later in the lifecycle (see StoryOrchestrator
// stage 2 in CLAUDE.md). Used to gate the eval-verdict indicator so we don't
// fetch/show "Evals: 0/4" for a story that's still in Backlog.
export function storyHasReachedValidation(status) {
  return ['VALIDATING', 'REVIEW_READY', 'NEEDS_FIX', 'DONE', 'CANCELLED'].includes(status);
}

// countEvalVerdicts counts event.KindEvalVerdict entries in a story's event
// stream — up to 4 expected (evaluator_quality/security/correctness/performance).
export function countEvalVerdicts(events) {
  return (events || []).filter(e => e && e.kind === 'eval_verdict').length;
}

// ── Stories tab: rendering state ─────────────────────────────────────────────

// draggingStoryId is set for the duration of an HTML5 drag so column
// dragover handlers can check whether the dragged story's own status maps
// to *this* column (reorder-in-place only — see renderStoriesBoard) and so
// poll() can avoid re-rendering the board out from under an active drag.
let draggingStoryId = null;
// storiesById is refreshed on every renderStoriesPanel() call; column
// dragover/drop handlers and persistColumnOrder consult it instead of
// re-fetching per drag event.
let storiesById = new Map();

function getStoriesViewMode() {
  return localStorage.getItem('storiesViewMode') || 'board';
}
function setStoriesViewMode(mode) {
  localStorage.setItem('storiesViewMode', mode);
}

// ── Stories tab: card ─────────────────────────────────────────────────────────

function createStoryCard(story, { draggable = true } = {}) {
  const card = document.createElement('div');
  card.className = 'story-card';
  card.dataset.storyId = story.id;
  card.draggable = draggable;

  const header = document.createElement('div');
  header.className = 'story-card-header';
  const name = document.createElement('span');
  name.className = 'story-name';
  name.textContent = story.name;
  const badge = document.createElement('span');
  badge.className = 'story-status-badge';
  badge.dataset.status = story.status;
  badge.textContent = (story.status || '').replace(/_/g, ' ');
  header.append(name, badge);
  card.appendChild(header);

  const meta = document.createElement('div');
  meta.className = 'story-meta';
  if (story.priority) {
    const p = document.createElement('span');
    p.textContent = `priority: ${story.priority}`;
    meta.appendChild(p);
  }
  const ac = document.createElement('span');
  ac.textContent = `AC: ${(story.acceptance_criteria || []).length}`;
  meta.appendChild(ac);
  card.appendChild(meta);

  if (storyHasReachedValidation(story.status)) {
    const evalEl = document.createElement('div');
    evalEl.className = 'story-eval-indicator';
    evalEl.textContent = 'Evals: …';
    card.appendChild(evalEl);
    fetchStoryEvents(story.id).then(events => {
      evalEl.textContent = `Evals: ${countEvalVerdicts(events)}/4`;
    });
  }

  card.addEventListener('click', () => openStoryModal(story.id));

  if (draggable) {
    card.addEventListener('dragstart', (e) => {
      draggingStoryId = story.id;
      card.classList.add('dragging');
      e.dataTransfer.setData('text/plain', story.id);
      e.dataTransfer.effectAllowed = 'move';
    });
    card.addEventListener('dragend', () => {
      draggingStoryId = null;
      card.classList.remove('dragging');
      document.querySelectorAll('.stories-column.drag-over').forEach(c => c.classList.remove('drag-over'));
    });
  }

  return card;
}

// getDragAfterElement finds the card the dragged element should be inserted
// before, based on vertical cursor position — standard vanilla-JS
// drag-reorder technique (no library).
function getDragAfterElement(container, y) {
  const els = [...container.querySelectorAll('.story-card:not(.dragging)')];
  return els.reduce((closest, child) => {
    const box = child.getBoundingClientRect();
    const offset = y - box.top - box.height / 2;
    if (offset < 0 && offset > closest.offset) {
      return { offset, element: child };
    }
    return closest;
  }, { offset: Number.NEGATIVE_INFINITY, element: null }).element;
}

// persistColumnOrder re-ranks every card currently in `list` (in DOM order)
// as priority "0", "10", "20", … and PUTs any that actually changed.
// Ranks are only unique within a column, never globally — sorting only ever
// happens within one column's group (groupStoriesByColumn), so cross-column
// rank collisions are harmless.
async function persistColumnOrder(list) {
  const ids = [...list.querySelectorAll('.story-card')].map(c => c.dataset.storyId);
  await Promise.all(ids.map((id, idx) => {
    const story = storiesById.get(id);
    const newPriority = String(idx * 10);
    if (!story || story.priority === newPriority) return Promise.resolve();
    return updateStory(id, { priority: newPriority })
      .then(() => { story.priority = newPriority; })
      .catch(err => console.error('Failed to persist story priority reorder:', err));
  }));
}

// ── Stories tab: Kanban board ─────────────────────────────────────────────────
//
// Drag-and-drop decision (documented per the phase spec's either/or): dragging
// a card to a *different* column is disabled outright rather than allowed-but-
// a-no-op. A column's dragover handler only ever calls preventDefault() when
// the dragged story's own status already maps to that column — so a foreign
// column never shows a reorder preview and the browser's native "not allowed"
// drop-cursor kicks in. The alternative (accept the drop, snap back on next
// poll) would let a card visibly move to the wrong column for several seconds,
// which reads as a bug rather than a deliberate constraint.
function renderStoriesBoard(stories, container) {
  const groups = groupStoriesByColumn(stories);
  container.innerHTML = '';
  const board = document.createElement('div');
  board.className = 'stories-board';

  for (const col of STORY_COLUMNS) {
    const colEl = document.createElement('div');
    colEl.className = 'stories-column';
    colEl.dataset.columnKey = col.key;

    const header = document.createElement('div');
    header.className = 'stories-column-header';
    const title = document.createElement('span');
    title.textContent = col.label;
    const count = document.createElement('span');
    count.className = 'stories-column-count';
    count.textContent = String(groups[col.key].length);
    header.append(title, count);
    colEl.appendChild(header);

    const list = document.createElement('div');
    list.className = 'stories-column-list';
    for (const story of groups[col.key]) {
      list.appendChild(createStoryCard(story));
    }
    colEl.appendChild(list);

    list.addEventListener('dragover', (e) => {
      const dragged = storiesById.get(draggingStoryId);
      if (!dragged || columnForStatus(dragged.status) !== col.key) return;
      e.preventDefault();
      e.dataTransfer.dropEffect = 'move';
      colEl.classList.add('drag-over');
      const draggingEl = list.querySelector('.dragging');
      if (!draggingEl) return;
      const after = getDragAfterElement(list, e.clientY);
      if (after == null) list.appendChild(draggingEl);
      else list.insertBefore(draggingEl, after);
    });
    list.addEventListener('dragleave', (e) => {
      if (!colEl.contains(e.relatedTarget)) colEl.classList.remove('drag-over');
    });
    list.addEventListener('drop', (e) => {
      e.preventDefault();
      colEl.classList.remove('drag-over');
      persistColumnOrder(list);
    });

    board.appendChild(colEl);
  }

  container.appendChild(board);
}

// ── Stories tab: epic swimlanes ───────────────────────────────────────────────

function renderSwimlane(lane) {
  const laneEl = document.createElement('div');
  laneEl.className = 'epic-swimlane';

  const header = document.createElement('div');
  header.className = 'epic-swimlane-header';

  const name = document.createElement('span');
  name.className = 'epic-swimlane-name';
  name.textContent = lane.name;
  header.appendChild(name);

  const total = lane.stories.length;
  const done = lane.stories.filter(s => s.status === 'DONE').length;

  const progressWrap = document.createElement('div');
  progressWrap.className = 'epic-progress';
  const track = document.createElement('div');
  track.className = 'epic-progress-track';
  const fill = document.createElement('div');
  fill.className = 'epic-progress-fill';
  fill.style.width = total > 0 ? `${Math.round((done / total) * 100)}%` : '0%';
  track.appendChild(fill);
  const label = document.createElement('span');
  label.className = 'epic-progress-label';
  label.textContent = `${done}/${total} done`;
  progressWrap.append(track, label);
  header.appendChild(progressWrap);

  laneEl.appendChild(header);

  const row = document.createElement('div');
  row.className = 'epic-swimlane-stories';
  if (lane.stories.length === 0) {
    const empty = document.createElement('span');
    empty.className = 'task-meta';
    empty.textContent = 'No stories.';
    row.appendChild(empty);
  } else {
    for (const s of lane.stories.slice().sort(storyPriorityComparator)) {
      row.appendChild(createStoryCard(s, { draggable: false }));
    }
  }
  laneEl.appendChild(row);

  return laneEl;
}

async function renderEpicSwimlanes(stories, container) {
  container.innerHTML = '<p class="task-meta">Loading epics…</p>';
  let epics;
  try {
    epics = await fetchEpics();
  } catch (err) {
    container.innerHTML = `<p class="task-meta" style="padding:1rem">Failed to load epics: ${err.message}</p>`;
    return;
  }

  const byEpic = new Map();
  const unassigned = [];
  for (const s of stories) {
    if (s.epic_id) {
      if (!byEpic.has(s.epic_id)) byEpic.set(s.epic_id, []);
      byEpic.get(s.epic_id).push(s);
    } else {
      unassigned.push(s);
    }
  }

  const lanes = epics.map(e => ({ id: e.id, name: e.name, stories: byEpic.get(e.id) || [] }));
  if (unassigned.length > 0 || lanes.length === 0) {
    lanes.push({ id: '', name: 'Unassigned', stories: unassigned });
  }

  container.innerHTML = '';
  const wrap = document.createElement('div');
  wrap.className = 'epic-swimlanes';
  if (lanes.length === 0) {
    wrap.innerHTML = '<p class="task-meta">No epics or stories yet.</p>';
  } else {
    for (const lane of lanes) wrap.appendChild(renderSwimlane(lane));
  }
  container.appendChild(wrap);
}

// ── Stories tab: panel entry point ───────────────────────────────────────────

async function renderStoriesPanel() {
  const panel = document.querySelector('[data-panel="stories"]');
  if (!panel) return;
  const container = panel.querySelector('.stories-view-container');
  if (!container) return;

  const mode = getStoriesViewMode();
  panel.querySelectorAll('.view-toggle-btn').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.view === mode);
  });

  let stories;
  try {
    stories = await fetchStories();
  } catch (err) {
    container.innerHTML = `<p class="task-meta" style="padding:1rem">Failed to load stories: ${err.message}</p>`;
    return;
  }

  storiesById = new Map(stories.map(s => [s.id, s]));

  if (mode === 'epics') {
    await renderEpicSwimlanes(stories, container);
  } else {
    renderStoriesBoard(stories, container);
  }
}

// ── Story task-tree DAG ──────────────────────────────────────────────────────
// Plain SVG + vanilla JS, no graph-layout library: a simple layered
// top-to-bottom layout, rows assigned by BFS depth from root_task_id
// following both "spawned" (parent_task_id) and "depends on" (depends_on)
// edges — the same two edge types GET /api/stories/{id}/task-tree itself
// walks server-side (ListSubtasks/ListDependents) to build the flat node
// list this renders.

// computeTaskTreeDepths returns Map<nodeId, depth>. Defensive fallbacks:
// an unresolvable root, or a node genuinely unreachable from it (shouldn't
// happen given how the API built the list, but a cycle or a stale
// parent_task_id could in principle produce one), still get a depth so
// nothing silently vanishes from the layout.
export function computeTaskTreeDepths(nodes, rootId) {
  const byId = new Map(nodes.map(n => [n.id, n]));
  const childrenOf = new Map();
  const addEdge = (fromId, toId) => {
    if (!childrenOf.has(fromId)) childrenOf.set(fromId, []);
    childrenOf.get(fromId).push(toId);
  };
  for (const n of nodes) {
    if (n.parent_task_id && byId.has(n.parent_task_id)) addEdge(n.parent_task_id, n.id);
    for (const dep of n.depends_on || []) {
      if (byId.has(dep)) addEdge(dep, n.id);
    }
  }

  const depths = new Map();
  if (!byId.has(rootId)) {
    for (const n of nodes) depths.set(n.id, 0);
    return depths;
  }

  depths.set(rootId, 0);
  const queue = [rootId];
  while (queue.length > 0) {
    const id = queue.shift();
    const depth = depths.get(id);
    for (const childId of childrenOf.get(id) || []) {
      if (!depths.has(childId)) {
        depths.set(childId, depth + 1);
        queue.push(childId);
      }
    }
  }
  let maxDepth = 0;
  for (const d of depths.values()) maxDepth = Math.max(maxDepth, d);
  for (const n of nodes) {
    if (!depths.has(n.id)) depths.set(n.id, maxDepth + 1);
  }
  return depths;
}

const DAG_NODE_WIDTH = 160;
const DAG_NODE_HEIGHT = 44;
const DAG_COL_GAP = 24;
const DAG_ROW_GAP = 48;

// layoutTaskTree assigns each node an {x, y} top-left position: rows by BFS
// depth (top-to-bottom), columns by original node order within a row.
export function layoutTaskTree(nodes, rootId) {
  const depths = computeTaskTreeDepths(nodes, rootId);
  const byDepth = new Map();
  for (const n of nodes) {
    const d = depths.get(n.id) || 0;
    if (!byDepth.has(d)) byDepth.set(d, []);
    byDepth.get(d).push(n);
  }
  const depthKeys = [...byDepth.keys()];
  const maxDepth = depthKeys.length > 0 ? Math.max(...depthKeys) : 0;

  const positions = new Map();
  for (let d = 0; d <= maxDepth; d++) {
    const row = byDepth.get(d) || [];
    row.forEach((n, i) => {
      positions.set(n.id, {
        x: i * (DAG_NODE_WIDTH + DAG_COL_GAP),
        y: d * (DAG_NODE_HEIGHT + DAG_ROW_GAP),
      });
    });
  }
  const rowLengths = [...byDepth.values()].map(r => r.length);
  const maxCols = rowLengths.length > 0 ? Math.max(...rowLengths) : 1;
  return {
    positions,
    width: Math.max(DAG_NODE_WIDTH, maxCols * (DAG_NODE_WIDTH + DAG_COL_GAP) - DAG_COL_GAP),
    height: (maxDepth + 1) * (DAG_NODE_HEIGHT + DAG_ROW_GAP) - DAG_ROW_GAP,
  };
}

const SVG_NS = 'http://www.w3.org/2000/svg';

const DAG_LEGEND_STATES = [
  'PENDING', 'QUEUED', 'RUNNING', 'READY', 'BLOCKED',
  'COMPLETED', 'FAILED', 'TIMED_OUT', 'CANCELLED', 'BUDGET_EXCEEDED',
];

function renderDagLegend() {
  const wrap = document.createElement('div');

  const stateLegend = document.createElement('div');
  stateLegend.className = 'dag-legend';
  for (const state of DAG_LEGEND_STATES) {
    const item = document.createElement('span');
    item.className = 'dag-legend-item';
    const swatch = document.createElement('span');
    swatch.className = 'dag-legend-swatch';
    swatch.dataset.state = state;
    const label = document.createElement('span');
    label.textContent = state.replace(/_/g, ' ');
    item.append(swatch, label);
    stateLegend.appendChild(item);
  }
  wrap.appendChild(stateLegend);

  const edgeLegend = document.createElement('div');
  edgeLegend.className = 'dag-edge-legend';
  const parentItem = document.createElement('span');
  const parentSwatch = document.createElement('span');
  parentSwatch.className = 'dag-edge-legend-swatch';
  parentItem.append(parentSwatch, document.createTextNode('spawned (parent → child)'));
  const dependsItem = document.createElement('span');
  const dependsSwatch = document.createElement('span');
  dependsSwatch.className = 'dag-edge-legend-swatch dag-edge-legend-swatch--depends';
  dependsItem.append(dependsSwatch, document.createTextNode('depends on'));
  edgeLegend.append(parentItem, dependsItem);
  wrap.appendChild(edgeLegend);

  return wrap;
}

function drawDagEdge(g, from, to, kind) {
  const line = document.createElementNS(SVG_NS, 'line');
  line.setAttribute('x1', from.x);
  line.setAttribute('y1', from.y);
  line.setAttribute('x2', to.x);
  line.setAttribute('y2', to.y);
  line.setAttribute('class', `dag-edge dag-edge--${kind}`);
  line.setAttribute('marker-end', 'url(#dag-arrow)');
  g.appendChild(line);
}

function renderDagNode(node, pos, pad) {
  const g = document.createElementNS(SVG_NS, 'g');
  g.setAttribute('class', 'dag-node');
  g.setAttribute('transform', `translate(${pos.x + pad}, ${pos.y + pad})`);

  const rect = document.createElementNS(SVG_NS, 'rect');
  rect.setAttribute('width', DAG_NODE_WIDTH);
  rect.setAttribute('height', DAG_NODE_HEIGHT);
  rect.setAttribute('rx', 6);
  rect.setAttribute('class', 'dag-node-rect');
  rect.dataset.state = node.state;
  g.appendChild(rect);

  const title = document.createElementNS(SVG_NS, 'title');
  title.textContent = `${node.name}\nState: ${node.state}${node.role ? `\nRole: ${node.role}` : ''}`;
  g.appendChild(title);

  const nameText = document.createElementNS(SVG_NS, 'text');
  nameText.setAttribute('x', 8);
  nameText.setAttribute('y', 18);
  nameText.setAttribute('class', 'dag-node-name');
  // Full text for now — fitDagNodeLabels (run once every node is attached to
  // the live document) measures and truncates with an ellipsis, since a
  // single long word (e.g. a role name) has no word-boundary to truncate at
  // and a fixed character count either clips it anyway or wastes space on
  // shorter names. "Measure first" per the dataviz guidance, not guess.
  nameText.textContent = node.name || node.id;
  g.appendChild(nameText);

  const subText = document.createElementNS(SVG_NS, 'text');
  subText.setAttribute('x', 8);
  subText.setAttribute('y', 34);
  subText.setAttribute('class', 'dag-node-sub');
  subText.textContent = node.role ? `${node.role} · ${node.state}` : node.state;
  g.appendChild(subText);

  return g;
}

// renderTaskTreeDAG renders a GET /api/stories/{id}/task-tree response into
// `container` as an SVG layered graph, color-coded by task.State (reusing
// the app's existing --state-* tokens — see dag-node-rect rules in
// style.css) with a text legend, plus a distinct name/state text label on
// every node so identity is never color-alone.
function renderTaskTreeDAG(tree, container) {
  container.innerHTML = '';
  const nodes = (tree && tree.nodes) || [];
  if (nodes.length === 0) {
    container.innerHTML = '<p class="task-meta">No task tree yet — this story has no root_task_id, or its root task has not been created.</p>';
    return;
  }

  const { positions, width, height } = layoutTaskTree(nodes, tree.root_task_id);
  const pad = 16;

  const svg = document.createElementNS(SVG_NS, 'svg');
  svg.setAttribute('viewBox', `0 0 ${width + pad * 2} ${height + pad * 2}`);
  svg.setAttribute('width', width + pad * 2);
  svg.setAttribute('height', height + pad * 2);
  svg.classList.add('dag-svg');

  const defs = document.createElementNS(SVG_NS, 'defs');
  const marker = document.createElementNS(SVG_NS, 'marker');
  marker.setAttribute('id', 'dag-arrow');
  marker.setAttribute('viewBox', '0 0 10 10');
  marker.setAttribute('refX', '9');
  marker.setAttribute('refY', '5');
  marker.setAttribute('markerWidth', '7');
  marker.setAttribute('markerHeight', '7');
  marker.setAttribute('orient', 'auto-start-reverse');
  const arrowPath = document.createElementNS(SVG_NS, 'path');
  arrowPath.setAttribute('d', 'M0,0 L10,5 L0,10 z');
  arrowPath.setAttribute('class', 'dag-arrow-head');
  marker.appendChild(arrowPath);
  defs.appendChild(marker);
  svg.appendChild(defs);

  const byId = new Map(nodes.map(n => [n.id, n]));
  function center(n) {
    const p = positions.get(n.id) || { x: 0, y: 0 };
    return { x: p.x + DAG_NODE_WIDTH / 2 + pad, y: p.y + DAG_NODE_HEIGHT / 2 + pad };
  }

  const edgesG = document.createElementNS(SVG_NS, 'g');
  edgesG.setAttribute('class', 'dag-edges');
  for (const n of nodes) {
    if (n.parent_task_id && byId.has(n.parent_task_id)) {
      drawDagEdge(edgesG, center(byId.get(n.parent_task_id)), center(n), 'parent');
    }
    for (const dep of n.depends_on || []) {
      if (byId.has(dep)) {
        drawDagEdge(edgesG, center(byId.get(dep)), center(n), 'depends');
      }
    }
  }
  svg.appendChild(edgesG);

  const nodesG = document.createElementNS(SVG_NS, 'g');
  nodesG.setAttribute('class', 'dag-nodes');
  for (const n of nodes) {
    nodesG.appendChild(renderDagNode(n, positions.get(n.id) || { x: 0, y: 0 }, pad));
  }
  svg.appendChild(nodesG);

  const wrap = document.createElement('div');
  wrap.className = 'dag-container';
  wrap.appendChild(svg);
  container.appendChild(wrap);
  container.appendChild(renderDagLegend());

  // Text elements are now part of the live document (container was already
  // on-page) — getComputedTextLength() needs that to return real numbers.
  fitDagNodeLabels(svg, DAG_NODE_WIDTH - 16);
}

// fitDagNodeLabels truncates each .dag-node-name/.dag-node-sub text element
// to fit maxWidth, measuring actual rendered glyph width via
// getComputedTextLength() rather than assuming a character-count budget —
// a role name like "evaluator_performance" is one unbroken word with no
// truncateToWordBoundary-style word break to fall back on, and different
// browsers/fonts render the same string at different widths.
function fitDagNodeLabels(svgRoot, maxWidth) {
  const els = svgRoot.querySelectorAll('.dag-node-name, .dag-node-sub');
  for (const el of els) {
    const full = el.textContent;
    let length;
    try {
      length = el.getComputedTextLength();
    } catch {
      continue; // no layout available (e.g. non-browser test env) — leave as-is
    }
    if (!Number.isFinite(length) || length <= maxWidth) continue;

    let lo = 0;
    let hi = full.length;
    while (lo < hi) {
      const mid = Math.ceil((lo + hi) / 2);
      el.textContent = full.slice(0, mid) + '…';
      if (el.getComputedTextLength() <= maxWidth) lo = mid;
      else hi = mid - 1;
    }
    el.textContent = lo > 0 ? full.slice(0, lo) + '…' : '…';
  }
}

// ── Story detail modal ────────────────────────────────────────────────────────

function acListElement(items) {
  const ul = document.createElement('ul');
  if (!items || items.length === 0) {
    ul.className = 'ac-list empty';
    const li = document.createElement('li');
    li.textContent = 'No acceptance criteria recorded.';
    ul.appendChild(li);
    return ul;
  }
  ul.className = 'ac-list';
  for (const item of items) {
    const li = document.createElement('li');
    li.textContent = item;
    ul.appendChild(li);
  }
  return ul;
}

async function renderStoryModalContent(storyId) {
  const title = document.getElementById('story-modal-title');
  const body = document.getElementById('story-modal-body');

  let story, tree, events;
  try {
    [story, tree, events] = await Promise.all([
      fetchStory(storyId),
      fetchStoryTaskTree(storyId),
      fetchStoryEvents(storyId),
    ]);
  } catch (err) {
    title.textContent = 'Story';
    body.innerHTML = `<div class="panel-fetch-error">Failed to load: ${err.message}</div>`;
    return;
  }

  let epic = null;
  if (story.epic_id) {
    try { epic = await fetchEpic(story.epic_id); } catch { epic = null; }
  }

  title.textContent = story.name;
  body.innerHTML = '';

  // ── Metadata ──
  const metaSection = makeSection('Story');
  const grid = document.createElement('div');
  grid.className = 'meta-grid';

  const statusItem = document.createElement('div');
  statusItem.className = 'meta-item';
  const statusLbl = document.createElement('div');
  statusLbl.className = 'meta-label';
  statusLbl.textContent = 'Status';
  const statusBadge = document.createElement('span');
  statusBadge.className = 'story-status-badge';
  statusBadge.dataset.status = story.status;
  statusBadge.textContent = (story.status || '').replace(/_/g, ' ');
  statusItem.append(statusLbl, statusBadge);
  grid.appendChild(statusItem);

  grid.append(
    makeMetaItem('Priority', story.priority),
    makeMetaItem('Epic', epic ? epic.name : (story.epic_id ? story.epic_id : '—'), { muted: !epic && !story.epic_id }),
    makeMetaItem('Created', formatDateLong(story.created_at)),
    makeMetaItem('Updated', formatDateLong(story.updated_at)),
    makeMetaItem('ID', story.id, { fullWidth: true, mono: true }),
  );
  metaSection.appendChild(grid);

  if (story.spec) {
    const specLabel = document.createElement('div');
    specLabel.className = 'meta-label';
    specLabel.style.marginTop = '0.75rem';
    specLabel.textContent = 'Spec';
    const specText = document.createElement('p');
    specText.className = 'task-summary';
    specText.textContent = story.spec;
    metaSection.appendChild(specLabel);
    metaSection.appendChild(specText);
  }

  const acLabel = document.createElement('div');
  acLabel.className = 'meta-label';
  acLabel.style.marginTop = '0.75rem';
  acLabel.textContent = 'Acceptance Criteria';
  metaSection.appendChild(acLabel);
  metaSection.appendChild(acListElement(story.acceptance_criteria));

  if (story.status === 'REVIEW_READY') {
    const acceptRow = document.createElement('div');
    acceptRow.className = 'story-modal-actions';
    const acceptBtn = document.createElement('button');
    acceptBtn.className = 'btn-accept';
    acceptBtn.textContent = 'Accept';
    acceptBtn.addEventListener('click', async () => {
      acceptBtn.disabled = true;
      acceptBtn.textContent = 'Accepting…';
      try {
        await acceptStory(story.id);
        await renderStoryModalContent(storyId);
        renderStoriesPanel();
      } catch (err) {
        acceptBtn.disabled = false;
        acceptBtn.textContent = 'Accept';
        const errEl = document.createElement('span');
        errEl.className = 'task-error';
        errEl.textContent = `Failed: ${err.message}`;
        acceptRow.appendChild(errEl);
      }
    });
    acceptRow.appendChild(acceptBtn);
    metaSection.appendChild(acceptRow);
  }

  body.appendChild(metaSection);

  // ── Task tree DAG ──
  const dagSection = makeSection('Task Tree');
  const dagContainer = document.createElement('div');
  dagSection.appendChild(dagContainer);
  body.appendChild(dagSection);
  renderTaskTreeDAG(tree, dagContainer);

  // ── Event timeline ──
  const timelineSection = makeSection('Timeline');
  timelineSection.appendChild(renderEventTimeline(events));
  body.appendChild(timelineSection);
}

async function openStoryModal(storyId) {
  const modal = document.getElementById('story-modal');
  const title = document.getElementById('story-modal-title');
  const body = document.getElementById('story-modal-body');
  if (!modal) return;
  title.textContent = 'Loading…';
  body.innerHTML = '<div class="panel-loading">Loading…</div>';
  modal.showModal();
  await renderStoryModalContent(storyId);
}

function closeStoryModal() {
  const modal = document.getElementById('story-modal');
  if (modal) modal.close();
}

// ── Budget & Escalation dashboard (Phase 9b) ──────────────────────────────────
// Per-provider spend headroom (GET /api/budget, already wired for the header
// chips), the escalation funnel (GET /api/escalation-funnel — how much work
// resolved at each rung of a role's ladder), and spend-over-time
// (GET /api/spend-timeseries), all per the dataviz skill: provider identity is
// a categorical color job, so it gets a fixed-order palette distinct from the
// --state-* task-state tokens (which are constrained/reused elsewhere and
// pre-date this phase); everything is also always paired with a text
// label/legend so identity never depends on color alone.

// Fixed categorical order + validated (dark-surface) hex per provider — see
// dataviz skill's palette.md categorical slots 1/2/3/4/5/6 (blue/aqua/yellow/
// green/violet/red), run through scripts/validate_palette.js against this
// app's dark chart surface (~#0f172a): all 6 pass the lightness/chroma/
// contrast checks, CVD separation lands in the 8-12 "floor" band, which is
// legal only paired with direct labels/legend — hence every render below
// carries a legend and/or text label, never color alone.
const PROVIDER_COLOR_ORDER = ['local', 'anthropic', 'google', 'groq', 'openrouter', 'openai'];
const PROVIDER_COLORS = {
  local:      '#3987e5', // blue
  anthropic:  '#199e70', // aqua
  google:     '#c98500', // yellow
  groq:       '#008300', // green
  openrouter: '#9085e9', // violet
  openai:     '#e66767', // red
};
const PROVIDER_COLOR_FALLBACK = '#898781'; // muted ink — any provider outside the fixed order

export function colorForProvider(agent) {
  return PROVIDER_COLORS[agent] || PROVIDER_COLOR_FALLBACK;
}

export function providerLabel(agent) {
  if (!agent) return 'Unknown';
  return agent.charAt(0).toUpperCase() + agent.slice(1);
}

function sortProvidersCanonically(agents) {
  return [...agents].sort((a, b) => {
    const ia = PROVIDER_COLOR_ORDER.indexOf(a);
    const ib = PROVIDER_COLOR_ORDER.indexOf(b);
    return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib);
  });
}

// Dataviz skill's "good/warning/critical" status palette (fixed, never
// themed, distinct from the categorical provider slots above) — used for the
// budget meter fill, since remaining-headroom severity is a status job, not
// an identity job.
const BUDGET_STATUS_GOOD = '#0ca30c';
const BUDGET_STATUS_WARNING = '#fab219';
const BUDGET_STATUS_CRITICAL = '#d03b3b';

function budgetStatusColor(fractionRemaining) {
  if (fractionRemaining < 0.2) return BUDGET_STATUS_CRITICAL;
  if (fractionRemaining < 0.5) return BUDGET_STATUS_WARNING;
  return BUDGET_STATUS_GOOD;
}

// computeEscalationFunnel reshapes the raw (rung, agent, count, cost_usd)
// aggregate rows from GET /api/escalation-funnel into per-rung totals plus a
// provider breakdown, sorted by rung ascending (rung 0 first — the harness's
// "resolved without escalating" story).
export function computeEscalationFunnel(buckets) {
  const byRung = new Map();
  let grandTotal = 0;
  for (const b of (buckets || [])) {
    grandTotal += b.count;
    let r = byRung.get(b.rung);
    if (!r) {
      r = { rung: b.rung, total: 0, cost: 0, byAgent: [] };
      byRung.set(b.rung, r);
    }
    r.total += b.count;
    r.cost += b.cost_usd || 0;
    r.byAgent.push({ agent: b.agent || '', count: b.count, cost: b.cost_usd || 0 });
  }
  const rungs = Array.from(byRung.values()).sort((a, b) => a.rung - b.rung);
  return { rungs, grandTotal };
}

// computeSpendSeries reshapes the raw (bucket, agent, cost_usd) points from
// GET /api/spend-timeseries into aligned per-provider arrays over a shared,
// sorted bucket axis (missing points fill as 0), plus the max value for
// scaling a chart's y-axis.
export function computeSpendSeries(points) {
  const bucketsSet = new Set();
  const agentsSet = new Set();
  const byKey = new Map();
  for (const p of (points || [])) {
    bucketsSet.add(p.bucket);
    const agent = p.agent || '';
    agentsSet.add(agent);
    byKey.set(`${p.bucket}|${agent}`, p.cost_usd || 0);
  }
  const buckets = Array.from(bucketsSet).sort();
  const agents = Array.from(agentsSet).sort();
  const series = {};
  let maxCost = 0;
  for (const agent of agents) {
    series[agent] = buckets.map(b => {
      const v = byKey.get(`${b}|${agent}`) || 0;
      if (v > maxCost) maxCost = v;
      return v;
    });
  }
  return { buckets, agents, series, maxCost };
}

// formatBucketLabel turns a spend-timeseries bucket key — either an RFC3339
// hour ("2026-07-02T14:00:00Z") or a calendar day ("2026-07-02") — into a
// short human label.
export function formatBucketLabel(bucket) {
  if (!bucket) return '';
  if (bucket.includes('T')) {
    return new Date(bucket).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit' });
  }
  return new Date(bucket + 'T12:00:00Z').toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}

function renderProviderLegend(agents, doc = document) {
  const legend = doc.createElement('div');
  legend.className = 'provider-legend';
  for (const agent of sortProvidersCanonically(agents)) {
    const item = doc.createElement('span');
    item.className = 'provider-legend-item';
    const swatch = doc.createElement('span');
    swatch.className = 'provider-legend-swatch';
    swatch.style.background = colorForProvider(agent);
    item.appendChild(swatch);
    const text = doc.createElement('span');
    text.textContent = providerLabel(agent);
    item.appendChild(text);
    legend.appendChild(item);
  }
  return legend;
}

// renderEscalationFunnel builds the funnel chart: one horizontal bar per
// rung (bar length = share of the window's total executions — the "how much
// falls through each stage" story), stacked by provider within the bar. Bar
// length already encodes the funnel shape via ordinal position + decreasing
// magnitude, so rung identity needs no color of its own; provider identity
// (the stacked segments) is the one categorical color job here, backed by a
// legend and per-segment title tooltips (never color alone).
export function renderEscalationFunnel(funnelData, doc = (typeof document !== 'undefined' ? document : null)) {
  if (doc == null) return null;
  const wrap = doc.createElement('div');
  wrap.className = 'funnel-chart';

  if (!funnelData.rungs.length) {
    const empty = doc.createElement('p');
    empty.className = 'task-meta';
    empty.textContent = 'No executions in this window.';
    wrap.appendChild(empty);
    return wrap;
  }

  const maxTotal = Math.max(...funnelData.rungs.map(r => r.total), 1);
  const allAgents = new Set();

  for (const r of funnelData.rungs) {
    const row = doc.createElement('div');
    row.className = 'funnel-row';

    const label = doc.createElement('span');
    label.className = 'funnel-row-label';
    label.textContent = `Rung ${r.rung}`;
    row.appendChild(label);

    // trackOuter is the full-width baseline; track is sized to this rung's
    // share of the largest rung (the funnel taper), and holds the
    // provider-colored segments distributed by flex-grow within it.
    const trackOuter = doc.createElement('div');
    trackOuter.className = 'funnel-track-outer';

    const track = doc.createElement('div');
    track.className = 'funnel-track';
    track.style.width = `${((r.total / maxTotal) * 100).toFixed(1)}%`;

    for (const a of sortProvidersCanonically(r.byAgent.map(x => x.agent)).map(agent => r.byAgent.find(x => x.agent === agent))) {
      allAgents.add(a.agent);
      const seg = doc.createElement('div');
      seg.className = 'funnel-seg';
      seg.style.background = colorForProvider(a.agent);
      seg.style.flexGrow = String(a.count);
      const pct = r.total > 0 ? Math.round((a.count / r.total) * 100) : 0;
      seg.title = `${providerLabel(a.agent)}: ${a.count} (${pct}%)`;
      track.appendChild(seg);
    }

    trackOuter.appendChild(track);
    row.appendChild(trackOuter);

    const countEl = doc.createElement('span');
    countEl.className = 'funnel-count';
    const pctOfGrand = funnelData.grandTotal > 0 ? Math.round((r.total / funnelData.grandTotal) * 100) : 0;
    countEl.textContent = `${r.total} (${pctOfGrand}%)`;
    row.appendChild(countEl);

    wrap.appendChild(row);
  }

  wrap.appendChild(renderProviderLegend(Array.from(allAgents), doc));
  return wrap;
}

// renderSpendTimeseries builds a multi-line SVG chart, one line per provider
// (categorical color, fixed order) — cost trend over time is the story, and
// "tell distinct series apart over time" is exactly the multi-line job per
// the dataviz skill's form table. Direct end-labels only when there are few
// enough series to not collide (<=4); a legend always carries identity
// regardless. Hover tooltips (native <title>) on every point per the skill's
// "ship a crosshair+tooltip on line/area" interaction guidance — kept to
// native titles rather than a custom crosshair overlay, consistent with this
// app's existing charts (stats tab's throughput/billing bars use the same
// col.title convention).
export function renderSpendTimeseries(seriesData, doc = (typeof document !== 'undefined' ? document : null)) {
  if (doc == null) return null;
  const { buckets, agents, series, maxCost } = seriesData;
  const wrap = doc.createElement('div');
  wrap.className = 'spend-chart-wrap';

  if (buckets.length === 0 || agents.length === 0) {
    const empty = doc.createElement('p');
    empty.className = 'task-meta';
    empty.textContent = 'No spend data in this window.';
    wrap.appendChild(empty);
    return wrap;
  }

  const width = 640, height = 200;
  const padL = 8, padR = 52, padT = 12, padB = 24;
  const plotW = width - padL - padR;
  const plotH = height - padT - padB;
  const yMax = maxCost > 0 ? maxCost * 1.15 : 1;

  const xFor = i => (buckets.length > 1 ? padL + (i / (buckets.length - 1)) * plotW : padL + plotW / 2);
  const yFor = v => (height - padB) - (v / yMax) * plotH;

  const svg = doc.createElementNS(SVG_NS, 'svg');
  svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
  svg.setAttribute('width', '100%');
  svg.setAttribute('height', String(height));
  svg.classList.add('spend-chart-svg');

  const axis = doc.createElementNS(SVG_NS, 'line');
  axis.setAttribute('x1', String(padL));
  axis.setAttribute('x2', String(width - padR));
  axis.setAttribute('y1', String(height - padB));
  axis.setAttribute('y2', String(height - padB));
  axis.setAttribute('class', 'spend-chart-axis');
  svg.appendChild(axis);

  const sortedAgents = sortProvidersCanonically(agents);
  const directLabels = sortedAgents.length <= 4;

  // Pre-compute end-label eligibility: when two series' final values land
  // close together in y, only the first (top-most) keeps its direct label;
  // per the dataviz skill's "when end-labels collide, don't stack them"
  // rule, the rest fall back to the legend + hover tooltip rather than
  // being nudged apart (which would detach a label from its line).
  const labelEligible = new Set();
  if (directLabels) {
    const MIN_LABEL_GAP_PX = 14;
    const candidates = sortedAgents
      .map(agent => {
        const values = series[agent] || [];
        return values.length > 0 ? { agent, y: yFor(values[values.length - 1]) } : null;
      })
      .filter(Boolean)
      .sort((a, b) => a.y - b.y);
    let lastLabeledY = -Infinity;
    for (const c of candidates) {
      if (c.y - lastLabeledY >= MIN_LABEL_GAP_PX) {
        labelEligible.add(c.agent);
        lastLabeledY = c.y;
      }
    }
  }

  for (const agent of sortedAgents) {
    const values = series[agent] || [];
    const color = colorForProvider(agent);
    const pointsAttr = values.map((v, i) => `${xFor(i).toFixed(1)},${yFor(v).toFixed(1)}`).join(' ');

    const poly = doc.createElementNS(SVG_NS, 'polyline');
    poly.setAttribute('points', pointsAttr);
    poly.setAttribute('fill', 'none');
    poly.setAttribute('stroke', color);
    poly.setAttribute('stroke-width', '2');
    poly.setAttribute('stroke-linejoin', 'round');
    poly.setAttribute('stroke-linecap', 'round');
    poly.classList.add('spend-chart-line');
    svg.appendChild(poly);

    values.forEach((v, i) => {
      const dot = doc.createElementNS(SVG_NS, 'circle');
      dot.setAttribute('cx', xFor(i).toFixed(1));
      dot.setAttribute('cy', yFor(v).toFixed(1));
      dot.setAttribute('r', i === values.length - 1 ? '4' : '3');
      dot.setAttribute('fill', color);
      dot.classList.add('spend-chart-dot');
      const title = doc.createElementNS(SVG_NS, 'title');
      title.textContent = `${providerLabel(agent)} · ${formatBucketLabel(buckets[i])}: $${v.toFixed(3)}`;
      dot.appendChild(title);
      svg.appendChild(dot);
    });

    if (labelEligible.has(agent) && values.length > 0) {
      const last = values[values.length - 1];
      const label = doc.createElementNS(SVG_NS, 'text');
      label.setAttribute('x', (xFor(values.length - 1) + 6).toFixed(1));
      label.setAttribute('y', (yFor(last) + 4).toFixed(1));
      label.setAttribute('class', 'spend-chart-label');
      label.textContent = `$${last.toFixed(2)}`;
      svg.appendChild(label);
    }
  }

  const tickIdxs = buckets.length > 1 ? [0, Math.floor((buckets.length - 1) / 2), buckets.length - 1] : [0];
  const seenTicks = new Set();
  for (const i of tickIdxs) {
    if (seenTicks.has(i)) continue;
    seenTicks.add(i);
    const t = doc.createElementNS(SVG_NS, 'text');
    t.setAttribute('x', xFor(i).toFixed(1));
    t.setAttribute('y', String(height - 6));
    t.setAttribute('class', 'spend-chart-tick');
    t.setAttribute('text-anchor', i === 0 ? 'start' : (i === buckets.length - 1 ? 'end' : 'middle'));
    t.textContent = formatBucketLabel(buckets[i]);
    svg.appendChild(t);
  }

  wrap.appendChild(svg);
  wrap.appendChild(renderProviderLegend(sortedAgents, doc));
  return wrap;
}

// renderBudgetMeters builds a bar/meter per limited provider showing spend
// vs. its rolling-window cap. Fill color is a status (severity) job — how
// much headroom is left — not an identity job, so it uses the dataviz
// skill's fixed good/warning/critical status palette (deliberately distinct
// from both the --state-* task tokens and the provider categorical palette
// above), always paired with the numeric label so severity never rides on
// color alone.
export function renderBudgetMeters(headrooms, doc = (typeof document !== 'undefined' ? document : null)) {
  if (doc == null) return null;
  const wrap = doc.createElement('div');
  wrap.className = 'budget-meters';

  const limited = (headrooms || []).filter(h => h && h.limited);
  if (limited.length === 0) {
    const empty = doc.createElement('p');
    empty.className = 'task-meta';
    empty.textContent = 'No provider spend limits configured.';
    wrap.appendChild(empty);
    return wrap;
  }

  for (const h of limited) {
    const row = doc.createElement('div');
    row.className = 'budget-meter-row';

    const label = doc.createElement('div');
    label.className = 'budget-meter-label';
    const name = doc.createElement('span');
    name.textContent = providerLabel(h.provider);
    const value = doc.createElement('span');
    value.className = 'budget-meter-value';
    const pctLeft = Math.round((h.fraction_remaining || 0) * 100);
    value.textContent = `$${(h.spent_usd || 0).toFixed(2)} / $${(h.limit_usd || 0).toFixed(2)} · ${pctLeft}% left`;
    label.append(name, value);
    row.appendChild(label);

    const track = doc.createElement('div');
    track.className = 'budget-meter-track';
    const fill = doc.createElement('div');
    fill.className = 'budget-meter-fill';
    const spentPct = h.limit_usd > 0 ? Math.min(100, ((h.spent_usd || 0) / h.limit_usd) * 100) : 0;
    fill.style.width = `${spentPct.toFixed(1)}%`;
    fill.style.background = budgetStatusColor(h.fraction_remaining || 0);
    track.appendChild(fill);
    row.appendChild(track);

    wrap.appendChild(row);
  }

  return wrap;
}

function getBudgetWindow() {
  return localStorage.getItem('budgetWindow') || '24h';
}

function setBudgetWindow(w) {
  localStorage.setItem('budgetWindow', w);
}

async function renderBudgetPanel() {
  const panel = document.querySelector('[data-panel="budget"]');
  if (!panel) return;

  const win = getBudgetWindow();
  try {
    const [headrooms, funnelRaw, spendRaw] = await Promise.all([
      fetch(`${BASE_PATH}/api/budget`).then(r => r.ok ? r.json() : []),
      fetch(`${BASE_PATH}/api/escalation-funnel?window=${encodeURIComponent(win)}`).then(r => r.ok ? r.json() : []),
      fetch(`${BASE_PATH}/api/spend-timeseries?window=${encodeURIComponent(win)}`).then(r => r.ok ? r.json() : []),
    ]);

    panel.innerHTML = '';

    // ── Provider spend headroom ──
    const budgetSection = document.createElement('div');
    budgetSection.className = 'stats-section';
    const budgetHeading = document.createElement('h2');
    budgetHeading.textContent = 'Provider Spend Headroom';
    budgetSection.appendChild(budgetHeading);
    budgetSection.appendChild(renderBudgetMeters(headrooms));
    panel.appendChild(budgetSection);

    // ── Window selector (shared by funnel + spend-over-time below) ──
    const windowRow = document.createElement('div');
    windowRow.className = 'dashboard-window-row';
    const windowLabel = document.createElement('label');
    windowLabel.textContent = 'Window: ';
    const windowSelect = document.createElement('select');
    windowSelect.className = 'agent-selector dashboard-window-select';
    for (const opt of [['5h', 'Last 5 hours'], ['24h', 'Last 24 hours'], ['7d', 'Last 7 days']]) {
      const o = document.createElement('option');
      o.value = opt[0];
      o.textContent = opt[1];
      if (opt[0] === win) o.selected = true;
      windowSelect.appendChild(o);
    }
    windowSelect.addEventListener('change', () => {
      setBudgetWindow(windowSelect.value);
      renderBudgetPanel();
    });
    windowLabel.appendChild(windowSelect);
    windowRow.appendChild(windowLabel);
    panel.appendChild(windowRow);

    // ── Escalation funnel ──
    const funnelSection = document.createElement('div');
    funnelSection.className = 'stats-section';
    const funnelHeading = document.createElement('h2');
    funnelHeading.textContent = 'Escalation Funnel';
    funnelSection.appendChild(funnelHeading);
    const funnelNote = document.createElement('p');
    funnelNote.className = 'task-meta funnel-note';
    funnelNote.textContent = 'Share of executions resolved at each escalation rung (rung 0 = first tier / local-first; higher rungs = escalated to a costlier provider). Non-role-typed tasks always show at rung 0 alongside role-typed tasks resolved there.';
    funnelSection.appendChild(funnelNote);
    funnelSection.appendChild(renderEscalationFunnel(computeEscalationFunnel(funnelRaw)));
    panel.appendChild(funnelSection);

    // ── Spend over time ──
    const spendSection = document.createElement('div');
    spendSection.className = 'stats-section';
    const spendHeading = document.createElement('h2');
    spendHeading.textContent = 'Spend Over Time';
    spendSection.appendChild(spendHeading);
    spendSection.appendChild(renderSpendTimeseries(computeSpendSeries(spendRaw)));
    panel.appendChild(spendSection);
  } catch (err) {
    panel.innerHTML = `<div class="panel-fetch-error">Failed to load budget dashboard: ${err.message}</div>`;
  }
}

// ── Role/config management panel (Phase 9b) ───────────────────────────────────
// Lists every role with at least one role_configs row (GET /api/roles), each
// role's version history (GET /api/roles/{role}/versions), and an Activate
// button on draft versions (POST /api/roles/{role}/activate?version=N) — the
// human-facing side of the Phase 8 retro loop.

// formatEscalationLadder turns a role.RoleConfig's escalation_ladder into a
// small readable structure (tier index, selection mode, retry budget, and a
// "provider/model" string per candidate) instead of a raw JSON dump.
export function formatEscalationLadder(ladder) {
  if (!ladder || ladder.length === 0) return [];
  return ladder.map((tier, i) => ({
    tier: i,
    mode: tier.selection_mode || 'round_robin',
    maxRetries: tier.max_retries || 0,
    candidates: (tier.candidates || []).map(c => (c.model ? `${c.provider}/${c.model}` : c.provider)),
  }));
}

function renderEscalationLadderTable(ladder, doc = document) {
  const rows = formatEscalationLadder(ladder);
  if (rows.length === 0) {
    const empty = doc.createElement('p');
    empty.className = 'task-meta';
    empty.textContent = 'No escalation ladder configured.';
    return empty;
  }
  const list = doc.createElement('ol');
  list.className = 'escalation-ladder-list';
  for (const row of rows) {
    const li = doc.createElement('li');
    li.className = 'escalation-ladder-item';
    const tierLabel = doc.createElement('span');
    tierLabel.className = 'escalation-ladder-tier';
    tierLabel.textContent = `Tier ${row.tier}`;
    const candidates = doc.createElement('span');
    candidates.className = 'escalation-ladder-candidates';
    candidates.textContent = row.candidates.join(', ') || '(none)';
    const meta = doc.createElement('span');
    meta.className = 'escalation-ladder-meta';
    meta.textContent = `${row.mode}, max ${row.maxRetries} retr${row.maxRetries === 1 ? 'y' : 'ies'} before escalating`;
    li.append(tierLabel, candidates, meta);
    list.appendChild(li);
  }
  return list;
}

async function handleActivateRoleVersionClick(roleName, version, btn) {
  btn.disabled = true;
  const original = btn.textContent;
  btn.textContent = 'Activating…';
  try {
    const res = await fetch(`${API_BASE}/api/roles/${encodeURIComponent(roleName)}/activate?version=${version}`, { method: 'POST' });
    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      throw new Error(body.error || `HTTP ${res.status}`);
    }
    await renderSettingsPanel();
  } catch (err) {
    btn.disabled = false;
    btn.textContent = original;
    alert(`Failed to activate version ${version}: ${err.message}`);
  }
}

function renderRoleCard(roleName, versions, doc = document) {
  const card = doc.createElement('div');
  card.className = 'role-card';

  const header = doc.createElement('div');
  header.className = 'role-card-header';
  const title = doc.createElement('h3');
  title.textContent = roleName;
  header.appendChild(title);

  const active = versions.find(v => v.status === 'active');
  const activeBadge = doc.createElement('span');
  activeBadge.className = 'role-active-badge' + (active ? '' : ' role-active-badge--none');
  activeBadge.textContent = active ? `Active: v${active.version}` : 'No active version';
  header.appendChild(activeBadge);
  card.appendChild(header);

  if (active) {
    const ladderSection = doc.createElement('div');
    ladderSection.className = 'role-ladder-section';
    const ladderLabel = doc.createElement('div');
    ladderLabel.className = 'panel-section-title';
    ladderLabel.textContent = `Escalation Ladder (v${active.version})`;
    ladderSection.appendChild(ladderLabel);
    ladderSection.appendChild(renderEscalationLadderTable(active.config && active.config.escalation_ladder, doc));
    card.appendChild(ladderSection);
  }

  const list = doc.createElement('div');
  list.className = 'role-version-list';
  const sorted = [...versions].sort((a, b) => b.version - a.version);
  for (const v of sorted) {
    const row = doc.createElement('div');
    row.className = 'role-version-row role-version-row--' + v.status;

    const vLabel = doc.createElement('span');
    vLabel.className = 'role-version-num';
    vLabel.textContent = `v${v.version}`;
    row.appendChild(vLabel);

    const statusBadge = doc.createElement('span');
    statusBadge.className = 'role-version-status role-version-status--' + v.status;
    statusBadge.textContent = v.status;
    row.appendChild(statusBadge);

    const proposedBy = doc.createElement('span');
    proposedBy.className = 'role-version-meta';
    proposedBy.textContent = v.proposed_by ? `by ${v.proposed_by}` : '';
    row.appendChild(proposedBy);

    const created = doc.createElement('span');
    created.className = 'role-version-meta';
    created.textContent = v.created_at ? formatDate(v.created_at) : '';
    row.appendChild(created);

    if (v.status === 'draft') {
      const activateBtn = doc.createElement('button');
      activateBtn.className = 'btn-primary btn-sm';
      activateBtn.textContent = 'Activate';
      activateBtn.addEventListener('click', () => handleActivateRoleVersionClick(roleName, v.version, activateBtn));
      row.appendChild(activateBtn);
    }

    list.appendChild(row);
  }
  card.appendChild(list);

  return card;
}

async function renderRolesPanel(container = document.querySelector('[data-panel="roles"]')) {
  if (!container) return;

  try {
    const namesRes = await fetch(`${BASE_PATH}/api/roles`);
    const names = namesRes.ok ? await namesRes.json() : [];
    if (!names || names.length === 0) {
      const empty = document.createElement('div');
      empty.className = 'task-empty';
      empty.textContent = 'No role configs yet.';
      container.appendChild(empty);
      return;
    }

    const versionsByRole = await Promise.all(names.map(name =>
      fetch(`${BASE_PATH}/api/roles/${encodeURIComponent(name)}/versions`).then(r => r.ok ? r.json() : []),
    ));

    names.forEach((name, i) => {
      container.appendChild(renderRoleCard(name, versionsByRole[i] || []));
    });
  } catch (err) {
    const errEl = document.createElement('div');
    errEl.className = 'panel-fetch-error';
    errEl.textContent = `Failed to load roles: ${err.message}`;
    container.appendChild(errEl);
  }
}

// ── Tab switching ─────────────────────────────────────────────────────────────

function switchTab(name) {
  setActiveMainTab(name);

  // Update tab button active state
  document.querySelectorAll('.tab').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.tab === name);
  });

  // Show/hide panels
  document.querySelectorAll('[data-panel]').forEach(panel => {
    if (panel.dataset.panel === name) {
      panel.removeAttribute('hidden');
    } else {
      panel.setAttribute('hidden', '');
    }
  });

  // Trigger immediate render for the newly active tab
  poll();
}

// ── Version color ─────────────────────────────────────────────────────────────

async function applyVersionColor() {
  try {
    const res = await fetch(`${BASE_PATH}/api/version`);
    if (!res.ok) return;
    const { version } = await res.json();
    // Use first 6 hex chars of version as hue seed (works for commit hashes and "dev")
    const hex = version.replace(/[^0-9a-f]/gi, '').slice(0, 6).padEnd(6, '0');
    const hue = Math.round((parseInt(hex, 16) / 0xffffff) * 360);
    const h1 = document.querySelector('header h1');
    if (h1) h1.style.color = `hsl(${hue}, 70%, 55%)`;
  } catch {
    // non-fatal — logo stays default color
  }
}

// ── Boot ──────────────────────────────────────────────────────────────────────

if (typeof document !== 'undefined') {
  document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('btn-start-next').addEventListener('click', function() {
      handleStartNextTask(this);
    });

    applyVersionColor();
    switchTab(getActiveMainTab());
    startPolling();
    connectWebSocket();

    // Side panel close
    document.getElementById('btn-close-panel').addEventListener('click', closeTaskPanel);
    document.getElementById('task-panel-backdrop').addEventListener('click', closeTaskPanel);

    // Execution logs modal close
    document.getElementById('btn-close-logs').addEventListener('click', () => {
      document.getElementById('logs-modal').close();
    });

    // Story detail modal close
    const btnCloseStoryModal = document.getElementById('btn-close-story-modal');
    if (btnCloseStoryModal) btnCloseStoryModal.addEventListener('click', closeStoryModal);

    // Stories board/epics view toggle
    document.querySelectorAll('.view-toggle-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        setStoriesViewMode(btn.dataset.view);
        renderStoriesPanel();
      });
    });

    // Tab bar
    document.querySelectorAll('.tab').forEach(btn => {
      btn.addEventListener('click', () => switchTab(btn.dataset.tab));
    });


    // Push notifications button
    const btnNotify = document.getElementById('btn-notifications');
    if (btnNotify) {
      btnNotify.addEventListener('click', () => enableNotifications(btnNotify));
    }


  });
}