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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! `TabBar<T>` — header strip driven by a data source.
//!
//! Horizontal and vertical orientations, with shared / independent
//! sizing. Bar-leading and bar-trailing slots are wired. Overflow is
//! handled by a `ScrollArea` around the headers row, plus optional
//! scroll arrows and a "show all tabs" overflow dropdown (both on by
//! default); whichever tab is activated is scrolled back into view (see
//! [`RevealState`]). Closable tabs (with middle-click close),
//! drag-to-reorder with edge auto-scroll, and a leading icon-only
//! pinned-tab strip are all supported. Multi-line (multi-row) wrapping
//! is the one layout mode not yet implemented.
//!
//! The data source is consumed via the `pub(crate)` [`ListSource`]
//! abstraction so callers can pass either a `ListModel<T>` (clonable,
//! mutable) or any external `ListDataSource<Item = T>` (a database
//! cursor, a virtual list, …) without TabBar having to carry a generic
//! source parameter.
//!
//! ## Accessibility
//!
//! The bar emits `Role::TabList` with an `aria-orientation`
//! reflecting whether it was built with [`TabBar::horizontal`] or
//! [`TabBar::vertical`]. When a page hosts more than one tab list,
//! give each one an accessible name via
//! [`.access_label(tr!(tab_list_name()))`](teksilo_core::widget_builder::WidgetBuilder::access_label)
//! so screen readers can distinguish them (ARIA APG recommendation).
//!
//! ```ignore
//! use teksilo_widgets::tab_widget::{TabBar, TabDelegate, TabId};
//! use teksilo_data::ListModel;
//! use teksilo_core::signal::Signal;
//!
//! #[derive(Clone)]
//! struct Tab { id: TabId, title: String }
//!
//! let model: ListModel<Tab> = ListModel::new();
//! let selected: Signal<Option<TabId>> = Signal::new(None);
//! let delegate = TabDelegate::new(|_i, t: &Tab| teksilo_i18n::lit!(t.title.clone()));
//! let _bar = TabBar::horizontal(model, delegate, selected, |_i, t| t.id)
//!     .reorderable(true)
//!     .tab_dividers();
//! ```

use std::cell::RefCell;
use std::rc::Rc;
use teksilo_i18n::lit;

use teksilo_canvas::{Canvas, Point, Rect, Size, SizeProposal};
use teksilo_core::DropFeedback;
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::binding::BindingLevel;
use teksilo_core::build_context::BuildContext;
use teksilo_core::drag_payload::{DragPayload, DropOutcome};
use teksilo_core::event::{EventResponse, ScrollDelta, WidgetEvent};
use teksilo_core::overlay::OverlayPlacement;
use teksilo_core::signal::Signal;
use teksilo_core::widget::{
    EventContext, LayoutContext, LayoutResponse, PaintContext, PendingChild, Widget,
    WidgetPlacement,
};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;
use teksilo_data::{ListDataSource, ListModel};
use teksilo_i18n::LocalizedString;
use teksilo_tokens::Easing;

use crate::list_source::ListSource;
use crate::primitives::FixedSize;
use crate::scroll_area::{ScrollArea, ScrollBarMode, ScrollBarPolicy};
use crate::tab_widget::delegate::{
    TabBarOrientation, TabDelegate, TabDisplayMode, TabOverflowButton, TabSizing,
};
use crate::tab_widget::header::{HeaderShared, TabHeader, TabHeaderConfig};
use crate::tab_widget::id::TabId;
use crate::{
    Button, ButtonVariant, Expand, HStack, IconButton, IconButtonSize, IconWidget, ListView, Panel,
    PopoverIconButton,
};
use teksilo_core::accesskit::HasPopup;
use teksilo_tokens::{BorderRole, SurfaceRole, TextRole};

use std::collections::HashMap;

/// Default min width for an unpinned tab.
pub const DEFAULT_MIN_TAB_WIDTH: f32 = 96.0;
/// Default max width for an unpinned tab.
pub const DEFAULT_MAX_TAB_WIDTH: f32 = 240.0;
/// Default spacing between tab headers in the row. `0.0` so tabs sit
/// flush against each other (Firefox / Chrome convention) — adjacent
/// tab boundaries are visually separated by the per-tab borders, not
/// by an empty gap.
pub const DEFAULT_TAB_SPACING: f32 = 0.0;
/// Default spacing between the bar's leading slot, scroll area, and
/// trailing slot.
pub const DEFAULT_BAR_SLOT_SPACING: f32 = 8.0;
/// Default width (in dp) of a pinned tab — icon-only squares.
pub const DEFAULT_PINNED_TAB_WIDTH: f32 = 32.0;
/// Distance (in dp) one click of a scroll arrow advances the
/// horizontal scroll position. Roughly one tab's worth.
const SCROLL_ARROW_STEP: f32 = 120.0;
/// Pixels-per-line conversion for `ScrollDelta::Lines`. Mouse wheels
/// send their deltas in units of "lines"; the bar treats one line as
/// roughly one tab-width's worth of scrolling so a single notch
/// scrolls one full tab into view.
const WHEEL_LINE_PIXELS: f32 = 64.0;
/// Edge-zone width inside which `on_drag_tick` ramps the auto-scroll
/// velocity up to [`DRAG_MAX_VELOCITY`].
const DRAG_EDGE_ZONE: f32 = 32.0;
/// Cap on per-frame auto-scroll velocity during a drag at the bar
/// edges.
const DRAG_MAX_VELOCITY: f32 = 12.0;

/// Drag payload published by a tab header when the user starts
/// dragging it.
///
/// Generic over the bar's item type `T` so a `TabBar<T>` only ever
/// downcasts (`get_typed::<TabBarDragData<T>>()`) a drag started by
/// another `TabBar<T>` — a drag from a `TabBar<OtherT>` simply never
/// matches, giving cross-bar transfer type-safety for free.
///
/// Two consumers:
/// - **Intra-bar reorder**: the bar's own `on_drop` matches
///   `source_bar_id == self_id` and uses `source_index` to drive
///   `move_item`. `item` is unused on this path (and may be `None`).
/// - **Cross-bar transfer**: a *different* bar that opted in via
///   [`accept_external_tabs`](TabBar::accept_external_tabs) takes
///   `item` by value and hands it to its
///   [`on_tab_received`](TabBar::on_tab_received) callback. `item` is
///   `Some` only when the source bar opted in *and* the per-tab
///   transferable predicate allows it (static tabs are excluded).
pub struct TabBarDragData<T: 'static> {
    /// Model index of the dragged tab in the *source* bar.
    pub source_index: usize,
    /// Widget id of the source `TabBar`. The receiving bar compares
    /// it to its own id to tell an intra-bar reorder from a
    /// cross-bar transfer.
    pub source_bar_id: WidgetId,
    /// Stable id of the dragged tab — handed to the source bar's
    /// `on_transfer_out` so the app can remove it by id.
    pub source_id: TabId,
    /// A clone of the dragged item, carried for cross-bar transfer.
    /// `None` when the source bar didn't opt into transfer or the tab
    /// is non-transferable (e.g. a static tab).
    pub item: Option<T>,
}

/// A reactive header strip that pulls its tab list from a data source
/// and writes the active tab into a shared `Signal<Option<TabId>>`.
///
/// Selection is **id-based**: the bar holds a stable [`TabId`] per
/// item (extracted via the `id_of` closure passed to the constructor)
/// and the public `selected_id` signal is the source of truth across
/// reorders / removals / locale changes. Internal index-based work
/// (keyboard nav, scroll-to-active, click activation) reads a
/// **private** `selected_index` signal that the bar keeps in
/// bidirectional sync with `selected_id` at build time.
pub struct TabBar<T: 'static> {
    source: ListSource<T>,
    delegate: TabDelegate<T>,
    /// Public selection signal — id-based, stable across reorders.
    selected_id: Signal<Option<TabId>>,
    /// Closure that extracts a stable [`TabId`] from each model item.
    /// Called per-item at every build.
    id_of: Rc<dyn Fn(usize, &T) -> TabId>,
    /// Private index signal used by internal index-based code
    /// (keyboard nav, scroll, click). Synced with `selected_id` at
    /// build time via two `ctx.effect`s installed in [`Widget::build`].
    selected: Signal<usize>,

    orientation: TabBarOrientation,
    sizing: TabSizing,
    tab_display: TabDisplayMode,
    min_tab_width: f32,
    max_tab_width: f32,
    pinned_tab_width: f32,
    spacing: f32,
    /// Optional tab-strip cross-axis extent override (compact bars).
    tab_height: Option<f32>,

    /// All-states surface color/role shorthand applied to every tab
    /// header — the per-state overrides below fall back to this, which
    /// itself falls back to transparent. Default `None`.
    tab_background: Option<teksilo_core::color_prop::ColorProp>,
    /// Background for the **selected** tab (falls back to
    /// `tab_background`, then transparent).
    selected_tab_background: Option<teksilo_core::color_prop::ColorProp>,
    /// Background for the **hovered** (non-selected) tab (falls back to
    /// `tab_background`, then transparent).
    hover_tab_background: Option<teksilo_core::color_prop::ColorProp>,
    /// Background for **idle** tabs (falls back to `tab_background`, then
    /// transparent).
    idle_tab_background: Option<teksilo_core::color_prop::ColorProp>,
    /// Backdrop fill spanning the whole bar strip, painted behind the
    /// headers / slots / arrows. Independent of the per-tab backgrounds.
    /// Default `None` = transparent.
    bar_background: Option<teksilo_core::color_prop::ColorProp>,
    /// Text role used for the label (and matching icon tint) on the
    /// selected tab. Default: `TextRole::Primary`.
    selected_text_role: TextRole,
    /// Text role used for the label (and matching icon tint) on idle
    /// tabs (not selected, not disabled). Default: `TextRole::Secondary`.
    idle_text_role: TextRole,
    /// When `true`, draw a 1 dp divider between consecutive tabs (in both
    /// the scrollable and the pinned strip).
    tab_dividers: bool,
    /// Color of the inter-tab dividers. `None` ⇒ `BorderRole::Divider`.
    tab_divider_color: Option<teksilo_core::color_prop::ColorProp>,
    /// Which edge the active-tab highlight indicator hugs. Default
    /// [`TabIndicatorPosition::OuterEdge`](teksilo_core::styles::TabIndicatorPosition).
    active_indicator: teksilo_core::styles::TabIndicatorPosition,
    /// Per-call style override propagated to every header in the bar.
    /// `None` means "use the theme slot or the bundled `RecipeTabStyle`".
    style_override: Option<teksilo_core::styles::SharedTabStyle>,

    bar_leading_slot: Option<PendingChild>,
    bar_trailing_slot: Option<PendingChild>,

    show_separator: bool,
    show_scroll_arrows: bool,
    overflow_button: TabOverflowButton,
    vertical_wheel_scrolls_horizontally: bool,
    shift_wheel_scrolls_horizontally: bool,

    on_close: Option<Rc<dyn Fn(usize, &mut EventContext)>>,
    reorderable: bool,
    on_reorder: Option<Rc<dyn Fn(usize, usize, &mut EventContext)>>,
    on_pin_toggle: Option<Rc<dyn Fn(usize, bool, &mut EventContext)>>,

    /// Cross-bar transfer opt-in. When `true`, headers publish an
    /// item-carrying [`TabBarDragData`] (a drag source) AND the bar
    /// accepts foreign tabs as a drop target. Set via
    /// [`accept_external_tabs`](Self::accept_external_tabs).
    accept_external_tabs: bool,
    /// Item-clone closure, installed by
    /// [`accept_external_tabs`](Self::accept_external_tabs) where
    /// `T: Clone`. Captures the `Clone` capability so `build()` (which
    /// is not `T: Clone`-bounded) can produce the carried item clone.
    /// `None` ⇒ payloads carry `item: None` (reorder-only).
    clone_item: Option<Rc<dyn Fn(&T) -> T>>,
    /// Target-side callback: a foreign tab was dropped here. Receives
    /// the moved item, the model insertion index in *this* bar, and
    /// the firing context. The app inserts into its own model.
    on_tab_received: Option<Rc<dyn Fn(T, usize, &mut EventContext)>>,
    /// Source-side callback: one of this bar's tabs was accepted by a
    /// *different* bar. Receives the transferred tab's id; the app
    /// removes it from its own model.
    on_transfer_out: Option<Rc<dyn Fn(TabId, &mut EventContext)>>,
    /// Drop handler for **non-tab** payloads — an in-app foreign drag
    /// (a tree/list row carrying app data) or an OS file/text/URL
    /// drop. Receives the raw payload, the model insertion index, and
    /// the firing context; returns `true` if accepted. Distinct from
    /// [`on_tab_received`](Self::on_tab_received), which only handles
    /// tabs dragged from a peer `TabBar<T>`.
    on_external_drop: Option<Rc<dyn Fn(&DragPayload, usize, &mut EventContext) -> bool>>,
    /// Per-tab transferable predicate. `None` ⇒ all tabs transferable.
    /// `TabWidget` installs one that excludes static tabs.
    transferable_fn: Option<Rc<dyn Fn(usize, &T) -> bool>>,
    /// Set `true` by the bar's own `on_drop` when it consumes a drag
    /// as an intra-bar reorder; read-and-reset by the source header's
    /// `on_drag_ended` to suppress a spurious `on_transfer_out` (which
    /// would otherwise remove the just-reordered tab). `on_drop` runs
    /// before `on_drag_ended` in the same dispatch, so no reset-at-
    /// drag-start is needed.
    self_reorder_flag: Rc<std::cell::Cell<bool>>,

    /// Optional shared buffer the parent `TabWidget<T>` populates with
    /// its content panel ids so the headers can publish the
    /// `controls()` accessibility relation. `None` for stand-alone
    /// `TabBar` use — the headers simply omit the relation in that
    /// case (which is the right semantics: there is no panel to
    /// control).
    panel_ids_buffer: Option<Rc<RefCell<Vec<WidgetId>>>>,

    /// Optional shared buffer the parent `TabWidget<T>` reads after
    /// the bar builds to obtain each header's `WidgetId` (in tab
    /// order). Used to wire the `TabPanel → aria-labelledby → Tab`
    /// accessibility relation on the TabPane side. `None` for
    /// stand-alone `TabBar` use.
    header_ids_buffer: Option<Rc<RefCell<Vec<WidgetId>>>>,

    /// Drop indicator x position in bar-local coords, painted by
    /// `paint()`. `None` means no drag in progress / not dropping
    /// here. Cloned into the on_drag_hover / on_drag_leave handlers
    /// at build time and into the bar's paint via `paint_state`.
    paint_state: PaintState,

    /// "Scroll the active tab into view" plumbing, shared with the
    /// header row. Lives on the bar (not on the row, which is rebuilt
    /// from scratch every pass) so `revealed` remembers across rebuilds
    /// what the strip was last scrolled to.
    reveal: RevealState,

    root_child_id: Option<WidgetId>,

    /// Direct widget-id handles to the bar's natural-width
    /// contributors. In vertical orientation, `layout_response`
    /// probes each at unspecified width to compute the bar's
    /// intrinsic width (max across them), then clamps to
    /// `[min_tab_width, max_tab_width]`. Bypasses the inner
    /// `ScrollArea` whose own `layout_response` echoes its
    /// proposal, which would otherwise let the bar swallow
    /// whatever cross-axis space the parent gave it.
    header_row_id: Option<WidgetId>,
    pinned_strip_id: Option<WidgetId>,
    bar_leading_slot_id: Option<WidgetId>,
    bar_trailing_slot_id: Option<WidgetId>,
    /// The bar's outer stack (slots + arrows + the scroll slot +
    /// dropdown), *inside* the style chrome. A vertical bar measures
    /// this at an unbounded height to recover its natural height —
    /// the scroll slot is an `Expand::vertical`, which reports 0 and
    /// takes its size from surplus, so the stack alone would say the
    /// bar is 0 dp tall. See `natural_height_vertical`.
    outer_stack_id: Option<WidgetId>,
}

#[derive(Clone)]
struct PaintState {
    /// Drop-indicator x in bar-local coords (`Some(x)`) or `None`
    /// when no drag is in progress over the bar. A `Signal` (not a
    /// bare `Cell`) so the `TabStyle`-built chrome painter can bind
    /// to it and repaint when a drag updates the insertion point.
    drop_indicator_x: Signal<Option<f32>>,
    /// Cached bar world bounds recorded by `place_children`. Drop
    /// handlers use the origin to translate world-coords header
    /// bounds into bar-local space, and the size to detect when the
    /// pointer is in the edge auto-scroll zone.
    last_bar_bounds: Rc<std::cell::Cell<Rect>>,
}

impl Default for PaintState {
    fn default() -> Self {
        Self {
            drop_indicator_x: Signal::new(None),
            last_bar_bounds: Rc::new(std::cell::Cell::new(Rect::new(0.0, 0.0, 0.0, 0.0))),
        }
    }
}

impl std::fmt::Debug for PaintState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PaintState")
            .field("drop_indicator_x", &self.drop_indicator_x.get())
            .field("last_bar_bounds", &self.last_bar_bounds.get())
            .finish()
    }
}

/// Below this many logical pixels a reveal is not worth a scroll write —
/// the tab is already flush with the edge it was chasing.
const REVEAL_EPSILON: f32 = 0.5;

/// The enclosing `ScrollArea`'s handles, resolved once it exists.
///
/// The area is built *from* the header row's id, so the row cannot be
/// handed these at construction — [`RevealState::area`] is filled in
/// immediately afterwards, which is still long before any layout runs.
#[derive(Clone)]
struct RevealArea {
    /// Offset along the bar's layout axis: `scroll_x` for a horizontal
    /// bar, `scroll_y` for a vertical one.
    scroll_main: Signal<f32>,
    /// The viewport the area last placed its content into.
    viewport: Rc<std::cell::Cell<Size>>,
}

/// "Scroll the active tab back into view", as an edge-triggered request
/// shared between the bar and its header row.
///
/// A tab activated by pointer or keyboard is revealed for free: both move
/// focus, and the framework's focus follow dispatches `ScrollIntoView` up
/// the ancestor chain. Selection written *programmatically* — an app
/// setting `selected_id`, the overflow dropdown, the AT click path — moves
/// no focus, so without this the active tab can sit outside the strip's
/// viewport indefinitely.
///
/// The bar arms; [`TabHeaderRow`] consumes, because that is where the
/// per-tab extents live.
#[derive(Clone)]
struct RevealState {
    /// Position of the tab to reveal **in unpinned-header space** (the
    /// space the row's extents are indexed by), or `None` when nothing is
    /// pending. Taken by the row's next real measurement.
    pending: Rc<std::cell::Cell<Option<usize>>>,
    /// Bumped on every arm, and bound to the header row at
    /// [`BindingLevel::Relayout`] so arming schedules the layout pass
    /// that consumes it. Without it, a selection change that resizes
    /// nothing would only repaint and the request would sit unread until
    /// some unrelated relayout happened by.
    generation: Signal<u64>,
    /// The tab the strip was last scrolled to. Guards the build-time arm:
    /// a rebuild for an unrelated reason — a locale flip, a retitled tab,
    /// a tab added elsewhere in the strip — must not yank the viewport
    /// back to the active tab after the user scrolled away from it by
    /// hand.
    revealed: Rc<std::cell::Cell<Option<TabId>>>,
    /// Set once the enclosing `ScrollArea` is built. See [`RevealArea`].
    area: Rc<RefCell<Option<RevealArea>>>,
}

impl Default for RevealState {
    fn default() -> Self {
        Self {
            pending: Rc::new(std::cell::Cell::new(None)),
            generation: Signal::new(0),
            revealed: Rc::new(std::cell::Cell::new(None)),
            area: Rc::new(RefCell::new(None)),
        }
    }
}

impl RevealState {
    /// Request that unpinned header `position` be scrolled into view on
    /// the next layout pass, and schedule that pass.
    fn arm(&self, position: usize) {
        self.pending.set(Some(position));
        self.generation.set(self.generation.get().wrapping_add(1));
    }
}

impl std::fmt::Debug for RevealState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RevealState")
            .field("pending", &self.pending.get())
            .field("generation", &self.generation.get())
            .field("revealed", &self.revealed.get())
            .field("area", &self.area.borrow().is_some())
            .finish()
    }
}

impl<T: 'static> std::fmt::Debug for TabBar<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TabBar")
            .field("len", &self.source.len())
            .field("selected", &self.selected.get())
            .field("sizing", &self.sizing)
            .field("min_tab_width", &self.min_tab_width)
            .field("max_tab_width", &self.max_tab_width)
            .finish()
    }
}

impl<T: 'static> TabBar<T> {
    /// Construct a horizontal tab bar from a [`ListModel<T>`].
    /// Default sizing is [`TabSizing::Shared`].
    ///
    /// `selected_id` is the id-based selection signal — written by
    /// the bar on click / keyboard / drag-drop and observable by
    /// callers. `id_of(index, &item)` extracts the stable [`TabId`]
    /// from each model item.
    pub fn horizontal(
        model: ListModel<T>,
        delegate: TabDelegate<T>,
        selected_id: Signal<Option<TabId>>,
        id_of: impl Fn(usize, &T) -> TabId + 'static,
    ) -> Self {
        Self::from_list_source(
            ListSource::from_model(model),
            delegate,
            selected_id,
            Rc::new(id_of),
            TabBarOrientation::Horizontal,
        )
    }

    /// Construct a horizontal tab bar from any [`ListDataSource`].
    /// Default sizing is [`TabSizing::Shared`].
    pub fn horizontal_from_source<S: ListDataSource<Item = T>>(
        source: S,
        delegate: TabDelegate<T>,
        selected_id: Signal<Option<TabId>>,
        id_of: impl Fn(usize, &T) -> TabId + 'static,
    ) -> Self {
        Self::from_list_source(
            ListSource::from_data_source(source),
            delegate,
            selected_id,
            Rc::new(id_of),
            TabBarOrientation::Horizontal,
        )
    }

    /// Construct a vertical tab bar from a [`ListModel<T>`]. Tabs
    /// stack top-to-bottom as horizontal pills (icon + label + close
    /// button arranged left-to-right within each pill). Default
    /// sizing is [`TabSizing::Shared`] — uniform pill heights.
    pub fn vertical(
        model: ListModel<T>,
        delegate: TabDelegate<T>,
        selected_id: Signal<Option<TabId>>,
        id_of: impl Fn(usize, &T) -> TabId + 'static,
    ) -> Self {
        Self::from_list_source(
            ListSource::from_model(model),
            delegate,
            selected_id,
            Rc::new(id_of),
            TabBarOrientation::Vertical,
        )
    }

    /// Construct a vertical tab bar from any [`ListDataSource`].
    pub fn vertical_from_source<S: ListDataSource<Item = T>>(
        source: S,
        delegate: TabDelegate<T>,
        selected_id: Signal<Option<TabId>>,
        id_of: impl Fn(usize, &T) -> TabId + 'static,
    ) -> Self {
        Self::from_list_source(
            ListSource::from_data_source(source),
            delegate,
            selected_id,
            Rc::new(id_of),
            TabBarOrientation::Vertical,
        )
    }

    pub(crate) fn from_list_source(
        source: ListSource<T>,
        delegate: TabDelegate<T>,
        selected_id: Signal<Option<TabId>>,
        id_of: Rc<dyn Fn(usize, &T) -> TabId>,
        orientation: TabBarOrientation,
    ) -> Self {
        Self {
            source,
            delegate,
            selected_id,
            id_of,
            selected: Signal::new(0_usize),
            orientation,
            sizing: TabSizing::Shared,
            tab_display: TabDisplayMode::Auto,
            min_tab_width: DEFAULT_MIN_TAB_WIDTH,
            max_tab_width: DEFAULT_MAX_TAB_WIDTH,
            pinned_tab_width: DEFAULT_PINNED_TAB_WIDTH,
            spacing: DEFAULT_TAB_SPACING,
            tab_height: None,
            tab_background: None,
            selected_tab_background: None,
            hover_tab_background: None,
            idle_tab_background: None,
            bar_background: None,
            selected_text_role: TextRole::Primary,
            idle_text_role: TextRole::Secondary,
            tab_dividers: false,
            tab_divider_color: None,
            active_indicator: teksilo_core::styles::TabIndicatorPosition::OuterEdge,
            style_override: None,
            bar_leading_slot: None,
            bar_trailing_slot: None,
            show_separator: true,
            show_scroll_arrows: true,
            overflow_button: TabOverflowButton::Auto,
            vertical_wheel_scrolls_horizontally: true,
            shift_wheel_scrolls_horizontally: true,
            on_close: None,
            reorderable: false,
            on_reorder: None,
            on_pin_toggle: None,
            accept_external_tabs: false,
            clone_item: None,
            on_tab_received: None,
            on_transfer_out: None,
            on_external_drop: None,
            transferable_fn: None,
            self_reorder_flag: Rc::new(std::cell::Cell::new(false)),
            panel_ids_buffer: None,
            header_ids_buffer: None,
            paint_state: PaintState::default(),
            reveal: RevealState::default(),
            root_child_id: None,
            header_row_id: None,
            pinned_strip_id: None,
            bar_leading_slot_id: None,
            bar_trailing_slot_id: None,
            outer_stack_id: None,
        }
    }

    /// Override the per-tab sizing strategy. See [`TabSizing`].
    pub fn tab_sizing(mut self, mode: TabSizing) -> Self {
        self.sizing = mode;
        self
    }

    /// The natural height of a **vertical** bar: the headers' own extent
    /// plus whatever the non-scrolling slots (pinned strip, scroll
    /// arrows, overflow dropdown, leading / trailing slot widgets) and
    /// their spacings contribute.
    ///
    /// The outer stack can't answer this on its own: the scroll slot is
    /// an `Expand::vertical`, which reports 0 at its natural size and
    /// grows from surplus, so measuring the stack at an unbounded height
    /// yields "everything except the tabs". Adding the header column's
    /// own unbounded height back gives the whole bar — no duplicate
    /// spacing arithmetic (the stack already counted it).
    ///
    /// Without this a vertical bar next to a flexible sibling (the
    /// `Spacer` that pins a nav to the bottom of a sidebar) collapses to
    /// 0 dp and its pills spill out of it.
    fn natural_height_vertical(&self, width: Option<f32>, ctx: &LayoutContext) -> f32 {
        let probe = SizeProposal {
            width,
            height: None,
        };
        let slots_h = self
            .outer_stack_id
            .and_then(|id| ctx.child_size(id, probe))
            .map(|s| s.height)
            .unwrap_or(0.0);
        let headers_h = self
            .header_row_id
            .and_then(|id| ctx.child_size(id, probe))
            .map(|s| s.height)
            .unwrap_or(0.0);
        slots_h + headers_h
    }

    /// Choose what every tab shows — icon, label, or both. See
    /// [`TabDisplayMode`]. Default [`TabDisplayMode::Auto`] (render each tab as
    /// its `TabInfo` declares).
    pub fn tab_display(mut self, mode: TabDisplayMode) -> Self {
        self.tab_display = mode;
        self
    }

    /// Minimum width (in dp) any unpinned tab will be drawn at.
    /// Default: [`DEFAULT_MIN_TAB_WIDTH`].
    ///
    /// In **horizontal** orientation this clamps the **per-tab** width.
    /// In **vertical** orientation every tab is forced to the bar's
    /// cross-axis width, so the same knob defines the bar's minimum
    /// width — the sidebar adapts to the widest piece of bar content
    /// (tab labels or a slot widget) and never shrinks below this floor.
    /// Vertical pill heights stay at `theme.components.tab.editor_tab_height`
    /// regardless of this knob.
    ///
    /// Under [`TabSizing::Fill`] a **vertical** bar takes the width it is
    /// offered outright, so this floor no longer applies to it; in a
    /// **horizontal** `Fill` bar it still does (the tabs overflow into
    /// scroll rather than squeeze below it).
    pub fn min_tab_width(mut self, dp: f32) -> Self {
        self.min_tab_width = dp.max(0.0);
        self
    }

    /// Override the tab-strip cross-axis extent (the strip height for a
    /// horizontal bar; the per-tab pill height for a vertical one). `None`
    /// keeps the style's `editor_tab_height`. Use for a compact bar.
    pub fn tab_bar_height(mut self, dp: f32) -> Self {
        self.tab_height = Some(dp.max(0.0));
        self
    }

    /// Maximum width (in dp) any unpinned tab will be drawn at — long
    /// labels truncate with an ellipsis at this width.
    /// Default: [`DEFAULT_MAX_TAB_WIDTH`].
    ///
    /// In **horizontal** orientation this clamps the **per-tab** width.
    /// In **vertical** orientation it caps the whole sidebar's width —
    /// see [`min_tab_width`](Self::min_tab_width) for the symmetric
    /// adapt-to-content rule.
    ///
    /// [`TabSizing::Fill`] ignores this cap in both orientations — filling
    /// the bar is the point, and a cap would leave exactly the slack the
    /// mode exists to remove.
    pub fn max_tab_width(mut self, dp: f32) -> Self {
        self.max_tab_width = dp.max(0.0);
        self
    }

    /// Override the spacing (in dp) between adjacent tab headers in
    /// the row. Default: [`DEFAULT_TAB_SPACING`].
    pub fn tab_spacing(mut self, dp: f32) -> Self {
        self.spacing = dp.max(0.0);
        self
    }

    /// Width (in dp) of an icon-only pinned tab.
    /// Default: [`DEFAULT_PINNED_TAB_WIDTH`].
    pub fn pinned_tab_width(mut self, dp: f32) -> Self {
        self.pinned_tab_width = dp.max(0.0);
        self
    }

    /// All-states shorthand for the per-tab background — every tab
    /// (selected, idle, hovered) paints this unless a per-state override
    /// below is set. Accepts any `Color`, `SurfaceRole`, or `Signal<Color>`
    /// (via [`ColorProp`](teksilo_core::color_prop::ColorProp)).
    /// Default `None` = transparent. To tint the bar's backdrop instead,
    /// use [`bar_background`](Self::bar_background).
    pub fn tab_background(mut self, color: impl Into<teksilo_core::color_prop::ColorProp>) -> Self {
        self.tab_background = Some(color.into());
        self
    }

    /// Background for the **selected** tab. Falls back to
    /// [`tab_background`](Self::tab_background), then transparent.
    pub fn selected_tab_background(
        mut self,
        color: impl Into<teksilo_core::color_prop::ColorProp>,
    ) -> Self {
        self.selected_tab_background = Some(color.into());
        self
    }

    /// Background for the **hovered** (non-selected) tab. Falls back to
    /// [`tab_background`](Self::tab_background), then transparent.
    pub fn hover_tab_background(
        mut self,
        color: impl Into<teksilo_core::color_prop::ColorProp>,
    ) -> Self {
        self.hover_tab_background = Some(color.into());
        self
    }

    /// Background for **idle** tabs (not selected, not hovered). Falls back
    /// to [`tab_background`](Self::tab_background), then transparent.
    pub fn idle_tab_background(
        mut self,
        color: impl Into<teksilo_core::color_prop::ColorProp>,
    ) -> Self {
        self.idle_tab_background = Some(color.into());
        self
    }

    /// Set the backdrop fill spanning the whole bar strip (behind the
    /// headers, slots, and scroll arrows). Independent of the per-tab
    /// backgrounds. Accepts any `Color`, `SurfaceRole`, or `Signal<Color>`.
    /// Default `None` = transparent.
    pub fn bar_background(mut self, color: impl Into<teksilo_core::color_prop::ColorProp>) -> Self {
        self.bar_background = Some(color.into());
        self
    }

    /// Draw a 1 dp divider between consecutive tabs (scrollable and pinned
    /// strips). Off by default. See [`tab_divider_color`](Self::tab_divider_color).
    pub fn tab_dividers(mut self) -> Self {
        self.tab_dividers = true;
        self
    }

    /// Like [`tab_dividers`](Self::tab_dividers), but with an explicit
    /// colour. Accepts any `Color`, [`BorderRole`],
    /// or `Signal<Color>`. Implies `tab_dividers()`.
    pub fn tab_divider_color(
        mut self,
        color: impl Into<teksilo_core::color_prop::ColorProp>,
    ) -> Self {
        self.tab_dividers = true;
        self.tab_divider_color = Some(color.into());
        self
    }

    /// Choose which edge the active-tab highlight indicator hugs. Default
    /// [`TabIndicatorPosition::OuterEdge`](teksilo_core::styles::TabIndicatorPosition)
    /// (top for horizontal / leading for vertical);
    /// [`InnerEdge`](teksilo_core::styles::TabIndicatorPosition::InnerEdge)
    /// puts it below the label (horizontal) / on the trailing edge (vertical).
    /// Honoured by the default `RecipeTabStyle`; a custom
    /// [`TabStyle`](teksilo_core::styles::TabStyle) may interpret it freely.
    pub fn active_indicator(
        mut self,
        position: teksilo_core::styles::TabIndicatorPosition,
    ) -> Self {
        self.active_indicator = position;
        self
    }

    /// Set the text role used for the label (and matching icon tint)
    /// on the **selected** tab. Default: [`TextRole::Primary`] — the
    /// Int UI editor-strip convention. Override to e.g.
    /// [`TextRole::Accent`] when the strip sits over a tinted surface.
    pub fn selected_text_role(mut self, role: TextRole) -> Self {
        self.selected_text_role = role;
        self
    }

    /// Set the text role used for the label (and matching icon tint)
    /// on **idle** tabs (not selected, not disabled). Default:
    /// [`TextRole::Secondary`]. Disabled tabs always read as
    /// [`TextRole::Disabled`] regardless of this setting.
    pub fn idle_text_role(mut self, role: TextRole) -> Self {
        self.idle_text_role = role;
        self
    }

    /// Override the active [`TabStyle`](teksilo_core::styles::TabStyle)
    /// for every header in this bar. The widget keeps responsibility
    /// for the label / icon / close button composition, the
    /// optional per-state tab backgrounds, and all input handling;
    /// the style only paints the accent indicator and focus ring
    /// chrome via `make_body`. Per-call override > theme slot >
    /// built-in `RecipeTabStyle` default.
    pub fn style(mut self, style: impl teksilo_core::styles::TabStyle) -> Self {
        self.style_override = Some(std::rc::Rc::new(style));
        self
    }

    /// Install a pin-toggle handler called whenever the user crosses
    /// a pinned tab over the unpinned region or vice-versa during a
    /// drag. Receives `(model_index, new_pinned_flag, ctx)`. The
    /// firing [`EventContext`] lets the handler confirm the
    /// transition via a dialog or route it through an intent before
    /// mutating the item; apps decide whether to actually flip the
    /// pinned state.
    pub fn on_pin_toggle(mut self, f: impl Fn(usize, bool, &mut EventContext) + 'static) -> Self {
        self.on_pin_toggle = Some(Rc::new(f));
        self
    }

    /// Bar-level leading slot — a widget rendered before the headers
    /// row (and before any pinned region in later phases).
    pub fn bar_leading_slot(mut self, w: impl Widget + 'static) -> Self {
        self.bar_leading_slot = Some(PendingChild::Deferred(Box::new(w)));
        self
    }

    /// Bar-level leading slot accepting a pre-registered widget id.
    pub fn bar_leading_slot_id(mut self, id: WidgetId) -> Self {
        self.bar_leading_slot = Some(PendingChild::Id(id));
        self
    }

    /// Bar-level trailing slot — a widget rendered after the headers
    /// row (and after any overflow dropdown in later phases).
    pub fn bar_trailing_slot(mut self, w: impl Widget + 'static) -> Self {
        self.bar_trailing_slot = Some(PendingChild::Deferred(Box::new(w)));
        self
    }

    /// Bar-level trailing slot accepting a pre-registered widget id.
    pub fn bar_trailing_slot_id(mut self, id: WidgetId) -> Self {
        self.bar_trailing_slot = Some(PendingChild::Id(id));
        self
    }

    /// Toggle the 1 dp bottom separator the bar paints under the
    /// headers. Default: on.
    pub fn separator(mut self, on: bool) -> Self {
        self.show_separator = on;
        self
    }

    /// Toggle the leading + trailing scroll-arrow buttons. They
    /// auto-show when the headers row overflows the bar's viewport,
    /// and click animates the scroll position by one tab-width.
    /// Default: on.
    pub fn show_scroll_arrows(mut self, on: bool) -> Self {
        self.show_scroll_arrows = on;
        self
    }

    /// When the trailing "show all tabs" overflow dropdown appears — a
    /// `Popover` with a `MenuList` of every tab. Default:
    /// [`TabOverflowButton::Auto`] (shown only when the headers overflow the
    /// viewport). See [`TabOverflowButton`] for `Always` / `Never`.
    pub fn overflow_button(mut self, mode: TabOverflowButton) -> Self {
        self.overflow_button = mode;
        self
    }

    /// Convenience over [`overflow_button`](Self::overflow_button): `true` maps
    /// to [`TabOverflowButton::Always`], `false` to [`TabOverflowButton::Never`].
    /// Prefer `overflow_button(TabOverflowButton::Auto)` for the default
    /// "only when overflowing" behaviour.
    pub fn show_overflow_dropdown(mut self, on: bool) -> Self {
        self.overflow_button = if on {
            TabOverflowButton::Always
        } else {
            TabOverflowButton::Never
        };
        self
    }

    /// On a horizontal bar, treat a plain vertical-wheel event as a
    /// horizontal scroll (Firefox / Chrome convention). Has no
    /// effect on vertical or multi-line bars (those still scroll
    /// vertically). Default: on.
    pub fn vertical_wheel_scrolls_horizontally(mut self, on: bool) -> Self {
        self.vertical_wheel_scrolls_horizontally = on;
        self
    }

    /// `Shift` + vertical wheel forces a horizontal scroll regardless
    /// of orientation. Default: on.
    pub fn shift_wheel_scrolls_horizontally(mut self, on: bool) -> Self {
        self.shift_wheel_scrolls_horizontally = on;
        self
    }

    /// Install a close-tab handler called whenever the user clicks a
    /// closable tab's close button, middle-clicks the tab header, or
    /// presses `Delete` on a focused tab. The handler receives the
    /// firing [`EventContext`] so it can open a confirmation dialog
    /// (`ctx.present_modal(MessageBox::confirm(...))`), dispatch an
    /// intent, or otherwise route the close request through the
    /// framework. To veto the close, do nothing in the handler; to
    /// confirm-then-close, run the confirmation flow and only mutate
    /// the underlying model on accept.
    ///
    /// If unset and the bar is backed by a [`ListModel<T>`], the
    /// default behavior is to remove the item at the given index
    /// from the model (no confirmation, no ctx needed for that path).
    pub fn on_close(mut self, f: impl Fn(usize, &mut EventContext) + 'static) -> Self {
        self.on_close = Some(Rc::new(f));
        self
    }

    /// Enable drag-to-reorder. Each tab header becomes a drag source
    /// and the bar accepts drops anywhere along the headers row,
    /// painting an insertion-line indicator at the would-be
    /// position. On drop the bar calls [`on_reorder`](Self::on_reorder)
    /// — falling back to `ListModel::move_item` when the bar is
    /// backed by a `ListModel<T>` and no explicit handler is set.
    /// Default: off.
    pub fn reorderable(mut self, on: bool) -> Self {
        self.reorderable = on;
        self
    }

    /// Install a reorder handler called whenever the user drag-drops
    /// a tab to a new position. Receives `(from, to, ctx)` —
    /// `from`/`to` are model indices and `ctx` is the firing
    /// [`EventContext`] so the handler can open a confirmation
    /// dialog or dispatch an intent before persisting the move.
    /// Implies [`reorderable(true)`](Self::reorderable).
    pub fn on_reorder(mut self, f: impl Fn(usize, usize, &mut EventContext) + 'static) -> Self {
        self.on_reorder = Some(Rc::new(f));
        self.reorderable = true;
        self
    }

    /// Opt into cross-bar tab transfer. When enabled, this bar's
    /// headers become transfer drag sources (their drag payload
    /// carries a clone of the dragged item) **and** the bar accepts
    /// tabs dragged from *other* `TabBar<T>`s, painting the same
    /// insertion-line indicator as an intra-bar reorder.
    ///
    /// Requires `T: Clone` — the dragged item is cloned into the
    /// payload (cheap for handle-like `T` whose heavy state lives
    /// behind an `Rc`). Default: off.
    ///
    /// Pair with [`on_tab_received`](Self::on_tab_received) (this bar,
    /// as a drop target — insert the item into your model) and
    /// [`on_transfer_out`](Self::on_transfer_out) (the source bar —
    /// remove the tab from your model).
    pub fn accept_external_tabs(mut self, on: bool) -> Self
    where
        T: Clone,
    {
        self.accept_external_tabs = on;
        self.clone_item = if on {
            Some(Rc::new(|t: &T| t.clone()))
        } else {
            None
        };
        self
    }

    /// Install the target-side callback fired when a foreign tab is
    /// dropped onto this bar. Receives `(item, insertion_index, ctx)`
    /// — the moved item (taken by value from the drag payload), the
    /// model index in *this* bar where it should land, and the firing
    /// context. The app inserts the item into its own model. Implies
    /// [`accept_external_tabs(true)`](Self::accept_external_tabs).
    pub fn on_tab_received(mut self, f: impl Fn(T, usize, &mut EventContext) + 'static) -> Self
    where
        T: Clone,
    {
        self.on_tab_received = Some(Rc::new(f));
        if !self.accept_external_tabs {
            self = self.accept_external_tabs(true);
        }
        self
    }

    /// Install the source-side callback fired after one of this bar's
    /// tabs has been accepted by a *different* bar. Receives the
    /// transferred tab's [`TabId`]; the app removes it from its own
    /// model. Not fired for intra-bar reorders (those go through
    /// [`on_reorder`](Self::on_reorder)) or rejected / cancelled
    /// drags. Implies [`accept_external_tabs(true)`](Self::accept_external_tabs).
    pub fn on_transfer_out(mut self, f: impl Fn(TabId, &mut EventContext) + 'static) -> Self
    where
        T: Clone,
    {
        self.on_transfer_out = Some(Rc::new(f));
        if !self.accept_external_tabs {
            self = self.accept_external_tabs(true);
        }
        self
    }

    /// Accept **non-tab** drops onto the bar — an in-app foreign drag
    /// (e.g. a file dragged from a `TreeView`, carrying app data) or an
    /// OS file/text/URL drop. The bar paints the same insertion-line
    /// indicator while such a payload hovers, and on drop calls `f`
    /// with the raw [`DragPayload`], the model insertion index, and the
    /// firing context. Return `true` if accepted — the app inspects the
    /// payload (`get_typed::<T>()` / `files()` / `text()` / `uris()`)
    /// and mints whatever it needs (e.g. opens a tab).
    ///
    /// Independent of [`accept_external_tabs`](Self::accept_external_tabs):
    /// a bar can accept foreign tabs, non-tab payloads, both, or
    /// neither. OS drops additionally require the app to have called
    /// `TeksiloAppBuilder::install_external_dnd()`.
    ///
    /// Note: the hover indicator is *optimistic* — it shows for any
    /// non-tab payload while this handler is installed; `f`'s return
    /// value is authoritative at drop time.
    pub fn on_external_drop(
        mut self,
        f: impl Fn(&DragPayload, usize, &mut EventContext) -> bool + 'static,
    ) -> Self {
        self.on_external_drop = Some(Rc::new(f));
        self
    }

    /// Internal hook: install the non-tab drop handler. `pub(crate)`
    /// because `TabWidget` wires its own index-translation layer.
    pub(crate) fn on_external_drop_rc(
        mut self,
        f: Rc<dyn Fn(&DragPayload, usize, &mut EventContext) -> bool>,
    ) -> Self {
        self.on_external_drop = Some(f);
        self
    }

    /// Internal hook: install a per-tab transferable predicate.
    /// `TabWidget` uses it to exclude static tabs (whose content has
    /// no factory on a receiving bar) from cross-bar transfer. When
    /// the predicate returns `false`, the tab's drag payload carries
    /// `item: None` and a foreign bar rejects the drop.
    pub(crate) fn with_transferable_predicate(
        mut self,
        f: impl Fn(usize, &T) -> bool + 'static,
    ) -> Self {
        self.transferable_fn = Some(Rc::new(f));
        self
    }

    /// Internal hook: install the source-side transfer-out callback.
    /// `pub(crate)` because `TabWidget` wires its own translation
    /// layer; the public entry point is on `TabWidget`.
    pub(crate) fn on_transfer_out_rc(mut self, f: Rc<dyn Fn(TabId, &mut EventContext)>) -> Self {
        self.on_transfer_out = Some(f);
        self
    }

    /// Internal hook: install the target-side received callback.
    /// `pub(crate)` because `TabWidget` wires its own translation
    /// layer; the public entry point is on `TabWidget`.
    pub(crate) fn on_tab_received_rc(mut self, f: Rc<dyn Fn(T, usize, &mut EventContext)>) -> Self {
        self.on_tab_received = Some(f);
        self
    }

    /// Internal hook used by `TabWidget<T>` to share a panel-ids
    /// buffer with this bar. The wrapping widget passes its
    /// `Switcher`'s captured panel ids in; the headers read them in
    /// `accessibility()` to publish the Tab → TabPanel `controls()`
    /// relation.
    pub(crate) fn with_panel_ids(mut self, buffer: Rc<RefCell<Vec<WidgetId>>>) -> Self {
        self.panel_ids_buffer = Some(buffer);
        self
    }

    /// Share the bar's header-ids buffer with the parent so each
    /// `TabPane` can wire its `aria-labelledby` relation to the
    /// header at the matching index. Populated by `build()` once
    /// every header has been added to the arena; readers must
    /// `borrow()` after the bar's build pass.
    pub(crate) fn with_header_ids(mut self, buffer: Rc<RefCell<Vec<WidgetId>>>) -> Self {
        self.header_ids_buffer = Some(buffer);
        self
    }
}

impl<T: 'static> Widget for TabBar<T> {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        // Rebuild on data-source changes. We store a `version: Signal<u64>`
        // bound at `BindingLevel::Rebuild`; the observer increments it
        // for every `DataChange`. Lifetime of the observer is tied to
        // this build pass via `ctx.own_handle(...)`.
        let self_id = ctx.self_id();
        let version = ctx.signal(0u64);
        version.bind_to(self_id, ctx.binding_registry(), BindingLevel::Rebuild);

        let data_ver = Rc::new(std::cell::Cell::new(0_u64));
        let observer_handle = (self.source.observe_fn)(Box::new({
            let version = version.clone();
            let dv = data_ver.clone();
            move |_change| {
                let next = dv.get().wrapping_add(1);
                dv.set(next);
                version.set(next);
            }
        }));
        ctx.own_handle(observer_handle);

        // Snapshot enabled + pinned flags up front. Headers need
        // the full enabled vector (for arrow-key skip-over) and we
        // need pinned[i] to partition the layout into pinned strip
        // vs scrollable region. The `ListSource::with_item_fn` API
        // is widget-shaped, so we side-channel the booleans through
        // a `Cell` and discard the throwaway widget it produces.
        let n = self.source.len();
        let mut enabled_tabs = Vec::with_capacity(n);
        let mut pinned_tabs: Vec<bool> = Vec::with_capacity(n);
        for i in 0..n {
            let cell = std::cell::Cell::new((true, false));
            (self.source.with_item_fn)(i, &|item| {
                cell.set((
                    self.delegate.resolve_enabled(i, item),
                    self.delegate.resolve_pinned(i, item),
                ));
                Box::new(EnabledProbe) as Box<dyn Widget>
            });
            let (e, p) = cell.get();
            enabled_tabs.push(e);
            pinned_tabs.push(p);
        }
        let enabled_tabs = Rc::new(enabled_tabs);

        // ── Bidirectional id ↔ index selection sync ────────────────
        //
        // The bar's PUBLIC API is id-based (`selected_id`); its
        // internal index-based code (keyboard, scroll, click) reads
        // `selected` (the private index signal). At build time we:
        //
        //   1. Compute id↔index lookup tables from the live model
        //      via `id_of`.
        //   2. Pre-build sync: bring the two signals into agreement —
        //      valid id wins, stale id falls back to the
        //      previously-selected index clamped into range
        //      (positional fallback = next neighbor of the closed
        //      tab; browser convention).
        //   3. Install two `ctx.effect`s for steady-state propagation:
        //      external id changes → index, internal index changes
        //      (from header click / keyboard) → id. No-op guards
        //      prevent ping-pong.
        let mut id_to_index: HashMap<TabId, usize> = HashMap::with_capacity(n);
        let mut index_to_id: Vec<TabId> = Vec::with_capacity(n);
        for i in 0..n {
            let cell: std::cell::Cell<Option<TabId>> = std::cell::Cell::new(None);
            (self.source.with_item_fn)(i, &|item| {
                cell.set(Some((self.id_of)(i, item)));
                Box::new(EnabledProbe) as Box<dyn Widget>
            });
            if let Some(id) = cell.get() {
                id_to_index.insert(id, i);
                index_to_id.push(id);
            }
        }
        let id_to_index = Rc::new(id_to_index);
        let index_to_id = Rc::new(index_to_id);

        if n > 0 {
            let valid = self
                .selected_id
                .get()
                .and_then(|id| id_to_index.get(&id).copied());
            if let Some(target_idx) = valid {
                if self.selected.get() != target_idx {
                    self.selected.set(target_idx);
                }
            } else {
                let clamped = self.selected.get().min(n - 1);
                if self.selected.get() != clamped {
                    self.selected.set(clamped);
                }
                let new_id = index_to_id[clamped];
                if self.selected_id.get() != Some(new_id) {
                    self.selected_id.set(Some(new_id));
                }
            }
        } else if self.selected_id.get().is_some() {
            self.selected_id.set(None);
        }

        let id_to_idx_for_eff = id_to_index.clone();
        let idx_for_id_eff = self.selected.clone();
        ctx.effect(&self.selected_id, move |maybe_id| {
            if let Some(id) = maybe_id
                && let Some(&i) = id_to_idx_for_eff.get(id)
                && idx_for_id_eff.get() != i
            {
                idx_for_id_eff.set(i);
            }
        });
        let idx_to_id_for_eff = index_to_id.clone();
        let id_for_idx_eff = self.selected_id.clone();
        ctx.effect(&self.selected, move |i| {
            let new_id = idx_to_id_for_eff.get(*i).copied();
            if id_for_idx_eff.get() != new_id {
                id_for_idx_eff.set(new_id);
            }
        });

        let header_ids_buf = self
            .header_ids_buffer
            .clone()
            .unwrap_or_else(|| Rc::new(RefCell::new(Vec::with_capacity(n))));
        // If a parent provided a pre-allocated buffer (e.g.
        // `TabWidget` rebuilding after a dynamic-model mutation),
        // clear stale entries so the new tab order replaces — never
        // appends to — the prior pass.
        header_ids_buf.borrow_mut().clear();
        let panel_ids_buf = self
            .panel_ids_buffer
            .clone()
            .unwrap_or_else(|| Rc::new(RefCell::new(Vec::new())));
        let shared = Rc::new(HeaderShared {
            header_ids: header_ids_buf.clone(),
            panel_ids: panel_ids_buf,
            enabled_tabs: enabled_tabs.clone(),
        });

        // Pinned tabs render in a leading non-scrolling strip;
        // unpinned tabs go inside the scrollable TabHeaderRow.
        // We accumulate both lists here, then compose the row_outer
        // with the strips in the right order below.
        let mut pinned_header_ids: Vec<WidgetId> = Vec::new();
        let mut unpinned_header_ids: Vec<WidgetId> = Vec::with_capacity(n);
        // Maps each unpinned-region position to its index in the
        // **model**. Used by the drop handler to translate the
        // `insertion_index_for(...)` result (which is in unpinned
        // space — `header_bounds_buf` only contains the unpinned
        // row's bounds) to a model index that `move_item` can
        // consume directly.
        let mut unpinned_to_model: Vec<usize> = Vec::with_capacity(n);
        // Collected per-tab labels are reused by the overflow
        // dropdown's MenuList. Resolved at build time → re-resolved on
        // every data-source change (the bar rebuilds via `version`)
        // and on every locale change (because the dropdown's
        // MenuItems consume `LocalizedString` directly, which carries
        // its own reactive resolver).
        let mut header_labels: Vec<LocalizedString> = Vec::with_capacity(n);

        // Reorder handler. Explicit `on_reorder` wins; otherwise
        // fall back to the source's `move_item_fn` (populated for
        // ListModel-backed bars).
        //
        // No pre-emptive `selected.set(...)` here: selection is
        // **id-based**. The id stored in `selected_id` is unchanged
        // by a reorder (the same tab is just at a different index),
        // and the bar's pre-build sync re-resolves the id → index
        // mapping during the rebuild that the model mutation
        // triggers. Writing the bar's private `selected` index
        // signal *before* the move would fire the index → id
        // effect against the pre-move `index_to_id` map and stamp
        // the wrong id into `selected_id`, which the post-rebuild
        // sync would then promote — causing the active tab to
        // change visually (and the content pane to fall out of
        // sync) on every drag.
        let reorder_handler: Option<Rc<dyn Fn(usize, usize, &mut EventContext)>> =
            if self.reorderable {
                if let Some(explicit) = self.on_reorder.clone() {
                    Some(explicit)
                } else {
                    self.source.move_item_fn.clone().map(|move_fn| {
                        Rc::new(move |from: usize, to: usize, _ctx: &mut EventContext| {
                            (move_fn)(from, to);
                        }) as Rc<dyn Fn(usize, usize, &mut EventContext)>
                    })
                }
            } else {
                None
            };

        // Close handler. The explicit `on_close` overrides everything;
        // otherwise we fall back to the source's `remove_item_fn`
        // (populated when backed by a `ListModel`) and lift it into
        // the ctx-accepting shape by ignoring ctx. Same id-based
        // discipline as reorder: don't pre-empt the index signal.
        // After model.remove the rebuild's pre-build sync handles
        // both the "selected id still valid" case (re-indexes to
        // the survivor) and the "selected id stale" case (stale-id
        // fallback picks the next neighbor, browser convention).
        let close_handler: Option<Rc<dyn Fn(usize, &mut EventContext)>> =
            if let Some(explicit) = self.on_close.clone() {
                Some(explicit)
            } else {
                self.source.remove_item_fn.clone().map(|remove| {
                    Rc::new(move |i: usize, _ctx: &mut EventContext| {
                        (remove)(i);
                    }) as Rc<dyn Fn(usize, &mut EventContext)>
                })
            };
        for i in 0..n {
            // Build the TabHeader for index i. The data-source
            // `with_item_fn` requires a `Fn(&T) -> Box<dyn Widget>`
            // closure; we use it as the bridge to construct a
            // `Box<TabHeader>` from the resolved delegate fields.
            let is_pinned = pinned_tabs[i];
            let selected = self.selected.clone();
            let shared_for_header = shared.clone();
            // Pinned tabs use the fixed pinned width; non-pinned use
            // the bar's `[min, max]` clamp.
            let (min_w, max_w) = if is_pinned {
                (self.pinned_tab_width, self.pinned_tab_width)
            } else {
                (self.min_tab_width, self.max_tab_width)
            };
            let label_capture: Rc<RefCell<Option<LocalizedString>>> = Rc::new(RefCell::new(None));
            let label_capture_clone = label_capture.clone();
            let close_handler_for_tab = close_handler.clone();
            let header = (self.source.with_item_fn)(i, &|item| -> Box<dyn Widget> {
                let label = self.delegate.resolve_label(i, item);
                // Capture the *original* title (pre display-mode transform) so
                // the overflow dropdown / a11y always read the real name even in
                // icon-only mode.
                *label_capture_clone.borrow_mut() = Some(label.clone());
                let icon = self.delegate.resolve_icon(i, item);
                let leading_slot = self.delegate.resolve_leading(i, item);
                let trailing_slot = self.delegate.resolve_trailing(i, item);
                let tooltip = self.delegate.resolve_tooltip(i, item);
                // Preserve the original title as the accessible name before the
                // display mode may blank the visible label (icon-only tabs).
                let at_name = label.clone();
                // Apply the bar-level display mode (icon / text / icon+text).
                let (label, icon, tooltip) =
                    apply_tab_display(self.tab_display, label, icon, tooltip);
                let rich_tooltip = self.delegate.resolve_rich_tooltip(i, item);
                let composite_tooltip = self.delegate.resolve_composite_tooltip(i, item);
                let context_menu_factory = self.delegate.resolve_context_menu(i, item);
                let enabled = self.delegate.resolve_enabled(i, item);
                let closable = self.delegate.resolve_closable(i, item);
                let on_close: Option<Rc<dyn Fn(&mut EventContext)>> = if closable {
                    close_handler_for_tab.clone().map(|f| {
                        Rc::new(move |ctx: &mut EventContext| (f)(i, ctx))
                            as Rc<dyn Fn(&mut EventContext)>
                    })
                } else {
                    None
                };

                let on_reorder_to: Option<Rc<dyn Fn(usize, &mut EventContext)>> = if !is_pinned {
                    reorder_handler.clone().map(|reorder| {
                        Rc::new(move |to: usize, ctx: &mut EventContext| (reorder)(i, to, ctx))
                            as Rc<dyn Fn(usize, &mut EventContext)>
                    })
                } else {
                    None
                };

                // A header is a drag source when reordering is on OR
                // cross-bar transfer is enabled. Build the payload
                // factory here (we have `&item` in scope): it carries
                // the source identity always, and a clone of the item
                // when transfer is enabled and the tab is transferable
                // (the `clone_item` closure encapsulates `T: Clone` so
                // `build()` need not be bounded on it).
                let is_drag_source = reorder_handler.is_some() || self.accept_external_tabs;
                let make_drag_payload: Option<Rc<dyn Fn() -> DragPayload>> = if is_drag_source {
                    let tab_id = (self.id_of)(i, item);
                    let transferable = self.transferable_fn.as_ref().is_none_or(|f| f(i, item));
                    let item_payload: Option<(T, Rc<dyn Fn(&T) -> T>)> = if transferable {
                        self.clone_item.as_ref().map(|cf| ((cf)(item), cf.clone()))
                    } else {
                        None
                    };
                    let src_index = i;
                    let bar_id = self_id;
                    Some(Rc::new(move || {
                        let item = item_payload.as_ref().map(|(it, cf)| (cf)(it));
                        DragPayload::typed(TabBarDragData {
                            source_index: src_index,
                            source_bar_id: bar_id,
                            source_id: tab_id,
                            item,
                        })
                    }) as Rc<dyn Fn() -> DragPayload>)
                } else {
                    None
                };

                // Source-side completion: when one of our tabs is
                // accepted by a *different* bar, fire on_transfer_out.
                // Suppressed for intra-bar reorders via the shared
                // self-reorder flag (set by our own on_drop, which
                // runs before on_drag_ended in the same dispatch).
                let on_drag_ended: Option<Rc<dyn Fn(DropOutcome, &mut EventContext)>> =
                    match (self.accept_external_tabs, self.on_transfer_out.clone()) {
                        (true, Some(transfer_out)) => {
                            let tab_id = (self.id_of)(i, item);
                            let self_reorder = self.self_reorder_flag.clone();
                            Some(
                                Rc::new(move |outcome: DropOutcome, ctx: &mut EventContext| {
                                    if matches!(outcome, DropOutcome::InApp { accepted: true })
                                        && !self_reorder.replace(false)
                                    {
                                        (transfer_out)(tab_id, ctx);
                                    }
                                })
                                    as Rc<dyn Fn(DropOutcome, &mut EventContext)>,
                            )
                        }
                        _ => None,
                    };

                Box::new(TabHeader::new(TabHeaderConfig {
                    label,
                    at_name,
                    icon,
                    leading_slot,
                    trailing_slot,
                    tooltip,
                    rich_tooltip,
                    composite_tooltip,
                    context_menu_factory,
                    // Pinned tabs suppress the close button —
                    // Firefox / Chrome convention. They're closed
                    // via the context menu only.
                    on_close: if is_pinned { None } else { on_close },
                    on_reorder_to,
                    make_drag_payload,
                    on_drag_ended,
                    index: i,
                    initial_enabled: enabled,
                    selected: selected.clone(),
                    shared: shared_for_header.clone(),
                    min_width: min_w,
                    max_width: max_w,
                    pinned: is_pinned,
                    orientation: self.orientation,
                    tab_background: self.tab_background.clone(),
                    selected_tab_background: self.selected_tab_background.clone(),
                    hover_tab_background: self.hover_tab_background.clone(),
                    idle_tab_background: self.idle_tab_background.clone(),
                    selected_text_role: self.selected_text_role,
                    idle_text_role: self.idle_text_role,
                    active_indicator: self.active_indicator,
                    style_override: self.style_override.clone(),
                }))
            });
            // Should never be `None` for `i < len()`, but defend:
            // skipping this index keeps the bar coherent if the source
            // mutated mid-build (e.g., another thread — though the
            // tree is single-threaded today).
            if let Some(header) = header {
                let id = ctx.add_boxed(header);
                if is_pinned {
                    pinned_header_ids.push(id);
                } else {
                    unpinned_header_ids.push(id);
                    unpinned_to_model.push(i);
                }
                header_ids_buf.borrow_mut().push(id);
                if let Some(lbl) = label_capture.borrow_mut().take() {
                    header_labels.push(lbl);
                } else {
                    header_labels.push(lit!(String::new()));
                }
            }
        }
        let unpinned_to_model = Rc::new(unpinned_to_model);
        let model_len = n;

        // ── Scroll-the-active-tab-into-view ───────────────────────────
        //
        // Model index → position in the *unpinned* row, which is the
        // space `TabHeaderRow`'s extents are indexed by. A pinned tab
        // maps to `None`: it lives in the leading strip, which never
        // scrolls, so it is visible by construction.
        let mut model_to_unpinned: Vec<Option<usize>> = vec![None; n];
        for (position, &model_index) in unpinned_to_model.iter().enumerate() {
            model_to_unpinned[model_index] = Some(position);
        }
        let model_to_unpinned = Rc::new(model_to_unpinned);

        // Arm on the way out of a build. Two things reach this point: a
        // selection that changed while the bar was rebuilding anyway (a
        // tab was opened, or closed and its neighbour promoted), and a
        // request armed by the effect below just before the rebuild —
        // whose position was resolved against the *old* tab order, so it
        // is re-resolved here against the new one.
        let selected_target = self.selected_id.get();
        if selected_target.is_some()
            && (self.reveal.revealed.get() != selected_target
                || self.reveal.pending.get().is_some())
        {
            self.reveal.revealed.set(selected_target);
            match model_to_unpinned
                .get(self.selected.get())
                .copied()
                .flatten()
            {
                Some(position) => self.reveal.arm(position),
                None => self.reveal.pending.set(None),
            }
        }

        // Steady state: selection written from outside (an app setting
        // `selected_id`, the overflow dropdown below, the AT click path)
        // moves the index without rebuilding the bar, so the arm above
        // never runs. Neither does the framework's focus follow, which is
        // what reveals a pointer- or keyboard-activated tab for free.
        // This is the case the bar used to have no answer for.
        {
            let reveal = self.reveal.clone();
            let positions = model_to_unpinned.clone();
            let ids = index_to_id.clone();
            ctx.effect(&self.selected, move |index| {
                let target = ids.get(*index).copied();
                if target.is_none() || reveal.revealed.get() == target {
                    return;
                }
                reveal.revealed.set(target);
                match positions.get(*index).copied().flatten() {
                    Some(position) => reveal.arm(position),
                    None => reveal.pending.set(None),
                }
            });
        }

        // ScrollArea wants a fixed `preferred_size.height` so the
        // viewport doesn't get squashed by the focus-ring envelope
        // headers reserve. Snapshot the theme values up front — we
        // don't want to hold a borrow on `ctx` while later code
        // mutates the arena.
        let (header_min_height, motion_duration_normal, motion_easing_standard) = {
            let theme = ctx.theme();
            // `editor_tab_height` is the outer bounds height of a
            // tab header — the focus-ring envelope is reserved
            // inside (see `TabHeader::intrinsic_height`), so the
            // bar's preferred row height is exactly the token (or the
            // `tab_bar_height` override for a compact strip).
            (
                self.tab_height
                    .unwrap_or(crate::styles::recipe_tab_style::TAB_EDITOR_HEIGHT),
                theme.motion.duration_normal,
                theme.motion.easing_standard,
            )
        };

        // Custom row widget: lays out the headers side-by-side with
        // shared-or-independent width semantics. The bounds buffers
        // are shared with the bar's drag-target handlers below so we
        // can map a drop-hover pointer position onto the right tab
        // boundary even when the row scrolls.
        let header_bounds_buf: Rc<RefCell<Vec<Rect>>> =
            Rc::new(RefCell::new(Vec::with_capacity(unpinned_header_ids.len())));
        let row_bounds_buf: Rc<std::cell::Cell<Rect>> =
            Rc::new(std::cell::Cell::new(Rect::new(0.0, 0.0, 0.0, 0.0)));
        // Resolved inter-tab divider colour (used by both the scrollable
        // row's overlay and the pinned strip), or `None` when off.
        let divider_prop: Option<teksilo_core::color_prop::ColorProp> =
            self.tab_dividers.then(|| {
                self.tab_divider_color
                    .clone()
                    .unwrap_or_else(|| BorderRole::Divider.into())
            });
        let row = TabHeaderRow {
            header_ids: unpinned_header_ids.clone(),
            axis: self.orientation,
            sizing: self.sizing,
            min_extent: self.min_tab_width,
            max_extent: self.max_tab_width,
            spacing: self.spacing,
            tab_height: self.tab_height,
            header_bounds_buf: header_bounds_buf.clone(),
            row_bounds_buf: row_bounds_buf.clone(),
            divider: divider_prop.clone().map(|c| (c, self.spacing)),
            overlay_id: None,
            reveal: self.reveal.clone(),
        };
        let row_id = ctx.add(row);
        self.header_row_id = Some(row_id);

        let scroll = match self.orientation {
            TabBarOrientation::Horizontal => ScrollArea::from_id(row_id)
                .scroll_bar_style(ScrollBarMode::Thin)
                .vertical_scroll_bar_policy(ScrollBarPolicy::AlwaysOff)
                .horizontal_scroll_bar_policy(ScrollBarPolicy::AsNeeded)
                .widget_resizable(true)
                .preferred_size(0.0, header_min_height),
            TabBarOrientation::Vertical => ScrollArea::from_id(row_id)
                .scroll_bar_style(ScrollBarMode::Overlay)
                .horizontal_scroll_bar_policy(ScrollBarPolicy::AlwaysOff)
                .vertical_scroll_bar_policy(ScrollBarPolicy::AsNeeded)
                .widget_resizable(true),
        };
        // Capture scroll signals BEFORE moving the ScrollArea into
        // the arena — drives arrow visibility and the wheel-mapping
        // handler. `scroll_x` / `max_scroll_x` for horizontal,
        // `scroll_y` / `max_scroll_y` for vertical.
        let scroll_x = scroll.scroll_x_signal().clone();
        let max_scroll_x = scroll.max_scroll_x_signal().clone();
        let scroll_y = scroll.scroll_y_signal().clone();
        let max_scroll_y = scroll.max_scroll_y_signal().clone();
        let scroll_viewport = scroll.viewport_size_cell();
        let scroll_id = ctx.add(scroll);

        // Wrap the scroll area in a stack so the bar slots have a
        // place to sit. The scroll area takes all the slack along
        // the layout axis. Outer container axis matches the bar's
        // orientation: HStack for horizontal, VStack for vertical
        // (slot → pinned strip → leading arrow → scroll area →
        // trailing arrow → dropdown → trailing slot).
        let scroll_main = match self.orientation {
            TabBarOrientation::Horizontal => scroll_x.clone(),
            TabBarOrientation::Vertical => scroll_y.clone(),
        };
        let max_scroll_main = match self.orientation {
            TabBarOrientation::Horizontal => max_scroll_x.clone(),
            TabBarOrientation::Vertical => max_scroll_y.clone(),
        };
        // Hand the header row the two things it can only get from the
        // area — which is built *from* the row's id, so this is the
        // earliest it can be done. Still long before any layout runs.
        *self.reveal.area.borrow_mut() = Some(RevealArea {
            scroll_main: scroll_main.clone(),
            viewport: scroll_viewport,
        });
        // Accumulate the outer-stack children into a Vec, then
        // construct the actual HStack / VStack at the end based on
        // orientation. Keeps the body axis-agnostic.
        let mut outer_children: Vec<WidgetId> = Vec::new();

        if let Some(slot) = self.bar_leading_slot.take() {
            let id = match slot {
                PendingChild::Id(id) => id,
                PendingChild::Deferred(w) => ctx.add_boxed(w),
            };
            self.bar_leading_slot_id = Some(id);
            outer_children.push(id);
        }

        // Pinned strip — non-scrolling, fixed-width icons. Lives at
        // the leading edge so pinned tabs are always visible
        // regardless of how far the unpinned tabs scroll. Strip
        // orientation matches the bar.
        if !pinned_header_ids.is_empty() {
            // A 1 dp divider widget between consecutive pinned headers when
            // dividers are enabled. The pinned strip is a plain stack (it
            // does not use `header_bounds_buf`), so we interleave real
            // `Divider` widgets rather than an overlay — they're inert and
            // don't affect pinned drag/reorder.
            let make_divider = |ctx: &mut BuildContext| -> Option<WidgetId> {
                divider_prop.clone().map(|c| {
                    let d = match self.orientation {
                        TabBarOrientation::Horizontal => crate::primitives::Divider::vertical(),
                        TabBarOrientation::Vertical => crate::primitives::Divider::horizontal(),
                    };
                    ctx.add(d.color(c))
                })
            };
            let pinned_id = match self.orientation {
                TabBarOrientation::Horizontal => {
                    let mut pinned = HStack::new().spacing(self.spacing);
                    for (i, id) in pinned_header_ids.iter().enumerate() {
                        if i > 0
                            && let Some(div) = make_divider(ctx)
                        {
                            pinned = pinned.add_child(div);
                        }
                        pinned = pinned.add_child(*id);
                    }
                    ctx.add(pinned)
                }
                TabBarOrientation::Vertical => {
                    let mut pinned = crate::VStack::new().spacing(self.spacing);
                    for (i, id) in pinned_header_ids.iter().enumerate() {
                        if i > 0
                            && let Some(div) = make_divider(ctx)
                        {
                            pinned = pinned.add_child(div);
                        }
                        pinned = pinned.add_child(*id);
                    }
                    ctx.add(pinned)
                }
            };
            self.pinned_strip_id = Some(pinned_id);
            outer_children.push(pinned_id);
        }

        // Leading scroll arrow.
        if self.show_scroll_arrows {
            let arrow_id = build_scroll_arrow(
                ctx,
                ScrollArrowKind::Leading,
                self.orientation,
                scroll_main.clone(),
                max_scroll_main.clone(),
                motion_duration_normal,
                motion_easing_standard,
                self.idle_text_role,
            );
            // Visibility: only when there's something to scroll back.
            let visible = scroll_main.clone().map(|x| *x > 0.5);
            ctx.visible_when(arrow_id, visible);
            outer_children.push(arrow_id);
        }

        // The scroll area takes all the slack along the layout axis.
        let scroll_slot = match self.orientation {
            TabBarOrientation::Horizontal => ctx.add(Expand::horizontal().child_id(scroll_id)),
            TabBarOrientation::Vertical => ctx.add(Expand::vertical().child_id(scroll_id)),
        };
        outer_children.push(scroll_slot);

        // Trailing scroll arrow.
        if self.show_scroll_arrows {
            let arrow_id = build_scroll_arrow(
                ctx,
                ScrollArrowKind::Trailing,
                self.orientation,
                scroll_main.clone(),
                max_scroll_main.clone(),
                motion_duration_normal,
                motion_easing_standard,
                self.idle_text_role,
            );
            // Visibility: only when there's more to scroll forward.
            let visible = scroll_main
                .clone()
                .zip(&max_scroll_main)
                .map(|(x, max)| *x + 0.5 < *max);
            ctx.visible_when(arrow_id, visible);
            outer_children.push(arrow_id);
        }

        // Overflow dropdown — a chevron-down `PopoverIconButton` whose
        // popover content is a `ListView` mirroring the full tab
        // list. Activating an item sets `selected_id` and dismisses
        // the popover. `Auto` (default) reveals it only when the headers
        // overflow the viewport (`max_scroll_main > 0`), mirroring the
        // scroll-arrow auto-show; `Always` keeps it pinned; `Never` omits it.
        if self.overflow_button != TabOverflowButton::Never && !header_labels.is_empty() {
            // Build (id, label, enabled) entries so the dropdown can
            // route activation by stable TabId rather than by index.
            let entries: Vec<DropdownEntry> = header_labels
                .iter()
                .zip(index_to_id.iter().copied())
                .zip(enabled_tabs.iter().copied())
                .map(|((label, id), enabled)| DropdownEntry {
                    id,
                    label: label.clone(),
                    enabled,
                })
                .collect();
            let dropdown_id = build_overflow_dropdown(
                ctx,
                self.selected_id.clone(),
                entries,
                self.idle_text_role,
            );
            if self.overflow_button == TabOverflowButton::Auto {
                // Reveal only when there is something scrolled out of view.
                let overflowing = max_scroll_main.clone().map(|m| *m > 0.5);
                ctx.visible_when(dropdown_id, overflowing);
            }
            outer_children.push(dropdown_id);
        }

        if let Some(slot) = self.bar_trailing_slot.take() {
            let id = match slot {
                PendingChild::Id(id) => id,
                PendingChild::Deferred(w) => ctx.add_boxed(w),
            };
            self.bar_trailing_slot_id = Some(id);
            outer_children.push(id);
        }

        let root_id = match self.orientation {
            TabBarOrientation::Horizontal => {
                let mut row = HStack::new().spacing(DEFAULT_BAR_SLOT_SPACING);
                for id in &outer_children {
                    row = row.add_child(*id);
                }
                ctx.add(row)
            }
            TabBarOrientation::Vertical => {
                let mut col = crate::VStack::new().spacing(DEFAULT_BAR_SLOT_SPACING);
                for id in &outer_children {
                    col = col.add_child(*id);
                }
                ctx.add(col)
            }
        };
        self.outer_stack_id = Some(root_id);
        // Resolve the active `TabStyle` and let it wrap the bar
        // content with the strip chrome — backdrop fill, content-pane
        // separator, drag-reorder drop indicator. Per-call override >
        // theme slot > built-in `RecipeTabStyle`. This replaces the
        // old `TabBar::paint`: the bar is now pure composition.
        let style: teksilo_core::styles::SharedTabStyle = self
            .style_override
            .clone()
            .or_else(|| ctx.theme().style_slots.tab.clone())
            .unwrap_or_else(|| Rc::new(crate::styles::RecipeTabStyle::default()));
        let chrome_cfg = teksilo_core::styles::TabBarChromeConfig {
            content: root_id,
            orientation: self.orientation.into(),
            show_separator: self.show_separator,
            surface_role: self.bar_background.clone(),
            drop_indicator: self.paint_state.drop_indicator_x.clone(),
        };
        let bar_root = style.make_bar(&chrome_cfg, ctx);
        self.root_child_id = Some(bar_root);

        // Wheel-mapping handler. Attached via `on_pointer_event`
        // (not `on_scroll`) so the framework fires it in the
        // *preview pass* on each strict ancestor of the pointer
        // target — i.e. before the descendant ScrollArea has a
        // chance to consume the event. That's what lets us
        // remap "wheel down" → "scroll right" on a horizontal-only
        // bar; if we ran in bubble, ScrollArea would have already
        // handled the event and stopped propagation.
        //
        // We only consume events we're actively remapping; genuine
        // horizontal-wheel deltas (trackpad two-finger pan) pass
        // through to ScrollArea unchanged.
        let vert_to_horiz = self.vertical_wheel_scrolls_horizontally;
        let shift_to_horiz = self.shift_wheel_scrolls_horizontally;
        let scroll_x_for_wheel = scroll_x.clone();
        let max_scroll_x_for_wheel = max_scroll_x.clone();
        let orientation_for_wheel = self.orientation;
        let handler = HandlerSet::new().on_pointer_event(
            move |event: &WidgetEvent, _ctx: &mut EventContext| -> EventResponse {
                // Vertical bars scroll vertically — ScrollArea handles
                // wheel events natively; nothing to remap here.
                if orientation_for_wheel == TabBarOrientation::Vertical {
                    return EventResponse::Ignored;
                }
                let WidgetEvent::Scroll { delta, modifiers } = event else {
                    return EventResponse::Ignored;
                };
                let (dx, dy) = match delta {
                    ScrollDelta::Lines { x, y } => (x * WHEEL_LINE_PIXELS, y * WHEEL_LINE_PIXELS),
                    ScrollDelta::Pixels { x, y } => (*x, *y),
                };
                let shift = modifiers.shift();
                // Decide whether *this* event is one we want to
                // remap. Shift always remaps; otherwise we only
                // remap a vertical-only wheel on a horizontal bar.
                let should_remap = if shift && shift_to_horiz {
                    true
                } else {
                    vert_to_horiz && dx.abs() < f32::EPSILON && dy.abs() > 0.0
                };
                if !should_remap {
                    return EventResponse::Ignored;
                }
                let mapped_dx = if dx.abs() > 0.0 { dx } else { dy };
                if mapped_dx.abs() < f32::EPSILON {
                    return EventResponse::Ignored;
                }
                // Sign convention matches ScrollArea: positive delta
                // moves the content (so positive `y` from a wheel-down
                // event scrolls right when remapped to horizontal).
                let new_x =
                    (scroll_x_for_wheel.get() + mapped_dx).clamp(0.0, max_scroll_x_for_wheel.get());
                scroll_x_for_wheel.set(new_x);
                EventResponse::Handled
            },
        );
        ctx.apply_self_handlers(handler);

        // Drag-target handlers: attached when reordering is on OR the
        // bar accepts cross-bar transfers. The bar acts as the single
        // drop target — we convert pointer position (delivered in
        // bar-local coords) into a tab boundary by walking
        // `header_bounds_buf` (world coords) translated into bar-local
        // space via `last_bar_bounds.origin` cached by `place_children`.
        //
        // Two payload consumers share this target:
        //   - intra-bar reorder: `data.source_bar_id == self_id` →
        //     `reorder(from, to)` (only when `reorder` is set).
        //   - cross-bar transfer: a foreign bar's payload carrying
        //     `item: Some(_)` → `on_tab_received(item, to_model)`
        //     (only when `accept_external` is on).
        if reorder_handler.is_some() || self.accept_external_tabs || self.on_external_drop.is_some()
        {
            let bar_id_for_drop = self_id;
            let axis = self.orientation;
            let accept_external = self.accept_external_tabs;
            let has_external_drop = self.on_external_drop.is_some();
            // Insertion line cross-extent used when the target bar has
            // no unpinned headers yet (empty bar): span the bar's
            // cross axis so the indicator is still visible.
            let drop_handler = HandlerSet::new()
                .on_drag_hover({
                    let header_bounds = header_bounds_buf.clone();
                    let drop_indicator = self.paint_state.drop_indicator_x.clone();
                    let bar_bounds = self.paint_state.last_bar_bounds.clone();
                    move |payload: &DragPayload,
                          position: Point,
                          _ctx: &mut EventContext|
                          -> DropFeedback {
                        match payload.get_typed::<TabBarDragData<T>>() {
                            Some(data) => {
                                // Accept an intra-bar reorder, or a
                                // foreign tab when this bar opted into
                                // transfer and the payload carries a
                                // transferable item.
                                let is_intra = data.source_bar_id == bar_id_for_drop;
                                let is_foreign_ok = accept_external && data.item.is_some();
                                if !is_intra && !is_foreign_ok {
                                    drop_indicator.set(None);
                                    return DropFeedback::NoFeedback;
                                }
                            }
                            None => {
                                // Non-tab payload (foreign in-app drag
                                // or OS drop): accepted only if a
                                // non-tab drop handler is installed.
                                // The indicator is optimistic — the
                                // handler decides for real at drop.
                                if !has_external_drop {
                                    drop_indicator.set(None);
                                    return DropFeedback::NoFeedback;
                                }
                            }
                        }
                        let bar = bar_bounds.get();
                        let bounds = header_bounds.borrow();
                        // Empty target bar (no unpinned headers): drop
                        // at the leading edge, indicator spans the
                        // bar's cross axis.
                        if bounds.is_empty() {
                            let cross = match axis {
                                TabBarOrientation::Horizontal => bar.height,
                                TabBarOrientation::Vertical => bar.width,
                            };
                            drop_indicator.set(Some(0.0));
                            return DropFeedback::InsertionLine {
                                y: 0.0,
                                width: cross,
                            };
                        }
                        // Layout-axis pointer position in world coords:
                        // x for horizontal bars, y for vertical bars.
                        let (pointer_world_main, bar_origin_main) = match axis {
                            TabBarOrientation::Horizontal => (position.x + bar.x, bar.x),
                            TabBarOrientation::Vertical => (position.y + bar.y, bar.y),
                        };
                        let insertion_world_main =
                            insertion_world_main_for(&bounds, pointer_world_main, axis);
                        let insertion_local_main = insertion_world_main - bar_origin_main;
                        drop_indicator.set(Some(insertion_local_main));
                        DropFeedback::InsertionLine {
                            y: 0.0,
                            width: bounds[0].height,
                        }
                    }
                })
                .on_drag_leave({
                    let drop_indicator = self.paint_state.drop_indicator_x.clone();
                    move |_ctx: &mut EventContext| {
                        drop_indicator.set(None);
                    }
                })
                .on_drop({
                    let header_bounds = header_bounds_buf.clone();
                    let bar_bounds = self.paint_state.last_bar_bounds.clone();
                    let drop_indicator = self.paint_state.drop_indicator_x.clone();
                    let reorder = reorder_handler.clone();
                    let on_received = self.on_tab_received.clone();
                    let on_external_drop = self.on_external_drop.clone();
                    let self_reorder = self.self_reorder_flag.clone();
                    let unpinned_to_model = unpinned_to_model.clone();
                    let bar_id = bar_id_for_drop;
                    move |mut payload: DragPayload,
                          position: Point,
                          ctx: &mut EventContext|
                          -> bool {
                        drop_indicator.set(None);
                        // Extract the tab payload if this is one; a
                        // failed downcast leaves `payload` intact for
                        // the non-tab branch below.
                        let mut data = payload.take_typed::<TabBarDragData<T>>();
                        let bar = bar_bounds.get();
                        let bounds = header_bounds.borrow();
                        // Resolve the model insertion index from the
                        // pointer. `insertion_index_for` works in
                        // **unpinned** space (the bounds buffer only
                        // holds unpinned headers); map it to a model
                        // index. An empty target bar inserts at 0.
                        let to_model = if bounds.is_empty() {
                            0
                        } else {
                            let pointer_world_main = match axis {
                                TabBarOrientation::Horizontal => position.x + bar.x,
                                TabBarOrientation::Vertical => position.y + bar.y,
                            };
                            let to_unpinned =
                                insertion_index_for(&bounds, pointer_world_main, axis);
                            if to_unpinned < unpinned_to_model.len() {
                                unpinned_to_model[to_unpinned]
                            } else {
                                // Past the trailing edge of the
                                // unpinned region — insert just after
                                // the last unpinned tab.
                                unpinned_to_model
                                    .last()
                                    .map(|&last| last + 1)
                                    .unwrap_or(model_len)
                            }
                        };

                        let Some(data) = data.as_mut() else {
                            // ── Non-tab payload (foreign drag / OS) ─
                            // `payload` is intact (downcast missed).
                            drop(bounds);
                            return match on_external_drop.as_ref() {
                                Some(cb) => (cb)(&payload, to_model, ctx),
                                None => false,
                            };
                        };

                        if data.source_bar_id == bar_id {
                            // ── Intra-bar reorder ──────────────────
                            // Mark the drag as a self-reorder so the
                            // source header's on_drag_ended suppresses
                            // on_transfer_out (which would otherwise
                            // remove the just-reordered tab).
                            self_reorder.set(true);
                            let Some(reorder) = reorder.as_ref() else {
                                return true;
                            };
                            let from = data.source_index;
                            // `move_item(from, to)` interprets `to` as
                            // the **post-removal** insertion position,
                            // so a forward drag adjusts by -1.
                            let adjusted_to = if from < to_model {
                                to_model.saturating_sub(1)
                            } else {
                                to_model
                            };
                            if from != adjusted_to {
                                (reorder)(from, adjusted_to, ctx);
                            }
                            true
                        } else if accept_external {
                            // ── Cross-bar transfer ─────────────────
                            // No `-1` correction: there is no source
                            // slot inside *this* model to compensate
                            // for. The app inserts the moved item at
                            // exactly `to_model`.
                            let Some(item) = data.item.take() else {
                                return false;
                            };
                            if let Some(cb) = on_received.as_ref() {
                                (cb)(item, to_model, ctx);
                            }
                            true
                        } else {
                            false
                        }
                    }
                })
                .on_drag_tick({
                    // Edge auto-scroll while a drag is in progress.
                    // Ramp the scroll velocity linearly inside the
                    // edge zones; cap at `DRAG_MAX_VELOCITY` so fast
                    // drags don't rocket past the content. Axis-aware:
                    // horizontal bars scroll by x, vertical by y.
                    let scroll_main = scroll_main.clone();
                    let max_scroll_main = max_scroll_main.clone();
                    let bar_bounds = self.paint_state.last_bar_bounds.clone();
                    move |position: Point, _ctx: &mut EventContext| {
                        let bar = bar_bounds.get();
                        let (pointer_main, bar_extent) = match axis {
                            TabBarOrientation::Horizontal => (position.x, bar.width),
                            TabBarOrientation::Vertical => (position.y, bar.height),
                        };
                        let max = max_scroll_main.get();
                        let cur = scroll_main.get();
                        let leading_in = (DRAG_EDGE_ZONE - pointer_main).max(0.0);
                        let trailing_in = (pointer_main - (bar_extent - DRAG_EDGE_ZONE)).max(0.0);
                        let delta = if leading_in > 0.0 {
                            -(leading_in / DRAG_EDGE_ZONE) * DRAG_MAX_VELOCITY
                        } else if trailing_in > 0.0 {
                            (trailing_in / DRAG_EDGE_ZONE) * DRAG_MAX_VELOCITY
                        } else {
                            0.0
                        };
                        if delta.abs() > 0.001 {
                            scroll_main.set((cur + delta).clamp(0.0, max));
                        }
                    }
                });
            ctx.apply_self_handlers(drop_handler);
        }

        vec![bar_root]
    }

    fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
        let Some(root_id) = self.root_child_id else {
            return proposal.resolve(0.0, 0.0).into();
        };
        let final_proposal = match self.orientation {
            TabBarOrientation::Vertical => {
                // Adapt the bar's cross-axis (width) to whichever piece
                // of bar content is widest — tab labels, the pinned
                // strip, or a leading / trailing slot widget — clamped
                // to [min_tab_width, max_tab_width]. Probing the inner
                // ScrollArea would just echo our own proposal back, so
                // we measure the row directly.
                //
                // Under `TabSizing::Fill` the bar instead takes the
                // width it is offered (the sidebar's full width) and
                // hands it down to the header column, which stretches
                // every pill to it. An unbounded proposal has no width
                // to fill, so it falls back to the intrinsic path.
                let target = match (self.sizing, proposal.width) {
                    (TabSizing::Fill, Some(p)) => p.max(0.0),
                    _ => {
                        let mut intrinsic_w = 0.0_f32;
                        for opt in [
                            self.header_row_id,
                            self.pinned_strip_id,
                            self.bar_leading_slot_id,
                            self.bar_trailing_slot_id,
                        ] {
                            if let Some(id) = opt
                                && let Some(s) = ctx.child_size(id, SizeProposal::unspecified())
                            {
                                intrinsic_w = intrinsic_w.max(s.width);
                            }
                        }
                        let mut t = intrinsic_w.clamp(self.min_tab_width, self.max_tab_width);
                        if let Some(p) = proposal.width {
                            t = t.min(p).max(self.min_tab_width);
                        }
                        t
                    }
                };
                SizeProposal {
                    width: Some(target),
                    height: proposal.height,
                }
            }
            TabBarOrientation::Horizontal => proposal,
        };
        let mut size = ctx
            .child_size(root_id, final_proposal)
            .unwrap_or_else(|| final_proposal.resolve(0.0, 0.0));
        // Unbounded height + vertical: the outer stack reports 0 (its
        // scroll slot is an `Expand::vertical`, which is 0-natural and
        // sizes from surplus), which would collapse the bar to nothing
        // beside a flexible sibling — a `Spacer` in a sidebar column.
        // Report the tabs' own extent instead, so a vertical bar has a
        // natural height like any other content widget.
        if self.orientation == TabBarOrientation::Vertical && proposal.height.is_none() {
            size.height = self.natural_height_vertical(final_proposal.width, ctx);
        }
        size.into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        // Record the bar's world bounds so the drag handlers can
        // translate bar-local pointer positions back to world coords
        // (matching the world-coords header bounds populated by
        // TabHeaderRow).
        self.paint_state.last_bar_bounds.set(bounds);
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }

    // No `paint()`: the bar is pure composition. Backdrop fill,
    // content-pane separator, and the drag-reorder drop indicator are
    // all drawn by the active `TabStyle`'s `make_bar` chrome (see
    // `RecipeTabStyle` / `TabBarChromePainter`).

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        builder.set_role(teksilo_core::accesskit::Role::TabList);
        builder.set_orientation(match self.orientation {
            TabBarOrientation::Horizontal => teksilo_core::accesskit::Orientation::Horizontal,
            TabBarOrientation::Vertical => teksilo_core::accesskit::Orientation::Vertical,
        });
        // The tab count, on the container rather than on each tab:
        // `size_of_set_from_container` walks up from an item, so a count
        // written on a `Role::Tab` is read by no adapter. This is the same
        // number `TabHeader` used to write on itself — pinned and regular tabs
        // share one TabList, and the buffer holds both.
        let count = self
            .header_ids_buffer
            .as_ref()
            .map(|b| b.borrow().len())
            .unwrap_or(0);
        if count > 0 {
            builder.set_size_of_set(count);
        }
    }

    fn children(&self) -> Vec<WidgetId> {
        self.root_child_id.into_iter().collect()
    }
}

// ─── Internal: the headers row / column ─────────────────────────────

/// The headers run — a horizontal row in [`TabBarOrientation::Horizontal`]
/// mode, a vertical column in [`TabBarOrientation::Vertical`] mode.
/// Owns the `Shared`/`Independent` sizing math and exposes per-tab
/// world bounds back to the bar's DnD handlers.
#[derive(Debug)]
struct TabHeaderRow {
    header_ids: Vec<WidgetId>,
    axis: TabBarOrientation,
    sizing: TabSizing,
    /// Min extent on the *layout axis* — width for horizontal,
    /// height for vertical. Reuses the same `min_tab_width` knob for
    /// the vertical case (it's about per-tab pill extent, not the
    /// width of the bar).
    min_extent: f32,
    max_extent: f32,
    spacing: f32,
    /// Optional per-tab extent override along the bar's cross axis (the tab
    /// strip height for a horizontal bar; the per-tab pill height for a
    /// vertical one). `None` → the style's `editor_tab_height`.
    tab_height: Option<f32>,
    /// Per-tab bounds in world coords, populated by `place_children`.
    /// Shared with the bar's drop handlers via `Rc<RefCell<...>>`;
    /// the bar reads this to compute drop-insertion position for an
    /// in-progress drag.
    header_bounds_buf: Rc<RefCell<Vec<Rect>>>,
    /// Cached row-level world bounds — used to map bar-local
    /// coordinates onto header bounds.
    row_bounds_buf: Rc<std::cell::Cell<Rect>>,
    /// `(color, spacing)` for an inter-tab divider overlay, or `None`
    /// when dividers are off. When `Some`, `build` appends a single
    /// `TabRowDividers` leaf as the last child (painted on top of the
    /// headers, reading `header_bounds_buf`).
    divider: Option<(teksilo_core::color_prop::ColorProp, f32)>,
    /// The appended divider-overlay child id, set in `build` when
    /// `divider` is `Some`. Kept so `children()` reports it too.
    overlay_id: Option<WidgetId>,
    /// Shared "scroll the active tab into view" request. Armed by the
    /// bar, consumed here — see [`Self::apply_pending_reveal`].
    reveal: RevealState,
}

impl TabHeaderRow {
    /// The per-tab cross-axis extent: the explicit override (compact bars) or
    /// the style's `editor_tab_height`.
    fn tab_extent(&self, ctx: &LayoutContext) -> f32 {
        self.tab_height
            .unwrap_or_else(|| TabHeader::intrinsic_height(ctx))
    }

    fn compute_extents(&self, viewport_main: Option<f32>, ctx: &LayoutContext) -> Vec<f32> {
        let n = self.header_ids.len();
        if n == 0 {
            return Vec::new();
        }
        match self.sizing {
            TabSizing::Shared | TabSizing::Fill => {
                let target = match self.axis {
                    TabBarOrientation::Horizontal => {
                        // Divide the viewport width across tabs
                        // (Firefox / Chrome convention) and clamp by
                        // the layout-axis [min, max] knobs. `Fill`
                        // drops the max cap: its whole point is to
                        // consume the strip edge to edge rather than
                        // leave trailing slack past `max_tab_width`.
                        // The min still holds — below it the headers
                        // overflow into scroll.
                        let total_spacing = self.spacing * (n.saturating_sub(1)) as f32;
                        let avail = viewport_main.unwrap_or(0.0).max(0.0);
                        let ideal = ((avail - total_spacing).max(0.0) / n as f32).max(0.0);
                        if self.sizing == TabSizing::Fill {
                            ideal.max(self.min_extent)
                        } else {
                            ideal.clamp(self.min_extent, self.max_extent)
                        }
                    }
                    TabBarOrientation::Vertical => {
                        // Vertical sidebar pills are NOT viewport-
                        // divided — that turns a tall bar into ~200 dp
                        // tab bands, which neither Firefox / Chrome
                        // (no native vertical mode) nor VS Code /
                        // IntelliJ do. Use the intrinsic per-tab
                        // height (`editor_tab_height`) so vertical
                        // tabs match horizontal tabs in size. `Fill`
                        // is no different here: in a vertical bar it
                        // stretches the pill *width* (see
                        // `layout_response`), never the height.
                        self.tab_extent(ctx)
                    }
                };
                vec![target; n]
            }
            TabSizing::Independent => self
                .header_ids
                .iter()
                .map(|&id| {
                    let s = ctx.child_size(id, SizeProposal::unspecified());
                    let raw = match self.axis {
                        TabBarOrientation::Horizontal => s.map(|s| s.width),
                        TabBarOrientation::Vertical => s.map(|s| s.height),
                    };
                    let fallback = match self.axis {
                        TabBarOrientation::Horizontal => self.min_extent,
                        TabBarOrientation::Vertical => self.tab_extent(ctx),
                    };
                    let raw = raw.unwrap_or(fallback);
                    // [min, max] are width-defaulted (96 / 240) and
                    // axis-mismatched in vertical mode where they'd
                    // force tab heights to ≥96 dp. Skip the clamp on
                    // the height axis; the intrinsic per-tab height
                    // is already the right answer.
                    match self.axis {
                        TabBarOrientation::Horizontal => {
                            raw.clamp(self.min_extent, self.max_extent)
                        }
                        TabBarOrientation::Vertical => raw,
                    }
                })
                .collect(),
        }
    }
}

impl TabHeaderRow {
    /// Consume a pending "scroll the active tab into view" request,
    /// given this pass's per-tab extents and the viewport's extent along
    /// the layout axis.
    ///
    /// Called from `layout_response`, deliberately, and not from
    /// `place_children`: the enclosing `ScrollArea` measures its content
    /// (this row) *before* it clamps and reads `scroll_x` to position
    /// that content, so an offset written here lands in the very same
    /// layout pass. Written from `place_children` — which runs after the
    /// area has already placed the row — it would be a frame late, and
    /// the strip would visibly lurch one frame after the tab activated.
    ///
    /// The move is minimal, matching the `ScrollIntoView` convention:
    /// only the edge the tab fell off is chased, so revealing a tab
    /// that is already visible is a no-op rather than a recentring.
    fn apply_pending_reveal(&self, extents: &[f32], viewport_main: f32) {
        // Not yet measurable — keep the request rather than resolve it
        // against a viewport we don't have.
        if viewport_main <= 0.0 {
            return;
        }
        let Some(target) = self.reveal.pending.get() else {
            return;
        };
        let Some(&extent) = extents.get(target) else {
            // The row no longer has that header — it was closed or
            // pinned between the arm and this pass. Drop the request
            // rather than scroll to whatever now sits at that position.
            self.reveal.pending.set(None);
            return;
        };
        let area_guard = self.reveal.area.borrow();
        let Some(area) = area_guard.as_ref() else {
            return;
        };
        self.reveal.pending.set(None);

        let content =
            extents.iter().sum::<f32>() + self.spacing * extents.len().saturating_sub(1) as f32;
        let max_scroll = (content - viewport_main).max(0.0);
        if max_scroll <= 0.0 {
            // Everything fits; there is nothing to reveal.
            return;
        }
        let lead = extents[..target].iter().sum::<f32>() + self.spacing * target as f32;
        let current = area.scroll_main.get();
        let next = if lead < current {
            lead
        } else if lead + extent > current + viewport_main {
            lead + extent - viewport_main
        } else {
            current
        }
        .clamp(0.0, max_scroll);
        if (next - current).abs() > REVEAL_EPSILON {
            area.scroll_main.set(next);
        }
    }

    /// The full child list: the pre-registered headers plus the optional
    /// divider overlay appended last.
    fn child_ids(&self) -> Vec<WidgetId> {
        let mut ids = self.header_ids.clone();
        ids.extend(self.overlay_id);
        ids
    }
}

impl Widget for TabHeaderRow {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        // Arming a reveal has to schedule the layout pass that consumes
        // it: activating a tab changes no size, so on its own it would
        // only repaint and the request would sit unread.
        self.reveal.generation.bind_to(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::Relayout,
        );
        // Headers are pre-registered with the bar's BuildContext; the row
        // just exposes them. When dividers are on, append a single overlay
        // leaf (last child → painted on top of the headers) that reads the
        // shared `header_bounds_buf` to draw a line at each boundary.
        if let Some((color, spacing)) = self.divider.clone() {
            let overlay = ctx.add_boxed(Box::new(TabRowDividers {
                header_bounds_buf: self.header_bounds_buf.clone(),
                axis: self.axis,
                color,
                spacing,
            }));
            self.overlay_id = Some(overlay);
        }
        self.child_ids()
    }

    fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
        let n = self.header_ids.len();
        if n == 0 {
            return Size::new(0.0, 0.0).into();
        }
        let total_spacing = self.spacing * (n - 1) as f32;
        match self.axis {
            TabBarOrientation::Horizontal => {
                // Cap the row's height at one tab header's intrinsic
                // height (= `editor_tab_height`). If the surrounding
                // outer HStack proposes a taller height because a
                // sibling (toolbar button, dropdown trigger) wants
                // more room, the row should NOT stretch — it would
                // turn the strip into a tall band with the pills
                // floating in the middle. Clamping here keeps the
                // tab strip exactly token-sized.
                let intrinsic = self.tab_extent(ctx);
                let height = proposal
                    .height
                    .map(|h| h.min(intrinsic))
                    .unwrap_or(intrinsic);
                let extents = self.compute_extents(proposal.width, ctx);
                let total = extents.iter().sum::<f32>() + total_spacing;
                // Resolve any pending reveal now that both halves of the
                // arithmetic are known. Only against a real width
                // proposal: an unbounded probe (the vertical bar's
                // natural-size measurement, a11y sizing) makes
                // `compute_extents` fall back to `min_extent` for every
                // tab, which would place the target at the wrong offset.
                // The area's own measurement always supplies a width.
                if let Some(viewport_main) = proposal.width {
                    self.apply_pending_reveal(&extents, viewport_main);
                }
                Size::new(total, height).into()
            }
            TabBarOrientation::Vertical => {
                // Adapt to the longest tab label, clamped to
                // [min_extent, max_extent]. Without this, the row
                // would echo `proposal.width` and let the bar swallow
                // whatever cross-axis space the parent gave it.
                //
                // `Fill` wants exactly that echo, though: the pills
                // span the width the bar is offered. Only when the
                // proposal is unbounded (nothing to fill) does it fall
                // back to the fit-to-widest-label width.
                let width = match (self.sizing, proposal.width) {
                    (TabSizing::Fill, Some(proposed)) => proposed.max(0.0),
                    _ => {
                        let intrinsic = self
                            .header_ids
                            .iter()
                            .filter_map(|&id| ctx.child_size(id, SizeProposal::unspecified()))
                            .map(|s| s.width)
                            .fold(0.0_f32, f32::max);
                        let mut w = intrinsic.clamp(self.min_extent, self.max_extent);
                        if let Some(proposed) = proposal.width {
                            w = w.min(proposed).max(self.min_extent);
                        }
                        w
                    }
                };
                let extents = self.compute_extents(proposal.height, ctx);
                let total = extents.iter().sum::<f32>() + total_spacing;
                // Vertical extents are the intrinsic per-tab height and
                // don't depend on the proposal (see `compute_extents`),
                // so a probe can't skew them — but the viewport height
                // *is* missing here: the `ScrollArea` measures its
                // content with `height: None`. Read the viewport it last
                // placed instead; it only goes stale on the frame the
                // bar is resized, which is not a frame a reveal is in
                // flight on.
                let viewport_main = self
                    .reveal
                    .area
                    .borrow()
                    .as_ref()
                    .map_or(0.0, |a| a.viewport.get().height);
                self.apply_pending_reveal(&extents, viewport_main);
                Size::new(width, total).into()
            }
        }
    }

    fn place_children(
        &self,
        bounds: Rect,
        proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        ctx: &LayoutContext,
    ) {
        // For Shared sizing, divide the *viewport* main extent (the
        // proposal main axis) — NOT the bounds main extent, which is
        // the content size returned by `layout_response`. ScrollArea
        // computes content size from `layout_response` and then calls
        // `place_children` with bounds = content_size, so using the
        // bounds main here would feedback-loop the layout pass.
        let viewport_main = match self.axis {
            TabBarOrientation::Horizontal => proposal.width,
            TabBarOrientation::Vertical => proposal.height,
        };
        let extents = self.compute_extents(viewport_main, ctx);
        let mut buf = self.header_bounds_buf.borrow_mut();
        buf.clear();
        match self.axis {
            TabBarOrientation::Horizontal => {
                let mut x = bounds.x;
                for (i, child) in children.iter_mut().enumerate() {
                    if i >= extents.len() {
                        break;
                    }
                    child.origin = Point::new(x, bounds.y);
                    child.size = Size::new(extents[i], bounds.height);
                    buf.push(Rect::new(x, bounds.y, extents[i], bounds.height));
                    x += extents[i] + self.spacing;
                }
            }
            TabBarOrientation::Vertical => {
                let mut y = bounds.y;
                for (i, child) in children.iter_mut().enumerate() {
                    if i >= extents.len() {
                        break;
                    }
                    child.origin = Point::new(bounds.x, y);
                    child.size = Size::new(bounds.width, extents[i]);
                    buf.push(Rect::new(bounds.x, y, bounds.width, extents[i]));
                    y += extents[i] + self.spacing;
                }
            }
        }
        drop(buf);
        // The divider overlay (appended last) is not a header — the loop
        // above broke before it (i >= extents.len()) so it never reached
        // `header_bounds_buf`. Place it spanning the whole row so it can
        // paint the inter-tab lines on top.
        if self.overlay_id.is_some()
            && let Some(last) = children.last_mut()
        {
            last.origin = bounds.origin();
            last.size = bounds.size();
        }
        self.row_bounds_buf.set(bounds);
    }

    fn children(&self) -> Vec<WidgetId> {
        self.child_ids()
    }
}

/// Pure-decoration overlay (the last child of [`TabHeaderRow`]) that paints
/// a 1 dp line at each boundary between consecutive tab headers, reading the
/// row's shared `header_bounds_buf` (world coords). Painted on top of the
/// headers so it shows over any per-tab background; pointer events pass
/// straight through.
struct TabRowDividers {
    header_bounds_buf: Rc<RefCell<Vec<Rect>>>,
    axis: TabBarOrientation,
    color: teksilo_core::color_prop::ColorProp,
    spacing: f32,
}

impl std::fmt::Debug for TabRowDividers {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TabRowDividers")
            .field("axis", &self.axis)
            .finish()
    }
}

impl Widget for TabRowDividers {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        // Repaint when the (possibly bound) divider colour changes.
        self.color.register_if_bound(
            ctx.self_id(),
            ctx.binding_registry(),
            BindingLevel::RepaintOnly,
        );
        ctx.apply_self_handlers(HandlerSet::new().event_pass_through(true));
        vec![]
    }

    fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        // Leaf overlay — fill whatever bounds the row places it at.
        proposal.resolve(0.0, 0.0).into()
    }

    fn paint(&self, _bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
        let headers = self.header_bounds_buf.borrow();
        if headers.len() < 2 {
            return;
        }
        let color = self.color.resolve(ctx.theme, true);
        let t = ctx.theme.shape.border_width.max(1.0);
        // Draw between consecutive headers. When `spacing > 0` the line is
        // centred in the gap; with flush tabs it sits on the shared edge.
        for pair in headers.windows(2) {
            let (a, b) = (pair[0], pair[1]);
            let line = match self.axis {
                TabBarOrientation::Horizontal => {
                    let mid = (a.right() + b.x) * 0.5;
                    Rect::new(mid - t * 0.5, a.y, t, a.height)
                }
                TabBarOrientation::Vertical => {
                    let mid = (a.bottom() + b.y) * 0.5;
                    Rect::new(a.x, mid - t * 0.5, a.width, t)
                }
            };
            canvas.fill_rect(line, color);
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        builder.set_hidden();
    }
}

// ─── Scroll arrow + overflow dropdown construction ───────────────────

/// Apply a bar-level [`TabDisplayMode`] to one tab's resolved label / icon /
/// tooltip. Icon-only modes blank the displayed label (the header then sizes to
/// the icon) and promote the title to the hover tooltip; with no icon they fall
/// back to the title's initial letter so the tab is never blank.
fn apply_tab_display(
    mode: TabDisplayMode,
    label: LocalizedString,
    icon: Option<IconWidget>,
    tooltip: Option<LocalizedString>,
) -> (LocalizedString, Option<IconWidget>, Option<LocalizedString>) {
    match mode {
        // Render as declared (Auto) or both when available (IconText) — there
        // is nothing to force-add, so these are identical transforms.
        TabDisplayMode::Auto | TabDisplayMode::IconText => (label, icon, tooltip),
        // Title only — drop the icon.
        TabDisplayMode::Text => (label, None, tooltip),
        // Icon only — blank the displayed label, promote the title to the
        // tooltip, and fall back to the initial letter when there is no icon.
        TabDisplayMode::Icon => {
            let resolved = label.clone().resolve_now();
            let tip = tooltip.or_else(|| (!resolved.trim().is_empty()).then(|| label.clone()));
            if icon.is_some() {
                (lit!(""), icon, tip)
            } else {
                let initial: String = resolved.chars().take(1).collect();
                (lit!(initial), None, tip)
            }
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum ScrollArrowKind {
    Leading,
    Trailing,
}

fn build_scroll_arrow(
    ctx: &mut BuildContext,
    kind: ScrollArrowKind,
    orientation: TabBarOrientation,
    scroll_main: Signal<f32>,
    max_scroll_main: Signal<f32>,
    duration: std::time::Duration,
    easing: Easing,
    icon_role: TextRole,
) -> WidgetId {
    let _ = ctx;
    let icon_size = crate::styles::recipe_button_style::BUTTON_ICON_SIZE;
    let icon = match (orientation, kind) {
        (TabBarOrientation::Horizontal, ScrollArrowKind::Leading) => {
            IconWidget::chevron_left(icon_size)
        }
        (TabBarOrientation::Horizontal, ScrollArrowKind::Trailing) => {
            IconWidget::chevron_right(icon_size)
        }
        (TabBarOrientation::Vertical, ScrollArrowKind::Leading) => {
            IconWidget::chevron_up(icon_size)
        }
        (TabBarOrientation::Vertical, ScrollArrowKind::Trailing) => {
            IconWidget::chevron_down(icon_size)
        }
    };
    let tooltip = match (orientation, kind) {
        (TabBarOrientation::Horizontal, ScrollArrowKind::Leading) => {
            lit!("Scroll tabs left")
        }
        (TabBarOrientation::Horizontal, ScrollArrowKind::Trailing) => {
            lit!("Scroll tabs right")
        }
        (TabBarOrientation::Vertical, ScrollArrowKind::Leading) => {
            lit!("Scroll tabs up")
        }
        (TabBarOrientation::Vertical, ScrollArrowKind::Trailing) => {
            lit!("Scroll tabs down")
        }
    };
    let button = IconButton::new(icon)
        .embedded()
        .size(IconButtonSize::Compact)
        .icon_role(icon_role)
        .tooltip(tooltip)
        .on_activate_fn(move |_ctx| {
            let cur = scroll_main.get();
            let target = match kind {
                ScrollArrowKind::Leading => (cur - SCROLL_ARROW_STEP).max(0.0),
                ScrollArrowKind::Trailing => (cur + SCROLL_ARROW_STEP).min(max_scroll_main.get()),
            };
            // The main-axis scroll signal is created via
            // `Signal::new_animated` inside ScrollArea, so
            // `animate_to` is supported.
            scroll_main.animate_to(target, duration, easing);
        });
    ctx.add(button)
}

/// One entry in the overflow dropdown — a stable [`TabId`], the
/// resolved label, and whether the tab is enabled. Built fresh per
/// bar build pass; cloned into the `ListView`'s underlying
/// `ListModel`.
#[derive(Clone)]
struct DropdownEntry {
    id: TabId,
    label: LocalizedString,
    enabled: bool,
}

impl std::fmt::Debug for DropdownEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DropdownEntry")
            .field("id", &self.id)
            .field("enabled", &self.enabled)
            .finish()
    }
}

/// Width of the overflow popover. Roughly two tab-widths so the
/// labels read at the same density as the bar itself.
const DROPDOWN_WIDTH: f32 = 240.0;
/// Cap on the popover height — beyond this many items the ListView
/// scrolls internally. Roughly ten rows of `DROPDOWN_ROW_HEIGHT`.
const DROPDOWN_MAX_HEIGHT: f32 = 320.0;
/// Per-row height. Smaller than a tab header so the dropdown reads
/// as a menu rather than a strip preview.
const DROPDOWN_ROW_HEIGHT: f32 = 28.0;
/// Padding inside the dropdown surface.
const DROPDOWN_PADDING: f32 = 4.0;

fn build_overflow_dropdown(
    ctx: &mut BuildContext,
    selected_id: Signal<Option<TabId>>,
    entries: Vec<DropdownEntry>,
    icon_role: TextRole,
) -> WidgetId {
    let _ = ctx;
    let icon_size = crate::styles::recipe_button_style::BUTTON_ICON_SIZE;
    // Same square, icon-sized control as the scroll arrows (an `IconButton`, not
    // a label-less `Button` that pads out around the glyph) so it stays adapted
    // to its icon and consistent in both bar orientations.
    let trigger = IconButton::new(IconWidget::chevron_down(icon_size))
        .embedded()
        .size(IconButtonSize::Compact)
        .icon_role(icon_role)
        .tooltip(lit!("Show all tabs"));

    // Cap each row at the dropdown height so a click still hits a
    // sensible-sized button regardless of `entries.len()`.
    let row_count = entries.len();
    let model = ListModel::from_vec(entries);
    let selected_for_delegate = selected_id.clone();
    let list = ListView::new(model, move |_i, entry: &DropdownEntry, _selected| {
        let entry_id = entry.id;
        let label = entry.label.clone();
        let enabled = entry.enabled;
        let sel = selected_for_delegate.clone();
        Box::new(
            Button::new(label)
                .variant(ButtonVariant::Ghost)
                .enabled(enabled)
                .on_activate_fn(move |ctx: &mut EventContext| {
                    sel.set(Some(entry_id));
                    ctx.dismiss_self_overlay_chain();
                }),
        ) as Box<dyn Widget>
    })
    .item_height(DROPDOWN_ROW_HEIGHT);

    // Compute a shrink-to-content height for short tab lists; cap
    // at `DROPDOWN_MAX_HEIGHT` for long ones (the ListView's
    // internal scroll bar takes over past the cap).
    let natural_h = (row_count as f32 * DROPDOWN_ROW_HEIGHT) + (DROPDOWN_PADDING * 2.0);
    let content_h = natural_h.min(DROPDOWN_MAX_HEIGHT);

    // Sized container. `FixedSize` forces both axes (content_h
    // shrinks on a short list; the constant width keeps the popover
    // from stretching to fit a long label).
    let sized = FixedSize::new()
        .width(DROPDOWN_WIDTH - DROPDOWN_PADDING * 2.0)
        .height(content_h - DROPDOWN_PADDING * 2.0)
        .child(list);

    // Raised surface — `SurfaceRole::Raised` is the popup-fill
    // token; the `BorderRole::Default` 1 dp border gives the
    // popover a clean edge over arbitrary backgrounds.
    let surface = Panel::new()
        .background(SurfaceRole::Raised)
        .border_color(BorderRole::Default)
        .border_width(1.0)
        .padding(DROPDOWN_PADDING)
        .child(sized);

    ctx.add(
        PopoverIconButton::new(trigger)
            // `surface` is already a chromed `Panel` (Raised) — opt out
            // of the auto popover surface to avoid double-chroming.
            .content(surface)
            .bare()
            .placement(OverlayPlacement::BelowPreferred)
            .has_popup_kind(HasPopup::Menu),
    )
}

// ─── Helper math: drop-insertion index + selection adjust ───────────

/// Pull the layout-axis range `(start, end)` out of a header's world
/// bounds. Horizontal bars use `(x, right)`; vertical bars use
/// `(y, bottom)`.
fn axis_range(rect: &Rect, axis: TabBarOrientation) -> (f32, f32) {
    match axis {
        TabBarOrientation::Horizontal => (rect.x, rect.right()),
        TabBarOrientation::Vertical => (rect.y, rect.bottom()),
    }
}

/// Find the world-coord (along the layout axis) of the insertion-line
/// position closest to `pointer_main`, given each header's world
/// bounds. The returned coordinate is a tab boundary — the leading
/// edge of a header, or the trailing edge of the last header.
fn insertion_world_main_for(bounds: &[Rect], pointer_main: f32, axis: TabBarOrientation) -> f32 {
    let n = bounds.len();
    debug_assert!(n > 0);
    let (_, last_end) = axis_range(&bounds[n - 1], axis);
    if pointer_main >= last_end {
        return last_end;
    }
    let (first_start, _) = axis_range(&bounds[0], axis);
    if pointer_main <= first_start {
        return first_start;
    }
    for header in bounds {
        let (start, end) = axis_range(header, axis);
        let mid = (start + end) * 0.5;
        if pointer_main < mid {
            return start;
        }
    }
    last_end
}

/// Find the model index where the dragged tab should be inserted.
/// `n` items → `n+1` valid insertion indices: 0 means "before the
/// first", `n` means "after the last".
fn insertion_index_for(bounds: &[Rect], pointer_main: f32, axis: TabBarOrientation) -> usize {
    let n = bounds.len();
    if n == 0 {
        return 0;
    }
    let (_, last_end) = axis_range(&bounds[n - 1], axis);
    if pointer_main >= last_end {
        return n;
    }
    let (first_start, _) = axis_range(&bounds[0], axis);
    if pointer_main <= first_start {
        return 0;
    }
    for (i, header) in bounds.iter().enumerate() {
        let (start, end) = axis_range(header, axis);
        let mid = (start + end) * 0.5;
        if pointer_main < mid {
            return i;
        }
    }
    n
}

// Selection adjustment after move/remove is unnecessary now: the
// public selection signal is `Signal<Option<TabId>>`, which is
// stable across reorders by definition (the moved tab keeps its
// id) and across removals it goes stale and the bar's pre-build
// sync routes the id-not-found case to the next-neighbor fallback
// (browser convention).

#[cfg(test)]
mod drop_math_tests {
    use super::*;

    fn three_tabs() -> Vec<Rect> {
        vec![
            Rect::new(0.0, 0.0, 100.0, 30.0),   // x ∈ [0..100)
            Rect::new(100.0, 0.0, 100.0, 30.0), // x ∈ [100..200)
            Rect::new(200.0, 0.0, 100.0, 30.0), // x ∈ [200..300)
        ]
    }

    fn three_tabs_vertical() -> Vec<Rect> {
        vec![
            Rect::new(0.0, 0.0, 200.0, 50.0),   // y ∈ [0..50)
            Rect::new(0.0, 50.0, 200.0, 50.0),  // y ∈ [50..100)
            Rect::new(0.0, 100.0, 200.0, 50.0), // y ∈ [100..150)
        ]
    }

    #[test]
    fn pointer_before_first_tab_inserts_at_zero() {
        let bounds = three_tabs();
        let axis = TabBarOrientation::Horizontal;
        assert_eq!(insertion_index_for(&bounds, -10.0, axis), 0);
        assert_eq!(insertion_world_main_for(&bounds, -10.0, axis), 0.0);
    }

    #[test]
    fn pointer_past_last_tab_appends() {
        let bounds = three_tabs();
        let axis = TabBarOrientation::Horizontal;
        assert_eq!(insertion_index_for(&bounds, 999.0, axis), 3);
        assert_eq!(insertion_world_main_for(&bounds, 999.0, axis), 300.0);
    }

    #[test]
    fn pointer_in_left_half_of_a_tab_inserts_before_it() {
        let bounds = three_tabs();
        let axis = TabBarOrientation::Horizontal;
        // Tab 1 spans 100..200; pointer at x=120 is in its left half.
        assert_eq!(insertion_index_for(&bounds, 120.0, axis), 1);
        assert_eq!(insertion_world_main_for(&bounds, 120.0, axis), 100.0);
    }

    #[test]
    fn pointer_in_right_half_of_a_tab_inserts_after_it() {
        let bounds = three_tabs();
        let axis = TabBarOrientation::Horizontal;
        // Tab 1's right half is 150..200 → insertion at index 2.
        assert_eq!(insertion_index_for(&bounds, 175.0, axis), 2);
        assert_eq!(insertion_world_main_for(&bounds, 175.0, axis), 200.0);
    }

    #[test]
    fn vertical_pointer_above_first_tab_inserts_at_zero() {
        let bounds = three_tabs_vertical();
        let axis = TabBarOrientation::Vertical;
        assert_eq!(insertion_index_for(&bounds, -10.0, axis), 0);
        assert_eq!(insertion_world_main_for(&bounds, -10.0, axis), 0.0);
    }

    #[test]
    fn vertical_pointer_past_last_tab_appends() {
        let bounds = three_tabs_vertical();
        let axis = TabBarOrientation::Vertical;
        assert_eq!(insertion_index_for(&bounds, 999.0, axis), 3);
        assert_eq!(insertion_world_main_for(&bounds, 999.0, axis), 150.0);
    }

    #[test]
    fn vertical_pointer_in_top_half_of_a_tab_inserts_before_it() {
        let bounds = three_tabs_vertical();
        let axis = TabBarOrientation::Vertical;
        // Tab 1 spans y=50..100; pointer at y=60 is in its top half.
        assert_eq!(insertion_index_for(&bounds, 60.0, axis), 1);
        assert_eq!(insertion_world_main_for(&bounds, 60.0, axis), 50.0);
    }

    #[test]
    fn vertical_pointer_in_bottom_half_of_a_tab_inserts_after_it() {
        let bounds = three_tabs_vertical();
        let axis = TabBarOrientation::Vertical;
        // Tab 1's bottom half is y=75..100 → insertion at index 2.
        assert_eq!(insertion_index_for(&bounds, 88.0, axis), 2);
        assert_eq!(insertion_world_main_for(&bounds, 88.0, axis), 100.0);
    }
}

// ─── Helper: a 0×0 widget used as a throwaway return value when we
// only need the side-effect of `ListSource::with_item_fn` (its
// closure access to `&T`), not an actual widget. The probe is
// constructed, returned to `with_item_fn`, and dropped immediately.
// ────────────────────────────────────────────────────────────────────

#[derive(Debug)]
struct EnabledProbe;

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