teksilo-widgets 0.9.1

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

use std::cell::Cell;
use std::rc::Rc;
use teksilo_i18n::LocalizedString;
use teksilo_i18n::lit;

use teksilo_canvas::{Point, Size, SizeProposal};
use teksilo_core::accesskit;
use teksilo_core::event::{Key, Modifiers, ScrollDelta, WidgetEvent};
use teksilo_core::signal::Signal;
use teksilo_core::widget::{LayoutContext, LayoutResponse, Widget};
use teksilo_core::widget_id::WidgetId;
use teksilo_core::widget_tree::WidgetTree;
use teksilo_data::ListModel;

use crate::primitives::{FixedSize, VStack};
use crate::tab_widget::{
    TabBar, TabBarOrientation, TabDelegate, TabHandle, TabId, TabInfo, TabSizing, TabWidget,
};

// ─── shared test helpers ────────────────────────────────────────────

#[derive(Debug)]
struct FixedLeaf(f32, f32);

impl Widget for FixedLeaf {
    fn layout_response(&self, _proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        Size::new(self.0, self.1).into()
    }
}

/// A focusable leaf that publishes its own `WidgetId` on build, so a
/// test can assert focus landed on it.
#[derive(Debug)]
struct FocusableLeaf {
    id_out: Rc<Cell<Option<WidgetId>>>,
}

impl Widget for FocusableLeaf {
    fn build(&mut self, ctx: &mut teksilo_core::build_context::BuildContext) -> Vec<WidgetId> {
        self.id_out.set(Some(ctx.self_id()));
        ctx.apply_self_handlers(teksilo_core::widget_builder::HandlerSet::new().focusable(true));
        Vec::new()
    }

    fn layout_response(&self, _proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        Size::new(100.0, 40.0).into()
    }
}

#[derive(Debug)]
struct BuildCountingLeaf {
    build_count: Rc<Cell<usize>>,
}

impl Widget for BuildCountingLeaf {
    fn build(&mut self, _ctx: &mut teksilo_core::build_context::BuildContext) -> Vec<WidgetId> {
        self.build_count.set(self.build_count.get() + 1);
        Vec::new()
    }

    fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        proposal.resolve(120.0, 48.0).into()
    }
}

/// The bar's content row/column. `TabBar`'s direct child is the
/// `TabStyle::make_bar` chrome container — `[backdrop?, chrome
/// painter, content]` — so the content (the `row_outer` HStack /
/// VStack) is the container's last child.
fn bar_content(tree: &WidgetTree, bar_id: WidgetId) -> WidgetId {
    let chrome = tree.child_widget(bar_id, 0);
    *tree
        .children(chrome)
        .last()
        .expect("bar chrome has a content child")
}

/// Walk a stand-alone `TabBar` (no `TabWidget` wrapper) to the
/// `TabHeaderRow` containing the unpinned headers.
fn data_source_header_row(tree: &WidgetTree, bar_id: WidgetId) -> WidgetId {
    let row_outer = bar_content(tree, bar_id);
    let expand = expand_in_row_outer(tree, row_outer);
    let scroll = tree.child_widget(expand, 0);
    tree.child_widget(scroll, 0)
}

/// Locate the `Expand` child of `row_outer` regardless of whether
/// scroll arrows / overflow dropdown / pinned strip are present —
/// signature: a child whose only descendant is a `ScrollView`.
fn expand_in_row_outer(tree: &WidgetTree, row_outer: WidgetId) -> WidgetId {
    for child in tree.children(row_outer) {
        if tree.children(child).len() == 1 {
            let scroll = tree.child_widget(child, 0);
            let info = tree.accessibility_node(scroll);
            if info.role() == accesskit::Role::ScrollView {
                return child;
            }
        }
    }
    panic!("no Expand[ScrollArea] child found in row_outer");
}

fn label(s: &str) -> LocalizedString {
    lit!(s)
}

// ─── TabWidget — static-only construction ───────────────────────────

#[test]
fn icon_only_tab_centers_its_icon() {
    use crate::IconWidget;
    use crate::tab_widget::TabDisplayMode;

    fn first_tab(tree: &WidgetTree, id: WidgetId) -> Option<WidgetId> {
        if tree.accessibility_node(id).role() == accesskit::Role::Tab
            && tree.bounds(id).height > 0.0
        {
            return Some(id);
        }
        tree.children(id).iter().find_map(|&c| first_tab(tree, c))
    }
    // Smallest roughly-square leaf in the subtree — the icon glyph (background
    // / indicator rects are full-width, the icon is a small square).
    fn icon_leaf(tree: &WidgetTree, id: WidgetId, best: &mut Option<teksilo_canvas::Rect>) {
        let kids = tree.children(id);
        if kids.is_empty() {
            let b = tree.bounds(id);
            let squarish = (b.width - b.height).abs() < 6.0;
            if b.width > 4.0 && b.width < 40.0 && squarish {
                if best.is_none_or(|cur| b.width < cur.width) {
                    *best = Some(b);
                }
            }
        }
        for &c in kids.iter() {
            icon_leaf(tree, c, best);
        }
    }

    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    // Content-sized (Independent, the dock's mode): the tab sizes to icon +
    // padding, so the lone icon must (a) still render and (b) sit centred.
    let root = tree.add(
        TabWidget::new(selected)
            .tab_display(TabDisplayMode::Icon)
            .tab_sizing(TabSizing::Independent)
            .min_tab_width(20.0)
            .static_tab(
                TabInfo::new()
                    .title(label("Alpha"))
                    .icon(|| IconWidget::checkmark(16.0)),
                FixedLeaf(120.0, 48.0),
            )
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    let tab = first_tab(&tree, root).expect("an icon-only tab renders");
    let tb = tree.bounds(tab);
    // The icon must still be laid out with real bounds (it must not vanish).
    let mut icon = None;
    icon_leaf(&tree, tab, &mut icon);
    let icon = icon.expect("the icon glyph still renders in icon-only mode");
    assert!(
        icon.width > 4.0 && icon.height > 4.0,
        "the icon has real bounds ({}×{})",
        icon.width,
        icon.height
    );
    let icon_cx = icon.x + icon.width / 2.0;
    let tab_cx = tb.x + tb.width / 2.0;
    assert!(
        (icon_cx - tab_cx).abs() < 3.0,
        "the lone icon is centred: icon_cx={icon_cx}, tab_cx={tab_cx}"
    );
}

#[test]
fn tab_display_flips_icon_text_live() {
    use crate::IconWidget;
    use crate::tab_widget::TabDisplayMode;

    fn tab_named(tree: &WidgetTree, id: WidgetId, name: &str) -> Option<WidgetId> {
        let n = tree.accessibility_node(id);
        if n.role() == accesskit::Role::Tab
            && n.name() == Some(name)
            && tree.bounds(id).height > 0.0
        {
            return Some(id);
        }
        tree.children(id)
            .iter()
            .find_map(|&c| tab_named(tree, c, name))
    }

    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mode = Signal::new(TabDisplayMode::Text);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let root = tree.add(
        TabWidget::new(selected.clone())
            .tab_display(mode.clone())
            .tab_sizing(TabSizing::Independent)
            // A compact floor so an icon-only tab can shrink below the default
            // editor-tab minimum (the bar's row clamps to `min_tab_width`).
            .min_tab_width(20.0)
            .static_tab(
                TabInfo::new()
                    .title(label("Alpha"))
                    .icon(|| IconWidget::checkmark(16.0)),
                FixedLeaf(120.0, 48.0),
            )
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    let text_tab = tab_named(&tree, root, "Alpha").expect("text mode names the tab 'Alpha'");
    let w_text = tree.bounds(text_tab).width;

    // Flipping the bound signal must rebuild the bar live into icon-only: the
    // tab shrinks to its icon, but its *accessible name* stays "Alpha" (the
    // title moved to the tooltip — a screen reader must still identify it).
    mode.set(TabDisplayMode::Icon);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    let icon_tab = tab_named(&tree, root, "Alpha")
        .expect("icon mode keeps the accessible name 'Alpha' (a11y, not a visual)");
    let w_icon = tree.bounds(icon_tab).width;
    assert!(
        w_icon < w_text,
        "flipping tab_display to Icon shrinks the tab to its icon live \
         ({w_icon} < {w_text})"
    );
}

#[test]
fn static_tab_initial_selection_lands_on_first_tab() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // After build, selected_id has been auto-populated by the
    // index → id sync effect (initial_idx = 0, mapped to the first
    // static tab's TabId).
    assert!(
        selected.get().is_some(),
        "static tabs should auto-populate selection from index 0"
    );
}

#[test]
fn static_tabs_dormancy_preserved_across_switches() {
    // Use a stable TabId per static tab so we can flip selection
    // by id from outside without depending on index lookups.
    let id_first = TabId::fresh();
    let id_second = TabId::fresh();
    let selected: Signal<Option<TabId>> = Signal::new(Some(id_first));

    let first_builds = Rc::new(Cell::new(0));
    let second_builds = Rc::new(Cell::new(0));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab_with_id(
                id_first,
                TabInfo::new().title(label("First")),
                BuildCountingLeaf {
                    build_count: first_builds.clone(),
                },
            )
            .static_tab_with_id(
                id_second,
                TabInfo::new().title(label("Second")),
                BuildCountingLeaf {
                    build_count: second_builds.clone(),
                },
            )
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // Both tabs build once on initial layout (Switcher is eager;
    // dormant means hidden, not unbuilt).
    assert_eq!(first_builds.get(), 1);
    assert_eq!(second_builds.get(), 1);

    // Flip to second tab. No model mutation, but visibility flips
    // and the dormant pane stays dormant — neither pane should
    // build a second time.
    selected.set(Some(id_second));
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(first_builds.get(), 1, "first pane should not rebuild");
    assert_eq!(second_builds.get(), 1, "second pane should not rebuild");

    // Flip back. Same expectation.
    selected.set(Some(id_first));
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(first_builds.get(), 1);
    assert_eq!(second_builds.get(), 1);
}

#[test]
fn static_tab_pane_survives_dynamic_model_push() {
    // Regression: before pane memoization, a dynamic_model mutation
    // forced TabWidget to rebuild and substituted Spacer placeholders
    // for static-tab content. With memoization the static pane's
    // build counter must NOT increment on subsequent rebuilds.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let static_builds = Rc::new(Cell::new(0));
    let model: ListModel<TabHandle> = ListModel::new();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab(
                TabInfo::new().title(label("Welcome")),
                BuildCountingLeaf {
                    build_count: static_builds.clone(),
                },
            )
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(static_builds.get(), 1, "static pane builds once");

    // Push a dynamic tab — TabWidget rebuilds, Switcher recomposes,
    // but the static pane WidgetId is memoized so the inner widget
    // is NOT rebuilt.
    model.push(TabHandle::dynamic(
        TabId::fresh(),
        "doc",
        TabInfo::new().title(label("Doc1")),
        (),
    ));
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(
        static_builds.get(),
        1,
        "static pane must NOT rebuild on dynamic-model mutation"
    );

    // Removing the dynamic tab triggers another rebuild. Same.
    let _ = model.remove(0);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(static_builds.get(), 1);
}

#[test]
fn static_tab_id_survives_rebuild() {
    // The DSL element-valued slot path: static_tab_id pre-registers
    // the content in the arena, then memoization keeps the pane
    // referring to that id across rebuilds.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model: ListModel<TabHandle> = ListModel::new();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let content_id = tree.add(FixedLeaf(120.0, 48.0));
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab_id(TabInfo::new().title(label("Pre")), content_id)
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // The pre-registered widget is reachable via the AT tree.
    let update = tree.sync_accessibility();
    let panel_count_before = update
        .nodes
        .iter()
        .filter(|(_, n)| n.role() == accesskit::Role::TabPanel)
        .count();
    assert_eq!(panel_count_before, 1, "exactly one tab panel");

    // Trigger a rebuild via dynamic_model.push.
    model.push(TabHandle::dynamic(
        TabId::fresh(),
        "doc",
        TabInfo::new().title(label("Doc")),
        (),
    ));
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // After the rebuild, the static-tab panel must STILL exist —
    // before memoization this would have been replaced by a Spacer
    // (no TabPanel role). Only ONE panel is visible at a time (the
    // active one), so we count == 1 and verify it's the static.
    let update = tree.sync_accessibility();
    let panels: Vec<String> = update
        .nodes
        .iter()
        .filter(|(_, n)| n.role() == accesskit::Role::TabPanel)
        .map(|(_, n)| n.label().unwrap_or("").to_string())
        .collect();
    assert_eq!(panels.len(), 1, "one visible panel at a time");
    assert_eq!(
        panels[0], "Pre",
        "static panel must survive rebuild — was replaced before memoization"
    );

    // Now flip selection to the dynamic tab; the dynamic panel
    // should appear (proving it was created and dormant, not lost).
    if let Some(dyn_id) = (0..model.len())
        .filter_map(|i| model.with_item(i, |h| h.id))
        .next()
    {
        selected.set(Some(dyn_id));
        tree.layout(SizeProposal::exact(640.0, 320.0));
        let update = tree.sync_accessibility();
        let panels: Vec<String> = update
            .nodes
            .iter()
            .filter(|(_, n)| n.role() == accesskit::Role::TabPanel)
            .map(|(_, n)| n.label().unwrap_or("").to_string())
            .collect();
        assert_eq!(panels.len(), 1);
        assert_eq!(panels[0], "Doc", "dynamic panel reachable after activation");
    }
}

#[test]
fn bar_trailing_slot_survives_rebuild() {
    // Regression: the bar slot was consumed on first build via
    // PendingChild::Deferred and lost on rebuild. With BarSlot
    // memoization the slot's WidgetId must remain reachable.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model: ListModel<TabHandle> = ListModel::new();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());

    #[derive(Debug)]
    struct MarkerLeaf;
    impl Widget for MarkerLeaf {
        fn layout_response(&self, _proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
            Size::new(48.0, 24.0).into()
        }
        fn accessibility(&self, b: &mut teksilo_core::accessibility::AccessNodeBuilder) {
            b.set_role(accesskit::Role::Button);
            b.set_name("MARKER_SLOT");
        }
    }

    tree.add(
        TabWidget::new(selected.clone())
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .bar_trailing_slot(MarkerLeaf)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    let marker_present = |tree: &mut WidgetTree| -> bool {
        let update = tree.sync_accessibility();
        update
            .nodes
            .iter()
            .any(|(_, n)| n.role() == accesskit::Role::Button && n.label() == Some("MARKER_SLOT"))
    };
    assert!(
        marker_present(&mut tree),
        "marker slot present after first build"
    );

    // Force a rebuild via dynamic_model push.
    model.push(TabHandle::dynamic(
        TabId::fresh(),
        "doc",
        TabInfo::new().title(label("Doc")),
        (),
    ));
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        marker_present(&mut tree),
        "marker slot must still be present after rebuild"
    );
}

#[test]
fn dynamic_tab_pane_state_survives_reorder() {
    // Heavy state lives in the handle's payload (not the widget),
    // and the pane WidgetId is memoized by TabId — so a tab that
    // moves to a different position keeps the SAME pane widget.
    // Verify by tracking pane build counts: a memoized pane builds
    // exactly once, regardless of reorders.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let id_c = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![
        TabHandle::dynamic(id_a, "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(id_b, "doc", TabInfo::new().title(label("B")), ()),
        TabHandle::dynamic(id_c, "doc", TabInfo::new().title(label("C")), ()),
    ]);

    // Track build count per TabId via a shared map. The factory is
    // called once per (id, first build); after memoization, NEVER
    // again. We verify the factory call count, NOT the pane's
    // internal build counter.
    let factory_calls: Rc<Cell<usize>> = Rc::new(Cell::new(0));
    let fc = factory_calls.clone();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", move |_h, _s| {
                fc.set(fc.get() + 1);
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(factory_calls.get(), 3, "three factory calls for three tabs");

    // Move A to the end → [B, C, A].
    model.move_item(0, 2);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(
        factory_calls.get(),
        3,
        "reorder must NOT recreate dynamic panes (state would be lost)"
    );

    // Insert a fresh tab. Only the new one calls the factory.
    let id_d = TabId::fresh();
    model.push(TabHandle::dynamic(
        id_d,
        "doc",
        TabInfo::new().title(label("D")),
        (),
    ));
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(factory_calls.get(), 4, "exactly one new factory call");
}

#[test]
fn reorder_preserves_selected_id() {
    // Regression: the bar's reorder wrapper used to call
    // `selected.set(adjusted_index)` *before* `move_item`, which
    // fired the bar's index → id effect against the pre-move
    // `index_to_id` and stamped the wrong TabId into `selected_id`.
    // After the rebuild the visually-selected tab and the visible
    // content pane fell out of sync. Verify a reorder (`move_item`)
    // never changes which TabId is active.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let id_c = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![
        TabHandle::dynamic(id_a, "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(id_b, "doc", TabInfo::new().title(label("B")), ()),
        TabHandle::dynamic(id_c, "doc", TabInfo::new().title(label("C")), ()),
    ]);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .reorderable(true)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // Activate B (the middle tab).
    selected.set(Some(id_b));
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(selected.get(), Some(id_b));

    // Move B from index 1 to index 2 → [A, C, B]. The selected
    // *id* must still be B (its position in the model changed but
    // its identity is stable).
    model.move_item(1, 2);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(
        selected.get(),
        Some(id_b),
        "reorder must not change which tab id is active"
    );

    // Move A (now at 0) to the end → [C, B, A]. Still B selected.
    model.move_item(0, 2);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(selected.get(), Some(id_b));

    // Move B (now at 1) to position 0 — the active tab itself
    // moves; its id stays.
    model.move_item(1, 0);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(selected.get(), Some(id_b));
}

#[test]
fn dynamic_pane_dropped_when_tab_removed() {
    // After model.remove, the removed tab's pane id should be
    // pruned from the memo so we don't leak references.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![
        TabHandle::dynamic(id_a, "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(id_b, "doc", TabInfo::new().title(label("B")), ()),
    ]);

    let factory_calls: Rc<Cell<usize>> = Rc::new(Cell::new(0));
    let fc = factory_calls.clone();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", move |_h, _s| {
                fc.set(fc.get() + 1);
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(factory_calls.get(), 2);

    // Remove A. Then re-push a tab with the same id (apps reuse
    // ids on session restore). The factory should fire AGAIN for
    // the resurrected id — proving the prior memo entry was
    // pruned, not retained.
    let _ = model.remove(0);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(factory_calls.get(), 2);

    model.push(TabHandle::dynamic(
        id_a,
        "doc",
        TabInfo::new().title(label("A2")),
        (),
    ));
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(
        factory_calls.get(),
        3,
        "factory must fire again for a re-pushed id (memo entry was pruned)"
    );
}

#[test]
fn dynamic_tab_removal_reaps_pane_no_active_leak() {
    // The reconcile fix at the framework level: TabWidget is
    // `preserves_children_on_rebuild`, so before the fix a removed tab's pane
    // stayed in the arena AND active (a ghost), growing the active-widget set
    // on every add/remove cycle. Cycling add→remove must leave the active
    // count flat.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model: ListModel<TabHandle> = ListModel::new();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    let baseline = tree.active_widget_count();

    for _ in 0..5 {
        model.push(TabHandle::dynamic(
            TabId::fresh(),
            "doc",
            TabInfo::new().title(label("Tmp")),
            (),
        ));
        tree.layout(SizeProposal::exact(640.0, 320.0));
        let _ = model.remove(model.len() - 1);
        tree.layout(SizeProposal::exact(640.0, 320.0));
    }

    assert_eq!(
        tree.active_widget_count(),
        baseline,
        "each removed tab's pane must be reaped — no stranded active ghosts"
    );
}

#[test]
fn locale_change_retitles_live_tabs() {
    // Regression for the eager-resolution bug: with delegate-based
    // label resolution, live tabs must retitle when the locale
    // changes — without recreating the widget. The test installs a
    // process-thread-local i18n manager, switches it, and verifies
    // the AT label changes accordingly.
    use teksilo_i18n::{
        I18nConfig, I18nManager, LanguageIdentifier, LocalizedString, localized, resolve_message,
        thread_local::{clear, install},
    };

    clear();
    let cfg = I18nConfig::test_only("en-US", &[("tab-greeting", "Hello")])
        .with_locale("fr-FR", &[("tab-greeting", "Bonjour")]);
    let mgr = I18nManager::from_config(&cfg);
    install(mgr.clone());

    let selected: Signal<Option<TabId>> = Signal::new(None);
    let title: LocalizedString = localized(|| resolve_message("tab-greeting", &[]));

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab(TabInfo::new().title(title), FixedLeaf(120.0, 48.0))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    let label_of_tab = |tree: &mut WidgetTree| -> String {
        let update = tree.sync_accessibility();
        let tab = update
            .nodes
            .iter()
            .find(|(_, n)| n.role() == accesskit::Role::Tab)
            .expect("at least one tab in tree");
        tab.1.label().unwrap_or("").to_string()
    };
    assert_eq!(label_of_tab(&mut tree), "Hello");

    let fr: LanguageIdentifier = "fr-FR".parse().unwrap();
    mgr.set_locale(fr);
    // The widget tree also needs to be told the locale changed so
    // it marks the accessibility cache dirty for re-emission.
    tree.set_locale("fr-FR".to_string());
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(
        label_of_tab(&mut tree),
        "Bonjour",
        "tab label must retitle on locale change"
    );
    clear();
}

#[test]
#[should_panic(expected = "is reserved by the framework for static tabs")]
fn dynamic_tab_kind_must_not_be_static_kind_at_registration() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let _ = TabWidget::new(selected).dynamic_tab::<()>(crate::tab_widget::STATIC_KIND, |_h, _s| {
        Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
    });
}

#[test]
#[should_panic(expected = "is reserved for static tabs")]
fn tab_handle_dynamic_rejects_static_kind() {
    // Construction-side defense — even if the registration check
    // is bypassed, building a TabHandle with the reserved kind must
    // also fail.
    let _ = TabHandle::dynamic(
        TabId::fresh(),
        crate::tab_widget::STATIC_KIND,
        TabInfo::new().title(label("oops")),
        (),
    );
}

#[test]
fn cross_boundary_default_reorder_silently_dropped() {
    // The default on_reorder rejects moves that cross the
    // static / dynamic boundary, since static tabs are pinned in
    // place. The model is unchanged after such a drop.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_static = TabId::fresh();
    let id_dyn_a = TabId::fresh();
    let id_dyn_b = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![
        TabHandle::dynamic(id_dyn_a, "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(id_dyn_b, "doc", TabInfo::new().title(label("B")), ()),
    ]);
    let initial_ids: Vec<TabId> = (0..model.len())
        .filter_map(|i| model.with_item(i, |h| h.id))
        .collect();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(
        TabWidget::new(selected)
            .static_tab_with_id(
                id_static,
                TabInfo::new().title(label("S")),
                FixedLeaf(120.0, 48.0),
            )
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .reorderable(true)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // Synthesize a cross-boundary reorder by directly invoking the
    // bar's on_reorder dispatcher via its index. We don't have a
    // public hook to call the bar's callback from outside, but we
    // can verify the *outcome*: simulate the reorder via a
    // `move_item` fired from the bar layer would, by definition,
    // hit the default handler. Drag-DnD path is exercised in bar
    // tests; here we just verify the model's dynamic region is
    // unchanged when nothing in our own code moves it. End-state
    // check: model still in original order.
    let _ = widget_id;
    let after_ids: Vec<TabId> = (0..model.len())
        .filter_map(|i| model.with_item(i, |h| h.id))
        .collect();
    assert_eq!(after_ids, initial_ids, "model unchanged");
}

#[test]
fn on_pin_toggle_handler_fires_with_tab_id() {
    // Wire a pin-toggle callback and verify it fires with the
    // correct TabId when the bar reports a pin/unpin from a
    // cross-boundary drag. We can't drive the bar's DnD pipeline
    // from a unit test directly (it requires a dragged-item
    // handle), so we verify the wiring at the API level: the
    // setter installs a handler, and the build path translates
    // index → id correctly when the bar fires.
    //
    // This test verifies that the closure is wired up; bar-level
    // DnD drive tests live alongside bar.rs.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![TabHandle::dynamic(
        id_a,
        "doc",
        TabInfo::new().title(label("A")),
        (),
    )]);

    let captured: Rc<Cell<Option<(TabId, bool)>>> = Rc::new(Cell::new(None));
    let cap = captured.clone();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(
        TabWidget::new(selected)
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model)
            .on_pin_toggle(move |id, pinned, _ctx| cap.set(Some((id, pinned))))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // The wiring is in place; bar-level DnD pipelines drive the
    // actual fire. This test just establishes that the API path
    // doesn't panic and that a TabWidget with on_pin_toggle
    // installed reaches a stable state. Setting `captured` is
    // exercised in bar-level DnD tests.
    let _ = widget_id;
    assert_eq!(
        captured.get(),
        None,
        "no drag yet — handler should not have fired"
    );
}

#[test]
fn empty_model_after_close_drains_selection() {
    // Close the only tab → selection drains to None.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![TabHandle::dynamic(
        id_a,
        "doc",
        TabInfo::new().title(label("Only")).closable(true),
        (),
    )]);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(selected.get(), Some(id_a));

    // Close the tab via the close button (hover-only — the helper
    // simulates the hover before locating + clicking).
    let bar = bar_of(&tree, widget_id);
    let header_row = data_source_header_row(&tree, bar);
    let headers = tree.children(header_row);
    hover_and_click_close(&mut tree, headers[0]);
    tree.layout(SizeProposal::exact(640.0, 320.0));

    assert_eq!(model.len(), 0);
    assert_eq!(selected.get(), None, "empty model drains selection to None");
}

#[test]
fn static_tab_disabled_skipped_by_arrow_keys() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .static_tab(
                TabInfo::new().title(label("Locked")).enabled(false),
                FixedLeaf(120.0, 48.0),
            )
            .static_tab(TabInfo::new().title(label("C")), FixedLeaf(120.0, 48.0))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // Tab into the strip, then ArrowRight: should jump from
    // index 0 ("A") past the disabled "Locked" to index 2 ("C").
    tree.press_key(Key::Tab, Modifiers::NONE);
    tree.press_key(Key::ArrowRight, Modifiers::NONE);

    // The active id should now correspond to the third static tab.
    // We can't get its TabId from outside the widget directly;
    // verify the AT tree reports the right Tab as selected.
    let update = tree.sync_accessibility();
    let tab_nodes: Vec<_> = update
        .nodes
        .iter()
        .filter(|(_, n)| n.role() == accesskit::Role::Tab)
        .collect();
    assert_eq!(tab_nodes.len(), 3);
    let selected_count = tab_nodes
        .iter()
        .filter(|(_, n)| n.is_selected().unwrap_or(false))
        .count();
    assert_eq!(
        selected_count, 1,
        "exactly one tab should be marked selected after keyboard nav"
    );
}

/// Both `Enter` and `Space` activate the focused tab AND dive focus into
/// its content panel — the desktop tab-control convention (Space/Enter
/// keyboard parity for invocable controls). Parameterized so each key is
/// asserted identically.
fn assert_activation_key_dives_into_panel(activation: Key) {
    let leaf_id: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab(
                TabInfo::new().title(label("A")),
                FocusableLeaf {
                    id_out: leaf_id.clone(),
                },
            )
            .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // Tab into the strip — focus lands on the selected (index 0) header.
    tree.press_key(Key::Tab, Modifiers::NONE);
    let header = tree.focused().expect("Tab should focus a tab header");
    let leaf = leaf_id.get().expect("panel content should have built");
    assert_ne!(
        header, leaf,
        "focus should start on the header, not the panel"
    );

    // The activation key dives focus into the selected tab's content panel.
    tree.press_key(activation, Modifiers::NONE);
    assert_eq!(
        tree.focused(),
        Some(leaf),
        "{activation:?} on a focused tab header should move focus into the panel's first control"
    );

    // The focus must survive the next build/layout pass — activation sets
    // the (already-selected) tab, and a rebuild must not yank focus back
    // to the header.
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(
        tree.focused(),
        Some(leaf),
        "focus should remain inside the panel after a rebuild/layout pass"
    );
}

#[test]
fn enter_on_tab_header_moves_focus_into_panel_content() {
    assert_activation_key_dives_into_panel(Key::Enter);
}

#[test]
fn space_on_tab_header_moves_focus_into_panel_content() {
    assert_activation_key_dives_into_panel(Key::Space);
}

/// A content-less tab (no focusable descendant, no `focusable_panel`
/// opt-in) must NOT trap focus on the non-interactive panel — focus stays
/// on the header for both activation keys.
fn assert_activation_key_keeps_focus_on_contentless_header(activation: Key) {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    tree.press_key(Key::Tab, Modifiers::NONE);
    let header = tree.focused().expect("Tab should focus a tab header");

    tree.press_key(activation, Modifiers::NONE);
    assert_eq!(
        tree.focused(),
        Some(header),
        "{activation:?} on a tab with no focusable panel content should leave focus on the header"
    );
}

#[test]
fn enter_on_contentless_tab_keeps_focus_on_header() {
    assert_activation_key_keeps_focus_on_contentless_header(Key::Enter);
}

#[test]
fn space_on_contentless_tab_keeps_focus_on_header() {
    assert_activation_key_keeps_focus_on_contentless_header(Key::Space);
}

// ─── TabWidget — dynamic registration + ListModel mutations ─────────

#[derive(Debug, Clone)]
struct DocState {
    initial_text: String,
}

#[derive(Debug, Clone)]
struct ImageState {
    url: String,
}

fn new_dynamic_handle<S: 'static>(kind: &'static str, title: &str, state: S) -> TabHandle {
    TabHandle::dynamic(
        TabId::fresh(),
        kind,
        TabInfo::new().title(label(title)).closable(true),
        state,
    )
}

#[test]
fn dynamic_tab_factory_dispatches_on_kind() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![
        new_dynamic_handle(
            "plain-text-doc",
            "Notes",
            DocState {
                initial_text: "hi".to_string(),
            },
        ),
        new_dynamic_handle(
            "image",
            "Logo",
            ImageState {
                url: "logo.png".to_string(),
            },
        ),
    ]);

    let doc_calls = Rc::new(Cell::new(0));
    let img_calls = Rc::new(Cell::new(0));
    let dc = doc_calls.clone();
    let ic = img_calls.clone();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected)
            .dynamic_tab::<DocState>("plain-text-doc", move |_h, _s| {
                dc.set(dc.get() + 1);
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_tab::<ImageState>("image", move |_h, _s| {
                ic.set(ic.get() + 1);
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    assert_eq!(doc_calls.get(), 1, "doc factory should be called once");
    assert_eq!(img_calls.get(), 1, "image factory should be called once");
}

#[test]
fn dynamic_model_push_triggers_rebuild_with_new_tab() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model: ListModel<TabHandle> = ListModel::new();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<DocState>("plain-text-doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // Initially zero tabs — selection stays None.
    assert_eq!(selected.get(), None);

    // Push a new tab; widget should rebuild and adopt selection.
    let new_id = TabId::fresh();
    model.push(TabHandle::dynamic(
        new_id,
        "plain-text-doc",
        TabInfo::new().title(label("New")).closable(true),
        DocState {
            initial_text: "x".into(),
        },
    ));
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // After the rebuild, the index→id sync effect should have set
    // selected_id to the new tab (since selected_index_internal
    // defaults to 0 and there's now exactly one tab).
    assert_eq!(selected.get(), Some(new_id));
}

#[test]
fn dynamic_default_close_removes_from_model() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![
        TabHandle::dynamic(
            id_a,
            "doc",
            TabInfo::new().title(label("A")).closable(true),
            (),
        ),
        TabHandle::dynamic(
            id_b,
            "doc",
            TabInfo::new().title(label("B")).closable(true),
            (),
        ),
    ]);
    let model_for_assert = model.clone();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // Walk to the close button on tab A and click it (the close
    // button is hover-only, so we hover the header first).
    let bar = bar_of(&tree, widget_id);
    let header_row = data_source_header_row(&tree, bar);
    let headers = tree.children(header_row);
    let header_a = headers[0];
    hover_and_click_close(&mut tree, header_a);
    tree.layout(SizeProposal::exact(640.0, 320.0));

    assert_eq!(
        model_for_assert.len(),
        1,
        "tab A should be removed by default close"
    );
    // Selection moved to the surviving tab.
    assert_eq!(selected.get(), Some(id_b));
}

#[test]
fn primary_click_activates_tab_secondary_does_not() {
    use teksilo_canvas::Point;
    use teksilo_core::event::PointerButton;

    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(
        TabWidget::new(selected.clone())
            .static_tab_with_id(
                id_a,
                TabInfo::new().title(label("A")),
                FixedLeaf(120.0, 48.0),
            )
            .static_tab_with_id(
                id_b,
                TabInfo::new().title(label("B")),
                FixedLeaf(120.0, 48.0),
            )
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // Initial selection lands on A (first static tab).
    assert_eq!(selected.get(), Some(id_a));

    let bar = bar_of(&tree, widget_id);
    let header_row = data_source_header_row(&tree, bar);
    let headers = tree.children(header_row);
    let center_b: Point = tree.bounds(headers[1]).center();

    // Right-click on tab B with no context-menu factory installed:
    // the framework's secondary-click path falls through to the
    // widget, but the auto-wired `TapRecognizer` defaults to
    // `ButtonMask::PRIMARY` and silently ignores non-Primary
    // presses, so no Tap is recognised. Selection must not move.
    tree.pointer_down_button(center_b, PointerButton::Secondary);
    tree.pointer_up_button(center_b, PointerButton::Secondary);
    assert_eq!(
        selected.get(),
        Some(id_a),
        "right-click must not activate a tab"
    );

    // Middle-click likewise must not activate (the close handler is
    // independent and doesn't fire here because the tab isn't
    // closable).
    tree.pointer_down_button(center_b, PointerButton::Middle);
    tree.pointer_up_button(center_b, PointerButton::Middle);
    assert_eq!(
        selected.get(),
        Some(id_a),
        "middle-click must not activate a tab"
    );

    // Primary click does activate.
    tree.pointer_down_button(center_b, PointerButton::Primary);
    tree.pointer_up_button(center_b, PointerButton::Primary);
    assert_eq!(
        selected.get(),
        Some(id_b),
        "primary-click must activate the clicked tab"
    );
}

#[test]
fn explicit_on_close_receives_tab_id() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![
        TabHandle::dynamic(
            id_a,
            "doc",
            TabInfo::new().title(label("A")).closable(true),
            (),
        ),
        TabHandle::dynamic(
            id_b,
            "doc",
            TabInfo::new().title(label("B")).closable(true),
            (),
        ),
    ]);

    let captured: Rc<Cell<Option<TabId>>> = Rc::new(Cell::new(None));
    let cap = captured.clone();

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model)
            .on_close(move |id, _ctx| cap.set(Some(id)))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    let bar = bar_of(&tree, widget_id);
    let header_row = data_source_header_row(&tree, bar);
    let headers = tree.children(header_row);
    hover_and_click_close(&mut tree, headers[1]);

    assert_eq!(
        captured.get(),
        Some(id_b),
        "explicit on_close should fire with the closed tab's id"
    );
}

#[test]
#[should_panic(expected = "tab kind 'image' was registered for")]
fn payload_kind_mismatch_panics_with_clear_message() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![TabHandle::dynamic(
        id,
        "image",
        TabInfo::new().title(label("Wrong")),
        DocState {
            initial_text: "doc-state-payload".into(),
        }, // wrong kind!
    )]);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected)
            // Register "image" with payload type ImageState.
            .dynamic_tab::<ImageState>("image", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );

    // The mismatch surfaces during the build → layout pass when
    // the dynamic factory tries to downcast the payload.
    tree.layout(SizeProposal::exact(640.0, 320.0));
}

#[test]
fn static_then_dynamic_renders_in_order() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let dyn_id = TabId::fresh();
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![TabHandle::dynamic(
        dyn_id,
        "doc",
        TabInfo::new().title(label("Doc1")).closable(true),
        DocState {
            initial_text: "x".into(),
        },
    )]);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(
        TabWidget::new(selected)
            .static_tab(
                TabInfo::new().title(label("Welcome")).pinned(true),
                FixedLeaf(120.0, 48.0),
            )
            .dynamic_tab::<DocState>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(800.0, 320.0));

    // The static "Welcome" tab is pinned → renders in the leading
    // pinned strip; the dynamic Doc1 tab renders in the scrollable
    // row.
    let bar = bar_of(&tree, widget_id);
    let row_outer = bar_content(&tree, bar);
    let pinned_strip_count: usize = tree
        .children(row_outer)
        .iter()
        .filter_map(|&c| {
            let kids = tree.children(c);
            if kids.len() == 1 {
                let info = tree.accessibility_node(kids[0]);
                if info.role() == accesskit::Role::ScrollView {
                    return None; // Expand wrapper
                }
            }
            Some(kids.len())
        })
        .max()
        .unwrap_or(0);
    assert_eq!(
        pinned_strip_count, 1,
        "expected the pinned static tab in the leading strip"
    );

    let header_row = data_source_header_row(&tree, bar);
    assert_eq!(
        tree.children(header_row).len(),
        1,
        "expected the dynamic tab in the scrollable row"
    );
}

// ─── TabBar (stand-alone) — sizing + data-source mode ───────────────

#[test]
fn tab_bar_shared_sizing_divides_viewport_equally() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model = ListModel::from_vec(vec![
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("B")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("C")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("D")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("E")), ()),
    ]);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(
        TabBar::horizontal(model, delegate, selected, |_, h: &TabHandle| h.id)
            .tab_sizing(TabSizing::Shared)
            .min_tab_width(0.0)
            .max_tab_width(1000.0)
            .tab_spacing(0.0)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(1000.0, 60.0));

    let header_row = data_source_header_row(&tree, bar_id);
    let headers = tree.children(header_row);
    let widths: Vec<f32> = headers.iter().map(|&h| tree.bounds(h).width).collect();
    let target = widths[0];
    for w in &widths {
        assert!(
            (w - target).abs() < 0.5,
            "widths drift in Shared mode: {widths:?}"
        );
    }
    assert!(
        (target - 200.0).abs() < 1.0,
        "expected ~200 dp per tab, got {target}"
    );
}

#[test]
fn pinned_tab_renders_in_leading_strip() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model = ListModel::from_vec(vec![
        TabHandle::dynamic(
            TabId::fresh(),
            "doc",
            TabInfo::new().title(label("Pinned")).pinned(true),
            (),
        ),
        TabHandle::dynamic(
            TabId::fresh(),
            "doc",
            TabInfo::new().title(label("Normal")),
            (),
        ),
    ]);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")))
            .pinned(|_, h: &TabHandle| h.info.pinned);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(
        TabBar::horizontal(model, delegate, selected, |_, h: &TabHandle| h.id)
            .pinned_tab_width(36.0)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(800.0, 60.0));

    let header_row = data_source_header_row(&tree, bar_id);
    assert_eq!(
        tree.children(header_row).len(),
        1,
        "only the unpinned tab is in the scroll row"
    );
}

// ─── TabBar — scroll the active tab into view ───────────────────────
//
// A tab activated by pointer or keyboard is revealed for free: both move
// focus, and the framework's focus follow walks the clipping ancestors.
// Selection written *programmatically* moves no focus, so before the
// reveal plumbing the active tab could sit outside the strip's viewport
// with nothing to bring it back.

/// The strip's scroll viewport — the `ScrollArea` wrapping the header row.
fn strip_viewport(tree: &WidgetTree, bar_id: WidgetId) -> WidgetId {
    let row_outer = bar_content(tree, bar_id);
    let expand = expand_in_row_outer(tree, row_outer);
    tree.child_widget(expand, 0)
}

/// How far the strip is scrolled along `axis`, read off placed geometry
/// (the content row's origin against the viewport's).
fn strip_offset(tree: &WidgetTree, bar_id: WidgetId, axis: TabBarOrientation) -> f32 {
    let viewport = tree.bounds(strip_viewport(tree, bar_id));
    let row = tree.bounds(data_source_header_row(tree, bar_id));
    match axis {
        TabBarOrientation::Horizontal => viewport.x - row.x,
        TabBarOrientation::Vertical => viewport.y - row.y,
    }
}

/// Whether unpinned header `index` sits entirely inside the viewport.
fn header_fully_visible(tree: &WidgetTree, bar_id: WidgetId, index: usize) -> bool {
    let viewport = tree.bounds(strip_viewport(tree, bar_id));
    let header = tree.bounds(tree.children(data_source_header_row(tree, bar_id))[index]);
    header.x >= viewport.x - 0.5
        && header.right() <= viewport.right() + 0.5
        && header.y >= viewport.y - 0.5
        && header.bottom() <= viewport.bottom() + 0.5
}

fn many_tabs(count: usize) -> (Vec<TabId>, ListModel<TabHandle>) {
    let ids: Vec<TabId> = (0..count).map(|_| TabId::fresh()).collect();
    let model = ListModel::from_vec(
        ids.iter()
            .enumerate()
            .map(|(i, &id)| {
                TabHandle::dynamic(id, "doc", TabInfo::new().title(label(&format!("T{i}"))), ())
            })
            .collect(),
    );
    (ids, model)
}

fn overflowing_bar(
    model: ListModel<TabHandle>,
    selected: Signal<Option<TabId>>,
) -> TabBar<TabHandle> {
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    TabBar::horizontal(model, delegate, selected, |_, h: &TabHandle| h.id)
        .tab_sizing(TabSizing::Shared)
        .min_tab_width(120.0)
        .max_tab_width(120.0)
        .tab_spacing(0.0)
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false)
}

#[test]
fn programmatic_selection_scrolls_the_active_tab_into_view() {
    // 20 tabs × 120 dp = 2400 dp of headers in a 480 dp strip: the tail
    // is well outside the viewport. Selecting it by id — the path an app
    // takes when it focuses an already-open document — must bring it in.
    let (ids, model) = many_tabs(20);
    let selected: Signal<Option<TabId>> = Signal::new(None);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(overflowing_bar(model, selected.clone()));
    tree.layout(SizeProposal::exact(480.0, 60.0));

    assert!(
        header_fully_visible(&tree, bar_id, 0),
        "the first tab starts visible"
    );
    assert!(
        !header_fully_visible(&tree, bar_id, 19),
        "the last tab starts outside the viewport — otherwise this test proves nothing"
    );

    selected.set(Some(ids[19]));
    tree.layout(SizeProposal::exact(480.0, 60.0));

    assert!(
        header_fully_visible(&tree, bar_id, 19),
        "activating a tab by id must scroll it into view; strip offset is {}",
        strip_offset(&tree, bar_id, TabBarOrientation::Horizontal)
    );
}

#[test]
fn reveal_moves_the_minimum_and_leaves_a_visible_tab_alone() {
    // The `ScrollIntoView` convention: chase only the edge the tab fell
    // off. A tab already inside the viewport must not recentre the strip.
    let (ids, model) = many_tabs(20);
    let selected: Signal<Option<TabId>> = Signal::new(None);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(overflowing_bar(model, selected.clone()));
    tree.layout(SizeProposal::exact(480.0, 60.0));

    selected.set(Some(ids[19]));
    tree.layout(SizeProposal::exact(480.0, 60.0));
    let at_tail = strip_offset(&tree, bar_id, TabBarOrientation::Horizontal);
    // 2400 dp of content in 480 dp: the trailing edge is 1920 dp in.
    assert!(
        (at_tail - 1920.0).abs() < 1.0,
        "revealing the last tab should land flush with the trailing edge, got {at_tail}"
    );

    // Tab 18 is already visible (the viewport shows 16..19), so this
    // must not move the strip at all.
    selected.set(Some(ids[18]));
    tree.layout(SizeProposal::exact(480.0, 60.0));
    assert!(
        (strip_offset(&tree, bar_id, TabBarOrientation::Horizontal) - at_tail).abs() < 0.5,
        "revealing an already-visible tab must not scroll"
    );

    // Tab 15 is one step off the leading edge: chase that edge only.
    selected.set(Some(ids[15]));
    tree.layout(SizeProposal::exact(480.0, 60.0));
    let at_head = strip_offset(&tree, bar_id, TabBarOrientation::Horizontal);
    assert!(
        (at_head - 1800.0).abs() < 1.0,
        "revealing a tab just past the leading edge should align it flush there, got {at_head}"
    );
}

#[test]
fn opening_a_new_tab_reveals_it_on_the_first_layout() {
    // The app pattern: push the tab, then select it. The bar rebuilds,
    // so the reveal has to be resolved against the *new* tab order — and
    // land on the pass that first lays the new header out, or the strip
    // visibly lurches a frame later.
    let (ids, model) = many_tabs(20);
    let selected: Signal<Option<TabId>> = Signal::new(Some(ids[0]));

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(overflowing_bar(model.clone(), selected.clone()));
    tree.layout(SizeProposal::exact(480.0, 60.0));

    let fresh = TabId::fresh();
    model.push(TabHandle::dynamic(
        fresh,
        "doc",
        TabInfo::new().title(label("New")),
        (),
    ));
    selected.set(Some(fresh));
    tree.layout(SizeProposal::exact(480.0, 60.0));

    assert!(
        header_fully_visible(&tree, bar_id, 20),
        "a newly opened tab must be visible as soon as it is laid out; strip offset is {}",
        strip_offset(&tree, bar_id, TabBarOrientation::Horizontal)
    );
}

#[test]
fn an_unrelated_rebuild_does_not_yank_the_strip_back() {
    // The reveal is edge-triggered on the selection, not an invariant
    // re-asserted every pass. Once the user has scrolled away from the
    // active tab by hand, a rebuild for some other reason — a retitled
    // tab, a locale flip, a tab opened elsewhere in the strip — must
    // leave the viewport where they put it.
    let (ids, model) = many_tabs(20);
    let selected: Signal<Option<TabId>> = Signal::new(None);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(overflowing_bar(model.clone(), selected.clone()));
    tree.layout(SizeProposal::exact(480.0, 60.0));

    selected.set(Some(ids[19]));
    tree.layout(SizeProposal::exact(480.0, 60.0));
    assert!(header_fully_visible(&tree, bar_id, 19));

    // Scroll back to the head by hand. The bar remaps a vertical wheel
    // onto its horizontal axis, so a negative delta walks left.
    tree.pointer_move(Point::new(240.0, 20.0));
    tree.dispatch_event(WidgetEvent::Scroll {
        delta: ScrollDelta::Pixels { x: 0.0, y: -5000.0 },
        modifiers: Modifiers::default(),
    });
    tree.layout(SizeProposal::exact(480.0, 60.0));
    let by_hand = strip_offset(&tree, bar_id, TabBarOrientation::Horizontal);
    assert!(
        by_hand.abs() < 0.5,
        "the wheel should have walked the strip back to the head, got {by_hand}"
    );

    // A rebuild that does not touch the selection.
    model.push(TabHandle::dynamic(
        TabId::fresh(),
        "doc",
        TabInfo::new().title(label("Elsewhere")),
        (),
    ));
    tree.layout(SizeProposal::exact(480.0, 60.0));

    assert!(
        strip_offset(&tree, bar_id, TabBarOrientation::Horizontal).abs() < 0.5,
        "an unrelated rebuild must not re-reveal the active tab"
    );
}

#[test]
fn a_vertical_bar_reveals_its_active_tab_too() {
    // A vertical bar's content is measured with `height: None`, so the
    // row cannot recover the viewport extent from its size proposal and
    // reads the area's last-placed viewport instead.
    let (ids, model) = many_tabs(20);
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(
        TabBar::vertical(model, delegate, selected.clone(), |_, h: &TabHandle| h.id)
            .tab_spacing(0.0)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(200.0, 200.0));

    assert!(
        !header_fully_visible(&tree, bar_id, 19),
        "the last pill starts outside the 200 dp column"
    );

    selected.set(Some(ids[19]));
    tree.layout(SizeProposal::exact(200.0, 200.0));

    assert!(
        header_fully_visible(&tree, bar_id, 19),
        "a vertical bar must reveal its active pill too; strip offset is {}",
        strip_offset(&tree, bar_id, TabBarOrientation::Vertical)
    );
}

// ─── helpers ────────────────────────────────────────────────────────

fn bar_of(tree: &WidgetTree, widget_id: WidgetId) -> WidgetId {
    // TabWidget root: VStack { TabBar, Expand[Switcher] }
    let root = tree.child_widget(widget_id, 0);
    tree.child_widget(root, 0)
}

fn find_close_button(tree: &WidgetTree, header: WidgetId) -> WidgetId {
    fn walk(tree: &WidgetTree, id: WidgetId, out: &mut Option<WidgetId>) {
        if out.is_some() {
            return;
        }
        let info = tree.accessibility_node(id);
        if info.role() == accesskit::Role::Button
            && let Some(name) = info.name()
            && name.contains("Close")
        {
            *out = Some(id);
            return;
        }
        for child in tree.children(id) {
            walk(tree, child, out);
        }
    }
    let mut out = None;
    walk(tree, header, &mut out);
    out.expect("expected a close button on this tab header")
}

/// Hover the given header (so its close button becomes visible),
/// then locate and click the close button. The close button is now
/// hidden until the surrounding tab is hovered (Firefox / Chrome
/// convention) — this helper bundles the hover + click for tests
/// that just want to invoke the close affordance.
fn hover_and_click_close(tree: &mut WidgetTree, header: WidgetId) {
    let center = tree.bounds(header).center();
    tree.pointer_move(center);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    let close = find_close_button(tree, header);
    tree.click(close);
}

// ─── Overflow dropdown visibility mode ──────────────────────────────

/// Find the "show all tabs" overflow trigger by its AT name, requiring
/// real laid-out bounds — so a dormant (hidden) trigger reads as `None`.
fn active_overflow_trigger(tree: &WidgetTree, id: WidgetId) -> Option<WidgetId> {
    let info = tree.accessibility_node(id);
    if info.role() == accesskit::Role::Button
        && info.name().is_some_and(|n| n.contains("Show all tabs"))
        && tree.bounds(id).height > 0.0
    {
        return Some(id);
    }
    tree.children(id)
        .iter()
        .find_map(|&c| active_overflow_trigger(tree, c))
}

fn overflow_bar(mode: crate::tab_widget::TabOverflowButton) -> (WidgetTree, WidgetId) {
    // Six min-120 tabs: fit at 900 px wide (no overflow), overflow at 300.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model = ListModel::from_vec(
        (0..6)
            .map(|i| {
                TabHandle::dynamic(
                    TabId::fresh(),
                    "doc",
                    TabInfo::new().title(label(&format!("Document {i}"))),
                    (),
                )
            })
            .collect::<Vec<_>>(),
    );
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar = tree.add(
        TabBar::horizontal(model, delegate, selected, |_, h: &TabHandle| h.id)
            .min_tab_width(120.0)
            .overflow_button(mode),
    );
    (tree, bar)
}

#[test]
fn overflow_button_auto_reveals_only_when_tabs_overflow() {
    use crate::tab_widget::TabOverflowButton;
    // The ScrollArea writes its `max_scroll` extent during layout; the
    // `visible_when` gate on that signal re-activates on the *next* pass (as
    // the frame loop settles). Lay out twice per size to reach that steady
    // state, exactly as a live window would.
    let settle = |tree: &mut WidgetTree, w: f32| {
        tree.layout(SizeProposal::exact(w, 60.0));
        tree.layout(SizeProposal::exact(w, 60.0));
    };
    let (mut tree, bar) = overflow_bar(TabOverflowButton::Auto);
    // Narrow: the headers overflow the viewport → the trigger appears. Grab
    // its (rebuild-stable) id here so we can query dormancy directly across
    // resizes, rather than re-reading a pruned AT node / stale bounds.
    settle(&mut tree, 300.0);
    let trigger = active_overflow_trigger(&tree, bar)
        .expect("Auto: overflow → the 'show all tabs' trigger is revealed");
    assert!(tree.is_active(trigger), "Auto: revealed trigger is active");
    // Re-widen: everything fits → the trigger goes dormant again (regression
    // against a stuck-visible trigger).
    settle(&mut tree, 900.0);
    assert!(
        !tree.is_active(trigger),
        "Auto: no overflow → the 'show all tabs' trigger is hidden"
    );
    // Narrow again: it comes back.
    settle(&mut tree, 300.0);
    assert!(
        tree.is_active(trigger),
        "Auto: re-narrowed → the trigger is revealed again"
    );
}

#[test]
fn overflow_button_always_shows_even_without_overflow() {
    use crate::tab_widget::TabOverflowButton;
    let (mut tree, bar) = overflow_bar(TabOverflowButton::Always);
    tree.layout(SizeProposal::exact(900.0, 60.0));
    assert!(
        active_overflow_trigger(&tree, bar).is_some(),
        "Always: the trigger is shown even when every tab fits"
    );
}

#[test]
fn overflow_button_never_omits_the_trigger() {
    use crate::tab_widget::TabOverflowButton;
    let (mut tree, bar) = overflow_bar(TabOverflowButton::Never);
    // Even when the tabs overflow, Never never builds the trigger.
    tree.layout(SizeProposal::exact(300.0, 60.0));
    assert!(
        active_overflow_trigger(&tree, bar).is_none(),
        "Never: the 'show all tabs' trigger is never built"
    );
}

// ─── Vertical orientation ───────────────────────────────────────────

#[test]
fn vertical_bar_lays_out_pills_top_to_bottom() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model = ListModel::from_vec(vec![
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("B")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("C")), ()),
    ]);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(
        TabBar::vertical(model, delegate, selected, |_, h: &TabHandle| h.id)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(200.0, 600.0));

    let header_row = data_source_header_row(&tree, bar_id);
    let headers = tree.children(header_row);
    assert_eq!(headers.len(), 3);

    // Each header below the previous one — y strictly increasing.
    let bounds: Vec<_> = headers.iter().map(|&h| tree.bounds(h)).collect();
    assert!(bounds[0].y < bounds[1].y, "y order: {bounds:?}");
    assert!(bounds[1].y < bounds[2].y, "y order: {bounds:?}");
    // X is the same — pills stacked, no horizontal flow.
    assert!((bounds[0].x - bounds[1].x).abs() < 0.5);
    assert!((bounds[1].x - bounds[2].x).abs() < 0.5);
}

#[test]
fn vertical_shared_sizing_uses_intrinsic_pill_height() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model = ListModel::from_vec(vec![
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("B")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("C")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("D")), ()),
    ]);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    let theme = teksilo_core::presets::intui::light();
    let intrinsic = crate::styles::recipe_tab_style::TAB_EDITOR_HEIGHT;
    let mut tree = WidgetTree::new().with_theme(theme);
    let bar_id = tree.add(
        TabBar::vertical(model, delegate, selected, |_, h: &TabHandle| h.id)
            .tab_sizing(TabSizing::Shared)
            .tab_spacing(0.0)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(200.0, 800.0));

    let header_row = data_source_header_row(&tree, bar_id);
    let headers = tree.children(header_row);
    let heights: Vec<f32> = headers.iter().map(|&h| tree.bounds(h).height).collect();
    let target = heights[0];
    for h in &heights {
        assert!(
            (h - target).abs() < 0.5,
            "heights drift in Shared mode: {heights:?}"
        );
    }
    // Vertical Shared does NOT divide the viewport — sidebar pills
    // stay at the intrinsic per-tab height (`editor_tab_height`)
    // regardless of bar height. A 800 dp bar with 4 tabs gives 4
    // pills of ~50 dp each, not 4 × ~200 dp bands.
    assert!(
        (target - intrinsic).abs() < 0.5,
        "expected ~{intrinsic} dp per tab (editor_tab_height), got {target}"
    );
}

/// The nav-sidebar shape the mode exists for: a bottom-pinned bar in a
/// fixed-width column, which places the bar at the width the bar *asks
/// for* (a `VStack` aligns, it does not stretch). `Shared` asks for its
/// widest label and leaves the rest of the sidebar empty; `Fill` asks
/// for the whole column, so the pills span it. Heights are untouched
/// either way — in a vertical bar `Fill` acts on the cross axis.
///
/// Also covers the natural height: the bar sits beside a flexible
/// `Spacer` with no height pin, and must still report its content
/// extent (3 pills) rather than collapsing to the 0 dp its greedy
/// scroll slot would otherwise report.
#[test]
fn vertical_fill_sizing_stretches_pills_to_sidebar_width() {
    const SIDEBAR_W: f32 = 240.0;
    const SIDEBAR_H: f32 = 400.0;
    const PILL_H: f32 = 34.0;

    fn sidebar(sizing: TabSizing) -> (WidgetTree, WidgetId) {
        let model = ListModel::from_vec(vec![
            TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("A")), ()),
            TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("B")), ()),
            TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("C")), ()),
        ]);
        let delegate =
            TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let bar_id = tree.add(
            TabBar::vertical(model, delegate, Signal::new(None), |_, h: &TabHandle| h.id)
                .tab_sizing(sizing)
                .tab_bar_height(PILL_H)
                .tab_spacing(0.0)
                .show_scroll_arrows(false)
                .show_overflow_dropdown(false),
        );
        // A `Spacer` above pins the nav to the sidebar's bottom — no
        // height pin on the bar itself.
        let spacer = tree.add(crate::primitives::Spacer::new());
        let column = tree.add(VStack::new().add_child(spacer).add_child(bar_id));
        let _sidebar = tree.add(
            FixedSize::new()
                .width(SIDEBAR_W)
                .height(SIDEBAR_H)
                .child_id(column),
        );
        tree.layout(SizeProposal::exact(SIDEBAR_W, SIDEBAR_H));
        (tree, bar_id)
    }

    let (shared_tree, shared_bar) = sidebar(TabSizing::Shared);
    let shared_w = shared_tree.bounds(shared_bar).width;
    assert!(
        shared_w < SIDEBAR_W - 1.0,
        "Shared fits the widest label — it should not span the {SIDEBAR_W} dp sidebar; got {shared_w}"
    );

    let (tree, bar_id) = sidebar(TabSizing::Fill);
    let bar = tree.bounds(bar_id);
    assert!(
        (bar.width - SIDEBAR_W).abs() < 0.5,
        "the Fill bar takes the width it is offered, got {}",
        bar.width
    );
    // Natural height beside a flexible sibling: 3 pills, and pushed to
    // the bottom of the column by the Spacer.
    assert!(
        (bar.height - 3.0 * PILL_H).abs() < 0.5,
        "expected the bar's content height (3 × {PILL_H}), got {}",
        bar.height
    );
    assert!(
        (bar.y + bar.height - SIDEBAR_H).abs() < 0.5,
        "the Spacer should pin the nav to the sidebar bottom, got y={}",
        bar.y
    );

    let header_row = data_source_header_row(&tree, bar_id);
    let headers = tree.children(header_row);
    assert_eq!(headers.len(), 3);
    for &h in &headers {
        let b = tree.bounds(h);
        assert!(
            (b.width - SIDEBAR_W).abs() < 1.0,
            "every pill spans the sidebar under Fill: got {} in a {SIDEBAR_W} dp column",
            b.width
        );
        // …and Fill did not touch the layout axis: pill height is still
        // the per-tab extent, not viewport / 3.
        assert!(
            (b.height - PILL_H).abs() < 0.5,
            "Fill must not stretch pill heights: got {}",
            b.height
        );
    }
}

/// An unbounded width proposal (a `Center`, an `HStack` measuring the
/// natural size) has nothing to fill — `Fill` must not collapse the bar
/// to zero; it falls back to the `Shared` fit-to-widest-label width.
#[test]
fn vertical_fill_sizing_falls_back_to_intrinsic_width_when_unbounded() {
    let tabs = || {
        ListModel::from_vec(vec![
            TabHandle::dynamic(
                TabId::fresh(),
                "doc",
                TabInfo::new().title(label("Examples")),
                (),
            ),
            TabHandle::dynamic(
                TabId::fresh(),
                "doc",
                TabInfo::new().title(label("About")),
                (),
            ),
        ])
    };
    let delegate =
        || TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    let unbounded = SizeProposal {
        width: None,
        height: Some(400.0),
    };

    let mut fill_tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let fill_bar = fill_tree.add(
        TabBar::vertical(tabs(), delegate(), Signal::new(None), |_, h: &TabHandle| {
            h.id
        })
        .tab_sizing(TabSizing::Fill)
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false),
    );
    fill_tree.layout(unbounded);

    let mut shared_tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let shared_bar = shared_tree.add(
        TabBar::vertical(tabs(), delegate(), Signal::new(None), |_, h: &TabHandle| {
            h.id
        })
        .tab_sizing(TabSizing::Shared)
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false),
    );
    shared_tree.layout(unbounded);

    let fill_w = fill_tree.bounds(fill_bar).width;
    let shared_w = shared_tree.bounds(shared_bar).width;
    assert!(fill_w > 0.0, "an unbounded Fill bar must not collapse");
    assert!(
        (fill_w - shared_w).abs() < 0.5,
        "with no width to fill, Fill falls back to Shared: {fill_w} vs {shared_w}"
    );
}

/// Horizontal `Fill` divides the viewport like `Shared` but drops the
/// `max_tab_width` cap — the strip is filled edge to edge instead of
/// leaving trailing slack.
#[test]
fn horizontal_fill_sizing_ignores_max_tab_width() {
    let tabs = || {
        ListModel::from_vec(vec![
            TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("A")), ()),
            TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("B")), ()),
            TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("C")), ()),
        ])
    };
    let delegate =
        || TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(
        TabBar::horizontal(tabs(), delegate(), Signal::new(None), |_, h: &TabHandle| {
            h.id
        })
        .tab_sizing(TabSizing::Fill)
        .min_tab_width(0.0)
        .max_tab_width(120.0) // Shared would stop here, leaving 540 dp of slack
        .tab_spacing(0.0)
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(900.0, 60.0));

    let header_row = data_source_header_row(&tree, bar_id);
    let widths: Vec<f32> = tree
        .children(header_row)
        .iter()
        .map(|&h| tree.bounds(h).width)
        .collect();
    for w in &widths {
        assert!(
            (w - 300.0).abs() < 1.0,
            "expected 900/3 = 300 dp per tab under Fill (max ignored), got {widths:?}"
        );
    }
}

/// …but `min_tab_width` still holds under horizontal `Fill`: past the
/// point where the tabs would squeeze below it, they overflow into the
/// bar's scroll area instead.
#[test]
fn horizontal_fill_sizing_respects_min_tab_width() {
    let handles: Vec<TabHandle> = (0..10)
        .map(|i| {
            TabHandle::dynamic(
                TabId::fresh(),
                "doc",
                TabInfo::new().title(label(&format!("Tab {i}"))),
                (),
            )
        })
        .collect();
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(
        TabBar::horizontal(
            ListModel::from_vec(handles),
            delegate,
            Signal::new(None),
            |_, h: &TabHandle| h.id,
        )
        .tab_sizing(TabSizing::Fill)
        .min_tab_width(80.0)
        .tab_spacing(0.0)
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false),
    );
    // 300 dp / 10 tabs = 30 dp each — under the 80 dp floor.
    tree.layout(SizeProposal::exact(300.0, 60.0));

    let header_row = data_source_header_row(&tree, bar_id);
    let widths: Vec<f32> = tree
        .children(header_row)
        .iter()
        .map(|&h| tree.bounds(h).width)
        .collect();
    for w in &widths {
        assert!(
            (w - 80.0).abs() < 1.0,
            "Fill must not squeeze tabs below min_tab_width, got {widths:?}"
        );
    }
}

#[test]
fn compact_tab_bar_height_overrides_editor_height() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let model = ListModel::from_vec(vec![
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("B")), ()),
    ]);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let bar_id = tree.add(
        TabBar::horizontal(model, delegate, selected, |_, h: &TabHandle| h.id)
            .tab_bar_height(38.0)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    // Leave the height unconstrained so the bar takes its NATURAL height (what
    // a TabWidget allocates) rather than being stretched to a forced extent.
    tree.layout(SizeProposal {
        width: Some(400.0),
        height: None,
    });

    let h = tree.bounds(bar_id).height;
    assert!(
        (h - 38.0).abs() < 1.0,
        "compact bar should be 38 dp tall, got {h}"
    );
    // …and well under the 50 dp default.
    assert!(h < crate::styles::recipe_tab_style::TAB_EDITOR_HEIGHT);
}

#[test]
fn tab_widget_vertical_compose_lays_bar_on_leading_edge() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(
        TabWidget::new(selected.clone())
            .vertical()
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(800.0, 600.0));

    // TabWidget root is now an HStack { bar, content } in vertical
    // mode (instead of VStack).
    let root = tree.child_widget(widget_id, 0);
    let root_kids = tree.children(root);
    assert_eq!(root_kids.len(), 2);
    let bar_bounds = tree.bounds(root_kids[0]);
    let content_bounds = tree.bounds(root_kids[1]);
    // Bar on the leading edge (smaller x), content on trailing.
    assert!(
        bar_bounds.x < content_bounds.x,
        "bar should be on leading edge: bar={bar_bounds:?} content={content_bounds:?}"
    );
}

/// Regression: a vertical bar with a per-tab background must keep every
/// header (and therefore its leading accent indicator) pinned to the bar's
/// leading edge, regardless of how wide each tab's label is. The background
/// wraps the chrome in an extra `ZStack[bg, chrome]`; a plain ZStack
/// there sized the chrome to its label and centered it, dragging the
/// indicator inward by a per-label amount (the bug: indicator x drifted as
/// the selected tab changed because the texts differ). The fix wraps the
/// chrome in `Expand` so it fills the full tab width.
#[test]
fn vertical_surface_role_keeps_headers_flush_leading() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    // Deliberately varied label widths — the bug only shows when labels
    // differ, since the drift is `(tab_width - label_width) / 2`.
    let titles = ["X", "Containers", "Rich Text", "Date & Time", "OK"];
    let mut tw = TabWidget::new(selected.clone())
        .vertical()
        .max_tab_width(180.0)
        .tab_background(teksilo_tokens::SurfaceRole::Sunken);
    for t in titles {
        tw = tw.static_tab(TabInfo::new().title(label(t)), FixedLeaf(120.0, 48.0));
    }
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let widget_id = tree.add(tw);
    tree.layout(SizeProposal::exact(900.0, 600.0));

    let root = tree.child_widget(widget_id, 0);
    let bar_id = tree.child_widget(root, 0);
    let header_row = data_source_header_row(&tree, bar_id);
    let headers = tree.children(header_row);
    assert_eq!(headers.len(), titles.len());

    // Every header fills the full bar width and starts at the same x.
    let first = tree.bounds(headers[0]);
    for &h in &headers {
        let b = tree.bounds(h);
        assert!(
            (b.x - first.x).abs() < 0.5,
            "header x drifts with label width: {:?} vs {:?}",
            b,
            first
        );
        assert!(
            (b.width - first.width).abs() < 0.5,
            "header width drifts with label width: {:?} vs {:?}",
            b,
            first
        );
    }

    // The bar must adopt the *widest* tab's natural width so the longest
    // label ("Date & Time") renders without truncation. Under
    // `MockTextBackend` (8 px/char) that label measures 11 × 8 = 88 px; the
    // header reserves it plus the label→spacer `INNER_GAP` (6) and the two
    // horizontal paddings (2 × 12). A regression in `estimate_natural_width`
    // (wrong text style, or forgetting the spacer gap) compresses the label
    // below 88 and truncates it.
    let widest_text = 11.0 * 8.0; // "Date & Time"
    let needed = widest_text + 6.0 + 2.0 * 12.0; // text + INNER_GAP + pad*2
    assert!(
        first.width + 0.5 >= needed,
        "bar didn't adopt the widest tab width: header {} < needed {}",
        first.width,
        needed
    );

    // And the leading accent indicator (the `TabBodyPainter` leaf) sits at
    // the header's leading edge — find each header's deepest leaf chain and
    // assert the painter-bearing chrome layer starts at the bar leading x.
    // The painter is the first non-bg leaf that spans the full header width;
    // we verify by checking that some descendant fills the full width at the
    // header's x (the chrome no longer collapses to the label).
    for &h in &headers {
        let hb = tree.bounds(h);
        let mut fills_at_leading = false;
        fn walk(tree: &WidgetTree, id: WidgetId, hb: teksilo_canvas::Rect, found: &mut bool) {
            let b = tree.bounds(id);
            if (b.x - hb.x).abs() < 0.5
                && (b.width - hb.width).abs() < 0.5
                && tree.children(id).is_empty()
            {
                *found = true;
            }
            for c in tree.children(id) {
                walk(tree, c, hb, found);
            }
        }
        walk(&tree, h, hb, &mut fills_at_leading);
        assert!(
            fills_at_leading,
            "no full-width leaf at the header leading edge — indicator would be inset/centered"
        );
    }
}

// ─── Reorder custom actions ─────────────────────────────────────────

#[test]
fn enabled_reorderable_tabs_advertise_move_custom_actions() {
    use accesskit::Role;

    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let id_c = TabId::fresh();
    let model = ListModel::from_vec(vec![
        TabHandle::dynamic(id_a, "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(id_b, "doc", TabInfo::new().title(label("B")), ()),
        TabHandle::dynamic(id_c, "doc", TabInfo::new().title(label("C")), ()),
    ]);

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", |_h, _s| {
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .reorderable(true)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(800.0, 600.0));

    let update = tree.sync_accessibility();
    // Collect the three Tab nodes in node order.
    let tabs: Vec<_> = update
        .nodes
        .iter()
        .filter(|(_, n)| n.role() == Role::Tab)
        .collect();
    assert_eq!(tabs.len(), 3);

    // First tab: only "Move Right" (no left neighbor).
    let first_actions = tabs[0].1.custom_actions();
    let descs: Vec<&str> = first_actions
        .iter()
        .map(|a| a.description.as_ref())
        .collect();
    assert_eq!(descs, vec!["Move Right"], "first tab — only Move Right");

    // Middle tab: both directions advertised.
    let mid_actions = tabs[1].1.custom_actions();
    let descs: Vec<&str> = mid_actions.iter().map(|a| a.description.as_ref()).collect();
    assert_eq!(
        descs,
        vec!["Move Left", "Move Right"],
        "middle tab — both directions"
    );

    // Last tab: only "Move Left".
    let last_actions = tabs[2].1.custom_actions();
    let descs: Vec<&str> = last_actions
        .iter()
        .map(|a| a.description.as_ref())
        .collect();
    assert_eq!(descs, vec!["Move Left"], "last tab — only Move Left");
}

#[test]
fn non_reorderable_tabs_do_not_advertise_move_actions() {
    use accesskit::Role;

    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabWidget::new(selected.clone())
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0))
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(800.0, 600.0));

    let update = tree.sync_accessibility();
    for (_, node) in &update.nodes {
        if node.role() == Role::Tab {
            assert!(
                node.custom_actions().is_empty(),
                "non-reorderable tab must not advertise Move actions"
            );
        }
    }
}

// ─── Selection bridge sanity (id ↔ index inside TabBar) ─────────────

#[test]
fn tab_bar_internal_bridge_sets_selected_id_when_initial_is_none() {
    // The TabBar pre-build sync should auto-populate `selected_id`
    // when the bar gets non-empty data and the id is None.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let model = ListModel::from_vec(vec![
        TabHandle::dynamic(id_a, "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(id_b, "doc", TabInfo::new().title(label("B")), ()),
    ]);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabBar::horizontal(model, delegate, selected.clone(), |_, h: &TabHandle| h.id)
            .show_scroll_arrows(false)
            .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(800.0, 60.0));

    assert_eq!(
        selected.get(),
        Some(id_a),
        "bar should auto-select the first tab when selected_id is None"
    );
}

#[test]
fn tab_bar_internal_bridge_drops_selection_when_target_id_disappears() {
    // Pre-build sync: a stale id falls back to the previously-known
    // index, clamped. After model.remove of the active tab, the
    // surviving tab gets selected.
    let id_a = TabId::fresh();
    let id_b = TabId::fresh();
    let selected: Signal<Option<TabId>> = Signal::new(Some(id_b));
    let model = ListModel::from_vec(vec![
        TabHandle::dynamic(id_a, "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(id_b, "doc", TabInfo::new().title(label("B")), ()),
    ]);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabBar::horizontal(
            model.clone(),
            delegate,
            selected.clone(),
            |_, h: &TabHandle| h.id,
        )
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(800.0, 60.0));
    assert_eq!(selected.get(), Some(id_b));

    // Remove tab B. The bar's pre-build sync should fall back —
    // index was 1, model now has 1 item, clamped to 0 → selects id_a.
    let _ = model.remove(1);
    tree.layout(SizeProposal::exact(800.0, 60.0));
    assert_eq!(
        selected.get(),
        Some(id_a),
        "stale id should fall back to the surviving neighbor"
    );
}

#[test]
fn tab_bar_drains_selection_to_none_when_model_emptied() {
    let id_a = TabId::fresh();
    let selected: Signal<Option<TabId>> = Signal::new(Some(id_a));
    let model = ListModel::from_vec(vec![TabHandle::dynamic(
        id_a,
        "doc",
        TabInfo::new().title(label("A")),
        (),
    )]);
    let delegate =
        TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    tree.add(
        TabBar::horizontal(
            model.clone(),
            delegate,
            selected.clone(),
            |_, h: &TabHandle| h.id,
        )
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false),
    );
    tree.layout(SizeProposal::exact(800.0, 60.0));

    let _ = model.remove(0);
    tree.layout(SizeProposal::exact(800.0, 60.0));
    assert_eq!(selected.get(), None, "empty model drains selection");
}

// ─── Cross-bar tab transfer (app-internal DnD between TabBars) ──────

/// Build a dynamic `TabHandle` carrying an `Rc`-shared marker as its
/// payload so a test can prove (via `Rc::ptr_eq`) that a migrated tab
/// carries the *same* heavy state, not a rebuilt copy.
fn doc_handle(title: &str, marker: std::rc::Rc<u32>) -> TabHandle {
    let payload: std::rc::Rc<dyn std::any::Any> = marker;
    TabHandle::dynamic_shared(
        TabId::fresh(),
        "doc",
        TabInfo::new().title(label(title)).closable(true),
        payload,
    )
}

fn doc_delegate() -> TabDelegate<TabHandle> {
    TabDelegate::new(|_, h: &TabHandle| h.info.title.clone().unwrap_or_else(|| label("")))
}

/// Remove the tab with `id` from a `ListModel<TabHandle>` (the model
/// mutation an app does in `on_transfer_out`).
fn remove_by_id(model: &ListModel<TabHandle>, id: TabId) {
    if let Some(pos) = (0..model.len()).find(|&i| model.with_item(i, |h| h.id) == Some(id)) {
        let _ = model.remove(pos);
    }
}

/// Center of the `index`-th unpinned header in a stand-alone `TabBar`.
fn header_center(tree: &WidgetTree, bar_id: WidgetId, index: usize) -> teksilo_canvas::Point {
    let row = data_source_header_row(tree, bar_id);
    let header = tree.child_widget(row, index);
    tree.bounds(header).center()
}

#[test]
fn cross_bar_transfer_moves_tab_and_preserves_state() {
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());

    let marker = std::rc::Rc::new(42_u32);
    let dragged = doc_handle("A1", marker.clone());
    let dragged_id = dragged.id;
    let dragged_payload = dragged.payload.clone();

    let model_a = ListModel::from_vec(vec![dragged, doc_handle("A2", std::rc::Rc::new(2))]);
    let model_b = ListModel::from_vec(vec![doc_handle("B1", std::rc::Rc::new(9))]);

    let bar_a = TabBar::horizontal(
        model_a.clone(),
        doc_delegate(),
        Signal::new(None),
        |_, h: &TabHandle| h.id,
    )
    .show_scroll_arrows(false)
    .show_overflow_dropdown(false)
    .on_transfer_out({
        let m = model_a.clone();
        move |id, _ctx| remove_by_id(&m, id)
    });

    let bar_b = TabBar::horizontal(
        model_b.clone(),
        doc_delegate(),
        Signal::new(None),
        |_, h: &TabHandle| h.id,
    )
    .show_scroll_arrows(false)
    .show_overflow_dropdown(false)
    .on_tab_received({
        let m = model_b.clone();
        move |handle, idx, _ctx| m.insert(idx.min(m.len()), handle)
    });

    let a_id = tree.add(bar_a);
    let b_id = tree.add(bar_b);
    let expand_a = tree.add(crate::Expand::new().flex(1.0).child_id(a_id));
    let expand_b = tree.add(crate::Expand::new().flex(1.0).child_id(b_id));
    tree.add(crate::HStack::new().add_child(expand_a).add_child(expand_b));
    tree.layout(SizeProposal::exact(900.0, 80.0));

    // Drag A's first tab onto B's header strip.
    let from = header_center(&tree, a_id, 0);
    let to = header_center(&tree, b_id, 0);
    tree.drag(from, to);
    tree.layout(SizeProposal::exact(900.0, 80.0));

    // Moved out of A, into B.
    assert_eq!(model_a.len(), 1, "source bar lost the dragged tab");
    assert!(
        (0..model_a.len()).all(|i| model_a.with_item(i, |h| h.id) != Some(dragged_id)),
        "dragged tab no longer in source model"
    );
    assert_eq!(model_b.len(), 2, "target bar gained the dragged tab");
    let landed = (0..model_b.len()).find(|&i| model_b.with_item(i, |h| h.id) == Some(dragged_id));
    assert!(landed.is_some(), "dragged tab id present in target model");

    // State preserved: the migrated handle carries the *same* Rc
    // payload (proves a real move, not a reconstruction).
    let same_state = model_b
        .with_item(landed.unwrap(), |h| {
            std::rc::Rc::ptr_eq(&h.payload, &dragged_payload)
        })
        .unwrap_or(false);
    assert!(
        same_state,
        "migrated tab must carry the same Rc<dyn Any> state"
    );
    assert_eq!(*marker, 42, "shared marker still reachable");
}

#[test]
fn cross_bar_rejected_when_target_not_opted_in() {
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());

    let dragged = doc_handle("A1", std::rc::Rc::new(1));
    let dragged_id = dragged.id;
    let model_a = ListModel::from_vec(vec![dragged, doc_handle("A2", std::rc::Rc::new(2))]);
    let model_b = ListModel::from_vec(vec![doc_handle("B1", std::rc::Rc::new(9))]);

    // Source opts in; target does NOT accept external tabs.
    let bar_a = TabBar::horizontal(
        model_a.clone(),
        doc_delegate(),
        Signal::new(None),
        |_, h: &TabHandle| h.id,
    )
    .show_scroll_arrows(false)
    .show_overflow_dropdown(false)
    .on_transfer_out({
        let m = model_a.clone();
        move |id, _ctx| remove_by_id(&m, id)
    });

    let bar_b = TabBar::horizontal(
        model_b.clone(),
        doc_delegate(),
        Signal::new(None),
        |_, h: &TabHandle| h.id,
    )
    .show_scroll_arrows(false)
    .show_overflow_dropdown(false);

    let a_id = tree.add(bar_a);
    let b_id = tree.add(bar_b);
    let expand_a = tree.add(crate::Expand::new().flex(1.0).child_id(a_id));
    let expand_b = tree.add(crate::Expand::new().flex(1.0).child_id(b_id));
    tree.add(crate::HStack::new().add_child(expand_a).add_child(expand_b));
    tree.layout(SizeProposal::exact(900.0, 80.0));

    let from = header_center(&tree, a_id, 0);
    let to = header_center(&tree, b_id, 0);
    tree.drag(from, to);
    tree.layout(SizeProposal::exact(900.0, 80.0));

    assert_eq!(model_a.len(), 2, "tab stays in source when target rejects");
    assert!(
        (0..model_a.len()).any(|i| model_a.with_item(i, |h| h.id) == Some(dragged_id)),
        "dragged tab still in source model"
    );
    assert_eq!(model_b.len(), 1, "target model unchanged");
}

#[test]
fn intra_bar_reorder_does_not_fire_transfer_out() {
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());

    let model = ListModel::from_vec(vec![
        doc_handle("T0", std::rc::Rc::new(0)),
        doc_handle("T1", std::rc::Rc::new(1)),
        doc_handle("T2", std::rc::Rc::new(2)),
    ]);
    let transfer_out_calls = std::rc::Rc::new(std::cell::Cell::new(0usize));

    let bar = TabBar::horizontal(
        model.clone(),
        doc_delegate(),
        Signal::new(None),
        |_, h: &TabHandle| h.id,
    )
    .show_scroll_arrows(false)
    .show_overflow_dropdown(false)
    .reorderable(true)
    .on_reorder({
        let m = model.clone();
        move |from, to, _ctx| m.move_item(from, to)
    })
    .on_transfer_out({
        let calls = transfer_out_calls.clone();
        move |_id, _ctx| calls.set(calls.get() + 1)
    });

    let bar_id = tree.add(bar);
    let expand = tree.add(crate::Expand::new().flex(1.0).child_id(bar_id));
    tree.add(crate::HStack::new().add_child(expand));
    tree.layout(SizeProposal::exact(600.0, 80.0));

    // Drag tab 0 onto tab 2's slot — an intra-bar reorder.
    let from = header_center(&tree, bar_id, 0);
    let to = header_center(&tree, bar_id, 2);
    tree.drag(from, to);
    tree.layout(SizeProposal::exact(600.0, 80.0));

    assert_eq!(
        transfer_out_calls.get(),
        0,
        "intra-bar reorder must NOT fire on_transfer_out (would drop the moved tab)"
    );
    assert_eq!(model.len(), 3, "reorder keeps every tab in the model");
}

/// A non-tab in-app drag payload (stands in for a file dragged from a
/// tree / list).
#[derive(Clone, Debug)]
struct FileRef {
    name: String,
}

/// A leaf widget that, on drag-start, publishes a `FileRef` payload —
/// i.e. a drag that is *not* a `TabBarDragData`.
#[derive(Debug)]
struct FileDragSource {
    name: String,
}

impl Widget for FileDragSource {
    fn build(&mut self, ctx: &mut teksilo_core::build_context::BuildContext) -> Vec<WidgetId> {
        let self_id = ctx.self_id();
        let name = self.name.clone();
        let hs = teksilo_core::widget_builder::HandlerSet::new().on_drag(move |phase, ctx| {
            if let teksilo_core::gesture::DragPhase::Started { .. } = phase {
                ctx.start_drag(
                    self_id,
                    teksilo_core::drag_payload::DragPayload::typed(FileRef { name: name.clone() }),
                );
            }
        });
        ctx.apply_self_handlers(hs);
        Vec::new()
    }

    fn layout_response(&self, _proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        Size::new(120.0, 48.0).into()
    }
}

#[test]
fn on_external_drop_accepts_non_tab_payload() {
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());

    let model = ListModel::from_vec(vec![doc_handle("T0", std::rc::Rc::new(0))]);
    let dropped: std::rc::Rc<std::cell::RefCell<Vec<(String, usize)>>> =
        std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));

    let bar = TabBar::horizontal(
        model.clone(),
        doc_delegate(),
        Signal::new(None),
        |_, h: &TabHandle| h.id,
    )
    .show_scroll_arrows(false)
    .show_overflow_dropdown(false)
    .on_external_drop({
        let dropped = dropped.clone();
        move |payload, idx, _ctx| {
            if let Some(file) = payload.get_typed::<FileRef>() {
                dropped.borrow_mut().push((file.name.clone(), idx));
                true
            } else {
                false
            }
        }
    });

    let bar_id = tree.add(bar);
    let source_id = tree.add(FileDragSource {
        name: "notes.txt".to_string(),
    });
    let expand_bar = tree.add(crate::Expand::new().flex(1.0).child_id(bar_id));
    let expand_src = tree.add(crate::Expand::new().flex(1.0).child_id(source_id));
    tree.add(
        crate::HStack::new()
            .add_child(expand_src)
            .add_child(expand_bar),
    );
    tree.layout(SizeProposal::exact(900.0, 80.0));

    let from = tree.bounds(source_id).center();
    let to = header_center(&tree, bar_id, 0);
    tree.drag(from, to);

    let calls = dropped.borrow();
    assert_eq!(calls.len(), 1, "on_external_drop should fire once");
    assert_eq!(calls[0].0, "notes.txt", "payload delivered to handler");
}

#[test]
fn non_tab_payload_rejected_without_handler() {
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());

    let model = ListModel::from_vec(vec![doc_handle("T0", std::rc::Rc::new(0))]);
    // Reorderable bar, but NO on_external_drop: a FileRef drag must be
    // ignored (the bar only consumes TabBarDragData here).
    let bar = TabBar::horizontal(
        model.clone(),
        doc_delegate(),
        Signal::new(None),
        |_, h: &TabHandle| h.id,
    )
    .show_scroll_arrows(false)
    .show_overflow_dropdown(false)
    .reorderable(true)
    .on_reorder({
        let m = model.clone();
        move |from, to, _| m.move_item(from, to)
    });

    let bar_id = tree.add(bar);
    let source_id = tree.add(FileDragSource {
        name: "x.txt".to_string(),
    });
    let expand_bar = tree.add(crate::Expand::new().flex(1.0).child_id(bar_id));
    let expand_src = tree.add(crate::Expand::new().flex(1.0).child_id(source_id));
    tree.add(
        crate::HStack::new()
            .add_child(expand_src)
            .add_child(expand_bar),
    );
    tree.layout(SizeProposal::exact(900.0, 80.0));

    // Should not panic, and the model is untouched (no tab created).
    let from = tree.bounds(source_id).center();
    let to = header_center(&tree, bar_id, 0);
    tree.drag(from, to);
    assert_eq!(model.len(), 1, "non-tab drop without a handler is a no-op");
}

// ─── bar_visibility ─────────────────────────────────────────────────

/// Recursively report whether any node in `id`'s subtree carries the
/// given accessibility role.
fn subtree_has_role(tree: &WidgetTree, id: WidgetId, role: accesskit::Role) -> bool {
    if tree.accessibility_node(id).role() == role {
        return true;
    }
    tree.children(id)
        .iter()
        .any(|&c| subtree_has_role(tree, c, role))
}

fn count_role(tree: &WidgetTree, id: WidgetId, role: accesskit::Role) -> usize {
    let here = usize::from(tree.accessibility_node(id).role() == role);
    here + tree
        .children(id)
        .iter()
        .map(|&c| count_role(tree, c, role))
        .sum::<usize>()
}

#[test]
fn bar_visibility_always_shows_strip() {
    use crate::tab_widget::TabBarVisibility;
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let root = tree.add(
        TabWidget::new(selected.clone())
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0))
            .bar_visibility(TabBarVisibility::Always),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        subtree_has_role(&tree, root, accesskit::Role::TabList),
        "Always must render the TabList strip"
    );
}

#[test]
fn bar_visibility_never_hides_strip() {
    use crate::tab_widget::TabBarVisibility;
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let root = tree.add(
        TabWidget::new(selected.clone())
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0))
            .bar_visibility(TabBarVisibility::Never),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        !subtree_has_role(&tree, root, accesskit::Role::TabList),
        "Never must not render any TabList strip"
    );
}

#[test]
fn bar_visibility_when_multiple_is_reactive_and_preserves_content() {
    use crate::tab_widget::TabBarVisibility;
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let pane_builds = Rc::new(Cell::new(0));
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![TabHandle::dynamic(
        TabId::fresh(),
        "doc",
        TabInfo::new().title(label("Only")),
        (),
    )]);

    let pb = pane_builds.clone();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let root = tree.add(
        TabWidget::new(selected.clone())
            .dynamic_tab::<()>("doc", move |_h, _s| {
                pb.set(pb.get() + 1);
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model.clone())
            .bar_visibility(TabBarVisibility::WhenMultiple),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));

    // One tab → strip hidden.
    assert!(
        !subtree_has_role(&tree, root, accesskit::Role::TabList),
        "WhenMultiple hides the strip at a single tab"
    );
    assert_eq!(pane_builds.get(), 1, "the sole pane builds once");

    // Add a second tab → strip appears (reactive via the rebuild).
    model.push(TabHandle::dynamic(
        TabId::fresh(),
        "doc",
        TabInfo::new().title(label("Second")),
        (),
    ));
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        subtree_has_role(&tree, root, accesskit::Role::TabList),
        "WhenMultiple shows the strip once a second tab appears"
    );
    // The first pane's content survives the 1→2 strip toggle (memoized).
    assert_eq!(
        pane_builds.get(),
        2,
        "only the newly-added pane builds; the first is preserved across the toggle"
    );

    // Remove back down to one → strip hides again.
    let _ = model.remove(1);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        !subtree_has_role(&tree, root, accesskit::Role::TabList),
        "WhenMultiple hides the strip again at a single tab"
    );
    assert_eq!(pane_builds.get(), 2, "no pane rebuild on the 2→1 toggle");
}

/// A **bound** policy flips the strip in place, and the panes underneath
/// survive it. This is the contract an app-level "hide the chrome" mode
/// depends on: entering and leaving the mode must not cost the user their
/// caret or scroll position, which swapping two `TabWidget`s in a
/// `Switcher` would.
#[test]
fn bar_visibility_bound_signal_toggles_strip_without_rebuilding_panes() {
    use crate::tab_widget::TabBarVisibility;
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let policy = Signal::new(TabBarVisibility::Always);
    let pane_builds = Rc::new(Cell::new(0));
    let model: ListModel<TabHandle> = ListModel::from_vec(vec![
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("A")), ()),
        TabHandle::dynamic(TabId::fresh(), "doc", TabInfo::new().title(label("B")), ()),
    ]);

    let pb = pane_builds.clone();
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let root = tree.add(
        TabWidget::new(selected)
            .dynamic_tab::<()>("doc", move |_h, _s| {
                pb.set(pb.get() + 1);
                Box::new(FixedLeaf(120.0, 48.0)) as Box<dyn Widget>
            })
            .dynamic_model(model)
            .bar_visibility(policy.clone()),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        subtree_has_role(&tree, root, accesskit::Role::TabList),
        "a bound Always renders the strip"
    );
    let built_before = pane_builds.get();
    assert!(built_before > 0, "panes built at least once up front");

    // Flip to Never — the strip goes away without a teardown of the content.
    policy.set(TabBarVisibility::Never);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        !subtree_has_role(&tree, root, accesskit::Role::TabList),
        "flipping the bound policy to Never must hide the strip"
    );
    assert_eq!(
        pane_builds.get(),
        built_before,
        "hiding the strip must not rebuild the panes"
    );

    // ...and back. A hidden strip still learns it should return, which is
    // why the binding is registered outside the `show_bar` block.
    policy.set(TabBarVisibility::Always);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        subtree_has_role(&tree, root, accesskit::Role::TabList),
        "flipping back to Always must bring the strip back"
    );
    assert_eq!(
        pane_builds.get(),
        built_before,
        "restoring the strip must not rebuild the panes either"
    );
}

/// A **derived** (`.map`) signal drives the policy too. Derived signals are
/// read-only and panic under `observe`, so this pins that the binding path
/// resolves through to the mutable roots instead — the app-side shape is
/// `focus_mode_signal().map(..)`, which has no mutable
/// `Signal<TabBarVisibility>` behind it.
#[test]
fn bar_visibility_accepts_a_derived_signal() {
    use crate::tab_widget::TabBarVisibility;
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let focus_mode = Signal::new(false);
    let policy = focus_mode.map(|on| {
        if *on {
            TabBarVisibility::Never
        } else {
            TabBarVisibility::Always
        }
    });

    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let root = tree.add(
        TabWidget::new(selected)
            .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
            .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0))
            .bar_visibility(policy),
    );
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        subtree_has_role(&tree, root, accesskit::Role::TabList),
        "derived policy resolves to Always while the source is false"
    );

    focus_mode.set(true);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(
        !subtree_has_role(&tree, root, accesskit::Role::TabList),
        "setting the derived signal's mutable root must re-derive the policy"
    );
}

// ─── Appearance API — per-state colours, dividers, indicator ────────

use teksilo_core::styles::TabIndicatorPosition;

/// A horizontal `TabWidget` with `n` static tabs, optionally with
/// inter-tab dividers, laid out at a generous size.
fn appearance_widget(n: usize, dividers: bool) -> (WidgetTree, WidgetId) {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let mut tw = TabWidget::new(selected)
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false);
    if dividers {
        tw = tw.tab_dividers();
    }
    for i in 0..n {
        tw = tw.static_tab(
            TabInfo::new().title(label(&format!("Tab {i}"))),
            FixedLeaf(120.0, 48.0),
        );
    }
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(tw);
    tree.layout(SizeProposal::exact(900.0, 320.0));
    (tree, id)
}

#[test]
fn tab_dividers_append_one_overlay_child_to_the_scroll_row() {
    // Off: the row's children are exactly the headers.
    let (tree, id) = appearance_widget(3, false);
    let row = data_source_header_row(&tree, bar_of(&tree, id));
    assert_eq!(
        tree.children(row).len(),
        3,
        "no overlay child when dividers are off"
    );

    // On: exactly one extra child (the divider overlay), and it is not a
    // Tab (so the tab count is unchanged) and is hidden from AT.
    let (tree, id) = appearance_widget(3, true);
    let row = data_source_header_row(&tree, bar_of(&tree, id));
    let kids = tree.children(row);
    assert_eq!(kids.len(), 4, "dividers add one overlay child to the row");
    let tabs = kids
        .iter()
        .filter(|&&c| tree.accessibility_node(c).role() == accesskit::Role::Tab)
        .count();
    assert_eq!(tabs, 3, "the overlay is not a tab");
    // The last child is the overlay — hidden from assistive tech.
    let overlay = *kids.last().unwrap();
    assert!(
        tree.accessibility_node(overlay).is_hidden(),
        "the divider overlay is presentational (AT-hidden)"
    );
}

#[test]
fn pinned_tabs_with_dividers_build() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let tw = TabWidget::new(selected)
        .tab_divider_color(teksilo_tokens::BorderRole::DividerStrong)
        .show_scroll_arrows(false)
        .show_overflow_dropdown(false)
        .static_tab(
            TabInfo::new().title(label("P1")).pinned(true),
            FixedLeaf(40.0, 48.0),
        )
        .static_tab(
            TabInfo::new().title(label("P2")).pinned(true),
            FixedLeaf(40.0, 48.0),
        )
        .static_tab(TabInfo::new().title(label("Doc")), FixedLeaf(120.0, 48.0));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(tw);
    tree.layout(SizeProposal::exact(800.0, 320.0));
    // Two pinned tabs + one unpinned all render (smoke: no panic, tabs present).
    let tab_count = count_role(&tree, id, accesskit::Role::Tab);
    assert_eq!(
        tab_count, 3,
        "all three tabs render with pinned-strip dividers"
    );
}

#[test]
fn active_indicator_inner_edge_builds_and_lays_out() {
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let tw = TabWidget::new(selected)
        .active_indicator(TabIndicatorPosition::InnerEdge)
        .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
        .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(tw);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert!(subtree_has_role(&tree, id, accesskit::Role::Tab));
}

#[test]
fn per_state_tab_backgrounds_build_with_and_without() {
    use teksilo_tokens::SurfaceRole;
    // All three states set: builds, lays out, all tabs present.
    let selected: Signal<Option<TabId>> = Signal::new(None);
    let tw = TabWidget::new(selected)
        .selected_tab_background(SurfaceRole::Raised)
        .hover_tab_background(SurfaceRole::Hover)
        .idle_tab_background(SurfaceRole::Transparent)
        .bar_background(SurfaceRole::Sunken)
        .static_tab(TabInfo::new().title(label("A")), FixedLeaf(120.0, 48.0))
        .static_tab(TabInfo::new().title(label("B")), FixedLeaf(120.0, 48.0));
    let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
    let id = tree.add(tw);
    tree.layout(SizeProposal::exact(640.0, 320.0));
    assert_eq!(count_role(&tree, id, accesskit::Role::Tab), 2);

    // Regression (nested-ZStack collapse): the selected tab's background rect
    // must FILL its tab, not shrink to 0×0. The first tab is selected by
    // default; its header → root ZStack → first child is the selected-state
    // RectWidget, which must cover the full tab bounds.
    fn first_tab(tree: &WidgetTree, id: WidgetId) -> Option<WidgetId> {
        if tree.accessibility_node(id).role() == accesskit::Role::Tab
            && tree.bounds(id).height > 0.0
        {
            return Some(id);
        }
        tree.children(id).iter().find_map(|&c| first_tab(tree, c))
    }
    let tab = first_tab(&tree, id).expect("a tab header");
    let tab_b = tree.bounds(tab);
    let root_zstack = tree.children(tab)[0];
    let sel_bg = tree.children(root_zstack)[0];
    let bg_b = tree.bounds(sel_bg);
    assert!(
        (bg_b.width - tab_b.width).abs() < 0.5 && (bg_b.height - tab_b.height).abs() < 0.5,
        "selected-tab background must fill its tab ({bg_b:?} vs {tab_b:?}) — \
         a nested ZStack would collapse it to zero"
    );

    // Default (no backgrounds): also builds with the same tab count.
    let (tree, id) = appearance_widget(2, false);
    assert_eq!(count_role(&tree, id, accesskit::Role::Tab), 2);
}

// ─── Suppress unused-warning when only some tests run ───────────────
#[cfg(test)]
fn _orientation_export_used() {
    let _ = TabBarOrientation::Horizontal;
}