paperboy 0.4.0

A Rust TUI API tester
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
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
//! The GUI PaperTrail report editor — a Scratch-style block editor over the
//! shared [`ReportFlow`] AST, plus a raw source view. Both views edit the *same*
//! report: every structural block edit re-serializes the AST back into the
//! report text via [`ReportFlow::to_text`], and the source view parses text back
//! into blocks, so they round-trip. All the heavy lifting — flattening the flow
//! into rows, inserting / moving / removing / replacing nodes, the node-kind
//! palette, and validation against the bound collection — is reused from the
//! front-end-agnostic [`crate::report::edit`] and [`crate::report::context`]
//! modules the terminal UI's node editor is built on.

use eframe::egui::{self, Color32, RichText};

use crate::i18n::{Status, Strings};
use crate::report::Report;
use crate::report::context;
use crate::report::edit::{
    self, CarriedMod, DetachWhich, HEADER_PLACEHOLDER, HeaderKind, HeaderSpec, InsertPos, Modifier,
    NodeKind, RowKind, attach_modifier, attach_to_node, carry_modifier, detach_modifier, flatten,
    header_specs, insert_node, insert_pos_after, move_node, node_at, remove_node, replace_node,
    report_assignment, request_node, set_request_name, transfer_modifier,
};
use crate::report::filter::RowFilter;
use crate::report::flow::{FlowNode, ReportFlow, ReportStmt, WithItem};
use crate::report::indent::{
    INDENT_UNIT, ReformatError, indent_for_new_line, is_end_line, matching_opener_indent,
};
use crate::report::model::ReportResult;
use crate::report::validate::{Diagnostic, Severity};

use crate::tui::report_highlight::{self, HlCtx};

use super::app::GuiApp;
use super::report_run::{self, ParkedRun, RowState, RunHandle, RunKey, RunProgress};
use super::theme::GuiTheme;

/// Which of the two editor views is shown.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum EditorView {
    /// The Scratch-style stacked, nested, colour-coded blocks.
    Blocks,
    /// The raw `.trail` source text.
    Source,
    /// The results grid from the last (or in-flight) run.
    Results,
}

/// Where the editor's report is saved back to.
pub enum ReportOrigin {
    /// A report tab carried in the session (index into [`crate::session::Session::reports`]).
    Session(usize),
    /// A `.trail` file opened from a Workspace tree, saved to its own path.
    Workspace,
}

/// The GUI report editor's state. Owns a core [`Report`] (text = source of
/// truth) plus the parsed AST cache, current selection and per-view scratch.
pub struct ReportEditor {
    pub origin: ReportOrigin,
    pub report: Report,
    pub view: EditorView,
    /// Parsed AST cache, recomputed from `report.text` after every edit.
    pub flow: Option<ReportFlow>,
    pub parse_error: Option<String>,
    /// 1-based line the parser rejected, so the Source view can mark exactly
    /// that line the way the terminal UI does.
    pub parse_error_line: Option<usize>,
    pub diagnostics: Vec<Diagnostic>,
    /// The report's aliased helper collections, loaded alongside `diagnostics`.
    ///
    /// Behind the same fingerprint gate, because loading them reads files from
    /// disk and everything that needs them (the chip tints, the request combo,
    /// the highlighter) runs while drawing — i.e. on every frame.
    pub helpers: Vec<crate::report::run::HelperCollection>,
    /// The [`context::diagnostics_fingerprint`] the current `diagnostics` were
    /// computed from. Validation is re-run only when this changes, so it happens
    /// on an edit rather than on every frame — see that function for why.
    diag_key: Option<u64>,
    /// The last highlighter context built for the Source view, with the
    /// fingerprint of what it was built from.
    ///
    /// Same reasoning as `diag_key`, one step further in: the Source view asks
    /// for this on every frame, and building it collects the bound collection's
    /// (and every helper's) request names into a fresh `HashSet` of freshly
    /// formatted qualified strings — a per-frame allocation per request, to
    /// answer a question whose answer only changes when a request is renamed.
    hl_cache: Option<(u64, std::rc::Rc<HlCtx>)>,
    /// The selected node's path (a sequence of indices into nested loop
    /// bodies). Empty = the synthetic `Begin` root.
    pub selection: Vec<usize>,
    /// When `Some`, the insert palette is open, inserting at this position.
    pub palette: Option<PaletteState>,
    /// Snapshots of `report.text` for undo (Ctrl+Z), newest last.
    pub undo: Vec<String>,
    /// The last run's output (skeleton while streaming, finalized at the end),
    /// rendered as a grid in [`EditorView::Results`].
    pub result: Option<ReportResult>,
    /// Live streaming state while a run is in flight; `None` when idle.
    pub progress: Option<RunProgress>,
    /// The in-flight run's handle (cancel flag + update channel); `None` when idle.
    pub run: Option<RunHandle>,
    /// Whether the current `result` has been exported since it was produced.
    pub results_exported: bool,
    /// The file the last successful export wrote, so "Open" can hand it to the
    /// desktop without asking where it went. Cleared when a fresh run replaces
    /// the result, because the file then describes a run that is no longer on
    /// screen.
    pub last_export: Option<String>,
    /// Which of the results view's row filters is selected, as an index into
    /// [`crate::report::filter::RowFilter::available`] for the current result.
    ///
    /// Held as an index rather than the filter itself because the set of
    /// filters worth offering is derived from the result: a stored `Regressed`
    /// would have to be validated against every new result anyway, and an index
    /// only has to be clamped. Reset with the result.
    pub results_filter: usize,
    /// The results view's find box: a case-insensitive substring the shown
    /// columns are searched for, narrowing the rows the filter already chose.
    pub results_find: String,
    /// The row whose drill-down panel is open, if any.
    ///
    /// One at a time, unlike the HTML export's independently-expanding rows: a
    /// panel holds full-size pictures and whole response bodies, and several
    /// open at once in a fixed-height pane would leave the grid a sliver.
    pub results_detail: Option<usize>,
    /// Decoded textures for the pictures the drill-down has shown, keyed by row
    /// and column.
    ///
    /// Uploading a picture to the GPU is not something to do sixty times a
    /// second, so each one is decoded once and kept. Cleared with the result
    /// that produced it — the keys are row indices, which mean nothing once the
    /// rows change.
    results_textures: std::collections::HashMap<(usize, String), egui::TextureHandle>,
    /// When `Some`, a node-configure wizard (request / envs / files) is open as
    /// a modal over the blocks view.
    pub wizard: Option<super::report_wizard::Wizard>,
    /// Height (px) reserved for the validation panel at the bottom of the
    /// Blocks / Source views. User-adjustable by dragging the splitter above it
    /// (the GUI's stand-in for a fixed panel), so a report with many validation
    /// errors can be given as much room as needed.
    pub diag_h: f32,
    /// Height (px) the results view's summary block (metric cards, filter bar
    /// and confusion matrices) is allowed before it starts scrolling within
    /// itself. Adjustable by dragging the splitter under it: a matrix per
    /// ground-truthed column can fill most of the pane, which leaves the grid
    /// it is describing with nothing — but a reader comparing cells wants the
    /// opposite, so the split is theirs to make.
    pub summary_h: f32,
    /// Height (px) reserved for the row drill-down panel under the results
    /// grid, adjustable by dragging the splitter above it. A drill-down holds
    /// full-size pictures and whole response bodies, so how much of the view it
    /// should take is a matter of what the reader is doing — reading rows or
    /// reading one row — rather than something the app can pick for them.
    pub detail_h: f32,
    /// Width (px) of the palette column in the Blocks view. User-adjustable by
    /// dragging the divider between the palette and the block stack.
    pub palette_w: f32,
    /// When `Some`, the results cell inspector window is open, showing one
    /// cell's full (pretty-printed) value — the GUI stand-in for the TUI's
    /// result-cell popup, so a long/truncated cell can be read in full.
    pub inspector: Option<CellInspector>,
    /// When `Some`, the Results view is showing a dry run — what the flow
    /// *would* emit, worked out without sending a request — instead of the last
    /// real result.
    ///
    /// Held apart from [`Self::result`] rather than written into it, so a
    /// preview never destroys the results you actually ran for (and can't be
    /// exported as though it were them). Dismissing the preview brings them
    /// straight back.
    pub dry_run: Option<Box<crate::report::dry_run::DryRunReport>>,
    /// The values chosen for this report's `PARAM`s, keyed by raw name. Owned
    /// by the editor rather than the report: a value belongs to the run, not to
    /// the file (which stays the same for everyone who opens it).
    pub param_values: crate::report::params::ParamValues,
    /// Whether [`ReportEditor::seed_params`] has run. The editor is built
    /// without the session in hand, so the last-used values are filled in on
    /// the first frame instead — once.
    params_seeded: bool,
    /// What the report's `PARAM` declarations looked like when the answers were
    /// last confirmed. Editing a declaration re-asks the questions; editing
    /// anything else does not.
    params_sig: String,
    /// Whether the questions have been answered for this editing session. Set
    /// when the dialog is left by Run or Dry run, so a preview can be followed
    /// straight by the real run without answering twice.
    params_confirmed: bool,
    /// The open run-settings dialog, and what pressing its primary button will
    /// do. `None` when it isn't showing.
    params_modal: Option<RunIntent>,
    /// What the result on screen was actually run with, in the order the
    /// report declares. Kept beside the result rather than in it, because the
    /// question it answers — "what did *this* table come from?" — is only ever
    /// asked while looking at the table, and because the answers can be
    /// changed afterwards without rerunning.
    result_params: Vec<(String, String)>,
    /// A toolbar button pressed this frame, run *after* the body has been drawn
    /// (see [`ToolbarAct`]).
    pending_toolbar: Option<ToolbarAct>,
}

/// Which button the run-settings dialog was opened on the way to, and so which
/// of its two exits is the primary one.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum RunIntent {
    Run,
    DryRun,
    /// Opened deliberately from the toolbar rather than on the way anywhere.
    /// Both exits are offered; neither is emphasised.
    Review,
}

/// A toolbar button press, deferred to the end of the frame that pressed it.
///
/// The header strip is drawn before the view below it, and the inline chip
/// fields in that view commit what has been typed into them when they lose
/// focus — which is the same frame the button click takes focus away. Acting
/// immediately therefore acted on the *pre-edit* report: Run ran the old flow
/// (and switched to Results, so the field was never redrawn and the typing was
/// simply dropped), and Save wrote the old text. Deferring to the end of the
/// frame lets the field commit first, so a button always acts on what is on
/// screen.
#[derive(Clone, PartialEq, Eq, Debug)]
enum ToolbarAct {
    Run,
    DryRun,
    /// Open the run-settings dialog without starting anything.
    RunSettings,
    Save,
    Close,
    /// Hand the named file (the last export) to the desktop's opener.
    OpenExport(String),
}

/// One results cell opened in the inspector window: the column header (title)
/// and the cell's full, unflattened (JSON-pretty-printed when applicable) value.
pub struct CellInspector {
    pub title: String,
    pub content: String,
}

/// The insert-palette popup state: where a new node lands, and whether we're on
/// the second step choosing a request name.
pub struct PaletteState {
    pub pos: InsertPos,
    /// `Some(report)` once a REQUEST / REPORT REQUEST kind is chosen and we're
    /// picking its name (`report` distinguishes the two).
    pub pick_request: Option<bool>,
    /// The free-text request name while picking (seeded from the first bound
    /// request, editable).
    pub request_name: String,
}

impl ReportEditor {
    /// Build an editor for a core [`Report`], parsing its text up front.
    pub fn new(origin: ReportOrigin, report: Report) -> Self {
        let mut ed = Self {
            origin,
            report,
            view: EditorView::Blocks,
            flow: None,
            parse_error: None,
            parse_error_line: None,
            diagnostics: Vec::new(),
            helpers: Vec::new(),
            diag_key: None,
            hl_cache: None,
            selection: Vec::new(),
            palette: None,
            undo: Vec::new(),
            result: None,
            progress: None,
            run: None,
            results_exported: false,
            last_export: None,
            results_filter: 0,
            results_find: String::new(),
            results_detail: None,
            results_textures: std::collections::HashMap::new(),
            wizard: None,
            diag_h: 132.0,
            summary_h: 240.0,
            detail_h: 320.0,
            palette_w: 168.0,
            inspector: None,
            dry_run: None,
            param_values: Default::default(),
            result_params: Vec::new(),
            params_seeded: false,
            params_sig: String::new(),
            params_confirmed: false,
            params_modal: None,
            pending_toolbar: None,
        };
        ed.reparse();
        ed
    }

    /// What this editor's run is filed under while the editor isn't on screen.
    pub fn run_key(&self) -> RunKey {
        RunKey::of(&self.report)
    }

    /// Lift the run out of the editor so it can outlive it.
    ///
    /// Called when the editor is closed or replaced. Everything about a *run*
    /// moves out; everything about the *view* (selection, palette, undo) goes
    /// with the editor, because it is rebuilt from the report text anyway.
    pub fn park_run(&mut self) -> ParkedRun {
        ParkedRun {
            result: self.result.take(),
            progress: self.progress.take(),
            run: self.run.take(),
            results_exported: self.results_exported,
            last_export: self.last_export.clone(),
            params: std::mem::take(&mut self.param_values),
        }
    }

    /// Take back a run parked earlier, so reopening a report shows the rows it
    /// collected while you were elsewhere — and keeps streaming if it is still
    /// going.
    pub fn adopt_run(&mut self, parked: ParkedRun) {
        self.result = parked.result;
        self.progress = parked.progress;
        self.run = parked.run;
        self.results_exported = parked.results_exported;
        self.last_export = parked.last_export;
        if !parked.params.is_empty() {
            self.param_values = parked.params;
            // Already answered: don't overwrite them from the remembered set.
            self.params_seeded = true;
        }
        if self.result.is_some() {
            self.view = EditorView::Results;
        }
    }

    /// The report file path this editor is bound to, if any.
    pub fn path(&self) -> Option<&std::path::Path> {
        self.report.path.as_deref()
    }

    /// Whether this editor was opened from a Workspace tree (so it closes when
    /// the user navigates away in that tab).
    pub fn is_workspace(&self) -> bool {
        matches!(self.origin, ReportOrigin::Workspace)
    }

    /// Re-parse `report.text` into the AST cache and parse-error state.
    fn reparse(&mut self) {
        match self.report.flow() {
            Ok(flow) => {
                self.flow = Some(flow);
                self.parse_error = None;
                self.parse_error_line = None;
            }
            Err(e) => {
                self.flow = None;
                self.parse_error = Some(e.to_string());
                self.parse_error_line = Some(e.line);
            }
        }
        // Answers are confirmed against the questions that were asked. Change
        // what the report declares — a new parameter, a different set of
        // choices — and the next run asks again; change anything else and it
        // doesn't, so editing a report between runs isn't a interrogation.
        // Only judged when the text parses: an edit caught mid-keystroke has
        // no declarations to compare, and re-asking every time a report is
        // momentarily unparseable would ask on nearly every keystroke.
        let Some(sig) = self.param_signature() else {
            return;
        };
        if sig != self.params_sig {
            self.params_sig = sig;
            self.params_confirmed = false;
            // A parameter that has just appeared has no value yet.
            self.params_seeded = false;
        }
    }

    /// What this report asks, as one string: every declaration's name, type and
    /// default. Compared rather than inspected, so it only has to be stable.
    fn param_signature(&self) -> Option<String> {
        let flow = self.flow.as_ref()?;
        Some(
            flow.params()
                .iter()
                .map(|p| {
                    // The *whole* kind, not just its keyword: adding an option to a
                    // CHOICE changes what is being asked as much as a new
                    // parameter does.
                    format!(
                        "{}:{:?}:{}",
                        p.name,
                        p.kind,
                        p.default.as_deref().unwrap_or("")
                    )
                })
                .collect::<Vec<_>>()
                .join("\n"),
        )
    }

    /// Set the report text (marking it dirty) and re-parse.
    fn set_text(&mut self, text: String) {
        self.report.set_text(text);
        self.reparse();
    }

    /// Push the current text onto the undo stack, then apply a structural edit
    /// to the AST via `f` and re-serialize. Keeps the two views round-tripping.
    /// A no-op edit (one whose re-serialized text is unchanged) is dropped
    /// entirely — it neither marks the report dirty nor pushes an undo entry, so
    /// inline commits (e.g. blurring an `AS` field without changing it) are free.
    fn edit_flow(&mut self, f: impl FnOnce(&mut ReportFlow)) {
        let Some(mut flow) = self.flow.clone() else {
            return;
        };
        f(&mut flow);
        let new_text = flow.to_text();
        if new_text != self.report.text {
            self.undo.push(self.report.text.clone());
            self.set_text(new_text);
        }
    }

    /// Re-indent the source to its true block depth, as one undo step.
    ///
    /// Deliberately *not* routed through [`Self::edit_flow`]: that re-serializes
    /// the AST, which has nowhere to keep a body comment, so it would quietly
    /// delete them. [`indent::reformat`] only moves leading whitespace.
    /// `Ok(true)` when the text moved, `Ok(false)` when it was already tidy.
    /// The caller turns the outcome into a status so the message can be
    /// translated against the live language.
    fn reformat(&mut self) -> Result<bool, ReformatError> {
        match crate::report::indent::reformat(&self.report.text)? {
            Some(text) => {
                self.undo.push(self.report.text.clone());
                self.set_text(text);
                Ok(true)
            }
            None => Ok(false),
        }
    }

    /// Undo the last structural edit (or source change captured on the stack).
    fn undo(&mut self) {
        if let Some(prev) = self.undo.pop() {
            self.report.set_text(prev);
            self.reparse();
        }
    }

    /// Replace the node at `path` with `node` (from a configure wizard),
    /// re-select it, and mirror the result back into the session — the wizard
    /// module's single commit path into the editor's private edit machinery.
    pub(super) fn wizard_apply(&mut self, app: &mut GuiApp, path: &[usize], node: FlowNode) {
        self.edit_flow(|flow| {
            replace_node(flow, path, node);
        });
        self.selection = path.to_vec();
        sync_back(self, app);
    }

    /// Commit an arbitrary in-place flow mutation (undo-tracked) and mirror it
    /// back into the session — the wizard module's path for edits that tweak
    /// *part* of a node (e.g. a single `WITH` field) rather than replacing it
    /// wholesale like [`Self::wizard_apply`].
    pub(super) fn commit_edit(&mut self, app: &mut GuiApp, f: impl FnOnce(&mut ReportFlow)) {
        self.edit_flow(f);
        sync_back(self, app);
    }

    /// Whether a run is currently in flight.
    pub(super) fn is_running(&self) -> bool {
        self.run.as_ref().is_some_and(|h| !h.finished())
    }

    /// Whether the report can be run right now: it parses and carries no
    /// error-level diagnostics (an unbound collection is itself an error, so
    /// this also gates on binding).
    fn can_run(&self) -> bool {
        self.flow.is_some()
            && self
                .diagnostics
                .iter()
                .all(|d| d.severity != Severity::Error)
    }

    /// Whether this report declares any `PARAM`s — the question every "should
    /// the run settings be here?" decision asks.
    pub fn has_params(&self) -> bool {
        self.flow.as_ref().is_some_and(|f| !f.params().is_empty())
    }

    /// The run settings form: one row per declared parameter, built fresh from
    /// the flow and the chosen values (never cached, so it can't drift from the
    /// source) by the same shared builder the terminal UI uses.
    pub fn param_rows(&self, s: &Strings) -> Vec<crate::report::params::ParamRow> {
        let Some(flow) = self.flow.as_ref() else {
            return Vec::new();
        };
        crate::report::params::rows(&flow.params(), &self.param_values, s)
    }

    /// Fill in the values this report was last run with, once. Anything the
    /// remembered set doesn't cover keeps the declared default, so adding a
    /// parameter to a report someone has already run doesn't leave it blank —
    /// and nothing already chosen is overwritten, because the user's own answer
    /// outranks both.
    pub fn seed_params(&mut self, session: &crate::session::Session) {
        if self.params_seeded {
            return;
        }
        self.params_seeded = true;
        let Some(flow) = self.flow.as_ref() else {
            return;
        };
        let remembered = session.remembered_params(&self.report.param_key());
        let declared: Vec<(String, Option<String>)> = flow
            .params()
            .into_iter()
            .map(|p| (p.name.clone(), p.default.clone()))
            .collect();
        for (name, default) in declared {
            if self.param_values.contains_key(&name) {
                continue;
            }
            let value = remembered
                .get(&name)
                .cloned()
                .or(default)
                .unwrap_or_default();
            self.param_values.insert(name, value);
        }
    }

    /// Whether starting should stop at the questions first.
    ///
    /// Once per editing session, not once per run: the point of answering is to
    /// be able to preview, look, and run the same thing — being asked again
    /// between those two steps would make the preview meaningless as a
    /// confirmation. [`Self::reparse`] re-arms this when a declaration changes.
    fn run_needs_settings(&self) -> bool {
        !self.is_running() && !self.params_confirmed && self.has_params()
    }

    /// Whether the answers now differ from the ones the result on screen was
    /// produced with. False when there is nothing to compare against — a
    /// report that has never been run is not "changed".
    pub(super) fn params_changed_since_result(&self, s: &Strings) -> bool {
        if self.result_params.is_empty() || (self.result.is_none() && self.dry_run.is_none()) {
            return false;
        }
        let now: Vec<(String, String)> = self
            .param_rows(s)
            .iter()
            .map(|r| (r.name.clone(), r.value.clone()))
            .collect();
        now != self.result_params
    }

    /// Open the run-settings dialog, seeded with what the last run used.
    pub(super) fn open_param_modal(&mut self, app: &GuiApp, intent: RunIntent) {
        self.seed_params(&app.session);
        self.params_modal = Some(intent);
    }

    /// The chosen values in one line — `REGION=au · TICKET=FR-12` — for the
    /// toolbar, so what the next run will use is on screen without opening
    /// anything.
    pub(super) fn param_summary(&self, s: &Strings) -> String {
        self.param_rows(s)
            .iter()
            .map(|r| {
                let v = if r.value.is_empty() {
                    s.param_value_unset
                } else {
                    r.value.as_str()
                };
                format!("{}={}", r.name, v)
            })
            .collect::<Vec<_>>()
            .join(" · ")
    }

    /// Start a background run of the current flow, switching to the Results view.
    /// A blocked run (unbound / no inputs) reports why in the status line.
    fn start_run(&mut self, app: &mut GuiApp) {
        let Some(flow) = self.flow.clone() else {
            return;
        };
        // The questions first — see `run_needs_settings`. Asking discards
        // nothing, so this happens before any result is cleared below.
        if self.run_needs_settings() {
            self.open_param_modal(app, RunIntent::Run);
            return;
        }
        let rows = self.param_rows(&app.strings);
        if let Some(problem) = rows
            .iter()
            .find_map(|r| r.problem.as_ref().map(|p| format!("{}: {p}", r.prompt)))
        {
            // Refuse rather than run: a report that asks for something and is
            // given nothing produces plausible-looking rows built around a hole.
            app.session.status = Some(Status::ReportRunBlocked(problem));
            self.open_param_modal(app, RunIntent::Run);
            return;
        }
        // Remember the answers for next time, keyed by the report (path → git
        // origin → name) rather than by its process-unique id.
        let chosen: crate::report::params::ParamValues = rows
            .iter()
            .map(|r| (r.name.clone(), r.value.clone()))
            .collect();
        if app
            .session
            .remember_params(&self.report.param_key(), &chosen)
        {
            app.session.save();
        }
        self.result_params = rows
            .iter()
            .map(|r| (r.name.clone(), r.value.clone()))
            .collect();
        match context::report_run_inputs(
            &app.session.collections,
            &app.session.global_envs,
            app.session.active_env_id,
            &flow,
            self.report.path.as_deref(),
        ) {
            Ok(mut inputs) => {
                // Only the app knows the chosen language; the run's own errors
                // are user-facing text like any other.
                inputs.language = app.session.language.clone();
                inputs.params = chosen;
                self.result = None;
                self.progress = None;
                self.results_exported = false;
                self.last_export = None;
                // The old result's filters and panels described the old rows.
                self.results_filter = 0;
                self.results_find.clear();
                self.results_detail = None;
                self.results_textures.clear();
                // A real run supersedes any preview of it.
                self.dry_run = None;
                self.view = EditorView::Results;
                self.run = Some(report_run::spawn(inputs));
                app.session.status = Some(Status::ReportRunning);
            }
            Err(context::RunInputError::Unbound) => {
                app.session.status = Some(Status::ReportRunBlocked(
                    app.strings.report_run_unbound.to_string(),
                ));
            }
        }
    }

    /// Hand a finished preview to the Results view and switch to it.
    ///
    /// The Dry run button sits on the toolbar above *every* view, but the
    /// preview is rendered by the Results view — so without this the button
    /// does nothing visible when pressed from Blocks or Source, which is
    /// exactly where it is pressed from.
    fn show_preview(&mut self, preview: Box<crate::report::dry_run::DryRunReport>) {
        self.dry_run = Some(preview);
        self.view = EditorView::Results;
    }

    /// Expand the flow with no HTTP and show the preview in the Results view.
    ///
    /// Runs on the calling thread rather than through
    /// [`report_run::spawn`]'s worker: a dry run sends nothing, so it finishes
    /// in the time it takes to walk the flow, and making the user wait on a
    /// background thread for that would only add a frame of latency and a
    /// second run-state to reason about.
    fn start_dry_run(&mut self, app: &mut GuiApp) {
        use crate::report::run::{DryRunner, RunContext, run_flow_raw};

        let Some(flow) = self.flow.clone() else {
            return;
        };
        // A preview is only worth looking at if it previews the run you mean,
        // so the questions are asked here too -- once, shared with Run.
        if self.run_needs_settings() {
            self.open_param_modal(app, RunIntent::DryRun);
            return;
        }
        // The preview answers the same questions the real run will, so it has
        // to be given the same values -- a dry run against unset parameters
        // would describe a flow nobody is going to run.
        let rows = self.param_rows(&app.strings);
        let chosen: crate::report::params::ParamValues = rows
            .iter()
            .map(|r| (r.name.clone(), r.value.clone()))
            .collect();
        self.result_params = rows
            .iter()
            .map(|r| (r.name.clone(), r.value.clone()))
            .collect();
        match context::report_run_inputs(
            &app.session.collections,
            &app.session.global_envs,
            app.session.active_env_id,
            &flow,
            self.report.path.as_deref(),
        ) {
            Ok(inputs) => {
                let strings = Strings::for_language(&app.session.language);
                let ctx = RunContext {
                    entries: &inputs.entries,
                    helpers: &inputs.helpers,
                    base_vars: inputs.base_vars.clone(),
                    named_envs: inputs.named_envs.clone(),
                    root: inputs.root.clone(),
                    runner: &DryRunner,
                    strings: &strings,
                    params: chosen,
                    sink: None,
                };
                let result = run_flow_raw(&inputs.flow, &ctx);
                // The non-blocking variable-availability warnings are worth
                // showing here even though they never stop a run: a preview is
                // exactly when you want to hear about a `{{VAR}}` that might
                // not be set by the time its request goes out.
                let var_warnings: Vec<String> = self
                    .diagnostics
                    .iter()
                    .filter(|d| d.severity == Severity::Warning)
                    .map(|d| d.message.clone())
                    .collect();
                self.show_preview(Box::new(crate::report::dry_run::DryRunReport::from_result(
                    result,
                    flow.header.clone(),
                    var_warnings,
                )));
            }
            Err(context::RunInputError::Unbound) => {
                app.session.status = Some(Status::ReportRunBlocked(
                    app.strings.report_run_unbound.to_string(),
                ));
            }
        }
    }

    /// Stop an in-flight run, retaining whatever partial grid has streamed in.
    ///
    /// The handle is retired *now* — cancelled and dropped, taking our end of
    /// the channel with it — rather than left in place until the worker's `Done`
    /// arrives. Cancelling only stops new requests being fired; an in-flight one
    /// still has to finish, and a `PARALLEL` batch can take a while to wind
    /// down, during which `is_running()` would keep reporting the run as live
    /// and the Run button would stay a Stop button. Retiring immediately means
    /// the very next click starts a fresh run. The detached worker keeps
    /// draining in the background; its remaining messages land on a dropped
    /// receiver and are ignored. Mirrors the TUI's `prepare_report_run`.
    fn stop_run(&mut self, app: &mut GuiApp) {
        if let Some(h) = self.run.take() {
            h.cancel();
        }
        // Clear streaming progress so no row is left rendering as "running".
        // The partial grid in `self.result` is intentionally kept.
        self.progress = None;
        app.session.status = Some(Status::ReportRunStopped);
    }

    /// Drain the run channel this frame, folding streamed rows into the grid.
    /// Returns `true` while the run is still live (so the caller keeps
    /// repainting). Retires the handle once the run finishes or disconnects.
    fn poll_run(&mut self, app: &mut GuiApp) -> bool {
        let Some(handle) = self.run.as_mut() else {
            return false;
        };
        match report_run::drain(handle, &mut self.result, &mut self.progress) {
            report_run::Drained::Progress { done, total } => {
                app.session.status = Some(Status::ReportRunProgress { done, total });
            }
            report_run::Drained::Done { rows, errors } => {
                app.session.status = Some(Status::ReportRunDone { rows, errors });
            }
            report_run::Drained::Disconnected => {
                self.run = None;
                return false;
            }
            report_run::Drained::Idle => {}
        }
        if handle.finished() {
            self.run = None;
            false
        } else {
            true
        }
    }
}

fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
    let l = |x: u8, y: u8| (x as f32 * (1.0 - t) + y as f32 * t).round() as u8;
    Color32::from_rgb(l(a.r(), b.r()), l(a.g(), b.g()), l(a.b(), b.b()))
}

/// A colour for a palette block, by category — matches [`node_chips`] so a
/// palette chip reads the same colour as the block it inserts.
fn kind_color(kind: NodeKind, th: &GuiTheme) -> Color32 {
    match kind {
        NodeKind::Request | NodeKind::ReportRequest => th.ok,
        NodeKind::ReportVar | NodeKind::ReportComputed => th.subst,
        NodeKind::Assign => th.accent,
        NodeKind::ForFiles | NodeKind::ForFolders | NodeKind::ForEnvs => th.accent,
        NodeKind::List => th.pending,
    }
}

/// Build the [`FlowNode`] a dropped/clicked palette `kind` inserts. Request
/// kinds pick up a default name from the bound collection (first request, else a
/// `request` placeholder shown amber until the user edits it inline).
fn node_for_kind(kind: NodeKind, titles: &[String]) -> FlowNode {
    if kind.needs_request() {
        let name = titles
            .first()
            .cloned()
            .unwrap_or_else(|| "request".to_string());
        request_node(&name, matches!(kind, NodeKind::ReportRequest))
    } else {
        kind.template()
            .unwrap_or_else(|| request_node("request", false))
    }
}

/// A drag payload for an *existing* in-report item (as opposed to the palette's
/// `NodeKind` / `Modifier` payloads for adding new ones). Dragging a base chip
/// carries its whole row (to reorder it onto a drop strip, or bin it); dragging
/// a modifier chip carries the detach it represents (to bin it off its node).
#[derive(Clone, PartialEq, Eq)]
enum DragItem {
    /// A whole block/row identified by its path — reorder or delete.
    Row(Vec<usize>),
    /// A modifier chip on the node at `path` — detach (bin) it.
    Chip {
        path: Vec<usize>,
        which: DetachWhich,
    },
}

/// One chip in a row's chip cluster (a compositional block is drawn as several
/// chips side by side). Exactly one chip per node is the *base* (the editable
/// subject: click it to select the row, double-click to open its wizard); the
/// rest are modifier chips, each of which may carry a detach (`×`) action.
struct Chip {
    text: String,
    color: Color32,
    /// The editable subject chip (selects the row; its wizard opens on
    /// double-click; it is the row's drag handle for reordering).
    is_base: bool,
    /// `Some(which)` shows a `×` that detaches this modifier from the node.
    detach: Option<DetachWhich>,
    /// An optional inline dropdown replacing part of the chip label with a
    /// picker (e.g. the request name, or a BASELINE/COMPARISON environment).
    edit: ChipEdit,
    /// Hover help: what this chip is, and what its editable parts do. Empty for
    /// a chip whose meaning is already spelled out by its own label.
    help: &'static str,
    /// This chip qualifies the one immediately before it rather than the node
    /// as a whole, so it is drawn tucked against it and joined to it by a
    /// bracket. Without that, `BASELINE(prod) SHOW(Time) COMPARISON(stage)`
    /// reads as three peers in a row and the SHOW looks like it governs all of
    /// them.
    tethered: bool,
    /// Whether this chip is drawn merged with its neighbour into one segmented
    /// pill: the joined edge is squared off so the pair shares a single
    /// outline. Derived from [`Chip::tethered`] by [`link_tethers`] rather than
    /// set at construction, because it depends on the neighbours — and it is
    /// cleared again wherever the pair is being pulled apart, so a chip is
    /// never drawn joined to something that has left its slot.
    join_prev: bool,
    join_next: bool,
    /// This chip's row is the one under the pointer, or travels with it. Drawn
    /// in a stronger version of its own colour — see [`chip_colors`]. Set by
    /// the row loop from *last* frame's hover group, because which rows light
    /// up isn't known until every row has been measured (see
    /// [`paint_hover_group`]).
    hovered: bool,
}

impl Chip {
    /// Mark this chip as belonging to the one before it (see
    /// [`Chip::tethered`]).
    fn tether(mut self) -> Chip {
        self.tethered = true;
        self
    }
}

impl Chip {
    /// Attach hover help, so the chip constructors stay short at their call
    /// sites (`Chip::modifier(…).with_help(s.chip_help_report)`).
    fn with_help(mut self, help: &'static str) -> Chip {
        self.help = help;
        self
    }
}

/// The inline picker a chip hosts, if any. The chip still shows a keyword prefix
/// (`REQUEST`, `BASELINE`, …) as a drag/select handle; the enumerable part
/// becomes a combo box the user picks from.
#[derive(Clone)]
enum ChipEdit {
    None,
    /// A request-name dropdown: the prefix is `REQUEST`, the combo lists the
    /// bound collection's request titles. Carries the current name.
    Request {
        name: String,
    },
    /// A `BASELINE`/`COMPARISON` environment dropdown for the role ref at
    /// `index` (an `Env(…)` ref); the combo lists the loaded environments.
    EnvRole {
        baseline: bool,
        index: usize,
        name: String,
    },
    /// An inline editable `AS <alias>` field: the prefix is `AS`, followed by a
    /// text box that commits the alias/name on blur.
    Alias {
        text: String,
    },
    /// The `PARALLEL` modifier's optional max-concurrency: the prefix is
    /// `PARALLEL`, followed by a small numeric box. Empty means "no explicit
    /// limit" (plain `PARALLEL`), which the runner resolves from the prelude's
    /// `MAX_PARALLEL`; `degree` carries the current value.
    Parallel {
        degree: Option<u32>,
    },
    /// A `FOR` loop head, broken into the parts of it that are worth editing in
    /// place: the loop variable, and — for the producers that draw from one
    /// path — that path, with a picker beside it, plus a `FILES` loop's `MATCH`
    /// glob.
    ///
    /// The point is legibility as much as convenience: a loop head rendered as
    /// one long label gave no hint that the folder or the variable name were
    /// things you could change, so both were only ever found through the
    /// wizard. Boxes look editable.
    Loop(LoopEdit),
}

/// The editable parts of a `FOR` loop head (see [`ChipEdit::Loop`]).
#[derive(Clone)]
struct LoopEdit {
    /// The loop variable, when the pattern binds exactly one name. `None` for a
    /// destructuring pattern (`FOR (A, B) IN …`) or a `_` discard, where one
    /// box could not say which binder it meant — those keep to the wizard.
    var: Option<String>,
    /// The keyword between the variable and the source: `IN FILES`, `IN ENVS`,
    /// `IN TUPLES FROM`, or plain `IN`.
    keyword: String,
    /// The single folder/file the loop draws from, and whether it is a file
    /// (`TUPLES FROM`) rather than a folder, which decides which picker opens.
    dir: Option<(String, bool)>,
    /// A `FILES` loop's `MATCH` glob. `Some("")` when the loop is a `FILES` one
    /// with no glob yet (so the box is offered); `None` when the producer has
    /// no glob at all.
    glob: Option<String>,
    /// Whatever the producer is when it can't be broken up — a list literal, a
    /// `ZIP`/`CONCAT`, or a named `LIST`. Shown as a plain label after the
    /// keyword.
    tail: String,
}

impl Chip {
    /// The chip's label and the extra width its inline editor occupies, for
    /// drawing a same-sized placeholder of it.
    ///
    /// Several chips keep their keyword in [`ChipEdit`] rather than in `text`
    /// (a `PARALLEL` chip's `text` is empty — its label and numeric box are both
    /// drawn by `parallel_chip`), so a ghost built from `text` alone came out a
    /// thin sliver rather than the size of the block that will land there.
    fn ghost_shape(&self) -> (String, f32) {
        match &self.edit {
            ChipEdit::None => (self.text.clone(), 0.0),
            ChipEdit::Request { name } => (format!("{} {name}", self.text), COMBO_CHIP_WIDTH),
            ChipEdit::EnvRole { name, .. } => (format!("{} {name}", self.text), COMBO_CHIP_WIDTH),
            ChipEdit::Alias { text } => (format!("AS {text}"), ALIAS_FIELD_WIDTH),
            ChipEdit::Parallel { degree } => (
                degree
                    .map(|n| format!("PARALLEL({n})"))
                    .unwrap_or_else(|| "PARALLEL".to_string()),
                PARALLEL_FIELD_WIDTH,
            ),
            ChipEdit::Loop(l) => {
                let mut label = "FOR".to_string();
                let mut extra = 0.0;
                if let Some(v) = &l.var {
                    label.push(' ');
                    label.push_str(v);
                    extra += LOOP_VAR_FIELD_WIDTH;
                }
                label.push(' ');
                label.push_str(&l.keyword);
                if let Some((dir, _)) = &l.dir {
                    label.push(' ');
                    label.push_str(dir);
                    // The box and the picker button beside it.
                    extra += LOOP_PATH_FIELD_WIDTH + PICKER_BUTTON_WIDTH;
                }
                if let Some(g) = &l.glob {
                    label.push_str(" MATCH ");
                    label.push_str(g);
                    extra += LOOP_GLOB_FIELD_WIDTH;
                }
                if !l.tail.is_empty() {
                    label.push(' ');
                    label.push_str(&l.tail);
                }
                (label, extra)
            }
        }
    }

    fn base(text: String, color: Color32) -> Chip {
        Chip {
            text,
            color,
            is_base: true,
            detach: None,
            edit: ChipEdit::None,
            help: "",
            tethered: false,
            join_prev: false,
            join_next: false,
            hovered: false,
        }
    }
    fn modifier(text: String, color: Color32, which: DetachWhich) -> Chip {
        Chip {
            text,
            color,
            is_base: false,
            detach: Some(which),
            edit: ChipEdit::None,
            help: "",
            tethered: false,
            join_prev: false,
            join_next: false,
            hovered: false,
        }
    }
    /// The request base chip, whose name is picked from an inline dropdown.
    fn request(name: &str, color: Color32) -> Chip {
        Chip {
            text: format!("REQUEST {name}"),
            color,
            is_base: true,
            detach: None,
            edit: ChipEdit::Request {
                name: name.to_string(),
            },
            help: "",
            tethered: false,
            join_prev: false,
            join_next: false,
            hovered: false,
        }
    }
    /// A `BASELINE`/`COMPARISON` chip carrying a single-environment dropdown.
    /// Detachable: dragging it out (or clicking its `×`) drops that role, which
    /// leaves the loop iterating whatever environments remain.
    fn env_role(baseline: bool, index: usize, name: &str, color: Color32) -> Chip {
        let kw = if baseline { "BASELINE" } else { "COMPARISON" };
        Chip {
            text: format!("{kw}({name})"),
            color,
            is_base: false,
            detach: Some(DetachWhich::Role { baseline, index }),
            edit: ChipEdit::EnvRole {
                baseline,
                index,
                name: name.to_string(),
            },
            help: "",
            tethered: false,
            join_prev: false,
            join_next: false,
            hovered: false,
        }
    }
    /// An `AS <alias>` chip whose alias is edited inline. `detach` is `Some(As)`
    /// for an optional alias (a report request / reported variable) and `None`
    /// for a required one (a computed column, whose `AS` name can't be removed).
    fn alias(text: &str, color: Color32, detach: Option<DetachWhich>) -> Chip {
        Chip {
            text: String::new(),
            color,
            is_base: false,
            detach,
            edit: ChipEdit::Alias {
                text: text.to_string(),
            },
            help: "",
            tethered: false,
            join_prev: false,
            join_next: false,
            hovered: false,
        }
    }
    /// A `FOR` loop head whose variable, folder and glob are edited inline.
    /// Still the row's base chip, so it stays the drag/select handle.
    fn loop_head(edit: LoopEdit, color: Color32) -> Chip {
        Chip {
            text: String::new(),
            color,
            is_base: true,
            detach: None,
            edit: ChipEdit::Loop(edit),
            help: "",
            tethered: false,
            join_prev: false,
            join_next: false,
            hovered: false,
        }
    }
    /// A `PARALLEL` chip whose concurrency limit is edited inline.
    fn parallel(degree: Option<u32>, color: Color32) -> Chip {
        Chip {
            text: String::new(),
            color,
            is_base: false,
            detach: Some(DetachWhich::Parallel),
            edit: ChipEdit::Parallel { degree },
            help: "",
            tethered: false,
            join_prev: false,
            join_next: false,
            hovered: false,
        }
    }
}

/// Break a `FOR` loop head into the parts the chip edits in place.
///
/// `envs` marks the `FOR … IN ENVS` form, whose source is a clause rendered as
/// its own `BASELINE`/`COMPARISON` chips rather than a path, so it contributes
/// only the variable and the keyword.
fn loop_edit_parts(node: &FlowNode, envs: bool) -> LoopEdit {
    use crate::report::flow::{Binder, Producer};

    // Only a pattern binding exactly one name can be edited through one box.
    let var = match node {
        FlowNode::ForEnvs { var, .. } => Some(var.clone()),
        FlowNode::ForEach { pattern, .. } => match (pattern.rest, pattern.binders.as_slice()) {
            (false, [Binder::Named(n)]) => Some(n.clone()),
            _ => None,
        },
        _ => None,
    };
    if envs {
        // A `Roles` clause is drawn as its own BASELINE/COMPARISON chips beside
        // this one, so the head carries nothing more. A `Plain` list of
        // environment names has no chips of its own and would otherwise vanish,
        // so it is shown as the tail.
        let tail = match node {
            FlowNode::ForEnvs {
                clause: crate::report::flow::EnvClause::Plain(names),
                ..
            } => names
                .iter()
                .map(|n| format!("\"{n}\""))
                .collect::<Vec<_>>()
                .join(", "),
            _ => String::new(),
        };
        return LoopEdit {
            var,
            keyword: "IN ENVS".to_string(),
            dir: None,
            glob: None,
            tail,
        };
    }
    let FlowNode::ForEach { producer, .. } = node else {
        return LoopEdit {
            var,
            keyword: "IN".to_string(),
            dir: None,
            glob: None,
            tail: String::new(),
        };
    };
    match producer {
        // `FILES` always offers the glob box, even when the loop has no MATCH
        // yet: an empty box invites the glob, where nothing at all hides that
        // the loop can be narrowed.
        Producer::Files { dir, glob } => LoopEdit {
            var,
            keyword: "IN FILES".to_string(),
            dir: Some((dir.clone(), false)),
            glob: Some(glob.clone().unwrap_or_default()),
            tail: String::new(),
        },
        // `FOLDERS` takes the same `MATCH` glob as `FILES` (matching the folder
        // name, and recursing when it contains `**`), so it gets the same box.
        // Its `WITH role="glob"` list is several named globs rather than one, so
        // that part stays in the wizard and is shown as the tail.
        Producer::Folders { dir, glob, roles } => LoopEdit {
            var,
            keyword: "IN FOLDERS".to_string(),
            dir: Some((dir.clone(), false)),
            glob: Some(glob.clone().unwrap_or_default()),
            tail: if roles.is_empty() {
                String::new()
            } else {
                let rs: Vec<String> = roles.iter().map(role_label).collect();
                format!("WITH {}", rs.join(", "))
            },
        },
        Producer::Tuples { path } => LoopEdit {
            var,
            keyword: "IN TUPLES FROM".to_string(),
            // A file, so the picker opens a file dialog rather than a folder one.
            dir: Some((path.clone(), true)),
            glob: None,
            tail: String::new(),
        },
        // No single path to point at: shown whole, as before.
        other => LoopEdit {
            var,
            keyword: "IN".to_string(),
            dir: None,
            glob: None,
            tail: producer_label(other),
        },
    }
}

/// A producer with no single path, rendered as the label the loop head used to
/// carry. Mirrors `flow::producer_text`, which is private to the model.
/// A single `WITH` role binding as it is written in the source, so the chip's
/// tail reads back exactly what the file says — including the `?` that marks a
/// role as optional.
fn role_label(r: &crate::report::flow::RoleBinding) -> String {
    let opt = if r.optional { "?" } else { "" };
    format!("{}=\"{}\"{opt}", r.name, r.glob)
}

fn producer_label(p: &crate::report::flow::Producer) -> String {
    use crate::report::flow::{Element, Producer};
    fn element(e: &Element) -> String {
        match e {
            Element::Scalar(s) => format!("\"{s}\""),
            Element::Tuple(parts) => {
                let items: Vec<String> = parts.iter().map(|s| format!("\"{s}\"")).collect();
                format!("({})", items.join(", "))
            }
        }
    }
    match p {
        Producer::List(elems) => {
            let items: Vec<String> = elems.iter().map(element).collect();
            format!("[{}]", items.join(", "))
        }
        Producer::Zip(ps) => {
            let items: Vec<String> = ps.iter().map(producer_label).collect();
            format!("ZIP({})", items.join(", "))
        }
        Producer::Concat(ps) => {
            let items: Vec<String> = ps.iter().map(producer_label).collect();
            format!("CONCAT({})", items.join(", "))
        }
        Producer::Named(n) => n.clone(),
        Producer::Files { dir, glob } => match glob {
            Some(g) => format!("FILES \"{dir}\" MATCH \"{g}\""),
            None => format!("FILES \"{dir}\""),
        },
        Producer::Folders { dir, glob, .. } => match glob {
            Some(g) => format!("FOLDERS \"{dir}\" MATCH \"{g}\""),
            None => format!("FOLDERS \"{dir}\""),
        },
        Producer::Tuples { path } => format!("TUPLES FROM \"{path}\""),
    }
}

/// Decompose a node into its chip cluster: the leading modifier chips, the
/// editable base chip, and any trailing modifier chips (`AS`, `WITH …`).
fn node_chips(
    node: &FlowNode,
    req_ok: Option<bool>,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
) -> Vec<Chip> {
    let req_col = |ok: Option<bool>| match ok {
        Some(true) => th.ok,
        Some(false) => th.pending,
        None => th.ok,
    };
    let mut chips = build_node_chips(node, req_col(req_ok), th, s);
    // The rule for whether a chip can be pulled out of a line on its own: only
    // if the statement still stands without it. `REPORT` on a reported *column*
    // is the case that matters — take it away and there is no statement left at
    // all — so grabbing that chip has to move the whole row instead of
    // half-deleting it. Applied centrally rather than at each construction site
    // so it can't be forgotten for a chip added later.
    for chip in &mut chips {
        if let Some(which) = chip.detach
            && !crate::report::edit::detach_leaves_statement(node, which)
        {
            chip.detach = None;
        }
    }
    chips
}

/// The chips a node is drawn as, before the load-bearing rule in [`node_chips`]
/// is applied. `req_col` is the colour a request chip takes (its last run's
/// outcome), already resolved by the caller.
fn build_node_chips(
    node: &FlowNode,
    req_col: Color32,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
) -> Vec<Chip> {
    match node {
        // One chip holding the comment verbatim. It has no detachable parts —
        // a comment is text, not a statement with clauses — but it is a block
        // like any other, so it can be dragged, moved and deleted.
        FlowNode::Comment(text) => {
            vec![Chip::base(format!("#{text}"), th.dim).with_help(s.chip_help_comment)]
        }
        FlowNode::Request { name } => {
            vec![Chip::request(name, req_col).with_help(s.chip_help_request)]
        }
        FlowNode::Report(ReportStmt::Request {
            name,
            alias,
            response_fmt,
            show,
            hide,
            with,
        }) => {
            let mut chips = vec![
                Chip::modifier("REPORT".into(), th.subst, DetachWhich::Report)
                    .with_help(s.chip_help_report),
            ];
            chips.push(Chip::request(name, req_col).with_help(s.chip_help_request));
            // RESPONSE / SHOW / HIDE are their own detachable chips so a long
            // reported request reads as a row of small, legible clauses rather
            // than one dense line.
            if let Some(fmt) = response_fmt {
                let text = match fmt {
                    crate::report::flow::ResponseFmt::Raw => "RESPONSE RAW",
                    crate::report::flow::ResponseFmt::Pretty => "RESPONSE PRETTY",
                };
                chips.push(
                    Chip::modifier(text.into(), th.accent, DetachWhich::Response)
                        .with_help(s.chip_help_response),
                );
            }
            if !show.is_empty() {
                chips.push(
                    Chip::modifier(
                        format!("SHOW({})", crate::report::flow::show_text(show)),
                        th.ok,
                        DetachWhich::Show,
                    )
                    .with_help(s.chip_help_show),
                );
            }
            if !hide.is_empty() {
                chips.push(
                    Chip::modifier(
                        format!("HIDE({})", hide.join(", ")),
                        th.dim,
                        DetachWhich::Hide,
                    )
                    .with_help(s.chip_help_hide),
                );
            }
            if let Some(a) = alias {
                chips.push(
                    Chip::alias(a, th.pending, Some(DetachWhich::As)).with_help(s.chip_help_alias),
                );
            }
            // The `WITH … END` fields are rendered as a *nested block* under the
            // request line (see `with_block` in `block_row`); the line itself
            // only carries the opening `WITH` keyword so it reads like the
            // textual form (`… SHOW(Time) WITH`).
            if !with.is_empty() {
                chips.push(
                    Chip::modifier("WITH".into(), th.accent, DetachWhich::WithBlock)
                        .with_help(s.chip_help_with),
                );
            }
            chips
        }
        FlowNode::Report(ReportStmt::Vars(vars)) => {
            let text = if vars.len() == 1 {
                vars[0].clone()
            } else {
                format!("({})", vars.join(", "))
            };
            // The reported value is a plain identifier (a loop var / raw name),
            // so it reads in the neutral text colour — matching the terminal UI
            // and keeping it distinct from the `REPORT` keyword's own colour.
            vec![
                Chip::modifier("REPORT".into(), th.subst, DetachWhich::Report)
                    .with_help(s.chip_help_report),
                Chip::base(text, th.text).with_help(s.chip_help_var),
            ]
        }
        FlowNode::Report(ReportStmt::VarAs {
            var,
            name,
            stats,
            image,
            truth,
            detail,
        }) => {
            let mut chips = vec![
                Chip::modifier("REPORT".into(), th.subst, DetachWhich::Report)
                    .with_help(s.chip_help_report),
                Chip::base(var.clone(), th.text).with_help(s.chip_help_var),
                Chip::alias(name, th.pending, Some(DetachWhich::As)).with_help(s.chip_help_alias),
            ];
            chips.extend(stats_chip(stats, th, s));
            chips.extend(clause_chips(
                image.as_ref(),
                truth.as_deref(),
                *detail,
                th,
                s,
            ));
            chips
        }
        FlowNode::Report(ReportStmt::Computed {
            template,
            name,
            stats,
            image,
            truth,
            detail,
        }) => {
            let mut chips = vec![
                Chip::modifier("REPORT".into(), th.subst, DetachWhich::Report)
                    .with_help(s.chip_help_report),
                Chip::base(format!("\"{template}\""), th.text).with_help(s.chip_help_computed),
                // A computed column requires its AS name, so this chip is
                // inline-editable but never detachable.
                Chip::alias(name, th.pending, None).with_help(s.chip_help_alias_required),
            ];
            chips.extend(stats_chip(stats, th, s));
            chips.extend(clause_chips(
                image.as_ref(),
                truth.as_deref(),
                *detail,
                th,
                s,
            ));
            chips
        }
        // One chip carrying the whole declaration. Editing it is the run
        // settings panel's job, not the block editor's — what matters here is
        // that a parameter is visible as the first thing the report does.
        FlowNode::Param(_) => {
            vec![Chip::base(node.label(), th.pending).with_help(s.chip_help_param)]
        }
        FlowNode::Assign { .. } | FlowNode::ListDecl { .. } => {
            let (col, help) = if matches!(node, FlowNode::Assign { .. }) {
                (th.accent, s.chip_help_assign)
            } else {
                (th.pending, s.chip_help_list)
            };
            vec![Chip::base(node.label(), col).with_help(help)]
        }
        FlowNode::ForEach { parallel, .. } | FlowNode::ForEnvs { parallel, .. } => {
            let mut chips = Vec::new();
            if let Some(spec) = parallel {
                // PARALLEL is its own chip, and uses the theme's *error* hue so
                // it stands apart from the blue loop/set chips it sits beside
                // (`PARALLEL(8) FOR …`). The loop head below is built from the
                // node rather than from its label, so the prefix is never
                // duplicated and there is nothing to strip back off.
                chips.push(Chip::parallel(spec.degree, th.err).with_help(s.chip_help_parallel));
            }
            // For an ENVS comparison loop, split the BASELINE/COMPARISON clause
            // off the head into their own chips so a long compare line reads as
            // legible parts. They are edited through the ENVS wizard, so the
            // chips are fixed (no detach ×) — the base chip becomes just the
            // `FOR … IN ENVS` opener.
            if let FlowNode::ForEnvs {
                clause:
                    crate::report::flow::EnvClause::Roles {
                        baseline,
                        comparisons,
                        baseline_show,
                    },
                ..
            } = node
            {
                chips.push(
                    Chip::loop_head(loop_edit_parts(node, true), th.accent)
                        .with_help(s.chip_help_for_envs),
                );
                // A single live-environment role becomes an inline dropdown; any
                // other shape (multiple refs, or a FILE snapshot) stays a fixed
                // chip edited through the ENVS wizard.
                use crate::report::flow::RoleRef;
                if let [RoleRef::Env(name)] = baseline.as_slice() {
                    chips.push(
                        Chip::env_role(true, 0, name, th.pending).with_help(s.chip_help_baseline),
                    );
                } else if !baseline.is_empty() {
                    chips.push(
                        Chip::modifier(
                            format!("BASELINE({})", role_refs_text(baseline)),
                            th.pending,
                            DetachWhich::Role {
                                baseline: true,
                                index: 0,
                            },
                        )
                        .with_help(s.chip_help_roles_fixed),
                    );
                }
                // The SHOW belongs to the BASELINE, so it follows it directly —
                // before the COMPARISON, mirroring the source order — and is
                // *tethered* to it, which merges the two into one segmented pill
                // (see `link_tethers`). It keeps SHOW's own colour: the pill
                // already says which chip it qualifies, so the hue is free to go
                // on saying what kind of clause it is.
                if !baseline_show.is_empty() {
                    chips.push(
                        Chip::modifier(
                            format!("SHOW({})", crate::report::flow::show_text(baseline_show)),
                            th.ok,
                            DetachWhich::BaselineShow,
                        )
                        .with_help(s.chip_help_baseline_show)
                        .tether(),
                    );
                }
                if let [RoleRef::Env(name)] = comparisons.as_slice() {
                    chips.push(
                        Chip::env_role(false, 0, name, th.pending)
                            .with_help(s.chip_help_comparison),
                    );
                } else if !comparisons.is_empty() {
                    chips.push(
                        Chip::modifier(
                            format!("COMPARISON({})", role_refs_text(comparisons)),
                            th.pending,
                            DetachWhich::Role {
                                baseline: false,
                                index: 0,
                            },
                        )
                        .with_help(s.chip_help_roles_fixed),
                    );
                }
            } else {
                let envs = matches!(node, FlowNode::ForEnvs { .. });
                let help = if envs {
                    s.chip_help_for_envs
                } else {
                    s.chip_help_for
                };
                chips.push(Chip::loop_head(loop_edit_parts(node, envs), th.accent).with_help(help));
            }
            chips
        }
    }
}

/// The `STATISTICS(…)` chip for a named report column, or nothing when the
/// column has no statistics. Tethered, because the statistics belong to the
/// column named immediately before them rather than to the statement as a
/// whole — so the two are drawn as one segmented pill (see [`link_tethers`]).
fn stats_chip(
    stats: &[crate::report::model::StatKind],
    th: &GuiTheme,
    s: &crate::i18n::Strings,
) -> Option<Chip> {
    if stats.is_empty() {
        return None;
    }
    let list = stats
        .iter()
        .map(|k| k.keyword())
        .collect::<Vec<_>>()
        .join(", ");
    Some(
        Chip::modifier(
            format!("STATISTICS({list})"),
            th.subst,
            DetachWhich::Statistics,
        )
        .with_help(s.chip_help_statistics)
        .tether(),
    )
}

/// The `IMAGE` / `TRUTH` / `DETAIL` chips for one column, in the order they are
/// written. Tethered, like [`stats_chip`]: all four clauses belong to the
/// column named immediately before them rather than to the statement, so they
/// read as one segmented pill.
///
fn clause_chips(
    image: Option<&crate::report::flow::ImageSpec>,
    truth: Option<&str>,
    detail: bool,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
) -> Vec<Chip> {
    let mut out = Vec::new();
    if image.is_some() {
        out.push(
            Chip::modifier(
                crate::report::flow::image_text(image).trim().to_string(),
                th.subst,
                DetachWhich::Image,
            )
            .with_help(s.chip_help_image)
            .tether(),
        );
    }
    if truth.is_some() {
        out.push(
            Chip::modifier(
                crate::report::flow::truth_text(truth).trim().to_string(),
                th.subst,
                DetachWhich::Truth,
            )
            .with_help(s.chip_help_truth)
            .tether(),
        );
    }
    if detail {
        out.push(
            Chip::modifier("DETAIL".to_string(), th.subst, DetachWhich::Detail)
                .with_help(s.chip_help_detail)
                .tether(),
        );
    }
    out
}

/// Render a list of environment role refs for a BASELINE/COMPARISON chip: a
/// bare env name, or `FILE("…")` for a saved-snapshot reference.
fn role_refs_text(refs: &[crate::report::flow::RoleRef]) -> String {
    use crate::report::flow::RoleRef;
    refs.iter()
        .map(|r| match r {
            RoleRef::Env(n) => n.clone(),
            RoleRef::File(p) => format!("FILE(\"{p}\")"),
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// An action collected while rendering the (borrow-frozen) blocks, applied to
/// the editor afterwards.
enum Act {
    Select(Vec<usize>),
    OpenPalette(InsertPos),
    ClosePalette,
    PickKind(NodeKind),
    InsertRequest {
        report: bool,
        name: String,
    },
    /// Move the block at `path` up (`up`) or down among its siblings. The path
    /// is captured when the button is pressed rather than read back from the
    /// selection later, because a value commit applied first re-selects the
    /// field it wrote — the move has to act on what was highlighted on screen.
    Move {
        path: Vec<usize>,
        up: bool,
    },
    /// A palette block was dragged and dropped at `pos` (from the always-visible
    /// palette list). The node is built at drop time so request kinds pick up a
    /// default name from the bound collection.
    DropNode {
        pos: InsertPos,
        node: FlowNode,
    },
    /// A modifier chip (REPORT / PARALLEL / WITH / AS) was dragged onto the node
    /// at `path`, attaching it (see [`attach_modifier`]).
    AttachMod {
        path: Vec<usize>,
        modifier: Modifier,
    },
    /// A clause pulled off one line was dropped on another: move it there, or
    /// with `copy` (Shift held at the drop) leave the original in place and
    /// graft a duplicate (see [`transfer_modifier`]).
    MoveMod {
        from: Vec<usize>,
        which: DetachWhich,
        to: Vec<usize>,
        copy: bool,
    },
    /// A modifier chip's `×` was clicked, detaching it from the node at `path`
    /// (see [`detach_modifier`]).
    DetachMod {
        path: Vec<usize>,
        which: DetachWhich,
    },
    /// The request-name picker chose `name` for the node at `path`, renamed in
    /// place so a report request keeps its `AS` / `WITH` / `RESPONSE` modifiers.
    RenameRequest {
        path: Vec<usize>,
        name: String,
    },
    /// A `BASELINE`/`COMPARISON` env dropdown picked `name` for the role ref at
    /// `index` of the ENVS loop at `path` (see [`edit::set_env_role`]).
    SetEnvRole {
        path: Vec<usize>,
        baseline: bool,
        index: usize,
        name: String,
    },
    /// An existing block was dragged from `from` onto a drop strip, relocating
    /// it to `pos` (see [`edit::move_node_to`]).
    MoveNode {
        from: Vec<usize>,
        pos: InsertPos,
    },
    /// A block dragged onto the trash bin: delete the node at `path`.
    DeletePath(Vec<usize>),
    /// Open the configure wizard for the node at `path`.
    OpenWizard(Vec<usize>),
    /// The inline `AS` field committed a new alias/name for the node at `path`
    /// (see [`edit::set_report_alias`]).
    SetAlias {
        path: Vec<usize>,
        text: String,
    },
    /// One of the loop chip's inline boxes committed: the loop variable, the
    /// folder/file it draws from, or a `FILES` loop's `MATCH` glob.
    SetLoopVar {
        path: Vec<usize>,
        text: String,
    },
    SetLoopDir {
        path: Vec<usize>,
        text: String,
    },
    SetLoopGlob {
        path: Vec<usize>,
        text: String,
    },
    /// The folder/file picker beside a loop's path box. `file` picks a file
    /// (`TUPLES FROM`) rather than a folder.
    PickLoopDir {
        path: Vec<usize>,
        file: bool,
    },
    /// The inline `PARALLEL` box committed a new max-concurrency for the loop at
    /// `path`; `None` clears it back to the prelude-driven default.
    SetParallelDegree {
        path: Vec<usize>,
        degree: Option<u32>,
    },
    /// The nested `WITH` block's "add field" affordance: open the WITH-field
    /// wizard for a new field on the report request at `path`.
    AddWith {
        path: Vec<usize>,
    },
    /// Edit the existing `WITH` field at `index` of the report request at `path`
    /// (open its wizard).
    EditWith {
        path: Vec<usize>,
        index: usize,
    },
    /// Remove the `WITH` item at `index` of the report request at `path`.
    RemoveWith {
        path: Vec<usize>,
        index: usize,
    },
    /// Attach `STATISTICS(…)` to the `WITH` field at `index` of the report
    /// request at `path` — the drop a `WITH` field row accepts. Its own action
    /// rather than an [`Act::AttachMod`] because a field is addressed by
    /// (path, index) and isn't a `FlowNode` a modifier can be attached to.
    AttachWithStats {
        path: Vec<usize>,
        index: usize,
    },
    /// A header-strip chip committed a `# key: value` directive; `None` removes
    /// the directive (see [`edit::set_header`]).
    SetHeader {
        key: &'static str,
        /// Which occurrence of `key` to write. Always 0 except for
        /// `collection:`, which repeats — occurrence 0 is the primary
        /// collection, each one after it an aliased helper.
        occurrence: usize,
        value: Option<String>,
    },
    /// Browse for the file a path-valued header directive should point at.
    PickHeaderFile {
        key: &'static str,
        occurrence: usize,
    },
}

impl Act {
    /// Whether this action only writes a value the user typed into an inline
    /// field, leaving the shape of the flow alone. These are applied first (see
    /// [`apply_block_actions`]) because their paths were resolved against the
    /// tree as drawn.
    fn is_value_commit(&self) -> bool {
        matches!(
            self,
            Act::SetAlias { .. }
                | Act::SetLoopVar { .. }
                | Act::SetLoopDir { .. }
                | Act::SetLoopGlob { .. }
                | Act::SetParallelDegree { .. }
                | Act::SetHeader { .. }
        )
    }
}

pub fn ui(app: &mut GuiApp, ui: &mut egui::Ui) {
    // Take the editor out so we can freely borrow `app.session` alongside it.
    let Some(mut ed) = app.report_editor.take() else {
        return;
    };
    let th = app.theme;
    let mut close = false;
    // Fill the form from what this report was last run with, once per editor.
    ed.seed_params(&app.session);
    // NB: `pending_toolbar` is *not* cleared here. It is always taken at the end
    // of the frame that set it, so there is nothing stale to clear -- but a
    // shortcut or menu entry outside the editor (Ctrl+S, File > Save > Report)
    // sets it *before* this runs, and clearing would swallow that request.

    // Fold any streamed run updates into the grid, and keep repainting while a
    // run is live so the grid fills in real time.
    let running = ed.poll_run(app);
    if running {
        ui.ctx().request_repaint();
    }

    // Revalidate against the current collections/envs, but only when one of the
    // inputs has actually changed. Doing it per frame re-ran a deep-cloning walk
    // dozens of times a second and — because parts of it are driven by hash-set
    // iteration — reshuffled the panel each time, so the warnings visibly
    // flickered whenever the mouse moved (see `diagnostics_fingerprint`).
    match &ed.flow {
        Some(flow) => {
            let key = context::diagnostics_fingerprint(
                &app.session.collections,
                &app.session.global_envs,
                app.session.active_env_id,
                flow,
                ed.report.path.as_deref(),
                &app.strings,
            );
            if ed.diag_key != Some(key) {
                ed.diagnostics = context::report_diagnostics(
                    &app.session.collections,
                    &app.session.global_envs,
                    app.session.active_env_id,
                    flow,
                    ed.report.path.as_deref(),
                    &app.strings,
                );
                let (helpers, _) = context::load_helpers(
                    &app.session.collections,
                    flow,
                    ed.report.path.as_deref(),
                    &app.strings,
                );
                ed.helpers = helpers;
                ed.diag_key = Some(key);
            }
        }
        None => {
            ed.diagnostics.clear();
            ed.helpers.clear();
            ed.diag_key = None;
        }
    }

    // ── Header: name, view toggle, and every action, all on one line ───────
    //
    // These were three stacked strips — title, view toggle, and (in the results
    // view) a near-empty band holding Baseline/Export. Three lines of chrome
    // over a table is three rows of that table not being read, and the report
    // editor is a tool for reading tables. They fold together because they are
    // all the same kind of thing: what this document is, which way you are
    // looking at it, and what you can do to it.
    let mut reindent = false;
    ui.horizontal(|ui| {
        let mut title = RichText::new(&ed.report.name).strong().color(th.text);
        if ed.report.dirty {
            title = RichText::new(format!("{}", ed.report.name))
                .strong()
                .color(th.accent);
        }
        ui.label(title);
        ui.separator();
        for (view, label) in [
            (EditorView::Blocks, app.strings.gui_report_view_blocks),
            (EditorView::Source, app.strings.gui_report_view_source),
            (EditorView::Results, app.strings.gui_report_view_results),
        ] {
            if super::widgets::selectable(ui, ed.view == view, RichText::new(label)).clicked() {
                ed.view = view;
            }
        }
        // Re-indent the source to its real block depth. Lives beside the view
        // toggle rather than inside the source view because it is about the
        // document, not about one way of looking at it.
        ui.separator();
        if ui
            .button(app.strings.gui_report_reindent)
            .on_hover_text(app.strings.gui_report_reindent_help)
            .clicked()
        {
            reindent = true;
        }
        // The run's own status, which used to head the results view. It reads
        // as well here, beside the Run button that started it.
        if ed.is_running() {
            ui.separator();
            ui.colored_label(
                th.pending,
                format!(
                    "{} {}",
                    super::icons::RUNNING,
                    app.strings.gui_report_running
                ),
            );
        }
        if let Some(prog) = &ed.progress {
            ui.colored_label(th.dim, format!("{}/{}", prog.done, prog.total));
        }

        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            if ui
                .button(format!("{} {}", super::icons::CLOSE, app.strings.gui_close))
                .clicked()
            {
                ed.pending_toolbar = Some(ToolbarAct::Close);
            }
            let save = ui.add_enabled(
                ed.report.dirty,
                egui::Button::new(format!("{} {}", super::icons::SAVE, app.strings.gui_save)),
            );
            if save.clicked() {
                ed.pending_toolbar = Some(ToolbarAct::Save);
            }
            // Run toggles to Stop while a run is in flight.
            if ed.is_running() {
                if ui
                    .button(format!(
                        "{} {}",
                        super::icons::STOP,
                        app.strings.gui_report_stop
                    ))
                    .clicked()
                {
                    ed.stop_run(app);
                }
            } else {
                let run = ui.add_enabled(
                    ed.can_run(),
                    egui::Button::new(format!(
                        "{} {}",
                        super::icons::PLAY,
                        app.strings.gui_report_run
                    )),
                );
                if run.clicked() {
                    ed.pending_toolbar = Some(ToolbarAct::Run);
                }
                // Dry run sits beside Run, disabled on the same terms: it
                // expands the flow for real, so a flow with errors can't be
                // previewed any more than it can be run.
                let dry = ui
                    .add_enabled(
                        ed.can_run(),
                        egui::Button::new(format!(
                            "{} {}",
                            super::icons::PREVIEW,
                            app.strings.gui_report_dry_run
                        )),
                    )
                    .on_hover_text(app.strings.gui_report_dry_run_tooltip);
                if dry.clicked() {
                    ed.pending_toolbar = Some(ToolbarAct::DryRun);
                }
                // The answers themselves, and the way back to the questions —
                // one thing, not two. They used to be a button beside a dim
                // label, which split reading from acting: the part you could
                // read looked like a status message, and the part you could
                // click said "Run settings" without saying what the settings
                // were. Now the line *is* the button.
                if ed.has_params() {
                    if param_chip(ui, &ed, app, &th).clicked() {
                        ed.pending_toolbar = Some(ToolbarAct::RunSettings);
                    }
                }
            }
            // What you can do with a *result*, shown only where there is one to
            // do it with. Left of the run controls, and separated from them:
            // these act on the rows that came back, not on the report.
            if ed.view == EditorView::Results && ed.dry_run.is_none() {
                ui.separator();
                let has_rows = ed.result.as_ref().is_some_and(|r| !r.rows.is_empty());
                let export = ui.add_enabled(
                    has_rows,
                    egui::Button::new(format!(
                        "{} {}",
                        super::icons::EXPORT,
                        app.strings.gui_report_export
                    )),
                );
                if export.clicked() {
                    open_export_dialog(app);
                }
                // Appears only once there is a file to open, and disappears
                // again when a rerun makes that file describe a different run:
                // an "Open" that shows yesterday's numbers is worse than no
                // button at all.
                if let Some(exported) = ed.last_export.clone() {
                    let open = ui
                        .add(egui::Button::new(format!(
                            "{} {}",
                            super::icons::OPEN_EXTERNAL,
                            app.strings.gui_report_open_export
                        )))
                        .on_hover_text(exported.clone());
                    if open.clicked() {
                        ed.pending_toolbar = Some(ToolbarAct::OpenExport(exported));
                    }
                }
                // Saving the run as a snapshot is a different thing from
                // exporting it for reading, so it gets its own button rather
                // than hiding as a format in the export dialog: the file it
                // writes is an input to a later run, not a report anyone opens.
                let baseline = ui
                    .add_enabled(
                        has_rows,
                        egui::Button::new(format!(
                            "{} {}",
                            super::icons::SAVE,
                            app.strings.gui_report_save_baseline
                        )),
                    )
                    .on_hover_text(app.strings.help_report_baseline)
                    .on_disabled_hover_text(app.strings.report_baseline_no_result);
                if baseline.clicked() {
                    super::menu::save_via_picker(app, super::app::SaveKind::ReportBaseline);
                }
            }
        });
    });
    ui.separator();

    if reindent {
        app.session.status = Some(match ed.reformat() {
            Ok(true) => Status::ReportReformatted,
            Ok(false) => Status::ReportAlreadyTidy,
            Err(ReformatError::Unparseable(msg)) => Status::ReportReformatFailed(msg),
            Err(ReformatError::WouldChangeMeaning) => {
                Status::ReportReformatFailed(app.strings.report_reformat_unsafe.to_string())
            }
        });
    }

    match ed.view {
        EditorView::Source => source_view(&mut ed, app, ui),
        EditorView::Blocks => blocks_view(&mut ed, app, ui),
        EditorView::Results => results_view(&mut ed, app, ui),
    }

    // `p` opens the run settings, as it does in the terminal UI — but not while
    // a text field has focus (it is a perfectly good letter) and not while the
    // dialog it would open is already up.
    let typing = ui.memory(|m| m.focused().is_some());
    if !typing
        && ed.has_params()
        && ed.params_modal.is_none()
        && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::P))
    {
        ed.pending_toolbar = Some(ToolbarAct::RunSettings);
    }

    // The run settings dialog: the report's own questions, asked on the way to
    // a run rather than occupying a view of their own.
    show_param_modal(&mut ed, app, ui.ctx());

    // The node-configure wizard modal (opened by double-clicking a block on the
    // blocks view) floats above whichever view is showing.
    super::report_wizard::show(&mut ed, app, ui.ctx());

    // The results cell inspector: a floating window showing one cell's full
    // (JSON-pretty-printed) value, so a long/truncated cell can be read and
    // copied in full. The GUI stand-in for the TUI's result-cell popup.
    if ed.inspector.is_some() {
        let mut open = true;
        let esc = ui.ctx().input(|i| i.key_pressed(egui::Key::Escape));
        let ins = ed.inspector.as_ref().unwrap();
        // Titled like every other window in the app: a plain `RichText` here
        // is body-sized, which left the one floating window with a title
        // smaller than the dialogs beside it.
        egui::Window::new(RichText::new(&ins.title).heading().color(th.text))
            .id(egui::Id::new("pt_cell_inspector"))
            .collapsible(false)
            .resizable(true)
            .default_size([520.0, 340.0])
            .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
            .open(&mut open)
            .show(ui.ctx(), |ui| {
                ui.horizontal(|ui| {
                    if ui.button(app.strings.gui_report_cell_copy_full).clicked() {
                        ui.ctx().copy_text(ins.content.clone());
                        app.session.status = Some(crate::i18n::Status::Copied);
                    }
                });
                ui.separator();
                egui::ScrollArea::both()
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        egui::Frame::new()
                            .fill(th.sunken())
                            .inner_margin(6.0)
                            .show(ui, |ui| {
                                ui.add(
                                    egui::Label::new(
                                        RichText::new(&ins.content).monospace().color(th.text),
                                    )
                                    .selectable(true)
                                    .wrap_mode(egui::TextWrapMode::Extend),
                                );
                            });
                    });
            });
        if !open || esc {
            ed.inspector = None;
        }
    }

    // Global keys: Ctrl+Z undoes the last *structural* edit; Delete on the
    // blocks view is handled inside `blocks_view` so it doesn't fire while
    // typing.
    //
    // The source view is deliberately excluded: egui's `TextEdit` has an undoer
    // of its own that no one can turn off, so running this stack there meant
    // both fired at once and the widget wrote its own history straight back
    // over the editor's — the change appeared to vanish for a frame and then
    // came back with the caret moved. Text editing is exactly what the widget's
    // undoer is for (it undoes by typed word, not by whole snapshot), so in
    // that view it is left to do the job alone.
    if ed.view != EditorView::Source
        && ui.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Z))
    {
        ed.undo();
    }

    // The header's buttons act here, at the end of the frame that pressed them,
    // so any inline field that committed on losing focus above has already been
    // folded into the report (see [`ToolbarAct`]).
    match ed.pending_toolbar.take() {
        Some(ToolbarAct::Run) => ed.start_run(app),
        Some(ToolbarAct::DryRun) => ed.start_dry_run(app),
        Some(ToolbarAct::RunSettings) => ed.open_param_modal(app, RunIntent::Review),
        Some(ToolbarAct::Save) => save_report(&mut ed, app),
        Some(ToolbarAct::Close) => close = true,
        Some(ToolbarAct::OpenExport(path)) => {
            app.session.status = Some(match crate::shared_utils::open_in_desktop(&path) {
                Ok(()) => Status::ReportOpened(path),
                Err(e) => Status::Error(format!("{path}: {e}")),
            });
        }
        None => {}
    }

    if close {
        // The editor goes, the run stays: closing the view must not cancel a
        // report mid-flight or discard the rows it has already collected.
        let key = ed.run_key();
        let parked = ed.park_run();
        if parked.is_worth_keeping() {
            app.report_runs.insert(key, parked);
        }
    } else {
        app.report_editor = Some(ed);
    }
}

/// The dry-run preview's contents: a notice that nothing was sent, the
/// projected row count, the grid the run would produce, and the problems the
/// expansion turned up.
///
/// Reuses [`results_grid`], so the preview looks exactly like the result it is
/// predicting — including the clickable cells, since a projected value can be
/// just as long as a real one.
fn dry_run_body(
    app: &GuiApp,
    ui: &mut egui::Ui,
    preview: &crate::report::dry_run::DryRunReport,
) -> Option<CellInspector> {
    let th = app.theme;
    let s = &app.strings;
    let mut opened = None;

    ui.colored_label(th.dim, s.report_dry_run_preview_notice);
    ui.add_space(4.0);
    ui.label(
        RichText::new(format!("{} {}", s.report_dry_run_rows, preview.rows))
            .strong()
            .color(th.accent),
    );
    ui.add_space(4.0);

    // Problems first here, unlike the terminal UI's bottom-of-the-scroll
    // placement: a window this size can hide them below the fold, and an
    // unresolved request is the whole reason to have asked for a preview.
    if preview.var_warnings.is_empty() && preview.errors.is_empty() {
        ui.colored_label(th.accent, s.report_dry_run_no_problems);
    } else {
        if !preview.var_warnings.is_empty() {
            ui.label(
                RichText::new(s.report_dry_run_warnings_heading)
                    .strong()
                    .color(th.pending),
            );
            for w in &preview.var_warnings {
                ui.colored_label(th.pending, format!("! {w}"));
            }
        }
        if !preview.errors.is_empty() {
            ui.label(
                RichText::new(s.report_dry_run_problems_heading)
                    .strong()
                    .color(th.err),
            );
            for e in &preview.errors {
                ui.colored_label(th.err, format!("{e}"));
            }
        }
    }
    ui.separator();

    if preview.rows == 0 {
        ui.colored_label(th.dim, s.report_dry_run_no_rows);
        return None;
    }
    let columns = preview.result.resolved_columns(&preview.header);
    if columns.is_empty() {
        ui.colored_label(th.dim, app.strings.gui_report_no_results);
        return None;
    }
    // `None` states: a dry run has no streaming progress, so the grid draws
    // without status icons, exactly like a finished run.
    let (preview_grid_cols, preview_detail_cols) = crate::report::detail::split_columns(&columns);
    let mut none = None;
    if let Some(ins) = results_grid(
        &th,
        ui,
        &preview.result,
        &preview_grid_cols,
        None,
        None,
        &preview_detail_cols,
        &mut none,
    ) {
        opened = Some(ins);
    }
    opened
}

/// Build the highlighter context for `ed`: which line the parser rejected, and
/// which of the report's references currently resolve.
///
/// The colours only *mean* something with this context — a `# collection:` or
/// `ENVS` name reads green when it binds to something loaded and amber when it
/// doesn't — so the Source view answers "is this report wired up?" at a glance,
/// exactly as the terminal UI's does.
fn highlight_ctx(ed: &mut ReportEditor, app: &GuiApp) -> std::rc::Rc<HlCtx> {
    let bound = ed.flow.as_ref().and_then(|flow| {
        context::resolve_bound_collection(&app.session.collections, flow, ed.report.path.as_deref())
    });
    let key = highlight_ctx_key(ed, app, bound);
    if let Some((cached_key, ctx)) = &ed.hl_cache
        && *cached_key == key
    {
        return ctx.clone();
    }
    let ctx = std::rc::Rc::new(HlCtx {
        error_line: ed.parse_error_line,
        collection_resolves: bound.is_some(),
        loaded_envs: app
            .session
            .global_envs
            .iter()
            .map(|e| e.name.clone())
            .collect(),
        request_names: bound
            .map(|ci| {
                // Qualified, so a helper's request reads green in the Source
                // view rather than misleadingly amber.
                context::request_choices(&app.session.collections[ci].entries, &ed.helpers)
                    .into_iter()
                    .map(|c| c.qualified)
                    .collect()
            })
            .unwrap_or_default(),
    });
    ed.hl_cache = Some((key, ctx.clone()));
    ctx
}

/// Everything [`highlight_ctx`] reads, in one number.
///
/// Names only, because names are all the context holds: which collection the
/// report binds to, what its (and its helpers') requests are called, and what
/// environments are loaded. Hashing those is a pass over a few kilobytes of
/// title text; building the context is an allocation per request.
///
/// **Maintenance:** anything [`highlight_ctx`] starts reading has to be added
/// here, or the colours will stop following it.
fn highlight_ctx_key(ed: &ReportEditor, app: &GuiApp, bound: Option<usize>) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    ed.parse_error_line.hash(&mut h);
    bound.hash(&mut h);
    for e in &app.session.global_envs {
        e.name.hash(&mut h);
    }
    if let Some(ci) = bound {
        for e in &app.session.collections[ci].entries {
            e.title.hash(&mut h);
        }
    }
    for helper in &ed.helpers {
        helper.alias.hash(&mut h);
        for e in &helper.entries {
            e.title.hash(&mut h);
        }
    }
    h.finish()
}

/// Lay `text` out as a syntax-highlighted [`egui::text::LayoutJob`], reusing the
/// terminal UI's PaperTrail highlighter so both front-ends colour a script
/// identically (see [`crate::tui::report_highlight`]).
///
/// The highlighter works a line at a time and drops the line breaks, so the
/// newlines are re-inserted here as their own sections — otherwise the whole
/// script would lay out as one run-on line.
fn highlight_job(
    text: &str,
    ctx: &HlCtx,
    spec: &crate::theme::ThemeSpec,
    th: &GuiTheme,
    font: egui::FontId,
    wrap_width: f32,
) -> egui::text::LayoutJob {
    use egui::text::{LayoutJob, TextFormat};

    let theme = spec.to_theme();
    let mut job = LayoutJob {
        wrap: egui::text::TextWrapping {
            max_width: wrap_width,
            ..Default::default()
        },
        ..Default::default()
    };
    for (i, line) in text.split('\n').enumerate() {
        if i > 0 {
            job.append("\n", 0.0, TextFormat::simple(font.clone(), th.text));
        }
        // `highlight_row` is 0-based over the visible rows; it maps that onto
        // the highlighter's 1-based `error_line` itself.
        for span in report_highlight::highlight_row(i, line, ctx, &theme) {
            let style = span.style;
            let mut fmt = TextFormat::simple(
                font.clone(),
                style
                    .fg
                    .map_or(th.text, |c| super::theme::from_ratatui(c, th.text)),
            );
            fmt.underline = if style
                .add_modifier
                .contains(ratatui::style::Modifier::UNDERLINED)
            {
                egui::Stroke::new(1.0, fmt.color)
            } else {
                egui::Stroke::NONE
            };
            job.append(&span.content, 0.0, fmt);
        }
    }
    job
}

/// [`highlight_job`], reused between frames while nothing it depends on has
/// changed.
///
/// `TextEdit` asks its layouter for a job on every frame, and building one
/// re-tokenises the whole document — around 270µs for a 200-line report, on
/// every frame, whether or not a key was pressed. Cloning a cached job costs a
/// fraction of that, and handing it to `layout_job` as before leaves egui's own
/// galley cache in charge of the actual text layout (which is what keeps this
/// correct across a font or scale change).
#[allow(clippy::too_many_arguments)]
fn cached_highlight_job(
    ui: &egui::Ui,
    id: egui::Id,
    text: &str,
    ctx: &HlCtx,
    spec: &crate::theme::ThemeSpec,
    th: &GuiTheme,
    font: egui::FontId,
    wrap_width: f32,
) -> egui::text::LayoutJob {
    let key = highlight_key(text, ctx, spec, &font, wrap_width);
    if let Some((cached_key, job)) = ui.data(|d| d.get_temp::<(u64, egui::text::LayoutJob)>(id))
        && cached_key == key
    {
        return job;
    }
    let job = highlight_job(text, ctx, spec, th, font, wrap_width);
    ui.data_mut(|d| d.insert_temp(id, (key, job.clone())));
    job
}

/// Everything [`highlight_job`] reads, in one number.
///
/// **Maintenance:** anything the highlighter starts colouring by has to be
/// added here, or the colours will stop following it.
fn highlight_key(
    text: &str,
    ctx: &HlCtx,
    spec: &crate::theme::ThemeSpec,
    font: &egui::FontId,
    wrap_width: f32,
) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    // The document itself dominates, so it is hashed with the cheap mixer
    // rather than a SipHash pass over every byte.
    fnv1a(text.as_bytes(), FNV_OFFSET).hash(&mut h);
    ctx.error_line.hash(&mut h);
    ctx.collection_resolves.hash(&mut h);
    // Both name sets are hash sets, so their iteration order is not stable:
    // combine each name's hash with `^` so the key depends on the membership
    // and not on the order it comes out in.
    let mut names = 0u64;
    for e in &ctx.loaded_envs {
        names ^= fnv1a(e.as_bytes(), FNV_OFFSET);
    }
    for r in &ctx.request_names {
        names ^= fnv1a(r.as_bytes(), 0x9e37_79b9_7f4a_7c15);
    }
    names.hash(&mut h);
    spec.hash(&mut h);
    font.size.to_bits().hash(&mut h);
    wrap_width.to_bits().hash(&mut h);
    h.finish()
}

/// The byte offset of char index `at` in `text` (clamped to the end).
fn byte_at(text: &str, at: usize) -> usize {
    text.char_indices()
        .nth(at)
        .map(|(b, _)| b)
        .unwrap_or(text.len())
}

/// The (row, column) — both counted in chars — of char index `at`.
fn row_col_at(text: &str, at: usize) -> (usize, usize) {
    let (mut row, mut col) = (0usize, 0usize);
    for ch in text.chars().take(at) {
        if ch == '\n' {
            row += 1;
            col = 0;
        } else {
            col += 1;
        }
    }
    (row, col)
}

/// The char index at which `row` starts (clamped to the end of `text`).
fn row_start(text: &str, row: usize) -> usize {
    let mut idx = 0usize;
    for (n, line) in text.split('\n').enumerate() {
        if n == row {
            return idx;
        }
        idx += line.chars().count() + 1; // + the newline itself
    }
    text.chars().count()
}

/// The text and new cursor position after Enter replaces the char range `sel`,
/// with PaperTrail's auto-indent applied.
///
/// `egui`'s own Enter would insert a bare `\n`, dumping the caret in column 0
/// of a nested block; this inherits the current line's indentation instead (and
/// adds a level after a block opener), matching the terminal editor. Like that
/// editor, a *mid-line* split stays a plain newline — the rule is for the
/// ordinary "type to the end of the line, press Enter" flow, where anything else
/// would be a surprise. What counts as "the end" is measured at `sel.end`, since
/// that is where the caret lands once the selection is replaced, while the
/// indent is taken from the line the selection *starts* on.
fn newline_with_indent(text: &str, sel: std::ops::Range<usize>) -> (String, usize) {
    let lines: Vec<&str> = text.split('\n').collect();
    let (row, _) = row_col_at(text, sel.start);
    let (end_row, end_col) = row_col_at(text, sel.end);
    let at_line_end = end_col == lines.get(end_row).map_or(0, |l| l.chars().count());
    let indent = if at_line_end {
        indent_for_new_line(lines.get(row).copied().unwrap_or(""))
    } else {
        String::new()
    };
    let (from, to) = (byte_at(text, sel.start), byte_at(text, sel.end));
    let mut out = String::with_capacity(text.len() + 1 + indent.len());
    out.push_str(&text[..from]);
    out.push('\n');
    out.push_str(&indent);
    out.push_str(&text[to..]);
    (out, sel.start + 1 + indent.chars().count())
}

/// The text and new cursor position after Tab indents one level over the char
/// range `sel` (replacing any selection, as typing a character would).
fn indent_at(text: &str, sel: std::ops::Range<usize>) -> (String, usize) {
    let (from, to) = (byte_at(text, sel.start), byte_at(text, sel.end));
    let mut out = String::with_capacity(text.len() + INDENT_UNIT.len());
    out.push_str(&text[..from]);
    out.push_str(INDENT_UNIT);
    out.push_str(&text[to..]);
    (out, sel.start + INDENT_UNIT.chars().count())
}

/// How many chars a de-indent at char index `at` should delete: back to the
/// previous four-column stop within the run of spaces ending at the caret, so
/// one press clears a whole level rather than a single space. `None` when the
/// caret isn't preceded by a space, in which case the key means what it always
/// did. Mirrors the terminal editor's Tab/Backspace rule.
fn dedent_span(text: &str, at: usize) -> Option<usize> {
    let (row, col) = row_col_at(text, at);
    let chars: Vec<char> = text.split('\n').nth(row)?.chars().collect();
    if col == 0 || chars.get(col - 1) != Some(&' ') {
        return None;
    }
    let mut run_start = col;
    while run_start > 0 && chars[run_start - 1] == ' ' {
        run_start -= 1;
    }
    Some((col - run_start - 1) % INDENT_UNIT.len() + 1)
}

/// The text and new cursor position after deleting `n` chars before `at`.
fn delete_before(text: &str, at: usize, n: usize) -> (String, usize) {
    let start = at.saturating_sub(n);
    let (from, to) = (byte_at(text, start), byte_at(text, at));
    let mut out = String::with_capacity(text.len());
    out.push_str(&text[..from]);
    out.push_str(&text[to..]);
    (out, start)
}

/// Handle the source editor's code-editing keys, which `egui`'s text area would
/// otherwise take literally: Enter (auto-indent), Tab / Shift+Tab (indent by one
/// four-space level rather than inserting a literal `\t`) and Backspace over
/// indentation (clear a whole level). Returns the replacement text and caret
/// position, or `None` to let the widget handle the key itself.
///
/// Tab stays in the field either way — `code_editor()` locks focus — so
/// **Escape** is the way out of the editor (egui releases focus on it, and the
/// focus filter deliberately lets it through).
fn source_edit_key(
    ui: &egui::Ui,
    text: &str,
    sel: std::ops::Range<usize>,
) -> Option<(String, usize)> {
    use egui::{Key, Modifiers};
    if ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {
        return Some(newline_with_indent(text, sel));
    }
    if ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)) {
        return Some(indent_at(text, sel));
    }
    // Shift+Tab is always swallowed, even where there is no indentation to
    // remove: with focus locked it can't mean "previous widget", and letting the
    // widget see it would insert egui's own tab-flavoured indentation instead.
    if ui.input_mut(|i| i.consume_key(Modifiers::SHIFT, Key::Tab)) {
        return dedent_span(text, sel.start).map(|n| delete_before(text, sel.start, n));
    }
    // Backspace is only taken when it really is deleting indentation, so an
    // ordinary character delete (and every selection-aware case) stays egui's.
    if sel.is_empty()
        && let Some(n) = dedent_span(text, sel.start)
        && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Backspace))
    {
        return Some(delete_before(text, sel.start, n));
    }
    None
}

/// If the line holding char index `at` now reads exactly `END`, snap it to its
/// opener's indentation and return the corrected text with the cursor parked at
/// the line end — so finishing a block dedents one level, as it does in the
/// terminal editor. `None` when nothing needs changing (already aligned, not an
/// `END`, or the nesting above is unbalanced, in which case guessing would be
/// worse than leaving the typed text alone).
fn snap_end_line(text: &str, at: usize) -> Option<(String, usize)> {
    let lines: Vec<&str> = text.split('\n').collect();
    let (row, _) = row_col_at(text, at);
    let line = *lines.get(row)?;
    if !is_end_line(line) {
        return None;
    }
    let indent = matching_opener_indent(&lines[..row])?;
    let fixed = format!("{indent}{}", line.trim_start());
    if fixed == line {
        return None;
    }
    let start = row_start(text, row);
    let cursor = start + fixed.chars().count();
    let mut out: Vec<&str> = lines;
    out[row] = &fixed;
    Some((out.join("\n"), cursor))
}

/// The raw `.trail` source editor + validation panel.
/// The run settings dialog: one card per declared `PARAM` — what it asks for,
/// the value this run will use, and what is wrong with it, if anything.
///
/// A dialog rather than a view because it is a step on the way to a run, not a
/// place to be: it is opened by Run (and by Dry run, which needs the same
/// answers to preview the run you actually mean), and it leaves by starting
/// one. Both exits are offered whichever button opened it, so changing your
/// mind about previewing first doesn't mean answering twice.
///
/// Deliberately a *form*, not a script: most people who run a report never open
/// it, so every parameter is a labelled field with the widget its declared type
/// deserves (a drop-down for a closed set, a picker for a path). The raw name
/// and type sit beside it dimmed — the form doubles as the reference for anyone
/// who does go on to read the source. Drawn as tinted, rounded cards in the
/// Blocks view's own idiom, in the `subst` hue every other `{{substitution}}`
/// carries — which is exactly what a parameter is.
/// The toolbar's run-settings chip: what the next run will use, as one
/// clickable line.
///
/// Every part of it is readable *and* clickable, which is the whole point — the
/// values used to be a dim label sitting beside a button, and a line you can
/// read but not act on reads as a status message rather than a question. A
/// value that has no answer is painted in the colour the app uses for "not
/// settled yet" (or the error colour where it would actually stop the run), so
/// an unanswered report looks unanswered instead of merely informative.
fn param_chip(
    ui: &mut egui::Ui,
    ed: &ReportEditor,
    app: &GuiApp,
    th: &super::theme::GuiTheme,
) -> egui::Response {
    use egui::text::{LayoutJob, TextFormat};

    let s = &app.strings;
    let font = egui::TextStyle::Button.resolve(ui.style());
    let fmt = |color: egui::Color32| TextFormat {
        font_id: font.clone(),
        color,
        ..Default::default()
    };
    let mut job = LayoutJob::default();
    // One row, however long the answers are: the toolbar is a row, not a
    // paragraph, and the whole of it is on hover.
    job.wrap.max_rows = 1;
    job.wrap.break_anywhere = true;
    job.wrap.overflow_character = Some('');
    job.wrap.max_width = (ui.available_width() - 24.0).max(120.0);
    job.append(
        &format!("{} {}: ", super::icons::ENV, s.gui_report_run_settings),
        0.0,
        fmt(th.text),
    );
    for (i, row) in ed.param_rows(s).iter().enumerate() {
        if i > 0 {
            job.append(" · ", 0.0, fmt(th.dim));
        }
        job.append(&format!("{}=", row.name), 0.0, fmt(th.dim));
        let (text, color) = if row.problem.is_some() {
            (s.param_value_unset, th.err)
        } else if row.value.is_empty() {
            (s.param_value_unset, th.pending)
        } else {
            (row.value.as_str(), th.text)
        };
        job.append(text, 0.0, fmt(color));
    }
    // A result on screen that was produced with different answers is the one
    // case where the chip is not describing what the reader is looking at.
    // Saying so here beats a strip above the table, which would cost a row of
    // the table every run, changed or not.
    let stale = ed.params_changed_since_result(s);
    if stale {
        job.append(
            &format!(" · {}", s.param_changed_since_run),
            0.0,
            fmt(th.accent),
        );
    }
    let mut hover = format!(
        "{}\n{}",
        ed.param_summary(s),
        s.gui_report_run_settings_shortcut
    );
    if stale {
        hover = format!(
            "{}\n{}",
            s.param_result_ran_with
                .replace("{}", &summarize(&ed.result_params, s)),
            hover
        );
    }
    ui.add(egui::Button::new(job)).on_hover_text(hover)
}

/// `NAME=value · NAME=value`, with an empty value written as the same
/// "(not set)" the form shows.
fn summarize(values: &[(String, String)], s: &Strings) -> String {
    values
        .iter()
        .map(|(name, value)| {
            let shown = if value.is_empty() {
                s.param_value_unset
            } else {
                value.as_str()
            };
            format!("{name}={shown}")
        })
        .collect::<Vec<_>>()
        .join(" · ")
}

#[cfg(test)]
pub(crate) fn arm_params_for_audit(ed: &mut ReportEditor) {
    ed.params_modal = Some(RunIntent::Run);
}

fn show_param_modal(ed: &mut ReportEditor, app: &mut GuiApp, ctx: &egui::Context) {
    let Some(intent) = ed.params_modal else {
        return;
    };
    let th = app.theme;
    // A copy of its own, so the app is free to be borrowed mutably for the file
    // picker at the end without the form's own words going out of scope.
    let s = Strings::for_language(&app.session.language);
    let rows = ed.param_rows(&s);
    let envs: Vec<String> = app
        .session
        .global_envs
        .iter()
        .map(|e| e.name.clone())
        .collect();
    // Nothing may be started while a value would send the run at a hole.
    let ready = rows.iter().all(|r| r.problem.is_none());

    // What the frame decided, applied once the modal closure has let go of
    // everything it borrowed.
    let mut set: Option<(String, String)> = None;
    let mut browse: Option<(String, bool)> = None;
    let mut leave: Option<Option<RunIntent>> = None;

    let modal = egui::Modal::new(egui::Id::new("pt_run_settings")).show(ctx, |ui| {
        ui.set_min_width(FORM_MAX_WIDTH);
        ui.set_max_width(FORM_MAX_WIDTH);
        ui.horizontal(|ui| {
            // Sized like the title bar of every framed dialog in the app: a
            // modal draws its own title, and a body-sized one reads as a
            // stray line rather than as the name of the window.
            ui.heading(RichText::new(s.param_view_title).color(th.text));
            // A modal has no title bar to hang a close button off, so it gets
            // its own: every dialog in the app can be left by the corner as
            // well as by Escape.
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if ui
                    .button(RichText::new(super::icons::CLOSE).color(th.dim))
                    .clicked()
                {
                    leave = Some(None);
                }
            });
        });
        ui.colored_label(th.dim, s.param_view_lead);
        ui.add_space(8.0);

        // Capped so a long form scrolls inside the dialog rather than growing
        // it past the window it is centred in.
        egui::ScrollArea::vertical()
            .max_height(420.0)
            .auto_shrink([false, true])
            .show(ui, |ui| {
                for row in &rows {
                    if let Some((name, edit)) = param_card(ui, &th, row, &envs, &s) {
                        match edit {
                            CardEdit::Set(v) => set = Some((name, v)),
                            CardEdit::Browse(folder) => browse = Some((name, folder)),
                        }
                    }
                    ui.add_space(6.0);
                }
            });

        ui.add_space(8.0);
        ui.separator();
        ui.horizontal(|ui| {
            // The button that was pressed to get here comes first, so the
            // dialog reads as the middle of the gesture that opened it rather
            // than as a fork in it.
            let run = |ui: &mut egui::Ui, leave: &mut Option<Option<RunIntent>>| {
                if ui
                    .add_enabled(
                        ready,
                        egui::Button::new(format!("{} {}", super::icons::PLAY, s.gui_report_run)),
                    )
                    .clicked()
                {
                    *leave = Some(Some(RunIntent::Run));
                }
            };
            let dry = |ui: &mut egui::Ui, leave: &mut Option<Option<RunIntent>>| {
                if ui
                    .add_enabled(
                        ready,
                        egui::Button::new(format!(
                            "{} {}",
                            super::icons::PREVIEW,
                            s.gui_report_dry_run
                        )),
                    )
                    .on_hover_text(s.gui_report_dry_run_tooltip)
                    .clicked()
                {
                    *leave = Some(Some(RunIntent::DryRun));
                }
            };
            if intent == RunIntent::DryRun {
                dry(ui, &mut leave);
                run(ui, &mut leave);
            } else {
                run(ui, &mut leave);
                dry(ui, &mut leave);
            }
            if ui.button(s.gui_cancel).clicked() {
                leave = Some(None);
            }
            // Not the per-card message repeated: beside the disabled buttons
            // the useful thing to say is what to do about it.
            if !ready {
                ui.colored_label(th.err, s.param_blocked_hint);
            }
        });
    });
    if modal.should_close() {
        leave = Some(None);
    }

    if let Some((name, value)) = set {
        ed.param_values.insert(name, value);
    }
    if let Some((name, folder)) = browse {
        let seed = ed
            .report
            .path
            .as_deref()
            .and_then(|p| p.parent())
            .map(std::path::Path::to_path_buf);
        let kind = if folder {
            super::filepick::PickKind::Folder
        } else {
            super::filepick::PickKind::File {
                filters: super::filepick::owned_filters(&[("*", &["*"])]),
            }
        };
        app.request_pick(
            kind,
            s.param_pick_path,
            seed.as_deref(),
            super::menu::PickAction::ReportParamPath { name },
        );
    }
    if let Some(started) = leave {
        ed.params_modal = None;
        // Answered: Run and Dry run both act at once from here on, so a preview
        // can be followed straight by the run it previewed. `reparse` re-arms
        // this if the questions themselves change.
        if let Some(intent) = started {
            ed.params_confirmed = true;
            match intent {
                RunIntent::Run => ed.start_run(app),
                RunIntent::DryRun => ed.start_dry_run(app),
                RunIntent::Review => {}
            }
        }
    }
}

/// How wide the run settings form is allowed to grow. Wide enough for a long
/// path, narrow enough that a label and its field stay in one glance.
const FORM_MAX_WIDTH: f32 = 620.0;
/// How wide a parameter's field is. Fixed rather than fitted to the value so a
/// column of fields lines up — a form of ragged boxes reads as an accident.
const PARAM_FIELD_WIDTH: f32 = 320.0;

/// What a [`param_card`] asked for this frame.
enum CardEdit {
    Set(String),
    /// Browse for a path; `true` for a folder.
    Browse(bool),
}

/// One parameter's card: its question, its field, and its identity.
///
/// Returns the parameter's name with whatever the user did to it, so the caller
/// can apply it once the borrow of the rows is over.
fn param_card(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    row: &crate::report::params::ParamRow,
    envs: &[String],
    s: &Strings,
) -> Option<(String, CardEdit)> {
    use crate::report::flow::ParamKind;

    // The hue of a substitution, because that is what a parameter becomes.
    // Deepened when something is wrong, so an unanswered card is findable in a
    // column of them without reading a word.
    let hue = if row.problem.is_some() {
        th.err
    } else {
        th.subst
    };
    let mut edit = None;
    egui::Frame::NONE
        .fill(mix(th.panel, hue, 0.10))
        .stroke(egui::Stroke::new(1.0, mix(th.panel, hue, 0.45)))
        .inner_margin(egui::Margin::symmetric(10, 8))
        .corner_radius(BLOCK_RADIUS as u8)
        .show(ui, |ui| {
            ui.set_min_width(ui.available_width());
            // The question, and — pushed to the far side — what the script
            // calls it. Someone filling the form in reads the left; someone
            // cross-referencing the source reads the right.
            ui.horizontal(|ui| {
                ui.label(RichText::new(&row.prompt).strong().color(th.text));
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    ui.colored_label(th.dim, row.kind.keyword());
                    ui.label(
                        RichText::new(&row.name)
                            .monospace()
                            .color(mix(th.dim, th.subst, 0.5)),
                    );
                });
            });
            ui.add_space(4.0);

            let mut value = row.value.clone();
            let name = row.name.clone();
            ui.horizontal(|ui| {
                match &row.kind {
                    ParamKind::Choice(options) if !options.is_empty() => {
                        if param_combo(ui, th, &name, &mut value, options) {
                            edit = Some((name.clone(), CardEdit::Set(value.clone())));
                        }
                    }
                    // Nothing loaded to choose between: typing a name by hand
                    // still works, and is the right answer for an environment
                    // that lives on another machine.
                    ParamKind::Env if !envs.is_empty() => {
                        if param_combo(ui, th, &name, &mut value, envs) {
                            edit = Some((name.clone(), CardEdit::Set(value.clone())));
                        }
                    }
                    ParamKind::Folder | ParamKind::File => {
                        if param_field(ui, &mut value, s.param_value_unset) {
                            edit = Some((name.clone(), CardEdit::Set(value.clone())));
                        }
                        if ui
                            .button(format!("{} {}", super::icons::FOLDER, s.gui_browse))
                            .on_hover_text(s.param_pick_path)
                            .clicked()
                        {
                            edit = Some((
                                name.clone(),
                                CardEdit::Browse(matches!(row.kind, ParamKind::Folder)),
                            ));
                        }
                    }
                    _ => {
                        if param_field(ui, &mut value, s.param_value_unset) {
                            edit = Some((name.clone(), CardEdit::Set(value.clone())));
                        }
                    }
                }
            });

            if let Some(problem) = &row.problem {
                ui.add_space(4.0);
                ui.colored_label(th.err, format!("{}  {}", super::icons::WARNING, problem));
            }
        });
    edit
}

/// A parameter's text field: fixed width, monospace, and hinted with what the
/// run would use if it were left alone.
fn param_field(ui: &mut egui::Ui, value: &mut String, hint: &str) -> bool {
    ui.add(
        egui::TextEdit::singleline(value)
            .hint_text(hint)
            // Monospace for the same reason an inline field in the Blocks view
            // is: what goes in here is the user's own text, not the editor's
            // vocabulary, and the two shouldn't look alike.
            .font(egui::TextStyle::Monospace)
            .desired_width(PARAM_FIELD_WIDTH),
    )
    .changed()
}

/// A parameter's drop-down: the closed set of answers its type allows, plus
/// whatever it is currently set to if that isn't one of them (a value from a
/// remembered run, or an environment that isn't loaded today — hiding it would
/// silently change what the run does). Returns true when the pick changed.
fn param_combo(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    name: &str,
    value: &mut String,
    options: &[String],
) -> bool {
    let mut changed = false;
    let known = options.iter().any(|o| o == value);
    let shown = if value.is_empty() {
        RichText::new("").color(th.dim)
    } else {
        RichText::new(value.clone()).color(if known { th.text } else { th.pending })
    };
    egui::ComboBox::from_id_salt(("pt_param", name))
        .width(PARAM_FIELD_WIDTH)
        .selected_text(shown)
        .show_ui(ui, |ui| {
            // An unrecognised current value is offered back to itself so
            // opening the list can't quietly discard it.
            if !known && !value.is_empty() {
                let cur = value.clone();
                let _ = ui.selectable_label(true, RichText::new(cur).color(th.pending));
            }
            for o in options {
                if ui.selectable_label(o == value, o).clicked() {
                    *value = o.clone();
                    changed = true;
                }
            }
        });
    changed
}

fn source_view(ed: &mut ReportEditor, app: &GuiApp, ui: &mut egui::Ui) {
    // Reserve room for the diagnostics panel at the bottom, then let the editor
    // fill the rest. Keeping the editor above avoids nesting egui panels inside
    // the centre panel (which egui 0.35 disallows in a `panel_frame` closure).
    let avail = ui.available_height();
    let diag_h = ed.diag_h.clamp(48.0, (avail - 100.0).max(48.0));
    let edit_h = (avail - diag_h - 8.0).max(80.0);
    let hl_ctx = highlight_ctx(ed, app);
    let hl = &*hl_ctx;
    let spec = app.session.active_theme_spec();
    let th = app.theme;
    // `TextEdit` asks for a job every frame; re-tokenising the whole document
    // that often is the expensive part, so it is cached and egui's galley cache
    // still handles the layout itself.
    let job_id = egui::Id::new("report_source_highlight");
    let mut layouter = |ui: &egui::Ui, buf: &dyn egui::TextBuffer, wrap_width: f32| {
        let font = egui::TextStyle::Monospace.resolve(ui.style());
        let job = cached_highlight_job(ui, job_id, buf.as_str(), &hl, &spec, &th, font, wrap_width);
        ui.ctx().fonts_mut(|f| f.layout_job(job))
    };
    egui::ScrollArea::vertical()
        .auto_shrink([false, false])
        .max_height(edit_h)
        .show(ui, |ui| {
            let te_id = ui.id().with("trail_source");
            let mut text = ed.report.text.clone();
            // The code-editing keys are intercepted *before* the widget sees
            // them: egui would insert a bare newline or a literal tab, so the
            // only way to indent PaperTrail's way is to consume the key and
            // perform the edit (caret included) ourselves. Modified variants are
            // left alone — Ctrl/Cmd+Enter runs the report, and Shift+Enter stays
            // a plain-newline escape hatch.
            // Only intercept when there is a live cursor to work from: with no
            // stored state we have no idea where the newline goes, so the key
            // is left for egui rather than consumed and dropped on the floor.
            let cursor = ui
                .memory(|m| m.has_focus(te_id))
                .then(|| egui::TextEdit::load_state(ui.ctx(), te_id))
                .flatten()
                .and_then(|s| s.cursor.char_range())
                .map(|r| {
                    let r = r.as_sorted_char_range();
                    r.start.0..r.end.0
                });
            let mut new_cursor: Option<usize> = None;
            let mut edited = false;
            if let Some(range) = cursor
                && let Some((next, caret)) = source_edit_key(ui, &text, range)
            {
                text = next;
                new_cursor = Some(caret);
                edited = true;
            }
            let resp = ui.add(
                egui::TextEdit::multiline(&mut text)
                    .id(te_id)
                    // Also locks focus, so Tab stays in the field (Escape is the
                    // way out) — we just intercept it above to indent in spaces
                    // rather than the literal `\t` egui would insert.
                    .code_editor()
                    .desired_width(f32::INFINITY)
                    .desired_rows(20)
                    .layouter(&mut layouter),
            );
            // A line that has just become `END` dedents to its opener. Done
            // after the widget so it also catches the `END` the user typed by
            // hand, not just the one a newline left behind.
            if (edited || resp.changed())
                && let Some(state) = egui::TextEdit::load_state(ui.ctx(), te_id)
            {
                let at = new_cursor.unwrap_or_else(|| {
                    state
                        .cursor
                        .char_range()
                        .map(|r| r.primary.index.0)
                        .unwrap_or(0)
                });
                if let Some((next, caret)) = snap_end_line(&text, at) {
                    text = next;
                    new_cursor = Some(caret);
                    edited = true;
                }
            }
            if let Some(caret) = new_cursor
                && let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), te_id)
            {
                state
                    .cursor
                    .set_char_range(Some(egui::text_selection::CCursorRange::one(
                        egui::text::CCursor::new(egui::text::CharIndex(caret)),
                    )));
                egui::TextEdit::store_state(ui.ctx(), te_id, state);
            }
            if edited || resp.changed() {
                // Snapshot for undo only when transitioning from a saved
                // baseline, to avoid one entry per keystroke.
                if ed.undo.last().map(String::as_str) != Some(ed.report.text.as_str()) {
                    ed.undo.push(ed.report.text.clone());
                }
                ed.set_text(text);
            }
        });
    diag_splitter(ed, ui);
    diagnostics_panel(ed, app, ui);
}

/// The results grid from the last (or in-flight) run, plus an Export button.
fn results_view(ed: &mut ReportEditor, app: &mut GuiApp, ui: &mut egui::Ui) {
    let th = app.theme;

    // A dry run is a result like any other, so it is shown in this view rather
    // than in a window of its own — same table, same cell viewer, nothing
    // floating over the top of anything. Its banner is what says it isn't real.
    if let Some(preview) = ed.dry_run.take() {
        let mut keep = true;
        ui.horizontal(|ui| {
            ui.colored_label(th.pending, app.strings.report_dry_run_preview_notice);
            // A preview is read as "this is what would happen", so the answers
            // it assumed belong beside it rather than only in the toolbar.
            if !ed.result_params.is_empty() {
                ui.colored_label(
                    th.dim,
                    format!(
                        "{} {}",
                        app.strings.param_previewed_with,
                        summarize(&ed.result_params, &app.strings)
                    ),
                );
            }
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if ui
                    .button(format!(
                        "{} {}",
                        super::icons::CLOSE,
                        app.strings.gui_report_dry_run_close
                    ))
                    .on_hover_text(app.strings.gui_report_dry_run_close_tooltip)
                    .clicked()
                {
                    keep = false;
                }
            });
        });
        ui.separator();
        if let Some(ins) = dry_run_body(app, ui, &preview) {
            ed.inspector = Some(ins);
        }
        if keep {
            ed.dry_run = Some(preview);
        }
        return;
    }

    // The run's status and its Baseline/Export buttons live in the editor's one
    // header row (see `report_header`), not in a strip of their own: this view
    // is a table, and every line spent above it is a row of that table not
    // being read.
    let Some(result) = ed.result.as_ref() else {
        ui.add_space(8.0);
        ui.colored_label(th.dim, app.strings.gui_report_no_results);
        return;
    };

    // Resolve columns via the flow header's `columns:` directive (falling back
    // to the discovered column order when the flow doesn't parse or names none).
    let header = ed
        .flow
        .as_ref()
        .map(|f| f.header.clone())
        .unwrap_or_default();
    let columns = result.resolved_columns(&header);
    // `DETAIL` columns leave the grid for the drill-down, exactly as they do in
    // the export -- a column that vanished from one and not the other would
    // look like a bug in whichever you noticed second.
    let (grid_columns, detail_columns) = crate::report::detail::split_columns(&columns);
    if columns.is_empty() {
        ui.add_space(8.0);
        ui.colored_label(th.dim, app.strings.gui_report_no_results);
        return;
    }

    // Run-level errors (unresolved requests, producer problems) above the grid.
    if !result.errors.is_empty() {
        for e in &result.errors {
            ui.colored_label(th.err, format!("{} {e}", super::icons::FAIL));
        }
        ui.add_space(2.0);
    }

    let states = ed.progress.as_ref().map(|p| p.states.as_slice());

    // The metric cards and the filter bar, the two things the interactive HTML
    // export offers that reading the grid alone doesn't. Both are skipped while
    // a run is streaming: the figures would be computed over a half-filled
    // table and would tick misleadingly as rows land, and `visible_rows` drops
    // pending rows, so filtering a live run would empty the very view you are
    // watching.
    let live = states.is_some();
    if let Some(visible) = visible_for_view(
        result,
        &columns,
        &header,
        live,
        &mut ed.results_filter,
        &ed.results_find,
    ) {
        let metrics = result.metrics(&columns, &header);
        let (filters, buttons) = crate::report::filter::all_filters(result, metrics.as_ref());
        // The summary block scrolls inside a height of its own rather than
        // pushing the grid off the bottom. A report with a matrix per
        // ground-truthed column can otherwise leave no room at all for the rows
        // the matrices describe.
        let summary_h = ed
            .summary_h
            .clamp(60.0, (ui.available_height() - 120.0).max(60.0));
        let mut filter = ed.results_filter;
        let mut find = std::mem::take(&mut ed.results_find);
        egui::ScrollArea::vertical()
            .id_salt("pb_report_summary")
            .max_height(summary_h)
            // Vertical auto-shrink is left on so a report with no matrices
            // doesn't reserve a band of empty space above its grid.
            .auto_shrink([false, true])
            .show(ui, |ui| {
                if let Some(metrics) = &metrics {
                    metric_cards(&th, ui, app, metrics);
                }
                filter_bar(
                    &th,
                    ui,
                    app,
                    &filters[..buttons],
                    &mut filter,
                    &mut find,
                    visible.len(),
                    result.rows.len(),
                );
                // The matrices sit under the bar they drive: a cell is itself a
                // filter, and picking one selects exactly the rows that cell
                // counted.
                if let Some(metrics) = &metrics {
                    for m in &metrics.columns {
                        if let Some(matrix) = &m.matrix {
                            confusion_matrix(
                                &th,
                                ui,
                                app,
                                &m.header,
                                matrix,
                                &filters,
                                &mut filter,
                            );
                        }
                    }
                }
            });
        ed.results_filter = filter;
        ed.results_find = find;
        summary_splitter(&mut ed.summary_h, ui);
        ui.colored_label(
            th.dim,
            app.strings
                .gui_report_cell_hint
                .replace("{c}", super::icons::CARET_RIGHT),
        );
        ui.add_space(2.0);
        // A row whose panel is open still has to be *reachable*, so the grid
        // gives up the height the reader dragged the panel to (defaulting to
        // something a picture fits in) rather than the panel appearing
        // off-screen below it.
        let avail = ui.available_height();
        let grid_h = if ed.results_detail.is_some() {
            let panel = ed.detail_h.clamp(80.0, (avail - 120.0).max(80.0));
            (avail - panel - 10.0).max(80.0)
        } else {
            avail
        };
        let mut open_detail = ed.results_detail;
        let mut inspector = None;
        ui.allocate_ui(egui::vec2(ui.available_width(), grid_h), |ui| {
            inspector = results_grid(
                &th,
                ui,
                result,
                &grid_columns,
                states,
                Some(&visible),
                &detail_columns,
                &mut open_detail,
            );
        });
        if let Some(ins) = inspector {
            ed.inspector = Some(ins);
        }
        // A filtered-away row must not keep its panel open: the panel is the
        // row's, and the row is no longer on screen to close it.
        if open_detail.is_some_and(|r| !visible.contains(&r)) {
            open_detail = None;
        }
        ed.results_detail = open_detail;
        if let Some(r) = ed.results_detail {
            detail_splitter(&mut ed.detail_h, ui);
            detail_panel(
                &th,
                ui,
                app,
                result,
                r,
                &columns,
                &detail_columns,
                &mut ed.results_textures,
                &mut ed.results_detail,
            );
        }
        return;
    }
    ui.colored_label(
        th.dim,
        app.strings
            .gui_report_cell_hint
            .replace("{c}", super::icons::CARET_RIGHT),
    );
    ui.add_space(2.0);
    let mut none = None;
    if let Some(ins) = results_grid(
        &th,
        ui,
        result,
        &grid_columns,
        states,
        None,
        &detail_columns,
        &mut none,
    ) {
        ed.inspector = Some(ins);
    }
}

/// A thin draggable handle between the results grid and an open drill-down.
/// Dragging it up or down grows or shrinks the panel (`ed.detail_h`), which is
/// saved with the rest of the GUI's geometry so a reader who wants a big
/// picture pane keeps it between runs and between sessions.
///
/// Deliberately a copy of [`diag_splitter`]'s look rather than a shared widget:
/// the two hold different fields with different clamps, and the drawing is four
/// lines. Keep them in step by eye.
fn detail_splitter(height: &mut f32, ui: &mut egui::Ui) {
    ui.add_space(2.0);
    let (rect, resp) =
        ui.allocate_exact_size(egui::vec2(ui.available_width(), 6.0), egui::Sense::drag());
    if resp.dragged() {
        // Dragging *up* makes the panel taller, since the panel is below the
        // handle — the same sense as the diagnostics splitter.
        *height = (*height - resp.drag_delta().y).clamp(80.0, 2000.0);
    }
    if resp.hovered() || resp.dragged() {
        ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
    }
    let active = resp.hovered() || resp.dragged();
    let visuals = ui.visuals();
    let colour = if active {
        visuals.widgets.active.fg_stroke.color
    } else {
        visuals.widgets.noninteractive.bg_stroke.color
    };
    let w = (rect.width() * 0.25).clamp(40.0, 160.0);
    let x0 = rect.center().x - w / 2.0;
    ui.painter()
        .hline(x0..=x0 + w, rect.center().y, egui::Stroke::new(2.0, colour));
}

/// A thin draggable handle under the results view's summary block. Dragging it
/// down gives the metric cards, filter bar and matrices more room before they
/// start scrolling; dragging it up gives the room back to the grid.
///
/// Same shape as [`detail_splitter`], opposite sense: the pane this one sizes
/// is *above* the handle, so dragging down grows it.
fn summary_splitter(height: &mut f32, ui: &mut egui::Ui) {
    let (rect, resp) =
        ui.allocate_exact_size(egui::vec2(ui.available_width(), 6.0), egui::Sense::drag());
    if resp.dragged() {
        *height = (*height + resp.drag_delta().y).clamp(60.0, 2000.0);
    }
    if resp.hovered() || resp.dragged() {
        ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
    }
    let active = resp.hovered() || resp.dragged();
    let visuals = ui.visuals();
    let colour = if active {
        visuals.widgets.active.fg_stroke.color
    } else {
        visuals.widgets.noninteractive.bg_stroke.color
    };
    let w = (rect.width() * 0.25).clamp(40.0, 160.0);
    let x0 = rect.center().x - w / 2.0;
    ui.painter()
        .hline(x0..=x0 + w, rect.center().y, egui::Stroke::new(2.0, colour));
}

/// How many side-by-side columns a drill-down's sections should be laid out in.
///
/// Mirrors the interactive HTML export's `flex: 1 1 22rem; min-width: min(100%,
/// 22rem)`: sections sit beside each other while each still gets a readable
/// width, and fall back to a single column when the pane is narrow. Never more
/// columns than there are sections, so two sections never leave a third of the
/// pane empty.
fn detail_layout_columns(avail: f32, min_w: f32, sections: usize) -> usize {
    if sections == 0 {
        return 1;
    }
    let fits = (avail / min_w).floor().max(1.0) as usize;
    fits.min(sections).max(1)
}

/// The width a drill-down section wants before it is willing to share a row,
/// the pixel equivalent of the HTML export's `22rem`.
const DETAIL_MIN_SECTION_W: f32 = 340.0;

/// One row's drill-down: its pictures at full size, its `DETAIL` columns in
/// full, and a field-by-field diff against the baseline where there is one.
///
/// What goes in it is decided by [`crate::report::detail::sections`], the same
/// call the HTML export makes, so the two panels can never show different
/// things about the same row.
#[allow(clippy::too_many_arguments)]
fn detail_panel(
    th: &GuiTheme,
    ui: &mut egui::Ui,
    app: &GuiApp,
    result: &ReportResult,
    r: usize,
    all_columns: &[crate::report::model::OutputColumn],
    detail_columns: &[&crate::report::model::OutputColumn],
    textures: &mut std::collections::HashMap<(usize, String), egui::TextureHandle>,
    open: &mut Option<usize>,
) {
    ui.horizontal(|ui| {
        ui.label(
            RichText::new(
                app.strings
                    .report_detail_title
                    .replace("{n}", &(r + 1).to_string()),
            )
            .strong()
            .color(th.accent),
        );
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            if ui
                .add(egui::Button::new(super::icons::CLOSE).frame(false))
                .on_hover_text(app.strings.report_detail_close)
                .clicked()
            {
                *open = None;
            }
        });
    });
    egui::ScrollArea::vertical()
        .id_salt("pb_report_detail")
        .auto_shrink([false, false])
        .show(ui, |ui| {
            let sections = crate::report::detail::sections(result, r, all_columns, detail_columns);
            // Laid out across the pane rather than down it, exactly as the
            // interactive HTML export does: a picture beside its response body
            // is how the row is actually read, and stacking them buried the
            // JSON a screen below a full-height photograph.
            let n =
                detail_layout_columns(ui.available_width(), DETAIL_MIN_SECTION_W, sections.len());
            ui.columns(n, |cols| {
                for (i, section) in sections.into_iter().enumerate() {
                    // Round-robin, which for the first row of sections is the
                    // same order the HTML's `flex-wrap` produces.
                    let ui = &mut cols[i % n];
                    detail_section(th, ui, app, r, section, textures);
                    ui.add_space(6.0);
                }
            });
        });
}

/// Draw one section of a row's drill-down into whichever column it landed in.
fn detail_section(
    th: &GuiTheme,
    ui: &mut egui::Ui,
    app: &GuiApp,
    r: usize,
    section: crate::report::detail::DetailSection<'_>,
    textures: &mut std::collections::HashMap<(usize, String), egui::TextureHandle>,
) {
    use crate::report::detail::DetailSection;
    match section {
        DetailSection::Image {
            header,
            image,
            value,
        } => {
            ui.label(RichText::new(header).strong().color(th.accent));
            detail_image(ui, textures, r, header, image, &value, app);
        }
        DetailSection::Text {
            header,
            value,
            verdict,
        } => {
            // A `DETAIL` column carrying a `TRUTH` says whether it is right,
            // exactly as its grid cell would have. The panel is where the
            // value is actually read, so a heading that stayed neutral over a
            // wrong answer would read as one nobody checked.
            ui.horizontal(|ui| {
                ui.label(RichText::new(header).strong().color(th.accent));
                if let Some((v, truth)) = &verdict {
                    let col = if *v == crate::report::model::Verdict::Correct {
                        th.ok
                    } else {
                        th.err
                    };
                    ui.label(
                        RichText::new(crate::report::detail::verdict_label(*v, truth))
                            .strong()
                            .color(col),
                    );
                }
            });
            // Monospace and selectable: a detail column is usually a
            // response body, which is read by picking bits out of it.
            ui.add(
                egui::TextEdit::multiline(&mut value.as_str())
                    .font(egui::TextStyle::Monospace)
                    .desired_width(f32::INFINITY),
            );
        }
        DetailSection::Diff { header, fields } => {
            ui.label(
                RichText::new(app.strings.report_detail_changed.replace("{c}", header))
                    .strong()
                    .color(th.accent),
            );
            egui::Grid::new(("pb_detail_diff", header))
                .striped(true)
                .num_columns(3)
                .show(ui, |ui| {
                    for f in &fields {
                        // Unchanged fields are kept and the changed
                        // ones highlighted, so the reader can find
                        // the field they care about either way.
                        let col = if f.differs() { th.err } else { th.dim };
                        ui.colored_label(col, &f.path);
                        ui.colored_label(col, f.baseline.as_deref().unwrap_or("\u{2014}"));
                        ui.colored_label(col, f.candidate.as_deref().unwrap_or("\u{2014}"));
                        ui.end_row();
                    }
                });
        }
    }
}

/// Draw one of a row's pictures, decoding and uploading it on first sight.
///
/// The decode is cached because the panel is redrawn on every frame it is open,
/// and a report picture is a photograph -- decoding one sixty times a second is
/// not a thing to do by accident.
fn detail_image(
    ui: &mut egui::Ui,
    textures: &mut std::collections::HashMap<(usize, String), egui::TextureHandle>,
    r: usize,
    header: &str,
    image: &crate::report::model::ImageData,
    value: &str,
    app: &GuiApp,
) {
    let key = (r, header.to_string());
    let tex = textures.entry(key).or_insert_with(|| {
        let colour = ::image::load_from_memory(&image.bytes)
            .map(|i| {
                let rgba = i.to_rgba8();
                let (w, h) = rgba.dimensions();
                egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], rgba.as_raw())
            })
            // A picture PaperBoy embedded but egui cannot decode is a 1x1
            // placeholder rather than a panic: the rest of the panel is still
            // worth reading, and the cell text below says where it came from.
            .unwrap_or_else(|_| egui::ColorImage::new([1, 1], vec![egui::Color32::TRANSPARENT]));
        ui.ctx().load_texture(
            format!("pb_detail_{r}_{header}"),
            colour,
            egui::TextureOptions::LINEAR,
        )
    });
    // Shown as large as the panel allows, up to the picture's own size: this is
    // the view the grid thumbnail cannot give, so shrinking it further would
    // defeat the point of opening the row.
    let natural = egui::vec2(tex.size()[0] as f32, tex.size()[1] as f32);
    let scale = (ui.available_width() / natural.x).min(1.0);
    ui.add(egui::Image::new((tex.id(), natural * scale)))
        .on_hover_text(value);
    // The caption is the picture's path, and it is read -- it says which file
    // of a thousand this row is. At the small text style it was a grey line too
    // fine to make out under a full-size photograph, so it is set at body size
    // and selectable, so a path can be picked up and pasted somewhere useful.
    // Laid out explicitly left-to-right rather than in the caller's layout:
    // the drill-down's columns are *justified*, and a justified wrapped label
    // spreads its first line's glyphs across the full width — which turned the
    // path into `/ h o m e / j o n a…`.
    ui.with_layout(egui::Layout::top_down(egui::Align::LEFT), |ui| {
        ui.add(egui::Label::new(RichText::new(value).color(ui.visuals().weak_text_color())).wrap());
    });
    let _ = app;
}

/// The rows the results view should show, or `None` to show every row
/// unfiltered.
///
/// `None` while a run is `live`, deliberately: `visible_rows` drops pending
/// rows, so filtering a streaming run would empty the very view being watched,
/// and the metric figures would be computed over a half-filled table and tick
/// misleadingly as rows land.
///
/// `selected` is clamped rather than validated: the set of filters worth
/// offering comes from the result, so a selection made against an earlier
/// result can point past the end of the current one.
fn visible_for_view(
    result: &ReportResult,
    columns: &[crate::report::model::OutputColumn],
    header: &crate::report::flow::Header,
    live: bool,
    selected: &mut usize,
    find: &str,
) -> Option<Vec<usize>> {
    if live {
        return None;
    }
    // The *full* list, matrix cells included: a matrix cell is picked by index
    // exactly as a button is, so clamping against the buttons alone would throw
    // away every selection made by clicking the matrix.
    let (filters, _) =
        crate::report::filter::all_filters(result, result.metrics(columns, header).as_ref());
    *selected = (*selected).min(filters.len().saturating_sub(1));
    let labels = crate::report::labels::LabelMap::parse(&header.labels());
    Some(crate::report::filter::visible_rows(
        result,
        columns,
        &labels,
        filters.get(*selected).unwrap_or(&RowFilter::All),
        find,
    ))
}

/// The results view's metric cards: the same figures the interactive HTML
/// export leads with, drawn natively so a ground-truthed run can be judged
/// without exporting it first.
///
/// The *labels* are translated here even though the exported document's are
/// not: this is application chrome, and the reason the export stays English is
/// that a shared file has no reader whose language is known.
fn metric_cards(
    th: &GuiTheme,
    ui: &mut egui::Ui,
    app: &GuiApp,
    metrics: &crate::report::metrics::Metrics,
) {
    let tinted = |ui: &mut egui::Ui, k: &str, v: &str, colour: egui::Color32| {
        egui::Frame::group(ui.style())
            .inner_margin(egui::Margin::symmetric(8, 4))
            .show(ui, |ui| {
                ui.vertical(|ui| {
                    ui.label(RichText::new(k).size(11.0).color(th.dim));
                    ui.label(RichText::new(v).strong().color(colour));
                });
            });
    };
    let card = |ui: &mut egui::Ui, k: &str, v: &str| tinted(ui, k, v, th.text);

    // How the run moved comes first when there is a baseline to have moved
    // from: the accuracy cards below cannot tell a run that fixed three rows
    // and broke three others from one that touched nothing.
    if let Some(mv) = &metrics.movement {
        ui.horizontal_wrapped(|ui| {
            if mv.is_still() {
                card(
                    ui,
                    app.strings.report_metric_movement,
                    app.strings.report_metric_nothing_moved,
                );
            } else {
                tinted(
                    ui,
                    app.strings.report_metric_fixed,
                    &mv.fixed.to_string(),
                    th.ok,
                );
                // The regression count is the one figure here anybody is
                // scanning for, so it is the one that stays plain at zero: red
                // on a `0` teaches the eye to ignore the colour.
                tinted(
                    ui,
                    app.strings.report_metric_regressed,
                    &mv.regressed.to_string(),
                    if mv.regressed > 0 { th.err } else { th.text },
                );
            }
            if mv.still_wrong > 0 {
                card(
                    ui,
                    app.strings.report_metric_still_wrong,
                    &mv.still_wrong.to_string(),
                );
            }
        });
        ui.add_space(2.0);
    }
    // The roll-up first when there is one -- it answers "did this run pass?",
    // and the per-column breakdown is the follow-up question.
    for m in metrics.overall.iter().chain(metrics.columns.iter()) {
        ui.horizontal_wrapped(|ui| {
            card(
                ui,
                &format!("{}{}", m.header, app.strings.report_metric_compared),
                &format!("{} / {}", m.compared, m.total),
            );
            card(
                ui,
                app.strings.report_metric_incorrect,
                &m.incorrect.to_string(),
            );
            card(
                ui,
                app.strings.report_metric_accuracy,
                m.accuracy_text().as_deref().unwrap_or("\u{2014}"),
            );
        });
        ui.add_space(2.0);
    }
}

/// One column's confusion matrix as a heatmap: truth down the side, the value
/// the run produced across the top.
///
/// Every non-empty cell is a button that selects the rows it counted — "which
/// seven rows are those?" is the first question anyone asks of an off-diagonal
/// count, and the alternative is reading the grid looking for them by hand.
///
/// The shading comes from [`crate::report::metrics::heat_rgb`], the same ramp
/// the HTML export uses, so one matrix cannot come out looking like two.
#[allow(clippy::too_many_arguments)]
fn confusion_matrix(
    th: &GuiTheme,
    ui: &mut egui::Ui,
    app: &GuiApp,
    column: &str,
    matrix: &crate::report::metrics::ConfusionMatrix,
    filters: &[RowFilter],
    selected: &mut usize,
) {
    let max = matrix.max();
    // A matrix is read by comparing cells, which needs them big enough to scan
    // at a glance: at body size the counts and their axis labels were a grid of
    // small grey numbers. Sized off the body height so it still follows the
    // app's text scale rather than being pinned to a pixel count.
    let base = ui.text_style_height(&egui::TextStyle::Body);
    let cell_font = base * 1.15;
    let axis_font = base * 1.0;
    // Every cell the same width, so a column of counts lines up and the block
    // of colour reads as a heatmap rather than as ragged boxes.
    let cell_w = (base * 3.2).max(
        matrix
            .axis
            .iter()
            .map(|l| l.chars().count())
            .max()
            .unwrap_or(1) as f32
            * base
            * 0.45,
    );
    egui::CollapsingHeader::new(RichText::new(column).strong().size(base * 1.1))
        .id_salt(("pb_matrix", column))
        .default_open(true)
        .show(ui, |ui| {
            egui::Grid::new(("pb_matrix_grid", column))
                .spacing(egui::vec2(2.0, 2.0))
                .show(ui, |ui| {
                    ui.label("");
                    for label in &matrix.axis {
                        cell_slot(ui, cell_w, base, |ui| {
                            ui.label(RichText::new(label).color(th.dim).size(axis_font));
                        });
                    }
                    ui.end_row();
                    for (t, truth) in matrix.axis.iter().enumerate() {
                        ui.label(RichText::new(truth).color(th.dim).size(axis_font));
                        for (p, answer) in matrix.axis.iter().enumerate() {
                            let n = matrix.counts[t][p];
                            let ([r, g, b], hot) =
                                crate::report::metrics::heat_rgb(n, max);
                            let fg = if hot {
                                egui::Color32::WHITE
                            } else {
                                egui::Color32::from_rgb(0x12, 0x30, 0x5a)
                            };
                            // An empty cell counted nothing, so there is
                            // nothing for it to show -- it stays a plain
                            // number rather than a button that selects no rows.
                            let pick = (n > 0)
                                .then(|| {
                                    filters.iter().position(|f| {
                                        matches!(
                                            f,
                                            RowFilter::MatrixCell { column: c, truth: tr, answer: a }
                                            if c == column && tr == truth && a == answer
                                        )
                                    })
                                })
                                .flatten();
                            let framed = egui::Frame::NONE
                                .fill(egui::Color32::from_rgb(r, g, b))
                                .inner_margin(egui::Margin::symmetric(6, 6))
                                .show(ui, |ui| {
                                    ui.set_min_width(cell_w);
                                    ui.vertical_centered(|ui| {
                                        ui.add(
                                            egui::Label::new(
                                                RichText::new(n.to_string())
                                                    .color(fg)
                                                    .size(cell_font),
                                            )
                                            .selectable(false),
                                        );
                                    });
                                });
                            // The *cell* is the target, not the digits in it. A
                            // sense on the label alone made the clickable area
                            // the width of the number -- so a "7" was a few
                            // pixels wide in the middle of a large block of
                            // colour that looked like a button and wasn't.
                            // Interacted after the frame is drawn, so it sits
                            // over the whole painted cell; there is nothing
                            // interactive inside for it to steal a click from.
                            let cell = framed.response.rect;
                            if let Some(i) = pick {
                                let resp = ui.interact(
                                    cell,
                                    ui.id().with(("pb_matrix_cell", column, t, p)),
                                    egui::Sense::click(),
                                );
                                if resp
                                    .on_hover_cursor(egui::CursorIcon::PointingHand)
                                    .on_hover_text(app.strings.help_report_matrix_cell)
                                    .clicked()
                                {
                                    *selected = i;
                                }
                            }
                        }
                        ui.end_row();
                    }
                });
            let clean = if matrix.is_diagonal() {
                app.strings.report_matrix_all_matched
            } else {
                ""
            };
            ui.label(
                RichText::new(format!(
                    "{} {clean}",
                    app.strings
                        .report_matrix_caption
                        .replace("{n}", &matrix.total().to_string())
                ))
                .color(th.dim)
                .size(axis_font * 0.95),
            );
        });
    ui.add_space(2.0);
}

/// The row-filter buttons, the find box and the row count.
///
/// The buttons are drawn only when there is more than one -- `available` always
/// offers `All`, and a lone `All` is a control whose only possible effect is the
/// state it is already in (the HTML export hides it for the same reason). The
/// find box and count are always drawn: those help in any report.
#[allow(clippy::too_many_arguments)]
fn filter_bar(
    th: &GuiTheme,
    ui: &mut egui::Ui,
    app: &GuiApp,
    filters: &[RowFilter],
    selected: &mut usize,
    find: &mut String,
    shown: usize,
    total: usize,
) {
    ui.horizontal_wrapped(|ui| {
        if filters.len() > 1 {
            for (i, f) in filters.iter().enumerate() {
                if ui
                    .selectable_label(i == *selected, filter_label(&app.strings, f))
                    .on_hover_text(app.strings.help_report_filter)
                    .clicked()
                {
                    *selected = i;
                }
            }
            ui.separator();
        }
        ui.add(
            egui::TextEdit::singleline(find)
                .desired_width(180.0)
                .hint_text(app.strings.report_find_placeholder),
        );
        ui.colored_label(
            th.dim,
            app.strings
                .report_rows_shown
                .replace("{shown}", &shown.to_string())
                .replace("{total}", &total.to_string()),
        );
    });
    ui.add_space(2.0);
}

/// A filter's button text in the user's language.
///
/// [`RowFilter::label`] is deliberately English -- it names buttons in an
/// exported document that is read by whoever it is sent to -- so the in-app bar
/// translates the fixed filters here and falls back to that label for a matrix
/// cell, whose text is the report's own data and so is not translatable.
fn filter_label(s: &crate::i18n::Strings, f: &RowFilter) -> String {
    match f {
        RowFilter::All => s.report_filter_all.to_string(),
        RowFilter::Differ => s.report_filter_differences.to_string(),
        RowFilter::Incorrect => s.report_filter_incorrect.to_string(),
        RowFilter::Regressed => s.report_filter_regressions.to_string(),
        RowFilter::MatrixCell { .. } => f.label(),
    }
}

/// The narrowest a column is allowed to get when the table is squeezed, in
/// pixels — roughly four characters plus the ellipsis. Below this a column
/// shows nothing useful, so it is better to stop shrinking and let the table
/// scroll sideways instead.
const MIN_COL_W: f32 = 46.0;

/// Share `avail` pixels out between columns that would naturally like
/// `natural` pixels each.
///
/// Two jobs in one, because they are the same sum from opposite sides:
///
/// * **Too much room** — the widths are grown in proportion so the table fills
///   the window rather than huddling at the left edge.
/// * **Not enough room** — the widths are *water-filled*: a level is found such
///   that every column wider than it is cut down to it and every column
///   narrower than it is left alone. Shrinking proportionally instead would
///   punish a 3-character `Status` column just as hard as a sprawling body
///   column, which is exactly backwards; capping the greedy columns first is
///   what keeps everything on screen and still legible.
///
/// Columns are never squeezed below [`MIN_COL_W`]. If even that doesn't fit,
/// the returned widths deliberately overflow `avail` — the caller's horizontal
/// scroll bar is the honest answer at that point, and the cell viewer is there
/// for whatever still gets clipped.
fn fit_column_widths(natural: &[f32], avail: f32, spacing: f32) -> Vec<f32> {
    if natural.is_empty() {
        return Vec::new();
    }
    let gaps = spacing * (natural.len() as f32 - 1.0);
    let budget = (avail - gaps).max(0.0);
    let total: f32 = natural.iter().sum();

    if total <= 0.0 {
        return vec![(budget / natural.len() as f32).max(MIN_COL_W); natural.len()];
    }
    if total <= budget {
        // Grow in proportion to what each column asked for, so the extra room
        // goes to the columns most likely to be truncating.
        let scale = budget / total;
        return natural.iter().map(|w| w * scale).collect();
    }

    // Water-fill: walk the columns narrowest-first, handing each the smaller of
    // what it wants and an even share of what is left.
    let mut order: Vec<usize> = (0..natural.len()).collect();
    order.sort_by(|&a, &b| natural[a].total_cmp(&natural[b]));
    let mut out = vec![0.0f32; natural.len()];
    let mut left = budget;
    for (i, &c) in order.iter().enumerate() {
        let share = left / (order.len() - i) as f32;
        if natural[c] <= share {
            out[c] = natural[c];
            left -= natural[c];
        } else {
            out[c] = share;
            left -= share;
        }
    }
    out.iter().map(|w| w.max(MIN_COL_W)).collect()
}

/// Render the results as a scrollable table: a header row, one row per data row
/// (greyed/marked by its streaming [`RowState`]), then any STATISTICS summary
/// rows. Mirrors the TUI's `report_grid_lines` semantics.
fn results_grid(
    th: &GuiTheme,
    ui: &mut egui::Ui,
    result: &ReportResult,
    columns: &[crate::report::model::OutputColumn],
    states: Option<&[RowState]>,
    visible: Option<&[usize]>,
    detail_columns: &[&crate::report::model::OutputColumn],
    open_detail: &mut Option<usize>,
) -> Option<CellInspector> {
    let show_icons = states.is_some();
    // The expander column is offered only when *some* row has something to
    // drill into: on a run with no pictures and no `DETAIL` columns it would be
    // a column of blanks.
    let expandable: std::collections::HashSet<usize> = (0..result.rows.len())
        .filter(|&r| {
            !crate::report::detail::sections(result, r, columns, detail_columns).is_empty()
        })
        .collect();
    let show_expanders = !expandable.is_empty();
    let mut opened: Option<CellInspector> = None;
    let widths = fitted_column_widths(ui, result, columns, show_icons);
    let row_h = ui.text_style_height(&egui::TextStyle::Body);

    egui::ScrollArea::both()
        .auto_shrink([false, false])
        .show(ui, |ui| {
            egui::Grid::new("report_results_grid")
                .striped(true)
                .spacing(egui::vec2(SPACING_X, 3.0))
                .show(ui, |ui| {
                    // Header row. The expander column comes first, where a
                    // tree control's twisty lives.
                    if show_expanders {
                        ui.label(" ");
                    }
                    if show_icons {
                        ui.label(" ");
                    }
                    for (c, col) in columns.iter().enumerate() {
                        let w = widths.get(c).copied().unwrap_or(MIN_COL_W);
                        cell_slot(ui, w, row_h, |ui| {
                            ui.add(
                                egui::Label::new(
                                    RichText::new(&col.header).strong().color(th.accent),
                                )
                                .truncate(),
                            )
                            .on_hover_text(&col.header);
                        });
                    }
                    ui.end_row();

                    // Data rows. `visible` is the filtered row order when the
                    // view is filtering; the column widths are still measured
                    // over *every* row, so narrowing the rows doesn't make the
                    // table jump about as the reader types in the find box.
                    let order: Vec<usize> = match visible {
                        Some(v) => v.to_vec(),
                        None => (0..result.rows.len()).collect(),
                    };
                    for i in order {
                        let Some(row) = result.rows.get(i) else {
                            continue;
                        };
                        let state = states.and_then(|s| s.get(i)).copied();
                        // A click anywhere on the row opens its drill-down --
                        // including the gaps between columns, and the empty
                        // space inside a column that its text doesn't fill. The
                        // target is reserved *before* the cells so the cells,
                        // added after, still win where they overlap it (egui
                        // hit-tests in favour of the later widget), which keeps
                        // each cell's own hover text and its inspector click.
                        // Its size is known up front: the widths were measured
                        // before the loop.
                        let row_target = expandable.contains(&i).then(|| {
                            let w: f32 = widths.iter().sum::<f32>()
                                + SPACING_X * widths.len() as f32
                                + if show_expanders { 24.0 } else { 0.0 }
                                + if show_icons { 18.0 + SPACING_X } else { 0.0 };
                            let rect =
                                egui::Rect::from_min_size(ui.cursor().min, egui::vec2(w, row_h));
                            let r = ui.interact(
                                rect,
                                ui.id().with(("pb_result_row", i)),
                                egui::Sense::click(),
                            );
                            // The pointing hand has to cover the whole row, not
                            // just the words in it. `hovered()` is no use here:
                            // the cells are drawn after this target and take the
                            // hover from it wherever they overlap -- over their
                            // own text, which is exactly the part that most
                            // looks clickable. `contains_pointer` doesn't care
                            // who is on top, so the cursor stays a hand all the
                            // way across.
                            if r.contains_pointer() {
                                ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
                            }
                            r
                        });
                        if show_expanders {
                            let has = expandable.contains(&i);
                            let open = *open_detail == Some(i);
                            // A row with nothing to drill into gets a blank
                            // rather than a caret that opens an empty panel.
                            if has {
                                let glyph = if open {
                                    super::icons::CARET_DOWN
                                } else {
                                    super::icons::CARET_RIGHT
                                };
                                if ui
                                    .add(
                                        egui::Button::new(RichText::new(glyph).color(if open {
                                            th.accent
                                        } else {
                                            th.dim
                                        }))
                                        .frame(false),
                                    )
                                    .clicked()
                                {
                                    // Clicking the open row's caret closes it,
                                    // so the panel can be got rid of the same
                                    // way it was opened.
                                    *open_detail = (!open).then_some(i);
                                }
                            } else {
                                ui.label(" ");
                            }
                        }
                        if show_icons {
                            let (glyph, colour) = match state {
                                Some(RowState::Running) => (super::icons::RUNNING, th.pending),
                                Some(RowState::Finished) => (super::icons::PASS, th.ok),
                                _ => (super::icons::ROW_SCHEDULED, th.dim),
                            };
                            ui.colored_label(colour, glyph);
                        }
                        let text_col = match state {
                            Some(RowState::Running) => th.pending,
                            Some(RowState::Scheduled) => th.dim,
                            _ => th.text,
                        };
                        for (c, col) in columns.iter().enumerate() {
                            let full = col.value(row, &result.no_match_marker);
                            let w = widths.get(c).copied().unwrap_or(MIN_COL_W);
                            cell_slot(ui, w, row_h, |ui| {
                                if let Some(ins) = result_cell(ui, text_col, &col.header, &full) {
                                    // Clicking anywhere in a row that has a
                                    // drill-down opens it: the panel is the
                                    // fuller answer to "what is this row?" than
                                    // one cell's text, and it is what the
                                    // interactive HTML export does too. A row
                                    // with nothing to drill into keeps the cell
                                    // inspector, which is otherwise the only
                                    // way to read a truncated value.
                                    if expandable.contains(&i) {
                                        *open_detail = Some(i);
                                    } else {
                                        opened = Some(ins);
                                    }
                                }
                            });
                        }
                        if row_target.is_some_and(|r| r.clicked()) {
                            *open_detail = Some(i);
                        }
                        ui.end_row();
                    }

                    // STATISTICS summary rows (a footer, distinguished by italic accent).
                    for srow in result.summary_rows(columns) {
                        if show_expanders {
                            ui.label(" ");
                        }
                        if show_icons {
                            ui.label(" ");
                        }
                        for (c, col) in columns.iter().enumerate() {
                            let full = srow.text_cell(c);
                            let cell = flatten_cell(&full);
                            let w = widths.get(c).copied().unwrap_or(MIN_COL_W);
                            cell_slot(ui, w, row_h, |ui| {
                                let resp = ui
                                    .add(
                                        egui::Label::new(
                                            RichText::new(truncate_cell(&cell))
                                                .italics()
                                                .color(th.accent),
                                        )
                                        .truncate()
                                        .sense(egui::Sense::click()),
                                    )
                                    .on_hover_text(&cell);
                                if resp.clicked() {
                                    opened = Some(CellInspector {
                                        title: col.header.clone(),
                                        content: pretty_json_cell(&full),
                                    });
                                }
                            });
                        }
                        ui.end_row();
                    }
                });
        });
    opened
}

/// The gap left between a tethered chip and the chip it qualifies: none, so the
/// two sit flush and their touching borders form the divider of a single
/// segmented pill (see [`link_tethers`]).
///
/// Applied while laying out the *anchor*, not the tethered chip. egui advances
/// the cursor — spacing included — as each widget is allocated, so the gap
/// between two chips is the one in effect when the **first** of them was added;
/// narrowing it just before the second has no effect on the space already left
/// behind it.
const TETHER_GAP: f32 = 0.0;

/// The corner radius of a chip.
///
/// Small on purpose. A large radius reads as a soft, toy-like pill; the shallow
/// one here still says "this is a discrete object you can pick up" without the
/// bubbliness. It is the single number most responsible for how playful or how
/// businesslike the flow looks, so it is worth keeping deliberately low.
const CHIP_RADIUS: u8 = 3;

/// Fully rounded corners, for a chip that never joins a neighbour.
const ROUND_CHIP: egui::CornerRadius = egui::CornerRadius::same(CHIP_RADIUS);

/// The corner radii for a chip, squaring off whichever edge it shares with a
/// tethered neighbour so the pair is drawn as one pill split into segments
/// rather than as two separate chips that happen to be adjacent.
fn chip_corners(chip: &Chip) -> egui::CornerRadius {
    let joined = |yes: bool| if yes { 0 } else { CHIP_RADIUS };
    egui::CornerRadius {
        nw: joined(chip.join_prev),
        sw: joined(chip.join_prev),
        ne: joined(chip.join_next),
        se: joined(chip.join_next),
    }
}

/// Work out how each tethered chip joins the chip it qualifies.
///
/// A tethered chip is drawn as the right-hand segment of a single pill: the
/// pair sits flush, the anchor keeps its rounded left corners and squares off
/// its right, and the hanger mirrors it, so one outline encloses both and their
/// touching borders read as a divider. Segmented controls and breadcrumbs
/// already teach that shape as "one control in two parts". The bracket this
/// replaces was drawn *beside* the chips, and a thin line in a muted grey read
/// as decoration — it never said which of the two owned the other.
///
/// Only the shape changes: each chip keeps the colour its own kind always has,
/// so a `SHOW` is recognisable as a `SHOW` wherever it appears. Restating the
/// ownership in the hue as well would trade that away for something the pill
/// already says.
fn link_tethers(chips: &mut [Chip]) {
    for i in 1..chips.len() {
        if !chips[i].tethered {
            continue;
        }
        chips[i - 1].join_next = true;
        chips[i].join_prev = true;
    }
}

/// Undo the join between `chips[i - 1]` and `chips[i]`, restoring both the
/// rounded corners and the normal inter-chip gap.
///
/// Used where the pair is about to stop being adjacent: either half is in hand,
/// or a hovering clause is about to be dropped between them. Merging across
/// that gap would say "these two are one thing" at exactly the moment the user
/// is separating them, and would leave a squared-off edge facing an empty slot.
fn split_tether(chips: &mut [Chip], i: usize) {
    chips[i - 1].join_next = false;
    chips[i].join_prev = false;
    chips[i].tethered = false;
}

/// Highlight both halves of a tethered pair while the pointer is over either of
/// them: a single outline around the two, which answers "what does this SHOW
/// belong to?" the moment the user goes looking, without adding anything to the
/// resting state of an already-busy line.
fn paint_tether_hover(ui: &egui::Ui, th: &GuiTheme, anchor: egui::Rect, hanger: egui::Rect) {
    let pair = anchor.union(hanger);
    // Suppressed mid-drag: the pointer is then carrying something, and an
    // outline under it reads as a drop target rather than as an explanation.
    if ui.ctx().dragged_id().is_some() || !ui.rect_contains_pointer(pair) {
        return;
    }
    // Also suppressed when the pointer is on a chip that a drag would lift on
    // its own: that chip gets its own outline (see `record_chip_hover`), and
    // two nested outlines around the same pointer say two different things
    // about what letting go would do. Resting on the *anchor* still draws the
    // pair, which is where "what does this belong to?" is actually asked.
    if ui
        .ctx()
        .data(|d| d.get_temp::<Option<egui::Rect>>(chip_hover_id()))
        .flatten()
        .is_some()
    {
        return;
    }
    ui.painter().rect_stroke(
        pair.expand(2.0),
        egui::CornerRadius::same(CHIP_RADIUS + 2),
        egui::Stroke::new(1.0, mix(th.panel, th.text, 0.75)),
        egui::StrokeKind::Outside,
    );
}

/// Horizontal spacing between the grid's columns.
const SPACING_X: f32 = 14.0;

/// The width to give each data column of `result` in the space `ui` has left:
/// what the column would like, fitted to the window by [`fit_column_widths`].
fn fitted_column_widths(
    ui: &egui::Ui,
    result: &ReportResult,
    columns: &[crate::report::model::OutputColumn],
    show_icons: bool,
) -> Vec<f32> {
    // The status-glyph column is a fixed narrow gutter, not a data column, so
    // it is taken off the top of the budget rather than shared in it.
    let icon_w = if show_icons { 18.0 + SPACING_X } else { 0.0 };
    let natural = cached_natural_widths(ui, result, columns);
    let avail = (ui.available_width() - icon_w).max(0.0);
    // Fitting is pure arithmetic over the naturals, so it stays uncached and
    // the grid still follows the window as it is dragged.
    fit_column_widths(&natural, avail, SPACING_X)
}

/// [`natural_column_widths`], reused between frames while nothing it depends on
/// has changed.
///
/// Measuring is not cheap — a `String` per cell, a text layout per column, and
/// a full pass over the summary rows — and the grid is redrawn on every frame,
/// including the ones where all that happened was the mouse moving. The widths
/// only depend on the values, the columns and the font, so they are kept in
/// egui's own per-frame memory (rather than on `ReportEditor`) because the grid
/// is drawn by free functions that are also called from the dry-run preview and
/// from tests.
fn cached_natural_widths(
    ui: &egui::Ui,
    result: &ReportResult,
    columns: &[crate::report::model::OutputColumn],
) -> Vec<f32> {
    let key = widths_fingerprint(ui, result, columns);
    let id = egui::Id::new("report_grid_widths");
    if let Some((cached_key, widths)) = ui.data(|d| d.get_temp::<(u64, Vec<f32>)>(id))
        && cached_key == key
    {
        return widths;
    }
    let widths = natural_column_widths(ui, result, columns);
    ui.data_mut(|d| d.insert_temp(id, (key, widths.clone())));
    widths
}

/// FNV-1a's starting value.
pub(super) const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;

/// FNV-1a over `bytes`, continuing from `seed`.
///
/// Used instead of a `DefaultHasher` per cell in [`widths_fingerprint`]: the
/// fingerprint runs over every cell of the table on every frame, and building a
/// SipHash state for each of tens of thousands of cells costs more than hashing
/// their bytes does. This is not a hash anyone attacks — it guards a cache of
/// column widths — so the cheap mixing function is the right one.
pub(super) fn fnv1a(bytes: &[u8], seed: u64) -> u64 {
    let mut h = seed;
    for b in bytes {
        h ^= *b as u64;
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

/// Everything [`natural_column_widths`] reads, in one number.
///
/// This hashes the cell *text* rather than something cheaper like the row
/// count, because a streaming run replaces rows in place: the grid is built as
/// a skeleton of empty rows and each one is overwritten as its result arrives,
/// so a key that only counted rows would pin the columns at the width of an
/// empty table for the whole run. Hashing the text is still far less work than
/// laying it out — no allocation, one pass — which is what makes the cache
/// worth having rather than a second copy of the same cost.
///
/// **Maintenance:** anything `natural_column_widths` starts reading has to be
/// added here too, or the widths will stop following it.
fn widths_fingerprint(
    ui: &egui::Ui,
    result: &ReportResult,
    columns: &[crate::report::model::OutputColumn],
) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    // The font decides how wide any of it renders.
    let font = egui::TextStyle::Body.resolve(ui.style());
    font.size.to_bits().hash(&mut h);
    format!("{:?}", font.family).hash(&mut h);
    result.no_match_marker.hash(&mut h);
    for col in columns {
        col.header.hash(&mut h);
        // A column's own definition decides what it pulls out of each row, and
        // its statistics decide whether there are summary rows to measure.
        format!("{:?}", col.stats).hash(&mut h);
        format!("{:?}", col.sources).hash(&mut h);
    }
    result.rows.len().hash(&mut h);
    for row in &result.rows {
        // `cells` and `vars` are hash maps, so their iteration order changes
        // from run to run. Combining each entry's hash with `^` makes the
        // fingerprint depend on the contents and not on the order they come
        // out in — the same trap that made the validation panel flicker.
        let mut cells = 0u64;
        for (k, v) in row.cells.iter().chain(&row.vars) {
            cells ^= fnv1a(k.as_bytes(), fnv1a(v.as_bytes(), FNV_OFFSET));
        }
        cells.hash(&mut h);
        row.target.hash(&mut h);
    }
    h.finish()
}

/// Lay a cell's content out in a slot exactly `w` wide.
///
/// `egui::Grid` sizes a column to its widest cell, so pinning every cell in a
/// column to the same width is what makes the column that width — and it keeps
/// the grid's striping and row alignment, which hand-rolling the rows would
/// throw away. `set_min_size` is the part that matters: without it a short
/// label would allocate only its own width and the column would collapse.
fn cell_slot(ui: &mut egui::Ui, w: f32, h: f32, add: impl FnOnce(&mut egui::Ui)) {
    ui.allocate_ui_with_layout(
        egui::vec2(w, h),
        egui::Layout::left_to_right(egui::Align::Center),
        |ui| {
            ui.set_min_size(egui::vec2(w, h));
            add(ui);
        },
    );
}

/// How wide each column would like to be: the width of its header or of its
/// longest value, whichever is greater.
///
/// Only the *longest-by-character-count* value in each column is actually
/// measured. Laying out every cell of a thousand-row report each frame to find
/// the widest pixel width would be far more work than the answer is worth, and
/// in a proportional font the longest string is almost always the widest one.
/// Where it isn't, the loser is truncated by a character or two — which the
/// cell viewer already covers.
fn natural_column_widths(
    ui: &egui::Ui,
    result: &ReportResult,
    columns: &[crate::report::model::OutputColumn],
) -> Vec<f32> {
    let font = egui::TextStyle::Body.resolve(ui.style());
    // Computed once, not once per column: `summary_rows` walks every row of
    // every column, so calling it inside the per-column loop below made finding
    // the widths quadratic in the number of columns.
    let summary = result.summary_rows(columns);
    // Leave room for the cell's own padding so text isn't flush against the
    // next column.
    let pad = 6.0;
    let measure = |text: &str| {
        ui.painter()
            .layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE)
            .size()
            .x
            + pad
    };

    columns
        .iter()
        .enumerate()
        .map(|(c, col)| {
            let mut longest = String::new();
            let mut longest_len = 0usize;
            let mut consider = |text: String| {
                let n = text.chars().count();
                if n > longest_len {
                    longest_len = n;
                    longest = text;
                }
            };
            for row in &result.rows {
                consider(truncate_cell(&flatten_cell(
                    &col.value(row, &result.no_match_marker),
                )));
            }
            for srow in &summary {
                consider(truncate_cell(&flatten_cell(&srow.text_cell(c))));
            }
            measure(&col.header).max(measure(&longest))
        })
        .collect()
}

/// A single clickable results cell: shows the truncated one-line value, the full
/// value on hover, and — when clicked — returns a [`CellInspector`] carrying the
/// cell's full (JSON-pretty-printed) value so a long cell can be read in full.
fn result_cell(
    ui: &mut egui::Ui,
    text_col: Color32,
    header: &str,
    full: &str,
) -> Option<CellInspector> {
    let cell = flatten_cell(full);
    let resp = ui
        .add(
            egui::Label::new(RichText::new(truncate_cell(&cell)).color(text_col))
                .truncate()
                .sense(egui::Sense::click()),
        )
        .on_hover_cursor(egui::CursorIcon::PointingHand)
        .on_hover_text(cell);
    resp.clicked().then(|| CellInspector {
        title: header.to_string(),
        content: pretty_json_cell(full),
    })
}

/// Pretty-print a cell whose whole trimmed value is a single JSON object/array
/// (e.g. a captured response body) so the inspector shows an indented,
/// one-field-per-line view; anything else is returned unchanged. Mirrors the
/// TUI's `pretty_print_json_cell`.
fn pretty_json_cell(raw: &str) -> String {
    let trimmed = raw.trim();
    if !(trimmed.starts_with('{') || trimmed.starts_with('[')) {
        return raw.to_string();
    }
    match serde_json::from_str::<serde_json::Value>(trimmed) {
        Ok(value) => serde_json::to_string_pretty(&value).unwrap_or_else(|_| raw.to_string()),
        Err(_) => raw.to_string(),
    }
}

/// Collapse a cell's newlines to a single line (a response body can be huge).
fn flatten_cell(value: &str) -> String {
    if value.contains(['\n', '\r']) {
        value.replace("\r\n", "").replace(['\n', '\r'], "")
    } else {
        value.to_string()
    }
}

/// Per-cell display cap so one wide cell can't push the grid off-screen; the
/// full value is available on hover. Mirrors the TUI's `MAX_COL_WIDTH`.
fn truncate_cell(value: &str) -> String {
    const MAX: usize = 48;
    if value.chars().count() > MAX {
        let mut s: String = value.chars().take(MAX - 1).collect();
        s.push('');
        s
    } else {
        value.to_string()
    }
}

/// Open the native save picker for exporting the active report's results,
/// defaulting to a `.csv` beside the report (or in the current dir for a scratch
/// report).
fn open_export_dialog(app: &mut GuiApp) {
    // Seeded with the name the report's own `# output:` directive asks for, so
    // the common case is press-Export-and-done.
    let path = app
        .report_editor
        .as_ref()
        .map(|e| {
            let p = crate::report::writer::export_path(
                &e.report,
                &crate::report::writer::report_output_extension(&e.report),
            );
            // A saved report exports beside itself, so `export_path` already
            // gives an absolute name. A scratch report gives a bare filename,
            // which would land wherever PaperBoy happens to have been started
            // from -- anchor it to the report's own base directory, the folder
            // the terminal UI's picker opens in.
            if p.is_absolute() {
                p
            } else {
                crate::report::context::report_base_dir(
                    &e.flow.clone().unwrap_or_default(),
                    e.report.path.as_deref(),
                )
                .0
                .join(p)
            }
        })
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|| "results.csv".to_string());
    app.dialog = Some(super::app::Dialog::ExportResults { path });
}

/// The Scratch-style block view: a toolbar plus the stacked, nested blocks.
fn blocks_view(ed: &mut ReportEditor, app: &mut GuiApp, ui: &mut egui::Ui) {
    let th = app.theme;

    if let Some(err) = &ed.parse_error {
        ui.add_space(6.0);
        ui.colored_label(th.err, app.strings.report_nodes_parse_error);
        ui.colored_label(th.dim, err);
        ui.separator();
        // Fall back to the source view's diagnostics panel so the user can fix it.
        diagnostics_panel(ed, app, ui);
        return;
    }
    let Some(flow) = ed.flow.clone() else {
        return;
    };

    // Which request names resolve in the bound collection (for green/amber).
    let bound = context::resolve_bound_collection(
        &app.session.collections,
        &flow,
        ed.report.path.as_deref(),
    );
    let entries = bound
        .map(|ci| app.session.collections[ci].entries.as_slice())
        .unwrap_or(&[]);
    let choices = context::request_choices(entries, &ed.helpers);
    // Primary collection first (guaranteed by `request_choices`), so a newly
    // dropped REQUEST block — which seeds itself from the first title — never
    // defaults to a helper.
    let titles: Vec<String> = choices.iter().map(|c| c.qualified.clone()).collect();
    let helpers = ed.helpers.clone();
    let resolves =
        move |name: &str| crate::report::run::resolve_qualified(entries, &helpers, name).is_some();
    let rows = flatten(&flow, &resolves);

    let mut acts: Vec<Act> = Vec::new();

    // Toolbar for the current selection.
    ui.horizontal(|ui| {
        let sel_pos = rows
            .iter()
            .position(|r| r.path == ed.selection && r.kind != RowKind::LoopEnd)
            .or_else(|| rows.iter().position(|r| r.kind == RowKind::Begin))
            .unwrap_or(0);
        if ui
            .button(format!(
                "{} {}",
                super::icons::PLUS,
                app.strings.gui_report_add_block
            ))
            .clicked()
        {
            acts.push(Act::OpenPalette(insert_pos_after(&rows, sel_pos)));
        }
        let on_node = !ed.selection.is_empty();
        if ui
            .add_enabled(
                on_node,
                egui::Button::new(super::icons::CARET_UP.to_string()),
            )
            .on_hover_text(app.strings.gui_report_move_up)
            .clicked()
        {
            acts.push(Act::Move {
                path: ed.selection.clone(),
                up: true,
            });
        }
        if ui
            .add_enabled(
                on_node,
                egui::Button::new(super::icons::CARET_DOWN.to_string()),
            )
            .on_hover_text(app.strings.gui_report_move_down)
            .clicked()
        {
            acts.push(Act::Move {
                path: ed.selection.clone(),
                up: false,
            });
        }
        if ui
            .add_enabled(
                on_node,
                egui::Button::new(format!(
                    "{} {}",
                    super::icons::TRASH,
                    app.strings.gui_report_delete_block
                )),
            )
            .clicked()
        {
            acts.push(Act::DeletePath(ed.selection.clone()));
        }
    });
    ui.separator();

    // The insert palette popup (the click-based Add flow, with request-name
    // picking) is shown inline when open — complementary to the always-visible
    // drag palette below.
    if ed.palette.is_some() {
        palette_panel(ed, app, ui, &titles, &mut acts);
    }

    // ── Two panes: the always-visible drag palette (left) and the report's
    // stacked blocks (right). Blocks are dropped from the palette onto a row to
    // insert after it (onto a FOR header inserts inside it; onto Begin inserts
    // at the top). Reserve room for the diagnostics panel below.
    let avail = ui.available_height();
    let diag_h = ed.diag_h.clamp(48.0, (avail - 120.0).max(48.0));
    let body_h = (avail - diag_h - 12.0).max(120.0);
    ui.allocate_ui(egui::vec2(ui.available_width(), body_h), |ui| {
        ui.horizontal_top(|ui| {
            // The palette column width is user-adjustable via the divider drawn
            // just after it (mirrors the diagnostics splitter's drag model).
            let palette_w = ed
                .palette_w
                .clamp(96.0, (ui.available_width() - 160.0).max(96.0));
            ui.allocate_ui_with_layout(
                egui::vec2(palette_w, body_h),
                egui::Layout::top_down(egui::Align::Min),
                |ui| {
                    ui.set_min_width(palette_w);
                    ui.set_max_width(palette_w);
                    egui::ScrollArea::vertical()
                        .id_salt("pt_palette")
                        .auto_shrink([false, false])
                        .show(ui, |ui| palette_list(app, ui));
                },
            );
            palette_splitter(ed, ui, body_h);
            ui.vertical(|ui| {
                egui::ScrollArea::vertical()
                    .id_salt("pt_blocks")
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        // A click on empty space in the blocks pane deselects.
                        // This background sense is registered *before* the rows
                        // so the chips (added on top, each sensing its own
                        // click) win clicks that land on them; the background
                        // only fires where no chip caught the click.
                        let bg = ui.interact(
                            ui.max_rect(),
                            ui.id().with("pt_bg_deselect"),
                            egui::Sense::click(),
                        );
                        // Whole-report settings, pinned above BEGIN (see
                        // `header_strip`) — deliberately outside the row loop so
                        // no drop target, drag lift or selection ever reaches
                        // them.
                        header_strip(ed, app, ui, &mut acts);
                        ui.add_space(4.0);
                        let mut lift = DragLift::default();
                        let mut hovers: Vec<RowHover> = Vec::new();
                        for (i, row) in rows.iter().enumerate() {
                            let selected = row.path == ed.selection
                                && (row.kind != RowKind::LoopEnd || ed.selection.is_empty());
                            let drop_pos = insert_pos_after(&rows, i);
                            if let Some(h) = block_row(
                                ed, app, ui, row, i, selected, &drop_pos, &titles, &mut lift,
                                &mut acts,
                            ) {
                                hovers.push(h);
                            }
                        }
                        // Now that every row has been measured, light the block
                        // under the pointer and everything a drag would take
                        // with it (see `paint_hover_group`).
                        paint_hover_group(ui, &th, &hovers);
                        // A report with no steps is where every new report
                        // starts, and an empty gap between BEGIN and END says
                        // nothing about what to do next — the palette's own
                        // hint is over in the other column, easy to skim past.
                        if rows.is_empty() {
                            empty_flow_hint(ui, &th, &app.strings);
                        }
                        // Every lifted row is now in the drag layer, so the
                        // whole picked-up subtree can be moved under the pointer
                        // in one go (see `DragLift`).
                        lift.follow_pointer(ui.ctx());
                        // Close the flow with an `END` matching the `BEGIN` at
                        // the top, so the whole report reads as one bracketed
                        // block the way each FOR loop does. It is drawn here
                        // rather than emitted by the shared `flatten` because it
                        // is pure punctuation: there is no node to select, move
                        // or drop onto, and adding a row would shift every index
                        // the terminal UI's node editor navigates by.
                        flow_end_row(ui, &th, &app.strings);
                        // The empty space under the last row is itself a drop
                        // target: dropping a base block (or an existing row)
                        // anywhere below the report appends it as the last
                        // top-level line.
                        tail_drop_zone(ui, &th, flow.nodes.len(), &titles, &mut acts);
                        if bg.clicked() && !ed.selection.is_empty() {
                            acts.push(Act::Select(Vec::new()));
                        }
                    });
            });
        });
    });

    // Delete key removes the selection (but not while a text field has focus).
    let typing = ui.memory(|m| m.focused().is_some());
    if !typing && !ed.selection.is_empty() && ui.input(|i| i.key_pressed(egui::Key::Delete)) {
        acts.push(Act::DeletePath(ed.selection.clone()));
    }

    // The delete drop target lives here — a distinct full-width bar that only
    // appears while a block/chip is being dragged, so it never reads as just
    // another palette block.
    if egui::DragAndDrop::has_payload_of_type::<DragItem>(ui.ctx()) {
        ui.add_space(4.0);
        trash_bar(app, ui, &mut acts);
    }

    diag_splitter(ed, ui);
    diagnostics_panel(ed, app, ui);

    apply_block_actions(ed, app, acts);
    let _ = th;
}

/// The base blocks the palette offers, in display order. Each drops in as a new
/// statement row.
///
/// `ReportRequest` is the one kind deliberately absent: a reported request is
/// composed by dropping the `REPORT` modifier onto a `REQUEST`, so offering both
/// would be two routes to the same block. `ReportVar` is *not* such a case —
/// dropping `REPORT` on a `VARIABLE` only reports a variable this flow sets
/// right there, which leaves no way at all to report a captured value or a loop
/// variable — so it is offered as a block of its own.
const BASE_KINDS: [NodeKind; 8] = [
    NodeKind::Request,
    NodeKind::ReportVar,
    NodeKind::ReportComputed,
    NodeKind::Assign,
    NodeKind::List,
    NodeKind::ForFiles,
    NodeKind::ForFolders,
    NodeKind::ForEnvs,
];

/// The always-visible palette, split into two groups: **Blocks** (base
/// statements, dragged into the gaps between rows to insert a new line) and
/// **Modifiers** (dragged *onto* a row to attach REPORT / PARALLEL / WITH / AS).
/// Drag-only — the toolbar's "Add block" popup still covers click-based insert.
/// (The delete drop target is a separate bar shown at the foot of the editor
/// while dragging — see [`trash_bar`].)
fn palette_list(app: &GuiApp, ui: &mut egui::Ui) {
    let th = app.theme;
    ui.label(
        RichText::new(app.strings.gui_report_palette_blocks)
            .strong()
            .color(th.text),
    );
    ui.colored_label(th.dim, app.strings.gui_report_palette_hint);
    ui.add_space(2.0);
    for (i, kind) in BASE_KINDS.into_iter().enumerate() {
        let base = kind_color(kind, &th);
        let id = ui.id().with(("pt_base_chip", i));
        let src = ui.dnd_drag_source(id, kind, |ui| {
            palette_chip(ui, &th, kind.label(&app.strings), base);
        });
        // Remember how big the chip in hand is, so the drop markers down in the
        // flow can be drawn at that size rather than a full-width bar (see
        // `dragged_block_size`).
        if ui.ctx().is_being_dragged(id) {
            let size = src.response.rect.size();
            ui.ctx()
                .data_mut(|d| d.insert_temp(palette_drag_size_id(), size));
        }
        ui.add_space(4.0);
    }

    ui.add_space(6.0);
    ui.label(
        RichText::new(app.strings.gui_report_palette_mods)
            .strong()
            .color(th.text),
    );
    ui.colored_label(th.dim, app.strings.gui_report_palette_mods_hint);
    ui.add_space(2.0);
    for (i, m) in Modifier::ALL.into_iter().enumerate() {
        let base = modifier_color(m, &th);
        let id = ui.id().with(("pt_mod_chip", i));
        ui.dnd_drag_source(id, m, |ui| {
            palette_chip(ui, &th, m.label(&app.strings), base);
        });
        ui.add_space(4.0);
    }
}

/// The delete drop target: a distinct full-width bar shown at the foot of the
/// editor *only while a block/chip is being dragged*, so it never reads as just
/// another palette block. It reacts only to an in-report [`DragItem`]: a dropped
/// row is deleted, a dropped modifier chip is detached from its node.
fn trash_bar(app: &GuiApp, ui: &mut egui::Ui, acts: &mut Vec<Act>) {
    let th = app.theme;
    let frame = egui::Frame::NONE
        .fill(mix(th.panel, th.err, 0.14))
        .stroke(egui::Stroke::new(1.0, mix(th.panel, th.err, 0.5)))
        .inner_margin(egui::Margin::symmetric(8, 8))
        .corner_radius(BLOCK_RADIUS as u8);
    let resp = frame
        .show(ui, |ui| {
            ui.set_min_width(ui.available_width());
            ui.vertical_centered(|ui| {
                ui.add(
                    egui::Label::new(
                        RichText::new(format!(
                            "{}  {}",
                            super::icons::TRASH,
                            app.strings.gui_report_trash
                        ))
                        .color(th.err),
                    )
                    .selectable(false),
                );
            });
        })
        .response;
    let zone = ui.interact(resp.rect, ui.id().with("pt_trash"), egui::Sense::hover());
    if zone.dnd_hover_payload::<DragItem>().is_some() {
        ui.painter().rect_stroke(
            resp.rect.expand(2.0),
            egui::CornerRadius::same(6),
            egui::Stroke::new(2.0, th.err),
            egui::StrokeKind::Outside,
        );
    }
    if let Some(item) = release_payload::<DragItem>(&zone) {
        match &*item {
            DragItem::Row(path) => acts.push(Act::DeletePath(path.clone())),
            DragItem::Chip { path, which } => acts.push(Act::DetachMod {
                path: path.clone(),
                which: *which,
            }),
        }
    }
}

/// One rounded, category-tinted palette chip.
///
/// Drawn through [`chip_shell`] rather than its own frame so a palette entry and
/// the chip it drops into the flow are the same object visually — same rule,
/// same tint, same corners. They differ only in that the palette chip is inert.
fn palette_chip(ui: &mut egui::Ui, th: &GuiTheme, text: &str, base: Color32) {
    let tint = chip_tint(th, base);
    chip_shell(ui, &tint, true, ROUND_CHIP, |ui| {
        ui.add(egui::Label::new(RichText::new(text).color(tint.text)).selectable(false));
    });
}

/// The palette colour for a modifier chip. Kept in step with [`node_chips`] so
/// a palette modifier reads the same colour as the chip it drops in.
fn modifier_color(m: Modifier, th: &GuiTheme) -> Color32 {
    match m {
        Modifier::Report => th.subst,
        Modifier::With => th.accent,
        Modifier::As => th.pending,
        Modifier::Parallel => th.err,
        // RESPONSE / SHOW / HIDE reuse the same hues their attached chips carry
        // (see `node_chips`) so the palette entry reads as the chip it creates.
        Modifier::Response => th.accent,
        Modifier::Show => th.ok,
        Modifier::Hide => th.dim,
        Modifier::Statistics => th.subst,
    }
}

/// Render one flattened row as a horizontal cluster of chips (a compositional
/// block: the base subject plus any attached `REPORT` / `PARALLEL` / `WITH` /
/// `AS` modifier chips). The row is both a **modifier drop zone** (drop a
/// modifier chip onto it to attach) and sits above a **base insert strip** that
/// opens an animated gap when a base block is dragged over it. Leaf and loop
/// heads carry an inline single-line editor when selected.
#[allow(clippy::too_many_arguments)]
/// Consume a drag-and-drop payload of type `T` on the release frame — but only
/// when the payload in flight is *actually* a `T`.
///
/// egui's [`egui::Response::dnd_release_payload`] is destructive in a subtle
/// way: it `take()`s the stored payload out of the DnD plugin *before* it checks
/// its type, so asking it for a type that doesn't match still throws the payload
/// away — silently starving any later reader on the same frame. Several drop
/// zones overlap each report row (the modifier zone reads [`Modifier`], the
/// insert strip reads [`NodeKind`] *and* [`DragItem`]), so an unguarded
/// `dnd_release_payload::<NodeKind>()` would eat a [`DragItem::Row`] before the
/// reorder branch ever ran (which is exactly why drops "opened a gap" but never
/// moved anything). Peeking non-destructively with `dnd_hover_payload` first and
/// only consuming a matching payload lets the zones coexist.
fn release_payload<T: std::any::Any + Send + Sync>(
    resp: &egui::Response,
) -> Option<std::sync::Arc<T>> {
    resp.dnd_hover_payload::<T>()?;
    resp.dnd_release_payload::<T>()
}

/// Minimum widths of the inline editors embedded in a chip. Each field grows
/// past this to fit what is actually in it (see [`fitted_field_width`]) and
/// stops at [`FIELD_MAX_WIDTH`]; these are the resting sizes an empty box takes,
/// and what the same-sized placeholder a pending drop draws uses (see
/// [`Chip::ghost_shape`]) so the two can't drift apart.
const ALIAS_FIELD_WIDTH: f32 = 96.0;
const PARALLEL_FIELD_WIDTH: f32 = 44.0;
/// A loop variable is an identifier, and short ones are the convention.
const LOOP_VAR_FIELD_WIDTH: f32 = 72.0;
/// A folder path is the longest thing on a loop head, and the one most worth
/// being able to read without scrolling the row.
const LOOP_PATH_FIELD_WIDTH: f32 = 150.0;
const LOOP_GLOB_FIELD_WIDTH: f32 = 84.0;
/// How wide any inline field is allowed to grow to fit its contents.
///
/// A deep folder path would otherwise push a loop head past the width of the
/// pane and put the rest of the statement out of sight. Past this the box
/// scrolls internally, which is the old behaviour — but now only for the
/// genuinely long values rather than for almost all of them.
const FIELD_MAX_WIDTH: f32 = 320.0;
/// The folder/file picker button beside a loop's path box.
///
/// Wider than the glyph needs because the button now carries a frame: it looked
/// like decoration when drawn flat, and users didn't discover it was a button.
const PICKER_BUTTON_WIDTH: f32 = 28.0;
/// A combo chip's dropdown grows to fit its text, which the ghost already spells
/// out; this is just the arrow and its padding.
const COMBO_CHIP_WIDTH: f32 = 24.0;

/// Horizontal indent applied per nesting level in the block editor, so a
/// statement inside a `FOR`/`PARALLEL`/`WITH` block sits clearly further right
/// than its parent. Used for both the chip clusters and the drop-placeholder /
/// nested-field indents so they all line up at the same depth.
const INDENT_STEP: f32 = 24.0;

/// The report path of the block currently being dragged for reordering (an
/// active `DragItem::Row` payload), if any. Read at the start of a row's render
/// from the payload set last frame, so the dragged block can be lifted out of
/// its slot and floated under the cursor (see [`block_row`]).
fn dragged_row_path(ctx: &egui::Context) -> Option<Vec<usize>> {
    egui::DragAndDrop::payload::<DragItem>(ctx).and_then(|d| match &*d {
        DragItem::Row(p) => Some(p.clone()),
        _ => None,
    })
}

/// The chip currently picked up on its own (an active [`DragItem::Chip`]
/// payload), if any. Read at the start of a row's render from the payload set
/// last frame — exactly like [`dragged_row_path`] — so the chip can be lifted
/// out of its slot and floated under the cursor.
fn dragged_chip(ctx: &egui::Context) -> Option<(Vec<usize>, DetachWhich)> {
    egui::DragAndDrop::payload::<DragItem>(ctx).and_then(|d| match &*d {
        DragItem::Chip { path, which } => Some((path.clone(), *which)),
        _ => None,
    })
}

/// Whether `row_path` is part of the subtree currently being dragged: the
/// dragged path itself, or any descendant of it (a `FOR` loop's body rows and
/// its synthetic `END`, all of which carry the loop's path as a prefix). A leaf
/// therefore lifts only itself; a loop lifts its whole body in one piece.
fn row_is_lifted(dragged: &[usize], row_path: &[usize]) -> bool {
    row_path.starts_with(dragged)
}

/// How strongly a row is highlighted while the pointer rests on a block.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum HoverTier {
    /// The hovered block itself. A `FOR` loop is *two* rows at this tier — its
    /// header and its `END` — because those are the two halves of one block, and
    /// lighting only the half under the pointer made a loop look like it ended
    /// somewhere it doesn't.
    Block,
    /// A row that isn't the block but travels with it: the body of a hovered
    /// loop. Softer, because it answers a different question ("and this comes
    /// too") from the block under the pointer.
    CarriedAlong,
}

/// The highlight `row_path` earns while `hovered` is the block under the
/// pointer, or `None` if it is unaffected.
///
/// Deliberately the same subtree rule as [`row_is_lifted`] — the highlight's
/// whole promise is "this is what a drag would pick up", so if the two ever
/// disagreed the preview would be a lie. A leaf therefore lights only itself; a
/// loop lights its body and its `END` as well.
fn hover_tier(hovered: &[usize], row_path: &[usize]) -> Option<HoverTier> {
    if !row_is_lifted(hovered, row_path) {
        None
    } else if row_path.len() == hovered.len() {
        Some(HoverTier::Block)
    } else {
        Some(HoverTier::CarriedAlong)
    }
}

/// `rect` with the row's indent trimmed off its left edge: the block's own
/// bounds. Never collapses the rect, however deeply nested the row is.
fn indented_content(rect: egui::Rect, depth: usize) -> egui::Rect {
    let indent = (depth as f32 * INDENT_STEP).min((rect.width() - 1.0).max(0.0));
    egui::Rect::from_min_max(
        egui::pos2(rect.left() + indent, rect.top()),
        rect.right_bottom(),
    )
}

/// Where the measured *silhouette* of the picked-up subtree is stashed between
/// frames, so the drop markers can take its shape (see [`DragLift`] and
/// [`dragged_block_shape`]). One drag is in flight at a time, so a single
/// global id is enough.
///
/// A subtree is not a rectangle: a `FOR` loop is a short head, an indented body
/// of varying widths and a short `END`. Storing one rect per row — each
/// positioned relative to the subtree's own top-left corner — lets the marker
/// show that outline instead of the bounding box, which for a loop over three
/// requests promised a large solid slab nothing like the block in hand.
fn lifted_shape_id() -> egui::Id {
    egui::Id::new("pt_lifted_block_shape")
}

/// Where the size of the palette chip currently being dragged is stashed.
///
/// A palette block has no laid-out block to measure — it doesn't exist in the
/// flow yet — but the thing physically in the user's hand *is* the palette
/// chip's floating preview, so matching the drop ghost to that is both the
/// honest answer and the one that looks right.
fn palette_drag_size_id() -> egui::Id {
    egui::Id::new("pt_palette_drag_size")
}

/// The floating ("picked up") subtree, accumulated as the block list renders.
///
/// Every lifted row paints into one shared layer so the whole block moves as a
/// single unit, but the translation that puts it under the pointer can only be
/// applied **after the last of those rows has been painted**:
/// [`egui::Context::transform_layer_shapes`] moves the shapes *already in* the
/// layer, so applying it from inside the head row — which always renders before
/// its body — moved the head alone and left a `FOR` loop's body and its `END`
/// sitting at their layout positions. That is what made the parts of a dragged
/// loop appear to move at different speeds.
#[derive(Default)]
struct DragLift {
    /// The shared layer every lifted row painted into.
    layer: Option<egui::LayerId>,
    /// The head row's laid-out rect — the anchor centred on the pointer, so the
    /// rest of the subtree hangs off it at its natural offsets.
    head: Option<egui::Rect>,
    /// Union of every lifted row's rect: the true size of the block in hand.
    bounds: Option<egui::Rect>,
    /// Every lifted row's rect, in layout order — the block's silhouette.
    rows: Vec<egui::Rect>,
}

impl DragLift {
    fn add(&mut self, layer: egui::LayerId, rect: egui::Rect, is_head: bool) {
        self.layer = Some(layer);
        if is_head {
            self.head = Some(rect);
        }
        self.bounds = Some(match self.bounds {
            Some(bounds) => bounds.union(rect),
            None => rect,
        });
        self.rows.push(rect);
    }

    /// Move the whole picked-up subtree under the pointer in one transform, and
    /// remember its measured height for the drop ghosts. Call once per frame,
    /// after every row has been rendered.
    fn follow_pointer(self, ctx: &egui::Context) {
        let (Some(layer), Some(head), Some(bounds)) = (self.layer, self.head, self.bounds) else {
            // Nothing in hand this frame — forget the last drag's measurement so
            // the next drag's first frame doesn't briefly shape its marker like
            // the previous (possibly much bigger) block.
            ctx.data_mut(|d| d.remove::<Vec<egui::Rect>>(lifted_shape_id()));
            return;
        };
        // Normalised to the subtree's own top-left so the marker can simply be
        // translated to wherever the block would land.
        let shape: Vec<egui::Rect> = self
            .rows
            .iter()
            .map(|r| egui::Rect::from_min_size(r.min - bounds.min.to_vec2(), r.size()))
            .collect();
        ctx.data_mut(|d| d.insert_temp(lifted_shape_id(), shape));
        if let Some(pointer) = ctx.pointer_interact_pos() {
            ctx.transform_layer_shapes(
                layer,
                egui::emath::TSTransform::from_translation(pointer - head.center()),
            );
        }
    }
}

/// The silhouette of the block currently in hand — one rect per row it will
/// occupy, positioned relative to the block's own top-left corner — so a drop
/// marker can be drawn in the *shape* of what will land there rather than a
/// rectangle covering its bounding box.
///
///   * A palette block ([`NodeKind`]) has nothing laid out in the flow to
///     measure. Its rows come from what it will flatten to — a `FOR` inserts a
///     head plus its `END`, everything else a single row — and its width from
///     the palette chip being dragged (see [`palette_drag_size_id`]), which is
///     literally the preview in the user's hand.
///   * An existing block ([`DragItem::Row`]) is measured from the floating
///     subtree itself by [`DragLift`], so a `FOR` loop's stepped outline (short
///     head, indented body, short `END`) is reproduced exactly. That
///     measurement is necessarily the previous frame's — the lifted rows are
///     painted interleaved with the very drop strips that need it — which is
///     invisible mid-drag; a drag's first frame falls back to a single block.
fn dragged_block_shape(ui: &egui::Ui) -> Vec<egui::Rect> {
    let ctx = ui.ctx();
    let one = chip_h(ui) + 10.0;
    // A width to fall back on when nothing has been measured yet. Wide enough
    // to read as a block, narrow enough that it never looks like the old
    // full-width bar.
    let default_w = 160.0;
    let stack = |w: f32, rows: usize| -> Vec<egui::Rect> {
        (0..rows)
            .map(|i| egui::Rect::from_min_size(egui::pos2(0.0, i as f32 * one), egui::vec2(w, one)))
            .collect()
    };
    if let Some(kind) = egui::DragAndDrop::payload::<NodeKind>(ctx) {
        let rows = match *kind {
            NodeKind::ForFiles | NodeKind::ForFolders | NodeKind::ForEnvs => 2,
            _ => 1,
        };
        let w = ctx
            .data(|d| d.get_temp::<egui::Vec2>(palette_drag_size_id()))
            .map(|s| s.x)
            .filter(|w| *w >= 1.0)
            .unwrap_or(default_w);
        return stack(w, rows);
    }
    let dragging_row = egui::DragAndDrop::payload::<DragItem>(ctx)
        .is_some_and(|d| matches!(&*d, DragItem::Row(_)));
    if dragging_row
        && let Some(shape) = ctx.data(|d| d.get_temp::<Vec<egui::Rect>>(lifted_shape_id()))
        && !shape.is_empty()
        && shape.iter().all(|r| r.width() >= 1.0 && r.height() >= 1.0)
    {
        // A subtree measured as shorter than a single row is a stale or
        // degenerate reading; a marker that small would be invisible.
        let h: f32 = shape
            .iter()
            .fold(f32::NEG_INFINITY, |acc, r| acc.max(r.bottom()));
        if h >= one {
            return shape;
        }
    }
    stack(default_w, 1)
}

/// The bounding size of [`dragged_block_shape`] — what the insert strips
/// animate a gap open to.
fn dragged_block_size(ui: &egui::Ui) -> egui::Vec2 {
    dragged_block_shape(ui)
        .into_iter()
        .reduce(egui::Rect::union)
        .map_or(egui::Vec2::ZERO, |r| r.max.to_vec2())
}

/// Just the height of [`dragged_block_size`] — the dimension the insert strips
/// animate open.
fn dragged_block_h(ui: &egui::Ui) -> f32 {
    dragged_block_size(ui).y
}

/// Paint the block that will land here as its own silhouette: one rounded,
/// accent-tinted rect per row, laid out from `origin` and clipped to `clip`.
///
/// Clipping (rather than scaling) is what lets the marker animate open — the
/// gap grows from nothing to the block's full height, revealing more of the
/// same fixed shape, so the block never appears to stretch. The clip also
/// bounds a very wide block to the editor.
fn paint_drop_silhouette(
    ui: &egui::Ui,
    origin: egui::Pos2,
    shape: &[egui::Rect],
    clip: egui::Rect,
    th: &GuiTheme,
) {
    if clip.width() < 1.0 || clip.height() < 1.0 {
        return;
    }
    let painter = ui.painter().with_clip_rect(clip);
    for r in shape {
        let rect = egui::Rect::from_min_size(origin + r.min.to_vec2(), r.size());
        if rect.width() < 1.0 || rect.height() < 1.0 {
            continue;
        }
        painter.rect(
            // A hair of inset between stacked rows so a loop's head, body and
            // `END` read as separate blocks rather than one column.
            rect.shrink2(egui::vec2(0.0, 2.0)),
            egui::CornerRadius::same(BLOCK_RADIUS as u8),
            mix(th.panel, th.accent, 0.18),
            egui::Stroke::new(1.5, th.accent),
            egui::StrokeKind::Inside,
        );
    }
}

/// The corner radius every block, chip and ghost shares, so an outline drawn
/// around a block traces the same silhouette the block itself has.
const BLOCK_RADIUS: f32 = 3.0;

/// A closed polyline tracing `rect` with rounded corners, for dashing along.
///
/// `egui` can dash an arbitrary path but only knows how to *fill* a rounded
/// rectangle, so a dashed rounded outline has to be approximated by hand. Eight
/// segments per quarter-turn is indistinguishable from a curve at the radii
/// blocks use, while staying cheap enough to rebuild every frame of a drag.
fn rounded_rect_path(rect: egui::Rect, radius: f32) -> Vec<egui::Pos2> {
    // A radius can never exceed half the shorter side, or the corners overlap
    // and the path folds back on itself.
    let r = radius
        .min(rect.width() * 0.5)
        .min(rect.height() * 0.5)
        .max(0.0);
    const SEGMENTS: usize = 8;
    let mut path = Vec::with_capacity(SEGMENTS * 4 + 5);
    // Corner centres and the sweep each one starts at, walking clockwise from
    // the top-left corner in screen coordinates (y grows downwards).
    let corners = [
        (
            egui::pos2(rect.left() + r, rect.top() + r),
            std::f32::consts::PI,
        ),
        (
            egui::pos2(rect.right() - r, rect.top() + r),
            1.5 * std::f32::consts::PI,
        ),
        (egui::pos2(rect.right() - r, rect.bottom() - r), 0.0),
        (
            egui::pos2(rect.left() + r, rect.bottom() - r),
            0.5 * std::f32::consts::PI,
        ),
    ];
    for (centre, start) in corners {
        for i in 0..=SEGMENTS {
            let a = start + (i as f32 / SEGMENTS as f32) * 0.5 * std::f32::consts::PI;
            path.push(egui::pos2(centre.x + r * a.cos(), centre.y + r * a.sin()));
        }
    }
    // Close the loop so the final corner joins the first.
    if let Some(&first) = path.first() {
        path.push(first);
    }
    path
}

/// Paint a faint dashed "ghost" of a block into the current (base) layer,
/// marking the slot a dragged block was lifted from. So if a block was picked
/// up by accident, there's an obvious outline showing where it came from and
/// where dropping it back would return it.
///
/// `rect` is the block's *own* rect — its indent already stripped off the left
/// edge by the caller — so the outline traces exactly where the block sat
/// rather than starting at the far left of the editor, which made a nested
/// block's ghost look like it belonged to the whole flow.
fn paint_origin_ghost(painter: &egui::Painter, rect: egui::Rect, th: &GuiTheme) {
    if rect.width() < 1.0 || rect.height() < 1.0 {
        return;
    }
    let r = rect.expand(1.0);
    let radius = BLOCK_RADIUS;
    painter.rect_filled(
        r,
        egui::CornerRadius::same(radius as u8),
        mix(th.panel, th.dim, 0.12),
    );
    // A dashed outline reads as "empty slot / drop back here" rather than a
    // solid block; dashing round a rounded path (not the four straight edges)
    // keeps its corners as round as the block's own.
    for shape in egui::Shape::dashed_line(
        &rounded_rect_path(r, radius),
        egui::Stroke::new(1.0, th.dim),
        4.0,
        3.0,
    ) {
        painter.add(shape);
    }
}

/// A modifier drop that is currently *pending* over a line — either a fresh
/// clause dragged in from the palette, or one pulled off another line and
/// carried here with its contents (see [`CarriedMod`]).
///
/// Both are answered by the same three questions — will it go here, why not,
/// and what will it look like — so the drop zone handles one type rather than
/// branching on the payload everywhere.
#[derive(Clone)]
enum PendingMod {
    New(Modifier),
    Moved(CarriedMod),
}

impl PendingMod {
    fn reject_reason(&self, node: &FlowNode, s: &crate::i18n::Strings) -> Option<&'static str> {
        match self {
            PendingMod::New(m) => m.reject_reason(node, s),
            PendingMod::Moved(carried) => carried.reject_reason(node, s),
        }
    }

    /// Perform the drop on `node`. Used on a throwaway clone to work out what
    /// the result would look like, so the preview and the drop can't disagree.
    fn apply(&self, node: &mut FlowNode) -> bool {
        match self {
            PendingMod::New(m) => attach_to_node(node, *m),
            PendingMod::Moved(carried) => carried.attach_to(node),
        }
    }
}

/// The chip a pending drop would add to `node`, and where in the chip cluster it
/// would sit.
///
/// Worked out by *rehearsing the drop* on a throwaway clone and diffing the
/// resulting chips against the current ones, so the preview can never drift from
/// what the drop actually does — the same trick
/// [`edit::detach_leaves_statement`] uses. `None` when the drop rewrites the
/// line without adding a chip of its own (outlining the whole row is the honest
/// preview then).
fn preview_chip(
    node: &FlowNode,
    pending: &PendingMod,
    req_ok: Option<bool>,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
) -> Option<(usize, String, f32)> {
    let mut probe = node.clone();
    if !pending.apply(&mut probe) {
        return None;
    }
    let before = node_chips(node, req_ok, th, s);
    let after = node_chips(&probe, req_ok, th, s);
    if after.len() <= before.len() {
        return None;
    }
    let idx = before
        .iter()
        .zip(after.iter())
        .position(|(b, a)| b.ghost_shape() != a.ghost_shape())
        .unwrap_or(before.len());
    let (text, extra) = after.get(idx)?.ghost_shape();
    Some((idx, text, extra))
}

/// The ctx-data key a row parks its drop preview under. The preview is computed
/// by the drop zone, which is only laid out *after* the chip cluster it needs to
/// open a gap in, so it is handed to the next frame rather than to this one — a
/// lag of a single frame in the middle of a drag that lasts hundreds.
fn mod_ghost_id(row_index: usize) -> egui::Id {
    egui::Id::new(("pt_modghost", row_index))
}

/// A dashed, chip-shaped placeholder standing in for the block a pending drop
/// would add, drawn inline in the chip cluster at the position it will occupy —
/// so the line visibly opens up to make room and the user can see how the drop
/// changes the statement *before* letting go.
///
/// Laid out with exactly the frame a real chip uses (same margins, same minimum
/// height) and showing the chip's own text, which is what guarantees the gap is
/// the size of the block that will fill it.
fn ghost_chip(ui: &mut egui::Ui, th: &GuiTheme, text: &str, extra_width: f32) {
    let h = chip_h(ui);
    let rect = egui::Frame::NONE
        .inner_margin(egui::Margin::symmetric(8, 3))
        .corner_radius(ROUND_CHIP)
        .show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.set_min_height(h);
                ui.add(
                    egui::Label::new(RichText::new(text).color(th.dim))
                        .selectable(false)
                        .truncate(),
                );
                // The chip that lands here carries an inline editor (a name
                // field, a concurrency box, a dropdown) that has no text of its
                // own yet — reserve its width too, or the gap is narrower than
                // the block about to fill it.
                ui.add_space(extra_width);
            });
        })
        .response
        .rect;
    ui.painter().rect_filled(
        rect,
        egui::CornerRadius::same(6),
        mix(th.panel, th.accent, 0.10),
    );
    for shape in egui::Shape::dashed_line(
        &rounded_rect_path(rect, 6.0),
        egui::Stroke::new(1.0, th.accent),
        4.0,
        3.0,
    ) {
        ui.painter().add(shape);
    }
}

/// A row's geometry and its reserved background slot, collected as the rows are
/// laid out so the hover highlight can be painted once the whole pane has been
/// walked and the block under the pointer is known.
///
/// The slot matters: the highlight has to sit *behind* the row's chips, but
/// which rows light up isn't decided until every row has been measured (hovering
/// a loop header lights rows that haven't been laid out yet). Reserving a shape
/// index up-front and filling it in at the end gets both — a background that is
/// genuinely in the background, with no frame of lag.
struct RowHover {
    path: Vec<usize>,
    kind: RowKind,
    /// The block's own bounds, with the indent trimmed off (see
    /// [`indented_content`]) so the highlight hugs the block rather than
    /// starting at the far-left margin.
    rect: egui::Rect,
    bg: egui::layers::ShapeIdx,
    pointer_inside: bool,
}

fn block_row(
    ed: &mut ReportEditor,
    app: &GuiApp,
    ui: &mut egui::Ui,
    row: &edit::NodeRow,
    row_index: usize,
    selected: bool,
    drop_pos: &InsertPos,
    titles: &[String],
    lift: &mut DragLift,
    acts: &mut Vec<Act>,
) -> Option<RowHover> {
    let th = app.theme;
    let s = &app.strings;
    // Reserved *before* any of the row's own content, so whatever the hover
    // highlight later puts here is painted underneath the chips rather than over
    // them. Filled in by `paint_hover_group` once every row has been laid out.
    let bg_slot = ui.painter().add(egui::Shape::Noop);
    // Loaded environment names — the choices a BASELINE/COMPARISON dropdown
    // offers. Cheap to gather; only consulted by env-role chips.
    let env_choices: Vec<String> = app
        .session
        .global_envs
        .iter()
        .map(|e| e.name.clone())
        .collect();
    // A cheap owned copy of the node so the chip cluster / applicability checks
    // don't hold a borrow of `ed` across the inline editor (which needs `&mut`).
    let node = ed
        .flow
        .as_ref()
        .and_then(|f| node_at(f, &row.path))
        .cloned();
    // The report-request's `WITH … END` fields, rendered as a nested block under
    // the line (GUI-only — the shared `flatten` never emits WITH rows).
    let with_items: Vec<WithItem> = match &node {
        Some(FlowNode::Report(ReportStmt::Request { with, .. })) => with.clone(),
        _ => Vec::new(),
    };

    // The whole block is the request line plus any nested WITH block; capture
    // both its first-line rect (for the modifier drop zone) and its full rect
    // (for the insert strip) so a drop lands *after the whole block*.
    //
    // When this row belongs to the picked-up subtree, lift it out of its slot
    // and paint it into a floating (Tooltip-order) layer that follows the
    // pointer — so it reads as physically picked up, leaving an empty slot
    // where it was. A leaf lifts just itself; a FOR loop lifts its head, its
    // whole body and the matching `END` (every row whose path is prefixed by
    // the dragged path), all into one shared layer so they float together as a
    // single unit. This mirrors egui's own `dnd_drag_source`, which we can't
    // use directly here because the drag handle is an inner chip, not the row.
    let drag_path = dragged_row_path(ui.ctx());
    let lifted = drag_path
        .as_deref()
        .is_some_and(|d| row_is_lifted(d, &row.path));
    let is_drag_head = drag_path.as_deref() == Some(row.path.as_slice());
    // A chip dragged out on its own (rather than Ctrl-dragged to move the whole
    // line) is lifted the same way a row is: it paints into a floating layer
    // that follows the pointer and leaves a dashed ghost in the slot it came
    // from. Without that, pulling a clause out of a line looked like nothing was
    // happening at all.
    let lifted_chip = dragged_chip(ui.ctx());
    let chip_in_this_row = |which: DetachWhich| {
        lifted_chip
            .as_ref()
            .is_some_and(|(p, w)| p.as_slice() == row.path.as_slice() && *w == which)
    };
    // What the chip in hand is actually carrying (`SHOW(Time, Status)`, not just
    // "a SHOW"), read once here so every row's drop zone can ask whether that
    // clause would fit — and so dropping it on another line re-creates it with
    // its contents rather than as a fresh placeholder.
    let carried_chip: Option<(Vec<usize>, DetachWhich, CarriedMod)> =
        lifted_chip.as_ref().and_then(|(p, w)| {
            let node = ed.flow.as_ref().and_then(|f| node_at(f, p))?;
            Some((p.clone(), *w, carry_modifier(node, *w)?))
        });
    // Whether this row is in last frame's hover group, which is what colours
    // its chips (see `hover_group_id`). `END` is excluded: it is the tail of
    // the loop above it, and lighting it as a chip of its own made a loop look
    // like it had a second, separate block at the bottom.
    let hover_lit = row.kind != RowKind::LoopEnd
        && hovered_last_frame(ui).is_some_and(|h| hover_tier(&h, &row.path).is_some());
    // The gap this row opened for a hovering modifier, decided by last frame's
    // drop zone (see `mod_ghost_id`).
    let mod_ghost: Option<(usize, String, f32)> = ui
        .ctx()
        .data(|d| d.get_temp(mod_ghost_id(row_index)))
        .unwrap_or(None);
    let block_body = |ui: &mut egui::Ui| -> egui::Rect {
        // Where the picked-up chip's floating layer ended up, so it can be moved
        // under the pointer once everything lifted with it has been painted.
        let mut chip_lift: Option<(egui::LayerId, egui::Rect)> = None;
        // Top-align the chip cluster (rather than the default centre alignment):
        // every chip is the same height, so top-alignment keeps them level while
        // avoiding egui's horizontal-centre re-centring, which otherwise drifts
        // each successive chip on the line progressively lower.
        let inner = ui.horizontal_top(|ui| {
            ui.add_space(row.depth as f32 * INDENT_STEP);
            match row.kind {
                // Drawn in `dim`, not `accent`: this row is the one thing in the
                // flow that is *not* in the file. It exists so there is
                // somewhere to drop a first statement and somewhere for the
                // top of the report to be. Giving it a keyword's colour made it
                // look like syntax — users reasonably asked whether `BEGIN` was
                // a word they had to write, and it isn't (the grammar has `END`,
                // but no opening keyword at all). So it stays sentence case,
                // stays translated, and reads as a caption.
                RowKind::Begin => static_chip(
                    ui,
                    &th,
                    app.strings.report_node_begin,
                    th.dim,
                    s.chip_help_begin,
                ),
                // Deliberately the literal, untranslated "END": unlike the
                // `Begin` row above, this one is not an editor invention. It
                // renders a real `END` keyword that the parser requires and
                // that the Source view shows verbatim, so translating or
                // title-casing it would make the two views disagree about what
                // is actually in the file.
                RowKind::LoopEnd => static_chip(ui, &th, "END", th.accent, s.chip_help_end),
                // The GUI never asks for expanded `WITH` rows (it draws each
                // field as a chip on the request's own row), so these are
                // unreachable here — see `flatten_expanded`.
                RowKind::WithField(_)
                | RowKind::WithComment(_)
                | RowKind::WithAdd
                | RowKind::WithEnd => {}
                RowKind::Leaf | RowKind::LoopHead | RowKind::Comment => {
                    let mut chips = node
                        .as_ref()
                        .map(|n| node_chips(n, row.req_ok, &th, s))
                        .unwrap_or_default();
                    // Deepen the whole row's chips while it is in the hover
                    // group, so what a drag would pick up is legible even on a
                    // row whose chips leave almost none of the panel behind
                    // them showing.
                    if hover_lit {
                        for chip in &mut chips {
                            chip.hovered = true;
                        }
                    }
                    // Merge each tethered chip into one pill with the chip it
                    // qualifies (see `link_tethers`) — except where the two are
                    // about to stop being neighbours, because either half is in
                    // hand or a hovering clause is about to be dropped between
                    // them.
                    link_tethers(&mut chips);
                    for i in (1..chips.len()).rev() {
                        let parted = [i - 1, i]
                            .iter()
                            .any(|&j| chips[j].detach.is_some_and(&chip_in_this_row))
                            || mod_ghost.as_ref().is_some_and(|(gi, _, _)| *gi == i);
                        if chips[i].join_prev && parted {
                            split_tether(&mut chips, i);
                        }
                    }
                    // A tethered chip is pulled flush against the chip it
                    // qualifies (see `TETHER_GAP`, which is why this keys off
                    // the anchor's `join_next` rather than the tethered chip's
                    // own flag); everything else keeps the normal inter-chip
                    // gap.
                    let gap = ui.spacing().item_spacing.x;
                    let mut prev: Option<egui::Rect> = None;
                    let mut tethers: Vec<(egui::Rect, egui::Rect)> = Vec::new();
                    for (ci, chip) in chips.iter().enumerate() {
                        // Open the gap *before* the chip the drop would land in
                        // front of, so the rest of the line slides right and the
                        // placeholder sits exactly where the new block will.
                        if let Some((gi, text, extra)) = &mod_ghost
                            && *gi == ci
                        {
                            ghost_chip(ui, &th, text, *extra);
                        }
                        if chip.join_next {
                            ui.spacing_mut().item_spacing.x = TETHER_GAP;
                        }
                        let in_hand = chip.detach.is_some_and(&chip_in_this_row);
                        let rect = if in_hand {
                            let (layer, slot) = lift_chip(
                                ui,
                                &th,
                                s,
                                chip,
                                selected,
                                &row.path,
                                row_index,
                                titles,
                                &env_choices,
                                acts,
                            );
                            chip_lift = Some((layer, slot));
                            slot
                        } else {
                            render_chip(
                                ui,
                                &th,
                                s,
                                chip,
                                selected,
                                &row.path,
                                titles,
                                &env_choices,
                                acts,
                            )
                        };
                        ui.spacing_mut().item_spacing.x = gap;
                        // Remember the pair so it can be highlighted together
                        // on hover. `split_tether` has already cleared the flag
                        // for a pair that is being pulled apart, so there is no
                        // in-hand case left to exclude here.
                        if chip.join_prev
                            && let Some(anchor) = prev
                        {
                            tethers.push((anchor, rect));
                        }
                        prev = Some(rect);
                    }
                    // A clause that appends to the end of the line gets its gap
                    // after the last chip.
                    if let Some((gi, text, extra)) = &mod_ghost
                        && *gi >= chips.len()
                    {
                        ghost_chip(ui, &th, text, *extra);
                    }
                    for (anchor, hanger) in tethers {
                        paint_tether_hover(ui, &th, anchor, hanger);
                    }
                }
            }
        });
        if !with_items.is_empty() {
            let cluster = inner.response.rect;
            // Dragging the `WITH` chip detaches the *whole* block, fields and
            // all, so the fields have to travel with it. Painting them into the
            // chip's own floating layer keeps chip and fields rigidly together
            // (one transform moves both) and leaves a ghost over the space they
            // vacated, so what is being pulled out is what you see moving.
            let lifting_with = chip_in_this_row(DetachWhich::WithBlock);
            let with_rect = match chip_lift {
                Some((layer, _)) if lifting_with => {
                    let rect = ui
                        .scope_builder(
                            egui::UiBuilder::new()
                                .layer_id(layer)
                                .layout(egui::Layout::top_down(egui::Align::Min)),
                            |ui| with_block(ui, &th, s, &row.path, row.depth, &with_items, acts),
                        )
                        .inner;
                    paint_origin_ghost(ui.painter(), rect, &th);
                    rect
                }
                _ => with_block(ui, &th, s, &row.path, row.depth, &with_items, acts),
            };
            // Enclose the request line and its WITH fields in one subtle border
            // so the block reads as a single unit — you drop *around* it, never
            // into the middle of its WITH statements. The border hugs from the
            // request line's indent down past the `END` footer. Suppressed while
            // the WITH block is being pulled off: a border drawn around a
            // half-empty unit says "still one thing" at exactly the wrong moment.
            if !lifting_with {
                let indent = row.depth as f32 * INDENT_STEP;
                let unit = egui::Rect::from_min_max(
                    egui::pos2(cluster.left() + indent, cluster.top()),
                    egui::pos2(cluster.right().max(with_rect.right()), with_rect.bottom()),
                )
                .expand(3.0);
                ui.painter().rect_stroke(
                    unit,
                    egui::CornerRadius::same(6),
                    egui::Stroke::new(1.0, mix(th.panel, th.subst, 0.55)),
                    egui::StrokeKind::Outside,
                );
            }
        }
        // Everything that belongs to the picked-up chip's layer is painted, so
        // it is finally safe to move the layer under the pointer.
        if let Some((layer, slot)) = chip_lift {
            follow_pointer(ui.ctx(), layer, slot);
        }
        inner.response.rect
    };
    if lifted {
        // All lifted rows share one layer (keyed by the dragged path) so a
        // single transform moves the whole subtree together, keeping each row's
        // relative offset. Their slots stay blank (the `scope_builder` still
        // reserves the space), and we skip the drop targets below — you can't
        // drop onto a row that's currently in your hand.
        let layer_id = egui::LayerId::new(
            egui::Order::Tooltip,
            ui.id()
                .with(("pt_drag_subtree", drag_path.as_ref().unwrap())),
        );
        let ir = ui.scope_builder(
            egui::UiBuilder::new()
                .layer_id(layer_id)
                .layout(egui::Layout::top_down(egui::Align::Min)),
            block_body,
        );
        // The row's laid-out rect starts at the editor's left margin because the
        // indent is `add_space`d *inside* the layout; strip it back off so both
        // the origin ghost and the lift's measurement describe the block itself,
        // not the block plus a stripe of empty indent.
        let content = indented_content(ir.response.rect, row.depth);
        // Leave a dashed ghost in the (now blank) origin slot so the lift is
        // obviously reversible — dropping the block back here restores it.
        paint_origin_ghost(ui.painter(), content, &th);
        // Hand the row to the shared lift; the single transform that puts the
        // whole subtree under the pointer is applied once every row has been
        // painted (see `DragLift`), never from here.
        lift.add(layer_id, content, is_drag_head);
        return None;
    }
    let block = ui.vertical(block_body);
    let cluster = block.inner;
    let block_rect = block.response.rect;
    // The block's own bounds (indent stripped), and whether the pointer is over
    // them. `rect_contains_pointer` rather than an `interact` so this purely
    // observational read never competes with the row's chips or its drop zones
    // for the click.
    let hover_rect = indented_content(block_rect, row.depth);
    let hover = RowHover {
        path: row.path.clone(),
        kind: row.kind,
        rect: hover_rect,
        bg: bg_slot,
        pointer_inside: ui.rect_contains_pointer(hover_rect),
    };

    // ── Modifier drop zone: dropping a modifier chip onto a real node attaches
    // it. Only reacts to `Modifier` payloads, so it never competes with the base
    // insert strip below (which reacts to `NodeKind`).
    if let Some(n) = &node
        && matches!(row.kind, RowKind::Leaf | RowKind::LoopHead)
    {
        // The modifier drop zone spans the whole first line to the right of the
        // base chip (not just the chips), so a modifier can be dropped anywhere
        // on the row rather than having to hit the small cluster exactly.
        let zone_rect =
            egui::Rect::from_x_y_ranges(cluster.left()..=ui.max_rect().right(), cluster.y_range());
        let zresp = ui.interact(
            zone_rect,
            ui.id().with(("pt_modzone", row_index)),
            egui::Sense::hover(),
        );
        // The zone takes a fresh clause from the palette *or* one pulled off
        // another line — a `SHOW` lifted from one reported request drops onto
        // the next, bringing the columns it was carrying with it.
        let pending: Option<PendingMod> = if let Some(m) = zresp.dnd_hover_payload::<Modifier>() {
            Some(PendingMod::New(*m))
        } else if zresp.dnd_hover_payload::<DragItem>().is_some() {
            carried_chip
                .as_ref()
                .filter(|(from, _, _)| from.as_slice() != row.path.as_slice())
                .map(|(_, _, carried)| PendingMod::Moved(carried.clone()))
        } else {
            None
        };

        // Park the gap this row should open for the hovering clause. Computed
        // here (where the hover is known) and consumed by the chip cluster on
        // the next frame — see `mod_ghost_id`.
        let ghost = match &pending {
            Some(p) if p.reject_reason(n, s).is_none() => preview_chip(n, p, row.req_ok, &th, s),
            _ => None,
        };
        ui.ctx()
            .data_mut(|d| d.insert_temp(mod_ghost_id(row_index), ghost.clone()));

        if let Some(p) = &pending {
            match p.reject_reason(n, s) {
                None => {
                    // A row that has already opened a gap showing exactly where
                    // the clause lands needs no outline as well — the gap *is*
                    // the highlight, and the box round the whole line only
                    // competed with it.
                    if ghost.is_none() {
                        ui.painter().rect_stroke(
                            zone_rect.expand(2.0),
                            egui::CornerRadius::same(6),
                            egui::Stroke::new(2.0, th.accent),
                            egui::StrokeKind::Outside,
                        );
                    }
                }
                // A refusal gets its own (error-coloured) outline plus the
                // reason at the pointer, so the chip springing back reads as
                // "not here, because…" rather than as a missed drop.
                Some(why) => {
                    ui.painter().rect_stroke(
                        zone_rect.expand(2.0),
                        egui::CornerRadius::same(6),
                        egui::Stroke::new(2.0, th.err),
                        egui::StrokeKind::Outside,
                    );
                    egui::Tooltip::always_open(
                        ui.ctx().clone(),
                        ui.layer_id(),
                        ui.id().with(("pt_modwhy", row_index)),
                        egui::PopupAnchor::Pointer,
                    )
                    .show(|ui| {
                        ui.colored_label(th.err, why);
                    });
                }
            }
        }
        if let Some(m) = release_payload::<Modifier>(&zresp)
            && m.applies_to(n)
        {
            acts.push(Act::AttachMod {
                path: row.path.clone(),
                modifier: *m,
            });
        }
        // Shift is read at the *drop*, not at the pick-up, so the user can
        // change their mind mid-drag — and so the decision is made at the
        // moment they can see where the clause is about to land.
        let copy = ui.input(|i| i.modifiers.shift);
        // Every guard is checked *before* taking the payload: releasing it is
        // destructive, and swallowing a `DragItem::Row` here (or a clause this
        // line won't take) would silently cancel a block reorder that the
        // insert strip below is about to handle.
        if let Some((from, which, carried)) = &carried_chip
            && from.as_slice() != row.path.as_slice()
            && carried.applies_to(n)
            && release_payload::<DragItem>(&zresp).is_some()
        {
            acts.push(Act::MoveMod {
                from: from.clone(),
                which: *which,
                to: row.path.clone(),
                copy,
            });
        }
    }

    // ── Base insert strip: a full-width strip over the block that, when a base
    // block is dragged over it, opens an animated gap below the block (the
    // existing blocks slide down to make room) with a dashed placeholder where
    // the new block will land. The strip is sized to include the currently-open
    // gap (read from last frame) so the pointer stays over it as the gap opens —
    // avoiding open/close flicker at the seam. The gap is sized to the block
    // actually in hand (see `dragged_block_h`), so dragging a whole `FOR` loop
    // or a request with `WITH` fields opens a gap the size of that whole block
    // rather than a one-line sliver it obviously won't fit into.
    let gap_h = dragged_block_h(ui);
    let gap_id = ui.id().with(("pt_gap", row_index));
    let prev_gap: f32 = ui.ctx().data(|d| d.get_temp(gap_id)).unwrap_or(0.0);
    let strip = egui::Rect::from_x_y_ranges(
        ui.max_rect().x_range(),
        block_rect.top()..=block_rect.bottom() + prev_gap,
    );
    let strip_resp = ui.interact(
        strip,
        ui.id().with(("pt_drop", row_index)),
        egui::Sense::hover(),
    );
    // The strip opens its gap for either a palette base block (`NodeKind`) or an
    // existing block being dragged to a new home (`DragItem::Row`) — but not
    // when a row is hovering its own insert point (dropping there is a no-op).
    let hovering_new = strip_resp.dnd_hover_payload::<NodeKind>().is_some();
    let hovering_move = strip_resp
        .dnd_hover_payload::<DragItem>()
        .map(|d| matches!(&*d, DragItem::Row(from) if *from != row.path))
        .unwrap_or(false);
    let hovering_base = hovering_new || hovering_move;
    let gap =
        ui.ctx()
            .animate_value_with_time(gap_id, if hovering_base { gap_h } else { 0.0 }, 0.12);
    ui.ctx().data_mut(|d| d.insert_temp(gap_id, gap));
    if let Some(kind) = release_payload::<NodeKind>(&strip_resp) {
        acts.push(Act::DropNode {
            pos: drop_pos.clone(),
            node: node_for_kind(*kind, titles),
        });
    } else if let Some(item) = release_payload::<DragItem>(&strip_resp) {
        if let DragItem::Row(from) = &*item
            && *from != row.path
        {
            acts.push(Act::MoveNode {
                from: from.clone(),
                pos: drop_pos.clone(),
            });
        }
    }
    if gap > 0.5 {
        // Indent the silhouette to the depth the block will *land* at, not the
        // depth of the row it is hovering. They differ wherever a drop steps
        // inward: after `BEGIN` (a synthetic depth-0 row whose statements are
        // depth 1) and after a `FOR` header (which inserts into the loop body).
        // A drop path's depth is one per body it nests inside, plus one for the
        // top level, so it is read off the insert position itself and can't
        // drift from where the block really goes.
        let indent = (drop_pos.parent.len() + 1) as f32 * INDENT_STEP;
        let top = block_rect.bottom() + 2.0;
        let origin = egui::pos2(strip.left() + indent, top);
        // The marker is a preview of the block: its own outline, at its own
        // indent, revealed as the gap animates open.
        let clip =
            egui::Rect::from_min_max(origin, egui::pos2(strip.right() - 8.0, top + gap - 4.0));
        paint_drop_silhouette(ui, origin, &dragged_block_shape(ui), clip, &th);
        ui.add_space(gap);
    }
    Some(hover)
}

/// The block under the pointer, if any: the *last* matching row, so a nested row
/// wins over the loop whose rect happens to reach it.
///
/// The synthetic `Begin` row is never a candidate. Its path is empty, which
/// every other path starts with, so treating it as hoverable would light the
/// entire report the moment the pointer crossed the top of the pane — and
/// `Begin` isn't a block you can select or move anyway, so the highlight would
/// be promising something that can't happen.
fn hovered_block(rows: &[RowHover]) -> Option<&[usize]> {
    rows.iter()
        .rev()
        .find(|r| r.pointer_inside && r.kind != RowKind::Begin)
        .map(|r| r.path.as_slice())
}

/// Paint the hover highlight: a filled panel behind the block under the pointer,
/// and a softer one behind everything that would travel with it.
///
/// Skipped entirely while something is being dragged. A drag already says what
/// is in hand — the lifted subtree floats under the pointer and leaves dashed
/// ghosts behind — and adding a second, differently-shaped highlight to that
/// only muddled which of the two to read.
fn paint_hover_group(ui: &egui::Ui, th: &GuiTheme, rows: &[RowHover]) {
    // A chip that a drag would lift on its own outranks the block it sits in:
    // lighting the whole line while the pointer rests on a `PARALLEL` promised
    // to move the line, which is not what letting go there would do.
    // Stored as an `Option` because `remove_temp` needs a `Default`, which
    // `Rect` has no sensible one of.
    let chip_rect: Option<egui::Rect> = ui.ctx().data_mut(|d| {
        let r = d.get_temp::<Option<egui::Rect>>(chip_hover_id()).flatten();
        d.remove_temp::<Option<egui::Rect>>(chip_hover_id());
        r
    });
    if let Some(rect) = chip_rect {
        ui.ctx().data_mut(|d| {
            d.insert_temp::<Option<Vec<usize>>>(hover_group_id(), None);
        });
        ui.painter().rect_stroke(
            rect.expand(2.0),
            egui::CornerRadius::same(CHIP_RADIUS + 2),
            egui::Stroke::new(1.5, th.accent),
            egui::StrokeKind::Outside,
        );
        return;
    }
    let hovered = (!drag_in_flight(ui.ctx()))
        .then(|| hovered_block(rows))
        .flatten();
    // Hand the group to the next frame, where the chips are drawn: a chip is
    // painted long before the pane has been measured, so it can't ask which row
    // is hovered — see `hover_group_id`. Written unconditionally, `None`
    // included, or the chips would stay lit after the pointer left.
    ui.ctx()
        .data_mut(|d| d.insert_temp(hover_group_id(), hovered.map(<[usize]>::to_vec)));
    let Some(hovered) = hovered else {
        return;
    };
    // Derived from the panel colour rather than fixed, so the highlight stays a
    // gentle lift off the background on a light theme as well as a dark one.
    let block = mix(th.panel, th.accent, 0.28);
    let carried = mix(th.panel, th.accent, 0.12);
    for row in rows {
        let Some(tier) = hover_tier(hovered, &row.path) else {
            continue;
        };
        let fill = match tier {
            HoverTier::Block => block,
            HoverTier::CarriedAlong => carried,
        };
        ui.painter().set(
            row.bg,
            egui::Shape::rect_filled(
                row.rect.expand2(egui::vec2(4.0, 1.0)),
                egui::CornerRadius::same(4),
                fill,
            ),
        );
    }
}

/// The ctx-data key holding the rect of the detachable chip under the pointer.
///
/// Unlike the hover *group*, this is a within-frame hand-off: chips are drawn
/// before [`paint_hover_group`] runs, which reads the value and takes it back
/// out again, so a frame where the pointer is over no chip at all leaves
/// nothing behind to go stale.
fn chip_hover_id() -> egui::Id {
    egui::Id::new("pt_hoverchip")
}

/// Note that the pointer is over a chip that a plain drag would pick up *on its
/// own*, so the hover highlight can outline exactly that chip rather than the
/// whole block.
///
/// The highlight has to answer "what would I be lifting?", and for a detachable
/// chip the answer is the chip: dragging `PARALLEL` takes the `PARALLEL`, not
/// the loop it sits on. Holding Ctrl changes the answer — that is what
/// [`chip_drag_payload`] switches to a whole-row drag — so with Ctrl down
/// nothing is recorded here and the block highlight stands, matching what the
/// gesture would actually do.
fn record_chip_hover(ui: &egui::Ui, chip: &Chip, rect: egui::Rect) {
    if chip.is_base
        || chip.detach.is_none()
        || drag_in_flight(ui.ctx())
        || ui.input(|i| i.modifiers.command)
        || !ui.rect_contains_pointer(rect)
    {
        return;
    }
    ui.ctx()
        .data_mut(|d| d.insert_temp(chip_hover_id(), Some(rect)));
}

/// The ctx-data key the hover group is parked under for the next frame.
///
/// Same one-frame hand-off as [`mod_ghost_id`], and for the same reason: which
/// rows are in the group isn't known until every row has been laid out, but the
/// chips have to be coloured while they are drawn. A single frame's lag on a
/// pointer that stays put for many is invisible.
fn hover_group_id() -> egui::Id {
    egui::Id::new("pt_hovergroup")
}

/// The hover group last frame settled on, for a row that needs to colour its
/// chips before this frame's group is known.
fn hovered_last_frame(ui: &egui::Ui) -> Option<Vec<usize>> {
    ui.ctx().data(|d| d.get_temp(hover_group_id())).flatten()
}

/// Whether anything at all is currently being dragged in the block editor — a
/// palette block, a modifier clause or an existing row. Each travels as its own
/// payload type, so all three have to be asked.
fn drag_in_flight(ctx: &egui::Context) -> bool {
    egui::DragAndDrop::has_payload_of_type::<DragItem>(ctx)
        || egui::DragAndDrop::has_payload_of_type::<NodeKind>(ctx)
        || egui::DragAndDrop::has_payload_of_type::<Modifier>(ctx)
}

/// Render the `WITH … END` fields of a report-request as a nested block under
/// its line (indented one level): each field is an editable `name: query` row
/// with a `×` to remove it, followed by an "add field" affordance and an `END`
/// footer aligned to the request line. This is a **GUI-only** view over
/// [`ReportStmt::Request::with`] — the shared [`flatten`] deliberately doesn't
/// emit WITH rows, so this never affects the TUI or the flow's drop-index maths.
fn with_block(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    path: &[usize],
    depth: usize,
    items: &[WithItem],
    acts: &mut Vec<Act>,
) -> egui::Rect {
    let field_indent = (depth as f32 + 1.0) * INDENT_STEP;
    ui.vertical(|ui| {
        for (i, item) in items.iter().enumerate() {
            ui.horizontal(|ui| {
                ui.add_space(field_indent);
                let text = match item {
                    // A field's own clauses belong on its row: leaving them out
                    // made clauses that are plainly there in the source
                    // invisible in the block editor. They are written into the
                    // row's text rather than drawn as detachable chips because
                    // the row *is* one chip -- a field is edited through its
                    // wizard, which is where all four clauses are set.
                    WithItem::Field {
                        name,
                        query,
                        stats,
                        image,
                        truth,
                        detail,
                    } => {
                        let mut t = format!("{name}: {query}");
                        if !stats.is_empty() {
                            t.push_str(&format!(
                                " STATISTICS({})",
                                stats
                                    .iter()
                                    .map(|k| k.keyword())
                                    .collect::<Vec<_>>()
                                    .join(", ")
                            ));
                        }
                        t.push_str(&crate::report::flow::image_text(image.as_ref()));
                        t.push_str(&crate::report::flow::truth_text(truth.as_deref()));
                        t.push_str(&crate::report::flow::detail_text(*detail));
                        t
                    }
                    WithItem::ResponseFmt(fmt) => format!(
                        "RESPONSE {}",
                        match fmt {
                            crate::report::flow::ResponseFmt::Raw => "RAW",
                            crate::report::flow::ResponseFmt::Pretty => "PRETTY",
                        }
                    ),
                    WithItem::Comment(text) => format!("#{text}"),
                };
                // A commented-out line reads as a comment, not as a field it
                // isn't: dimmed like a `FlowNode::Comment` block. It keeps its
                // `×` so it can be deleted, but has no wizard.
                let tint = if matches!(item, WithItem::Comment(_)) {
                    chip_tint(th, th.dim)
                } else {
                    chip_tint(th, th.subst)
                };
                let lbl = chip_shell(ui, &tint, true, ROUND_CHIP, |ui| {
                    let lbl = ui.add(
                        egui::Label::new(RichText::new(&text).color(tint.text))
                            .selectable(false)
                            .sense(egui::Sense::click()),
                    );
                    if detach_x(ui, tint.text) {
                        acts.push(Act::RemoveWith {
                            path: path.to_vec(),
                            index: i,
                        });
                    }
                    lbl
                });
                // Only `name: query` fields have a wizard; a bare `WITH RESPONSE`
                // item is edited/removed via its `×` only.
                if lbl.clicked() && matches!(item, WithItem::Field { .. }) {
                    acts.push(Act::EditWith {
                        path: path.to_vec(),
                        index: i,
                    });
                }
                // A `WITH` field is a report column with a name of its own, so
                // it is what a `STATISTICS` clause attaches to — the request
                // line above has no single column to summarise. The row is
                // therefore its own drop target: without one the clause bounced
                // off every part of a `WITH` block, and there was no way at all
                // to add a summary to a field by dragging.
                let zone = egui::Rect::from_x_y_ranges(
                    lbl.rect.left()..=ui.max_rect().right(),
                    lbl.rect.y_range(),
                );
                let zresp = ui.interact(
                    zone,
                    ui.id().with(("pt_withstats", path, i)),
                    egui::Sense::hover(),
                );
                if let Some(m) = zresp.dnd_hover_payload::<Modifier>() {
                    let ok = *m == Modifier::Statistics && edit::with_stats_applies(items, i);
                    ui.painter().rect_stroke(
                        zone.expand(2.0),
                        egui::CornerRadius::same(6),
                        egui::Stroke::new(2.0, if ok { th.accent } else { th.err }),
                        egui::StrokeKind::Outside,
                    );
                    // The refusals a field row can give differ from a node's, so
                    // they are spelled out here rather than through
                    // `Modifier::reject_reason` (which only speaks about nodes).
                    if !ok {
                        let why = if *m != Modifier::Statistics {
                            s.mod_reject_with_field
                        } else {
                            s.mod_reject_present
                        };
                        egui::Tooltip::always_open(
                            ui.ctx().clone(),
                            ui.layer_id(),
                            ui.id().with(("pt_withwhy", path, i)),
                            egui::PopupAnchor::Pointer,
                        )
                        .show(|ui| {
                            ui.colored_label(th.err, why);
                        });
                    }
                }
                if let Some(m) = release_payload::<Modifier>(&zresp)
                    && *m == Modifier::Statistics
                    && edit::with_stats_applies(items, i)
                {
                    acts.push(Act::AttachWithStats {
                        path: path.to_vec(),
                        index: i,
                    });
                }
            });
        }
        ui.horizontal(|ui| {
            ui.add_space(field_indent);
            if ui
                .add(
                    egui::Button::new(
                        RichText::new(format!("{} {}", super::icons::PLUS, s.gui_report_with_add))
                            .color(th.subst),
                    )
                    .small(),
                )
                .clicked()
            {
                acts.push(Act::AddWith {
                    path: path.to_vec(),
                });
            }
        });
        ui.horizontal(|ui| {
            ui.add_space(depth as f32 * INDENT_STEP);
            static_chip(ui, th, "END", th.accent, "");
        });
    })
    .response
    .rect
}

/// A catch-all drop target filling the empty space beneath the last row: a base
/// block dropped here is appended as the last top-level line, and an existing
/// row dragged here is moved to the end. `top_len` is the current number of
/// top-level nodes (the append index). A no-op when there is no spare vertical
/// space (the report already fills / overflows the viewport — the last row's own
/// insert strip covers appending in that case).

/// One option in the `collection:` dropdown.
///
/// The label and the stored value are deliberately different things. What gets
/// written into the directive has to be a *path*, because that is literally
/// what the runner opens (`report_cli` does a `read_to_string` on it); but a
/// path is a poor thing to pick from a list, so the user sees the collection's
/// name and the path only as secondary detail.
#[derive(Clone, Debug, PartialEq)]
struct CollectionChoice {
    /// Written into `# collection:` — relative to the report when it can be,
    /// so a report and its collection can be moved together.
    value: String,
    /// The collection's name, which is what the user actually recognises.
    label: String,
    /// Where it is, shown under the name to tell two same-named collections
    /// apart: relative to the workspace root for a workspace file, otherwise
    /// the path as stored.
    detail: String,
    /// Whether it lives inside this report's workspace. Those are listed first
    /// and shown by default; anything else is a deliberate reach outside.
    in_workspace: bool,
}

/// The collections a report can bind to: every collection file in its
/// workspace, plus any collection open in a tab.
///
/// The workspace is scanned rather than read from the open tabs because a
/// workspace usually holds far more collections than are open at any moment,
/// and those are exactly the ones a report living in that workspace is likely
/// to want. Open tabs are still offered (a report doesn't have to live in a
/// workspace at all), but only when they aren't already in the scan.
fn collection_choices(
    root: Option<&std::path::Path>,
    report_path: Option<&std::path::Path>,
    open: &[crate::collection::Collection],
    unsaved_label: &str,
) -> Vec<CollectionChoice> {
    let mut out: Vec<CollectionChoice> = Vec::new();
    let root_scope = root;

    if let Some(root) = root {
        for e in crate::workspace::scan_workspace(root, true) {
            if e.is_dir || !is_collection_file(&e.path) {
                continue;
            }
            out.push(CollectionChoice {
                value: portable_ref(&e.path, report_path, root_scope),
                label: collection_label(&e.path),
                detail: e
                    .path
                    .strip_prefix(root)
                    .unwrap_or(&e.path)
                    .to_string_lossy()
                    .into_owned(),
                in_workspace: true,
            });
        }
    }

    for c in open {
        match c.path.as_deref() {
            Some(p) => {
                // Already offered by the scan above — listing it twice would
                // only invite picking the "wrong" identical one.
                let value = portable_ref(p, report_path, root_scope);
                if out.iter().any(|ch| ch.value == value) {
                    continue;
                }
                out.push(CollectionChoice {
                    value,
                    label: c.name.clone(),
                    detail: p.to_string_lossy().into_owned(),
                    in_workspace: root.is_some_and(|r| p.starts_with(r)),
                });
            }
            // An unsaved collection has no path to write, so it can only be
            // referenced by name — which is the fallback
            // `resolve_bound_collection` keeps for exactly this case. It won't
            // resolve for the headless runner, hence the explicit label.
            None => out.push(CollectionChoice {
                value: c.name.clone(),
                label: c.name.clone(),
                detail: unsaved_label.to_string(),
                in_workspace: false,
            }),
        }
    }

    // Workspace files first, then alphabetically, so the list is stable no
    // matter what order the tabs happen to be in.
    out.sort_by(|a, b| {
        b.in_workspace
            .cmp(&a.in_workspace)
            .then_with(|| a.label.to_lowercase().cmp(&b.label.to_lowercase()))
            .then_with(|| a.value.cmp(&b.value))
    });
    out
}

/// Whether `path` is a collection, as opposed to the reports and environments
/// that share a workspace with it.
fn is_collection_file(path: &std::path::Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some("hurl") | Some("json")
    )
}

/// The name to show for a collection file: its filename without the extension.
/// `# collection:` stores a path, but a path is not what the user named the
/// thing, so the list shows this and keeps the path as detail.
fn collection_label(path: &std::path::Path) -> String {
    path.file_stem()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.to_string_lossy().into_owned())
}

/// The body of the `collection:` dropdown: the workspace's own collections
/// under a heading, and anything else behind an opt-in toggle.
///
/// Collections outside the report's workspace are hidden by default because
/// they are almost always the wrong answer — binding to one writes a path that
/// escapes the workspace, so the report stops travelling with it. They stay one
/// click away rather than being removed, since a report needn't live in a
/// workspace at all (and when it doesn't, there is nothing to hide behind and
/// everything is shown).
fn collection_menu(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    choices: &[CollectionChoice],
    current: &str,
    picked: &mut Option<String>,
    browse: &mut bool,
) {
    let (mine, others): (Vec<&CollectionChoice>, Vec<&CollectionChoice>) =
        choices.iter().partition(|c| c.in_workspace);

    let show_all_id = ui.make_persistent_id("pt_hdr_collection_show_all");
    // With no workspace to scope to there is nothing to reveal, so the toggle
    // would only be a switch that does nothing.
    let mut show_all = mine.is_empty()
        || ui
            .ctx()
            .data(|d| d.get_temp::<bool>(show_all_id))
            .unwrap_or(false);

    if !mine.is_empty() {
        ui.label(
            RichText::new(s.gui_report_ws_collections)
                .color(th.dim)
                .small(),
        );
        for c in &mine {
            collection_item(ui, th, c, current, picked);
        }
    }

    if !others.is_empty() {
        if mine.is_empty() {
            show_all = true;
        } else {
            ui.separator();
            if ui
                .checkbox(&mut show_all, s.gui_report_show_all_collections)
                .changed()
            {
                ui.ctx().data_mut(|d| d.insert_temp(show_all_id, show_all));
            }
        }
        if show_all {
            if !mine.is_empty() {
                ui.label(
                    RichText::new(s.gui_report_other_collections)
                        .color(th.dim)
                        .small(),
                );
            }
            for c in &others {
                collection_item(ui, th, c, current, picked);
            }
        }
    }

    // A report outside a workspace, opened before any collection, has nothing
    // to list at all — and `collection:` is the one setting a report can't run
    // without. An empty menu would be a dead end, so say so and offer the way
    // out. Browse is always available; the list is a shortcut, not the only way.
    if choices.is_empty() {
        ui.colored_label(th.dim, s.gui_report_no_collections);
    }
    if !choices.is_empty() {
        ui.separator();
    }
    if ui.button(s.gui_report_browse).clicked() {
        *browse = true;
        ui.close();
    }
}

/// One row of the collection dropdown: the name, with where it lives beneath it
/// so two collections that share a name can still be told apart.
fn collection_item(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    c: &CollectionChoice,
    current: &str,
    picked: &mut Option<String>,
) {
    if ui
        .selectable_label(c.value == current, &c.label)
        .on_hover_text(&c.detail)
        .clicked()
    {
        *picked = Some(c.value.clone());
    }
    ui.label(RichText::new(&c.detail).color(th.dim).small());
}

/// The workspace a report belongs to, if any: the deepest open workspace root
/// that contains it. Deepest, because workspaces can be nested and the closest
/// one is the one whose collections are actually relevant.
fn report_workspace_root(app: &GuiApp, ed: &ReportEditor) -> Option<std::path::PathBuf> {
    let path = ed.report.path.as_deref()?;
    app.session
        .collections
        .iter()
        .filter_map(|c| c.workspace_root.as_ref())
        .filter(|root| path.starts_with(root))
        .max_by_key(|root| root.components().count())
        .cloned()
}

/// The panel the report settings are drawn in.
///
/// Enclosing them says what a column of chips above `BEGIN` could not: these
/// are settings *for* the report, not the first steps *of* it. Unframed they
/// read as blocks that merely happened not to be draggable. The muted fill and
/// quiet border mark the boundary without competing with the flow for
/// attention, and the frame's own left edge lines up with the blocks below so
/// the two still read as one column.
fn settings_frame(th: &GuiTheme) -> egui::Frame {
    egui::Frame::NONE
        .fill(mix(th.panel, th.dim, 0.10))
        .stroke(egui::Stroke::new(1.0, mix(th.panel, th.dim, 0.35)))
        .inner_margin(egui::Margin::symmetric(8, 6))
        .corner_radius(BLOCK_RADIUS as u8)
}

/// The report's `# key: value` header directives, drawn as a pinned strip above
/// `BEGIN`.
///
/// These are settings for the report as a *whole* — which collection it runs
/// against, where its results go — not steps in the flow, so they are
/// deliberately not blocks: there is nothing meaningful about reordering them,
/// dropping one inside a loop, or binning them onto the trash bar. Keeping them
/// in a fixed strip above `BEGIN` says exactly that, while still making them
/// discoverable and editable, which they previously weren't from the GUI at all.
///
/// The two directives a report can't run without are always shown (as an unset
/// prompt when empty); the rest appear once set, or on demand from the `+`.
fn header_strip(ed: &ReportEditor, app: &GuiApp, ui: &mut egui::Ui, acts: &mut Vec<Act>) {
    let th = app.theme;
    let s = &app.strings;
    let Some(flow) = ed.flow.as_ref() else {
        return;
    };
    // Built on demand rather than every frame: it scans the workspace off disk,
    // and the list is only ever looked at while the dropdown is open.
    let ws_root = report_workspace_root(app, ed);
    let collections = || {
        collection_choices(
            ws_root.as_deref(),
            ed.report.path.as_deref(),
            &app.session.collections,
            s.gui_report_collection_unsaved,
        )
    };
    let envs: Vec<String> = app
        .session
        .global_envs
        .iter()
        .map(|e| e.name.clone())
        .collect();

    let formats: Vec<String> = crate::report::writer::OUTPUT_EXTENSIONS
        .iter()
        .map(|e| e.to_string())
        .collect();

    settings_panel(
        ui,
        &th,
        s,
        &|key| {
            flow.header
                .get_all(key)
                .into_iter()
                .map(str::to_string)
                .collect()
        },
        &collections,
        &envs,
        &formats,
        acts,
    );
}

/// The settings panel itself, given only the values it shows.
///
/// Split from `header_strip` so the layout can be exercised without standing up
/// a whole `GuiApp`: the caller resolves each directive's current value and the
/// choices its dropdowns offer, and this decides what is drawn and in what
/// order.
#[allow(clippy::too_many_arguments)]
fn settings_panel(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    value_of: &dyn Fn(&str) -> Vec<String>,
    collections: &dyn Fn() -> Vec<CollectionChoice>,
    envs: &Vec<String>,
    formats: &Vec<String>,
    acts: &mut Vec<Act>,
) {
    let specs = header_specs();
    settings_frame(th).show(ui, |ui| {
        // A heading, because the frame alone only said "these are grouped", not
        // what the group *is*. The same words the TUI's panel uses.
        ui.label(
            RichText::new(s.report_settings_heading)
                .strong()
                .color(th.text),
        )
        .on_hover_text(s.report_settings_help);
        // One setting per line, each starting at the same left edge as `BEGIN`
        // below. Laying them out in a row instead left them ragged — a combo
        // chip and a text chip are different widths and sit differently in a
        // wrapped line.
        ui.set_width(settings_width(ui));
        for spec in &specs {
            // `collection:` repeats — one chip for the primary and one for each
            // aliased helper — so a helper is visible and editable here rather
            // than only in the raw source. Every other directive has exactly one.
            let mut values = value_of(spec.key);
            if values.is_empty() {
                values.push(String::new());
            }
            for (occurrence, value) in values.into_iter().enumerate() {
                if value.is_empty() && !spec.always_shown {
                    continue;
                }
                let choices = match spec.kind {
                    HeaderKind::Environment => Some(envs),
                    HeaderKind::Format => Some(formats),
                    _ => None,
                };
                ui.horizontal(|ui| {
                    header_chip(
                        ui,
                        th,
                        s,
                        spec,
                        occurrence,
                        &value,
                        choices,
                        collections,
                        acts,
                    )
                });
            }
        }

        // Optional directives that aren't set yet are offered from the button
        // rather than shown as a row of empty prompts, which would bury the two
        // that matter. It sits below the settings it appends to, where a list's
        // "add another" belongs. When every setting is already present there is
        // nothing to add, so it isn't drawn at all.
        let missing: Vec<&HeaderSpec> = specs
            .iter()
            .filter(|sp| !sp.always_shown && value_of(sp.key).is_empty())
            .collect();
        // The add menu is always drawn now: a helper collection can always be
        // added, since `collection:` repeats and so is never "already set".
        header_add_menu(
            ui,
            s,
            &missing,
            value_of("collection").len().max(1),
            value_of("labels").len(),
            acts,
        );
    });
}

/// How wide the settings panel is drawn: the full width of the editor pane.
///
/// Not shrink-wrapped to its contents, which change width constantly (picking a
/// longer collection name, adding a setting, clearing one) — a panel that
/// resized with them would make the whole view twitch every time a dropdown was
/// used. Filling the pane is just as stable and doesn't leave the panel
/// stranded in a sea of empty space, which made it read as a stray tooltip
/// rather than as the report's own settings. It also gives a long collection
/// path or output name room to sit unabbreviated, instead of being truncated to
/// `billing-servi…` in a box that had space to spare beside it.
fn settings_width(ui: &egui::Ui) -> f32 {
    ui.available_width()
}

/// The menu offering the optional directives that aren't set yet.
///
/// Spelled out rather than a bare `+`: on its own, a plus above the flow gives
/// no hint whether it adds a *block* (which is what everything else in this
/// view does) or a report-wide setting. The button also carries the explanation
/// of what report settings are, which previously hung off a decorative icon
/// beside it that did nothing else.
fn header_add_menu(
    ui: &mut egui::Ui,
    s: &crate::i18n::Strings,
    missing: &[&HeaderSpec],
    next_collection: usize,
    next_label: usize,
    acts: &mut Vec<Act>,
) {
    let label = format!("{}  {}", super::icons::PLUS, s.report_add_setting);
    ui.menu_button(label, |ui| {
        for spec in missing {
            if ui
                .button(spec.key.to_uppercase())
                .on_hover_text(edit::header_help(spec.key, s))
                .clicked()
            {
                // Seed with a placeholder so the chip appears; the user
                // then types or picks the real value. An empty string
                // would immediately be dropped again by `set_header`.
                acts.push(Act::SetHeader {
                    key: spec.key,
                    occurrence: 0,
                    value: Some(HEADER_PLACEHOLDER.to_string()),
                });
                ui.close();
            }
        }
        // Always offered: unlike the one-shot directives, another collection
        // can always be added.
        if ui
            .button(s.report_add_helper_collection)
            .on_hover_text(s.report_helper_collection_help)
            .clicked()
        {
            acts.push(Act::SetHeader {
                key: "collection",
                occurrence: next_collection,
                value: Some(HEADER_PLACEHOLDER.to_string()),
            });
            ui.close();
        }
        // Likewise a further label class, once the first has been added: the
        // vocabulary a report scores against is nearly always at least two
        // classes, and the one-shot entry above is gone after the first.
        if next_label > 0
            && ui
                .button(s.report_add_label_class)
                .on_hover_text(edit::header_help("labels", s))
                .clicked()
        {
            acts.push(Act::SetHeader {
                key: "labels",
                occurrence: next_label,
                value: Some(HEADER_PLACEHOLDER.to_string()),
            });
            ui.close();
        }
    })
    .response
    .on_hover_text(s.report_settings_help);
}

/// One chip in the header strip: an uppercase key label plus its editor.
fn header_chip(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    spec: &HeaderSpec,
    occurrence: usize,
    value: &str,
    choices: Option<&Vec<String>>,
    collections: &dyn Fn() -> Vec<CollectionChoice>,
    acts: &mut Vec<Act>,
) {
    // A helper collection stores `path AS alias` in one directive, but they are
    // two different things to edit: the dropdown picks the file, a small text
    // field beside it names the alias. Splitting here (and rejoining on write)
    // keeps the chip honest about both without inventing a second directive.
    let helper = spec.key == "collection" && occurrence > 0;
    let (value, alias) = if spec.key == "collection" {
        let (r, a) = crate::report::flow::split_collection_ref(value);
        (r, a.unwrap_or_default())
    } else {
        (value, "")
    };
    let rejoin = move |reference: &str| {
        if helper && !alias.is_empty() {
            format!("{reference} AS {alias}")
        } else {
            reference.to_string()
        }
    };
    // An unset required directive is drawn in the error colour: it is the one
    // thing standing between the report and a run, so it should look like it.
    let unset = value.is_empty() || value == "?";
    let color = if unset && spec.required {
        th.err
    } else {
        th.dim
    };
    let mut tint = chip_tint(th, color);
    if !(unset && spec.required) {
        // A settings row is chrome, not a category: its rule would otherwise be
        // a grey bar saying nothing. An *unset required* one keeps its red rule,
        // where the bar is doing real work — it marks the row blocking the run.
        tint.rule = None;
    }
    tint.text = if unset && spec.required {
        th.err
    } else {
        th.text
    };
    let key = spec.key;
    let text_col = tint.text;

    let combo = matches!(
        spec.kind,
        HeaderKind::Collection | HeaderKind::Environment | HeaderKind::Format
    );

    let scope = ui.scope(|ui| {
        // A combo box sets its own (tallest) height; everything else has to be
        // grown to match, exactly as in the flow's chips.
        chip_shell(ui, &tint, !combo, ROUND_CHIP, |ui| {
            // The key label goes on the left, but a combo box is taller than a
            // label and only sets the row height once it has been added — a
            // label placed first would be "centred" in a still-short row and end
            // up sitting above the combo's own text. So reserve its slot now and
            // paint it after, centred against the finished row. (The flow's
            // request chips do exactly this, for exactly this reason.)
            let font = egui::TextStyle::Button.resolve(ui.style());
            let galley = ui.painter().layout_no_wrap(key.to_uppercase(), font, color);
            let gsize = galley.size();
            let (label_rect, _) = ui.allocate_exact_size(gsize, egui::Sense::hover());
            match spec.kind {
                HeaderKind::Collection | HeaderKind::Environment | HeaderKind::Format => {
                    // A collection is stored as a path but shown by name, so
                    // the closed text has to be derived rather than echoed.
                    let shown = if unset {
                        s.report_setting_unset.to_string()
                    } else if matches!(spec.kind, HeaderKind::Collection) {
                        collection_label(std::path::Path::new(value))
                    } else {
                        value.to_string()
                    };
                    let mut picked = None;
                    let mut browse = false;
                    egui::ComboBox::from_id_salt(("pt_hdr", key))
                        .selected_text(RichText::new(shown).color(text_col))
                        .show_ui(ui, |ui| {
                            if matches!(spec.kind, HeaderKind::Collection) {
                                collection_menu(
                                    ui,
                                    th,
                                    s,
                                    &collections(),
                                    value,
                                    &mut picked,
                                    &mut browse,
                                );
                            } else {
                                for c in choices.map(Vec::as_slice).unwrap_or_default() {
                                    if ui.selectable_label(c == value, c).clicked() {
                                        picked = Some(c.clone());
                                    }
                                }
                            }
                        });
                    if browse {
                        acts.push(Act::PickHeaderFile { key, occurrence });
                    }
                    if let Some(v) = picked
                        && v != value
                    {
                        acts.push(Act::SetHeader {
                            key,
                            occurrence,
                            value: Some(rejoin(&v)),
                        });
                    }
                    // The alias a helper's requests are addressed through. Only
                    // on helpers: the primary collection is *the* collection,
                    // and an alias on it is a validation error.
                    if helper {
                        let id = ui.make_persistent_id(("pt_hdr_alias", occurrence));
                        if let Some(text) = inline_text_edit(
                            ui,
                            id,
                            alias,
                            s.report_alias_unset,
                            "AS ",
                            80.0,
                            FIELD_MAX_WIDTH,
                        ) && text != alias
                        {
                            let text = text.trim().to_string();
                            let joined = if text.is_empty() {
                                value.to_string()
                            } else {
                                format!("{value} AS {text}")
                            };
                            acts.push(Act::SetHeader {
                                key,
                                occurrence,
                                value: Some(joined),
                            });
                        }
                    }
                }
                // A label class is one directive but two different things to
                // edit -- the label a report displays and scores by, and the
                // other spellings that mean it -- so it is split into two
                // fields with the `=` drawn between them, exactly as a helper
                // collection is split around its `AS`. A single text box made
                // the user remember both the `=` and the comma rules; two
                // boxes and a keyword show them.
                HeaderKind::Text if key == "labels" => {
                    let raw = if value == "?" { "" } else { value };
                    let (name, synonyms) = crate::report::flow::split_label_class(raw);
                    // Writing back always keeps the class name, even with no
                    // synonyms yet: a class that only knows its own label is a
                    // perfectly good half-finished line, and dropping it would
                    // delete the row out from under someone mid-edit.
                    let rejoin = |name: &str, synonyms: &str| {
                        let name = name.trim();
                        let synonyms = synonyms.trim();
                        let name = if name.is_empty() {
                            HEADER_PLACEHOLDER
                        } else {
                            name
                        };
                        if synonyms.is_empty() {
                            name.to_string()
                        } else {
                            format!("{name} = {synonyms}")
                        }
                    };
                    let id = ui.make_persistent_id(("pt_hdr_label", occurrence));
                    if let Some(text) = inline_text_edit(
                        ui,
                        id,
                        name,
                        s.report_label_class_unset,
                        "",
                        90.0,
                        FIELD_MAX_WIDTH,
                    ) && text != name
                    {
                        acts.push(Act::SetHeader {
                            key,
                            occurrence,
                            value: Some(rejoin(&text, synonyms)),
                        });
                    }
                    // The `=` is drawn, unlike the helper collection's `AS`
                    // just above (which is only hover text): it is the
                    // directive's own syntax, and seeing it is what tells the
                    // reader these two boxes are one line of the source.
                    //
                    // It does read a little like assignment, which the relation
                    // isn't -- every spelling here counts as the same answer,
                    // and matching is symmetric (`LabelMap::same`). But the two
                    // halves aren't interchangeable either: the left-hand side
                    // is the label that gets *printed* and the order the
                    // confusion-matrix axes read in, so a symmetric glyph like
                    // `≡` would over-claim. Matching the source exactly was
                    // judged worth more than either shade of imprecision.
                    ui.label(RichText::new("=").color(color).monospace());
                    let id = ui.make_persistent_id(("pt_hdr_label_syn", occurrence));
                    if let Some(text) = inline_text_edit(
                        ui,
                        id,
                        synonyms,
                        s.report_label_synonyms_unset,
                        s.report_label_synonyms_help,
                        150.0,
                        FIELD_MAX_WIDTH,
                    ) && text != synonyms
                    {
                        acts.push(Act::SetHeader {
                            key,
                            occurrence,
                            value: Some(rejoin(name, &text)),
                        });
                    }
                }
                HeaderKind::Folder | HeaderKind::File | HeaderKind::Text => {
                    let current = if value == "?" { "" } else { value };
                    let id = ui.make_persistent_id(("pt_hdr_text", key));
                    if let Some(text) = inline_text_edit(
                        ui,
                        id,
                        current,
                        s.report_setting_unset,
                        "",
                        150.0,
                        FIELD_MAX_WIDTH,
                    ) && text != current
                    {
                        acts.push(Act::SetHeader {
                            key,
                            occurrence,
                            value: Some(text),
                        });
                    }
                    if spec.kind.is_path()
                        && ui
                            .small_button(super::icons::FOLDER)
                            .on_hover_text(s.gui_report_browse)
                            .clicked()
                    {
                        acts.push(Act::PickHeaderFile { key, occurrence });
                    }
                }
            }
            // Anything actually set can be cleared, `collection:` included —
            // an always-shown setting simply falls back to its unset prompt
            // rather than disappearing, and the rest return to the add menu.
            //
            // An *optional* setting keeps its `×` even while unset: it was put
            // here from the add menu and starts life showing the unset prompt,
            // so without one there would be no way to take it off again.
            // A helper is always removable: it is one of many, so clearing it
            // takes the whole line out rather than leaving an unset prompt.
            if (!unset || !spec.always_shown || helper) && detach_x(ui, color) {
                acts.push(Act::SetHeader {
                    key,
                    occurrence,
                    value: None,
                });
            }
            let cy = ui.min_rect().center().y;
            ui.painter().galley(
                egui::pos2(label_rect.left(), cy - gsize.y / 2.0),
                galley,
                color,
            );
        });
    });
    if ui.ctx().dragged_id().is_none() {
        scope.response.on_hover_text(edit::header_help(key, s));
    }
}

/// Browse for the file (or folder, for `root:`) a path-valued header directive
/// should point at, and store it relative to the report when that is shorter —
/// a report and its data usually travel together, so an absolute path would
/// break the moment the pair moved.
fn pick_header_file(ed: &mut ReportEditor, app: &mut GuiApp, key: &'static str, occurrence: usize) {
    // A helper's stored value is `path AS alias`; only the path part seeds the
    // browser, and only it is replaced by what comes back.
    let current = ed
        .flow
        .as_ref()
        .and_then(|f| f.header.get_all(key).get(occurrence).copied())
        .unwrap_or_default()
        .to_string();
    let (current_ref, _) = crate::report::flow::split_collection_ref(&current);
    let seed = Some(current_ref)
        .filter(|r| !r.is_empty())
        .and_then(super::filepick::seed_dir)
        .or_else(|| {
            ed.report
                .path
                .as_deref()
                .and_then(|p| p.parent())
                .map(std::path::Path::to_path_buf)
        });
    let title = edit::header_help(key, &app.strings);
    // Only `root:` and `baseline:` are paths — `output:` names a format and is
    // picked from a list, so it never reaches here.
    let kind = match key {
        "root" => super::filepick::PickKind::Folder,
        // `collection:` is normally chosen from the dropdown, but that list can
        // be empty (a report outside a workspace, opened before any collection),
        // so Browse is offered there too and lands here.
        "collection" => super::filepick::PickKind::File {
            filters: super::filepick::owned_filters(&[("hurl", &["hurl"]), ("*", &["*"])]),
        },
        _ => super::filepick::PickKind::File {
            filters: super::filepick::owned_filters(&[
                ("baseline", &["baseline", "json"]),
                ("*", &["*"]),
            ]),
        },
    };
    app.request_pick(
        kind,
        title,
        seed.as_deref(),
        super::menu::PickAction::ReportHeaderFile { key, occurrence },
    );
}

/// Write back the file a [`pick_header_file`] dialog returned.
///
/// Split from the request because the dialog runs off the frame loop (see
/// [`super::filepick`]), so this happens frames later with only the app in
/// hand. The alias is re-read here rather than captured at request time: the
/// user may have edited it while the dialog was up.
pub(super) fn apply_picked_header_file(
    app: &mut GuiApp,
    key: &'static str,
    occurrence: usize,
    picked: Option<std::path::PathBuf>,
) {
    let Some(path) = picked else {
        return; // cancelled
    };
    let Some(mut ed) = app.report_editor.take() else {
        return; // the editor closed while the dialog was open
    };
    apply_header_file(&mut ed, app, key, occurrence, &path);
    app.report_editor = Some(ed);
}

fn apply_header_file(
    ed: &mut ReportEditor,
    app: &mut GuiApp,
    key: &'static str,
    occurrence: usize,
    path: &std::path::Path,
) {
    let current = ed
        .flow
        .as_ref()
        .and_then(|f| f.header.get_all(key).get(occurrence).copied())
        .unwrap_or_default()
        .to_string();
    let (_, alias) = crate::report::flow::split_collection_ref(&current);
    // A browsed collection is relativised the same way a picked one is — the
    // dropdown writes a portable `../`-walking ref, and Browse must not quietly
    // bake in an absolute path instead.
    let text = if key == "collection" {
        portable_ref(
            path,
            ed.report.path.as_deref(),
            report_workspace_root(app, ed).as_deref(),
        )
    } else {
        relative_to_report(path, ed.report.path.as_deref())
    };
    // The alias is the user's, not the picker's — browsing for a different file
    // must not silently drop it.
    let text = match alias {
        Some(a) if key == "collection" && occurrence > 0 => format!("{text} AS {a}"),
        _ => text,
    };
    ed.edit_flow(|flow| {
        edit::set_header_nth(flow, key, occurrence, Some(&text));
    });
}

/// The folder/file picker beside a loop's path box.
///
/// Seeded from the path the loop already names, resolved against the report's
/// own folder, so browsing starts where the loop is looking rather than at the
/// process working directory. What comes back is written relative to the report
/// wherever it can be: a loop that hard-codes an absolute path stops working
/// the moment the report is shared or moved, and picking a folder is exactly
/// when that would otherwise happen without the user noticing.
fn pick_loop_dir(ed: &mut ReportEditor, app: &mut GuiApp, path: &[usize], file: bool) {
    let report_dir = ed
        .report
        .path
        .as_deref()
        .and_then(|p| p.parent())
        .map(std::path::Path::to_path_buf);
    let current = ed
        .flow
        .as_ref()
        .and_then(|f| edit::loop_dir(f, path))
        .unwrap_or_default();
    // Resolve the loop's own (usually relative) path against the report so the
    // dialog opens on the folder it names.
    let seed = if current.is_empty() {
        report_dir.clone()
    } else {
        let joined = match &report_dir {
            Some(dir) => dir.join(&current),
            None => std::path::PathBuf::from(&current),
        };
        super::filepick::seed_dir(joined.to_string_lossy().as_ref()).or(report_dir.clone())
    };

    let title = if file {
        app.strings.gui_pick_loop_file
    } else {
        app.strings.gui_pick_loop_folder
    };
    let kind = if file {
        super::filepick::PickKind::File {
            filters: super::filepick::owned_filters(&[("*", &["*"])]),
        }
    } else {
        super::filepick::PickKind::Folder
    };
    app.request_pick(
        kind,
        title,
        seed.as_deref(),
        super::menu::PickAction::ReportLoopDir {
            path: path.to_vec(),
            file,
        },
    );
}

/// Write back the folder a [`pick_loop_dir`] dialog returned, frames later.
pub(super) fn apply_picked_loop_dir(
    app: &mut GuiApp,
    path: &[usize],
    _file: bool,
    picked: Option<std::path::PathBuf>,
) {
    let Some(picked) = picked else {
        return; // cancelled
    };
    let Some(mut ed) = app.report_editor.take() else {
        return; // the editor closed while the dialog was open
    };
    let text = relative_to_report(&picked, ed.report.path.as_deref());
    ed.edit_flow(|flow| {
        edit::set_loop_dir(flow, path, &text);
    });
    ed.selection = path.to_vec();
    app.report_editor = Some(ed);
}

/// `path` expressed relative to the report's own folder when it lives under it,
/// else the absolute path.
fn relative_to_report(path: &std::path::Path, report: Option<&std::path::Path>) -> String {
    report
        .and_then(|r| r.parent())
        .and_then(|dir| path.strip_prefix(dir).ok())
        .unwrap_or(path)
        .to_string_lossy()
        .into_owned()
}

/// `path` expressed relative to the report, walking *up* out of the report's
/// folder where it has to (`../apis/billing.hurl`), so long as it stays inside
/// `scope`.
///
/// This is what makes a workspace portable. A report in `reports/` binding to a
/// collection in `apis/` shares no prefix with it, so a plain `strip_prefix`
/// gives up and writes an absolute path — which is a path on *this* machine,
/// and breaks the moment the workspace is handed to someone else. Both files
/// are in the same workspace and will be copied together, so the way to say
/// where the collection is, is by where it sits relative to the report.
///
/// `scope` bounds how far up we're willing to walk: outside it the two files
/// aren't travelling together anyway, so a relative path would be a lie and the
/// absolute one is the honest answer.
fn portable_ref(
    path: &std::path::Path,
    report: Option<&std::path::Path>,
    scope: Option<&std::path::Path>,
) -> String {
    let plain = relative_to_report(path, report);
    if !std::path::Path::new(&plain).is_absolute() {
        return plain;
    }
    let (Some(dir), Some(scope)) = (report.and_then(std::path::Path::parent), scope) else {
        return plain;
    };
    if !path.starts_with(scope) || !dir.starts_with(scope) {
        return plain;
    }

    // Drop the shared leading components, then step up once per component of
    // the report's folder that remains.
    let mut from = dir.components().peekable();
    let mut to = path.components().peekable();
    while let (Some(a), Some(b)) = (from.peek(), to.peek()) {
        if a != b {
            break;
        }
        from.next();
        to.next();
    }
    let mut rel = std::path::PathBuf::new();
    for _ in from {
        rel.push("..");
    }
    rel.extend(to);
    if rel.as_os_str().is_empty() {
        return plain;
    }
    // Forward slashes even on Windows: the directive is written into a file
    // that is meant to be read on someone else's machine, and every path API
    // involved accepts them.
    rel.to_string_lossy().replace('\\', "/")
}

/// The `END` closing the whole flow, mirroring the `BEGIN` chip at the top.
///
/// Laid out exactly like a depth-0 block row (the same vertical/horizontal
/// nesting) so it lines up with `BEGIN` rather than sitting at a different
/// indent.
/// The closing caption of the whole flow, matching the synthetic `Begin` row at
/// the top.
///
/// Dim, sentence case and translated, exactly like its opening partner and
/// deliberately *unlike* the uppercase `END` that closes a `FOR` or a `WITH`.
/// Those are real keywords the parser requires and the Source view prints
/// verbatim; this one is punctuation the editor draws so the report reads as one
/// bracketed block, and there is no node behind it to select, move or drop onto.
/// Two things that look identical but behave completely differently is the worst
/// of both, so the pair that isn't in the file is the pair that looks like a
/// caption.
fn flow_end_row(ui: &mut egui::Ui, th: &GuiTheme, s: &crate::i18n::Strings) {
    ui.vertical(|ui| {
        ui.horizontal_top(|ui| {
            static_chip(ui, th, s.report_node_end, th.dim, s.chip_help_flow_end);
        });
    });
}

/// The "nothing here yet" line drawn between `BEGIN` and `END` when the report
/// has no steps. Indented to sit where the first block will, and dimmed so it
/// reads as guidance rather than as a block of its own.
fn empty_flow_hint(ui: &mut egui::Ui, th: &GuiTheme, s: &crate::i18n::Strings) {
    ui.horizontal(|ui| {
        ui.add_space(INDENT_STEP);
        ui.colored_label(th.dim, s.gui_report_empty_flow);
    });
    ui.add_space(2.0);
}

fn tail_drop_zone(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    top_len: usize,
    titles: &[String],
    acts: &mut Vec<Act>,
) {
    let remaining = ui.available_size_before_wrap();
    if remaining.y < 6.0 {
        return;
    }
    let (rect, _) = ui.allocate_exact_size(remaining, egui::Sense::hover());
    let resp = ui.interact(rect, ui.id().with("pt_tail_drop"), egui::Sense::hover());
    let end = InsertPos {
        parent: Vec::new(),
        index: top_len,
    };
    let hovering = resp.dnd_hover_payload::<NodeKind>().is_some()
        || resp
            .dnd_hover_payload::<DragItem>()
            .is_some_and(|d| matches!(&*d, DragItem::Row(_)));
    if hovering {
        // Match the insert-strip placeholder's fully-open height (the block
        // actually in hand, less the same 4px inset) so the tail ghost is the
        // size of the block being dropped — including a whole `FOR` loop — not
        // a fixed sliver.
        let size = dragged_block_size(ui);
        let clip = egui::Rect::from_min_size(
            rect.left_top(),
            egui::vec2(
                (rect.width() - 8.0).max(1.0),
                (size.y - 4.0).min(rect.height()).max(6.0),
            ),
        );
        paint_drop_silhouette(ui, rect.left_top(), &dragged_block_shape(ui), clip, th);
    }
    if let Some(kind) = release_payload::<NodeKind>(&resp) {
        acts.push(Act::DropNode {
            pos: end,
            node: node_for_kind(*kind, titles),
        });
    } else if let Some(item) = release_payload::<DragItem>(&resp) {
        // Moving the row that is *already* last to the end is a no-op — skip it
        // so it doesn't push a redundant undo entry / mark the report dirty.
        if let DragItem::Row(from) = &*item
            && from.as_slice() != [top_len.saturating_sub(1)]
        {
            acts.push(Act::MoveNode {
                from: from.clone(),
                pos: end,
            });
        }
    }
}

/// The uniform content height every chip reserves — the natural height of the
/// tallest inline control a chip can host, a combo box (`interact_size.y` grown
/// by the app's larger `button_padding`, rounded up to a whole pixel). Shorter
/// controls are lifted to this height so a plain-label chip is exactly as tall
/// as one hosting a combo box or a text field.
fn chip_h(ui: &egui::Ui) -> f32 {
    let sp = ui.spacing();
    let row = ui.text_style_height(&egui::TextStyle::Body);
    (sp.interact_size.y.max(row + 2.0 * sp.button_padding.y)).ceil()
}

/// Lay out a chip's content inside a rounded, tinted frame of uniform height.
///
/// A combo box grows to fill whatever vertical space its row offers, so it
/// already renders at the tallest chip height on its own — pass `grow = false`
/// for a chip that hosts one. Every *other* control (a plain label, a text
/// field) is shorter, so `grow = true` reserves a [`chip_h`]-tall row and
/// centres the content in it, lifting those chips to exactly the same height as
/// a combo-box chip. Returns the content closure's value.
/// Lay out a chip's label as two distinct kinds of word rather than one
/// undifferentiated run: the editor's own keyword in the UI face, and any
/// identifier the user supplied in the monospace face.
///
/// This is most of what makes a flow skimmable. `BASELINE(staging)` is two
/// different things joined by punctuation — one is vocabulary the editor
/// defines, the other is the user's own data — and setting them identically
/// makes the reader parse the brackets to tell which is which. A face change
/// does that pre-attentively, and it is the convention every code editor
/// already teaches, so it needs no explaining.
///
/// egui has no bold variant of the default proportional font (only Phosphor is
/// registered alongside it), so weight is not available as a channel here; face
/// and the theme's brighter `strong` colour carry the emphasis instead.
fn chip_label_job(ui: &egui::Ui, text: &str, color: Color32) -> egui::text::LayoutJob {
    let base = egui::TextStyle::Button.resolve(ui.style());
    let mono = egui::FontId::new(base.size, egui::FontFamily::Monospace);

    // The keyword runs up to the first bracket or space; everything after it is
    // the user's. A label with neither is all keyword (`GET`, `PARALLEL`).
    let split = text.find(['(', ' ']).unwrap_or(text.len());
    let (keyword, rest) = text.split_at(split);

    let mut job = egui::text::LayoutJob::default();
    let mut push = |s: &str, font: egui::FontId| {
        if s.is_empty() {
            return;
        }
        job.append(
            s,
            0.0,
            egui::TextFormat {
                font_id: font,
                color,
                ..Default::default()
            },
        );
    };
    push(keyword, base.clone());
    push(rest, mono);
    job
}

/// A chip label, laid out by [`chip_label_job`] and sensing clicks and drags.
fn chip_label(ui: &mut egui::Ui, text: &str, color: Color32) -> egui::Response {
    let job = chip_label_job(ui, text, color);
    ui.add(
        egui::Label::new(job)
            .selectable(false)
            .sense(egui::Sense::click_and_drag()),
    )
}

fn chip_shell<R>(
    ui: &mut egui::Ui,
    tint: &ChipTint,
    grow: bool,
    corners: egui::CornerRadius,
    content: impl FnOnce(&mut egui::Ui) -> R,
) -> R {
    let h = chip_h(ui);
    let framed = egui::Frame::NONE
        .fill(tint.fill)
        .stroke(tint.stroke)
        .inner_margin(egui::Margin::symmetric(8, 3))
        .corner_radius(corners)
        .show(ui, |ui| {
            // egui sizes a combo box (and a button) to
            // `max(interact_size.y, content + 2 * button_padding.y)`, which is
            // the same formula `chip_h` uses — so the two *coincided* until the
            // app scaled its text and they landed a fraction of a pixel apart,
            // enough to round to a visibly uneven bottom edge next to a label
            // chip. Pinning `interact_size.y` to the chip height makes the combo
            // *derive* its height from `chip_h` instead of agreeing with it by
            // arithmetic: the max can only resolve to `h`, because `h` is by
            // definition at least the content plus its padding.
            ui.spacing_mut().interact_size.y = h;
            ui.horizontal(|ui| {
                if grow {
                    ui.set_min_height(h);
                }
                content(ui)
            })
            .inner
        });
    // The category bar, painted after the frame so it sits over the border it
    // replaces along that edge. It mirrors the chip's own left corner radii and
    // squares off on the right, so on a tethered pill it stops cleanly at the
    // seam instead of bulging past it.
    if let Some(rule) = tint.rule {
        let rect = framed.response.rect;
        ui.painter().rect_filled(
            egui::Rect::from_min_max(
                rect.min,
                egui::pos2(rect.left() + CHIP_RULE_W, rect.bottom()),
            ),
            egui::CornerRadius {
                nw: corners.nw,
                sw: corners.sw,
                ne: 0,
                se: 0,
            },
            rule,
        );
    }
    // The seam, painted over the two borders that meet at it: a hanger's left
    // border and its anchor's right one are the same hue as their fills, so
    // without this the segments of a pill run together.
    if let Some(seam) = tint.seam {
        let rect = framed.response.rect;
        ui.painter().vline(
            rect.left(),
            rect.top() + 1.0..=rect.bottom() - 1.0,
            egui::Stroke::new(1.0, seam),
        );
    }
    framed.inner
}

/// How strongly a chip's category colour is allowed to show, as blend factors
/// against the panel colour: the background wash, the border, and how far the
/// label text is pulled from the ordinary text colour toward the category hue.
///
/// These are deliberately one set of constants rather than a literal repeated at
/// each chip site. A block flow puts five categories on screen at once, and when
/// the fill, the border *and* the text were all near-full chroma the result read
/// as coloured building blocks — several professional users called the editor
/// childish on the strength of it. Quietening the surface while keeping the hue
/// identifiable is a single judgement about the whole editor, so it is made in
/// one place and every chip reads from it.
///
/// The *hue* per category is untouched (see [`kind_color`]): a `FOR` is the same
/// colour it always was, just no longer shouted.
///
/// The fill and border are now barely tinted at all, because the category is
/// carried by the rule down the chip's leading edge instead (see [`ChipTint`]).
/// Spending the whole chip surface on the hue and spending a 3px bar on it say
/// the same thing, but only one of them fills the window with colour.
const CHIP_FILL_MIX: f32 = 0.05;
const CHIP_STROKE_MIX: f32 = 0.16;
/// The same two mixes for a chip in the hover group. The fill carries the
/// change (a chip is mostly fill); the stroke follows so the edge doesn't
/// disappear into the stronger fill behind it.
const CHIP_FILL_MIX_HOVER: f32 = 0.32;
const CHIP_STROKE_MIX_HOVER: f32 = 0.55;
const CHIP_TEXT_MIX: f32 = 0.45;

/// The width of the category rule down a chip's leading edge.
///
/// It fits inside [`chip_shell`]'s existing 8px left inner margin, so turning
/// the rule on cost no reflow: the label sits exactly where it always did, with
/// 5px of clear space beside the bar.
const CHIP_RULE_W: f32 = 3.0;

/// How a chip is coloured: a near-neutral surface plus a full-strength category
/// bar down its leading edge.
///
/// The bar is the reason the surface can be neutral. Colour used as a *fill*
/// scales with the size of the thing filled, so a flow of blocks became a wall
/// of colour; the same hue used as a rule is just as identifiable — the eye
/// scans a column of coloured edges very well — while leaving the chip itself a
/// quiet card. This is the pattern editors and issue trackers already use for
/// exactly this reason.
struct ChipTint {
    fill: Color32,
    stroke: egui::Stroke,
    text: Color32,
    /// The category bar, or `None` for a chip that shouldn't show one: a
    /// selected chip (whose fill already carries the selection colour) and the
    /// hanger of a tethered pair (whose leading edge is *inside* the pill, where
    /// a bar would read as a divider rather than as a category).
    rule: Option<Color32>,
    /// The seam divider, drawn down this chip's left edge when it is the hanger
    /// of a tethered pair. See [`CHIP_SEAM_MIX`] for why a pill needs one.
    seam: Option<Color32>,
}

/// The colours for a chip of category colour `color`.
///
/// Text is blended *from the theme's text colour toward* the category hue rather
/// than being the hue itself: full-chroma text on a tint of the same hue is both
/// loud and low-contrast, and the label has to stay comfortably readable — it is
/// the part that actually says what the block does.
fn chip_tint(th: &GuiTheme, color: Color32) -> ChipTint {
    ChipTint {
        fill: mix(th.panel, color, CHIP_FILL_MIX),
        stroke: egui::Stroke::new(1.0, mix(th.panel, color, CHIP_STROKE_MIX)),
        text: mix(th.text, color, CHIP_TEXT_MIX),
        rule: Some(color),
        seam: None,
    }
}

/// The colours for a chip, honouring the selected-base highlight and the hover
/// group.
///
/// Hovering deepens the chip's *own* colour rather than tinting it towards a
/// single highlight hue: the colour is what says which kind of block this is, so
/// a highlight that overwrote it would cost more than it gave. The panel behind
/// the row says the same thing, but on a row whose chips cover most of their
/// width there is barely any panel left to see — which is exactly the row where
/// knowing what a drag would pick up matters most.
fn chip_colors(th: &GuiTheme, chip: &Chip, selected: bool) -> ChipTint {
    let mut tint = if chip.is_base && selected {
        // Keep the stroke *width* identical to the unselected state (only the
        // colour and fill change): a thicker stroke would expand the frame by a
        // pixel and shift the chip and its neighbours, so selecting a block
        // would visibly nudge it. Selection must recolour in place, never
        // resize or move.
        ChipTint {
            fill: th.select_bg,
            stroke: egui::Stroke::new(1.0, th.select_fg),
            text: th.select_fg,
            rule: None,
            seam: None,
        }
    } else if chip.hovered {
        ChipTint {
            fill: mix(th.panel, chip.color, CHIP_FILL_MIX_HOVER),
            stroke: egui::Stroke::new(1.0, mix(th.panel, chip.color, CHIP_STROKE_MIX_HOVER)),
            // The label is left alone: it is already at full contrast, and
            // pushing it further only made hovered text look bolder than its
            // neighbours, which reads as a different *kind* of chip rather than
            // as the same chip highlighted.
            text: mix(th.text, chip.color, CHIP_TEXT_MIX),
            rule: Some(chip.color),
            seam: None,
        }
    } else {
        chip_tint(th, chip.color)
    };
    if chip.join_prev {
        // The category bar would sit *inside* the pill here, where it reads as
        // a divider rather than as a category — so it goes, and a proper
        // divider takes its place (see `CHIP_SEAM_MIX`).
        tint.rule = None;
        tint.seam = Some(mix(tint.fill, tint.text, CHIP_SEAM_MIX));
    }
    tint
}

/// How far the seam between two tethered chips is pulled from the fill toward
/// the label colour.
///
/// A tethered pair is drawn as one pill split into segments, and with nothing
/// but two same-hued borders meeting at the seam the split was invisible: a
/// column carrying `STATISTICS`, `IMAGE`, `TRUTH` *and* `DETAIL` came out as
/// one long blob of text, and users read the clauses as having merged into the
/// thing they qualify. The seam is what makes it a *segmented* pill — the same
/// device a segmented control uses — so it has to be clearly visible while
/// still being quieter than the pill's outer border.
const CHIP_SEAM_MIX: f32 = 0.45;

/// A small frameless `×` button. Returns whether it was clicked. Kept separate
/// from the chip's drag handle so its click is never stolen by a frame-wide
/// drag interaction (the bug where the detach `×` did nothing).
fn detach_x(ui: &mut egui::Ui, col: Color32) -> bool {
    ui.add(
        egui::Button::new(RichText::new("×").color(col))
            .small()
            .frame(false),
    )
    .clicked()
}

/// The width to give an inline field so its current value actually fits.
///
/// The fields used to be fixed-width, which meant anything longer than the
/// guess — most real folder paths, and any alias longer than a word — was
/// silently cut off, with no indication that the box held more than it showed.
/// Measuring instead means a field is as wide as what is in it, clamped so a
/// long path can't push the rest of the row off screen (past `max` the box
/// scrolls, as before, but now only in the genuinely long cases).
fn fitted_field_width(ui: &egui::Ui, text: &str, hint: &str, min: f32, max: f32) -> f32 {
    let font = egui::TextStyle::Monospace.resolve(ui.style());
    // Measure the hint too, so an *empty* box is still wide enough to show its
    // placeholder rather than clipping it.
    let measure = |t: &str| {
        ui.painter()
            .layout_no_wrap(t.to_string(), font.clone(), egui::Color32::PLACEHOLDER)
            .size()
            .x
    };
    // Room for the text edit's own margin plus the caret sitting after the last
    // character — without it the caret lands on the border when the box is full.
    let padding = 12.0;
    (measure(text).max(measure(hint)) + padding).clamp(min, max)
}

/// An inline single-line text field that commits on blur. The in-progress buffer
/// lives in egui temp memory keyed by `id` (so it survives across frames while
/// focused) and is dropped once committed / idle, keeping the field synced to
/// the AST. Returns `Some(trimmed value)` on the frame focus is lost.
///
/// `hint` is the placeholder shown inside the empty box and must stay short
/// enough to fit it; `help` is the full explanation, shown on hover. These were
/// once the same string, so a field's entire explanation was crammed into a
/// box a few characters wide and read as "Only files ...".
fn inline_text_edit(
    ui: &mut egui::Ui,
    id: egui::Id,
    current: &str,
    hint: &str,
    help: &str,
    min_width: f32,
    max_width: f32,
) -> Option<String> {
    let mut buf = ui
        .data(|d| d.get_temp::<String>(id))
        .unwrap_or_else(|| current.to_string());
    let width = fitted_field_width(ui, &buf, hint, min_width, max_width);
    let resp = ui.add(
        egui::TextEdit::singleline(&mut buf)
            .hint_text(hint)
            // Match the fill a combo-box chip (BASELINE/COMPARISON/REQUEST) uses
            // for its button, so an inline field (the AS alias) doesn't read as
            // a darker, sunken box beside them.
            .background_color(ui.visuals().widgets.inactive.weak_bg_fill)
            // Monospace for the same reason the identifier half of a chip label
            // is (see `chip_label_job`): what goes in here is the user's own
            // name for something, not the editor's vocabulary, and the two
            // should not look alike. It also stops an alias and the keyword
            // beside it from reading as one phrase.
            .font(egui::TextStyle::Monospace)
            .desired_width(width),
    );
    // Only when not being typed into: a tooltip popping up under the cursor
    // while the user is editing is in the way of the thing they're editing.
    if !help.is_empty() && !resp.has_focus() {
        resp.clone().on_hover_text(help);
    }
    if resp.lost_focus() {
        ui.data_mut(|d| d.remove::<String>(id));
        Some(buf.trim().to_string())
    } else if resp.has_focus() {
        ui.data_mut(|d| d.insert_temp(id, buf));
        None
    } else {
        ui.data_mut(|d| d.remove::<String>(id));
        None
    }
}

/// A plain, non-interactive tinted chip (the synthetic `Begin` / `END` rows).
fn static_chip(ui: &mut egui::Ui, th: &GuiTheme, text: &str, color: Color32, help: &str) {
    let tint = chip_tint(th, color);
    let text_col = tint.text;
    let scope = ui.scope(|ui| {
        chip_shell(ui, &tint, true, ROUND_CHIP, |ui| {
            let job = chip_label_job(ui, text, text_col);
            ui.add(egui::Label::new(job).selectable(false));
        });
    });
    if !help.is_empty() && ui.ctx().dragged_id().is_none() {
        scope.response.on_hover_text(help);
    }
}

/// Render one [`Chip`]. The base chip is click-to-select, double-click-to-open
/// the wizard, and a drag source that relocates or bins its whole row; a
/// modifier chip shows a `×` that detaches it and is itself a drag source that
/// bins the modifier.
/// Render a chip that has been picked up on its own: into a floating layer that
/// follows the pointer, with a dashed ghost left behind in its slot.
///
/// The chip still allocates its space in the row (so the line doesn't reflow
/// under the pointer) and is still rendered by [`render_chip`], so it keeps its
/// widget id and the drag stays alive.
///
/// Returns the floating layer and the *slot* rect. The caller applies the
/// transform that puts the layer under the pointer, and only once it has
/// finished adding to that layer: a `WITH` chip carries its whole field block
/// with it, and transforming from here would move the chip while leaving the
/// fields behind — the same "parts move at different speeds" bug [`DragLift`]
/// exists to avoid.
#[allow(clippy::too_many_arguments)]
fn lift_chip(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    chip: &Chip,
    selected: bool,
    path: &[usize],
    row_index: usize,
    titles: &[String],
    env_choices: &[String],
    acts: &mut Vec<Act>,
) -> (egui::LayerId, egui::Rect) {
    // One lifted chip per row at most, so the row index is a sufficient key.
    let layer_id = egui::LayerId::new(
        egui::Order::Tooltip,
        ui.id().with(("pt_drag_chip", row_index)),
    );
    let slot = ui
        .scope_builder(
            egui::UiBuilder::new()
                .layer_id(layer_id)
                .layout(egui::Layout::left_to_right(egui::Align::Min)),
            |ui| render_chip(ui, th, s, chip, selected, path, titles, env_choices, acts),
        )
        .inner;
    // Painted after the scope, into the *base* layer: the chip itself has moved
    // to the floating layer, so the slot underneath is empty.
    paint_origin_ghost(ui.painter(), slot, th);
    (layer_id, slot)
}

/// Put a chip's floating layer under the pointer, anchored so the chip itself
/// sits on the cursor and anything lifted with it hangs off at its natural
/// offset. Call once, after everything that belongs to the layer is painted.
fn follow_pointer(ctx: &egui::Context, layer_id: egui::LayerId, anchor: egui::Rect) {
    if let Some(pointer) = ctx.pointer_interact_pos() {
        ctx.transform_layer_shapes(
            layer_id,
            egui::emath::TSTransform::from_translation(pointer - anchor.center()),
        );
    }
}

#[allow(clippy::too_many_arguments)]
fn render_chip(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    chip: &Chip,
    selected: bool,
    path: &[usize],
    titles: &[String],
    env_choices: &[String],
    acts: &mut Vec<Act>,
) -> egui::Rect {
    // The hover help is attached to a wrapper covering the whole chip rather
    // than to any one widget inside it, so it shows over the label, the `×` and
    // the inline combo/text field alike. It is suppressed mid-drag, where a
    // tooltip trailing the pointer would just obscure the drop targets.
    let scope = ui.scope(|ui| {
        render_chip_body(ui, th, s, chip, selected, path, titles, env_choices, acts);
    });
    let rect = scope.response.rect;
    record_chip_hover(ui, chip, rect);
    // A detachable chip also spells out the drag gesture. It is not otherwise
    // discoverable that a plain drag pulls one chip out of a line while Ctrl
    // takes the whole line, and the two are easy to trigger by accident.
    if ui.ctx().dragged_id().is_none() {
        let help = match (chip.help.is_empty(), chip.detach.is_some()) {
            (true, false) => String::new(),
            (false, false) => chip.help.to_string(),
            (true, true) => s.chip_help_drag_gesture.to_string(),
            (false, true) => format!("{}\n\n{}", chip.help, s.chip_help_drag_gesture),
        };
        if !help.is_empty() {
            scope.response.on_hover_text(help);
        }
    }
    rect
}

#[allow(clippy::too_many_arguments)]
fn render_chip_body(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    chip: &Chip,
    selected: bool,
    path: &[usize],
    titles: &[String],
    env_choices: &[String],
    acts: &mut Vec<Act>,
) {
    // Chips that host an inline control draw a keyword prefix (the drag/select
    // handle) plus a combo box / text field; they only fall back to a plain
    // label when there is nothing to pick from.
    match &chip.edit {
        ChipEdit::Request { name } if !titles.is_empty() => {
            combo_chip(
                ui,
                th,
                s,
                chip,
                selected,
                path,
                "REQUEST",
                name,
                titles,
                true,
                acts,
                |picked| Act::RenameRequest {
                    path: path.to_vec(),
                    name: picked,
                },
            );
            return;
        }
        ChipEdit::EnvRole {
            baseline,
            index,
            name,
        } if !env_choices.is_empty() => {
            let kw = if *baseline { "BASELINE" } else { "COMPARISON" };
            let (baseline, index) = (*baseline, *index);
            combo_chip(
                ui,
                th,
                s,
                chip,
                selected,
                path,
                kw,
                name,
                env_choices,
                false,
                acts,
                move |picked| Act::SetEnvRole {
                    path: path.to_vec(),
                    baseline,
                    index,
                    name: picked,
                },
            );
            return;
        }
        ChipEdit::Alias { text } => {
            alias_chip(ui, th, s, chip, path, text, acts);
            return;
        }
        ChipEdit::Parallel { degree } => {
            parallel_chip(ui, th, s, chip, path, *degree, acts);
            return;
        }
        ChipEdit::Loop(l) => {
            let l = l.clone();
            loop_chip(ui, th, s, chip, path, &l, acts);
            return;
        }
        _ => {}
    }

    let tint = chip_colors(th, chip, selected);
    let text_col = tint.text;
    let handle = chip_shell(ui, &tint, true, chip_corners(chip), |ui| {
        // The label is the drag/select handle, kept separate from the `×`
        // button so the button's click is never stolen by the drag sense.
        let handle = chip_label(ui, &chip.text, text_col);
        if let Some(which) = chip.detach
            && detach_x(ui, text_col)
        {
            acts.push(Act::DetachMod {
                path: path.to_vec(),
                which,
            });
        }
        handle
    });

    if handle.dragged() {
        handle.dnd_set_drag_payload(chip_drag_payload(ui, chip, path));
    }
    if chip.is_base {
        if handle.double_clicked() {
            acts.push(Act::OpenWizard(path.to_vec()));
        } else if handle.clicked() {
            acts.push(Act::Select(path.to_vec()));
        }
    } else if chip_opens_wizard_on_click(chip) && handle.clicked() {
        // SHOW / HIDE / RESPONSE are edited through the request wizard's field
        // pickers, so a plain click on one of these chips opens that wizard
        // (dragging it still detaches it — see `chip_drag_payload`).
        acts.push(Act::OpenWizard(path.to_vec()));
    }
}

/// Choose the drag payload for a chip. Holding Ctrl/Cmd forces moving the whole
/// line/subtree from *any* chip (`DragItem::Row`); otherwise a detachable
/// modifier chip is picked up on its own to detach it (`DragItem::Chip`), and
/// every other chip (the editable base, the request handle, fixed keywords)
/// moves the line. This is the "plain-drag detaches a chip, Ctrl-drag moves the
/// line" behaviour, applied uniformly across every draggable chip.
fn chip_drag_payload(ui: &egui::Ui, chip: &Chip, path: &[usize]) -> DragItem {
    let force_row = ui.input(|i| i.modifiers.command);
    match (force_row, chip.is_base, chip.detach) {
        (false, false, Some(which)) => DragItem::Chip {
            path: path.to_vec(),
            which,
        },
        _ => DragItem::Row(path.to_vec()),
    }
}

/// Whether a plain click on this (non-base) chip should open a wizard to edit
/// it. True for the `SHOW` / `HIDE` / `RESPONSE` clauses, whose fields are
/// picked in the request wizard rather than typed inline, and for an ENVS
/// loop's `BASELINE … SHOW(…)`, whose checklist lives in the ENVS wizard — the
/// wizard opened is the one belonging to the chip's own node, so both land in
/// the right place.
fn chip_opens_wizard_on_click(chip: &Chip) -> bool {
    matches!(
        chip.detach,
        Some(
            DetachWhich::Show
                | DetachWhich::Hide
                | DetachWhich::Response
                | DetachWhich::BaselineShow
        )
    )
}

/// Render an `AS <alias>` chip: an `AS` prefix (the drag/detach handle) followed
/// by an inline text field that commits the alias/name on blur.
fn alias_chip(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    chip: &Chip,
    path: &[usize],
    current: &str,
    acts: &mut Vec<Act>,
) {
    let tint = chip_colors(th, chip, false);
    let text_col = tint.text;
    let handle = chip_shell(ui, &tint, true, chip_corners(chip), |ui| {
        let handle = ui.add(
            egui::Label::new(RichText::new("AS").color(text_col))
                .selectable(false)
                .sense(egui::Sense::click_and_drag()),
        );
        let id = ui.make_persistent_id(("pt_alias", path));
        if let Some(text) = inline_text_edit(
            ui,
            id,
            current,
            s.gui_report_alias_hint,
            "",
            ALIAS_FIELD_WIDTH,
            FIELD_MAX_WIDTH,
        ) && text != current
        {
            acts.push(Act::SetAlias {
                path: path.to_vec(),
                text,
            });
        }
        if let Some(which) = chip.detach
            && detach_x(ui, text_col)
        {
            acts.push(Act::DetachMod {
                path: path.to_vec(),
                which,
            });
        }
        handle
    });

    if handle.dragged() {
        handle.dnd_set_drag_payload(chip_drag_payload(ui, chip, path));
    }
}

/// The `PARALLEL` chip: a `PARALLEL` drag handle plus a small box for the
/// optional max-concurrency. Leaving the box empty is meaningful — it is the
/// plain `PARALLEL` form, where the limit comes from the prelude's
/// `MAX_PARALLEL` — so a blank commits `None` rather than being ignored. Text
/// that isn't a positive number is discarded on blur, which keeps the flow from
/// ever holding the `PARALLEL(0)` the parser would reject on reload.
/// Render a `FOR` loop head with its editable parts inline: `FOR` (the drag
/// handle) followed by a box for the loop variable, the source keyword, a box
/// and picker for the folder/file, and a `FILES` loop's `MATCH` glob.
///
/// The parts that can't be edited in one box — a destructuring pattern, a list
/// literal, a `FOLDERS … WITH` role list — are drawn as plain labels, exactly as
/// the whole head used to be, and are still reached through the wizard.
fn loop_chip(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    chip: &Chip,
    path: &[usize],
    l: &LoopEdit,
    acts: &mut Vec<Act>,
) {
    let tint = chip_colors(th, chip, false);
    let text_col = tint.text;
    let handle = chip_shell(ui, &tint, true, chip_corners(chip), |ui| {
        // Every fixed word on the loop head is a drag/select handle, and the
        // editable boxes between them are not — a click meant for a field must
        // never start a drag of the row. `FOR` alone used to be the only handle,
        // which made a loop the one block in the editor you had to hit a
        // three-letter target to pick up; the keywords beside it (`IN FILES`,
        // `MATCH`, the tail) are just as fixed, so they join in.
        let mut handle = ui.add(
            egui::Label::new(RichText::new("FOR").color(text_col))
                .selectable(false)
                .sense(egui::Sense::click_and_drag()),
        );
        if let Some(var) = &l.var {
            let id = ui.make_persistent_id(("pt_loop_var", path));
            let resp = inline_text_edit(
                ui,
                id,
                var,
                s.gui_report_loop_var_hint,
                s.chip_help_loop_var,
                LOOP_VAR_FIELD_WIDTH,
                FIELD_MAX_WIDTH,
            );
            if let Some(text) = resp
                && &text != var
            {
                acts.push(Act::SetLoopVar {
                    path: path.to_vec(),
                    text,
                });
            }
        }
        handle |= ui.add(
            egui::Label::new(RichText::new(&l.keyword).color(text_col))
                .selectable(false)
                .sense(egui::Sense::click_and_drag()),
        );
        if let Some((dir, is_file)) = &l.dir {
            let id = ui.make_persistent_id(("pt_loop_dir", path));
            let resp = inline_text_edit(
                ui,
                id,
                dir,
                s.gui_report_loop_dir_hint,
                s.chip_help_loop_dir,
                LOOP_PATH_FIELD_WIDTH,
                FIELD_MAX_WIDTH,
            );
            if let Some(text) = resp
                && &text != dir
            {
                acts.push(Act::SetLoopDir {
                    path: path.to_vec(),
                    text,
                });
            }
            // Framed, not flat. Drawn without a frame this read as an icon
            // printed on the chip rather than as something to press, and users
            // reported not realising a folder picker was there at all. The
            // frame gives it egui's normal hover fill, and the pointing-hand
            // cursor confirms it before the click.
            let pick = ui
                .add(
                    egui::Button::new(RichText::new(super::icons::FOLDER).color(text_col))
                        .min_size(egui::vec2(PICKER_BUTTON_WIDTH, 0.0)),
                )
                .on_hover_cursor(egui::CursorIcon::PointingHand)
                .on_hover_text(if *is_file {
                    s.chip_help_loop_pick_file
                } else {
                    s.chip_help_loop_pick_folder
                });
            if pick.clicked() {
                acts.push(Act::PickLoopDir {
                    path: path.to_vec(),
                    file: *is_file,
                });
            }
        }
        if let Some(glob) = &l.glob {
            // The keyword carries the same explanation as the box beside it:
            // "MATCH" alone says nothing to someone meeting it for the first
            // time, and it is the word their eye lands on first.
            handle |= ui
                .add(
                    egui::Label::new(RichText::new("MATCH").color(text_col))
                        .selectable(false)
                        .sense(egui::Sense::click_and_drag()),
                )
                .on_hover_text(s.chip_help_loop_glob);
            let id = ui.make_persistent_id(("pt_loop_glob", path));
            let resp = inline_text_edit(
                ui,
                id,
                glob,
                s.gui_report_loop_glob_hint,
                s.chip_help_loop_glob,
                LOOP_GLOB_FIELD_WIDTH,
                FIELD_MAX_WIDTH,
            );
            if let Some(text) = resp
                && &text != glob
            {
                acts.push(Act::SetLoopGlob {
                    path: path.to_vec(),
                    text,
                });
            }
        }
        if !l.tail.is_empty() {
            handle |= ui.add(
                egui::Label::new(RichText::new(&l.tail).color(text_col))
                    .selectable(false)
                    .sense(egui::Sense::click_and_drag()),
            );
        }
        handle
    });

    if handle.dragged() {
        handle.dnd_set_drag_payload(chip_drag_payload(ui, chip, path));
    }
    // Selecting and wizard-opening, the same as every other chip's handle. A
    // loop head was the one chip you could not click to select, so keyboard
    // actions aimed at "the selected block" could not be pointed at a loop.
    if handle.double_clicked() {
        acts.push(Act::OpenWizard(path.to_vec()));
    } else if handle.clicked() {
        acts.push(Act::Select(path.to_vec()));
    }
}

fn parallel_chip(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    chip: &Chip,
    path: &[usize],
    current: Option<u32>,
    acts: &mut Vec<Act>,
) {
    let tint = chip_colors(th, chip, false);
    let text_col = tint.text;
    let shown = current.map(|n| n.to_string()).unwrap_or_default();
    let handle = chip_shell(ui, &tint, true, chip_corners(chip), |ui| {
        let handle = ui.add(
            egui::Label::new(RichText::new("PARALLEL").color(text_col))
                .selectable(false)
                .sense(egui::Sense::click_and_drag()),
        );
        let id = ui.make_persistent_id(("pt_parallel", path));
        if let Some(text) = inline_text_edit(
            ui,
            id,
            &shown,
            s.node_form_parallel_degree,
            "",
            PARALLEL_FIELD_WIDTH,
            FIELD_MAX_WIDTH,
        ) && text != shown
        {
            let degree = match text.trim() {
                "" => Some(None),
                t => t.parse::<u32>().ok().filter(|n| *n > 0).map(Some),
            };
            if let Some(degree) = degree {
                acts.push(Act::SetParallelDegree {
                    path: path.to_vec(),
                    degree,
                });
            }
        }
        if let Some(which) = chip.detach
            && detach_x(ui, text_col)
        {
            acts.push(Act::DetachMod {
                path: path.to_vec(),
                which,
            });
        }
        handle
    });

    if handle.dragged() {
        handle.dnd_set_drag_payload(chip_drag_payload(ui, chip, path));
    }
}

/// Render a chip whose enumerable part is an inline dropdown. The keyword
/// `prefix` (e.g. `REQUEST`) is the drag/select handle so the combo beside it
/// stays free to open without starting a drag; picking a new value emits the
/// action `make_act(value)`. When `filter` is set the dropdown gains a search
/// box that narrows the choices as you type (the TUI-style request picker).
#[allow(clippy::too_many_arguments)]
fn combo_chip(
    ui: &mut egui::Ui,
    th: &GuiTheme,
    s: &crate::i18n::Strings,
    chip: &Chip,
    selected: bool,
    path: &[usize],
    prefix: &str,
    current: &str,
    choices: &[String],
    filter: bool,
    acts: &mut Vec<Act>,
    make_act: impl FnOnce(String) -> Act,
) {
    let tint = chip_colors(th, chip, selected);
    let text_col = tint.text;
    let mut picked: Option<String> = None;
    let mut detached: Option<DetachWhich> = None;
    // A combo box already renders at the tallest chip height, so this chip does
    // not grow its row (which would only inflate the combo box further).
    let handle = chip_shell(ui, &tint, false, chip_corners(chip), |ui| {
        // The keyword prefix is the interactive handle (drag to reorder, click
        // to select, double-click to open the wizard). It must be added *before*
        // the combo (so it sits on the left), but the combo is taller and only
        // sets the row height once it is added — a plain label placed first
        // would therefore be "centred" in a still-short row and end up sitting
        // above the combo's text. So we reserve the prefix's slot now (as the
        // drag handle) but defer painting the text until the combo has set the
        // row height, then paint it vertically centred against the combo.
        let font = egui::TextStyle::Button.resolve(ui.style());
        let galley = ui
            .painter()
            .layout_no_wrap(prefix.to_string(), font, text_col);
        let gsize = galley.size();
        let (label_rect, handle) = ui.allocate_exact_size(gsize, egui::Sense::click_and_drag());
        egui::ComboBox::from_id_salt((path, prefix))
            .selected_text(RichText::new(current).color(text_col))
            .show_ui(ui, |ui| {
                if filter {
                    filtered_choices(ui, s, path, prefix, current, choices, &mut picked);
                } else {
                    for c in choices {
                        if ui.selectable_label(c == current, c).clicked() {
                            picked = Some(c.clone());
                        }
                    }
                }
            });
        // A detachable combo chip (a BASELINE/COMPARISON role) gets the same
        // `×` as every other detachable chip, so the dropdown isn't the only
        // thing you can do to it.
        if let Some(which) = chip.detach
            && detach_x(ui, text_col)
        {
            detached = Some(which);
        }
        let cy = ui.min_rect().center().y;
        ui.painter().galley(
            egui::pos2(label_rect.left(), cy - gsize.y / 2.0),
            galley,
            text_col,
        );
        handle
    });
    if let Some(which) = detached {
        acts.push(Act::DetachMod {
            path: path.to_vec(),
            which,
        });
    }

    // Same rule as every other chip: plain-drag pulls a detachable chip out of
    // the line, Ctrl/Cmd-drag moves the whole line (see `chip_drag_payload`).
    if handle.dragged() {
        handle.dnd_set_drag_payload(chip_drag_payload(ui, chip, path));
    }
    if handle.double_clicked() {
        acts.push(Act::OpenWizard(path.to_vec()));
    } else if handle.clicked() {
        acts.push(Act::Select(path.to_vec()));
    }
    if let Some(name) = picked
        && name != current
    {
        acts.push(make_act(name));
    }
}

/// The filtered body of a request dropdown: an auto-focused search field at the
/// top, then the choices narrowed (case-insensitively) by what's typed —
/// mirroring the terminal UI's type-to-filter request picker. Sets `*picked`
/// when a match is clicked.
fn filtered_choices(
    ui: &mut egui::Ui,
    s: &crate::i18n::Strings,
    path: &[usize],
    prefix: &str,
    current: &str,
    choices: &[String],
    picked: &mut Option<String>,
) {
    let filt_id = ui.make_persistent_id(("pt_chip_filter", path, prefix));
    let mut q = ui
        .data(|d| d.get_temp::<String>(filt_id))
        .unwrap_or_default();
    let te = ui.add(
        egui::TextEdit::singleline(&mut q)
            .hint_text(s.gui_report_filter_hint)
            .desired_width(200.0),
    );
    // Focus the filter the frame the dropdown opens (nothing else is focused
    // yet) so the user can just start typing, like the TUI picker.
    if q.is_empty() && ui.memory(|m| m.focused().is_none()) {
        te.request_focus();
    }
    ui.data_mut(|d| d.insert_temp(filt_id, q.clone()));
    ui.separator();
    let needle = q.to_lowercase();
    egui::ScrollArea::vertical()
        .max_height(220.0)
        .show(ui, |ui| {
            for c in choices
                .iter()
                .filter(|c| needle.is_empty() || c.to_lowercase().contains(&needle))
            {
                if ui.selectable_label(c == current, c).clicked() {
                    *picked = Some(c.clone());
                    ui.data_mut(|d| d.remove::<String>(filt_id));
                }
            }
        });
}

/// The insert palette: pick a node kind, then (for request kinds) a name.
fn palette_panel(
    ed: &mut ReportEditor,
    app: &GuiApp,
    ui: &mut egui::Ui,
    titles: &[String],
    acts: &mut Vec<Act>,
) {
    let th = app.theme;
    let s = &app.strings;
    egui::Frame::NONE
        .fill(th.raised())
        .stroke(egui::Stroke::new(1.0, th.accent))
        .inner_margin(8)
        .corner_radius(BLOCK_RADIUS as u8)
        .show(ui, |ui| {
            let pick_request = ed.palette.as_ref().and_then(|p| p.pick_request);
            ui.horizontal(|ui| {
                let title = if pick_request.is_some() {
                    s.node_pick_request_title
                } else {
                    s.gui_report_add_block
                };
                ui.label(RichText::new(title).strong().color(th.text));
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if ui.button(super::icons::CLOSE.to_string()).clicked() {
                        acts.push(Act::ClosePalette);
                    }
                });
            });
            ui.separator();

            match pick_request {
                None => {
                    for kind in BASE_KINDS {
                        if ui.selectable_label(false, kind.label(s)).clicked() {
                            acts.push(Act::PickKind(kind));
                        }
                    }
                }
                Some(report) => {
                    if titles.is_empty() {
                        ui.colored_label(th.dim, s.node_pick_request_none);
                    }
                    if let Some(p) = ed.palette.as_mut() {
                        ui.horizontal(|ui| {
                            ui.add(
                                egui::TextEdit::singleline(&mut p.request_name)
                                    .hint_text(s.node_pick_request_title)
                                    .desired_width(200.0),
                            );
                            if ui.button(s.gui_ok).clicked() && !p.request_name.trim().is_empty() {
                                acts.push(Act::InsertRequest {
                                    report,
                                    name: p.request_name.trim().to_string(),
                                });
                            }
                        });
                    }
                    for name in titles {
                        if ui.selectable_label(false, name).clicked() {
                            acts.push(Act::InsertRequest {
                                report,
                                name: name.clone(),
                            });
                        }
                    }
                }
            }
        });
}

/// The diagnostics panel: parse error line, then validation warnings/errors.
/// A thin draggable handle above the validation panel. Dragging it up/down
/// grows or shrinks the panel (`ed.diag_h`), the GUI's replacement for a fixed
/// panel height: a report with many validation errors can be given as much room
/// as the user wants. Drag *up* (negative Δy) enlarges the panel.
fn diag_splitter(ed: &mut ReportEditor, ui: &mut egui::Ui) {
    ui.add_space(2.0);
    let (rect, resp) =
        ui.allocate_exact_size(egui::vec2(ui.available_width(), 6.0), egui::Sense::drag());
    if resp.dragged() {
        ed.diag_h = (ed.diag_h - resp.drag_delta().y).clamp(48.0, 600.0);
    }
    if resp.hovered() || resp.dragged() {
        ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
    }
    // A short grab bar centred in the strip, brightened while hovered/dragged so
    // the resize affordance reads as interactive.
    let active = resp.hovered() || resp.dragged();
    let visuals = ui.visuals();
    let colour = if active {
        visuals.widgets.active.fg_stroke.color
    } else {
        visuals.widgets.noninteractive.bg_stroke.color
    };
    let w = (rect.width() * 0.25).clamp(40.0, 160.0);
    let x0 = rect.center().x - w / 2.0;
    ui.painter()
        .hline(x0..=x0 + w, rect.center().y, egui::Stroke::new(2.0, colour));
}

/// A thin draggable handle between the palette and the block stack. Dragging it
/// left/right grows or shrinks the palette column (`ed.palette_w`), the GUI's
/// click-and-drag replacement for the TUI's fixed panel widths.
fn palette_splitter(ed: &mut ReportEditor, ui: &mut egui::Ui, body_h: f32) {
    let (rect, resp) = ui.allocate_exact_size(egui::vec2(8.0, body_h), egui::Sense::drag());
    if resp.dragged() {
        ed.palette_w = (ed.palette_w + resp.drag_delta().x).clamp(96.0, 480.0);
    }
    if resp.hovered() || resp.dragged() {
        ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
    }
    // A short grab bar centred in the strip, brightened while hovered/dragged so
    // the resize affordance reads as interactive.
    let active = resp.hovered() || resp.dragged();
    let visuals = ui.visuals();
    let colour = if active {
        visuals.widgets.active.fg_stroke.color
    } else {
        visuals.widgets.noninteractive.bg_stroke.color
    };
    let h = (rect.height() * 0.25).clamp(24.0, 120.0);
    let y0 = rect.center().y - h / 2.0;
    ui.painter()
        .vline(rect.center().x, y0..=y0 + h, egui::Stroke::new(2.0, colour));
}

fn diagnostics_panel(ed: &ReportEditor, app: &GuiApp, ui: &mut egui::Ui) {
    let th = app.theme;
    ui.add_space(4.0);
    ui.label(
        RichText::new(app.strings.report_validation_heading)
            .strong()
            .color(th.text),
    );
    egui::ScrollArea::vertical()
        .id_salt("report_diags")
        .auto_shrink([false, false])
        .show(ui, |ui| {
            if ed.diagnostics.is_empty() && ed.parse_error.is_none() {
                ui.colored_label(th.ok, app.strings.report_no_diagnostics);
                return;
            }
            if let Some(err) = &ed.parse_error {
                ui.colored_label(th.err, format!("{} {err}", super::icons::FAIL));
            }
            for d in &ed.diagnostics {
                let (icon, colour) = match d.severity {
                    Severity::Error => (super::icons::FAIL, th.err),
                    Severity::Warning => (super::icons::WARNING, th.pending),
                };
                ui.colored_label(colour, format!("{icon} {}", d.message));
            }
        });
}

/// Apply the collected block actions to the editor and session.
///
/// Value commits are applied before anything else. An inline chip field commits
/// what has been typed into it when it loses focus — which is the same click
/// that presses a button on the toolbar drawn *above* it, so both land in the
/// same batch, with the toolbar's action first (it was drawn first). Both carry
/// paths describing the tree as it was on screen, but a structural action
/// rewrites those paths out from under the commit: applied in collection order,
/// deleting one block would land the edit on whichever block shuffled up into
/// its slot — renaming a block the user never touched, and losing the edit they
/// did make. Sorting the commits to the front keeps every path meaning what it
/// meant when it was drawn. The partition is stable, so commits keep their own
/// relative order, and so does everything else.
fn apply_block_actions(ed: &mut ReportEditor, app: &mut GuiApp, acts: Vec<Act>) {
    let (commits, rest): (Vec<Act>, Vec<Act>) = acts.into_iter().partition(Act::is_value_commit);
    for act in commits.into_iter().chain(rest) {
        match act {
            Act::Select(path) => {
                ed.selection = path;
            }
            Act::OpenPalette(pos) => {
                ed.palette = Some(PaletteState {
                    pos,
                    pick_request: None,
                    request_name: String::new(),
                });
            }
            Act::ClosePalette => ed.palette = None,
            Act::PickKind(kind) => {
                if kind.needs_request() {
                    if let Some(p) = ed.palette.as_mut() {
                        p.pick_request = Some(matches!(kind, NodeKind::ReportRequest));
                    }
                } else if let Some(node) = kind.template() {
                    if let Some(sel) = insert_at_palette(ed, node) {
                        super::report_wizard::open(ed, app, &sel);
                    }
                }
            }
            Act::InsertRequest { report, name } => {
                if let Some(sel) = insert_at_palette(ed, request_node(&name, report)) {
                    super::report_wizard::open(ed, app, &sel);
                }
            }
            Act::Move { path, up } => {
                let mut new_sel = None;
                ed.edit_flow(|flow| {
                    new_sel = move_node(flow, &path, up);
                });
                if let Some(ns) = new_sel {
                    ed.selection = ns;
                }
            }
            Act::DropNode { pos, node } => {
                ed.edit_flow(|flow| insert_node(flow, &pos, node));
                let mut sel = pos.parent.clone();
                sel.push(pos.index);
                ed.selection = sel.clone();
                // Placing a new block opens its configure wizard straight away
                // so the user can fill it in (pick a request, set VAR=VALUE, …)
                // without a second click.
                super::report_wizard::open(ed, app, &sel);
            }
            Act::AttachMod { path, modifier } => {
                // Dropping WITH opens the WITH-field wizard directly (append on
                // OK) rather than attaching a placeholder field, so a cancelled
                // drop leaves no empty `field: HttpStatus` behind.
                if modifier == Modifier::With {
                    ed.selection = path.clone();
                    super::report_wizard::open_with_field(ed, &path, None);
                    continue;
                }
                // REPORT on a VARIABLE (`Assign`) doesn't transform it (the
                // assignment must stay to define the variable) — it inserts a
                // sibling `REPORT (VAR)` line right after it. Every other
                // modifier transforms its node in place.
                let assign_report = modifier == Modifier::Report
                    && matches!(
                        ed.flow.as_ref().and_then(|f| node_at(f, &path)),
                        Some(FlowNode::Assign { .. })
                    );
                if assign_report {
                    let mut new_sel = None;
                    ed.edit_flow(|flow| {
                        new_sel = report_assignment(flow, &path);
                    });
                    ed.selection = new_sel.unwrap_or(path);
                } else {
                    ed.edit_flow(|flow| {
                        attach_modifier(flow, &path, modifier);
                    });
                    ed.selection = path;
                }
                // Dropping a modifier chip (AS/REPORT/PARALLEL) opens the
                // affected node's wizard so the new clause can be filled in
                // immediately.
                let sel = ed.selection.clone();
                super::report_wizard::open(ed, app, &sel);
            }
            Act::MoveMod {
                from,
                which,
                to,
                copy,
            } => {
                let mut moved = false;
                ed.edit_flow(|flow| {
                    moved = transfer_modifier(flow, &from, which, &to, copy);
                });
                // Select the line the clause landed on, so the result of the
                // drop is what's highlighted. A refused transfer leaves the
                // selection (and the flow) exactly as it was.
                if moved {
                    ed.selection = to;
                }
            }
            Act::DetachMod { path, which } => {
                ed.edit_flow(|flow| {
                    if detach_modifier(flow, &path, which) {
                        remove_node(flow, &path);
                    }
                });
                ed.selection = Vec::new();
            }
            Act::RenameRequest { path, name } => {
                ed.edit_flow(|flow| {
                    set_request_name(flow, &path, &name);
                });
                ed.selection = path;
            }
            Act::SetEnvRole {
                path,
                baseline,
                index,
                name,
            } => {
                ed.edit_flow(|flow| {
                    edit::set_env_role(flow, &path, baseline, index, &name);
                });
                ed.selection = path;
            }
            Act::MoveNode { from, pos } => {
                let mut new_sel = None;
                ed.edit_flow(|flow| {
                    new_sel = edit::move_node_to(flow, &from, &pos);
                });
                if let Some(ns) = new_sel {
                    ed.selection = ns;
                }
            }
            Act::DeletePath(path) => {
                ed.edit_flow(|flow| {
                    remove_node(flow, &path);
                });
                ed.selection = Vec::new();
            }
            Act::OpenWizard(path) => super::report_wizard::open(ed, app, &path),
            Act::SetAlias { path, text } => {
                ed.edit_flow(|flow| {
                    edit::set_report_alias(flow, &path, &text);
                });
                ed.selection = path;
            }
            Act::SetLoopVar { path, text } => {
                ed.edit_flow(|flow| {
                    edit::set_loop_var(flow, &path, &text);
                });
                ed.selection = path;
            }
            Act::SetLoopDir { path, text } => {
                ed.edit_flow(|flow| {
                    edit::set_loop_dir(flow, &path, &text);
                });
                ed.selection = path;
            }
            Act::SetLoopGlob { path, text } => {
                ed.edit_flow(|flow| {
                    edit::set_loop_glob(flow, &path, &text);
                });
                ed.selection = path;
            }
            Act::PickLoopDir { path, file } => {
                pick_loop_dir(ed, app, &path, file);
            }
            Act::SetParallelDegree { path, degree } => {
                ed.edit_flow(|flow| {
                    edit::set_parallel_degree(flow, &path, degree);
                });
                ed.selection = path;
            }
            Act::SetHeader {
                key,
                occurrence,
                value,
            } => {
                ed.edit_flow(|flow| {
                    edit::set_header_nth(flow, key, occurrence, value.as_deref());
                });
            }
            Act::PickHeaderFile { key, occurrence } => {
                pick_header_file(ed, app, key, occurrence);
            }
            Act::AddWith { path } => {
                ed.selection = path.clone();
                super::report_wizard::open_with_field(ed, &path, None);
            }
            Act::EditWith { path, index } => {
                ed.selection = path.clone();
                super::report_wizard::open_with_field(ed, &path, Some(index));
            }
            Act::RemoveWith { path, index } => {
                ed.edit_flow(|flow| {
                    detach_modifier(flow, &path, DetachWhich::With(index));
                });
                ed.selection = path;
            }
            Act::AttachWithStats { path, index } => {
                ed.edit_flow(|flow| {
                    edit::attach_with_stats(flow, &path, index);
                });
                ed.selection = path;
            }
        }
    }
    sync_back(ed, app);
}

/// Insert `node` at the open palette's position, select it, close the palette,
/// and return the new node's path (so the caller can open its wizard). `None`
/// when no palette was open.
fn insert_at_palette(ed: &mut ReportEditor, node: FlowNode) -> Option<Vec<usize>> {
    let p = ed.palette.take()?;
    let pos = p.pos.clone();
    ed.edit_flow(|flow| insert_node(flow, &pos, node));
    // Select the newly inserted node.
    let mut sel = pos.parent.clone();
    sel.push(pos.index);
    ed.selection = sel.clone();
    Some(sel)
}

/// Mirror a Session-origin editor's text back into `session.reports` on every
/// edit so nothing is lost if the view is closed without an explicit Save.
fn sync_back(ed: &ReportEditor, app: &mut GuiApp) {
    if let ReportOrigin::Session(i) = ed.origin
        && let Some(r) = app.session.reports.get_mut(i)
    {
        r.text = ed.report.text.clone();
        r.name = ed.report.name.clone();
    }
}

/// Queue the toolbar's Save action, so a keyboard shortcut or a menu entry
/// saves by exactly the same path the toolbar button does (the editor is taken
/// out of the app while it draws, so saving can only happen from inside its own
/// frame).
pub(super) fn request_save(ed: &mut ReportEditor) {
    ed.pending_toolbar = Some(ToolbarAct::Save);
}

/// Save the open report to an explicit `path` (the "Save report as" path taken
/// by the File menu), adopting that path so later saves go straight there.
pub(super) fn save_report_to(app: &mut GuiApp, path: &std::path::Path) -> Result<(), String> {
    let Some(mut ed) = app.report_editor.take() else {
        return Err(app.strings.gui_nothing_to_save.to_string());
    };
    let res = ed.report.save_local(path);
    if res.is_ok() {
        sync_back(&ed, app);
        if let ReportOrigin::Session(i) = ed.origin
            && let Some(r) = app.session.reports.get_mut(i)
        {
            r.path = Some(path.to_string_lossy().into_owned());
        }
    }
    app.report_editor = Some(ed);
    res
}

/// Save the report: to disk when it has a path, and always back into the session.
fn save_report(ed: &mut ReportEditor, app: &mut GuiApp) {
    if let Some(path) = ed.report.path.clone() {
        if let Err(e) = ed.report.save_local(&path) {
            app.session.status = Some(crate::i18n::Status::Error(e));
            return;
        }
    } else {
        ed.report.dirty = false;
    }
    sync_back(ed, app);
    app.session.save();
    app.session.status = Some(crate::i18n::Status::Saved);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::i18n::{Language, Strings};

    /// Enter at the end of an indented line carries that indentation over, so a
    /// statement typed inside a loop body stays inside it visually.
    #[test]
    fn enter_inherits_the_current_lines_indent() {
        let text = "FOR F IN [\"a\"]\n    REQUEST r";
        let at = text.chars().count();
        let (out, caret) = newline_with_indent(text, at..at);
        assert_eq!(out, "FOR F IN [\"a\"]\n    REQUEST r\n    ");
        assert_eq!(caret, out.chars().count());
    }

    /// A block opener indents its body one further level.
    #[test]
    fn enter_after_an_opener_adds_a_level() {
        let text = "FOR F IN [\"a\"]";
        let at = text.chars().count();
        let (out, caret) = newline_with_indent(text, at..at);
        assert_eq!(out, "FOR F IN [\"a\"]\n    ");
        assert_eq!(caret, out.chars().count());

        let text = "    REPORT REQUEST p WITH";
        let at = text.chars().count();
        let (out, _) = newline_with_indent(text, at..at);
        assert_eq!(out, "    REPORT REQUEST p WITH\n        ");
    }

    /// Splitting a line in the middle stays a plain newline: the text after the
    /// caret moves down as-is, and silently inserting spaces in front of it
    /// would corrupt what the user was splitting.
    #[test]
    fn a_mid_line_split_is_not_indented() {
        let text = "    REQUEST rs";
        let at = text.chars().count() - 1;
        let (out, caret) = newline_with_indent(text, at..at);
        assert_eq!(out, "    REQUEST r\ns");
        assert_eq!(caret, at + 1);
    }

    /// Enter with a selection replaces it, like any typed character.
    #[test]
    fn enter_replaces_the_selection() {
        let text = "FOR F IN [\"a\"]\n    REQUEST rXXX";
        let start = text.chars().count() - 3;
        let (out, caret) = newline_with_indent(text, start..text.chars().count());
        assert_eq!(out, "FOR F IN [\"a\"]\n    REQUEST r\n    ");
        assert_eq!(caret, out.chars().count());
    }

    /// A line that has become `END` snaps back to its opener's indentation.
    #[test]
    fn end_dedents_to_its_opener() {
        let text = "FOR F IN [\"a\"]\n    REQUEST r\n    END";
        let at = text.chars().count();
        let (out, caret) = snap_end_line(text, at).expect("END should snap");
        assert_eq!(out, "FOR F IN [\"a\"]\n    REQUEST r\nEND");
        assert_eq!(caret, out.chars().count());
    }

    /// Snapping is idempotent, and leaves alone anything it can't resolve — a
    /// stray `END` is the user's to fix, not ours to guess at.
    #[test]
    fn end_snapping_leaves_aligned_or_unresolvable_lines_alone() {
        let aligned = "FOR F IN [\"a\"]\n    REQUEST r\nEND";
        assert!(snap_end_line(aligned, aligned.chars().count()).is_none());

        let stray = "REQUEST r\n    END";
        assert!(snap_end_line(stray, stray.chars().count()).is_none());

        let not_an_end = "FOR F IN [\"a\"]\n    ENDPOINT = x";
        assert!(snap_end_line(not_an_end, not_an_end.chars().count()).is_none());
    }

    /// Tab indents one four-space level, replacing any selection.
    #[test]
    fn tab_indents_one_level() {
        let (out, caret) = indent_at("REQUEST r", 0..0);
        assert_eq!(out, "    REQUEST r");
        assert_eq!(caret, 4);

        let (out, caret) = indent_at("REQUEST rXX", 9..11);
        assert_eq!(out, "REQUEST r    ");
        assert_eq!(caret, 13);
    }

    /// A de-indent deletes back to the previous four-column stop within the run
    /// of spaces at the caret, so one press clears a level rather than a space.
    #[test]
    fn dedent_walks_back_to_the_previous_four_stop() {
        assert_eq!(dedent_span("        END", 8), Some(4));
        assert_eq!(dedent_span("        END", 4), Some(4));
        // A partial level is cleared on its own, landing on the stop below.
        assert_eq!(dedent_span("      END", 6), Some(2));
        assert_eq!(dedent_span("     END", 5), Some(1));

        let (out, caret) = delete_before("        END", 8, 4);
        assert_eq!(out, "    END");
        assert_eq!(caret, 4);
    }

    /// Away from indentation the key keeps its ordinary meaning, so the widget
    /// keeps its own (selection-aware) handling.
    #[test]
    fn dedent_declines_anywhere_but_a_run_of_spaces() {
        assert_eq!(dedent_span("END", 3), None); // no space before the caret
        assert_eq!(dedent_span("    END", 0), None); // start of the line
        assert_eq!(dedent_span("\tEND", 1), None); // a tab is not our indent
    }

    /// Padding after content de-indents too — that's what Tab leaves behind
    /// when it lands mid-line.
    #[test]
    fn dedent_also_clears_trailing_padding() {
        assert_eq!(dedent_span("END    ", 7), Some(4));
        let (out, caret) = delete_before("END    ", 7, 4);
        assert_eq!(out, "END");
        assert_eq!(caret, 3);
    }

    /// Both helpers count in chars, so multi-byte text can't split a character
    /// or land the caret mid-codepoint.
    #[test]
    fn indent_helpers_are_char_indexed_not_byte_indexed() {
        let text = "    REQUEST \u{e9}\u{e9}\u{e9}";
        let at = text.chars().count();
        let (out, caret) = newline_with_indent(text, at..at);
        assert_eq!(out, "    REQUEST \u{e9}\u{e9}\u{e9}\n    ");
        assert_eq!(caret, out.chars().count());
        assert_eq!(row_col_at(text, at), (0, 15));
        assert_eq!(row_start("\u{e9}\u{e9}\n x", 1), 3);
    }

    /// The relative luminance of a colour, per WCAG 2.1.
    fn luminance(c: Color32) -> f64 {
        let ch = |v: u8| {
            let v = v as f64 / 255.0;
            if v <= 0.03928 {
                v / 12.92
            } else {
                ((v + 0.055) / 1.055).powf(2.4)
            }
        };
        0.2126 * ch(c.r()) + 0.7152 * ch(c.g()) + 0.0722 * ch(c.b())
    }

    /// The WCAG contrast ratio between two colours (1.0 = identical, 21.0 = the
    /// most any pair can manage).
    fn contrast(a: Color32, b: Color32) -> f64 {
        let (hi, lo) = {
            let (x, y) = (luminance(a), luminance(b));
            if x > y { (x, y) } else { (y, x) }
        };
        (hi + 0.05) / (lo + 0.05)
    }

    /// A chip's label must stay comfortably readable on its own tint, in every
    /// theme.
    ///
    /// This guards the change that quietened the blocks: the label colour is now
    /// blended from the theme text colour toward the category hue rather than
    /// being the hue itself, which is what makes the tinting safe to keep. Full
    /// chroma text on a tint of the same hue used to fall as low as 2.3:1 for
    /// `accent` chips on the English preset — text a user with ordinary eyesight
    /// has to lean in to read. Anyone tempted to turn the colour back up will
    /// trip this rather than find out from a customer.
    ///
    /// 4.5:1 is WCAG AA for body text. Checked against every built-in preset,
    /// since a preset is a set of arbitrary RGB triples and a new one could
    /// easily be picked that reads well in isolation but not behind a chip.
    #[test]
    fn every_chip_categorys_label_is_readable_on_its_own_tint_in_every_theme() {
        for spec in crate::theme::builtin_presets() {
            let th = GuiTheme::from_spec(&spec);
            for kind in [
                NodeKind::Request,
                NodeKind::ReportRequest,
                NodeKind::ReportVar,
                NodeKind::ReportComputed,
                NodeKind::Assign,
                NodeKind::ForFiles,
                NodeKind::ForFolders,
                NodeKind::ForEnvs,
                NodeKind::List,
            ] {
                let color = kind_color(kind, &th);
                let tint = chip_tint(&th, color);
                let ratio = contrast(tint.text, tint.fill);
                assert!(
                    ratio >= 4.5,
                    "{} chip {kind:?}: label contrast {ratio:.2} is below WCAG AA",
                    spec.name
                );
            }
            // The error colour never comes from `kind_color` but is used for
            // unset required settings — the one thing standing between the
            // report and a run, so of all of them it must be legible.
            let tint = chip_tint(&th, th.err);
            assert!(
                contrast(tint.text, tint.fill) >= 4.5,
                "{} error chip",
                spec.name
            );
        }
    }

    /// Categories are still told apart by colour, so quietening the chips must
    /// not have quietened them into each other.
    ///
    /// Checked on the *rule* rather than the fill, because the rule is now where
    /// the category lives: the surface is deliberately near-neutral, so fills
    /// that were once far apart are now all within a few points of the panel
    /// colour and would make this assertion meaningless.
    #[test]
    fn the_chip_categories_remain_visually_distinct_from_one_another() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let kinds = [
            NodeKind::Request,
            NodeKind::ReportVar,
            NodeKind::Assign,
            NodeKind::List,
        ];
        let rules: Vec<Color32> = kinds
            .into_iter()
            .map(|k| {
                chip_tint(&th, kind_color(k, &th))
                    .rule
                    .expect("a category chip shows a rule")
            })
            .collect();
        let labels: Vec<Color32> = kinds
            .into_iter()
            .map(|k| chip_tint(&th, kind_color(k, &th)).text)
            .collect();
        for channel in [&rules, &labels] {
            for (i, a) in channel.iter().enumerate() {
                for b in &channel[i + 1..] {
                    let dist = (a.r() as i32 - b.r() as i32).abs()
                        + (a.g() as i32 - b.g() as i32).abs()
                        + (a.b() as i32 - b.b() as i32).abs();
                    assert!(
                        dist > 40,
                        "two categories came out too close to tell apart: {a:?} vs {b:?}"
                    );
                }
            }
        }
    }

    /// The category rule is the full-strength hue, not a tint of it.
    ///
    /// The whole trade in moving the category from the fill to the rule is that
    /// a *small* area can afford *full* chroma. Tinting the bar as well would
    /// give up the identifiability the neutral surface was bought with, and
    /// would do it invisibly — the editor would just slowly become grey.
    #[test]
    fn the_category_rule_carries_the_hue_at_full_strength() {
        let th = GuiTheme::from_spec(&crate::theme::default_preset());
        for kind in [NodeKind::Request, NodeKind::Assign, NodeKind::List] {
            let color = kind_color(kind, &th);
            let tint = chip_tint(&th, color);
            assert_eq!(tint.rule, Some(color), "{kind:?} rule is the category hue");
            // ...while the surface it sits on stays close to the panel.
            let from_panel = (tint.fill.r() as i32 - th.panel.r() as i32).abs()
                + (tint.fill.g() as i32 - th.panel.g() as i32).abs()
                + (tint.fill.b() as i32 - th.panel.b() as i32).abs();
            assert!(
                from_panel < 60,
                "{kind:?} chip fill drifted away from the panel colour ({from_panel})"
            );
        }
    }

    /// A selected chip and the hanger of a tethered pair show no rule.
    ///
    /// The first because its fill already carries the selection colour, and a
    /// category bar inside it competes with that; the second because the
    /// hanger's leading edge is the *seam* of a two-part pill, where a coloured
    /// bar reads as a divider rather than as a category.
    #[test]
    fn chips_that_should_not_show_a_rule_do_not() {
        let th = GuiTheme::from_spec(&crate::theme::default_preset());

        let mut chip = Chip::base("GET".to_string(), th.accent);
        assert!(
            chip_colors(&th, &chip, false).rule.is_some(),
            "an ordinary base chip shows its category"
        );
        assert!(
            chip_colors(&th, &chip, true).rule.is_none(),
            "a selected chip drops the rule"
        );

        chip.join_prev = true;
        assert!(
            chip_colors(&th, &chip, false).rule.is_none(),
            "the hanger of a tethered pair drops the rule"
        );
    }

    /// The text of one laid-out section, for the label-face test below.
    fn section_text(job: &egui::text::LayoutJob, i: usize) -> &str {
        let r = &job.sections[i].byte_range;
        &job.text[usize::from(r.start)..usize::from(r.end)]
    }

    /// A chip label is set as two runs — the editor's keyword and the user's
    /// identifier — in two different faces.
    ///
    /// The split is what stops `BASELINE(staging)` reading as one word, so it is
    /// worth pinning: a future label built with a different separator would
    /// otherwise silently fall back to one undifferentiated run.
    #[test]
    fn a_chip_label_sets_the_keyword_and_the_identifier_in_different_faces() {
        let ctx = egui::Context::default();
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            {
                let col = Color32::WHITE;

                let job = chip_label_job(ui, "BASELINE(staging)", col);
                assert_eq!(job.sections.len(), 2, "keyword and identifier");
                assert_eq!(section_text(&job, 0), "BASELINE");
                assert_eq!(section_text(&job, 1), "(staging)");
                assert_eq!(
                    job.sections[1].format.font_id.family,
                    egui::FontFamily::Monospace,
                    "the user's own name is set in the monospace face"
                );
                assert_ne!(
                    job.sections[0].format.font_id.family,
                    egui::FontFamily::Monospace,
                    "the keyword stays in the UI face"
                );

                // `REQUEST orders` splits on the space just the same.
                let job = chip_label_job(ui, "REQUEST orders", col);
                assert_eq!(section_text(&job, 0), "REQUEST");
                assert_eq!(
                    job.sections[1].format.font_id.family,
                    egui::FontFamily::Monospace
                );

                // A bare keyword is a single run and stays in the UI face.
                let job = chip_label_job(ui, "PARALLEL", col);
                assert_eq!(job.sections.len(), 1);
                assert_ne!(
                    job.sections[0].format.font_id.family,
                    egui::FontFamily::Monospace
                );
            }
        });
    }

    /// The two synthetic sentinels are drawn as a matched pair, and neither is
    /// dressed as a keyword.
    ///
    /// `Begin` and the flow's closing `End` are editor punctuation: no node
    /// backs them, and nothing in the report file corresponds to them. The
    /// uppercase `END` that closes a `FOR` or a `WITH` *is* in the file. Users
    /// asked whether `BEGIN` was a word they had to write — it isn't — so the
    /// two kinds must not look alike.
    #[test]
    fn the_synthetic_sentinels_are_captions_not_keywords() {
        let th = GuiTheme::from_spec(&crate::theme::default_preset());
        let s = Strings::for_language(&Language::English);

        // Sentence case and translated, so they can never be mistaken for the
        // literal keyword.
        assert_ne!(s.report_node_begin, "BEGIN");
        assert_ne!(s.report_node_end, "END");
        for lang in [Language::English, Language::French, Language::Danish] {
            let s = Strings::for_language(&lang);
            assert_ne!(
                s.report_node_end, "END",
                "the synthetic end must not collide with the real keyword"
            );
        }

        // ...and drawn in the dim colour rather than the keyword accent.
        assert_ne!(
            th.dim, th.accent,
            "the test below is only meaningful if the two colours differ"
        );
    }

    /// An inline field is as wide as what is in it, within bounds.
    ///
    /// Fixed widths were the reason aliases and folder paths appeared cut off
    /// with nothing to say there was more text: the box simply ended. The clamp
    /// matters as much as the growth — an unbounded field would let one deep
    /// path push the rest of a loop head off the side of the pane.
    #[test]
    fn an_inline_field_grows_to_fit_its_value_but_not_without_limit() {
        let ctx = egui::Context::default();
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            let min = LOOP_PATH_FIELD_WIDTH;

            let empty = fitted_field_width(ui, "", "", min, FIELD_MAX_WIDTH);
            assert_eq!(empty, min, "an empty field rests at its minimum");

            let short = fitted_field_width(ui, "envs", "", min, FIELD_MAX_WIDTH);
            assert_eq!(short, min, "a value that already fits doesn't shrink it");

            let long = fitted_field_width(
                ui,
                "reports/2026/quarterly/regional-breakdowns",
                "",
                min,
                FIELD_MAX_WIDTH,
            );
            assert!(
                long > min,
                "a value wider than the box widens it ({long} vs {min})"
            );

            let absurd = fitted_field_width(ui, &"x".repeat(500), "", min, FIELD_MAX_WIDTH);
            assert_eq!(
                absurd, FIELD_MAX_WIDTH,
                "growth stops at the cap rather than running off the pane"
            );

            // An empty box still has to show its own placeholder.
            let hinted = fitted_field_width(ui, "", "*.json", 10.0, FIELD_MAX_WIDTH);
            assert!(hinted > 10.0, "an empty field makes room for its hint");
        });
    }

    /// The boxes' placeholders are short enough to actually fit them, and the
    /// long explanations are kept separate.
    ///
    /// These were once the same string, so a field a few characters wide was
    /// given a full sentence as its placeholder and rendered it as "Only files
    /// ..." — which is what prompted this. Checked in every language, since a
    /// translation is exactly where a "short" label quietly stops being short.
    #[test]
    fn a_fields_placeholder_is_short_and_its_explanation_is_not_the_same_string() {
        for lang in [Language::English, Language::French, Language::Danish] {
            let s = Strings::for_language(&lang);
            for hint in [
                s.gui_report_loop_var_hint,
                s.gui_report_loop_dir_hint,
                s.gui_report_loop_glob_hint,
                s.gui_report_alias_hint,
            ] {
                assert!(
                    hint.chars().count() <= 12,
                    "{lang:?}: placeholder {hint:?} is too long to fit its box"
                );
            }
            assert_ne!(
                s.gui_report_loop_glob_hint, s.chip_help_loop_glob,
                "{lang:?}: the placeholder must not be the explanation"
            );
            // The explanation, by contrast, has room to actually explain.
            assert!(
                s.chip_help_loop_glob.chars().count() > 40,
                "{lang:?}: the MATCH explanation should say what a pattern is"
            );
            assert!(
                s.chip_help_loop_pick_folder != s.chip_help_loop_dir,
                "{lang:?}: the picker button explains itself, not the box"
            );
        }
    }

    /// The Source view's colouring is the terminal UI's, span for span.
    ///
    /// Rather than restate the highlighting rules (which would let the two
    /// front-ends drift the moment one side gained a keyword), this walks the
    /// laid-out job and checks every byte carries the colour the shared
    /// highlighter assigned it for the same line.
    #[test]
    fn the_source_view_colours_match_the_terminal_uis_exactly() {
        let spec = crate::theme::preset_for_language(&Language::English);
        let th = GuiTheme::from_spec(&spec);
        let theme = spec.to_theme();
        let ctx = HlCtx::default();
        let text = "# collection: api.hurl\nFOR f IN FILES \"*.json\"\n  REQUEST Health\nEND\n";

        let job = highlight_job(
            text,
            &ctx,
            &spec,
            &th,
            egui::FontId::monospace(12.0),
            f32::INFINITY,
        );

        // Rebuild the expected colour for every byte from the ratatui spans.
        let mut expected: Vec<egui::Color32> = Vec::new();
        for (i, line) in text.split('\n').enumerate() {
            if i > 0 {
                expected.push(th.text);
            }
            for span in report_highlight::highlight_row(i, line, &ctx, &theme) {
                let c = span
                    .style
                    .fg
                    .map_or(th.text, |c| super::super::theme::from_ratatui(c, th.text));
                expected.extend(std::iter::repeat_n(c, span.content.len()));
            }
        }
        assert_eq!(
            expected.len(),
            job.text.len(),
            "every byte of the source is covered exactly once"
        );

        for section in &job.sections {
            let (start, end) = byte_span(section);
            for (b, want) in expected.iter().enumerate().take(end).skip(start) {
                assert_eq!(
                    section.format.color, *want,
                    "byte {b} of {text:?} is coloured like the terminal UI"
                );
            }
        }

        // Sanity: the keywords really are picked out, so a highlighter that
        // silently returned one plain span couldn't pass the check above.
        let distinct: std::collections::HashSet<_> =
            job.sections.iter().map(|s| s.format.color).collect();
        assert!(
            distinct.len() > 2,
            "the source is multi-coloured, not flat: {distinct:?}"
        );
    }

    /// A script the parser rejects underlines exactly the offending line, which
    /// is what makes a typo findable without reading the validation panel.
    #[test]
    fn the_line_the_parser_rejected_is_underlined() {
        let spec = crate::theme::preset_for_language(&Language::English);
        let th = GuiTheme::from_spec(&spec);
        let text = "REQUEST Health\nOOPS not papertrail\nREQUEST Other\n";
        let ctx = HlCtx {
            error_line: Some(2),
            ..Default::default()
        };

        let job = highlight_job(
            text,
            &ctx,
            &spec,
            &th,
            egui::FontId::monospace(12.0),
            f32::INFINITY,
        );

        let bad_start = text.find("OOPS").unwrap();
        let bad_end = bad_start + "OOPS not papertrail".len();
        for section in &job.sections {
            let underlined = section.format.underline != egui::Stroke::NONE;
            let (start, end) = byte_span(section);
            let overlaps = start < bad_end && bad_start < end;
            assert_eq!(
                underlined, overlaps,
                "only the rejected line is underlined (bytes {start}..{end})"
            );
        }
    }

    /// A layout section's byte range as plain `usize`s (egui wraps them in a
    /// newtype).
    fn byte_span(section: &egui::text::LayoutSection) -> (usize, usize) {
        (
            usize::from(section.byte_range.start),
            usize::from(section.byte_range.end),
        )
    }

    /// Apply the styling `GuiApp::new` applies, so a measurement taken here is
    /// the one the app renders at.
    ///
    /// The text scaling matters as much as the padding: chip heights agreed at
    /// egui's default sizes and drifted a fraction of a pixel apart once the
    /// text grew, which is precisely the bug this harness missed by measuring an
    /// unscaled context.
    fn style_like_the_app(ctx: &egui::Context) {
        ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
        ctx.all_styles_mut(|s| {
            for (_, font) in s.text_styles.iter_mut() {
                font.size *= 1.08;
            }
        });
    }

    /// Render a single chip in isolation and return the height of the frame it
    /// draws. Runs a few frames so egui's sizing settles.
    fn chip_height(build: impl Fn(&mut egui::Ui, &GuiTheme, &Strings, &mut Vec<Act>)) -> f32 {
        let ctx = egui::Context::default();
        style_like_the_app(&ctx);
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::for_language(&Language::English);
        let mut h = 0.0;
        for _ in 0..3 {
            let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                ui.horizontal(|ui| {
                    let mut acts = Vec::new();
                    let r = ui.scope(|ui| build(ui, &th, &s, &mut acts));
                    h = r.response.rect.height();
                });
            });
        }
        h
    }

    /// Lay two chips out the way `block_row` lays out a line — closing the gap
    /// in front of a tethered one — and return the rect each rendered into.
    fn pair_rects(chips: &[Chip]) -> Vec<egui::Rect> {
        let ctx = egui::Context::default();
        ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::for_language(&Language::English);
        let mut rects = Vec::new();
        // A few frames, so egui's sizing settles before the rects are read.
        for _ in 0..3 {
            rects.clear();
            let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                ui.horizontal_top(|ui| {
                    let gap = ui.spacing().item_spacing.x;
                    let mut acts = Vec::new();
                    for chip in chips {
                        if chip.join_next {
                            ui.spacing_mut().item_spacing.x = TETHER_GAP;
                        }
                        rects.push(render_chip(
                            ui,
                            &th,
                            &s,
                            chip,
                            false,
                            &[0],
                            &[],
                            &[],
                            &mut acts,
                        ));
                        ui.spacing_mut().item_spacing.x = gap;
                    }
                });
            });
        }
        rects
    }

    /// The pill only reads as one control if the two halves actually meet: a
    /// gap between them would leave the squared-off corners looking like a
    /// rendering fault rather than a divider.
    #[test]
    fn the_halves_of_a_tethered_pill_are_rendered_touching() {
        let pair = |tether: bool| {
            let show = Chip::modifier(
                "SHOW(Time)".into(),
                Color32::GREEN,
                DetachWhich::BaselineShow,
            );
            let mut chips = vec![
                Chip::modifier(
                    "BASELINE(prod)".into(),
                    Color32::RED,
                    DetachWhich::Statistics,
                ),
                if tether { show.tether() } else { show },
            ];
            link_tethers(&mut chips);
            let r = pair_rects(&chips);
            r[1].left() - r[0].right()
        };

        assert_eq!(
            pair(true),
            0.0,
            "the tethered half sits flush against the chip it qualifies, so their \
             borders meet as the pill's divider"
        );
        assert!(
            pair(false) > 0.0,
            "while an untethered neighbour keeps the normal gap — otherwise every \
             chip on the line would look joined"
        );
    }

    #[test]
    fn all_chip_kinds_render_at_the_same_height() {
        // A plain label chip.
        let label = chip_height(|ui, th, s, acts| {
            let chip = Chip::base("REPORT".into(), th.subst);
            render_chip(ui, th, s, &chip, false, &[0], &[], &[], acts);
        });
        // A chip hosting a combo box (the request picker).
        let combo = chip_height(|ui, th, s, acts| {
            let chip = Chip::request("oauth2", th.subst);
            let titles = vec!["oauth2".to_string()];
            render_chip(ui, th, s, &chip, false, &[0], &titles, &[], acts);
        });
        // A chip hosting an inline text field (the AS alias).
        let alias = chip_height(|ui, th, s, acts| {
            let chip = Chip::alias("Env", th.subst, Some(DetachWhich::As));
            render_chip(ui, th, s, &chip, false, &[0], &[], &[], acts);
        });

        assert!(label > 0.0 && combo > 0.0 && alias > 0.0);
        // Exactly equal, not merely close: a chip that is a fraction of a pixel
        // short still rounds to a visibly uneven bottom edge beside its
        // neighbour, which is how the combo chips came to sit a pixel high.
        assert_eq!(
            label, combo,
            "a combo chip must be exactly as tall as a label chip"
        );
        // The PARALLEL chip, which hosts a small numeric field.
        let parallel = chip_height(|ui, th, s, acts| {
            let chip = Chip::parallel(Some(4), th.err);
            render_chip(ui, th, s, &chip, false, &[0], &[], &[], acts);
        });

        assert!(parallel > 0.0);
        assert_eq!(
            label, alias,
            "an inline text field must be exactly as tall as a label chip"
        );
        assert_eq!(
            label, parallel,
            "the PARALLEL field must be exactly as tall as a label chip"
        );

        // The flow's closing `END`, which brackets the whole report against the
        // `BEGIN` at the top. It sits in the block column like any other row, so
        // it has to line up with them.
        let flow_end = chip_height(|ui, th, s, _acts| flow_end_row(ui, th, s));
        assert_eq!(
            label, flow_end,
            "the closing END must be exactly as tall as a label chip"
        );
    }

    /// `BEGIN` and the flow's `END` are drawn from the same static-chip helper,
    /// carry their own (distinct) hover help, and read as a matching pair.
    #[test]
    fn the_flow_is_bracketed_by_begin_and_a_matching_end() {
        let s = Strings::for_language(&Language::English);
        assert_ne!(
            s.chip_help_flow_end, s.chip_help_end,
            "the flow's END explains itself, not the loop END"
        );
        assert!(
            s.chip_help_flow_end.contains("END"),
            "the help names the block it describes"
        );

        // Both chips paint (a static chip with no text would silently vanish).
        let begin = chip_height(|ui, th, s, _acts| {
            static_chip(ui, th, s.report_node_begin, th.accent, s.chip_help_begin)
        });
        let end = chip_height(|ui, th, s, _acts| flow_end_row(ui, th, s));
        assert!(begin > 0.0 && end > 0.0);
        assert!(
            (begin - end).abs() < 0.5,
            "BEGIN {begin} and END {end} are the same size"
        );
    }

    #[test]
    fn the_settings_strip_covers_every_header_directive_the_language_has() {
        // The parser exposes exactly these directives; if one is added there
        // and not here, the GUI would quietly be unable to set it.
        let flow = crate::report::parse_flow(
            "# collection: c.hurl\n# output: o.csv\n# environment: dev\n# root: /r\n\
             # baseline: b.baseline\n# columns: a,b\n# labels: Pass = ok\nREQUEST login\n",
        )
        .expect("fixture parses");
        let specs = header_specs();
        for spec in &specs {
            assert!(
                flow.header.get(spec.key).is_some(),
                "{} is a real directive",
                spec.key
            );
        }
        assert_eq!(
            specs
                .iter()
                .filter(|sp| sp.always_shown)
                .map(|sp| sp.key)
                .collect::<Vec<_>>(),
            ["collection", "output"],
            "only collection and output are always shown; the rest are opt-in"
        );
        // Being shown and being mandatory are different things: an absent
        // `output:` still runs (the language defaults it to CSV), so only
        // `collection:` earns the error-coloured unset prompt.
        assert_eq!(
            specs
                .iter()
                .filter(|sp| sp.required)
                .map(|sp| sp.key)
                .collect::<Vec<_>>(),
            ["collection"],
            "only a missing collection actually stops the report running"
        );

        // Each directive explains itself in its own words.
        let s = Strings::for_language(&Language::English);
        let helps: Vec<&str> = specs
            .iter()
            .map(|sp| crate::report::edit::header_help(sp.key, &s))
            .collect();
        for (i, h) in helps.iter().enumerate() {
            assert!(!h.is_empty(), "{} has help", specs[i].key);
            assert!(
                helps.iter().filter(|o| o == &h).count() == 1,
                "{} has help of its own",
                specs[i].key
            );
        }
    }

    /// `set_header` drops an empty value, so an empty placeholder made picking a
    /// setting from the add menu silently do nothing — which is how `columns:`
    /// became unaddable.
    #[test]
    fn every_addable_setting_starts_at_a_value_that_survives_being_set() {
        assert!(
            !crate::report::edit::HEADER_PLACEHOLDER.is_empty(),
            "an added setting would be dropped again the moment it was added"
        );
        // And there is something to add in the first place.
        assert!(header_specs().iter().any(|sp| !sp.always_shown));
    }

    /// `# output:` names a format from a closed list — the runner derives the
    /// filename and rejects anything else — so it must be picked, not typed at
    /// with a file browser beside it.
    #[test]
    fn the_output_setting_offers_only_the_formats_the_runner_can_write() {
        let spec = header_specs()
            .into_iter()
            .find(|sp| sp.key == "output")
            .expect("output is a setting");
        assert!(
            matches!(spec.kind, HeaderKind::Format),
            "output is chosen from a list, not typed or browsed for"
        );

        // Every offered format really is one the runner can write, and every
        // format the runner can write is offered.
        for ext in crate::report::writer::OUTPUT_EXTENSIONS {
            assert!(
                crate::report::writer::writer_for_extension(ext).is_some(),
                "{ext} has a writer"
            );
            let flow = crate::report::parse_flow(&format!(
                "# collection: c.hurl\n# output: {ext}\nREQUEST a\n"
            ))
            .expect("parses");
            assert!(
                crate::report::validate::validate(
                    &flow,
                    &crate::report::validate::Context::default(),
                )
                .iter()
                .all(|d| !d.message.contains("unsupported output")),
                "{ext} is accepted by the validator"
            );
        }

        // No path-valued setting claims `output`, so the browse button is gone.
        let paths: Vec<&str> = header_specs()
            .iter()
            .filter(|sp| sp.kind.is_path())
            .map(|sp| sp.key)
            .collect();
        assert_eq!(paths, ["root", "baseline"]);
    }

    /// A report that asks for values names them in the toolbar, in the same
    /// words as the box that changes them, with anything unanswered called out
    /// — the box is asked for once per session, so otherwise the answers are
    /// invisible while the report is being read.
    #[test]
    fn the_run_settings_chip_shows_the_values_it_will_run_with() {
        const TRAIL: &str = "\
# name: Face
# collection: c.hurl
PARAM TEXT TICKET LABEL \"Ticket number\"
PARAM CHOICE(\"au\", \"eu\") REGION = \"au\"
REPORT REQUEST x
";
        let mut app = crate::gui::app::GuiApp::for_test(crate::session::Session::default());
        app.open_report_editor(
            ReportOrigin::Workspace,
            crate::report::Report::from_text("Face", TRAIL),
        );
        let ed = app.report_editor.take().unwrap();
        let s = Strings::for_language(&Language::English);
        let th = app.theme;

        let ctx = egui::Context::default();
        let out = ctx.run_ui(egui::RawInput::default(), |ui| {
            param_chip(ui, &ed, &app, &th);
        });
        let painted: String = out
            .shapes
            .iter()
            .filter_map(|c| match &c.shape {
                egui::Shape::Text(t) => Some(t.galley.text().to_string()),
                _ => None,
            })
            .collect();
        assert!(
            painted.contains(s.gui_report_run_settings),
            "the chip is labelled with the words of the box it opens: {painted:?}"
        );
        assert!(
            painted.contains("REGION=au"),
            "an answered value is shown: {painted:?}"
        );
        assert!(
            painted.contains(&format!("TICKET={}", s.param_value_unset)),
            "and an unanswered one is called out: {painted:?}"
        );
    }

    /// A result still on screen after its answers have changed is the one case
    /// where the chip is not describing what is being looked at, so it says so
    /// — and a report that has never been run has not "changed".
    #[test]
    fn the_chip_says_when_the_answers_moved_on_since_the_result() {
        const TRAIL: &str = "\
# name: Face
# collection: c.hurl
PARAM CHOICE(\"au\", \"eu\") REGION = \"au\"
REPORT REQUEST x
";
        let mut app = crate::gui::app::GuiApp::for_test(crate::session::Session::default());
        app.open_report_editor(
            ReportOrigin::Workspace,
            crate::report::Report::from_text("Face", TRAIL),
        );
        let ed = app.report_editor.as_mut().unwrap();
        let s = Strings::for_language(&Language::English);

        assert!(
            !ed.params_changed_since_result(&s),
            "nothing has been run, so nothing has moved on"
        );

        ed.result_params = ed
            .param_rows(&s)
            .iter()
            .map(|r| (r.name.clone(), r.value.clone()))
            .collect();
        ed.result = Some(crate::report::model::ReportResult::default());
        assert!(
            !ed.params_changed_since_result(&s),
            "the table on screen was made with exactly these answers"
        );

        ed.param_values
            .insert("REGION".to_string(), "eu".to_string());
        assert!(
            ed.params_changed_since_result(&s),
            "changing an answer leaves the table on screen out of date"
        );
    }

    /// The button that adds a report setting says what it adds. A bare `+`
    /// above the flow gives no hint whether it adds a *block* — which is what
    /// everything else in this view does — or a report-wide setting.
    #[test]
    fn the_add_setting_button_says_what_it_adds() {
        let ctx = egui::Context::default();
        let s = Strings::for_language(&Language::English);
        let specs = header_specs();
        let missing: Vec<&HeaderSpec> = specs.iter().filter(|sp| !sp.always_shown).collect();

        let out = ctx.run_ui(egui::RawInput::default(), |ui| {
            let mut acts = Vec::new();
            header_add_menu(ui, &s, &missing, 1, 0, &mut acts);
        });
        let painted: String = out
            .shapes
            .iter()
            .filter_map(|c| match &c.shape {
                egui::Shape::Text(t) => Some(t.galley.text().to_string()),
                _ => None,
            })
            .collect();
        assert!(
            painted.contains(s.report_add_setting),
            "the button is labelled, not a bare glyph (painted: {painted:?})"
        );

        // The label names the thing being added, in every language, so it can't
        // drift back to something as vague as "Add".
        for lang in [Language::English, Language::French, Language::Danish] {
            let s = Strings::for_language(&lang);
            assert!(
                s.report_add_setting.split_whitespace().count() >= 3,
                "{lang:?} label {:?} names what it adds",
                s.report_add_setting
            );
        }
    }

    /// The settings sit in a column above `BEGIN`, each starting at the same
    /// left edge as the flow — laid out in a row they were ragged against each
    /// other, and the leading icon pushed the first one out of line with the
    /// blocks below.
    #[test]
    fn the_settings_are_stacked_and_flush_with_the_flow() {
        let ctx = egui::Context::default();
        ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = Strings::for_language(&Language::English);
        let specs = header_specs();
        let choices = vec!["dev".to_string()];

        let mut rows: Vec<egui::Rect> = Vec::new();
        let mut frame_rect = egui::Rect::NOTHING;
        let mut begin_rect = egui::Rect::NOTHING;
        for _ in 0..3 {
            rows.clear();
            let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                ui.vertical(|ui| {
                    frame_rect = settings_frame(&th)
                        .show(ui, |ui| {
                            for spec in &specs {
                                let r = ui.horizontal(|ui| {
                                    let mut acts = Vec::new();
                                    header_chip(
                                        ui,
                                        &th,
                                        &s,
                                        spec,
                                        0,
                                        "dev",
                                        Some(&choices),
                                        &collection_choices_fixture,
                                        &mut acts,
                                    );
                                });
                                rows.push(r.response.rect);
                            }
                        })
                        .response
                        .rect;
                    // The flow's first block, for comparison.
                    begin_rect = ui
                        .horizontal_top(|ui| {
                            static_chip(ui, &th, s.report_node_begin, th.accent, s.chip_help_begin)
                        })
                        .response
                        .rect;
                });
            });
        }

        // Every setting starts at the same left edge as every other.
        let left = rows[0].left();
        for (i, r) in rows.iter().enumerate() {
            assert!(
                (r.left() - left).abs() < 0.5,
                "row {i} starts at {} but the first starts at {left}",
                r.left()
            );
        }
        // Stacked, not side by side: each row sits below the one before it.
        for pair in rows.windows(2) {
            assert!(
                pair[1].top() >= pair[0].bottom() - 0.5,
                "rows overlap: {:?} then {:?}",
                pair[0],
                pair[1]
            );
        }
        // The panel around them lines up with the flow below, so the settings
        // and the blocks still read as one column.
        assert!(
            (frame_rect.left() - begin_rect.left()).abs() < 0.5,
            "the settings panel starts at {} but BEGIN starts at {}",
            frame_rect.left(),
            begin_rect.left()
        );
        assert!(
            frame_rect.bottom() <= begin_rect.top() + 0.5,
            "the settings panel overlaps the flow"
        );
    }

    /// The dropdown shows collections by name, but what it *stores* has to
    /// stay a path — `report_cli` opens the directive's value straight off
    /// disk, so a bare name would leave the report unrunnable headless.
    #[test]
    fn the_collection_dropdown_shows_names_but_stores_relative_paths() {
        let root = std::env::temp_dir().join(format!("paperboy_cc_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("apis")).expect("scratch workspace");
        std::fs::write(
            root.join("apis/billing.hurl"),
            "GET https://x
",
        )
        .expect("collection");
        std::fs::write(
            root.join("smoke.hurl"),
            "GET https://x
",
        )
        .expect("collection");
        // Neither of these is a collection, so neither may be offered as one.
        std::fs::write(
            root.join("nightly.trail"),
            "# collection: smoke.hurl
",
        )
        .expect("report");
        std::fs::write(
            root.join("dev.vars"),
            "K=v
",
        )
        .expect("env");

        let report = root.join("nightly.trail");
        let choices = collection_choices(Some(&root), Some(&report), &[], "unsaved");

        let labels: Vec<&str> = choices.iter().map(|c| c.label.as_str()).collect();
        assert_eq!(
            labels,
            ["billing", "smoke"],
            "collections are listed by name, and only collections are listed"
        );
        let values: Vec<&str> = choices.iter().map(|c| c.value.as_str()).collect();
        assert_eq!(
            values,
            [
                std::path::Path::new("apis/billing.hurl")
                    .to_string_lossy()
                    .as_ref(),
                "smoke.hurl"
            ],
            "the stored value stays a path, relative to the report so the pair stays portable"
        );
        assert!(
            choices.iter().all(|c| c.in_workspace),
            "everything found by scanning the workspace is in the workspace"
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    /// A workspace has to survive being handed to someone else, so a report
    /// bound to a collection in a sibling folder must say `../apis/…` rather
    /// than an absolute path that only exists on the machine it was made on.
    #[test]
    fn a_collection_in_a_sibling_folder_is_referenced_relatively_so_it_stays_portable() {
        let root = std::path::Path::new("/w");
        let report = std::path::Path::new("/w/reports/nightly.trail");
        let target = std::path::Path::new("/w/apis/billing.hurl");

        assert_eq!(
            portable_ref(target, Some(report), Some(root)),
            "../apis/billing.hurl",
            "it walks up out of reports/ and back down into apis/"
        );
        // Below the report, no walking up is needed.
        assert_eq!(
            portable_ref(
                std::path::Path::new("/w/reports/sub/c.hurl"),
                Some(report),
                Some(root)
            ),
            "sub/c.hurl",
            "a collection under the report is named directly"
        );
        // Outside the workspace the two files aren't travelling together, so a
        // relative path would be a lie.
        assert_eq!(
            portable_ref(
                std::path::Path::new("/elsewhere/legacy.hurl"),
                Some(report),
                Some(root)
            ),
            "/elsewhere/legacy.hurl",
            "nothing outside the workspace is made to look relative to it"
        );
        // With no workspace to bound the walk, the old behaviour stands.
        assert_eq!(
            portable_ref(target, Some(report), None),
            "/w/apis/billing.hurl",
            "without a workspace there is no scope to stay inside"
        );

        // And what it writes is what the runners resolve: both front-ends send
        // a relative ref back through the report's own directory.
        assert_eq!(
            crate::report::context::resolve_ref_path(Some(report), "../apis/billing.hurl"),
            std::path::PathBuf::from("/w/reports/../apis/billing.hurl"),
            "the relative ref resolves against the report's folder"
        );
    }

    /// Collections open in a tab are still offered, marked as being from
    /// outside the workspace so they can be told apart — and never listed
    /// twice when the workspace scan already found them.
    #[test]
    fn open_collections_outside_the_workspace_are_offered_but_marked_as_such() {
        let root = std::env::temp_dir().join(format!("paperboy_cc2_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).expect("scratch workspace");
        std::fs::write(
            root.join("smoke.hurl"),
            "GET https://x
",
        )
        .expect("collection");
        let report = root.join("nightly.trail");

        let mut inside = crate::collection::Collection::new("smoke".to_string(), Vec::new());
        inside.path = Some(root.join("smoke.hurl"));
        let mut outside = crate::collection::Collection::new("legacy".to_string(), Vec::new());
        outside.path = Some(std::path::PathBuf::from("/elsewhere/legacy.hurl"));
        let scratch = crate::collection::Collection::new("Untitled".to_string(), Vec::new());

        let choices = collection_choices(
            Some(&root),
            Some(&report),
            &[inside, outside, scratch],
            "unsaved",
        );

        assert_eq!(
            choices.iter().filter(|c| c.label == "smoke").count(),
            1,
            "a collection both open and in the workspace is offered once, not twice"
        );
        let legacy = choices
            .iter()
            .find(|c| c.label == "legacy")
            .expect("an open collection outside the workspace is still offered");
        assert!(!legacy.in_workspace, "it is not in the workspace");
        assert_eq!(
            legacy.value, "/elsewhere/legacy.hurl",
            "with nowhere shorter to be relative to, the path stays absolute"
        );
        let scratch = choices
            .iter()
            .find(|c| c.label == "Untitled")
            .expect("an unsaved collection is offered");
        assert_eq!(
            (scratch.value.as_str(), scratch.detail.as_str()),
            ("Untitled", "unsaved"),
            "with no path to write it can only be referenced by name, and says so"
        );
        // Workspace collections sort first: they are the likely answer.
        assert!(
            choices[0].in_workspace,
            "the workspace's own collections are offered first"
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    /// A stand-in collection list for the layout tests, which are about
    /// geometry rather than about what happens to be on disk.
    fn collection_choices_fixture() -> Vec<CollectionChoice> {
        vec![CollectionChoice {
            value: "c.hurl".to_string(),
            label: "c".to_string(),
            detail: "c.hurl".to_string(),
            in_workspace: true,
        }]
    }

    /// Renders the settings panel over a fixed set of values and returns the
    /// panel's rect plus the rect of every text run painted inside it.
    fn run_settings_panel(
        ctx: &egui::Context,
        set: &[(&str, &str)],
        avail: f32,
    ) -> (egui::Rect, Vec<(String, egui::Rect)>) {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = Strings::for_language(&Language::English);
        let envs = vec!["dev".to_string()];
        let formats: Vec<String> = crate::report::writer::OUTPUT_EXTENSIONS
            .iter()
            .map(|e| e.to_string())
            .collect();
        let owned: Vec<(String, String)> = set
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        let value_of = move |key: &str| -> Vec<String> {
            owned
                .iter()
                .filter(|(k, _)| k == key)
                .map(|(_, v)| v.clone())
                .collect()
        };

        let mut rect = egui::Rect::NOTHING;
        let mut out = None;
        // Three passes: combo boxes and galley measurements only settle once
        // the layout has been seen at least once.
        for _ in 0..3 {
            let full = ctx.run_ui(egui::RawInput::default(), |ui| {
                ui.set_max_width(avail);
                let mut acts = Vec::new();
                rect = ui
                    .scope(|ui| {
                        settings_panel(
                            ui,
                            &th,
                            &s,
                            &value_of,
                            &collection_choices_fixture,
                            &envs,
                            &formats,
                            &mut acts,
                        );
                    })
                    .response
                    .rect;
            });
            out = Some(full);
        }
        let mut texts = Vec::new();
        fn walk(sh: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
            match sh {
                egui::Shape::Text(t) => {
                    out.push((
                        t.galley.text().to_string(),
                        egui::Rect::from_min_size(t.pos, t.galley.size()),
                    ));
                }
                egui::Shape::Vec(v) => v.iter().for_each(|sh| walk(sh, out)),
                _ => {}
            }
        }
        for c in &out.expect("rendered").shapes {
            walk(&c.shape, &mut texts);
        }
        (rect, texts)
    }

    /// "Add a report setting" appends to the list, so it belongs underneath it —
    /// above the settings it read as a heading for them.
    #[test]
    fn the_add_setting_button_sits_below_the_settings_it_adds_to() {
        let ctx = egui::Context::default();
        let s = Strings::for_language(&Language::English);
        let (_, texts) = run_settings_panel(&ctx, &[("collection", "c.hurl")], 600.0);

        let button = texts
            .iter()
            .find(|(t, _)| t.contains(s.report_add_setting))
            .map(|(_, r)| *r)
            .expect("the add button is drawn while settings are still missing");
        let collection = texts
            .iter()
            .find(|(t, _)| t == "COLLECTION")
            .map(|(_, r)| *r)
            .expect("the collection setting is drawn");
        assert!(
            button.top() >= collection.bottom(),
            "the add button at {} should sit below the settings ending at {}",
            button.top(),
            collection.bottom()
        );

        // Even with every one-shot directive set the button stays: another
        // collection can always be added, because `collection:` repeats.
        let (_, full) = run_settings_panel(
            &ctx,
            &[
                ("collection", "c.hurl"),
                ("output", "csv"),
                ("environment", "dev"),
                ("root", "/r"),
                ("baseline", "b.baseline"),
                ("columns", "a,b"),
            ],
            600.0,
        );
        assert!(
            full.iter().any(|(t, _)| t.contains(s.report_add_setting)),
            "a helper collection can still be added"
        );
    }

    /// The panel spans the editor pane and keeps that width whatever it happens
    /// to contain: a box that grew and shrank as dropdowns were used would make
    /// the view twitch, and one sized to its contents left the settings adrift
    /// in empty space with their own values truncated beside it.
    #[test]
    fn the_settings_panel_keeps_its_width_whatever_it_holds() {
        let ctx = egui::Context::default();
        let (bare, _) = run_settings_panel(&ctx, &[("collection", "c.hurl")], 600.0);
        let (full, _) = run_settings_panel(
            &ctx,
            &[
                ("collection", "c.hurl"),
                ("output", "xlsx"),
                ("environment", "dev"),
                (
                    "root",
                    "/a/very/long/root/path/that/would/otherwise/stretch/things",
                ),
                ("baseline", "/another/rather/long/baseline/path.baseline"),
                ("columns", "name,status,duration,size,assertions"),
            ],
            600.0,
        );
        assert!(
            (bare.width() - full.width()).abs() < 0.5,
            "one setting gives width {} but six give {}",
            bare.width(),
            full.width()
        );
        assert!(
            bare.width() > 500.0,
            "the panel fills the 600px pane rather than sitting in a corner of it, got {}",
            bare.width()
        );

        // It still yields to a narrow column, so the panel never forces a wide
        // editor pane. It can only give back what its contents don't need: a
        // dropdown has a minimum width of its own, which is the floor here, so
        // the test asserts it shrank rather than naming a width the chips can't
        // actually reach.
        let (narrow, _) = run_settings_panel(&ctx, &[("collection", "c.hurl")], 120.0);
        assert!(
            narrow.width() < bare.width(),
            "a 120px column still gave the panel {} (it takes {} when there is room)",
            narrow.width(),
            bare.width()
        );
    }

    /// The hover highlight paints a panel *behind* the row, which a row whose
    /// chips cover most of its width almost entirely hides — so the chips
    /// themselves deepen too. Their own colour is kept: it is what says which
    /// kind of block this is.
    #[test]
    fn a_hovered_chip_deepens_its_own_colour() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let mut chip = Chip::base("REQUEST login".into(), th.accent);
        let plain = chip_colors(&th, &chip, false);
        chip.hovered = true;
        let lit = chip_colors(&th, &chip, false);

        // Deeper, not merely different: the fill has moved further from the
        // panel colour it started at.
        let dist = |c: Color32| {
            let d = |a: u8, b: u8| (a as f32 - b as f32).abs();
            d(c.r(), th.panel.r()) + d(c.g(), th.panel.g()) + d(c.b(), th.panel.b())
        };
        assert!(
            dist(lit.fill) > dist(plain.fill) + 1.0,
            "hovered fill {:?} is no deeper than {:?} against panel {:?}",
            lit.fill,
            plain.fill,
            th.panel
        );
        assert!(
            dist(lit.stroke.color) > dist(plain.stroke.color) + 1.0,
            "the edge follows the fill so it doesn't vanish into it"
        );
        assert_eq!(
            lit.text, plain.text,
            "the label is left alone — a bolder-looking label reads as a different kind of chip"
        );
        assert_eq!(lit.rule, plain.rule, "the colour rule still identifies it");

        // Selection still wins on the base chip: a chip can be both, and
        // selection is the one the user set deliberately.
        let sel = chip_colors(&th, &chip, true);
        assert_eq!(sel.fill, th.select_bg);
    }

    /// The key label in a combo-box setting is centred against the combo, not
    /// left floating above it — a label added before the (taller) combo is
    /// otherwise centred in a row that has not grown yet.
    #[test]
    fn a_settings_key_label_is_centred_against_its_dropdown() {
        let ctx = egui::Context::default();
        ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let strings = Strings::for_language(&Language::English);
        let choices = vec!["dev".to_string()];

        for spec in &header_specs() {
            let mut label = egui::Rect::NOTHING;
            let mut chip = egui::Rect::NOTHING;
            for _ in 0..3 {
                let out = ctx.run_ui(egui::RawInput::default(), |ui| {
                    let mut acts = Vec::new();
                    chip = ui
                        .horizontal(|ui| {
                            header_chip(
                                ui,
                                &th,
                                &strings,
                                spec,
                                0,
                                "dev",
                                Some(&choices),
                                &collection_choices_fixture,
                                &mut acts,
                            );
                        })
                        .response
                        .rect;
                });
                // The key is painted as a raw galley (see `header_chip`), so it
                // is found among the text shapes rather than as a widget.
                let want = spec.key.to_uppercase();
                label = out
                    .shapes
                    .iter()
                    .find_map(|c| match &c.shape {
                        egui::Shape::Text(t) if t.galley.text() == want => {
                            Some(egui::Rect::from_min_size(t.pos, t.galley.size()))
                        }
                        _ => None,
                    })
                    .unwrap_or_else(|| panic!("{} label was not painted", spec.key));
            }
            assert!(
                (label.center().y - chip.center().y).abs() < 2.0,
                "{}: label centred at {} but the chip at {}",
                spec.key,
                label.center().y,
                chip.center().y
            );
        }
    }

    #[test]
    fn settings_chips_render_at_the_same_height_as_flow_chips() {
        let specs = header_specs();
        let baseline = chip_height(|ui, th, s, acts| {
            let chip = Chip::base("REPORT".into(), th.subst);
            render_chip(ui, th, s, &chip, false, &[0], &[], &[], acts);
        });
        for spec in &specs {
            let choices = vec!["dev".to_string()];
            let h = chip_height(|ui, th, s, acts| {
                header_chip(
                    ui,
                    th,
                    s,
                    spec,
                    0,
                    "dev",
                    Some(&choices),
                    &collection_choices_fixture,
                    acts,
                );
            });
            assert!(
                (h - baseline).abs() < 1.0,
                "{} chip is {h}, flow chips are {baseline}",
                spec.key
            );
        }
    }

    #[test]
    fn a_picked_path_is_stored_relative_to_the_report_when_it_can_be() {
        let report = std::path::Path::new("/w/reports/daily.paper");
        assert_eq!(
            relative_to_report(std::path::Path::new("/w/reports/out.csv"), Some(report)),
            "out.csv",
            "a sibling file travels with the report"
        );
        assert_eq!(
            relative_to_report(std::path::Path::new("/elsewhere/out.csv"), Some(report)),
            "/elsewhere/out.csv",
            "anything outside the report's folder keeps its absolute path"
        );
        assert_eq!(
            relative_to_report(std::path::Path::new("/w/out.csv"), None),
            "/w/out.csv",
            "an unsaved report has nothing to be relative to"
        );
    }

    #[test]
    fn every_chip_a_block_can_show_carries_hover_help() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = Strings::for_language(&Language::English);
        // One source line per block shape the palette can produce, so a chip
        // added later without help text fails here rather than shipping bare.
        let sources = [
            "REQUEST login",
            "REPORT REQUEST login AS Login RESPONSE PRETTY SHOW(Time) HIDE(Error)",
            "REPORT userId",
            "REPORT userId AS Id",
            "REPORT \"{{a}}-{{b}}\" AS Combined",
            "TOKEN = abc",
            "LIST NAMES = [\"a\", \"b\"]",
            "PARALLEL(3) FOR F IN FILES \"/d\"",
            "FOR T IN ENVS BASELINE(\"dev\"), COMPARISON(\"prod\")",
            "FOR T IN ENVS BASELINE(FILE(\"a.baseline\")), COMPARISON(\"prod\", \"uat\")",
        ];
        for src in sources {
            let node = crate::report::edit::parse_one_node(src, true)
                .unwrap_or_else(|| panic!("could not parse {src:?}"));
            for chip in node_chips(&node, None, &th, &s) {
                assert!(
                    !chip.help.is_empty(),
                    "chip {:?} of {src:?} has no hover help",
                    chip.text
                );
            }
        }
    }

    #[test]
    fn a_parallel_loop_shows_an_editable_degree_chip() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = Strings::for_language(&Language::English);

        // With an explicit degree the chip carries it; the base chip beside it
        // must not repeat the "PARALLEL(4)" prefix that the head label embeds.
        let node =
            crate::report::edit::parse_one_node("PARALLEL(4) FOR F IN FILES \"/d\"", true).unwrap();
        let chips = node_chips(&node, None, &th, &s);
        assert!(matches!(
            chips[0].edit,
            ChipEdit::Parallel { degree: Some(4) }
        ));
        assert!(
            !chips[1].text.contains("PARALLEL"),
            "base chip repeated the PARALLEL prefix: {:?}",
            chips[1].text
        );

        // A plain PARALLEL has no explicit limit, so the box shows blank rather
        // than inventing the runner's default.
        let node =
            crate::report::edit::parse_one_node("PARALLEL FOR F IN FILES \"/d\"", true).unwrap();
        let chips = node_chips(&node, None, &th, &s);
        assert!(matches!(chips[0].edit, ChipEdit::Parallel { degree: None }));

        // A serial loop gets no PARALLEL chip at all.
        let node = crate::report::edit::parse_one_node("FOR F IN FILES \"/d\"", true).unwrap();
        let chips = node_chips(&node, None, &th, &s);
        assert!(
            !chips
                .iter()
                .any(|c| matches!(c.edit, ChipEdit::Parallel { .. }))
        );
    }

    #[test]
    fn chips_on_a_line_stay_vertically_aligned() {
        // Reproduce `block_row`'s chip cluster (a top-aligned horizontal row of
        // mixed label / combo / text-field chips) and confirm every chip sits at
        // the same vertical position — i.e. the line does not "cascade" each
        // successive chip lower, which the default centre-aligned row does.
        let ctx = egui::Context::default();
        ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::for_language(&Language::English);
        let mut tops: Vec<f32> = Vec::new();
        for _ in 0..3 {
            tops.clear();
            let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                // The same layout `block_row` uses for the chip cluster.
                ui.horizontal_top(|ui| {
                    let mut acts = Vec::new();
                    let staging = vec!["api_staging".to_string()];
                    let dev = vec!["api_dev".to_string()];
                    let classify = vec!["classify_result".to_string()];
                    let chips: Vec<(Chip, &[String])> = vec![
                        (Chip::base("FOR".into(), th.subst), &[]),
                        (Chip::env_role(true, 0, "api_staging", th.subst), &staging),
                        (Chip::env_role(false, 1, "api_dev", th.subst), &dev),
                        (
                            Chip::modifier(
                                "RESPONSE PRETTY".into(),
                                th.subst,
                                DetachWhich::Response,
                            ),
                            &[],
                        ),
                        (Chip::request("classify_result", th.subst), &classify),
                        (
                            Chip::alias("Environment", th.subst, Some(DetachWhich::As)),
                            &[],
                        ),
                    ];
                    for (chip, envs) in &chips {
                        let r = ui.scope(|ui| {
                            render_chip(ui, &th, &s, chip, false, &[0], envs, envs, &mut acts)
                        });
                        tops.push(r.response.rect.top());
                    }
                });
            });
        }
        let first = tops[0];
        for (i, t) in tops.iter().enumerate() {
            assert!(
                (t - first).abs() < 0.5,
                "chip {i} top {t} drifted from first chip top {first}: {tops:?}"
            );
        }
    }

    #[test]
    fn selecting_a_block_keeps_its_size_and_position() {
        // Selecting a base chip must only recolour it, never resize or move it
        // (a thicker selection stroke used to expand the frame by a pixel and
        // nudge the chip and its neighbours).
        let ctx = egui::Context::default();
        ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::for_language(&Language::English);
        let mut unsel = egui::Rect::ZERO;
        let mut sel = egui::Rect::ZERO;
        for _ in 0..3 {
            let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                let mut acts = Vec::new();
                let chip = Chip::base("REQUEST".into(), th.subst);
                unsel = ui
                    .horizontal_top(|ui| {
                        render_chip(ui, &th, &s, &chip, false, &[0], &[], &[], &mut acts)
                    })
                    .response
                    .rect;
                sel = ui
                    .horizontal_top(|ui| {
                        render_chip(ui, &th, &s, &chip, true, &[0], &[], &[], &mut acts)
                    })
                    .response
                    .rect;
            });
        }
        assert!(
            (unsel.width() - sel.width()).abs() < 0.5,
            "selected width {} vs unselected {}",
            sel.width(),
            unsel.width()
        );
        assert!(
            (unsel.height() - sel.height()).abs() < 0.5,
            "selected height {} vs unselected {}",
            sel.height(),
            unsel.height()
        );
    }

    #[test]
    fn pretty_json_cell_reflows_json_documents_only() {
        // A JSON object/array is indented one-field-per-line.
        let pretty = pretty_json_cell(r#"{"a":1,"b":[2,3]}"#);
        assert!(pretty.contains('\n'), "object should be reflowed: {pretty}");
        assert!(pretty.contains("\"a\": 1"));
        // A bare scalar / plain string is left exactly as-is.
        assert_eq!(pretty_json_cell("42"), "42");
        assert_eq!(pretty_json_cell("just text"), "just text");
        // Invalid JSON that merely starts like an object is returned unchanged.
        assert_eq!(pretty_json_cell("{not json"), "{not json");
    }

    /// The floating-drag lift only applies to a whole-row (`DragItem::Row`)
    /// drag, and reports exactly the path being dragged; a modifier-chip drag
    /// (`DragItem::Chip`) must not lift a row.
    #[test]
    fn dragged_row_path_tracks_only_row_drags() {
        let ctx = egui::Context::default();
        assert_eq!(dragged_row_path(&ctx), None, "no drag → no lifted row");

        egui::DragAndDrop::set_payload(&ctx, DragItem::Row(vec![1, 2]));
        assert_eq!(dragged_row_path(&ctx), Some(vec![1, 2]));

        egui::DragAndDrop::set_payload(
            &ctx,
            DragItem::Chip {
                path: vec![0],
                which: DetachWhich::Report,
            },
        );
        assert_eq!(
            dragged_row_path(&ctx),
            None,
            "a modifier-chip drag must not lift a row"
        );
    }

    /// The mirror of the above: a chip drag lifts exactly that chip (so it can
    /// float under the pointer and leave a ghost) and a row drag lifts none, so
    /// the two lifts can never both fire for one drag.
    /// A statistics clause present in the source has to be visible as a chip,
    /// and the load-bearing rule has to leave the row's REPORT chip undraggable
    /// on its own.
    #[test]
    fn a_named_column_shows_its_statistics_and_keeps_report_attached() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::english();
        let flow = crate::report::parse_flow("REPORT TIER AS Plan STATISTICS(MEAN)\n")
            .expect("fixture parses");
        let chips = node_chips(&flow.nodes[0], None, &th, s);
        assert!(
            chips.iter().any(|c| c.text.contains("STATISTICS(MEAN)")),
            "the statistics clause is drawn: {:?}",
            chips.iter().map(|c| &c.text).collect::<Vec<_>>()
        );
        let report = chips
            .iter()
            .find(|c| c.text == "REPORT")
            .expect("the REPORT chip is drawn");
        assert!(
            report.detach.is_none(),
            "REPORT is load-bearing here, so grabbing it moves the whole row"
        );
    }

    /// `TRUTH`, `IMAGE` and `DETAIL` are as much a part of a column as its
    /// `STATISTICS`, and were the only clauses the block editor left invisible
    /// -- a ground-truthed column looked identical to an ordinary one.
    #[test]
    fn a_named_column_shows_all_four_of_its_clauses() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::english();
        let flow = crate::report::parse_flow(
            "REPORT SHOT AS Frame STATISTICS(COUNT) IMAGE(HEIGHT 110) TRUTH \"pass\" DETAIL\n",
        )
        .expect("fixture parses");
        let chips = node_chips(&flow.nodes[0], None, &th, s);
        let texts: Vec<&String> = chips.iter().map(|c| &c.text).collect();
        for want in [
            "STATISTICS(COUNT)",
            "IMAGE(HEIGHT 110)",
            "TRUTH \"pass\"",
            "DETAIL",
        ] {
            assert!(
                texts.iter().any(|t| t.as_str() == want),
                "{want} is drawn: {texts:?}"
            );
        }
    }

    /// Detaching a clause chip takes that clause off and leaves the column --
    /// and the other three clauses -- alone.
    #[test]
    fn detaching_one_clause_leaves_the_column_and_its_other_clauses() {
        let mut flow = crate::report::parse_flow(
            "REPORT SHOT AS Frame IMAGE(HEIGHT 110) TRUTH \"pass\" DETAIL\n",
        )
        .expect("fixture parses");
        crate::report::edit::detach_modifier(&mut flow, &[0], DetachWhich::Truth);
        let text = flow.to_text();
        assert!(!text.contains("TRUTH"), "the truth is gone: {text}");
        assert!(
            text.contains("AS Frame")
                && text.contains("IMAGE(HEIGHT 110)")
                && text.contains("DETAIL"),
            "and nothing else is: {text}"
        );
    }

    /// A `WITH` field's clauses are written into its row, since the row is one
    /// chip rather than a line of them.
    #[test]
    fn a_with_field_shows_its_clauses_in_its_row() {
        let flow = crate::report::parse_flow(
            "REPORT REQUEST svc WITH\n    Frame: jsonpath \"$.f\" IMAGE TRUTH \"ok\" DETAIL\nEND\n",
        )
        .expect("fixture parses");
        let crate::report::flow::FlowNode::Report(crate::report::flow::ReportStmt::Request {
            with,
            ..
        }) = &flow.nodes[0]
        else {
            panic!("fixture is a report request");
        };
        let crate::report::flow::WithItem::Field {
            image,
            truth,
            detail,
            ..
        } = &with[0]
        else {
            panic!("fixture's first item is a field");
        };
        assert!(
            image.is_some() && truth.is_some() && *detail,
            "parsed: {with:?}"
        );
    }

    /// The drop preview is computed by rehearsing the drop, so the ghost has to
    /// be the very chip that appears — same text, same slot — once it lands.
    #[test]
    fn the_drop_preview_is_exactly_the_chip_the_drop_will_add() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::english();
        let flow = crate::report::parse_flow("REPORT REQUEST A\n").expect("fixture parses");
        let node = &flow.nodes[0];

        let pending = PendingMod::New(Modifier::Show);
        let (idx, text, _) =
            preview_chip(node, &pending, Some(true), &th, s).expect("SHOW adds a chip");

        let before = node_chips(node, Some(true), &th, s);
        assert_eq!(idx, before.len(), "SHOW appends to the end of the line");

        let mut after_node = node.clone();
        assert!(pending.apply(&mut after_node));
        assert_eq!(
            node_chips(&after_node, Some(true), &th, s)[idx]
                .ghost_shape()
                .0,
            text,
            "the ghost's label is the landed chip's label, so the gap is its size"
        );
    }

    /// Every block a user cannot compose out of something else has to be in the
    /// palette, or the GUI simply can't write that statement.
    #[test]
    fn the_palette_offers_every_block_that_cannot_be_composed() {
        for kind in NodeKind::ALL {
            // A reported request is `REQUEST` plus the `REPORT` modifier, so it
            // is the one kind the palette deliberately leaves out.
            if matches!(kind, NodeKind::ReportRequest) {
                assert!(
                    !BASE_KINDS.contains(&kind),
                    "{kind:?} is composed from REQUEST + REPORT, not offered directly"
                );
                continue;
            }
            assert!(
                BASE_KINDS.contains(&kind),
                "{kind:?} has no other route into a report, so the palette must offer it"
            );
        }
    }

    /// A chip that keeps its keyword in its inline editor rather than in `text`
    /// still has to produce a full-sized ghost — `PARALLEL` came out a sliver.
    #[test]
    fn a_ghost_is_sized_from_what_the_chip_really_draws() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::english();
        let flow = crate::report::parse_flow("FOR X IN FILES \"/a\"\n    REQUEST A\nEND\n")
            .expect("fixture parses");

        let (_, text, extra) = preview_chip(
            &flow.nodes[0],
            &PendingMod::New(Modifier::Parallel),
            None,
            &th,
            s,
        )
        .expect("PARALLEL adds a chip");
        assert_eq!(
            text, "PARALLEL",
            "the keyword is in the ghost, not an empty box"
        );
        assert!(
            extra >= PARALLEL_FIELD_WIDTH,
            "the concurrency box's width is reserved too, got {extra}"
        );
    }

    /// A clause the line won't take gets no gap — the row must not open space
    /// for a drop that is about to be refused.
    #[test]
    fn a_refused_drop_previews_nothing() {
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = crate::i18n::Strings::english();
        let flow =
            crate::report::parse_flow("REPORT REQUEST A SHOW(Time)\n").expect("fixture parses");
        let carried = crate::report::edit::carry_modifier(&flow.nodes[0], DetachWhich::Show)
            .expect("the SHOW is there to pick up");
        assert!(
            preview_chip(
                &flow.nodes[0],
                &PendingMod::Moved(carried),
                Some(true),
                &th,
                s
            )
            .is_none(),
            "a request that already has SHOW opens no gap for another"
        );
    }

    #[test]
    fn dragged_chip_tracks_only_chip_drags() {
        let ctx = egui::Context::default();
        assert_eq!(dragged_chip(&ctx), None, "no drag → no lifted chip");

        egui::DragAndDrop::set_payload(
            &ctx,
            DragItem::Chip {
                path: vec![0, 3],
                which: DetachWhich::BaselineShow,
            },
        );
        assert_eq!(
            dragged_chip(&ctx),
            Some((vec![0, 3], DetachWhich::BaselineShow)),
            "the picked-up chip is identified by its row and its clause"
        );

        egui::DragAndDrop::set_payload(&ctx, DragItem::Row(vec![0, 3]));
        assert_eq!(
            dragged_chip(&ctx),
            None,
            "a whole-line drag must not also lift a chip out of that line"
        );
    }

    /// A tethered pair is drawn as one pill *split into segments*. Without a
    /// visible seam a column carrying `STATISTICS`, `IMAGE`, `TRUTH` and
    /// `DETAIL` reads as one blob and the clauses look merged into the thing
    /// they qualify.
    #[test]
    fn a_tethered_chip_gets_a_seam_to_be_read_apart_by() {
        let th = GuiTheme::from_spec(&crate::theme::default_preset());
        let mut chips = vec![
            Chip::alias("Result", th.pending, None),
            Chip::modifier("TRUTH(\"Expected\")".into(), th.subst, DetachWhich::Truth).tether(),
        ];
        link_tethers(&mut chips);

        assert!(
            chip_colors(&th, &chips[0], false).seam.is_none(),
            "the anchor opens the pill, so nothing is drawn down its leading edge"
        );
        let hanger = chip_colors(&th, &chips[1], false);
        assert!(
            hanger.seam.is_some(),
            "the hanger's leading edge is the seam between the two segments"
        );
        assert!(
            hanger.rule.is_none(),
            "and the category bar goes, since inside a pill it reads as a divider"
        );
    }

    /// The hover highlight has to promise exactly what a drag would pick up.
    /// Resting on a detachable chip outlines that chip; holding Ctrl — which is
    /// what turns the same gesture into a whole-line drag — hands the highlight
    /// back to the block.
    #[test]
    fn hovering_a_detachable_chip_scopes_the_highlight_to_that_chip() {
        let modi = Chip::modifier(
            "PARALLEL(8)".into(),
            egui::Color32::WHITE,
            DetachWhich::Parallel,
        );
        let base = Chip::base("FOR f IN FILES".into(), egui::Color32::WHITE);
        let rect = egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(80.0, 20.0));
        let over = egui::RawInput {
            events: vec![egui::Event::PointerMoved(rect.center())],
            ..Default::default()
        };
        let ctrl_over = egui::RawInput {
            modifiers: egui::Modifiers {
                ctrl: true,
                command: true,
                ..Default::default()
            },
            events: vec![egui::Event::PointerMoved(rect.center())],
            ..Default::default()
        };
        let recorded = |input: egui::RawInput, chip: &Chip| {
            let ctx = egui::Context::default();
            // Two passes: the first delivers the pointer event, the second runs
            // with the pointer already where it was put.
            let _ = ctx.run_ui(input.clone(), |ui| record_chip_hover(ui, chip, rect));
            ctx.data_mut(|d| d.remove_temp::<Option<egui::Rect>>(chip_hover_id()));
            let _ = ctx.run_ui(input, |ui| record_chip_hover(ui, chip, rect));
            ctx.data(|d| d.get_temp::<Option<egui::Rect>>(chip_hover_id()))
                .flatten()
        };

        assert_eq!(
            recorded(over.clone(), &modi),
            Some(rect),
            "a plain drag would lift this chip alone, so it is what lights up"
        );
        assert_eq!(
            recorded(ctrl_over, &modi),
            None,
            "with Ctrl the drag takes the whole line, so the block highlight stands"
        );
        assert_eq!(
            recorded(over, &base),
            None,
            "a base chip moves its line either way, so it never scopes the highlight"
        );
    }

    #[test]
    fn chip_drag_payload_detaches_plainly_and_moves_the_line_with_ctrl() {
        let ctx = egui::Context::default();
        let base = Chip::base("REQUEST x".into(), egui::Color32::WHITE);
        let modi = Chip::modifier("SHOW(Time)".into(), egui::Color32::WHITE, DetachWhich::Show);
        let path = vec![1usize];

        // Plain drag: the base chip moves the whole line, a modifier chip is
        // picked up on its own to detach it.
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            assert!(matches!(
                chip_drag_payload(ui, &base, &path),
                DragItem::Row(p) if p == path
            ));
            assert!(matches!(
                chip_drag_payload(ui, &modi, &path),
                DragItem::Chip {
                    which: DetachWhich::Show,
                    ..
                }
            ));
        });

        // Ctrl/Cmd held: *any* chip — even a detachable modifier — moves the
        // whole line/subtree instead of detaching.
        let ctrl = egui::RawInput {
            modifiers: egui::Modifiers {
                ctrl: true,
                command: true,
                ..Default::default()
            },
            ..Default::default()
        };
        let _ = ctx.run_ui(ctrl, |ui| {
            assert!(matches!(
                chip_drag_payload(ui, &modi, &path),
                DragItem::Row(p) if p == path
            ));
            assert!(matches!(
                chip_drag_payload(ui, &base, &path),
                DragItem::Row(p) if p == path
            ));
        });
    }

    #[test]
    fn clause_chips_open_the_wizard_on_click() {
        assert!(chip_opens_wizard_on_click(&Chip::modifier(
            "SHOW".into(),
            egui::Color32::WHITE,
            DetachWhich::Show
        )));
        assert!(chip_opens_wizard_on_click(&Chip::modifier(
            "HIDE".into(),
            egui::Color32::WHITE,
            DetachWhich::Hide
        )));
        assert!(chip_opens_wizard_on_click(&Chip::modifier(
            "RESPONSE".into(),
            egui::Color32::WHITE,
            DetachWhich::Response
        )));
        // An ENVS loop's BASELINE SHOW is picked the same way, in the ENVS
        // wizard — its chip has to open too, or its checklist is unreachable.
        assert!(chip_opens_wizard_on_click(&Chip::modifier(
            "SHOW(Time)".into(),
            egui::Color32::WHITE,
            DetachWhich::BaselineShow
        )));
        // REPORT / WITH / plain base chips are not opened this way.
        assert!(!chip_opens_wizard_on_click(&Chip::modifier(
            "REPORT".into(),
            egui::Color32::WHITE,
            DetachWhich::Report
        )));
        assert!(!chip_opens_wizard_on_click(&Chip::base(
            "x".into(),
            egui::Color32::WHITE
        )));
    }

    #[test]
    fn lifted_subtree_covers_a_loop_body_but_not_siblings() {
        // Dragging a leaf lifts only that leaf.
        assert!(row_is_lifted(&[2], &[2]));
        assert!(!row_is_lifted(&[2], &[1]));
        assert!(!row_is_lifted(&[2], &[3]));

        // Dragging a FOR loop at [2] lifts its head ([2]), every body row
        // ([2,0], [2,1], …) and its synthetic END (path == [2]) — but never a
        // sibling ([3]) or a cousin under a different loop ([1,0]).
        assert!(row_is_lifted(&[2], &[2, 0]), "loop body row is lifted");
        assert!(row_is_lifted(&[2], &[2, 1, 0]), "nested body row is lifted");
        assert!(!row_is_lifted(&[2], &[3]), "the next sibling stays put");
        assert!(
            !row_is_lifted(&[2], &[1, 0]),
            "another loop's body stays put"
        );
        // A path that merely shares a leading digit is not a descendant.
        assert!(
            !row_is_lifted(&[2], &[20]),
            "prefix is index-wise, not textual"
        );
    }

    /// The hover highlight must promise exactly what a drag delivers, so it is
    /// keyed off the same subtree rule — but split into two tiers so "this
    /// block" and "and this comes with it" read differently.
    #[test]
    fn hover_lights_the_block_strongly_and_its_body_softly() {
        // A leaf lights only itself.
        assert_eq!(hover_tier(&[2], &[2]), Some(HoverTier::Block));
        assert_eq!(hover_tier(&[2], &[1]), None);
        assert_eq!(hover_tier(&[2], &[3]), None);

        // A loop's body and its nested rows come along, one tier down.
        assert_eq!(hover_tier(&[2], &[2, 0]), Some(HoverTier::CarriedAlong));
        assert_eq!(hover_tier(&[2], &[2, 1, 0]), Some(HoverTier::CarriedAlong));
        assert_eq!(hover_tier(&[2], &[1, 0]), None);
        assert_eq!(hover_tier(&[2], &[20]), None);

        // Hovering a row *inside* a loop lights that row, not the loop around
        // it: dragging it out takes only itself.
        assert_eq!(hover_tier(&[2, 1], &[2, 1]), Some(HoverTier::Block));
        assert_eq!(hover_tier(&[2, 1], &[2]), None);
        assert_eq!(hover_tier(&[2, 1], &[2, 0]), None);

        // Every row the highlight touches is a row the drag would lift, and
        // vice versa — the two must never disagree.
        for path in [vec![2], vec![2, 0], vec![2, 1, 0], vec![3], vec![1, 0]] {
            assert_eq!(
                hover_tier(&[2], &path).is_some(),
                row_is_lifted(&[2], &path),
                "hover and lift disagree about {path:?}"
            );
        }
    }

    /// The block under the pointer is the innermost one: a `FOR` header and a
    /// row in its body can both contain the pointer, and the body row is the one
    /// the user is pointing at.
    #[test]
    fn hovered_block_prefers_the_innermost_row_and_ignores_begin() {
        fn row(path: &[usize], kind: RowKind, inside: bool) -> RowHover {
            RowHover {
                path: path.to_vec(),
                kind,
                rect: egui::Rect::ZERO,
                bg: egui::layers::ShapeIdx(0),
                pointer_inside: inside,
            }
        }
        let rows = vec![
            row(&[], RowKind::Begin, true),
            row(&[0], RowKind::LoopHead, true),
            row(&[0, 0], RowKind::Leaf, true),
            row(&[0], RowKind::LoopEnd, false),
        ];
        assert_eq!(hovered_block(&rows), Some([0, 0].as_slice()));

        // Begin is never the answer, even when it is the only row the pointer is
        // over — its empty path would light the whole report.
        let only_begin = vec![
            row(&[], RowKind::Begin, true),
            row(&[0], RowKind::Leaf, false),
        ];
        assert_eq!(hovered_block(&only_begin), None);

        // A loop's END stands in for the loop, so pointing at it lights the
        // whole block.
        let on_end = vec![
            row(&[0], RowKind::LoopHead, false),
            row(&[0, 0], RowKind::Leaf, false),
            row(&[0], RowKind::LoopEnd, true),
        ];
        assert_eq!(hovered_block(&on_end), Some([0].as_slice()));
        assert_eq!(hover_tier(&[0], &[0]), Some(HoverTier::Block));
    }

    #[test]
    fn origin_ghost_paints_without_panicking() {
        let ctx = egui::Context::default();
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            // A normal slot draws a ghost; a degenerate rect is a safe no-op.
            paint_origin_ghost(
                ui.painter(),
                egui::Rect::from_min_size(egui::pos2(4.0, 4.0), egui::vec2(80.0, 22.0)),
                &th,
            );
            paint_origin_ghost(ui.painter(), egui::Rect::ZERO, &th);
        });
    }

    /// The dashed outline marking where a block was lifted from has to trace the
    /// block, not the whole editor width: a nested block sits in from the left by
    /// its indent, and the outline has to start there too.
    #[test]
    fn the_origin_outline_starts_at_the_blocks_own_indent() {
        // A row's laid-out rect always begins at the editor's left margin,
        // because the indent is `add_space`d inside the row's own layout.
        let row = egui::Rect::from_min_size(egui::pos2(4.0, 40.0), egui::vec2(300.0, 22.0));

        let top = indented_content(row, 0);
        assert_eq!(top, row, "an unindented block is its own rect");

        let nested = indented_content(row, 2);
        assert_eq!(
            nested.left(),
            row.left() + 2.0 * INDENT_STEP,
            "the outline starts where the nested block does"
        );
        assert_eq!(nested.right(), row.right(), "the right edge is untouched");
        assert_eq!(nested.y_range(), row.y_range(), "the height is untouched");

        // A row narrower than its own indent (only reachable from a degenerate
        // layout pass) must not invert into a negative-width rect.
        let tiny = indented_content(
            egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(10.0, 22.0)),
            8,
        );
        assert!(tiny.width() > 0.0, "the outline never collapses: {tiny:?}");
    }

    /// The outline is as round as the block it replaces — dashed along a rounded
    /// path rather than round the four straight edges, which left square corners
    /// inside a rounded fill.
    #[test]
    fn the_origin_outline_is_as_rounded_as_a_block() {
        let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(100.0, 40.0));
        let path = rounded_rect_path(rect, BLOCK_RADIUS);
        assert!(path.len() > 8, "a rounded path is more than four corners");
        assert_eq!(path.first(), path.last(), "the path closes back on itself");
        for p in &path {
            assert!(
                rect.expand(0.01).contains(*p),
                "{p:?} escapes the rect it traces"
            );
        }
        // The true corners are cut off: nothing sits within the radius square of
        // a corner except along its arc, so no point lands *on* the corner.
        for corner in [
            rect.left_top(),
            rect.right_top(),
            rect.right_bottom(),
            rect.left_bottom(),
        ] {
            let nearest = path
                .iter()
                .map(|p| (*p - corner).length())
                .fold(f32::MAX, f32::min);
            assert!(
                nearest > BLOCK_RADIUS * 0.3,
                "the path reaches the square corner {corner:?} (nearest {nearest})"
            );
        }
        // A radius larger than the box can hold is clamped rather than folding
        // the path inside out.
        let thin = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(100.0, 4.0));
        for p in rounded_rect_path(thin, BLOCK_RADIUS) {
            assert!(thin.expand(0.01).contains(p), "{p:?} escapes a thin rect");
        }
    }

    /// The drop marker is a preview of the block that will land, so it has the
    /// block's width — not a bar running to the right-hand edge of the editor.
    #[test]
    fn the_drop_marker_is_as_wide_as_the_block_being_dropped() {
        let measure = |setup: &dyn Fn(&egui::Context)| -> egui::Vec2 {
            let ctx = egui::Context::default();
            ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
            let mut size = egui::Vec2::ZERO;
            for _ in 0..2 {
                setup(&ctx);
                let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                    size = dragged_block_size(ui)
                });
            }
            size
        };

        // An existing block reports the width the lift measured.
        let moved = measure(&|ctx| {
            egui::DragAndDrop::set_payload(ctx, DragItem::Row(vec![0]));
            ctx.data_mut(|d| {
                d.insert_temp(
                    lifted_shape_id(),
                    vec![egui::Rect::from_min_size(
                        egui::Pos2::ZERO,
                        egui::vec2(214.0, 60.0),
                    )],
                )
            });
        });
        assert_eq!(moved, egui::vec2(214.0, 60.0));

        // A palette block has nothing laid out in the flow to measure, so it
        // reports the width of the chip actually in hand.
        let from_palette = measure(&|ctx| {
            egui::DragAndDrop::set_payload(ctx, NodeKind::Request);
            ctx.data_mut(|d| d.insert_temp(palette_drag_size_id(), egui::vec2(96.0, 24.0)));
        });
        assert_eq!(from_palette.x, 96.0, "the palette chip's own width");

        // With nothing measured yet (a drag's very first frame) the marker still
        // has a sane block-like width rather than zero or the full editor.
        let unmeasured = measure(&|ctx| egui::DragAndDrop::set_payload(ctx, NodeKind::Request));
        assert!(
            unmeasured.x > 40.0 && unmeasured.x < 400.0,
            "unmeasured width {} is block-like",
            unmeasured.x
        );
    }

    /// A dragged `FOR` loop is not a rectangle — short head, indented body,
    /// short `END` — and the drop marker has to say so, otherwise it promises a
    /// solid slab nothing like the block in hand.
    #[test]
    fn the_drop_marker_takes_the_shape_of_the_block_being_dropped() {
        let ctx = egui::Context::default();
        ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        // A loop's silhouette, relative to its own top-left.
        let shape = vec![
            egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(140.0, 24.0)),
            egui::Rect::from_min_size(egui::pos2(24.0, 24.0), egui::vec2(180.0, 24.0)),
            egui::Rect::from_min_size(egui::pos2(0.0, 48.0), egui::vec2(50.0, 24.0)),
        ];
        let origin = egui::pos2(30.0, 100.0);
        let out = ctx.run_ui(egui::RawInput::default(), |ui| {
            paint_drop_silhouette(
                ui,
                origin,
                &shape,
                egui::Rect::from_min_size(origin, egui::vec2(400.0, 72.0)),
                &th,
            );
        });

        let painted: Vec<egui::Rect> = out
            .shapes
            .iter()
            .filter_map(|c| match &c.shape {
                egui::Shape::Rect(r) => Some(r.rect),
                _ => None,
            })
            .collect();
        assert_eq!(painted.len(), 3, "one rect per row, not one bounding box");
        for (drawn, want) in painted.iter().zip(&shape) {
            assert_eq!(
                drawn.left(),
                origin.x + want.left(),
                "the row keeps its own indent"
            );
            assert_eq!(drawn.width(), want.width(), "the row keeps its own width");
        }
        // The stepped outline really is stepped: the three rows differ.
        assert_ne!(painted[0].left(), painted[1].left());
        assert_ne!(painted[0].width(), painted[2].width());
        // A bounding-box marker would have covered this corner; the silhouette
        // does not.
        let under_the_end = egui::pos2(origin.x + 150.0, origin.y + 60.0);
        assert!(
            !painted.iter().any(|r| r.contains(under_the_end)),
            "the marker filled in a gap the block does not occupy"
        );
    }

    /// While the gap animates open the marker is *revealed*, never stretched —
    /// a block that grew from a sliver to full height would read as the block
    /// changing size on the way in.
    #[test]
    fn a_half_open_drop_marker_is_clipped_not_stretched() {
        let ctx = egui::Context::default();
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let shape = vec![
            egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(140.0, 24.0)),
            egui::Rect::from_min_size(egui::pos2(0.0, 24.0), egui::vec2(140.0, 24.0)),
        ];
        let origin = egui::pos2(0.0, 0.0);
        let clipped = |h: f32| -> Vec<(egui::Rect, egui::Rect)> {
            ctx.run_ui(egui::RawInput::default(), |ui| {
                paint_drop_silhouette(
                    ui,
                    origin,
                    &shape,
                    egui::Rect::from_min_size(origin, egui::vec2(400.0, h)),
                    &th,
                );
            })
            .shapes
            .iter()
            .filter_map(|c| match &c.shape {
                egui::Shape::Rect(r) => Some((r.rect, c.clip_rect)),
                _ => None,
            })
            .collect()
        };

        let full = clipped(48.0);
        let half = clipped(20.0);
        assert_eq!(full.len(), half.len(), "the same rows are always emitted");
        for (a, b) in full.iter().zip(&half) {
            assert_eq!(a.0, b.0, "the row's own geometry never changes");
        }
        assert!(
            half[0].1.height() < full[0].1.height(),
            "the half-open marker is held back by a shorter clip"
        );
    }

    /// A raw input with a pointer sitting at `pos` and a real screen rect, so
    /// `Context::pointer_interact_pos` reports something during the test frame.
    fn input_with_pointer(pos: egui::Pos2) -> egui::RawInput {
        egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(1000.0, 800.0),
            )),
            events: vec![egui::Event::PointerMoved(pos)],
            ..Default::default()
        }
    }

    /// Every part of a picked-up subtree must move by the *same* delta.
    ///
    /// Regression test for dragging a whole `FOR` loop: the transform used to be
    /// applied from inside the head row, and `Context::transform_layer_shapes`
    /// only moves the shapes *already in* the layer — so the loop's body and its
    /// `END`, painted after the head, stayed at their layout positions while the
    /// head alone tracked the cursor, making the parts of one block appear to
    /// move at different speeds.
    #[test]
    fn a_dragged_subtree_moves_every_row_by_the_same_delta() {
        let ctx = egui::Context::default();
        let head_rect = egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(120.0, 20.0));
        let body_rect = egui::Rect::from_min_size(egui::pos2(10.0, 34.0), egui::vec2(120.0, 20.0));
        let end_rect = egui::Rect::from_min_size(egui::pos2(10.0, 58.0), egui::vec2(120.0, 20.0));
        let fills = [
            Color32::from_rgb(1, 2, 3),
            Color32::from_rgb(4, 5, 6),
            Color32::from_rgb(7, 8, 9),
        ];
        let rects = [head_rect, body_rect, end_rect];
        let pointer = egui::pos2(400.0, 300.0);

        // Two passes: egui settles its layout/ids on the first frame.
        let mut out = ctx.run_ui(input_with_pointer(pointer), |_| {});
        for _ in 0..2 {
            out = ctx.run_ui(input_with_pointer(pointer), |ui| {
                let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("pt_test_drag"));
                let mut lift = DragLift::default();
                // Exactly what `block_row` does for a lifted row: paint it into
                // the shared drag layer, then hand it to the lift.
                for (i, (rect, fill)) in rects.iter().zip(fills).enumerate() {
                    ui.scope_builder(egui::UiBuilder::new().layer_id(layer), |ui| {
                        ui.painter()
                            .rect_filled(*rect, egui::CornerRadius::ZERO, fill);
                    });
                    lift.add(layer, *rect, i == 0);
                }
                lift.follow_pointer(ui.ctx());
            });
        }

        let painted = |fill: Color32| -> egui::Rect {
            out.shapes
                .iter()
                .find_map(|clipped| match &clipped.shape {
                    egui::Shape::Rect(r) if r.fill == fill => Some(r.rect),
                    _ => None,
                })
                .unwrap_or_else(|| panic!("no rect painted with fill {fill:?}"))
        };

        let deltas: Vec<egui::Vec2> = rects
            .iter()
            .zip(fills)
            .map(|(rect, fill)| painted(fill).min - rect.min)
            .collect();
        for (i, delta) in deltas.iter().enumerate() {
            assert!(
                (*delta - deltas[0]).length() < 0.5,
                "row {i} moved by {delta:?}, head moved by {:?}",
                deltas[0]
            );
        }
        // The subtree really did move (a no-op transform would trivially pass
        // the equal-delta check above), anchored with the head on the pointer.
        assert!(deltas[0].length() > 1.0, "the subtree never moved");
        assert!(
            (painted(fills[0]).center() - pointer).length() < 0.5,
            "the head is not centred on the pointer"
        );
    }

    /// The lift measures the whole subtree, not just its head, and keeps each
    /// row separately — that silhouette is what the drop markers take the shape
    /// of.
    #[test]
    fn the_lift_records_the_whole_subtrees_silhouette_for_the_drop_marker() {
        let ctx = egui::Context::default();
        // A `FOR` loop's real shape: a head, an indented (and here narrower)
        // body row, then the `END` back at the head's indent.
        let rects = [
            egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(120.0, 20.0)),
            egui::Rect::from_min_size(egui::pos2(20.0, 34.0), egui::vec2(90.0, 20.0)),
            egui::Rect::from_min_size(egui::pos2(10.0, 58.0), egui::vec2(60.0, 20.0)),
        ];
        let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("pt_test_measure"));
        let mut lift = DragLift::default();
        for (i, rect) in rects.iter().enumerate() {
            lift.add(layer, *rect, i == 0);
        }
        lift.follow_pointer(&ctx);
        let stored: Vec<egui::Rect> = ctx
            .data(|d| d.get_temp(lifted_shape_id()))
            .expect("the lift stashed a silhouette");
        // One rect per row, positioned relative to the subtree's own top-left,
        // so the whole thing spans 0.0 → 68.0 rather than the head's 20.0.
        assert_eq!(stored.len(), rects.len());
        assert_eq!(stored[0].min, egui::pos2(0.0, 0.0));
        assert_eq!(stored.last().unwrap().bottom(), 68.0);
        // The body row keeps its own indent and width — that stepped outline is
        // the whole point of storing rows rather than a bounding box.
        assert_eq!(stored[1].min, egui::pos2(10.0, 24.0));
        assert_eq!(stored[1].width(), 90.0);

        // And with nothing in hand the measurement is forgotten, so the next
        // drag's first frame can't inherit this (bigger) block's shape.
        DragLift::default().follow_pointer(&ctx);
        assert_eq!(
            ctx.data(|d| d.get_temp::<Vec<egui::Rect>>(lifted_shape_id())),
            None
        );
    }

    /// The drop gap is sized to the block actually being dragged: one row for a
    /// plain palette block, two for a `FOR` (which inserts a head *and* its
    /// `END`), and the measured subtree height when an existing block is moved.
    #[test]
    fn the_drop_ghost_is_sized_to_the_block_being_dragged() {
        let measure = |setup: &dyn Fn(&egui::Context)| -> f32 {
            let ctx = egui::Context::default();
            ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
            let mut h = 0.0;
            for _ in 0..2 {
                setup(&ctx);
                let _ = ctx.run_ui(egui::RawInput::default(), |ui| h = dragged_block_h(ui));
            }
            h
        };

        let idle = measure(&|_| {});
        let leaf = measure(&|ctx| egui::DragAndDrop::set_payload(ctx, NodeKind::Request));
        let loop_kind = measure(&|ctx| egui::DragAndDrop::set_payload(ctx, NodeKind::ForFiles));
        let moved_subtree = measure(&|ctx| {
            egui::DragAndDrop::set_payload(ctx, DragItem::Row(vec![0]));
            ctx.data_mut(|d| {
                d.insert_temp(
                    lifted_shape_id(),
                    vec![egui::Rect::from_min_size(
                        egui::Pos2::ZERO,
                        egui::vec2(120.0, 137.0),
                    )],
                )
            });
        });

        assert!(idle > 0.0);
        assert_eq!(leaf, idle, "a plain palette block opens a one-row gap");
        assert_eq!(
            loop_kind,
            idle * 2.0,
            "a FOR block inserts a head and an END, so its gap is two rows"
        );
        assert_eq!(
            moved_subtree, 137.0,
            "an existing block's gap matches its measured height"
        );
    }

    /// A measured height smaller than a single block (a stale/degenerate
    /// reading) never shrinks the ghost below one row.
    #[test]
    fn a_degenerate_measurement_never_shrinks_the_drop_ghost_below_one_block() {
        let ctx = egui::Context::default();
        ctx.all_styles_mut(|s| s.spacing.button_padding = egui::vec2(8.0, 4.0));
        let mut h = 0.0;
        let mut one = 0.0;
        for _ in 0..2 {
            egui::DragAndDrop::set_payload(&ctx, DragItem::Row(vec![0]));
            ctx.data_mut(|d| {
                d.insert_temp(
                    lifted_shape_id(),
                    vec![egui::Rect::from_min_size(
                        egui::Pos2::ZERO,
                        egui::vec2(120.0, 1.0),
                    )],
                )
            });
            let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                h = dragged_block_h(ui);
                one = chip_h(ui) + 10.0;
            });
        }
        assert_eq!(h, one);
    }
}

/// The `FOR` loop head's inline editors: which parts of a loop the chip breaks
/// out into boxes, and which it leaves as plain text for the wizard.
#[cfg(test)]
mod loop_chip_tests {
    use super::{ChipEdit, LoopEdit, node_chips};
    use crate::gui::theme::GuiTheme;
    use crate::i18n::{Language, Strings};

    /// The `LoopEdit` the first node of `src` builds its head chip from.
    fn loop_edit(src: &str) -> LoopEdit {
        let flow = crate::report::parser::parse_flow(src).expect("the fixture flow parses");
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = Strings::for_language(&Language::English);
        node_chips(&flow.nodes[0], None, &th, &s)
            .into_iter()
            .find_map(|c| match c.edit {
                ChipEdit::Loop(l) => Some(l),
                _ => None,
            })
            .expect("a loop renders a loop-head chip")
    }

    /// The commonest loop: every part of it is a box.
    #[test]
    fn a_files_loop_offers_boxes_for_its_variable_folder_and_glob() {
        let l = loop_edit("FOR doc IN FILES \"cases\" MATCH \"*.json\"\n  REQUEST A\nEND\n");
        assert_eq!(l.var.as_deref(), Some("doc"));
        assert_eq!(l.keyword, "IN FILES");
        assert_eq!(
            l.dir,
            Some(("cases".to_string(), false)),
            "the folder is editable and picked with a *folder* dialog"
        );
        assert_eq!(l.glob.as_deref(), Some("*.json"));
        assert!(l.tail.is_empty(), "nothing is left over as dead text");
    }

    /// A `FILES` loop with no `MATCH` still offers the glob box: an empty box
    /// invites the glob, where nothing at all hides that the loop can be
    /// narrowed at all.
    #[test]
    fn a_files_loop_without_a_match_still_offers_an_empty_glob_box() {
        let l = loop_edit("FOR f IN FILES \"cases\"\n  REQUEST A\nEND\n");
        assert_eq!(l.glob.as_deref(), Some(""));
    }

    /// `TUPLES FROM` names a file, not a folder, so its picker must be a file
    /// dialog — a folder picker could not select `rows.csv` at all.
    #[test]
    fn a_tuples_loop_picks_a_file_rather_than_a_folder() {
        let l = loop_edit("FOR row IN TUPLES FROM \"rows.csv\"\n  REQUEST A\nEND\n");
        assert_eq!(l.keyword, "IN TUPLES FROM");
        assert_eq!(l.dir, Some(("rows.csv".to_string(), true)));
        assert_eq!(l.glob, None, "a tuples loop has no glob to offer");
    }

    /// A `FOLDERS … WITH role="glob"` list is several named globs rather than
    /// one, so it stays with the wizard and is shown as plain text. Its single
    /// `MATCH` glob, however, is the same one box `FILES` gets -- offered empty
    /// when the loop has none, so the way to narrow the walk is visible.
    #[test]
    fn a_folders_loops_role_list_is_left_as_text_beside_its_editable_folder() {
        let l = loop_edit("FOR d IN FOLDERS \"envs\" WITH req=\"*.hurl\"\n  REQUEST A\nEND\n");
        assert_eq!(l.dir, Some(("envs".to_string(), false)));
        assert_eq!(l.glob, Some(String::new()));
        assert_eq!(l.tail, "WITH req=\"*.hurl\"");
    }

    /// A recursive, filtered `FOLDERS` walk: the `MATCH` glob fills the same box
    /// `FILES` uses, and an optional role keeps its `?` in the tail so the chip
    /// reads back exactly what the file says.
    #[test]
    fn a_folders_loop_shows_its_match_glob_in_the_glob_box() {
        let l = loop_edit(
            "FOR d IN FOLDERS \"cases\" MATCH \"**/case_*\" WITH front=\"*f.jpg\", back=\"*b.jpg\"?\n  REQUEST A\nEND\n",
        );
        assert_eq!(l.glob, Some("**/case_*".to_string()));
        assert_eq!(l.tail, "WITH front=\"*f.jpg\", back=\"*b.jpg\"?");
    }

    /// A pattern that binds more than one name has no single thing a box could
    /// rename, so no box is offered -- rather than one that silently renamed
    /// whichever binder came first.
    #[test]
    fn a_destructuring_loop_offers_no_variable_box() {
        let l = loop_edit("FOR (NAME, URL) IN DOCS\n  REQUEST A\nEND\n");
        assert_eq!(l.var, None);
        assert_eq!(l.tail, "DOCS", "the source is still shown");
    }

    /// A producer with no single path keeps the text it always had, so nothing
    /// disappears from the head just because it can't be boxed.
    #[test]
    fn a_list_literal_keeps_its_text_and_offers_no_folder_picker() {
        let l = loop_edit("FOR x IN [\"a\", \"b\"]\n  REQUEST A\nEND\n");
        assert_eq!(l.var.as_deref(), Some("x"));
        assert_eq!(l.keyword, "IN");
        assert_eq!(l.dir, None, "there is no one folder to pick");
        assert_eq!(l.tail, "[\"a\", \"b\"]");
    }

    /// An ENVS loop's variable is editable, but its roles are chips of their
    /// own beside the head, so the head carries no tail for them.
    #[test]
    fn an_envs_loop_offers_its_variable_box_and_leaves_the_roles_to_their_chips() {
        let l = loop_edit(
            "FOR TARGET IN ENVS BASELINE(\"prod\"), COMPARISON(\"stage\")\n  REQUEST A\nEND\n",
        );
        assert_eq!(l.var.as_deref(), Some("TARGET"));
        assert_eq!(l.keyword, "IN ENVS");
        assert_eq!(l.dir, None);
        assert!(
            l.tail.is_empty(),
            "BASELINE/COMPARISON are chips, not text on the head"
        );
    }

    /// A plain list of environments has no chips of its own, so it must stay
    /// visible on the head rather than vanishing.
    #[test]
    fn an_envs_loop_over_named_environments_still_shows_them() {
        let l = loop_edit("FOR e IN ENVS \"dev\", \"prod\"\n  REQUEST A\nEND\n");
        assert_eq!(l.var.as_deref(), Some("e"));
        assert_eq!(l.tail, "\"dev\", \"prod\"");
    }

    /// A `PARALLEL` loop's head is built from the node, not from its label, so
    /// the prefix belongs to the PARALLEL chip alone and is never repeated.
    #[test]
    fn a_parallel_loops_head_does_not_repeat_the_parallel_prefix() {
        let l = loop_edit("PARALLEL(4) FOR f IN FILES \"cases\"\n  REQUEST A\nEND\n");
        assert_eq!(l.var.as_deref(), Some("f"));
        assert_eq!(l.keyword, "IN FILES");
        assert!(!l.tail.contains("PARALLEL"));
    }
}

#[cfg(test)]
mod baseline_show_chip_tests {
    use super::{
        CHIP_RADIUS, Chip, Color32, DetachWhich, ROUND_CHIP, chip_corners, link_tethers,
        node_chips, split_tether,
    };
    use crate::gui::theme::GuiTheme;
    use crate::i18n::{Language, Strings};

    /// The chip labels a flow's first node renders as.
    fn chip_labels(src: &str) -> Vec<String> {
        let flow = crate::report::parser::parse_flow(src).expect("the fixture flow parses");
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = Strings::for_language(&Language::English);
        node_chips(&flow.nodes[0], None, &th, &s)
            .into_iter()
            .map(|c| c.text)
            .collect()
    }

    #[test]
    fn a_baselines_show_clause_is_chipped_between_the_baseline_and_the_comparison() {
        let chips = chip_labels(
            "FOR TARGET IN ENVS BASELINE(\"prod\") SHOW(Time, Status), COMPARISON(\"stage\")\n    REQUEST A\nEND\n",
        );
        let at = |needle: &str| {
            chips
                .iter()
                .position(|c| c.contains(needle))
                .unwrap_or_else(|| panic!("expected a {needle} chip in {chips:?}"))
        };
        assert!(
            at("prod") < at("SHOW(") && at("SHOW(") < at("stage"),
            "the SHOW sits with the BASELINE it belongs to, not the comparison: {chips:?}"
        );
        assert!(
            chips.iter().any(|c| c == "SHOW(Time, Status)"),
            "and it names the fields it selects: {chips:?}"
        );
    }

    #[test]
    fn the_baselines_show_is_tethered_to_it_and_keeps_its_own_colour() {
        let flow = crate::report::parser::parse_flow(
            "FOR TARGET IN ENVS BASELINE(\"prod\") SHOW(Time), COMPARISON(\"stage\")\n    REQUEST A\nEND\n",
        )
        .expect("the fixture flow parses");
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let s = Strings::for_language(&Language::English);
        let mut chips = node_chips(&flow.nodes[0], None, &th, &s);

        let show_at = chips
            .iter()
            .position(|c| c.text.starts_with("SHOW("))
            .expect("the SHOW is chipped");
        assert!(
            chips[show_at].tethered,
            "it is tied to the chip before it, not left floating between three peers"
        );
        assert!(
            chips[show_at - 1].text.contains("prod"),
            "and the chip it is tied to is the BASELINE, so the tie says who owns it"
        );

        link_tethers(&mut chips);
        let (baseline, show) = (&chips[show_at - 1], &chips[show_at]);
        assert!(
            baseline.join_next && show.join_prev,
            "the pair is drawn as one segmented pill rather than two loose chips"
        );
        assert!(
            !chips
                .iter()
                .any(|c| c.text.starts_with("COMPARISON(") && (c.join_prev || c.join_next)),
            "but the COMPARISON stays a peer — it qualifies the loop, not the baseline"
        );
        assert_eq!(
            show.color, th.ok,
            "and the SHOW keeps the colour every SHOW has, so it stays recognisable \
             as a SHOW — the pill is what says which chip it belongs to"
        );
        assert_ne!(
            show.color, baseline.color,
            "so the two halves are still told apart at a glance"
        );
    }

    #[test]
    fn a_tethered_chip_squares_off_only_the_edge_it_shares() {
        let mut chips = vec![
            Chip::modifier(
                "BASELINE(prod)".into(),
                Color32::RED,
                DetachWhich::Statistics,
            ),
            Chip::modifier(
                "SHOW(Time)".into(),
                Color32::GREEN,
                DetachWhich::BaselineShow,
            )
            .tether(),
        ];
        link_tethers(&mut chips);

        let (left, right) = (chip_corners(&chips[0]), chip_corners(&chips[1]));
        assert_eq!(
            (left.nw, left.sw, right.ne, right.se),
            (CHIP_RADIUS, CHIP_RADIUS, CHIP_RADIUS, CHIP_RADIUS),
            "the outside of the pair stays rounded, so it reads as a single pill"
        );
        assert_eq!(
            (left.ne, left.se, right.nw, right.sw),
            (0, 0, 0, 0),
            "and the meeting edges are square, so no gap or bulge shows between the halves"
        );
    }

    #[test]
    fn a_pair_being_pulled_apart_is_no_longer_drawn_joined() {
        let mut chips = vec![
            Chip::modifier(
                "BASELINE(prod)".into(),
                Color32::RED,
                DetachWhich::Statistics,
            ),
            Chip::modifier(
                "SHOW(Time)".into(),
                Color32::GREEN,
                DetachWhich::BaselineShow,
            )
            .tether(),
        ];
        link_tethers(&mut chips);
        split_tether(&mut chips, 1);

        assert!(
            !chips[0].join_next && !chips[1].join_prev,
            "a squared-off edge facing an empty slot would look like damage, not a join"
        );
        assert!(
            !chips[1].tethered,
            "and the pair falls back to the normal gap, so the row does not close up around the hole"
        );
        assert_eq!(
            chip_corners(&chips[0]),
            ROUND_CHIP,
            "the chip left behind is a whole chip again"
        );
    }

    #[test]
    fn a_baseline_without_a_show_clause_gets_no_show_chip() {
        let chips = chip_labels(
            "FOR TARGET IN ENVS BASELINE(\"prod\"), COMPARISON(\"stage\")\n    REQUEST A\nEND\n",
        );
        assert!(
            !chips.iter().any(|c| c.starts_with("SHOW(")),
            "no clause, no chip — an empty SHOW would claim a restriction that isn't there: {chips:?}"
        );
    }
}

#[cfg(test)]
mod results_table_tests {
    use super::{MIN_COL_W, fit_column_widths};

    /// Total width of a laid-out table, gaps included.
    fn spanned(widths: &[f32], spacing: f32) -> f32 {
        widths.iter().sum::<f32>() + spacing * (widths.len() as f32 - 1.0)
    }

    #[test]
    fn a_table_with_room_to_spare_grows_to_fill_the_whole_window() {
        let widths = fit_column_widths(&[60.0, 100.0, 40.0], 800.0, 10.0);
        assert!(
            (spanned(&widths, 10.0) - 800.0).abs() < 0.01,
            "the table spans the full width instead of huddling at the left edge: {widths:?}"
        );
        assert!(
            widths[1] > widths[0] && widths[0] > widths[2],
            "and the spare room is shared in proportion, so the column order is unchanged: {widths:?}"
        );
    }

    #[test]
    fn a_squeezed_table_takes_the_room_from_its_widest_columns_first() {
        // A narrow status column beside a sprawling body column: shrinking both
        // by the same proportion would leave the status column unreadable for
        // no gain, so only the greedy one should give ground.
        let widths = fit_column_widths(&[50.0, 600.0], 400.0, 10.0);
        assert!(
            (widths[0] - 50.0).abs() < 0.01,
            "the column that was already narrow is left alone: {widths:?}"
        );
        assert!(
            widths[1] < 600.0,
            "and the wide one absorbs the whole squeeze: {widths:?}"
        );
        assert!(
            spanned(&widths, 10.0) <= 400.01,
            "so everything still fits on screen: {widths:?}"
        );
    }

    #[test]
    fn columns_that_all_want_the_same_width_are_squeezed_equally() {
        let widths = fit_column_widths(&[300.0, 300.0, 300.0], 600.0, 0.0);
        for w in &widths {
            assert!(
                (w - 200.0).abs() < 0.01,
                "with nothing to choose between them they share the shortfall: {widths:?}"
            );
        }
    }

    #[test]
    fn a_table_too_wide_even_for_its_minimums_overflows_so_it_can_be_scrolled() {
        // Twenty columns can't be made readable in 200 pixels. Rather than
        // grinding them all to slivers, the widths overrun the viewport and the
        // caller's horizontal scroll bar takes over.
        let widths = fit_column_widths(&[100.0; 20], 200.0, 0.0);
        for w in &widths {
            assert!(
                *w >= MIN_COL_W,
                "no column is shrunk past the point of showing anything: {widths:?}"
            );
        }
        assert!(
            spanned(&widths, 0.0) > 200.0,
            "the overflow is what makes the scroll bar appear: {widths:?}"
        );
    }

    #[test]
    fn a_table_with_no_columns_is_not_a_division_by_zero() {
        assert!(
            fit_column_widths(&[], 500.0, 10.0).is_empty(),
            "an empty report lays out to nothing rather than panicking"
        );
    }
}

#[cfg(test)]
mod results_render_tests {
    use super::{MIN_COL_W, SPACING_X, fitted_column_widths, results_grid};
    use crate::gui::theme::GuiTheme;
    use crate::i18n::Language;
    use crate::report::model::{OutputColumn, ReportResult, ReportRow};
    use eframe::egui;

    /// A result of `rows` rows whose every cell in column `c` holds `fills[c]`.
    fn fixture(headers: &[&str], fills: &[&str], rows: usize) -> (ReportResult, Vec<OutputColumn>) {
        let columns: Vec<OutputColumn> = headers
            .iter()
            .map(|h| OutputColumn {
                header: h.to_string(),
                sources: vec![h.to_string()],
                stats: Vec::new(),
                image: None,
                truth: None,
                detail: false,
            })
            .collect();
        let mut result = ReportResult::default();
        for _ in 0..rows {
            let mut row = ReportRow::default();
            for (h, v) in headers.iter().zip(fills) {
                row.cells.insert(h.to_string(), v.to_string());
            }
            result.rows.push(row);
        }
        (result, columns)
    }

    /// A streaming run must not be filtered: `visible_rows` drops pending rows,
    /// so a live filter would hide the very rows the reader is watching arrive.
    #[test]
    fn a_live_run_is_shown_unfiltered() {
        let (result, columns) = fixture(&["A"], &["x"], 3);
        let header = crate::report::flow::Header::default();
        let mut sel = 0;
        assert!(
            super::visible_for_view(&result, &columns, &header, true, &mut sel, "").is_none(),
            "a live run shows every row it has, filters and all"
        );
    }

    /// The find box narrows the rows the filter chose, over the columns that are
    /// actually shown.
    #[test]
    fn the_find_box_narrows_the_rows() {
        let (mut result, columns) = fixture(&["A"], &["x"], 3);
        result.rows[1]
            .cells
            .insert("A".to_string(), "needle".to_string());
        let header = crate::report::flow::Header::default();
        let mut sel = 0;
        let all = super::visible_for_view(&result, &columns, &header, false, &mut sel, "").unwrap();
        assert_eq!(all, vec![0, 1, 2], "no text means no narrowing");
        let hit =
            super::visible_for_view(&result, &columns, &header, false, &mut sel, "NEED").unwrap();
        assert_eq!(hit, vec![1], "and the search is case-insensitive");
    }

    /// The filter selection is an index into a list derived from the *result*,
    /// so a selection made against a richer result must not index past the end
    /// of a plainer one (or silently select the wrong filter).
    #[test]
    fn a_stale_filter_selection_is_clamped_rather_than_panicking() {
        let (result, columns) = fixture(&["A"], &["x"], 2);
        let header = crate::report::flow::Header::default();
        // A plain result offers only `All`, so index 3 cannot stand.
        let mut sel = 3;
        let rows =
            super::visible_for_view(&result, &columns, &header, false, &mut sel, "").unwrap();
        assert_eq!(sel, 0, "clamped back onto the only filter there is");
        assert_eq!(rows, vec![0, 1], "which selects everything");
    }

    /// The in-app bar translates its own buttons; the exported document's stay
    /// English because it has no reader whose language is known.
    #[test]
    fn the_filter_buttons_are_translated_but_a_matrix_cell_is_not() {
        use crate::report::filter::RowFilter;
        let s = crate::i18n::Strings::for_language(&Language::French);
        assert_eq!(
            super::filter_label(&s, &RowFilter::Incorrect),
            s.report_filter_incorrect
        );
        let cell = RowFilter::MatrixCell {
            column: "Verdict".to_string(),
            truth: "pass".to_string(),
            answer: "fail".to_string(),
        };
        assert_eq!(
            super::filter_label(&s, &cell),
            cell.label(),
            "a matrix cell names the report's own data, which is not translatable"
        );
    }

    /// The GUI grid and the export must agree about which columns are where:
    /// a column that vanished from one and not the other reads as a bug in
    /// whichever you noticed second.
    #[test]
    fn the_grid_drops_the_same_detail_columns_the_export_does() {
        let (_, mut columns) = fixture(&["Name", "Body"], &["a", "{}"], 1);
        columns[1].detail = true;
        let (grid, detail) = crate::report::detail::split_columns(&columns);
        assert_eq!(
            grid.iter().map(|c| &c.header).collect::<Vec<_>>(),
            vec!["Name"],
            "the detail column is not in the grid"
        );
        assert_eq!(detail.len(), 1, "it is in the panel instead");
    }

    /// A row with nothing to drill into gets no expander, so the caret is never
    /// an invitation to open an empty panel.
    #[test]
    fn only_rows_with_something_to_show_are_expandable() {
        let (mut result, mut columns) = fixture(&["Name", "Body"], &["a", ""], 2);
        columns[1].detail = true;
        result.rows[1]
            .cells
            .insert("Body".to_string(), "{\"a\":1}".to_string());
        let (grid, detail) = crate::report::detail::split_columns(&columns);
        assert!(
            crate::report::detail::sections(&result, 0, &grid, &detail).is_empty(),
            "the row with a blank body has nothing to show"
        );
        assert!(
            !crate::report::detail::sections(&result, 1, &grid, &detail).is_empty(),
            "the row with a body does"
        );
    }

    /// The drill-down's sections are laid across the pane the way the HTML
    /// export's flex row does: side by side while each still gets a readable
    /// width, one column when the pane is narrow, and never more columns than
    /// there are sections to fill them.
    #[test]
    fn detail_sections_share_the_width_they_have() {
        let w = super::DETAIL_MIN_SECTION_W;
        assert_eq!(
            super::detail_layout_columns(w * 2.5, w, 4),
            2,
            "two whole sections fit, so two columns"
        );
        assert_eq!(
            super::detail_layout_columns(w * 0.5, w, 4),
            1,
            "a pane narrower than one section still gets one column, not zero"
        );
        assert_eq!(
            super::detail_layout_columns(w * 4.0, w, 2),
            2,
            "four would fit but there are only two sections to put in them"
        );
        assert_eq!(
            super::detail_layout_columns(w * 4.0, w, 0),
            1,
            "an empty panel never asks for zero columns"
        );
    }

    /// The source editor asks its layouter for a job on every frame, so the job
    /// is cached — but it has to follow every input the highlighter colours by.
    #[test]
    fn the_highlight_key_notices_every_input_it_guards() {
        use crate::tui::report_highlight::HlCtx;
        let text = "REPORT REQUEST login AS l\n";
        let ctx = HlCtx {
            error_line: None,
            collection_resolves: true,
            loaded_envs: ["dev".to_string()].into_iter().collect(),
            request_names: ["login".to_string()].into_iter().collect(),
        };
        let spec = crate::theme::default_preset();
        let font = egui::FontId::monospace(12.0);
        let key = |t: &str, c: &HlCtx, s: &crate::theme::ThemeSpec, f: &egui::FontId, w: f32| {
            super::highlight_key(t, c, s, f, w)
        };
        let base = key(text, &ctx, &spec, &font, 800.0);

        assert_ne!(
            base,
            key("REPORT REQUEST logout AS l\n", &ctx, &spec, &font, 800.0),
            "the source text"
        );

        let mut c = ctx.clone();
        c.error_line = Some(1);
        assert_ne!(base, key(text, &c, &spec, &font, 800.0), "the error line");

        c.error_line = None;
        c.collection_resolves = false;
        assert_ne!(
            base,
            key(text, &c, &spec, &font, 800.0),
            "whether the collection binds — it is what makes a name green"
        );

        c.collection_resolves = true;
        c.request_names = ["other".to_string()].into_iter().collect();
        assert_ne!(
            base,
            key(text, &c, &spec, &font, 800.0),
            "which requests exist"
        );

        c.request_names = ctx.request_names.clone();
        c.loaded_envs = ["prod".to_string()].into_iter().collect();
        assert_ne!(
            base,
            key(text, &c, &spec, &font, 800.0),
            "which environments are loaded"
        );

        let other_theme = crate::theme::preset_for_language(&crate::i18n::Language::French);
        assert_ne!(
            base,
            key(text, &ctx, &other_theme, &font, 800.0),
            "the theme, which is where every colour comes from"
        );

        assert_ne!(
            base,
            key(text, &ctx, &spec, &egui::FontId::monospace(18.0), 800.0),
            "the font size"
        );
        assert_ne!(
            base,
            key(text, &ctx, &spec, &font, 400.0),
            "the wrap width, which the job carries"
        );

        // Two contexts holding the same names in a different insertion order are
        // the same context: both are hash sets, and iterating one straight into
        // the hasher is what made the validation panel flicker.
        let mut same = ctx.clone();
        same.request_names.insert("zzz".to_string());
        same.request_names.remove("zzz");
        assert_eq!(
            base,
            key(text, &same, &spec, &font, 800.0),
            "the same set is the same key"
        );
    }

    /// Render the grid twice in one context, so the second pass sees whatever
    /// the first left in egui's memory, and report the widths each time.
    fn widths_across_two_frames(
        first: &(ReportResult, Vec<OutputColumn>),
        then: impl FnOnce(&mut ReportResult),
    ) -> (Vec<f32>, Vec<f32>) {
        let ctx = egui::Context::default();
        let (mut result, columns) = (first.0.clone(), first.1.clone());
        let mut a = Vec::new();
        let mut b = Vec::new();
        let draw = |ctx: &egui::Context, result: &ReportResult, out: &mut Vec<f32>| {
            for _ in 0..2 {
                let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                    ui.set_max_width(4000.0);
                    ui.set_min_width(4000.0);
                    // The *natural* widths are what is cached; fitting them to
                    // the window is pure arithmetic on top.
                    *out = super::cached_natural_widths(ui, result, &columns);
                });
            }
        };
        draw(&ctx, &result, &mut a);
        then(&mut result);
        draw(&ctx, &result, &mut b);
        (a, b)
    }

    /// The widths are cached between frames, and a streaming run replaces its
    /// rows **in place** — the grid starts as a skeleton of empty rows that are
    /// overwritten as results arrive. A cache keyed on anything less than the
    /// cell text would therefore pin the columns at the width of an empty table
    /// for the whole run.
    #[test]
    fn cached_widths_follow_a_row_that_is_filled_in_place() {
        let empty = fixture(&["Result"], &[""], 4);
        let (before, after) = widths_across_two_frames(&empty, |result| {
            for row in &mut result.rows {
                row.cells.insert(
                    "Result".to_string(),
                    "a much longer value than the header".to_string(),
                );
            }
        });
        assert!(
            after[0] > before[0] + 20.0,
            "the column grew for the arriving values: {before:?} then {after:?}"
        );
    }

    /// The same table two frames running must measure the same, or the columns
    /// would twitch as the mouse moves.
    #[test]
    fn cached_widths_are_stable_when_nothing_changes() {
        let table = fixture(&["A", "B"], &["one", "two"], 5);
        let (before, after) = widths_across_two_frames(&table, |_| {});
        assert_eq!(before, after);
    }

    /// The fingerprint is hand-maintained, so it gets the same contract test the
    /// validation cache has: it must move for every input the measurement reads.
    #[test]
    fn the_width_fingerprint_notices_every_input_it_guards() {
        let ctx = egui::Context::default();
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            let (base_res, base_cols) = fixture(&["A"], &["one"], 2);
            let base = super::widths_fingerprint(ui, &base_res, &base_cols);

            let mut r = base_res.clone();
            r.rows[0]
                .cells
                .insert("A".to_string(), "changed".to_string());
            assert_ne!(
                base,
                super::widths_fingerprint(ui, &r, &base_cols),
                "a cell's text"
            );

            let mut r = base_res.clone();
            r.rows.push(ReportRow::default());
            assert_ne!(
                base,
                super::widths_fingerprint(ui, &r, &base_cols),
                "a new row"
            );

            let mut r = base_res.clone();
            r.no_match_marker = "\u{2014}".to_string();
            assert_ne!(
                base,
                super::widths_fingerprint(ui, &r, &base_cols),
                "the no-match marker, which is what an empty cell renders as"
            );

            let mut r = base_res.clone();
            r.rows[0].target = Some("staging".to_string());
            assert_ne!(
                base,
                super::widths_fingerprint(ui, &r, &base_cols),
                "the row's ENVS target"
            );

            let mut r = base_res.clone();
            r.rows[0].vars.insert("v".to_string(), "x".to_string());
            assert_ne!(
                base,
                super::widths_fingerprint(ui, &r, &base_cols),
                "a variable a columns: directive could show"
            );

            let (_, wider) = fixture(&["A Much Longer Header"], &["one"], 2);
            assert_ne!(
                base,
                super::widths_fingerprint(ui, &base_res, &wider),
                "the column header"
            );

            let mut cols = base_cols.clone();
            cols[0].stats = vec![crate::report::model::StatKind::Count];
            assert_ne!(
                base,
                super::widths_fingerprint(ui, &base_res, &cols),
                "statistics, which add summary rows to measure"
            );

            // Two rows whose cells were inserted in a different order are the
            // same table, and must not look like a change: `cells` is a hash
            // map, and iterating one straight into the hasher is exactly what
            // made the validation panel flicker.
            let (a, cols2) = fixture(&["A", "B"], &["one", "two"], 1);
            let mut b = ReportResult::default();
            let mut row = ReportRow::default();
            row.cells.insert("B".to_string(), "two".to_string());
            row.cells.insert("A".to_string(), "one".to_string());
            b.rows.push(row);
            assert_eq!(
                super::widths_fingerprint(ui, &a, &cols2),
                super::widths_fingerprint(ui, &b, &cols2),
                "insertion order is not a difference"
            );
        });
    }

    /// The widths the grid would give `columns` in a window `avail` wide, and
    /// the total they span. Renders for real, so the measurement is the font's
    /// and not a guess.
    fn widths_at(result: &ReportResult, columns: &[OutputColumn], avail: f32) -> (Vec<f32>, f32) {
        let ctx = egui::Context::default();
        let mut widths = Vec::new();
        // Twice: galley measurements only settle once the layout has been seen.
        for _ in 0..2 {
            let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
                ui.set_max_width(avail);
                ui.set_min_width(avail);
                widths = fitted_column_widths(ui, result, columns, false);
            });
        }
        let span = widths.iter().sum::<f32>() + SPACING_X * (widths.len() as f32 - 1.0);
        (widths, span)
    }

    #[test]
    fn a_narrow_table_is_stretched_across_the_whole_window() {
        // Three tiny columns in a wide window: left to themselves they would
        // huddle in the first hundred pixels and leave the rest blank.
        let (result, columns) = fixture(&["A", "B", "C"], &["1", "2", "3"], 3);
        let (widths, span) = widths_at(&result, &columns, 900.0);
        assert!(
            span > 850.0,
            "the table spans essentially the whole 900px window: {widths:?} ({span})"
        );
    }

    #[test]
    fn a_wide_table_is_squeezed_to_stay_inside_the_window() {
        // Six columns of long values in a narrow window have to be cut down
        // rather than run off the right edge — the cell viewer is what recovers
        // whatever the truncation hides.
        let long = "a value long enough to want a column all to itself";
        let (result, columns) = fixture(
            &["One", "Two", "Three", "Four", "Five", "Six"],
            &[long; 6],
            4,
        );
        let (widths, span) = widths_at(&result, &columns, 600.0);
        assert!(
            span <= 600.5,
            "everything fits inside the window: {widths:?} ({span})"
        );
    }

    #[test]
    fn a_column_of_long_values_is_given_more_room_than_a_column_of_short_ones() {
        let (result, columns) = fixture(
            &["Id", "Body"],
            &["7", "a considerably longer captured value"],
            5,
        );
        let (widths, _) = widths_at(&result, &columns, 800.0);
        assert!(
            widths[1] > widths[0] * 2.0,
            "width follows what a column actually has to show: {widths:?}"
        );
    }

    #[test]
    fn a_header_wider_than_its_values_still_gets_room_for_its_own_name() {
        // A column of one-character values under a long header must be sized by
        // the header, or the column would be unidentifiable.
        let (result, columns) = fixture(&["A", "AnUncommonlyLongHeader"], &["1", "2"], 3);
        let (widths, _) = widths_at(&result, &columns, 900.0);
        assert!(
            widths[1] > widths[0],
            "the long header claims the wider column: {widths:?}"
        );
    }

    #[test]
    fn a_table_with_more_columns_than_can_ever_fit_overflows_for_the_scroll_bar() {
        // Thirty columns can't be shown legibly in 400 pixels at any width, so
        // the grid deliberately overruns its window and the scroll area takes
        // over, rather than grinding every column down to an ellipsis.
        let headers: Vec<String> = (0..30).map(|i| format!("Col{i}")).collect();
        let heads: Vec<&str> = headers.iter().map(|h| h.as_str()).collect();
        let (result, columns) = fixture(&heads, &["value"; 30], 2);
        let (widths, span) = widths_at(&result, &columns, 400.0);
        assert!(
            widths.iter().all(|w| *w >= MIN_COL_W),
            "every column keeps a readable minimum: {widths:?}"
        );
        assert!(
            span > 400.0,
            "and the overflow is what puts the scroll bar there: {span}"
        );
    }

    #[test]
    fn drawing_the_grid_itself_survives_a_window_too_narrow_for_one_column() {
        // A pathological pane width must not panic or divide by zero — it just
        // scrolls.
        let (result, columns) = fixture(&["A", "B", "C"], &["1", "2", "3"], 2);
        let ctx = egui::Context::default();
        let th = GuiTheme::from_spec(&crate::theme::preset_for_language(&Language::English));
        let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
            ui.set_max_width(1.0);
            let mut none = None;
            results_grid(&th, ui, &result, &columns, None, None, &[], &mut none);
        });
    }
}

#[cfg(test)]
mod dry_run_view_tests {
    use super::{EditorView, ReportEditor, ReportOrigin};

    /// The reindent button re-indents as a single undo step, and — unlike every
    /// other editor action — must not round-trip through the AST, because the
    /// flow has nowhere to keep a body comment.
    #[test]
    fn reindenting_is_one_undo_step_and_keeps_body_comments() {
        let before = "# collection: c\n\nFOR T IN FILES \"*.txt\"\n# keep me\nREQUEST a\nEND\n";
        let report = crate::report::Report::from_text("r", before);
        let mut ed = ReportEditor::new(ReportOrigin::Session(0), report);

        assert!(matches!(ed.reformat(), Ok(true)), "text moved");
        assert!(
            ed.report.text.contains("    # keep me"),
            "the comment is kept and indented: {:?}",
            ed.report.text
        );
        assert!(
            ed.report.text.contains("    REQUEST a"),
            "the body is indented: {:?}",
            ed.report.text
        );

        // Already tidy the second time, so it costs no further undo entry.
        assert!(matches!(ed.reformat(), Ok(false)));
        ed.undo();
        assert_eq!(ed.report.text, before, "one undo restores the original");
    }

    /// The Dry run button lives on the toolbar, which is above every view, but
    /// the preview is drawn by the Results view. Pressing it from Blocks (where
    /// you build the report, and so where you press it from) has to take you to
    /// the preview — otherwise the button looks dead.
    #[test]
    fn a_dry_run_switches_to_the_view_that_actually_shows_it() {
        let report = crate::report::Report::scratch("r");
        let mut ed = ReportEditor::new(ReportOrigin::Session(0), report);
        assert!(
            ed.view == EditorView::Blocks,
            "an editor opens on the Blocks view"
        );

        ed.show_preview(Box::new(crate::report::dry_run::DryRunReport::from_result(
            crate::report::ReportResult::default(),
            crate::report::flow::Header::default(),
            Vec::new(),
        )));

        assert!(
            ed.view == EditorView::Results,
            "the preview should be on screen, not waiting in a view nobody is looking at"
        );
        assert!(ed.dry_run.is_some(), "and the preview itself is held");
    }
}

#[cfg(test)]
mod detail_verdict_tests {
    use super::*;
    use crate::gui::app::GuiApp;
    use crate::report::model::{OutputColumn, ReportResult, ReportRow, StatKind, Verdict};
    use crate::session::Session;

    /// A `DETAIL` column carrying a `TRUTH` is read in the drill-down, so the
    /// drill-down has to say whether what it is showing was right — the grid
    /// cell that would have said so is not on screen.
    #[test]
    fn a_ground_truthed_detail_section_shows_its_verdict() {
        let mut column = OutputColumn {
            header: "Raw".to_string(),
            sources: vec!["Raw".to_string()],
            stats: Vec::<StatKind>::new(),
            image: None,
            truth: Some("Low Risk".to_string()),
            detail: true,
        };
        column.detail = true;
        let mut row = ReportRow::default();
        row.cells.insert("Raw".to_string(), "High Risk".to_string());
        let mut result = ReportResult {
            column_order: vec!["Raw".into()],
            rows: vec![row],
            ..Default::default()
        };
        result
            .verdicts
            .insert((0, "Raw".into()), Verdict::Incorrect);
        result.truths.insert((0, "Raw".into()), "Low Risk".into());
        let columns = vec![column];
        let (grid, detail) = crate::report::detail::split_columns(&columns);
        let section = crate::report::detail::sections(&result, 0, &grid, &detail)
            .into_iter()
            .next()
            .expect("the detail column has a section");

        let app = GuiApp::for_test(Session::default());
        let th = app.theme.clone();
        let ctx = egui::Context::default();
        let mut input = egui::RawInput::default();
        input.screen_rect = Some(egui::Rect::from_min_size(
            egui::pos2(0.0, 0.0),
            egui::vec2(600.0, 400.0),
        ));
        let mut textures = std::collections::HashMap::new();
        let out = ctx.run_ui(input, |ui| {
            detail_section(&th, ui, &app, 0, section.clone(), &mut textures);
        });
        let mut text = String::new();
        fn walk(s: &egui::epaint::Shape, out: &mut String) {
            match s {
                egui::epaint::Shape::Text(t) => {
                    out.push_str(t.galley.text());
                    out.push('\n');
                }
                egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                _ => {}
            }
        }
        for c in &out.shapes {
            walk(&c.shape, &mut text);
        }
        assert!(
            text.contains("incorrect"),
            "the section says it is wrong: {text}"
        );
        assert!(
            text.contains("expected Low Risk"),
            "and what was wanted instead, which is otherwise only in the script: {text}"
        );
    }
}

#[cfg(test)]
mod toolbar_commit_tests {
    use super::*;
    use crate::gui::app::GuiApp;

    /// Every piece of text painted this frame, with the rect it was painted in,
    /// so a test can click a widget by the label it shows.
    fn painted(shapes: &[egui::epaint::ClippedShape]) -> Vec<(String, egui::Rect)> {
        fn walk(s: &egui::epaint::Shape, out: &mut Vec<(String, egui::Rect)>) {
            match s {
                egui::epaint::Shape::Text(t) => {
                    out.push((t.galley.text().to_string(), t.visual_bounding_rect()))
                }
                egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                _ => {}
            }
        }
        let mut out = Vec::new();
        for c in shapes {
            walk(&c.shape, &mut out);
        }
        out
    }

    fn input() -> egui::RawInput {
        let mut i = egui::RawInput::default();
        i.screen_rect = Some(egui::Rect::from_min_size(
            egui::pos2(0.0, 0.0),
            egui::vec2(1000.0, 760.0),
        ));
        i
    }

    fn click_at(pos: egui::Pos2) -> egui::RawInput {
        let mut i = input();
        i.events.push(egui::Event::PointerMoved(pos));
        i.events.push(egui::Event::PointerButton {
            pos,
            button: egui::PointerButton::Primary,
            pressed: true,
            modifiers: Default::default(),
        });
        i.events.push(egui::Event::PointerButton {
            pos,
            button: egui::PointerButton::Primary,
            pressed: false,
            modifiers: Default::default(),
        });
        i
    }

    /// An app with one bound collection and the given report open in its editor.
    fn app_with_report(text: &str) -> GuiApp {
        let mut session = crate::session::Session::default();
        session.collections.clear();
        let entry = crate::hurl::HurlEntry {
            title: "A".into(),
            url: "http://127.0.0.1:1/".into(),
            ..Default::default()
        };
        session.collections.push(crate::collection::Collection::new(
            "api".into(),
            vec![entry],
        ));
        let mut app = GuiApp::for_test(session);
        let mut report = crate::report::Report::scratch("r");
        report.set_text(text.to_string());
        app.report_editor = Some(ReportEditor::new(ReportOrigin::Session(0), report));
        app
    }

    /// The Source view asks for the highlighter context on every frame, so it
    /// has to come back from the cache until one of the names in it moves.
    #[test]
    fn the_highlighter_context_is_reused_until_a_name_it_shows_changes() {
        let mut app = app_with_report("# collection: api\nREQUEST A\n");
        if let Some(ed) = app.report_editor.as_mut() {
            ed.flow = ed.report.flow().ok();
        }

        let mut ed = app.report_editor.take().expect("editor");
        let first = super::highlight_ctx(&mut ed, &app);
        assert!(
            first.request_names.contains("A"),
            "the bound collection's request is known: {:?}",
            first.request_names
        );
        let again = super::highlight_ctx(&mut ed, &app);
        assert!(
            std::rc::Rc::ptr_eq(&first, &again),
            "nothing changed, so the context is not rebuilt"
        );

        // Renaming a request has to reach the colours.
        app.session.collections[0].entries[0].title = "B".into();
        let renamed = super::highlight_ctx(&mut ed, &app);
        assert!(
            !std::rc::Rc::ptr_eq(&first, &renamed),
            "a rename rebuilds the context"
        );
        assert!(
            renamed.request_names.contains("B"),
            "and the new name is the one highlighted: {:?}",
            renamed.request_names
        );

        // So does loading an environment, which the view underlines by name.
        let before_env = super::highlight_ctx(&mut ed, &app);
        app.session
            .global_envs
            .push(crate::environment::parse_vars("staging".into(), ""));
        let with_env = super::highlight_ctx(&mut ed, &app);
        assert!(
            !std::rc::Rc::ptr_eq(&before_env, &with_env),
            "a newly loaded environment rebuilds the context"
        );
        assert!(with_env.loaded_envs.iter().any(|n| n == "staging"));
    }

    #[test]
    fn export_offers_the_report_s_own_name_the_way_the_tui_does() {
        // The terminal UI seeds its export picker with the report's name and
        // its `# output:` format; the GUI dialog has to agree, or the same
        // report exports under two different names depending on the front-end.
        let mut app = app_with_report("# output: xlsx\n# collection: api\n");
        let dir = std::env::temp_dir().join(format!("pb_exp_{}", std::process::id()));
        std::fs::create_dir_all(&dir).ok();
        let trail = dir.join("Face FR tickets.trail");
        if let Some(ed) = app.report_editor.as_mut() {
            ed.report.path = Some(trail.clone());
            ed.flow = ed.report.flow().ok();
        }
        super::open_export_dialog(&mut app);
        let path = match app.dialog {
            Some(super::super::app::Dialog::ExportResults { path }) => path,
            _ => panic!("Export opens PaperBoy's own dialog"),
        };
        std::fs::remove_dir_all(&dir).ok();
        assert_eq!(
            path,
            trail.with_extension("xlsx").to_string_lossy(),
            "the file is named for the report, in the format it declares, beside it"
        );
    }

    #[test]
    fn a_scratch_report_exports_into_its_own_base_directory() {
        // With no file of its own a report's export name is bare, and would
        // land wherever PaperBoy was started from; `# root:` says where the
        // report's world is, so that is where its results go.
        let dir = std::env::temp_dir().join(format!("pb_exp_root_{}", std::process::id()));
        std::fs::create_dir_all(&dir).ok();
        let mut app = app_with_report(&format!("# root: {}\n# collection: api\n", dir.display()));
        if let Some(ed) = app.report_editor.as_mut() {
            ed.flow = ed.report.flow().ok();
        }
        super::open_export_dialog(&mut app);
        let path = match app.dialog {
            Some(super::super::app::Dialog::ExportResults { path }) => path,
            _ => panic!("Export opens PaperBoy's own dialog"),
        };
        std::fs::remove_dir_all(&dir).ok();
        assert!(
            std::path::Path::new(&path).starts_with(&dir),
            "an unsaved report's results are offered in its base directory: {path}"
        );
    }

    /// The same collision inside the Blocks view, where the button queues a
    /// *structural* edit: the field commit carries the path of the block it was
    /// drawn on, so it has to be applied while that path still means what it
    /// meant on screen. Applied after a deletion instead, it lands on whichever
    /// block shuffled into that slot — renaming a block the user never touched.
    #[test]
    fn a_field_commit_is_not_applied_to_a_block_that_moved_under_it() {
        let mut app = app_with_report(
            "# collection: api\nREPORT REQUEST A AS One\nREPORT REQUEST A AS Two\nREPORT REQUEST A AS Three\n",
        );
        let ctx = egui::Context::default();

        let out = ctx.run_ui(input(), |ui| super::ui(&mut app, ui));
        let painted = painted(&out.shapes);
        let two = painted
            .iter()
            .find(|(t, _)| t == "Two")
            .map(|(_, r)| *r)
            .expect("the second block's alias field");
        let trash = painted
            .iter()
            .find(|(t, _)| t.contains(app.strings.gui_report_delete_block))
            .map(|(_, r)| *r)
            .expect("the Delete block button");

        // Click into the second block's alias and type, without leaving it.
        let caret = egui::pos2(two.right() - 1.0, two.center().y);
        let _ = ctx.run_ui(click_at(caret), |ui| super::ui(&mut app, ui));
        let mut typing = input();
        typing.events.push(egui::Event::Text("x".into()));
        let _ = ctx.run_ui(typing, |ui| super::ui(&mut app, ui));

        // With the *first* block selected, delete it while the second block's
        // field still holds uncommitted text.
        app.report_editor.as_mut().unwrap().selection = vec![0];
        // egui resolves a click against the previous frame's widgets, so the
        // Delete button has to have been drawn enabled once before it can be
        // pressed.
        let _ = ctx.run_ui(input(), |ui| super::ui(&mut app, ui));
        let _ = ctx.run_ui(click_at(trash.center()), |ui| super::ui(&mut app, ui));

        let text = &app.report_editor.as_ref().expect("editor open").report.text;
        assert!(!text.contains("AS One"), "the selected block is deleted");
        assert!(
            text.contains("AS Twox"),
            "the edited block keeps its own edit: {text:?}"
        );
        assert!(
            text.contains("AS Three"),
            "and the block below it is left alone: {text:?}"
        );
    }

    /// Typing in an inline chip field and pressing a toolbar button in one go
    /// must keep what was typed: the field commits when the click takes its
    /// focus away, and the button acts on the result. Before, the button acted
    /// first and switched view, so the field was never redrawn, its commit
    /// never ran, and the typing was silently thrown away.
    #[test]
    fn a_toolbar_press_keeps_what_was_being_typed() {
        let mut app = app_with_report("# collection: api\nREPORT REQUEST A AS Old\n");
        let ctx = egui::Context::default();

        // Frame 1: lay the editor out so the alias field has a position.
        let out = ctx.run_ui(input(), |ui| super::ui(&mut app, ui));
        let painted = painted(&out.shapes);
        let alias = painted
            .iter()
            .find(|(t, _)| t == "Old")
            .map(|(_, r)| *r)
            .expect("the alias field shows its current value");
        let dry = painted
            .iter()
            .find(|(t, _)| t.contains(app.strings.gui_report_dry_run))
            .map(|(_, r)| *r)
            .expect("the Dry run button is on the toolbar");

        // Frame 2: click into the alias field, putting the caret after "Old".
        let caret = egui::pos2(alias.right() - 1.0, alias.center().y);
        let _ = ctx.run_ui(click_at(caret), |ui| super::ui(&mut app, ui));

        // Frame 3: type, without leaving the field.
        let mut typing = input();
        typing.events.push(egui::Event::Text("er".into()));
        let _ = ctx.run_ui(typing, |ui| super::ui(&mut app, ui));
        assert!(
            app.report_editor
                .as_ref()
                .is_some_and(|ed| ed.report.text.contains("AS Old")),
            "still uncommitted while the field has focus"
        );

        // Frame 4: press Dry run straight from the field.
        let _ = ctx.run_ui(click_at(dry.center()), |ui| super::ui(&mut app, ui));
        let ed = app.report_editor.as_ref().expect("the editor stays open");
        assert!(
            ed.report.text.contains("AS Older"),
            "the typing survives the button press: {:?}",
            ed.report.text
        );
        assert!(ed.view == EditorView::Results, "and the button still acted");
    }
}

#[cfg(test)]
mod param_view_tests {
    use super::*;
    use crate::report::Report;
    use crate::session::Session;

    const TRAIL: &str = "\
# name: Face
# collection: c.hurl
PARAM TEXT TICKET LABEL \"Ticket number\"
PARAM CHOICE(\"au\", \"eu\") REGION = \"au\"
REPORT REQUEST x
";

    fn editor(text: &str) -> (GuiApp, ReportEditor) {
        let mut app = GuiApp::for_test(Session::default());
        app.open_report_editor(ReportOrigin::Workspace, Report::from_text("Face", text));
        let ed = app.report_editor.take().expect("editor is open");
        (app, ed)
    }

    /// Every piece of text painted by one frame of the editor, in `ctx` — which
    /// the caller owns, because a modal's layer is laid out on the frame after
    /// the one that asked for it and a fresh context would never get there.
    fn painted(ctx: &egui::Context, app: &mut GuiApp) -> String {
        let mut input = egui::RawInput::default();
        input.screen_rect = Some(egui::Rect::from_min_size(
            egui::pos2(0.0, 0.0),
            egui::vec2(1000.0, 760.0),
        ));
        let out = ctx.run_ui(input, |ui| super::ui(app, ui));
        fn walk(s: &egui::epaint::Shape, out: &mut String) {
            match s {
                egui::epaint::Shape::Text(t) => {
                    out.push_str(t.galley.text());
                    out.push('\n');
                }
                egui::epaint::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
                _ => {}
            }
        }
        let mut text = String::new();
        for c in &out.shapes {
            walk(&c.shape, &mut text);
        }
        text
    }

    /// The questions are a step on the way to a run, not a place: the editor
    /// opens where the report is built, and Run is what asks.
    #[test]
    fn run_asks_the_questions_before_it_starts() {
        let (mut app, mut ed) = editor(TRAIL);
        assert!(ed.view == EditorView::Blocks, "opens where it is built");
        assert!(ed.params_modal.is_none(), "and asks nothing unprompted");

        ed.start_run(&mut app);
        assert_eq!(ed.params_modal, Some(RunIntent::Run));
        assert!(!ed.is_running(), "nothing has been run yet");
    }

    /// A preview is only worth looking at if it previews the run you mean, so
    /// Dry run asks the same questions — and says so by leading with its own
    /// button when the dialog opens.
    #[test]
    fn a_dry_run_asks_the_same_questions() {
        let (mut app, mut ed) = editor(TRAIL);
        ed.start_dry_run(&mut app);
        assert_eq!(ed.params_modal, Some(RunIntent::DryRun));
        assert!(ed.dry_run.is_none(), "and previews nothing yet");
    }

    /// Answered once, not once per run: the whole point of previewing first is
    /// to run the same thing afterwards without being asked again.
    #[test]
    fn once_answered_the_buttons_act_at_once() {
        let (mut app, mut ed) = editor(TRAIL);
        ed.seed_params(&app.session);
        ed.param_values.insert("TICKET".into(), "FR-12".into());
        ed.params_confirmed = true;
        ed.start_run(&mut app);
        assert!(ed.params_modal.is_none(), "no second interrogation");
    }

    /// ...but changing what the report *asks* re-arms the questions: the
    /// answers were confirmed against the old declarations.
    #[test]
    fn changing_a_declaration_asks_again() {
        let (mut app, mut ed) = editor(TRAIL);
        ed.params_confirmed = true;
        ed.set_text(TRAIL.replace("\"au\", \"eu\"", "\"au\", \"eu\", \"us\""));
        assert!(
            !ed.params_confirmed,
            "the choices are not the ones answered"
        );

        // Editing anything else leaves the answers alone.
        ed.seed_params(&app.session);
        ed.param_values.insert("TICKET".into(), "FR-12".into());
        ed.params_confirmed = true;
        let same_questions = ed.report.text.replace("REQUEST x", "REQUEST y");
        ed.set_text(same_questions);
        assert!(ed.params_confirmed);
        ed.start_run(&mut app);
        assert!(ed.params_modal.is_none());
    }

    /// The form is built from the declarations, defaults included, and the row
    /// with no default is the one flagged as missing.
    #[test]
    fn the_form_asks_one_question_per_parameter() {
        let (app, mut ed) = editor(TRAIL);
        ed.seed_params(&app.session);
        let rows = ed.param_rows(&app.strings);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].name, "TICKET");
        assert_eq!(rows[0].prompt, "Ticket number", "the LABEL is the prompt");
        assert!(rows[0].problem.is_some(), "nothing given and no default");
        assert_eq!(rows[1].value, "au", "the declared default fills the row");
        assert!(rows[1].problem.is_none());
    }

    /// The toolbar says what the next run will use without anything being
    /// opened — the dialog only shows itself once.
    #[test]
    fn the_toolbar_shows_the_answers_it_will_run_with() {
        let (app, mut ed) = editor(TRAIL);
        ed.seed_params(&app.session);
        ed.param_values.insert("TICKET".into(), "FR-12".into());
        let summary = ed.param_summary(&app.strings);
        assert!(summary.contains("TICKET=FR-12"), "{summary}");
        assert!(summary.contains("REGION=au"), "{summary}");
    }

    /// The dialog has to actually paint: the prompt, the value the run would
    /// use, and the raw name beside it. A state-correct dialog that draws
    /// nothing is the failure mode this guards.
    #[test]
    fn the_dialog_paints_the_question_the_value_and_the_name() {
        let mut app = GuiApp::for_test(Session::default());
        app.open_report_editor(ReportOrigin::Workspace, Report::from_text("Face", TRAIL));
        // Nothing of the dialog until it is asked for. (The *source* says
        // "Ticket number" in either case, so the dialog's own lead line is
        // what distinguishes the two.)
        let lead = app.strings.param_view_lead;
        let ctx = egui::Context::default();
        let before = painted(&ctx, &mut app);
        assert!(!before.contains(lead), "{before}");

        if let Some(ed) = app.report_editor.as_mut() {
            ed.params_modal = Some(RunIntent::Run);
        }
        // Twice: a modal's own layer is laid out on the frame after the one
        // that asked for it.
        painted(&ctx, &mut app);
        let text = painted(&ctx, &mut app);
        assert!(text.contains(lead), "the dialog is up: {text}");
        assert!(text.contains("Ticket number"), "the prompt: {text}");
        assert!(text.contains("TICKET"), "and the name the script uses");
        assert!(
            text.contains("au"),
            "and the value the run would use: {text}"
        );
    }

    /// Answers survive a trip to another tab, so nobody types them twice.
    #[test]
    fn the_answers_travel_with_a_parked_run() {
        let (app, mut ed) = editor(TRAIL);
        ed.seed_params(&app.session);
        ed.param_values.insert("TICKET".into(), "FR-12".into());
        let parked = ed.park_run();

        let (_app2, mut fresh) = editor(TRAIL);
        fresh.adopt_run(parked);
        assert_eq!(
            fresh.param_values.get("TICKET").map(String::as_str),
            Some("FR-12")
        );
    }
}

#[cfg(test)]
mod stop_run_tests {
    use super::*;
    use crate::gui::report_run::{RunUpdate, test_handle};
    use crate::report::Report;
    use crate::report::model::{ReportResult, ReportRow};
    use crate::session::Session;

    fn editor() -> (GuiApp, ReportEditor) {
        let mut app = GuiApp::for_test(Session::default());
        app.open_report_editor(ReportOrigin::Workspace, Report::scratch("nightly"));
        let ed = app.report_editor.take().expect("editor is open");
        (app, ed)
    }

    fn result_with(cell: &str) -> ReportResult {
        let mut res = ReportResult::default();
        let mut row = ReportRow::default();
        row.cells.insert("A".to_string(), cell.to_string());
        res.rows.push(row);
        res
    }

    /// Stopping used to only raise the cancel flag and leave the handle in
    /// place, so `is_running()` stayed true — and the button stayed a Stop
    /// button — until the worker's `Done` finally arrived. Cancelling doesn't
    /// abort an in-flight request, and a `PARALLEL` batch can take a long time
    /// to wind down, so the report was unrunnable for a while. The TUI retires
    /// the run at once; so must this.
    #[test]
    fn stopping_frees_the_report_to_be_run_again_at_once() {
        let (mut app, mut ed) = editor();
        let (handle, tx) = test_handle();
        ed.run = Some(handle);
        assert!(ed.is_running(), "a live handle is a live run");

        ed.stop_run(&mut app);

        assert!(
            !ed.is_running(),
            "the run is retired immediately, without waiting for the worker"
        );
        assert!(matches!(app.session.status, Some(Status::ReportRunStopped)));

        // The worker is still alive and still winding down: it has not sent
        // `Done`, and sending now must not resurrect the run.
        assert!(
            tx.send(RunUpdate::Done(ReportResult::default())).is_err(),
            "our end of the channel went with the handle, so late updates \
             land nowhere rather than being folded in"
        );
        assert!(!ed.is_running());
    }

    /// Retiring the handle must not take the partial grid with it: rows that
    /// completed before the stop keep their real responses, and the user can
    /// still read, save or export them.
    #[test]
    fn stopping_keeps_the_rows_that_already_arrived_but_clears_the_progress() {
        let (mut app, mut ed) = editor();
        let (handle, _tx) = test_handle();
        ed.run = Some(handle);
        ed.result = Some(result_with("200"));
        ed.progress = Some(crate::gui::report_run::RunProgress {
            states: vec![crate::gui::report_run::RowState::Running],
            index: Default::default(),
            done: 0,
            total: 1,
        });

        ed.stop_run(&mut app);

        assert_eq!(
            ed.result.as_ref().map(|r| r.rows.len()),
            Some(1),
            "the partial grid survives the stop"
        );
        assert!(
            ed.progress.is_none(),
            "but no row is left rendering as still running"
        );
    }

    /// The cancel flag still has to be raised, or the detached worker would
    /// carry on firing requests at the network after the user stopped it.
    #[test]
    fn stopping_still_tells_the_worker_to_wind_down() {
        let (mut app, mut ed) = editor();
        let (handle, _tx) = test_handle();
        let flag = handle.cancel_flag_for_test();
        ed.run = Some(handle);

        ed.stop_run(&mut app);

        assert!(
            flag.load(std::sync::atomic::Ordering::Relaxed),
            "dropping our end alone would not stop the worker: it watches the flag"
        );
    }
}