quadraui 0.6.1

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

use crate::backend::BackendWidget;
use crate::compose::focus_group::FocusGroup;
use crate::event::Rect;
use crate::primitives::drop_zone::{
    drop_zone_hit_test, drop_zone_overlay, DropEdge, DropGroupRect, DropOverlay, DropZone,
    DropZoneHit, DropZoneKind,
};
use crate::primitives::split::{Split, SplitDirection};
// `TabBarHits` is `#[deprecated]` — this compose helper caches
// exactly what `Backend::draw_tab_bar` returns for click/drag dispatch. See
// that struct's doc for the replacement plan.
#[allow(deprecated)]
use crate::primitives::tab_bar::{TabBar, TabBarHits, TabBarSegment, TabItem};
use crate::types::WidgetId;
use crate::Backend;

// ── Recursive layout tree ─────────────────────────────────────────────────────

/// Recursive binary split tree describing how panes are arranged.
///
/// `Leaf(k)` references the pane at index `k` in the controller's internal
/// pane vec. `Split` describes how a rect is divided between two sub-trees.
///
/// In-order leaf traversal gives panes from first (left/top) to last
/// (right/bottom). In-order split traversal gives dividers in the same
/// display order, matching the `divider_idx` used in events and
/// `handle_drag_start`.
///
/// The controller maintains the invariant that every pane vec index `0..n`
/// appears exactly once as a leaf, so `Leaf(k)` always corresponds to pane
/// `k` in the vec.
#[derive(Clone, Debug, PartialEq)]
pub enum GroupLayout {
    /// A single pane (referenced by vec index).
    Leaf(usize),
    /// A binary split: `first` occupies `ratio` of the parent rect,
    /// `second` gets the rest.
    Split {
        /// Split orientation for this node.
        direction: SplitDirection,
        /// Fraction of the parent rect assigned to `first` (0.0–1.0).
        ratio: f32,
        /// Left/top sub-tree.
        first: Box<GroupLayout>,
        /// Right/bottom sub-tree.
        second: Box<GroupLayout>,
    },
}

impl GroupLayout {
    /// Number of leaves in the tree.
    pub fn leaf_count(&self) -> usize {
        match self {
            GroupLayout::Leaf(_) => 1,
            GroupLayout::Split { first, second, .. } => first.leaf_count() + second.leaf_count(),
        }
    }

    /// Whether the tree contains a leaf with value `idx`.
    fn contains_leaf(&self, idx: usize) -> bool {
        match self {
            GroupLayout::Leaf(k) => *k == idx,
            GroupLayout::Split { first, second, .. } => {
                first.contains_leaf(idx) || second.contains_leaf(idx)
            }
        }
    }

    /// Remove the leaf with value `pane_idx`, replacing its parent `Split`
    /// with the surviving sibling. Returns `None` when this node IS the leaf
    /// being removed (signals the caller to replace the parent).
    ///
    /// After calling this, all leaf values > `pane_idx` must be shifted down
    /// with [`shift_indices_down_above`](Self::shift_indices_down_above).
    fn remove_leaf(self, pane_idx: usize) -> Option<Self> {
        match self {
            GroupLayout::Leaf(k) if k == pane_idx => None,
            GroupLayout::Leaf(k) => Some(GroupLayout::Leaf(k)),
            GroupLayout::Split {
                direction,
                ratio,
                first,
                second,
            } => {
                if first.contains_leaf(pane_idx) {
                    match first.remove_leaf(pane_idx) {
                        None => Some(*second),
                        Some(new_first) => Some(GroupLayout::Split {
                            direction,
                            ratio,
                            first: Box::new(new_first),
                            second,
                        }),
                    }
                } else {
                    match second.remove_leaf(pane_idx) {
                        None => Some(*first),
                        Some(new_second) => Some(GroupLayout::Split {
                            direction,
                            ratio,
                            first,
                            second: Box::new(new_second),
                        }),
                    }
                }
            }
        }
    }

    /// Shift all leaf indices > `threshold` down by one.
    ///
    /// Use after [`remove_leaf`](Self::remove_leaf) to keep the vec-index
    /// invariant intact.
    fn shift_indices_down_above(self, threshold: usize) -> Self {
        match self {
            GroupLayout::Leaf(k) => GroupLayout::Leaf(if k > threshold { k - 1 } else { k }),
            GroupLayout::Split {
                direction,
                ratio,
                first,
                second,
            } => GroupLayout::Split {
                direction,
                ratio,
                first: Box::new(first.shift_indices_down_above(threshold)),
                second: Box::new(second.shift_indices_down_above(threshold)),
            },
        }
    }

    /// Collect all leaf values into `out` (in-order traversal).
    fn collect_leaves(&self, out: &mut Vec<usize>) {
        match self {
            GroupLayout::Leaf(k) => out.push(*k),
            GroupLayout::Split { first, second, .. } => {
                first.collect_leaves(out);
                second.collect_leaves(out);
            }
        }
    }

    /// Validate that the tree is a bijection onto `0..n`.
    ///
    /// Returns `Ok(())` when every index in `0..n` appears exactly once as a
    /// leaf. Returns `Err` with a descriptive message otherwise.
    fn validate_for_pane_count(&self, n: usize) -> Result<(), String> {
        let mut leaves = Vec::with_capacity(n);
        self.collect_leaves(&mut leaves);

        if leaves.len() != n {
            return Err(format!(
                "layout has {} leaf nodes but {} panes were provided",
                leaves.len(),
                n
            ));
        }

        let mut seen = vec![false; n];
        for &idx in &leaves {
            if idx >= n {
                return Err(format!(
                    "leaf index {idx} is out of range for {n} panes (indices must be 0..{n})"
                ));
            }
            if seen[idx] {
                return Err(format!(
                    "leaf index {idx} appears more than once in the layout"
                ));
            }
            seen[idx] = true;
        }

        Ok(())
    }

    /// Shift all leaf indices >= `threshold` up by one.
    ///
    /// Use before inserting a new pane into the middle of the vec.
    fn shift_indices_up_from(self, threshold: usize) -> Self {
        match self {
            GroupLayout::Leaf(k) => GroupLayout::Leaf(if k >= threshold { k + 1 } else { k }),
            GroupLayout::Split {
                direction,
                ratio,
                first,
                second,
            } => GroupLayout::Split {
                direction,
                ratio,
                first: Box::new(first.shift_indices_up_from(threshold)),
                second: Box::new(second.shift_indices_up_from(threshold)),
            },
        }
    }

    /// Find `Leaf(target)` and wrap it in a `Split(dir, 0.5, Leaf(new), Leaf(target))`.
    fn insert_before_leaf(self, target: usize, new_idx: usize, dir: SplitDirection) -> Self {
        match self {
            GroupLayout::Leaf(k) if k == target => GroupLayout::Split {
                direction: dir,
                ratio: 0.5,
                first: Box::new(GroupLayout::Leaf(new_idx)),
                second: Box::new(GroupLayout::Leaf(k)),
            },
            GroupLayout::Leaf(k) => GroupLayout::Leaf(k),
            GroupLayout::Split {
                direction,
                ratio,
                first,
                second,
            } => GroupLayout::Split {
                direction,
                ratio,
                first: Box::new(first.insert_before_leaf(target, new_idx, dir)),
                second: Box::new(second.insert_before_leaf(target, new_idx, dir)),
            },
        }
    }

    /// Find `Leaf(target)` and wrap it in a `Split(dir, 0.5, Leaf(target), Leaf(new))`.
    fn insert_after_leaf(self, target: usize, new_idx: usize, dir: SplitDirection) -> Self {
        match self {
            GroupLayout::Leaf(k) if k == target => GroupLayout::Split {
                direction: dir,
                ratio: 0.5,
                first: Box::new(GroupLayout::Leaf(k)),
                second: Box::new(GroupLayout::Leaf(new_idx)),
            },
            GroupLayout::Leaf(k) => GroupLayout::Leaf(k),
            GroupLayout::Split {
                direction,
                ratio,
                first,
                second,
            } => GroupLayout::Split {
                direction,
                ratio,
                first: Box::new(first.insert_after_leaf(target, new_idx, dir)),
                second: Box::new(second.insert_after_leaf(target, new_idx, dir)),
            },
        }
    }
}

// ── Private layout state ──────────────────────────────────────────────────────

/// Cached info about one divider from the last render pass.
struct DividerInfo {
    /// The thin strip that is the visual divider handle.
    divider_bounds: Rect,
    /// Orientation of this split.
    direction: SplitDirection,
    /// Full bounds of the `Split` node (first + divider + second combined).
    /// Used by [`handle_drag_move`](TabGroupController::handle_drag_move) to
    /// recompute the split ratio from cursor position without needing the
    /// caller to pass the global bounds again.
    split_bounds: Rect,
    /// Current ratio (cached so we can redraw without mutating the tree during drag).
    ratio: f32,
}

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

/// One tab within a [`Pane`].
pub struct PaneTab {
    /// Unique identifier within the pane. Used in events and for `active_tab_id`.
    pub id: String,
    /// Display label shown in the tab strip.
    pub label: String,
    /// When `true`, the tab renders a `×` close button.
    pub closable: bool,
    /// Content rendered into the pane body when this tab is active.
    pub content: Box<dyn BackendWidget>,
}

/// One split pane managed by a [`TabGroupController`].
///
/// Panes are not constructed directly; use
/// [`TabGroupController::with_pane`] or
/// [`TabGroupController::add_pane_with_tab`].
pub struct Pane {
    /// Unique identifier for this pane (consumer-chosen, e.g. `"pane:0"`).
    pub id: String,
    tabs: Vec<PaneTab>,
    active_tab_id: String,
    tab_scroll_offset: usize,
}

impl Pane {
    /// Construct a new pane.
    ///
    /// `active_tab_id` is resolved against `tabs`; when the named tab is absent
    /// the first tab's id is used as the fallback.
    ///
    /// Primarily used with [`TabGroupController::from_layout`] to build a
    /// controller from an explicit split tree.
    pub fn new(
        id: impl Into<String>,
        tabs: Vec<PaneTab>,
        active_tab_id: impl Into<String>,
    ) -> Self {
        let active_tab_id = active_tab_id.into();
        // Fallback to first tab when the named one is absent.
        let resolved = if tabs.iter().any(|t| t.id == active_tab_id) {
            active_tab_id
        } else {
            tabs.first().map(|t| t.id.clone()).unwrap_or_default()
        };
        Self {
            id: id.into(),
            tabs,
            active_tab_id: resolved,
            tab_scroll_offset: 0,
        }
    }

    /// The id of the currently-active tab in this pane.
    pub fn active_tab_id(&self) -> &str {
        &self.active_tab_id
    }

    /// Ordered slice of all tabs in this pane.
    pub fn tabs(&self) -> &[PaneTab] {
        &self.tabs
    }

    /// Build the [`TabBar`] descriptor for this pane.
    fn build_tab_bar(&self, pane_idx: usize) -> TabBar {
        let items: Vec<TabItem> = self
            .tabs
            .iter()
            .map(|t| TabItem {
                label: t.label.clone(),
                is_active: t.id == self.active_tab_id,
                is_dirty: false,
                is_preview: false,
                is_closable: t.closable,
            })
            .collect();
        TabBar {
            id: WidgetId::new(format!("tg:pane{}:tabs", pane_idx)),
            tabs: items,
            scroll_offset: self.tab_scroll_offset,
            right_segments: vec![TabBarSegment {
                text: " + ".to_string(),
                width_cells: 3,
                id: Some(WidgetId::new(format!("tg:pane{}:new-tab", pane_idx))),
                is_active: false,
            }],
            active_accent: None,
            show_tab_close: self.tabs.iter().any(|t| t.closable),
            compact: false,
        }
    }

    /// Switch the active tab to `tab_id`. Returns `false` when not found.
    fn activate_tab(&mut self, tab_id: &str) -> bool {
        if self.tabs.iter().any(|t| t.id == tab_id) {
            self.active_tab_id = tab_id.to_string();
            self.tab_scroll_offset = 0;
            true
        } else {
            false
        }
    }

    /// Remove the tab with `tab_id`. Returns `false` when not found.
    /// When the removed tab was active, the previous tab (or first) becomes active.
    fn remove_tab(&mut self, tab_id: &str) -> bool {
        let Some(idx) = self.tabs.iter().position(|t| t.id == tab_id) else {
            return false;
        };
        self.tabs.remove(idx);
        if self.active_tab_id == tab_id {
            // Prefer the tab that was just before the removed one.
            let new_idx = if idx > 0 { idx - 1 } else { 0 };
            self.active_tab_id = self
                .tabs
                .get(new_idx)
                .map(|t| t.id.clone())
                .unwrap_or_default();
        }
        true
    }

    fn is_empty(&self) -> bool {
        self.tabs.is_empty()
    }
}

// ── Events ────────────────────────────────────────────────────────────────────

/// Semantic events emitted by [`TabGroupController`].
#[derive(Debug, Clone, PartialEq)]
pub enum TabGroupEvent {
    /// User activated a tab in `pane_idx`.
    TabActivated { pane_idx: usize, tab_id: String },
    /// User closed a tab in `pane_idx`.
    TabClosed { pane_idx: usize, tab_id: String },
    /// The last tab in `pane_idx` was closed.
    ///
    /// **When more than one pane exists:** the pane is removed and the
    /// controller renumbers the remaining panes.
    ///
    /// **When only one pane remains:** `collapse_pane` is a no-op — the
    /// empty pane is retained in the controller (dropping to zero panes is
    /// not permitted). Consumers should treat this case as "all tabs closed;
    /// the single pane is now empty" and react accordingly (e.g. show a
    /// welcome screen in the content area).
    PaneCollapsed {
        /// Index the pane had *before* collapse.
        pane_idx: usize,
    },
    /// A new pane was added (split). `pane_idx` is its index.
    PaneAdded { pane_idx: usize },
    /// User clicked inside a pane's content area — pane received focus.
    PaneFocused { pane_idx: usize },
    /// User dragged a divider. `divider_idx` is the 0-based in-order index
    /// of the divider (matching the tree's in-order split traversal).
    DividerResized { divider_idx: usize },
    /// User clicked the "+" new-tab button in a pane. Apps should call
    /// [`TabGroupController::add_tab`] in response.
    NewTabRequested { pane_idx: usize },

    // ── Cross-group tab drag events ─────────────────────────────────
    /// A tab was reordered within its pane via drag-and-drop.
    ///
    /// `from_idx` and `to_idx` are the before and after positions in
    /// `pane_idx`'s tab list.
    TabReordered {
        pane_idx: usize,
        /// Id of the tab that moved.
        tab_id: String,
        /// Position before the move.
        from_idx: usize,
        /// Position after the move.
        to_idx: usize,
    },

    /// A tab was dragged from one pane to another (merge).
    ///
    /// The tab was inserted into `to_pane_idx` at `insert_idx`. If the source
    /// pane was left empty it was collapsed; `from_pane_idx` is the index the
    /// source pane held **before** any collapse, and a separate
    /// [`TabGroupEvent::PaneCollapsed`] event is emitted alongside this one
    /// (see [`TabGroupController::handle_tab_drop`] for the event order).
    TabMovedToPane {
        from_pane_idx: usize,
        to_pane_idx: usize,
        tab_id: String,
        /// Position in the target pane's tab list where the tab landed.
        insert_idx: usize,
    },

    /// A tab was dragged to a group edge, creating a new adjacent pane.
    ///
    /// If the source pane was left empty it was collapsed; `from_pane_idx` is
    /// the index it held **before** any collapse, and a separate
    /// [`TabGroupEvent::PaneCollapsed`] event is emitted alongside this one
    /// (see [`TabGroupController::handle_tab_drop`] for the event order).
    /// `new_pane_idx` is the final vec index of the new pane after all
    /// mutations.
    ///
    /// `target_pane_idx` is the **original** index of the target pane (before
    /// any collapse). Both `target_pane_idx` and `new_pane_idx` may shift if
    /// the source pane was collapsed first.
    TabSplitToNewPane {
        from_pane_idx: usize,
        tab_id: String,
        /// The pane whose edge was targeted (original index, pre-collapse).
        target_pane_idx: usize,
        /// Which edge the tab was dropped onto.
        edge: DropEdge,
        /// Final vec index of the newly created pane (post-collapse).
        new_pane_idx: usize,
    },
}

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

/// Resolved pane regions for one rendered frame.
#[derive(Debug, Clone, PartialEq)]
pub struct TabGroupLayout {
    /// Per-pane full bounds (tab strip + content area combined), in pane vec order.
    pub pane_bounds: Vec<Rect>,
    /// Per-pane tab-strip bounds (top row of each pane), in pane vec order.
    pub strip_bounds: Vec<Rect>,
    /// Per-pane content area bounds (below the tab strip), in pane vec order.
    pub content_bounds: Vec<Rect>,
}

/// Externally-supplied geometry for one pane, used by
/// [`TabGroupController::set_drag_geometry`] to prime the drag hit-test cache
/// without a [`render`](TabGroupController::render) pass.
///
/// Consumers that compute their own per-pane layout (e.g. a native backend
/// with its own geometry engine) populate one `PaneDragRect` per pane and
/// pass the slice to `set_drag_geometry`. After that call,
/// [`handle_tab_drag_move`](TabGroupController::handle_tab_drag_move),
/// [`handle_tab_drop`](TabGroupController::handle_tab_drop),
/// [`drop_group_rects`](TabGroupController::drop_group_rects),
/// [`drop_zone_at`](TabGroupController::drop_zone_at), and
/// [`tab_drag_overlay`](TabGroupController::tab_drag_overlay) all work without
/// ever calling `render`.
///
/// `tab_slots` uses the same sentinel convention as [`TabBarHits`]: pass
/// `(0.0, 0.0)` for any tab that is scrolled off the left edge of the strip.
#[derive(Debug, Clone, PartialEq)]
pub struct PaneDragRect {
    /// Bounds of the tab strip row (top of the pane).
    pub strip_bounds: Rect,
    /// Bounds of the pane's content area (below the tab strip).
    pub content_bounds: Rect,
    /// Absolute `(start_x, end_x)` for each tab slot, in pane tab-list order.
    ///
    /// Tabs that are scrolled off the left edge of the strip must be
    /// represented by a `(0.0, 0.0)` sentinel so that indices here stay
    /// aligned with the controller's internal tab vec.
    pub tab_slots: Vec<(f32, f32)>,
}

// ── Host-owned-model adoption ───────────────────────────────────────────────────

/// Identifies the tab being dragged, from the host's *own* pane/tab model.
///
/// Input to [`resolve_tab_drop`]. Unlike [`TabGroupController::handle_tab_drop`],
/// which resolves the dragged tab's current position by searching its own
/// owned `Vec<Pane>`, `resolve_tab_drop` takes the position as given — the
/// host already knows it, because the host owns the model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TabDragSource {
    /// Index of the pane the drag started in, in the host's own pane order.
    pub pane_idx: usize,
    /// Index of the tab within that pane, in the host's own tab order.
    pub tab_idx: usize,
}

/// A position-based drop instruction: the result of resolving a tab
/// drag-and-drop gesture against pane geometry, expressed purely as indices
/// and a split direction — never as a mutation applied to an owned model.
///
/// Returned by [`resolve_tab_drop`]. The host translates each variant into
/// its own mutation (e.g. `Engine::editor_groups[pane_idx].tabs.remove(...)`)
/// instead of `TabGroupController` performing the mutation on a `Vec<Pane>`
/// it would otherwise have to own.
///
/// Mirrors the shape of [`TabGroupEvent`]'s cross-group-drag variants
/// (`TabReordered`, `TabMovedToPane`, `TabSplitToNewPane`, `PaneCollapsed`)
/// deliberately — those were already index/id-based, not
/// `Pane`-object-based; `resolve_tab_drop` just makes it possible to compute
/// them without a `TabGroupController` owning the panes at all.
#[derive(Debug, Clone, PartialEq)]
pub enum TabDropInstruction {
    /// The drop was a no-op: outside every pane, dropped back onto the
    /// source tab's own position, or (for `Split`) the only tab of the
    /// only pane dropped on its own edge.
    NoOp,
    /// Reorder the tab within its own pane.
    Reorder {
        pane_idx: usize,
        /// Position before the move.
        from_idx: usize,
        /// Position after the move.
        to_idx: usize,
    },
    /// Move the tab into a different pane (merge).
    MoveToPane {
        from_pane_idx: usize,
        /// Position the tab held in the source pane before the move.
        from_idx: usize,
        to_pane_idx: usize,
        /// Position in the target pane's tab list where the tab should land.
        insert_idx: usize,
        /// `true` when removing the tab leaves the source pane with zero
        /// tabs — the host should collapse it (or not; `resolve_tab_drop`
        /// never decides that, since collapsing means renumbering the
        /// host's own pane indices, which only the host can do correctly).
        source_now_empty: bool,
    },
    /// Split the target pane, creating a new pane adjacent to it that holds
    /// the dragged tab.
    SplitToNewPane {
        from_pane_idx: usize,
        /// Position the tab held in the source pane before the move.
        from_idx: usize,
        /// The pane whose edge was targeted.
        target_pane_idx: usize,
        /// Which edge the tab was dropped onto.
        edge: DropEdge,
        /// `Left`/`Right` edges split horizontally; `Top`/`Bottom` split
        /// vertically — pre-resolved here so the host doesn't have to
        /// duplicate this mapping.
        split_direction: SplitDirection,
        /// Same meaning as [`TabDropInstruction::MoveToPane::source_now_empty`].
        source_now_empty: bool,
    },
}

/// Resolve a tab drag-and-drop gesture into a [`TabDropInstruction`], using
/// only caller-supplied geometry and drag-source identity — no
/// `TabGroupController`, no owned `Vec<Pane>`.
///
/// This is the adoption path for a host that already owns its tab/pane
/// model (e.g. vimcode's `Engine::editor_groups`, keyed by `GroupId`):
/// build `groups` from your own layout each frame (or drag), and translate
/// the returned instruction into your own mutations directly, without
/// mirroring that model into a second `Vec<Pane>` just to drive drag/drop.
///
/// # Arguments
///
/// * `source` — which pane/tab is being dragged, per the host's own model.
/// * `pane_tab_counts` — tab count of *every* pane, indexed the same way as
///   `groups` (i.e. `pane_tab_counts[i]` is the tab count of the pane
///   described by `groups[i]`). Used to detect an empty-after-removal
///   source pane and to clamp reorder/insert indices — deliberately **not**
///   derived from `groups[i].tab_slots.len()`, since tabs scrolled off a
///   tab strip are omitted from `tab_slots` and would undercount.
/// * `cursor_x`, `cursor_y`, `groups`, `tab_bar_height` — forwarded to
///   [`drop_zone_hit_test`]; see that function's docs.
///
/// [`TabGroupController::handle_tab_drop`] is itself implemented in terms of
/// this function — it is the reference implementation, not a parallel
/// reimplementation that could drift.
pub fn resolve_tab_drop(
    source: TabDragSource,
    pane_tab_counts: &[usize],
    cursor_x: f32,
    cursor_y: f32,
    groups: &[DropGroupRect],
    tab_bar_height: f32,
) -> TabDropInstruction {
    let DropZoneHit::Zone(zone) = drop_zone_hit_test(cursor_x, cursor_y, groups, tab_bar_height)
    else {
        return TabDropInstruction::NoOp;
    };

    let from = source.pane_idx;
    let to = zone.group_idx;
    let cur_idx = source.tab_idx;
    let from_count = pane_tab_counts.get(from).copied().unwrap_or(0);

    // Extracted up-front so the merge arm doesn't need to re-match on
    // `zone.kind` after the outer match has consumed it.
    let reorder_insert_idx = if let DropZoneKind::TabReorder(idx) = zone.kind {
        Some(idx)
    } else {
        None
    };

    match zone.kind {
        // ── Reorder within same pane ────────────────────────────────
        DropZoneKind::TabReorder(insert_idx) if to == from => {
            // Drop at the same position: no-op.
            if cur_idx == insert_idx || cur_idx + 1 == insert_idx {
                return TabDropInstruction::NoOp;
            }
            // After removal, indices > cur_idx shift down by 1.
            let adj = if insert_idx > cur_idx {
                insert_idx - 1
            } else {
                insert_idx
            };
            let adj = adj.min(from_count.saturating_sub(1));
            TabDropInstruction::Reorder {
                pane_idx: from,
                from_idx: cur_idx,
                to_idx: adj,
            }
        }

        // ── No-op: dropped on own content area ──────────────────────
        DropZoneKind::Center if to == from => TabDropInstruction::NoOp,

        // ── Merge: move tab to another pane ─────────────────────────
        DropZoneKind::Center | DropZoneKind::TabReorder(_) => {
            let to_count = pane_tab_counts.get(to).copied().unwrap_or(0);
            let insert_idx = reorder_insert_idx
                .map(|idx| idx.min(to_count))
                .unwrap_or(to_count);
            TabDropInstruction::MoveToPane {
                from_pane_idx: from,
                from_idx: cur_idx,
                to_pane_idx: to,
                insert_idx,
                source_now_empty: from_count <= 1,
            }
        }

        // ── Split: create a new adjacent pane ───────────────────────
        DropZoneKind::Split(edge) => {
            // Guard: splitting the only tab of the only pane is a no-op.
            if from_count == 1 && pane_tab_counts.len() == 1 {
                return TabDropInstruction::NoOp;
            }
            let split_direction = match edge {
                DropEdge::Left | DropEdge::Right => SplitDirection::Horizontal,
                DropEdge::Top | DropEdge::Bottom => SplitDirection::Vertical,
            };
            TabDropInstruction::SplitToNewPane {
                from_pane_idx: from,
                from_idx: cur_idx,
                target_pane_idx: to,
                edge,
                split_direction,
                source_now_empty: from_count <= 1,
            }
        }
    }
}

// ── Controller ────────────────────────────────────────────────────────────────

/// Stateful controller that manages N split panes arranged in a recursive
/// H/V split tree, each pane with its own tab bar.
///
/// # Typical lifecycle
///
/// ```ignore
/// // Create with one initial pane.
/// let mut group = TabGroupController::with_pane(
///     "pane:0", initial_tabs, "tab-0", SplitDirection::Horizontal
/// );
///
/// // Open a second pane (creates a split).
/// let pane_idx = group.add_pane_with_tab(
///     "pane:1",
///     PaneTab { id: "t-x".into(), label: "new.rs".into(),
///               closable: true, content: Box::new(MyContent) },
/// );
///
/// // In render:
/// let layout = group.render(backend, content_rect);
///
/// // In handle (try tab drag before divider drag):
/// if group.handle_tab_drag_start(x, y) {
///     tab_drag_active = true;
/// } else if group.handle_drag_start(x, y) {
///     divider_drag_active = true;
/// }
/// ```
pub struct TabGroupController {
    panes: Vec<Pane>,
    focus: FocusGroup,
    /// Recursive split tree. `Leaf(k)` references `panes[k]`.
    /// Maintained so that the vec index of every pane equals the leaf value
    /// that references it.
    layout: GroupLayout,
    /// Default direction used by [`add_pane_with_tab`](Self::add_pane_with_tab).
    default_split_direction: SplitDirection,
    /// Monotonically incrementing counter for generating unique pane IDs.
    next_pane_counter: usize,

    // ── Hit-test cache from last render ────────────────────────────
    last_bounds: Option<Rect>,
    /// Per-pane: (hits, strip_bounds). `None` before first render.
    /// Indexed by pane vec index.
    last_pane_hits: Vec<Option<PaneHitCache>>,
    /// Dividers from the last render (in-order split traversal). N-1 entries
    /// for N panes.
    last_dividers: Vec<DividerInfo>,

    // ── Interaction state ───────────────────────────────────────────
    /// Index of the divider currently being dragged, if any.
    dragging_divider: Option<usize>,
    /// In-progress tab drag, if any (mutually exclusive with `dragging_divider`).
    dragging_tab: Option<TabDragState>,
}

/// Cached hit-test state for one pane from the last render.
struct PaneHitCache {
    #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
    hits: TabBarHits,
    strip_bounds: Rect,
    content_bounds: Rect,
}

/// In-progress tab drag state.
struct TabDragState {
    /// Index of the pane the drag started in.
    source_pane_idx: usize,
    /// Id of the tab being dragged.
    tab_id: String,
    /// Most recently computed drop zone (updated by [`handle_tab_drag_move`]).
    ///
    /// [`handle_tab_drag_move`]: TabGroupController::handle_tab_drag_move
    current_zone: Option<DropZone>,
    /// Last known cursor position (used by [`render`] to draw the overlay).
    ///
    /// [`render`]: TabGroupController::render
    cursor_x: f32,
    cursor_y: f32,
}

impl TabGroupController {
    // ── Constructors ────────────────────────────────────────────────

    /// Create a controller with a single pane.
    pub fn with_pane(
        pane_id: impl Into<String>,
        tabs: Vec<PaneTab>,
        active_tab_id: impl Into<String>,
        split_direction: SplitDirection,
    ) -> Self {
        let pane = Pane::new(pane_id, tabs, active_tab_id);
        Self {
            panes: vec![pane],
            focus: FocusGroup::new(1),
            layout: GroupLayout::Leaf(0),
            default_split_direction: split_direction,
            next_pane_counter: 1,
            last_bounds: None,
            last_pane_hits: (0..1).map(|_| None).collect(),
            last_dividers: vec![],
            dragging_divider: None,
            dragging_tab: None,
        }
    }

    /// Construct a controller from an explicit pane list and layout tree.
    ///
    /// This is the primary constructor when the caller already owns an
    /// arbitrary mixed-direction split tree — for example, when reconstructing
    /// a saved session that mixes horizontal and vertical splits.
    ///
    /// # Arguments
    ///
    /// * `panes` — the ordered pane vec; use [`Pane::new`] to build each entry.
    ///   Must be non-empty.
    /// * `layout` — the binary split tree. Every index `0..panes.len()` must
    ///   appear **exactly once** as a `Leaf`; the tree must contain no other
    ///   indices.
    /// * `default_split_direction` — the direction used by future
    ///   [`add_pane_with_tab`](Self::add_pane_with_tab) calls.
    ///
    /// # Errors
    ///
    /// Returns `Err(message)` when:
    ///
    /// * `panes` is empty.
    /// * The layout contains a leaf index ≥ `panes.len()`.
    /// * A leaf index appears more than once.
    /// * The number of leaves ≠ `panes.len()`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Three panes: left | (top-right / bottom-right)
    /// let layout = GroupLayout::Split {
    ///     direction: SplitDirection::Horizontal,
    ///     ratio: 0.5,
    ///     first: Box::new(GroupLayout::Leaf(0)),
    ///     second: Box::new(GroupLayout::Split {
    ///         direction: SplitDirection::Vertical,
    ///         ratio: 0.5,
    ///         first:  Box::new(GroupLayout::Leaf(1)),
    ///         second: Box::new(GroupLayout::Leaf(2)),
    ///     }),
    /// };
    /// let ctrl = TabGroupController::from_layout(
    ///     vec![
    ///         Pane::new("pane:0", left_tabs,        "t0"),
    ///         Pane::new("pane:1", top_right_tabs,   "t1"),
    ///         Pane::new("pane:2", bottom_right_tabs,"t2"),
    ///     ],
    ///     layout,
    ///     SplitDirection::Horizontal,
    /// )?;
    /// ```
    pub fn from_layout(
        panes: Vec<Pane>,
        layout: GroupLayout,
        default_split_direction: SplitDirection,
    ) -> Result<Self, String> {
        let n = panes.len();
        if n == 0 {
            return Err("panes must be non-empty".into());
        }
        layout.validate_for_pane_count(n)?;
        Ok(Self {
            panes,
            focus: FocusGroup::new(n),
            layout,
            default_split_direction,
            // Start auto-generated drag-split IDs above n so names like
            // "pane:0", "pane:1", … (that the consumer may have used) are
            // not repeated by the first handle_tab_drop split.
            next_pane_counter: n,
            last_bounds: None,
            last_pane_hits: (0..n).map(|_| None).collect(),
            last_dividers: vec![],
            dragging_divider: None,
            dragging_tab: None,
        })
    }

    // ── Accessors ───────────────────────────────────────────────────

    /// Number of panes currently open.
    pub fn pane_count(&self) -> usize {
        self.panes.len()
    }

    /// Borrow the pane at `idx`, or `None` if out of range.
    pub fn pane(&self, idx: usize) -> Option<&Pane> {
        self.panes.get(idx)
    }

    /// Index of the currently focused pane, or `None` when nothing is focused.
    pub fn focused_pane(&self) -> Option<usize> {
        self.focus.active()
    }

    /// Explicitly focus a pane. Out-of-range indices are clamped.
    pub fn focus_pane(&mut self, pane_idx: usize) {
        if !self.panes.is_empty() {
            let clamped = pane_idx.min(self.panes.len() - 1);
            self.focus.set_active(Some(clamped));
        }
    }

    /// Cycle focus forward (+1) or backward (−1) across panes.
    pub fn cycle_focus(&mut self, delta: isize) {
        self.focus.cycle(delta);
    }

    /// Read-only reference to the layout tree.
    pub fn layout(&self) -> &GroupLayout {
        &self.layout
    }

    // ── Tab lifecycle ───────────────────────────────────────────────

    /// Add a tab to the pane at `pane_idx`. Returns `false` if the index is
    /// out of range. Does **not** activate the new tab.
    pub fn add_tab(&mut self, pane_idx: usize, tab: PaneTab) -> bool {
        if let Some(pane) = self.panes.get_mut(pane_idx) {
            pane.tabs.push(tab);
            true
        } else {
            false
        }
    }

    /// Add a tab to `pane_idx` and make it active immediately.
    pub fn add_and_activate_tab(&mut self, pane_idx: usize, tab: PaneTab) -> bool {
        let id = tab.id.clone();
        if self.add_tab(pane_idx, tab) {
            self.panes[pane_idx].activate_tab(&id);
            true
        } else {
            false
        }
    }

    /// Switch the active tab in `pane_idx` to `tab_id`.
    /// Returns `false` when the pane index or tab id is not found.
    pub fn switch_tab(&mut self, pane_idx: usize, tab_id: &str) -> bool {
        self.panes
            .get_mut(pane_idx)
            .map(|p| p.activate_tab(tab_id))
            .unwrap_or(false)
    }

    /// Close a tab in `pane_idx`. Returns the event produced (which may be
    /// `PaneCollapsed` when the last tab is closed), or `None` when the pane
    /// index / tab id is not found.
    pub fn close_tab(&mut self, pane_idx: usize, tab_id: &str) -> Option<TabGroupEvent> {
        let pane = self.panes.get_mut(pane_idx)?;
        if !pane.remove_tab(tab_id) {
            return None;
        }
        let tab_id_owned = tab_id.to_string();
        if pane.is_empty() {
            // Collapse the pane.
            self.collapse_pane(pane_idx);
            Some(TabGroupEvent::PaneCollapsed { pane_idx })
        } else {
            Some(TabGroupEvent::TabClosed {
                pane_idx,
                tab_id: tab_id_owned,
            })
        }
    }

    // ── Pane lifecycle ──────────────────────────────────────────────

    /// Open a new pane containing a single tab. The new pane is inserted after
    /// the currently focused pane (splitting it), or appended at the end when
    /// no pane is focused. The split direction is the controller's
    /// `default_split_direction` (set via [`with_pane`](Self::with_pane)).
    ///
    /// Returns the vec index of the new pane.
    pub fn add_pane_with_tab(&mut self, pane_id: impl Into<String>, tab: PaneTab) -> usize {
        let tab_id = tab.id.clone();
        let new_pane = Pane::new(pane_id, vec![tab], tab_id);

        // Insert after the focused pane (or at the end).
        let focused = self
            .focus
            .active()
            .unwrap_or_else(|| self.panes.len().saturating_sub(1));
        let insert_pos = (focused + 1).min(self.panes.len());

        // Update the tree: shift all leaf indices >= insert_pos up by 1, then
        // wrap the focused pane's leaf in a new Split with the new pane after it.
        self.layout = self.layout.clone().shift_indices_up_from(insert_pos);
        self.panes.insert(insert_pos, new_pane);
        // After shift, focused leaf is still `focused` (we shifted indices >= insert_pos
        // = focused+1, not focused itself).
        self.layout = self.layout.clone().insert_after_leaf(
            focused,
            insert_pos,
            self.default_split_direction,
        );

        let n = self.panes.len();
        self.focus.set_count(n);
        self.focus.set_active(Some(insert_pos));
        self.last_pane_hits = (0..n).map(|_| None).collect();
        self.last_dividers = vec![];

        insert_pos
    }

    /// Remove and drop the pane at `pane_idx`, giving its space to the
    /// nearest sibling in the split tree. No-op when only one pane remains.
    pub fn collapse_pane(&mut self, pane_idx: usize) {
        if self.panes.len() <= 1 || pane_idx >= self.panes.len() {
            return;
        }

        // Remove the leaf from the tree, replacing its parent Split with the sibling.
        let new_layout = self
            .layout
            .clone()
            .remove_leaf(pane_idx)
            .expect("pane_idx must exist as a leaf in the layout tree");
        // Shift down all leaf indices > pane_idx.
        self.layout = new_layout.shift_indices_down_above(pane_idx);

        // Remove from the pane vec.
        self.panes.remove(pane_idx);

        let n = self.panes.len();
        self.focus.set_count(n);
        if let Some(fi) = self.focus.active() {
            if fi >= n {
                self.focus.set_active(n.checked_sub(1));
            }
        }
        self.last_pane_hits = (0..n).map(|_| None).collect();
        self.last_dividers = vec![];
    }

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

    /// Render all panes into `bounds`. Calls `backend.draw_split` for each
    /// inter-pane divider and `backend.draw_tab_bar` for each pane's tab
    /// strip. Active-pane content is rendered via [`BackendWidget::render`].
    /// When a tab drag is active, automatically calls
    /// `backend.draw_drop_overlay` at the end of the frame.
    ///
    /// Returns a [`TabGroupLayout`] with resolved pane/strip/content rects
    /// in pane vec order.
    #[allow(deprecated)] // `Backend::draw_tab_bar` returns `TabBarHits` — issue #823
    pub fn render(&mut self, backend: &mut dyn Backend, bounds: Rect) -> TabGroupLayout {
        if self.panes.is_empty() {
            return TabGroupLayout {
                pane_bounds: vec![],
                strip_bounds: vec![],
                content_bounds: vec![],
            };
        }

        self.last_bounds = Some(bounds);
        let n = self.panes.len();

        // ── Step 1: compute per-pane bounds via recursive layout ────
        let mut pane_bounds_by_idx: Vec<Option<Rect>> = vec![None; n];
        self.last_dividers.clear();
        layout_recursive(
            &self.layout,
            backend,
            bounds,
            &mut pane_bounds_by_idx,
            &mut self.last_dividers,
        );

        // ── Step 2: draw dividers ───────────────────────────────────
        for (i, info) in self.last_dividers.iter().enumerate() {
            let split = Split {
                id: WidgetId::new(format!("tg:div{}", i)),
                direction: info.direction,
                ratio: info.ratio,
                first_min: 0.0,
                second_min: 0.0,
            };
            backend.draw_split(info.split_bounds, &split);
        }

        // ── Step 3: for each pane, draw tab strip + content ─────────
        let lh = backend.chrome_line_height();
        let mut pane_bounds_out = Vec::with_capacity(n);
        let mut strip_bounds = Vec::with_capacity(n);
        let mut content_bounds = Vec::with_capacity(n);

        if self.last_pane_hits.len() != n {
            self.last_pane_hits = (0..n).map(|_| None).collect();
        }

        for (pane_idx, pane) in self.panes.iter_mut().enumerate() {
            let pb = pane_bounds_by_idx[pane_idx].unwrap_or(bounds);

            let strip = Rect::new(pb.x, pb.y, pb.width, lh);
            let content_h = (pb.height - lh).max(0.0);
            let content = Rect::new(pb.x, pb.y + lh, pb.width, content_h);

            pane_bounds_out.push(pb);
            strip_bounds.push(strip);
            content_bounds.push(content);

            // Draw tab bar.
            let tab_bar = pane.build_tab_bar(pane_idx);
            let hits = backend.draw_tab_bar(strip, &tab_bar, None);
            pane.tab_scroll_offset = hits.correct_scroll_offset;

            // Render active content.
            if content.width > 0.0 && content.height > 0.0 {
                if let Some(tab_pos) = pane.tabs.iter().position(|t| t.id == pane.active_tab_id) {
                    pane.tabs[tab_pos].content.render(backend, content);
                }
            }

            self.last_pane_hits[pane_idx] = Some(PaneHitCache {
                hits,
                strip_bounds: strip,
                content_bounds: content,
            });
        }

        // ── Step 4: draw drop overlay when a tab drag is in progress ─
        // Compute the overlay before borrowing backend mutably.
        let overlay: Option<DropOverlay> = if let Some(drag) = self.dragging_tab.as_ref() {
            if drag.current_zone.is_some() {
                let ghost_offset = lh;
                self.tab_drag_overlay(drag.cursor_x, drag.cursor_y, 2.0, ghost_offset)
            } else {
                None
            }
        } else {
            None
        };
        if let Some(ov) = overlay {
            backend.draw_drop_overlay(&ov);
        }

        TabGroupLayout {
            pane_bounds: pane_bounds_out,
            strip_bounds,
            content_bounds,
        }
    }

    // ── Click dispatch ──────────────────────────────────────────────

    /// Resolve a mouse click at `(x, y)` in viewport coordinates.
    ///
    /// Applies resulting state changes (tab activation, close, pane focus)
    /// and returns the emitted event. Returns `None` when the click is
    /// outside all tab strips and content areas, or on dead space.
    ///
    /// Typical call site: mouse-down handler after background dismissal.
    #[allow(deprecated)] // reads the deprecated `TabBarHits` cache — issue #823
    pub fn handle_click(&mut self, x: f32, y: f32) -> Option<TabGroupEvent> {
        let n = self.panes.len();
        let click_x = x as f64;
        let in_range = |range: (f64, f64)| click_x >= range.0 && click_x < range.1;

        for pane_idx in 0..n {
            let Some(cache) = self.last_pane_hits[pane_idx].as_ref() else {
                continue;
            };
            let strip = cache.strip_bounds;
            let content = cache.content_bounds;
            let hits = &cache.hits;

            // ── Tab strip click ───────────────────────────────────
            let in_strip = y >= strip.y
                && y < strip.y + strip.height
                && x >= strip.x
                && x < strip.x + strip.width;
            if in_strip {
                // Focus this pane.
                self.focus.set_active(Some(pane_idx));

                // Close buttons take precedence.
                for (idx, cb) in hits.close_bounds.iter().enumerate() {
                    if let Some(range) = cb {
                        if in_range(*range) {
                            if let Some(tab) = self.panes[pane_idx].tabs.get(idx) {
                                if tab.closable {
                                    let tab_id = tab.id.clone();
                                    return self.close_tab(pane_idx, &tab_id);
                                }
                            }
                            return None;
                        }
                    }
                }

                // Right segments (new-tab button).
                for rb in &hits.right_segment_bounds {
                    if in_range(*rb) {
                        return Some(TabGroupEvent::NewTabRequested { pane_idx });
                    }
                }

                // Tab body.
                for (idx, range) in hits.slot_positions.iter().enumerate() {
                    if in_range(*range) {
                        if let Some(tab) = self.panes[pane_idx].tabs.get(idx) {
                            let tab_id = tab.id.clone();
                            if tab_id != self.panes[pane_idx].active_tab_id {
                                self.panes[pane_idx].activate_tab(&tab_id);
                                return Some(TabGroupEvent::TabActivated { pane_idx, tab_id });
                            }
                        }
                        return None;
                    }
                }
                return None;
            }

            // ── Content area click → focus ────────────────────────
            let in_content = y >= content.y
                && y < content.y + content.height
                && x >= content.x
                && x < content.x + content.width;
            if in_content {
                if self.focus.active() != Some(pane_idx) {
                    self.focus.set_active(Some(pane_idx));
                    return Some(TabGroupEvent::PaneFocused { pane_idx });
                }
                return None;
            }
        }
        None
    }

    // ── Divider drag ────────────────────────────────────────────────

    /// Start a drag if `(x, y)` is on a divider. Returns `true` when a
    /// drag was initiated.
    pub fn handle_drag_start(&mut self, x: f32, y: f32) -> bool {
        for (i, info) in self.last_dividers.iter().enumerate() {
            let d = &info.divider_bounds;
            if x >= d.x && x < d.x + d.width && y >= d.y && y < d.y + d.height {
                self.dragging_divider = Some(i);
                return true;
            }
        }
        false
    }

    /// Update the dragged divider position. Returns a `DividerResized` event
    /// when the split ratio changes. Call with each mouse-moved event while
    /// dragging.
    ///
    /// The `bounds` parameter is accepted for API compatibility but is no
    /// longer needed — the controller uses the cached split bounds from the
    /// last render instead.
    pub fn handle_drag_move(&mut self, x: f32, y: f32, _bounds: Rect) -> Option<TabGroupEvent> {
        let div_idx = self.dragging_divider?;
        let info = self.last_dividers.get(div_idx)?;

        // Compute new ratio from cursor position relative to the split's own bounds.
        let new_ratio = match info.direction {
            SplitDirection::Horizontal => {
                if info.split_bounds.width > 0.0 {
                    ((x - info.split_bounds.x) / info.split_bounds.width).clamp(0.05, 0.95)
                } else {
                    return None;
                }
            }
            SplitDirection::Vertical => {
                if info.split_bounds.height > 0.0 {
                    ((y - info.split_bounds.y) / info.split_bounds.height).clamp(0.05, 0.95)
                } else {
                    return None;
                }
            }
        };

        let mut counter = 0usize;
        let changed =
            update_split_ratio_inorder(&mut self.layout, div_idx, new_ratio, &mut counter)
                .unwrap_or(false);

        if changed {
            Some(TabGroupEvent::DividerResized {
                divider_idx: div_idx,
            })
        } else {
            None
        }
    }

    /// End any active divider drag.
    pub fn handle_drag_end(&mut self) {
        self.dragging_divider = None;
    }

    // ── DropZone integration ────────────────────────────────────────

    /// Return [`DropGroupRect`]s for all panes from the last render, suitable
    /// for passing to [`crate::compute_drop_zone`].
    ///
    /// Tab slot positions are derived from the last [`TabBarHits`] recorded
    /// during [`render`](Self::render). If `render` has not been called yet,
    /// the result is empty.
    #[allow(deprecated)] // reads the deprecated `TabBarHits` cache — issue #823
    pub fn drop_group_rects(&self) -> Vec<DropGroupRect> {
        self.last_pane_hits
            .iter()
            .filter_map(|cache| {
                let c = cache.as_ref()?;
                let strip = c.strip_bounds;
                // Full pane bounds = strip + content.
                let full = Rect::new(
                    strip.x,
                    strip.y,
                    strip.width,
                    strip.height + c.content_bounds.height,
                );
                // Convert slot_positions (absolute x pairs) into (start, end) pairs.
                let tab_slots: Vec<(f32, f32)> = c
                    .hits
                    .slot_positions
                    .iter()
                    .filter(|(s, e)| *s != 0.0 || *e != 0.0)
                    .map(|(s, e)| (*s as f32, *e as f32))
                    .collect();
                Some(DropGroupRect {
                    bounds: full,
                    tab_slots,
                })
            })
            .collect()
    }

    /// Prime drag hit-test geometry from externally-computed pane rects, so
    /// [`handle_tab_drag_move`](Self::handle_tab_drag_move),
    /// [`handle_tab_drop`](Self::handle_tab_drop),
    /// [`drop_group_rects`](Self::drop_group_rects),
    /// [`drop_zone_at`](Self::drop_zone_at), and
    /// [`tab_drag_overlay`](Self::tab_drag_overlay) work without a
    /// [`render`](Self::render) pass.
    ///
    /// Use this when your application already owns and renders its own per-pane
    /// layout — for example a native backend that computes geometry
    /// independently. Without calling `render`, the drop-zone logic would have
    /// no data to work from; this method injects that data directly so drag
    /// logic can proceed headlessly (useful for unit tests, too).
    ///
    /// The `panes` slice must be in the same order as the controller's internal
    /// pane vec (index 0 corresponds to pane 0, etc.). Excess entries beyond
    /// [`pane_count`](Self::pane_count) are silently ignored; if `panes` is
    /// shorter than the pane count the remaining panes are left un-primed
    /// (their drag geometry stays `None`).
    ///
    /// # Interaction with `handle_tab_drag_start`
    ///
    /// [`handle_tab_drag_start`](Self::handle_tab_drag_start) detects which tab
    /// is under the cursor from `tab_slots` and also checks close-button /
    /// right-segment bounds to reject those click targets. Because
    /// `PaneDragRect` does not carry those bounds (they come from the tab-bar
    /// renderer), close-button and right-segment exclusion is skipped for panes
    /// primed via `set_drag_geometry`. If your consumer already excludes those
    /// targets before routing to the controller, this is fine. If you need full
    /// exclusion, call `render()` instead.
    #[allow(deprecated)] // constructs the deprecated `TabBarHits` — issue #823
    pub fn set_drag_geometry(&mut self, panes: &[PaneDragRect]) {
        let n = self.panes.len();
        if self.last_pane_hits.len() != n {
            self.last_pane_hits = (0..n).map(|_| None).collect();
        }
        for (pane_idx, drag_rect) in panes.iter().enumerate().take(n) {
            let slot_positions: Vec<(f64, f64)> = drag_rect
                .tab_slots
                .iter()
                .map(|(s, e)| (*s as f64, *e as f64))
                .collect();
            let n_slots = slot_positions.len();
            let hits = crate::primitives::tab_bar::TabBarHits {
                slot_positions,
                close_bounds: vec![None; n_slots],
                right_segment_bounds: vec![],
                available_cols: 0,
                correct_scroll_offset: 0,
            };
            self.last_pane_hits[pane_idx] = Some(PaneHitCache {
                hits,
                strip_bounds: drag_rect.strip_bounds,
                content_bounds: drag_rect.content_bounds,
            });
        }
    }

    // ── Cross-group tab drag ────────────────────────────────────────

    /// Return the strip height from cached render data, or a default of 1.0.
    fn strip_height(&self) -> f32 {
        self.last_pane_hits
            .iter()
            .find_map(|c| c.as_ref().map(|c| c.strip_bounds.height))
            .unwrap_or(1.0)
    }

    /// Start a tab drag if `(x, y)` lands on a draggable tab slot (not a
    /// close button or the new-tab segment). Returns `true` when a drag was
    /// initiated; `false` means the caller should fall through to
    /// [`handle_click`](Self::handle_click).
    ///
    /// A tab drag and a divider drag are mutually exclusive; starting one
    /// implicitly cancels the other.
    #[allow(deprecated)] // reads the deprecated `TabBarHits` cache — issue #823
    pub fn handle_tab_drag_start(&mut self, x: f32, y: f32) -> bool {
        let click_x = x as f64;
        let in_range = |range: (f64, f64)| click_x >= range.0 && click_x < range.1;

        let n = self.panes.len();
        for pane_idx in 0..n {
            let Some(cache) = self.last_pane_hits[pane_idx].as_ref() else {
                continue;
            };
            let strip = cache.strip_bounds;
            let hits = &cache.hits;

            let in_strip = y >= strip.y
                && y < strip.y + strip.height
                && x >= strip.x
                && x < strip.x + strip.width;
            if !in_strip {
                continue;
            }

            // Reject close buttons — those are click actions, not drags.
            for range in hits.close_bounds.iter().flatten() {
                if in_range(*range) {
                    return false;
                }
            }
            // Reject right segments (new-tab button etc.).
            for rb in &hits.right_segment_bounds {
                if in_range(*rb) {
                    return false;
                }
            }

            // Accept any tab slot.
            for (tab_idx, range) in hits.slot_positions.iter().enumerate() {
                if in_range(*range) {
                    if let Some(tab) = self.panes[pane_idx].tabs.get(tab_idx) {
                        self.dragging_divider = None;
                        self.dragging_tab = Some(TabDragState {
                            source_pane_idx: pane_idx,
                            tab_id: tab.id.clone(),
                            current_zone: None,
                            cursor_x: x,
                            cursor_y: y,
                        });
                        return true;
                    }
                    return false;
                }
            }
        }
        false
    }

    /// Update the drag position. Returns the current [`DropZone`] under the
    /// cursor, or `None` when no drag is in progress or the cursor is outside
    /// all groups.
    ///
    /// Call on every mouse-moved event while dragging. The result can be
    /// passed to [`drop_zone_overlay`] directly,
    /// or use [`tab_drag_overlay`](Self::tab_drag_overlay) as a convenience.
    pub fn handle_tab_drag_move(&mut self, x: f32, y: f32) -> Option<DropZone> {
        self.dragging_tab.as_ref()?;
        let groups = self.drop_group_rects();
        let tab_bar_h = self.strip_height();
        // Routed through `drop_zone_hit_test` rather than
        // `compute_drop_zone` directly — same geometry, but this is now
        // the primitive's canonical hit-test entry point.
        let zone = match drop_zone_hit_test(x, y, &groups, tab_bar_h) {
            DropZoneHit::Zone(z) => Some(z),
            DropZoneHit::Empty => None,
        };
        if let Some(drag) = &mut self.dragging_tab {
            drag.current_zone = zone.clone();
            drag.cursor_x = x;
            drag.cursor_y = y;
        }
        zone
    }

    /// Compute the drop overlay for the current tab drag, ready to hand to
    /// the backend's drop-overlay renderer.
    ///
    /// Uses the [`DropZone`] last stored by [`handle_tab_drag_move`]. Returns
    /// `None` when no tab drag is in progress or no drop zone has been
    /// resolved yet (cursor was outside all groups).
    ///
    /// `bar_thickness` is the insertion-bar width in logical units (typically
    /// 2–3 px for GTK, 1 cell for TUI). `ghost_offset` is how far the ghost
    /// label floats from the cursor (typically one line height).
    ///
    /// Note: [`render`](Self::render) calls this automatically and passes the
    /// overlay to `backend.draw_drop_overlay`. Only call this directly if you
    /// need the overlay for a custom rendering path.
    pub fn tab_drag_overlay(
        &self,
        cursor_x: f32,
        cursor_y: f32,
        bar_thickness: f32,
        ghost_offset: f32,
    ) -> Option<DropOverlay> {
        let drag = self.dragging_tab.as_ref()?;
        let zone = drag.current_zone.as_ref()?;
        let groups = self.drop_group_rects();
        let tab_bar_h = self.strip_height();
        Some(drop_zone_overlay(
            zone,
            &groups,
            cursor_x,
            cursor_y,
            tab_bar_h,
            bar_thickness,
            ghost_offset,
        ))
    }

    /// Finalise a tab drag by applying the drop at `(x, y)`.
    ///
    /// Returns the list of [`TabGroupEvent`]s describing the resulting
    /// mutation, in temporal order. An empty `Vec` means the drop was a no-op
    /// (no drag in progress, cursor outside all groups, dropped on the source
    /// pane's own content, dropped at the same tab position, or attempted to
    /// split the only tab of the only pane).
    ///
    /// Handles three cases:
    ///
    /// * **Reorder within the same pane** — `DropZoneKind::TabReorder` on the
    ///   source pane: reorders the tab list and emits a single
    ///   [`TabGroupEvent::TabReordered`].
    /// * **Merge into another pane** — `DropZoneKind::Center` or
    ///   `DropZoneKind::TabReorder` on a different pane: moves the tab and
    ///   emits [`TabGroupEvent::TabMovedToPane`]. If the source pane is left
    ///   empty it is collapsed and an additional
    ///   [`TabGroupEvent::PaneCollapsed`] (with the source's pre-collapse
    ///   index) is appended.
    /// * **Split to new pane** — `DropZoneKind::Split`: removes the tab from
    ///   its pane, creates a new pane adjacent to the target, and emits
    ///   [`TabGroupEvent::TabSplitToNewPane`]. If the source pane is left
    ///   empty it is collapsed and an additional
    ///   [`TabGroupEvent::PaneCollapsed`] is appended. Dropping the only tab
    ///   of the only pane onto its own edge is a no-op. `Left`/`Right` edges
    ///   create a **horizontal** split; `Top`/`Bottom` edges create a
    ///   **vertical** split.
    ///
    /// Clears drag state regardless of outcome.
    ///
    /// Implemented in terms of [`resolve_tab_drop`] — this method is the
    /// reference translation of a [`TabDropInstruction`] into mutations on
    /// the controller's own owned `Vec<Pane>`. A host with its own model
    /// calls `resolve_tab_drop` directly and writes an equivalent
    /// translation against its own data instead.
    pub fn handle_tab_drop(&mut self, x: f32, y: f32) -> Vec<TabGroupEvent> {
        let Some(drag) = self.dragging_tab.take() else {
            return Vec::new();
        };
        let groups = self.drop_group_rects();
        let tab_bar_h = self.strip_height();

        let from = drag.source_pane_idx;
        let Some(cur_idx) = self.panes[from]
            .tabs
            .iter()
            .position(|t| t.id == drag.tab_id)
        else {
            return Vec::new();
        };

        let pane_tab_counts: Vec<usize> = self.panes.iter().map(|p| p.tabs.len()).collect();
        let source = TabDragSource {
            pane_idx: from,
            tab_idx: cur_idx,
        };
        let instruction = resolve_tab_drop(source, &pane_tab_counts, x, y, &groups, tab_bar_h);

        match instruction {
            TabDropInstruction::NoOp => Vec::new(),

            // ── Reorder within same pane ────────────────────────────
            TabDropInstruction::Reorder {
                pane_idx,
                from_idx,
                to_idx,
            } => {
                let moved_tab = self.panes[pane_idx].tabs.remove(from_idx);
                self.panes[pane_idx].tabs.insert(to_idx, moved_tab);
                vec![TabGroupEvent::TabReordered {
                    pane_idx,
                    tab_id: drag.tab_id,
                    from_idx,
                    to_idx,
                }]
            }

            // ── Merge: move tab to another pane ─────────────────────
            TabDropInstruction::MoveToPane {
                from_pane_idx,
                from_idx,
                to_pane_idx,
                insert_idx,
                source_now_empty,
            } => {
                let moved_tab = self.panes[from_pane_idx].tabs.remove(from_idx);
                // Fix active tab in source pane.
                if self.panes[from_pane_idx].active_tab_id == drag.tab_id {
                    let fallback = if from_idx > 0 { from_idx - 1 } else { 0 };
                    self.panes[from_pane_idx].active_tab_id = self.panes[from_pane_idx]
                        .tabs
                        .get(fallback)
                        .map(|t| t.id.clone())
                        .unwrap_or_default();
                }
                let tab_id = moved_tab.id.clone();
                self.panes[to_pane_idx].tabs.insert(insert_idx, moved_tab);
                self.panes[to_pane_idx].active_tab_id = tab_id.clone();

                // Collapse source pane if empty; adjust the reported target index.
                let final_to = if source_now_empty {
                    self.collapse_pane(from_pane_idx);
                    // collapse_pane removes index `from_pane_idx`; all indices
                    // above it shift down.
                    if from_pane_idx < to_pane_idx {
                        to_pane_idx - 1
                    } else {
                        to_pane_idx
                    }
                } else {
                    to_pane_idx
                };

                let mut events = vec![TabGroupEvent::TabMovedToPane {
                    from_pane_idx,
                    to_pane_idx: final_to,
                    tab_id,
                    insert_idx,
                }];
                if source_now_empty {
                    events.push(TabGroupEvent::PaneCollapsed {
                        pane_idx: from_pane_idx,
                    });
                }
                events
            }

            // ── Split: create a new adjacent pane ───────────────────
            TabDropInstruction::SplitToNewPane {
                from_pane_idx,
                from_idx,
                target_pane_idx,
                edge,
                split_direction,
                source_now_empty,
            } => {
                let moved_tab = self.panes[from_pane_idx].tabs.remove(from_idx);
                if self.panes[from_pane_idx].active_tab_id == drag.tab_id {
                    let fallback = if from_idx > 0 { from_idx - 1 } else { 0 };
                    self.panes[from_pane_idx].active_tab_id = self.panes[from_pane_idx]
                        .tabs
                        .get(fallback)
                        .map(|t| t.id.clone())
                        .unwrap_or_default();
                }
                let tab_id = moved_tab.id.clone();
                let original_target = target_pane_idx;

                let insert_before = matches!(edge, DropEdge::Left | DropEdge::Top);

                // Adjust target index if source collapses first.
                let mut adjusted_to = target_pane_idx;
                if source_now_empty {
                    self.collapse_pane(from_pane_idx);
                    if from_pane_idx < adjusted_to {
                        adjusted_to -= 1;
                    }
                }

                // New pane will be inserted at `actual_pos` in the vec.
                let actual_pos = if insert_before {
                    adjusted_to
                } else {
                    adjusted_to + 1
                };

                // Build the new pane with a unique ID.
                let new_pane_id = format!("pane:{}", self.next_pane_counter);
                self.next_pane_counter += 1;
                let new_tab_id = moved_tab.id.clone();
                let new_pane = Pane::new(new_pane_id, vec![moved_tab], new_tab_id);

                // Shift tree indices >= actual_pos up by 1, then insert into vec.
                self.layout = self.layout.clone().shift_indices_up_from(actual_pos);
                self.panes.insert(actual_pos, new_pane);

                // Wrap the target leaf in a new Split with the new pane.
                // After the shift, the target pane is at:
                //   - insert_before: adjusted_to + 1  (was shifted up)
                //   - insert_after:  adjusted_to       (was not shifted)
                if insert_before {
                    self.layout = self.layout.clone().insert_before_leaf(
                        adjusted_to + 1,
                        actual_pos,
                        split_direction,
                    );
                } else {
                    self.layout = self.layout.clone().insert_after_leaf(
                        adjusted_to,
                        actual_pos,
                        split_direction,
                    );
                }

                let new_n = self.panes.len();
                self.focus.set_count(new_n);
                self.focus.set_active(Some(actual_pos));
                self.last_pane_hits = (0..new_n).map(|_| None).collect();
                self.last_dividers = vec![];

                let mut events = vec![TabGroupEvent::TabSplitToNewPane {
                    from_pane_idx,
                    tab_id,
                    target_pane_idx: original_target,
                    edge,
                    new_pane_idx: actual_pos,
                }];
                if source_now_empty {
                    events.push(TabGroupEvent::PaneCollapsed {
                        pane_idx: from_pane_idx,
                    });
                }
                events
            }
        }
    }

    /// Cancel an in-progress tab drag without moving any tab.
    pub fn cancel_tab_drag(&mut self) {
        self.dragging_tab = None;
    }

    /// Return `true` if a tab drag is currently in progress.
    pub fn is_tab_dragging(&self) -> bool {
        self.dragging_tab.is_some()
    }

    /// Compute the drop zone at `(cursor_x, cursor_y)` using the cached
    /// group rects from the last render.
    ///
    /// Convenience wrapper around [`crate::primitives::drop_zone::drop_zone_hit_test`]
    /// that derives `tab_bar_height` from the stored strip bounds. Returns
    /// `None` before the first render or when the cursor is outside all
    /// groups.
    pub fn drop_zone_at(&self, cursor_x: f32, cursor_y: f32) -> Option<DropZone> {
        let groups = self.drop_group_rects();
        let tab_bar_h = self.strip_height();
        match drop_zone_hit_test(cursor_x, cursor_y, &groups, tab_bar_h) {
            DropZoneHit::Zone(z) => Some(z),
            DropZoneHit::Empty => None,
        }
    }
}

// ── Layout helpers ────────────────────────────────────────────────────────────

/// Walk the layout tree, computing per-pane bounds and collecting divider info
/// in in-order split traversal.
///
/// `pane_bounds[k]` is set to the bounds for the pane at vec index `k`.
/// `dividers` receives one entry per `Split` node in in-order traversal
/// (left subtree's splits, then the current split, then right subtree's
/// splits), matching the divider ordering used in `last_dividers` and
/// `DividerResized` events.
fn layout_recursive(
    tree: &GroupLayout,
    backend: &dyn Backend,
    bounds: Rect,
    pane_bounds: &mut Vec<Option<Rect>>,
    dividers: &mut Vec<DividerInfo>,
) {
    match tree {
        GroupLayout::Leaf(idx) => {
            if *idx < pane_bounds.len() {
                pane_bounds[*idx] = Some(bounds);
            }
        }
        GroupLayout::Split {
            direction,
            ratio,
            first,
            second,
        } => {
            let split = Split {
                id: WidgetId::new("tg:layout"),
                direction: *direction,
                ratio: *ratio,
                first_min: 0.0,
                second_min: 0.0,
            };
            let sl = backend.split_layout(bounds, &split);
            // In-order: first subtree's dividers, then this divider, then second.
            layout_recursive(first, backend, sl.first_bounds, pane_bounds, dividers);
            dividers.push(DividerInfo {
                divider_bounds: sl.divider_bounds,
                direction: *direction,
                split_bounds: bounds,
                ratio: *ratio,
            });
            layout_recursive(second, backend, sl.second_bounds, pane_bounds, dividers);
        }
    }
}

/// Update the ratio of the in-order-`target` `Split` node in `tree`.
///
/// Returns `Some(true)` when the node was found and the ratio changed
/// significantly (≥ 0.001), `Some(false)` when found but unchanged, and
/// `None` when the target index was not found.
///
/// `counter` must start at 0 on the first call.
fn update_split_ratio_inorder(
    tree: &mut GroupLayout,
    target: usize,
    new_ratio: f32,
    counter: &mut usize,
) -> Option<bool> {
    match tree {
        GroupLayout::Leaf(_) => None,
        GroupLayout::Split {
            ratio,
            first,
            second,
            ..
        } => {
            // In-order: check first subtree, then current node, then second subtree.
            if let Some(r) = update_split_ratio_inorder(first, target, new_ratio, counter) {
                return Some(r);
            }
            if *counter == target {
                let old = *ratio;
                *counter += 1;
                *ratio = new_ratio;
                return Some((new_ratio - old).abs() >= 0.001);
            }
            *counter += 1;
            update_split_ratio_inorder(second, target, new_ratio, counter)
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::tab_bar_hits_from_layout;
    use crate::primitives::tab_bar::{SegmentMeasure, TabMeasure};

    // ── Minimal BackendWidget for tests ──────────────────────────────────────

    struct NoOpContent;
    impl BackendWidget for NoOpContent {
        fn render(&self, _backend: &mut dyn Backend, _rect: Rect) {}
    }

    // ── Helpers ──────────────────────────────────────────────────────────────

    fn tab(id: &str, label: &str, closable: bool) -> PaneTab {
        PaneTab {
            id: id.to_string(),
            label: label.to_string(),
            closable,
            content: Box::new(NoOpContent),
        }
    }

    fn make_group() -> TabGroupController {
        TabGroupController::with_pane(
            "pane:0",
            vec![tab("t0", "main.rs", true), tab("t1", "lib.rs", true)],
            "t0",
            SplitDirection::Horizontal,
        )
    }

    /// Prime the hit-test cache for `pane_idx` without a real backend render.
    /// Each tab is given `tab_w` cells (last `close_w` cells = close region).
    /// The "new-tab" right segment is given 3 cells.
    #[allow(deprecated)] // builds the deprecated `TabBarHits` test fixture — issue #823
    fn prime_pane(
        ctrl: &mut TabGroupController,
        pane_idx: usize,
        strip_x: f32,
        strip_y: f32,
        bar_w: f32,
        tab_w: f32,
        close_w: f32,
    ) {
        let Some(pane) = ctrl.panes.get(pane_idx) else {
            return;
        };
        let bar = pane.build_tab_bar(pane_idx);
        let n_tabs = pane.tabs.len();
        let layout = bar.layout(
            bar_w,
            1.0,
            0.0,
            |i| {
                if i < n_tabs && pane.tabs[i].closable {
                    TabMeasure::new(tab_w, close_w)
                } else {
                    TabMeasure::new(tab_w, 0.0)
                }
            },
            |_| SegmentMeasure::new(3.0),
        );
        let mut hits = tab_bar_hits_from_layout(&layout, &bar);
        // Shift hits to absolute coords (mirror what backends do).
        let ox = strip_x as f64;
        for sp in &mut hits.slot_positions {
            if *sp != (0.0, 0.0) {
                sp.0 += ox;
                sp.1 += ox;
            }
        }
        for cb in hits.close_bounds.iter_mut().flatten() {
            cb.0 += ox;
            cb.1 += ox;
        }
        for rb in &mut hits.right_segment_bounds {
            rb.0 += ox;
            rb.1 += ox;
        }
        let strip = Rect::new(strip_x, strip_y, bar_w, 1.0);
        let content = Rect::new(strip_x, strip_y + 1.0, bar_w, 10.0);
        ctrl.last_pane_hits[pane_idx] = Some(PaneHitCache {
            hits,
            strip_bounds: strip,
            content_bounds: content,
        });
    }

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

    #[test]
    fn new_controller_has_one_pane_with_tabs() {
        let ctrl = make_group();
        assert_eq!(ctrl.pane_count(), 1);
        assert_eq!(ctrl.panes[0].tabs().len(), 2);
        assert_eq!(ctrl.panes[0].active_tab_id(), "t0");
        assert_eq!(ctrl.focused_pane(), None); // starts unfocused
    }

    // ── from_layout ───────────────────────────────────────────────────────────

    #[test]
    fn from_layout_single_pane() {
        let pane = Pane::new("p0", vec![tab("t0", "main.rs", true)], "t0");
        let layout = GroupLayout::Leaf(0);
        let ctrl = TabGroupController::from_layout(vec![pane], layout, SplitDirection::Horizontal)
            .expect("valid single-pane layout");
        assert_eq!(ctrl.pane_count(), 1);
        assert_eq!(ctrl.layout, GroupLayout::Leaf(0));
        assert_eq!(ctrl.focused_pane(), None); // starts unfocused
        assert_eq!(ctrl.panes[0].active_tab_id(), "t0");
    }

    #[test]
    fn from_layout_two_pane_horizontal() {
        let panes = vec![
            Pane::new("p0", vec![tab("t0", "a.rs", true)], "t0"),
            Pane::new("p1", vec![tab("t1", "b.rs", true)], "t1"),
        ];
        let layout = GroupLayout::Split {
            direction: SplitDirection::Horizontal,
            ratio: 0.4,
            first: Box::new(GroupLayout::Leaf(0)),
            second: Box::new(GroupLayout::Leaf(1)),
        };
        let ctrl = TabGroupController::from_layout(panes, layout.clone(), SplitDirection::Vertical)
            .expect("valid two-pane layout");
        assert_eq!(ctrl.pane_count(), 2);
        assert_eq!(ctrl.layout, layout);
        // Spot-check pane ids.
        assert_eq!(ctrl.panes[0].id, "p0");
        assert_eq!(ctrl.panes[1].id, "p1");
    }

    #[test]
    fn from_layout_three_pane_mixed_direction() {
        // Left pane | (top-right pane / bottom-right pane)
        // Root split is Horizontal; the right sub-tree is Vertical.
        // This is the canonical mixed-direction case the issue targets.
        let panes = vec![
            Pane::new("left", vec![tab("tl", "left.rs", true)], "tl"),
            Pane::new("top-right", vec![tab("tr", "top.rs", true)], "tr"),
            Pane::new("bottom-right", vec![tab("tb", "bottom.rs", true)], "tb"),
        ];
        let layout = GroupLayout::Split {
            direction: SplitDirection::Horizontal,
            ratio: 0.5,
            first: Box::new(GroupLayout::Leaf(0)),
            second: Box::new(GroupLayout::Split {
                direction: SplitDirection::Vertical,
                ratio: 0.5,
                first: Box::new(GroupLayout::Leaf(1)),
                second: Box::new(GroupLayout::Leaf(2)),
            }),
        };
        let ctrl = TabGroupController::from_layout(panes, layout, SplitDirection::Horizontal)
            .expect("valid mixed-direction layout");

        assert_eq!(ctrl.pane_count(), 3);
        assert_eq!(ctrl.layout.leaf_count(), 3);
        assert!(ctrl.layout.contains_leaf(0));
        assert!(ctrl.layout.contains_leaf(1));
        assert!(ctrl.layout.contains_leaf(2));

        // Confirm the root split is Horizontal and the nested split is Vertical.
        match &ctrl.layout {
            GroupLayout::Split {
                direction: SplitDirection::Horizontal,
                second,
                ..
            } => match second.as_ref() {
                GroupLayout::Split {
                    direction: SplitDirection::Vertical,
                    ..
                } => {}
                other => panic!("expected Vertical nested split, got {other:?}"),
            },
            other => panic!("expected Horizontal root split, got {other:?}"),
        }
    }

    #[test]
    fn from_layout_custom_ratio_preserved() {
        // Verify that the exact ratio provided is stored as-is.
        let panes = vec![
            Pane::new("p0", vec![tab("t0", "a.rs", false)], "t0"),
            Pane::new("p1", vec![tab("t1", "b.rs", false)], "t1"),
        ];
        let layout = GroupLayout::Split {
            direction: SplitDirection::Horizontal,
            ratio: 0.3,
            first: Box::new(GroupLayout::Leaf(0)),
            second: Box::new(GroupLayout::Leaf(1)),
        };
        let ctrl = TabGroupController::from_layout(panes, layout, SplitDirection::Horizontal)
            .expect("valid");
        let ratio = match &ctrl.layout {
            GroupLayout::Split { ratio, .. } => *ratio,
            _ => panic!("expected Split"),
        };
        assert!((ratio - 0.3).abs() < 1e-6, "ratio={ratio}");
    }

    #[test]
    fn from_layout_add_pane_after_construction() {
        // A from_layout controller should behave correctly with subsequent
        // add_pane_with_tab calls (important: next_pane_counter must not
        // collide with pre-existing pane ids).
        let panes = vec![
            Pane::new("p0", vec![tab("t0", "a.rs", true)], "t0"),
            Pane::new("p1", vec![tab("t1", "b.rs", true)], "t1"),
        ];
        let layout = GroupLayout::Split {
            direction: SplitDirection::Horizontal,
            ratio: 0.5,
            first: Box::new(GroupLayout::Leaf(0)),
            second: Box::new(GroupLayout::Leaf(1)),
        };
        let mut ctrl = TabGroupController::from_layout(panes, layout, SplitDirection::Horizontal)
            .expect("valid");
        assert_eq!(ctrl.pane_count(), 2);

        // Add a third pane via the regular incremental API.
        let new_idx = ctrl.add_pane_with_tab("extra", tab("te", "extra.rs", false));
        assert_eq!(ctrl.pane_count(), 3);
        assert_eq!(ctrl.layout.leaf_count(), 3);
        assert_eq!(ctrl.panes[new_idx].id, "extra");
    }

    // ── from_layout: error cases ──────────────────────────────────────────────

    #[test]
    fn from_layout_error_empty_panes() {
        let result = TabGroupController::from_layout(
            vec![],
            GroupLayout::Leaf(0),
            SplitDirection::Horizontal,
        );
        assert!(result.is_err(), "expected Err for empty panes");
        let msg = result.err().unwrap();
        assert!(msg.contains("non-empty"), "unexpected message: {msg}");
    }

    #[test]
    fn from_layout_error_leaf_count_mismatch() {
        let panes = vec![Pane::new("p0", vec![tab("t0", "a.rs", false)], "t0")];
        // Tree has 2 leaves but only 1 pane provided.
        let layout = GroupLayout::Split {
            direction: SplitDirection::Horizontal,
            ratio: 0.5,
            first: Box::new(GroupLayout::Leaf(0)),
            second: Box::new(GroupLayout::Leaf(1)),
        };
        let result = TabGroupController::from_layout(panes, layout, SplitDirection::Horizontal);
        assert!(result.is_err(), "expected Err for count mismatch");
        let msg = result.err().unwrap();
        assert!(
            msg.contains("2") && msg.contains("1"),
            "error should mention counts, got: {msg}"
        );
    }

    #[test]
    fn from_layout_error_duplicate_leaf_index() {
        let panes = vec![
            Pane::new("p0", vec![tab("t0", "a.rs", false)], "t0"),
            Pane::new("p1", vec![tab("t1", "b.rs", false)], "t1"),
        ];
        // Both leaves reference index 0.
        let layout = GroupLayout::Split {
            direction: SplitDirection::Horizontal,
            ratio: 0.5,
            first: Box::new(GroupLayout::Leaf(0)),
            second: Box::new(GroupLayout::Leaf(0)), // duplicate!
        };
        let result = TabGroupController::from_layout(panes, layout, SplitDirection::Horizontal);
        assert!(result.is_err(), "expected Err for duplicate leaf");
        let msg = result.err().unwrap();
        assert!(
            msg.contains("more than once") || msg.contains("duplicate"),
            "unexpected error message: {msg}"
        );
    }

    #[test]
    fn from_layout_error_out_of_range_leaf_index() {
        let panes = vec![
            Pane::new("p0", vec![tab("t0", "a.rs", false)], "t0"),
            Pane::new("p1", vec![tab("t1", "b.rs", false)], "t1"),
        ];
        // Leaf index 2 is out of range for 2 panes (valid range: 0..2).
        let layout = GroupLayout::Split {
            direction: SplitDirection::Horizontal,
            ratio: 0.5,
            first: Box::new(GroupLayout::Leaf(0)),
            second: Box::new(GroupLayout::Leaf(2)), // out of range!
        };
        let result = TabGroupController::from_layout(panes, layout, SplitDirection::Horizontal);
        assert!(result.is_err(), "expected Err for out-of-range leaf");
        let msg = result.err().unwrap();
        assert!(
            msg.contains("out of range") || msg.contains("range"),
            "unexpected error message: {msg}"
        );
    }

    // ── Tab switching ─────────────────────────────────────────────────────────

    #[test]
    fn switch_tab_changes_active() {
        let mut ctrl = make_group();
        assert!(ctrl.switch_tab(0, "t1"));
        assert_eq!(ctrl.panes[0].active_tab_id(), "t1");
    }

    #[test]
    fn switch_tab_unknown_returns_false() {
        let mut ctrl = make_group();
        assert!(!ctrl.switch_tab(0, "no-such"));
        assert_eq!(ctrl.panes[0].active_tab_id(), "t0"); // unchanged
    }

    // ── Add tab ───────────────────────────────────────────────────────────────

    #[test]
    fn add_tab_appends_without_activating() {
        let mut ctrl = make_group();
        ctrl.add_tab(0, tab("t2", "new.rs", true));
        assert_eq!(ctrl.panes[0].tabs().len(), 3);
        assert_eq!(ctrl.panes[0].active_tab_id(), "t0"); // unchanged
    }

    #[test]
    fn add_and_activate_tab_makes_it_active() {
        let mut ctrl = make_group();
        ctrl.add_and_activate_tab(0, tab("t2", "new.rs", true));
        assert_eq!(ctrl.panes[0].active_tab_id(), "t2");
    }

    // ── Close tab ─────────────────────────────────────────────────────────────

    #[test]
    fn close_inactive_tab_emits_tab_closed() {
        let mut ctrl = make_group();
        let ev = ctrl.close_tab(0, "t1");
        assert_eq!(
            ev,
            Some(TabGroupEvent::TabClosed {
                pane_idx: 0,
                tab_id: "t1".into()
            })
        );
        assert_eq!(ctrl.panes[0].tabs().len(), 1);
        assert_eq!(ctrl.panes[0].active_tab_id(), "t0");
    }

    #[test]
    fn close_active_tab_switches_to_previous() {
        let mut ctrl = make_group();
        ctrl.switch_tab(0, "t1"); // make t1 active
        let ev = ctrl.close_tab(0, "t1");
        assert_eq!(
            ev,
            Some(TabGroupEvent::TabClosed {
                pane_idx: 0,
                tab_id: "t1".into()
            })
        );
        assert_eq!(ctrl.panes[0].active_tab_id(), "t0"); // fell back to t0
    }

    #[test]
    fn close_unknown_tab_returns_none() {
        let mut ctrl = make_group();
        assert_eq!(ctrl.close_tab(0, "ghost"), None);
    }

    // ── Close-last-tab collapses the pane ─────────────────────────────────────

    #[test]
    fn close_last_tab_in_solo_pane_does_not_collapse() {
        let mut ctrl = TabGroupController::with_pane(
            "p0",
            vec![tab("t0", "only", true)],
            "t0",
            SplitDirection::Horizontal,
        );
        let ev = ctrl.close_tab(0, "t0");
        assert_eq!(ev, Some(TabGroupEvent::PaneCollapsed { pane_idx: 0 }));
        // Controller retains 1 pane (collapse_pane is a no-op at len==1).
        assert_eq!(ctrl.pane_count(), 1);
    }

    #[test]
    fn close_last_tab_in_second_pane_collapses_it() {
        let mut ctrl = make_group();
        let idx = ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", true));
        assert_eq!(ctrl.pane_count(), 2);

        let ev = ctrl.close_tab(idx, "x0");
        assert_eq!(ev, Some(TabGroupEvent::PaneCollapsed { pane_idx: idx }));
        assert_eq!(ctrl.pane_count(), 1);
        // Layout should be a single Leaf.
        assert!(matches!(ctrl.layout, GroupLayout::Leaf(0)));
    }

    // ── Pane lifecycle ────────────────────────────────────────────────────────

    #[test]
    fn add_pane_with_tab_creates_second_pane() {
        let mut ctrl = make_group();
        let idx = ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", true));
        assert_eq!(idx, 1);
        assert_eq!(ctrl.pane_count(), 2);
        assert_eq!(ctrl.focused_pane(), Some(1));
        // Layout should be a Split at root.
        assert!(matches!(ctrl.layout, GroupLayout::Split { .. }));
        // Tree has exactly 2 leaves.
        assert_eq!(ctrl.layout.leaf_count(), 2);
    }

    #[test]
    fn three_panes_fractions_sum_to_one() {
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", false));
        ctrl.add_pane_with_tab("p2", tab("y0", "y.rs", false));
        assert_eq!(ctrl.pane_count(), 3);
        // All 3 pane indices appear as leaves.
        assert_eq!(ctrl.layout.leaf_count(), 3);
    }

    // ── Focus tracking ────────────────────────────────────────────────────────

    #[test]
    fn focus_pane_sets_active() {
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", false));
        ctrl.focus_pane(0);
        assert_eq!(ctrl.focused_pane(), Some(0));
    }

    #[test]
    fn cycle_focus_wraps_around() {
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", false));
        ctrl.focus_pane(0);
        ctrl.cycle_focus(1); // → 1
        assert_eq!(ctrl.focused_pane(), Some(1));
        ctrl.cycle_focus(1); // → wraps to 0
        assert_eq!(ctrl.focused_pane(), Some(0));
    }

    // ── handle_click: tab strip ───────────────────────────────────────────────

    #[test]
    fn click_inactive_tab_emits_tab_activated() {
        let mut ctrl = make_group();
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);

        let ev = ctrl.handle_click(9.0, 0.5); // x=9 → t1 body
        assert_eq!(
            ev,
            Some(TabGroupEvent::TabActivated {
                pane_idx: 0,
                tab_id: "t1".into()
            })
        );
        assert_eq!(ctrl.panes[0].active_tab_id(), "t1");
    }

    #[test]
    fn click_active_tab_returns_none() {
        let mut ctrl = make_group();
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        assert_eq!(ctrl.handle_click(3.0, 0.5), None);
    }

    #[test]
    fn click_close_button_emits_tab_closed() {
        let mut ctrl = make_group();
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        let ev = ctrl.handle_click(7.0, 0.5);
        assert_eq!(
            ev,
            Some(TabGroupEvent::TabClosed {
                pane_idx: 0,
                tab_id: "t0".into()
            })
        );
        assert_eq!(ctrl.panes[0].tabs().len(), 1);
    }

    #[test]
    fn click_new_tab_button_emits_new_tab_requested() {
        let mut ctrl = make_group();
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        let ev = ctrl.handle_click(78.0, 0.5);
        assert_eq!(ev, Some(TabGroupEvent::NewTabRequested { pane_idx: 0 }));
    }

    // ── handle_click: content area ────────────────────────────────────────────

    #[test]
    fn click_content_area_focuses_pane() {
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", false));
        ctrl.focus_pane(0);
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        prime_pane(&mut ctrl, 1, 80.0, 0.0, 80.0, 8.0, 2.0);

        let ev = ctrl.handle_click(85.0, 5.0);
        assert_eq!(ev, Some(TabGroupEvent::PaneFocused { pane_idx: 1 }));
        assert_eq!(ctrl.focused_pane(), Some(1));
    }

    #[test]
    fn click_already_focused_content_returns_none() {
        let mut ctrl = make_group();
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        ctrl.focus_pane(0);
        assert_eq!(ctrl.handle_click(5.0, 5.0), None);
    }

    // ── handle_click: non-zero origin ────────────────────────────────────────

    #[test]
    fn click_with_offset_strip_resolves_correctly() {
        let mut ctrl = make_group();
        prime_pane(&mut ctrl, 0, 20.0, 5.0, 80.0, 8.0, 2.0);

        let ev = ctrl.handle_click(30.0, 5.5);
        assert_eq!(
            ev,
            Some(TabGroupEvent::TabActivated {
                pane_idx: 0,
                tab_id: "t1".into()
            })
        );
    }

    // ── Divider drag ──────────────────────────────────────────────────────────

    #[test]
    fn drag_start_on_non_divider_returns_false() {
        let mut ctrl = make_group();
        assert!(!ctrl.handle_drag_start(50.0, 50.0));
    }

    #[test]
    fn drag_start_on_divider_returns_true() {
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", false));
        // Manually place a divider.
        ctrl.last_dividers = vec![DividerInfo {
            divider_bounds: Rect::new(40.0, 0.0, 1.0, 20.0),
            direction: SplitDirection::Horizontal,
            split_bounds: Rect::new(0.0, 0.0, 80.0, 20.0),
            ratio: 0.5,
        }];
        assert!(ctrl.handle_drag_start(40.5, 10.0));
        assert_eq!(ctrl.dragging_divider, Some(0));
    }

    #[test]
    fn drag_move_updates_split_ratio() {
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", false));
        // Place a divider centred at x=50 on a 100-wide split.
        ctrl.last_dividers = vec![DividerInfo {
            divider_bounds: Rect::new(50.0, 0.0, 1.0, 20.0),
            direction: SplitDirection::Horizontal,
            split_bounds: Rect::new(0.0, 0.0, 100.0, 20.0),
            ratio: 0.5,
        }];
        ctrl.handle_drag_start(50.5, 5.0);

        let bounds = Rect::new(0.0, 0.0, 100.0, 20.0); // ignored by new impl
        let ev = ctrl.handle_drag_move(30.0, 5.0, bounds); // drag to x=30 → ratio ≈ 0.30
        assert_eq!(ev, Some(TabGroupEvent::DividerResized { divider_idx: 0 }));
        // The root split's ratio should now be ≈ 0.30.
        let ratio = match &ctrl.layout {
            GroupLayout::Split { ratio, .. } => *ratio,
            _ => panic!("expected Split at root"),
        };
        assert!(
            (ratio - 0.30).abs() < 0.02,
            "ratio={ratio}, expected ≈ 0.30"
        );
        assert!((1.0 - ratio - 0.70).abs() < 0.02);
    }

    #[test]
    fn drag_end_clears_drag_state() {
        let mut ctrl = make_group();
        ctrl.dragging_divider = Some(0);
        ctrl.handle_drag_end();
        assert_eq!(ctrl.dragging_divider, None);
    }

    // ── drop_group_rects ──────────────────────────────────────────────────────

    #[test]
    fn drop_group_rects_empty_before_render() {
        let ctrl = make_group();
        assert!(ctrl.drop_group_rects().is_empty());
    }

    #[test]
    fn drop_group_rects_populated_after_prime() {
        let mut ctrl = make_group();
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        let rects = ctrl.drop_group_rects();
        assert_eq!(rects.len(), 1);
        assert_eq!(rects[0].bounds.width, 80.0);
    }

    // ── Pane fractions / layout tree invariants ───────────────────────────────

    #[test]
    fn collapse_pane_reduces_leaf_count() {
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", false));
        ctrl.add_pane_with_tab("p2", tab("y0", "y.rs", false));
        assert_eq!(ctrl.pane_count(), 3);
        assert_eq!(ctrl.layout.leaf_count(), 3);

        ctrl.collapse_pane(1);
        assert_eq!(ctrl.pane_count(), 2);
        assert_eq!(ctrl.layout.leaf_count(), 2);
    }

    // ── Recursive split tree ──────────────────────────────────────────────────

    #[test]
    fn layout_after_two_adds_is_correct() {
        // Start: Leaf(0)
        // Add p1 (after p0): Split(H, Leaf(0), Leaf(1))
        // Add p2 (after p1, which is focused): Split(H, Leaf(0), Split(H, Leaf(1), Leaf(2)))
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", false));
        ctrl.add_pane_with_tab("p2", tab("y0", "y.rs", false));
        // All three leaf indices present.
        assert!(ctrl.layout.contains_leaf(0));
        assert!(ctrl.layout.contains_leaf(1));
        assert!(ctrl.layout.contains_leaf(2));
        assert_eq!(ctrl.layout.leaf_count(), 3);
    }

    #[test]
    fn top_bottom_edge_drops_create_vertical_splits() {
        // When a tab is dropped on a Top or Bottom edge, the resulting split
        // in the tree must have direction == Vertical.
        let mut ctrl = make_group();
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", true));
        ctrl.focus_pane(0);
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        prime_pane(&mut ctrl, 1, 80.0, 0.0, 80.0, 8.0, 2.0);

        // Drag t1 from pane 0 to the top edge of pane 1.
        // top-edge: y < tab_bar_h + edge_h → but y must be in content area.
        // Per compute_drop_zone: top edge = content area, y - content_top < edge_h(=3).
        // Content top for pane 1 = 1.0 (strip height). Edge zone: y < 1.0+3=4.
        ctrl.handle_tab_drag_start(9.0, 0.5); // drag t1
        let evs = ctrl.handle_tab_drop(120.0, 2.5); // top-edge of pane 1 content

        if let Some(TabGroupEvent::TabSplitToNewPane { edge, .. }) = evs.first() {
            assert!(
                matches!(edge, DropEdge::Top),
                "expected Top edge, got {edge:?}"
            );
        } else {
            // If not a split (e.g. fell into center), skip direction check.
            return;
        }

        // Find the newly inserted split node in the tree — it must be Vertical.
        fn find_any_vertical(node: &GroupLayout) -> bool {
            match node {
                GroupLayout::Leaf(_) => false,
                GroupLayout::Split {
                    direction,
                    first,
                    second,
                    ..
                } => {
                    *direction == SplitDirection::Vertical
                        || find_any_vertical(first)
                        || find_any_vertical(second)
                }
            }
        }
        assert!(
            find_any_vertical(&ctrl.layout),
            "expected a Vertical split in tree after Top-edge drop"
        );
    }

    // ── Cross-group tab drag: helpers ─────────────────────────────────────────

    /// Build a two-pane controller with:
    ///   pane 0 at x=0  : tabs [t0, t1], strip height=1, bar_w=80
    ///   pane 1 at x=80 : tabs [x0],     strip height=1, bar_w=80
    fn make_two_pane() -> TabGroupController {
        let mut ctrl = TabGroupController::with_pane(
            "p0",
            vec![tab("t0", "main.rs", true), tab("t1", "lib.rs", true)],
            "t0",
            SplitDirection::Horizontal,
        );
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", true));
        ctrl.focus_pane(0);
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        prime_pane(&mut ctrl, 1, 80.0, 0.0, 80.0, 8.0, 2.0);
        ctrl
    }

    // ── handle_tab_drag_start ─────────────────────────────────────────────────

    #[test]
    fn tab_drag_start_on_tab_body_returns_true() {
        let mut ctrl = make_two_pane();
        assert!(ctrl.handle_tab_drag_start(9.0, 0.5));
        assert!(ctrl.is_tab_dragging());
        let drag = ctrl.dragging_tab.as_ref().unwrap();
        assert_eq!(drag.source_pane_idx, 0);
        assert_eq!(drag.tab_id, "t1");
    }

    #[test]
    fn tab_drag_start_on_close_button_returns_false() {
        let mut ctrl = make_two_pane();
        assert!(!ctrl.handle_tab_drag_start(7.0, 0.5));
        assert!(!ctrl.is_tab_dragging());
    }

    #[test]
    fn tab_drag_start_on_new_tab_button_returns_false() {
        let mut ctrl = make_two_pane();
        assert!(!ctrl.handle_tab_drag_start(78.0, 0.5));
        assert!(!ctrl.is_tab_dragging());
    }

    #[test]
    fn tab_drag_start_in_content_area_returns_false() {
        let mut ctrl = make_two_pane();
        assert!(!ctrl.handle_tab_drag_start(40.0, 5.0));
        assert!(!ctrl.is_tab_dragging());
    }

    #[test]
    fn tab_drag_start_outside_all_panes_returns_false() {
        let mut ctrl = make_two_pane();
        assert!(!ctrl.handle_tab_drag_start(999.0, 0.5));
        assert!(!ctrl.is_tab_dragging());
    }

    // ── handle_tab_drag_move + tab_drag_overlay ───────────────────────────────

    #[test]
    fn tab_drag_move_returns_none_when_not_dragging() {
        let mut ctrl = make_two_pane();
        assert!(ctrl.handle_tab_drag_move(120.0, 5.0).is_none());
    }

    #[test]
    fn tab_drag_move_returns_drop_zone_and_stores_it() {
        let mut ctrl = make_two_pane();
        assert!(ctrl.handle_tab_drag_start(9.0, 0.5));
        let zone = ctrl.handle_tab_drag_move(120.0, 5.0);
        assert_eq!(
            zone,
            Some(crate::DropZone {
                kind: crate::DropZoneKind::Center,
                group_idx: 1,
            })
        );
        let stored = ctrl.dragging_tab.as_ref().unwrap().current_zone.as_ref();
        assert_eq!(stored.unwrap().group_idx, 1);
    }

    #[test]
    fn tab_drag_overlay_returns_none_without_zone() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        assert!(ctrl.tab_drag_overlay(9.0, 0.5, 2.0, 10.0).is_none());
    }

    #[test]
    fn tab_drag_overlay_returns_highlight_after_move() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        ctrl.handle_tab_drag_move(120.0, 5.0);
        let ov = ctrl.tab_drag_overlay(120.0, 5.0, 2.0, 10.0).unwrap();
        assert_eq!(ov.highlight, Some(crate::Rect::new(80.0, 1.0, 80.0, 10.0)));
        assert!(ov.insertion_bar.is_none());
    }

    // ── cancel_tab_drag / is_tab_dragging ─────────────────────────────────────

    #[test]
    fn cancel_tab_drag_clears_state() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        assert!(ctrl.is_tab_dragging());
        ctrl.cancel_tab_drag();
        assert!(!ctrl.is_tab_dragging());
    }

    // ── drop_zone_at ──────────────────────────────────────────────────────────

    #[test]
    fn drop_zone_at_center_of_pane_1() {
        let ctrl = make_two_pane();
        let zone = ctrl.drop_zone_at(120.0, 5.0).unwrap();
        assert_eq!(zone.group_idx, 1);
        assert_eq!(zone.kind, crate::DropZoneKind::Center);
    }

    #[test]
    fn drop_zone_at_tab_bar_of_pane_1_reorder() {
        let ctrl = make_two_pane();
        let zone = ctrl.drop_zone_at(82.0, 0.5).unwrap();
        assert_eq!(zone.group_idx, 1);
        assert!(matches!(zone.kind, crate::DropZoneKind::TabReorder(_)));
    }

    // ── handle_tab_drop: reorder within same pane ─────────────────────────────

    #[test]
    fn tab_drop_reorders_within_same_pane() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(3.0, 0.5);
        assert_eq!(
            evs,
            vec![TabGroupEvent::TabReordered {
                pane_idx: 0,
                tab_id: "t1".into(),
                from_idx: 1,
                to_idx: 0,
            }]
        );
        assert_eq!(ctrl.panes[0].tabs()[0].id, "t1");
        assert_eq!(ctrl.panes[0].tabs()[1].id, "t0");
        assert_eq!(ctrl.pane_count(), 2);
    }

    #[test]
    fn tab_drop_reorder_same_position_is_noop() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(14.0, 0.5);
        assert!(evs.is_empty());
        assert_eq!(ctrl.panes[0].tabs()[0].id, "t0");
        assert_eq!(ctrl.panes[0].tabs()[1].id, "t1");
    }

    #[test]
    fn tab_drop_same_pane_center_is_noop() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(40.0, 5.0);
        assert!(evs.is_empty());
        assert_eq!(ctrl.pane_count(), 2);
        assert_eq!(ctrl.panes[0].tabs().len(), 2);
    }

    // ── handle_tab_drop: merge into another pane ──────────────────────────────

    #[test]
    fn tab_drop_moves_tab_to_another_pane_center() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(120.0, 5.0);
        assert_eq!(
            evs,
            vec![TabGroupEvent::TabMovedToPane {
                from_pane_idx: 0,
                to_pane_idx: 1,
                tab_id: "t1".into(),
                insert_idx: 1,
            }]
        );
        assert_eq!(ctrl.pane_count(), 2);
        assert_eq!(ctrl.panes[0].tabs().len(), 1);
        assert_eq!(ctrl.panes[0].tabs()[0].id, "t0");
        assert_eq!(ctrl.panes[1].tabs().len(), 2);
        assert_eq!(ctrl.panes[1].tabs()[1].id, "t1");
        assert_eq!(ctrl.panes[1].active_tab_id(), "t1");
        assert_eq!(ctrl.layout.leaf_count(), 2);
    }

    #[test]
    fn tab_drop_moves_tab_to_another_pane_tab_bar() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(82.0, 0.5);
        assert_eq!(
            evs,
            vec![TabGroupEvent::TabMovedToPane {
                from_pane_idx: 0,
                to_pane_idx: 1,
                tab_id: "t1".into(),
                insert_idx: 0,
            }]
        );
        assert_eq!(ctrl.panes[1].tabs()[0].id, "t1");
        assert_eq!(ctrl.panes[1].tabs()[1].id, "x0");
    }

    #[test]
    fn tab_drop_source_collapses_when_last_tab_moved() {
        let mut ctrl = TabGroupController::with_pane(
            "p0",
            vec![tab("only", "only.rs", true)],
            "only",
            SplitDirection::Horizontal,
        );
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", true));
        ctrl.focus_pane(0);
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        prime_pane(&mut ctrl, 1, 80.0, 0.0, 80.0, 8.0, 2.0);

        ctrl.handle_tab_drag_start(3.0, 0.5);
        let evs = ctrl.handle_tab_drop(120.0, 5.0);

        assert_eq!(ctrl.pane_count(), 1);
        assert_eq!(
            evs,
            vec![
                TabGroupEvent::TabMovedToPane {
                    from_pane_idx: 0,
                    to_pane_idx: 0,
                    tab_id: "only".into(),
                    insert_idx: 1,
                },
                TabGroupEvent::PaneCollapsed { pane_idx: 0 },
            ]
        );
        assert_eq!(ctrl.panes[0].tabs().len(), 2);
        assert_eq!(ctrl.panes[0].tabs()[1].id, "only");
        assert_eq!(ctrl.layout.leaf_count(), 1);
    }

    // ── handle_tab_drop: split to new pane ────────────────────────────────────

    #[test]
    fn tab_drop_splits_right_edge_creates_pane_after_target() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(150.0, 5.0);
        assert_eq!(evs.len(), 1, "no collapse expected: {evs:?}");
        assert!(
            matches!(
                &evs[0],
                TabGroupEvent::TabSplitToNewPane {
                    from_pane_idx: 0,
                    tab_id,
                    target_pane_idx: 1,
                    edge: crate::DropEdge::Right,
                    new_pane_idx: 2,
                } if tab_id == "t1"
            ),
            "unexpected event: {:?}",
            evs[0]
        );
        assert_eq!(ctrl.pane_count(), 3);
        assert_eq!(ctrl.panes[0].tabs()[0].id, "t0");
        assert_eq!(ctrl.panes[1].tabs()[0].id, "x0");
        assert_eq!(ctrl.panes[2].tabs()[0].id, "t1");
        assert_eq!(ctrl.layout.leaf_count(), 3);
    }

    #[test]
    fn tab_drop_splits_left_edge_creates_pane_before_target() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(83.0, 5.0);
        assert_eq!(evs.len(), 1, "no collapse expected: {evs:?}");
        assert!(
            matches!(
                &evs[0],
                TabGroupEvent::TabSplitToNewPane {
                    from_pane_idx: 0,
                    tab_id,
                    target_pane_idx: 1,
                    edge: crate::DropEdge::Left,
                    new_pane_idx: 1,
                } if tab_id == "t1"
            ),
            "unexpected event: {:?}",
            evs[0]
        );
        assert_eq!(ctrl.pane_count(), 3);
        assert_eq!(ctrl.panes[0].tabs()[0].id, "t0");
        assert_eq!(ctrl.panes[1].tabs()[0].id, "t1");
        assert_eq!(ctrl.panes[2].tabs()[0].id, "x0");
    }

    #[test]
    fn tab_drop_split_source_collapses_when_last_tab() {
        let mut ctrl = TabGroupController::with_pane(
            "p0",
            vec![tab("only", "only.rs", true)],
            "only",
            SplitDirection::Horizontal,
        );
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", true));
        ctrl.focus_pane(0);
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        prime_pane(&mut ctrl, 1, 80.0, 0.0, 80.0, 8.0, 2.0);

        ctrl.handle_tab_drag_start(3.0, 0.5);
        let evs = ctrl.handle_tab_drop(150.0, 5.0);

        assert_eq!(ctrl.pane_count(), 2);
        assert_eq!(evs.len(), 2, "expected split + collapse: {evs:?}");
        assert!(
            matches!(
                &evs[0],
                TabGroupEvent::TabSplitToNewPane {
                    from_pane_idx: 0,
                    tab_id,
                    new_pane_idx: 1,
                    ..
                } if tab_id == "only"
            ),
            "unexpected primary event: {:?}",
            evs[0]
        );
        assert_eq!(evs[1], TabGroupEvent::PaneCollapsed { pane_idx: 0 });
        assert_eq!(ctrl.panes[0].tabs()[0].id, "x0");
        assert_eq!(ctrl.panes[1].tabs()[0].id, "only");
        assert_eq!(ctrl.layout.leaf_count(), 2);
    }

    #[test]
    fn tab_drop_only_tab_only_pane_split_is_noop() {
        let mut ctrl = TabGroupController::with_pane(
            "p0",
            vec![tab("t0", "only.rs", true)],
            "t0",
            SplitDirection::Horizontal,
        );
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);

        ctrl.handle_tab_drag_start(3.0, 0.5);
        let evs = ctrl.handle_tab_drop(70.0, 5.0);
        assert!(evs.is_empty());
        assert_eq!(ctrl.pane_count(), 1);
        assert_eq!(ctrl.panes[0].tabs().len(), 1);
    }

    #[test]
    fn tab_drop_clears_drag_state_on_noop() {
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(999.0, 999.0);
        assert!(evs.is_empty());
        assert!(!ctrl.is_tab_dragging());
    }

    /// Self-pane edge drop with multiple tabs: pane has ≥2 tabs, drag one out
    /// to its OWN pane's edge. Source pane stays alive (no collapse), a new
    /// pane is created adjacent to it.
    #[test]
    fn tab_drop_self_pane_edge_with_multiple_tabs_splits_without_collapse() {
        let mut ctrl = make_two_pane();
        // Pane 0 has tabs [t0, t1]; drag t1 onto pane 0's own left edge.
        // Left edge of pane 0 content: x < 0 + edge_w(=3). Use x=1.0, y=5.0 (in content).
        ctrl.handle_tab_drag_start(9.0, 0.5); // t1 from pane 0
        let evs = ctrl.handle_tab_drop(1.0, 5.0); // pane 0 left edge

        // Exactly one event (split, no collapse since pane 0 still has t0).
        assert_eq!(evs.len(), 1, "no collapse expected: {evs:?}");
        assert!(
            matches!(
                &evs[0],
                TabGroupEvent::TabSplitToNewPane {
                    from_pane_idx: 0,
                    tab_id,
                    target_pane_idx: 0,
                    edge: crate::DropEdge::Left,
                    new_pane_idx: 0,
                } if tab_id == "t1"
            ),
            "unexpected event: {:?}",
            evs[0]
        );
        // Pane count grew from 2 to 3; layout tree still has 3 unique leaves.
        assert_eq!(ctrl.pane_count(), 3);
        assert_eq!(ctrl.layout.leaf_count(), 3);
        // The new pane (vec index 0) carries the moved tab; the old pane 0
        // (now at vec index 1) keeps its remaining tab.
        assert_eq!(ctrl.panes[0].tabs().len(), 1);
        assert_eq!(ctrl.panes[0].tabs()[0].id, "t1");
        assert_eq!(ctrl.panes[1].tabs().len(), 1);
        assert_eq!(ctrl.panes[1].tabs()[0].id, "t0");
        // The original "other pane" (was index 1) is now at index 2.
        assert_eq!(ctrl.panes[2].tabs()[0].id, "x0");
    }

    // ── set_drag_geometry ─────────────────────────────────────────────────────
    //
    // Geometry layout used in these tests (no render() call anywhere):
    //
    //  Pane 0: strip (x=0, y=0, w=80, h=1),  content (x=0, y=1, w=80, h=10)
    //          tab_slots: [(0,8), (8,16)]  → t0 at [0,8), t1 at [8,16)
    //
    //  Pane 1: strip (x=80, y=0, w=80, h=1), content (x=80, y=1, w=80, h=10)
    //          tab_slots: [(80,88)]         → x0 at [80,88)
    //
    //  edge_zone_size(80) = 80*0.2 = 16.0   → left: rel_x < 16, right: rel_x >= 64
    //  edge_zone_size(10) = 10*0.2 = 2 → clamped to 3   → top: rel_y < 3, bottom: rel_y >= 7

    fn two_pane_drag_rects() -> (TabGroupController, Vec<PaneDragRect>) {
        let mut ctrl = TabGroupController::with_pane(
            "p0",
            vec![tab("t0", "main.rs", true), tab("t1", "lib.rs", true)],
            "t0",
            SplitDirection::Horizontal,
        );
        ctrl.add_pane_with_tab("p1", tab("x0", "x.rs", true));
        ctrl.focus_pane(0);

        let rects = vec![
            PaneDragRect {
                strip_bounds: Rect::new(0.0, 0.0, 80.0, 1.0),
                content_bounds: Rect::new(0.0, 1.0, 80.0, 10.0),
                tab_slots: vec![(0.0, 8.0), (8.0, 16.0)],
            },
            PaneDragRect {
                strip_bounds: Rect::new(80.0, 0.0, 80.0, 1.0),
                content_bounds: Rect::new(80.0, 1.0, 80.0, 10.0),
                tab_slots: vec![(80.0, 88.0)],
            },
        ];
        (ctrl, rects)
    }

    #[test]
    fn set_drag_geometry_populates_drop_group_rects() {
        let (mut ctrl, rects) = two_pane_drag_rects();
        // Before priming: no rects.
        assert!(ctrl.drop_group_rects().is_empty());

        ctrl.set_drag_geometry(&rects);

        let groups = ctrl.drop_group_rects();
        assert_eq!(groups.len(), 2, "both panes should be primed");
        // Pane 0: full bounds = strip + content = (0, 0, 80, 11)
        assert_eq!(groups[0].bounds.x, 0.0);
        assert_eq!(groups[0].bounds.width, 80.0);
        assert_eq!(groups[0].bounds.height, 11.0);
        assert_eq!(groups[0].tab_slots.len(), 2);
        assert_eq!(groups[0].tab_slots[0], (0.0, 8.0));
        // Pane 1: full bounds = (80, 0, 80, 11)
        assert_eq!(groups[1].bounds.x, 80.0);
        assert_eq!(groups[1].tab_slots.len(), 1);
    }

    #[test]
    fn set_drag_geometry_enables_drop_zone_at() {
        let (mut ctrl, rects) = two_pane_drag_rects();
        ctrl.set_drag_geometry(&rects);

        // Center of pane 1 content: x=120, y=5 → DropZoneKind::Center, group_idx=1
        let zone = ctrl.drop_zone_at(120.0, 5.0).expect("should resolve");
        assert_eq!(zone.group_idx, 1);
        assert!(matches!(
            zone.kind,
            crate::primitives::drop_zone::DropZoneKind::Center
        ));
    }

    #[test]
    fn set_drag_geometry_enables_handle_tab_drag_start() {
        let (mut ctrl, rects) = two_pane_drag_rects();
        ctrl.set_drag_geometry(&rects);

        // x=9.0 lands in pane 0 slot [8, 16) → tab t1.
        assert!(ctrl.handle_tab_drag_start(9.0, 0.5));
        assert!(ctrl.is_tab_dragging());
        let drag = ctrl.dragging_tab.as_ref().unwrap();
        assert_eq!(drag.source_pane_idx, 0);
        assert_eq!(drag.tab_id, "t1");
    }

    #[test]
    fn set_drag_geometry_enables_handle_tab_drag_move() {
        let (mut ctrl, rects) = two_pane_drag_rects();
        ctrl.set_drag_geometry(&rects);
        ctrl.handle_tab_drag_start(9.0, 0.5); // drag t1

        // Move cursor to center of pane 1 (x=120, y=5).
        let zone = ctrl.handle_tab_drag_move(120.0, 5.0);
        assert!(zone.is_some(), "should resolve a drop zone");
        assert_eq!(zone.unwrap().group_idx, 1);
    }

    #[test]
    fn set_drag_geometry_reorder_within_pane() {
        let (mut ctrl, rects) = two_pane_drag_rects();
        ctrl.set_drag_geometry(&rects);
        ctrl.handle_tab_drag_start(9.0, 0.5); // drag t1 (slot [8,16))

        // Drop at x=3 in pane 0 strip → reorder: t1 goes before t0.
        let evs = ctrl.handle_tab_drop(3.0, 0.5);
        assert_eq!(
            evs,
            vec![TabGroupEvent::TabReordered {
                pane_idx: 0,
                tab_id: "t1".into(),
                from_idx: 1,
                to_idx: 0,
            }]
        );
        assert_eq!(ctrl.panes[0].tabs()[0].id, "t1");
        assert_eq!(ctrl.panes[0].tabs()[1].id, "t0");
    }

    #[test]
    fn set_drag_geometry_move_tab_to_other_pane() {
        let (mut ctrl, rects) = two_pane_drag_rects();
        ctrl.set_drag_geometry(&rects);
        ctrl.handle_tab_drag_start(9.0, 0.5); // drag t1

        // Drop in pane 1 center: x=120 (rel_x=40, between edges 16..64), y=5.
        let evs = ctrl.handle_tab_drop(120.0, 5.0);
        assert_eq!(evs.len(), 1, "no collapse expected: {evs:?}");
        assert!(
            matches!(
                &evs[0],
                TabGroupEvent::TabMovedToPane {
                    from_pane_idx: 0,
                    to_pane_idx: 1,
                    tab_id,
                    ..
                } if tab_id == "t1"
            ),
            "unexpected event: {:?}",
            evs[0]
        );
        assert_eq!(ctrl.pane_count(), 2);
        assert_eq!(ctrl.panes[0].tabs().len(), 1);
        assert_eq!(ctrl.panes[1].tabs().len(), 2);
    }

    #[test]
    fn set_drag_geometry_split_to_new_pane() {
        let (mut ctrl, rects) = two_pane_drag_rects();
        ctrl.set_drag_geometry(&rects);
        ctrl.handle_tab_drag_start(9.0, 0.5); // drag t1

        // Drop on right edge of pane 1: x=150 (rel_x=70 >= 64), y=5.
        let evs = ctrl.handle_tab_drop(150.0, 5.0);
        assert_eq!(evs.len(), 1, "no collapse: {evs:?}");
        assert!(
            matches!(
                &evs[0],
                TabGroupEvent::TabSplitToNewPane {
                    from_pane_idx: 0,
                    tab_id,
                    edge: crate::DropEdge::Right,
                    ..
                } if tab_id == "t1"
            ),
            "unexpected event: {:?}",
            evs[0]
        );
        assert_eq!(ctrl.pane_count(), 3);
        assert_eq!(ctrl.layout.leaf_count(), 3);
    }

    #[test]
    fn set_drag_geometry_ignores_excess_entries() {
        // Passing more PaneDragRect entries than panes should not panic or corrupt.
        let (mut ctrl, mut rects) = two_pane_drag_rects();
        rects.push(PaneDragRect {
            strip_bounds: Rect::new(200.0, 0.0, 80.0, 1.0),
            content_bounds: Rect::new(200.0, 1.0, 80.0, 10.0),
            tab_slots: vec![(200.0, 208.0)],
        });
        ctrl.set_drag_geometry(&rects);
        // Only 2 panes primed; excess entry silently dropped.
        assert_eq!(ctrl.drop_group_rects().len(), 2);
    }

    #[test]
    fn set_drag_geometry_partial_prime_leaves_rest_unprimed() {
        // Passing fewer entries primes only those panes; the rest stay None.
        let (mut ctrl, rects) = two_pane_drag_rects();
        ctrl.set_drag_geometry(&rects[..1]); // only pane 0
        let groups = ctrl.drop_group_rects();
        assert_eq!(groups.len(), 1, "only pane 0 should be primed");
        assert_eq!(groups[0].bounds.x, 0.0);
    }

    // ── Unique pane IDs after repeated splits ─────────────────────────────────

    #[test]
    fn split_then_collapse_then_split_unique_ids() {
        // Drag t1 out to create pane:1, collapse it, then drag a different tab
        // to create another split.  The second new pane must have a distinct id.
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5); // drag t1
        ctrl.handle_tab_drop(150.0, 5.0); // split → pane[2].id == "pane:1"
        assert_eq!(ctrl.pane_count(), 3);
        let first_new_id = ctrl.panes[2].id.clone();

        ctrl.collapse_pane(2); // remove the new pane
        assert_eq!(ctrl.pane_count(), 2);

        // Add an extra tab so pane 0 won't be emptied by the next drag.
        ctrl.add_tab(0, tab("t-extra", "extra.rs", false));

        // Re-prime: pane 0 now has 2 tabs (t0, t-extra), pane 1 has 1 tab (x0).
        prime_pane(&mut ctrl, 0, 0.0, 0.0, 80.0, 8.0, 2.0);
        prime_pane(&mut ctrl, 1, 80.0, 0.0, 80.0, 8.0, 2.0);

        // Drag t-extra (slot [8..16), x=9) to right edge of pane 1 → creates pane:2.
        ctrl.handle_tab_drag_start(9.0, 0.5);
        let evs = ctrl.handle_tab_drop(150.0, 5.0);

        assert_eq!(
            ctrl.pane_count(),
            3,
            "second split should create 3 panes: {evs:?}"
        );
        let second_new_id = ctrl.panes[2].id.clone();
        assert_ne!(
            second_new_id, first_new_id,
            "second split pane must have a unique id (got {second_new_id:?})"
        );
    }

    // ── resolve_tab_drop: host-owned-model adoption path ───────────────────────
    //
    // These tests call `resolve_tab_drop` directly with hand-built
    // `DropGroupRect`s and a `TabDragSource` — no `TabGroupController`
    // anywhere. This is the shape a host with its own tab/pane model (e.g.
    // vimcode's `Engine::editor_groups`) uses: build `groups` from its own
    // layout, call `resolve_tab_drop`, translate the result into its own
    // mutations directly. Geometry mirrors `two_pane_drag_rects()` above so
    // the numbers are directly comparable to the `TabGroupController`-owned
    // tests.

    fn two_group_rects() -> Vec<DropGroupRect> {
        vec![
            DropGroupRect {
                bounds: Rect::new(0.0, 0.0, 80.0, 11.0),
                tab_slots: vec![(0.0, 8.0), (8.0, 16.0)],
            },
            DropGroupRect {
                bounds: Rect::new(80.0, 0.0, 80.0, 11.0),
                tab_slots: vec![(80.0, 88.0)],
            },
        ]
    }

    #[test]
    fn resolve_tab_drop_reorders_within_same_pane() {
        let groups = two_group_rects();
        let counts = [2usize, 1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 1, // "t1"
        };
        let instr = resolve_tab_drop(source, &counts, 3.0, 0.5, &groups, 1.0);
        assert_eq!(
            instr,
            TabDropInstruction::Reorder {
                pane_idx: 0,
                from_idx: 1,
                to_idx: 0,
            }
        );
    }

    #[test]
    fn resolve_tab_drop_same_position_is_noop() {
        let groups = two_group_rects();
        let counts = [2usize, 1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 1,
        };
        let instr = resolve_tab_drop(source, &counts, 14.0, 0.5, &groups, 1.0);
        assert_eq!(instr, TabDropInstruction::NoOp);
    }

    #[test]
    fn resolve_tab_drop_same_pane_center_is_noop() {
        let groups = two_group_rects();
        let counts = [2usize, 1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 1,
        };
        let instr = resolve_tab_drop(source, &counts, 40.0, 5.0, &groups, 1.0);
        assert_eq!(instr, TabDropInstruction::NoOp);
    }

    #[test]
    fn resolve_tab_drop_moves_tab_to_another_pane_center() {
        let groups = two_group_rects();
        let counts = [2usize, 1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 1,
        };
        let instr = resolve_tab_drop(source, &counts, 120.0, 5.0, &groups, 1.0);
        assert_eq!(
            instr,
            TabDropInstruction::MoveToPane {
                from_pane_idx: 0,
                from_idx: 1,
                to_pane_idx: 1,
                insert_idx: 1,
                source_now_empty: false,
            }
        );
    }

    #[test]
    fn resolve_tab_drop_reports_source_now_empty_when_last_tab_moves() {
        let groups = two_group_rects();
        // Source pane down to its last tab, as the host's own model would
        // report once earlier tabs are already gone.
        let counts = [1usize, 1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 0,
        };
        let instr = resolve_tab_drop(source, &counts, 120.0, 5.0, &groups, 1.0);
        assert_eq!(
            instr,
            TabDropInstruction::MoveToPane {
                from_pane_idx: 0,
                from_idx: 0,
                to_pane_idx: 1,
                insert_idx: 1,
                source_now_empty: true,
            }
        );
    }

    #[test]
    fn resolve_tab_drop_splits_right_edge() {
        let groups = two_group_rects();
        let counts = [2usize, 1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 1,
        };
        let instr = resolve_tab_drop(source, &counts, 150.0, 5.0, &groups, 1.0);
        assert_eq!(
            instr,
            TabDropInstruction::SplitToNewPane {
                from_pane_idx: 0,
                from_idx: 1,
                target_pane_idx: 1,
                edge: DropEdge::Right,
                split_direction: SplitDirection::Horizontal,
                source_now_empty: false,
            }
        );
    }

    #[test]
    fn resolve_tab_drop_only_tab_only_pane_split_is_noop() {
        let groups = vec![DropGroupRect {
            bounds: Rect::new(0.0, 0.0, 80.0, 11.0),
            tab_slots: vec![(0.0, 8.0)],
        }];
        let counts = [1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 0,
        };
        let instr = resolve_tab_drop(source, &counts, 1.0, 5.0, &groups, 1.0);
        assert_eq!(instr, TabDropInstruction::NoOp);
    }

    #[test]
    fn resolve_tab_drop_outside_all_groups_is_noop() {
        let groups = two_group_rects();
        let counts = [2usize, 1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 1,
        };
        let instr = resolve_tab_drop(source, &counts, 999.0, 999.0, &groups, 1.0);
        assert_eq!(instr, TabDropInstruction::NoOp);
    }

    #[test]
    fn resolve_tab_drop_agrees_with_controller_handle_tab_drop() {
        // Cross-check: `TabGroupController::handle_tab_drop` (the owned
        // model path) and `resolve_tab_drop` (the host-owned-model path)
        // must reach equivalent conclusions from equivalent inputs, since
        // the former is implemented in terms of the latter.
        let mut ctrl = make_two_pane();
        ctrl.handle_tab_drag_start(9.0, 0.5); // drag t1 from pane 0
        let events = ctrl.handle_tab_drop(150.0, 5.0); // split right edge of pane 1

        let groups = two_group_rects();
        let counts = [2usize, 1usize];
        let source = TabDragSource {
            pane_idx: 0,
            tab_idx: 1,
        };
        let instr = resolve_tab_drop(source, &counts, 150.0, 5.0, &groups, 1.0);

        assert_eq!(
            instr,
            TabDropInstruction::SplitToNewPane {
                from_pane_idx: 0,
                from_idx: 1,
                target_pane_idx: 1,
                edge: DropEdge::Right,
                split_direction: SplitDirection::Horizontal,
                source_now_empty: false,
            }
        );
        assert_eq!(
            events,
            vec![TabGroupEvent::TabSplitToNewPane {
                from_pane_idx: 0,
                tab_id: "t1".into(),
                target_pane_idx: 1,
                edge: DropEdge::Right,
                new_pane_idx: 2,
            }]
        );
    }

    // ── chrome_line_height governs the tab strip ───────────────────────────

    #[test]
    fn strip_height_uses_chrome_line_height() {
        let mut ctrl = make_group();
        let mut backend = crate::testing::RecordingBackend {
            line_height: 20.0,
            chrome_line_height: Some(35.0),
            viewport: crate::Viewport {
                width: 800.0,
                height: 600.0,
                scale: 1.0,
            },
            char_width: 8.0,
            ..Default::default()
        };

        let bounds = Rect::new(0.0, 0.0, 800.0, 600.0);
        let layout = ctrl.render(&mut backend, bounds);

        // The strip height must be chrome_line_height (35), not
        // the editor line_height (20).
        assert_eq!(layout.strip_bounds.len(), 1);
        assert_eq!(layout.strip_bounds[0].height, 35.0);
        // Content area starts after the strip.
        assert_eq!(layout.content_bounds[0].y, 35.0);
        assert_eq!(layout.content_bounds[0].height, 600.0 - 35.0);
    }
}