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
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
#![forbid(unsafe_code)]

//! Presenter: state-tracked ANSI emission.
//!
//! The Presenter transforms buffer diffs into minimal terminal output by tracking
//! the current terminal state and only emitting sequences when changes are needed.
//!
//! # Design Principles
//!
//! - **State tracking**: Track current style, link, and cursor to avoid redundant output
//! - **Run grouping**: Use ChangeRuns to minimize cursor positioning
//! - **Single write**: Buffer all output and flush once per frame
//! - **Synchronized output**: Use DEC 2026 to prevent flicker on supported terminals
//!
//! # Usage
//!
//! ```ignore
//! use ftui_render::presenter::Presenter;
//! use ftui_render::buffer::Buffer;
//! use ftui_render::diff::BufferDiff;
//! use ftui_core::terminal_capabilities::TerminalCapabilities;
//!
//! let caps = TerminalCapabilities::detect();
//! let mut presenter = Presenter::new(std::io::stdout(), caps);
//!
//! let mut current = Buffer::new(80, 24);
//! let mut next = Buffer::new(80, 24);
//! // ... render widgets into `next` ...
//!
//! let diff = BufferDiff::compute(&current, &next);
//! presenter.present(&next, &diff)?;
//! std::mem::swap(&mut current, &mut next);
//! ```

use std::io::{self, BufWriter, Write};

use crate::ansi::{self, EraseLineMode};
use crate::buffer::Buffer;
use crate::cell::{Cell, CellAttrs, GraphemeId, PackedRgba, StyleFlags};
use crate::char_width;
use crate::counting_writer::{CountingWriter, PresentStats, StatsCollector};
use crate::diff::{BufferDiff, ChangeRun};
use crate::display_width;
use crate::grapheme_pool::GraphemePool;
use crate::link_registry::LinkRegistry;
use crate::sanitize::sanitize;

pub use ftui_core::terminal_capabilities::TerminalCapabilities;

/// Size of the internal write buffer (64KB).
const BUFFER_CAPACITY: usize = 64 * 1024;
/// Maximum hyperlink URL length allowed in OSC 8 payloads.
const MAX_SAFE_HYPERLINK_URL_BYTES: usize = 4096;

#[inline]
fn is_safe_hyperlink_url(url: &str) -> bool {
    url.len() <= MAX_SAFE_HYPERLINK_URL_BYTES && !url.chars().any(char::is_control)
}

// =============================================================================
// DP Cost Model for ANSI Emission
// =============================================================================

/// Byte-cost estimates for ANSI cursor and output operations.
///
/// The cost model computes the cheapest emission plan for each row by comparing
/// sparse-run emission (CUP per run) against merged write-through (one CUP,
/// fill gaps with buffer content). This is a shortest-path problem on a small
/// state graph per row.
mod cost_model {
    use smallvec::SmallVec;

    use super::ChangeRun;

    /// Number of decimal digits needed to represent `n`.
    #[inline]
    fn digit_count(n: u16) -> usize {
        // Terminal coordinates and relative deltas are overwhelmingly small.
        // Check the common low ranges first so the planner pays fewer compares
        // on its hottest cost-model path.
        if n < 10 {
            1
        } else if n < 100 {
            2
        } else if n < 1000 {
            3
        } else if n < 10000 {
            4
        } else {
            5
        }
    }

    /// Byte cost of CUP: `\x1b[{row+1};{col+1}H`
    #[inline]
    pub fn cup_cost(row: u16, col: u16) -> usize {
        // CSI (2) + row digits + ';' (1) + col digits + 'H' (1)
        4 + digit_count(row.saturating_add(1)) + digit_count(col.saturating_add(1))
    }

    /// Byte cost of CHA (column-only): `\x1b[{col+1}G`
    #[inline]
    pub fn cha_cost(col: u16) -> usize {
        // CSI (2) + col digits + 'G' (1)
        3 + digit_count(col.saturating_add(1))
    }

    /// Byte cost of CUF (cursor forward): `\x1b[{n}C` or `\x1b[C` for n=1.
    #[inline]
    pub fn cuf_cost(n: u16) -> usize {
        match n {
            0 => 0,
            1 => 3, // \x1b[C
            _ => 3 + digit_count(n),
        }
    }

    /// Byte cost of CUB (cursor back): `\x1b[{n}D` or `\x1b[D` for n=1.
    #[inline]
    pub fn cub_cost(n: u16) -> usize {
        match n {
            0 => 0,
            1 => 3, // \x1b[D
            _ => 3 + digit_count(n),
        }
    }

    /// Cheapest cursor movement cost from (from_x, from_y) to (to_x, to_y).
    /// Returns 0 if already at the target position.
    pub fn cheapest_move_cost(
        from_x: Option<u16>,
        from_y: Option<u16>,
        to_x: u16,
        to_y: u16,
    ) -> usize {
        // Already at target?
        if from_x == Some(to_x) && from_y == Some(to_y) {
            return 0;
        }

        match (from_x, from_y) {
            (Some(fx), Some(fy)) if fy == to_y => {
                // On the same row, CHA strictly dominates CUP because CUP always
                // pays the extra row field (`CSI row;col H`) while CHA only
                // updates the column (`CSI col G`). Therefore the optimal move
                // on a shared row is always CHA or a relative move.
                let cha = cha_cost(to_x);
                if to_x > fx {
                    let cuf = cuf_cost(to_x - fx);
                    cha.min(cuf)
                } else if to_x < fx {
                    let cub = cub_cost(fx - to_x);
                    cha.min(cub)
                } else {
                    0
                }
            }
            _ => cup_cost(to_y, to_x),
        }
    }

    /// Planned contiguous span to emit on a single row.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct RowSpan {
        /// Row index.
        pub y: u16,
        /// Start column (inclusive).
        pub x0: u16,
        /// End column (inclusive).
        pub x1: u16,
    }

    /// Row emission plan (possibly multiple merged spans).
    ///
    /// Uses SmallVec<[RowSpan; 8]> to avoid heap allocation for the common case
    /// of sparse rows with several isolated runs. RowSpan is 6 bytes, so
    /// 8 spans = 48 bytes inline.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct RowPlan {
        spans: SmallVec<[RowSpan; 8]>,
        total_cost: usize,
    }

    impl RowPlan {
        #[inline]
        #[must_use]
        pub fn spans(&self) -> &[RowSpan] {
            &self.spans
        }

        /// Total cost of this row plan (for strategy selection).
        #[inline]
        #[allow(dead_code)] // API for future diff strategy integration
        pub fn total_cost(&self) -> usize {
            self.total_cost
        }
    }

    /// Reusable scratch buffers for `plan_row_reuse`, avoiding per-call heap
    /// allocations. Store one instance in `Presenter` and pass it into every
    /// `plan_row_reuse` call so that the buffers are reused across rows and
    /// frames.
    #[derive(Debug, Default)]
    pub struct RowPlanScratch {
        prefix_cells: Vec<usize>,
        dp: Vec<usize>,
        prev: Vec<usize>,
    }

    /// Compute the optimal emission plan for a set of runs on the same row.
    ///
    /// This is a shortest-path / DP partitioning problem over contiguous run
    /// segments. Each segment may be emitted as a merged span (writing through
    /// gaps). Single-run segments correspond to sparse emission.
    ///
    /// Gap cells cost ~1 byte each (character content), plus potential style
    /// overhead estimated at 1 byte per gap cell (conservative).
    #[allow(dead_code)]
    pub fn plan_row(row_runs: &[ChangeRun], prev_x: Option<u16>, prev_y: Option<u16>) -> RowPlan {
        let mut scratch = RowPlanScratch::default();
        plan_row_reuse(row_runs, prev_x, prev_y, &mut scratch)
    }

    /// Like `plan_row` but reuses heap allocations via the provided scratch
    /// buffers, eliminating per-call allocations in the hot path.
    pub fn plan_row_reuse(
        row_runs: &[ChangeRun],
        prev_x: Option<u16>,
        prev_y: Option<u16>,
        scratch: &mut RowPlanScratch,
    ) -> RowPlan {
        if row_runs.is_empty() {
            return RowPlan {
                spans: SmallVec::new(),
                total_cost: 0,
            };
        }

        let row_y = row_runs[0].y;
        let run_count = row_runs.len();

        if run_count == 1 {
            let run = row_runs[0];
            let mut spans: SmallVec<[RowSpan; 8]> = SmallVec::new();
            spans.push(RowSpan {
                y: row_y,
                x0: run.x0,
                x1: run.x1,
            });
            return RowPlan {
                spans,
                total_cost: cheapest_move_cost(prev_x, prev_y, run.x0, row_y)
                    .saturating_add(run.len()),
            };
        }

        // Resize scratch buffers (no-op if already large enough).
        scratch.prefix_cells.clear();
        scratch.prefix_cells.resize(run_count + 1, 0);
        scratch.dp.clear();
        scratch.dp.resize(run_count, usize::MAX);
        scratch.prev.clear();
        scratch.prev.resize(run_count, 0);

        // Prefix sum of changed cell counts for O(1) segment cost.
        for (i, run) in row_runs.iter().enumerate() {
            scratch.prefix_cells[i + 1] = scratch.prefix_cells[i] + run.len();
        }

        // DP over segments: dp[j] is min cost to emit runs[0..=j].
        for j in 0..run_count {
            let mut best_cost = usize::MAX;
            let mut best_i = j;

            // Optimization: iterate backwards and break if the gap becomes too large.
            // The gap cost grows linearly, while cursor movement cost is bounded (~10-15 bytes).
            // Once the gap exceeds ~20 cells, merging is strictly worse than moving.
            // We use 32 as a conservative safety bound.
            for i in (0..=j).rev() {
                let changed_cells = scratch.prefix_cells[j + 1] - scratch.prefix_cells[i];
                let total_cells =
                    (row_runs[j].x1 as usize).saturating_sub(row_runs[i].x0 as usize) + 1;
                let gap_cells = total_cells.saturating_sub(changed_cells);

                if gap_cells > 32 {
                    break;
                }

                let from_x = if i == 0 {
                    prev_x
                } else {
                    Some(row_runs[i - 1].x1.saturating_add(1))
                };
                let from_y = if i == 0 { prev_y } else { Some(row_y) };

                let move_cost = cheapest_move_cost(from_x, from_y, row_runs[i].x0, row_y);
                let gap_overhead = gap_cells * 2; // conservative: char + style amortized
                let emit_cost = changed_cells + gap_overhead;

                let prev_cost = if i == 0 { 0 } else { scratch.dp[i - 1] };
                let cost = prev_cost
                    .saturating_add(move_cost)
                    .saturating_add(emit_cost);

                if cost < best_cost {
                    best_cost = cost;
                    best_i = i;
                }
            }

            scratch.dp[j] = best_cost;
            scratch.prev[j] = best_i;
        }

        // Reconstruct spans from back to front.
        let mut spans: SmallVec<[RowSpan; 8]> = SmallVec::new();
        let mut j = run_count - 1;
        loop {
            let i = scratch.prev[j];
            spans.push(RowSpan {
                y: row_y,
                x0: row_runs[i].x0,
                x1: row_runs[j].x1,
            });
            if i == 0 {
                break;
            }
            j = i - 1;
        }
        spans.reverse();

        RowPlan {
            spans,
            total_cost: scratch.dp[run_count - 1],
        }
    }
}

/// Cached style state for comparison.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CellStyle {
    fg: PackedRgba,
    bg: PackedRgba,
    attrs: StyleFlags,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PreparedContent {
    Empty,
    Char(char),
    Grapheme(GraphemeId),
}

impl PreparedContent {
    #[inline]
    fn from_cell(cell: &Cell) -> (Self, usize) {
        let content = cell.content;
        if let Some(grapheme_id) = content.grapheme_id() {
            (Self::Grapheme(grapheme_id), content.width())
        } else if let Some(ch) = content.as_char() {
            let width = if ch.is_ascii() {
                match ch {
                    '\t' | '\n' | '\r' => 1,
                    ' '..='~' => 1,
                    _ => 0,
                }
            } else {
                char_width(ch)
            };
            (Self::Char(ch), width)
        } else {
            (Self::Empty, 0)
        }
    }
}

impl Default for CellStyle {
    fn default() -> Self {
        Self {
            fg: PackedRgba::TRANSPARENT,
            bg: PackedRgba::TRANSPARENT,
            attrs: StyleFlags::empty(),
        }
    }
}
impl CellStyle {
    fn from_cell(cell: &Cell) -> Self {
        Self {
            fg: cell.fg,
            bg: cell.bg,
            attrs: cell.attrs.flags(),
        }
    }
}

/// State-tracked ANSI presenter.
///
/// Transforms buffer diffs into minimal terminal output by tracking
/// the current terminal state and only emitting necessary escape sequences.
pub struct Presenter<W: Write> {
    /// Buffered writer for efficient output, with byte counting.
    writer: CountingWriter<BufWriter<W>>,
    /// Current style state (None = unknown/reset).
    current_style: Option<CellStyle>,
    /// Current hyperlink ID (None = no link).
    current_link: Option<u32>,
    /// Current cursor X position (0-indexed). None = unknown.
    cursor_x: Option<u16>,
    /// Current cursor Y position (0-indexed). None = unknown.
    cursor_y: Option<u16>,
    /// Viewport Y offset (added to all row coordinates).
    viewport_offset_y: u16,
    /// Terminal capabilities for conditional output.
    capabilities: TerminalCapabilities,
    /// Cached hyperlink policy for the lifetime of this presenter.
    hyperlinks_enabled: bool,
    /// Reusable scratch buffers for the cost-model DP, avoiding per-row
    /// heap allocations in the hot presentation path.
    plan_scratch: cost_model::RowPlanScratch,
    /// Reusable buffer for change runs, avoiding per-frame allocation.
    runs_buf: Vec<ChangeRun>,
}

impl<W: Write> Presenter<W> {
    /// Create a new presenter with the given writer and capabilities.
    pub fn new(writer: W, capabilities: TerminalCapabilities) -> Self {
        Self {
            writer: CountingWriter::new(BufWriter::with_capacity(BUFFER_CAPACITY, writer)),
            current_style: None,
            current_link: None,
            cursor_x: None,
            cursor_y: None,
            viewport_offset_y: 0,
            hyperlinks_enabled: capabilities.use_hyperlinks(),
            capabilities,
            plan_scratch: cost_model::RowPlanScratch::default(),
            runs_buf: Vec::new(),
        }
    }

    /// Get mutable access to the innermost writer (`W`).
    ///
    /// This allows the caller to write raw data (e.g. logs) bypassing the
    /// presenter's state tracking. Note that this may invalidate cursor
    /// tracking if the raw writes move the cursor.
    pub fn writer_mut(&mut self) -> &mut W {
        self.writer.inner_mut().get_mut()
    }

    /// Get mutable access to the full counting writer stack.
    ///
    /// This exposes `CountingWriter<BufWriter<W>>` so callers can access
    /// byte counting, buffered flush, etc.
    pub fn counting_writer_mut(&mut self) -> &mut CountingWriter<BufWriter<W>> {
        &mut self.writer
    }

    /// Set the viewport Y offset.
    ///
    /// All subsequent render operations will add this offset to row coordinates.
    /// Useful for inline mode where the UI starts at a specific row.
    pub fn set_viewport_offset_y(&mut self, offset: u16) {
        self.viewport_offset_y = offset;
    }

    /// Get the terminal capabilities.
    #[inline]
    pub fn capabilities(&self) -> &TerminalCapabilities {
        &self.capabilities
    }

    /// Present a frame using the given buffer and diff.
    ///
    /// This is the main entry point for rendering. It:
    /// 1. Begins synchronized output (if supported)
    /// 2. Emits changes based on the diff
    /// 3. Resets style and closes links
    /// 4. Ends synchronized output
    /// 5. Flushes all buffered output
    pub fn present(&mut self, buffer: &Buffer, diff: &BufferDiff) -> io::Result<PresentStats> {
        self.present_with_pool(buffer, diff, None, None)
    }

    /// Present a frame with grapheme pool and link registry.
    pub fn present_with_pool(
        &mut self,
        buffer: &Buffer,
        diff: &BufferDiff,
        pool: Option<&GraphemePool>,
        links: Option<&LinkRegistry>,
    ) -> io::Result<PresentStats> {
        let bracket_supported = self.capabilities.use_sync_output();

        #[cfg(feature = "tracing")]
        let _span = tracing::info_span!(
            "present",
            width = buffer.width(),
            height = buffer.height(),
            changes = diff.len()
        );
        #[cfg(feature = "tracing")]
        let _guard = _span.enter();

        #[cfg(feature = "tracing")]
        let fallback_used = !bracket_supported;
        #[cfg(feature = "tracing")]
        let _sync_span = tracing::info_span!(
            "render.sync_bracket",
            bracket_supported,
            fallback_used,
            frame_bytes = tracing::field::Empty,
        );
        #[cfg(feature = "tracing")]
        let _sync_guard = _sync_span.enter();

        // Calculate runs upfront for stats, reusing the runs buffer.
        diff.runs_into(&mut self.runs_buf);
        let run_count = self.runs_buf.len();
        let cells_changed = diff.len();

        // Start stats collection
        self.writer.reset_counter();
        let collector = StatsCollector::start(cells_changed, run_count);

        // Begin synchronized output to prevent flicker.
        // When sync brackets are supported, use DEC 2026 for atomic frame display.
        // Otherwise, fall back to cursor-hiding to reduce visual flicker.
        if bracket_supported {
            if let Err(err) = ansi::sync_begin(&mut self.writer) {
                // Begin writes can fail after partial bytes; best-effort close
                // avoids leaving the terminal parser in sync-output mode.
                let _ = ansi::sync_end(&mut self.writer);
                let _ = self.writer.flush();
                return Err(err);
            }
        } else {
            #[cfg(feature = "tracing")]
            tracing::warn!("sync brackets unsupported; falling back to cursor-hide strategy");
            ansi::cursor_hide(&mut self.writer)?;
        }

        // Emit diff using run grouping for efficiency.
        let emit_result = self.emit_diff_runs(buffer, pool, links);

        // Always attempt to restore terminal state, even if diff emission failed.
        let frame_end_result = self.finish_frame();

        let bracket_end_result = if bracket_supported {
            ansi::sync_end(&mut self.writer)
        } else {
            ansi::cursor_show(&mut self.writer)
        };

        let flush_result = self.writer.flush();

        // Prioritize terminal-state restoration errors over emission errors:
        // if cleanup fails (reset/link-close/sync-end/flush), callers need that
        // failure surfaced immediately to avoid leaving the terminal wedged.
        let cleanup_error = frame_end_result
            .err()
            .or_else(|| bracket_end_result.err())
            .or_else(|| flush_result.err());
        if let Some(err) = cleanup_error {
            return Err(err);
        }
        emit_result?;

        let stats = collector.finish(self.writer.bytes_written());

        #[cfg(feature = "tracing")]
        {
            _sync_span.record("frame_bytes", stats.bytes_emitted);
            stats.log();
            tracing::trace!("frame presented");
        }

        Ok(stats)
    }

    /// Emit diff runs using the cost model and internal buffers.
    ///
    /// This allows advanced callers (like TerminalWriter) to drive the emission
    /// phase manually while still benefiting from the optimization logic.
    /// The caller must populate `self.runs_buf` before calling this (e.g. via `diff.runs_into`).
    pub fn emit_diff_runs(
        &mut self,
        buffer: &Buffer,
        pool: Option<&GraphemePool>,
        links: Option<&LinkRegistry>,
    ) -> io::Result<()> {
        #[cfg(feature = "tracing")]
        let _span = tracing::debug_span!("emit_diff");
        #[cfg(feature = "tracing")]
        let _guard = _span.enter();

        #[cfg(feature = "tracing")]
        tracing::trace!(run_count = self.runs_buf.len(), "emitting runs (reuse)");

        // Group runs by row and apply cost model per row
        let mut i = 0;
        while i < self.runs_buf.len() {
            let row_y = self.runs_buf[i].y;

            // Collect all runs on this row
            let row_start = i;
            while i < self.runs_buf.len() && self.runs_buf[i].y == row_y {
                i += 1;
            }
            let row_runs = &self.runs_buf[row_start..i];

            let plan = cost_model::plan_row_reuse(
                row_runs,
                self.cursor_x,
                self.cursor_y,
                &mut self.plan_scratch,
            );

            #[cfg(feature = "tracing")]
            tracing::trace!(
                row = row_y,
                spans = plan.spans().len(),
                cost = plan.total_cost(),
                "row plan"
            );

            let row = buffer.row_cells(row_y);
            for span in plan.spans() {
                self.move_cursor_optimal(span.x0, span.y)?;
                // Hot path: avoid recomputing `y * width + x` for every cell.
                let start = span.x0 as usize;
                let end = span.x1 as usize;
                debug_assert!(start <= end);
                debug_assert!(end < row.len());
                let mut idx = start;
                while idx <= end {
                    let cell = &row[idx];
                    self.emit_cell(idx as u16, cell, pool, links)?;

                    // Repair invalid wide-char tails.
                    //
                    // Direct wide chars are always safe to repair because they can
                    // only span a small, fixed number of cells. Grapheme-pool refs
                    // may encode much wider payloads (up to 15 cells), so blindly
                    // repairing all missing tails can erase unrelated content later in
                    // the row. We only extend the repair to width-2 grapheme refs,
                    // where clearing a single orphan tail cell is still bounded.
                    let mut advance = 1usize;
                    let width = cell.content.width();
                    let should_repair_invalid_tail = cell.content.as_char().is_some()
                        || (cell.content.is_grapheme() && width == 2);
                    if width > 1 && should_repair_invalid_tail {
                        for off in 1..width {
                            let tx = idx + off;
                            if tx >= row.len() {
                                break;
                            }
                            if row[tx].is_continuation() {
                                if tx <= end {
                                    advance = advance.max(off + 1);
                                }
                                continue;
                            }
                            // Orphan detected: repair with a space.
                            self.move_cursor_optimal(tx as u16, span.y)?;
                            self.emit_orphan_continuation_space(tx as u16, links)?;
                            if tx <= end {
                                advance = advance.max(off + 1);
                            }
                        }
                    }

                    idx = idx.saturating_add(advance);
                }
            }
        }
        Ok(())
    }

    /// Prepare the runs buffer from a diff.
    ///
    /// Helper for external callers to populate the runs buffer before calling `emit_diff_runs`.
    pub fn prepare_runs(&mut self, diff: &BufferDiff) {
        diff.runs_into(&mut self.runs_buf);
    }

    /// Finish a frame by restoring neutral SGR state and closing any open link.
    ///
    /// Callers that drive emission manually through [`emit_diff_runs`] must
    /// invoke this before returning control to non-UI terminal output.
    pub fn finish_frame(&mut self) -> io::Result<()> {
        let reset_result = ansi::sgr_reset(&mut self.writer);
        self.current_style = None;

        let hyperlink_close_result = if self.current_link.is_some() {
            let res = ansi::hyperlink_end(&mut self.writer);
            if res.is_ok() {
                self.current_link = None;
            }
            Some(res)
        } else {
            None
        };

        if let Some(err) = reset_result
            .err()
            .or_else(|| hyperlink_close_result.and_then(Result::err))
        {
            return Err(err);
        }

        Ok(())
    }

    /// Best-effort frame cleanup used on error and drop paths.
    pub fn finish_frame_best_effort(&mut self) {
        let _ = ansi::sgr_reset(&mut self.writer);
        self.current_style = None;

        if self.current_link.is_some() {
            let _ = ansi::hyperlink_end(&mut self.writer);
            self.current_link = None;
        }
    }

    /// Emit a single cell.
    fn emit_cell(
        &mut self,
        x: u16,
        cell: &Cell,
        pool: Option<&GraphemePool>,
        links: Option<&LinkRegistry>,
    ) -> io::Result<()> {
        // Drift protection: Ensure cursor is synchronized before emitting content.
        // This catches cases where the previous emission (e.g. a wide char) advanced
        // the cursor further than the buffer index advanced (e.g. because the
        // continuation cell was missing/overwritten in an invalid buffer state).
        //
        // If we detect drift, we force a re-synchronization.
        if let Some(cx) = self.cursor_x {
            if cx != x && !cell.is_continuation() {
                // Re-sync. We assume cursor_y is set because we are in a run.
                if let Some(y) = self.cursor_y {
                    self.move_cursor_optimal(x, y)?;
                }
            }
        } else {
            // No known cursor position: must sync.
            if let Some(y) = self.cursor_y {
                self.move_cursor_optimal(x, y)?;
            }
        }

        // Continuation cells are the tail cells of wide glyphs. Emitting the
        // head glyph already advanced the terminal cursor by the full width, so
        // we normally skip emitting these cells.
        //
        // If we ever start emitting at a continuation cell (e.g. a run begins
        // mid-wide-character), we must still advance the terminal cursor by one
        // cell to keep subsequent emissions aligned. We write a space to clear
        // any potential garbage (orphan cleanup) rather than just skipping with CUF.
        if cell.is_continuation() {
            match self.cursor_x {
                // Cursor already advanced past this cell by a previously-emitted wide head.
                Some(cx) if cx > x => return Ok(()),
                Some(cx) => {
                    // Cursor is positioned at (or before) this continuation cell:
                    // Treat as orphan and overwrite with space to ensure clean state.
                    if cx < x
                        && let Some(y) = self.cursor_y
                    {
                        self.move_cursor_optimal(x, y)?;
                    }
                    return self.emit_orphan_continuation_space(x, links);
                }
                // Defensive: move_cursor_optimal should always set cursor_x before emit_cell is called.
                None => {
                    if let Some(y) = self.cursor_y {
                        self.move_cursor_optimal(x, y)?;
                    }
                    return self.emit_orphan_continuation_space(x, links);
                }
            }
        }

        // Emit style changes if needed
        self.emit_style_changes(cell)?;

        // Emit link changes if needed
        self.emit_link_changes(cell, links)?;

        let (prepared_content, raw_width) = PreparedContent::from_cell(cell);

        // Calculate effective width and check for zero-width content (e.g. combining marks)
        // stored as standalone cells. These must be replaced to maintain grid alignment.
        let is_zero_width_content = raw_width == 0 && !cell.is_empty() && !cell.is_continuation();

        if is_zero_width_content {
            // Replace with U+FFFD Replacement Character (width 1)
            self.writer.write_all(b"\xEF\xBF\xBD")?;
        } else {
            // Emit normal content
            self.emit_content(prepared_content, raw_width, pool)?;
        }

        // Update cursor position (character output advances cursor)
        if let Some(cx) = self.cursor_x {
            // Empty cells are emitted as spaces (width 1).
            // Zero-width content replaced by U+FFFD is width 1.
            let width = if cell.is_empty() || is_zero_width_content {
                1
            } else {
                raw_width
            };
            self.cursor_x = Some(cx.saturating_add(width as u16));
        }

        Ok(())
    }

    /// Clear a continuation cell with a visually neutral blank.
    ///
    /// This path intentionally resets style and closes hyperlinks first so the
    /// cleanup space cannot inherit stale state from the previous emitted cell.
    fn emit_orphan_continuation_space(
        &mut self,
        x: u16,
        links: Option<&LinkRegistry>,
    ) -> io::Result<()> {
        let blank = Cell::default();
        self.emit_style_changes(&blank)?;
        self.emit_link_changes(&blank, links)?;
        self.writer.write_all(b" ")?;
        self.cursor_x = Some(x.saturating_add(1));
        Ok(())
    }

    /// Emit style changes if the cell style differs from current.
    ///
    /// Uses SGR delta: instead of resetting and re-applying all style properties,
    /// we compute the minimal set of changes needed (fg delta, bg delta, attr
    /// toggles). Falls back to reset+apply only when a full reset would be cheaper.
    fn emit_style_changes(&mut self, cell: &Cell) -> io::Result<()> {
        let new_style = CellStyle::from_cell(cell);

        // Check if style changed
        if self.current_style == Some(new_style) {
            return Ok(());
        }

        match self.current_style {
            None => {
                // No known style state: re-establish a full terminal style baseline.
                self.emit_style_full(new_style)?;
            }
            Some(old_style) => {
                self.emit_style_delta(old_style, new_style)?;
            }
        }

        self.current_style = Some(new_style);
        Ok(())
    }

    /// Full style apply (reset + set all properties). Used when previous state is unknown.
    fn emit_style_full(&mut self, style: CellStyle) -> io::Result<()> {
        ansi::sgr_reset(&mut self.writer)?;
        if style.fg.a() > 0 {
            ansi::sgr_fg_packed(&mut self.writer, style.fg)?;
        }
        if style.bg.a() > 0 {
            ansi::sgr_bg_packed(&mut self.writer, style.bg)?;
        }
        if !style.attrs.is_empty() {
            ansi::sgr_flags(&mut self.writer, style.attrs)?;
        }
        Ok(())
    }

    #[inline]
    fn dec_len_u8(value: u8) -> u32 {
        if value >= 100 {
            3
        } else if value >= 10 {
            2
        } else {
            1
        }
    }

    #[inline]
    fn sgr_code_len(code: u8) -> u32 {
        2 + Self::dec_len_u8(code) + 1
    }

    #[inline]
    fn sgr_flags_len(flags: StyleFlags) -> u32 {
        if flags.is_empty() {
            return 0;
        }
        let mut count = 0u32;
        let mut digits = 0u32;
        for (flag, codes) in ansi::FLAG_TABLE {
            if flags.contains(flag) {
                count += 1;
                digits += Self::dec_len_u8(codes.on);
            }
        }
        if count == 0 {
            return 0;
        }
        3 + digits + (count - 1)
    }

    #[inline]
    fn sgr_flags_off_len(flags: StyleFlags) -> u32 {
        if flags.is_empty() {
            return 0;
        }
        let mut len = 0u32;
        for (flag, codes) in ansi::FLAG_TABLE {
            if flags.contains(flag) {
                len += Self::sgr_code_len(codes.off);
            }
        }
        len
    }

    #[inline]
    fn sgr_rgb_len(color: PackedRgba) -> u32 {
        10 + Self::dec_len_u8(color.r()) + Self::dec_len_u8(color.g()) + Self::dec_len_u8(color.b())
    }

    /// Emit minimal SGR delta between old and new styles.
    ///
    /// Computes which properties changed and emits only those.
    /// Falls back to reset+apply when that would produce fewer bytes.
    fn emit_style_delta(&mut self, old: CellStyle, new: CellStyle) -> io::Result<()> {
        let attrs_removed = old.attrs & !new.attrs;
        let attrs_added = new.attrs & !old.attrs;
        let fg_changed = old.fg != new.fg;
        let bg_changed = old.bg != new.bg;

        // Hot path for VFX-style workloads: attributes are unchanged and only
        // colors vary. In this case, delta emission is always no worse than a
        // reset+reapply baseline, so skip cost estimation and flag diff logic.
        if old.attrs == new.attrs {
            if fg_changed {
                ansi::sgr_fg_packed(&mut self.writer, new.fg)?;
            }
            if bg_changed {
                ansi::sgr_bg_packed(&mut self.writer, new.bg)?;
            }
            return Ok(());
        }

        let mut collateral = StyleFlags::empty();
        if attrs_removed.contains(StyleFlags::BOLD) && new.attrs.contains(StyleFlags::DIM) {
            collateral |= StyleFlags::DIM;
        }
        if attrs_removed.contains(StyleFlags::DIM) && new.attrs.contains(StyleFlags::BOLD) {
            collateral |= StyleFlags::BOLD;
        }

        let mut delta_len = 0u32;
        delta_len += Self::sgr_flags_off_len(attrs_removed);
        delta_len += Self::sgr_flags_len(collateral);
        delta_len += Self::sgr_flags_len(attrs_added);
        if fg_changed {
            delta_len += if new.fg.a() == 0 {
                5
            } else {
                Self::sgr_rgb_len(new.fg)
            };
        }
        if bg_changed {
            delta_len += if new.bg.a() == 0 {
                5
            } else {
                Self::sgr_rgb_len(new.bg)
            };
        }

        let mut baseline_len = 4u32;
        if new.fg.a() > 0 {
            baseline_len += Self::sgr_rgb_len(new.fg);
        }
        if new.bg.a() > 0 {
            baseline_len += Self::sgr_rgb_len(new.bg);
        }
        baseline_len += Self::sgr_flags_len(new.attrs);

        if delta_len > baseline_len {
            return self.emit_style_full(new);
        }

        // Handle attr removal: emit individual off codes
        if !attrs_removed.is_empty() {
            let collateral = ansi::sgr_flags_off(&mut self.writer, attrs_removed, new.attrs)?;
            // Re-enable any collaterally disabled flags
            if !collateral.is_empty() {
                ansi::sgr_flags(&mut self.writer, collateral)?;
            }
        }

        // Handle attr addition: emit on codes for newly added flags
        if !attrs_added.is_empty() {
            ansi::sgr_flags(&mut self.writer, attrs_added)?;
        }

        // Handle fg color change
        if fg_changed {
            ansi::sgr_fg_packed(&mut self.writer, new.fg)?;
        }

        // Handle bg color change
        if bg_changed {
            ansi::sgr_bg_packed(&mut self.writer, new.bg)?;
        }

        Ok(())
    }

    /// Emit hyperlink changes if the cell link differs from current.
    fn emit_link_changes(&mut self, cell: &Cell, links: Option<&LinkRegistry>) -> io::Result<()> {
        // Respect capability policy so callers running in mux contexts don't
        // emit OSC 8 sequences even if the raw capability flag is set.
        if !self.hyperlinks_enabled {
            if self.current_link.is_none() {
                return Ok(());
            }
            if self.current_link.is_some() {
                ansi::hyperlink_end(&mut self.writer)?;
            }
            self.current_link = None;
            return Ok(());
        }

        let raw_link_id = cell.attrs.link_id();
        let new_link = if raw_link_id == CellAttrs::LINK_ID_NONE {
            None
        } else {
            Some(raw_link_id)
        };

        // Check if link changed
        if self.current_link == new_link {
            return Ok(());
        }

        // Close current link if open
        if self.current_link.is_some() {
            ansi::hyperlink_end(&mut self.writer)?;
        }

        // Open new link if present and resolvable
        let actually_opened = if let (Some(link_id), Some(registry)) = (new_link, links)
            && let Some(url) = registry.get(link_id)
            && is_safe_hyperlink_url(url)
        {
            ansi::hyperlink_start(&mut self.writer, url)?;
            true
        } else {
            false
        };

        // Only track as current if we actually opened it
        self.current_link = if actually_opened { new_link } else { None };
        Ok(())
    }

    /// Emit cell content after width/content classification.
    fn emit_content(
        &mut self,
        content: PreparedContent,
        raw_width: usize,
        pool: Option<&GraphemePool>,
    ) -> io::Result<()> {
        match content {
            PreparedContent::Grapheme(grapheme_id) => {
                if let Some(pool) = pool
                    && let Some(text) = pool.get(grapheme_id)
                {
                    let safe = sanitize(text);
                    if !safe.is_empty() && display_width(safe.as_ref()) == raw_width {
                        return self.writer.write_all(safe.as_bytes());
                    }
                }
                // Fallback when sanitization strips bytes or changes display width:
                // emit width-1 placeholders so the terminal cursor advances by the
                // exact number of cells encoded in the grapheme ID.
                if raw_width > 0 {
                    for _ in 0..raw_width {
                        self.writer.write_all(b"?")?;
                    }
                }
                Ok(())
            }
            PreparedContent::Char(ch) => {
                if ch.is_ascii() {
                    // Width-0 ASCII controls are filtered earlier via the
                    // replacement-character path. The remaining ASCII controls
                    // here are width-1 (`\n`/`\r`) and must still sanitize to
                    // a visually neutral single cell.
                    let byte = if ch.is_ascii_control() {
                        b' '
                    } else {
                        ch as u8
                    };
                    return self.writer.write_all(&[byte]);
                }
                // Sanitize control characters that would break the grid.
                let safe_ch = if ch.is_control() { ' ' } else { ch };
                let mut buf = [0u8; 4];
                let encoded = safe_ch.encode_utf8(&mut buf);
                self.writer.write_all(encoded.as_bytes())
            }
            PreparedContent::Empty => {
                // Empty cell - emit space
                self.writer.write_all(b" ")
            }
        }
    }

    /// Move cursor to the specified position.
    fn move_cursor_to(&mut self, x: u16, y: u16) -> io::Result<()> {
        // Skip if already at position
        if self.cursor_x == Some(x) && self.cursor_y == Some(y) {
            return Ok(());
        }

        // Use CUP (cursor position) for absolute positioning
        ansi::cup(
            &mut self.writer,
            y.saturating_add(self.viewport_offset_y),
            x,
        )?;
        self.cursor_x = Some(x);
        self.cursor_y = Some(y);
        Ok(())
    }

    /// Move cursor using the cheapest available operation.
    ///
    /// Compares CUP (absolute), CHA (column-only), and CUF/CUB (relative)
    /// to select the minimum-cost cursor movement.
    fn move_cursor_optimal(&mut self, x: u16, y: u16) -> io::Result<()> {
        // Skip if already at position
        if self.cursor_x == Some(x) && self.cursor_y == Some(y) {
            return Ok(());
        }

        // Decide cheapest move
        let same_row = self.cursor_y == Some(y);
        let actual_y = y.saturating_add(self.viewport_offset_y);

        if same_row {
            if let Some(cx) = self.cursor_x {
                if x > cx {
                    // Forward
                    let dx = x - cx;
                    let cuf = cost_model::cuf_cost(dx);
                    let cha = cost_model::cha_cost(x);
                    let cup = cost_model::cup_cost(actual_y, x);

                    if cuf <= cha && cuf <= cup {
                        ansi::cuf(&mut self.writer, dx)?;
                    } else if cha <= cup {
                        ansi::cha(&mut self.writer, x)?;
                    } else {
                        ansi::cup(&mut self.writer, actual_y, x)?;
                    }
                } else if x < cx {
                    // Backward
                    let dx = cx - x;
                    let cub = cost_model::cub_cost(dx);
                    let cha = cost_model::cha_cost(x);
                    let cup = cost_model::cup_cost(actual_y, x);

                    if cha <= cub && cha <= cup {
                        ansi::cha(&mut self.writer, x)?;
                    } else if cub <= cup {
                        ansi::cub(&mut self.writer, dx)?;
                    } else {
                        ansi::cup(&mut self.writer, actual_y, x)?;
                    }
                } else {
                    // Same column (should have been caught by early check, but for safety)
                }
            } else {
                // Unknown x, same row (unlikely but possible if we only tracked y?)
                // Fallback to absolute
                ansi::cup(&mut self.writer, actual_y, x)?;
            }
        } else {
            // Different row: CUP is the only option
            ansi::cup(&mut self.writer, actual_y, x)?;
        }

        self.cursor_x = Some(x);
        self.cursor_y = Some(y);
        Ok(())
    }

    /// Clear the entire screen.
    pub fn clear_screen(&mut self) -> io::Result<()> {
        ansi::erase_display(&mut self.writer, ansi::EraseDisplayMode::All)?;
        ansi::cup(&mut self.writer, 0, 0)?;
        self.cursor_x = Some(0);
        self.cursor_y = Some(0);
        self.writer.flush()
    }

    /// Clear a single line.
    pub fn clear_line(&mut self, y: u16) -> io::Result<()> {
        self.move_cursor_to(0, y)?;
        ansi::erase_line(&mut self.writer, EraseLineMode::All)?;
        self.writer.flush()
    }

    /// Hide the cursor.
    pub fn hide_cursor(&mut self) -> io::Result<()> {
        ansi::cursor_hide(&mut self.writer)?;
        self.writer.flush()
    }

    /// Show the cursor.
    pub fn show_cursor(&mut self) -> io::Result<()> {
        ansi::cursor_show(&mut self.writer)?;
        self.writer.flush()
    }

    /// Position the cursor at the specified coordinates.
    pub fn position_cursor(&mut self, x: u16, y: u16) -> io::Result<()> {
        self.move_cursor_to(x, y)?;
        self.writer.flush()
    }

    /// Reset the presenter state.
    ///
    /// Useful after resize or when terminal state is unknown.
    pub fn reset(&mut self) {
        self.current_style = None;
        self.current_link = None;
        self.cursor_x = None;
        self.cursor_y = None;
    }

    /// Flush any buffered output.
    pub fn flush(&mut self) -> io::Result<()> {
        self.writer.flush()
    }

    /// Get the inner writer (consuming the presenter).
    ///
    /// Flushes any buffered data before returning the writer.
    pub fn into_inner(self) -> Result<W, io::Error> {
        self.writer
            .into_inner() // CountingWriter -> BufWriter<W>
            .into_inner() // BufWriter<W> -> Result<W, IntoInnerError>
            .map_err(|e| e.into_error())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cell::{CellAttrs, CellContent};
    use crate::link_registry::LinkRegistry;

    fn test_presenter() -> Presenter<Vec<u8>> {
        let caps = TerminalCapabilities::basic();
        Presenter::new(Vec::new(), caps)
    }

    fn test_presenter_with_sync() -> Presenter<Vec<u8>> {
        let mut caps = TerminalCapabilities::basic();
        caps.sync_output = true;
        Presenter::new(Vec::new(), caps)
    }

    fn test_presenter_with_hyperlinks() -> Presenter<Vec<u8>> {
        let mut caps = TerminalCapabilities::basic();
        caps.osc8_hyperlinks = true;
        Presenter::new(Vec::new(), caps)
    }

    fn get_output(presenter: Presenter<Vec<u8>>) -> Vec<u8> {
        presenter.into_inner().unwrap()
    }

    fn legacy_plan_row(
        row_runs: &[ChangeRun],
        prev_x: Option<u16>,
        prev_y: Option<u16>,
    ) -> Vec<cost_model::RowSpan> {
        if row_runs.is_empty() {
            return Vec::new();
        }

        if row_runs.len() == 1 {
            let run = row_runs[0];
            return vec![cost_model::RowSpan {
                y: run.y,
                x0: run.x0,
                x1: run.x1,
            }];
        }

        let row_y = row_runs[0].y;
        let first_x = row_runs[0].x0;
        let last_x = row_runs[row_runs.len() - 1].x1;

        // Estimate sparse cost: sum of move + content for each run
        let mut sparse_cost: usize = 0;
        let mut cursor_x = prev_x;
        let mut cursor_y = prev_y;

        for run in row_runs {
            let move_cost = cost_model::cheapest_move_cost(cursor_x, cursor_y, run.x0, run.y);
            let cells = (run.x1 as usize).saturating_sub(run.x0 as usize) + 1;
            sparse_cost += move_cost + cells;
            cursor_x = Some(run.x1.saturating_add(1));
            cursor_y = Some(row_y);
        }

        // Estimate merged cost: one move + all cells from first to last
        let merge_move = cost_model::cheapest_move_cost(prev_x, prev_y, first_x, row_y);
        let total_cells = (last_x as usize).saturating_sub(first_x as usize) + 1;
        let changed_cells: usize = row_runs
            .iter()
            .map(|r| (r.x1 as usize).saturating_sub(r.x0 as usize) + 1)
            .sum();
        let gap_cells = total_cells.saturating_sub(changed_cells);
        let gap_overhead = gap_cells * 2;
        let merged_cost = merge_move + changed_cells + gap_overhead;

        if merged_cost < sparse_cost {
            vec![cost_model::RowSpan {
                y: row_y,
                x0: first_x,
                x1: last_x,
            }]
        } else {
            row_runs
                .iter()
                .map(|run| cost_model::RowSpan {
                    y: run.y,
                    x0: run.x0,
                    x1: run.x1,
                })
                .collect()
        }
    }

    fn emit_spans_for_output(buffer: &Buffer, spans: &[cost_model::RowSpan]) -> Vec<u8> {
        let mut presenter = test_presenter();

        for span in spans {
            presenter
                .move_cursor_optimal(span.x0, span.y)
                .expect("cursor move should succeed");
            for x in span.x0..=span.x1 {
                let cell = buffer.get_unchecked(x, span.y);
                presenter
                    .emit_cell(x, cell, None, None)
                    .expect("emit_cell should succeed");
            }
        }

        presenter
            .writer
            .write_all(b"\x1b[0m")
            .expect("reset should succeed");

        presenter.into_inner().expect("presenter output")
    }

    #[test]
    fn empty_diff_produces_minimal_output() {
        let mut presenter = test_presenter();
        let buffer = Buffer::new(10, 10);
        let diff = BufferDiff::new();

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        // Without sync, fallback hides cursor first, then SGR reset, then cursor show
        assert!(output.starts_with(ansi::CURSOR_HIDE));
        assert!(output.ends_with(ansi::CURSOR_SHOW));
        // SGR reset is still present between the cursor brackets
        assert!(
            output.windows(b"\x1b[0m".len()).any(|w| w == b"\x1b[0m"),
            "SGR reset should be present"
        );
    }

    #[test]
    fn sync_output_wraps_frame() {
        let mut presenter = test_presenter_with_sync();
        let mut buffer = Buffer::new(3, 1);
        buffer.set_raw(0, 0, Cell::from_char('X'));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        assert!(
            output.starts_with(ansi::SYNC_BEGIN),
            "sync output should begin with DEC 2026 begin"
        );
        assert!(
            output.ends_with(ansi::SYNC_END),
            "sync output should end with DEC 2026 end"
        );
    }

    #[test]
    fn sync_output_obeys_mux_policy() {
        let caps = TerminalCapabilities::builder()
            .sync_output(true)
            .in_tmux(true)
            .build();
        let mut presenter = Presenter::new(Vec::new(), caps);

        let mut buffer = Buffer::new(2, 1);
        buffer.set_raw(0, 0, Cell::from_char('X'));
        let old = Buffer::new(2, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        assert!(
            !output
                .windows(ansi::SYNC_BEGIN.len())
                .any(|w| w == ansi::SYNC_BEGIN),
            "tmux policy should suppress sync begin"
        );
        assert!(
            !output
                .windows(ansi::SYNC_END.len())
                .any(|w| w == ansi::SYNC_END),
            "tmux policy should suppress sync end"
        );
    }

    #[test]
    fn hyperlink_sequences_emitted_and_closed() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(3, 1);

        let mut registry = LinkRegistry::new();
        let link_id = registry.register("https://example.com");
        let linked = Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id));
        buffer.set_raw(0, 0, linked);

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter
            .present_with_pool(&buffer, &diff, None, Some(&registry))
            .unwrap();
        let output = get_output(presenter);

        let start = b"\x1b]8;;https://example.com\x07";
        let end = b"\x1b]8;;\x07";

        let start_pos = output
            .windows(start.len())
            .position(|w| w == start)
            .expect("hyperlink start not found");
        let end_pos = output
            .windows(end.len())
            .position(|w| w == end)
            .expect("hyperlink end not found");
        let char_pos = output
            .iter()
            .position(|&b| b == b'L')
            .expect("linked character not found");

        assert!(start_pos < char_pos, "link start should precede text");
        assert!(char_pos < end_pos, "link end should follow text");
    }

    #[test]
    fn single_cell_change() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(10, 10);
        buffer.set_raw(5, 5, Cell::from_char('X'));

        let old = Buffer::new(10, 10);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        // Should contain cursor position and character
        let output_str = String::from_utf8_lossy(&output);
        assert!(output_str.contains("X"));
        assert!(output_str.contains("\x1b[")); // Contains escape sequences
    }

    #[test]
    fn style_tracking_avoids_redundant_sgr() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(10, 1);

        // Set multiple cells with same style
        let fg = PackedRgba::rgb(255, 0, 0);
        buffer.set_raw(0, 0, Cell::from_char('A').with_fg(fg));
        buffer.set_raw(1, 0, Cell::from_char('B').with_fg(fg));
        buffer.set_raw(2, 0, Cell::from_char('C').with_fg(fg));

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        // Count SGR sequences (should be minimal due to style tracking)
        let output_str = String::from_utf8_lossy(&output);
        let sgr_count = output_str.matches("\x1b[38;2").count();
        // Should have exactly 1 fg color sequence (style set once, reused for ABC)
        assert_eq!(
            sgr_count, 1,
            "Expected 1 SGR fg sequence, got {}",
            sgr_count
        );
    }

    #[test]
    fn reset_reapplies_style_after_clear() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(1, 1);
        let styled = Cell::from_char('A').with_fg(PackedRgba::rgb(10, 20, 30));
        buffer.set_raw(0, 0, styled);

        let old = Buffer::new(1, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        presenter.reset();
        presenter.present(&buffer, &diff).unwrap();

        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);
        let sgr_count = output_str.matches("\x1b[38;2").count();

        assert_eq!(
            sgr_count, 2,
            "Expected style to be re-applied after reset, got {sgr_count} sequences"
        );
    }

    #[test]
    fn cursor_position_optimized() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(10, 5);

        // Set adjacent cells (should be one run)
        buffer.set_raw(3, 2, Cell::from_char('A'));
        buffer.set_raw(4, 2, Cell::from_char('B'));
        buffer.set_raw(5, 2, Cell::from_char('C'));

        let old = Buffer::new(10, 5);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        // Should have only one CUP sequence for the run
        let output_str = String::from_utf8_lossy(&output);
        let _cup_count = output_str.matches("\x1b[").filter(|_| true).count();

        // Content should be "ABC" somewhere in output
        assert!(
            output_str.contains("ABC")
                || (output_str.contains('A')
                    && output_str.contains('B')
                    && output_str.contains('C'))
        );
    }

    #[test]
    fn sync_output_wrapped_when_supported() {
        let mut presenter = test_presenter_with_sync();
        let buffer = Buffer::new(10, 10);
        let diff = BufferDiff::new();

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        // Should have sync begin and end
        assert!(output.starts_with(ansi::SYNC_BEGIN));
        assert!(
            output
                .windows(ansi::SYNC_END.len())
                .any(|w| w == ansi::SYNC_END)
        );
    }

    #[test]
    fn clear_screen_works() {
        let mut presenter = test_presenter();
        presenter.clear_screen().unwrap();
        let output = get_output(presenter);

        // Should contain erase display sequence
        assert!(output.windows(b"\x1b[2J".len()).any(|w| w == b"\x1b[2J"));
    }

    #[test]
    fn cursor_visibility() {
        let mut presenter = test_presenter();

        presenter.hide_cursor().unwrap();
        presenter.show_cursor().unwrap();

        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        assert!(output_str.contains("\x1b[?25l")); // Hide
        assert!(output_str.contains("\x1b[?25h")); // Show
    }

    #[test]
    fn reset_clears_state() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(50);
        presenter.cursor_y = Some(20);
        presenter.current_style = Some(CellStyle::default());

        presenter.reset();

        assert!(presenter.cursor_x.is_none());
        assert!(presenter.cursor_y.is_none());
        assert!(presenter.current_style.is_none());
    }

    #[test]
    fn position_cursor() {
        let mut presenter = test_presenter();
        presenter.position_cursor(10, 5).unwrap();

        let output = get_output(presenter);
        // CUP is 1-indexed: row 6, col 11
        assert!(
            output
                .windows(b"\x1b[6;11H".len())
                .any(|w| w == b"\x1b[6;11H")
        );
    }

    #[test]
    fn skip_cursor_move_when_already_at_position() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(5);
        presenter.cursor_y = Some(3);

        // Move to same position
        presenter.move_cursor_to(5, 3).unwrap();

        // Should produce no output
        let output = get_output(presenter);
        assert!(output.is_empty());
    }

    #[test]
    fn continuation_cells_skipped() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(10, 1);

        // Set a wide character
        buffer.set_raw(0, 0, Cell::from_char('中'));
        // The next cell would be a continuation - simulate it
        buffer.set_raw(1, 0, Cell::CONTINUATION);

        // Create a diff that includes both cells
        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        // Should contain the wide character
        let output_str = String::from_utf8_lossy(&output);
        assert!(output_str.contains('中'));
    }

    #[test]
    fn continuation_at_run_start_clears_orphan_tail() {
        let mut presenter = test_presenter();
        let mut old = Buffer::new(3, 1);
        let mut new = Buffer::new(3, 1);

        // Construct an inconsistent old/new pair that forces a diff which begins at a
        // continuation cell. This simulates starting emission mid-wide-character.
        //
        // In this case, the presenter should clear the orphan continuation cell so
        // stale terminal content cannot leak through.
        old.set_raw(0, 0, Cell::from_char('中'));
        new.set_raw(0, 0, Cell::from_char('中'));
        old.set_raw(1, 0, Cell::from_char('X'));
        new.set_raw(1, 0, Cell::CONTINUATION);

        let diff = BufferDiff::compute(&old, &new);
        assert_eq!(diff.changes(), &[(1u16, 0u16)]);

        presenter.present(&new, &diff).unwrap();
        let output = get_output(presenter);

        assert!(
            output.contains(&b' '),
            "orphan continuation should be cleared with a space"
        );
    }

    #[test]
    fn continuation_cleanup_resets_style_and_closes_link_before_space() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut links = LinkRegistry::new();
        let link_id = links.register("https://example.com");

        let styled = Cell::from_char('X')
            .with_fg(PackedRgba::rgb(255, 0, 0))
            .with_bg(PackedRgba::rgb(0, 0, 255))
            .with_attrs(CellAttrs::new(StyleFlags::UNDERLINE, link_id));
        presenter.current_style = Some(CellStyle::from_cell(&styled));
        presenter.current_link = Some(link_id);
        presenter.cursor_x = Some(0);
        presenter.cursor_y = Some(0);

        presenter
            .emit_cell(0, &Cell::CONTINUATION, None, Some(&links))
            .unwrap();
        let output = presenter.into_inner().unwrap();

        let reset = b"\x1b[0m";
        let close = b"\x1b]8;;\x07";
        let reset_pos = output
            .windows(reset.len())
            .position(|window| window == reset)
            .expect("continuation cleanup should reset SGR state");
        let close_pos = output
            .windows(close.len())
            .position(|window| window == close)
            .expect("continuation cleanup should close OSC 8");
        let space_pos = output
            .iter()
            .position(|&byte| byte == b' ')
            .expect("continuation cleanup should emit a space");

        assert!(
            reset_pos < space_pos,
            "cleanup reset must precede the blank"
        );
        assert!(
            close_pos < space_pos,
            "cleanup link close must precede the blank"
        );
    }

    #[test]
    fn wide_char_missing_continuation_causes_drift() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(10, 1);

        // Bug scenario: User sets wide char but forgets continuation
        buffer.set_raw(0, 0, Cell::from_char('中'));
        // (1,0) remains empty (space), instead of CONTINUATION

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        // Expected behavior with fix:
        // 1. Emit '中' at 0. Cursor -> 2.
        // 2. Loop visits 1. Cell is ' '.
        // 3. Drift check sees x=1, cx=2. Mismatch!
        // 4. Force move to 1. Emits CUP or CHA (CHA is cheaper: \x1b[2G).
        // 5. Emit ' '. Cursor -> 2.

        // Without fix, it would just emit ' ' at 2.

        let output_str = String::from_utf8_lossy(&output);

        // Assert we see the wide char
        assert!(output_str.contains('中'));

        // Assert we see a back-step or positioning sequence.
        // CHA 2 is "\x1b[2G". CUB 1 is "\x1b[D".
        // The cost model might choose CUB 1 (3 bytes) vs CHA 2 (4 bytes).
        // So check for either.

        let has_correction = output_str.contains("\x1b[D")
            || output_str.contains("\x1b[2G")
            || output_str.contains("\x1b[1;2H");

        assert!(
            has_correction,
            "Presenter should correct cursor drift when wide char tail is missing. Output: {:?}",
            output_str
        );
    }

    #[test]
    fn hyperlink_emitted_with_registry() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(10, 1);
        let mut links = LinkRegistry::new();

        let link_id = links.register("https://example.com");
        let cell = Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id));
        buffer.set_raw(0, 0, cell);

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // OSC 8 open with URL
        assert!(
            output_str.contains("\x1b]8;;https://example.com\x07"),
            "Expected OSC 8 open, got: {:?}",
            output_str
        );
        // OSC 8 close (empty URL)
        assert!(
            output_str.contains("\x1b]8;;\x07"),
            "Expected OSC 8 close, got: {:?}",
            output_str
        );
    }

    #[test]
    fn hyperlink_not_emitted_without_registry() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(10, 1);

        // Set a link ID without providing a registry
        let cell = Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), 1));
        buffer.set_raw(0, 0, cell);

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        // Present without link registry
        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // No OSC 8 sequences should appear
        assert!(
            !output_str.contains("\x1b]8;"),
            "OSC 8 should not appear without registry, got: {:?}",
            output_str
        );
    }

    #[test]
    fn hyperlink_not_emitted_for_unknown_id() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(10, 1);
        let links = LinkRegistry::new();

        let cell = Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), 42));
        buffer.set_raw(0, 0, cell);

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        assert!(
            !output_str.contains("\x1b]8;"),
            "OSC 8 should not appear for unknown link IDs, got: {:?}",
            output_str
        );
        assert!(output_str.contains('L'));
    }

    #[test]
    fn hyperlink_closed_at_frame_end() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(10, 1);
        let mut links = LinkRegistry::new();

        let link_id = links.register("https://example.com");
        // Set all cells with the same link
        for x in 0..5 {
            buffer.set_raw(
                x,
                0,
                Cell::from_char('A').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
            );
        }

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();
        let output = get_output(presenter);

        // The close sequence should appear (frame end cleanup)
        let close_seq = b"\x1b]8;;\x07";
        assert!(
            output.windows(close_seq.len()).any(|w| w == close_seq),
            "Link must be closed at frame end"
        );
    }

    #[test]
    fn hyperlink_transitions_between_links() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(10, 1);
        let mut links = LinkRegistry::new();

        let link_a = links.register("https://a.com");
        let link_b = links.register("https://b.com");

        buffer.set_raw(
            0,
            0,
            Cell::from_char('A').with_attrs(CellAttrs::new(StyleFlags::empty(), link_a)),
        );
        buffer.set_raw(
            1,
            0,
            Cell::from_char('B').with_attrs(CellAttrs::new(StyleFlags::empty(), link_b)),
        );
        buffer.set_raw(2, 0, Cell::from_char('C')); // no link

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Both links should appear
        assert!(output_str.contains("https://a.com"));
        assert!(output_str.contains("https://b.com"));

        // Close sequence must appear at least once (transition or frame end)
        let close_count = output_str.matches("\x1b]8;;\x07").count();
        assert!(
            close_count >= 2,
            "Expected at least 2 link close sequences (transition + frame end), got {}",
            close_count
        );
    }

    #[test]
    fn hyperlink_obeys_mux_policy_even_when_capability_flag_set() {
        let caps = TerminalCapabilities::builder()
            .osc8_hyperlinks(true)
            .in_tmux(true)
            .build();
        let mut presenter = Presenter::new(Vec::new(), caps);
        let mut buffer = Buffer::new(3, 1);
        let mut links = LinkRegistry::new();
        let link_id = links.register("https://example.com");
        buffer.set_raw(
            0,
            0,
            Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
        );

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);
        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();

        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);
        assert!(
            !output_str.contains("\x1b]8;"),
            "tmux policy should suppress OSC 8 sequences"
        );
        assert!(output_str.contains('L'));
    }

    #[test]
    fn hyperlink_disabled_policy_noops_when_no_link_is_open() {
        let mut presenter = test_presenter();
        presenter
            .emit_link_changes(&Cell::from_char('X'), None)
            .unwrap();
        assert!(presenter.into_inner().unwrap().is_empty());
    }

    #[test]
    fn hyperlink_disabled_policy_still_closes_stale_open_link() {
        let mut presenter = test_presenter();
        presenter.current_link = Some(7);
        presenter
            .emit_link_changes(&Cell::from_char('X'), None)
            .unwrap();
        assert_eq!(presenter.into_inner().unwrap(), b"\x1b]8;;\x07");
    }

    #[test]
    fn hyperlink_unsafe_url_not_emitted() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(3, 1);
        let mut links = LinkRegistry::new();
        let link_id = links.register("https://example.com/\x1b[?2026h");
        buffer.set_raw(
            0,
            0,
            Cell::from_char('X').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
        );

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);
        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();

        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);
        assert!(
            !output_str.contains("\x1b]8;;https://example.com/"),
            "unsafe hyperlink URL should be suppressed"
        );
        assert!(
            !output_str.contains("\x1b[?2026h"),
            "control payload must never be emitted via OSC 8"
        );
        assert!(output_str.contains('X'));
    }

    #[test]
    fn hyperlink_overlong_url_not_emitted() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(3, 1);
        let mut links = LinkRegistry::new();
        let long_url = format!(
            "https://example.com/{}",
            "a".repeat(MAX_SAFE_HYPERLINK_URL_BYTES + 1)
        );
        let link_id = links.register(&long_url);
        buffer.set_raw(
            0,
            0,
            Cell::from_char('Y').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
        );

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);
        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();

        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);
        assert!(
            !output_str.contains("\x1b]8;;https://example.com/"),
            "overlong hyperlink URL should be suppressed"
        );
        assert!(output_str.contains('Y'));
    }

    // =========================================================================
    // Single-write-per-frame behavior tests
    // =========================================================================

    #[test]
    fn sync_output_not_wrapped_when_unsupported() {
        // When sync_output capability is false, sync sequences should NOT appear
        let mut presenter = test_presenter(); // basic caps, sync_output = false
        let buffer = Buffer::new(10, 10);
        let diff = BufferDiff::new();

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        // Should NOT contain sync sequences
        assert!(
            !output
                .windows(ansi::SYNC_BEGIN.len())
                .any(|w| w == ansi::SYNC_BEGIN),
            "Sync begin should not appear when sync_output is disabled"
        );
        assert!(
            !output
                .windows(ansi::SYNC_END.len())
                .any(|w| w == ansi::SYNC_END),
            "Sync end should not appear when sync_output is disabled"
        );

        // Instead, cursor-hide fallback should be used
        assert!(
            output.starts_with(ansi::CURSOR_HIDE),
            "Fallback should start with cursor hide"
        );
        assert!(
            output.ends_with(ansi::CURSOR_SHOW),
            "Fallback should end with cursor show"
        );
    }

    #[test]
    fn present_flushes_buffered_output() {
        // Verify that present() flushes all buffered output by checking
        // that the output contains expected content after present()
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(5, 1);
        buffer.set_raw(0, 0, Cell::from_char('T'));
        buffer.set_raw(1, 0, Cell::from_char('E'));
        buffer.set_raw(2, 0, Cell::from_char('S'));
        buffer.set_raw(3, 0, Cell::from_char('T'));

        let old = Buffer::new(5, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // All characters should be present in output (flushed)
        assert!(
            output_str.contains("TEST"),
            "Expected 'TEST' in flushed output"
        );
    }

    #[test]
    fn present_stats_reports_cells_and_bytes() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(10, 1);

        // Set 5 cells
        for i in 0..5 {
            buffer.set_raw(i, 0, Cell::from_char('X'));
        }

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        let stats = presenter.present(&buffer, &diff).unwrap();

        // Stats should reflect the changes
        assert_eq!(stats.cells_changed, 5, "Expected 5 cells changed");
        assert!(stats.bytes_emitted > 0, "Expected some bytes written");
        assert!(stats.run_count >= 1, "Expected at least 1 run");
    }

    // =========================================================================
    // Cursor tracking tests
    // =========================================================================

    #[test]
    fn cursor_tracking_after_wide_char() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(0);
        presenter.cursor_y = Some(0);

        let mut buffer = Buffer::new(10, 1);
        // Wide char at x=0 should advance cursor by 2
        buffer.set_raw(0, 0, Cell::from_char('中'));
        buffer.set_raw(1, 0, Cell::CONTINUATION);
        // Narrow char at x=2
        buffer.set_raw(2, 0, Cell::from_char('A'));

        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();

        // After presenting, cursor should be at x=3 (0 + 2 for wide + 1 for 'A')
        // Note: cursor_x gets reset during present(), but we can verify output order
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Both characters should appear
        assert!(output_str.contains('中'));
        assert!(output_str.contains('A'));
    }

    #[test]
    fn cursor_position_after_multiple_runs() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(20, 3);

        // Create two separate runs on different rows
        buffer.set_raw(0, 0, Cell::from_char('A'));
        buffer.set_raw(1, 0, Cell::from_char('B'));
        buffer.set_raw(5, 2, Cell::from_char('X'));
        buffer.set_raw(6, 2, Cell::from_char('Y'));

        let old = Buffer::new(20, 3);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // All characters should be present
        assert!(output_str.contains('A'));
        assert!(output_str.contains('B'));
        assert!(output_str.contains('X'));
        assert!(output_str.contains('Y'));

        // Should have multiple CUP sequences (one per run)
        let cup_count = output_str.matches("\x1b[").count();
        assert!(
            cup_count >= 2,
            "Expected at least 2 escape sequences for multiple runs"
        );
    }

    // =========================================================================
    // Style tracking tests
    // =========================================================================

    #[test]
    fn style_with_all_flags() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(5, 1);

        // Create a cell with all style flags
        let all_flags = StyleFlags::BOLD
            | StyleFlags::DIM
            | StyleFlags::ITALIC
            | StyleFlags::UNDERLINE
            | StyleFlags::BLINK
            | StyleFlags::REVERSE
            | StyleFlags::STRIKETHROUGH;

        let cell = Cell::from_char('X').with_attrs(CellAttrs::new(all_flags, 0));
        buffer.set_raw(0, 0, cell);

        let old = Buffer::new(5, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Should contain the character and SGR sequences
        assert!(output_str.contains('X'));
        // Should have SGR with multiple attributes (1;2;3;4;5;7;9m pattern)
        assert!(output_str.contains("\x1b["), "Expected SGR sequences");
    }

    #[test]
    fn style_transitions_between_different_colors() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);

        // Three cells with different foreground colors
        buffer.set_raw(
            0,
            0,
            Cell::from_char('R').with_fg(PackedRgba::rgb(255, 0, 0)),
        );
        buffer.set_raw(
            1,
            0,
            Cell::from_char('G').with_fg(PackedRgba::rgb(0, 255, 0)),
        );
        buffer.set_raw(
            2,
            0,
            Cell::from_char('B').with_fg(PackedRgba::rgb(0, 0, 255)),
        );

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // All colors should appear in the output
        assert!(output_str.contains("38;2;255;0;0"), "Expected red fg");
        assert!(output_str.contains("38;2;0;255;0"), "Expected green fg");
        assert!(output_str.contains("38;2;0;0;255"), "Expected blue fg");
    }

    // =========================================================================
    // Link tracking tests
    // =========================================================================

    #[test]
    fn link_at_buffer_boundaries() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(5, 1);
        let mut links = LinkRegistry::new();

        let link_id = links.register("https://boundary.test");

        // Link at first cell
        buffer.set_raw(
            0,
            0,
            Cell::from_char('F').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
        );
        // Link at last cell
        buffer.set_raw(
            4,
            0,
            Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
        );

        let old = Buffer::new(5, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Link URL should appear
        assert!(output_str.contains("https://boundary.test"));
        // Characters should appear
        assert!(output_str.contains('F'));
        assert!(output_str.contains('L'));
    }

    #[test]
    fn link_state_cleared_after_reset() {
        let mut presenter = test_presenter();
        let mut links = LinkRegistry::new();
        let link_id = links.register("https://example.com");

        // Simulate having an open link
        presenter.current_link = Some(link_id);
        presenter.current_style = Some(CellStyle::default());
        presenter.cursor_x = Some(5);
        presenter.cursor_y = Some(3);

        presenter.reset();

        // All state should be cleared
        assert!(
            presenter.current_link.is_none(),
            "current_link should be None after reset"
        );
        assert!(
            presenter.current_style.is_none(),
            "current_style should be None after reset"
        );
        assert!(
            presenter.cursor_x.is_none(),
            "cursor_x should be None after reset"
        );
        assert!(
            presenter.cursor_y.is_none(),
            "cursor_y should be None after reset"
        );
    }

    #[test]
    fn link_transitions_linked_unlinked_linked() {
        let mut presenter = test_presenter_with_hyperlinks();
        let mut buffer = Buffer::new(5, 1);
        let mut links = LinkRegistry::new();

        let link_id = links.register("https://toggle.test");

        // Linked -> Unlinked -> Linked pattern
        buffer.set_raw(
            0,
            0,
            Cell::from_char('A').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
        );
        buffer.set_raw(1, 0, Cell::from_char('B')); // no link
        buffer.set_raw(
            2,
            0,
            Cell::from_char('C').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
        );

        let old = Buffer::new(5, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Link URL should appear at least twice (once for A, once for C)
        let url_count = output_str.matches("https://toggle.test").count();
        assert!(
            url_count >= 2,
            "Expected link to open at least twice, got {} occurrences",
            url_count
        );

        // Close sequence should appear (after A, and at frame end)
        let close_count = output_str.matches("\x1b]8;;\x07").count();
        assert!(
            close_count >= 2,
            "Expected at least 2 link closes, got {}",
            close_count
        );
    }

    // =========================================================================
    // Multiple frame tests
    // =========================================================================

    #[test]
    fn multiple_presents_maintain_correct_state() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(10, 1);

        // First frame
        buffer.set_raw(0, 0, Cell::from_char('1'));
        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);
        presenter.present(&buffer, &diff).unwrap();

        // Second frame - change a different cell
        let prev = buffer.clone();
        buffer.set_raw(1, 0, Cell::from_char('2'));
        let diff = BufferDiff::compute(&prev, &buffer);
        presenter.present(&buffer, &diff).unwrap();

        // Third frame - change another cell
        let prev = buffer.clone();
        buffer.set_raw(2, 0, Cell::from_char('3'));
        let diff = BufferDiff::compute(&prev, &buffer);
        presenter.present(&buffer, &diff).unwrap();

        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // All numbers should appear in final output
        assert!(output_str.contains('1'));
        assert!(output_str.contains('2'));
        assert!(output_str.contains('3'));
    }

    // =========================================================================
    // SGR Delta Engine tests (bd-4kq0.2.1)
    // =========================================================================

    #[test]
    fn sgr_delta_fg_only_change_no_reset() {
        // When only fg changes, delta should NOT emit reset
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);

        let fg1 = PackedRgba::rgb(255, 0, 0);
        let fg2 = PackedRgba::rgb(0, 255, 0);
        buffer.set_raw(0, 0, Cell::from_char('A').with_fg(fg1));
        buffer.set_raw(1, 0, Cell::from_char('B').with_fg(fg2));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Count SGR resets - the first cell needs a reset (from None state),
        // but the second cell should use delta (no reset)
        let reset_count = output_str.matches("\x1b[0m").count();
        // One reset at start (for first cell from unknown state) + one at frame end
        assert_eq!(
            reset_count, 2,
            "Expected 2 resets (initial + frame end), got {} in: {:?}",
            reset_count, output_str
        );
    }

    #[test]
    fn sgr_delta_bg_only_change_no_reset() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);

        let bg1 = PackedRgba::rgb(0, 0, 255);
        let bg2 = PackedRgba::rgb(255, 255, 0);
        buffer.set_raw(0, 0, Cell::from_char('A').with_bg(bg1));
        buffer.set_raw(1, 0, Cell::from_char('B').with_bg(bg2));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Only 2 resets: initial cell + frame end
        let reset_count = output_str.matches("\x1b[0m").count();
        assert_eq!(
            reset_count, 2,
            "Expected 2 resets, got {} in: {:?}",
            reset_count, output_str
        );
    }

    #[test]
    fn sgr_delta_attr_addition_no_reset() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);

        // First cell: bold. Second cell: bold + italic
        let attrs1 = CellAttrs::new(StyleFlags::BOLD, 0);
        let attrs2 = CellAttrs::new(StyleFlags::BOLD | StyleFlags::ITALIC, 0);
        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Second cell should add italic (code 3) without reset
        let reset_count = output_str.matches("\x1b[0m").count();
        assert_eq!(
            reset_count, 2,
            "Expected 2 resets, got {} in: {:?}",
            reset_count, output_str
        );
        // Should contain italic-on code for the delta
        assert!(
            output_str.contains("\x1b[3m"),
            "Expected italic-on sequence in: {:?}",
            output_str
        );
    }

    #[test]
    fn sgr_delta_attr_removal_uses_off_code() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);

        // First cell: bold+italic. Second cell: bold only
        let attrs1 = CellAttrs::new(StyleFlags::BOLD | StyleFlags::ITALIC, 0);
        let attrs2 = CellAttrs::new(StyleFlags::BOLD, 0);
        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Should contain italic-off code (23) for delta
        assert!(
            output_str.contains("\x1b[23m"),
            "Expected italic-off sequence in: {:?}",
            output_str
        );
        // Only 2 resets (initial + frame end), not 3
        let reset_count = output_str.matches("\x1b[0m").count();
        assert_eq!(
            reset_count, 2,
            "Expected 2 resets, got {} in: {:?}",
            reset_count, output_str
        );
    }

    #[test]
    fn sgr_delta_bold_dim_collateral_re_enables() {
        // Bold off (code 22) also disables Dim. If Dim should remain,
        // the delta engine must re-enable it.
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);

        // First cell: Bold + Dim. Second cell: Dim only
        let attrs1 = CellAttrs::new(StyleFlags::BOLD | StyleFlags::DIM, 0);
        let attrs2 = CellAttrs::new(StyleFlags::DIM, 0);
        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Should contain bold-off (22) and then dim re-enable (2)
        assert!(
            output_str.contains("\x1b[22m"),
            "Expected bold-off (22) in: {:?}",
            output_str
        );
        assert!(
            output_str.contains("\x1b[2m"),
            "Expected dim re-enable (2) in: {:?}",
            output_str
        );
    }

    #[test]
    fn sgr_delta_same_style_no_output() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);

        let fg = PackedRgba::rgb(255, 0, 0);
        let attrs = CellAttrs::new(StyleFlags::BOLD, 0);
        buffer.set_raw(0, 0, Cell::from_char('A').with_fg(fg).with_attrs(attrs));
        buffer.set_raw(1, 0, Cell::from_char('B').with_fg(fg).with_attrs(attrs));
        buffer.set_raw(2, 0, Cell::from_char('C').with_fg(fg).with_attrs(attrs));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Only 1 fg color sequence (style set once for all three cells)
        let fg_count = output_str.matches("38;2;255;0;0").count();
        assert_eq!(
            fg_count, 1,
            "Expected 1 fg sequence, got {} in: {:?}",
            fg_count, output_str
        );
    }

    #[test]
    fn sgr_delta_cost_dominance_never_exceeds_baseline() {
        // Test that delta output is never larger than reset+apply would be
        // for a variety of style transitions
        let transitions: Vec<(CellStyle, CellStyle)> = vec![
            // Only fg change
            (
                CellStyle {
                    fg: PackedRgba::rgb(255, 0, 0),
                    bg: PackedRgba::TRANSPARENT,
                    attrs: StyleFlags::empty(),
                },
                CellStyle {
                    fg: PackedRgba::rgb(0, 255, 0),
                    bg: PackedRgba::TRANSPARENT,
                    attrs: StyleFlags::empty(),
                },
            ),
            // Only bg change
            (
                CellStyle {
                    fg: PackedRgba::TRANSPARENT,
                    bg: PackedRgba::rgb(255, 0, 0),
                    attrs: StyleFlags::empty(),
                },
                CellStyle {
                    fg: PackedRgba::TRANSPARENT,
                    bg: PackedRgba::rgb(0, 0, 255),
                    attrs: StyleFlags::empty(),
                },
            ),
            // Only attr addition
            (
                CellStyle {
                    fg: PackedRgba::rgb(100, 100, 100),
                    bg: PackedRgba::TRANSPARENT,
                    attrs: StyleFlags::BOLD,
                },
                CellStyle {
                    fg: PackedRgba::rgb(100, 100, 100),
                    bg: PackedRgba::TRANSPARENT,
                    attrs: StyleFlags::BOLD | StyleFlags::ITALIC,
                },
            ),
            // Attr removal
            (
                CellStyle {
                    fg: PackedRgba::rgb(100, 100, 100),
                    bg: PackedRgba::TRANSPARENT,
                    attrs: StyleFlags::BOLD | StyleFlags::ITALIC,
                },
                CellStyle {
                    fg: PackedRgba::rgb(100, 100, 100),
                    bg: PackedRgba::TRANSPARENT,
                    attrs: StyleFlags::BOLD,
                },
            ),
        ];

        for (old_style, new_style) in &transitions {
            // Measure delta cost
            let delta_buf = {
                let mut delta_presenter = {
                    let caps = TerminalCapabilities::basic();
                    Presenter::new(Vec::new(), caps)
                };
                delta_presenter.current_style = Some(*old_style);
                delta_presenter
                    .emit_style_delta(*old_style, *new_style)
                    .unwrap();
                delta_presenter.into_inner().unwrap()
            };

            // Measure reset+apply cost
            let reset_buf = {
                let mut reset_presenter = {
                    let caps = TerminalCapabilities::basic();
                    Presenter::new(Vec::new(), caps)
                };
                reset_presenter.emit_style_full(*new_style).unwrap();
                reset_presenter.into_inner().unwrap()
            };

            assert!(
                delta_buf.len() <= reset_buf.len(),
                "Delta ({} bytes) exceeded reset+apply ({} bytes) for {:?} -> {:?}.\n\
                 Delta: {:?}\nReset: {:?}",
                delta_buf.len(),
                reset_buf.len(),
                old_style,
                new_style,
                String::from_utf8_lossy(&delta_buf),
                String::from_utf8_lossy(&reset_buf),
            );
        }
    }

    /// Generate a deterministic JSONL evidence ledger proving the SGR delta engine
    /// emits fewer (or equal) bytes than reset+apply for every transition.
    ///
    /// Each line is a JSON object with:
    ///   seed, from_fg, from_bg, from_attrs, to_fg, to_bg, to_attrs,
    ///   delta_bytes, baseline_bytes, cost_delta, used_fallback
    #[test]
    fn sgr_delta_evidence_ledger() {
        use std::io::Write as _;

        // Deterministic seed for reproducibility
        const SEED: u64 = 0xDEAD_BEEF_CAFE;

        // Simple LCG for deterministic pseudorandom values
        let mut rng_state = SEED;
        let mut next_u64 = || -> u64 {
            rng_state = rng_state.wrapping_mul(6364136223846793005).wrapping_add(1);
            rng_state
        };

        let random_style = |rng: &mut dyn FnMut() -> u64| -> CellStyle {
            let v = rng();
            let fg = if v & 1 == 0 {
                PackedRgba::TRANSPARENT
            } else {
                let r = ((v >> 8) & 0xFF) as u8;
                let g = ((v >> 16) & 0xFF) as u8;
                let b = ((v >> 24) & 0xFF) as u8;
                PackedRgba::rgb(r, g, b)
            };
            let v2 = rng();
            let bg = if v2 & 1 == 0 {
                PackedRgba::TRANSPARENT
            } else {
                let r = ((v2 >> 8) & 0xFF) as u8;
                let g = ((v2 >> 16) & 0xFF) as u8;
                let b = ((v2 >> 24) & 0xFF) as u8;
                PackedRgba::rgb(r, g, b)
            };
            let attrs = StyleFlags::from_bits_truncate(rng() as u8);
            CellStyle { fg, bg, attrs }
        };

        let mut ledger = Vec::new();
        let num_transitions = 200;

        for i in 0..num_transitions {
            let old_style = random_style(&mut next_u64);
            let new_style = random_style(&mut next_u64);

            // Measure delta cost
            let mut delta_p = {
                let caps = TerminalCapabilities::basic();
                Presenter::new(Vec::new(), caps)
            };
            delta_p.current_style = Some(old_style);
            delta_p.emit_style_delta(old_style, new_style).unwrap();
            let delta_out = delta_p.into_inner().unwrap();

            // Measure reset+apply cost
            let mut reset_p = {
                let caps = TerminalCapabilities::basic();
                Presenter::new(Vec::new(), caps)
            };
            reset_p.emit_style_full(new_style).unwrap();
            let reset_out = reset_p.into_inner().unwrap();

            let delta_bytes = delta_out.len();
            let baseline_bytes = reset_out.len();

            // Compute whether fallback was used (delta >= baseline means fallback likely)
            let attrs_removed = old_style.attrs & !new_style.attrs;
            let removed_count = attrs_removed.bits().count_ones();
            let fg_changed = old_style.fg != new_style.fg;
            let bg_changed = old_style.bg != new_style.bg;
            let used_fallback = removed_count >= 3 && fg_changed && bg_changed;

            // Assert cost dominance
            assert!(
                delta_bytes <= baseline_bytes,
                "Transition {i}: delta ({delta_bytes}B) > baseline ({baseline_bytes}B)"
            );

            // Emit JSONL record
            writeln!(
                &mut ledger,
                "{{\"seed\":{SEED},\"i\":{i},\"from_fg\":\"{:?}\",\"from_bg\":\"{:?}\",\
                 \"from_attrs\":{},\"to_fg\":\"{:?}\",\"to_bg\":\"{:?}\",\"to_attrs\":{},\
                 \"delta_bytes\":{delta_bytes},\"baseline_bytes\":{baseline_bytes},\
                 \"cost_delta\":{},\"used_fallback\":{used_fallback}}}",
                old_style.fg,
                old_style.bg,
                old_style.attrs.bits(),
                new_style.fg,
                new_style.bg,
                new_style.attrs.bits(),
                baseline_bytes as isize - delta_bytes as isize,
            )
            .unwrap();
        }

        // Verify we produced valid JSONL (every line parses)
        let text = String::from_utf8(ledger).unwrap();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), num_transitions);

        // Verify aggregate: total savings should be non-negative
        let mut total_saved: isize = 0;
        for line in &lines {
            // Quick parse of cost_delta field
            let cd_start = line.find("\"cost_delta\":").unwrap() + 13;
            let cd_end = line[cd_start..].find(',').unwrap() + cd_start;
            let cd: isize = line[cd_start..cd_end].parse().unwrap();
            total_saved += cd;
        }
        assert!(
            total_saved >= 0,
            "Total byte savings should be non-negative, got {total_saved}"
        );
    }

    /// E2E style stress test: scripted style churn across a full buffer
    /// with byte metrics proving delta engine correctness under load.
    #[test]
    fn e2e_style_stress_with_byte_metrics() {
        let width = 40u16;
        let height = 10u16;

        // Build a buffer with maximum style diversity
        let mut buffer = Buffer::new(width, height);
        for y in 0..height {
            for x in 0..width {
                let i = (y as usize * width as usize + x as usize) as u8;
                let fg = PackedRgba::rgb(i, 255 - i, i.wrapping_mul(3));
                let bg = if i.is_multiple_of(4) {
                    PackedRgba::rgb(i.wrapping_mul(7), i.wrapping_mul(11), i.wrapping_mul(13))
                } else {
                    PackedRgba::TRANSPARENT
                };
                let flags = StyleFlags::from_bits_truncate(i % 128);
                let ch = char::from_u32(('!' as u32) + (i as u32 % 90)).unwrap_or('?');
                let cell = Cell::from_char(ch)
                    .with_fg(fg)
                    .with_bg(bg)
                    .with_attrs(CellAttrs::new(flags, 0));
                buffer.set_raw(x, y, cell);
            }
        }

        // Present from blank (first frame)
        let blank = Buffer::new(width, height);
        let diff = BufferDiff::compute(&blank, &buffer);
        let mut presenter = test_presenter();
        presenter.present(&buffer, &diff).unwrap();
        let frame1_bytes = presenter.into_inner().unwrap().len();

        // Build second buffer: shift all styles by one position (churn)
        let mut buffer2 = Buffer::new(width, height);
        for y in 0..height {
            for x in 0..width {
                let i = (y as usize * width as usize + x as usize + 1) as u8;
                let fg = PackedRgba::rgb(i, 255 - i, i.wrapping_mul(3));
                let bg = if i.is_multiple_of(4) {
                    PackedRgba::rgb(i.wrapping_mul(7), i.wrapping_mul(11), i.wrapping_mul(13))
                } else {
                    PackedRgba::TRANSPARENT
                };
                let flags = StyleFlags::from_bits_truncate(i % 128);
                let ch = char::from_u32(('!' as u32) + (i as u32 % 90)).unwrap_or('?');
                let cell = Cell::from_char(ch)
                    .with_fg(fg)
                    .with_bg(bg)
                    .with_attrs(CellAttrs::new(flags, 0));
                buffer2.set_raw(x, y, cell);
            }
        }

        // Second frame: incremental update should use delta engine
        let diff2 = BufferDiff::compute(&buffer, &buffer2);
        let mut presenter2 = test_presenter();
        presenter2.present(&buffer2, &diff2).unwrap();
        let frame2_bytes = presenter2.into_inner().unwrap().len();

        // Incremental should be smaller than full redraw since delta
        // engine can reuse partial style state
        assert!(
            frame2_bytes > 0,
            "Second frame should produce output for style churn"
        );
        assert!(!diff2.is_empty(), "Style shift should produce changes");

        // Verify frame2 is at most frame1 size (delta should never be worse
        // than a full redraw for the same number of changed cells)
        // Note: frame2 may differ in size due to different diff (changed cells
        // vs all cells), so just verify it's reasonable.
        assert!(
            frame2_bytes <= frame1_bytes * 2,
            "Incremental frame ({frame2_bytes}B) unreasonably large vs full ({frame1_bytes}B)"
        );
    }

    // =========================================================================
    // DP Cost Model Tests (bd-4kq0.2.2)
    // =========================================================================

    #[test]
    fn cost_model_empty_row_single_run() {
        // Single run on a row should always use Sparse (no merge benefit)
        let runs = [ChangeRun::new(5, 10, 20)];
        let plan = cost_model::plan_row(&runs, None, None);
        assert_eq!(plan.spans().len(), 1);
        assert_eq!(plan.spans()[0].x0, 10);
        assert_eq!(plan.spans()[0].x1, 20);
        assert!(plan.total_cost() > 0);
    }

    #[test]
    fn cost_model_full_row_merges() {
        // Two small runs far apart on same row - gap is smaller than 2x CUP overhead
        // Runs at columns 0-2 and 77-79 on an 80-col row
        // Sparse: CUP + 3 cells + CUP + 3 cells
        // Merged: CUP + 80 cells but with gap overhead
        // This should stay sparse since the gap is very large
        let runs = [ChangeRun::new(0, 0, 2), ChangeRun::new(0, 77, 79)];
        let plan = cost_model::plan_row(&runs, None, None);
        // Large gap (74 cells * 2 overhead = 148) vs CUP savings (~8) => no merge.
        assert_eq!(plan.spans().len(), 2);
        assert_eq!(plan.spans()[0].x0, 0);
        assert_eq!(plan.spans()[0].x1, 2);
        assert_eq!(plan.spans()[1].x0, 77);
        assert_eq!(plan.spans()[1].x1, 79);
    }

    #[test]
    fn cost_model_adjacent_runs_merge() {
        // Many single-cell runs with 1-cell gaps should merge
        // 8 single-cell runs at columns 10, 12, 14, 16, 18, 20, 22, 24
        let runs = [
            ChangeRun::new(3, 10, 10),
            ChangeRun::new(3, 12, 12),
            ChangeRun::new(3, 14, 14),
            ChangeRun::new(3, 16, 16),
            ChangeRun::new(3, 18, 18),
            ChangeRun::new(3, 20, 20),
            ChangeRun::new(3, 22, 22),
            ChangeRun::new(3, 24, 24),
        ];
        let plan = cost_model::plan_row(&runs, None, None);
        // Sparse: 1 CUP + 7 CUF(2) * 4 bytes + 8 cells = ~7+28+8 = 43
        // Merged: 1 CUP + 8 changed + 7 gap * 2 = 7+8+14 = 29
        assert_eq!(plan.spans().len(), 1);
        assert_eq!(plan.spans()[0].x0, 10);
        assert_eq!(plan.spans()[0].x1, 24);
    }

    #[test]
    fn cost_model_single_cell_stays_sparse() {
        let runs = [ChangeRun::new(0, 40, 40)];
        let plan = cost_model::plan_row(&runs, Some(0), Some(0));
        assert_eq!(plan.spans().len(), 1);
        assert_eq!(plan.spans()[0].x0, 40);
        assert_eq!(plan.spans()[0].x1, 40);
    }

    #[test]
    fn cost_model_cup_vs_cha_vs_cuf() {
        // CUF should be cheapest for small forward moves on same row
        assert!(cost_model::cuf_cost(1) <= cost_model::cha_cost(5));
        assert!(cost_model::cuf_cost(3) <= cost_model::cup_cost(0, 5));

        // CHA should be cheapest for backward moves on same row (vs CUP)
        let cha = cost_model::cha_cost(5);
        let cup = cost_model::cup_cost(0, 5);
        assert!(cha <= cup);

        // Cheapest move from known position (same row, forward 1)
        let cost = cost_model::cheapest_move_cost(Some(5), Some(0), 6, 0);
        assert_eq!(cost, 3); // CUF(1) = "\x1b[C" = 3 bytes
    }

    #[test]
    fn cost_model_digit_estimation_accuracy() {
        // Verify CUP cost estimates are accurate by comparing to actual output
        let mut buf = Vec::new();
        ansi::cup(&mut buf, 0, 0).unwrap();
        assert_eq!(buf.len(), cost_model::cup_cost(0, 0));

        buf.clear();
        ansi::cup(&mut buf, 9, 9).unwrap();
        assert_eq!(buf.len(), cost_model::cup_cost(9, 9));

        buf.clear();
        ansi::cup(&mut buf, 99, 99).unwrap();
        assert_eq!(buf.len(), cost_model::cup_cost(99, 99));

        buf.clear();
        ansi::cha(&mut buf, 0).unwrap();
        assert_eq!(buf.len(), cost_model::cha_cost(0));

        buf.clear();
        ansi::cuf(&mut buf, 1).unwrap();
        assert_eq!(buf.len(), cost_model::cuf_cost(1));

        buf.clear();
        ansi::cuf(&mut buf, 10).unwrap();
        assert_eq!(buf.len(), cost_model::cuf_cost(10));
    }

    #[test]
    fn cost_model_merged_row_produces_correct_output() {
        // Verify that merged emission produces the same visual result as sparse
        let width = 30u16;
        let mut buffer = Buffer::new(width, 1);

        // Set up scattered changes: columns 5, 10, 15, 20
        for col in [5u16, 10, 15, 20] {
            let ch = char::from_u32('A' as u32 + col as u32 % 26).unwrap();
            buffer.set_raw(col, 0, Cell::from_char(ch));
        }

        let old = Buffer::new(width, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        // Present and verify output contains expected characters
        let mut presenter = test_presenter();
        presenter.present(&buffer, &diff).unwrap();
        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);

        for col in [5u16, 10, 15, 20] {
            let ch = char::from_u32('A' as u32 + col as u32 % 26).unwrap();
            assert!(
                output_str.contains(ch),
                "Missing character '{ch}' at col {col} in output"
            );
        }
    }

    #[test]
    fn cost_model_optimal_cursor_uses_cuf_on_same_row() {
        // Verify move_cursor_optimal uses CUF for small forward moves
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(5);
        presenter.cursor_y = Some(0);
        presenter.move_cursor_optimal(6, 0).unwrap();
        let output = presenter.into_inner().unwrap();
        // CUF(1) = "\x1b[C"
        assert_eq!(&output, b"\x1b[C", "Should use CUF for +1 column move");
    }

    #[test]
    fn cost_model_optimal_cursor_uses_cha_on_same_row_backward() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(10);
        presenter.cursor_y = Some(3);

        let target_x = 2;
        let target_y = 3;
        let cha_cost = cost_model::cha_cost(target_x);
        let cup_cost = cost_model::cup_cost(target_y, target_x);
        assert!(
            cha_cost <= cup_cost,
            "Expected CHA to be cheaper for backward move (cha={cha_cost}, cup={cup_cost})"
        );

        presenter.move_cursor_optimal(target_x, target_y).unwrap();
        let output = presenter.into_inner().unwrap();
        let mut expected = Vec::new();
        ansi::cha(&mut expected, target_x).unwrap();
        assert_eq!(output, expected, "Should use CHA for backward move");
    }

    #[test]
    fn cost_model_optimal_cursor_uses_cup_on_row_change() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(4);
        presenter.cursor_y = Some(1);

        presenter.move_cursor_optimal(7, 4).unwrap();
        let output = presenter.into_inner().unwrap();
        let mut expected = Vec::new();
        ansi::cup(&mut expected, 4, 7).unwrap();
        assert_eq!(output, expected, "Should use CUP when row changes");
    }

    #[test]
    fn cost_model_chooses_full_row_when_cheaper() {
        // Create a scenario where merged is definitely cheaper:
        // 10 single-cell runs with 1-cell gaps on the same row
        let width = 40u16;
        let mut buffer = Buffer::new(width, 1);

        // Every other column: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18
        for col in (0..20).step_by(2) {
            buffer.set_raw(col, 0, Cell::from_char('X'));
        }

        let old = Buffer::new(width, 1);
        let diff = BufferDiff::compute(&old, &buffer);
        let runs = diff.runs();

        // The cost model should merge (many small gaps < many CUP costs)
        let row_runs: Vec<_> = runs.iter().filter(|r| r.y == 0).copied().collect();
        if row_runs.len() > 1 {
            let plan = cost_model::plan_row(&row_runs, None, None);
            assert!(
                plan.spans().len() == 1,
                "Expected single merged span for many small runs, got {} spans",
                plan.spans().len()
            );
            assert_eq!(plan.spans()[0].x0, 0);
            assert_eq!(plan.spans()[0].x1, 18);
        }
    }

    #[test]
    fn perf_cost_model_overhead() {
        // Verify the cost model planning is fast (microsecond scale)
        use std::time::Instant;

        let runs: Vec<ChangeRun> = (0..100)
            .map(|i| ChangeRun::new(0, i * 3, i * 3 + 1))
            .collect();

        let (iterations, max_ms) = if cfg!(debug_assertions) {
            (1_000, 1_000u128)
        } else {
            (10_000, 500u128)
        };

        let start = Instant::now();
        for _ in 0..iterations {
            let _ = cost_model::plan_row(&runs, None, None);
        }
        let elapsed = start.elapsed();

        // Keep this generous in debug builds to avoid flaky perf assertions.
        assert!(
            elapsed.as_millis() < max_ms,
            "Cost model planning too slow: {elapsed:?} for {iterations} iterations"
        );
    }

    #[test]
    fn perf_legacy_vs_dp_worst_case_sparse() {
        use std::time::Instant;

        let width = 200u16;
        let height = 1u16;
        let mut buffer = Buffer::new(width, height);

        // Two dense clusters with a large gap between them.
        for col in (0..40).step_by(2) {
            buffer.set_raw(col, 0, Cell::from_char('X'));
        }
        for col in (160..200).step_by(2) {
            buffer.set_raw(col, 0, Cell::from_char('Y'));
        }

        let blank = Buffer::new(width, height);
        let diff = BufferDiff::compute(&blank, &buffer);
        let runs = diff.runs();
        let row_runs: Vec<_> = runs.iter().filter(|r| r.y == 0).copied().collect();

        let dp_plan = cost_model::plan_row(&row_runs, None, None);
        let legacy_spans = legacy_plan_row(&row_runs, None, None);

        let dp_output = emit_spans_for_output(&buffer, dp_plan.spans());
        let legacy_output = emit_spans_for_output(&buffer, &legacy_spans);

        assert!(
            dp_output.len() <= legacy_output.len(),
            "DP output should be <= legacy output (dp={}, legacy={})",
            dp_output.len(),
            legacy_output.len()
        );

        let (iterations, max_ms) = if cfg!(debug_assertions) {
            (1_000, 1_000u128)
        } else {
            (10_000, 500u128)
        };
        let start = Instant::now();
        for _ in 0..iterations {
            let _ = cost_model::plan_row(&row_runs, None, None);
        }
        let dp_elapsed = start.elapsed();

        let start = Instant::now();
        for _ in 0..iterations {
            let _ = legacy_plan_row(&row_runs, None, None);
        }
        let legacy_elapsed = start.elapsed();

        assert!(
            dp_elapsed.as_millis() < max_ms,
            "DP planning too slow: {dp_elapsed:?} for {iterations} iterations"
        );

        let _ = legacy_elapsed;
    }

    // =========================================================================
    // Presenter Perf + Golden Outputs (bd-4kq0.2.3)
    // =========================================================================

    /// Build a deterministic "style-heavy" scene: every cell has a unique style.
    fn build_style_heavy_scene(width: u16, height: u16, seed: u64) -> Buffer {
        let mut buffer = Buffer::new(width, height);
        let mut rng = seed;
        let mut next = || -> u64 {
            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1);
            rng
        };
        for y in 0..height {
            for x in 0..width {
                let v = next();
                let ch = char::from_u32(('!' as u32) + (v as u32 % 90)).unwrap_or('?');
                let fg = PackedRgba::rgb((v >> 8) as u8, (v >> 16) as u8, (v >> 24) as u8);
                let bg = if v & 3 == 0 {
                    PackedRgba::rgb((v >> 32) as u8, (v >> 40) as u8, (v >> 48) as u8)
                } else {
                    PackedRgba::TRANSPARENT
                };
                let flags = StyleFlags::from_bits_truncate((v >> 56) as u8);
                let cell = Cell::from_char(ch)
                    .with_fg(fg)
                    .with_bg(bg)
                    .with_attrs(CellAttrs::new(flags, 0));
                buffer.set_raw(x, y, cell);
            }
        }
        buffer
    }

    /// Build a "sparse-update" scene: only ~10% of cells differ between frames.
    fn build_sparse_update(base: &Buffer, seed: u64) -> Buffer {
        let mut buffer = base.clone();
        let width = base.width();
        let height = base.height();
        let mut rng = seed;
        let mut next = || -> u64 {
            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1);
            rng
        };
        let change_count = (width as usize * height as usize) / 10;
        for _ in 0..change_count {
            let v = next();
            let x = (v % width as u64) as u16;
            let y = ((v >> 16) % height as u64) as u16;
            let ch = char::from_u32(('A' as u32) + (v as u32 % 26)).unwrap_or('?');
            buffer.set_raw(x, y, Cell::from_char(ch));
        }
        buffer
    }

    #[test]
    fn snapshot_presenter_equivalence() {
        // Golden snapshot: style-heavy 40x10 scene with deterministic seed.
        // The output hash must be stable across runs.
        let buffer = build_style_heavy_scene(40, 10, 0xDEAD_CAFE_1234);
        let blank = Buffer::new(40, 10);
        let diff = BufferDiff::compute(&blank, &buffer);

        let mut presenter = test_presenter();
        presenter.present(&buffer, &diff).unwrap();
        let output = presenter.into_inner().unwrap();

        // Compute checksum for golden comparison
        let checksum = {
            let mut hash: u64 = 0xcbf29ce484222325; // FNV-1a offset basis
            for &byte in &output {
                hash ^= byte as u64;
                hash = hash.wrapping_mul(0x100000001b3); // FNV prime
            }
            hash
        };

        // Verify determinism: same seed + scene = same output
        let mut presenter2 = test_presenter();
        presenter2.present(&buffer, &diff).unwrap();
        let output2 = presenter2.into_inner().unwrap();
        assert_eq!(output, output2, "Presenter output must be deterministic");

        // Log golden checksum for the record
        let _ = checksum; // Used in JSONL test below
    }

    #[test]
    fn perf_presenter_microbench() {
        use std::env;
        use std::io::Write as _;
        use std::time::Instant;

        let width = 120u16;
        let height = 40u16;
        let seed = 0x00BE_EFCA_FE42;
        let scene = build_style_heavy_scene(width, height, seed);
        let blank = Buffer::new(width, height);
        let diff_full = BufferDiff::compute(&blank, &scene);

        // Also build a sparse update scene
        let scene2 = build_sparse_update(&scene, seed.wrapping_add(1));
        let diff_sparse = BufferDiff::compute(&scene, &scene2);

        let mut jsonl = Vec::new();
        let iterations = env::var("FTUI_PRESENTER_BENCH_ITERS")
            .ok()
            .and_then(|value| value.parse::<u32>().ok())
            .unwrap_or(50);

        let runs_full = diff_full.runs();
        let runs_sparse = diff_sparse.runs();

        let plan_rows = |runs: &[ChangeRun]| -> (usize, usize) {
            let mut idx = 0;
            let mut total_cost = 0usize;
            let mut span_count = 0usize;
            let mut prev_x = None;
            let mut prev_y = None;

            while idx < runs.len() {
                let y = runs[idx].y;
                let start = idx;
                while idx < runs.len() && runs[idx].y == y {
                    idx += 1;
                }

                let plan = cost_model::plan_row(&runs[start..idx], prev_x, prev_y);
                span_count += plan.spans().len();
                total_cost = total_cost.saturating_add(plan.total_cost());
                if let Some(last) = plan.spans().last() {
                    prev_x = Some(last.x1);
                    prev_y = Some(y);
                }
            }

            (total_cost, span_count)
        };

        for i in 0..iterations {
            let (diff_ref, buf_ref, runs_ref, label) = if i % 2 == 0 {
                (&diff_full, &scene, &runs_full, "full")
            } else {
                (&diff_sparse, &scene2, &runs_sparse, "sparse")
            };

            let plan_start = Instant::now();
            let (plan_cost, plan_spans) = plan_rows(runs_ref);
            let plan_time_us = plan_start.elapsed().as_micros() as u64;

            let mut presenter = test_presenter();
            let start = Instant::now();
            let stats = presenter.present(buf_ref, diff_ref).unwrap();
            let elapsed_us = start.elapsed().as_micros() as u64;
            let output = presenter.into_inner().unwrap();

            // FNV-1a checksum
            let checksum = {
                let mut hash: u64 = 0xcbf29ce484222325;
                for &b in &output {
                    hash ^= b as u64;
                    hash = hash.wrapping_mul(0x100000001b3);
                }
                hash
            };

            writeln!(
                &mut jsonl,
                "{{\"seed\":{seed},\"width\":{width},\"height\":{height},\
                 \"scene\":\"{label}\",\"changes\":{},\"runs\":{},\
                 \"plan_cost\":{plan_cost},\"plan_spans\":{plan_spans},\
                 \"plan_time_us\":{plan_time_us},\"bytes\":{},\
                 \"emit_time_us\":{elapsed_us},\
                 \"checksum\":\"{checksum:016x}\"}}",
                stats.cells_changed, stats.run_count, stats.bytes_emitted,
            )
            .unwrap();
        }

        let text = String::from_utf8(jsonl).unwrap();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), iterations as usize);

        // Parse and verify: full frames should be deterministic (same checksum)
        let full_checksums: Vec<&str> = lines
            .iter()
            .filter(|l| l.contains("\"full\""))
            .map(|l| {
                let start = l.find("\"checksum\":\"").unwrap() + 12;
                let end = l[start..].find('"').unwrap() + start;
                &l[start..end]
            })
            .collect();
        assert!(full_checksums.len() > 1);
        assert!(
            full_checksums.windows(2).all(|w| w[0] == w[1]),
            "Full frame checksums should be identical across runs"
        );

        // Sparse frame bytes should be less than full frame bytes
        let full_bytes: Vec<u64> = lines
            .iter()
            .filter(|l| l.contains("\"full\""))
            .map(|l| {
                let start = l.find("\"bytes\":").unwrap() + 8;
                let end = l[start..].find(',').unwrap() + start;
                l[start..end].parse::<u64>().unwrap()
            })
            .collect();
        let sparse_bytes: Vec<u64> = lines
            .iter()
            .filter(|l| l.contains("\"sparse\""))
            .map(|l| {
                let start = l.find("\"bytes\":").unwrap() + 8;
                let end = l[start..].find(',').unwrap() + start;
                l[start..end].parse::<u64>().unwrap()
            })
            .collect();

        let avg_full: u64 = full_bytes.iter().sum::<u64>() / full_bytes.len() as u64;
        let avg_sparse: u64 = sparse_bytes.iter().sum::<u64>() / sparse_bytes.len() as u64;
        assert!(
            avg_sparse < avg_full,
            "Sparse updates ({avg_sparse}B) should emit fewer bytes than full ({avg_full}B)"
        );
    }

    #[test]
    fn perf_emit_style_delta_microbench() {
        use std::env;
        use std::io::Write as _;
        use std::time::Instant;

        let iterations = env::var("FTUI_EMIT_STYLE_BENCH_ITERS")
            .ok()
            .and_then(|value| value.parse::<u32>().ok())
            .unwrap_or(200);
        let mode = env::var("FTUI_EMIT_STYLE_BENCH_MODE").unwrap_or_default();
        let emit_json = mode != "raw";

        let mut styles = Vec::with_capacity(128);
        let mut rng = 0x00A5_A51E_AF42_u64;
        let mut next = || -> u64 {
            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1);
            rng
        };

        for _ in 0..128 {
            let v = next();
            let fg = PackedRgba::rgb(
                (v & 0xFF) as u8,
                ((v >> 8) & 0xFF) as u8,
                ((v >> 16) & 0xFF) as u8,
            );
            let bg = PackedRgba::rgb(
                ((v >> 24) & 0xFF) as u8,
                ((v >> 32) & 0xFF) as u8,
                ((v >> 40) & 0xFF) as u8,
            );
            let flags = StyleFlags::from_bits_truncate((v >> 48) as u8);
            let cell = Cell::from_char('A')
                .with_fg(fg)
                .with_bg(bg)
                .with_attrs(CellAttrs::new(flags, 0));
            styles.push(CellStyle::from_cell(&cell));
        }

        let mut presenter = test_presenter();
        let mut jsonl = Vec::new();
        let mut sink = 0u64;

        for i in 0..iterations {
            let old = styles[i as usize % styles.len()];
            let new = styles[(i as usize + 1) % styles.len()];

            presenter.writer.reset_counter();
            presenter.writer.inner_mut().get_mut().clear();

            let start = Instant::now();
            presenter.emit_style_delta(old, new).unwrap();
            let elapsed_us = start.elapsed().as_micros() as u64;
            let bytes = presenter.writer.bytes_written();

            if emit_json {
                writeln!(
                    &mut jsonl,
                    "{{\"iter\":{i},\"emit_time_us\":{elapsed_us},\"bytes\":{bytes}}}"
                )
                .unwrap();
            } else {
                sink = sink.wrapping_add(elapsed_us ^ bytes);
            }
        }

        if emit_json {
            let text = String::from_utf8(jsonl).unwrap();
            let lines: Vec<&str> = text.lines().collect();
            assert_eq!(lines.len() as u32, iterations);
        } else {
            std::hint::black_box(sink);
        }
    }

    #[test]
    fn e2e_presenter_stress_deterministic() {
        // Deterministic stress test: seeded style churn across multiple frames,
        // verifying no visual divergence via terminal model.
        use crate::terminal_model::TerminalModel;

        let width = 60u16;
        let height = 20u16;
        let num_frames = 10;

        let mut prev_buffer = Buffer::new(width, height);
        let mut presenter = test_presenter();
        let mut model = TerminalModel::new(width as usize, height as usize);
        let mut rng = 0x5D2E_55DE_5D42_u64;
        let mut next = || -> u64 {
            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1);
            rng
        };

        for _frame in 0..num_frames {
            // Build next frame: modify ~20% of cells each time
            let mut buffer = prev_buffer.clone();
            let changes = (width as usize * height as usize) / 5;
            for _ in 0..changes {
                let v = next();
                let x = (v % width as u64) as u16;
                let y = ((v >> 16) % height as u64) as u16;
                let ch = char::from_u32(('!' as u32) + (v as u32 % 90)).unwrap_or('?');
                let fg = PackedRgba::rgb((v >> 8) as u8, (v >> 24) as u8, (v >> 40) as u8);
                let cell = Cell::from_char(ch).with_fg(fg);
                buffer.set_raw(x, y, cell);
            }

            let diff = BufferDiff::compute(&prev_buffer, &buffer);
            presenter.present(&buffer, &diff).unwrap();

            prev_buffer = buffer;
        }

        // Get all output and verify final frame via terminal model
        let output = presenter.into_inner().unwrap();
        model.process(&output);

        // Verify a sampling of cells match the final buffer
        let mut checked = 0;
        for y in 0..height {
            for x in 0..width {
                let buf_cell = prev_buffer.get_unchecked(x, y);
                if !buf_cell.is_empty()
                    && let Some(model_cell) = model.cell(x as usize, y as usize)
                {
                    let expected = buf_cell.content.as_char().unwrap_or(' ');
                    let mut buf = [0u8; 4];
                    let expected_str = expected.encode_utf8(&mut buf);
                    if model_cell.text.as_str() == expected_str {
                        checked += 1;
                    }
                }
            }
        }

        // At least 80% of non-empty cells should match (some may be
        // overwritten by cursor positioning sequences in the model)
        let total_nonempty = (0..height)
            .flat_map(|y| (0..width).map(move |x| (x, y)))
            .filter(|&(x, y)| !prev_buffer.get_unchecked(x, y).is_empty())
            .count();

        assert!(
            checked > total_nonempty * 80 / 100,
            "Frame {num_frames}: only {checked}/{total_nonempty} cells match final buffer"
        );
    }

    #[test]
    fn style_state_persists_across_frames() {
        let mut presenter = test_presenter();
        let fg = PackedRgba::rgb(100, 150, 200);

        // First frame - set style
        let mut buffer = Buffer::new(5, 1);
        buffer.set_raw(0, 0, Cell::from_char('A').with_fg(fg));
        let old = Buffer::new(5, 1);
        let diff = BufferDiff::compute(&old, &buffer);
        presenter.present(&buffer, &diff).unwrap();

        // Style should be tracked (but reset at frame end per the implementation)
        // After present(), current_style is None due to sgr_reset at frame end
        assert!(
            presenter.current_style.is_none(),
            "Style should be reset after frame end"
        );
    }

    // =========================================================================
    // Edge-case tests (bd-27tya)
    // =========================================================================

    // --- Cost model boundary values ---

    #[test]
    fn cost_cup_zero_zero() {
        // CUP at (0,0) → "\x1b[1;1H" = 6 bytes
        assert_eq!(cost_model::cup_cost(0, 0), 6);
    }

    #[test]
    fn cost_cup_max_max() {
        // CUP at (u16::MAX, u16::MAX) → "\x1b[65536;65536H"
        // 2 (CSI) + 5 (row digits) + 1 (;) + 5 (col digits) + 1 (H) = 14
        assert_eq!(cost_model::cup_cost(u16::MAX, u16::MAX), 14);
    }

    #[test]
    fn cost_cha_zero() {
        // CHA at col 0 → "\x1b[1G" = 4 bytes
        assert_eq!(cost_model::cha_cost(0), 4);
    }

    #[test]
    fn cost_cha_max() {
        // CHA at col u16::MAX → "\x1b[65536G" = 8 bytes
        assert_eq!(cost_model::cha_cost(u16::MAX), 8);
    }

    #[test]
    fn cost_cuf_zero_is_free() {
        assert_eq!(cost_model::cuf_cost(0), 0);
    }

    #[test]
    fn cost_cuf_one_is_three() {
        // CUF(1) = "\x1b[C" = 3 bytes
        assert_eq!(cost_model::cuf_cost(1), 3);
    }

    #[test]
    fn cost_cuf_two_has_digit() {
        // CUF(2) = "\x1b[2C" = 4 bytes
        assert_eq!(cost_model::cuf_cost(2), 4);
    }

    #[test]
    fn cost_cuf_max() {
        // CUF(u16::MAX) = "\x1b[65535C" = 3 + 5 = 8 bytes
        assert_eq!(cost_model::cuf_cost(u16::MAX), 8);
    }

    #[test]
    fn cost_cheapest_move_already_at_target() {
        assert_eq!(cost_model::cheapest_move_cost(Some(5), Some(3), 5, 3), 0);
    }

    #[test]
    fn cost_cheapest_move_unknown_position() {
        // When from is unknown, can only use CUP
        let cost = cost_model::cheapest_move_cost(None, None, 5, 3);
        assert_eq!(cost, cost_model::cup_cost(3, 5));
    }

    #[test]
    fn cost_cheapest_move_known_y_unknown_x() {
        // from_x=None, from_y=Some → still uses CUP
        let cost = cost_model::cheapest_move_cost(None, Some(3), 5, 3);
        assert_eq!(cost, cost_model::cup_cost(3, 5));
    }

    #[test]
    fn cost_cheapest_move_backward_same_row() {
        // On the same row, CUP is strictly dominated by CHA.
        let cost = cost_model::cheapest_move_cost(Some(50), Some(0), 5, 0);
        let cha = cost_model::cha_cost(5);
        let cub = cost_model::cub_cost(45);
        assert_eq!(cost, cha.min(cub));
        assert!(cost_model::cup_cost(0, 5) > cha);
    }

    #[test]
    fn cost_cheapest_move_forward_same_row() {
        let cost = cost_model::cheapest_move_cost(Some(5), Some(0), 50, 0);
        let cha = cost_model::cha_cost(50);
        let cuf = cost_model::cuf_cost(45);
        assert_eq!(cost, cha.min(cuf));
        assert!(cost_model::cup_cost(0, 50) > cha);
    }

    #[test]
    fn cost_cheapest_move_same_row_same_col() {
        // Same (x, y) via the (fx, fy) == (to_x, to_y) check
        assert_eq!(cost_model::cheapest_move_cost(Some(0), Some(0), 0, 0), 0);
    }

    // --- CUP/CHA/CUF cost accuracy across digit boundaries ---

    #[test]
    fn cost_cup_digit_boundaries() {
        let mut buf = Vec::new();
        for (row, col) in [
            (0u16, 0u16),
            (8, 8),
            (9, 9),
            (98, 98),
            (99, 99),
            (998, 998),
            (999, 999),
            (9998, 9998),
            (9999, 9999),
            (u16::MAX, u16::MAX),
        ] {
            buf.clear();
            ansi::cup(&mut buf, row, col).unwrap();
            assert_eq!(
                buf.len(),
                cost_model::cup_cost(row, col),
                "CUP cost mismatch at ({row}, {col})"
            );
        }
    }

    #[test]
    fn cost_cha_digit_boundaries() {
        let mut buf = Vec::new();
        for col in [0u16, 8, 9, 98, 99, 998, 999, 9998, 9999, u16::MAX] {
            buf.clear();
            ansi::cha(&mut buf, col).unwrap();
            assert_eq!(
                buf.len(),
                cost_model::cha_cost(col),
                "CHA cost mismatch at col {col}"
            );
        }
    }

    #[test]
    fn cost_cuf_digit_boundaries() {
        let mut buf = Vec::new();
        for n in [1u16, 2, 9, 10, 99, 100, 999, 1000, 9999, 10000, u16::MAX] {
            buf.clear();
            ansi::cuf(&mut buf, n).unwrap();
            assert_eq!(
                buf.len(),
                cost_model::cuf_cost(n),
                "CUF cost mismatch for n={n}"
            );
        }
    }

    // --- RowPlan scratch reuse ---

    #[test]
    fn plan_row_reuse_matches_plan_row() {
        let runs = [
            ChangeRun::new(5, 2, 4),
            ChangeRun::new(5, 8, 10),
            ChangeRun::new(5, 20, 25),
        ];
        let plan1 = cost_model::plan_row(&runs, Some(0), Some(5));
        let mut scratch = cost_model::RowPlanScratch::default();
        let plan2 = cost_model::plan_row_reuse(&runs, Some(0), Some(5), &mut scratch);
        assert_eq!(plan1, plan2);
    }

    #[test]
    fn plan_row_reuse_single_run_matches_plan_row() {
        let runs = [ChangeRun::new(7, 18, 24)];
        let plan1 = cost_model::plan_row(&runs, Some(2), Some(7));
        let mut scratch = cost_model::RowPlanScratch::default();
        let plan2 = cost_model::plan_row_reuse(&runs, Some(2), Some(7), &mut scratch);
        assert_eq!(plan1, plan2);
        assert_eq!(
            plan2.total_cost(),
            cost_model::cheapest_move_cost(Some(2), Some(7), 18, 7) + runs[0].len()
        );
    }

    #[test]
    fn plan_row_reuse_across_different_sizes() {
        // Use scratch with a large row first, then a small row
        let mut scratch = cost_model::RowPlanScratch::default();

        let large_runs: Vec<ChangeRun> = (0..20)
            .map(|i| ChangeRun::new(0, i * 4, i * 4 + 1))
            .collect();
        let plan_large = cost_model::plan_row_reuse(&large_runs, None, None, &mut scratch);
        assert!(!plan_large.spans().is_empty());

        let small_runs = [ChangeRun::new(1, 5, 8)];
        let plan_small = cost_model::plan_row_reuse(&small_runs, None, None, &mut scratch);
        assert_eq!(plan_small.spans().len(), 1);
        assert_eq!(plan_small.spans()[0].x0, 5);
        assert_eq!(plan_small.spans()[0].x1, 8);
    }

    // --- DP gap boundary (exactly 32 and 33 cells) ---

    #[test]
    fn plan_row_gap_exactly_32_cells() {
        // Two runs with exactly 32-cell gap: run at 0-0 and 33-33
        // gap = 33 - 0 + 1 - 2 = 32 cells
        let runs = [ChangeRun::new(0, 0, 0), ChangeRun::new(0, 33, 33)];
        let plan = cost_model::plan_row(&runs, None, None);
        // 32-cell gap is at the break boundary; the DP may still consider merging
        // since the check is `gap_cells > 32` (strictly greater)
        // gap = 34 total - 2 changed = 32, which is NOT > 32, so merge is considered
        assert!(
            plan.spans().len() <= 2,
            "32-cell gap should still consider merge"
        );
    }

    #[test]
    fn plan_row_gap_33_cells_stays_sparse() {
        // Two runs with 33-cell gap: run at 0-0 and 34-34
        // gap = 34 - 0 + 1 - 2 = 33 > 32, so merge is NOT considered
        let runs = [ChangeRun::new(0, 0, 0), ChangeRun::new(0, 34, 34)];
        let plan = cost_model::plan_row(&runs, None, None);
        assert_eq!(
            plan.spans().len(),
            2,
            "33-cell gap should stay sparse (gap > 32 breaks)"
        );
    }

    // --- SmallVec spill: >4 separate spans ---

    #[test]
    fn plan_row_many_sparse_spans() {
        // 6 runs with 34+ cell gaps between them (each gap > 32, no merging)
        let runs = [
            ChangeRun::new(0, 0, 0),
            ChangeRun::new(0, 40, 40),
            ChangeRun::new(0, 80, 80),
            ChangeRun::new(0, 120, 120),
            ChangeRun::new(0, 160, 160),
            ChangeRun::new(0, 200, 200),
        ];
        let plan = cost_model::plan_row(&runs, None, None);
        // All gaps are > 32, so no merging possible
        assert_eq!(plan.spans().len(), 6, "Should have 6 separate sparse spans");
    }

    // --- CellStyle ---

    #[test]
    fn cell_style_default_is_transparent_no_attrs() {
        let style = CellStyle::default();
        assert_eq!(style.fg, PackedRgba::TRANSPARENT);
        assert_eq!(style.bg, PackedRgba::TRANSPARENT);
        assert!(style.attrs.is_empty());
    }

    #[test]
    fn cell_style_from_cell_captures_all() {
        let fg = PackedRgba::rgb(10, 20, 30);
        let bg = PackedRgba::rgb(40, 50, 60);
        let flags = StyleFlags::BOLD | StyleFlags::ITALIC;
        let cell = Cell::from_char('X')
            .with_fg(fg)
            .with_bg(bg)
            .with_attrs(CellAttrs::new(flags, 5));
        let style = CellStyle::from_cell(&cell);
        assert_eq!(style.fg, fg);
        assert_eq!(style.bg, bg);
        assert_eq!(style.attrs, flags);
    }

    #[test]
    fn cell_style_eq_and_clone() {
        let a = CellStyle {
            fg: PackedRgba::rgb(1, 2, 3),
            bg: PackedRgba::TRANSPARENT,
            attrs: StyleFlags::DIM,
        };
        let b = a;
        assert_eq!(a, b);
    }

    // --- SGR length estimation ---

    #[test]
    fn sgr_flags_len_empty() {
        assert_eq!(Presenter::<Vec<u8>>::sgr_flags_len(StyleFlags::empty()), 0);
    }

    #[test]
    fn sgr_flags_len_single() {
        // Single flag: "\x1b[1m" = 4 bytes → 3 + digits(code) + 0 separators
        let len = Presenter::<Vec<u8>>::sgr_flags_len(StyleFlags::BOLD);
        assert!(len > 0);
        // Verify by actually emitting
        let mut buf = Vec::new();
        ansi::sgr_flags(&mut buf, StyleFlags::BOLD).unwrap();
        assert_eq!(len as usize, buf.len());
    }

    #[test]
    fn sgr_flags_len_multiple() {
        let flags = StyleFlags::BOLD | StyleFlags::ITALIC | StyleFlags::UNDERLINE;
        let len = Presenter::<Vec<u8>>::sgr_flags_len(flags);
        let mut buf = Vec::new();
        ansi::sgr_flags(&mut buf, flags).unwrap();
        assert_eq!(len as usize, buf.len());
    }

    #[test]
    fn sgr_flags_off_len_empty() {
        assert_eq!(
            Presenter::<Vec<u8>>::sgr_flags_off_len(StyleFlags::empty()),
            0
        );
    }

    #[test]
    fn sgr_rgb_len_matches_actual() {
        let color = PackedRgba::rgb(0, 0, 0);
        let estimated = Presenter::<Vec<u8>>::sgr_rgb_len(color);
        // "\x1b[38;2;0;0;0m" = 2(CSI) + "38;2;" + "0;0;0" + "m" but sgr_rgb_len
        // is used for cost comparison, not exact output. Just check > 0.
        assert!(estimated > 0);
    }

    #[test]
    fn sgr_rgb_len_large_values() {
        let color = PackedRgba::rgb(255, 255, 255);
        let small_color = PackedRgba::rgb(0, 0, 0);
        let large_len = Presenter::<Vec<u8>>::sgr_rgb_len(color);
        let small_len = Presenter::<Vec<u8>>::sgr_rgb_len(small_color);
        // 255,255,255 has more digits than 0,0,0
        assert!(large_len > small_len);
    }

    #[test]
    fn dec_len_u8_boundaries() {
        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(0), 1);
        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(9), 1);
        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(10), 2);
        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(99), 2);
        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(100), 3);
        assert_eq!(Presenter::<Vec<u8>>::dec_len_u8(255), 3);
    }

    // --- Style delta corner cases ---

    #[test]
    fn sgr_delta_all_attrs_removed_at_once() {
        let mut presenter = test_presenter();
        let all_flags = StyleFlags::BOLD
            | StyleFlags::DIM
            | StyleFlags::ITALIC
            | StyleFlags::UNDERLINE
            | StyleFlags::BLINK
            | StyleFlags::REVERSE
            | StyleFlags::STRIKETHROUGH;
        let old = CellStyle {
            fg: PackedRgba::rgb(100, 100, 100),
            bg: PackedRgba::TRANSPARENT,
            attrs: all_flags,
        };
        let new = CellStyle {
            fg: PackedRgba::rgb(100, 100, 100),
            bg: PackedRgba::TRANSPARENT,
            attrs: StyleFlags::empty(),
        };

        presenter.current_style = Some(old);
        presenter.emit_style_delta(old, new).unwrap();
        let output = presenter.into_inner().unwrap();

        // Should either use individual off codes or fall back to full reset
        // Either way, output should be non-empty
        assert!(!output.is_empty());
    }

    #[test]
    fn sgr_delta_fg_to_transparent() {
        let mut presenter = test_presenter();
        let old = CellStyle {
            fg: PackedRgba::rgb(200, 100, 50),
            bg: PackedRgba::TRANSPARENT,
            attrs: StyleFlags::empty(),
        };
        let new = CellStyle {
            fg: PackedRgba::TRANSPARENT,
            bg: PackedRgba::TRANSPARENT,
            attrs: StyleFlags::empty(),
        };

        presenter.current_style = Some(old);
        presenter.emit_style_delta(old, new).unwrap();
        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);

        // When going to TRANSPARENT fg, the delta should emit the default fg code
        // or reset. Either way, output should be non-empty.
        assert!(!output.is_empty(), "Should emit fg removal: {output_str:?}");
    }

    #[test]
    fn sgr_delta_bg_to_transparent() {
        let mut presenter = test_presenter();
        let old = CellStyle {
            fg: PackedRgba::TRANSPARENT,
            bg: PackedRgba::rgb(30, 60, 90),
            attrs: StyleFlags::empty(),
        };
        let new = CellStyle {
            fg: PackedRgba::TRANSPARENT,
            bg: PackedRgba::TRANSPARENT,
            attrs: StyleFlags::empty(),
        };

        presenter.current_style = Some(old);
        presenter.emit_style_delta(old, new).unwrap();
        let output = presenter.into_inner().unwrap();
        assert!(!output.is_empty(), "Should emit bg removal");
    }

    #[test]
    fn sgr_delta_dim_removed_bold_stays() {
        // Reverse of the bold-dim collateral test: removing DIM while BOLD stays.
        // DIM off (code 22) also disables BOLD. If BOLD should remain,
        // the delta engine must re-enable BOLD.
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);

        let attrs1 = CellAttrs::new(StyleFlags::BOLD | StyleFlags::DIM, 0);
        let attrs2 = CellAttrs::new(StyleFlags::BOLD, 0);
        buffer.set_raw(0, 0, Cell::from_char('A').with_attrs(attrs1));
        buffer.set_raw(1, 0, Cell::from_char('B').with_attrs(attrs2));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Should contain dim-off (22) and then bold re-enable (1)
        assert!(
            output_str.contains("\x1b[22m"),
            "Expected dim-off (22) in: {output_str:?}"
        );
        assert!(
            output_str.contains("\x1b[1m"),
            "Expected bold re-enable (1) in: {output_str:?}"
        );
    }

    #[test]
    fn sgr_delta_fallback_to_full_reset_when_cheaper() {
        // Many attrs removed + colors changed → delta is expensive, full reset is cheaper
        let mut presenter = test_presenter();
        let old = CellStyle {
            fg: PackedRgba::rgb(10, 20, 30),
            bg: PackedRgba::rgb(40, 50, 60),
            attrs: StyleFlags::BOLD
                | StyleFlags::DIM
                | StyleFlags::ITALIC
                | StyleFlags::UNDERLINE
                | StyleFlags::STRIKETHROUGH,
        };
        let new = CellStyle {
            fg: PackedRgba::TRANSPARENT,
            bg: PackedRgba::TRANSPARENT,
            attrs: StyleFlags::empty(),
        };

        presenter.current_style = Some(old);
        presenter.emit_style_delta(old, new).unwrap();
        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);

        // With everything removed and going to default, full reset ("\x1b[0m") is cheapest
        assert!(
            output_str.contains("\x1b[0m"),
            "Expected full reset fallback: {output_str:?}"
        );
    }

    // --- Content emission edge cases ---

    #[test]
    fn emit_cell_control_char_replaced_with_fffd() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(0);
        presenter.cursor_y = Some(0);

        // Control character '\x01' has width 0, not empty, not continuation.
        // The zero-width-content path replaces it with U+FFFD.
        let cell = Cell::from_char('\x01');
        presenter.emit_cell(0, &cell, None, None).unwrap();
        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);

        // Should emit U+FFFD (replacement character), not the raw control char
        assert!(
            output_str.contains('\u{FFFD}'),
            "Control char (width 0) should be replaced with U+FFFD, got: {output:?}"
        );
        assert!(
            !output.contains(&0x01),
            "Raw control char should not appear"
        );
    }

    #[test]
    fn emit_content_empty_cell_emits_space() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(0);
        presenter.cursor_y = Some(0);

        let cell = Cell::default();
        assert!(cell.is_empty());
        presenter.emit_cell(0, &cell, None, None).unwrap();
        let output = presenter.into_inner().unwrap();
        assert!(output.contains(&b' '), "Empty cell should emit space");
    }

    #[test]
    fn emit_content_ascii_char_emits_single_byte() {
        let mut presenter = test_presenter();
        presenter
            .emit_content(PreparedContent::Char('A'), 1, None)
            .unwrap();
        let output = presenter.into_inner().unwrap();
        assert_eq!(output, b"A");
    }

    #[test]
    fn emit_content_ascii_control_sanitizes_to_space() {
        let mut presenter = test_presenter();
        presenter
            .emit_content(PreparedContent::Char('\n'), 1, None)
            .unwrap();
        let output = presenter.into_inner().unwrap();
        assert_eq!(output, b" ");
    }

    #[test]
    fn prepared_content_ascii_widths_match_char_width_contract() {
        for ch in ['A', ' ', '\n', '\r', '\x1f', '\x7f'] {
            let cell = Cell::from_char(ch);
            let (prepared, width) = PreparedContent::from_cell(&cell);
            assert_eq!(prepared, PreparedContent::Char(ch));
            assert_eq!(width, char_width(ch), "width mismatch for {ch:?}");
        }
    }

    #[test]
    fn prepared_content_tab_uses_canonicalized_space() {
        let cell = Cell::from_char('\t');
        let (prepared, width) = PreparedContent::from_cell(&cell);
        assert_eq!(prepared, PreparedContent::Char(' '));
        assert_eq!(width, 1);
    }

    #[test]
    fn prepared_content_nul_uses_empty_cell_representation() {
        let cell = Cell::from_char('\0');
        let (prepared, width) = PreparedContent::from_cell(&cell);
        assert_eq!(prepared, PreparedContent::Empty);
        assert_eq!(width, 0);
    }

    #[test]
    fn emit_content_grapheme_sanitizes_escape_sequences() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(0);
        presenter.cursor_y = Some(0);

        let mut pool = GraphemePool::new();
        let gid = pool.intern("A\x1b[31mB\x1b[0m", 2);
        let cell = Cell::new(CellContent::from_grapheme(gid));
        presenter.emit_cell(0, &cell, Some(&pool), None).unwrap();

        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);
        assert!(
            output_str.contains("AB"),
            "sanitized grapheme should preserve visible payload"
        );
        assert!(
            !output_str.contains("\x1b[31m"),
            "raw escape sequence must not be emitted"
        );
    }

    #[test]
    fn emit_content_grapheme_width_mismatch_uses_placeholders() {
        let mut presenter = test_presenter();
        let mut pool = GraphemePool::new();
        let gid = pool.intern("A\x07", 2);

        presenter
            .emit_content(PreparedContent::Grapheme(gid), 2, Some(&pool))
            .unwrap();

        let output = presenter.into_inner().unwrap();
        assert_eq!(output, b"??");
    }

    #[test]
    fn wide_grapheme_tail_repair_does_not_blank_unrelated_following_cells() {
        let mut presenter = test_presenter();
        let mut pool = GraphemePool::new();
        let gid = pool.intern("XYZ", 3);
        let mut buffer = Buffer::new(8, 1);

        buffer.set_raw(0, 0, Cell::new(CellContent::from_grapheme(gid)));
        buffer.set_raw(1, 0, Cell::from_char('a'));
        buffer.set_raw(2, 0, Cell::from_char('b'));
        buffer.set_raw(3, 0, Cell::from_char('c'));

        let old = Buffer::new(8, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter
            .present_with_pool(&buffer, &diff, Some(&pool), None)
            .unwrap();

        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);
        let visible = sanitize(output_str.as_ref());

        assert!(
            visible.contains("XYZabc"),
            "width-3 grapheme repair must not erase following cells: {:?}",
            visible
        );
    }

    // --- Continuation cell cursor_x variants ---

    #[test]
    fn continuation_cell_cursor_x_none() {
        let mut presenter = test_presenter();
        // cursor_x = None -> defensive path, clears orphan continuation.
        presenter.cursor_x = None;
        presenter.cursor_y = Some(0);

        let cell = Cell::CONTINUATION;
        presenter.emit_cell(5, &cell, None, None).unwrap();
        let output = presenter.into_inner().unwrap();

        // Should emit a clearing space.
        assert!(
            output.contains(&b' '),
            "Should emit a space for continuation with unknown cursor_x"
        );
    }

    #[test]
    fn continuation_cell_cursor_already_past() {
        let mut presenter = test_presenter();
        // cursor_x > cell x → cursor already advanced past, skip
        presenter.cursor_x = Some(10);
        presenter.cursor_y = Some(0);

        let cell = Cell::CONTINUATION;
        presenter.emit_cell(5, &cell, None, None).unwrap();
        let output = presenter.into_inner().unwrap();

        // Should produce no output (cursor already past)
        assert!(
            output.is_empty(),
            "Should skip continuation when cursor is past it"
        );
    }

    // --- clear_line ---

    #[test]
    fn clear_line_positions_cursor_and_erases() {
        let mut presenter = test_presenter();
        presenter.clear_line(5).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Should contain CUP to row 5 col 0 and erase line
        assert!(
            output_str.contains("\x1b[2K"),
            "Should contain erase line sequence"
        );
    }

    // --- into_inner ---

    #[test]
    fn into_inner_returns_accumulated_output() {
        let mut presenter = test_presenter();
        presenter.position_cursor(0, 0).unwrap();
        let inner = presenter.into_inner().unwrap();
        assert!(!inner.is_empty(), "into_inner should return buffered data");
    }

    // --- move_cursor_optimal edge cases ---

    #[test]
    fn move_cursor_optimal_same_row_forward_large() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(0);
        presenter.cursor_y = Some(0);

        // Forward by 100 columns. CUF(100) vs CHA(100) vs CUP(0,100)
        presenter.move_cursor_optimal(100, 0).unwrap();
        let output = presenter.into_inner().unwrap();

        // Verify the output picks the cheapest move
        let cuf = cost_model::cuf_cost(100);
        let cha = cost_model::cha_cost(100);
        let cup = cost_model::cup_cost(0, 100);
        let cheapest = cuf.min(cha).min(cup);
        assert_eq!(output.len(), cheapest, "Should pick cheapest cursor move");
    }

    #[test]
    fn move_cursor_optimal_same_row_backward_to_zero() {
        let mut presenter = test_presenter();
        presenter.cursor_x = Some(50);
        presenter.cursor_y = Some(0);

        presenter.move_cursor_optimal(0, 0).unwrap();
        let output = presenter.into_inner().unwrap();

        // CHA(0) → "\x1b[1G" = 4 bytes, CUP(0,0) = "\x1b[1;1H" = 6 bytes
        // CHA should win
        let mut expected = Vec::new();
        ansi::cha(&mut expected, 0).unwrap();
        assert_eq!(output, expected, "Should use CHA for backward to col 0");
    }

    #[test]
    fn move_cursor_optimal_unknown_cursor_uses_cup() {
        let mut presenter = test_presenter();
        // cursor_x and cursor_y are None
        presenter.move_cursor_optimal(10, 5).unwrap();
        let output = presenter.into_inner().unwrap();
        let mut expected = Vec::new();
        ansi::cup(&mut expected, 5, 10).unwrap();
        assert_eq!(output, expected, "Should use CUP when cursor is unknown");
    }

    // --- Present with sync: verify wrap order ---

    #[test]
    fn sync_wrap_order_begin_content_reset_end() {
        let mut presenter = test_presenter_with_sync();
        let mut buffer = Buffer::new(3, 1);
        buffer.set_raw(0, 0, Cell::from_char('Z'));

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);

        let sync_begin_pos = output
            .windows(ansi::SYNC_BEGIN.len())
            .position(|w| w == ansi::SYNC_BEGIN)
            .expect("sync begin missing");
        let z_pos = output
            .iter()
            .position(|&b| b == b'Z')
            .expect("character Z missing");
        let reset_pos = output
            .windows(b"\x1b[0m".len())
            .rposition(|w| w == b"\x1b[0m")
            .expect("SGR reset missing");
        let sync_end_pos = output
            .windows(ansi::SYNC_END.len())
            .rposition(|w| w == ansi::SYNC_END)
            .expect("sync end missing");

        assert!(sync_begin_pos < z_pos, "sync begin before content");
        assert!(z_pos < reset_pos, "content before reset");
        assert!(reset_pos < sync_end_pos, "reset before sync end");
    }

    // --- Multi-frame style state ---

    #[test]
    fn style_none_after_each_frame() {
        let mut presenter = test_presenter();
        let fg = PackedRgba::rgb(255, 128, 64);

        for _ in 0..5 {
            let mut buffer = Buffer::new(3, 1);
            buffer.set_raw(0, 0, Cell::from_char('X').with_fg(fg));
            let old = Buffer::new(3, 1);
            let diff = BufferDiff::compute(&old, &buffer);
            presenter.present(&buffer, &diff).unwrap();

            // After each present(), current_style should be None (reset at frame end)
            assert!(
                presenter.current_style.is_none(),
                "Style should be None after frame end"
            );
            assert!(
                presenter.current_link.is_none(),
                "Link should be None after frame end"
            );
        }
    }

    // --- Link state after present with open link ---

    #[test]
    fn link_closed_at_frame_end_even_if_all_cells_linked() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(3, 1);
        let mut links = LinkRegistry::new();
        let link_id = links.register("https://all-linked.test");

        // All cells have the same link
        for x in 0..3 {
            buffer.set_raw(
                x,
                0,
                Cell::from_char('L').with_attrs(CellAttrs::new(StyleFlags::empty(), link_id)),
            );
        }

        let old = Buffer::new(3, 1);
        let diff = BufferDiff::compute(&old, &buffer);
        presenter
            .present_with_pool(&buffer, &diff, None, Some(&links))
            .unwrap();

        // After present, current_link must be None (closed at frame end)
        assert!(
            presenter.current_link.is_none(),
            "Link must be closed at frame end"
        );
    }

    // --- PresentStats ---

    #[test]
    fn present_stats_empty_diff() {
        let mut presenter = test_presenter();
        let buffer = Buffer::new(10, 10);
        let diff = BufferDiff::new();
        let stats = presenter.present(&buffer, &diff).unwrap();

        assert_eq!(stats.cells_changed, 0);
        assert_eq!(stats.run_count, 0);
        // bytes_emitted includes the SGR reset
        assert!(stats.bytes_emitted > 0);
    }

    #[test]
    fn present_stats_full_row() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(10, 1);
        for x in 0..10 {
            buffer.set_raw(x, 0, Cell::from_char('A'));
        }
        let old = Buffer::new(10, 1);
        let diff = BufferDiff::compute(&old, &buffer);
        let stats = presenter.present(&buffer, &diff).unwrap();

        assert_eq!(stats.cells_changed, 10);
        assert!(stats.run_count >= 1);
        assert!(stats.bytes_emitted > 10, "Should include ANSI overhead");
    }

    // --- Capabilities accessor ---

    #[test]
    fn capabilities_accessor() {
        let mut caps = TerminalCapabilities::basic();
        caps.sync_output = true;
        let presenter = Presenter::new(Vec::<u8>::new(), caps);
        assert!(presenter.capabilities().sync_output);
    }

    // --- Flush ---

    #[test]
    fn flush_succeeds_on_empty_presenter() {
        let mut presenter = test_presenter();
        presenter.flush().unwrap();
        let output = get_output(presenter);
        assert!(output.is_empty());
    }

    // --- RowPlan total_cost ---

    #[test]
    fn row_plan_total_cost_matches_dp() {
        let runs = [ChangeRun::new(3, 5, 10), ChangeRun::new(3, 15, 20)];
        let plan = cost_model::plan_row(&runs, None, None);
        assert!(plan.total_cost() > 0);
        // The total cost includes move costs + cell costs
        // Just verify it's consistent (non-zero) and accessible
    }

    // --- Style delta: same attrs, only colors change (hot path) ---

    #[test]
    fn sgr_delta_hot_path_only_fg_change() {
        let mut presenter = test_presenter();
        let old = CellStyle {
            fg: PackedRgba::rgb(255, 0, 0),
            bg: PackedRgba::rgb(0, 0, 0),
            attrs: StyleFlags::BOLD | StyleFlags::ITALIC,
        };
        let new = CellStyle {
            fg: PackedRgba::rgb(0, 255, 0),
            bg: PackedRgba::rgb(0, 0, 0),
            attrs: StyleFlags::BOLD | StyleFlags::ITALIC, // same attrs
        };

        presenter.current_style = Some(old);
        presenter.emit_style_delta(old, new).unwrap();
        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);

        // Only fg should change, no reset
        assert!(output_str.contains("38;2;0;255;0"), "Should emit new fg");
        assert!(
            !output_str.contains("\x1b[0m"),
            "No reset needed for color-only change"
        );
        // Should NOT re-emit attrs
        assert!(
            !output_str.contains("\x1b[1m"),
            "Bold should not be re-emitted"
        );
    }

    #[test]
    fn sgr_delta_hot_path_both_colors_change() {
        let mut presenter = test_presenter();
        let old = CellStyle {
            fg: PackedRgba::rgb(1, 2, 3),
            bg: PackedRgba::rgb(4, 5, 6),
            attrs: StyleFlags::UNDERLINE,
        };
        let new = CellStyle {
            fg: PackedRgba::rgb(7, 8, 9),
            bg: PackedRgba::rgb(10, 11, 12),
            attrs: StyleFlags::UNDERLINE, // same
        };

        presenter.current_style = Some(old);
        presenter.emit_style_delta(old, new).unwrap();
        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);

        assert!(output_str.contains("38;2;7;8;9"), "Should emit new fg");
        assert!(output_str.contains("48;2;10;11;12"), "Should emit new bg");
        assert!(!output_str.contains("\x1b[0m"), "No reset for color-only");
    }

    // --- Style full apply ---

    #[test]
    fn emit_style_full_default_is_just_reset() {
        let mut presenter = test_presenter();
        let default_style = CellStyle::default();
        presenter.emit_style_full(default_style).unwrap();
        let output = presenter.into_inner().unwrap();

        // Default style (transparent fg/bg, no attrs) should just be reset
        assert_eq!(output, b"\x1b[0m");
    }

    #[test]
    fn emit_style_full_with_all_properties() {
        let mut presenter = test_presenter();
        let style = CellStyle {
            fg: PackedRgba::rgb(10, 20, 30),
            bg: PackedRgba::rgb(40, 50, 60),
            attrs: StyleFlags::BOLD | StyleFlags::ITALIC,
        };
        presenter.emit_style_full(style).unwrap();
        let output = presenter.into_inner().unwrap();
        let output_str = String::from_utf8_lossy(&output);

        // Should have reset + fg + bg + attrs
        assert!(output_str.contains("\x1b[0m"), "Should start with reset");
        assert!(output_str.contains("38;2;10;20;30"), "Should have fg");
        assert!(output_str.contains("48;2;40;50;60"), "Should have bg");
    }

    // --- Multiple rows with different strategies ---

    #[test]
    fn present_multiple_rows_different_strategies() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(80, 5);

        // Row 0: dense changes (should merge)
        for x in (0..20).step_by(2) {
            buffer.set_raw(x, 0, Cell::from_char('D'));
        }
        // Row 2: sparse changes (large gap, should stay sparse)
        buffer.set_raw(0, 2, Cell::from_char('L'));
        buffer.set_raw(79, 2, Cell::from_char('R'));
        // Row 4: single cell
        buffer.set_raw(40, 4, Cell::from_char('M'));

        let old = Buffer::new(80, 5);
        let diff = BufferDiff::compute(&old, &buffer);
        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        assert!(output_str.contains('D'));
        assert!(output_str.contains('L'));
        assert!(output_str.contains('R'));
        assert!(output_str.contains('M'));
    }

    #[test]
    fn zero_width_chars_replaced_with_placeholder() {
        let mut presenter = test_presenter();
        let mut buffer = Buffer::new(5, 1);

        // U+0301 is COMBINING ACUTE ACCENT (width 0).
        // It is not empty, not continuation, not grapheme (unless pooled).
        // Storing it directly as a char means it's a standalone cell content.
        let zw_char = '\u{0301}';

        // Ensure our assumption about width is correct for this environment
        assert_eq!(Cell::from_char(zw_char).content.width(), 0);

        buffer.set_raw(0, 0, Cell::from_char(zw_char));
        buffer.set_raw(1, 0, Cell::from_char('A'));

        let old = Buffer::new(5, 1);
        let diff = BufferDiff::compute(&old, &buffer);

        presenter.present(&buffer, &diff).unwrap();
        let output = get_output(presenter);
        let output_str = String::from_utf8_lossy(&output);

        // Should contain U+FFFD (Replacement Character)
        assert!(
            output_str.contains("\u{FFFD}"),
            "Expected replacement character for zero-width content, got: {:?}",
            output_str
        );

        // Should NOT contain the raw combining mark
        assert!(
            !output_str.contains(zw_char),
            "Should not contain raw zero-width char"
        );

        // Should contain 'A' (verify cursor sync didn't swallow it)
        assert!(
            output_str.contains('A'),
            "Should contain subsequent character 'A'"
        );
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use crate::cell::{Cell, PackedRgba};
    use crate::diff::BufferDiff;
    use crate::terminal_model::TerminalModel;
    use proptest::prelude::*;

    /// Create a presenter for testing.
    fn test_presenter() -> Presenter<Vec<u8>> {
        let caps = TerminalCapabilities::basic();
        Presenter::new(Vec::new(), caps)
    }

    proptest! {
        /// Property: Presenter output, when applied to terminal model, produces
        /// the correct characters for changed cells.
        #[test]
        fn presenter_roundtrip_characters(
            width in 5u16..40,
            height in 3u16..20,
            num_chars in 1usize..50, // At least 1 char to have meaningful diff
        ) {
            let mut buffer = Buffer::new(width, height);
            let mut changed_positions = std::collections::HashSet::new();

            // Fill some cells with ASCII chars
            for i in 0..num_chars {
                let x = (i * 7 + 3) as u16 % width;
                let y = (i * 11 + 5) as u16 % height;
                let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
                buffer.set_raw(x, y, Cell::from_char(ch));
                changed_positions.insert((x, y));
            }

            // Present full buffer
            let mut presenter = test_presenter();
            let old = Buffer::new(width, height);
            let diff = BufferDiff::compute(&old, &buffer);
            presenter.present(&buffer, &diff).unwrap();
            let output = presenter.into_inner().unwrap();

            // Apply to terminal model
            let mut model = TerminalModel::new(width as usize, height as usize);
            model.process(&output);

            // Verify ONLY changed characters match (model may have different default)
            for &(x, y) in &changed_positions {
                let buf_cell = buffer.get_unchecked(x, y);
                let expected_ch = buf_cell.content.as_char().unwrap_or(' ');
                let mut expected_buf = [0u8; 4];
                let expected_str = expected_ch.encode_utf8(&mut expected_buf);

                if let Some(model_cell) = model.cell(x as usize, y as usize) {
                    prop_assert_eq!(
                        model_cell.text.as_str(),
                        expected_str,
                        "Character mismatch at ({}, {})", x, y
                    );
                }
            }
        }

        /// Property: After complete frame presentation, SGR is reset.
        #[test]
        fn style_reset_after_present(
            width in 5u16..30,
            height in 3u16..15,
            num_styled in 1usize..20,
        ) {
            let mut buffer = Buffer::new(width, height);

            // Add some styled cells
            for i in 0..num_styled {
                let x = (i * 7) as u16 % width;
                let y = (i * 11) as u16 % height;
                let fg = PackedRgba::rgb(
                    ((i * 31) % 256) as u8,
                    ((i * 47) % 256) as u8,
                    ((i * 71) % 256) as u8,
                );
                buffer.set_raw(x, y, Cell::from_char('X').with_fg(fg));
            }

            // Present
            let mut presenter = test_presenter();
            let old = Buffer::new(width, height);
            let diff = BufferDiff::compute(&old, &buffer);
            presenter.present(&buffer, &diff).unwrap();
            let output = presenter.into_inner().unwrap();
            let output_str = String::from_utf8_lossy(&output);

            // Output should end with SGR reset sequence
            prop_assert!(
                output_str.contains("\x1b[0m"),
                "Output should contain SGR reset"
            );
        }

        /// Property: Presenter handles empty diff correctly.
        #[test]
        fn empty_diff_minimal_output(
            width in 5u16..50,
            height in 3u16..25,
        ) {
            let buffer = Buffer::new(width, height);
            let diff = BufferDiff::new(); // Empty diff

            let mut presenter = test_presenter();
            presenter.present(&buffer, &diff).unwrap();
            let output = presenter.into_inner().unwrap();

            // Output should only be SGR reset (or very minimal)
            // No cursor moves or cell content for empty diff
            prop_assert!(output.len() < 50, "Empty diff should have minimal output");
        }

        /// Property: Full buffer change produces diff with all cells.
        ///
        /// When every cell differs, the diff should contain exactly
        /// width * height changes.
        #[test]
        fn diff_size_bounds(
            width in 5u16..30,
            height in 3u16..15,
        ) {
            // Full change buffer
            let old = Buffer::new(width, height);
            let mut new = Buffer::new(width, height);

            for y in 0..height {
                for x in 0..width {
                    new.set_raw(x, y, Cell::from_char('X'));
                }
            }

            let diff = BufferDiff::compute(&old, &new);

            // Diff should capture all cells
            prop_assert_eq!(
                diff.len(),
                (width as usize) * (height as usize),
                "Full change should have all cells in diff"
            );
        }

        /// Property: Presenter cursor state is consistent after operations.
        #[test]
        fn presenter_cursor_consistency(
            width in 10u16..40,
            height in 5u16..20,
            num_runs in 1usize..10,
        ) {
            let mut buffer = Buffer::new(width, height);

            // Create some runs of changes
            for i in 0..num_runs {
                let start_x = (i * 5) as u16 % (width - 5);
                let y = i as u16 % height;
                for x in start_x..(start_x + 3) {
                    buffer.set_raw(x, y, Cell::from_char('A'));
                }
            }

            // Multiple presents should work correctly
            let mut presenter = test_presenter();
            let old = Buffer::new(width, height);

            for _ in 0..3 {
                let diff = BufferDiff::compute(&old, &buffer);
                presenter.present(&buffer, &diff).unwrap();
            }

            // Should not panic and produce valid output
            let output = presenter.into_inner().unwrap();
            prop_assert!(!output.is_empty(), "Should produce some output");
        }

        /// Property (bd-4kq0.2.1): SGR delta produces identical visual styling
        /// as reset+apply for random style transitions. Verified via terminal
        /// model roundtrip.
        #[test]
        fn sgr_delta_transition_equivalence(
            width in 5u16..20,
            height in 3u16..10,
            num_styled in 2usize..15,
        ) {
            let mut buffer = Buffer::new(width, height);
            // Track final character at each position (later writes overwrite earlier)
            let mut expected: std::collections::HashMap<(u16, u16), char> =
                std::collections::HashMap::new();

            // Create cells with varying styles to exercise delta engine
            for i in 0..num_styled {
                let x = (i * 3 + 1) as u16 % width;
                let y = (i * 5 + 2) as u16 % height;
                let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
                let fg = PackedRgba::rgb(
                    ((i * 73) % 256) as u8,
                    ((i * 137) % 256) as u8,
                    ((i * 41) % 256) as u8,
                );
                let bg = if i % 3 == 0 {
                    PackedRgba::rgb(
                        ((i * 29) % 256) as u8,
                        ((i * 53) % 256) as u8,
                        ((i * 97) % 256) as u8,
                    )
                } else {
                    PackedRgba::TRANSPARENT
                };
                let flags_bits = ((i * 37) % 256) as u8;
                let flags = StyleFlags::from_bits_truncate(flags_bits);
                let cell = Cell::from_char(ch)
                    .with_fg(fg)
                    .with_bg(bg)
                    .with_attrs(CellAttrs::new(flags, 0));
                buffer.set_raw(x, y, cell);
                expected.insert((x, y), ch);
            }

            // Present with delta engine
            let mut presenter = test_presenter();
            let old = Buffer::new(width, height);
            let diff = BufferDiff::compute(&old, &buffer);
            presenter.present(&buffer, &diff).unwrap();
            let output = presenter.into_inner().unwrap();

            // Apply to terminal model and verify characters
            let mut model = TerminalModel::new(width as usize, height as usize);
            model.process(&output);

            for (&(x, y), &ch) in &expected {
                let mut buf = [0u8; 4];
                let expected_str = ch.encode_utf8(&mut buf);

                if let Some(model_cell) = model.cell(x as usize, y as usize) {
                    prop_assert_eq!(
                        model_cell.text.as_str(),
                        expected_str,
                        "Character mismatch at ({}, {}) with delta engine", x, y
                    );
                }
            }
        }

        /// Property (bd-4kq0.2.2): DP cost model produces correct output
        /// regardless of which row strategy is chosen (sparse vs merged).
        /// Verified via terminal model roundtrip with scattered runs.
        #[test]
        fn dp_emit_equivalence(
            width in 20u16..60,
            height in 5u16..15,
            num_changes in 5usize..30,
        ) {
            let mut buffer = Buffer::new(width, height);
            let mut expected: std::collections::HashMap<(u16, u16), char> =
                std::collections::HashMap::new();

            // Create scattered changes that will trigger both sparse and merged strategies
            for i in 0..num_changes {
                let x = (i * 7 + 3) as u16 % width;
                let y = (i * 3 + 1) as u16 % height;
                let ch = char::from_u32(('A' as u32) + (i as u32 % 26)).unwrap();
                buffer.set_raw(x, y, Cell::from_char(ch));
                expected.insert((x, y), ch);
            }

            // Present with DP cost model
            let mut presenter = test_presenter();
            let old = Buffer::new(width, height);
            let diff = BufferDiff::compute(&old, &buffer);
            presenter.present(&buffer, &diff).unwrap();
            let output = presenter.into_inner().unwrap();

            // Apply to terminal model and verify all characters are correct
            let mut model = TerminalModel::new(width as usize, height as usize);
            model.process(&output);

            for (&(x, y), &ch) in &expected {
                let mut buf = [0u8; 4];
                let expected_str = ch.encode_utf8(&mut buf);

                if let Some(model_cell) = model.cell(x as usize, y as usize) {
                    prop_assert_eq!(
                        model_cell.text.as_str(),
                        expected_str,
                        "DP cost model: character mismatch at ({}, {})", x, y
                    );
                }
            }
        }
    }
}