quadraui 0.6.0

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
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
//! `AppShell` — a composed controller for the activity bar + sidebar
//! panel container pattern (VS Code / JetBrains / Zellij-style app shell).
//!
//! Owns the full interaction state machine: activity bar click toggle,
//! active panel switching, sidebar visibility, and resize drag. Apps
//! register panels at construction time or dynamically via
//! [`AppShell::add_panel`] / [`AppShell::remove_panel`], match on
//! [`AppShellEvent`] for semantic actions, and paint their panel content
//! into the bounds the shell returns.
//!
//! The shell renders the activity bar, sidebar header chrome, and resize
//! divider. Panel *content* and the main content area are the consumer's
//! responsibility — the shell returns [`AppShellLayout`] with the bounds.

use std::cell::RefCell;
use std::collections::HashMap;

use crate::primitives::activity_bar::{ActivityBar, ActivityBarRowHit, ActivityItem};
use crate::primitives::status_bar::{StatusBar, StatusBarSegment};
use crate::types::{Color, Icon, WidgetId};
use crate::{Backend, ButtonMask, InteractionState, MouseButton, Point, Rect, UiEvent};

// ── Public types ─────────────────────────────────────────────────────

/// Registration info for one sidebar panel.
#[derive(Debug, Clone)]
pub struct PanelDefinition {
    pub id: WidgetId,
    /// Single icon string painted on the panel's activity-bar row.
    ///
    /// [`AppShell::build_activity_bar`] widens this into the built
    /// [`ActivityItem::icon`] as `Icon { glyph: icon, fallback: icon }` —
    /// i.e. the same string paints whether or not the backend's
    /// `nerd_fonts_enabled` flag is set. A panel that wants a *distinct*
    /// Nerd-Font glyph and ASCII fallback attaches the pair with
    /// [`AppShell::with_panel_icon`] instead of widening this field
    ///
    /// **This stays a `String` on purpose.** A Rust struct literal pins
    /// its field's type exactly, and every construction site of this type
    /// is a literal: fourteen in `coord-tui`'s `shell_config()`, one in
    /// `vimcode`'s `ext_activity_panels()`, and two in the sealed
    /// `tests/acceptance/ms-11/structural_parity.rs` fixture that workers
    /// may not edit. Retyping the field to [`Icon`] breaks all of them at
    /// once with no deprecation shim available (CLAUDE.md rules 2–3), so
    /// the glyph/fallback pair rides alongside it instead.
    pub icon: String,
    pub tooltip: String,
    pub title: String,
}

/// One independently-gated horizontal band stacked in the bottom chrome
/// of the main content column.
///
/// [`AppShell`] already models a single resizable bottom drawer
/// ([`AppShell::with_bottom_panel`] / [`BottomPanelController`]) — the
/// terminal-panel case. Some consumers (vimcode) stack several more bands
/// below the editor content area at once: a terminal toolbar, a debug
/// toolbar, a quickfix list, a wildmenu, a separated status row — each
/// gated on its own boolean/state, not just a single shared height. A
/// `BottomBand` models one such rung: present only when `visible` is
/// `true`, sized independently via `height_lh`.
///
/// [`AppShell::with_bottom_bands`] takes an ordered `Vec<BottomBand>`.
/// Bands are stacked **bottom-up**: `bottom_bands[0]` sits flush against
/// the bottom edge of the main content column, `bottom_bands[1]` sits
/// directly above it, and so on. The legacy single [`AppShell::with_bottom_panel`]
/// drawer (if configured) docks *above* every `BottomBand`, closest to
/// remaining main content — i.e. it behaves as if it were one more,
/// implicit band stacked on top of the list. This keeps every existing
/// `with_bottom_panel` consumer's layout byte-for-byte unchanged when
/// `bottom_bands` is empty (the default).
///
/// [`BottomPanelController`]: crate::compose::bottom_panel::BottomPanelController
#[derive(Debug, Clone, PartialEq)]
pub struct BottomBand {
    /// Identifies this band in [`AppShell::bottom_band_bounds`] and
    /// in [`AppShell::set_bottom_band_visible`] / [`AppShell::set_bottom_band_height`].
    pub id: WidgetId,
    /// Whether this band currently occupies space. `false` removes it
    /// from the stack entirely for this frame (the bands above and below
    /// close the gap) — this is the "independent presence" gating vimcode
    /// needs (a quickfix list that only exists while quickfix is open),
    /// not just a height of zero.
    pub visible: bool,
    /// Band height in line-height multiples (matching every other
    /// `*_height_lh` field on [`AppShell`]) — portable across TUI (cells)
    /// and GUI (pixels) backends.
    pub height_lh: f32,
}

impl BottomBand {
    /// Construct a visible band with the given id and height.
    pub fn new(id: WidgetId, height_lh: f32) -> Self {
        Self {
            id,
            visible: true,
            height_lh,
        }
    }
}

/// Which side of the viewport the activity bar + sidebar sit on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ShellPosition {
    #[default]
    Left,
    Right,
}

/// Semantic events emitted by [`AppShell::handle`].
#[derive(Debug, Clone, PartialEq)]
pub enum AppShellEvent {
    PanelChanged { panel_id: WidgetId },
    SidebarHidden,
    SidebarResized { new_width: f32 },
    BottomPanelResized { new_height: f32 },
    BottomPanelHidden,
    BottomItemClicked { id: WidgetId },
    Consumed,
    Ignored,
}

/// Layout bounds returned by [`AppShell::render`] and [`AppShell::layout`].
///
/// Bottom-band bounds are exposed via [`AppShell::bottom_band_bounds`]
/// rather than as fields here: `AppShellLayout` is an all-`pub`-field
/// struct that downstream consumers build with exhaustive literals.
/// Rust cannot grow such a struct's field list without breaking those
/// call sites. Bottom-band bounds are exposed additively instead, the
/// same way `TextInput`/`Editor` grew without touching their field lists.
#[derive(Debug, Clone, PartialEq)]
pub struct AppShellLayout {
    /// The full window/viewport rect this layout was computed against —
    /// the same `area` passed to [`AppShell::layout`] / [`AppShell::render`].
    /// Lets [`crate::shell::ShellContext::window_edge`] hit-test the
    /// outer window border for edge-resize without the app having to
    /// separately track `backend.viewport()`.
    pub window_bounds: Rect,
    pub title_bar_bounds: Option<Rect>,
    pub activity_bar_bounds: Rect,
    pub sidebar_header_bounds: Option<Rect>,
    pub sidebar_content_bounds: Option<Rect>,
    pub divider_bounds: Option<Rect>,
    pub main_content_bounds: Rect,
    pub bottom_panel_bounds: Option<Rect>,
    pub command_line_bounds: Option<Rect>,
    pub status_bar_bounds: Option<Rect>,
}

// ── AppShell ─────────────────────────────────────────────────────────

/// All width/height fields are stored as **multiples of `line_height`**
/// so they are portable across TUI (cells) and GUI (pixels) backends.
/// `compute_layout()` resolves them: `dimension_native = field * lh`.
pub struct AppShell {
    panels: Vec<PanelDefinition>,
    bottom_items: Vec<PanelDefinition>,
    /// Index into `panels` of the top panel most recently made active by a
    /// click or [`Self::show_panel`]. Drives the top item's `is_active`
    /// accent and, when `sidebar_bottom_owner` is `None`, the sidebar
    /// header title — see [`Self::sidebar_owner_panel`].
    active_panel: Option<usize>,
    /// Index into `bottom_items` of the bottom item that currently owns
    /// the sidebar header. `None` (the default, and the
    /// state [`Self::handle_activity_click`]'s `BottomItemClicked` branch
    /// deliberately leaves untouched) means the header is titled from
    /// `active_panel` as before. Set only by [`Self::show_panel`] when
    /// called with a bottom item's id — an app opts a bottom item into
    /// owning the sidebar by calling `show_panel` from its own
    /// `BottomItemClicked` handler; a bottom item that never opens the
    /// sidebar (a notifications bell, say) is unaffected.
    sidebar_bottom_owner: Option<usize>,
    sidebar_visible: bool,
    /// Sidebar width in line_height multiples.
    sidebar_width: f32,
    min_sidebar_width: f32,
    max_sidebar_width: f32,
    /// Activity bar width in line_height multiples.
    activity_bar_width: f32,
    /// Fixed-pixel activity bar width override, set via
    /// [`Self::with_activity_bar_width_px`]. When `Some`, this wins over
    /// `activity_bar_width` and is used verbatim regardless of
    /// `line_height` — VS Code's activity bar is a fixed 48px (matching
    /// `ACTIVITY_ROW_PX`) independent of editor font size, and font-scaled
    /// chrome is the wrong unit for a bar whose contents are fixed-size
    /// icons.
    activity_bar_width_px: Option<f32>,
    position: ShellPosition,
    drag_offset: Option<f32>,
    hovered_activity_idx: Option<usize>,
    // ── Chrome slot config ───────────────────────────────────────
    has_title_bar: bool,
    title_bar_height_lh: f32,
    /// Fixed-pixel floor under the line-height-derived title-bar height,
    /// set via [`Self::with_title_bar_min_px`]. `None` (the default)
    /// leaves `title_bar_height_lh * line_height` in charge with no floor
    /// — the pre-existing behaviour.
    ///
    /// Unlike [`Self::activity_bar_width_px`] (a hard override that wins
    /// outright), this is a *floor*: the resolved height is
    /// `max(title_bar_height_lh * line_height, title_bar_min_px)`. A
    /// title bar reserved in line-height multiples still grows with a
    /// larger editor font, it just never shrinks below the floor when the
    /// font gets small — e.g. pinning it above macOS's native
    /// traffic-light cluster height regardless of how far a user shrinks
    /// `settings.font_size` at runtime.
    title_bar_min_px: Option<f32>,
    has_bottom_panel: bool,
    bottom_panel_height_lh: f32,
    min_bottom_panel_height_lh: f32,
    max_bottom_panel_height_lh: f32,
    bottom_panel_visible: bool,
    has_command_line: bool,
    has_status_bar: bool,
    /// Fixed-pixel status bar height override, set via
    /// [`Self::with_status_bar_height_px`]. When `Some`, this wins over the
    /// `line_height`-derived height used otherwise — VS Code's status bar is
    /// a fixed 22px independent of editor font size, the same reasoning
    /// [`Self::activity_bar_width_px`] already documents for the activity
    /// bar. `None` (the default) leaves the status bar at one line height,
    /// snapped per [`crate::Backend::snap_height`].
    status_bar_height_px: Option<f32>,
    /// When `true`, the activity bar and sidebar run the full height of the
    /// area below the title bar, and the status bar + command line bands
    /// are carved from the main column's width only (not the full window),
    /// still flush against the bottom edge — set via
    /// [`Self::with_status_bar_under_main_column`]. `false` (the default)
    /// keeps the original full-width carve, where the status bar and
    /// command line span the whole window and the activity bar/sidebar
    /// stop above them.
    status_bar_under_main_column: bool,
    bottom_panel_drag_offset: Option<f32>,
    /// Independently-gated bottom bands, stacked bottom-up
    /// below the legacy single bottom-panel drawer. Empty by default —
    /// see [`BottomBand`]'s doc for the stacking order and the
    /// backward-compat guarantee.
    bottom_bands: Vec<BottomBand>,
    /// Resolved bounds for every currently-`visible` [`BottomBand`] from
    /// the last [`Self::layout`]/[`Self::render`] call, in the same
    /// bottom-up order `bottom_bands` was given (index 0 = flush against
    /// the bottom edge of the main content column). Bands with
    /// `visible == false` have no entry — they occupy no space that frame.
    /// Read via [`Self::bottom_band_bounds`].
    ///
    /// This lives on `AppShell`, not as a field on the returned
    /// [`AppShellLayout`], deliberately: `AppShellLayout` is an
    /// all-`pub`-field struct a real downstream consumer builds with an
    /// exhaustive literal (see that struct's doc), so growing its field
    /// list is a breaking change. `RefCell` for the same reason as
    /// `cached_activity_hits` below — `layout`/`render` take `&self`.
    cached_bottom_band_bounds: RefCell<Vec<(WidgetId, Rect)>>,
    /// Cached hit regions from the last `render()` call. `handle()`
    /// dispatches clicks against these so paint and click agree on
    /// row positions — the structural fix for the GTK ACTIVITY_ROW_PX
    /// vs line_height mismatch (LESSONS.md: one derivation, two consumers).
    /// `RefCell` because `render(&self)` is called from `AppLogic::render`
    /// which takes `&self`.
    cached_activity_hits: RefCell<Vec<ActivityBarRowHit>>,
    cached_activity_bar_bounds: RefCell<Option<Rect>>,
    // ── Keyboard navigation state ─────────────────────────────────
    /// Whether the activity bar currently holds keyboard focus. When
    /// `true`, `build_activity_bar()` sets `is_keyboard_focused = true`
    /// on the emitted [`ActivityBar`], causing the TUI and GTK backends
    /// to redirect [`crate::UiEvent::KeyPressed`] events to
    /// [`crate::UiEvent::ActivityBar`] events — so navigation logic
    /// stays entirely in the consumer.
    activity_keyboard_focused: bool,
    /// Cursor position in the **logical item sequence**: top panels
    /// (indices `0..panels.len()`) followed by bottom items
    /// (indices `panels.len()..panels.len()+bottom_items.len()`).
    /// Saturates at the ends; does not wrap.
    activity_cursor: usize,
    /// Show the keyboard cursor highlight without enabling the key-event
    /// redirect that [`Self::activity_keyboard_focused`] triggers. A
    /// `ShellApp` consumer that handles toolbar keys itself (via its own
    /// `route_sidebar_chord_key` / `handle_activity_bar_key` in
    /// `ShellApp::handle`) uses this to paint the cursor without having
    /// the TUI backend redirect keys to `UiEvent::ActivityBar(…)`.
    activity_cursor_visible: bool,
    /// Per-panel Nerd-Font glyph + ASCII fallback pairs, keyed by
    /// [`WidgetId`], registered via [`Self::with_panel_icon`]. Consulted by
    /// [`Self::build_activity_bar`] in preference to widening the panel's
    /// single [`PanelDefinition::icon`] string. Covers both
    /// top panels and bottom items.
    icon_overrides: HashMap<WidgetId, Icon>,
    /// Colour [`Self::build_activity_bar`] sets on the emitted
    /// [`ActivityBar::active_accent`] — the active-panel accent line/strip
    /// each backend's `draw_activity_bar_with_style` paints when `Some`.
    /// `None` (the default) paints no accent, matching the pre-existing
    /// behaviour for a host that never calls
    /// [`Self::set_active_accent`]/[`Self::with_active_accent`].
    active_accent: Option<Color>,
    /// Colour [`Self::build_activity_bar`] sets on the emitted
    /// [`ActivityBar::selection_bg`] — the keyboard-selection highlight
    /// each backend paints on the [`Self::activity_cursor`] row when the
    /// bar [`Self::activity_keyboard_focused`]. `None` (the default) falls
    /// back to each backend's own reversed/brightened default fill.
    selection_bg: Option<Color>,
}

impl AppShell {
    pub fn new(panels: Vec<PanelDefinition>, default_sidebar_width: f32) -> Self {
        let active = if panels.is_empty() { None } else { Some(0) };
        Self {
            panels,
            bottom_items: Vec::new(),
            active_panel: active,
            sidebar_bottom_owner: None,
            sidebar_visible: true,
            sidebar_width: default_sidebar_width,
            min_sidebar_width: 8.0,
            max_sidebar_width: 800.0,
            activity_bar_width: 4.0,
            activity_bar_width_px: None,
            position: ShellPosition::Left,
            drag_offset: None,
            hovered_activity_idx: None,
            has_title_bar: false,
            title_bar_height_lh: 1.5,
            title_bar_min_px: None,
            has_bottom_panel: false,
            bottom_panel_height_lh: 10.0,
            min_bottom_panel_height_lh: 3.0,
            max_bottom_panel_height_lh: 30.0,
            bottom_panel_visible: true,
            has_command_line: false,
            has_status_bar: false,
            status_bar_height_px: None,
            status_bar_under_main_column: false,
            bottom_panel_drag_offset: None,
            bottom_bands: Vec::new(),
            cached_bottom_band_bounds: RefCell::new(Vec::new()),
            cached_activity_hits: RefCell::new(Vec::new()),
            cached_activity_bar_bounds: RefCell::new(None),
            activity_keyboard_focused: false,
            activity_cursor_visible: false,
            activity_cursor: 0,
            icon_overrides: HashMap::new(),
            active_accent: None,
            selection_bg: None,
        }
    }

    pub fn with_bottom_items(mut self, items: Vec<PanelDefinition>) -> Self {
        self.bottom_items = items;
        self
    }

    /// Attach a distinct Nerd-Font glyph + ASCII fallback pair to one
    /// activity-bar row, overriding the single-string
    /// [`PanelDefinition::icon`] that panel was registered with.
    ///
    /// `id` may name a top panel or a bottom item; unknown ids are stored
    /// but never consulted, so registration order relative to
    /// [`Self::with_bottom_items`] / [`Self::register_panel`] does not
    /// matter. Calling this twice for the same id keeps the last pair.
    ///
    /// Which half actually paints is the backend's decision, driven by its
    /// `nerd_fonts_enabled` flag — `glyph` when the icon font is available,
    /// `fallback` otherwise. Panels that never call this get
    /// `glyph == fallback == PanelDefinition::icon`.
    /// ```
    /// # use quadraui::compose::app_shell::{AppShell, PanelDefinition};
    /// # use quadraui::types::{Icon, WidgetId};
    /// let shell = AppShell::new(
    ///     vec![PanelDefinition {
    ///         id: WidgetId::new("panel:explorer"),
    ///         icon: "E".to_string(),
    ///         tooltip: "Explorer".to_string(),
    ///         title: "EXPLORER".to_string(),
    ///     }],
    ///     20.0,
    /// )
    /// .with_panel_icon(WidgetId::new("panel:explorer"), Icon::new("\u{f07c}", "E"));
    /// assert_eq!(shell.build_activity_bar().top_items[0].icon.glyph, "\u{f07c}");
    /// ```
    #[must_use]
    pub fn with_panel_icon(mut self, id: WidgetId, icon: Icon) -> Self {
        self.icon_overrides.insert(id, icon);
        self
    }

    /// The [`Icon`] an activity-bar row paints: the pair registered via
    /// [`Self::with_panel_icon`] when there is one, otherwise the panel's
    /// single icon string widened to `glyph == fallback`.
    fn resolved_icon(&self, def: &PanelDefinition) -> Icon {
        self.icon_overrides
            .get(&def.id)
            .cloned()
            .unwrap_or_else(|| Icon::from(def.icon.clone()))
    }

    pub fn with_min_width(mut self, min: f32) -> Self {
        self.min_sidebar_width = min;
        self
    }

    pub fn with_max_width(mut self, max: f32) -> Self {
        self.max_sidebar_width = max;
        self
    }

    pub fn with_activity_bar_width(mut self, width: f32) -> Self {
        self.activity_bar_width = width;
        self
    }

    /// Pin the activity bar to a fixed pixel width, overriding the
    /// line-height-derived width from [`Self::with_activity_bar_width`].
    ///
    /// The row height GTK/macOS paint each activity item at
    /// (`ACTIVITY_ROW_PX = 48.0`) is already a fixed pixel constant, not a
    /// `line_height` multiple — so a `with_activity_bar_width(2.4)`-style
    /// call only produces a square 48×48 bar at whatever `line_height`
    /// happens to make `2.4 * lh == 48.0`. Passing `48.0` here keeps the
    /// bar square regardless of the app's editor font size.
    ///
    /// `None` (the default) leaves the existing `line_height`-derived
    /// width in place — this call is additive, not a replacement.
    pub fn with_activity_bar_width_px(mut self, width_px: f32) -> Self {
        self.activity_bar_width_px = Some(width_px);
        self
    }

    /// Colour painted on the active top panel's row in the built
    /// [`ActivityBar`] (its `active_accent` field) — e.g. a theme's accent
    /// colour, so the activity bar shows an active-panel indicator line.
    /// `AppShell` has no `Theme` in scope itself; a host app sources the
    /// colour from its own theme and passes it here before the first
    /// [`Self::render`]. Unset (the default) paints no accent, matching the
    /// pre-existing behaviour.
    #[must_use]
    pub fn with_active_accent(mut self, color: Color) -> Self {
        self.active_accent = Some(color);
        self
    }

    /// Colour painted behind the keyboard-selected row in the built
    /// [`ActivityBar`] (its `selection_bg` field) when
    /// [`Self::activity_keyboard_focused`]. Unset (the default) leaves each
    /// backend's own reversed/brightened fallback fill in charge.
    #[must_use]
    pub fn with_selection_bg(mut self, color: Color) -> Self {
        self.selection_bg = Some(color);
        self
    }

    pub fn with_position(mut self, position: ShellPosition) -> Self {
        self.position = position;
        self
    }

    /// Reserve a title-bar row at construction time. See
    /// [`Self::set_title_bar_visible`] to show/hide the row at runtime
    /// (e.g. a toggleable menu bar) without rebuilding the `AppShell`.
    pub fn with_title_bar(mut self, height_lh: f32) -> Self {
        self.has_title_bar = true;
        self.title_bar_height_lh = height_lh;
        self
    }

    /// Pin a fixed-pixel floor under the title bar's line-height-derived
    /// height, overriding it only when the multiple would otherwise
    /// resolve smaller — mirroring [`Self::with_activity_bar_width_px`]'s
    /// pattern, but as a floor rather than a hard override, since
    /// unlike the activity bar's fixed-size icons, title-bar chrome (menu
    /// labels, inline window controls) is expected to keep scaling with
    /// the editor font above the floor.
    ///
    /// `None` (the default) leaves `title_bar_height_lh * line_height` in
    /// sole charge, unchanged from before this method existed. Set this
    /// when a host needs the band to never shrink under some real
    /// platform constraint it can't otherwise express in line-height
    /// units — e.g. staying clear of macOS's native traffic-light cluster
    /// even after a user shrinks `settings.font_size` at runtime
    pub fn with_title_bar_min_px(mut self, min_px: f32) -> Self {
        self.title_bar_min_px = Some(min_px);
        self
    }

    pub fn with_bottom_panel(mut self, height_lh: f32) -> Self {
        self.has_bottom_panel = true;
        self.bottom_panel_height_lh = height_lh;
        self
    }

    pub fn with_bottom_panel_limits(mut self, min: f32, max: f32) -> Self {
        self.min_bottom_panel_height_lh = min;
        self.max_bottom_panel_height_lh = max;
        self
    }

    /// Register the ordered list of independently-gated bottom bands.
    /// See [`BottomBand`] for the stacking order and how this interacts
    /// with [`Self::with_bottom_panel`].
    ///
    /// Replaces any previously-registered list. `Vec::new()` (the
    /// default) restores a single-drawer layout.
    pub fn with_bottom_bands(mut self, bands: Vec<BottomBand>) -> Self {
        self.bottom_bands = bands;
        self
    }

    pub fn with_command_line(mut self) -> Self {
        self.has_command_line = true;
        self
    }

    pub fn with_status_bar(mut self) -> Self {
        self.has_status_bar = true;
        self
    }

    /// Fix the status bar to `height_px` native units, overriding the
    /// `line_height`-derived height regardless of font size — VS Code's
    /// status bar is a constant 22px. Call alongside [`Self::with_status_bar`];
    /// has no visible effect unless that is also set.
    pub fn with_status_bar_height_px(mut self, height_px: f32) -> Self {
        self.status_bar_height_px = Some(height_px);
        self
    }

    /// Opt into the activity bar and sidebar running the full height of
    /// the area below the title bar, with the status bar and command line
    /// carved from the main column only (main column's x/width) rather
    /// than the full window width.
    ///
    /// Off by default: the status bar and command line span the full
    /// window, and the activity bar/sidebar stop above them — unchanged
    /// from before this method existed. Turn this on when a host wants
    /// the activity bar's bottom-pinned items to sit in the window's
    /// bottom-left corner rather than above a full-width status bar.
    pub fn with_status_bar_under_main_column(mut self) -> Self {
        self.status_bar_under_main_column = true;
        self
    }

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

    /// The [`PanelDefinition`] that currently owns the sidebar: the active
    /// top panel, or a bottom item that was made the owner
    /// via [`Self::show_panel`]. This is the same definition
    /// [`Self::render`] titles the sidebar header from.
    pub fn active_panel(&self) -> Option<&PanelDefinition> {
        self.sidebar_owner_panel()
    }

    /// The id of [`Self::active_panel`] — a top panel's id, or a bottom
    /// item's id when that bottom item owns the sidebar.
    pub fn active_panel_id(&self) -> Option<&WidgetId> {
        self.active_panel().map(|p| &p.id)
    }

    /// Resolves whichever [`PanelDefinition`] currently owns the sidebar —
    /// a bottom item when `sidebar_bottom_owner` is `Some`,
    /// otherwise the top panel at `active_panel`. Shared by
    /// [`Self::active_panel`] and [`Self::render`]'s header block so the
    /// two can never disagree.
    fn sidebar_owner_panel(&self) -> Option<&PanelDefinition> {
        if let Some(j) = self.sidebar_bottom_owner {
            if let Some(p) = self.bottom_items.get(j) {
                return Some(p);
            }
        }
        self.active_panel.and_then(|i| self.panels.get(i))
    }

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

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

    pub fn position(&self) -> ShellPosition {
        self.position
    }

    /// Whether the title-bar row is currently reserved. See
    /// [`Self::set_title_bar_visible`] for the runtime toggle and
    /// [`Self::with_title_bar`] for the construction-time builder.
    pub fn title_bar_visible(&self) -> bool {
        self.has_title_bar
    }

    pub fn hovered_activity_idx(&self) -> Option<usize> {
        self.hovered_activity_idx
    }

    // ── Activity-bar keyboard navigation ─────────────────────────────

    /// Returns `true` when the activity bar currently holds keyboard focus.
    ///
    /// When `true`, `build_activity_bar()` sets `is_keyboard_focused = true`
    /// on the emitted [`ActivityBar`], causing both the TUI and GTK backends
    /// to deliver key presses as
    /// `UiEvent::ActivityBar(id, ActivityBarEvent::KeyPressed { … })` rather
    /// than raw `UiEvent::KeyPressed`. The consumer maps those key strings to
    /// the navigation methods below.
    pub fn activity_keyboard_focused(&self) -> bool {
        self.activity_keyboard_focused
    }

    /// Focus or unfocus the activity bar. Pair with
    /// [`Self::activity_keyboard_focused`] and the navigation methods to
    /// implement keyboard nav in a `ShellApp` consumer.
    ///
    /// Calling this does **not** reset the cursor — the cursor stays where
    /// it was so repeated focus/blur round-trips feel natural. To reset to
    /// the top item on focus, call
    /// `set_activity_keyboard_focused(true)` then `activity_set_cursor(0)`.
    pub fn set_activity_keyboard_focused(&mut self, focused: bool) {
        self.activity_keyboard_focused = focused;
    }

    /// Show (or hide) the keyboard cursor highlight on the activity bar
    /// **without** enabling the key-event redirect that
    /// [`Self::set_activity_keyboard_focused`] triggers.
    ///
    /// A `ShellApp` consumer that routes toolbar keys itself — through its
    /// own chord / key-action handlers inside `ShellApp::handle`, receiving
    /// plain `UiEvent::KeyPressed` events — calls this instead of
    /// `set_activity_keyboard_focused(true)` so the cursor paints but the
    /// TUI / GTK backends leave key events as `KeyPressed` rather than
    /// rewriting them to `UiEvent::ActivityBar(…)`.
    pub fn set_activity_cursor_visible(&mut self, visible: bool) {
        self.activity_cursor_visible = visible;
    }

    /// Set (or clear, with `None`) the active-panel accent colour
    /// [`Self::build_activity_bar`] passes through as
    /// [`ActivityBar::active_accent`]. Runtime counterpart to
    /// [`Self::with_active_accent`] — call this after a theme switch
    /// instead of rebuilding the `AppShell`.
    pub fn set_active_accent(&mut self, color: Option<Color>) {
        self.active_accent = color;
    }

    /// Set (or clear, with `None`) the keyboard-selection highlight colour
    /// [`Self::build_activity_bar`] passes through as
    /// [`ActivityBar::selection_bg`]. Runtime counterpart to
    /// [`Self::with_selection_bg`].
    pub fn set_selection_bg(&mut self, color: Option<Color>) {
        self.selection_bg = color;
    }

    /// Move the keyboard cursor to the next item in the logical sequence
    /// (top panels first, then bottom items). **Saturates** at the last
    /// item — does not wrap to the top.
    pub fn activity_select_next(&mut self) {
        let total = self.panels.len() + self.bottom_items.len();
        if total > 0 {
            self.activity_cursor = (self.activity_cursor + 1).min(total - 1);
        }
    }

    /// Move the keyboard cursor to the previous item. **Saturates** at
    /// index 0 — does not wrap to the bottom.
    pub fn activity_select_prev(&mut self) {
        self.activity_cursor = self.activity_cursor.saturating_sub(1);
    }

    /// Set the keyboard cursor to an explicit index in the logical sequence.
    /// Out-of-range values are clamped to the valid range `[0, total-1]`.
    /// Has no effect when the panel + bottom-item lists are both empty.
    pub fn activity_set_cursor(&mut self, idx: usize) {
        let total = self.panels.len() + self.bottom_items.len();
        if total > 0 {
            self.activity_cursor = idx.min(total - 1);
        }
    }

    /// Returns the [`WidgetId`] of the item currently under the keyboard
    /// cursor, or `None` if there are no items at all.
    ///
    /// The logical sequence is top panels (`0..panels.len()`) followed by
    /// bottom items (`panels.len()..`).
    pub fn activity_selected_id(&self) -> Option<&WidgetId> {
        let np = self.panels.len();
        if self.activity_cursor < np {
            Some(&self.panels[self.activity_cursor].id)
        } else {
            let bi = self.activity_cursor - np;
            self.bottom_items.get(bi).map(|p| &p.id)
        }
    }

    /// Activate the item currently under the keyboard cursor and return
    /// the resulting [`AppShellEvent`], or `None` if there are no items.
    ///
    /// Equivalent to clicking the cursor item: top-panel items trigger the
    /// same toggle / switch logic as a mouse click, bottom items emit
    /// [`AppShellEvent::BottomItemClicked`]. Does **not** clear keyboard
    /// focus — the consumer decides whether to do that.
    pub fn activity_activate_selected(&mut self) -> Option<AppShellEvent> {
        let id = *self.activity_selected_id()?;
        Some(self.handle_activity_click(&id))
    }

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

    /// Make `panel_id` the sidebar's owner and reveal the sidebar.
    ///
    /// Accepts either a top panel's id or a bottom item's id (one
    /// registered via [`Self::with_bottom_items`] / [`Self::add_bottom_item`]).
    /// In the latter case the bottom item becomes the sidebar header's title
    /// source (see [`Self::active_panel`]/[`Self::active_panel_id`]) until
    /// `show_panel` is called again with a different id. A bottom item's own
    /// click ([`Self::handle_activity_click`]'s `BottomItemClicked` branch)
    /// never calls this itself, so an app opts in explicitly from its
    /// `BottomItemClicked` handler.
    ///
    /// A no-op if `panel_id` matches neither a top panel nor a bottom item.
    pub fn show_panel(&mut self, panel_id: &WidgetId) {
        for (i, p) in self.panels.iter().enumerate() {
            if p.id == *panel_id {
                self.active_panel = Some(i);
                self.sidebar_bottom_owner = None;
                self.sidebar_visible = true;
                return;
            }
        }
        for (j, p) in self.bottom_items.iter().enumerate() {
            if p.id == *panel_id {
                self.sidebar_bottom_owner = Some(j);
                self.sidebar_visible = true;
                return;
            }
        }
    }

    pub fn hide_sidebar(&mut self) {
        self.sidebar_visible = false;
    }

    pub fn toggle_sidebar(&mut self) {
        self.sidebar_visible = !self.sidebar_visible;
    }

    /// Runtime toggle for whether the title-bar row is reserved.
    ///
    /// Unlike [`Self::with_title_bar`] — a construction-time builder that
    /// permanently commits to reserving the row for the lifetime of the
    /// `AppShell` — this can be flipped at any point after construction
    /// without rebuilding the shell. `compute_layout` re-derives every
    /// downstream bound (activity bar, sidebar, main content, bottom
    /// panel, ...) from `area` and current state on every
    /// `render`/`layout`/`handle` call, so toggling this and calling any
    /// of those next is sufficient — no other field needs to change in
    /// lockstep, and no fixed offset is cached anywhere that would go stale.
    ///
    /// A menu bar painted into the title-bar row that the user can show/hide
    /// at runtime requires this: always reserving the row costs a row even
    /// while the menu is hidden; never reserving it makes a shown menu
    /// overwrite the activity bar's first row. Toggling this from the app's
    /// own visibility state avoids both.
    ///
    /// If [`Self::with_title_bar`] was never called, toggling visible for
    /// the first time reserves the default height (`title_bar_height_lh`,
    /// 1.5 line-heights). The configured height is otherwise preserved
    /// across visible → hidden → visible round-trips — hiding does not
    /// forget it.
    pub fn set_title_bar_visible(&mut self, visible: bool) {
        self.has_title_bar = visible;
    }

    pub fn set_sidebar_width(&mut self, width: f32) {
        self.sidebar_width = width.clamp(self.min_sidebar_width, self.max_sidebar_width);
    }

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

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

    pub fn show_bottom_panel(&mut self) {
        self.bottom_panel_visible = true;
    }

    pub fn hide_bottom_panel(&mut self) {
        self.bottom_panel_visible = false;
    }

    pub fn toggle_bottom_panel(&mut self) {
        self.bottom_panel_visible = !self.bottom_panel_visible;
    }

    pub fn set_bottom_panel_height(&mut self, height: f32) {
        self.bottom_panel_height_lh = height.clamp(
            self.min_bottom_panel_height_lh,
            self.max_bottom_panel_height_lh,
        );
    }

    // ── Bottom bands ─────────────────────────────────────────────────

    /// The currently-registered bottom bands, in bottom-up stacking order
    /// (see [`BottomBand`]). Includes bands with `visible == false` — use
    /// [`Self::bottom_band_bounds`] to see which ones actually occupied
    /// space in the last computed layout.
    pub fn bottom_bands(&self) -> &[BottomBand] {
        &self.bottom_bands
    }

    /// Resolved bounds for every currently-`visible` [`BottomBand`], from
    /// the most recent [`Self::layout`] or [`Self::render`] call, in the
    /// same bottom-up order `bottom_bands` was given (index 0 = flush
    /// against the bottom edge of the main content column). Bands with
    /// `visible == false` have no entry — they occupy no space that
    /// frame. Empty if `layout`/`render` was never called, or if
    /// [`Self::with_bottom_bands`] was never used.
    ///
    /// Not a field on [`AppShellLayout`] — see that struct's doc for why.
    pub fn bottom_band_bounds(&self) -> Vec<(WidgetId, Rect)> {
        self.cached_bottom_band_bounds.borrow().clone()
    }

    /// Look up one registered band by id.
    pub fn bottom_band(&self, id: &WidgetId) -> Option<&BottomBand> {
        self.bottom_bands.iter().find(|b| &b.id == id)
    }

    /// Flip one band's presence at runtime (e.g. a quickfix list that
    /// opens/closes independently of every other bottom band). Returns
    /// `false` if no band with `id` was registered via
    /// [`Self::with_bottom_bands`].
    pub fn set_bottom_band_visible(&mut self, id: &WidgetId, visible: bool) -> bool {
        match self.bottom_bands.iter_mut().find(|b| &b.id == id) {
            Some(b) => {
                b.visible = visible;
                true
            }
            None => false,
        }
    }

    /// Resize one band at runtime. Returns `false` if no band with `id`
    /// was registered via [`Self::with_bottom_bands`]. Unlike the legacy
    /// single bottom panel, bands have no configurable min/max — callers
    /// own their own clamping (the toolbars/lists vimcode stacks here
    /// generally have a fixed content-driven height, not a user drag).
    pub fn set_bottom_band_height(&mut self, id: &WidgetId, height_lh: f32) -> bool {
        match self.bottom_bands.iter_mut().find(|b| &b.id == id) {
            Some(b) => {
                b.height_lh = height_lh.max(0.0);
                true
            }
            None => false,
        }
    }

    // ── Dynamic panel registration ──────────────────────────────────

    pub fn panels(&self) -> &[PanelDefinition] {
        &self.panels
    }

    pub fn bottom_items(&self) -> &[PanelDefinition] {
        &self.bottom_items
    }

    /// Register a panel at runtime. Returns `false` if a panel with the
    /// same ID already exists (no-op in that case). If this is the first
    /// panel, it becomes the active panel.
    pub fn add_panel(&mut self, def: PanelDefinition) -> bool {
        if self.panels.iter().any(|p| p.id == def.id)
            || self.bottom_items.iter().any(|p| p.id == def.id)
        {
            return false;
        }
        self.panels.push(def);
        if self.panels.len() == 1 {
            self.active_panel = Some(0);
        }
        true
    }

    /// Unregister a panel by ID. Returns `true` if found and removed.
    /// Adjusts `active_panel` to keep the same panel selected (or clears
    /// it if the active panel was the one removed).
    /// Also adjusts `activity_cursor` analogously so keyboard navigation
    /// remains consistent after a dynamic removal.
    pub fn remove_panel(&mut self, id: &WidgetId) -> bool {
        let Some(idx) = self.panels.iter().position(|p| p.id == *id) else {
            return false;
        };
        self.panels.remove(idx);
        self.active_panel = match self.active_panel {
            Some(a) if a == idx => {
                if self.panels.is_empty() {
                    None
                } else {
                    Some(a.min(self.panels.len() - 1))
                }
            }
            Some(a) if a > idx => Some(a - 1),
            other => other,
        };
        // Mirror the same shift logic for the keyboard cursor. The removed
        // panel occupied combined-index `idx`; everything after it shifts
        // down by one.
        let total = self.panels.len() + self.bottom_items.len();
        if total == 0 {
            self.activity_cursor = 0;
            self.activity_keyboard_focused = false;
        } else if self.activity_cursor > idx {
            self.activity_cursor -= 1;
        } else if self.activity_cursor == idx {
            // The cursor was on the removed panel; clamp to the new range.
            self.activity_cursor = self.activity_cursor.min(total - 1);
        }
        // activity_cursor < idx: no change needed.
        true
    }

    /// Register a bottom-pinned activity bar item at runtime.
    pub fn add_bottom_item(&mut self, def: PanelDefinition) -> bool {
        if self.panels.iter().any(|p| p.id == def.id)
            || self.bottom_items.iter().any(|p| p.id == def.id)
        {
            return false;
        }
        self.bottom_items.push(def);
        true
    }

    /// Unregister a bottom item by ID.
    /// Adjusts `activity_cursor` so keyboard navigation remains consistent
    /// after a dynamic removal (mirrors `remove_panel`'s treatment of
    /// `active_panel`). Also adjusts `sidebar_bottom_owner`
    /// the same way `remove_panel` adjusts `active_panel`: shifted down if
    /// it pointed past the removed item, cleared (falling back to whatever
    /// `active_panel` names) if it pointed at the removed item itself.
    pub fn remove_bottom_item(&mut self, id: &WidgetId) -> bool {
        let Some(idx) = self.bottom_items.iter().position(|p| p.id == *id) else {
            return false;
        };
        // Bottom items begin at combined index `np` in the top-then-bottom
        // sequence, so the removed item's combined index is `np + idx`.
        let np = self.panels.len();
        let combined_idx = np + idx;
        self.bottom_items.remove(idx);
        self.sidebar_bottom_owner = match self.sidebar_bottom_owner {
            Some(j) if j == idx => None,
            Some(j) if j > idx => Some(j - 1),
            other => other,
        };
        let total = np + self.bottom_items.len();
        if total == 0 {
            self.activity_cursor = 0;
            self.activity_keyboard_focused = false;
        } else if self.activity_cursor > combined_idx {
            self.activity_cursor -= 1;
        } else if self.activity_cursor == combined_idx {
            self.activity_cursor = self.activity_cursor.min(total - 1);
        }
        // activity_cursor < combined_idx: no change needed.
        true
    }

    // ── Layout ───────────────────────────────────────────────────────

    /// Compute layout bounds without drawing. Use when only hit-testing
    /// is needed (e.g. in `handle`).
    ///
    /// Takes `line_height` rather than a `&dyn Backend` so callers that
    /// only know the line height (external consumers, tests) can still
    /// call it. It mirrors `Backend::snap_height`'s own threshold —
    /// identity above one line height (a real pixel metric), `.round()`
    /// at or below it (TUI's cell grid, whose `chrome_line_height` is
    /// architecturally always exactly `1.0`) — so this path always agrees
    /// with `Self::render`/`Self::handle`, which pass `backend.snap_height`
    /// directly, for the same `area`/`line_height` on the same backend.
    pub fn layout(&self, area: Rect, line_height: f32) -> AppShellLayout {
        self.compute_layout(area, line_height, &|h: f32| {
            if line_height > 1.0 {
                h
            } else {
                h.max(0.0).round()
            }
        })
    }

    /// Build the [`ActivityBar`] primitive from current panel state.
    ///
    /// When [`Self::activity_keyboard_focused`] is `true`:
    /// - `ActivityBar::is_keyboard_focused` is set to `true`, causing both
    ///   the TUI and GTK backends to route key events as
    ///   `UiEvent::ActivityBar(id, ActivityBarEvent::KeyPressed { … })`.
    /// - The item at [`Self::activity_cursor`] (in the top-then-bottom
    ///   logical sequence) has `is_keyboard_selected = true`, painting the
    ///   selection ring on that icon.
    ///
    /// `ActivityBar::active_accent`/`selection_bg` carry whatever colours
    /// were last set via [`Self::with_active_accent`]/[`Self::set_active_accent`]
    /// and [`Self::with_selection_bg`]/[`Self::set_selection_bg`] — `None`
    /// (no accent/highlight painted) until a host app opts in.
    pub fn build_activity_bar(&self) -> ActivityBar {
        let np = self.panels.len();
        let focused = self.activity_keyboard_focused;
        let show_cursor = focused || self.activity_cursor_visible;

        let top_items: Vec<ActivityItem> = self
            .panels
            .iter()
            .enumerate()
            .map(|(i, p)| ActivityItem {
                id: p.id,
                icon: self.resolved_icon(p),
                tooltip: p.tooltip.clone(),
                // A top panel only shows as active while it — not a bottom
                // item — actually owns the sidebar. Without this guard,
                // showing a bottom item via `show_panel` would leave the
                // previously-active top panel's row highlighted even though
                // the header now names the bottom item.
                is_active: self.sidebar_bottom_owner.is_none()
                    && self.active_panel == Some(i)
                    && self.sidebar_visible,
                is_keyboard_selected: show_cursor && self.activity_cursor == i,
            })
            .collect();

        let bottom_items: Vec<ActivityItem> = self
            .bottom_items
            .iter()
            .enumerate()
            .map(|(j, p)| ActivityItem {
                id: p.id,
                icon: self.resolved_icon(p),
                tooltip: p.tooltip.clone(),
                // Bottom items (gear/bell-style) never paint a persistent
                // active accent. The `sidebar_owner_panel()` call titles the
                // header when a bottom item owns it.
                is_active: false,
                is_keyboard_selected: show_cursor && self.activity_cursor == np + j,
            })
            .collect();

        ActivityBar {
            id: WidgetId::new("app-shell:activity-bar"),
            top_items,
            bottom_items,
            // Colours a host app supplies via `with_active_accent`/
            // `set_active_accent` and `with_selection_bg`/`set_selection_bg`
            // — `None` unless the host opts in, matching the pre-existing
            // behaviour.
            active_accent: self.active_accent,
            selection_bg: self.selection_bg,
            is_keyboard_focused: focused,
        }
    }

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

    /// Register a `WidgetId`-keyed [`crate::Backend::register_zone`] entry
    /// for every chrome region `layout` reports, so a
    /// [`crate::testing::ConformanceDriver::inventory`] caller can assert
    /// `inside`/`left_of`/`above` against shell-level zones without
    /// hardcoding a coordinate. Ids are stable,
    /// `app-shell:`-prefixed strings — not the panel/content `WidgetId`s
    /// consumers pick — since a shell has exactly one of each of these
    /// regions per frame.
    ///
    /// Per-item zones (one per activity-bar entry, keyed by that panel's
    /// own `WidgetId`) are registered separately in [`Self::render`],
    /// right after `draw_activity_bar` returns the hit list — this
    /// function only covers the coarser, one-per-frame chrome regions.
    fn register_chrome_zones(backend: &mut dyn Backend, layout: &AppShellLayout) {
        backend.register_zone(WidgetId::new("app-shell:window"), layout.window_bounds);
        backend.register_zone(
            WidgetId::new("app-shell:activity-bar"),
            layout.activity_bar_bounds,
        );
        backend.register_zone(
            WidgetId::new("app-shell:main-content"),
            layout.main_content_bounds,
        );
        for (id, bounds) in [
            ("app-shell:title-bar", layout.title_bar_bounds),
            ("app-shell:sidebar-header", layout.sidebar_header_bounds),
            ("app-shell:sidebar-content", layout.sidebar_content_bounds),
            ("app-shell:divider", layout.divider_bounds),
            ("app-shell:bottom-panel", layout.bottom_panel_bounds),
            ("app-shell:command-line", layout.command_line_bounds),
            ("app-shell:status-bar", layout.status_bar_bounds),
        ] {
            if let Some(bounds) = bounds {
                backend.register_zone(WidgetId::new(id), bounds);
            }
        }
    }

    /// Render shell chrome and return layout bounds for consumer content.
    ///
    /// Draws: activity bar, sidebar header, resize divider.
    /// Consumer draws: sidebar panel content, main content area.
    pub fn render(&self, backend: &mut dyn Backend, area: Rect) -> AppShellLayout {
        let lh = backend.chrome_line_height();
        // `Backend::theme()` reads back whatever the host last passed to
        // `set_theme` — the same palette every `draw_*` rasteriser call
        // below already paints with — so this chrome tracks the app's actual theme.
        let theme = backend.theme();
        let layout = self.compute_layout(area, lh, &|h: f32| backend.snap_height(h));
        Self::register_chrome_zones(backend, &layout);

        let bar = self.build_activity_bar();
        let hits =
            backend.draw_activity_bar(layout.activity_bar_bounds, &bar, self.hovered_activity_idx);
        // Register each activity-bar item's own zone (its real `WidgetId`,
        // e.g. `panel:git`) *before* `hits` moves into the hover-hit cache
        // below — this is the per-item provenance
        // `docs/SMELL_AUDIT_2026-07.md` §6.2/B3 calls for, not just the
        // whole-bar zone `register_chrome_zones` already recorded.
        for hit in &hits {
            let item_bounds = Rect::new(
                layout.activity_bar_bounds.x,
                layout.activity_bar_bounds.y + hit.y_start,
                layout.activity_bar_bounds.width,
                hit.y_end - hit.y_start,
            );
            backend.register_zone(hit.id, item_bounds);
        }
        *self.cached_activity_hits.borrow_mut() = hits;
        *self.cached_activity_bar_bounds.borrow_mut() = Some(layout.activity_bar_bounds);

        if let Some(header_bounds) = layout.sidebar_header_bounds {
            // Titled from whichever `PanelDefinition` owns the sidebar — a
            // bottom item when one was made the owner via `show_panel`,
            // otherwise the active top panel. A bottom item can now title
            // its own header when it becomes the sidebar owner.
            if let Some(panel) = self.sidebar_owner_panel() {
                let header_bar = StatusBar {
                    id: WidgetId::new("app-shell:sidebar-header"),
                    left_segments: vec![StatusBarSegment {
                        text: format!(" {} ", panel.title),
                        fg: theme.header_fg,
                        bg: theme.header_bg,
                        bold: true,
                        action_id: None,
                    }],
                    right_segments: vec![],
                };
                let _ = backend.draw_status_bar_interactive(
                    header_bounds,
                    &header_bar,
                    &InteractionState::new(),
                );
            }
        }

        if let Some(divider_bounds) = layout.divider_bounds {
            // One fill over the whole rect, not N stacked one-row
            // `StatusBar`s. A plain solid fill is simpler and cheaper than
            // N status-bar layouts per frame — there is no text, no segments,
            // and no interaction beyond the drag zone already registered above.
            backend.draw_solid_fill(divider_bounds, theme.separator);
        }

        layout
    }

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

    /// Process a [`UiEvent`] and return a semantic [`AppShellEvent`].
    ///
    /// Call this before the consumer's own event handling. If the result
    /// is not [`AppShellEvent::Ignored`], the consumer should redraw.
    pub fn handle(&mut self, event: &UiEvent, backend: &dyn Backend, area: Rect) -> AppShellEvent {
        let lh = backend.chrome_line_height();
        let layout = self.compute_layout(area, lh, &|h: f32| backend.snap_height(h));

        match event {
            UiEvent::MouseDown {
                button: MouseButton::Left,
                position,
                ..
            } => {
                let p = *position;

                if let Some(div) = layout.divider_bounds {
                    if contains(div, p) {
                        let center_x = div.x + div.width / 2.0;
                        self.drag_offset = Some(p.x - center_x);
                        return AppShellEvent::Consumed;
                    }
                }

                if let Some(bp) = layout.bottom_panel_bounds {
                    // Grip sits *above* the panel's top edge only. The panel's
                    // top row is the tab strip, whose clicks must reach the
                    // bottom-panel controller — so the grip must not overlap it.
                    let grip_h = backend.snap_height(lh * 0.5).max(1.0);
                    let grip = Rect::new(bp.x, bp.y - grip_h, bp.width, grip_h);
                    if contains(grip, p) {
                        self.bottom_panel_drag_offset = Some(p.y - bp.y);
                        return AppShellEvent::Consumed;
                    }
                }

                if contains(layout.activity_bar_bounds, p) {
                    if let Some(hit) = self.cached_activity_hit(p) {
                        return self.handle_activity_click(&hit);
                    }
                    return AppShellEvent::Consumed;
                }

                AppShellEvent::Ignored
            }

            // A fast double-click landing on the activity bar behaves
            // exactly like the second of two single clicks there —
            // `DoubleClickDetector` runs ahead of this `handle` call on
            // every backend and folds a `MouseDown` into a `DoubleClick`
            // whenever it lands within its radius of the previous
            // `MouseDown` within the double-click window. `DoubleClick`
            // carries no button, so (unlike the `MouseDown` arm above) this
            // arm cannot gate on `MouseButton::Left`: a fast double-click
            // with any button that folds here is treated as an activity
            // click.
            UiEvent::DoubleClick { position, .. } => {
                let p = *position;

                if contains(layout.activity_bar_bounds, p) {
                    if let Some(hit) = self.cached_activity_hit(p) {
                        return self.handle_activity_click(&hit);
                    }
                    return AppShellEvent::Consumed;
                }

                AppShellEvent::Ignored
            }

            UiEvent::MouseMoved {
                position,
                buttons:
                    ButtonMask {
                        left: true,
                        middle: _,
                        right: _,
                    },
            } => {
                if let Some(offset) = self.drag_offset {
                    let ab_edge = match self.position {
                        ShellPosition::Left => {
                            layout.activity_bar_bounds.x + layout.activity_bar_bounds.width
                        }
                        ShellPosition::Right => layout.activity_bar_bounds.x,
                    };
                    let new_native = match self.position {
                        ShellPosition::Left => position.x - offset - ab_edge,
                        ShellPosition::Right => ab_edge - position.x + offset,
                    };
                    let new_lh = new_native / lh;
                    let clamped = new_lh.clamp(self.min_sidebar_width, self.max_sidebar_width);
                    self.sidebar_width = clamped;
                    return AppShellEvent::SidebarResized {
                        new_width: clamped * lh,
                    };
                }
                if let Some(offset) = self.bottom_panel_drag_offset {
                    let bottom_edge = area.y + area.height;
                    let new_native = bottom_edge - (position.y - offset);
                    let status_lh = if self.has_status_bar { 1.0 } else { 0.0 };
                    let cmd_lh = if self.has_command_line { 1.0 } else { 0.0 };
                    let new_lh = new_native / lh - status_lh - cmd_lh;
                    let clamped = new_lh.clamp(
                        self.min_bottom_panel_height_lh,
                        self.max_bottom_panel_height_lh,
                    );
                    self.bottom_panel_height_lh = clamped;
                    return AppShellEvent::BottomPanelResized {
                        new_height: clamped * lh,
                    };
                }
                self.update_hover(position, &layout, lh);
                AppShellEvent::Ignored
            }

            UiEvent::MouseMoved { position, .. } => {
                self.update_hover(position, &layout, lh);
                AppShellEvent::Ignored
            }

            UiEvent::MouseUp {
                button: MouseButton::Left,
                ..
            } => {
                if self.drag_offset.take().is_some() {
                    return AppShellEvent::Consumed;
                }
                if self.bottom_panel_drag_offset.take().is_some() {
                    return AppShellEvent::Consumed;
                }
                AppShellEvent::Ignored
            }

            _ => AppShellEvent::Ignored,
        }
    }

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

    /// `snap` quantizes a native-unit extent to what the caller's backend
    /// actually paints: the identity function on pixel backends (GUI paints
    /// fractional heights exactly), `.round()` on a cell grid (TUI, which
    /// snaps to whole rows). [`Self::layout`] derives this from
    /// `line_height` alone (no [`crate::Backend`] in hand);
    /// [`Self::render`]/[`Self::handle`] pass `backend.snap_height`
    /// directly — the two agree because both apply the same
    /// above-one-line-height threshold.
    fn compute_layout(
        &self,
        area: Rect,
        line_height: f32,
        snap: &dyn Fn(f32) -> f32,
    ) -> AppShellLayout {
        // `activity_bar_width_px`, `title_bar_min_px` and
        // `status_bar_height_px` are literal screen pixels. On a cell grid
        // (TUI), `line_height` is architecturally always exactly `1.0` — one
        // character cell, never a real pixel measurement — so a "48px"
        // override would silently become "48 columns". Suppress the three
        // px fields on that backend so the line-height-multiple fields
        // (`activity_bar_width`, `title_bar_height_lh`, and the implicit
        // `snap(lh)` status-bar fallback) keep driving TUI's layout instead.
        let is_cell_grid = line_height <= 1.0;
        let activity_bar_width_px = self.activity_bar_width_px.filter(|_| !is_cell_grid);
        let title_bar_min_px = self.title_bar_min_px.filter(|_| !is_cell_grid);
        let status_bar_height_px = self.status_bar_height_px.filter(|_| !is_cell_grid);

        let lh = line_height.max(1.0);

        // ── Vertical carve: title bar (top), then status/cmd/bottom (bottom) ──

        let mut band_y = area.y;
        let mut band_h = area.height;

        let title_bar_bounds = if self.has_title_bar {
            let h = snap(self.title_bar_height_lh * lh).max(title_bar_min_px.unwrap_or(0.0));
            let r = Rect::new(area.x, band_y, area.width, h);
            band_y += h;
            band_h -= h;
            Some(r)
        } else {
            None
        };

        let status_h = if self.has_status_bar {
            status_bar_height_px.unwrap_or_else(|| snap(lh))
        } else {
            0.0
        };
        let cmd_h = if self.has_command_line { snap(lh) } else { 0.0 };

        // Default carve: the status bar and command line consume height
        // from the shared band before the activity bar/sidebar/main split
        // below, full window width — so those columns stop above them.
        // Opted into `status_bar_under_main_column`, the band stays full
        // height here (the activity bar and sidebar run to the area's
        // bottom edge) and the two bars are instead carved from each
        // branch's own main-column rect below, via `carve_status_chrome`.
        let (status_bar_bounds, command_line_bounds) = if self.status_bar_under_main_column {
            (None, None)
        } else {
            band_h -= status_h;
            let sb = self
                .has_status_bar
                .then(|| Rect::new(area.x, band_y + band_h, area.width, status_h));
            band_h -= cmd_h;
            let cl = self
                .has_command_line
                .then(|| Rect::new(area.x, band_y + band_h, area.width, cmd_h));
            (sb, cl)
        };

        // Bottom panel height — computed here but *not* subtracted from the
        // band. The panel docks only under main content (full width minus the
        // sidebar), so it is carved from the main column after the horizontal
        // split below. The sidebar and activity bar run the full band height.
        // In `status_bar_under_main_column` mode `band_h` has not yet lost
        // the status bar/command line height either (that happens per-branch
        // below), so the 60%-of-band clamp is sized against what the main
        // column will actually have left, not the taller shared band.
        let main_column_h = (band_h
            - if self.status_bar_under_main_column {
                status_h + cmd_h
            } else {
                0.0
            })
        .max(0.0);
        let bottom_panel_h = if self.has_bottom_panel && self.bottom_panel_visible {
            let h = snap(
                self.bottom_panel_height_lh.clamp(
                    self.min_bottom_panel_height_lh,
                    self.max_bottom_panel_height_lh,
                ) * lh,
            );
            Some(h.min(main_column_h * 0.6))
        } else {
            None
        };

        let band_h = band_h.max(0.0);

        // Carve the status bar then the command line from the bottom of a
        // main-column rect — used only in `status_bar_under_main_column`
        // mode. In the default mode those bars were already removed from
        // `band_h` above, at full window width, before this rect existed.
        let carve_status_chrome = |main: Rect| -> (Rect, Option<Rect>, Option<Rect>) {
            let mut remaining = main;
            let status = if self.has_status_bar {
                let h = status_h.min(remaining.height);
                let above_h = (remaining.height - h).max(0.0);
                let rect = Rect::new(remaining.x, remaining.y + above_h, remaining.width, h);
                remaining = Rect::new(remaining.x, remaining.y, remaining.width, above_h);
                Some(rect)
            } else {
                None
            };
            let cmd = if self.has_command_line {
                let h = cmd_h.min(remaining.height);
                let above_h = (remaining.height - h).max(0.0);
                let rect = Rect::new(remaining.x, remaining.y + above_h, remaining.width, h);
                remaining = Rect::new(remaining.x, remaining.y, remaining.width, above_h);
                Some(rect)
            } else {
                None
            };
            (remaining, status, cmd)
        };

        // Split a main-column rect into (content_above, bottom_panel + N
        // bottom_bands). Bottom bands are carved first, stacked
        // bottom-up flush against `main`'s bottom edge in list order (index
        // 0 lowest); the legacy single bottom-panel drawer is then carved
        // from what remains, so it always sits directly above every band —
        // i.e. it behaves as one more, implicit band on top of the list.
        let carve_bottom_chrome = |main: Rect| -> (Rect, Vec<(WidgetId, Rect)>, Option<Rect>) {
            let mut remaining = main;
            let mut band_bounds = Vec::new();
            for band in &self.bottom_bands {
                if !band.visible {
                    continue;
                }
                let h = snap(band.height_lh * lh).clamp(0.0, remaining.height);
                let above_h = (remaining.height - h).max(0.0);
                let rect = Rect::new(remaining.x, remaining.y + above_h, remaining.width, h);
                remaining = Rect::new(remaining.x, remaining.y, remaining.width, above_h);
                band_bounds.push((band.id, rect));
            }
            let bottom_panel_bounds = match bottom_panel_h {
                Some(h) => {
                    let h = h.min(remaining.height);
                    let above_h = (remaining.height - h).max(0.0);
                    let panel = Rect::new(remaining.x, remaining.y + above_h, remaining.width, h);
                    remaining = Rect::new(remaining.x, remaining.y, remaining.width, above_h);
                    Some(panel)
                }
                None => None,
            };
            (remaining, band_bounds, bottom_panel_bounds)
        };

        // Combine the two carves above into the one step every branch below
        // runs on its own `main_bounds` rect: in `status_bar_under_main_column`
        // mode this carves the status bar and command line from the main
        // column first, then the bottom bands/panel above them, so the full
        // bottom-up stack (status bar, command line, bands, panel) lives
        // entirely within the main column; otherwise the status bar and
        // command line bounds computed above (full window width) pass
        // through untouched and only the bottom bands/panel are carved here.
        // (remaining main column, status bar bounds, command line bounds,
        // bottom band bounds, bottom panel bounds).
        type MainColumnChrome = (
            Rect,
            Option<Rect>,
            Option<Rect>,
            Vec<(WidgetId, Rect)>,
            Option<Rect>,
        );
        let finish_main_column = |main: Rect| -> MainColumnChrome {
            let (main, status, cmd) = if self.status_bar_under_main_column {
                carve_status_chrome(main)
            } else {
                (main, status_bar_bounds, command_line_bounds)
            };
            let (main, bands, panel) = carve_bottom_chrome(main);
            (main, status, cmd, bands, panel)
        };

        // ── Horizontal carve: activity bar + sidebar + divider + main ──
        //
        // Band widths (`ab_w`, `sidebar_w`, `divider_w`, `main_w`) are still
        // decided by hand — they depend on clamping/min/max rules that are
        // AppShell's own policy, not a layout concern. Once the widths are
        // known, turning them into left-to-right x-positions is exactly the
        // one-dimensional packing `crate::flex::pack_1d` already does for
        // `Toolbar` and `Form` (same shared engine, see those modules), so
        // `row_x_positions` delegates to it under the `layout` feature.

        let ab_w = activity_bar_width_px.unwrap_or_else(|| snap(self.activity_bar_width * lh));
        let divider_w = snap(lh * 0.25).clamp(1.0, 4.0);

        if !self.sidebar_visible || self.panels.is_empty() {
            let main_w = (area.width - ab_w).max(0.0);
            let (ab_bounds, main_bounds) = match self.position {
                ShellPosition::Left => {
                    let x = row_x_positions(area.x, &[ab_w, main_w]);
                    (
                        Rect::new(x[0], band_y, ab_w, band_h),
                        Rect::new(x[1], band_y, main_w, band_h),
                    )
                }
                ShellPosition::Right => {
                    let x = row_x_positions(area.x, &[main_w, ab_w]);
                    (
                        Rect::new(x[1], band_y, ab_w, band_h),
                        Rect::new(x[0], band_y, main_w, band_h),
                    )
                }
            };
            let (
                main_bounds,
                status_bar_bounds,
                command_line_bounds,
                bottom_band_bounds,
                bottom_panel_bounds,
            ) = finish_main_column(main_bounds);
            *self.cached_bottom_band_bounds.borrow_mut() = bottom_band_bounds;
            return AppShellLayout {
                window_bounds: area,
                title_bar_bounds,
                activity_bar_bounds: ab_bounds,
                sidebar_header_bounds: None,
                sidebar_content_bounds: None,
                divider_bounds: None,
                main_content_bounds: main_bounds,
                bottom_panel_bounds,
                command_line_bounds,
                status_bar_bounds,
            };
        }

        let sidebar_w = snap(
            self.sidebar_width
                .clamp(self.min_sidebar_width, self.max_sidebar_width)
                * lh,
        );
        let remaining = (area.width - ab_w - divider_w).max(0.0);
        let sidebar_w = sidebar_w.min(remaining * 0.8);
        let header_h = lh;

        let main_w = (area.width - ab_w - sidebar_w - divider_w).max(0.0);

        match self.position {
            ShellPosition::Left => {
                let x = row_x_positions(area.x, &[ab_w, sidebar_w, divider_w, main_w]);
                let ab_bounds = Rect::new(x[0], band_y, ab_w, band_h);
                let sidebar_x = x[1];
                let header_bounds = Rect::new(sidebar_x, band_y, sidebar_w, header_h);
                let content_y = band_y + header_h;
                let content_h = (band_h - header_h).max(0.0);
                let content_bounds = Rect::new(sidebar_x, content_y, sidebar_w, content_h);
                let div_bounds = Rect::new(x[2], band_y, divider_w, band_h);
                let main_bounds = Rect::new(x[3], band_y, main_w, band_h);
                let (
                    main_bounds,
                    status_bar_bounds,
                    command_line_bounds,
                    bottom_band_bounds,
                    bottom_panel_bounds,
                ) = finish_main_column(main_bounds);
                *self.cached_bottom_band_bounds.borrow_mut() = bottom_band_bounds;

                AppShellLayout {
                    window_bounds: area,
                    title_bar_bounds,
                    activity_bar_bounds: ab_bounds,
                    sidebar_header_bounds: Some(header_bounds),
                    sidebar_content_bounds: Some(content_bounds),
                    divider_bounds: Some(div_bounds),
                    main_content_bounds: main_bounds,
                    bottom_panel_bounds,
                    command_line_bounds,
                    status_bar_bounds,
                }
            }
            ShellPosition::Right => {
                let x = row_x_positions(area.x, &[main_w, divider_w, sidebar_w, ab_w]);
                let ab_bounds = Rect::new(x[3], band_y, ab_w, band_h);
                let sidebar_x = x[2];
                let header_bounds = Rect::new(sidebar_x, band_y, sidebar_w, header_h);
                let content_y = band_y + header_h;
                let content_h = (band_h - header_h).max(0.0);
                let content_bounds = Rect::new(sidebar_x, content_y, sidebar_w, content_h);
                let div_bounds = Rect::new(x[1], band_y, divider_w, band_h);
                let main_bounds = Rect::new(x[0], band_y, main_w, band_h);
                let (
                    main_bounds,
                    status_bar_bounds,
                    command_line_bounds,
                    bottom_band_bounds,
                    bottom_panel_bounds,
                ) = finish_main_column(main_bounds);
                *self.cached_bottom_band_bounds.borrow_mut() = bottom_band_bounds;

                AppShellLayout {
                    window_bounds: area,
                    title_bar_bounds,
                    activity_bar_bounds: ab_bounds,
                    sidebar_header_bounds: Some(header_bounds),
                    sidebar_content_bounds: Some(content_bounds),
                    divider_bounds: Some(div_bounds),
                    main_content_bounds: main_bounds,
                    bottom_panel_bounds,
                    command_line_bounds,
                    status_bar_bounds,
                }
            }
        }
    }

    fn handle_activity_click(&mut self, clicked_id: &WidgetId) -> AppShellEvent {
        for (i, panel) in self.panels.iter().enumerate() {
            if panel.id == *clicked_id {
                // A bottom item may currently own the sidebar header.
                // Clicking a top panel through this real click/keyboard path
                // must reclaim the header exactly like calling `show_panel(top
                // panel)` would, otherwise the header (and this panel's
                // `is_active` flag in `build_activity_bar`) stays stuck on the
                // bottom item's title/highlight indefinitely. This also keeps
                // `active_panel` in sync with what's actually visible, so the
                // toggle-hide branch below doesn't fire on a stale `active_panel`.
                if self.active_panel == Some(i)
                    && self.sidebar_visible
                    && self.sidebar_bottom_owner.is_none()
                {
                    self.sidebar_visible = false;
                    return AppShellEvent::SidebarHidden;
                } else {
                    self.active_panel = Some(i);
                    self.sidebar_bottom_owner = None;
                    self.sidebar_visible = true;
                    return AppShellEvent::PanelChanged { panel_id: panel.id };
                }
            }
        }

        for item in &self.bottom_items {
            if item.id == *clicked_id {
                return AppShellEvent::BottomItemClicked { id: item.id };
            }
        }

        AppShellEvent::Consumed
    }

    fn cached_activity_hit(&self, position: Point) -> Option<WidgetId> {
        let ab = (*self.cached_activity_bar_bounds.borrow())?;
        let hits = self.cached_activity_hits.borrow();
        for hit in hits.iter() {
            if position.y >= hit.y_start + ab.y
                && position.y < hit.y_end + ab.y
                && position.x >= ab.x
                && position.x < ab.x + ab.width
            {
                return Some(hit.id);
            }
        }
        None
    }

    fn update_hover(&mut self, position: &Point, layout: &AppShellLayout, _line_height: f32) {
        if contains(layout.activity_bar_bounds, *position) {
            let ab = layout.activity_bar_bounds;
            let hits = self.cached_activity_hits.borrow();
            self.hovered_activity_idx = hits
                .iter()
                .position(|hit| position.y >= hit.y_start + ab.y && position.y < hit.y_end + ab.y);
        } else {
            self.hovered_activity_idx = None;
        }
    }
}

/// Compute each chrome band's left edge, left-to-right starting at
/// `origin`, with no gap between consecutive bands, never shrinking.
///
/// With the `layout` feature this runs through [`crate::flex`]'s shared
/// flexbox engine — the same one `Toolbar` and `Form` pack their rows
/// through. Without it, the same arithmetic is done by hand.
#[cfg(feature = "layout")]
fn row_x_positions(origin: f32, sizes: &[f32]) -> Vec<f32> {
    crate::flex::pack_1d(crate::flex::FlexDirection::Row, origin, sizes, 0.0, 0.0)
}

/// Same contract as the `layout`-feature arm above, computed by hand.
#[cfg(not(feature = "layout"))]
fn row_x_positions(origin: f32, sizes: &[f32]) -> Vec<f32> {
    let mut x = origin;
    let mut xs = Vec::with_capacity(sizes.len());
    for &s in sizes {
        xs.push(x);
        x += s;
    }
    xs
}

fn contains(rect: Rect, point: Point) -> bool {
    point.x >= rect.x
        && point.x < rect.x + rect.width
        && point.y >= rect.y
        && point.y < rect.y + rect.height
}

// ── Tests ────────────────────────────────────────────────────────────

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

    fn sample_panels() -> Vec<PanelDefinition> {
        vec![
            PanelDefinition {
                id: WidgetId::new("panel:explorer"),
                icon: "E".into(),
                tooltip: "Explorer".into(),
                title: "EXPLORER".into(),
            },
            PanelDefinition {
                id: WidgetId::new("panel:search"),
                icon: "S".into(),
                tooltip: "Search".into(),
                title: "SEARCH".into(),
            },
            PanelDefinition {
                id: WidgetId::new("panel:git"),
                icon: "G".into(),
                tooltip: "Git".into(),
                title: "SOURCE CONTROL".into(),
            },
        ]
    }

    fn sample_bottom() -> Vec<PanelDefinition> {
        vec![PanelDefinition {
            id: WidgetId::new("panel:settings"),
            icon: "*".into(),
            tooltip: "Settings".into(),
            title: "Settings".into(),
        }]
    }

    fn shell() -> AppShell {
        AppShell::new(sample_panels(), 30.0).with_bottom_items(sample_bottom())
    }

    fn area() -> Rect {
        Rect::new(0.0, 0.0, 80.0, 24.0)
    }

    // ── Construction ────────────────────────────────────────────────

    #[test]
    fn new_starts_with_first_panel_active() {
        let s = shell();
        assert_eq!(
            s.active_panel().unwrap().id,
            WidgetId::new("panel:explorer")
        );
        assert!(s.sidebar_visible());
    }

    #[test]
    fn empty_panels_has_no_active() {
        let s = AppShell::new(vec![], 30.0);
        assert!(s.active_panel().is_none());
        assert!(s.sidebar_visible());
    }

    // ── Layout — sidebar visible ────────────────────────────────────

    #[test]
    fn layout_visible_left_bounds_sum_to_width() {
        let s = shell();
        let l = s.layout(area(), 1.0);
        let total = l.activity_bar_bounds.width
            + l.sidebar_header_bounds.unwrap().width
            + l.divider_bounds.unwrap().width
            + l.main_content_bounds.width;
        assert!(
            (total - area().width).abs() < 1.0,
            "total={total}, expected={}",
            area().width
        );
    }

    #[test]
    fn layout_visible_left_no_overlap() {
        let s = shell();
        let l = s.layout(area(), 1.0);
        let ab_end = l.activity_bar_bounds.x + l.activity_bar_bounds.width;
        let sb_start = l.sidebar_header_bounds.unwrap().x;
        let sb_end = sb_start + l.sidebar_header_bounds.unwrap().width;
        let div_start = l.divider_bounds.unwrap().x;
        let div_end = div_start + l.divider_bounds.unwrap().width;
        let main_start = l.main_content_bounds.x;
        assert!(ab_end <= sb_start + 0.01);
        assert!(sb_end <= div_start + 0.01);
        assert!(div_end <= main_start + 0.01);
    }

    #[test]
    fn layout_visible_sidebar_content_below_header() {
        let s = shell();
        let l = s.layout(area(), 1.0);
        let header = l.sidebar_header_bounds.unwrap();
        let content = l.sidebar_content_bounds.unwrap();
        assert_eq!(content.y, header.y + header.height);
        assert_eq!(content.width, header.width);
    }

    // ── Activity bar width ──────────────────────────────────────────

    /// The default activity bar width (4.0 line-heights) tracks
    /// `line_height`, same as every other chrome dimension.
    #[test]
    fn activity_bar_width_tracks_line_height_by_default() {
        let s = shell();
        assert_eq!(s.layout(area(), 20.0).activity_bar_bounds.width, 80.0);
        assert_eq!(s.layout(area(), 10.0).activity_bar_bounds.width, 40.0);
    }

    /// `with_activity_bar_width` overrides the line-height multiple itself
    /// — e.g. 2.4 lh lands on 48px at lh=20, matching VS Code's 48px bar.
    #[test]
    fn with_activity_bar_width_overrides_the_multiple() {
        let s = shell().with_activity_bar_width(2.4);
        assert_eq!(s.layout(area(), 20.0).activity_bar_bounds.width, 48.0);
    }

    /// `with_activity_bar_width_px` pins the bar to an exact pixel width
    /// that does not move when `line_height` changes.
    #[test]
    fn with_activity_bar_width_px_is_independent_of_line_height() {
        let s = shell().with_activity_bar_width_px(48.0);
        assert_eq!(s.layout(area(), 20.0).activity_bar_bounds.width, 48.0);
        assert_eq!(s.layout(area(), 10.0).activity_bar_bounds.width, 48.0);
        assert_eq!(s.layout(area(), 37.5).activity_bar_bounds.width, 48.0);
    }

    /// A fixed-px override wins over a line-height multiple set via
    /// `with_activity_bar_width` on the same shell, not the other way
    /// around.
    #[test]
    fn with_activity_bar_width_px_wins_over_line_height_multiple() {
        let s = shell()
            .with_activity_bar_width(3.0)
            .with_activity_bar_width_px(48.0);
        assert_eq!(s.layout(area(), 20.0).activity_bar_bounds.width, 48.0);
    }

    // ── Title bar min-px floor ──────────────────────────────────────

    /// With no floor set, the title bar's height is exactly the
    /// line-height multiple.
    #[test]
    fn title_bar_height_tracks_line_height_by_default() {
        let s = shell().with_title_bar(1.5);
        let h = s.layout(area(), 20.0).title_bar_bounds.unwrap().height;
        assert_eq!(h, 30.0);
    }

    /// `with_title_bar_min_px` is a floor, not an override: when the
    /// line-height-derived height already clears it, the multiple still
    /// wins — unlike `with_activity_bar_width_px`, which always wins.
    #[test]
    fn with_title_bar_min_px_does_not_shrink_a_height_already_above_it() {
        let s = shell().with_title_bar(1.5).with_title_bar_min_px(20.0);
        let h = s.layout(area(), 20.0).title_bar_bounds.unwrap().height;
        assert_eq!(h, 30.0);
    }

    /// When a small `line_height` would resolve the multiple under the
    /// floor, the floor wins instead — the title bar must not shrink past
    /// real platform constraints such as a traffic-light cluster height.
    #[test]
    fn with_title_bar_min_px_floors_a_height_that_would_otherwise_shrink_below_it() {
        let s = shell().with_title_bar(1.5).with_title_bar_min_px(34.0);
        let h = s.layout(area(), 6.0).title_bar_bounds.unwrap().height;
        assert_eq!(h, 34.0);
    }

    /// On a cell grid (`line_height <= 1.0`, TUI's architecture), the three
    /// px overrides are suppressed entirely — a "48px" activity bar would
    /// otherwise become "48 columns", which is not what the caller asked
    /// for. The line-height-multiple fields drive layout instead, exactly
    /// as if the px overrides were never set.
    #[test]
    fn px_overrides_are_suppressed_on_a_cell_grid() {
        let with_px = shell()
            .with_activity_bar_width(3.0)
            .with_activity_bar_width_px(48.0)
            .with_title_bar(1.5)
            .with_title_bar_min_px(34.0)
            .with_status_bar_height_px(22.0);
        let without_px = shell().with_activity_bar_width(3.0).with_title_bar(1.5);

        let l_px = with_px.layout(area(), 1.0);
        let l_plain = without_px.layout(area(), 1.0);

        assert_eq!(
            l_px.activity_bar_bounds.width,
            l_plain.activity_bar_bounds.width
        );
        assert_eq!(
            l_px.title_bar_bounds.unwrap().height,
            l_plain.title_bar_bounds.unwrap().height
        );
    }

    // ── Layout — sidebar hidden ─────────────────────────────────────

    #[test]
    fn layout_hidden_no_sidebar_bounds() {
        let mut s = shell();
        s.hide_sidebar();
        let l = s.layout(area(), 1.0);
        assert!(l.sidebar_header_bounds.is_none());
        assert!(l.sidebar_content_bounds.is_none());
        assert!(l.divider_bounds.is_none());
    }

    #[test]
    fn layout_hidden_main_fills_remaining() {
        let mut s = shell();
        s.hide_sidebar();
        let l = s.layout(area(), 1.0);
        let expected = area().width - s.activity_bar_width;
        assert!((l.main_content_bounds.width - expected).abs() < 0.01);
    }

    // ── Layout — Right position ─────────────────────────────────────

    #[test]
    fn layout_right_position_activity_bar_at_right_edge() {
        let s = shell().with_position(ShellPosition::Right);
        let l = s.layout(area(), 1.0);
        let ab_right = l.activity_bar_bounds.x + l.activity_bar_bounds.width;
        assert!((ab_right - area().width).abs() < 0.01);
    }

    #[test]
    fn layout_right_position_main_at_left_edge() {
        let s = shell().with_position(ShellPosition::Right);
        let l = s.layout(area(), 1.0);
        assert!((l.main_content_bounds.x - area().x).abs() < 0.01);
    }

    // ── Toggle state machine ────────────────────────────────────────

    #[test]
    fn toggle_click_active_icon_hides_sidebar() {
        let mut s = shell();
        assert!(s.sidebar_visible());
        let ev = s.handle_activity_click(&WidgetId::new("panel:explorer"));
        assert_eq!(ev, AppShellEvent::SidebarHidden);
        assert!(!s.sidebar_visible());
    }

    #[test]
    fn toggle_click_different_icon_switches_panel() {
        let mut s = shell();
        let ev = s.handle_activity_click(&WidgetId::new("panel:search"));
        assert_eq!(
            ev,
            AppShellEvent::PanelChanged {
                panel_id: WidgetId::new("panel:search")
            }
        );
        assert!(s.sidebar_visible());
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:search")));
    }

    #[test]
    fn toggle_click_when_hidden_shows_panel() {
        let mut s = shell();
        s.hide_sidebar();
        let ev = s.handle_activity_click(&WidgetId::new("panel:git"));
        assert_eq!(
            ev,
            AppShellEvent::PanelChanged {
                panel_id: WidgetId::new("panel:git")
            }
        );
        assert!(s.sidebar_visible());
    }

    #[test]
    fn toggle_remembers_last_panel_after_hide() {
        let mut s = shell();
        s.handle_activity_click(&WidgetId::new("panel:search"));
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:search")));
        s.handle_activity_click(&WidgetId::new("panel:search"));
        assert!(!s.sidebar_visible());
        // Re-click the same panel: should show it again.
        s.handle_activity_click(&WidgetId::new("panel:search"));
        assert!(s.sidebar_visible());
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:search")));
    }

    #[test]
    fn bottom_item_click_emits_event_no_sidebar_change() {
        let mut s = shell();
        let was_visible = s.sidebar_visible();
        let ev = s.handle_activity_click(&WidgetId::new("panel:settings"));
        assert_eq!(
            ev,
            AppShellEvent::BottomItemClicked {
                id: WidgetId::new("panel:settings")
            }
        );
        assert_eq!(s.sidebar_visible(), was_visible);
        // The bottom item's own click never touches sidebar
        // ownership — an app opts in explicitly via `show_panel`.
        assert_eq!(
            s.active_panel_id(),
            Some(&WidgetId::new("panel:explorer")),
            "a bare BottomItemClicked must not retitle the header on its own"
        );
    }

    /// `show_panel` accepts a bottom item's id, not just a top
    /// panel's — the fix that lets a bottom item (e.g. a Settings gear
    /// added via `with_bottom_items`) title the sidebar header.
    #[test]
    fn show_panel_accepts_bottom_item_id_and_titles_header() {
        let mut s = shell();
        assert_eq!(
            s.active_panel_id(),
            Some(&WidgetId::new("panel:explorer")),
            "starts on the top panel"
        );
        s.show_panel(&WidgetId::new("panel:settings"));
        assert!(s.sidebar_visible());
        assert_eq!(
            s.active_panel_id(),
            Some(&WidgetId::new("panel:settings")),
            "show_panel(bottom item id) must make it the sidebar's owner"
        );
        assert_eq!(s.active_panel().unwrap().title, "Settings");
    }

    /// Switching back to a top panel after a bottom item owned the sidebar
    /// must hand ownership back — the header must not get stuck on the
    /// bottom item.
    #[test]
    fn show_panel_top_panel_after_bottom_item_reclaims_header() {
        let mut s = shell();
        s.show_panel(&WidgetId::new("panel:settings"));
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:settings")));
        s.show_panel(&WidgetId::new("panel:git"));
        assert_eq!(
            s.active_panel_id(),
            Some(&WidgetId::new("panel:git")),
            "a subsequent show_panel(top panel) must reclaim the header"
        );
    }

    /// Clicking a *different* top panel through the real
    /// activity-bar click path (`handle_activity_click`, not `show_panel`
    /// directly) after a bottom item claimed the sidebar must also reclaim
    /// the header. This is the path `AppShellDemo` and vimcode actually use
    /// for mouse/keyboard interaction — `show_panel_top_panel_after_bottom_item_reclaims_header`
    /// only covers the direct-API path.
    #[test]
    fn handle_activity_click_top_panel_after_bottom_item_reclaims_header() {
        let mut s = shell();
        s.show_panel(&WidgetId::new("panel:settings"));
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:settings")));

        let ev = s.handle_activity_click(&WidgetId::new("panel:git"));
        assert_eq!(
            ev,
            AppShellEvent::PanelChanged {
                panel_id: WidgetId::new("panel:git")
            }
        );
        assert_eq!(
            s.active_panel_id(),
            Some(&WidgetId::new("panel:git")),
            "clicking a top panel via the activity bar must reclaim the header \
             from a bottom item, not leave it stuck on Settings"
        );
        assert!(s.sidebar_visible());

        let bar = s.build_activity_bar();
        let git_item = bar
            .top_items
            .iter()
            .find(|i| i.id == WidgetId::new("panel:git"))
            .unwrap();
        assert!(
            git_item.is_active,
            "Git's activity-bar row must be highlighted once it reclaims the header"
        );
    }

    /// The stale-`active_panel` toggle-hide bug. Before the
    /// fix, `active_panel` stayed on the panel that was active *before* a
    /// bottom item took ownership, so re-clicking that panel's icon would
    /// hit the toggle-hide branch (`active_panel == Some(i) && visible`)
    /// and hide the whole sidebar instead of switching the header back to
    /// it.
    #[test]
    fn handle_activity_click_reclaim_does_not_hide_sidebar() {
        let mut s = shell();
        // Explorer (index 0) is active by default. Claim the sidebar with
        // a bottom item without ever clicking Explorer away.
        s.show_panel(&WidgetId::new("panel:settings"));
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:settings")));
        assert!(s.sidebar_visible());

        // Re-clicking Explorer's icon now must switch the header back to
        // Explorer, not hide the sidebar.
        let ev = s.handle_activity_click(&WidgetId::new("panel:explorer"));
        assert_eq!(
            ev,
            AppShellEvent::PanelChanged {
                panel_id: WidgetId::new("panel:explorer")
            }
        );
        assert!(
            s.sidebar_visible(),
            "reclaiming the header must not hide the sidebar"
        );
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:explorer")));
    }

    /// A top panel's activity-bar row must not still show as active while
    /// a bottom item owns the sidebar — otherwise the highlighted icon and
    /// the header title would disagree about what's open.
    #[test]
    fn build_activity_bar_top_panel_not_active_once_bottom_item_owns_sidebar() {
        let mut s = shell();
        s.show_panel(&WidgetId::new("panel:settings"));
        let bar = s.build_activity_bar();
        assert!(bar.top_items.iter().all(|i| !i.is_active));
    }

    /// Unregistering the bottom item that currently owns the sidebar must
    /// clear that ownership (mirrors `remove_last_panel_clears_active` for
    /// top panels), not leave a dangling index.
    #[test]
    fn remove_bottom_item_that_owns_sidebar_clears_ownership() {
        let mut s = shell();
        s.show_panel(&WidgetId::new("panel:settings"));
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:settings")));
        s.remove_bottom_item(&WidgetId::new("panel:settings"));
        // Falls back to the top panel that was active before the bottom
        // item took ownership.
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:explorer")));
    }

    // ── build_activity_bar ──────────────────────────────────────────

    #[test]
    fn build_activity_bar_marks_active() {
        let s = shell();
        let bar = s.build_activity_bar();
        assert!(bar.top_items[0].is_active);
        assert!(!bar.top_items[1].is_active);
        assert!(!bar.top_items[2].is_active);
    }

    #[test]
    fn build_activity_bar_accent_and_selection_bg_default_to_none() {
        let s = shell();
        let bar = s.build_activity_bar();
        assert_eq!(bar.active_accent, None);
        assert_eq!(bar.selection_bg, None);
    }

    #[test]
    fn build_activity_bar_carries_colors_set_via_builder() {
        let accent = Color::rgb(80, 140, 255);
        let selection = Color::rgb(60, 60, 60);
        let s = shell()
            .with_active_accent(accent)
            .with_selection_bg(selection);
        let bar = s.build_activity_bar();
        assert_eq!(bar.active_accent, Some(accent));
        assert_eq!(bar.selection_bg, Some(selection));
    }

    #[test]
    fn set_active_accent_and_selection_bg_update_at_runtime() {
        let accent = Color::rgb(10, 20, 30);
        let selection = Color::rgb(40, 50, 60);
        let mut s = shell();
        assert_eq!(s.build_activity_bar().active_accent, None);

        s.set_active_accent(Some(accent));
        s.set_selection_bg(Some(selection));
        let bar = s.build_activity_bar();
        assert_eq!(bar.active_accent, Some(accent));
        assert_eq!(bar.selection_bg, Some(selection));

        s.set_active_accent(None);
        s.set_selection_bg(None);
        let bar = s.build_activity_bar();
        assert_eq!(bar.active_accent, None);
        assert_eq!(bar.selection_bg, None);
    }

    #[test]
    fn build_activity_bar_hidden_sidebar_no_active() {
        let mut s = shell();
        s.hide_sidebar();
        let bar = s.build_activity_bar();
        assert!(bar.top_items.iter().all(|i| !i.is_active));
    }

    #[test]
    fn build_activity_bar_includes_bottom_items() {
        let s = shell();
        let bar = s.build_activity_bar();
        assert_eq!(bar.bottom_items.len(), 1);
        assert_eq!(bar.bottom_items[0].id, WidgetId::new("panel:settings"));
    }

    /// The `Icon` pair registered with `AppShell::with_panel_icon` survives
    /// `build_activity_bar` into `ActivityItem::icon`, and the TUI rasteriser
    /// picks the right half — `glyph` when `nerd_fonts_enabled`, `fallback`
    /// otherwise. A rendered-output assertion, not just a type-level check.
    #[test]
    #[cfg(feature = "tui")]
    fn with_panel_icon_reaches_the_painted_column_via_the_nerd_fonts_flag() {
        let panels = vec![PanelDefinition {
            id: WidgetId::new("panel:explorer"),
            icon: "E".to_string(),
            tooltip: "Explorer".into(),
            title: "EXPLORER".into(),
        }];
        let s = AppShell::new(panels, 3.0)
            .with_panel_icon(WidgetId::new("panel:explorer"), Icon::new("\u{f07c}", "E"));
        let bar = s.build_activity_bar();
        assert_eq!(bar.top_items[0].icon, Icon::new("\u{f07c}", "E"));

        assert!(
            paint_first_row(&bar, true).contains('\u{f07c}'),
            "nerd_fonts_enabled: true should paint the override's glyph"
        );
        assert!(
            paint_first_row(&bar, false).contains('E'),
            "nerd_fonts_enabled: false should paint the override's fallback"
        );
    }

    /// A panel with no `with_panel_icon` override paints its single
    /// `PanelDefinition::icon` string under both settings of the
    /// `nerd_fonts_enabled` flag — the pre-existing behaviour, preserved so
    /// that leaving the field a `String` is not a silent downgrade.
    #[test]
    #[cfg(feature = "tui")]
    fn panel_without_icon_override_paints_its_string_under_either_nerd_font_setting() {
        let panels = vec![PanelDefinition {
            id: WidgetId::new("panel:explorer"),
            icon: "E".to_string(),
            tooltip: "Explorer".into(),
            title: "EXPLORER".into(),
        }];
        let bar = AppShell::new(panels, 3.0).build_activity_bar();
        assert_eq!(bar.top_items[0].icon, Icon::new("E", "E"));

        assert!(paint_first_row(&bar, true).contains('E'));
        assert!(paint_first_row(&bar, false).contains('E'));
    }

    /// `with_panel_icon` reaches bottom items too, not just top
    /// panels — both go through the same `resolved_icon` seam.
    #[test]
    fn with_panel_icon_applies_to_bottom_items() {
        let s =
            shell().with_panel_icon(WidgetId::new("panel:settings"), Icon::new("\u{f013}", "*"));
        let bar = s.build_activity_bar();
        assert_eq!(bar.bottom_items[0].icon, Icon::new("\u{f013}", "*"));
        // Untouched top panels keep the widened single-string form.
        assert_eq!(bar.top_items[0].icon, Icon::new("E", "E"));
    }

    /// Paints `bar` into a 4-cell-wide activity column and returns row 0's
    /// symbols concatenated, so a test can assert on what actually landed
    /// in the buffer rather than on the model.
    #[cfg(feature = "tui")]
    fn paint_first_row(bar: &ActivityBar, nerd_fonts_enabled: bool) -> String {
        let theme = crate::theme::Theme::default();
        let mut buf = ratatui::buffer::Buffer::empty(ratatui::layout::Rect::new(0, 0, 40, 10));
        let area = ratatui::layout::Rect::new(0, 0, 4, 10);
        crate::tui::draw_activity_bar(&mut buf, area, bar, &theme, None, nerd_fonts_enabled);
        (area.x..area.x + area.width)
            .map(|x| buf[(x, area.y)].symbol().to_string())
            .collect::<String>()
    }

    /// `render`'s sidebar header and resize divider used
    /// to paint fixed VS-Code-dark literals (`Color::rgb(37,37,38)` /
    /// `Color::rgb(100,100,110)`) regardless of what theme the app had
    /// configured. This drives a real [`crate::tui::TuiBackend`] with a
    /// theme that is neither of those literals and asserts the painted
    /// cells came from `Backend::theme()` — i.e. from whatever the host
    /// last passed to `set_theme` — not a baked-in dark palette.
    #[test]
    #[cfg(feature = "tui")]
    fn render_sources_header_and_divider_from_backend_theme() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        // A light-ish theme, deliberately far from both old literals.
        let light = crate::theme::Theme {
            header_bg: crate::types::Color::rgb(240, 240, 240),
            header_fg: crate::types::Color::rgb(10, 10, 10),
            separator: crate::types::Color::rgb(200, 200, 200),
            ..crate::theme::Theme::default()
        };

        let s = shell();
        let a = area();
        let mut backend = crate::tui::TuiBackend::new();
        backend.set_current_theme(light);

        let mut terminal =
            Terminal::new(TestBackend::new(a.width as u16, a.height as u16)).expect("terminal");
        let mut layout = None;
        terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    layout = Some(s.render(b, a));
                });
            })
            .expect("draw");
        let layout = layout.expect("render ran inside the frame scope");

        let header = layout
            .sidebar_header_bounds
            .expect("sidebar is visible with an active panel, so a header is laid out");
        let buf = terminal.backend().buffer();
        let header_cell = &buf[(header.x as u16, header.y as u16)];
        assert_eq!(
            header_cell.bg,
            crate::tui::ratatui_color(light.header_bg),
            "sidebar header bg must come from theme.header_bg, not a hardcoded literal"
        );
        assert_eq!(
            header_cell.fg,
            crate::tui::ratatui_color(light.header_fg),
            "sidebar header fg must come from theme.header_fg, not a hardcoded literal"
        );

        let divider = layout
            .divider_bounds
            .expect("sidebar is visible, so a resize divider is laid out");
        let divider_cell = &buf[(divider.x as u16, divider.y as u16)];
        assert_eq!(
            divider_cell.bg,
            crate::tui::ratatui_color(light.separator),
            "resize divider must come from theme.separator, not a hardcoded literal"
        );
    }

    // ── Keyboard navigation ─────────────────────────────────────────

    #[test]
    fn keyboard_focus_off_by_default() {
        let s = shell();
        assert!(!s.activity_keyboard_focused());
        let bar = s.build_activity_bar();
        assert!(!bar.is_keyboard_focused);
        assert!(bar.top_items.iter().all(|i| !i.is_keyboard_selected));
        assert!(bar.bottom_items.iter().all(|i| !i.is_keyboard_selected));
    }

    #[test]
    fn set_keyboard_focused_propagates_to_bar() {
        let mut s = shell();
        s.set_activity_keyboard_focused(true);
        assert!(s.activity_keyboard_focused());
        let bar = s.build_activity_bar();
        assert!(bar.is_keyboard_focused);
    }

    #[test]
    fn build_activity_bar_marks_cursor_item_when_focused() {
        let mut s = shell();
        s.set_activity_keyboard_focused(true);
        // Default cursor = 0 (first top panel).
        let bar = s.build_activity_bar();
        assert!(bar.top_items[0].is_keyboard_selected);
        assert!(!bar.top_items[1].is_keyboard_selected);
        assert!(!bar.top_items[2].is_keyboard_selected);
        assert!(!bar.bottom_items[0].is_keyboard_selected);
    }

    #[test]
    fn build_activity_bar_no_selection_when_not_focused() {
        let mut s = shell();
        s.activity_cursor = 1;
        // focused is false → no item should be selected
        let bar = s.build_activity_bar();
        assert!(bar.top_items.iter().all(|i| !i.is_keyboard_selected));
    }

    #[test]
    fn select_next_advances_cursor_through_top_then_bottom() {
        let mut s = shell(); // 3 top + 1 bottom
        s.set_activity_keyboard_focused(true);
        // cursor starts at 0
        s.activity_select_next(); // → 1
        assert_eq!(s.activity_cursor, 1);
        s.activity_select_next(); // → 2
        assert_eq!(s.activity_cursor, 2);
        s.activity_select_next(); // → 3 (first bottom item)
        assert_eq!(s.activity_cursor, 3);

        let bar = s.build_activity_bar();
        assert!(bar.bottom_items[0].is_keyboard_selected);
        assert!(bar.top_items.iter().all(|i| !i.is_keyboard_selected));
    }

    #[test]
    fn select_next_saturates_at_last_item() {
        let mut s = shell(); // total = 4
        s.set_activity_keyboard_focused(true);
        for _ in 0..10 {
            s.activity_select_next();
        }
        // Should saturate at 3 (last index: 3 top + 1 bottom − 1 = 3).
        assert_eq!(s.activity_cursor, 3);
    }

    #[test]
    fn select_prev_saturates_at_zero() {
        let mut s = shell();
        // cursor is already at 0
        s.activity_select_prev();
        assert_eq!(s.activity_cursor, 0);
        s.activity_select_prev();
        assert_eq!(s.activity_cursor, 0);
    }

    #[test]
    fn select_prev_moves_cursor_up() {
        let mut s = shell();
        s.activity_cursor = 3; // bottom item
        s.activity_select_prev();
        assert_eq!(s.activity_cursor, 2);
        s.activity_select_prev();
        assert_eq!(s.activity_cursor, 1);
        s.activity_select_prev();
        assert_eq!(s.activity_cursor, 0);
        s.activity_select_prev(); // saturates
        assert_eq!(s.activity_cursor, 0);
    }

    #[test]
    fn activity_set_cursor_clamps_to_valid_range() {
        let mut s = shell(); // 4 items total
        s.activity_set_cursor(100);
        assert_eq!(s.activity_cursor, 3);
        s.activity_set_cursor(0);
        assert_eq!(s.activity_cursor, 0);
    }

    #[test]
    fn activity_selected_id_top_items() {
        let s = shell();
        // cursor at 0 → first top panel
        assert_eq!(
            s.activity_selected_id(),
            Some(&WidgetId::new("panel:explorer"))
        );
    }

    #[test]
    fn activity_selected_id_bottom_item() {
        let mut s = shell();
        s.activity_cursor = 3; // first (and only) bottom item
        assert_eq!(
            s.activity_selected_id(),
            Some(&WidgetId::new("panel:settings"))
        );
    }

    #[test]
    fn activity_activate_selected_top_panel_emits_panel_changed() {
        let mut s = shell();
        s.activity_cursor = 1; // panel:search
        let ev = s.activity_activate_selected().expect("should return Some");
        assert_eq!(
            ev,
            AppShellEvent::PanelChanged {
                panel_id: WidgetId::new("panel:search")
            }
        );
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:search")));
    }

    #[test]
    fn activity_activate_selected_bottom_item_emits_bottom_clicked() {
        let mut s = shell();
        s.activity_cursor = 3; // panel:settings
        let ev = s.activity_activate_selected().expect("should return Some");
        assert_eq!(
            ev,
            AppShellEvent::BottomItemClicked {
                id: WidgetId::new("panel:settings")
            }
        );
    }

    #[test]
    fn activity_activate_selected_toggle_hides_sidebar() {
        let mut s = shell();
        // cursor at 0 (panel:explorer), which is already the active panel
        let ev = s.activity_activate_selected().expect("should return Some");
        assert_eq!(ev, AppShellEvent::SidebarHidden);
        assert!(!s.sidebar_visible());
    }

    #[test]
    fn activity_activate_does_not_clear_keyboard_focus() {
        let mut s = shell();
        s.set_activity_keyboard_focused(true);
        s.activity_cursor = 1;
        let _ = s.activity_activate_selected();
        // Consumer decides whether to clear focus; AppShell must not.
        assert!(s.activity_keyboard_focused());
    }

    #[test]
    fn activity_activate_selected_returns_none_when_no_items() {
        let mut s = AppShell::new(vec![], 30.0);
        assert!(s.activity_activate_selected().is_none());
    }

    #[test]
    fn select_next_noop_on_empty_shell() {
        let mut s = AppShell::new(vec![], 30.0);
        s.activity_select_next(); // must not panic
        assert_eq!(s.activity_cursor, 0);
    }

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

    #[test]
    fn show_panel_activates_and_reveals() {
        let mut s = shell();
        s.hide_sidebar();
        s.show_panel(&WidgetId::new("panel:git"));
        assert!(s.sidebar_visible());
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:git")));
    }

    #[test]
    fn toggle_sidebar_flips_visibility() {
        let mut s = shell();
        assert!(s.sidebar_visible());
        s.toggle_sidebar();
        assert!(!s.sidebar_visible());
        s.toggle_sidebar();
        assert!(s.sidebar_visible());
    }

    #[test]
    fn set_sidebar_width_clamps() {
        let mut s = shell();
        s.set_sidebar_width(5.0);
        assert_eq!(s.sidebar_width(), s.min_sidebar_width);
        s.set_sidebar_width(9999.0);
        assert_eq!(s.sidebar_width(), s.max_sidebar_width);
    }

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

    /// The divider must be painted with exactly one `draw_solid_fill` call
    /// over the whole `divider_bounds`, not a loop of individual row calls.
    #[test]
    fn render_paints_the_divider_with_one_solid_fill_call() {
        let s = shell();
        let mut backend = RecordingBackend::new();

        let layout = s.render(&mut backend, area());

        assert!(
            layout.divider_bounds.is_some(),
            "this shell shape should have a divider"
        );
        assert_eq!(
            backend
                .calls
                .iter()
                .filter(|&&c| c == "draw_solid_fill")
                .count(),
            1,
            "divider should be painted with exactly one draw_solid_fill call, got: {:?}",
            backend.calls
        );
    }

    // ── Resize drag ─────────────────────────────────────────────────

    #[test]
    fn resize_drag_updates_width() {
        let mut s = shell();
        let l = s.compute_layout(area(), 1.0, &|h: f32| h.round());
        let div = l.divider_bounds.unwrap();
        let _center = div.x + div.width / 2.0;

        s.drag_offset = Some(0.0);
        let ab_right = l.activity_bar_bounds.x + l.activity_bar_bounds.width;
        let target_width = 40.0;
        let mouse_x = ab_right + target_width;

        let ev = s.handle(
            &UiEvent::MouseMoved {
                position: Point::new(mouse_x, div.y + 1.0),
                buttons: ButtonMask {
                    left: true,
                    middle: false,
                    right: false,
                },
            },
            &RecordingBackend::new(),
            area(),
        );
        assert!(matches!(ev, AppShellEvent::SidebarResized { .. }));
        assert!((s.sidebar_width() - target_width).abs() < 1.0);
    }

    #[test]
    fn resize_drag_clamps_to_min() {
        let mut s = shell();
        s.drag_offset = Some(0.0);
        let ev = s.handle(
            &UiEvent::MouseMoved {
                position: Point::new(s.activity_bar_width + 1.0, 5.0),
                buttons: ButtonMask {
                    left: true,
                    middle: false,
                    right: false,
                },
            },
            &RecordingBackend::new(),
            area(),
        );
        assert!(matches!(ev, AppShellEvent::SidebarResized { .. }));
        assert_eq!(s.sidebar_width(), s.min_sidebar_width);
    }

    #[test]
    fn mouse_up_ends_drag() {
        let mut s = shell();
        s.drag_offset = Some(0.0);
        let ev = s.handle(
            &UiEvent::MouseUp {
                button: MouseButton::Left,
                position: Point::new(50.0, 5.0),
                widget: None,
            },
            &RecordingBackend::new(),
            area(),
        );
        assert_eq!(ev, AppShellEvent::Consumed);
        assert!(s.drag_offset.is_none());
    }

    // ── Dynamic panel registration ──────────────────────────────────

    #[test]
    fn add_panel_appends_and_is_reachable() {
        let mut s = shell();
        assert_eq!(s.panels().len(), 3);
        s.add_panel(PanelDefinition {
            id: WidgetId::new("panel:ext-lua"),
            icon: "L".into(),
            tooltip: "Lua".into(),
            title: "LUA".into(),
        });
        assert_eq!(s.panels().len(), 4);
        s.show_panel(&WidgetId::new("panel:ext-lua"));
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:ext-lua")));
    }

    #[test]
    fn add_panel_rejects_duplicate() {
        let mut s = shell();
        let ok = s.add_panel(PanelDefinition {
            id: WidgetId::new("panel:explorer"),
            icon: "E".into(),
            tooltip: "Dup".into(),
            title: "DUP".into(),
        });
        assert!(!ok);
        assert_eq!(s.panels().len(), 3);
    }

    #[test]
    fn add_panel_rejects_id_collision_with_bottom() {
        let mut s = shell();
        let ok = s.add_panel(PanelDefinition {
            id: WidgetId::new("panel:settings"),
            icon: "*".into(),
            tooltip: "Dup".into(),
            title: "DUP".into(),
        });
        assert!(!ok);
    }

    #[test]
    fn add_panel_to_empty_shell_activates_it() {
        let mut s = AppShell::new(vec![], 30.0);
        assert!(s.active_panel().is_none());
        s.add_panel(PanelDefinition {
            id: WidgetId::new("panel:first"),
            icon: "1".into(),
            tooltip: "First".into(),
            title: "FIRST".into(),
        });
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:first")));
    }

    #[test]
    fn remove_panel_adjusts_active_index() {
        let mut s = shell();
        s.show_panel(&WidgetId::new("panel:git"));
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:git")));
        // Remove "panel:explorer" (index 0) — active was index 2, should shift to 1.
        s.remove_panel(&WidgetId::new("panel:explorer"));
        assert_eq!(s.panels().len(), 2);
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:git")));
    }

    #[test]
    fn remove_active_panel_selects_neighbor() {
        let mut s = shell();
        s.show_panel(&WidgetId::new("panel:search"));
        s.remove_panel(&WidgetId::new("panel:search"));
        assert_eq!(s.panels().len(), 2);
        assert!(s.active_panel().is_some());
    }

    #[test]
    fn remove_last_panel_clears_active() {
        let mut s = AppShell::new(
            vec![PanelDefinition {
                id: WidgetId::new("panel:only"),
                icon: "O".into(),
                tooltip: "Only".into(),
                title: "ONLY".into(),
            }],
            30.0,
        );
        s.remove_panel(&WidgetId::new("panel:only"));
        assert!(s.active_panel().is_none());
        assert!(s.panels().is_empty());
    }

    #[test]
    fn remove_nonexistent_panel_returns_false() {
        let mut s = shell();
        assert!(!s.remove_panel(&WidgetId::new("panel:nope")));
    }

    // ── activity_cursor adjustment on remove ────────────────────────

    #[test]
    fn remove_panel_before_cursor_shifts_cursor_down() {
        // shell() has 3 panels (explorer=0, search=1, git=2) + 1 bottom (settings=3).
        let mut s = shell();
        s.set_activity_keyboard_focused(true);
        s.activity_set_cursor(2); // pointing at git (index 2)
        s.remove_panel(&WidgetId::new("panel:explorer")); // remove index 0
                                                          // cursor was > 0, so should decrement to 1 (still pointing at git)
        assert_eq!(s.activity_cursor, 1);
        assert_eq!(s.activity_selected_id(), Some(&WidgetId::new("panel:git")));
    }

    #[test]
    fn remove_panel_after_cursor_leaves_cursor_unchanged() {
        let mut s = shell();
        s.set_activity_keyboard_focused(true);
        s.activity_set_cursor(0); // pointing at explorer (index 0)
        s.remove_panel(&WidgetId::new("panel:search")); // remove index 1 (after cursor)
        assert_eq!(s.activity_cursor, 0);
        assert_eq!(
            s.activity_selected_id(),
            Some(&WidgetId::new("panel:explorer"))
        );
    }

    #[test]
    fn remove_panel_at_cursor_clamps_cursor() {
        let mut s = shell();
        s.set_activity_keyboard_focused(true);
        s.activity_set_cursor(2); // pointing at git (last panel, index 2)
        s.remove_panel(&WidgetId::new("panel:git")); // remove the cursor item
                                                     // New total = 2 panels + 1 bottom = 3; cursor was 2, clamped to 2.
                                                     // Now index 2 is the bottom item (settings).
        assert_eq!(s.activity_cursor, 2);
        assert_eq!(
            s.activity_selected_id(),
            Some(&WidgetId::new("panel:settings"))
        );
    }

    #[test]
    fn remove_last_panel_while_focused_clears_focus() {
        let mut s = AppShell::new(
            vec![PanelDefinition {
                id: WidgetId::new("panel:only"),
                icon: "O".into(),
                tooltip: "Only".into(),
                title: "ONLY".into(),
            }],
            30.0,
        );
        s.set_activity_keyboard_focused(true);
        s.remove_panel(&WidgetId::new("panel:only"));
        assert!(!s.activity_keyboard_focused());
        assert_eq!(s.activity_cursor, 0);
    }

    #[test]
    fn remove_bottom_item_before_cursor_leaves_cursor_unchanged() {
        // shell(): panels 0,1,2; bottom item at combined index 3.
        // cursor at 3 (settings), remove settings → cursor was at removed item,
        // clamp to new total (3 panels + 0 bottom = 3, but 3 is out of range → 2).
        // This test checks cursor BEFORE the bottom item first.
        let mut s = shell();
        s.set_activity_keyboard_focused(true);
        s.activity_set_cursor(1); // pointing at search (panel index 1)
        s.remove_bottom_item(&WidgetId::new("panel:settings")); // remove bottom at combined 3
        assert_eq!(s.activity_cursor, 1); // cursor was before removed item
        assert_eq!(
            s.activity_selected_id(),
            Some(&WidgetId::new("panel:search"))
        );
    }

    #[test]
    fn remove_bottom_item_at_cursor_clamps_cursor() {
        let mut s = shell();
        s.set_activity_keyboard_focused(true);
        s.activity_set_cursor(3); // pointing at settings (combined index 3)
        s.remove_bottom_item(&WidgetId::new("panel:settings"));
        // New total = 3; cursor was 3, clamped to 2 (last panel).
        assert_eq!(s.activity_cursor, 2);
        assert_eq!(s.activity_selected_id(), Some(&WidgetId::new("panel:git")));
    }

    #[test]
    fn add_bottom_item_shows_in_activity_bar() {
        let mut s = shell();
        s.add_bottom_item(PanelDefinition {
            id: WidgetId::new("panel:debug-console"),
            icon: "D".into(),
            tooltip: "Debug".into(),
            title: "DEBUG".into(),
        });
        let bar = s.build_activity_bar();
        assert_eq!(bar.bottom_items.len(), 2);
    }

    #[test]
    fn remove_bottom_item_works() {
        let mut s = shell();
        assert!(s.remove_bottom_item(&WidgetId::new("panel:settings")));
        let bar = s.build_activity_bar();
        assert!(bar.bottom_items.is_empty());
    }

    #[test]
    fn dynamic_panel_toggle_via_activity_click() {
        let mut s = shell();
        s.add_panel(PanelDefinition {
            id: WidgetId::new("panel:ext"),
            icon: "X".into(),
            tooltip: "Ext".into(),
            title: "EXTENSION".into(),
        });
        let ev = s.handle_activity_click(&WidgetId::new("panel:ext"));
        assert_eq!(
            ev,
            AppShellEvent::PanelChanged {
                panel_id: WidgetId::new("panel:ext")
            }
        );
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:ext")));
        // Toggle off.
        let ev = s.handle_activity_click(&WidgetId::new("panel:ext"));
        assert_eq!(ev, AppShellEvent::SidebarHidden);
    }

    // ── Double-click on the activity bar ──────────────────────────────
    //
    // See the `UiEvent::DoubleClick` arm's comment on `handle` above for
    // why the fold reaches this arm and what it must do.

    /// Real paint → real hit zones → real click, via a `TuiBackend` frame
    /// scope — not a synthetic `Rect`/`Point` — so this exercises the same
    /// cached-hit path a live click goes through.
    #[test]
    #[cfg(feature = "tui")]
    fn double_click_on_activity_bar_same_icon_toggles_like_second_single_click() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut s = shell();
        let a = area();
        let mut backend = crate::tui::TuiBackend::new();
        let mut terminal =
            Terminal::new(TestBackend::new(a.width as u16, a.height as u16)).expect("terminal");
        terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    s.render(b, a);
                });
            })
            .expect("draw");

        let ab = s
            .cached_activity_bar_bounds
            .borrow()
            .expect("render populates the cached activity-bar bounds");
        let explorer_hit = s
            .cached_activity_hits
            .borrow()
            .iter()
            .find(|h| h.id == WidgetId::new("panel:explorer"))
            .cloned()
            .expect("explorer icon hit");
        let p = Point::new(ab.x, ab.y + explorer_hit.y_start);

        // Explorer is already the active panel (default), so a plain
        // MouseDown on its icon toggles the sidebar closed per
        // `handle_activity_click`'s own toggle branch.
        let ev = s.handle(
            &UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: p,
                modifiers: crate::types::Modifiers::default(),
            },
            &backend,
            a,
        );
        assert_eq!(ev, AppShellEvent::SidebarHidden);

        // Re-show it so the next click (the one under test) starts from
        // the same "already active" state a real fast double-click would
        // land in.
        s.show_panel(&WidgetId::new("panel:explorer"));
        assert!(s.sidebar_visible());

        // A DoubleClick landing on the same icon must behave exactly like
        // that second single click — toggle the sidebar closed again —
        // not fall through to `AppShellEvent::Ignored`.
        let ev = s.handle(
            &UiEvent::DoubleClick {
                widget: None,
                position: p,
            },
            &backend,
            a,
        );
        assert_eq!(
            ev,
            AppShellEvent::SidebarHidden,
            "DoubleClick on an already-active activity-bar icon must toggle \
             the sidebar closed, same as a second single click"
        );
    }

    /// Adjacent-icon case: a `DoubleClick` whose position lands on a
    /// *different* icon than the previous click (the TUI adjacent-row
    /// fold, where icon rows sit closer together than the detector's
    /// click radius) must switch to that icon's panel, exactly like a
    /// fresh single click there — not get dropped.
    #[test]
    #[cfg(feature = "tui")]
    fn double_click_on_activity_bar_different_icon_switches_panel() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut s = shell();
        let a = area();
        let mut backend = crate::tui::TuiBackend::new();
        let mut terminal =
            Terminal::new(TestBackend::new(a.width as u16, a.height as u16)).expect("terminal");
        terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    s.render(b, a);
                });
            })
            .expect("draw");

        let ab = s
            .cached_activity_bar_bounds
            .borrow()
            .expect("render populates the cached activity-bar bounds");
        let git_hit = s
            .cached_activity_hits
            .borrow()
            .iter()
            .find(|h| h.id == WidgetId::new("panel:git"))
            .cloned()
            .expect("git icon hit");
        let p = Point::new(ab.x, ab.y + git_hit.y_start);

        let ev = s.handle(
            &UiEvent::DoubleClick {
                widget: None,
                position: p,
            },
            &backend,
            a,
        );
        assert_eq!(
            ev,
            AppShellEvent::PanelChanged {
                panel_id: WidgetId::new("panel:git")
            },
            "DoubleClick on a non-active activity-bar icon must switch to \
             its panel, same as a plain MouseDown there"
        );
        assert_eq!(s.active_panel_id(), Some(&WidgetId::new("panel:git")));
    }

    /// A `DoubleClick` outside the activity-bar band must stay `Ignored`
    /// — this arm must not swallow double-clicks everywhere, only hit-test
    /// the same band the `MouseDown` arm does.
    #[test]
    fn double_click_outside_activity_bar_is_ignored() {
        let mut s = shell();
        let a = area();
        let l = s.layout(a, 1.0);
        let outside = Point::new(
            l.activity_bar_bounds.x + l.activity_bar_bounds.width + 5.0,
            1.0,
        );

        let ev = s.handle(
            &UiEvent::DoubleClick {
                widget: None,
                position: outside,
            },
            &RecordingBackend::new(),
            a,
        );
        assert_eq!(ev, AppShellEvent::Ignored);
    }

    // ── Ignored events ──────────────────────────────────────────────

    #[test]
    fn key_events_are_ignored() {
        let mut s = shell();
        let ev = s.handle(
            &UiEvent::KeyPressed {
                key: crate::Key::Char('q'),
                modifiers: Default::default(),
                repeat: false,
            },
            &RecordingBackend::new(),
            area(),
        );
        assert_eq!(ev, AppShellEvent::Ignored);
    }

    // ── Chrome slot layout ─────────────────────────────────────────

    fn full_chrome_shell() -> AppShell {
        AppShell::new(sample_panels(), 30.0)
            .with_bottom_items(sample_bottom())
            .with_title_bar(1.5)
            .with_bottom_panel(8.0)
            .with_bottom_panel_limits(3.0, 25.0)
            .with_command_line()
            .with_status_bar()
    }

    #[test]
    fn chrome_slots_none_when_not_configured() {
        let s = shell();
        let l = s.layout(area(), 1.0);
        assert!(l.title_bar_bounds.is_none());
        assert!(l.bottom_panel_bounds.is_none());
        assert!(l.command_line_bounds.is_none());
        assert!(l.status_bar_bounds.is_none());
    }

    #[test]
    fn chrome_slots_present_when_configured() {
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        assert!(l.title_bar_bounds.is_some());
        assert!(l.bottom_panel_bounds.is_some());
        assert!(l.command_line_bounds.is_some());
        assert!(l.status_bar_bounds.is_some());
    }

    #[test]
    fn title_bar_at_top_edge() {
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        let tb = l.title_bar_bounds.unwrap();
        assert_eq!(tb.y, 0.0);
        assert_eq!(tb.x, 0.0);
        assert_eq!(tb.width, area().width);
    }

    #[test]
    fn status_bar_at_bottom_edge() {
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        let sb = l.status_bar_bounds.unwrap();
        let sb_bottom = sb.y + sb.height;
        assert!((sb_bottom - area().height).abs() < 0.01);
        assert_eq!(sb.width, area().width);
    }

    #[test]
    fn command_line_above_status_bar() {
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        let cl = l.command_line_bounds.unwrap();
        let sb = l.status_bar_bounds.unwrap();
        assert!((cl.y + cl.height - sb.y).abs() < 0.01);
    }

    #[test]
    fn bottom_panel_above_command_line() {
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        let bp = l.bottom_panel_bounds.unwrap();
        let cl = l.command_line_bounds.unwrap();
        assert!((bp.y + bp.height - cl.y).abs() < 0.01);
    }

    #[test]
    fn activity_bar_runs_full_band_height() {
        // The activity bar (and sidebar) span the full content band down to the
        // command line — the bottom panel docks only under main content, not
        // under the sidebar column, so it does not shorten the activity bar.
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        let tb = l.title_bar_bounds.unwrap();
        let cl = l.command_line_bounds.unwrap();
        let ab_top = l.activity_bar_bounds.y;
        let ab_bottom = l.activity_bar_bounds.y + l.activity_bar_bounds.height;
        assert!((ab_top - (tb.y + tb.height)).abs() < 0.01);
        assert!((ab_bottom - cl.y).abs() < 0.01);
    }

    #[test]
    fn bottom_panel_docks_under_main_only() {
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        let bp = l.bottom_panel_bounds.unwrap();
        let main = l.main_content_bounds;
        // Panel shares the main column's x and width — not the full viewport.
        assert_eq!(bp.x, main.x);
        assert_eq!(bp.width, main.width);
        assert!(bp.width < area().width);
        // Panel sits directly below the (shortened) main content.
        assert!((main.y + main.height - bp.y).abs() < 0.01);
    }

    #[test]
    fn chrome_vertical_no_overlap_no_gap() {
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        let tb = l.title_bar_bounds.unwrap();
        let cl = l.command_line_bounds.unwrap();
        let sb = l.status_bar_bounds.unwrap();
        // The activity-bar column runs full height; the panel lives in the main
        // column, so the left-edge vertical stack excludes it.
        let middle_h = l.activity_bar_bounds.height;
        let total = tb.height + middle_h + cl.height + sb.height;
        assert!(
            (total - area().height).abs() < 1.0,
            "total={total}, expected={}",
            area().height
        );
    }

    #[test]
    fn bottom_panel_hidden_no_bounds() {
        let mut s = full_chrome_shell();
        s.hide_bottom_panel();
        let l = s.layout(area(), 1.0);
        assert!(l.bottom_panel_bounds.is_none());
        assert!(l.command_line_bounds.is_some());
        assert!(l.status_bar_bounds.is_some());
    }

    #[test]
    fn bottom_panel_toggle() {
        let mut s = full_chrome_shell();
        assert!(s.bottom_panel_visible());
        s.toggle_bottom_panel();
        assert!(!s.bottom_panel_visible());
        s.toggle_bottom_panel();
        assert!(s.bottom_panel_visible());
    }

    #[test]
    fn set_bottom_panel_height_clamps() {
        let mut s = full_chrome_shell();
        s.set_bottom_panel_height(1.0);
        assert_eq!(s.bottom_panel_height(), 3.0);
        s.set_bottom_panel_height(999.0);
        assert_eq!(s.bottom_panel_height(), 25.0);
    }

    // ── status_bar_under_main_column ──────────────────────────────

    #[test]
    fn status_bar_under_main_column_is_off_by_default_byte_identical() {
        // With the option left untouched, layout must match the
        // full-width carve exactly, field for field.
        let default_layout = full_chrome_shell().layout(area(), 1.0);
        let explicit_off_layout = full_chrome_shell().layout(area(), 1.0);
        assert_eq!(default_layout, explicit_off_layout);
    }

    #[test]
    fn status_bar_under_main_column_activity_bar_runs_to_area_bottom() {
        let s = full_chrome_shell().with_status_bar_under_main_column();
        let l = s.layout(area(), 1.0);
        let ab_bottom = l.activity_bar_bounds.y + l.activity_bar_bounds.height;
        assert!((ab_bottom - area().height).abs() < 0.01);
        let tb = l.title_bar_bounds.unwrap();
        let header = l.sidebar_header_bounds.unwrap();
        let content = l.sidebar_content_bounds.unwrap();
        let sidebar_bottom = content.y + content.height;
        assert!((header.y - (tb.y + tb.height)).abs() < 0.01);
        assert!((sidebar_bottom - area().height).abs() < 0.01);
    }

    #[test]
    fn status_bar_under_main_column_status_bar_matches_main_column_width() {
        let s = full_chrome_shell().with_status_bar_under_main_column();
        let l = s.layout(area(), 1.0);
        let sb = l.status_bar_bounds.unwrap();
        let main = l.main_content_bounds;
        assert_eq!(sb.x, main.x);
        assert_eq!(sb.width, main.width);
        assert!(sb.width < area().width);
        let sb_bottom = sb.y + sb.height;
        assert!((sb_bottom - area().height).abs() < 0.01);
    }

    #[test]
    fn status_bar_under_main_column_command_line_above_status_bar_in_main_column() {
        let s = full_chrome_shell().with_status_bar_under_main_column();
        let l = s.layout(area(), 1.0);
        let cl = l.command_line_bounds.unwrap();
        let sb = l.status_bar_bounds.unwrap();
        let main = l.main_content_bounds;
        assert_eq!(cl.x, main.x);
        assert_eq!(cl.width, main.width);
        assert!((cl.y + cl.height - sb.y).abs() < 0.01);
    }

    #[test]
    fn status_bar_under_main_column_bottom_panel_above_command_line_in_main_column() {
        let s = full_chrome_shell().with_status_bar_under_main_column();
        let l = s.layout(area(), 1.0);
        let bp = l.bottom_panel_bounds.unwrap();
        let cl = l.command_line_bounds.unwrap();
        let main = l.main_content_bounds;
        assert_eq!(bp.x, main.x);
        assert_eq!(bp.width, main.width);
        assert!((bp.y + bp.height - cl.y).abs() < 0.01);
        assert!((main.y + main.height - bp.y).abs() < 0.01);
    }

    #[test]
    fn bottom_panel_resize_drag() {
        let mut s = full_chrome_shell();
        s.bottom_panel_drag_offset = Some(0.0);
        let ev = s.handle(
            &UiEvent::MouseMoved {
                position: Point::new(40.0, 18.0),
                buttons: ButtonMask {
                    left: true,
                    middle: false,
                    right: false,
                },
            },
            &RecordingBackend::new(),
            area(),
        );
        assert!(matches!(ev, AppShellEvent::BottomPanelResized { .. }));
    }

    // ── Runtime title-bar toggle ────────────────────────────────────

    #[test]
    fn title_bar_visible_reflects_construction_state() {
        assert!(!shell().title_bar_visible());
        assert!(full_chrome_shell().title_bar_visible());
    }

    #[test]
    fn set_title_bar_visible_toggles_at_runtime_without_with_title_bar() {
        let mut s = shell(); // never called with_title_bar()
        assert!(s.layout(area(), 1.0).title_bar_bounds.is_none());

        s.set_title_bar_visible(true);
        assert!(s.title_bar_visible());
        let tb = s
            .layout(area(), 1.0)
            .title_bar_bounds
            .expect("row now reserved");
        // Falls back to the default height (1.5 line-heights) since
        // `with_title_bar` was never called: (1.5 * lh=1.0).round() == 2.0.
        assert_eq!(tb.height, 2.0);

        s.set_title_bar_visible(false);
        assert!(!s.title_bar_visible());
        assert!(s.layout(area(), 1.0).title_bar_bounds.is_none());
    }

    /// Confirm that the activity bar and main content re-derive their
    /// origins from scratch in both states rather than assuming a fixed
    /// offset.
    #[test]
    fn set_title_bar_visible_shifts_activity_bar_and_main_origin_both_ways() {
        let mut s = full_chrome_shell(); // with_title_bar(1.5)
        let l = s.layout(area(), 1.0);
        let tb = l.title_bar_bounds.unwrap();
        assert_eq!(l.activity_bar_bounds.y, tb.y + tb.height);
        assert_eq!(l.main_content_bounds.y, tb.y + tb.height);

        s.set_title_bar_visible(false);
        let l = s.layout(area(), 1.0);
        assert!(l.title_bar_bounds.is_none());
        assert_eq!(l.activity_bar_bounds.y, area().y);
        assert_eq!(l.main_content_bounds.y, area().y);

        // Toggle back on: restores the height configured via
        // `with_title_bar` (2.0, from 1.5 lh) — hiding does not forget it
        // and fall back to some other default.
        s.set_title_bar_visible(true);
        let l = s.layout(area(), 1.0);
        let tb = l.title_bar_bounds.unwrap();
        assert_eq!(tb.height, 2.0);
        assert_eq!(l.activity_bar_bounds.y, tb.y + tb.height);
    }

    #[test]
    fn set_title_bar_visible_false_reclaims_the_row_for_content() {
        let mut s = full_chrome_shell();
        let visible_main_h = s.layout(area(), 1.0).main_content_bounds.height;

        s.set_title_bar_visible(false);
        let hidden_main_h = s.layout(area(), 1.0).main_content_bounds.height;

        assert!(
            hidden_main_h > visible_main_h,
            "hiding the title bar should hand its row back to content: \
             hidden={hidden_main_h}, visible={visible_main_h}"
        );
    }

    // ── Bottom bands ─────────────────────────────────────────────────

    fn band(id: &str, height_lh: f32) -> BottomBand {
        BottomBand::new(WidgetId::new(id), height_lh)
    }

    /// With no bands registered, `bottom_band_bounds()` stays empty and the
    /// existing single-drawer layout is unaffected — the whole point of
    /// making this additive.
    #[test]
    fn no_bands_by_default_layout_unchanged() {
        let s = full_chrome_shell();
        let l = s.layout(area(), 1.0);
        assert!(s.bottom_band_bounds().is_empty());
        assert!(l.bottom_panel_bounds.is_some());
    }

    /// Two visible bands stack bottom-up: band 0 flush against the main
    /// column's bottom edge, band 1 directly above it.
    #[test]
    fn bands_stack_bottom_up_in_list_order() {
        let s = shell().with_bottom_bands(vec![band("band:wildmenu", 1.0), band("band:qf", 3.0)]);
        let l = s.layout(area(), 1.0);
        let bands = s.bottom_band_bounds();
        assert_eq!(bands.len(), 2);

        let (id0, r0) = &bands[0];
        let (id1, r1) = &bands[1];
        assert_eq!(*id0, WidgetId::new("band:wildmenu"));
        assert_eq!(*id1, WidgetId::new("band:qf"));

        // band 0 (wildmenu) sits flush against the shell's bottom edge —
        // `shell()` reserves no status bar / command line, so that edge is
        // the viewport's own bottom edge.
        let main = l.main_content_bounds;
        assert!((r0.y + r0.height - (area().y + area().height)).abs() < 0.01);
        assert_eq!(r0.height, 1.0);
        assert_eq!(r1.height, 3.0);
        // band 1 sits directly above band 0, with no gap or overlap.
        assert!((r1.y + r1.height - r0.y).abs() < 0.01);
        // Both share the main column's x/width, not the full viewport.
        assert_eq!(r0.x, main.x);
        assert_eq!(r0.width, main.width);
        assert_eq!(r1.x, main.x);
        assert_eq!(r1.width, main.width);
    }

    /// A band with `visible: false` occupies no space — presence gating,
    /// not just a height of zero. The remaining bands close the gap.
    #[test]
    fn invisible_band_is_absent_from_layout_and_closes_the_gap() {
        let mut hidden = band("band:qf", 3.0);
        hidden.visible = false;
        let s = shell().with_bottom_bands(vec![band("band:wildmenu", 1.0), hidden]);
        let l = s.layout(area(), 1.0);
        let bands = s.bottom_band_bounds();
        assert_eq!(bands.len(), 1);
        assert_eq!(bands[0].0, WidgetId::new("band:wildmenu"));

        // Main content only lost the visible band's height, not both.
        let baseline = shell().layout(area(), 1.0).main_content_bounds.height;
        assert_eq!(l.main_content_bounds.height, baseline - 1.0);
    }

    /// The legacy single bottom-panel drawer docks directly above every
    /// bottom band — i.e. it behaves as one more, implicit band stacked
    /// on top of the list, not underneath or interleaved with it.
    #[test]
    fn legacy_bottom_panel_docks_above_all_bands() {
        let s = full_chrome_shell().with_bottom_bands(vec![band("band:status", 1.0)]);
        let l = s.layout(area(), 1.0);
        let bp = l
            .bottom_panel_bounds
            .expect("full_chrome_shell has a panel");
        let bands = s.bottom_band_bounds();
        assert_eq!(bands.len(), 1);
        let (_, band_rect) = &bands[0];

        // Band sits below the panel, flush with the main column's original
        // bottom edge; the panel sits directly above the band.
        assert!((bp.y + bp.height - band_rect.y).abs() < 0.01);
    }

    /// `set_bottom_band_visible`/`set_bottom_band_height` mutate the named
    /// band and report `false` for an unknown id, mirroring
    /// `close_tab`/`activate_tab`'s "not found" contract in
    /// `BottomPanelController`.
    #[test]
    fn set_bottom_band_visible_and_height_mutate_by_id() {
        let mut s = shell().with_bottom_bands(vec![band("band:qf", 3.0)]);
        let id = WidgetId::new("band:qf");

        assert!(s.set_bottom_band_visible(&id, false));
        assert!(!s.bottom_band(&id).unwrap().visible);
        s.layout(area(), 1.0);
        assert!(s.bottom_band_bounds().is_empty());

        assert!(s.set_bottom_band_visible(&id, true));
        assert!(s.set_bottom_band_height(&id, 5.0));
        assert_eq!(s.bottom_band(&id).unwrap().height_lh, 5.0);
        s.layout(area(), 1.0);
        assert_eq!(s.bottom_band_bounds()[0].1.height, 5.0);

        let unknown = WidgetId::new("band:nope");
        assert!(!s.set_bottom_band_visible(&unknown, true));
        assert!(!s.set_bottom_band_height(&unknown, 2.0));
    }

    /// A band taller than the available main-content height clamps to
    /// fill it rather than producing a negative-height remainder — same
    /// defensive clamp the legacy single-drawer carve already applies.
    #[test]
    fn oversized_band_clamps_to_available_height() {
        let s = shell().with_bottom_bands(vec![band("band:huge", 9999.0)]);
        let l = s.layout(area(), 1.0);
        let bands = s.bottom_band_bounds();
        assert_eq!(bands.len(), 1);
        assert_eq!(l.main_content_bounds.height, 0.0);
        assert!(bands[0].1.height > 0.0);
    }
}