quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
//! `SidebarSystem` — a composed controller for MSV sidebar panels.
//!
//! Owns the full interaction state machine: per-section scroll/selection,
//! active section cycling, scrollbar drag, keyboard navigation, and
//! two-layer click dispatch (MSV → body with coordinate translation).
//!
//! Sections may be Tree-bodied (managed by `TreeController`) or
//! Form-bodied (managed by `FormController`). The section kind is set
//! at construction time via [`SectionKind`] on [`SidebarSectionDef`].
//!
//! Two navigation modes (set via [`SidebarSystem::set_navigation_mode`]):
//! - [`NavigationMode::Scroll`] (default): Up/Down scroll the viewport.
//! - [`NavigationMode::Selection`]: Up/Down/j/k move `selected_path` to
//!   the next/previous row with scroll-to-follow. Home/End/PageUp/PageDown
//!   jump by page or extremes. Enter emits [`SidebarEvent::RowActivated`].
//!
//! Apps define section structure via [`SidebarSectionDef`], set row data
//! per frame via [`SidebarSystem::set_rows`] (tree sections) or
//! [`SidebarSystem::set_form`] (form sections), and match on
//! [`SidebarEvent`] for semantic actions.
//!
//! Scroll-wheel events follow the [`ScrollDelta`](crate::ScrollDelta)
//! sign convention: positive `delta.y` = scroll content up (decrease
//! offset). Backends normalise their native direction before emitting.

use super::focus_group::FocusGroup;
use super::form_controller::{form_click_event, FormController};
use super::tree_controller::TreeController;
use super::tree_controller::TreeControllerEvent;
use crate::primitives::form::{
    FieldKind, Form, FormEvent, FormFieldMeasure, FormItemMeasure, FormLayout,
};
use crate::primitives::multi_section_view::{
    MsvLayoutMetrics, MultiSectionViewLayout, SectionMeasure,
};
use crate::primitives::scrollbar::{wheel_delta, wheel_row_delta, ThumbDrag};
use crate::{
    Backend, ButtonMask, Key, Modifiers, MouseButton, MsvAxis, MultiSectionView,
    MultiSectionViewHit, NamedKey, Point, Rect, ScrollMode, ScrollbarHit, Section, SectionBody,
    SectionHeader, SectionSize, SelectionMode, StyledText, TreePath, TreeRow, TreeRowEditState,
    TreeView, TreeViewHit, UiEvent, WidgetId,
};

/// How Up/Down keys behave in the sidebar.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NavigationMode {
    /// Up/Down scroll the viewport (legacy behaviour).
    #[default]
    Scroll,
    /// Up/Down move `selected_path` to the next/previous row; the
    /// viewport scrolls to keep the selection visible.
    Selection,
}

/// Whether a sidebar section hosts a TreeView or a Form.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SectionKind {
    #[default]
    Tree,
    Form,
}

/// Definition of one sidebar section (structure, not data).
#[derive(Debug, Clone)]
pub struct SidebarSectionDef {
    pub id: String,
    pub title: String,
    pub show_chevron: bool,
    pub size: SectionSize,
    pub kind: SectionKind,
}

impl SidebarSectionDef {
    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            show_chevron: false,
            size: SectionSize::EqualShare,
            kind: SectionKind::Tree,
        }
    }

    pub fn form(id: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            show_chevron: false,
            size: SectionSize::Content,
            kind: SectionKind::Form,
        }
    }
}

/// What happened after [`SidebarSystem::handle`] processed an event.
#[derive(Debug, Clone, PartialEq)]
pub enum SidebarEvent {
    /// Header clicked — section activated.
    HeaderActivated { section: usize },
    /// Tree row clicked — section activated + row selected.
    RowSelected { section: usize, path: TreePath },
    /// Enter pressed on the currently selected row (Selection mode).
    /// Distinct from `RowSelected` (click-driven) — lets apps
    /// distinguish keyboard activation from mouse selection.
    RowActivated { section: usize, path: TreePath },
    /// The expand/collapse chevron of a branch row was clicked, or Space
    /// was pressed while a branch row is selected.  The app owns per-row
    /// expand state and should toggle it, then push fresh `TreeRow`s.
    RowToggleExpand { section: usize, path: TreePath },
    /// Right-click on a body row. `position` is the click position
    /// in the backend's native coordinates (for context menu placement).
    ContextMenuRequested {
        section: usize,
        path: TreePath,
        position: Point,
    },
    /// Scrollbar interaction (drag or page).
    ScrollChanged { section: usize },
    /// The user confirmed an inline edit (pressed Enter).
    EditConfirmed {
        section: usize,
        path: TreePath,
        new_text: String,
    },
    /// The user cancelled an inline edit (pressed Escape).
    EditCancelled { section: usize, path: TreePath },
    /// The text buffer changed during inline editing.
    EditChanged {
        section: usize,
        path: TreePath,
        text: String,
    },
    /// A Form section emitted a form event (toggle, text input, button, etc.).
    FormEvent { section: usize, event: FormEvent },
    /// State changed (navigation, collapse) — app should redraw.
    StateChanged,
    /// Event consumed (drag update, hover) — app should redraw.
    Consumed,
    /// Event not relevant to the sidebar.
    Ignored,
}

/// A row-scroll thumb drag in progress on one tree section. Wraps the
/// shared [`ThumbDrag`] math with the section index it applies to.
struct SectionScrollDrag {
    section: usize,
    drag: ThumbDrag,
}

struct BackendInfo {
    line_height: f32,
    metrics: MsvLayoutMetrics,
}

enum SectionController {
    Tree(TreeController),
    Form(FormController),
}

pub struct SidebarSystem {
    defs: Vec<SidebarSectionDef>,
    sections: Vec<SectionController>,
    focus: FocusGroup,
    collapsed: Vec<bool>,
    visible: Vec<bool>,
    badges: Vec<Option<StyledText>>,
    scroll_drag: Option<SectionScrollDrag>,
    panel_drag: Option<ThumbDrag>,
    has_focus: bool,
    allow_collapse: bool,
    navigation_mode: NavigationMode,
    cached_viewport_rows: Option<(usize, usize)>,
    scroll_mode: ScrollMode,
    panel_scroll: f32,
    backend_info: Option<BackendInfo>,
    cached_form_layouts: Vec<Option<FormLayout>>,
}

impl SidebarSystem {
    pub fn new(defs: Vec<SidebarSectionDef>) -> Self {
        let n = defs.len();
        let sections = defs
            .iter()
            .map(|def| match def.kind {
                SectionKind::Tree => {
                    SectionController::Tree(TreeController::new(format!("{}-tree", def.id)))
                }
                SectionKind::Form => {
                    SectionController::Form(FormController::new(format!("{}-form", def.id)))
                }
            })
            .collect();
        Self {
            defs,
            sections,
            focus: FocusGroup::new(n),
            collapsed: vec![false; n],
            visible: vec![true; n],
            badges: vec![None; n],
            scroll_drag: None,
            panel_drag: None,
            has_focus: true,
            allow_collapse: false,
            navigation_mode: NavigationMode::default(),
            cached_viewport_rows: None,
            scroll_mode: ScrollMode::PerSection,
            panel_scroll: 0.0,
            backend_info: None,
            cached_form_layouts: vec![None; n],
        }
    }

    // ── Per-frame data ────────────────────────────────────────────────

    pub fn set_rows(&mut self, section: usize, rows: Vec<TreeRow>) {
        if let Some(SectionController::Tree(tc)) = self.sections.get_mut(section) {
            tc.set_rows(rows);
        }
    }

    pub fn set_form(&mut self, section: usize, form: Form) {
        if let Some(SectionController::Form(fc)) = self.sections.get_mut(section) {
            fc.set_form(form);
        }
    }

    // ── State accessors ───────────────────────────────────────────────

    pub fn active_section(&self) -> Option<usize> {
        self.focus.active()
    }

    pub fn selected_path(&self, section: usize) -> Option<&TreePath> {
        match self.sections.get(section) {
            Some(SectionController::Tree(tc)) => tc.selected_path(),
            _ => None,
        }
    }

    pub fn scroll_offset(&self, section: usize) -> usize {
        match self.sections.get(section) {
            Some(SectionController::Tree(tc)) => tc.scroll_offset(),
            _ => 0,
        }
    }

    pub fn form(&self, section: usize) -> Option<&Form> {
        match self.sections.get(section) {
            Some(SectionController::Form(fc)) => fc.form(),
            _ => None,
        }
    }

    pub fn section_kind(&self, section: usize) -> Option<SectionKind> {
        self.defs.get(section).map(|d| d.kind)
    }

    pub fn is_collapsed(&self, section: usize) -> bool {
        self.collapsed.get(section).copied().unwrap_or(false)
    }

    pub fn is_section_visible(&self, section: usize) -> bool {
        self.visible.get(section).copied().unwrap_or(true)
    }

    pub fn section_badge(&self, section: usize) -> Option<&StyledText> {
        self.badges.get(section).and_then(|b| b.as_ref())
    }

    // ── Programmatic state control ────────────────────────────────────

    pub fn set_active_section(&mut self, section: Option<usize>) {
        self.focus.set_active(section);
    }

    /// Mark a Form section as focused *for rendering purposes only*,
    /// without changing the active (nav) section.
    ///
    /// This decouples two orthogonal concerns: which section receives
    /// keyboard/nav events ([`Self::active_section`]) versus whether a
    /// form field renders with a cursor/focus ring. It lets an app show
    /// a focused text input (e.g. a FILTER box) while a *different*
    /// section's tree still drives selection and keyboard navigation.
    ///
    /// Without this, a form field only renders focused when its section
    /// is the active one — so rebuilding the `SidebarSystem` while a
    /// tree section is active (the common per-frame refresh pattern)
    /// silently strips the form's visible cursor. Call `focus_form`
    /// after each rebuild to restore it.
    ///
    /// No-op if `section` is out of range or hosts a Tree, not a Form.
    pub fn focus_form(&mut self, section: usize, focused: bool) {
        if let Some(SectionController::Form(fc)) = self.sections.get_mut(section) {
            fc.set_has_focus(focused);
        }
    }

    /// Whether the Form section at `section` is render-focused via
    /// [`Self::focus_form`]. Returns `false` for Tree sections, empty
    /// sections, or out-of-range indices.
    pub fn form_has_focus(&self, section: usize) -> bool {
        matches!(self.sections.get(section), Some(SectionController::Form(fc)) if fc.has_focus())
    }

    pub fn set_selected_path(&mut self, section: usize, path: Option<TreePath>) {
        if let Some(SectionController::Tree(tc)) = self.sections.get_mut(section) {
            tc.set_selected_path(path);
        }
    }

    /// Select `path` within `section`, expand the section if it's
    /// currently collapsed, and scroll its viewport so `path` ends up
    /// visible.
    ///
    /// Interactive navigation (arrow keys, click) already keeps the
    /// selected row on-screen — [`Self::move_selection_by`] and friends
    /// call [`TreeController::scroll_to_visible`] after moving the
    /// selection. A *programmatic* selection (e.g. restoring a saved
    /// path, jumping to a search hit) bypasses that path: nothing
    /// selects the row, un-collapses its section, or scrolls it into
    /// view on its own. `reveal` does all three in one call, reusing
    /// [`TreeController::scroll_to_visible`] — the exact same
    /// scroll-to-follow math interactive nav uses — rather than
    /// re-deriving it.
    ///
    /// No-op if `section` is out of range, hosts a Form (not a Tree),
    /// `path` isn't among the section's current rows, or
    /// [`Self::set_backend_info`] hasn't been called yet (the viewport's
    /// row capacity is unknown without it). A collapsed section is
    /// expanded *before* the viewport is measured, so the row-capacity
    /// computation reflects the now-visible body rather than the
    /// collapsed (zero-height) one.
    pub fn reveal(&mut self, section: usize, path: &TreePath, rect: Rect) {
        let Some(info) = self.backend_info.as_ref() else {
            return;
        };
        let lh = info.line_height;
        let metrics = info.metrics;

        let Some(SectionController::Tree(tc)) = self.sections.get(section) else {
            return;
        };
        if !tc.rows().iter().any(|r| &r.path == path) {
            return;
        }

        if let Some(collapsed) = self.collapsed.get_mut(section) {
            *collapsed = false;
        }

        let viewport_rows = self.section_viewport_rows(section, rect, lh, &metrics);

        let Some(SectionController::Tree(tc)) = self.sections.get_mut(section) else {
            return;
        };
        tc.set_selected_path(Some(path.clone()));
        let Some(row) = tc.rows().iter().position(|r| &r.path == path) else {
            return;
        };
        tc.scroll_to_visible(row, viewport_rows);
    }

    pub fn set_collapsed(&mut self, section: usize, collapsed: bool) {
        if section < self.collapsed.len() {
            self.collapsed[section] = collapsed;
        }
    }

    pub fn set_section_visible(&mut self, section: usize, visible: bool) {
        if section < self.visible.len() {
            self.visible[section] = visible;
        }
    }

    pub fn set_section_badge(&mut self, section: usize, badge: Option<StyledText>) {
        if section < self.badges.len() {
            self.badges[section] = badge;
        }
    }

    pub fn has_focus(&self) -> bool {
        self.has_focus
    }

    pub fn set_has_focus(&mut self, has_focus: bool) {
        self.has_focus = has_focus;
    }

    pub fn set_allow_collapse(&mut self, allow: bool) {
        self.allow_collapse = allow;
    }

    pub fn navigation_mode(&self) -> NavigationMode {
        self.navigation_mode
    }

    pub fn set_navigation_mode(&mut self, mode: NavigationMode) {
        self.navigation_mode = mode;
    }

    pub fn scroll_mode(&self) -> ScrollMode {
        self.scroll_mode
    }

    pub fn set_scroll_mode(&mut self, mode: ScrollMode) {
        self.scroll_mode = mode;
    }

    pub fn panel_scroll(&self) -> f32 {
        self.panel_scroll
    }

    pub fn set_panel_scroll(&mut self, offset: f32) {
        self.panel_scroll = offset.max(0.0);
    }

    /// Cache backend-specific layout info so [`Self::handle_cached`] can
    /// compute layouts without a Backend reference. Call once at init, or
    /// again if `line_height` changes (font/DPI change).
    pub fn set_backend_info(&mut self, line_height: f32, metrics: MsvLayoutMetrics) {
        self.backend_info = Some(BackendInfo {
            line_height,
            metrics,
        });
    }

    /// Pre-compute and cache form layouts using the backend's native
    /// measurement (Pango for GTK, char cells for TUI). Call after
    /// `render()` or `set_form()` so that [`Self::handle_cached`]
    /// uses pixel-accurate hit regions instead of the generic estimate.
    pub fn cache_form_layouts(&mut self, backend: &dyn Backend) {
        let (view, map) = self.build_view();
        let lh = backend.chrome_line_height();
        let metrics = backend.msv_metrics();
        let layout = view.layout(Rect::new(0.0, 0.0, 0.0, 0.0), metrics, |i| {
            body_measure(&view.sections[i], lh)
        });
        for (msv_idx, s_layout) in layout.sections.iter().enumerate() {
            let sidebar_idx = map[msv_idx];
            if let SectionBody::Form(ref f) = view.sections[msv_idx].body {
                let fl = backend.form_layout(s_layout.body_bounds, f);
                if sidebar_idx < self.cached_form_layouts.len() {
                    self.cached_form_layouts[sidebar_idx] = Some(fl);
                }
            }
        }
    }

    // ── Inline editing ───────────────────────────────────────────────

    pub fn start_editing(
        &mut self,
        section: usize,
        path: TreePath,
        initial_text: String,
        cursor: usize,
        selection_anchor: Option<usize>,
        placeholder: Option<String>,
    ) {
        if let Some(SectionController::Tree(tc)) = self.sections.get_mut(section) {
            tc.start_editing(path, initial_text, cursor, selection_anchor, placeholder);
        }
    }

    pub fn cancel_editing(&mut self, section: usize) {
        if let Some(SectionController::Tree(tc)) = self.sections.get_mut(section) {
            tc.cancel_editing();
        }
    }

    pub fn is_editing(&self) -> bool {
        self.sections
            .iter()
            .any(|sc| matches!(sc, SectionController::Tree(tc) if tc.is_editing()))
    }

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

    pub fn render(&self, backend: &mut dyn Backend, rect: Rect) {
        let (view, _) = self.build_view();
        backend.draw_multi_section_view(rect, &view);
    }

    // ── Handle ────────────────────────────────────────────────────────

    pub fn handle(
        &mut self,
        event: &UiEvent,
        backend: &mut dyn Backend,
        rect: Rect,
    ) -> SidebarEvent {
        let lh = backend.chrome_line_height();
        let metrics = backend.msv_metrics();
        self.handle_inner(event, rect, lh, &metrics, Some(&*backend))
    }

    /// Backend-free event handler. Requires [`Self::set_backend_info`]
    /// called first. Returns [`SidebarEvent::Ignored`] if backend info
    /// is not set.
    pub fn handle_cached(&mut self, event: &UiEvent, rect: Rect) -> SidebarEvent {
        let Some(ref info) = self.backend_info else {
            return SidebarEvent::Ignored;
        };
        let lh = info.line_height;
        let metrics = info.metrics;
        self.handle_inner(event, rect, lh, &metrics, None)
    }

    fn handle_inner(
        &mut self,
        event: &UiEvent,
        rect: Rect,
        lh: f32,
        metrics: &MsvLayoutMetrics,
        backend: Option<&dyn Backend>,
    ) -> SidebarEvent {
        self.cached_viewport_rows = None;

        // Route text input events to the editing section's TreeController.
        if self.is_editing() {
            match event {
                UiEvent::CharTyped(ch) => return self.forward_edit_char(*ch),
                UiEvent::ClipboardPaste(text) => return self.forward_edit_paste(text),
                _ => {}
            }
        }

        match event {
            // ── Mouse click ───────────────────────────────────────
            UiEvent::MouseDown {
                button: MouseButton::Left,
                position,
                ..
            } => self.click(rect, position.x, position.y, lh, metrics, backend),

            // ── Right-click ──────────────────────────────────────
            UiEvent::MouseDown {
                button: MouseButton::Right,
                position,
                ..
            } => self.right_click(rect, *position, lh, metrics),

            // ── Double-click → forward to TreeController for RowActivated
            UiEvent::DoubleClick { position, .. } => {
                self.double_click(rect, position.x, position.y, lh, metrics, backend)
            }

            // ── Mouse drag ────────────────────────────────────────
            UiEvent::MouseMoved {
                position,
                buttons:
                    ButtonMask {
                        left: true,
                        middle: _,
                        right: _,
                    },
            } => self.drag_to(position.y),

            // ── Mouse up ──────────────────────────────────────────
            UiEvent::MouseUp {
                button: MouseButton::Left,
                ..
            } => {
                self.scroll_drag = None;
                self.panel_drag = None;
                SidebarEvent::Ignored
            }

            // ── Scroll wheel ──────────────────────────────────────
            //
            // Route to the section under the cursor rather than always
            // sending to the active section. This is the native
            // convention on all desktop platforms: scroll goes to the
            // widget under the pointer, not to the focused widget.
            //
            // Fallback: if the cursor position doesn't hit any
            // scrollable section (e.g. keyboard-driven scroll where
            // backends emit a default origin, or cursor outside the
            // MSV bounds), we fall back to scrolling the active section.
            UiEvent::Scroll {
                delta, position, ..
            } => {
                if self.scroll_mode == ScrollMode::WholePanel {
                    let dy = wheel_delta(delta.y, lh);
                    self.scroll_panel(rect, dy, lh, metrics);
                } else {
                    let rows = wheel_row_delta(delta.y, 1.0);
                    if !self.scroll_section_at(*position, rect, rows, lh, metrics) {
                        self.scroll_active(rect, rows, lh, metrics);
                    }
                }
                SidebarEvent::Consumed
            }

            // ── Keyboard ──────────────────────────────────────────
            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::Tab),
                ..
            } => {
                self.cycle_active(1);
                if self.scroll_mode == ScrollMode::WholePanel {
                    self.scroll_to_active_section(rect, lh, metrics);
                }
                SidebarEvent::StateChanged
            }
            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::BackTab),
                ..
            } => {
                self.cycle_active(-1);
                if self.scroll_mode == ScrollMode::WholePanel {
                    self.scroll_to_active_section(rect, lh, metrics);
                }
                SidebarEvent::StateChanged
            }
            UiEvent::KeyPressed { key, modifiers, .. } => {
                if self.is_editing() {
                    return self.forward_edit_key(key, modifiers);
                }
                self.handle_key(key, rect, lh, metrics)
            }

            _ => SidebarEvent::Ignored,
        }
    }

    // ── Internal helpers ──────────────────────────────────────────────

    fn compute_layout(
        &self,
        rect: Rect,
        metrics: &MsvLayoutMetrics,
        lh: f32,
    ) -> (MultiSectionViewLayout, Vec<usize>) {
        let (view, map) = self.build_view();
        let layout = view.layout(rect, *metrics, |i| body_measure(&view.sections[i], lh));
        (layout, map)
    }

    fn compute_tree_layout(
        &self,
        body_b: Rect,
        tree: &TreeView,
        lh: f32,
    ) -> crate::primitives::tree::TreeViewLayout {
        // The shared pixel-layout math owns row pitch, indent and chevron
        // geometry — including `TreeStyle::row_height`, which it honors via
        // `tree_row_pitch`. Deriving any of it locally from `lh` would
        // re-introduce a copy that silently ignores that style field.
        // No live `TextMeasure` is reachable from this `&self` call site (no
        // cached backend handle on `SidebarSystem`), so the chevron end-x is
        // the `line_height * 0.65` estimate — same as every other caller of
        // `layout_metrics::tree_layout`.
        crate::primitives::layout_metrics::tree_layout(tree, body_b, lh as f64)
    }

    fn handle_key(
        &mut self,
        key: &Key,
        rect: Rect,
        lh: f32,
        metrics: &MsvLayoutMetrics,
    ) -> SidebarEvent {
        match self.navigation_mode {
            NavigationMode::Scroll => self.handle_key_scroll(key, rect, lh, metrics),
            NavigationMode::Selection => self.handle_key_selection(key, rect, lh, metrics),
        }
    }

    fn handle_key_scroll(
        &mut self,
        key: &Key,
        rect: Rect,
        lh: f32,
        metrics: &MsvLayoutMetrics,
    ) -> SidebarEvent {
        match key {
            Key::Named(NamedKey::Up) => {
                if self.scroll_mode == ScrollMode::WholePanel {
                    self.scroll_panel(rect, -lh, lh, metrics);
                } else {
                    self.scroll_active(rect, -1, lh, metrics);
                }
                SidebarEvent::Consumed
            }
            Key::Named(NamedKey::Down) => {
                if self.scroll_mode == ScrollMode::WholePanel {
                    self.scroll_panel(rect, lh, lh, metrics);
                } else {
                    self.scroll_active(rect, 1, lh, metrics);
                }
                SidebarEvent::Consumed
            }
            Key::Named(NamedKey::Enter) => {
                self.select_first_of_active();
                SidebarEvent::StateChanged
            }
            Key::Char(' ') => self.toggle_expand_selected(),
            _ => SidebarEvent::Ignored,
        }
    }

    fn handle_key_selection(
        &mut self,
        key: &Key,
        rect: Rect,
        lh: f32,
        metrics: &MsvLayoutMetrics,
    ) -> SidebarEvent {
        let vim = self
            .focus
            .active()
            .and_then(|i| self.sections.get(i))
            .is_none_or(|sc| match sc {
                SectionController::Tree(tc) => tc.vim_keys(),
                SectionController::Form(_) => false,
            });
        let vim_up = vim && matches!(key, Key::Char('k'));
        let vim_down = vim && matches!(key, Key::Char('j'));
        match key {
            Key::Named(NamedKey::Up) => self.move_selection(-1, rect, lh, metrics),
            _ if vim_up => self.move_selection(-1, rect, lh, metrics),
            Key::Named(NamedKey::Down) => self.move_selection(1, rect, lh, metrics),
            _ if vim_down => self.move_selection(1, rect, lh, metrics),
            Key::Named(NamedKey::Home) => self.jump_selection_to_edge(true, rect, lh, metrics),
            Key::Named(NamedKey::End) => self.jump_selection_to_edge(false, rect, lh, metrics),
            Key::Named(NamedKey::PageUp) => {
                let vr = self.active_viewport_rows(rect, lh, metrics);
                self.move_selection_by(-((vr.max(1) - 1).max(1) as isize), vr)
            }
            Key::Named(NamedKey::PageDown) => {
                let vr = self.active_viewport_rows(rect, lh, metrics);
                self.move_selection_by((vr.max(1) - 1).max(1) as isize, vr)
            }
            Key::Named(NamedKey::Enter) => self.activate_selection(),
            Key::Char(' ') => self.toggle_expand_selected(),
            _ => SidebarEvent::Ignored,
        }
    }

    fn move_selection(
        &mut self,
        delta: isize,
        rect: Rect,
        lh: f32,
        metrics: &MsvLayoutMetrics,
    ) -> SidebarEvent {
        let vr = self.active_viewport_rows(rect, lh, metrics);
        self.move_selection_by(delta, vr)
    }

    fn move_selection_by(&mut self, delta: isize, viewport_rows: usize) -> SidebarEvent {
        let Some(idx) = self.focus.active() else {
            return SidebarEvent::Ignored;
        };
        if self.collapsed[idx] {
            return SidebarEvent::Ignored;
        }
        let SectionController::Tree(tc) = &mut self.sections[idx] else {
            return SidebarEvent::Ignored;
        };
        match tc.move_selection_by(delta, viewport_rows) {
            TreeControllerEvent::RowSelected { path } => {
                SidebarEvent::RowSelected { section: idx, path }
            }
            TreeControllerEvent::Consumed => SidebarEvent::Consumed,
            _ => SidebarEvent::Ignored,
        }
    }

    fn jump_selection_to_edge(
        &mut self,
        to_start: bool,
        rect: Rect,
        lh: f32,
        metrics: &MsvLayoutMetrics,
    ) -> SidebarEvent {
        let vr = self.active_viewport_rows(rect, lh, metrics);
        self.jump_selection_to_edge_by(to_start, vr)
    }

    fn jump_selection_to_edge_by(&mut self, to_start: bool, viewport_rows: usize) -> SidebarEvent {
        let Some(idx) = self.focus.active() else {
            return SidebarEvent::Ignored;
        };
        let SectionController::Tree(tc) = &mut self.sections[idx] else {
            return SidebarEvent::Ignored;
        };
        match tc.jump_to_edge(to_start, viewport_rows) {
            TreeControllerEvent::RowSelected { path } => {
                SidebarEvent::RowSelected { section: idx, path }
            }
            _ => SidebarEvent::Ignored,
        }
    }

    fn activate_selection(&self) -> SidebarEvent {
        let Some(idx) = self.focus.active() else {
            return SidebarEvent::Ignored;
        };
        let SectionController::Tree(tc) = &self.sections[idx] else {
            return SidebarEvent::Ignored;
        };
        match tc.activate_selection() {
            TreeControllerEvent::RowActivated { path } => {
                SidebarEvent::RowActivated { section: idx, path }
            }
            _ => SidebarEvent::Ignored,
        }
    }

    /// Emit [`SidebarEvent::RowToggleExpand`] for the selected row of the
    /// active section, if that row is a branch (`is_expanded.is_some()`).
    /// Works in both [`NavigationMode::Scroll`] and
    /// [`NavigationMode::Selection`].
    pub fn toggle_expand_selected(&self) -> SidebarEvent {
        let Some(idx) = self.focus.active() else {
            return SidebarEvent::Ignored;
        };
        let SectionController::Tree(tc) = &self.sections[idx] else {
            return SidebarEvent::Ignored;
        };
        match tc.toggle_expand_selected() {
            TreeControllerEvent::RowToggleExpand { path } => {
                SidebarEvent::RowToggleExpand { section: idx, path }
            }
            _ => SidebarEvent::Ignored,
        }
    }

    // ── Inline editing forwarding ────────────────────────────────────

    fn editing_section(&self) -> Option<usize> {
        self.sections
            .iter()
            .position(|sc| matches!(sc, SectionController::Tree(tc) if tc.is_editing()))
    }

    fn forward_edit_char(&mut self, ch: char) -> SidebarEvent {
        let Some(idx) = self.editing_section() else {
            return SidebarEvent::Ignored;
        };
        let SectionController::Tree(tc) = &mut self.sections[idx] else {
            return SidebarEvent::Ignored;
        };
        tc.edit_insert_char_via(ch);
        self.map_tc_edit_event(idx)
    }

    fn forward_edit_paste(&mut self, text: &str) -> SidebarEvent {
        let Some(idx) = self.editing_section() else {
            return SidebarEvent::Ignored;
        };
        let SectionController::Tree(tc) = &mut self.sections[idx] else {
            return SidebarEvent::Ignored;
        };
        tc.edit_insert_str_via(text);
        self.map_tc_edit_event(idx)
    }

    fn forward_edit_key(&mut self, key: &Key, modifiers: &Modifiers) -> SidebarEvent {
        let Some(idx) = self.editing_section() else {
            return SidebarEvent::Ignored;
        };
        let SectionController::Tree(tc) = &mut self.sections[idx] else {
            return SidebarEvent::Ignored;
        };
        let ev = tc.handle_edit_key_via(key, modifiers);
        Self::map_tc_event(idx, ev)
    }

    fn map_tc_edit_event(&self, idx: usize) -> SidebarEvent {
        let SectionController::Tree(tc) = &self.sections[idx] else {
            return SidebarEvent::Consumed;
        };
        if let Some(path) = tc.editing_path() {
            SidebarEvent::EditChanged {
                section: idx,
                path: path.clone(),
                text: tc.editing_text().unwrap_or_default().to_string(),
            }
        } else {
            SidebarEvent::Consumed
        }
    }

    fn map_tc_event(idx: usize, ev: TreeControllerEvent) -> SidebarEvent {
        match ev {
            TreeControllerEvent::EditConfirmed { path, new_text } => SidebarEvent::EditConfirmed {
                section: idx,
                path,
                new_text,
            },
            TreeControllerEvent::EditCancelled { path } => {
                SidebarEvent::EditCancelled { section: idx, path }
            }
            TreeControllerEvent::EditChanged { path, text } => SidebarEvent::EditChanged {
                section: idx,
                path,
                text,
            },
            TreeControllerEvent::Consumed => SidebarEvent::Consumed,
            _ => SidebarEvent::Ignored,
        }
    }

    fn active_viewport_rows(&mut self, rect: Rect, lh: f32, metrics: &MsvLayoutMetrics) -> usize {
        let Some(idx) = self.focus.active() else {
            return 0;
        };
        if let Some((cached_section, cached_vr)) = self.cached_viewport_rows {
            if cached_section == idx {
                return cached_vr;
            }
        }
        let vr = self.section_viewport_rows(idx, rect, lh, metrics);
        self.cached_viewport_rows = Some((idx, vr));
        vr
    }

    fn section_viewport_rows(
        &self,
        section: usize,
        rect: Rect,
        lh: f32,
        metrics: &MsvLayoutMetrics,
    ) -> usize {
        let (layout, map) = self.compute_layout(rect, metrics, lh);
        let Some(msv_idx) = map.iter().position(|&s| s == section) else {
            return 0;
        };
        let body_b = layout.sections[msv_idx].body_bounds;
        self.viewport_rows_from_layout(body_b, msv_idx, lh)
    }

    fn viewport_rows_from_layout(&self, body_b: Rect, msv_section: usize, lh: f32) -> usize {
        let (view, _) = self.build_view();
        let SectionBody::Tree(t) = &view.sections[msv_section].body else {
            return 0;
        };
        let mut shadow = t.clone();
        shadow.scroll_offset = 0;
        let inner = self.compute_tree_layout(body_b, &shadow, lh);
        inner.visible_rows.len()
    }

    fn build_view(&self) -> (MultiSectionView, Vec<usize>) {
        let mut msv_to_sidebar: Vec<usize> = Vec::new();
        let mut sections: Vec<Section> = Vec::new();
        let active = self.focus.active();
        for (idx, def) in self.defs.iter().enumerate() {
            if !self.visible[idx] {
                continue;
            }
            let is_active = active == Some(idx);
            let title = if is_active {
                format!("▶ {}", def.title)
            } else {
                def.title.clone()
            };
            let body = match &self.sections[idx] {
                SectionController::Tree(tc) => {
                    let mut rows = tc.rows().to_vec();
                    if let Some(editing_path) = tc.editing_path() {
                        if let Some(row) = rows.iter_mut().find(|r| &r.path == editing_path) {
                            row.edit = Some(TreeRowEditState {
                                text: tc.editing_text().unwrap_or("").to_string(),
                                cursor: tc.editing_cursor(),
                                selection_anchor: tc.editing_selection_anchor(),
                                placeholder: tc.editing_placeholder().map(String::from),
                            });
                        }
                    }
                    SectionBody::Tree(TreeView {
                        id: WidgetId::new(format!("{}-tree", def.id)),
                        rows,
                        selection_mode: SelectionMode::Single,
                        selected_path: tc.selected_path().cloned(),
                        scroll_offset: tc.scroll_offset(),
                        style: Default::default(),
                        has_focus: is_active && self.has_focus,
                    })
                }
                SectionController::Form(fc) => {
                    // A form renders focused either when its section is
                    // the active (nav) section, or when the app has
                    // explicitly marked it render-focused via
                    // `focus_form` — letting a FILTER box keep its cursor
                    // while a different section's tree drives navigation.
                    let form_focus = fc.has_focus() || (is_active && self.has_focus);
                    let form = fc.form().cloned().unwrap_or_else(|| Form {
                        id: fc.default_form_id(),
                        fields: Vec::new(),
                        focused_field: None,
                        scroll_offset: 0,
                        has_focus: form_focus,
                    });
                    SectionBody::Form(Form {
                        has_focus: form_focus,
                        ..form
                    })
                }
            };
            sections.push(Section {
                id: def.id.clone(),
                header: SectionHeader {
                    title: StyledText::plain(title),
                    show_chevron: def.show_chevron,
                    badge: self.badges[idx].clone(),
                    ..Default::default()
                },
                body,
                aux: None,
                size: def.size,
                collapsed: self.collapsed[idx],
                min_size: None,
                max_size: None,
            });
            msv_to_sidebar.push(idx);
        }
        let msv_active = active.and_then(|a| msv_to_sidebar.iter().position(|&s| s == a));
        let view = MultiSectionView {
            id: WidgetId::new("sidebar-system"),
            sections,
            active_section: msv_active,
            axis: MsvAxis::Vertical,
            allow_resize: false,
            allow_collapse: self.allow_collapse,
            scroll_mode: self.scroll_mode,
            has_focus: self.has_focus,
            panel_scroll: self.panel_scroll,
        };
        (view, msv_to_sidebar)
    }

    fn click(
        &mut self,
        rect: Rect,
        x: f32,
        y: f32,
        lh: f32,
        metrics: &MsvLayoutMetrics,
        backend: Option<&dyn Backend>,
    ) -> SidebarEvent {
        let (layout, map) = self.compute_layout(rect, metrics, lh);
        let (view, _) = self.build_view();
        match layout.hit_test(x, y) {
            MultiSectionViewHit::Header {
                section: msv_idx, ..
            } => {
                let section = map[msv_idx];
                self.focus.set_active(Some(section));
                if let SectionController::Tree(tc) = &mut self.sections[section] {
                    tc.set_selected_path(None);
                }
                if self.allow_collapse {
                    self.collapsed[section] = !self.collapsed[section];
                }
                SidebarEvent::HeaderActivated { section }
            }
            MultiSectionViewHit::Body {
                section: msv_idx, ..
            } => {
                let section = map[msv_idx];
                self.focus.set_active(Some(section));
                let body_b = layout.sections[msv_idx].body_bounds;
                match &view.sections[msv_idx].body {
                    SectionBody::Tree(t) => {
                        let tree = t.clone();
                        let inner = self.compute_tree_layout(body_b, &tree, lh);
                        match inner.hit_test(x - body_b.x, y - body_b.y) {
                            TreeViewHit::Row(idx) => {
                                let path = tree.rows[idx].path.clone();
                                if let SectionController::Tree(tc) = &mut self.sections[section] {
                                    tc.set_selected_path(Some(path.clone()));
                                }
                                SidebarEvent::RowSelected { section, path }
                            }
                            TreeViewHit::Chevron(idx) => {
                                let path = tree.rows[idx].path.clone();
                                if let SectionController::Tree(tc) = &mut self.sections[section] {
                                    tc.set_selected_path(Some(path.clone()));
                                }
                                SidebarEvent::RowToggleExpand { section, path }
                            }
                            TreeViewHit::Empty => SidebarEvent::HeaderActivated { section },
                        }
                    }
                    SectionBody::Form(f) => {
                        let form_layout = if let Some(be) = backend {
                            be.form_layout(body_b, f)
                        } else if let Some(cached) = self
                            .cached_form_layouts
                            .get(section)
                            .and_then(|c| c.clone())
                        {
                            cached
                        } else {
                            let row_h = (lh * 1.4).round();
                            let char_w = lh * 0.6;
                            f.layout(body_b.width, body_b.height, |i| {
                                form_field_measure(&f.fields[i], row_h, char_w)
                            })
                        };
                        match form_layout.hit_test(x - body_b.x, y - body_b.y) {
                            crate::primitives::form::FormHit::Field(id) => {
                                let event = form_click_event(f, &id);
                                SidebarEvent::FormEvent { section, event }
                            }
                            crate::primitives::form::FormHit::Empty => {
                                SidebarEvent::HeaderActivated { section }
                            }
                        }
                    }
                    _ => SidebarEvent::Consumed,
                }
            }
            MultiSectionViewHit::Scrollbar {
                section: msv_idx,
                kind: ScrollbarHit::Thumb,
            } => {
                let section = map[msv_idx];
                let SectionController::Tree(tc) = &self.sections[section] else {
                    return SidebarEvent::Ignored;
                };
                let sb = layout.sections[msv_idx]
                    .scrollbar_bounds
                    .expect("scrollbar hit implies bounds present");
                let thumb_h = layout.sections[msv_idx]
                    .thumb_bounds
                    .map(|t| t.height)
                    .unwrap_or(sb.height);
                let body_b = layout.sections[msv_idx].body_bounds;
                let viewport_rows = self.viewport_rows_from_layout(body_b, msv_idx, lh);
                let row_count = tc.rows().len();
                let max_offset = row_count.saturating_sub(viewport_rows);
                let travel = (sb.height - thumb_h).max(0.0);
                self.scroll_drag = Some(SectionScrollDrag {
                    section,
                    drag: ThumbDrag::begin(y, tc.scroll_offset() as f32, travel, max_offset as f32),
                });
                SidebarEvent::ScrollChanged { section }
            }
            MultiSectionViewHit::Scrollbar {
                section: msv_idx,
                kind: ScrollbarHit::TrackBefore,
            } => {
                let section = map[msv_idx];
                let body_b = layout.sections[msv_idx].body_bounds;
                let viewport_rows = self.viewport_rows_from_layout(body_b, msv_idx, lh);
                let SectionController::Tree(tc) = &mut self.sections[section] else {
                    return SidebarEvent::Ignored;
                };
                tc.page_scroll(-(viewport_rows as isize), viewport_rows);
                SidebarEvent::ScrollChanged { section }
            }
            MultiSectionViewHit::Scrollbar {
                section: msv_idx,
                kind: ScrollbarHit::TrackAfter,
            } => {
                let section = map[msv_idx];
                let body_b = layout.sections[msv_idx].body_bounds;
                let viewport_rows = self.viewport_rows_from_layout(body_b, msv_idx, lh);
                let SectionController::Tree(tc) = &mut self.sections[section] else {
                    return SidebarEvent::Ignored;
                };
                tc.page_scroll(viewport_rows as isize, viewport_rows);
                SidebarEvent::ScrollChanged { section }
            }
            MultiSectionViewHit::PanelScrollbar {
                kind: ScrollbarHit::Thumb,
            } => {
                if let Some(thumb) = layout.panel_scrollbar_thumb {
                    // Total content the panel scrolls through — match
                    // `MultiSectionView::layout`'s `total_content`
                    // (sections + dividers) so `max_scroll` agrees with
                    // the painted thumb's travel range. The legacy code
                    // dropped divider sizes, breaking drag when
                    // `allow_resize=true`.
                    let sections_total: f32 = layout.sections.iter().map(|s| s.resolved_size).sum();
                    let dividers_total: f32 = layout.dividers.iter().map(|d| d.bounds.height).sum();
                    let total = sections_total + dividers_total;
                    let max_scroll = (total - rect.height).max(0.0);
                    // Thumb height comes straight from the layout (`panel_scrollbar_thumb`,
                    // computed once via `fit_thumb`) instead of re-deriving the min-thumb
                    // formula here.
                    let travel = (rect.height - thumb.height).max(0.0);
                    let _ = lh;
                    self.panel_drag =
                        Some(ThumbDrag::begin(y, self.panel_scroll, travel, max_scroll));
                    SidebarEvent::Consumed
                } else {
                    SidebarEvent::Ignored
                }
            }
            MultiSectionViewHit::PanelScrollbar {
                kind: ScrollbarHit::TrackBefore,
            } => {
                let total: f32 = layout.sections.iter().map(|s| s.resolved_size).sum();
                let max_scroll = (total - rect.height).max(0.0);
                self.panel_scroll = (self.panel_scroll - rect.height).clamp(0.0, max_scroll);
                SidebarEvent::Consumed
            }
            MultiSectionViewHit::PanelScrollbar {
                kind: ScrollbarHit::TrackAfter,
            } => {
                let total: f32 = layout.sections.iter().map(|s| s.resolved_size).sum();
                let max_scroll = (total - rect.height).max(0.0);
                self.panel_scroll = (self.panel_scroll + rect.height).clamp(0.0, max_scroll);
                SidebarEvent::Consumed
            }
            _ => SidebarEvent::Ignored,
        }
    }

    fn double_click(
        &mut self,
        rect: Rect,
        x: f32,
        y: f32,
        lh: f32,
        metrics: &MsvLayoutMetrics,
        _backend: Option<&dyn Backend>,
    ) -> SidebarEvent {
        let (layout, map) = self.compute_layout(rect, metrics, lh);
        let (view, _) = self.build_view();
        match layout.hit_test(x, y) {
            MultiSectionViewHit::Body {
                section: msv_idx, ..
            } => {
                let section = map[msv_idx];
                let body_b = layout.sections[msv_idx].body_bounds;
                if let SectionBody::Tree(t) = &view.sections[msv_idx].body {
                    let tree = t.clone();
                    let inner = self.compute_tree_layout(body_b, &tree, lh);
                    // Both Row and Chevron regions count as double-click → RowActivated.
                    let hit_idx = match inner.hit_test(x - body_b.x, y - body_b.y) {
                        TreeViewHit::Row(idx) | TreeViewHit::Chevron(idx) => Some(idx),
                        TreeViewHit::Empty => None,
                    };
                    if let Some(idx) = hit_idx {
                        let path = tree.rows[idx].path.clone();
                        if let SectionController::Tree(tc) = &mut self.sections[section] {
                            tc.set_selected_path(Some(path.clone()));
                        }
                        return SidebarEvent::RowActivated { section, path };
                    }
                }
                SidebarEvent::Ignored
            }
            _ => SidebarEvent::Ignored,
        }
    }

    fn right_click(
        &mut self,
        rect: Rect,
        position: Point,
        lh: f32,
        metrics: &MsvLayoutMetrics,
    ) -> SidebarEvent {
        let (layout, map) = self.compute_layout(rect, metrics, lh);
        let (view, _) = self.build_view();
        match layout.hit_test(position.x, position.y) {
            MultiSectionViewHit::Body {
                section: msv_idx, ..
            } => {
                let section = map[msv_idx];
                let body_b = layout.sections[msv_idx].body_bounds;
                let tree = match &view.sections[msv_idx].body {
                    SectionBody::Tree(t) => t.clone(),
                    _ => return SidebarEvent::Ignored,
                };
                let inner = self.compute_tree_layout(body_b, &tree, lh);
                match inner.hit_test(position.x - body_b.x, position.y - body_b.y) {
                    TreeViewHit::Row(idx) | TreeViewHit::Chevron(idx) => {
                        let path = tree.rows[idx].path.clone();
                        self.focus.set_active(Some(section));
                        if let SectionController::Tree(tc) = &mut self.sections[section] {
                            tc.set_selected_path(Some(path.clone()));
                        }
                        SidebarEvent::ContextMenuRequested {
                            section,
                            path,
                            position,
                        }
                    }
                    TreeViewHit::Empty => SidebarEvent::Ignored,
                }
            }
            _ => SidebarEvent::Ignored,
        }
    }

    fn drag_to(&mut self, y: f32) -> SidebarEvent {
        if let Some(drag) = &self.panel_drag {
            let Some(new) = drag.offset_at(y) else {
                return SidebarEvent::Ignored;
            };
            if (new - self.panel_scroll).abs() < 0.5 {
                return SidebarEvent::Ignored;
            }
            self.panel_scroll = new;
            return SidebarEvent::Consumed;
        }
        let Some(drag) = &self.scroll_drag else {
            return SidebarEvent::Ignored;
        };
        let Some(new) = drag.drag.offset_at(y) else {
            return SidebarEvent::Ignored;
        };
        let new = new.round() as usize;
        let section = drag.section;
        let SectionController::Tree(tc) = &mut self.sections[section] else {
            return SidebarEvent::Ignored;
        };
        if new == tc.scroll_offset() {
            return SidebarEvent::Ignored;
        }
        tc.set_scroll_offset(new);
        SidebarEvent::Consumed
    }

    fn cycle_active(&mut self, delta: isize) {
        let n = self.defs.len();
        if n == 0 {
            return;
        }
        self.focus.cycle(delta);
        // Skip invisible sections.
        for _ in 0..n {
            if let Some(idx) = self.focus.active() {
                if self.visible[idx] {
                    return;
                }
                self.focus.cycle(delta);
            } else {
                return;
            }
        }
    }

    fn scroll_panel(&mut self, rect: Rect, dy: f32, lh: f32, metrics: &MsvLayoutMetrics) {
        let (layout, _) = self.compute_layout(rect, metrics, lh);
        let total: f32 = layout.sections.iter().map(|s| s.resolved_size).sum();
        let max = (total - rect.height).max(0.0);
        self.panel_scroll = (self.panel_scroll + dy).clamp(0.0, max);
    }

    fn scroll_to_active_section(&mut self, rect: Rect, lh: f32, metrics: &MsvLayoutMetrics) {
        let Some(idx) = self.focus.active() else {
            return;
        };
        let (layout, map) = self.compute_layout(rect, metrics, lh);
        let Some(msv_idx) = map.iter().position(|&s| s == idx) else {
            return;
        };
        if msv_idx >= layout.sections.len() {
            return;
        }
        let total: f32 = layout.sections.iter().map(|s2| s2.resolved_size).sum();
        let max = (total - rect.height).max(0.0);
        let s = &layout.sections[msv_idx];
        let content_top = s.header_bounds.y - rect.y + self.panel_scroll;
        let content_bottom = content_top + s.resolved_size;
        if content_top < self.panel_scroll {
            self.panel_scroll = content_top.clamp(0.0, max);
        } else if content_bottom > self.panel_scroll + rect.height {
            self.panel_scroll = (content_bottom - rect.height).clamp(0.0, max);
        }
    }

    /// Route a scroll-wheel event to the tree section whose bounds
    /// contain `position`. Returns `true` when a section was hit and
    /// its scroll offset updated; returns `false` when the position
    /// lies outside all sections or over a non-tree section (caller
    /// falls back to active-section scroll).
    ///
    /// Used exclusively from the `PerSection` scroll-mode path in
    /// `handle_inner` so that hovering over section B while section A
    /// is active scrolls section B — matching the native desktop
    /// convention (scroll follows cursor, not focus).
    fn scroll_section_at(
        &mut self,
        position: Point,
        rect: Rect,
        rows: isize,
        lh: f32,
        metrics: &MsvLayoutMetrics,
    ) -> bool {
        let (layout, map) = self.compute_layout(rect, metrics, lh);
        let msv_idx = match layout.hit_test(position.x, position.y) {
            MultiSectionViewHit::Body { section }
            | MultiSectionViewHit::Header { section, .. }
            | MultiSectionViewHit::Scrollbar { section, .. } => section,
            _ => return false,
        };
        let section = map[msv_idx];
        let body_b = layout.sections[msv_idx].body_bounds;
        let viewport_rows = self.viewport_rows_from_layout(body_b, msv_idx, lh);
        let SectionController::Tree(tc) = &mut self.sections[section] else {
            return false;
        };
        let row_count = tc.rows().len();
        let max = row_count.saturating_sub(viewport_rows) as isize;
        let cur = tc.scroll_offset() as isize;
        let new = (cur + rows).max(0).min(max) as usize;
        tc.set_scroll_offset(new);
        true
    }

    fn scroll_active(&mut self, rect: Rect, delta: isize, lh: f32, metrics: &MsvLayoutMetrics) {
        let Some(idx) = self.focus.active() else {
            return;
        };
        if !matches!(self.sections[idx], SectionController::Tree(_)) {
            return;
        }
        let (layout, map) = self.compute_layout(rect, metrics, lh);
        let Some(msv_idx) = map.iter().position(|&s| s == idx) else {
            return;
        };
        let body_b = layout.sections[msv_idx].body_bounds;
        let viewport_rows = self.viewport_rows_from_layout(body_b, msv_idx, lh);
        let SectionController::Tree(tc) = &mut self.sections[idx] else {
            return;
        };
        let row_count = tc.rows().len();
        let max = row_count.saturating_sub(viewport_rows) as isize;
        let cur = tc.scroll_offset() as isize;
        let new = (cur + delta).max(0).min(max) as usize;
        tc.set_scroll_offset(new);
    }

    fn select_first_of_active(&mut self) {
        let Some(idx) = self.focus.active() else {
            return;
        };
        let SectionController::Tree(tc) = &mut self.sections[idx] else {
            return;
        };
        if let Some(first) = tc.rows().first() {
            let path = first.path.clone();
            tc.set_selected_path(Some(path));
            tc.set_scroll_offset(0);
        }
    }
}

fn form_field_measure(
    field: &crate::primitives::form::FormField,
    row_h: f32,
    char_w: f32,
) -> FormFieldMeasure {
    match &field.kind {
        FieldKind::ToggleGroup { toggles } => {
            let label_w = field.label.visible_width() as f32 * char_w;
            let start_x = if label_w > 0.0 {
                label_w + char_w * 2.0
            } else {
                char_w
            };
            let items = toggles
                .iter()
                .map(|t| FormItemMeasure {
                    id: t.id,
                    width: (t.label.chars().count() as f32 + 2.0) * char_w,
                })
                .collect();
            FormFieldMeasure::with_items(row_h, start_x, char_w, items)
        }
        FieldKind::ButtonRow { buttons } => {
            let label_w = field.label.visible_width() as f32 * char_w;
            let start_x = if label_w > 0.0 {
                label_w + char_w * 2.0
            } else {
                char_w
            };
            let items = buttons
                .iter()
                .map(|b| {
                    let icon_w = b
                        .icon
                        .as_ref()
                        .map(|i| {
                            let gw = i.fallback.chars().count() as f32;
                            if b.label.is_empty() {
                                gw
                            } else {
                                gw + 1.0
                            }
                        })
                        .unwrap_or(0.0);
                    FormItemMeasure {
                        id: b.id,
                        width: (b.label.chars().count() as f32 + icon_w + 2.0) * char_w,
                    }
                })
                .collect();
            FormFieldMeasure::with_items(row_h, start_x, char_w, items)
        }
        FieldKind::SegmentedControl { options, .. } => {
            let label_w = field.label.visible_width() as f32 * char_w;
            let start_x = if label_w > 0.0 {
                label_w + char_w * 2.0
            } else {
                char_w
            };
            let items = options
                .iter()
                .enumerate()
                .map(|(idx, opt)| FormItemMeasure {
                    id: WidgetId::new(format!("{}__seg_{idx}", field.id.as_str())),
                    width: (opt.chars().count() as f32 + 2.0) * char_w,
                })
                .collect();
            FormFieldMeasure::with_items(row_h, start_x, 0.0, items)
        }
        FieldKind::TextArea { visible_rows, .. } => {
            FormFieldMeasure::new(row_h * *visible_rows as f32)
        }
        _ => FormFieldMeasure::new(row_h),
    }
}

fn body_measure(section: &Section, lh: f32) -> SectionMeasure {
    let aux_size = if section.aux.is_some() {
        (lh * 1.4).round()
    } else {
        0.0
    };
    let item_h = (lh * 1.4).round();
    let content_size = match &section.body {
        SectionBody::Tree(t) => {
            let header_h = (lh * 1.2).round();
            t.rows
                .iter()
                .map(|r| {
                    if matches!(r.decoration, crate::types::Decoration::Header) {
                        header_h
                    } else {
                        item_h
                    }
                })
                .sum()
        }
        SectionBody::List(l) => {
            let title_h = if l.title.is_some() { lh } else { 0.0 };
            title_h + l.items.len() as f32 * item_h
        }
        SectionBody::Form(f) => f.fields.len() as f32 * item_h,
        _ => 0.0,
    };
    SectionMeasure {
        content_size,
        aux_size,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Decoration;

    fn sample_defs() -> Vec<SidebarSectionDef> {
        vec![
            SidebarSectionDef::new("variables", "VARIABLES"),
            SidebarSectionDef::new("watch", "WATCH"),
            SidebarSectionDef::new("breakpoints", "BREAKPOINTS"),
        ]
    }

    fn fake_rows(prefix: &str, n: usize) -> Vec<TreeRow> {
        (0..n)
            .map(|i| TreeRow {
                path: vec![i as u16],
                indent: 0,
                icon: None,
                text: StyledText::plain(format!("{prefix}{i}")),
                badge: None,
                is_expanded: None,
                decoration: Decoration::Normal,
                edit: None,
            })
            .collect()
    }

    #[test]
    fn new_starts_with_no_active_section() {
        let ss = SidebarSystem::new(sample_defs());
        assert_eq!(ss.active_section(), None);
        assert_eq!(ss.scroll_offset(0), 0);
        assert_eq!(ss.selected_path(0), None);
        assert!(!ss.is_collapsed(0));
    }

    #[test]
    fn set_rows_updates_section_data() {
        let mut ss = SidebarSystem::new(sample_defs());
        let tc = match &ss.sections[0] {
            SectionController::Tree(tc) => tc,
            _ => panic!("expected tree section"),
        };
        assert!(tc.rows().is_empty());
        ss.set_rows(0, fake_rows("v", 5));
        let tc = match &ss.sections[0] {
            SectionController::Tree(tc) => tc,
            _ => panic!("expected tree section"),
        };
        assert_eq!(tc.rows().len(), 5);
    }

    #[test]
    fn cycle_active_wraps() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.cycle_active(1);
        assert_eq!(ss.active_section(), Some(0));
        ss.cycle_active(1);
        assert_eq!(ss.active_section(), Some(1));
        ss.cycle_active(1);
        assert_eq!(ss.active_section(), Some(2));
        ss.cycle_active(1);
        assert_eq!(ss.active_section(), Some(0));
    }

    #[test]
    fn cycle_active_backward_wraps() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.cycle_active(-1);
        assert_eq!(ss.active_section(), Some(2));
        ss.cycle_active(-1);
        assert_eq!(ss.active_section(), Some(1));
    }

    #[test]
    fn set_active_and_selected_path() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 3));
        ss.set_active_section(Some(0));
        ss.set_selected_path(0, Some(vec![1]));
        assert_eq!(ss.active_section(), Some(0));
        assert_eq!(ss.selected_path(0), Some(&vec![1]));
    }

    #[test]
    fn select_first_of_active_sets_path_and_resets_scroll() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(1, fake_rows("w", 5));
        if let SectionController::Tree(tc) = &mut ss.sections[1] {
            tc.set_scroll_offset(3);
        }
        ss.focus.set_active(Some(1));
        ss.select_first_of_active();
        assert_eq!(ss.selected_path(1), Some(&vec![0]));
        assert_eq!(ss.scroll_offset(1), 0);
    }

    #[test]
    fn page_scroll_clamps_to_bounds() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 20));
        if let SectionController::Tree(tc) = &mut ss.sections[0] {
            tc.page_scroll(100, 5);
        }
        assert_eq!(ss.scroll_offset(0), 15); // 20 - 5
        if let SectionController::Tree(tc) = &mut ss.sections[0] {
            tc.page_scroll(-100, 5);
        }
        assert_eq!(ss.scroll_offset(0), 0);
    }

    #[test]
    fn build_view_produces_correct_sections() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 3));
        ss.focus.set_active(Some(0));
        let (view, _) = ss.build_view();
        assert_eq!(view.sections.len(), 3);
        assert!(view.sections[0].header.title.spans[0].text.starts_with("▶"));
        assert_eq!(view.active_section, Some(0));
    }

    // ── Selection-mode tests ────────────────────────────────────────

    fn selection_sidebar() -> SidebarSystem {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_navigation_mode(NavigationMode::Selection);
        ss.set_rows(0, fake_rows("v", 5));
        ss.set_rows(1, fake_rows("w", 3));
        ss.set_rows(2, fake_rows("b", 4));
        ss.focus.set_active(Some(0));
        ss
    }

    #[test]
    fn selection_down_selects_first_row_when_none_selected() {
        let mut ss = selection_sidebar();
        let ev = ss.move_selection_by(1, 10);
        assert_eq!(ss.selected_path(0), Some(&vec![0]));
        assert!(matches!(ev, SidebarEvent::RowSelected { section: 0, .. }));
    }

    #[test]
    fn selection_down_advances_to_next_row() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![0]));
        let ev = ss.move_selection_by(1, 10);
        assert_eq!(ss.selected_path(0), Some(&vec![1]));
        assert!(matches!(ev, SidebarEvent::RowSelected { section: 0, .. }));
    }

    #[test]
    fn selection_up_moves_to_previous_row() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![2]));
        ss.move_selection_by(-1, 10);
        assert_eq!(ss.selected_path(0), Some(&vec![1]));
    }

    #[test]
    fn selection_clamps_at_first_row() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![0]));
        let ev = ss.move_selection_by(-1, 10);
        assert_eq!(ss.selected_path(0), Some(&vec![0]));
        assert_eq!(ev, SidebarEvent::Consumed);
    }

    #[test]
    fn selection_clamps_at_last_row() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![4]));
        let ev = ss.move_selection_by(1, 10);
        assert_eq!(ss.selected_path(0), Some(&vec![4]));
        assert_eq!(ev, SidebarEvent::Consumed);
    }

    #[test]
    fn selection_up_with_no_selection_selects_last_row() {
        let mut ss = selection_sidebar();
        ss.move_selection_by(-1, 10);
        assert_eq!(ss.selected_path(0), Some(&vec![4]));
    }

    #[test]
    fn selection_home_jumps_to_first_row() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![3]));
        ss.jump_selection_to_edge_by(true, 10);
        assert_eq!(ss.selected_path(0), Some(&vec![0]));
    }

    #[test]
    fn selection_end_jumps_to_last_row() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![0]));
        ss.jump_selection_to_edge_by(false, 10);
        assert_eq!(ss.selected_path(0), Some(&vec![4]));
    }

    #[test]
    fn selection_page_down_jumps_by_viewport() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![0]));
        let jump = (3_usize.max(1) - 1).max(1) as isize; // viewport=3 → jump=2
        ss.move_selection_by(jump, 3);
        assert_eq!(ss.selected_path(0), Some(&vec![2]));
    }

    #[test]
    fn selection_enter_emits_row_activated() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![2]));
        let ev = ss.activate_selection();
        assert_eq!(
            ev,
            SidebarEvent::RowActivated {
                section: 0,
                path: vec![2]
            }
        );
    }

    #[test]
    fn selection_enter_with_no_selection_returns_ignored() {
        let ss = selection_sidebar();
        let ev = ss.activate_selection();
        assert_eq!(ev, SidebarEvent::Ignored);
    }

    #[test]
    fn selection_scroll_follows_when_row_below_viewport() {
        let mut ss = selection_sidebar();
        // 5 rows, viewport=3, start at row 0 with offset 0.
        ss.set_selected_path(0, Some(vec![0]));
        // Move down 4 times: 0→1→2→3→4
        for _ in 0..4 {
            ss.move_selection_by(1, 3);
        }
        assert_eq!(ss.selected_path(0), Some(&vec![4]));
        // scroll_offset should have followed: row 4 visible in 3-row viewport
        // means offset must be at least 2.
        assert!(ss.scroll_offset(0) >= 2, "offset={}", ss.scroll_offset(0));
        assert!(ss.scroll_offset(0) + 3 > 4);
    }

    #[test]
    fn selection_scroll_follows_when_row_above_viewport() {
        let mut ss = selection_sidebar();
        ss.set_selected_path(0, Some(vec![4]));
        if let SectionController::Tree(tc) = &mut ss.sections[0] {
            tc.set_scroll_offset(2);
        }
        // Move up to row 0.
        for _ in 0..4 {
            ss.move_selection_by(-1, 3);
        }
        assert_eq!(ss.selected_path(0), Some(&vec![0]));
        assert_eq!(ss.scroll_offset(0), 0);
    }

    #[test]
    fn selection_collapsed_section_returns_ignored() {
        let mut ss = selection_sidebar();
        ss.set_collapsed(0, true);
        let ev = ss.move_selection_by(1, 10);
        assert_eq!(ev, SidebarEvent::Ignored);
    }

    #[test]
    fn selection_no_active_section_returns_ignored() {
        let mut ss = selection_sidebar();
        ss.focus.set_active(None);
        let ev = ss.move_selection_by(1, 10);
        assert_eq!(ev, SidebarEvent::Ignored);
    }

    #[test]
    fn navigation_mode_defaults_to_scroll() {
        let ss = SidebarSystem::new(sample_defs());
        assert_eq!(ss.navigation_mode(), NavigationMode::Scroll);
    }

    #[test]
    fn scroll_mode_defaults_to_per_section() {
        let ss = SidebarSystem::new(sample_defs());
        assert_eq!(ss.scroll_mode(), ScrollMode::PerSection);
        assert_eq!(ss.panel_scroll(), 0.0);
    }

    #[test]
    fn set_scroll_mode_whole_panel() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_scroll_mode(ScrollMode::WholePanel);
        assert_eq!(ss.scroll_mode(), ScrollMode::WholePanel);
    }

    #[test]
    fn set_panel_scroll_clamps_negative() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_scroll_mode(ScrollMode::WholePanel);
        ss.set_panel_scroll(-10.0);
        assert_eq!(ss.panel_scroll(), 0.0);
    }

    #[test]
    fn build_view_uses_scroll_mode() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 5));
        ss.set_scroll_mode(ScrollMode::WholePanel);
        ss.set_panel_scroll(10.0);
        let (view, _) = ss.build_view();
        assert_eq!(view.scroll_mode, ScrollMode::WholePanel);
        assert_eq!(view.panel_scroll, 10.0);
    }

    // ── Section visibility ──────────────────────────────────────────

    #[test]
    fn sections_visible_by_default() {
        let ss = SidebarSystem::new(sample_defs());
        assert!(ss.is_section_visible(0));
        assert!(ss.is_section_visible(1));
    }

    #[test]
    fn hidden_section_excluded_from_view() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 3));
        ss.set_rows(1, fake_rows("w", 2));
        ss.set_section_visible(0, false);
        let (view, map) = ss.build_view();
        assert_eq!(view.sections.len(), 2);
        assert_eq!(view.sections[0].id, "watch");
        assert_eq!(view.sections[1].id, "breakpoints");
        assert_eq!(map, vec![1, 2]);
    }

    #[test]
    fn tab_skips_hidden_section() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 3));
        ss.set_rows(1, fake_rows("w", 2));
        ss.set_active_section(Some(0));
        ss.set_section_visible(1, false);
        ss.cycle_active(1);
        // Should skip section 1 (hidden) and land on section 0 (wraps).
        assert_ne!(ss.active_section(), Some(1));
    }

    // ── Section badges ──────────────────────────────────────────────

    #[test]
    fn badge_defaults_to_none() {
        let ss = SidebarSystem::new(sample_defs());
        assert_eq!(ss.section_badge(0), None);
    }

    #[test]
    fn set_badge_appears_in_view() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 3));
        ss.set_section_badge(0, Some(StyledText::plain("(3)")));
        let (view, _) = ss.build_view();
        assert_eq!(
            view.sections[0].header.badge,
            Some(StyledText::plain("(3)"))
        );
    }

    // ── Form section support ───────────────────────────────────────────

    fn mixed_defs() -> Vec<SidebarSectionDef> {
        vec![
            SidebarSectionDef::form("search", "SEARCH"),
            SidebarSectionDef::new("results", "RESULTS"),
        ]
    }

    fn sample_form() -> Form {
        use crate::primitives::form::{FieldKind, FormField};
        Form {
            id: WidgetId::new("search-form"),
            fields: vec![
                FormField {
                    id: WidgetId::new("query"),
                    label: StyledText::plain("Query"),
                    kind: FieldKind::TextInput {
                        value: String::new(),
                        placeholder: "Search...".into(),
                        cursor: None,
                        selection_anchor: None,
                    },
                    hint: StyledText::default(),
                    disabled: false,
                    validation: None,
                },
                FormField {
                    id: WidgetId::new("case-sensitive"),
                    label: StyledText::plain("Case"),
                    kind: FieldKind::Toggle { value: false },
                    hint: StyledText::default(),
                    disabled: false,
                    validation: None,
                },
            ],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        }
    }

    #[test]
    fn mixed_sidebar_creates_correct_controllers() {
        let ss = SidebarSystem::new(mixed_defs());
        assert!(matches!(ss.sections[0], SectionController::Form(_)));
        assert!(matches!(ss.sections[1], SectionController::Tree(_)));
    }

    #[test]
    fn form_def_defaults_to_content_size() {
        let def = SidebarSectionDef::form("s", "S");
        assert_eq!(def.kind, SectionKind::Form);
        assert_eq!(def.size, SectionSize::Content);
    }

    #[test]
    fn set_form_updates_form_section() {
        let mut ss = SidebarSystem::new(mixed_defs());
        assert!(ss.form(0).is_none());
        ss.set_form(0, sample_form());
        assert!(ss.form(0).is_some());
        assert_eq!(ss.form(0).unwrap().fields.len(), 2);
    }

    #[test]
    fn set_form_on_tree_section_is_noop() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_form(1, sample_form());
        assert!(ss.form(1).is_none());
    }

    #[test]
    fn set_rows_on_form_section_is_noop() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_rows(0, fake_rows("v", 5));
        assert_eq!(ss.scroll_offset(0), 0);
        assert_eq!(ss.selected_path(0), None);
    }

    #[test]
    fn build_view_produces_form_body() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_form(0, sample_form());
        ss.set_rows(1, fake_rows("r", 3));
        let (view, _) = ss.build_view();
        assert_eq!(view.sections.len(), 2);
        assert!(matches!(view.sections[0].body, SectionBody::Form(_)));
        assert!(matches!(view.sections[1].body, SectionBody::Tree(_)));
    }

    #[test]
    fn build_view_form_section_has_focus() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_form(0, sample_form());
        ss.focus.set_active(Some(0));
        let (view, _) = ss.build_view();
        match &view.sections[0].body {
            SectionBody::Form(f) => assert!(f.has_focus),
            _ => panic!("expected Form body"),
        }
    }

    #[test]
    fn focus_form_renders_form_focused_while_tree_section_active() {
        // The FILTER form (section 0) should render with a cursor while a tree
        // section (1) drives nav.
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_form(0, sample_form());
        ss.set_rows(1, fake_rows("r", 3));
        // Tree section is the active/nav section.
        ss.set_active_section(Some(1));
        // Without focus_form, the form is not render-focused.
        let (view, _) = ss.build_view();
        match &view.sections[0].body {
            SectionBody::Form(f) => assert!(!f.has_focus),
            _ => panic!("expected Form body"),
        }
        // Mark the form render-focused without changing the nav section.
        ss.focus_form(0, true);
        assert_eq!(ss.active_section(), Some(1));
        assert!(ss.form_has_focus(0));
        let (view, _) = ss.build_view();
        match &view.sections[0].body {
            SectionBody::Form(f) => assert!(f.has_focus),
            _ => panic!("expected Form body"),
        }
    }

    #[test]
    fn focus_form_survives_rebuild_via_reapply() {
        // The app re-creates the SidebarSystem each frame; focus_form is
        // re-applied after rebuild to keep the cursor visible.
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_form(0, sample_form());
        ss.set_active_section(Some(1));
        ss.focus_form(0, true);
        let (view, _) = ss.build_view();
        match &view.sections[0].body {
            SectionBody::Form(f) => assert!(f.has_focus),
            _ => panic!("expected Form body"),
        }
    }

    #[test]
    fn focus_form_can_be_cleared() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_form(0, sample_form());
        ss.set_active_section(Some(1));
        ss.focus_form(0, true);
        assert!(ss.form_has_focus(0));
        ss.focus_form(0, false);
        assert!(!ss.form_has_focus(0));
        let (view, _) = ss.build_view();
        match &view.sections[0].body {
            SectionBody::Form(f) => assert!(!f.has_focus),
            _ => panic!("expected Form body"),
        }
    }

    #[test]
    fn focus_form_on_tree_section_is_noop() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_rows(1, fake_rows("r", 3));
        ss.focus_form(1, true);
        assert!(!ss.form_has_focus(1));
    }

    #[test]
    fn focus_form_out_of_range_is_noop() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.focus_form(99, true);
        assert!(!ss.form_has_focus(99));
    }

    #[test]
    fn active_form_section_still_render_focused_without_focus_form() {
        // The pre-existing behaviour (active form section renders
        // focused) must keep working when focus_form was never called.
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_form(0, sample_form());
        ss.set_active_section(Some(0));
        assert!(!ss.form_has_focus(0)); // focus_form not called
        let (view, _) = ss.build_view();
        match &view.sections[0].body {
            SectionBody::Form(f) => assert!(f.has_focus), // active ⇒ focused
            _ => panic!("expected Form body"),
        }
    }

    #[test]
    fn build_view_empty_form_section() {
        let ss = SidebarSystem::new(mixed_defs());
        let (view, _) = ss.build_view();
        match &view.sections[0].body {
            SectionBody::Form(f) => assert!(f.fields.is_empty()),
            _ => panic!("expected Form body"),
        }
    }

    #[test]
    fn tab_cycles_through_mixed_sections() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_form(0, sample_form());
        ss.set_rows(1, fake_rows("r", 3));
        ss.cycle_active(1);
        assert_eq!(ss.active_section(), Some(0));
        ss.cycle_active(1);
        assert_eq!(ss.active_section(), Some(1));
        ss.cycle_active(1);
        assert_eq!(ss.active_section(), Some(0));
    }

    #[test]
    fn section_kind_accessor() {
        let ss = SidebarSystem::new(mixed_defs());
        assert_eq!(ss.section_kind(0), Some(SectionKind::Form));
        assert_eq!(ss.section_kind(1), Some(SectionKind::Tree));
        assert_eq!(ss.section_kind(99), None);
    }

    #[test]
    fn selection_on_form_section_returns_ignored() {
        let mut ss = SidebarSystem::new(mixed_defs());
        ss.set_navigation_mode(NavigationMode::Selection);
        ss.set_form(0, sample_form());
        ss.focus.set_active(Some(0));
        let ev = ss.move_selection_by(1, 10);
        assert_eq!(ev, SidebarEvent::Ignored);
    }

    // ── Form click event dispatch ──────────────────────────────────────

    #[test]
    fn form_click_text_input_emits_focus_changed() {
        let form = sample_form();
        let ev = form_click_event(&form, &WidgetId::new("query"));
        assert_eq!(
            ev,
            FormEvent::FocusChanged {
                id: WidgetId::new("query")
            }
        );
    }

    #[test]
    fn form_click_toggle_emits_toggle_changed_with_flipped_value() {
        let form = sample_form();
        let ev = form_click_event(&form, &WidgetId::new("case-sensitive"));
        assert_eq!(
            ev,
            FormEvent::ToggleChanged {
                id: WidgetId::new("case-sensitive"),
                value: true, // was false, click flips to true
            }
        );
    }

    #[test]
    fn form_click_button_emits_button_clicked() {
        use crate::primitives::form::FormField;
        let form = Form {
            id: WidgetId::new("f"),
            fields: vec![FormField {
                id: WidgetId::new("submit"),
                label: StyledText::plain("Go"),
                kind: FieldKind::Button,
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let ev = form_click_event(&form, &WidgetId::new("submit"));
        assert_eq!(
            ev,
            FormEvent::ButtonClicked {
                id: WidgetId::new("submit")
            }
        );
    }

    #[test]
    fn form_click_toggle_group_item_emits_toggle_changed() {
        use crate::primitives::form::{FormField, ToggleGroupItem};
        let form = Form {
            id: WidgetId::new("f"),
            fields: vec![FormField {
                id: WidgetId::new("flags"),
                label: StyledText::plain("Flags"),
                kind: FieldKind::ToggleGroup {
                    toggles: vec![
                        ToggleGroupItem {
                            id: WidgetId::new("case"),
                            label: "Aa".into(),
                            value: true,
                        },
                        ToggleGroupItem {
                            id: WidgetId::new("regex"),
                            label: ".*".into(),
                            value: false,
                        },
                    ],
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let ev = form_click_event(&form, &WidgetId::new("regex"));
        assert_eq!(
            ev,
            FormEvent::ToggleChanged {
                id: WidgetId::new("regex"),
                value: true, // was false, flipped
            }
        );
    }

    #[test]
    fn form_click_button_row_item_emits_button_clicked() {
        use crate::primitives::form::{ButtonRowItem, FormField};
        let form = Form {
            id: WidgetId::new("f"),
            fields: vec![FormField {
                id: WidgetId::new("actions"),
                label: StyledText::plain(""),
                kind: FieldKind::ButtonRow {
                    buttons: vec![ButtonRowItem {
                        id: WidgetId::new("replace-all"),
                        label: "Replace All".into(),
                        disabled: false,
                        icon: None,
                    }],
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let ev = form_click_event(&form, &WidgetId::new("replace-all"));
        assert_eq!(
            ev,
            FormEvent::ButtonClicked {
                id: WidgetId::new("replace-all")
            }
        );
    }

    #[test]
    fn form_click_unknown_id_emits_focus_changed() {
        let form = sample_form();
        let ev = form_click_event(&form, &WidgetId::new("nonexistent"));
        assert_eq!(
            ev,
            FormEvent::FocusChanged {
                id: WidgetId::new("nonexistent")
            }
        );
    }

    // ── TUI scrollbar thumb drag ────────────────────────────────────────
    //
    // TUI mode passes mouse coordinates in cell units (1 cell per row)
    // and `MsvLayoutMetrics::scrollbar_size = 1.0`. The drag-travel math in
    // `drag_to` must produce a non-zero per-section scroll change for a
    // 1-cell mouse drag, the same way it does for a 1-line GTK drag.
    //
    // Pre-fix: the per-section scrollbar thumb did not move under drag in
    // TUI because the layout produced thumb_bounds with `thumb_h == sb.height`
    // (no spare travel) when section sizing rounded the resolved body
    // dimensions to integer cells.

    #[test]
    fn tui_per_section_scrollbar_thumb_drag_scrolls_active_section() {
        // TUI metrics: 1-cell rows, 1-cell scrollbar gutter, integer-cell
        // section heights. Use PerSection scroll mode so the per-section
        // gutter (and `ScrollDrag`) is exercised.
        let mut ss = SidebarSystem::new(vec![SidebarSectionDef::new("t", "T")]);
        ss.set_rows(0, fake_rows("r", 30));
        ss.set_active_section(Some(0));
        ss.set_scroll_mode(ScrollMode::PerSection);

        let metrics = MsvLayoutMetrics {
            header_size: 1.0,
            divider_size: 0.0,
            scrollbar_size: 1.0,
            cell_quantum: 1.0,
        };
        ss.set_backend_info(1.0, metrics);

        // 21-cell tall sidebar: 1 cell header + 20 cells body. Body shows
        // 20 of the 30 rows → max_offset = 10, thumb has 6 cells of travel.
        let rect = Rect::new(0.0, 0.0, 20.0, 21.0);

        // Compute layout to find the painted thumb position.
        let (layout, _map) = ss.compute_layout(rect, &metrics, 1.0);
        let sb = layout.sections[0]
            .scrollbar_bounds
            .expect("overflow → per-section scrollbar reserved");
        let thumb = layout.sections[0]
            .thumb_bounds
            .expect("Tree body → thumb bounds computed from scroll state");

        // Click on the painted thumb. Mouse coords are integer cells in TUI.
        // TUI mouse coords come in as integer cells.
        let click_x = sb.x.round();
        let click_y = thumb.y.round();
        let down = UiEvent::MouseDown {
            widget: None,
            button: MouseButton::Left,
            position: Point::new(click_x, click_y),
            modifiers: Modifiers::default(),
        };
        let _ = ss.handle_cached(&down, rect);

        // Drag down 1 cell. In TUI cell units the crossterm Drag event
        // delivers integer-cell positions — simulate a 1-cell vertical
        // movement.
        let move_ev = UiEvent::MouseMoved {
            position: Point::new(click_x, click_y + 1.0),
            buttons: ButtonMask {
                left: true,
                ..Default::default()
            },
        };
        let _ = ss.handle_cached(&move_ev, rect);

        // The active section's scroll_offset must have advanced. Pre-fix
        // it stayed at 0 because the cell-precise drag was lost to either
        // (a) a `travel <= 0.0` guard when `thumb_h >= sb.height`, or
        // (b) a drow that rounded to 0 rows.
        let offset = ss.scroll_offset(0);
        assert!(
            offset > 0,
            "1-cell TUI drag on per-section thumb should advance scroll \
             offset, but it stayed at {offset} (sb={sb:?}, thumb={thumb:?})"
        );
    }

    /// Repro of the `examples/common/multi_tree.rs` shape under TUI:
    /// 4 `Content`-sized sections that together overflow the viewport
    /// by just 1 row, in `WholePanel` mode. Pre-fix: a 1-cell drag on
    /// the panel thumb produced no scroll, because the painted thumb
    /// nearly filled the gutter (travel < 1 cell) AND the drag-math
    /// guard returned `Ignored` for sub-half-cell `panel_scroll` deltas.
    #[test]
    fn tui_panel_drag_works_in_multi_tree_example_shape() {
        let mut ss = SidebarSystem::new(vec![
            SidebarSectionDef::new("vars", "VARIABLES"),
            SidebarSectionDef::new("watch", "WATCH"),
            SidebarSectionDef::new("stack", "CALL STACK"),
            SidebarSectionDef::new("bps", "BREAKPOINTS"),
        ]);
        ss.set_rows(0, fake_rows("v", 12));
        ss.set_rows(1, fake_rows("w", 8));
        ss.set_rows(2, fake_rows("frame", 5));
        ss.set_rows(3, fake_rows("bp", 0));
        ss.set_scroll_mode(ScrollMode::WholePanel);

        let metrics = MsvLayoutMetrics {
            header_size: 1.0,
            divider_size: 0.0,
            scrollbar_size: 1.0,
            cell_quantum: 1.0,
        };
        ss.set_backend_info(1.0, metrics);
        // 30-row terminal − 2-row status bar = 28 rows. Total content
        // (13+9+6+1) = 29 → 1 row of overflow.
        let rect = Rect::new(0.0, 0.0, 30.0, 28.0);

        let (layout, _) = ss.compute_layout(rect, &metrics, 1.0);
        let panel_sb = layout.panel_scrollbar.expect("overflowing → panel sb");

        // Click the painted thumb (top of gutter when panel_scroll=0).
        let click_x = panel_sb.x.round();
        let click_y = panel_sb.y.round();
        let _ = ss.handle_cached(
            &UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(click_x, click_y),
                modifiers: Modifiers::default(),
            },
            rect,
        );
        let _ = ss.handle_cached(
            &UiEvent::MouseMoved {
                position: Point::new(click_x, click_y + 1.0),
                buttons: ButtonMask {
                    left: true,
                    ..Default::default()
                },
            },
            rect,
        );
        let after = ss.panel_scroll();
        assert!(
            after > 0.0,
            "multi_tree-shaped 1-cell panel drag should scroll, got {after} \
             (panel_sb={panel_sb:?})"
        );
    }

    /// When the painted thumb fills nearly the whole gutter (small overflow),
    /// the drag-`travel` value approaches zero and the consumer's mouse cell
    /// coordinates can no longer move `scroll_offset`. Repro: 22 rows in a
    /// body that fits 20 rows.
    #[test]
    fn tui_per_section_drag_works_with_small_overflow() {
        let mut ss = SidebarSystem::new(vec![SidebarSectionDef::new("t", "T")]);
        ss.set_rows(0, fake_rows("r", 22));
        ss.set_active_section(Some(0));
        ss.set_scroll_mode(ScrollMode::PerSection);

        let metrics = MsvLayoutMetrics {
            header_size: 1.0,
            divider_size: 0.0,
            scrollbar_size: 1.0,
            cell_quantum: 1.0,
        };
        ss.set_backend_info(1.0, metrics);
        let rect = Rect::new(0.0, 0.0, 20.0, 21.0);

        let (layout, _) = ss.compute_layout(rect, &metrics, 1.0);
        let sb = layout.sections[0]
            .scrollbar_bounds
            .expect("scrollbar reserved");
        let thumb = layout.sections[0].thumb_bounds.expect("thumb computed");

        // TUI mouse coords come in as integer cells.
        let click_x = sb.x.round();
        let click_y = thumb.y.round();
        let _ = ss.handle_cached(
            &UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(click_x, click_y),
                modifiers: Modifiers::default(),
            },
            rect,
        );
        let _ = ss.handle_cached(
            &UiEvent::MouseMoved {
                position: Point::new(click_x, click_y + 1.0),
                buttons: ButtonMask {
                    left: true,
                    ..Default::default()
                },
            },
            rect,
        );
        let offset = ss.scroll_offset(0);
        assert!(
            offset > 0,
            "small-overflow 1-cell drag should advance scroll, got {offset} \
             (sb={sb:?}, thumb={thumb:?})"
        );
    }

    /// In TUI the panel scrollbar's layout uses `min_thumb = 8.0` pixels,
    /// painting a 2-cell thumb while the layout reserves an 8-cell hit region.
    /// A click at a row *below* the painted thumb (in cells 2..8) is treated
    /// as a thumb-drag start instead of a `TrackAfter` page-scroll.
    /// `panel_thumb_min` honours `cell_quantum` (1 cell in TUI), so the
    /// layout's thumb hit region matches the painted thumb's cells.
    #[test]
    fn tui_panel_thumb_hit_region_matches_painted_thumb_cells() {
        let mut ss = SidebarSystem::new(vec![SidebarSectionDef::new("t", "T")]);
        // Huge overflow → painted thumb is the minimum size in cells.
        ss.set_rows(0, fake_rows("r", 200));
        ss.set_scroll_mode(ScrollMode::WholePanel);

        let metrics = MsvLayoutMetrics {
            header_size: 1.0,
            divider_size: 0.0,
            scrollbar_size: 1.0,
            cell_quantum: 1.0,
        };
        let rect = Rect::new(0.0, 0.0, 30.0, 20.0);
        let (layout, _) = ss.compute_layout(rect, &metrics, 1.0);
        let panel_sb = layout.panel_scrollbar.expect("overflow → panel sb");

        // The painted thumb (per `paint_panel_scrollbar`) uses
        // `ceil(height * visible_frac).max(1)`. With height=20, total≈201,
        // visible_frac≈0.0995, painted thumb_h = ceil(1.99) = 2 cells.
        // Pre-fix the layout's thumb hit region was 8 cells; post-fix
        // it should be 2.
        let mut found_thumb_h: Option<f32> = None;
        for (rect, hit) in &layout.hit_regions {
            if matches!(
                hit,
                MultiSectionViewHit::PanelScrollbar {
                    kind: ScrollbarHit::Thumb
                }
            ) {
                found_thumb_h = Some(rect.height);
                break;
            }
        }
        let thumb_h = found_thumb_h.expect("layout must publish a Thumb hit region");
        assert!(
            thumb_h <= 4.0,
            "TUI panel thumb hit region was {thumb_h} cells (expected ~2 \
             to match the painted thumb). Pre-fix value was 8.0 cells, \
             which made the empty track below the painted thumb behave \
             like a thumb-drag. panel_sb={panel_sb:?}"
        );
    }

    /// When the natural thumb height is smaller than the layout's `min_thumb`
    /// (8.0 cells in TUI), the painted thumb travels a *short* distance per
    /// row of scroll. The drag init uses the layout's `min_thumb`, so the drag
    /// produces proportional scroll for each cell of mouse motion. Dragging
    /// 1 cell at a time produces a monotonically increasing thumb position.
    #[test]
    fn tui_panel_drag_matches_painted_thumb_under_large_overflow() {
        let mut ss = SidebarSystem::new(vec![SidebarSectionDef::new("t", "T")]);
        // Very tall content forces the natural thumb < min_thumb=8.
        ss.set_rows(0, fake_rows("r", 200));
        ss.set_scroll_mode(ScrollMode::WholePanel);

        let metrics = MsvLayoutMetrics {
            header_size: 1.0,
            divider_size: 0.0,
            scrollbar_size: 1.0,
            cell_quantum: 1.0,
        };
        ss.set_backend_info(1.0, metrics);
        let rect = Rect::new(0.0, 0.0, 30.0, 20.0);

        let (layout, _) = ss.compute_layout(rect, &metrics, 1.0);
        let panel_sb = layout.panel_scrollbar.expect("overflow → panel sb");

        // Click top of panel thumb (panel_scroll=0 → thumb at sb.y).
        let click_x = panel_sb.x.round();
        let click_y = panel_sb.y.round();
        let _ = ss.handle_cached(
            &UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(click_x, click_y),
                modifiers: Modifiers::default(),
            },
            rect,
        );

        // Drag 1 cell, then a second cell. The scroll must increase
        // monotonically AND not immediately jump to max_scroll on the
        // first cell — that's the pre-fix smell of using `lh=1` as the
        // min_thumb while the layout uses 8.0.
        let _ = ss.handle_cached(
            &UiEvent::MouseMoved {
                position: Point::new(click_x, click_y + 1.0),
                buttons: ButtonMask {
                    left: true,
                    ..Default::default()
                },
            },
            rect,
        );
        let after_one = ss.panel_scroll();

        let _ = ss.handle_cached(
            &UiEvent::MouseMoved {
                position: Point::new(click_x, click_y + 2.0),
                buttons: ButtonMask {
                    left: true,
                    ..Default::default()
                },
            },
            rect,
        );
        let after_two = ss.panel_scroll();

        let total = 200.0_f32 + 1.0; // 200 body rows + 1 header row
        let max_scroll = (total - rect.height).max(0.0);
        assert!(
            after_one > 0.0,
            "1-cell drag should advance panel_scroll (got {after_one})"
        );
        assert!(
            after_one < max_scroll,
            "1-cell drag should not instantly clamp to max_scroll \
             (got {after_one}, max_scroll={max_scroll}) — pre-fix sign \
             that drag travel was computed against the wrong min_thumb"
        );
        assert!(
            after_two > after_one,
            "2-cell drag should advance past 1-cell drag \
             (got after_two={after_two} vs after_one={after_one})"
        );
    }

    #[test]
    fn tui_panel_scrollbar_thumb_drag_scrolls_panel() {
        // Panel-level scrollbar in WholePanel mode under TUI metrics.
        // Multiple sections sized by Content overflow the rect → panel
        // scrollbar reserved on the trailing edge.
        let mut ss = SidebarSystem::new(vec![
            SidebarSectionDef::new("a", "A"),
            SidebarSectionDef::new("b", "B"),
            SidebarSectionDef::new("c", "C"),
        ]);
        ss.set_rows(0, fake_rows("a", 12));
        ss.set_rows(1, fake_rows("b", 12));
        ss.set_rows(2, fake_rows("c", 12));
        ss.set_scroll_mode(ScrollMode::WholePanel);

        let metrics = MsvLayoutMetrics {
            header_size: 1.0,
            divider_size: 0.0,
            scrollbar_size: 1.0,
            cell_quantum: 1.0,
        };
        ss.set_backend_info(1.0, metrics);
        let rect = Rect::new(0.0, 0.0, 20.0, 21.0);

        let (layout, _) = ss.compute_layout(rect, &metrics, 1.0);
        let panel_sb = layout
            .panel_scrollbar
            .expect("overflowing panel → panel scrollbar reserved");

        // Click somewhere in the panel scrollbar (thumb starts at the top
        // when panel_scroll == 0). Drag down 1 cell.
        // TUI mouse coords come in as integer cells.
        let click_x = panel_sb.x.round();
        let click_y = panel_sb.y.round();
        let down = UiEvent::MouseDown {
            widget: None,
            button: MouseButton::Left,
            position: Point::new(click_x, click_y),
            modifiers: Modifiers::default(),
        };
        let _ = ss.handle_cached(&down, rect);

        let move_ev = UiEvent::MouseMoved {
            position: Point::new(click_x, click_y + 1.0),
            buttons: ButtonMask {
                left: true,
                ..Default::default()
            },
        };
        let _ = ss.handle_cached(&move_ev, rect);

        let after = ss.panel_scroll();
        assert!(
            after > 0.0,
            "1-cell TUI drag on panel thumb should advance panel scroll, \
             but it stayed at {after} (panel_sb={panel_sb:?})"
        );
    }

    // ── Header row click precision ─────────────────────────────────────

    #[test]
    fn header_row_bottom_pixel_hits_header_not_child() {
        let lh: f32 = 16.0;
        let header_h = (lh * 1.2).round(); // 19.0

        let tree = TreeView {
            id: WidgetId::new("t"),
            rows: vec![
                TreeRow {
                    path: vec![0],
                    indent: 0,
                    icon: None,
                    text: StyledText::plain("src/"),
                    badge: None,
                    is_expanded: Some(true),
                    decoration: Decoration::Header,
                    edit: None,
                },
                TreeRow {
                    path: vec![0, 0],
                    indent: 1,
                    icon: None,
                    text: StyledText::plain("main.rs"),
                    badge: None,
                    is_expanded: None,
                    decoration: Decoration::Normal,
                    edit: None,
                },
            ],
            selection_mode: SelectionMode::Single,
            selected_path: None,
            scroll_offset: 0,
            style: Default::default(),
            has_focus: true,
        };

        let body_b = Rect::new(0.0, 0.0, 200.0, 200.0);
        let ss = SidebarSystem::new(vec![SidebarSectionDef::new("t", "T")]);
        let layout = ss.compute_tree_layout(body_b, &tree, lh);

        // Header row spans [0, header_h). Click at header_h - 0.5 (bottom pixel)
        // should still land on the header row (index 0), not the child (row 1).
        // The header is a branch row so x=5 may fall in the chevron region — both
        // Chevron(0) and Row(0) satisfy the row-discrimination requirement.
        let bottom_of_header = header_h - 0.5;
        match layout.hit_test(5.0, bottom_of_header) {
            TreeViewHit::Row(0) | TreeViewHit::Chevron(0) => {}
            other => panic!(
                "click at y={bottom_of_header} returned {:?}, expected Row(0) or Chevron(0)",
                other
            ),
        }

        // First pixel of child row should hit row 1.
        let top_of_child = header_h + 0.5;
        match layout.hit_test(5.0, top_of_child) {
            TreeViewHit::Row(idx) => assert_eq!(
                idx, 1,
                "click at y={top_of_child} (top of child row) hit row {idx}, expected 1"
            ),
            other => panic!(
                "click at y={top_of_child} returned {:?}, expected Row(1)",
                other
            ),
        }
    }

    // ── Form item-level click dispatch ─────────────────────────────────

    #[test]
    fn form_field_measure_populates_toggle_group_items() {
        use crate::primitives::form::{FormField, ToggleGroupItem};
        let field = FormField {
            id: WidgetId::new("flags"),
            label: StyledText::plain("Flags"),
            kind: FieldKind::ToggleGroup {
                toggles: vec![
                    ToggleGroupItem {
                        id: WidgetId::new("case"),
                        label: "Aa".into(),
                        value: false,
                    },
                    ToggleGroupItem {
                        id: WidgetId::new("regex"),
                        label: ".*".into(),
                        value: false,
                    },
                ],
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let m = form_field_measure(&field, 20.0, 10.0);
        assert_eq!(m.item_measures.len(), 2);
        assert_eq!(m.item_measures[0].id, WidgetId::new("case"));
        assert_eq!(m.item_measures[1].id, WidgetId::new("regex"));
        assert!(m.items_start_x > 0.0);
    }

    #[test]
    fn form_field_measure_populates_button_row_items() {
        use crate::primitives::form::{ButtonRowItem, FormField};
        let field = FormField {
            id: WidgetId::new("actions"),
            label: StyledText::plain(""),
            kind: FieldKind::ButtonRow {
                buttons: vec![
                    ButtonRowItem {
                        id: WidgetId::new("replace"),
                        label: "Replace".into(),
                        disabled: false,
                        icon: None,
                    },
                    ButtonRowItem {
                        id: WidgetId::new("replace-all"),
                        label: "Replace All".into(),
                        disabled: false,
                        icon: None,
                    },
                ],
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let m = form_field_measure(&field, 20.0, 10.0);
        assert_eq!(m.item_measures.len(), 2);
        assert_eq!(m.item_measures[0].id, WidgetId::new("replace"));
        assert_eq!(m.item_measures[1].id, WidgetId::new("replace-all"));
    }

    #[test]
    fn form_layout_hit_test_returns_individual_toggle_id() {
        use crate::primitives::form::{FormField, FormHit, ToggleGroupItem};
        let form = Form {
            id: WidgetId::new("f"),
            fields: vec![FormField {
                id: WidgetId::new("flags"),
                label: StyledText::plain(""),
                kind: FieldKind::ToggleGroup {
                    toggles: vec![
                        ToggleGroupItem {
                            id: WidgetId::new("case"),
                            label: "Aa".into(),
                            value: false,
                        },
                        ToggleGroupItem {
                            id: WidgetId::new("regex"),
                            label: ".*".into(),
                            value: false,
                        },
                    ],
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let lh: f32 = 16.0;
        let row_h = (lh * 1.4).round();
        let char_w = lh * 0.6;
        let layout = form.layout(200.0, 100.0, |i| {
            form_field_measure(&form.fields[i], row_h, char_w)
        });
        let m = &layout.visible_fields[0];
        assert!(
            !m.item_bounds.is_empty(),
            "item_bounds should be populated for ToggleGroup"
        );
        let (first_id, first_rect) = &m.item_bounds[0];
        assert_eq!(first_id, &WidgetId::new("case"));
        let hit = layout.hit_test(first_rect.x + 1.0, first_rect.y + 1.0);
        assert_eq!(hit, FormHit::Field(WidgetId::new("case")));
    }

    #[test]
    fn form_click_event_dispatches_individual_toggle() {
        use crate::primitives::form::{FormField, ToggleGroupItem};
        let form = Form {
            id: WidgetId::new("f"),
            fields: vec![FormField {
                id: WidgetId::new("flags"),
                label: StyledText::plain(""),
                kind: FieldKind::ToggleGroup {
                    toggles: vec![ToggleGroupItem {
                        id: WidgetId::new("case"),
                        label: "Aa".into(),
                        value: true,
                    }],
                },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let ev = form_click_event(&form, &WidgetId::new("case"));
        assert_eq!(
            ev,
            FormEvent::ToggleChanged {
                id: WidgetId::new("case"),
                value: false,
            }
        );
    }

    // ── Header click-to-collapse tests ──────────────────────────────────

    /// Rect, line-height, and metrics used by all header-click tests.
    fn collapse_click_setup() -> (Rect, f32, MsvLayoutMetrics) {
        let rect = Rect {
            x: 0.0,
            y: 0.0,
            width: 200.0,
            height: 600.0,
        };
        let lh = 20.0;
        // header_size matches lh so section-0 header occupies y ∈ [0, 20).
        let metrics = MsvLayoutMetrics {
            header_size: 20.0,
            divider_size: 0.0,
            scrollbar_size: 0.0,
            cell_quantum: 0.0,
        };
        (rect, lh, metrics)
    }

    #[test]
    fn header_click_toggles_collapsed_when_allow_collapse_true() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_allow_collapse(true);
        ss.set_rows(0, fake_rows("v", 3));
        let (rect, lh, metrics) = collapse_click_setup();
        assert!(!ss.is_collapsed(0));
        // Click centre of section-0 header.
        ss.click(rect, 5.0, 10.0, lh, &metrics, None);
        assert!(ss.is_collapsed(0), "first click should collapse section 0");
    }

    #[test]
    fn header_click_does_not_toggle_when_allow_collapse_false() {
        let mut ss = SidebarSystem::new(sample_defs());
        // allow_collapse is false by default — make it explicit.
        ss.set_allow_collapse(false);
        ss.set_rows(0, fake_rows("v", 3));
        let (rect, lh, metrics) = collapse_click_setup();
        ss.click(rect, 5.0, 10.0, lh, &metrics, None);
        assert!(
            !ss.is_collapsed(0),
            "click without allow_collapse must not toggle collapsed state"
        );
    }

    #[test]
    fn header_click_emits_header_activated_after_toggle() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_allow_collapse(true);
        ss.set_rows(0, fake_rows("v", 3));
        let (rect, lh, metrics) = collapse_click_setup();
        let ev = ss.click(rect, 5.0, 10.0, lh, &metrics, None);
        assert_eq!(
            ev,
            SidebarEvent::HeaderActivated { section: 0 },
            "HeaderActivated must still be emitted even when allow_collapse toggles state"
        );
    }

    #[test]
    fn header_click_multiple_toggles_persist_state() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_allow_collapse(true);
        ss.set_rows(0, fake_rows("v", 3));
        let (rect, lh, metrics) = collapse_click_setup();
        // false → true
        ss.click(rect, 5.0, 10.0, lh, &metrics, None);
        assert!(ss.is_collapsed(0), "after 1st click: should be collapsed");
        // true → false
        ss.click(rect, 5.0, 10.0, lh, &metrics, None);
        assert!(!ss.is_collapsed(0), "after 2nd click: should be expanded");
        // false → true again
        ss.click(rect, 5.0, 10.0, lh, &metrics, None);
        assert!(
            ss.is_collapsed(0),
            "after 3rd click: should be collapsed again"
        );
    }

    // ── Scroll-wheel position routing ──────────────────────────────────────
    //
    // Helpers shared by the scroll routing tests below.

    fn scroll_routing_sidebar() -> SidebarSystem {
        // Two sections, each with 50 rows so there's plenty of room to
        // scroll (viewport ≈ 19 rows → max_scroll ≈ 31).
        let defs = vec![
            SidebarSectionDef::new("top", "TOP"),
            SidebarSectionDef::new("bottom", "BOTTOM"),
        ];
        let mut ss = SidebarSystem::new(defs);
        ss.set_rows(0, fake_rows("t", 50));
        ss.set_rows(1, fake_rows("b", 50));
        // Start with section 0 active — this is the "wrong" section for
        // the scroll-routing tests that hover over section 1.
        ss.set_active_section(Some(0));
        // Provide backend info so handle_cached works.
        // lh=1.0, default MsvLayoutMetrics (header_size=1.0, scrollbar_size=1.0).
        ss.set_backend_info(1.0, MsvLayoutMetrics::default());
        ss
    }

    /// Compute which y-coordinate lies inside the body of a given section
    /// for a known rect and layout metrics, so we can construct correct
    /// scroll-event positions for the routing tests.
    fn section_body_y(ss: &SidebarSystem, section_idx: usize, rect: Rect) -> f32 {
        let lh = 1.0_f32;
        let metrics = MsvLayoutMetrics::default();
        let (layout, map) = ss.compute_layout(rect, &metrics, lh);
        let msv_idx = map.iter().position(|&s| s == section_idx).unwrap();
        let body_b = layout.sections[msv_idx].body_bounds;
        // Return a y-coordinate in the middle of the body.
        body_b.y + body_b.height / 2.0
    }

    #[test]
    fn scroll_routes_to_section_under_cursor_not_active_section() {
        // Section 0 is active, cursor is over section 1 body.
        // Scroll down should advance section 1's offset, not section 0's.
        let mut ss = scroll_routing_sidebar();
        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);
        let y1 = section_body_y(&ss, 1, rect);

        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, -1.0), // negative y → scroll down
            position: Point::new(5.0, y1),
        };
        let result = ss.handle_cached(&ev, rect);
        assert_eq!(result, SidebarEvent::Consumed);

        // Section 1 should have scrolled; section 0 should not have moved.
        assert_eq!(ss.scroll_offset(0), 0, "active section 0 should not scroll");
        assert!(
            ss.scroll_offset(1) > 0,
            "section 1 under cursor should have scrolled, offset={}",
            ss.scroll_offset(1)
        );
    }

    #[test]
    fn scroll_routes_to_section_0_when_cursor_over_it() {
        // Cursor is over section 0. Even though section 1 is active,
        // section 0 should scroll.
        let defs = vec![
            SidebarSectionDef::new("top", "TOP"),
            SidebarSectionDef::new("bottom", "BOTTOM"),
        ];
        let mut ss = SidebarSystem::new(defs);
        ss.set_rows(0, fake_rows("t", 20));
        ss.set_rows(1, fake_rows("b", 20));
        ss.set_active_section(Some(1)); // section 1 is active
        ss.set_backend_info(1.0, MsvLayoutMetrics::default());

        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);
        let y0 = section_body_y(&ss, 0, rect);

        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, -1.0),
            position: Point::new(5.0, y0),
        };
        ss.handle_cached(&ev, rect);

        assert!(
            ss.scroll_offset(0) > 0,
            "section 0 under cursor should scroll"
        );
        assert_eq!(ss.scroll_offset(1), 0, "active section 1 should not scroll");
    }

    #[test]
    fn scroll_falls_back_to_active_section_when_position_outside_msv() {
        // Position (0, 0) lies outside the MSV bounds (rect starts at 10, 10).
        // The fallback path kicks in and scrolls the active section.
        let mut ss = scroll_routing_sidebar();
        let rect = Rect::new(10.0, 10.0, 20.0, 40.0);
        ss.set_active_section(Some(0));

        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, -1.0),
            position: Point::new(0.0, 0.0), // outside rect
        };
        ss.handle_cached(&ev, rect);
        // Active section 0 receives the scroll via the fallback path.
        assert!(
            ss.scroll_offset(0) > 0,
            "fallback should scroll active section 0"
        );
        assert_eq!(ss.scroll_offset(1), 0);
    }

    #[test]
    fn scroll_up_decrements_offset_in_section_under_cursor() {
        let mut ss = scroll_routing_sidebar();
        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);
        let y1 = section_body_y(&ss, 1, rect);

        // First scroll section 1 down by 5.
        if let SectionController::Tree(tc) = &mut ss.sections[1] {
            tc.set_scroll_offset(5);
        }

        // Now scroll up with cursor over section 1.
        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, 1.0), // positive y → scroll up
            position: Point::new(5.0, y1),
        };
        ss.handle_cached(&ev, rect);
        assert_eq!(ss.scroll_offset(1), 4, "scroll up should decrement offset");
        assert_eq!(ss.scroll_offset(0), 0, "section 0 should be untouched");
    }

    /// Per-section scrolling moves as many rows as the gesture asks for,
    /// not one row per event regardless of magnitude.
    #[test]
    fn section_scroll_consumes_the_delta_magnitude_not_just_its_sign() {
        let mut ss = scroll_routing_sidebar();
        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);
        let y1 = section_body_y(&ss, 1, rect);

        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, -4.0),
            position: Point::new(5.0, y1),
        };
        assert_eq!(ss.handle_cached(&ev, rect), SidebarEvent::Consumed);
        assert_eq!(
            ss.scroll_offset(1),
            4,
            "a four-notch gesture moves four rows"
        );
    }

    /// A sub-row trackpad gesture still moves one row rather than being
    /// rounded away to nothing.
    #[test]
    fn section_scroll_still_moves_one_row_for_a_sub_row_gesture() {
        let mut ss = scroll_routing_sidebar();
        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);
        let y1 = section_body_y(&ss, 1, rect);

        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, -0.25),
            position: Point::new(5.0, y1),
        };
        ss.handle_cached(&ev, rect);
        assert_eq!(ss.scroll_offset(1), 1);
    }

    /// Whole-panel scrolling works in pixels: the panel offset moves by
    /// `delta.y * line_height`, so a sub-notch trackpad delta produces a
    /// sub-line pixel offset rather than a whole-line jump.
    #[test]
    fn panel_scroll_consumes_the_delta_magnitude_in_pixels() {
        let defs = vec![
            SidebarSectionDef::new("top", "TOP"),
            SidebarSectionDef::new("bottom", "BOTTOM"),
        ];
        let mut ss = SidebarSystem::new(defs);
        ss.set_rows(0, fake_rows("t", 50));
        ss.set_rows(1, fake_rows("b", 50));
        ss.set_scroll_mode(ScrollMode::WholePanel);
        ss.set_backend_info(10.0, MsvLayoutMetrics::default());

        let rect = Rect::new(0.0, 0.0, 20.0, 400.0);
        let ev = UiEvent::Scroll {
            widget: None,
            delta: crate::ScrollDelta::new(0.0, -2.5),
            position: Point::new(5.0, 50.0),
        };
        assert_eq!(ss.handle_cached(&ev, rect), SidebarEvent::Consumed);
        assert_eq!(
            ss.panel_scroll(),
            25.0,
            "2.5 notches × line_height 10.0 = 25px"
        );
    }

    // ── RowToggleExpand ─────────────────────────────────────────────

    fn branch_rows_for_sidebar() -> Vec<TreeRow> {
        vec![
            TreeRow {
                path: vec![0],
                indent: 0,
                icon: None,
                text: StyledText::plain("src"),
                badge: None,
                is_expanded: Some(true),
                decoration: Decoration::Normal,
                edit: None,
            },
            TreeRow {
                path: vec![1],
                indent: 0,
                icon: None,
                text: StyledText::plain("tests"),
                badge: None,
                is_expanded: Some(false),
                decoration: Decoration::Normal,
                edit: None,
            },
            TreeRow {
                path: vec![2],
                indent: 1,
                icon: None,
                text: StyledText::plain("main.rs"),
                badge: None,
                is_expanded: None,
                decoration: Decoration::Normal,
                edit: None,
            },
        ]
    }

    /// Space on a selected branch row emits RowToggleExpand.
    #[test]
    fn sidebar_space_on_branch_row_emits_row_toggle_expand() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, branch_rows_for_sidebar());
        ss.set_active_section(Some(0));
        ss.set_selected_path(0, Some(vec![0]));
        let ev = ss.toggle_expand_selected();
        assert_eq!(
            ev,
            SidebarEvent::RowToggleExpand {
                section: 0,
                path: vec![0]
            }
        );
    }

    /// Space on a collapsed branch row also emits RowToggleExpand.
    #[test]
    fn sidebar_space_on_collapsed_branch_emits_row_toggle_expand() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, branch_rows_for_sidebar());
        ss.set_active_section(Some(0));
        ss.set_selected_path(0, Some(vec![1]));
        let ev = ss.toggle_expand_selected();
        assert_eq!(
            ev,
            SidebarEvent::RowToggleExpand {
                section: 0,
                path: vec![1]
            }
        );
    }

    /// Space on a leaf returns Ignored.
    #[test]
    fn sidebar_space_on_leaf_returns_ignored() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, branch_rows_for_sidebar());
        ss.set_active_section(Some(0));
        ss.set_selected_path(0, Some(vec![2]));
        let ev = ss.toggle_expand_selected();
        assert_eq!(ev, SidebarEvent::Ignored);
    }

    /// Space with no active section returns Ignored.
    #[test]
    fn sidebar_space_no_active_section_returns_ignored() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, branch_rows_for_sidebar());
        let ev = ss.toggle_expand_selected();
        assert_eq!(ev, SidebarEvent::Ignored);
    }

    /// Space works in Selection mode (forwarded through handle_key_selection).
    #[test]
    fn sidebar_selection_mode_space_emits_row_toggle_expand() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_navigation_mode(NavigationMode::Selection);
        ss.set_rows(0, branch_rows_for_sidebar());
        ss.set_active_section(Some(0));
        ss.set_selected_path(0, Some(vec![0]));
        let ev = ss.toggle_expand_selected();
        assert_eq!(
            ev,
            SidebarEvent::RowToggleExpand {
                section: 0,
                path: vec![0]
            }
        );
    }

    /// RowToggleExpand is forwarded for the correct section index when
    /// section 1 (not 0) is active.
    #[test]
    fn sidebar_toggle_expand_reports_correct_section() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(1, branch_rows_for_sidebar());
        ss.set_active_section(Some(1));
        ss.set_selected_path(1, Some(vec![0]));
        let ev = ss.toggle_expand_selected();
        assert_eq!(
            ev,
            SidebarEvent::RowToggleExpand {
                section: 1,
                path: vec![0]
            }
        );
    }

    /// Existing RowSelected still works — chevron split does not break body clicks.
    /// (Regression guard: make sure toggle_expand_selected returning Ignored on
    /// a leaf does not emit RowToggleExpand.)
    #[test]
    fn sidebar_row_selected_still_works_for_leaf() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, branch_rows_for_sidebar());
        ss.set_active_section(Some(0));
        ss.set_selected_path(0, Some(vec![2])); // leaf
        let ev = ss.toggle_expand_selected();
        assert_eq!(ev, SidebarEvent::Ignored);
    }

    // ── Programmatic reveal (#reveal) ────────────────────────────────
    //
    // The "row actually ends up on screen" claim is proven end-to-end by
    // the `TuiDriver` tests in `tests/tui_example_driver.rs`
    // (`sidebar_reveal_*`), which render the real `SidebarRevealDemo`
    // example (`examples/common/sidebar_reveal_demo.rs`) and read row
    // text back off the rendered grid — not by inspecting
    // `scroll_offset`. (`DebugSidebar`/`multi_tree.rs` can't host that
    // proof: it uses `ScrollMode::WholePanel`, which ignores each
    // section's own `TreeController::scroll_offset` entirely, so even
    // interactive arrow-key nav never moves its screen.) The unit tests
    // below cover the state transitions `reveal` is responsible for
    // (selection, un-collapse, no-op guards) and the one
    // internal-consistency check that isn't observable from rendered
    // text: that `reveal` reuses `TreeController::scroll_to_visible`
    // rather than re-deriving its own scroll math.

    /// `reveal` selects `path` in the target section and scrolls it into view.
    /// This ensures both selection and visibility are updated together.
    #[test]
    fn reveal_selects_the_target_row() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 50));
        ss.set_backend_info(1.0, MsvLayoutMetrics::default());
        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);

        assert_eq!(ss.selected_path(0), None);
        ss.reveal(0, &vec![40], rect);
        assert_eq!(
            ss.selected_path(0),
            Some(&vec![40]),
            "reveal must select the row, not just scroll to it"
        );
    }

    /// `reveal` expands a collapsed section before scrolling — the old
    /// version left `self.collapsed[section]` untouched, and since a
    /// collapsed section's body has zero rows, `scroll_to_visible` was
    /// guaranteed to no-op (acceptance criterion 3: "reveal on a
    /// collapsed section expands it first, then scrolls").
    #[test]
    fn reveal_expands_a_collapsed_section() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 50));
        ss.set_backend_info(1.0, MsvLayoutMetrics::default());
        ss.set_collapsed(0, true);
        assert!(ss.is_collapsed(0));
        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);

        ss.reveal(0, &vec![40], rect);

        assert!(
            !ss.is_collapsed(0),
            "reveal must expand a collapsed section before scrolling"
        );
        assert_eq!(ss.selected_path(0), Some(&vec![40]));
    }

    /// `reveal` must reuse `TreeController::scroll_to_visible` — the same
    /// scroll-to-follow math that interactive arrow-key navigation uses —
    /// rather than re-deriving it. Drive selection down to row 40 via the
    /// interactive path to capture the "correct" resulting offset, then
    /// reset the scroll and confirm `reveal` lands on the identical value.
    /// (This checks the *implementation* shares one code path, not the
    /// user-visible "is it on screen" claim — see the module note above.)
    #[test]
    fn reveal_reuses_interactive_scroll_to_follow_math() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 50));
        ss.set_active_section(Some(0));
        let lh = 1.0_f32;
        let metrics = MsvLayoutMetrics::default();
        ss.set_backend_info(lh, metrics);
        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);

        // First move (no prior selection) lands on row 0; 40 further
        // moves advance to row 40.
        for _ in 0..41 {
            ss.move_selection(1, rect, lh, &metrics);
        }
        assert_eq!(ss.selected_path(0), Some(&vec![40]));
        let expected_offset = ss.scroll_offset(0);
        assert!(
            expected_offset > 0,
            "row 40 should have scrolled the viewport during interactive nav"
        );

        // Simulate an off-screen programmatic selection by resetting the
        // scroll offset while leaving the selected path untouched.
        if let SectionController::Tree(tc) = &mut ss.sections[0] {
            tc.set_scroll_offset(0);
        }
        assert_eq!(ss.scroll_offset(0), 0);

        ss.reveal(0, &vec![40], rect);

        assert_eq!(
            ss.scroll_offset(0),
            expected_offset,
            "reveal should reuse the same scroll-to-follow math as interactive nav"
        );
    }

    /// `reveal` is a safe no-op when `set_backend_info` was never called
    /// (viewport size unknown) or `path` doesn't match any current row —
    /// selection must stay exactly as it was before the call.
    #[test]
    fn reveal_is_noop_without_backend_info_or_unknown_path() {
        let mut ss = SidebarSystem::new(sample_defs());
        ss.set_rows(0, fake_rows("v", 50));
        ss.set_selected_path(0, Some(vec![3]));
        let rect = Rect::new(0.0, 0.0, 20.0, 40.0);

        // No `set_backend_info` call yet.
        ss.reveal(0, &vec![40], rect);
        assert_eq!(
            ss.selected_path(0),
            Some(&vec![3]),
            "reveal without backend info must not change selection"
        );

        ss.set_backend_info(1.0, MsvLayoutMetrics::default());
        ss.reveal(0, &vec![999], rect); // path not present among rows
        assert_eq!(
            ss.selected_path(0),
            Some(&vec![3]),
            "reveal for an unknown path must not change selection"
        );
    }

    #[cfg(feature = "gtk")]
    #[test]
    fn scroll_event_carries_cursor_position_via_gdk_scroll_to_uievent() {
        // Unit-test that `gdk_scroll_to_uievent` populates the position field
        // correctly. This is the translation function called by the fixed GTK
        // runner and `wire_da_events` — the real integration depends on the
        // shared cursor_pos state, but we can verify the helper signature here.
        use crate::gtk::events::gdk_scroll_to_uievent;
        let ev = gdk_scroll_to_uievent(0.0, 1.0, 42.0, 100.0);
        match ev {
            UiEvent::Scroll {
                position, delta, ..
            } => {
                assert_eq!(position.x, 42.0, "x from cursor should propagate");
                assert_eq!(position.y, 100.0, "y from cursor should propagate");
                // Negative dy convention is still applied (GTK positive = down).
                assert_eq!(delta.y, -1.0);
            }
            _ => panic!("expected Scroll event"),
        }
    }
}