ftui-render 0.4.0

Render kernel: cells, buffers, diffs, and ANSI presentation.
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
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
#![forbid(unsafe_code)]

//! Buffer grid storage.
//!
//! The `Buffer` is a 2D grid of [`Cell`]s representing the terminal display.
//! It provides efficient cell access, scissor (clipping) regions, and opacity
//! stacks for compositing.
//!
//! # Layout
//!
//! Cells are stored in row-major order: `index = y * width + x`.
//!
//! # Invariants
//!
//! 1. `cells.len() == width * height`
//! 2. Width and height never change after creation
//! 3. Scissor stack intersection monotonically decreases on push
//! 4. Opacity stack product stays in `[0.0, 1.0]`
//! 5. Scissor/opacity stacks always have at least one element
//!
//! # Dirty Row Tracking (bd-4kq0.1.1)
//!
//! ## Mathematical Invariant
//!
//! Let D be the set of dirty rows. The fundamental soundness property:
//!
//! ```text
//! ∀ y ∈ [0, height): if ∃ x such that old(x, y) ≠ new(x, y), then y ∈ D
//! ```
//!
//! This ensures the diff algorithm can safely skip non-dirty rows without
//! missing any changes. The invariant is maintained by marking rows dirty
//! on every cell mutation.
//!
//! ## Bookkeeping Cost
//!
//! - O(1) per mutation (single array write)
//! - O(height) space for dirty bitmap
//! - Target: < 2% overhead vs baseline rendering
//!
//! # Dirty Span Tracking (bd-3e1t.6.2)
//!
//! Dirty spans refine dirty rows by recording per-row x-ranges of mutations.
//!
//! ## Invariant
//!
//! ```text
//! ∀ (x, y) mutated since last clear, ∃ span in row y with x ∈ [x0, x1)
//! ```
//!
//! Spans are sorted, non-overlapping, and merged when overlapping, adjacent, or separated
//! by at most `DIRTY_SPAN_MERGE_GAP` cells (gap becomes dirty). If a row exceeds
//! `DIRTY_SPAN_MAX_SPANS_PER_ROW`, it falls back to full-row scan.

use smallvec::SmallVec;

use crate::budget::DegradationLevel;
use crate::cell::{Cell, GraphemeId};
use ftui_core::geometry::Rect;

/// Maximum number of dirty spans per row before falling back to full-row scan.
const DIRTY_SPAN_MAX_SPANS_PER_ROW: usize = 64;
/// Merge spans when the gap between them is at most this many cells.
const DIRTY_SPAN_MERGE_GAP: u16 = 1;

/// Configuration for dirty-span tracking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DirtySpanConfig {
    /// Enable dirty-span tracking (used by diff).
    pub enabled: bool,
    /// Maximum spans per row before falling back to full-row scan.
    pub max_spans_per_row: usize,
    /// Merge spans when the gap between them is at most this many cells.
    pub merge_gap: u16,
    /// Expand spans by this many cells on each side.
    pub guard_band: u16,
}

impl Default for DirtySpanConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_spans_per_row: DIRTY_SPAN_MAX_SPANS_PER_ROW,
            merge_gap: DIRTY_SPAN_MERGE_GAP,
            guard_band: 0,
        }
    }
}

impl DirtySpanConfig {
    /// Toggle dirty-span tracking.
    #[must_use]
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Set max spans per row before fallback.
    #[must_use]
    pub fn with_max_spans_per_row(mut self, max_spans: usize) -> Self {
        self.max_spans_per_row = max_spans;
        self
    }

    /// Set merge gap threshold.
    #[must_use]
    pub fn with_merge_gap(mut self, merge_gap: u16) -> Self {
        self.merge_gap = merge_gap;
        self
    }

    /// Set guard band expansion (cells).
    #[must_use]
    pub fn with_guard_band(mut self, guard_band: u16) -> Self {
        self.guard_band = guard_band;
        self
    }
}

/// Half-open dirty span [x0, x1) for a single row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DirtySpan {
    pub x0: u16,
    pub x1: u16,
}

impl DirtySpan {
    #[inline]
    pub const fn new(x0: u16, x1: u16) -> Self {
        Self { x0, x1 }
    }

    #[inline]
    pub const fn len(self) -> usize {
        self.x1.saturating_sub(self.x0) as usize
    }
}

#[derive(Debug, Default, Clone)]
pub(crate) struct DirtySpanRow {
    overflow: bool,
    /// Inline storage for up to 4 spans (16 bytes) avoids heap allocation for ~90% of rows.
    spans: SmallVec<[DirtySpan; 4]>,
}

impl DirtySpanRow {
    #[inline]
    fn new_full() -> Self {
        Self {
            overflow: true,
            spans: SmallVec::new(),
        }
    }

    #[inline]
    fn clear(&mut self) {
        self.overflow = false;
        self.spans.clear();
    }

    #[inline]
    fn set_full(&mut self) {
        self.overflow = true;
        self.spans.clear();
    }

    #[inline]
    pub(crate) fn spans(&self) -> &[DirtySpan] {
        &self.spans
    }

    #[inline]
    pub(crate) fn is_full(&self) -> bool {
        self.overflow
    }
}

/// Dirty-span statistics for logging/telemetry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DirtySpanStats {
    /// Rows marked as full-row dirty.
    pub rows_full_dirty: usize,
    /// Rows with at least one span.
    pub rows_with_spans: usize,
    /// Total number of spans across all rows.
    pub total_spans: usize,
    /// Total number of span overflow events since last clear.
    pub overflows: usize,
    /// Total coverage in cells (span lengths + full rows).
    pub span_coverage_cells: usize,
    /// Maximum span length observed (including full-row spans).
    pub max_span_len: usize,
    /// Configured max spans per row.
    pub max_spans_per_row: usize,
}

/// A 2D grid of terminal cells.
///
/// # Example
///
/// ```
/// use ftui_render::buffer::Buffer;
/// use ftui_render::cell::Cell;
///
/// let mut buffer = Buffer::new(80, 24);
/// buffer.set(0, 0, Cell::from_char('H'));
/// buffer.set(1, 0, Cell::from_char('i'));
/// ```
#[derive(Debug, Clone)]
pub struct Buffer {
    width: u16,
    height: u16,
    cells: Vec<Cell>,
    scissor_stack: Vec<Rect>,
    opacity_stack: Vec<f32>,
    /// Current degradation level for this frame.
    ///
    /// Widgets read this during rendering to decide how much visual fidelity
    /// to provide. Set by the runtime before calling `Model::view()`.
    pub degradation: DegradationLevel,
    /// Per-row dirty flags for diff optimization.
    ///
    /// When a row is marked dirty, the diff algorithm must compare it cell-by-cell.
    /// Clean rows can be skipped entirely.
    ///
    /// Invariant: `dirty_rows.len() == height`
    dirty_rows: Vec<bool>,
    /// Per-row dirty span tracking for sparse diff scans.
    dirty_spans: Vec<DirtySpanRow>,
    /// Dirty-span tracking configuration.
    dirty_span_config: DirtySpanConfig,
    /// Number of span overflow events since the last `clear_dirty()`.
    dirty_span_overflows: usize,
    /// Per-cell dirty bitmap for tile-based diff skipping.
    dirty_bits: Vec<u8>,
    /// Count of dirty cells tracked in the bitmap.
    dirty_cells: usize,
    /// Whether the whole buffer is marked dirty (bitmap may be stale).
    dirty_all: bool,
}

impl Buffer {
    /// Create a new buffer with the given dimensions.
    ///
    /// All cells are initialized to the default (empty cell with white
    /// foreground and transparent background).
    ///
    /// Dimensions are clamped to a minimum of 1x1 to prevent panics during
    /// extreme window resizes.
    pub fn new(width: u16, height: u16) -> Self {
        let width = width.max(1);
        let height = height.max(1);

        let size = width as usize * height as usize;
        let cells = vec![Cell::default(); size];

        let dirty_spans = (0..height)
            .map(|_| DirtySpanRow::new_full())
            .collect::<Vec<_>>();
        let dirty_bits = vec![0u8; size];
        let dirty_cells = size;
        let dirty_all = true;

        Self {
            width,
            height,
            cells,
            scissor_stack: vec![Rect::from_size(width, height)],
            opacity_stack: vec![1.0],
            degradation: DegradationLevel::Full,
            // All rows start dirty to ensure initial diffs against this buffer
            // (e.g. from DoubleBuffer resize) correctly identify it as changed/empty.
            dirty_rows: vec![true; height as usize],
            // Start with full-row dirty spans to force initial full scan.
            dirty_spans,
            dirty_span_config: DirtySpanConfig::default(),
            dirty_span_overflows: 0,
            dirty_bits,
            dirty_cells,
            dirty_all,
        }
    }

    /// Buffer width in cells.
    #[inline]
    pub const fn width(&self) -> u16 {
        self.width
    }

    /// Buffer height in cells.
    #[inline]
    pub const fn height(&self) -> u16 {
        self.height
    }

    /// Total number of cells.
    #[inline]
    pub fn len(&self) -> usize {
        self.cells.len()
    }

    /// Check if the buffer is empty (should never be true for valid buffers).
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.cells.is_empty()
    }

    /// Bounding rect of the entire buffer.
    #[inline]
    pub const fn bounds(&self) -> Rect {
        Rect::from_size(self.width, self.height)
    }

    /// Return the height of content (last non-empty row + 1).
    ///
    /// Rows are considered empty only if all cells are the default cell.
    /// Returns 0 if the buffer contains no content.
    #[inline]
    pub fn content_height(&self) -> u16 {
        let default_cell = Cell::default();
        let width = self.width as usize;
        for y in (0..self.height).rev() {
            let row_start = y as usize * width;
            let row_end = row_start + width;
            if self.cells[row_start..row_end]
                .iter()
                .any(|cell| *cell != default_cell)
            {
                return y + 1;
            }
        }
        0
    }

    // ----- Dirty Tracking API -----

    /// Mark a row as dirty (modified since last clear).
    ///
    /// This is O(1) and must be called on every cell mutation to maintain
    /// the dirty-soundness invariant.
    #[inline]
    fn mark_dirty_row(&mut self, y: u16) {
        if let Some(slot) = self.dirty_rows.get_mut(y as usize) {
            *slot = true;
        }
    }

    /// Mark a range of cells in a row as dirty in the bitmap (end exclusive).
    #[inline]
    fn mark_dirty_bits_range(&mut self, y: u16, start: u16, end: u16) {
        if self.dirty_all {
            return;
        }
        if y >= self.height {
            return;
        }

        let width = self.width;
        if start >= width {
            return;
        }
        let end = end.min(width);
        if start >= end {
            return;
        }

        let row_start = y as usize * width as usize;
        let slice = &mut self.dirty_bits[row_start + start as usize..row_start + end as usize];
        let newly_dirty = slice.iter().filter(|&&b| b == 0).count();
        slice.fill(1);
        self.dirty_cells = self.dirty_cells.saturating_add(newly_dirty);
    }

    /// Mark an entire row as dirty in the bitmap.
    #[inline]
    fn mark_dirty_bits_row(&mut self, y: u16) {
        self.mark_dirty_bits_range(y, 0, self.width);
    }

    /// Mark a row as fully dirty (full scan).
    #[inline]
    fn mark_dirty_row_full(&mut self, y: u16) {
        self.mark_dirty_row(y);
        if self.dirty_span_config.enabled
            && let Some(row) = self.dirty_spans.get_mut(y as usize)
        {
            row.set_full();
        }
        self.mark_dirty_bits_row(y);
    }

    /// Mark a span within a row as dirty (half-open).
    #[inline]
    pub(crate) fn mark_dirty_span(&mut self, y: u16, x0: u16, x1: u16) {
        self.mark_dirty_row(y);
        let width = self.width;
        let (start, mut end) = if x0 <= x1 { (x0, x1) } else { (x1, x0) };
        if start >= width {
            return;
        }
        if end > width {
            end = width;
        }
        if start >= end {
            return;
        }

        self.mark_dirty_bits_range(y, start, end);

        if !self.dirty_span_config.enabled {
            return;
        }

        let guard_band = self.dirty_span_config.guard_band;
        let span_start = start.saturating_sub(guard_band);
        let mut span_end = end.saturating_add(guard_band);
        if span_end > width {
            span_end = width;
        }
        if span_start >= span_end {
            return;
        }

        let Some(row) = self.dirty_spans.get_mut(y as usize) else {
            return;
        };

        if row.is_full() {
            return;
        }

        let new_span = DirtySpan::new(span_start, span_end);
        let spans = &mut row.spans;
        let insert_at = spans.partition_point(|span| span.x0 <= new_span.x0);
        spans.insert(insert_at, new_span);

        // Merge overlapping or near-adjacent spans (gap <= merge_gap).
        let merge_gap = self.dirty_span_config.merge_gap;
        let mut i = if insert_at > 0 { insert_at - 1 } else { 0 };
        while i + 1 < spans.len() {
            let current = spans[i];
            let next = spans[i + 1];
            let merge_limit = current.x1.saturating_add(merge_gap);
            if merge_limit >= next.x0 {
                spans[i].x1 = current.x1.max(next.x1);
                spans.remove(i + 1);
                continue;
            }
            i += 1;
        }

        if spans.len() > self.dirty_span_config.max_spans_per_row {
            row.set_full();
            self.dirty_span_overflows = self.dirty_span_overflows.saturating_add(1);
        }
    }

    /// Mark all rows as dirty (e.g., after a full clear or bulk write).
    #[inline]
    pub fn mark_all_dirty(&mut self) {
        self.dirty_rows.fill(true);
        if self.dirty_span_config.enabled {
            for row in &mut self.dirty_spans {
                row.set_full();
            }
        } else {
            for row in &mut self.dirty_spans {
                row.clear();
            }
        }
        self.dirty_all = true;
        self.dirty_cells = self.cells.len();
    }

    /// Reset all dirty flags and spans to clean.
    ///
    /// Call this after the diff has consumed the dirty state (between frames).
    #[inline]
    pub fn clear_dirty(&mut self) {
        self.dirty_rows.fill(false);
        for row in &mut self.dirty_spans {
            row.clear();
        }
        self.dirty_span_overflows = 0;
        self.dirty_bits.fill(0);
        self.dirty_cells = 0;
        self.dirty_all = false;
    }

    /// Check if a specific row is dirty.
    #[inline]
    pub fn is_row_dirty(&self, y: u16) -> bool {
        self.dirty_rows.get(y as usize).copied().unwrap_or(false)
    }

    /// Get the dirty row flags as a slice.
    ///
    /// Each element corresponds to a row: `true` means the row was modified
    /// since the last `clear_dirty()` call.
    #[inline]
    pub fn dirty_rows(&self) -> &[bool] {
        &self.dirty_rows
    }

    /// Count the number of dirty rows.
    #[inline]
    pub fn dirty_row_count(&self) -> usize {
        self.dirty_rows.iter().filter(|&&d| d).count()
    }

    /// Access the per-cell dirty bitmap (0 = clean, 1 = dirty).
    #[inline]
    #[allow(dead_code)]
    pub(crate) fn dirty_bits(&self) -> &[u8] {
        &self.dirty_bits
    }

    /// Count of dirty cells tracked in the bitmap.
    #[inline]
    #[allow(dead_code)]
    pub(crate) fn dirty_cell_count(&self) -> usize {
        self.dirty_cells
    }

    /// Whether the whole buffer is marked dirty (bitmap may be stale).
    #[inline]
    #[allow(dead_code)]
    pub(crate) fn dirty_all(&self) -> bool {
        self.dirty_all
    }

    /// Access a row's dirty span state.
    #[inline]
    #[allow(dead_code)]
    pub(crate) fn dirty_span_row(&self, y: u16) -> Option<&DirtySpanRow> {
        if !self.dirty_span_config.enabled {
            return None;
        }
        self.dirty_spans.get(y as usize)
    }

    /// Summarize dirty-span stats for logging/telemetry.
    pub fn dirty_span_stats(&self) -> DirtySpanStats {
        if !self.dirty_span_config.enabled {
            return DirtySpanStats {
                rows_full_dirty: 0,
                rows_with_spans: 0,
                total_spans: 0,
                overflows: 0,
                span_coverage_cells: 0,
                max_span_len: 0,
                max_spans_per_row: self.dirty_span_config.max_spans_per_row,
            };
        }

        let mut rows_full_dirty = 0usize;
        let mut rows_with_spans = 0usize;
        let mut total_spans = 0usize;
        let mut span_coverage_cells = 0usize;
        let mut max_span_len = 0usize;

        for row in &self.dirty_spans {
            if row.is_full() {
                rows_full_dirty += 1;
                span_coverage_cells += self.width as usize;
                max_span_len = max_span_len.max(self.width as usize);
                continue;
            }
            if !row.spans().is_empty() {
                rows_with_spans += 1;
            }
            total_spans += row.spans().len();
            for span in row.spans() {
                span_coverage_cells += span.len();
                max_span_len = max_span_len.max(span.len());
            }
        }

        DirtySpanStats {
            rows_full_dirty,
            rows_with_spans,
            total_spans,
            overflows: self.dirty_span_overflows,
            span_coverage_cells,
            max_span_len,
            max_spans_per_row: self.dirty_span_config.max_spans_per_row,
        }
    }

    /// Access the dirty-span configuration.
    #[inline]
    pub fn dirty_span_config(&self) -> DirtySpanConfig {
        self.dirty_span_config
    }

    /// Update dirty-span configuration (clears existing spans when changed).
    pub fn set_dirty_span_config(&mut self, config: DirtySpanConfig) {
        if self.dirty_span_config == config {
            return;
        }
        self.dirty_span_config = config;
        for row in &mut self.dirty_spans {
            row.clear();
        }
        self.dirty_span_overflows = 0;
    }

    // ----- Coordinate Helpers -----

    /// Convert (x, y) coordinates to a linear index.
    ///
    /// Returns `None` if coordinates are out of bounds.
    #[inline]
    fn index(&self, x: u16, y: u16) -> Option<usize> {
        if x < self.width && y < self.height {
            Some(y as usize * self.width as usize + x as usize)
        } else {
            None
        }
    }

    /// Convert (x, y) coordinates to a linear index without bounds checking.
    ///
    /// # Safety
    ///
    /// Caller must ensure x < width and y < height.
    #[inline]
    pub(crate) fn index_unchecked(&self, x: u16, y: u16) -> usize {
        debug_assert!(x < self.width && y < self.height);
        y as usize * self.width as usize + x as usize
    }

    /// Get mutable reference to a cell at a linear index without bounds checking.
    ///
    /// # Safety
    ///
    /// Caller must ensure idx < width * height and handle dirty tracking manually.
    #[inline]
    pub(crate) fn cell_mut_unchecked(&mut self, idx: usize) -> &mut Cell {
        &mut self.cells[idx]
    }

    /// Get a reference to the cell at (x, y).
    ///
    /// Returns `None` if coordinates are out of bounds.
    #[inline]
    #[must_use]
    pub fn get(&self, x: u16, y: u16) -> Option<&Cell> {
        self.index(x, y).map(|i| &self.cells[i])
    }

    /// Get a mutable reference to the cell at (x, y).
    ///
    /// Returns `None` if coordinates are out of bounds.
    /// Proactively marks the row dirty since the caller may mutate the cell.
    #[inline]
    #[must_use]
    pub fn get_mut(&mut self, x: u16, y: u16) -> Option<&mut Cell> {
        let idx = self.index(x, y)?;
        self.mark_dirty_span(y, x, x.saturating_add(1));
        Some(&mut self.cells[idx])
    }

    /// Get a reference to the cell at (x, y) without bounds checking.
    ///
    /// # Panics
    ///
    /// Panics in debug mode if coordinates are out of bounds.
    /// May cause undefined behavior in release mode if out of bounds.
    #[inline]
    pub fn get_unchecked(&self, x: u16, y: u16) -> &Cell {
        let i = self.index_unchecked(x, y);
        &self.cells[i]
    }

    /// Helper to clean up overlapping multi-width cells before writing.
    ///
    /// Returns the half-open span of any cells cleared by this cleanup.
    #[inline]
    fn cleanup_overlap(&mut self, x: u16, y: u16, new_cell: &Cell) -> Option<DirtySpan> {
        let idx = self.index(x, y)?;
        let current = self.cells[idx];
        let mut touched = false;
        let mut min_x = x;
        let mut max_x = x;

        // Case 1: Overwriting a Wide Head
        if current.content.width() > 1 {
            let width = current.content.width();
            // Clear the head
            // self.cells[idx] = Cell::default(); // Caller (set) will overwrite this, but for correctness/safety we could.
            // Actually, `set` overwrites `cells[idx]` immediately after.
            // But we must clear the tails.
            for i in 1..width {
                let Some(cx) = x.checked_add(i as u16) else {
                    break;
                };
                if let Some(tail_idx) = self.index(cx, y)
                    && self.cells[tail_idx].is_continuation()
                {
                    self.cells[tail_idx] = Cell::default();
                    touched = true;
                    min_x = min_x.min(cx);
                    max_x = max_x.max(cx);
                }
            }
        }
        // Case 2: Overwriting a Continuation
        else if current.is_continuation() && !new_cell.is_continuation() {
            let mut back_x = x;
            // Limit scan to max possible grapheme width to avoid O(N) scan on rows
            // filled with orphaned continuations.
            let limit = x.saturating_sub(GraphemeId::MAX_WIDTH as u16);

            while back_x > limit {
                back_x -= 1;
                if let Some(h_idx) = self.index(back_x, y) {
                    let h_cell = self.cells[h_idx];
                    if !h_cell.is_continuation() {
                        // Found the potential head
                        let width = h_cell.content.width();
                        if (back_x as usize + width) > x as usize {
                            // This head owns the cell we are overwriting.
                            // Clear the head.
                            self.cells[h_idx] = Cell::default();
                            touched = true;
                            min_x = min_x.min(back_x);
                            max_x = max_x.max(back_x);

                            // Clear all its tails (except the one we're about to write, effectively)
                            // We just iterate 1..width and clear CONTs.
                            for i in 1..width {
                                let Some(cx) = back_x.checked_add(i as u16) else {
                                    break;
                                };
                                if let Some(tail_idx) = self.index(cx, y) {
                                    // Note: tail_idx might be our current `idx`.
                                    // We can clear it; `set` will overwrite it in a moment.
                                    if self.cells[tail_idx].is_continuation() {
                                        self.cells[tail_idx] = Cell::default();
                                        touched = true;
                                        min_x = min_x.min(cx);
                                        max_x = max_x.max(cx);
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }

        if touched {
            Some(DirtySpan::new(min_x, max_x.saturating_add(1)))
        } else {
            None
        }
    }

    /// Helper to clean up orphaned continuation cells to the right of a write.
    ///
    /// If we write a cell at `x`, and `x+1` contains a continuation cell that
    /// is NOT owned by `x` (which is guaranteed since we just wrote `x`),
    /// then `x+1` (and subsequent continuations) are orphans. This method
    /// scans forward and clears them to prevent visual artifacts.
    #[inline]
    fn cleanup_orphaned_tails(&mut self, start_x: u16, y: u16) {
        if start_x >= self.width {
            return;
        }

        // Optimization: check first cell without loop overhead
        let Some(idx) = self.index(start_x, y) else {
            return;
        };
        if !self.cells[idx].is_continuation() {
            return;
        }

        // Found an orphan, start scanning
        let mut x = start_x;
        let mut max_x = x;
        let row_end_idx = (y as usize * self.width as usize) + self.width as usize;
        let mut curr_idx = idx;

        while curr_idx < row_end_idx && self.cells[curr_idx].is_continuation() {
            self.cells[curr_idx] = Cell::default();
            max_x = x;
            x = x.saturating_add(1);
            curr_idx += 1;
        }

        // Mark the cleared range as dirty
        self.mark_dirty_span(y, start_x, max_x.saturating_add(1));
    }

    /// Fast-path cell write for the common case.
    ///
    /// Bypasses scissor intersection, opacity blending, and overlap cleanup
    /// when all of the following hold:
    ///
    /// - The cell is single-width (`width() <= 1`) and not a continuation
    /// - The cell background is either fully opaque or fully transparent
    ///   (`bg.a() == 255 || bg.a() == 0`)
    /// - Only the base scissor is active (no nested push)
    /// - Only the base opacity is active (no nested push)
    /// - The existing cell at the target is also single-width and not a continuation
    ///
    /// Falls through to [`set()`] for any non-trivial case, so behavior is
    /// always identical to calling `set()` directly.
    #[inline]
    pub fn set_fast(&mut self, x: u16, y: u16, cell: Cell) {
        // Bail to full path for wide, continuation, or non-trivial bg alpha cells.
        // Must use width() not width_hint(): width_hint() returns 1 for all
        // direct chars including CJK, but width() does a proper unicode lookup.
        // set() always composites bg over the existing cell (src-over). We can
        // skip compositing only when bg alpha is 255 (result is bg) or 0 (result
        // is existing bg).
        let bg_a = cell.bg.a();
        if cell.content.width() > 1 || cell.is_continuation() || (bg_a != 255 && bg_a != 0) {
            return self.set(x, y, cell);
        }

        // Bail if scissor or opacity stacks are non-trivial
        if self.scissor_stack.len() != 1 || self.opacity_stack.len() != 1 {
            return self.set(x, y, cell);
        }

        // Bounds check
        let Some(idx) = self.index(x, y) else {
            return;
        };

        // Check that existing cell doesn't need overlap cleanup.
        // Must use width() for the same reason: a CJK direct char at this
        // position would have width() == 2 with a continuation at x+1.
        let existing = self.cells[idx];
        if existing.content.width() > 1 || existing.is_continuation() {
            return self.set(x, y, cell);
        }

        // All fast-path conditions met: direct write.
        //
        // bg compositing is safe to skip:
        // - alpha 255: bg.over(existing_bg) == bg
        // - alpha 0: bg.over(existing_bg) == existing_bg
        let mut final_cell = cell;
        if bg_a == 0 {
            final_cell.bg = existing.bg;
        }

        self.cells[idx] = final_cell;
        self.mark_dirty_span(y, x, x.saturating_add(1));
        self.cleanup_orphaned_tails(x.saturating_add(1), y);
    }

    /// Set the cell at (x, y).
    ///
    /// This method:
    /// - Respects the current scissor region (skips if outside)
    /// - Applies the current opacity stack to cell colors
    /// - Does nothing if coordinates are out of bounds
    /// - **Automatically sets CONTINUATION cells** for multi-width content
    /// - **Atomic wide writes**: If a wide character doesn't fully fit in the
    ///   scissor region/bounds, NOTHING is written.
    ///
    /// For bulk operations without scissor/opacity/safety, use [`set_raw`].
    #[inline]
    pub fn set(&mut self, x: u16, y: u16, cell: Cell) {
        let width = cell.content.width();

        // Single cell fast path (width 0 or 1)
        if width <= 1 {
            // Check bounds
            let Some(idx) = self.index(x, y) else {
                return;
            };

            // Check scissor region
            if !self.current_scissor().contains(x, y) {
                return;
            }

            // Cleanup overlaps and track any cleared span.
            let mut span_start = x;
            let mut span_end = x.saturating_add(1);
            if let Some(span) = self.cleanup_overlap(x, y, &cell) {
                span_start = span_start.min(span.x0);
                span_end = span_end.max(span.x1);
            }

            let existing_bg = self.cells[idx].bg;

            // Apply opacity to the incoming cell, then composite over existing background.
            let mut final_cell = if self.current_opacity() < 1.0 {
                let opacity = self.current_opacity();
                Cell {
                    fg: cell.fg.with_opacity(opacity),
                    bg: cell.bg.with_opacity(opacity),
                    ..cell
                }
            } else {
                cell
            };

            final_cell.bg = final_cell.bg.over(existing_bg);

            self.cells[idx] = final_cell;
            self.mark_dirty_span(y, span_start, span_end);
            self.cleanup_orphaned_tails(x.saturating_add(1), y);
            return;
        }

        // Multi-width character atomicity check
        // Ensure ALL cells (head + tail) are within bounds and scissor
        let scissor = self.current_scissor();
        for i in 0..width {
            let Some(cx) = x.checked_add(i as u16) else {
                return;
            };
            // Check bounds
            if cx >= self.width || y >= self.height {
                return;
            }
            // Check scissor
            if !scissor.contains(cx, y) {
                return;
            }
        }

        // If we get here, it's safe to write everything.

        // Cleanup overlaps for all cells and track any cleared span.
        let mut span_start = x;
        let mut span_end = x.saturating_add(width as u16);
        if let Some(span) = self.cleanup_overlap(x, y, &cell) {
            span_start = span_start.min(span.x0);
            span_end = span_end.max(span.x1);
        }
        for i in 1..width {
            // Safe: atomicity check above verified x + i fits in u16
            if let Some(span) = self.cleanup_overlap(x + i as u16, y, &Cell::CONTINUATION) {
                span_start = span_start.min(span.x0);
                span_end = span_end.max(span.x1);
            }
        }

        // 1. Write Head
        let idx = self.index_unchecked(x, y);
        let old_cell = self.cells[idx];
        let mut final_cell = if self.current_opacity() < 1.0 {
            let opacity = self.current_opacity();
            Cell {
                fg: cell.fg.with_opacity(opacity),
                bg: cell.bg.with_opacity(opacity),
                ..cell
            }
        } else {
            cell
        };

        // Composite background (src over dst)
        final_cell.bg = final_cell.bg.over(old_cell.bg);

        self.cells[idx] = final_cell;

        // 2. Write Tail (Continuation cells)
        // We can use set_raw-like access because we already verified bounds
        for i in 1..width {
            let idx = self.index_unchecked(x + i as u16, y);
            self.cells[idx] = Cell::CONTINUATION;
        }
        self.mark_dirty_span(y, span_start, span_end);
        self.cleanup_orphaned_tails(x.saturating_add(width as u16), y);
    }

    /// Set the cell at (x, y) without scissor or opacity processing.
    ///
    /// This is faster but bypasses clipping and transparency.
    ///
    /// Unlike [`set`](Self::set), this does not automatically write
    /// continuation cells for multi-width content; callers that build wide
    /// glyphs manually must still populate the tail cells themselves. For
    /// single-width and continuation writes, it still preserves
    /// overlap/orphan-tail cleanup so stale continuation cells are not left
    /// behind. Raw wide-head writes remain strictly local so callers can
    /// manage continuation ownership explicitly.
    /// Does nothing if coordinates are out of bounds.
    #[inline]
    pub fn set_raw(&mut self, x: u16, y: u16, cell: Cell) {
        if let Some(idx) = self.index(x, y) {
            let mut span = DirtySpan::new(x, x.saturating_add(1));
            let raw_wide_head = cell.content.width() > 1 && !cell.is_continuation();

            if !raw_wide_head && let Some(cleanup_span) = self.cleanup_overlap(x, y, &cell) {
                span = DirtySpan::new(span.x0.min(cleanup_span.x0), span.x1.max(cleanup_span.x1));
            }
            self.cells[idx] = cell;
            self.mark_dirty_span(y, span.x0, span.x1);
            if !raw_wide_head {
                self.cleanup_orphaned_tails(x.saturating_add(1), y);
            }
        }
    }

    /// Fill a rectangular region with the given cell.
    ///
    /// Respects scissor region and applies opacity.
    #[inline]
    pub fn fill(&mut self, rect: Rect, cell: Cell) {
        let clipped = self.current_scissor().intersection(&rect);
        if clipped.is_empty() {
            return;
        }

        // Fast path: full-row fill with an opaque, single-width cell and no opacity.
        // Safe because every cell in the row is overwritten, and no blending is required.
        let cell_width = cell.content.width();
        if cell_width <= 1
            && !cell.is_continuation()
            && self.current_opacity() >= 1.0
            && cell.bg.a() == 255
            && clipped.x == 0
            && clipped.width == self.width
        {
            let row_width = self.width as usize;
            for y in clipped.y..clipped.bottom() {
                let row_start = y as usize * row_width;
                let row_end = row_start + row_width;
                self.cells[row_start..row_end].fill(cell);
                self.mark_dirty_row_full(y);
            }
            return;
        }

        // Medium path: partial-width fill with opaque, single-width cell, base scissor/opacity.
        // Direct slice::fill per row instead of per-cell set(). We only need to handle
        // wide-char fragments at the fill boundaries (interior cells are fully overwritten).
        if cell_width <= 1
            && !cell.is_continuation()
            && self.current_opacity() >= 1.0
            && cell.bg.a() == 255
            && self.scissor_stack.len() == 1
        {
            let row_width = self.width as usize;
            let x_start = clipped.x as usize;
            let x_end = clipped.right() as usize;
            for y in clipped.y..clipped.bottom() {
                let row_start = y as usize * row_width;
                let mut dirty_left = clipped.x;
                let mut dirty_right = clipped.right();

                // Left boundary: if first fill cell is a continuation, its wide-char
                // head is outside the fill region and would be orphaned. Clear it.
                if x_start > 0 && self.cells[row_start + x_start].is_continuation() {
                    let mut head_found = None;
                    for hx in (0..x_start).rev() {
                        if !self.cells[row_start + hx].is_continuation() {
                            head_found = Some(hx);
                            break;
                        }
                    }

                    if let Some(hx) = head_found {
                        let c = self.cells[row_start + hx];
                        let width = c.content.width();
                        // Only clear if the head actually overlaps the fill region.
                        if width > 1 && hx + width > x_start {
                            // Clear the head and any tails before x_start.
                            // Tails from x_start onwards will be overwritten by the fill.
                            for cx in hx..x_start {
                                self.cells[row_start + cx] = Cell::default();
                            }
                            dirty_left = hx as u16;
                        }
                    }
                }

                // Right boundary: clear orphaned continuations past the fill whose
                // head is being overwritten.
                {
                    let mut cx = x_end;
                    while cx < row_width && self.cells[row_start + cx].is_continuation() {
                        self.cells[row_start + cx] = Cell::default();
                        dirty_right = (cx as u16).saturating_add(1);
                        cx += 1;
                    }
                }

                self.cells[row_start + x_start..row_start + x_end].fill(cell);
                self.mark_dirty_span(y, dirty_left, dirty_right);
            }
            return;
        }

        // Enforce strict bounds for wide characters to prevent spilling.
        self.push_scissor(clipped);

        let step = cell.content.width().max(1) as u16;
        for y in clipped.y..clipped.bottom() {
            let mut x = clipped.x;
            while x < clipped.right() {
                self.set(x, y, cell);
                x = x.saturating_add(step);
            }
        }

        self.pop_scissor();
    }

    /// Clear all cells to the default.
    #[inline]
    pub fn clear(&mut self) {
        self.cells.fill(Cell::default());
        self.mark_all_dirty();
    }

    /// Reset per-frame state and clear all cells.
    ///
    /// This restores scissor/opacity stacks to their base values to ensure
    /// each frame starts from a clean rendering state.
    pub fn reset_for_frame(&mut self) {
        self.scissor_stack.truncate(1);
        if let Some(base) = self.scissor_stack.first_mut() {
            *base = Rect::from_size(self.width, self.height);
        } else {
            self.scissor_stack
                .push(Rect::from_size(self.width, self.height));
        }

        self.opacity_stack.truncate(1);
        if let Some(base) = self.opacity_stack.first_mut() {
            *base = 1.0;
        } else {
            self.opacity_stack.push(1.0);
        }

        self.clear();
    }

    /// Clear all cells to the given cell.
    #[inline]
    pub fn clear_with(&mut self, cell: Cell) {
        if cell.is_continuation() {
            self.clear();
            return;
        }

        let width = cell.content.width();
        if width <= 1 {
            self.cells.fill(cell);
            self.mark_all_dirty();
            return;
        }

        self.cells.fill(Cell::default());
        let step = width as u16;
        for y in 0..self.height {
            let row_start = y as usize * self.width as usize;
            let mut x = 0u16;
            while x.saturating_add(step) <= self.width {
                let head_idx = row_start + x as usize;
                self.cells[head_idx] = cell;
                for off in 1..step {
                    self.cells[head_idx + off as usize] = Cell::CONTINUATION;
                }
                x = x.saturating_add(step);
            }
        }
        self.mark_all_dirty();
    }

    /// Get raw access to the cell slice.
    ///
    /// This is useful for diffing against another buffer.
    #[inline]
    pub fn cells(&self) -> &[Cell] {
        &self.cells
    }

    /// Get mutable raw access to the cell slice.
    ///
    /// Marks all rows dirty since caller may modify arbitrary cells.
    #[inline]
    pub fn cells_mut(&mut self) -> &mut [Cell] {
        self.mark_all_dirty();
        &mut self.cells
    }

    /// Get the cells for a single row as a slice.
    ///
    /// # Panics
    ///
    /// Panics if `y >= height`.
    #[inline]
    pub fn row_cells(&self, y: u16) -> &[Cell] {
        let start = y as usize * self.width as usize;
        &self.cells[start..start + self.width as usize]
    }

    /// Get mutable cells for a contiguous span on a row.
    ///
    /// The requested range is treated as half-open `[x0, x1)` and clamped to
    /// the buffer width. The span is marked dirty once before returning the
    /// mutable slice.
    ///
    /// This is a raw bulk-mutation helper: callers must already have applied
    /// any required scissor/opacity clipping and must not use it for writes
    /// that can change cell-content width invariants.
    #[inline]
    pub fn row_cells_mut_span(&mut self, y: u16, x0: u16, x1: u16) -> Option<&mut [Cell]> {
        if y >= self.height {
            return None;
        }
        if x0 >= x1 {
            return None;
        }

        let start = x0.min(self.width);
        let end = x1.min(self.width);
        if start >= end {
            return None;
        }

        self.mark_dirty_span(y, start, end);

        let row_start = y as usize * self.width as usize;
        let slice_start = row_start + start as usize;
        let slice_end = row_start + end as usize;
        Some(&mut self.cells[slice_start..slice_end])
    }

    // ========== Scissor Stack ==========

    /// Push a scissor (clipping) region onto the stack.
    ///
    /// The effective scissor is the intersection of all pushed rects.
    /// If the intersection is empty, no cells will be drawn.
    #[inline]
    pub fn push_scissor(&mut self, rect: Rect) {
        let current = self.current_scissor();
        let intersected = current.intersection(&rect);
        self.scissor_stack.push(intersected);
    }

    /// Pop a scissor region from the stack.
    ///
    /// Does nothing if only the base scissor remains.
    #[inline]
    pub fn pop_scissor(&mut self) {
        if self.scissor_stack.len() > 1 {
            self.scissor_stack.pop();
        }
    }

    /// Get the current effective scissor region.
    #[inline]
    pub fn current_scissor(&self) -> Rect {
        *self
            .scissor_stack
            .last()
            .expect("scissor stack always has at least one element")
    }

    /// Get the scissor stack depth.
    #[inline]
    pub fn scissor_depth(&self) -> usize {
        self.scissor_stack.len()
    }

    // ========== Opacity Stack ==========

    /// Push an opacity multiplier onto the stack.
    ///
    /// The effective opacity is the product of all pushed values.
    /// Values are clamped to `[0.0, 1.0]`.
    #[inline]
    pub fn push_opacity(&mut self, opacity: f32) {
        let clamped = opacity.clamp(0.0, 1.0);
        let current = self.current_opacity();
        self.opacity_stack.push(current * clamped);
    }

    /// Pop an opacity value from the stack.
    ///
    /// Does nothing if only the base opacity remains.
    #[inline]
    pub fn pop_opacity(&mut self) {
        if self.opacity_stack.len() > 1 {
            self.opacity_stack.pop();
        }
    }

    /// Get the current effective opacity.
    #[inline]
    pub fn current_opacity(&self) -> f32 {
        *self
            .opacity_stack
            .last()
            .expect("opacity stack always has at least one element")
    }

    /// Get the opacity stack depth.
    #[inline]
    pub fn opacity_depth(&self) -> usize {
        self.opacity_stack.len()
    }

    // ========== Copying and Diffing ==========

    /// Copy a rectangular region from another buffer.
    ///
    /// Copies cells from `src` at `src_rect` to this buffer at `dst_pos`.
    /// Respects scissor region.
    pub fn copy_from(&mut self, src: &Buffer, src_rect: Rect, dst_x: u16, dst_y: u16) {
        // Enforce strict bounds on the destination area to prevent wide characters
        // from leaking outside the requested copy region.
        let copy_bounds = Rect::new(dst_x, dst_y, src_rect.width, src_rect.height);
        self.push_scissor(copy_bounds);
        let clip = self.current_scissor();

        for dy in 0..src_rect.height {
            // Compute destination y with overflow check
            let Some(target_y) = dst_y.checked_add(dy) else {
                continue;
            };
            let Some(sy) = src_rect.y.checked_add(dy) else {
                continue;
            };

            let mut dx = 0u16;
            while dx < src_rect.width {
                // Compute coordinates with overflow checks
                let Some(target_x) = dst_x.checked_add(dx) else {
                    dx = dx.saturating_add(1);
                    continue;
                };
                let Some(sx) = src_rect.x.checked_add(dx) else {
                    dx = dx.saturating_add(1);
                    continue;
                };

                if let Some(cell) = src.get(sx, sy) {
                    // Continuation cells without their head should not be copied.
                    // Heads are handled separately and skip over tails, so any
                    // continuation we see here is orphaned by the copy region.
                    if cell.is_continuation() {
                        self.set(target_x, target_y, Cell::default());
                        dx = dx.saturating_add(1);
                        continue;
                    }

                    let width = cell.content.width();
                    let target_right = target_x.saturating_add(width as u16);

                    // Check for clipping.
                    // 1. Source clipping: tail extends beyond the source copy region.
                    // 2. Destination clipping: tail extends beyond the effective scissor.
                    let src_clipped = width > 1 && dx.saturating_add(width as u16) > src_rect.width;
                    let dst_clipped = target_right > clip.right();

                    if src_clipped || dst_clipped {
                        // Write default cells to all valid positions in the span to ensure
                        // previous content is cleared. `set` is atomic for wide chars,
                        // so we must write single-width default cells individually.
                        let valid_width = (clip.right().saturating_sub(target_x)).min(width as u16);
                        for i in 0..valid_width {
                            self.set(target_x + i, target_y, Cell::default());
                        }
                    } else {
                        self.set(target_x, target_y, *cell);
                    }

                    // Skip tails in source iteration.
                    if width > 1 {
                        dx = dx.saturating_add(width as u16);
                    } else {
                        dx = dx.saturating_add(1);
                    }
                } else {
                    dx = dx.saturating_add(1);
                }
            }
        }

        self.pop_scissor();
    }

    /// Check if two buffers have identical content.
    pub fn content_eq(&self, other: &Buffer) -> bool {
        self.width == other.width && self.height == other.height && self.cells == other.cells
    }
}

impl Default for Buffer {
    /// Create a 1x1 buffer (minimum size).
    fn default() -> Self {
        Self::new(1, 1)
    }
}

impl PartialEq for Buffer {
    fn eq(&self, other: &Self) -> bool {
        self.content_eq(other)
    }
}

impl Eq for Buffer {}

// ---------------------------------------------------------------------------
// DoubleBuffer: O(1) frame swap (bd-1rz0.4.4)
// ---------------------------------------------------------------------------

/// Double-buffered render target with O(1) swap.
///
/// Maintains two pre-allocated buffers and swaps between them by flipping an
/// index, avoiding the O(width × height) clone that a naive prev/current
/// pattern requires.
///
/// # Invariants
///
/// 1. Both buffers always have the same dimensions.
/// 2. `swap()` is O(1) — it only flips the index, never copies cells.
/// 3. After `swap()`, `current_mut().clear()` should be called to prepare
///    the new frame buffer.
/// 4. `resize()` discards both buffers and returns `true` so callers know
///    a full redraw is needed.
#[derive(Debug)]
pub struct DoubleBuffer {
    buffers: [Buffer; 2],
    /// Index of the *current* buffer (0 or 1).
    current_idx: u8,
}

// ---------------------------------------------------------------------------
// AdaptiveDoubleBuffer: Allocation-efficient resize (bd-1rz0.4.2)
// ---------------------------------------------------------------------------

/// Over-allocation factor for growth headroom (1.25x = 25% extra capacity).
const ADAPTIVE_GROWTH_FACTOR: f32 = 1.25;

/// Shrink threshold: only reallocate if new size < this fraction of capacity.
/// This prevents thrashing at size boundaries.
const ADAPTIVE_SHRINK_THRESHOLD: f32 = 0.50;

/// Maximum over-allocation per dimension (prevent excessive memory usage).
const ADAPTIVE_MAX_OVERAGE: u16 = 200;

/// Adaptive double-buffered render target with allocation efficiency.
///
/// Wraps `DoubleBuffer` with capacity tracking to minimize allocations during
/// resize storms. Key strategies:
///
/// 1. **Over-allocation headroom**: Allocate slightly more than needed to handle
///    minor size increases without reallocation.
/// 2. **Shrink threshold**: Only shrink if new size is significantly smaller
///    than allocated capacity (prevents thrashing at size boundaries).
/// 3. **Logical vs physical dimensions**: Track both the current view size
///    and the allocated capacity separately.
///
/// # Invariants
///
/// 1. `capacity_width >= logical_width` and `capacity_height >= logical_height`
/// 2. Logical dimensions represent the actual usable area for rendering.
/// 3. Physical capacity may exceed logical dimensions by up to `ADAPTIVE_GROWTH_FACTOR`.
/// 4. Shrink only occurs when logical size drops below `ADAPTIVE_SHRINK_THRESHOLD * capacity`.
///
/// # Failure Modes
///
/// | Condition | Behavior | Rationale |
/// |-----------|----------|-----------|
/// | Capacity overflow | Clamp to u16::MAX | Prevents panic on extreme sizes |
/// | Zero dimensions | Delegate to DoubleBuffer (panic) | Invalid state |
///
/// # Performance
///
/// - `resize()` is O(1) when the new size fits within capacity.
/// - `resize()` is O(width × height) when reallocation is required.
/// - Target: < 5% allocation overhead during resize storms.
#[derive(Debug)]
pub struct AdaptiveDoubleBuffer {
    /// The underlying double buffer (may have larger capacity than logical size).
    inner: DoubleBuffer,
    /// Logical width (the usable rendering area).
    logical_width: u16,
    /// Logical height (the usable rendering area).
    logical_height: u16,
    /// Allocated capacity width (>= logical_width).
    capacity_width: u16,
    /// Allocated capacity height (>= logical_height).
    capacity_height: u16,
    /// Statistics for observability.
    stats: AdaptiveStats,
}

/// Statistics for adaptive buffer allocation.
#[derive(Debug, Clone, Default)]
pub struct AdaptiveStats {
    /// Number of resize calls that avoided reallocation.
    pub resize_avoided: u64,
    /// Number of resize calls that required reallocation.
    pub resize_reallocated: u64,
    /// Number of resize calls for growth.
    pub resize_growth: u64,
    /// Number of resize calls for shrink.
    pub resize_shrink: u64,
}

impl AdaptiveStats {
    /// Reset statistics to zero.
    pub fn reset(&mut self) {
        *self = Self::default();
    }

    /// Calculate the reallocation avoidance ratio (higher is better).
    pub fn avoidance_ratio(&self) -> f64 {
        let total = self.resize_avoided + self.resize_reallocated;
        if total == 0 {
            1.0
        } else {
            self.resize_avoided as f64 / total as f64
        }
    }
}

impl DoubleBuffer {
    /// Create a double buffer with the given dimensions.
    ///
    /// Both buffers are initialized to default (empty) cells.
    /// Dimensions are clamped to a minimum of 1x1.
    pub fn new(width: u16, height: u16) -> Self {
        Self {
            buffers: [Buffer::new(width, height), Buffer::new(width, height)],
            current_idx: 0,
        }
    }

    /// O(1) swap: the current buffer becomes previous, and vice versa.
    ///
    /// After swapping, call `current_mut().clear()` to prepare for the
    /// next frame.
    #[inline]
    pub fn swap(&mut self) {
        self.current_idx = 1 - self.current_idx;
    }

    /// Reference to the current (in-progress) frame buffer.
    #[inline]
    pub fn current(&self) -> &Buffer {
        &self.buffers[self.current_idx as usize]
    }

    /// Mutable reference to the current (in-progress) frame buffer.
    #[inline]
    pub fn current_mut(&mut self) -> &mut Buffer {
        &mut self.buffers[self.current_idx as usize]
    }

    /// Reference to the previous (last-presented) frame buffer.
    #[inline]
    pub fn previous(&self) -> &Buffer {
        &self.buffers[(1 - self.current_idx) as usize]
    }

    /// Mutable reference to the previous (last-presented) frame buffer.
    #[inline]
    pub fn previous_mut(&mut self) -> &mut Buffer {
        &mut self.buffers[(1 - self.current_idx) as usize]
    }

    /// Width of both buffers.
    #[inline]
    pub fn width(&self) -> u16 {
        self.buffers[0].width()
    }

    /// Height of both buffers.
    #[inline]
    pub fn height(&self) -> u16 {
        self.buffers[0].height()
    }

    /// Resize both buffers. Returns `true` if dimensions actually changed.
    ///
    /// Both buffers are replaced with fresh allocations and the index is
    /// reset. Callers should force a full redraw when this returns `true`.
    pub fn resize(&mut self, width: u16, height: u16) -> bool {
        if self.buffers[0].width() == width && self.buffers[0].height() == height {
            return false;
        }
        self.buffers = [Buffer::new(width, height), Buffer::new(width, height)];
        self.current_idx = 0;
        true
    }

    /// Check whether both buffers have the given dimensions.
    #[inline]
    pub fn dimensions_match(&self, width: u16, height: u16) -> bool {
        self.buffers[0].width() == width && self.buffers[0].height() == height
    }
}

// ---------------------------------------------------------------------------
// AdaptiveDoubleBuffer implementation (bd-1rz0.4.2)
// ---------------------------------------------------------------------------

impl AdaptiveDoubleBuffer {
    /// Create a new adaptive buffer with the given logical dimensions.
    ///
    /// Initial capacity is set with growth headroom applied.
    /// Dimensions are clamped to a minimum of 1x1.
    pub fn new(width: u16, height: u16) -> Self {
        let (cap_w, cap_h) = Self::compute_capacity(width, height);
        Self {
            inner: DoubleBuffer::new(cap_w, cap_h),
            logical_width: width,
            logical_height: height,
            capacity_width: cap_w,
            capacity_height: cap_h,
            stats: AdaptiveStats::default(),
        }
    }

    /// Compute the capacity for a given logical size.
    ///
    /// Applies growth factor with clamping to prevent overflow.
    fn compute_capacity(width: u16, height: u16) -> (u16, u16) {
        let extra_w =
            ((width as f32 * (ADAPTIVE_GROWTH_FACTOR - 1.0)) as u16).min(ADAPTIVE_MAX_OVERAGE);
        let extra_h =
            ((height as f32 * (ADAPTIVE_GROWTH_FACTOR - 1.0)) as u16).min(ADAPTIVE_MAX_OVERAGE);

        let cap_w = width.saturating_add(extra_w);
        let cap_h = height.saturating_add(extra_h);

        (cap_w, cap_h)
    }

    /// Check if the new dimensions require reallocation.
    ///
    /// Returns `true` if reallocation is needed, `false` if current capacity suffices.
    fn needs_reallocation(&self, width: u16, height: u16) -> bool {
        // Growth beyond capacity always requires reallocation
        if width > self.capacity_width || height > self.capacity_height {
            return true;
        }

        // Shrink threshold: reallocate if new size is significantly smaller
        let shrink_threshold_w = (self.capacity_width as f32 * ADAPTIVE_SHRINK_THRESHOLD) as u16;
        let shrink_threshold_h = (self.capacity_height as f32 * ADAPTIVE_SHRINK_THRESHOLD) as u16;

        width < shrink_threshold_w || height < shrink_threshold_h
    }

    /// O(1) swap: the current buffer becomes previous, and vice versa.
    ///
    /// After swapping, call `current_mut().clear()` to prepare for the
    /// next frame.
    #[inline]
    pub fn swap(&mut self) {
        self.inner.swap();
    }

    /// Reference to the current (in-progress) frame buffer.
    ///
    /// Note: The buffer may have larger dimensions than the logical size.
    /// Use `logical_width()` and `logical_height()` for rendering bounds.
    #[inline]
    pub fn current(&self) -> &Buffer {
        self.inner.current()
    }

    /// Mutable reference to the current (in-progress) frame buffer.
    #[inline]
    pub fn current_mut(&mut self) -> &mut Buffer {
        self.inner.current_mut()
    }

    /// Reference to the previous (last-presented) frame buffer.
    #[inline]
    pub fn previous(&self) -> &Buffer {
        self.inner.previous()
    }

    /// Logical width (the usable rendering area).
    #[inline]
    pub fn width(&self) -> u16 {
        self.logical_width
    }

    /// Logical height (the usable rendering area).
    #[inline]
    pub fn height(&self) -> u16 {
        self.logical_height
    }

    /// Allocated capacity width (may be larger than logical width).
    #[inline]
    pub fn capacity_width(&self) -> u16 {
        self.capacity_width
    }

    /// Allocated capacity height (may be larger than logical height).
    #[inline]
    pub fn capacity_height(&self) -> u16 {
        self.capacity_height
    }

    /// Get allocation statistics.
    #[inline]
    pub fn stats(&self) -> &AdaptiveStats {
        &self.stats
    }

    /// Reset allocation statistics.
    pub fn reset_stats(&mut self) {
        self.stats.reset();
    }

    /// Resize the logical dimensions. Returns `true` if dimensions changed.
    ///
    /// This method minimizes allocations by:
    /// 1. Reusing existing capacity when the new size fits.
    /// 2. Only reallocating on significant shrink (below threshold).
    /// 3. Applying growth headroom to avoid immediate reallocation on growth.
    ///
    /// # Performance
    ///
    /// - O(1) when new size fits within existing capacity.
    /// - O(width × height) when reallocation is required.
    pub fn resize(&mut self, width: u16, height: u16) -> bool {
        // No change in logical dimensions
        if width == self.logical_width && height == self.logical_height {
            return false;
        }

        let is_growth = width > self.logical_width || height > self.logical_height;
        if is_growth {
            self.stats.resize_growth += 1;
        } else {
            self.stats.resize_shrink += 1;
        }

        if self.needs_reallocation(width, height) {
            // Reallocate with new capacity
            let (cap_w, cap_h) = Self::compute_capacity(width, height);
            self.inner = DoubleBuffer::new(cap_w, cap_h);
            self.capacity_width = cap_w;
            self.capacity_height = cap_h;
            self.stats.resize_reallocated += 1;
        } else {
            // Reuse existing capacity - just update logical dimensions
            // Clear both buffers to avoid stale content outside new bounds
            self.inner.current_mut().clear();
            self.inner.previous_mut().clear();
            self.stats.resize_avoided += 1;
        }

        self.logical_width = width;
        self.logical_height = height;
        true
    }

    /// Check whether logical dimensions match the given values.
    #[inline]
    pub fn dimensions_match(&self, width: u16, height: u16) -> bool {
        self.logical_width == width && self.logical_height == height
    }

    /// Get the logical bounding rect (for scissoring/rendering).
    #[inline]
    pub fn logical_bounds(&self) -> Rect {
        Rect::from_size(self.logical_width, self.logical_height)
    }

    /// Calculate memory efficiency (logical cells / capacity cells).
    pub fn memory_efficiency(&self) -> f64 {
        let logical = self.logical_width as u64 * self.logical_height as u64;
        let capacity = self.capacity_width as u64 * self.capacity_height as u64;
        if capacity == 0 {
            1.0
        } else {
            logical as f64 / capacity as f64
        }
    }
}

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

    #[test]
    fn set_composites_background() {
        let mut buf = Buffer::new(1, 1);

        // Set background to RED
        let red = PackedRgba::rgb(255, 0, 0);
        buf.set(0, 0, Cell::default().with_bg(red));

        // Write 'X' with transparent background
        let cell = Cell::from_char('X'); // Default bg is TRANSPARENT
        buf.set(0, 0, cell);

        let result = buf.get(0, 0).unwrap();
        assert_eq!(result.content.as_char(), Some('X'));
        assert_eq!(
            result.bg, red,
            "Background should be preserved (composited)"
        );
    }

    #[test]
    fn set_fast_matches_set_for_transparent_bg() {
        let red = PackedRgba::rgb(255, 0, 0);
        let cell = Cell::from_char('X').with_fg(PackedRgba::rgb(0, 255, 0));

        let mut a = Buffer::new(1, 1);
        a.set(0, 0, Cell::default().with_bg(red));
        a.set(0, 0, cell);

        let mut b = Buffer::new(1, 1);
        b.set(0, 0, Cell::default().with_bg(red));
        b.set_fast(0, 0, cell);

        assert_eq!(a.get(0, 0), b.get(0, 0));
    }

    #[test]
    fn set_fast_matches_set_for_opaque_bg() {
        let cell = Cell::from_char('X')
            .with_fg(PackedRgba::rgb(0, 255, 0))
            .with_bg(PackedRgba::rgb(255, 0, 0));

        let mut a = Buffer::new(1, 1);
        a.set(0, 0, cell);

        let mut b = Buffer::new(1, 1);
        b.set_fast(0, 0, cell);

        assert_eq!(a.get(0, 0), b.get(0, 0));
    }

    #[test]
    fn set_fast_clears_orphaned_tail_like_set() {
        let mut slow = Buffer::new(3, 1);
        slow.set_raw(0, 0, Cell::from_char('A'));
        slow.set_raw(1, 0, Cell::CONTINUATION);
        slow.clear_dirty();

        let mut fast = slow.clone();

        slow.set(0, 0, Cell::from_char('X'));
        fast.set_fast(0, 0, Cell::from_char('X'));

        assert_eq!(slow.cells(), fast.cells());
        assert_eq!(fast.get(1, 0), Some(&Cell::default()));

        let spans = fast.dirty_span_row(0).expect("dirty span row").spans();
        assert_eq!(spans, &[DirtySpan::new(0, 2)]);
    }

    #[test]
    fn rect_contains() {
        let r = Rect::new(5, 5, 10, 10);
        assert!(r.contains(5, 5)); // Top-left corner
        assert!(r.contains(14, 14)); // Bottom-right inside
        assert!(!r.contains(4, 5)); // Left of rect
        assert!(!r.contains(15, 5)); // Right of rect (exclusive)
        assert!(!r.contains(5, 15)); // Below rect (exclusive)
    }

    #[test]
    fn rect_intersection() {
        let a = Rect::new(0, 0, 10, 10);
        let b = Rect::new(5, 5, 10, 10);
        let i = a.intersection(&b);
        assert_eq!(i, Rect::new(5, 5, 5, 5));

        // Non-overlapping
        let c = Rect::new(20, 20, 5, 5);
        assert_eq!(a.intersection(&c), Rect::default());
    }

    #[test]
    fn buffer_creation() {
        let buf = Buffer::new(80, 24);
        assert_eq!(buf.width(), 80);
        assert_eq!(buf.height(), 24);
        assert_eq!(buf.len(), 80 * 24);
    }

    #[test]
    fn content_height_empty_is_zero() {
        let buf = Buffer::new(8, 4);
        assert_eq!(buf.content_height(), 0);
    }

    #[test]
    fn content_height_tracks_last_non_empty_row() {
        let mut buf = Buffer::new(5, 4);
        buf.set(0, 0, Cell::from_char('A'));
        assert_eq!(buf.content_height(), 1);

        buf.set(2, 3, Cell::from_char('Z'));
        assert_eq!(buf.content_height(), 4);
    }

    #[test]
    fn buffer_zero_width_clamped_to_one() {
        let buf = Buffer::new(0, 24);
        assert_eq!(buf.width(), 1);
        assert_eq!(buf.height(), 24);
    }

    #[test]
    fn buffer_zero_height_clamped_to_one() {
        let buf = Buffer::new(80, 0);
        assert_eq!(buf.width(), 80);
        assert_eq!(buf.height(), 1);
    }

    #[test]
    fn buffer_get_and_set() {
        let mut buf = Buffer::new(10, 10);
        let cell = Cell::from_char('X');
        buf.set(5, 5, cell);
        assert_eq!(buf.get(5, 5).unwrap().content.as_char(), Some('X'));
    }

    #[test]
    fn buffer_out_of_bounds_get() {
        let buf = Buffer::new(10, 10);
        assert!(buf.get(10, 0).is_none());
        assert!(buf.get(0, 10).is_none());
        assert!(buf.get(100, 100).is_none());
    }

    #[test]
    fn buffer_out_of_bounds_set_ignored() {
        let mut buf = Buffer::new(10, 10);
        buf.set(100, 100, Cell::from_char('X')); // Should not panic
        assert_eq!(buf.cells().iter().filter(|c| !c.is_empty()).count(), 0);
    }

    #[test]
    fn buffer_clear() {
        let mut buf = Buffer::new(10, 10);
        buf.set(5, 5, Cell::from_char('X'));
        buf.clear();
        assert!(buf.get(5, 5).unwrap().is_empty());
    }

    #[test]
    fn scissor_stack_basic() {
        let mut buf = Buffer::new(20, 20);

        // Default scissor covers entire buffer
        assert_eq!(buf.current_scissor(), Rect::from_size(20, 20));
        assert_eq!(buf.scissor_depth(), 1);

        // Push smaller scissor
        buf.push_scissor(Rect::new(5, 5, 10, 10));
        assert_eq!(buf.current_scissor(), Rect::new(5, 5, 10, 10));
        assert_eq!(buf.scissor_depth(), 2);

        // Set inside scissor works
        buf.set(7, 7, Cell::from_char('I'));
        assert_eq!(buf.get(7, 7).unwrap().content.as_char(), Some('I'));

        // Set outside scissor is ignored
        buf.set(0, 0, Cell::from_char('O'));
        assert!(buf.get(0, 0).unwrap().is_empty());

        // Pop scissor
        buf.pop_scissor();
        assert_eq!(buf.current_scissor(), Rect::from_size(20, 20));
        assert_eq!(buf.scissor_depth(), 1);

        // Now can set at (0, 0)
        buf.set(0, 0, Cell::from_char('N'));
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('N'));
    }

    #[test]
    fn scissor_intersection() {
        let mut buf = Buffer::new(20, 20);
        buf.push_scissor(Rect::new(5, 5, 10, 10));
        buf.push_scissor(Rect::new(8, 8, 10, 10));

        // Intersection: (8,8) to (15,15) intersected with (5,5) to (15,15)
        // Result: (8,8) to (15,15) -> width=7, height=7
        assert_eq!(buf.current_scissor(), Rect::new(8, 8, 7, 7));
    }

    #[test]
    fn scissor_base_cannot_be_popped() {
        let mut buf = Buffer::new(10, 10);
        buf.pop_scissor(); // Should be a no-op
        assert_eq!(buf.scissor_depth(), 1);
        buf.pop_scissor(); // Still no-op
        assert_eq!(buf.scissor_depth(), 1);
    }

    #[test]
    fn opacity_stack_basic() {
        let mut buf = Buffer::new(10, 10);

        // Default opacity is 1.0
        assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
        assert_eq!(buf.opacity_depth(), 1);

        // Push 0.5 opacity
        buf.push_opacity(0.5);
        assert!((buf.current_opacity() - 0.5).abs() < f32::EPSILON);
        assert_eq!(buf.opacity_depth(), 2);

        // Push another 0.5 -> effective 0.25
        buf.push_opacity(0.5);
        assert!((buf.current_opacity() - 0.25).abs() < f32::EPSILON);
        assert_eq!(buf.opacity_depth(), 3);

        // Pop back to 0.5
        buf.pop_opacity();
        assert!((buf.current_opacity() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn opacity_applied_to_cells() {
        let mut buf = Buffer::new(10, 10);
        buf.push_opacity(0.5);

        let cell = Cell::from_char('X').with_fg(PackedRgba::rgba(100, 100, 100, 255));
        buf.set(5, 5, cell);

        let stored = buf.get(5, 5).unwrap();
        // Alpha should be reduced by 0.5
        assert_eq!(stored.fg.a(), 128);
    }

    #[test]
    fn opacity_composites_background_before_storage() {
        let mut buf = Buffer::new(1, 1);

        let red = PackedRgba::rgb(255, 0, 0);
        let blue = PackedRgba::rgb(0, 0, 255);

        buf.set(0, 0, Cell::default().with_bg(red));
        buf.push_opacity(0.5);
        buf.set(0, 0, Cell::default().with_bg(blue));

        let stored = buf.get(0, 0).unwrap();
        let expected = blue.with_opacity(0.5).over(red);
        assert_eq!(stored.bg, expected);
    }

    #[test]
    fn opacity_clamped() {
        let mut buf = Buffer::new(10, 10);
        buf.push_opacity(2.0); // Should clamp to 1.0
        assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);

        buf.push_opacity(-1.0); // Should clamp to 0.0
        assert!((buf.current_opacity() - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn opacity_base_cannot_be_popped() {
        let mut buf = Buffer::new(10, 10);
        buf.pop_opacity(); // No-op
        assert_eq!(buf.opacity_depth(), 1);
    }

    #[test]
    fn buffer_fill() {
        let mut buf = Buffer::new(10, 10);
        let cell = Cell::from_char('#');
        buf.fill(Rect::new(2, 2, 5, 5), cell);

        // Inside fill region
        assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('#'));

        // Outside fill region
        assert!(buf.get(0, 0).unwrap().is_empty());
    }

    #[test]
    fn buffer_fill_respects_scissor() {
        let mut buf = Buffer::new(10, 10);
        buf.push_scissor(Rect::new(3, 3, 4, 4));

        let cell = Cell::from_char('#');
        buf.fill(Rect::new(0, 0, 10, 10), cell);

        // Only scissor region should be filled
        assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('#'));
        assert!(buf.get(0, 0).unwrap().is_empty());
        assert!(buf.get(7, 7).unwrap().is_empty());
    }

    #[test]
    fn buffer_copy_from() {
        let mut src = Buffer::new(10, 10);
        src.set(2, 2, Cell::from_char('S'));

        let mut dst = Buffer::new(10, 10);
        dst.copy_from(&src, Rect::new(0, 0, 5, 5), 3, 3);

        // Cell at (2,2) in src should be at (5,5) in dst (offset by 3,3)
        assert_eq!(dst.get(5, 5).unwrap().content.as_char(), Some('S'));
    }

    #[test]
    fn copy_from_clips_wide_char_at_boundary() {
        let mut src = Buffer::new(10, 1);
        // Wide char at x=0 (width 2)
        src.set(0, 0, Cell::from_char('中'));

        let mut dst = Buffer::new(10, 1);
        // Copy only the first column (x=0, width=1) from src to dst at (0,0)
        // This includes the head of '中' but EXCLUDES the tail.
        dst.copy_from(&src, Rect::new(0, 0, 1, 1), 0, 0);

        // The copy should be atomic: since the tail doesn't fit in the copy region,
        // the head should NOT be written (or at least the tail should not be written outside the region).

        // Check x=0: Should be empty (atomic rejection) or clipped?
        // With implicit scissor fix: atomic rejection means x=0 is empty.
        // Without fix: x=0 is '中', x=1 is CONTINUATION (leak).

        // Asserting the fix behavior (atomic rejection):
        assert!(
            dst.get(0, 0).unwrap().is_empty(),
            "Wide char head should not be written if tail is clipped"
        );
        assert!(
            dst.get(1, 0).unwrap().is_empty(),
            "Wide char tail should not be leaked outside copy region"
        );
    }

    #[test]
    fn buffer_content_eq() {
        let mut buf1 = Buffer::new(10, 10);
        let mut buf2 = Buffer::new(10, 10);

        assert!(buf1.content_eq(&buf2));

        buf1.set(0, 0, Cell::from_char('X'));
        assert!(!buf1.content_eq(&buf2));

        buf2.set(0, 0, Cell::from_char('X'));
        assert!(buf1.content_eq(&buf2));
    }

    #[test]
    fn buffer_bounds() {
        let buf = Buffer::new(80, 24);
        let bounds = buf.bounds();
        assert_eq!(bounds.x, 0);
        assert_eq!(bounds.y, 0);
        assert_eq!(bounds.width, 80);
        assert_eq!(bounds.height, 24);
    }

    #[test]
    fn buffer_set_raw_bypasses_scissor() {
        let mut buf = Buffer::new(10, 10);
        buf.push_scissor(Rect::new(5, 5, 5, 5));

        // set() respects scissor - this should be ignored
        buf.set(0, 0, Cell::from_char('S'));
        assert!(buf.get(0, 0).unwrap().is_empty());

        // set_raw() bypasses scissor - this should work
        buf.set_raw(0, 0, Cell::from_char('R'));
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('R'));
    }

    #[test]
    fn set_handles_wide_chars() {
        let mut buf = Buffer::new(10, 10);

        // Set a wide character (width 2)
        buf.set(0, 0, Cell::from_char('中'));

        // Check head
        let head = buf.get(0, 0).unwrap();
        assert_eq!(head.content.as_char(), Some('中'));

        // Check continuation
        let cont = buf.get(1, 0).unwrap();
        assert!(cont.is_continuation());
        assert!(!cont.is_empty());
    }

    #[test]
    fn set_handles_wide_chars_clipped() {
        let mut buf = Buffer::new(10, 10);
        buf.push_scissor(Rect::new(0, 0, 1, 10)); // Only column 0 is visible

        // Set wide char at 0,0. Tail at x=1 is outside scissor.
        // Atomic rejection: entire write is rejected because tail doesn't fit.
        buf.set(0, 0, Cell::from_char('中'));

        // Head should NOT be written (atomic rejection)
        assert!(buf.get(0, 0).unwrap().is_empty());
        // Tail position should also be unmodified
        assert!(buf.get(1, 0).unwrap().is_empty());
    }

    // ========== Wide Glyph Continuation Cleanup Tests ==========

    #[test]
    fn overwrite_wide_head_with_single_clears_tails() {
        let mut buf = Buffer::new(10, 1);

        // Write a wide character (width 2) at position 0
        buf.set(0, 0, Cell::from_char('中'));
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
        assert!(buf.get(1, 0).unwrap().is_continuation());

        // Overwrite the head with a single-width character
        buf.set(0, 0, Cell::from_char('A'));

        // Head should be replaced
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
        // Tail (continuation) should be cleared to default
        assert!(
            buf.get(1, 0).unwrap().is_empty(),
            "Continuation at x=1 should be cleared when head is overwritten"
        );
    }

    #[test]
    fn set_raw_overwrite_wide_head_with_single_clears_tails() {
        let mut buf = Buffer::new(10, 1);

        buf.set(0, 0, Cell::from_char('中'));
        assert!(buf.get(1, 0).unwrap().is_continuation());
        buf.clear_dirty();

        buf.set_raw(0, 0, Cell::from_char('A'));

        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
        assert!(
            buf.get(1, 0).unwrap().is_empty(),
            "set_raw should clear stale continuation tails when overwriting a wide head"
        );
        let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
        assert_eq!(spans, &[DirtySpan::new(0, 2)]);
    }

    #[test]
    fn set_raw_wide_head_preserves_manual_tail_cells() {
        let mut buf = Buffer::new(10, 1);

        buf.set_raw(0, 0, Cell::from_char('中'));
        buf.set_raw(1, 0, Cell::CONTINUATION);
        assert!(buf.get(1, 0).unwrap().is_continuation());
        buf.clear_dirty();

        buf.set_raw(0, 0, Cell::from_char('æ—¥'));

        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('æ—¥'));
        assert!(
            buf.get(1, 0).unwrap().is_continuation(),
            "set_raw wide-head replacement should not clear caller-managed tails"
        );
        let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
        assert_eq!(spans, &[DirtySpan::new(0, 1)]);
    }

    #[test]
    fn overwrite_continuation_with_single_clears_head_and_tails() {
        let mut buf = Buffer::new(10, 1);

        // Write a wide character at position 0
        buf.set(0, 0, Cell::from_char('中'));
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
        assert!(buf.get(1, 0).unwrap().is_continuation());

        // Overwrite the continuation (position 1) with a single-width char
        buf.set(1, 0, Cell::from_char('B'));

        // The head at position 0 should be cleared
        assert!(
            buf.get(0, 0).unwrap().is_empty(),
            "Head at x=0 should be cleared when its continuation is overwritten"
        );
        // Position 1 should have the new character
        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('B'));
    }

    #[test]
    fn overwrite_wide_with_another_wide() {
        let mut buf = Buffer::new(10, 1);

        // Write first wide character
        buf.set(0, 0, Cell::from_char('中'));
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
        assert!(buf.get(1, 0).unwrap().is_continuation());

        // Overwrite with another wide character
        buf.set(0, 0, Cell::from_char('æ—¥'));

        // Should have new wide character
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('æ—¥'));
        assert!(
            buf.get(1, 0).unwrap().is_continuation(),
            "Continuation should still exist for new wide char"
        );
    }

    #[test]
    fn overwrite_continuation_middle_of_wide_sequence() {
        let mut buf = Buffer::new(10, 1);

        // Write two adjacent wide characters: 中 at 0-1, 日 at 2-3
        buf.set(0, 0, Cell::from_char('中'));
        buf.set(2, 0, Cell::from_char('æ—¥'));

        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
        assert!(buf.get(1, 0).unwrap().is_continuation());
        assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('æ—¥'));
        assert!(buf.get(3, 0).unwrap().is_continuation());

        // Overwrite position 1 (continuation of first wide char)
        buf.set(1, 0, Cell::from_char('X'));

        // First wide char's head should be cleared
        assert!(
            buf.get(0, 0).unwrap().is_empty(),
            "Head of first wide char should be cleared"
        );
        // Position 1 has new char
        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('X'));
        // Second wide char should be unaffected
        assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('æ—¥'));
        assert!(buf.get(3, 0).unwrap().is_continuation());
    }

    #[test]
    fn wide_char_overlapping_previous_wide_char() {
        let mut buf = Buffer::new(10, 1);

        // Write wide char at position 0
        buf.set(0, 0, Cell::from_char('中'));
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
        assert!(buf.get(1, 0).unwrap().is_continuation());

        // Write another wide char at position 1 (overlaps with continuation)
        buf.set(1, 0, Cell::from_char('æ—¥'));

        // First wide char's head should be cleared (its continuation was overwritten)
        assert!(
            buf.get(0, 0).unwrap().is_empty(),
            "First wide char head should be cleared when continuation is overwritten by new wide"
        );
        // New wide char at positions 1-2
        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('æ—¥'));
        assert!(buf.get(2, 0).unwrap().is_continuation());
    }

    #[test]
    fn wide_char_at_end_of_buffer_atomic_reject() {
        let mut buf = Buffer::new(5, 1);

        // Try to write wide char at position 4 (would need position 5 for tail, out of bounds)
        buf.set(4, 0, Cell::from_char('中'));

        // Should be rejected atomically - nothing written
        assert!(
            buf.get(4, 0).unwrap().is_empty(),
            "Wide char should be rejected when tail would be out of bounds"
        );
    }

    #[test]
    fn three_wide_chars_sequential_cleanup() {
        let mut buf = Buffer::new(10, 1);

        // Write three wide chars: positions 0-1, 2-3, 4-5
        buf.set(0, 0, Cell::from_char('一'));
        buf.set(2, 0, Cell::from_char('二'));
        buf.set(4, 0, Cell::from_char('三'));

        // Verify initial state
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('一'));
        assert!(buf.get(1, 0).unwrap().is_continuation());
        assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('二'));
        assert!(buf.get(3, 0).unwrap().is_continuation());
        assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('三'));
        assert!(buf.get(5, 0).unwrap().is_continuation());

        // Overwrite middle wide char's continuation with single char
        buf.set(3, 0, Cell::from_char('M'));

        // First wide char should be unaffected
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('一'));
        assert!(buf.get(1, 0).unwrap().is_continuation());
        // Middle wide char's head should be cleared
        assert!(buf.get(2, 0).unwrap().is_empty());
        // Position 3 has new char
        assert_eq!(buf.get(3, 0).unwrap().content.as_char(), Some('M'));
        // Third wide char should be unaffected
        assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('三'));
        assert!(buf.get(5, 0).unwrap().is_continuation());
    }

    #[test]
    fn overwrite_empty_cell_no_cleanup_needed() {
        let mut buf = Buffer::new(10, 1);

        // Write to an empty cell - no cleanup should be needed
        buf.set(5, 0, Cell::from_char('X'));

        assert_eq!(buf.get(5, 0).unwrap().content.as_char(), Some('X'));
        // Adjacent cells should still be empty
        assert!(buf.get(4, 0).unwrap().is_empty());
        assert!(buf.get(6, 0).unwrap().is_empty());
    }

    #[test]
    fn wide_char_cleanup_with_opacity() {
        let mut buf = Buffer::new(10, 1);

        // Set background
        buf.set(0, 0, Cell::default().with_bg(PackedRgba::rgb(255, 0, 0)));
        buf.set(1, 0, Cell::default().with_bg(PackedRgba::rgb(0, 255, 0)));

        // Write wide char
        buf.set(0, 0, Cell::from_char('中'));

        // Overwrite with opacity
        buf.push_opacity(0.5);
        buf.set(0, 0, Cell::from_char('A'));
        buf.pop_opacity();

        // Check head is replaced
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
        // Continuation should be cleared
        assert!(buf.get(1, 0).unwrap().is_empty());
    }

    #[test]
    fn wide_char_continuation_not_treated_as_head() {
        let mut buf = Buffer::new(10, 1);

        // Write a wide character
        buf.set(0, 0, Cell::from_char('中'));

        // Verify the continuation cell has zero width (not treated as a head)
        let cont = buf.get(1, 0).unwrap();
        assert!(cont.is_continuation());
        assert_eq!(cont.content.width(), 0);

        // Writing another wide char starting at position 1 should work correctly
        buf.set(1, 0, Cell::from_char('æ—¥'));

        // Original head should be cleared
        assert!(buf.get(0, 0).unwrap().is_empty());
        // New wide char at 1-2
        assert_eq!(buf.get(1, 0).unwrap().content.as_char(), Some('æ—¥'));
        assert!(buf.get(2, 0).unwrap().is_continuation());
    }

    #[test]
    fn wide_char_fill_region() {
        let mut buf = Buffer::new(10, 3);

        // Fill a 4x2 region with a wide character.
        // Wide fills advance by width to prevent overlap churn.
        let wide_cell = Cell::from_char('中');
        buf.fill(Rect::new(0, 0, 4, 2), wide_cell);

        // Row 0 should contain two wide graphemes at x={0,2}.
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('中'));
        assert!(buf.get(1, 0).unwrap().is_continuation());
        assert_eq!(buf.get(2, 0).unwrap().content.as_char(), Some('中'));
        assert!(buf.get(3, 0).unwrap().is_continuation());
    }

    #[test]
    fn default_buffer_dimensions() {
        let buf = Buffer::default();
        assert_eq!(buf.width(), 1);
        assert_eq!(buf.height(), 1);
        assert_eq!(buf.len(), 1);
    }

    #[test]
    fn buffer_partial_eq_impl() {
        let buf1 = Buffer::new(5, 5);
        let buf2 = Buffer::new(5, 5);
        let mut buf3 = Buffer::new(5, 5);
        buf3.set(0, 0, Cell::from_char('X'));

        assert_eq!(buf1, buf2);
        assert_ne!(buf1, buf3);
    }

    #[test]
    fn degradation_level_accessible() {
        let mut buf = Buffer::new(10, 10);
        assert_eq!(buf.degradation, DegradationLevel::Full);

        buf.degradation = DegradationLevel::SimpleBorders;
        assert_eq!(buf.degradation, DegradationLevel::SimpleBorders);
    }

    // --- get_mut ---

    #[test]
    fn get_mut_modifies_cell() {
        let mut buf = Buffer::new(10, 10);
        buf.set(3, 3, Cell::from_char('A'));

        if let Some(cell) = buf.get_mut(3, 3) {
            *cell = Cell::from_char('B');
        }

        assert_eq!(buf.get(3, 3).unwrap().content.as_char(), Some('B'));
    }

    #[test]
    fn get_mut_out_of_bounds() {
        let mut buf = Buffer::new(5, 5);
        assert!(buf.get_mut(10, 10).is_none());
    }

    // --- clear_with ---

    #[test]
    fn clear_with_fills_all_cells() {
        let mut buf = Buffer::new(5, 3);
        let fill_cell = Cell::from_char('*');
        buf.clear_with(fill_cell);

        for y in 0..3 {
            for x in 0..5 {
                assert_eq!(buf.get(x, y).unwrap().content.as_char(), Some('*'));
            }
        }
    }

    #[test]
    fn clear_with_wide_cell_preserves_head_tail_invariant() {
        let mut buf = Buffer::new(5, 2);
        buf.clear_with(Cell::from_char('中'));

        for y in 0..2 {
            assert_eq!(buf.get(0, y).unwrap().content.as_char(), Some('中'));
            assert!(buf.get(1, y).unwrap().is_continuation());
            assert_eq!(buf.get(2, y).unwrap().content.as_char(), Some('中'));
            assert!(buf.get(3, y).unwrap().is_continuation());
            assert!(buf.get(4, y).unwrap().is_empty());
        }
    }

    // --- cells / cells_mut ---

    #[test]
    fn cells_slice_has_correct_length() {
        let buf = Buffer::new(10, 5);
        assert_eq!(buf.cells().len(), 50);
    }

    #[test]
    fn cells_mut_allows_direct_modification() {
        let mut buf = Buffer::new(3, 2);
        let cells = buf.cells_mut();
        cells[0] = Cell::from_char('Z');

        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('Z'));
    }

    // --- row_cells ---

    #[test]
    fn row_cells_returns_correct_row() {
        let mut buf = Buffer::new(5, 3);
        buf.set(2, 1, Cell::from_char('R'));

        let row = buf.row_cells(1);
        assert_eq!(row.len(), 5);
        assert_eq!(row[2].content.as_char(), Some('R'));
    }

    #[test]
    fn row_cells_mut_span_marks_once_and_returns_slice() {
        let mut buf = Buffer::new(5, 3);
        buf.clear_dirty();

        let row = buf
            .row_cells_mut_span(1, 1, 4)
            .expect("row span should be in bounds");
        assert_eq!(row.len(), 3);
        row[0] = Cell::from_char('A');
        row[1] = Cell::from_char('B');
        row[2] = Cell::from_char('C');

        assert!(buf.is_row_dirty(1));
        let spans = buf.dirty_span_row(1).expect("dirty span row").spans();
        assert_eq!(spans, &[DirtySpan::new(1, 4)]);
        assert_eq!(buf.get(1, 1).unwrap().content.as_char(), Some('A'));
        assert_eq!(buf.get(2, 1).unwrap().content.as_char(), Some('B'));
        assert_eq!(buf.get(3, 1).unwrap().content.as_char(), Some('C'));
    }

    #[test]
    fn row_cells_mut_span_clamps_to_buffer_width() {
        let mut buf = Buffer::new(5, 1);
        buf.clear_dirty();

        let row = buf
            .row_cells_mut_span(0, 3, 99)
            .expect("row span should clamp");
        assert_eq!(row.len(), 2);
        row[0] = Cell::from_char('X');
        row[1] = Cell::from_char('Y');

        let spans = buf.dirty_span_row(0).expect("dirty span row").spans();
        assert_eq!(spans, &[DirtySpan::new(3, 5)]);
        assert_eq!(buf.get(3, 0).unwrap().content.as_char(), Some('X'));
        assert_eq!(buf.get(4, 0).unwrap().content.as_char(), Some('Y'));
    }

    #[test]
    fn row_cells_mut_span_rejects_reversed_ranges() {
        let mut buf = Buffer::new(5, 1);
        buf.clear_dirty();

        assert!(buf.row_cells_mut_span(0, 4, 2).is_none());
        assert!(
            !buf.is_row_dirty(0),
            "reversed ranges should not mark rows dirty"
        );
        assert!(
            buf.dirty_span_row(0)
                .expect("dirty span row")
                .spans()
                .is_empty(),
            "reversed ranges should not add dirty spans"
        );
    }

    #[test]
    #[should_panic]
    fn row_cells_out_of_bounds_panics() {
        let buf = Buffer::new(5, 3);
        let _ = buf.row_cells(5);
    }

    // --- is_empty ---

    #[test]
    fn buffer_is_not_empty() {
        let buf = Buffer::new(1, 1);
        assert!(!buf.is_empty());
    }

    // --- set_raw out of bounds ---

    #[test]
    fn set_raw_out_of_bounds_is_safe() {
        let mut buf = Buffer::new(5, 5);
        buf.set_raw(100, 100, Cell::from_char('X'));
        // Should not panic, just be ignored
    }

    // --- copy_from with offset ---

    #[test]
    fn copy_from_out_of_bounds_partial() {
        let mut src = Buffer::new(5, 5);
        src.set(0, 0, Cell::from_char('A'));
        src.set(4, 4, Cell::from_char('B'));

        let mut dst = Buffer::new(5, 5);
        // Copy entire src with offset that puts part out of bounds
        dst.copy_from(&src, Rect::new(0, 0, 5, 5), 3, 3);

        // (0,0) in src → (3,3) in dst = inside
        assert_eq!(dst.get(3, 3).unwrap().content.as_char(), Some('A'));
        // (4,4) in src → (7,7) in dst = outside, should be ignored
        assert!(dst.get(4, 4).unwrap().is_empty());
    }

    // --- content_eq with different dimensions ---

    #[test]
    fn content_eq_different_dimensions() {
        let buf1 = Buffer::new(5, 5);
        let buf2 = Buffer::new(10, 10);
        // Different dimensions should not be equal (different cell counts)
        assert!(!buf1.content_eq(&buf2));
    }

    // ====== Property tests (proptest) ======

    mod property {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn buffer_dimensions_are_preserved(width in 1u16..200, height in 1u16..200) {
                let buf = Buffer::new(width, height);
                prop_assert_eq!(buf.width(), width);
                prop_assert_eq!(buf.height(), height);
                prop_assert_eq!(buf.len(), width as usize * height as usize);
            }

            #[test]
            fn buffer_get_in_bounds_always_succeeds(width in 1u16..100, height in 1u16..100) {
                let buf = Buffer::new(width, height);
                for x in 0..width {
                    for y in 0..height {
                        prop_assert!(buf.get(x, y).is_some(), "get({x},{y}) failed for {width}x{height} buffer");
                    }
                }
            }

            #[test]
            fn buffer_get_out_of_bounds_returns_none(width in 1u16..50, height in 1u16..50) {
                let buf = Buffer::new(width, height);
                prop_assert!(buf.get(width, 0).is_none());
                prop_assert!(buf.get(0, height).is_none());
                prop_assert!(buf.get(width, height).is_none());
            }

            #[test]
            fn buffer_set_get_roundtrip(
                width in 5u16..50,
                height in 5u16..50,
                x in 0u16..5,
                y in 0u16..5,
                ch_idx in 0u32..26,
            ) {
                let x = x % width;
                let y = y % height;
                let ch = char::from_u32('A' as u32 + ch_idx).unwrap();
                let mut buf = Buffer::new(width, height);
                buf.set(x, y, Cell::from_char(ch));
                let got = buf.get(x, y).unwrap();
                prop_assert_eq!(got.content.as_char(), Some(ch));
            }

            #[test]
            fn scissor_push_pop_stack_depth(
                width in 10u16..50,
                height in 10u16..50,
                push_count in 1usize..10,
            ) {
                let mut buf = Buffer::new(width, height);
                prop_assert_eq!(buf.scissor_depth(), 1); // base

                for i in 0..push_count {
                    buf.push_scissor(Rect::new(0, 0, width, height));
                    prop_assert_eq!(buf.scissor_depth(), i + 2);
                }

                for i in (0..push_count).rev() {
                    buf.pop_scissor();
                    prop_assert_eq!(buf.scissor_depth(), i + 1);
                }

                // Base cannot be popped
                buf.pop_scissor();
                prop_assert_eq!(buf.scissor_depth(), 1);
            }

            #[test]
            fn scissor_monotonic_intersection(
                width in 20u16..60,
                height in 20u16..60,
            ) {
                // Scissor stack always shrinks or stays the same
                let mut buf = Buffer::new(width, height);
                let outer = Rect::new(2, 2, width - 4, height - 4);
                buf.push_scissor(outer);
                let s1 = buf.current_scissor();

                let inner = Rect::new(5, 5, 10, 10);
                buf.push_scissor(inner);
                let s2 = buf.current_scissor();

                // Inner scissor must be contained within or equal to outer
                prop_assert!(s2.width <= s1.width, "inner width {} > outer width {}", s2.width, s1.width);
                prop_assert!(s2.height <= s1.height, "inner height {} > outer height {}", s2.height, s1.height);
            }

            #[test]
            fn opacity_push_pop_stack_depth(
                width in 5u16..20,
                height in 5u16..20,
                push_count in 1usize..10,
            ) {
                let mut buf = Buffer::new(width, height);
                prop_assert_eq!(buf.opacity_depth(), 1);

                for i in 0..push_count {
                    buf.push_opacity(0.9);
                    prop_assert_eq!(buf.opacity_depth(), i + 2);
                }

                for i in (0..push_count).rev() {
                    buf.pop_opacity();
                    prop_assert_eq!(buf.opacity_depth(), i + 1);
                }

                buf.pop_opacity();
                prop_assert_eq!(buf.opacity_depth(), 1);
            }

            #[test]
            fn opacity_multiplication_is_monotonic(
                opacity1 in 0.0f32..=1.0,
                opacity2 in 0.0f32..=1.0,
            ) {
                let mut buf = Buffer::new(5, 5);
                buf.push_opacity(opacity1);
                let after_first = buf.current_opacity();
                buf.push_opacity(opacity2);
                let after_second = buf.current_opacity();

                // Effective opacity can only decrease (or stay same at 0 or 1)
                prop_assert!(after_second <= after_first + f32::EPSILON,
                    "opacity increased: {} -> {}", after_first, after_second);
            }

            #[test]
            fn clear_resets_all_cells(width in 1u16..30, height in 1u16..30) {
                let mut buf = Buffer::new(width, height);
                // Write some data
                for x in 0..width {
                    buf.set_raw(x, 0, Cell::from_char('X'));
                }
                buf.clear();
                // All cells should be default (empty)
                for y in 0..height {
                    for x in 0..width {
                        prop_assert!(buf.get(x, y).unwrap().is_empty(),
                            "cell ({x},{y}) not empty after clear");
                    }
                }
            }

            #[test]
            fn content_eq_is_reflexive(width in 1u16..30, height in 1u16..30) {
                let buf = Buffer::new(width, height);
                prop_assert!(buf.content_eq(&buf));
            }

            #[test]
            fn content_eq_detects_single_change(
                width in 5u16..30,
                height in 5u16..30,
                x in 0u16..5,
                y in 0u16..5,
            ) {
                let x = x % width;
                let y = y % height;
                let buf1 = Buffer::new(width, height);
                let mut buf2 = Buffer::new(width, height);
                buf2.set_raw(x, y, Cell::from_char('Z'));
                prop_assert!(!buf1.content_eq(&buf2));
            }

            // --- Executable Invariant Tests (bd-10i.13.2) ---

            #[test]
            fn dimensions_immutable_through_operations(
                width in 5u16..30,
                height in 5u16..30,
            ) {
                let mut buf = Buffer::new(width, height);

                // Operations that must not change dimensions
                buf.set(0, 0, Cell::from_char('A'));
                prop_assert_eq!(buf.width(), width);
                prop_assert_eq!(buf.height(), height);
                prop_assert_eq!(buf.len(), width as usize * height as usize);

                buf.push_scissor(Rect::new(1, 1, 3, 3));
                prop_assert_eq!(buf.width(), width);
                prop_assert_eq!(buf.height(), height);

                buf.push_opacity(0.5);
                prop_assert_eq!(buf.width(), width);
                prop_assert_eq!(buf.height(), height);

                buf.pop_scissor();
                buf.pop_opacity();
                prop_assert_eq!(buf.width(), width);
                prop_assert_eq!(buf.height(), height);

                buf.clear();
                prop_assert_eq!(buf.width(), width);
                prop_assert_eq!(buf.height(), height);
                prop_assert_eq!(buf.len(), width as usize * height as usize);
            }

            #[test]
            fn scissor_area_never_increases_random_rects(
                width in 20u16..60,
                height in 20u16..60,
                rects in proptest::collection::vec(
                    (0u16..20, 0u16..20, 1u16..15, 1u16..15),
                    1..8
                ),
            ) {
                let mut buf = Buffer::new(width, height);
                let mut prev_area = (width as u32) * (height as u32);

                for (x, y, w, h) in rects {
                    buf.push_scissor(Rect::new(x, y, w, h));
                    let s = buf.current_scissor();
                    let area = (s.width as u32) * (s.height as u32);
                    prop_assert!(area <= prev_area,
                        "scissor area increased: {} -> {} after push({},{},{},{})",
                        prev_area, area, x, y, w, h);
                    prev_area = area;
                }
            }

            #[test]
            fn opacity_range_invariant_random_sequence(
                opacities in proptest::collection::vec(0.0f32..=1.0, 1..15),
            ) {
                let mut buf = Buffer::new(5, 5);

                for &op in &opacities {
                    buf.push_opacity(op);
                    let current = buf.current_opacity();
                    prop_assert!(current >= 0.0, "opacity below 0: {}", current);
                    prop_assert!(current <= 1.0 + f32::EPSILON,
                        "opacity above 1: {}", current);
                }

                // Pop everything and verify we get back to 1.0
                for _ in &opacities {
                    buf.pop_opacity();
                }
                // After popping all pushed, should be back to base (1.0)
                prop_assert!((buf.current_opacity() - 1.0).abs() < f32::EPSILON);
            }

            #[test]
            fn opacity_clamp_out_of_range(
                neg in -100.0f32..0.0,
                over in 1.01f32..100.0,
            ) {
                let mut buf = Buffer::new(5, 5);

                buf.push_opacity(neg);
                prop_assert!(buf.current_opacity() >= 0.0,
                    "negative opacity not clamped: {}", buf.current_opacity());
                buf.pop_opacity();

                buf.push_opacity(over);
                prop_assert!(buf.current_opacity() <= 1.0 + f32::EPSILON,
                    "over-1 opacity not clamped: {}", buf.current_opacity());
            }

            #[test]
            fn scissor_stack_always_has_base(
                pushes in 0usize..10,
                pops in 0usize..15,
            ) {
                let mut buf = Buffer::new(10, 10);

                for _ in 0..pushes {
                    buf.push_scissor(Rect::new(0, 0, 5, 5));
                }
                for _ in 0..pops {
                    buf.pop_scissor();
                }

                // Invariant: depth is always >= 1
                prop_assert!(buf.scissor_depth() >= 1,
                    "scissor depth dropped below 1 after {} pushes, {} pops",
                    pushes, pops);
            }

            #[test]
            fn opacity_stack_always_has_base(
                pushes in 0usize..10,
                pops in 0usize..15,
            ) {
                let mut buf = Buffer::new(10, 10);

                for _ in 0..pushes {
                    buf.push_opacity(0.5);
                }
                for _ in 0..pops {
                    buf.pop_opacity();
                }

                // Invariant: depth is always >= 1
                prop_assert!(buf.opacity_depth() >= 1,
                    "opacity depth dropped below 1 after {} pushes, {} pops",
                    pushes, pops);
            }

            #[test]
            fn cells_len_invariant_always_holds(
                width in 1u16..50,
                height in 1u16..50,
            ) {
                let mut buf = Buffer::new(width, height);
                let expected = width as usize * height as usize;

                prop_assert_eq!(buf.cells().len(), expected);

                // After mutations
                buf.set(0, 0, Cell::from_char('X'));
                prop_assert_eq!(buf.cells().len(), expected);

                buf.clear();
                prop_assert_eq!(buf.cells().len(), expected);
            }

            #[test]
            fn set_outside_scissor_is_noop(
                width in 10u16..30,
                height in 10u16..30,
            ) {
                let mut buf = Buffer::new(width, height);
                buf.push_scissor(Rect::new(2, 2, 3, 3));

                // Write outside scissor region
                buf.set(0, 0, Cell::from_char('X'));
                // Should be unmodified (still empty)
                let cell = buf.get(0, 0).unwrap();
                prop_assert!(cell.is_empty(),
                    "cell (0,0) modified outside scissor region");

                // Write inside scissor region should work
                buf.set(3, 3, Cell::from_char('Y'));
                let cell = buf.get(3, 3).unwrap();
                prop_assert_eq!(cell.content.as_char(), Some('Y'));
            }

            // --- Wide Glyph Cleanup Property Tests ---

            #[test]
            fn wide_char_overwrites_cleanup_tails(
                width in 10u16..30,
                x in 0u16..8,
            ) {
                let x = x % (width.saturating_sub(2).max(1));
                let mut buf = Buffer::new(width, 1);

                // Write wide char
                buf.set(x, 0, Cell::from_char('中'));

                // If it fit, check structure
                if x + 1 < width {
                    let head = buf.get(x, 0).unwrap();
                    let tail = buf.get(x + 1, 0).unwrap();

                    if head.content.as_char() == Some('中') {
                        prop_assert!(tail.is_continuation(),
                            "tail at x+1={} should be continuation", x + 1);

                        // Overwrite head with single char
                        buf.set(x, 0, Cell::from_char('A'));
                        let new_head = buf.get(x, 0).unwrap();
                        let cleared_tail = buf.get(x + 1, 0).unwrap();

                        prop_assert_eq!(new_head.content.as_char(), Some('A'));
                        prop_assert!(cleared_tail.is_empty(),
                            "tail should be cleared after head overwrite");
                    }
                }
            }

            #[test]
            fn wide_char_atomic_rejection_at_boundary(
                width in 3u16..20,
            ) {
                let mut buf = Buffer::new(width, 1);

                // Try to write wide char at last position (needs x and x+1)
                let last_pos = width - 1;
                buf.set(last_pos, 0, Cell::from_char('中'));

                // Should be rejected - cell should remain empty
                let cell = buf.get(last_pos, 0).unwrap();
                prop_assert!(cell.is_empty(),
                    "wide char at boundary position {} (width {}) should be rejected",
                    last_pos, width);
            }

            // =====================================================================
            // DoubleBuffer property tests (bd-1rz0.4.4)
            // =====================================================================

            #[test]
            fn double_buffer_swap_is_involution(ops in proptest::collection::vec(proptest::bool::ANY, 0..100)) {
                let mut db = DoubleBuffer::new(10, 10);
                let initial_idx = db.current_idx;

                for do_swap in &ops {
                    if *do_swap {
                        db.swap();
                    }
                }

                let swap_count = ops.iter().filter(|&&x| x).count();
                let expected_idx = if swap_count % 2 == 0 { initial_idx } else { 1 - initial_idx };

                prop_assert_eq!(db.current_idx, expected_idx,
                    "After {} swaps, index should be {} but was {}",
                    swap_count, expected_idx, db.current_idx);
            }

            #[test]
            fn double_buffer_resize_preserves_invariant(
                init_w in 1u16..200,
                init_h in 1u16..100,
                new_w in 1u16..200,
                new_h in 1u16..100,
            ) {
                let mut db = DoubleBuffer::new(init_w, init_h);
                db.resize(new_w, new_h);

                prop_assert_eq!(db.width(), new_w);
                prop_assert_eq!(db.height(), new_h);
                prop_assert!(db.dimensions_match(new_w, new_h));
            }

            #[test]
            fn double_buffer_current_previous_disjoint(
                width in 1u16..50,
                height in 1u16..50,
            ) {
                let mut db = DoubleBuffer::new(width, height);

                // Write to current
                db.current_mut().set(0, 0, Cell::from_char('C'));

                // Previous should be unaffected
                prop_assert!(db.previous().get(0, 0).unwrap().is_empty(),
                    "Previous buffer should not reflect changes to current");

                // After swap, roles reverse
                db.swap();
                prop_assert_eq!(db.previous().get(0, 0).unwrap().content.as_char(), Some('C'),
                    "After swap, previous should have the 'C' we wrote");
            }

            #[test]
            fn double_buffer_swap_content_semantics(
                width in 5u16..30,
                height in 5u16..30,
            ) {
                let mut db = DoubleBuffer::new(width, height);

                // Write 'X' to current
                db.current_mut().set(0, 0, Cell::from_char('X'));
                db.swap();

                // Write 'Y' to current (now the other buffer)
                db.current_mut().set(0, 0, Cell::from_char('Y'));
                db.swap();

                // After two swaps, we're back to the buffer with 'X'
                prop_assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('X'));
                prop_assert_eq!(db.previous().get(0, 0).unwrap().content.as_char(), Some('Y'));
            }

            #[test]
            fn double_buffer_resize_clears_both(
                w1 in 5u16..30,
                h1 in 5u16..30,
                w2 in 5u16..30,
                h2 in 5u16..30,
            ) {
                // Skip if dimensions are the same (resize returns early)
                prop_assume!(w1 != w2 || h1 != h2);

                let mut db = DoubleBuffer::new(w1, h1);

                // Populate both buffers
                db.current_mut().set(0, 0, Cell::from_char('A'));
                db.swap();
                db.current_mut().set(0, 0, Cell::from_char('B'));

                // Resize
                db.resize(w2, h2);

                // Both should be empty
                prop_assert!(db.current().get(0, 0).unwrap().is_empty(),
                    "Current buffer should be empty after resize");
                prop_assert!(db.previous().get(0, 0).unwrap().is_empty(),
                    "Previous buffer should be empty after resize");
            }
        }
    }

    // ========== Dirty Row Tracking Tests (bd-4kq0.1.1) ==========

    #[test]
    fn dirty_rows_start_dirty() {
        // All rows start dirty to ensure initial diffs see all content.
        let buf = Buffer::new(10, 5);
        assert_eq!(buf.dirty_row_count(), 5);
        for y in 0..5 {
            assert!(buf.is_row_dirty(y));
        }
    }

    #[test]
    fn dirty_bitmap_starts_full() {
        let buf = Buffer::new(4, 3);
        assert!(buf.dirty_all());
        assert_eq!(buf.dirty_cell_count(), 12);
    }

    #[test]
    fn dirty_bitmap_tracks_single_cell() {
        let mut buf = Buffer::new(4, 3);
        buf.clear_dirty();
        assert!(!buf.dirty_all());
        buf.set_raw(1, 1, Cell::from_char('X'));
        let idx = 1 + 4;
        assert_eq!(buf.dirty_cell_count(), 1);
        assert_eq!(buf.dirty_bits()[idx], 1);
    }

    #[test]
    fn dirty_bitmap_dedupes_cells() {
        let mut buf = Buffer::new(4, 3);
        buf.clear_dirty();
        buf.set_raw(2, 2, Cell::from_char('A'));
        buf.set_raw(2, 2, Cell::from_char('B'));
        assert_eq!(buf.dirty_cell_count(), 1);
    }

    #[test]
    fn set_marks_row_dirty() {
        let mut buf = Buffer::new(10, 5);
        buf.clear_dirty(); // Reset initial dirty state
        buf.set(3, 2, Cell::from_char('X'));
        assert!(buf.is_row_dirty(2));
        assert!(!buf.is_row_dirty(0));
        assert!(!buf.is_row_dirty(1));
        assert!(!buf.is_row_dirty(3));
        assert!(!buf.is_row_dirty(4));
    }

    #[test]
    fn set_raw_marks_row_dirty() {
        let mut buf = Buffer::new(10, 5);
        buf.clear_dirty(); // Reset initial dirty state
        buf.set_raw(0, 4, Cell::from_char('Z'));
        assert!(buf.is_row_dirty(4));
        assert_eq!(buf.dirty_row_count(), 1);
    }

    #[test]
    fn clear_marks_all_dirty() {
        let mut buf = Buffer::new(10, 5);
        buf.clear();
        assert_eq!(buf.dirty_row_count(), 5);
    }

    #[test]
    fn clear_dirty_resets_flags() {
        let mut buf = Buffer::new(10, 5);
        // All rows start dirty; clear_dirty should reset all of them.
        assert_eq!(buf.dirty_row_count(), 5);
        buf.clear_dirty();
        assert_eq!(buf.dirty_row_count(), 0);

        // Now mark specific rows dirty and verify clear_dirty resets again.
        buf.set(0, 0, Cell::from_char('A'));
        buf.set(0, 3, Cell::from_char('B'));
        assert_eq!(buf.dirty_row_count(), 2);

        buf.clear_dirty();
        assert_eq!(buf.dirty_row_count(), 0);
    }

    #[test]
    fn clear_dirty_resets_bitmap() {
        let mut buf = Buffer::new(4, 3);
        buf.clear();
        assert!(buf.dirty_all());
        buf.clear_dirty();
        assert!(!buf.dirty_all());
        assert_eq!(buf.dirty_cell_count(), 0);
        assert!(buf.dirty_bits().iter().all(|&b| b == 0));
    }

    #[test]
    fn fill_marks_affected_rows_dirty() {
        let mut buf = Buffer::new(10, 10);
        buf.clear_dirty(); // Reset initial dirty state
        buf.fill(Rect::new(0, 2, 5, 3), Cell::from_char('.'));
        // Rows 2, 3, 4 should be dirty
        assert!(!buf.is_row_dirty(0));
        assert!(!buf.is_row_dirty(1));
        assert!(buf.is_row_dirty(2));
        assert!(buf.is_row_dirty(3));
        assert!(buf.is_row_dirty(4));
        assert!(!buf.is_row_dirty(5));
    }

    #[test]
    fn get_mut_marks_row_dirty() {
        let mut buf = Buffer::new(10, 5);
        buf.clear_dirty(); // Reset initial dirty state
        if let Some(cell) = buf.get_mut(5, 3) {
            cell.fg = PackedRgba::rgb(255, 0, 0);
        }
        assert!(buf.is_row_dirty(3));
        assert_eq!(buf.dirty_row_count(), 1);
    }

    #[test]
    fn cells_mut_marks_all_dirty() {
        let mut buf = Buffer::new(10, 5);
        let _ = buf.cells_mut();
        assert_eq!(buf.dirty_row_count(), 5);
    }

    #[test]
    fn dirty_rows_slice_length_matches_height() {
        let buf = Buffer::new(10, 7);
        assert_eq!(buf.dirty_rows().len(), 7);
    }

    #[test]
    fn out_of_bounds_set_does_not_dirty() {
        let mut buf = Buffer::new(10, 5);
        buf.clear_dirty(); // Reset initial dirty state
        buf.set(100, 100, Cell::from_char('X'));
        assert_eq!(buf.dirty_row_count(), 0);
    }

    #[test]
    fn property_dirty_soundness() {
        // Randomized test: any mutation must mark its row.
        let mut buf = Buffer::new(20, 10);
        let positions = [(3, 0), (5, 2), (0, 9), (19, 5), (10, 7)];
        for &(x, y) in &positions {
            buf.set(x, y, Cell::from_char('*'));
        }
        for &(_, y) in &positions {
            assert!(
                buf.is_row_dirty(y),
                "Row {} should be dirty after set({}, {})",
                y,
                positions.iter().find(|(_, ry)| *ry == y).unwrap().0,
                y
            );
        }
    }

    #[test]
    fn dirty_clear_between_frames() {
        // Simulates frame transition: render, diff, clear, render again.
        let mut buf = Buffer::new(10, 5);

        // All rows start dirty (initial frame needs full diff).
        assert_eq!(buf.dirty_row_count(), 5);

        // Diff consumes dirty state after initial frame.
        buf.clear_dirty();
        assert_eq!(buf.dirty_row_count(), 0);

        // Frame 1: write to rows 0, 2
        buf.set(0, 0, Cell::from_char('A'));
        buf.set(0, 2, Cell::from_char('B'));
        assert_eq!(buf.dirty_row_count(), 2);

        // Diff consumes dirty state
        buf.clear_dirty();
        assert_eq!(buf.dirty_row_count(), 0);

        // Frame 2: write to row 4 only
        buf.set(0, 4, Cell::from_char('C'));
        assert_eq!(buf.dirty_row_count(), 1);
        assert!(buf.is_row_dirty(4));
        assert!(!buf.is_row_dirty(0));
    }

    // ========== Dirty Span Tracking Tests (bd-3e1t.6.2) ==========

    #[test]
    fn dirty_spans_start_full_dirty() {
        let buf = Buffer::new(10, 5);
        for y in 0..5 {
            let row = buf.dirty_span_row(y).unwrap();
            assert!(row.is_full(), "row {y} should start full-dirty");
            assert!(row.spans().is_empty(), "row {y} spans should start empty");
        }
    }

    #[test]
    fn clear_dirty_resets_spans() {
        let mut buf = Buffer::new(10, 5);
        buf.clear_dirty();
        for y in 0..5 {
            let row = buf.dirty_span_row(y).unwrap();
            assert!(!row.is_full(), "row {y} should clear full-dirty");
            assert!(row.spans().is_empty(), "row {y} spans should be cleared");
        }
        assert_eq!(buf.dirty_span_overflows, 0);
    }

    #[test]
    fn set_records_dirty_span() {
        let mut buf = Buffer::new(20, 2);
        buf.clear_dirty();
        buf.set(2, 0, Cell::from_char('A'));
        let row = buf.dirty_span_row(0).unwrap();
        assert_eq!(row.spans(), &[DirtySpan::new(2, 3)]);
        assert!(!row.is_full());
    }

    #[test]
    fn set_merges_adjacent_spans() {
        let mut buf = Buffer::new(20, 2);
        buf.clear_dirty();
        buf.set(2, 0, Cell::from_char('A'));
        buf.set(3, 0, Cell::from_char('B')); // adjacent, should merge
        let row = buf.dirty_span_row(0).unwrap();
        assert_eq!(row.spans(), &[DirtySpan::new(2, 4)]);
    }

    #[test]
    fn set_merges_close_spans() {
        let mut buf = Buffer::new(20, 2);
        buf.clear_dirty();
        buf.set(2, 0, Cell::from_char('A'));
        buf.set(4, 0, Cell::from_char('B')); // gap of 1, should merge
        let row = buf.dirty_span_row(0).unwrap();
        assert_eq!(row.spans(), &[DirtySpan::new(2, 5)]);
    }

    #[test]
    fn span_overflow_sets_full_row() {
        let width = (DIRTY_SPAN_MAX_SPANS_PER_ROW as u16 + 2) * 3;
        let mut buf = Buffer::new(width, 1);
        buf.clear_dirty();
        for i in 0..(DIRTY_SPAN_MAX_SPANS_PER_ROW + 1) {
            let x = (i as u16) * 3;
            buf.set(x, 0, Cell::from_char('x'));
        }
        let row = buf.dirty_span_row(0).unwrap();
        assert!(row.is_full());
        assert!(row.spans().is_empty());
        assert_eq!(buf.dirty_span_overflows, 1);
    }

    #[test]
    fn fill_full_row_marks_full_span() {
        let mut buf = Buffer::new(10, 3);
        buf.clear_dirty();
        let cell = Cell::from_char('x').with_bg(PackedRgba::rgb(0, 0, 0));
        buf.fill(Rect::new(0, 1, 10, 1), cell);
        let row = buf.dirty_span_row(1).unwrap();
        assert!(row.is_full());
        assert!(row.spans().is_empty());
    }

    #[test]
    fn get_mut_records_dirty_span() {
        let mut buf = Buffer::new(10, 5);
        buf.clear_dirty();
        let _ = buf.get_mut(5, 3);
        let row = buf.dirty_span_row(3).unwrap();
        assert_eq!(row.spans(), &[DirtySpan::new(5, 6)]);
    }

    #[test]
    fn cells_mut_marks_all_full_spans() {
        let mut buf = Buffer::new(10, 5);
        buf.clear_dirty();
        let _ = buf.cells_mut();
        for y in 0..5 {
            let row = buf.dirty_span_row(y).unwrap();
            assert!(row.is_full(), "row {y} should be full after cells_mut");
        }
    }

    #[test]
    fn dirty_span_config_disabled_skips_rows() {
        let mut buf = Buffer::new(10, 1);
        buf.clear_dirty();
        buf.set_dirty_span_config(DirtySpanConfig::default().with_enabled(false));
        buf.set(5, 0, Cell::from_char('x'));
        assert!(buf.dirty_span_row(0).is_none());
        let stats = buf.dirty_span_stats();
        assert_eq!(stats.total_spans, 0);
        assert_eq!(stats.span_coverage_cells, 0);
    }

    #[test]
    fn dirty_span_guard_band_expands_span_bounds() {
        let mut buf = Buffer::new(10, 1);
        buf.clear_dirty();
        buf.set_dirty_span_config(DirtySpanConfig::default().with_guard_band(2));
        buf.set(5, 0, Cell::from_char('x'));
        let row = buf.dirty_span_row(0).unwrap();
        assert_eq!(row.spans(), &[DirtySpan::new(3, 8)]);
    }

    #[test]
    fn dirty_span_max_spans_overflow_triggers_full_row() {
        let mut buf = Buffer::new(10, 1);
        buf.clear_dirty();
        buf.set_dirty_span_config(
            DirtySpanConfig::default()
                .with_max_spans_per_row(1)
                .with_merge_gap(0),
        );
        buf.set(0, 0, Cell::from_char('a'));
        buf.set(4, 0, Cell::from_char('b'));
        let row = buf.dirty_span_row(0).unwrap();
        assert!(row.is_full());
        assert!(row.spans().is_empty());
        assert_eq!(buf.dirty_span_overflows, 1);
    }

    #[test]
    fn dirty_span_stats_counts_full_rows_and_spans() {
        let mut buf = Buffer::new(6, 2);
        buf.clear_dirty();
        buf.set_dirty_span_config(DirtySpanConfig::default().with_merge_gap(0));
        buf.set(1, 0, Cell::from_char('a'));
        buf.set(4, 0, Cell::from_char('b'));
        buf.mark_dirty_row_full(1);

        let stats = buf.dirty_span_stats();
        assert_eq!(stats.rows_full_dirty, 1);
        assert_eq!(stats.rows_with_spans, 1);
        assert_eq!(stats.total_spans, 2);
        assert_eq!(stats.max_span_len, 6);
        assert_eq!(stats.span_coverage_cells, 8);
    }

    #[test]
    fn dirty_span_stats_reports_overflow_and_full_row() {
        let mut buf = Buffer::new(8, 1);
        buf.clear_dirty();
        buf.set_dirty_span_config(
            DirtySpanConfig::default()
                .with_max_spans_per_row(1)
                .with_merge_gap(0),
        );
        buf.set(0, 0, Cell::from_char('x'));
        buf.set(3, 0, Cell::from_char('y'));

        let stats = buf.dirty_span_stats();
        assert_eq!(stats.overflows, 1);
        assert_eq!(stats.rows_full_dirty, 1);
        assert_eq!(stats.total_spans, 0);
        assert_eq!(stats.span_coverage_cells, 8);
    }

    // =====================================================================
    // DoubleBuffer tests (bd-1rz0.4.4)
    // =====================================================================

    #[test]
    fn double_buffer_new_has_matching_dimensions() {
        let db = DoubleBuffer::new(80, 24);
        assert_eq!(db.width(), 80);
        assert_eq!(db.height(), 24);
        assert!(db.dimensions_match(80, 24));
        assert!(!db.dimensions_match(120, 40));
    }

    #[test]
    fn double_buffer_swap_is_o1() {
        let mut db = DoubleBuffer::new(80, 24);

        // Write to current buffer
        db.current_mut().set(0, 0, Cell::from_char('A'));
        assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('A'));

        // Swap — previous should now have 'A', current should be clean
        db.swap();
        assert_eq!(
            db.previous().get(0, 0).unwrap().content.as_char(),
            Some('A')
        );
        // Current was the old "previous" (empty by default)
        assert!(db.current().get(0, 0).unwrap().is_empty());
    }

    #[test]
    fn double_buffer_swap_round_trip() {
        let mut db = DoubleBuffer::new(10, 5);

        db.current_mut().set(0, 0, Cell::from_char('X'));
        db.swap();
        db.current_mut().set(0, 0, Cell::from_char('Y'));
        db.swap();

        // After two swaps, we're back to the buffer that had 'X'
        assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('X'));
        assert_eq!(
            db.previous().get(0, 0).unwrap().content.as_char(),
            Some('Y')
        );
    }

    #[test]
    fn double_buffer_resize_changes_dimensions() {
        let mut db = DoubleBuffer::new(80, 24);
        assert!(!db.resize(80, 24)); // No change
        assert!(db.resize(120, 40)); // Changed
        assert_eq!(db.width(), 120);
        assert_eq!(db.height(), 40);
        assert!(db.dimensions_match(120, 40));
    }

    #[test]
    fn double_buffer_resize_clears_content() {
        let mut db = DoubleBuffer::new(10, 5);
        db.current_mut().set(0, 0, Cell::from_char('Z'));
        db.swap();
        db.current_mut().set(0, 0, Cell::from_char('W'));

        db.resize(20, 10);

        // Both buffers should be fresh/empty
        assert!(db.current().get(0, 0).unwrap().is_empty());
        assert!(db.previous().get(0, 0).unwrap().is_empty());
    }

    #[test]
    fn double_buffer_current_and_previous_are_distinct() {
        let mut db = DoubleBuffer::new(10, 5);
        db.current_mut().set(0, 0, Cell::from_char('C'));

        // Previous should not reflect changes to current
        assert!(db.previous().get(0, 0).unwrap().is_empty());
        assert_eq!(db.current().get(0, 0).unwrap().content.as_char(), Some('C'));
    }

    // =====================================================================
    // AdaptiveDoubleBuffer tests (bd-1rz0.4.2)
    // =====================================================================

    #[test]
    fn adaptive_buffer_new_has_over_allocation() {
        let adb = AdaptiveDoubleBuffer::new(80, 24);

        // Logical dimensions match requested size
        assert_eq!(adb.width(), 80);
        assert_eq!(adb.height(), 24);
        assert!(adb.dimensions_match(80, 24));

        // Capacity should be larger (1.25x growth factor, capped at 200)
        // 80 * 0.25 = 20, so capacity_width = 100
        // 24 * 0.25 = 6, so capacity_height = 30
        assert!(adb.capacity_width() > 80);
        assert!(adb.capacity_height() > 24);
        assert_eq!(adb.capacity_width(), 100); // 80 + 20
        assert_eq!(adb.capacity_height(), 30); // 24 + 6
    }

    #[test]
    fn adaptive_buffer_resize_avoids_reallocation_when_within_capacity() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // Small growth should be absorbed by over-allocation
        assert!(adb.resize(90, 28)); // Still within (100, 30) capacity
        assert_eq!(adb.width(), 90);
        assert_eq!(adb.height(), 28);
        assert_eq!(adb.stats().resize_avoided, 1);
        assert_eq!(adb.stats().resize_reallocated, 0);
        assert_eq!(adb.stats().resize_growth, 1);
    }

    #[test]
    fn adaptive_buffer_resize_reallocates_on_growth_beyond_capacity() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // Growth beyond capacity requires reallocation
        assert!(adb.resize(120, 40)); // Exceeds (100, 30) capacity
        assert_eq!(adb.width(), 120);
        assert_eq!(adb.height(), 40);
        assert_eq!(adb.stats().resize_reallocated, 1);
        assert_eq!(adb.stats().resize_avoided, 0);

        // New capacity should have headroom
        assert!(adb.capacity_width() > 120);
        assert!(adb.capacity_height() > 40);
    }

    #[test]
    fn adaptive_buffer_resize_reallocates_on_significant_shrink() {
        let mut adb = AdaptiveDoubleBuffer::new(100, 50);

        // Shrink below 50% threshold should reallocate
        // Threshold: 100 * 0.5 = 50, 50 * 0.5 = 25
        assert!(adb.resize(40, 20)); // Below 50% of capacity
        assert_eq!(adb.width(), 40);
        assert_eq!(adb.height(), 20);
        assert_eq!(adb.stats().resize_reallocated, 1);
        assert_eq!(adb.stats().resize_shrink, 1);
    }

    #[test]
    fn adaptive_buffer_resize_avoids_reallocation_on_minor_shrink() {
        let mut adb = AdaptiveDoubleBuffer::new(100, 50);

        // Shrink above 50% threshold should reuse capacity
        // Threshold: capacity ~125 * 0.5 = 62.5 for width
        // 100 > 62.5, so no reallocation
        assert!(adb.resize(80, 40));
        assert_eq!(adb.width(), 80);
        assert_eq!(adb.height(), 40);
        assert_eq!(adb.stats().resize_avoided, 1);
        assert_eq!(adb.stats().resize_reallocated, 0);
        assert_eq!(adb.stats().resize_shrink, 1);
    }

    #[test]
    fn adaptive_buffer_no_change_returns_false() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        assert!(!adb.resize(80, 24)); // No change
        assert_eq!(adb.stats().resize_avoided, 0);
        assert_eq!(adb.stats().resize_reallocated, 0);
        assert_eq!(adb.stats().resize_growth, 0);
        assert_eq!(adb.stats().resize_shrink, 0);
    }

    #[test]
    fn adaptive_buffer_swap_works() {
        let mut adb = AdaptiveDoubleBuffer::new(10, 5);

        adb.current_mut().set(0, 0, Cell::from_char('A'));
        assert_eq!(
            adb.current().get(0, 0).unwrap().content.as_char(),
            Some('A')
        );

        adb.swap();
        assert_eq!(
            adb.previous().get(0, 0).unwrap().content.as_char(),
            Some('A')
        );
        assert!(adb.current().get(0, 0).unwrap().is_empty());
    }

    #[test]
    fn adaptive_buffer_stats_reset() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        adb.resize(90, 28);
        adb.resize(120, 40);
        assert!(adb.stats().resize_avoided > 0 || adb.stats().resize_reallocated > 0);

        adb.reset_stats();
        assert_eq!(adb.stats().resize_avoided, 0);
        assert_eq!(adb.stats().resize_reallocated, 0);
        assert_eq!(adb.stats().resize_growth, 0);
        assert_eq!(adb.stats().resize_shrink, 0);
    }

    #[test]
    fn adaptive_buffer_memory_efficiency() {
        let adb = AdaptiveDoubleBuffer::new(80, 24);

        let efficiency = adb.memory_efficiency();
        // 80*24 = 1920 logical cells
        // 100*30 = 3000 capacity cells
        // efficiency = 1920/3000 = 0.64
        assert!(efficiency > 0.5);
        assert!(efficiency < 1.0);
    }

    #[test]
    fn adaptive_buffer_logical_bounds() {
        let adb = AdaptiveDoubleBuffer::new(80, 24);

        let bounds = adb.logical_bounds();
        assert_eq!(bounds.x, 0);
        assert_eq!(bounds.y, 0);
        assert_eq!(bounds.width, 80);
        assert_eq!(bounds.height, 24);
    }

    #[test]
    fn adaptive_buffer_capacity_clamped_for_large_sizes() {
        // Test that over-allocation is capped at ADAPTIVE_MAX_OVERAGE (200)
        let adb = AdaptiveDoubleBuffer::new(1000, 500);

        // 1000 * 0.25 = 250, capped to 200
        // 500 * 0.25 = 125, not capped
        assert_eq!(adb.capacity_width(), 1000 + 200); // capped
        assert_eq!(adb.capacity_height(), 500 + 125); // not capped
    }

    #[test]
    fn adaptive_stats_avoidance_ratio() {
        let mut stats = AdaptiveStats::default();

        // Empty stats should return 1.0 (perfect avoidance)
        assert!((stats.avoidance_ratio() - 1.0).abs() < f64::EPSILON);

        // 3 avoided, 1 reallocated = 75% avoidance
        stats.resize_avoided = 3;
        stats.resize_reallocated = 1;
        assert!((stats.avoidance_ratio() - 0.75).abs() < f64::EPSILON);

        // All reallocations = 0% avoidance
        stats.resize_avoided = 0;
        stats.resize_reallocated = 5;
        assert!((stats.avoidance_ratio() - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn adaptive_buffer_resize_storm_simulation() {
        // Simulate a resize storm (rapid size changes)
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // Simulate user resizing terminal in small increments
        for i in 1..=10 {
            adb.resize(80 + i, 24 + (i / 2));
        }

        // Most resizes should have avoided reallocation due to over-allocation
        let ratio = adb.stats().avoidance_ratio();
        assert!(
            ratio > 0.5,
            "Expected >50% avoidance ratio, got {:.2}",
            ratio
        );
    }

    #[test]
    fn adaptive_buffer_width_only_growth() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // Grow only width, within capacity
        assert!(adb.resize(95, 24)); // 95 < 100 capacity
        assert_eq!(adb.stats().resize_avoided, 1);
        assert_eq!(adb.stats().resize_growth, 1);
    }

    #[test]
    fn adaptive_buffer_height_only_growth() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // Grow only height, within capacity
        assert!(adb.resize(80, 28)); // 28 < 30 capacity
        assert_eq!(adb.stats().resize_avoided, 1);
        assert_eq!(adb.stats().resize_growth, 1);
    }

    #[test]
    fn adaptive_buffer_one_dimension_exceeds_capacity() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // One dimension exceeds capacity, should reallocate
        assert!(adb.resize(105, 24)); // 105 > 100 capacity, 24 < 30
        assert_eq!(adb.stats().resize_reallocated, 1);
    }

    #[test]
    fn adaptive_buffer_current_and_previous_distinct() {
        let mut adb = AdaptiveDoubleBuffer::new(10, 5);
        adb.current_mut().set(0, 0, Cell::from_char('X'));

        // Previous should not reflect changes to current
        assert!(adb.previous().get(0, 0).unwrap().is_empty());
        assert_eq!(
            adb.current().get(0, 0).unwrap().content.as_char(),
            Some('X')
        );
    }

    #[test]
    fn adaptive_buffer_resize_within_capacity_clears_previous() {
        let mut adb = AdaptiveDoubleBuffer::new(10, 5);
        adb.current_mut().set(9, 4, Cell::from_char('X'));
        adb.swap();

        // Shrink within capacity (no reallocation expected)
        assert!(adb.resize(8, 4));

        // Previous buffer should be cleared to avoid stale content outside bounds.
        assert!(adb.previous().get(9, 4).unwrap().is_empty());
    }

    // Property tests for AdaptiveDoubleBuffer invariants
    #[test]
    fn adaptive_buffer_invariant_capacity_geq_logical() {
        // Test across various sizes that capacity always >= logical
        for width in [1u16, 10, 80, 200, 1000, 5000] {
            for height in [1u16, 10, 24, 100, 500, 2000] {
                let adb = AdaptiveDoubleBuffer::new(width, height);
                assert!(
                    adb.capacity_width() >= adb.width(),
                    "capacity_width {} < logical_width {} for ({}, {})",
                    adb.capacity_width(),
                    adb.width(),
                    width,
                    height
                );
                assert!(
                    adb.capacity_height() >= adb.height(),
                    "capacity_height {} < logical_height {} for ({}, {})",
                    adb.capacity_height(),
                    adb.height(),
                    width,
                    height
                );
            }
        }
    }

    #[test]
    fn adaptive_buffer_invariant_resize_dimensions_correct() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // After any resize, logical dimensions should match requested
        let test_sizes = [
            (100, 50),
            (40, 20),
            (80, 24),
            (200, 100),
            (10, 5),
            (1000, 500),
        ];
        for (w, h) in test_sizes {
            adb.resize(w, h);
            assert_eq!(adb.width(), w, "width mismatch for ({}, {})", w, h);
            assert_eq!(adb.height(), h, "height mismatch for ({}, {})", w, h);
            assert!(
                adb.capacity_width() >= w,
                "capacity_width < width for ({}, {})",
                w,
                h
            );
            assert!(
                adb.capacity_height() >= h,
                "capacity_height < height for ({}, {})",
                w,
                h
            );
        }
    }

    // Property test: no-ghosting on shrink
    // When buffer shrinks without reallocation, the current buffer is cleared
    // to prevent stale content from appearing in the visible area.
    #[test]
    fn adaptive_buffer_no_ghosting_on_shrink() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // Fill the entire logical area with content
        for y in 0..adb.height() {
            for x in 0..adb.width() {
                adb.current_mut().set(x, y, Cell::from_char('X'));
            }
        }

        // Shrink to a smaller size (still above 50% threshold, so no reallocation)
        // 80 * 0.5 = 40, so 60 > 40 means no reallocation
        adb.resize(60, 20);

        // Verify current buffer is cleared after shrink (no stale 'X' visible)
        // The current buffer should be empty because resize() calls clear()
        for y in 0..adb.height() {
            for x in 0..adb.width() {
                let cell = adb.current().get(x, y).unwrap();
                assert!(
                    cell.is_empty(),
                    "Ghost content at ({}, {}): expected empty, got {:?}",
                    x,
                    y,
                    cell.content
                );
            }
        }
    }

    // Property test: shrink-reallocation clears all content
    // When buffer shrinks below threshold (requiring reallocation), both buffers
    // should be fresh/empty.
    #[test]
    fn adaptive_buffer_no_ghosting_on_reallocation_shrink() {
        let mut adb = AdaptiveDoubleBuffer::new(100, 50);

        // Fill both buffers with content
        for y in 0..adb.height() {
            for x in 0..adb.width() {
                adb.current_mut().set(x, y, Cell::from_char('A'));
            }
        }
        adb.swap();
        for y in 0..adb.height() {
            for x in 0..adb.width() {
                adb.current_mut().set(x, y, Cell::from_char('B'));
            }
        }

        // Shrink below 50% threshold, forcing reallocation
        adb.resize(30, 15);
        assert_eq!(adb.stats().resize_reallocated, 1);

        // Both buffers should be fresh/empty
        for y in 0..adb.height() {
            for x in 0..adb.width() {
                assert!(
                    adb.current().get(x, y).unwrap().is_empty(),
                    "Ghost in current at ({}, {})",
                    x,
                    y
                );
                assert!(
                    adb.previous().get(x, y).unwrap().is_empty(),
                    "Ghost in previous at ({}, {})",
                    x,
                    y
                );
            }
        }
    }

    // Property test: growth preserves no-ghosting guarantee
    // When buffer grows beyond capacity (requiring reallocation), the new
    // capacity area should be empty.
    #[test]
    fn adaptive_buffer_no_ghosting_on_growth_reallocation() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);

        // Fill current buffer
        for y in 0..adb.height() {
            for x in 0..adb.width() {
                adb.current_mut().set(x, y, Cell::from_char('Z'));
            }
        }

        // Grow beyond capacity (100, 30) to force reallocation
        adb.resize(150, 60);
        assert_eq!(adb.stats().resize_reallocated, 1);

        // Entire new buffer should be empty
        for y in 0..adb.height() {
            for x in 0..adb.width() {
                assert!(
                    adb.current().get(x, y).unwrap().is_empty(),
                    "Ghost at ({}, {}) after growth reallocation",
                    x,
                    y
                );
            }
        }
    }

    // Property test: idempotence - same resize is no-op
    #[test]
    fn adaptive_buffer_resize_idempotent() {
        let mut adb = AdaptiveDoubleBuffer::new(80, 24);
        adb.current_mut().set(5, 5, Cell::from_char('K'));

        // Resize to same dimensions should be no-op
        let changed = adb.resize(80, 24);
        assert!(!changed);

        // Content should be preserved
        assert_eq!(
            adb.current().get(5, 5).unwrap().content.as_char(),
            Some('K')
        );
    }

    // =========================================================================
    // Dirty Span Tests (bd-3e1t.6.4)
    // =========================================================================

    #[test]
    fn dirty_span_merge_adjacent() {
        let mut buf = Buffer::new(100, 1);
        buf.clear_dirty(); // Start clean

        // Mark [10, 20) dirty
        buf.mark_dirty_span(0, 10, 20);
        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0], DirtySpan::new(10, 20));

        // Mark [20, 30) dirty (adjacent) -> merge
        buf.mark_dirty_span(0, 20, 30);
        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0], DirtySpan::new(10, 30));
    }

    #[test]
    fn dirty_span_merge_overlapping() {
        let mut buf = Buffer::new(100, 1);
        buf.clear_dirty();

        // Mark [10, 20)
        buf.mark_dirty_span(0, 10, 20);
        // Mark [15, 25) -> merge to [10, 25)
        buf.mark_dirty_span(0, 15, 25);

        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0], DirtySpan::new(10, 25));
    }

    #[test]
    fn dirty_span_merge_with_gap() {
        let mut buf = Buffer::new(100, 1);
        buf.clear_dirty();

        // DIRTY_SPAN_MERGE_GAP is 1
        // Mark [10, 20)
        buf.mark_dirty_span(0, 10, 20);
        // Mark [21, 30) -> gap is 1 (index 20) -> merge to [10, 30)
        buf.mark_dirty_span(0, 21, 30);

        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0], DirtySpan::new(10, 30));
    }

    #[test]
    fn dirty_span_no_merge_large_gap() {
        let mut buf = Buffer::new(100, 1);
        buf.clear_dirty();

        // Mark [10, 20)
        buf.mark_dirty_span(0, 10, 20);
        // Mark [22, 30) -> gap is 2 (indices 20, 21) -> no merge
        buf.mark_dirty_span(0, 22, 30);

        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert_eq!(spans.len(), 2);
        assert_eq!(spans[0], DirtySpan::new(10, 20));
        assert_eq!(spans[1], DirtySpan::new(22, 30));
    }

    #[test]
    fn dirty_span_overflow_to_full() {
        let mut buf = Buffer::new(1000, 1);
        buf.clear_dirty();

        // Create > 64 small spans separated by gaps
        for i in 0..DIRTY_SPAN_MAX_SPANS_PER_ROW + 10 {
            let start = (i * 4) as u16;
            buf.mark_dirty_span(0, start, start + 1);
        }

        let row = buf.dirty_span_row(0).unwrap();
        assert!(row.is_full(), "Row should overflow to full scan");
        assert!(
            row.spans().is_empty(),
            "Spans should be cleared on overflow"
        );
    }

    #[test]
    fn dirty_span_bounds_clamping() {
        let mut buf = Buffer::new(10, 1);
        buf.clear_dirty();

        // Mark out of bounds
        buf.mark_dirty_span(0, 15, 20);
        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert!(spans.is_empty());

        // Mark crossing bounds
        buf.mark_dirty_span(0, 8, 15);
        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0], DirtySpan::new(8, 10)); // Clamped to width
    }

    #[test]
    fn dirty_span_guard_band_clamps_bounds() {
        let mut buf = Buffer::new(10, 1);
        buf.clear_dirty();
        buf.set_dirty_span_config(DirtySpanConfig::default().with_guard_band(5));

        buf.mark_dirty_span(0, 2, 3);
        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0], DirtySpan::new(0, 8));

        buf.clear_dirty();
        buf.mark_dirty_span(0, 8, 10);
        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert_eq!(spans.len(), 1);
        assert_eq!(spans[0], DirtySpan::new(3, 10));
    }

    #[test]
    fn dirty_span_empty_span_is_ignored() {
        let mut buf = Buffer::new(10, 1);
        buf.clear_dirty();
        buf.mark_dirty_span(0, 5, 5);
        let spans = buf.dirty_span_row(0).unwrap().spans();
        assert!(spans.is_empty());
    }

    #[test]
    fn buffer_fill_wide_char_clipping() {
        // Regression test for wide character clipping during fill.
        // Verifies that wide characters are not written if they would be clipped,
        // and that previous wide characters are cleared correctly.
        let mut buf = Buffer::new(10, 5);
        let wide_cell = Cell::from_char('🦀'); // Width 2

        // 1. Fill with wide char
        buf.fill(Rect::new(0, 0, 10, 5), wide_cell);

        // Verify head and tail
        let head = buf.get(0, 0).unwrap();
        assert_eq!(head.content.as_char(), Some('🦀'));
        assert_eq!(head.content.width(), 2);

        let tail = buf.get(1, 0).unwrap();
        assert!(tail.is_continuation());

        // 2. Overwrite with clipping
        // Push a scissor that splits the wide char at (0,0)
        buf.push_scissor(Rect::new(0, 0, 1, 5));
        // Fill with 'X'
        let x_cell = Cell::from_char('X');
        buf.fill(Rect::new(0, 0, 10, 5), x_cell);

        // (0,0) should be 'X'. (1,0) should be cleared (orphaned tail).
        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('X'));
        assert!(buf.get(1, 0).unwrap().is_empty()); // Should be default/empty, not continuation

        buf.pop_scissor();
    }
}