retach 0.10.0

Persistent terminal sessions with native scrollback passthrough
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
use super::*;

#[test]
fn alt_screen_save_restore() {
    let mut screen = Screen::new(10, 3, 100);

    // Write "Hello" on the main screen
    screen.process(b"Hello");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'H');
    assert_eq!(screen.grid.visible_row(0)[4].c, 'o');

    // Enter alt screen (CSI ?1049h)
    screen.process(b"\x1b[?1049h");
    assert!(screen.in_alt_screen());
    // Alt screen should be cleared
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');

    // Write something on alt screen
    screen.process(b"Alt");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');

    // Leave alt screen (CSI ?1049l) — should restore main buffer (fix S7)
    screen.process(b"\x1b[?1049l");
    assert!(!screen.in_alt_screen());
    assert_eq!(screen.grid.visible_row(0)[0].c, 'H');
    assert_eq!(screen.grid.visible_row(0)[4].c, 'o');
}

#[test]
fn scrollback_on_scroll() {
    let mut screen = Screen::new(10, 3, 100);
    // Fill 3 rows and scroll
    screen.process(b"Line1\r\nLine2\r\nLine3\r\nLine4");
    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = AnsiRenderer::new().render_rows(&screen, &scrollback_rows);
    assert!(!scrollback.is_empty());
    // First scrolled line should contain "Line1"
    let first = String::from_utf8_lossy(&scrollback[0]);
    assert!(
        first.contains("Line1"),
        "scrollback should contain Line1, got: {}",
        first
    );
}

#[test]
fn no_scrollback_in_alt_screen() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"\x1b[?1049h"); // enter alt screen
    screen.process(b"A\r\nB\r\nC\r\nD"); // scroll in alt
    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = AnsiRenderer::new().render_rows(&screen, &scrollback_rows);
    assert!(
        scrollback.is_empty(),
        "alt screen should not generate scrollback"
    );
}

#[test]
fn history_preserved_across_sessions() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"A\r\nB\r\nC\r\nD\r\nE");
    let _ = screen.take_pending_scrollback();
    let history = screen.get_history();
    assert!(!history.is_empty());
}

#[test]
fn deferred_wrap_cr_stays_on_same_line() {
    // Simulates zsh PROMPT_SP: fill line to end, CR, overwrite
    let mut screen = Screen::new(5, 3, 100);
    // Write exactly 5 chars to fill the line
    screen.process(b"%    ");
    // wrap_pending should be set, cursor stays on row 0
    assert!(screen.grid.wrap_pending());
    assert_eq!(screen.grid.cursor_y(), 0);
    // CR should clear wrap_pending and go to column 0 of SAME row
    screen.process(b"\r");
    assert!(!screen.grid.wrap_pending());
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.cursor_y(), 0);
    // Space overwrites the '%'
    screen.process(b" ");
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
}

#[test]
fn deferred_wrap_next_print_wraps() {
    let mut screen = Screen::new(5, 3, 100);
    // Fill line
    screen.process(b"ABCDE");
    assert!(screen.grid.wrap_pending());
    assert_eq!(screen.grid.cursor_y(), 0);
    // Next char triggers actual wrap
    screen.process(b"F");
    assert_eq!(screen.grid.cursor_y(), 1);
    assert_eq!(screen.grid.visible_row(1)[0].c, 'F');
}

// --- New tests for escape sequence completeness ---

#[test]
fn dsr_cursor_position_report() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;10H"); // move to row 5, col 10
    screen.process(b"\x1b[6n"); // request CPR
    let responses = screen.take_responses();
    assert_eq!(responses.len(), 1);
    assert_eq!(responses[0], b"\x1b[5;10R");
}

#[test]
fn da1_primary_device_attributes() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[c");
    let responses = screen.take_responses();
    assert_eq!(responses.len(), 1);
    // Well-formed: VT220 (62) with ANSI color (22), no trailing empty parameter.
    assert_eq!(responses[0], b"\x1b[?62;22c");
}

#[test]
fn da2_secondary_device_attributes() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[>c");
    let responses = screen.take_responses();
    assert_eq!(responses.len(), 1);
    assert_eq!(responses[0], b"\x1b[>0;10;1c");
}

#[test]
fn dec_line_drawing_charset() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b(0"); // switch G0 to line drawing
    screen.process(b"lqk"); // should produce box-drawing chars
    assert_eq!(screen.grid.visible_row(0)[0].c, '\u{250C}'); //    assert_eq!(screen.grid.visible_row(0)[1].c, '\u{2500}'); //    assert_eq!(screen.grid.visible_row(0)[2].c, '\u{2510}'); //                                                             // Switch back to ASCII
    screen.process(b"\x1b(B");
    screen.process(b"l");
    assert_eq!(screen.grid.visible_row(0)[3].c, 'l'); // plain ASCII 'l'
}

#[test]
fn rep_repeats_last_char() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"A\x1b[3b"); // print A, then repeat 3 times
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[1].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[2].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[3].c, 'A');
}

#[test]
fn wide_character_occupies_two_cells() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process("".as_bytes());
    assert_eq!(screen.grid.visible_row(0)[0].c, '');
    assert_eq!(screen.grid.visible_row(0)[0].width, 2);
    assert_eq!(screen.grid.visible_row(0)[1].width, 0);
    assert_eq!(screen.grid.cursor_x(), 2);
}

#[test]
fn wide_char_wraps_at_end_of_line() {
    let mut screen = Screen::new(5, 3, 100);
    screen.process(b"ABCD"); // fill 4 of 5 cols
    screen.process("".as_bytes()); // needs 2 cols, only 1 left -> should wrap
                                     // Col 4 should be blanked, wide char on next line
    assert_eq!(screen.grid.visible_row(0)[4].c, ' ');
    assert_eq!(screen.grid.visible_row(1)[0].c, '');
    assert_eq!(screen.grid.visible_row(1)[0].width, 2);
    assert_eq!(screen.grid.visible_row(1)[1].width, 0);
}

#[test]
fn esc_c_full_reset() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[?2004h"); // enable bracketed paste
    screen.process(b"\x1b[5;10H"); // move cursor
    screen.process(b"Hello");
    screen.process(b"\x1b[2 q"); // set cursor shape
    screen.process(b"\x1bc"); // full reset
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.cursor_y(), 0);
    assert!(!screen.grid.modes().bracketed_paste);
    assert_eq!(screen.grid.modes().cursor_shape, grid::CursorShape::Default);
    assert!(screen.grid.cursor_visible());
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert!(screen.title().is_empty());
}

#[test]
fn osc_sets_title() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]0;My Terminal\x07");
    assert_eq!(screen.title(), "My Terminal");
    screen.process(b"\x1b]2;New Title\x07");
    assert_eq!(screen.title(), "New Title");
}

#[test]
fn osc_passthrough_non_title() {
    let mut screen = Screen::new(80, 24, 100);
    // OSC 52 (clipboard) goes to passthrough
    screen.process(b"\x1b]52;c;SGVsbG8=\x07");
    let pt = screen.take_passthrough();
    assert_eq!(pt.len(), 1, "should have one passthrough sequence");
    assert_eq!(pt[0], b"\x1b]52;c;SGVsbG8=\x07");
    // Title should not be set
    assert_eq!(screen.title(), "");
}

#[test]
fn osc_title_not_passedthrough() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]0;My Title\x07");
    let pt = screen.take_passthrough();
    assert!(pt.is_empty(), "OSC 0 should not be passedthrough");
    assert_eq!(screen.title(), "My Title");
}

// --- Bell / BEL tests ---

#[test]
fn bell_forwarded_as_passthrough() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x07");
    let pt = screen.take_passthrough();
    assert_eq!(pt.len(), 1, "standalone BEL should produce one passthrough");
    assert_eq!(pt[0], b"\x07");
}

#[test]
fn bell_does_not_affect_screen_state() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"Hello");
    let (cx, cy) = (screen.grid.cursor_x(), screen.grid.cursor_y());
    screen.process(b"\x07");
    assert_eq!(screen.grid.cursor_x(), cx, "BEL should not move cursor x");
    assert_eq!(screen.grid.cursor_y(), cy, "BEL should not move cursor y");
    assert_eq!(
        screen.grid.visible_row(0)[0].c,
        'H',
        "BEL should not alter cell content"
    );
}

#[test]
fn bell_drained_after_take() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x07");
    let pt1 = screen.take_passthrough();
    assert_eq!(pt1.len(), 1);
    // Second take should be empty
    let pt2 = screen.take_passthrough();
    assert!(
        pt2.is_empty(),
        "BEL should not persist after take_passthrough()"
    );
}

#[test]
fn bell_not_resent_on_render() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x07");
    let _ = screen.take_passthrough(); // drain
                                       // Render (simulates screen redraw)
    let mut cache = AnsiRenderer::new();
    let _ = cache.render(&screen, true);
    // Passthrough should still be empty
    let pt = screen.take_passthrough();
    assert!(pt.is_empty(), "BEL must not be re-sent on full redraw");
}

#[test]
fn bell_not_resent_on_incremental_render() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x07");
    let _ = screen.take_passthrough(); // drain
    let mut cache = AnsiRenderer::new();
    let _ = cache.render(&screen, false);
    let pt = screen.take_passthrough();
    assert!(
        pt.is_empty(),
        "BEL must not be re-sent on incremental render"
    );
}

#[test]
fn bell_not_resent_on_resize() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x07");
    let _ = screen.take_passthrough(); // drain
    screen.resize(120, 40);
    let pt = screen.take_passthrough();
    assert!(pt.is_empty(), "BEL must not be re-sent after resize");
}

#[test]
fn osc_777_drained_after_take() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]777;notify;title;body\x07");
    // OSC 777 goes to notification queue, not passthrough
    let pt = screen.take_passthrough();
    assert!(pt.is_empty(), "OSC 777 should not be in passthrough");
    let n1 = screen.take_queued_notifications();
    assert_eq!(n1.len(), 1);
    let n2 = screen.take_queued_notifications();
    assert!(
        n2.is_empty(),
        "OSC 777 should not persist after take_queued_notifications()"
    );
}

#[test]
fn osc_777_not_resent_on_render() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]777;notify;title;body\x07");
    let _ = screen.take_queued_notifications(); // drain
    let mut cache = AnsiRenderer::new();
    let _ = cache.render(&screen, true);
    let n = screen.take_queued_notifications();
    assert!(n.is_empty(), "OSC 777 must not be re-sent on full redraw");
}

#[test]
fn osc_777_not_resent_on_resize() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]777;notify;title;body\x07");
    let _ = screen.take_queued_notifications(); // drain
    screen.resize(120, 40);
    let n = screen.take_queued_notifications();
    assert!(n.is_empty(), "OSC 777 must not be re-sent after resize");
}

#[test]
fn osc_777_not_resent_on_resize_then_render() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]777;notify;title;body\x07");
    let _ = screen.take_queued_notifications(); // drain
    screen.resize(40, 10);
    let mut cache = AnsiRenderer::new();
    let _ = cache.render(&screen, true);
    let n = screen.take_queued_notifications();
    assert!(
        n.is_empty(),
        "OSC 777 must not re-appear after resize + full redraw"
    );
}

#[test]
fn multiple_bells_all_forwarded() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x07\x07\x07");
    let pt = screen.take_passthrough();
    assert_eq!(
        pt.len(),
        3,
        "three BELs should produce three passthrough entries"
    );
    for entry in &pt {
        assert_eq!(entry, &vec![0x07u8]);
    }
}

#[test]
fn bell_and_osc_777_interleaved() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x07\x1b]777;notify;t;b\x07\x07");
    // BELs go to passthrough, OSC 777 goes to notification queue
    let pt = screen.take_passthrough();
    assert_eq!(pt.len(), 2, "BEL + BEL = 2 passthrough entries");
    assert_eq!(pt[0], b"\x07", "first should be standalone BEL");
    assert_eq!(pt[1], b"\x07", "second should be standalone BEL");
    let notifs = screen.take_queued_notifications();
    assert_eq!(notifs.len(), 1);
    assert_eq!(
        notifs[0], b"\x1b]777;notify;t;b\x07",
        "OSC 777 should be in notification queue"
    );
}

#[test]
fn bell_in_osc_is_terminator_not_separate_bell() {
    let mut screen = Screen::new(80, 24, 100);
    // The BEL inside OSC is a terminator, not a separate bell event
    screen.process(b"\x1b]777;notify;title;body\x07");
    let pt = screen.take_passthrough();
    assert!(pt.is_empty(), "OSC 777 should not be in passthrough");
    // The notification should be the full OSC, not a separate BEL
    let notifs = screen.take_queued_notifications();
    assert_eq!(
        notifs.len(),
        1,
        "OSC terminated by BEL should produce exactly 1 notification"
    );
    assert!(
        notifs[0].starts_with(b"\x1b]"),
        "notification should be the OSC sequence"
    );
}

#[test]
fn bell_not_resent_on_render_with_scrollback() {
    let mut screen = Screen::new(10, 3, 100);
    // Generate some scrollback
    screen.process(b"A\r\nB\r\nC\r\nD");
    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = AnsiRenderer::new().render_rows(&screen, &scrollback_rows);
    // Now send a bell
    screen.process(b"\x07");
    let _ = screen.take_passthrough(); // drain
                                       // Render with scrollback (atomic scrollback injection + full redraw)
    let mut cache = AnsiRenderer::new();
    let _ = cache.render_with_scrollback(&screen, &scrollback);
    let pt = screen.take_passthrough();
    assert!(
        pt.is_empty(),
        "BEL must not re-appear after render_with_scrollback"
    );
}

#[test]
fn osc_777_not_resent_on_render_with_scrollback() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"A\r\nB\r\nC\r\nD");
    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = AnsiRenderer::new().render_rows(&screen, &scrollback_rows);
    screen.process(b"\x1b]777;notify;title;body\x07");
    let _ = screen.take_queued_notifications(); // drain
    let mut cache = AnsiRenderer::new();
    let _ = cache.render_with_scrollback(&screen, &scrollback);
    let n = screen.take_queued_notifications();
    assert!(
        n.is_empty(),
        "OSC 777 must not re-appear after render_with_scrollback"
    );
}

// --- ED mode 3 (clear scrollback) passthrough tests ---

#[test]
fn ed3_clears_scrollback_and_forwards_passthrough() {
    let mut screen = Screen::new(80, 24, 100);
    // Generate scrollback
    for i in 0..30 {
        screen.process(format!("Line{}\r\n", i).as_bytes());
    }
    assert!(screen.grid.scrollback_len() > 0, "should have scrollback");
    let _ = screen.take_passthrough(); // drain any prior

    // ED mode 3: clear scrollback
    screen.process(b"\x1b[3J");
    assert_eq!(
        screen.grid.scrollback_len(),
        0,
        "scrollback should be cleared"
    );

    let pt = screen.take_passthrough();
    assert_eq!(
        pt.len(),
        1,
        "ED mode 3 should produce one passthrough entry"
    );
    assert_eq!(pt[0], b"\x1b[3J", "passthrough should be \\e[3J");
}

#[test]
fn ed3_passthrough_even_without_scrollback() {
    // Even with no internal scrollback, outer terminal may have native scrollback
    // from previous render_with_scrollback cycles — must still forward
    let mut screen = Screen::new(80, 24, 0); // scrollback_limit=0
    screen.process(b"\x1b[3J");
    let pt = screen.take_passthrough();
    assert_eq!(
        pt.len(),
        1,
        "ED mode 3 should forward even with empty scrollback"
    );
    assert_eq!(pt[0], b"\x1b[3J");
}

#[test]
fn ed3_passthrough_drained_after_take() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[3J");
    let pt1 = screen.take_passthrough();
    assert_eq!(pt1.len(), 1);
    let pt2 = screen.take_passthrough();
    assert!(
        pt2.is_empty(),
        "ED mode 3 should not persist after take_passthrough()"
    );
}

#[test]
fn ed3_passthrough_not_resent_on_render() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[3J");
    let _ = screen.take_passthrough(); // drain
    let mut cache = AnsiRenderer::new();
    let _ = cache.render(&screen, true);
    let pt = screen.take_passthrough();
    assert!(
        pt.is_empty(),
        "ED mode 3 must not be re-sent on full redraw"
    );
}

#[test]
fn ed2_does_not_produce_passthrough() {
    // ED mode 2 (clear visible) should NOT passthrough — render handles it
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[2J");
    let pt = screen.take_passthrough();
    assert!(pt.is_empty(), "ED mode 2 should not produce passthrough");
}

#[test]
fn mode_flags_bracketed_paste() {
    let mut screen = Screen::new(80, 24, 100);
    assert!(!screen.grid.modes().bracketed_paste);
    screen.process(b"\x1b[?2004h");
    assert!(screen.grid.modes().bracketed_paste);
    screen.process(b"\x1b[?2004l");
    assert!(!screen.grid.modes().bracketed_paste);
}

#[test]
fn mode_flags_cursor_key_mode() {
    let mut screen = Screen::new(80, 24, 100);
    assert!(!screen.grid.modes().cursor_key_mode);
    screen.process(b"\x1b[?1h");
    assert!(screen.grid.modes().cursor_key_mode);
    screen.process(b"\x1b[?1l");
    assert!(!screen.grid.modes().cursor_key_mode);
}

#[test]
fn mode_flags_mouse() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[?1000h");
    assert!(screen.grid.modes().mouse_modes.click);
    assert_eq!(
        screen.grid.modes().mouse_modes.effective(),
        super::grid::MouseMode::Click
    );
    screen.process(b"\x1b[?1006h");
    assert_eq!(
        screen.grid.modes().mouse_encoding,
        super::grid::MouseEncoding::Sgr
    );
    screen.process(b"\x1b[?1000l");
    assert!(!screen.grid.modes().mouse_modes.click);
}

#[test]
fn keypad_app_mode() {
    let mut screen = Screen::new(80, 24, 100);
    assert!(!screen.grid.modes().keypad_app_mode);
    screen.process(b"\x1b=");
    assert!(screen.grid.modes().keypad_app_mode);
    screen.process(b"\x1b>");
    assert!(!screen.grid.modes().keypad_app_mode);
}

#[test]
fn cursor_shape_decscusr() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[2 q"); // steady block
    assert_eq!(
        screen.grid.modes().cursor_shape,
        grid::CursorShape::SteadyBlock
    );
    screen.process(b"\x1b[5 q"); // blinking bar
    assert_eq!(
        screen.grid.modes().cursor_shape,
        grid::CursorShape::BlinkBar
    );
    screen.process(b"\x1b[0 q"); // reset to default
    assert_eq!(screen.grid.modes().cursor_shape, grid::CursorShape::Default);
}

#[test]
fn autowrap_mode_disable_prevents_wrap() {
    let mut screen = Screen::new(5, 3, 100);
    screen.process(b"\x1b[?7l"); // disable autowrap
    screen.process(b"ABCDEF"); // write 6 chars in 5 cols
                               // Should NOT wrap — last char overwrites column 4
    assert_eq!(screen.grid.cursor_y(), 0);
    assert_eq!(screen.grid.visible_row(0)[4].c, 'F');
    assert!(!screen.grid.wrap_pending());
}

#[test]
fn sgr_hidden_attribute() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[8m"); // hidden
    screen.process(b"secret");
    assert!(screen.cell_style(0, 0).hidden);
    screen.process(b"\x1b[28m"); // reveal
    screen.process(b"visible");
    assert!(!screen.cell_style(0, 6).hidden);
}

#[test]
fn cursor_save_restore() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;10H"); // move to row 5, col 10
    screen.process(b"\x1b7"); // save cursor
    screen.process(b"\x1b[1;1H"); // move home
    assert_eq!(screen.grid.cursor_y(), 0);
    screen.process(b"\x1b8"); // restore cursor
    assert_eq!(screen.grid.cursor_y(), 4);
    assert_eq!(screen.grid.cursor_x(), 9);
}

#[test]
fn so_si_charset_switching() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b)0"); // set G1 to line drawing
    screen.process(b"\x0E"); // SO — activate G1
    screen.process(b"q"); // should be line drawing ─
    assert_eq!(screen.grid.visible_row(0)[0].c, '\u{2500}');
    screen.process(b"\x0F"); // SI — activate G0 (ASCII)
    screen.process(b"q");
    assert_eq!(screen.grid.visible_row(0)[1].c, 'q');
}

#[test]
fn cuu_cud_respects_scroll_region() {
    let mut screen = Screen::new(80, 24, 100);
    // Set scroll region to rows 5-15
    screen.process(b"\x1b[5;15r");
    // Cursor is at 0,0 after DECSTBM
    // Move into scroll region
    screen.process(b"\x1b[10;1H"); // row 10 (inside region)
                                   // Try moving up past scroll top
    screen.process(b"\x1b[20A"); // CUU 20 — should stop at row 5 (scroll_top=4)
    assert_eq!(screen.grid.cursor_y(), 4); // 0-based row 4 = display row 5
                                           // Move back down past scroll bottom
    screen.process(b"\x1b[20B"); // CUD 20 — should stop at row 15 (scroll_bottom=14)
    assert_eq!(screen.grid.cursor_y(), 14); // 0-based row 14 = display row 15
}

#[test]
fn vt_ff_treated_as_lf() {
    let mut screen = Screen::new(80, 3, 100);
    screen.process(b"A");
    screen.process(&[0x0B]); // VT
    assert_eq!(screen.grid.cursor_y(), 1);
    screen.process(&[0x0C]); // FF
    assert_eq!(screen.grid.cursor_y(), 2);
}

#[test]
fn dl_large_count_clamped() {
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"\x1b[2;1H"); // row 2 (1-indexed)
    screen.process(b"\x1b[99999M"); // DL with huge count
    assert_eq!(screen.grid.visible_row_count(), 5);
}

#[test]
fn il_large_count_clamped() {
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"\x1b[2;1H");
    screen.process(b"\x1b[99999L"); // IL with huge count
    assert_eq!(screen.grid.visible_row_count(), 5);
}

#[test]
fn alt_screen_mode_47_no_cursor_save() {
    let mut screen = Screen::new(10, 5, 100);
    // Move cursor to (3, 2) — row 3, col 4 (1-indexed)
    screen.process(b"\x1b[3;4H");
    assert_eq!(screen.grid.cursor_y(), 2);
    assert_eq!(screen.grid.cursor_x(), 3);
    // Save cursor explicitly with ESC 7
    screen.process(b"\x1b7");
    // Enter alt screen with mode 47 (should NOT save cursor again)
    screen.process(b"\x1b[?47h");
    // Move cursor on alt screen
    screen.process(b"\x1b[1;1H");
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.cursor_y(), 0);
    // Exit alt screen with mode 47 (should NOT restore cursor)
    screen.process(b"\x1b[?47l");
    // Cursor should remain at (0, 0) since mode 47 doesn't restore
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.cursor_y(), 0);
    // But ESC 8 should still restore the original saved cursor
    screen.process(b"\x1b8");
    assert_eq!(screen.grid.cursor_x(), 3);
    assert_eq!(screen.grid.cursor_y(), 2);
}

#[test]
fn mode_1048_save_restore_cursor() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;10H"); // move cursor
    screen.process(b"\x1b[?1048h"); // save cursor
    screen.process(b"\x1b[1;1H"); // move home
    screen.process(b"\x1b[?1048l"); // restore cursor
    assert_eq!(screen.grid.cursor_y(), 4);
    assert_eq!(screen.grid.cursor_x(), 9);
}

#[test]
fn dch_through_wide_char_no_orphan() {
    let mut screen = Screen::new(10, 3, 100);
    // Place: A [你] B — cells: A(w1) 你(w2) \0(w0) B(w1)
    screen.process(b"A");
    screen.process("".as_bytes());
    screen.process(b"B");
    // Cursor at col 4. Move to col 1 (the wide char start) and delete 1
    screen.process(b"\x1b[1;2H"); // row 1, col 2 (0-based x=1)
    screen.process(b"\x1b[P"); // DCH 1
                               // The continuation cell (width=0) should NOT remain at x=1
    assert_ne!(
        screen.grid.visible_row(0)[1].width,
        0,
        "orphaned continuation cell after DCH"
    );
}

#[test]
fn ich_pushes_wide_char_off_right_edge() {
    let mut screen = Screen::new(6, 3, 100);
    // Place wide char at cols 4-5 (the last two columns)
    screen.process(b"\x1b[1;5H"); // row 1, col 5 (0-based x=4)
    screen.process("".as_bytes());
    assert_eq!(screen.grid.visible_row(0)[4].c, '');
    assert_eq!(screen.grid.visible_row(0)[4].width, 2);
    assert_eq!(screen.grid.visible_row(0)[5].width, 0);
    // Move to col 1 and insert 1 char — pushes everything right,
    // the continuation cell falls off, orphaning width=2 at col 5
    screen.process(b"\x1b[1;1H");
    screen.process(b"\x1b[@"); // ICH 1
                               // The rightmost cell should NOT be an orphaned width=2
    assert_ne!(
        screen.grid.visible_row(0)[5].width,
        2,
        "orphaned wide char at right edge after ICH"
    );
}

#[test]
fn scrollback_captured_with_partial_scroll_region() {
    let mut screen = Screen::new(10, 5, 100);
    // Set scroll region to rows 1-3 (partial — not full screen)
    screen.process(b"\x1b[1;3r");
    // Move to row 1 and fill it, then scroll
    screen.process(b"\x1b[1;1H");
    screen.process(b"Line1\r\n");
    screen.process(b"Line2\r\n");
    screen.process(b"Line3\r\n"); // this should scroll within region
    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = AnsiRenderer::new().render_rows(&screen, &scrollback_rows);
    assert!(
        !scrollback.is_empty(),
        "scrollback should be captured even with partial scroll region (scroll_top==0)"
    );
}

// ---------------------------------------------------------------
// Additional performer.rs coverage tests
// ---------------------------------------------------------------

#[test]
fn csi_s_u_save_restore_cursor() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;10H"); // move to row 5, col 10
    screen.process(b"\x1b[s"); // CSI s — save cursor
    screen.process(b"\x1b[1;1H"); // move home
    assert_eq!(screen.grid.cursor_y(), 0);
    assert_eq!(screen.grid.cursor_x(), 0);
    screen.process(b"\x1b[u"); // CSI u — restore cursor
    assert_eq!(screen.grid.cursor_y(), 4); // 0-based row 4
    assert_eq!(screen.grid.cursor_x(), 9); // 0-based col 9
}

#[test]
fn cursor_movement_cuf_cub() {
    let mut screen = Screen::new(80, 24, 100);
    // Start at home (0,0)
    screen.process(b"\x1b[5C"); // CUF 5 — forward 5
    assert_eq!(screen.grid.cursor_x(), 5);
    screen.process(b"\x1b[2D"); // CUB 2 — backward 2
    assert_eq!(screen.grid.cursor_x(), 3);
    // CUB should not go below 0
    screen.process(b"\x1b[100D");
    assert_eq!(screen.grid.cursor_x(), 0);
    // CUF should clamp to cols-1
    screen.process(b"\x1b[200C");
    assert_eq!(screen.grid.cursor_x(), 79);
}

#[test]
fn cursor_movement_cnl_cpl() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[10;15H"); // move to row 10, col 15
    assert_eq!(screen.grid.cursor_y(), 9);
    assert_eq!(screen.grid.cursor_x(), 14);

    // CNL 3 — move down 3 lines, cursor to column 0
    screen.process(b"\x1b[3E");
    assert_eq!(screen.grid.cursor_y(), 12);
    assert_eq!(screen.grid.cursor_x(), 0);

    // CPL 2 — move up 2 lines, cursor to column 0
    screen.process(b"\x1b[5;20H"); // reposition with a non-zero column
    screen.process(b"\x1b[2F");
    assert_eq!(screen.grid.cursor_y(), 2); // row 5 - 1 (0-based=4) minus 2 = 2
    assert_eq!(screen.grid.cursor_x(), 0);

    // CNL should clamp to last row
    screen.process(b"\x1b[100E");
    assert_eq!(screen.grid.cursor_y(), 23);
    assert_eq!(screen.grid.cursor_x(), 0);

    // CPL should clamp to row 0
    screen.process(b"\x1b[100F");
    assert_eq!(screen.grid.cursor_y(), 0);
    assert_eq!(screen.grid.cursor_x(), 0);
}

#[test]
fn cursor_horizontal_absolute() {
    let mut screen = Screen::new(80, 24, 100);
    // CHA — CSI G sets cursor column (1-based)
    screen.process(b"\x1b[20G");
    assert_eq!(screen.grid.cursor_x(), 19); // 0-based
                                            // CHA 1 should go to column 0
    screen.process(b"\x1b[1G");
    assert_eq!(screen.grid.cursor_x(), 0);
    // CHA beyond cols should clamp
    screen.process(b"\x1b[200G");
    assert_eq!(screen.grid.cursor_x(), 79);
    // CHA with default (no param) should go to column 0
    screen.process(b"\x1b[G");
    assert_eq!(screen.grid.cursor_x(), 0);
}

#[test]
fn cursor_position_cup() {
    let mut screen = Screen::new(80, 24, 100);
    // CUP — CSI H sets row and column (1-based)
    screen.process(b"\x1b[12;40H");
    assert_eq!(screen.grid.cursor_y(), 11); // 0-based
    assert_eq!(screen.grid.cursor_x(), 39); // 0-based
                                            // CUP with no params goes to (0,0)
    screen.process(b"\x1b[H");
    assert_eq!(screen.grid.cursor_y(), 0);
    assert_eq!(screen.grid.cursor_x(), 0);
    // CUP should clamp to screen bounds
    screen.process(b"\x1b[100;200H");
    assert_eq!(screen.grid.cursor_y(), 23);
    assert_eq!(screen.grid.cursor_x(), 79);
}

#[test]
fn vpa_line_position_absolute() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;10H"); // start at row 5, col 10
                                   // VPA — CSI d sets cursor row (1-based), column unchanged
    screen.process(b"\x1b[15d");
    assert_eq!(screen.grid.cursor_y(), 14); // 0-based row 14
    assert_eq!(screen.grid.cursor_x(), 9); // column unchanged
                                           // VPA should clamp to last row
    screen.process(b"\x1b[100d");
    assert_eq!(screen.grid.cursor_y(), 23);
    // VPA with default goes to row 0
    screen.process(b"\x1b[d");
    assert_eq!(screen.grid.cursor_y(), 0);
}

#[test]
fn erase_in_display_j0() {
    let mut screen = Screen::new(10, 5, 100);
    // Fill entire screen with 'X'
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(b"XXXXXXXXXX");
    }
    // Move cursor to row 3, col 5 (0-based: row 2, col 4)
    screen.process(b"\x1b[3;5H");
    // CSI 0J — erase from cursor to end of screen
    screen.process(b"\x1b[0J");
    // Cells before cursor on row 2 should be preserved
    assert_eq!(screen.grid.visible_row(2)[0].c, 'X');
    assert_eq!(screen.grid.visible_row(2)[3].c, 'X');
    // Cells from cursor onward on row 2 should be blank
    assert_eq!(screen.grid.visible_row(2)[4].c, ' ');
    assert_eq!(screen.grid.visible_row(2)[9].c, ' ');
    // All cells on rows below should be blank
    assert_eq!(screen.grid.visible_row(3)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(4)[5].c, ' ');
    // Rows above should be preserved
    assert_eq!(screen.grid.visible_row(0)[0].c, 'X');
    assert_eq!(screen.grid.visible_row(1)[9].c, 'X');
}

#[test]
fn erase_in_display_j1() {
    let mut screen = Screen::new(10, 5, 100);
    // Fill entire screen with 'X'
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(b"XXXXXXXXXX");
    }
    // Move cursor to row 3, col 5 (0-based: row 2, col 4)
    screen.process(b"\x1b[3;5H");
    // CSI 1J — erase from start of screen to cursor
    screen.process(b"\x1b[1J");
    // All rows above cursor row should be blank
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(1)[9].c, ' ');
    // Cells on cursor row up to and including cursor should be blank
    assert_eq!(screen.grid.visible_row(2)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(2)[4].c, ' ');
    // Cells after cursor on row 2 should be preserved
    assert_eq!(screen.grid.visible_row(2)[5].c, 'X');
    assert_eq!(screen.grid.visible_row(2)[9].c, 'X');
    // Rows below should be preserved
    assert_eq!(screen.grid.visible_row(3)[0].c, 'X');
    assert_eq!(screen.grid.visible_row(4)[5].c, 'X');
}

#[test]
fn erase_in_display_j2() {
    let mut screen = Screen::new(10, 5, 100);
    // Fill entire screen with 'X'
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(b"XXXXXXXXXX");
    }
    // Move cursor somewhere (should not matter for J2)
    screen.process(b"\x1b[3;5H");
    // CSI 2J — erase entire screen
    screen.process(b"\x1b[2J");
    // All cells should be blank
    for row in 0..5 {
        for col in 0..10 {
            assert_eq!(
                screen.grid.visible_row(row)[col].c,
                ' ',
                "cell [{row}][{col}] should be blank after CSI 2J"
            );
        }
    }
}

#[test]
fn erase_in_line_k0() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0
    screen.process(b"\x1b[1;4H"); // move to row 1, col 4 (0-based col 3)
                                  // CSI 0K — erase from cursor to end of line
    screen.process(b"\x1b[0K");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[2].c, 'C');
    assert_eq!(screen.grid.visible_row(0)[3].c, ' '); // erased
    assert_eq!(screen.grid.visible_row(0)[9].c, ' '); // erased
}

#[test]
fn erase_in_line_k1() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0
    screen.process(b"\x1b[1;4H"); // move to row 1, col 4 (0-based col 3)
                                  // CSI 1K — erase from start of line to cursor
    screen.process(b"\x1b[1K");
    assert_eq!(screen.grid.visible_row(0)[0].c, ' '); // erased
    assert_eq!(screen.grid.visible_row(0)[3].c, ' '); // erased (cursor position included)
    assert_eq!(screen.grid.visible_row(0)[4].c, 'E'); // preserved
    assert_eq!(screen.grid.visible_row(0)[9].c, 'J'); // preserved
}

#[test]
fn erase_in_line_k2() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0
    screen.process(b"\x1b[1;4H"); // move to row 1, col 4 (0-based col 3)
                                  // CSI 2K — erase entire line
    screen.process(b"\x1b[2K");
    for col in 0..10 {
        assert_eq!(
            screen.grid.visible_row(0)[col].c,
            ' ',
            "col {col} should be blank after CSI 2K"
        );
    }
}

#[test]
fn erase_character_ech() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0
    screen.process(b"\x1b[1;3H"); // move to col 3 (0-based col 2)
                                  // CSI 4X — erase 4 chars starting at cursor, without moving cursor
    screen.process(b"\x1b[4X");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[1].c, 'B');
    assert_eq!(screen.grid.visible_row(0)[2].c, ' '); // erased
    assert_eq!(screen.grid.visible_row(0)[3].c, ' '); // erased
    assert_eq!(screen.grid.visible_row(0)[4].c, ' '); // erased
    assert_eq!(screen.grid.visible_row(0)[5].c, ' '); // erased
    assert_eq!(screen.grid.visible_row(0)[6].c, 'G'); // preserved
    assert_eq!(screen.grid.visible_row(0)[9].c, 'J'); // preserved
                                                      // Cursor should not have moved
    assert_eq!(screen.grid.cursor_x(), 2);
}

#[test]
fn delete_character_dch() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0
    screen.process(b"\x1b[1;3H"); // move to col 3 (0-based col 2)
                                  // CSI 2P — delete 2 chars at cursor, shifting left
    screen.process(b"\x1b[2P");
    // 'C' and 'D' are deleted; E-J shift left, blanks fill right
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[1].c, 'B');
    assert_eq!(screen.grid.visible_row(0)[2].c, 'E');
    assert_eq!(screen.grid.visible_row(0)[3].c, 'F');
    assert_eq!(screen.grid.visible_row(0)[7].c, 'J');
    assert_eq!(screen.grid.visible_row(0)[8].c, ' '); // blank fill
    assert_eq!(screen.grid.visible_row(0)[9].c, ' '); // blank fill
}

#[test]
fn insert_character_ich() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0
    screen.process(b"\x1b[1;3H"); // move to col 3 (0-based col 2)
                                  // CSI 2@ — insert 2 blank chars at cursor, shifting right
    screen.process(b"\x1b[2@");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[1].c, 'B');
    assert_eq!(screen.grid.visible_row(0)[2].c, ' '); // inserted blank
    assert_eq!(screen.grid.visible_row(0)[3].c, ' '); // inserted blank
    assert_eq!(screen.grid.visible_row(0)[4].c, 'C'); // shifted right
    assert_eq!(screen.grid.visible_row(0)[5].c, 'D'); // shifted right
                                                      // 'I' and 'J' fall off the right edge
    assert_eq!(screen.grid.visible_row(0)[9].c, 'H');
}

#[test]
fn scroll_up_su() {
    let mut screen = Screen::new(10, 5, 100);
    // Place identifiable content on each row
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("Row{}", row).as_bytes());
    }
    // CSI 2S — scroll up 2 lines
    screen.process(b"\x1b[2S");
    // Row 0 should now show what was row 2
    assert_eq!(screen.grid.visible_row(0)[0].c, 'R');
    assert_eq!(screen.grid.visible_row(0)[3].c, '2');
    // Last two rows should be blank
    assert_eq!(screen.grid.visible_row(3)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(4)[0].c, ' ');
}

#[test]
fn scroll_down_sd() {
    let mut screen = Screen::new(10, 5, 100);
    // Place identifiable content on each row
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("Row{}", row).as_bytes());
    }
    // CSI 2T — scroll down 2 lines
    screen.process(b"\x1b[2T");
    // First two rows should be blank
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(1)[0].c, ' ');
    // Row 2 should now show what was row 0
    assert_eq!(screen.grid.visible_row(2)[0].c, 'R');
    assert_eq!(screen.grid.visible_row(2)[3].c, '0');
}

#[test]
fn delete_lines_dl() {
    let mut screen = Screen::new(10, 5, 100);
    // Fill rows with identifiable content
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("Line{}", row).as_bytes());
    }
    // Move cursor to row 2 (0-based row 1)
    screen.process(b"\x1b[2;1H");
    // CSI 2M — delete 2 lines at cursor
    screen.process(b"\x1b[2M");
    // Row 1 should now be what was row 3 ("Line3")
    assert_eq!(screen.grid.visible_row(1)[4].c, '3');
    // Row 2 should now be what was row 4 ("Line4")
    assert_eq!(screen.grid.visible_row(2)[4].c, '4');
    // Bottom rows should be blank
    assert_eq!(screen.grid.visible_row(3)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(4)[0].c, ' ');
}

#[test]
fn insert_lines_il() {
    let mut screen = Screen::new(10, 5, 100);
    // Fill rows with identifiable content
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("Line{}", row).as_bytes());
    }
    // Move cursor to row 2 (0-based row 1)
    screen.process(b"\x1b[2;1H");
    // CSI 2L — insert 2 blank lines at cursor
    screen.process(b"\x1b[2L");
    // Row 0 should still be "Line0"
    assert_eq!(screen.grid.visible_row(0)[4].c, '0');
    // Rows 1 and 2 should be blank (inserted)
    assert_eq!(screen.grid.visible_row(1)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(2)[0].c, ' ');
    // Row 3 should be what was row 1 ("Line1")
    assert_eq!(screen.grid.visible_row(3)[4].c, '1');
    // "Line3" and "Line4" have been pushed off the bottom
}

#[test]
fn decstbm_set_scroll_region() {
    let mut screen = Screen::new(80, 24, 100);
    // Move cursor to a non-home position first
    screen.process(b"\x1b[10;20H");
    assert_eq!(screen.grid.cursor_y(), 9);
    assert_eq!(screen.grid.cursor_x(), 19);
    // CSI 5;15r — set scroll region to rows 5-15
    screen.process(b"\x1b[5;15r");
    // Scroll region should be set (0-based)
    assert_eq!(screen.grid.scroll_top(), 4);
    assert_eq!(screen.grid.scroll_bottom(), 14);
    // Cursor should move to 0,0
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.cursor_y(), 0);
    // wrap_pending should be cleared
    assert!(!screen.grid.wrap_pending());
}

#[test]
fn reverse_index_ri() {
    let mut screen = Screen::new(10, 5, 100);
    // Set scroll region to rows 2-4 (0-based: 1-3)
    screen.process(b"\x1b[2;4r");
    // Place content in scroll region
    screen.process(b"\x1b[2;1H");
    screen.process(b"LineA");
    screen.process(b"\x1b[3;1H");
    screen.process(b"LineB");
    screen.process(b"\x1b[4;1H");
    screen.process(b"LineC");
    // Move to top of scroll region (row 2, 0-based row 1)
    screen.process(b"\x1b[2;1H");
    assert_eq!(screen.grid.cursor_y(), 1);
    // ESC M — reverse index at top of scroll region should scroll down
    screen.process(b"\x1bM");
    // Cursor stays at scroll_top
    assert_eq!(screen.grid.cursor_y(), 1);
    // Row 1 should now be blank (new line scrolled in)
    assert_eq!(screen.grid.visible_row(1)[0].c, ' ');
    // Row 2 should now be "LineA" (shifted down)
    assert_eq!(screen.grid.visible_row(2)[0].c, 'L');
    assert_eq!(screen.grid.visible_row(2)[4].c, 'A');
}

#[test]
fn reverse_index_ri_not_at_top() {
    // When cursor is NOT at the scroll_top, RI just moves cursor up one line
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"\x1b[3;1H"); // row 3, col 1 (0-based row 2)
    screen.process(b"\x1bM"); // ESC M
    assert_eq!(screen.grid.cursor_y(), 1); // moved up one
}

#[test]
fn focus_reporting_mode() {
    let mut screen = Screen::new(80, 24, 100);
    assert!(!screen.grid.modes().focus_reporting);
    // CSI ?1004h — enable focus reporting
    screen.process(b"\x1b[?1004h");
    assert!(screen.grid.modes().focus_reporting);
    // CSI ?1004l — disable focus reporting
    screen.process(b"\x1b[?1004l");
    assert!(!screen.grid.modes().focus_reporting);
}

#[test]
fn autowrap_mode_re_enable() {
    let mut screen = Screen::new(5, 3, 100);
    // Disable autowrap
    screen.process(b"\x1b[?7l");
    assert!(!screen.grid.modes().autowrap_mode);
    // Write past end of line — should NOT wrap
    screen.process(b"ABCDEF");
    assert_eq!(screen.grid.cursor_y(), 0);
    assert_eq!(screen.grid.visible_row(0)[4].c, 'F');

    // Re-enable autowrap
    screen.process(b"\x1b[?7h");
    assert!(screen.grid.modes().autowrap_mode);
    // Go back to start, fill line, and verify wrap now works
    screen.process(b"\x1b[1;1H");
    screen.process(b"12345");
    assert!(screen.grid.wrap_pending());
    screen.process(b"6");
    assert_eq!(screen.grid.cursor_y(), 1);
    assert_eq!(screen.grid.visible_row(1)[0].c, '6');
}

#[test]
fn bce_erase_uses_bg_color() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0
                                   // Set background color to red (SGR 41)
    screen.process(b"\x1b[41m");
    // Move to col 3 and erase to end of line
    screen.process(b"\x1b[1;4H");
    screen.process(b"\x1b[0K");
    // Erased cells should have the red background
    let expected_bg = Some(style::Color::Indexed(1)); // red = index 1
    assert_eq!(
        screen.cell_style(0, 3).bg,
        expected_bg,
        "erased cell at col 3 should have red background (BCE)"
    );
    assert_eq!(
        screen.cell_style(0, 9).bg,
        expected_bg,
        "erased cell at col 9 should have red background (BCE)"
    );
    // Cells before cursor should NOT have the red bg (they were written before SGR 41)
    assert_eq!(
        screen.cell_style(0, 0).bg,
        None,
        "cell at col 0 should have default background"
    );

    // Also verify BCE with CSI 2J (erase entire display)
    screen.process(b"\x1b[2J");
    assert_eq!(
        screen.cell_style(1, 5).bg,
        expected_bg,
        "CSI 2J erased cell should have red background (BCE)"
    );

    // And ECH (erase character)
    screen.process(b"\x1b[1;1H");
    screen.process(b"XYZ");
    screen.process(b"\x1b[1;1H");
    screen.process(b"\x1b[2X"); // erase 2 chars
    assert_eq!(
        screen.cell_style(0, 0).bg,
        expected_bg,
        "ECH erased cell should have red background (BCE)"
    );
    assert_eq!(
        screen.cell_style(0, 1).bg,
        expected_bg,
        "ECH erased cell at col 1 should have red background (BCE)"
    );
}

// ---------------------------------------------------------------
// Additional coverage tests
// ---------------------------------------------------------------

#[test]
fn tab_advances_to_next_tab_stop() {
    let mut screen = Screen::new(80, 3, 100);
    screen.process(b"AB"); // cursor at col 2
    screen.process(b"\t"); // tab should advance to col 8
    assert_eq!(screen.grid.cursor_x(), 8);
    screen.process(b"\t"); // next tab stop at col 16
    assert_eq!(screen.grid.cursor_x(), 16);
}

#[test]
fn tab_at_end_of_line_clamps() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGH"); // cursor at col 8
    screen.process(b"\t"); // tab should clamp to col 9 (cols-1)
    assert_eq!(screen.grid.cursor_x(), 9);
}

#[test]
fn backspace_at_column_zero() {
    let mut screen = Screen::new(80, 3, 100);
    assert_eq!(screen.grid.cursor_x(), 0);
    screen.process(b"\x08"); // BS at col 0
    assert_eq!(screen.grid.cursor_x(), 0, "BS at column 0 should stay at 0");
}

#[test]
fn backspace_clears_wrap_pending() {
    let mut screen = Screen::new(5, 3, 100);
    screen.process(b"ABCDE"); // wrap_pending = true
    assert!(screen.grid.wrap_pending());
    screen.process(b"\x08"); // BS
    assert!(!screen.grid.wrap_pending(), "BS should clear wrap_pending");
    assert_eq!(screen.grid.cursor_x(), 3);
}

#[test]
fn erase_scrollback_j3() {
    let mut screen = Screen::new(10, 3, 100);
    // Generate scrollback
    screen.process(b"Line1\r\nLine2\r\nLine3\r\nLine4\r\nLine5");
    let history = screen.get_history();
    assert!(!history.is_empty(), "should have scrollback before J3");

    // CSI 3J — erase scrollback
    screen.process(b"\x1b[3J");
    let history_after = screen.get_history();
    assert!(
        history_after.is_empty(),
        "CSI 3J should clear all scrollback, got {} lines",
        history_after.len()
    );
}

#[test]
fn alt_screen_clears_wrap_pending() {
    let mut screen = Screen::new(5, 3, 100);
    screen.process(b"ABCDE"); // fills line, wrap_pending = true
    assert!(screen.grid.wrap_pending());

    // Enter alt screen
    screen.process(b"\x1b[?1049h");
    assert!(
        !screen.grid.wrap_pending(),
        "wrap_pending should be cleared on alt screen enter"
    );
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.cursor_y(), 0);
}

#[test]
fn alt_screen_mode_1047() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"Hello");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'H');

    // Enter alt screen via mode 1047
    screen.process(b"\x1b[?1047h");
    assert!(screen.in_alt_screen());
    assert_eq!(screen.grid.visible_row(0)[0].c, ' '); // alt screen cleared

    screen.process(b"Alt");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');

    // Leave alt screen
    screen.process(b"\x1b[?1047l");
    assert!(!screen.in_alt_screen());
    assert_eq!(screen.grid.visible_row(0)[0].c, 'H'); // main buffer restored
}

#[test]
fn alt_screen_mode_47() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"Main");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'M');

    screen.process(b"\x1b[?47h");
    assert!(screen.in_alt_screen());
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');

    screen.process(b"\x1b[?47l");
    assert!(!screen.in_alt_screen());
    assert_eq!(screen.grid.visible_row(0)[0].c, 'M');
}

#[test]
fn alt_screen_restores_modes() {
    let mut screen = Screen::new(10, 3, 100);
    // Set some modes on main screen
    screen.process(b"\x1b[?2004h"); // bracketed paste
    screen.process(b"\x1b[?1h"); // cursor key mode
    assert!(screen.grid.modes().bracketed_paste);
    assert!(screen.grid.modes().cursor_key_mode);

    // Enter alt screen
    screen.process(b"\x1b[?1049h");
    // Modes should still be there (saved, but current grid is alt)
    // Now change modes on alt screen
    screen.process(b"\x1b[?2004l");
    screen.process(b"\x1b[?1l");
    assert!(!screen.grid.modes().bracketed_paste);
    assert!(!screen.grid.modes().cursor_key_mode);

    // Leave alt screen — modes should be restored
    screen.process(b"\x1b[?1049l");
    assert!(
        screen.grid.modes().bracketed_paste,
        "bracketed paste should be restored on alt screen exit"
    );
    assert!(
        screen.grid.modes().cursor_key_mode,
        "cursor key mode should be restored on alt screen exit"
    );
}

#[test]
fn cursor_visibility_mode_25() {
    let mut screen = Screen::new(80, 24, 100);
    assert!(screen.grid.cursor_visible());
    screen.process(b"\x1b[?25l");
    assert!(
        !screen.grid.cursor_visible(),
        "cursor should be hidden after ?25l"
    );
    screen.process(b"\x1b[?25h");
    assert!(
        screen.grid.cursor_visible(),
        "cursor should be visible after ?25h"
    );
}

#[test]
fn render_with_hidden_cursor() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"\x1b[?25l"); // hide cursor
    let mut cache = AnsiRenderer::new();
    let result = cache.render(&screen, false);
    let text = String::from_utf8_lossy(&result);
    // Should NOT contain ?25h (cursor show) since cursor is hidden
    assert!(
        !text.contains("\x1b[?25h"),
        "hidden cursor should not emit ?25h in render output"
    );
    // Should contain ?25l (cursor hide for redraw)
    assert!(
        text.contains("\x1b[?25l"),
        "render should always hide cursor during redraw"
    );
}

#[test]
fn render_full_reattach_redraws_all() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"Hello");
    let mut cache = AnsiRenderer::new();
    // First render
    let _ = cache.render(&screen, false);

    // Simulate reattach: full render with existing cache
    let result = cache.render(&screen, true);
    let text = String::from_utf8_lossy(&result);
    assert!(text.contains("\x1b[2J"), "full render should screen clear");
    assert!(
        text.contains("Hello"),
        "full render should include screen content"
    );
}

#[test]
fn pending_scrollback_drained_separately() {
    let mut screen = Screen::new(10, 3, 100);
    // Cause scrollback
    screen.process(b"A\r\nB\r\nC\r\nD");
    let pending_rows = screen.take_pending_scrollback();
    let pending = AnsiRenderer::new().render_rows(&screen, &pending_rows);
    assert!(!pending.is_empty(), "should have pending scrollback");

    // Second drain should be empty
    let pending2_rows = screen.take_pending_scrollback();
    let pending2 = AnsiRenderer::new().render_rows(&screen, &pending2_rows);
    assert!(pending2.is_empty(), "second drain should be empty");

    // History should still contain everything
    let history = screen.get_history();
    assert!(
        !history.is_empty(),
        "history should be preserved after drain"
    );
}

#[test]
fn stale_pending_scrollback_after_reattach_simulation() {
    // Simulates: client1 processes data, disconnects mid-scroll,
    // client2 connects and shouldn't see duplicate scrollback
    let mut screen = Screen::new(10, 3, 100);

    // Simulate first client processing output (causes scrollback)
    screen.process(b"Line1\r\nLine2\r\nLine3\r\nLine4");
    // Client1 takes pending scrollback (normal operation)
    let _ = screen.take_pending_scrollback();

    // More output causes more scrollback
    screen.process(b"\r\nLine5\r\nLine6");
    // Client1 disconnects WITHOUT draining pending scrollback

    // Simulate reattach: get history (what would be sent as History msg)
    let history = screen.get_history();
    let history_count = history.len();

    // Drain stale pending scrollback (the fix in session_bridge.rs)
    let stale_rows = screen.take_pending_scrollback();
    let stale = AnsiRenderer::new().render_rows(&screen, &stale_rows);
    assert!(
        !stale.is_empty(),
        "there should be stale pending scrollback from the disconnect"
    );

    // Now new PTY output arrives
    screen.process(b"\r\nLine7");
    let new_pending_rows = screen.take_pending_scrollback();
    let new_pending = AnsiRenderer::new().render_rows(&screen, &new_pending_rows);

    // New pending should only contain Line7's scroll, not duplicates
    let new_history = screen.get_history();
    assert_eq!(
        new_history.len(),
        history_count + new_pending.len(),
        "new scrollback should only contain lines added after reattach drain"
    );
}

#[test]
fn window_ops_ignored() {
    let mut screen = Screen::new(80, 24, 100);
    // CSI t (window ops) should be silently ignored
    screen.process(b"\x1b[14t"); // report window size
    screen.process(b"\x1b[22;0t"); // push title
                                   // Should not crash, no responses generated
    let responses = screen.take_responses();
    assert!(
        responses.is_empty(),
        "window ops should not generate responses"
    );
}

#[test]
fn scroll_region_il_dl_interaction() {
    let mut screen = Screen::new(10, 6, 100);
    // Set scroll region to rows 2-5
    screen.process(b"\x1b[2;5r");
    // Fill all rows
    for row in 0..6 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("R{}", row).as_bytes());
    }
    // Move into scroll region and insert a line
    screen.process(b"\x1b[3;1H"); // row 3 (inside region)
    screen.process(b"\x1b[L"); // IL 1

    // Row 2 (0-indexed) should be blank (inserted)
    assert_eq!(
        screen.grid.visible_row(2)[0].c,
        ' ',
        "inserted line should be blank"
    );
    // Row 1 (above region) should be untouched
    assert_eq!(
        screen.grid.visible_row(0)[0].c,
        'R',
        "row above scroll region should be untouched"
    );
    // Row 5 (below region bottom) should be untouched
    assert_eq!(
        screen.grid.visible_row(5)[0].c,
        'R',
        "row below scroll region should be untouched"
    );
}

// --- New integration tests ---

#[test]
fn render_bce_erase_output() {
    // Rendered ANSI should include background color after BCE erase
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0
    screen.process(b"\x1b[41m"); // set bg red
    screen.process(b"\x1b[1;4H"); // move to col 3 (1-indexed col 4)
    screen.process(b"\x1b[0K"); // erase to end of line

    let mut cache = AnsiRenderer::new();
    let result = cache.render(&screen, true);
    let text = String::from_utf8_lossy(&result);
    // The rendered output should include the red bg SGR (code 41)
    // for the erased cells
    assert!(
        text.contains("41"),
        "rendered output should include red bg (41) after BCE erase"
    );
}

#[test]
fn wide_char_scrollback_rendering() {
    // Wide char in scrollback line should render correctly
    let mut screen = Screen::new(10, 3, 100);
    // Write a wide char on row 0
    screen.process("\u{4e16}\u{754c}".as_bytes()); // 世界
                                                   // Scroll it into scrollback
    screen.process(b"\r\nLine2\r\nLine3\r\nLine4");

    let history = screen.get_history();
    assert!(!history.is_empty(), "should have scrollback");
    // The first scrollback line should contain the wide chars rendered as ANSI
    let first_line = String::from_utf8_lossy(&history[0]);
    assert!(
        first_line.contains('\u{4e16}'),
        "scrollback should contain wide char 世"
    );
    assert!(
        first_line.contains('\u{754c}'),
        "scrollback should contain wide char 界"
    );
}

#[test]
fn combining_mark_attaches_to_previous_cell() {
    let mut screen = Screen::new(80, 24, 100);
    // Print 'e' followed by combining acute accent U+0301
    screen.process("e\u{0301}".as_bytes());
    assert_eq!(screen.grid.visible_row(0)[0].c, 'e');
    assert_eq!(screen.grid.visible_row(0).combining(0), &['\u{0301}']);
}

#[test]
fn combining_mark_with_wrap_pending() {
    let mut screen = Screen::new(5, 3, 100);
    // Fill the line to trigger wrap_pending
    screen.process(b"ABCDE");
    assert!(
        screen.grid.wrap_pending(),
        "wrap should be pending after filling line"
    );
    // Now send a combining mark — it should attach to the last cell (E)
    screen.process("\u{0308}".as_bytes()); // combining diaeresis
    assert_eq!(screen.grid.visible_row(0)[4].c, 'E');
    assert_eq!(screen.grid.visible_row(0).combining(4), &['\u{0308}']);
}

#[test]
fn combining_mark_on_wide_char() {
    let mut screen = Screen::new(80, 24, 100);
    // Print a wide char followed by a combining mark
    screen.process("\u{4e16}\u{0301}".as_bytes()); // 世 + combining acute
                                                   // The combining mark should attach to the wide char cell (col 0), not the continuation (col 1)
    assert_eq!(screen.grid.visible_row(0)[0].c, '\u{4e16}');
    assert_eq!(screen.grid.visible_row(0).combining(0), &['\u{0301}']);
    assert_eq!(screen.grid.visible_row(0)[1].width, 0); // continuation cell
}

#[test]
fn combining_mark_renders_in_output() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process("e\u{0301}".as_bytes());
    let mut cache = AnsiRenderer::new();
    let output = cache.render(&screen, true);
    let text = String::from_utf8_lossy(&output);
    assert!(
        text.contains("e\u{0301}"),
        "rendered output should contain base char + combining mark"
    );
}

#[test]
fn delete_lines_preserves_cursor_x() {
    let mut screen = Screen::new(80, 24, 100);
    // Position cursor at column 10, row 5
    screen.process(b"\x1b[6;11H"); // CUP row=6, col=11 (1-indexed)
    assert_eq!(screen.grid.cursor_x(), 10);
    assert_eq!(screen.grid.cursor_y(), 5);
    // Delete 1 line
    screen.process(b"\x1b[M");
    // cursor_x must be preserved per ECMA-48
    assert_eq!(screen.grid.cursor_x(), 10, "DL must not change cursor_x");
    assert_eq!(screen.grid.cursor_y(), 5, "DL must not change cursor_y");
}

#[test]
fn insert_lines_preserves_cursor_x() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[6;11H");
    assert_eq!(screen.grid.cursor_x(), 10);
    // Insert 1 line
    screen.process(b"\x1b[L");
    assert_eq!(screen.grid.cursor_x(), 10, "IL must not change cursor_x");
    assert_eq!(screen.grid.cursor_y(), 5, "IL must not change cursor_y");
}

// ─── Scroll tests ────────────────────────────────────────────────────────

/// Helper: collect visible grid rows as trimmed strings.
fn screen_lines(screen: &Screen) -> Vec<String> {
    screen
        .grid
        .visible_rows()
        .map(|row| {
            let s: String = row.iter().map(|c| c.c).collect();
            s.trim_end().to_string()
        })
        .collect()
}

/// Helper: strip ANSI escape sequences, returning only printable text.
fn strip_ansi(bytes: &[u8]) -> String {
    let s = String::from_utf8_lossy(bytes);
    let mut out = String::new();
    let mut in_esc = false;
    for ch in s.chars() {
        if in_esc {
            if ch.is_ascii_alphabetic() || ch == 'm' {
                in_esc = false;
            }
            continue;
        }
        if ch == '\x1b' {
            in_esc = true;
            continue;
        }
        if ch >= ' ' {
            out.push(ch);
        }
    }
    out.trim_end().to_string()
}

/// Helper: get scrollback history as trimmed text strings.
fn history_texts(screen: &Screen) -> Vec<String> {
    screen.get_history().iter().map(|b| strip_ansi(b)).collect()
}

#[test]
fn lf_at_bottom_scrolls_content_up() {
    // The most common scroll scenario: app outputs lines until the screen
    // is full, then the next LF at scroll_bottom scrolls everything up.
    let mut screen = Screen::new(10, 4, 100);
    // Fill all 4 rows
    screen.process(b"Row0\r\nRow1\r\nRow2\r\nRow3");
    assert_eq!(screen_lines(&screen), vec!["Row0", "Row1", "Row2", "Row3"]);

    // One more LF + content — triggers scroll
    screen.process(b"\r\nRow4");
    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Row1", "first visible row after scroll");
    assert_eq!(lines[1], "Row2");
    assert_eq!(lines[2], "Row3");
    assert_eq!(lines[3], "Row4", "new content at bottom");
}

#[test]
fn lf_scroll_captures_scrollback() {
    // When a line scrolls off the top, it goes into scrollback.
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"AAA\r\nBBB\r\nCCC\r\nDDD");

    let hist = history_texts(&screen);
    assert_eq!(hist.len(), 1, "exactly one line scrolled off");
    assert_eq!(hist[0], "AAA");
}

#[test]
fn su_does_not_capture_scrollback() {
    // SU (CSI Ps S) pans the scroll region up but, per xterm, must NOT add the
    // scrolled-out lines to the saved-lines buffer (a pager redrawing via SU
    // would otherwise leak duplicate content into history).
    let mut screen = Screen::new(10, 4, 100);
    screen.process(b"Row0\r\nRow1\r\nRow2\r\nRow3");
    assert_eq!(screen.grid.scrollback_len(), 0, "no scrollback yet");

    // Scroll up two lines via SU.
    screen.process(b"\x1b[2S");

    assert_eq!(
        screen.grid.scrollback_len(),
        0,
        "SU must not capture rows into scrollback"
    );
    assert!(history_texts(&screen).is_empty(), "history stays empty");

    // Visible content shifted up by two, blanks at the bottom.
    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Row2");
    assert_eq!(lines[1], "Row3");
    assert_eq!(lines[2], "");
    assert_eq!(lines[3], "");
}

#[test]
fn lf_still_captures_scrollback_after_su() {
    // Control: autonomous (LF-driven) scrolling at the bottom margin must
    // still capture to scrollback, unaffected by the SU no-capture path.
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"AAA\r\nBBB\r\nCCC");
    assert_eq!(screen.grid.scrollback_len(), 0);

    screen.process(b"\r\nDDD");

    let hist = history_texts(&screen);
    assert_eq!(hist.len(), 1, "LF scroll still captures one line");
    assert_eq!(hist[0], "AAA");
}

#[test]
fn many_lines_overflow_screen() {
    // Simulates `cat large_file` — 20 lines output into a 5-row terminal.
    let mut screen = Screen::new(10, 5, 100);
    for i in 0..20 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("L{:02}", i).as_bytes());
    }

    // Only the last 5 lines should be visible
    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "L15");
    assert_eq!(lines[1], "L16");
    assert_eq!(lines[2], "L17");
    assert_eq!(lines[3], "L18");
    assert_eq!(lines[4], "L19");

    // 15 lines should be in scrollback (L00..L14)
    let hist = history_texts(&screen);
    assert_eq!(hist.len(), 15);
    assert_eq!(hist[0], "L00", "first scrollback line");
    assert_eq!(hist[14], "L14", "last scrollback line");
}

#[test]
fn scrollback_order_preserved() {
    // Scrollback should maintain chronological order: oldest first.
    let mut screen = Screen::new(10, 3, 100);
    for i in 0..10 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Line{}", i).as_bytes());
    }

    let hist = history_texts(&screen);
    // 7 lines scrolled off (lines 0-6), 3 remain visible (7-9)
    assert_eq!(hist.len(), 7);
    for (idx, h) in hist.iter().enumerate() {
        assert_eq!(
            *h,
            format!("Line{}", idx),
            "scrollback line {} should be Line{}",
            idx,
            idx
        );
    }
}

#[test]
fn lf_within_scroll_region_only_scrolls_region() {
    // Apps like vim set a scroll region (e.g., leaving a status bar at bottom).
    // LF at scroll_bottom scrolls only within the region.
    let mut screen = Screen::new(10, 6, 100);

    // Put content on all rows first
    for row in 0..6 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("Row{}", row).as_bytes());
    }

    // Set scroll region to rows 2-5 (0-based: 1-4), leaving row 0 and row 5 outside
    screen.process(b"\x1b[2;5r");

    // Move to bottom of scroll region (row 5 = 0-based row 4)
    screen.process(b"\x1b[5;1H");
    // Write a LF — should scroll within region only
    screen.process(b"\r\n");
    screen.process(b"New");

    let lines = screen_lines(&screen);
    // Row 0 (above region) should be untouched
    assert_eq!(
        lines[0], "Row0",
        "row above scroll region must be untouched"
    );
    // Row 5 (below region) should be untouched
    assert_eq!(
        lines[5], "Row5",
        "row below scroll region must be untouched"
    );
    // Content within region should have scrolled up
    assert_eq!(lines[1], "Row2", "top of region should have what was row 2");
    assert_eq!(lines[2], "Row3");
    assert_eq!(lines[3], "Row4");
}

#[test]
fn scroll_region_preserves_outer_content_on_multiple_scrolls() {
    // Multiple scrolls within a region should never touch rows outside it.
    let mut screen = Screen::new(10, 6, 100);

    // Set header and footer
    screen.process(b"\x1b[1;1HHeader");
    screen.process(b"\x1b[6;1HFooter");

    // Set scroll region to rows 2-5
    screen.process(b"\x1b[2;5r");

    // Fill region and scroll many times
    screen.process(b"\x1b[2;1H");
    for i in 0..12 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Msg{:02}", i).as_bytes());
    }

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Header", "header must survive region scrolling");
    assert_eq!(lines[5], "Footer", "footer must survive region scrolling");
}

#[test]
fn csi_s_within_scroll_region() {
    // CSI S (scroll up) should respect the scroll region.
    let mut screen = Screen::new(10, 6, 100);

    for row in 0..6 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("R{}", row).as_bytes());
    }

    // Set scroll region to rows 2-5 (0-based: 1-4)
    screen.process(b"\x1b[2;5r");
    // CSI 2S — scroll up 2 lines
    screen.process(b"\x1b[2S");

    let lines = screen_lines(&screen);
    // Row 0 (above region) untouched
    assert_eq!(lines[0], "R0", "row above region untouched after CSI S");
    // Row 5 (below region) untouched
    assert_eq!(lines[5], "R5", "row below region untouched after CSI S");
    // Region content scrolled up by 2
    assert_eq!(lines[1], "R3", "region top after scroll by 2");
    assert_eq!(lines[2], "R4", "region second row after scroll by 2");
    // Bottom two rows of region should be blank
    assert_eq!(lines[3], "", "blank line after scroll");
    assert_eq!(lines[4], "", "blank line after scroll");
}

#[test]
fn csi_t_within_scroll_region() {
    // CSI T (scroll down) should respect the scroll region.
    let mut screen = Screen::new(10, 6, 100);

    for row in 0..6 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("R{}", row).as_bytes());
    }

    // Set scroll region to rows 2-5 (0-based: 1-4)
    screen.process(b"\x1b[2;5r");
    // CSI 2T — scroll down 2 lines
    screen.process(b"\x1b[2T");

    let lines = screen_lines(&screen);
    // Row 0 (above region) untouched
    assert_eq!(lines[0], "R0", "row above region untouched after CSI T");
    // Row 5 (below region) untouched
    assert_eq!(lines[5], "R5", "row below region untouched after CSI T");
    // Top two rows of region should be blank (scrolled down)
    assert_eq!(lines[1], "", "blank line after scroll down");
    assert_eq!(lines[2], "", "blank line after scroll down");
    // Original region content shifted down by 2
    assert_eq!(lines[3], "R1", "shifted content after scroll down");
    assert_eq!(lines[4], "R2", "shifted content after scroll down");
}

#[test]
fn scroll_down_does_not_generate_scrollback() {
    // Scroll down (CSI T) should NOT produce scrollback — lines are lost at the bottom.
    let mut screen = Screen::new(10, 5, 100);
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("Row{}", row).as_bytes());
    }

    screen.process(b"\x1b[3T"); // scroll down 3

    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = AnsiRenderer::new().render_rows(&screen, &scrollback_rows);
    assert!(
        scrollback.is_empty(),
        "CSI T (scroll down) should not generate scrollback"
    );
}

#[test]
fn cursor_stays_in_place_during_lf_scroll() {
    // When LF triggers scroll, the cursor stays at scroll_bottom and
    // its column does not change.
    let mut screen = Screen::new(20, 3, 100);
    screen.process(b"Row0\r\nRow1\r\nRow2");
    // Cursor is now at row 2, col 4
    assert_eq!(screen.grid.cursor_y(), 2);
    assert_eq!(screen.grid.cursor_x(), 4);

    // Move cursor to col 10
    screen.process(b"\x1b[1;11H"); // row 1, col 11 (0-based: row 0, col 10)
    screen.process(b"\x1b[3;11H"); // move to row 3 (bottom), col 11

    // Trigger LF-based scroll
    screen.process(b"\r\n");
    // Cursor should be at scroll_bottom, col 0 (CR moved it)
    assert_eq!(screen.grid.cursor_y(), 2, "cursor_y stays at scroll_bottom");
    assert_eq!(screen.grid.cursor_x(), 0, "cursor_x reset by CR");
}

#[test]
fn cursor_column_preserved_on_bare_lf_scroll() {
    // Bare LF (without CR) at the bottom: cursor_x should not change.
    let mut screen = Screen::new(20, 3, 100);
    screen.process(b"Row0\r\nRow1\r\n");
    // Cursor at row 2, col 0
    screen.process(b"\x1b[3;8H"); // move to row 3, col 8 (0-based: row 2, col 7)
    assert_eq!(screen.grid.cursor_y(), 2);
    assert_eq!(screen.grid.cursor_x(), 7);

    // Bare LF (no CR) triggers scroll
    screen.process(b"\n");
    assert_eq!(screen.grid.cursor_y(), 2, "cursor_y stays at scroll_bottom");
    assert_eq!(screen.grid.cursor_x(), 7, "bare LF preserves cursor_x");
}

#[test]
fn reverse_index_at_top_of_full_screen_scrolls_down() {
    // ESC M (RI) at row 0 with full-screen scroll region scrolls entire screen down.
    let mut screen = Screen::new(10, 4, 100);
    screen.process(b"Row0\r\nRow1\r\nRow2\r\nRow3");

    // Move cursor to row 0
    screen.process(b"\x1b[1;1H");
    // ESC M — reverse index
    screen.process(b"\x1bM");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "", "new blank line at top");
    assert_eq!(lines[1], "Row0", "original row 0 shifted down");
    assert_eq!(lines[2], "Row1", "original row 1 shifted down");
    assert_eq!(lines[3], "Row2", "original row 2 shifted down");
    // Row3 is lost (pushed off bottom)
}

#[test]
fn rapid_scroll_up_down_content_integrity() {
    // Alternating scroll up and scroll down should not corrupt content.
    let mut screen = Screen::new(10, 5, 100);
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("Row{}", row).as_bytes());
    }

    // Scroll up 2, then scroll down 2 — content should differ because
    // scroll_up blanks from bottom, scroll_down blanks from top
    screen.process(b"\x1b[2S"); // scroll up 2
    screen.process(b"\x1b[2T"); // scroll down 2

    let lines = screen_lines(&screen);
    // After scroll up 2: [Row2, Row3, Row4, "", ""]
    // After scroll down 2: pop 2 blanks from bottom, push 2 blanks at top
    // Result: ["", "", Row2, Row3, Row4]
    assert_eq!(lines[0], "", "blank at top after scroll down");
    assert_eq!(lines[1], "", "blank at top after scroll down");
    assert_eq!(lines[2], "Row2", "surviving content");
    assert_eq!(lines[3], "Row3", "surviving content");
    assert_eq!(lines[4], "Row4", "surviving content shifted back");
}

#[test]
fn lf_scroll_with_styled_content() {
    // BCE: when scrolling introduces a new blank line, it should use the
    // current background color. Verify blank cells have the active style.
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"Row0\r\nRow1\r\nRow2");

    // Set background to red before scrolling
    screen.process(b"\x1b[41m");
    // LF at bottom triggers scroll — new blank line should have red bg
    screen.process(b"\r\n");

    // The bottom row (row 2) should be blank with red background
    assert_eq!(screen.cell_char(2, 0), ' ', "new line should be blank");
    assert_eq!(
        screen.cell_style(2, 0).bg,
        Some(style::Color::Indexed(1)),
        "blank line should inherit current bg (BCE)"
    );
}

#[test]
fn scroll_region_lf_no_scrollback_when_top_nonzero() {
    // When scroll_top > 0, LF-driven scroll should NOT capture scrollback
    // (the line is internal to a partial region, not the physical top).
    let mut screen = Screen::new(10, 6, 100);

    // Set scroll region to rows 3-6 (0-based: 2-5) — scroll_top != 0
    screen.process(b"\x1b[3;6r");

    // Fill region and overflow
    screen.process(b"\x1b[3;1H");
    for i in 0..10 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Msg{}", i).as_bytes());
    }

    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = AnsiRenderer::new().render_rows(&screen, &scrollback_rows);
    assert!(
        scrollback.is_empty(),
        "scroll_top > 0: no scrollback should be captured"
    );
}

// ─── TUI app scroll tests ───────────────────────────────────────────────
// Scenarios for interactive programs (vim, htop, Claude CLI, etc.)
// that enter alt screen, set scroll regions, and scroll content.

#[test]
fn tui_app_alt_screen_scroll_region_lf() {
    // A TUI app enters alt screen, sets a scroll region (status bar at bottom),
    // and outputs enough lines to scroll the content area via LF.
    let mut screen = Screen::new(20, 6, 100);
    screen.process(b"MainContent"); // main screen content

    // Enter alt screen
    screen.process(b"\x1b[?1049h");

    // Draw status bar on row 6
    screen.process(b"\x1b[6;1HStatus: OK");

    // Set scroll region to rows 1-5 (content area, leaving status bar outside)
    screen.process(b"\x1b[1;5r");

    // Fill content area and overflow — triggers scroll within region
    screen.process(b"\x1b[1;1H");
    for i in 0..8 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Msg{:02}", i).as_bytes());
    }

    let lines = screen_lines(&screen);
    // Status bar (row 5, outside region) must be untouched
    assert_eq!(lines[5], "Status: OK", "status bar must survive scroll");
    // Last 5 messages should be visible in the content area
    assert_eq!(lines[0], "Msg03");
    assert_eq!(lines[1], "Msg04");
    assert_eq!(lines[2], "Msg05");
    assert_eq!(lines[3], "Msg06");
    assert_eq!(lines[4], "Msg07");
}

#[test]
fn tui_app_alt_screen_explicit_scroll_up() {
    // A TUI app uses CSI S (explicit scroll up) in alt screen to scroll content.
    let mut screen = Screen::new(15, 5, 100);

    // Enter alt screen
    screen.process(b"\x1b[?1049h");

    // Place content
    for row in 0..5 {
        screen.process(format!("\x1b[{};1H", row + 1).as_bytes());
        screen.process(format!("Line{}", row).as_bytes());
    }

    // CSI 2S — scroll up 2 lines
    screen.process(b"\x1b[2S");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Line2", "content shifted up by 2");
    assert_eq!(lines[1], "Line3");
    assert_eq!(lines[2], "Line4");
    assert_eq!(lines[3], "", "blank line at bottom");
    assert_eq!(lines[4], "", "blank line at bottom");

    // No scrollback should be generated in alt screen
    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = AnsiRenderer::new().render_rows(&screen, &scrollback_rows);
    assert!(
        scrollback.is_empty(),
        "alt screen CSI S should not generate scrollback"
    );
}

#[test]
fn tui_app_alt_screen_scroll_then_exit_restores_main() {
    // After scrolling in alt screen, exiting should restore the original main screen.
    let mut screen = Screen::new(15, 4, 100);
    screen.process(b"Original0\r\nOriginal1\r\nOriginal2\r\nOriginal3");

    // Enter alt screen, scroll heavily
    screen.process(b"\x1b[?1049h");
    for i in 0..20 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Alt{}", i).as_bytes());
    }

    // Exit alt screen
    screen.process(b"\x1b[?1049l");

    // Main screen should be fully restored
    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Original0");
    assert_eq!(lines[1], "Original1");
    assert_eq!(lines[2], "Original2");
    assert_eq!(lines[3], "Original3");
}

#[test]
fn tui_app_scroll_region_with_header_and_footer() {
    // App with header (row 1), content area (rows 2-4), footer (row 5).
    // Only content area scrolls.
    let mut screen = Screen::new(20, 5, 100);

    screen.process(b"\x1b[?1049h"); // enter alt screen

    // Draw header and footer
    screen.process(b"\x1b[1;1H== My App ==");
    screen.process(b"\x1b[5;1H[Ctrl+C quit]");

    // Set scroll region to rows 2-4
    screen.process(b"\x1b[2;4r");

    // Fill content area and scroll
    screen.process(b"\x1b[2;1H");
    for i in 0..10 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("item{}", i).as_bytes());
    }

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "== My App ==", "header must be preserved");
    assert_eq!(lines[4], "[Ctrl+C quit]", "footer must be preserved");
    // Last 3 items should be visible
    assert_eq!(lines[1], "item7");
    assert_eq!(lines[2], "item8");
    assert_eq!(lines[3], "item9");
}

#[test]
fn tui_app_delete_lines_within_scroll_region() {
    // A TUI app removes a line from a list using CSI M (Delete Lines)
    // within a scroll region. Content below shifts up, blank appears at region bottom.
    let mut screen = Screen::new(15, 6, 100);

    screen.process(b"\x1b[?1049h");
    screen.process(b"\x1b[1;1HTitle");
    screen.process(b"\x1b[6;1HStatus");

    // Set scroll region for content area
    screen.process(b"\x1b[2;5r");

    // Fill content area
    screen.process(b"\x1b[2;1HItem-A");
    screen.process(b"\x1b[3;1HItem-B");
    screen.process(b"\x1b[4;1HItem-C");
    screen.process(b"\x1b[5;1HItem-D");

    // Delete Item-B (row 3) — cursor must be at the line to delete
    screen.process(b"\x1b[3;1H");
    screen.process(b"\x1b[M"); // DL 1

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Title", "title preserved");
    assert_eq!(lines[5], "Status", "status preserved");
    assert_eq!(lines[1], "Item-A", "Item-A stays");
    assert_eq!(
        lines[2], "Item-C",
        "Item-C shifted up into Item-B's position"
    );
    assert_eq!(lines[3], "Item-D", "Item-D shifted up");
    assert_eq!(lines[4], "", "blank line at region bottom");
}

#[test]
fn tui_app_insert_lines_within_scroll_region() {
    // A TUI app inserts a new line into a list using CSI L (Insert Lines)
    // within a scroll region. Content below shifts down, last line in region is lost.
    let mut screen = Screen::new(15, 6, 100);

    screen.process(b"\x1b[?1049h");
    screen.process(b"\x1b[1;1HTitle");
    screen.process(b"\x1b[6;1HStatus");

    // Set scroll region for content area
    screen.process(b"\x1b[2;5r");

    // Fill content area
    screen.process(b"\x1b[2;1HItem-A");
    screen.process(b"\x1b[3;1HItem-B");
    screen.process(b"\x1b[4;1HItem-C");
    screen.process(b"\x1b[5;1HItem-D");

    // Insert a blank line at row 3 (between Item-A and Item-B)
    screen.process(b"\x1b[3;1H");
    screen.process(b"\x1b[L"); // IL 1
    screen.process(b"NEW ITEM");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Title", "title preserved");
    assert_eq!(lines[5], "Status", "status preserved");
    assert_eq!(lines[1], "Item-A", "Item-A stays");
    assert_eq!(lines[2], "NEW ITEM", "new item inserted");
    assert_eq!(lines[3], "Item-B", "Item-B shifted down");
    assert_eq!(lines[4], "Item-C", "Item-C shifted down");
    // Item-D is pushed off the bottom of the scroll region
}

#[test]
fn tui_app_reverse_index_in_scroll_region() {
    // A TUI app uses ESC M (Reverse Index) at the top of a scroll region
    // to scroll content down — e.g., inserting a line at the top of the output area.
    let mut screen = Screen::new(15, 6, 100);

    screen.process(b"\x1b[?1049h");
    screen.process(b"\x1b[1;1HHeader");
    screen.process(b"\x1b[6;1HFooter");

    // Set scroll region
    screen.process(b"\x1b[2;5r");

    // Fill content area
    screen.process(b"\x1b[2;1HMsg-A");
    screen.process(b"\x1b[3;1HMsg-B");
    screen.process(b"\x1b[4;1HMsg-C");
    screen.process(b"\x1b[5;1HMsg-D");

    // Move to top of scroll region and reverse index
    screen.process(b"\x1b[2;1H");
    screen.process(b"\x1bM"); // RI — scroll content down within region

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Header", "header preserved");
    assert_eq!(lines[5], "Footer", "footer preserved");
    assert_eq!(lines[1], "", "new blank line at region top");
    assert_eq!(lines[2], "Msg-A", "Msg-A shifted down");
    assert_eq!(lines[3], "Msg-B", "Msg-B shifted down");
    assert_eq!(lines[4], "Msg-C", "Msg-C shifted down");
    // Msg-D pushed off region bottom
}

#[test]
fn tui_app_scroll_region_change_mid_session() {
    // A TUI app changes its scroll region mid-session (e.g., toggling
    // a bottom panel). Content outside both old and new regions should survive.
    let mut screen = Screen::new(20, 8, 100);

    screen.process(b"\x1b[?1049h");
    screen.process(b"\x1b[1;1HTop Bar");
    screen.process(b"\x1b[8;1HBottom Bar");

    // First scroll region: rows 2-7 (full content area)
    screen.process(b"\x1b[2;7r");
    screen.process(b"\x1b[2;1H");
    for i in 0..6 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("V1_{}", i).as_bytes());
    }

    // Verify initial state
    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Top Bar");
    assert_eq!(lines[7], "Bottom Bar");

    // Change scroll region: now rows 2-4 (smaller content area, panel at rows 5-7)
    screen.process(b"\x1b[2;4r");
    screen.process(b"\x1b[5;1HPanel-A");
    screen.process(b"\x1b[6;1HPanel-B");
    screen.process(b"\x1b[7;1HPanel-C");

    // Scroll within the new smaller region
    screen.process(b"\x1b[2;1H");
    for i in 0..6 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("V2_{}", i).as_bytes());
    }

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Top Bar", "top bar survives region change");
    assert_eq!(lines[7], "Bottom Bar", "bottom bar survives region change");
    // Panel rows (5-7, outside new scroll region) should be intact
    assert_eq!(
        lines[4], "Panel-A",
        "panel row survives scroll in smaller region"
    );
    assert_eq!(
        lines[5], "Panel-B",
        "panel row survives scroll in smaller region"
    );
    assert_eq!(
        lines[6], "Panel-C",
        "panel row survives scroll in smaller region"
    );
}

// ─── Edge-case scroll tests ────────────────────────────────────────────

#[test]
fn scroll_up_count_exceeds_region_size() {
    // CSI 100S on a 3-row region — should blank the entire region without panic.
    let mut screen = Screen::new(10, 6, 100);
    for row in 0..6 {
        screen.process(format!("\x1b[{};1HR{}", row + 1, row).as_bytes());
    }
    // Set 3-row scroll region (rows 2-4, 0-based: 1-3)
    screen.process(b"\x1b[2;4r");
    // Scroll up way more than the region size
    screen.process(b"\x1b[100S");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "R0", "row above region untouched");
    assert_eq!(lines[5], "R5", "row below region untouched");
    // Entire region should be blank
    assert_eq!(lines[1], "", "region blanked");
    assert_eq!(lines[2], "", "region blanked");
    assert_eq!(lines[3], "", "region blanked");
}

#[test]
fn scroll_down_count_exceeds_region_size() {
    // CSI 100T on a 3-row region — should blank the entire region without panic.
    let mut screen = Screen::new(10, 6, 100);
    for row in 0..6 {
        screen.process(format!("\x1b[{};1HR{}", row + 1, row).as_bytes());
    }
    screen.process(b"\x1b[2;4r");
    screen.process(b"\x1b[100T");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "R0", "row above region untouched");
    assert_eq!(lines[5], "R5", "row below region untouched");
    assert_eq!(lines[1], "", "region blanked");
    assert_eq!(lines[2], "", "region blanked");
    assert_eq!(lines[3], "", "region blanked");
}

#[test]
fn lf_at_last_row_outside_scroll_region() {
    // Cursor at the absolute last row, but scroll region ends earlier.
    // LF should do nothing — cursor is stuck.
    let mut screen = Screen::new(10, 6, 100);
    screen.process(b"\x1b[6;1HBottom");

    // Set scroll region to rows 1-4 (0-based: 0-3)
    screen.process(b"\x1b[1;4r");

    // Move cursor to the very last row (below scroll region)
    screen.process(b"\x1b[6;1H");
    assert_eq!(screen.grid.cursor_y(), 5);

    // LF — cursor is at row 5 (last), scroll_bottom is 3. Should not scroll, should not move.
    screen.process(b"\n");
    assert_eq!(
        screen.grid.cursor_y(),
        5,
        "cursor stuck at last row outside region"
    );

    let lines = screen_lines(&screen);
    assert_eq!(lines[5], "Bottom", "content at last row unchanged");
}

#[test]
fn lf_between_scroll_top_and_bottom_just_moves_cursor() {
    // LF when cursor is inside the scroll region but NOT at scroll_bottom
    // should just move cursor down without scrolling.
    let mut screen = Screen::new(10, 6, 100);
    for row in 0..6 {
        screen.process(format!("\x1b[{};1HR{}", row + 1, row).as_bytes());
    }

    screen.process(b"\x1b[2;5r"); // region rows 2-5 (0-based: 1-4)
    screen.process(b"\x1b[3;1H"); // cursor at row 3 (0-based: 2), inside region

    screen.process(b"\n"); // LF

    assert_eq!(screen.grid.cursor_y(), 3, "cursor moved down by 1");
    // No scrolling — all content intact
    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "R0");
    assert_eq!(lines[1], "R1");
    assert_eq!(lines[2], "R2");
    assert_eq!(lines[3], "R3");
    assert_eq!(lines[4], "R4");
    assert_eq!(lines[5], "R5");
}

#[test]
fn autowrap_at_scroll_bottom_triggers_scroll() {
    // When the cursor is at (scroll_bottom, last_col) with autowrap on,
    // the next character triggers wrap which triggers scroll.
    let mut screen = Screen::new(4, 4, 100);
    screen.process(b"AAA0\r\nBBB1\r\nCCC2\r\nDDD3");

    // "DDD3" is 4 chars in 4-col terminal → cursor at col 3 with wrap_pending
    assert!(
        screen.grid.wrap_pending(),
        "wrap_pending after filling last cell"
    );

    // Print one more character — triggers deferred wrap → scroll.
    screen.process(b"X");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "BBB1", "scroll happened: AAA0 gone");
    assert_eq!(lines[1], "CCC2");
    assert_eq!(lines[2], "DDD3");
    assert_eq!(lines[3], "X", "new char on fresh line");
}

#[test]
fn autowrap_at_scroll_region_bottom_triggers_region_scroll() {
    // Same as above but within a scroll region.
    let mut screen = Screen::new(5, 6, 100);

    screen.process(b"\x1b[1;1HHead");
    screen.process(b"\x1b[6;1HFoot");

    // Set scroll region to rows 2-5 (0-based: 1-4)
    screen.process(b"\x1b[2;5r");

    // Fill the entire region row by row to the last column
    screen.process(b"\x1b[2;1HAAAAA"); // row 2 (all 5 cols filled)
    screen.process(b"\x1b[3;1HBBBBB"); // row 3
    screen.process(b"\x1b[4;1HCCCCC"); // row 4
    screen.process(b"\x1b[5;1HDDDDD"); // row 5 (scroll_bottom)

    // Cursor is at the end of row 5, wrap_pending is set.
    // Print a char — should trigger scroll within region.
    screen.process(b"Z");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Head", "header survives autowrap scroll");
    assert_eq!(lines[5], "Foot", "footer survives autowrap scroll");
    assert_eq!(
        lines[1], "BBBBB",
        "AAAAA scrolled off, BBBBB now at region top"
    );
    assert_eq!(lines[4], "Z", "Z on new line at region bottom");
}

#[test]
fn wide_char_wrap_at_scroll_bottom_triggers_scroll() {
    // A wide character (2 cells) that doesn't fit at the end of scroll_bottom
    // should trigger wrap + scroll.
    let mut screen = Screen::new(5, 3, 100);
    screen.process(b"Row0\r\nRow1\r\n");
    // Cursor at row 2, col 0. Fill to col 4 (last col)
    screen.process(b"ABCD");
    // Cursor at col 4 (0-based), which is the last column.
    assert_eq!(screen.grid.cursor_x(), 4);

    // Print a wide char — it needs 2 cells but only 1 available.
    // Should: fill col 4 with blank, wrap to next line (triggers scroll), then print wide char.
    screen.process("".as_bytes());

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Row1", "Row0 scrolled off");
    assert_eq!(lines[1], "ABCD", "original row with blank at col 4");
    // Wide char is on the new line
    assert_eq!(
        screen.grid.visible_row(2)[0].c,
        '',
        "wide char on scrolled-in line"
    );
    assert_eq!(screen.grid.visible_row(2)[0].width, 2);
}

#[test]
fn csi_r_reset_restores_full_screen_scroll() {
    // CSI r (no params) should reset scroll region to full screen.
    let mut screen = Screen::new(10, 6, 100);

    // Set partial region
    screen.process(b"\x1b[2;5r");
    assert_eq!(screen.grid.scroll_top(), 1);
    assert_eq!(screen.grid.scroll_bottom(), 4);

    // Reset with CSI r (no params)
    screen.process(b"\x1b[r");
    assert_eq!(screen.grid.scroll_top(), 0, "scroll_top reset to 0");
    assert_eq!(
        screen.grid.scroll_bottom(),
        5,
        "scroll_bottom reset to rows-1"
    );
}

#[test]
fn scroll_single_row_region() {
    // CSI n;nr where top == bottom — single-row scroll region is valid per spec.
    let mut screen = Screen::new(10, 6, 100);

    screen.process(b"\x1b[3;3r"); // top == bottom (row 3, 0-based: 2)

    // Region should be set to single row
    assert_eq!(screen.grid.scroll_top(), 2, "single-row region applied");
    assert_eq!(screen.grid.scroll_bottom(), 2, "single-row region applied");
    // Cursor resets to home
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.cursor_y(), 0);
}

#[test]
fn scroll_region_reversed_params_ignored() {
    // CSI 15;5r (top > bottom after conversion) — should NOT change region.
    let mut screen = Screen::new(10, 20, 100);
    let old_top = screen.grid.scroll_top();
    let old_bottom = screen.grid.scroll_bottom();

    screen.process(b"\x1b[15;5r"); // top 14 > bottom 4

    assert_eq!(screen.grid.scroll_top(), old_top);
    assert_eq!(screen.grid.scroll_bottom(), old_bottom);
}

#[test]
fn scrollback_limit_enforced_during_scroll() {
    // Scrollback should never grow beyond the configured limit.
    let limit = 5;
    let mut screen = Screen::new(10, 3, limit);

    // Generate more scrollback than the limit
    for i in 0..20 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("L{:02}", i).as_bytes());
    }

    let hist = history_texts(&screen);
    assert_eq!(
        hist.len(),
        limit,
        "scrollback should be exactly at limit {}, got {}",
        limit,
        hist.len()
    );
    // The oldest lines should have been evicted
    assert_eq!(hist[0], "L12", "oldest scrollback should be evicted");
}

#[test]
fn csi_s_does_not_move_cursor() {
    // CSI S should scroll content but NOT change cursor position.
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"\x1b[3;5H"); // cursor at row 3, col 5 (0-based: 2, 4)
    assert_eq!(screen.grid.cursor_y(), 2);
    assert_eq!(screen.grid.cursor_x(), 4);

    screen.process(b"\x1b[2S"); // scroll up 2

    assert_eq!(screen.grid.cursor_y(), 2, "CSI S must not change cursor_y");
    assert_eq!(screen.grid.cursor_x(), 4, "CSI S must not change cursor_x");
}

#[test]
fn csi_t_does_not_move_cursor() {
    // CSI T should scroll content but NOT change cursor position.
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"\x1b[3;5H");
    assert_eq!(screen.grid.cursor_y(), 2);
    assert_eq!(screen.grid.cursor_x(), 4);

    screen.process(b"\x1b[2T"); // scroll down 2

    assert_eq!(screen.grid.cursor_y(), 2, "CSI T must not change cursor_y");
    assert_eq!(screen.grid.cursor_x(), 4, "CSI T must not change cursor_x");
}

// ─── Scroll + content update tests (main screen) ───────────────────────
// Scenarios where an app scrolls and immediately overwrites content
// on the main screen (not alt screen): build logs, streaming output,
// status monitors, progress bars, etc.

#[test]
fn scroll_then_overwrite_last_line() {
    // Build output pattern: scroll up, then write new content on the bottom line.
    // Like `make` printing compiler output line by line.
    let mut screen = Screen::new(20, 4, 100);
    screen.process(b"compile a.c\r\n");
    screen.process(b"compile b.c\r\n");
    screen.process(b"compile c.c\r\n");
    screen.process(b"compile d.c");
    // Screen full: [a.c, b.c, c.c, d.c]

    // Next line scrolls + writes
    screen.process(b"\r\ncompile e.c");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "compile b.c");
    assert_eq!(lines[1], "compile c.c");
    assert_eq!(lines[2], "compile d.c");
    assert_eq!(lines[3], "compile e.c");

    // a.c should be in scrollback
    let hist = history_texts(&screen);
    assert_eq!(hist.len(), 1);
    assert_eq!(hist[0], "compile a.c");
}

#[test]
fn scroll_then_cup_overwrite_middle() {
    // App scrolls content, then uses CUP to jump back and overwrite a
    // middle row (e.g., updating a progress bar or status line on main screen).
    let mut screen = Screen::new(20, 5, 100);
    for i in 0..5 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Line{}", i).as_bytes());
    }
    // Screen: [Line0, Line1, Line2, Line3, Line4]

    // Scroll by 2
    screen.process(b"\r\nLine5\r\nLine6");
    // Screen: [Line2, Line3, Line4, Line5, Line6]

    // Jump to row 1 and overwrite with a progress bar
    screen.process(b"\x1b[1;1H");
    screen.process(b"[=====>    ] 50%");

    let lines = screen_lines(&screen);
    assert_eq!(
        lines[0], "[=====>    ] 50%",
        "row 0 overwritten after scroll"
    );
    assert_eq!(lines[1], "Line3", "row 1 unchanged");
    assert_eq!(lines[2], "Line4");
    assert_eq!(lines[3], "Line5");
    assert_eq!(lines[4], "Line6");

    // Scrollback should have Line0 and Line1
    let hist = history_texts(&screen);
    assert_eq!(hist.len(), 2);
    assert_eq!(hist[0], "Line0");
    assert_eq!(hist[1], "Line1");
}

#[test]
fn continuous_scroll_with_bottom_status_update() {
    // Pattern: streaming log on main screen, with a status line at the bottom
    // updated via CUP after each scroll. Like a download progress during install.
    let mut screen = Screen::new(30, 5, 100);

    // Set scroll region: rows 1-4, row 5 is the status line
    screen.process(b"\x1b[1;4r");
    screen.process(b"\x1b[5;1HProgress: 0%");

    // Stream log lines in the scroll region
    screen.process(b"\x1b[1;1H");
    for i in 0..10 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Installing pkg-{:02}...", i).as_bytes());

        // After each log line, update progress on row 5
        let pct = (i + 1) * 10;
        screen.process(format!("\x1b7\x1b[5;1H\x1b[2KProgress: {}%\x1b8", pct).as_bytes());
    }

    let lines = screen_lines(&screen);
    // Status line should show final progress
    assert_eq!(lines[4], "Progress: 100%", "status line updated");
    // Last 4 log lines visible in the content area
    assert_eq!(lines[0], "Installing pkg-06...");
    assert_eq!(lines[1], "Installing pkg-07...");
    assert_eq!(lines[2], "Installing pkg-08...");
    assert_eq!(lines[3], "Installing pkg-09...");
}

#[test]
fn scroll_with_erase_and_rewrite() {
    // Pattern: app scrolls, erases part of a line, rewrites it.
    // Like a compiler that shows "compiling..." then replaces with "done".
    let mut screen = Screen::new(20, 3, 100);
    screen.process(b"Step 1: done\r\n");
    screen.process(b"Step 2: done\r\n");
    screen.process(b"Step 3: running...");
    // Screen: [Step 1, Step 2, Step 3: running...]

    // Scroll + new line
    screen.process(b"\r\nStep 4: running...");
    // Screen: [Step 2, Step 3: running..., Step 4: running...]

    // Go back to Step 3's row (now row 1) and replace "running..." with "done"
    screen.process(b"\x1b[2;9H"); // row 2, col 9 (after "Step 3: ")
    screen.process(b"\x1b[0K"); // erase to end of line
    screen.process(b"done");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Step 2: done");
    assert_eq!(lines[1], "Step 3: done", "rewritten after scroll");
    assert_eq!(lines[2], "Step 4: running...");
}

#[test]
fn scroll_region_scroll_then_overwrite_fixed_rows() {
    // App with header/footer on main screen (no alt screen).
    // Content scrolls in a region; header and footer get updated independently.
    let mut screen = Screen::new(25, 6, 100);

    screen.process(b"\x1b[1;1HTitle: My App v1.0");
    screen.process(b"\x1b[6;1HItems: 0");

    // Scroll region for content area
    screen.process(b"\x1b[2;5r");
    screen.process(b"\x1b[2;1H");

    // Add items, scrolling the content area
    for i in 0..8 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Item #{}", i + 1).as_bytes());

        // Update footer count after each item
        screen.process(format!("\x1b7\x1b[6;1H\x1b[2KItems: {}\x1b8", i + 1).as_bytes());
    }

    // Update the header too
    screen.process(b"\x1b7\x1b[1;1H\x1b[2KTitle: My App v2.0\x1b8");

    let lines = screen_lines(&screen);
    assert_eq!(
        lines[0], "Title: My App v2.0",
        "header updated after scrolling"
    );
    assert_eq!(lines[5], "Items: 8", "footer updated with count");
    // Content area: last 4 items
    assert_eq!(lines[1], "Item #5");
    assert_eq!(lines[2], "Item #6");
    assert_eq!(lines[3], "Item #7");
    assert_eq!(lines[4], "Item #8");
}

#[test]
fn scroll_then_overwrite_scrolled_line_content_integrity() {
    // Verify that after scroll, overwriting a line doesn't corrupt adjacent lines.
    let mut screen = Screen::new(10, 5, 100);
    for i in 0..8 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("L{:02}", i).as_bytes());
    }
    // Visible: [L03, L04, L05, L06, L07]

    // Overwrite the middle line (row 2)
    screen.process(b"\x1b[3;1H\x1b[2K");
    screen.process(b"REPLACED");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "L03", "line above overwrite unchanged");
    assert_eq!(lines[1], "L04", "line above overwrite unchanged");
    assert_eq!(lines[2], "REPLACED", "middle line replaced");
    assert_eq!(lines[3], "L06", "line below overwrite unchanged");
    assert_eq!(lines[4], "L07", "line below overwrite unchanged");

    // Scrollback integrity
    let hist = history_texts(&screen);
    assert_eq!(hist.len(), 3);
    assert_eq!(hist[0], "L00");
    assert_eq!(hist[1], "L01");
    assert_eq!(hist[2], "L02");
}

#[test]
fn interleaved_scroll_and_cup_writes() {
    // Rapid interleaving: scroll one line, CUP to write somewhere, scroll again.
    // Simulates an app that mixes streaming output with in-place updates.
    let mut screen = Screen::new(15, 4, 100);

    // Initial content
    screen.process(b"A\r\nB\r\nC\r\nD");
    // [A, B, C, D]

    // Scroll, write at row 0
    screen.process(b"\r\nE");
    // [B, C, D, E]
    screen.process(b"\x1b[1;1H\x1b[2KHeader");
    // [Header, C, D, E]

    // Scroll again
    screen.process(b"\x1b[4;1H"); // go to bottom
    screen.process(b"\r\nF");
    // [C, D, E, F]  — "Header" was on old row 0, now scrolled off

    // Overwrite row 0 again
    screen.process(b"\x1b[1;1H\x1b[2KNewHdr");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "NewHdr");
    assert_eq!(lines[1], "D");
    assert_eq!(lines[2], "E");
    assert_eq!(lines[3], "F");

    // Scrollback should contain A, B, Header (in that order? or B, Header?)
    // A scrolled off first (when E was added), then B scrolled off (when F was added).
    // Wait — let me trace more carefully:
    // Initial: [A, B, C, D]
    // "\r\nE" → scroll: A to scrollback, [B, C, D, E]
    // CUP + write: [Header, C, D, E] (no scroll)
    // CUP to row 3, "\r\nF" → scroll: Header to scrollback, [C, D, E, F]
    // CUP + write: [NewHdr, D, E, F] (no scroll)
    let hist = history_texts(&screen);
    assert_eq!(hist.len(), 2);
    assert_eq!(hist[0], "A", "first scrolled-off line");
    assert_eq!(hist[1], "Header", "overwritten row scrolled off");
}

#[test]
fn scroll_and_partial_line_overwrite() {
    // App scrolls then overwrites only part of a line (not the whole line).
    // The rest of the line should keep its old content.
    let mut screen = Screen::new(20, 3, 100);
    screen.process(b"AAAAAAAAAAAAAAAAAAAA\r\n"); // 20 A's
    screen.process(b"BBBBBBBBBBBBBBBBBBBB\r\n"); // 20 B's
    screen.process(b"CCCCCCCCCCCCCCCCCCCC"); // 20 C's

    // Scroll
    screen.process(b"\r\nDDDDDDDDDDDDDDDDDDDD");
    // [BBB..., CCC..., DDD...]

    // Overwrite just the first 3 chars of row 0
    screen.process(b"\x1b[1;1H");
    screen.process(b"XYZ");

    let lines = screen_lines(&screen);
    assert_eq!(
        lines[0], "XYZBBBBBBBBBBBBBBBBB",
        "partial overwrite: first 3 replaced, rest intact"
    );
    assert_eq!(lines[1], "CCCCCCCCCCCCCCCCCCCC", "row 1 untouched");
    assert_eq!(lines[2], "DDDDDDDDDDDDDDDDDDDD", "row 2 untouched");
}

// ─── Risky scroll edge cases ───────────────────────────────────────────

#[test]
fn ind_esc_d_at_scroll_bottom_scrolls() {
    // ESC D (IND — Index) should move cursor down, scrolling if at scroll_bottom.
    // This is the counterpart of ESC M (RI). Some apps use ESC D explicitly.
    let mut screen = Screen::new(10, 4, 100);
    screen.process(b"Row0\r\nRow1\r\nRow2\r\nRow3");

    // Cursor is at row 3 (scroll_bottom). ESC D should scroll up.
    screen.process(b"\x1bD");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Row1", "ESC D at bottom should scroll: Row0 gone");
    assert_eq!(lines[1], "Row2");
    assert_eq!(lines[2], "Row3");
    assert_eq!(lines[3], "", "new blank line at bottom after IND scroll");
}

#[test]
fn ind_esc_d_mid_screen_just_moves_cursor() {
    // ESC D not at scroll_bottom should just move cursor down.
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"\x1b[2;1H"); // row 2 (0-based: 1)
    screen.process(b"\x1bD");

    assert_eq!(
        screen.grid.cursor_y(),
        2,
        "ESC D should move cursor down by 1"
    );
}

#[test]
fn save_cursor_scroll_restore_cursor_writes_at_shifted_content() {
    // Save cursor → scroll → restore cursor → print.
    // Cursor returns to the saved (row, col), but the content there has shifted.
    let mut screen = Screen::new(10, 4, 100);
    screen.process(b"Row0\r\nRow1\r\nRow2\r\nRow3");

    // Save cursor at row 1, col 5
    screen.process(b"\x1b[2;6H"); // row 2, col 6 (0-based: 1, 5)
    screen.process(b"\x1b7"); // DECSC save

    // Scroll by 2
    screen.process(b"\x1b[2S");
    // Screen now: [Row2, Row3, "", ""]

    // Restore cursor — should go back to (1, 5)
    screen.process(b"\x1b8");
    assert_eq!(screen.grid.cursor_y(), 1, "restored cursor_y");
    assert_eq!(screen.grid.cursor_x(), 5, "restored cursor_x");

    // Print at restored position — overwrites whatever is at row 1 col 5
    // (Row3 is now at row 1)
    screen.process(b"!");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "Row2", "row 0 after scroll");
    assert_eq!(
        lines[1], "Row3 !",
        "cursor writes at restored position in shifted content"
    );
}

#[test]
fn erase_display_ignores_scroll_region() {
    // CSI 2J should erase the ENTIRE display, not just the scroll region.
    let mut screen = Screen::new(10, 6, 100);
    for row in 0..6 {
        screen.process(format!("\x1b[{};1HR{}", row + 1, row).as_bytes());
    }

    // Set scroll region to rows 2-5
    screen.process(b"\x1b[2;5r");

    // Erase entire display
    screen.process(b"\x1b[2J");

    let lines = screen_lines(&screen);
    for (i, line) in lines.iter().enumerate() {
        assert_eq!(
            line, &"",
            "row {} should be erased by CSI 2J (regardless of scroll region)",
            i
        );
    }
}

#[test]
fn erase_display_0_from_cursor_ignores_scroll_region() {
    // CSI 0J (erase from cursor to end) should erase to screen end, not region end.
    let mut screen = Screen::new(10, 6, 100);
    for row in 0..6 {
        screen.process(format!("\x1b[{};1HR{}", row + 1, row).as_bytes());
    }

    // Set scroll region rows 2-4
    screen.process(b"\x1b[2;4r");

    // Put cursor at row 3 (inside region)
    screen.process(b"\x1b[3;1H");

    // CSI 0J — erase from cursor to END OF SCREEN (not end of region)
    screen.process(b"\x1b[0J");

    let lines = screen_lines(&screen);
    assert_eq!(lines[0], "R0", "row above cursor preserved");
    assert_eq!(lines[1], "R1", "row above cursor preserved");
    assert_eq!(lines[2], "", "cursor row erased");
    assert_eq!(lines[3], "", "row below cursor erased");
    assert_eq!(lines[4], "", "row below region erased (ED ignores region)");
    assert_eq!(lines[5], "", "last row erased (ED ignores region)");
}

#[test]
fn reattach_render_after_scroll_and_cup_overwrite() {
    // After scroll + CUP overwrite on main screen, a reattach render should
    // show the correct current screen state.
    let mut screen = Screen::new(15, 4, 100);
    for i in 0..7 {
        if i > 0 {
            screen.process(b"\r\n");
        }
        screen.process(format!("Line{}", i).as_bytes());
    }
    // Visible: [Line3, Line4, Line5, Line6]
    // Scrollback: [Line0, Line1, Line2]

    // Overwrite row 1 via CUP
    screen.process(b"\x1b[2;1H\x1b[2KModified");
    // Visible: [Line3, Modified, Line5, Line6]

    // Render for reattach
    let mut cache = render::AnsiRenderer::new();
    let output = cache.render(&screen, true);
    let rendered = String::from_utf8_lossy(&output);

    assert!(rendered.contains("Line3"), "reattach should show Line3");
    assert!(
        rendered.contains("Modified"),
        "reattach should show Modified (not Line4)"
    );
    assert!(rendered.contains("Line5"), "reattach should show Line5");
    assert!(rendered.contains("Line6"), "reattach should show Line6");
    assert!(
        !rendered.contains("Line4"),
        "Line4 was overwritten, should not appear"
    );
}

#[test]
fn scrollback_history_after_scroll_and_cup_overwrite() {
    // If we overwrite a line via CUP and THEN it scrolls off,
    // scrollback should contain the MODIFIED version.
    let mut screen = Screen::new(15, 3, 100);
    screen.process(b"Original\r\nRow1\r\nRow2");
    // Screen: [Original, Row1, Row2]

    // Overwrite row 0
    screen.process(b"\x1b[1;1H\x1b[2KChanged");
    // Screen: [Changed, Row1, Row2]

    // Scroll to push "Changed" into scrollback
    screen.process(b"\x1b[3;1H\r\nRow3");
    // Screen: [Row1, Row2, Row3], scrollback: [Changed]

    let hist = history_texts(&screen);
    assert_eq!(hist.len(), 1);
    assert_eq!(
        hist[0], "Changed",
        "scrollback should have the modified content, not 'Original'"
    );
}

#[test]
fn scroll_region_lf_cursor_outside_region_between_bottom_and_last_row() {
    // Cursor below scroll_bottom but not at last row.
    // LF should just move cursor down (no scroll).
    let mut screen = Screen::new(10, 8, 100);
    for row in 0..8 {
        screen.process(format!("\x1b[{};1HR{}", row + 1, row).as_bytes());
    }

    // Scroll region rows 1-4 (0-based: 0-3)
    screen.process(b"\x1b[1;4r");

    // Put cursor at row 6 (0-based: 5), between scroll_bottom(3) and last row(7)
    screen.process(b"\x1b[6;1H");
    assert_eq!(screen.grid.cursor_y(), 5);

    screen.process(b"\n"); // LF

    assert_eq!(screen.grid.cursor_y(), 6, "cursor moves down, no scroll");
    // ALL content should be unchanged
    let lines = screen_lines(&screen);
    for row in 0..8 {
        assert_eq!(lines[row], format!("R{}", row), "row {} unchanged", row);
    }
}

// ─── Edge case tests ─────────────────────────────────────────────────────────

#[test]
fn combining_mark_at_column_zero_no_previous_cell() {
    // A combining mark at column 0 with no previous cell should be silently ignored
    let mut screen = Screen::new(10, 3, 100);
    screen.process("\u{0301}".as_bytes()); // combining acute accent
                                           // Should not crash, cursor should stay at 0
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(0).combining_len(0), 0);
}

#[test]
fn multiple_combining_marks_on_single_cell() {
    let mut screen = Screen::new(80, 3, 100);
    // e + combining acute + combining diaeresis
    screen.process("e\u{0301}\u{0308}".as_bytes());
    assert_eq!(screen.grid.visible_row(0)[0].c, 'e');
    assert_eq!(screen.grid.visible_row(0).combining_len(0), 2);
    assert_eq!(screen.grid.visible_row(0).combining(0)[0], '\u{0301}');
    assert_eq!(screen.grid.visible_row(0).combining(0)[1], '\u{0308}');
}

#[test]
fn wide_char_exactly_fills_line() {
    // Wide char at cols-2 should fit without wrapping
    let mut screen = Screen::new(4, 3, 100);
    screen.process(b"AB"); // cursor at col 2
    screen.process("".as_bytes()); // width 2, needs cols 2-3 → fits exactly
    assert_eq!(screen.grid.visible_row(0)[2].c, '');
    assert_eq!(screen.grid.visible_row(0)[2].width, 2);
    assert_eq!(screen.grid.visible_row(0)[3].width, 0);
    assert_eq!(screen.grid.cursor_y(), 0, "should NOT have wrapped");
    assert!(
        screen.grid.wrap_pending(),
        "wrap should be pending after filling line"
    );
}

#[test]
fn wide_char_on_2_column_terminal() {
    let mut screen = Screen::new(2, 3, 100);
    screen.process("".as_bytes());
    assert_eq!(screen.grid.visible_row(0)[0].c, '');
    assert_eq!(screen.grid.visible_row(0)[0].width, 2);
    assert_eq!(screen.grid.visible_row(0)[1].width, 0);
    assert_eq!(screen.grid.cursor_y(), 0);
    assert!(screen.grid.wrap_pending());
}

#[test]
fn wide_char_on_1_column_terminal() {
    // A 1-column terminal cannot display a width-2 char — it should be dropped.
    let mut screen = Screen::new(1, 3, 100);
    screen.process("".as_bytes());
    // Wide char dropped: cursor stays at row 0, cell stays blank
    assert_eq!(
        screen.grid.cursor_y(),
        0,
        "wide char should be dropped on 1-col terminal"
    );
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(
        screen.grid.visible_row(0)[0].c,
        ' ',
        "cell should remain blank"
    );
}

#[test]
fn wide_char_no_autowrap_at_last_col() {
    // With autowrap off, wide char that doesn't fit at end is simply dropped
    let mut screen = Screen::new(5, 3, 100);
    screen.process(b"\x1b[?7l"); // disable autowrap
    screen.process(b"ABCD"); // cursor at col 4, 'D' at col 3
    screen.process("".as_bytes()); // width 2, only 1 col left, autowrap off → dropped
                                     // 'D' is at col 3, col 4 is still blank (wide char was dropped)
    assert_eq!(screen.grid.visible_row(0)[3].c, 'D');
    assert_eq!(
        screen.grid.visible_row(0)[4].c,
        ' ',
        "wide char dropped, col 4 stays blank"
    );
    assert_eq!(screen.grid.cursor_y(), 0, "no wrap");
}

#[test]
fn rep_with_no_prior_print() {
    // CSI b with default last_printed_char (' ') should repeat spaces
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"\x1b[3b"); // repeat last char 3 times
                                // Default last_printed_char is ' ', so 3 spaces (no visible change)
    assert_eq!(screen.grid.cursor_x(), 3);
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(0)[1].c, ' ');
    assert_eq!(screen.grid.visible_row(0)[2].c, ' ');
}

#[test]
fn restore_cursor_with_no_saved_state() {
    // ESC 8 (restore cursor) with no prior save should be a no-op
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;10H"); // move cursor
    screen.process(b"\x1b8"); // restore (no save done)
                              // Cursor should remain unchanged
    assert_eq!(screen.grid.cursor_y(), 4);
    assert_eq!(screen.grid.cursor_x(), 9);
}

#[test]
fn restore_cursor_csi_u_with_no_saved_state() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[3;5H");
    screen.process(b"\x1b[u"); // CSI u restore with no prior CSI s
    assert_eq!(screen.grid.cursor_y(), 2);
    assert_eq!(screen.grid.cursor_x(), 4);
}

#[test]
fn save_cursor_resize_then_restore_clamps() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[20;70H"); // cursor at row 20, col 70
    screen.process(b"\x1b7"); // save cursor
    screen.resize(40, 10); // shrink
    screen.process(b"\x1b8"); // restore cursor (should clamp)
    assert_eq!(
        screen.grid.cursor_x(),
        39,
        "restored x should clamp to cols-1"
    );
    assert_eq!(
        screen.grid.cursor_y(),
        9,
        "restored y should clamp to rows-1"
    );
}

#[test]
fn double_enter_alt_screen() {
    // Entering alt screen when already in alt screen should be ignored,
    // preserving the original main screen in saved_grid.
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"Main");
    screen.process(b"\x1b[?1049h"); // enter alt (saves "Main")
    assert!(screen.in_alt_screen());
    screen.process(b"Alt1");
    screen.process(b"\x1b[?1049h"); // enter alt again — ignored
    assert!(screen.in_alt_screen());
    // Alt1 content should still be on screen (second enter was ignored, no clear)
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');
    screen.process(b"\x1b[?1049l"); // exit restores original main screen
    assert!(!screen.in_alt_screen());
    assert_eq!(screen.grid.visible_row(0)[0].c, 'M');
    assert_eq!(screen.grid.visible_row(0)[3].c, 'n');
}

#[test]
fn exit_alt_screen_when_not_in_alt() {
    // Exiting alt screen when not in alt should be a no-op:
    // no scroll region reset, no cursor restore, no grid change.
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"Hello");
    // Set a custom scroll region and move cursor
    screen.process(b"\x1b[2;4r");
    screen.process(b"\x1b[3;5H"); // row 3, col 5
    let sr_top = screen.grid.scroll_top();
    let sr_bot = screen.grid.scroll_bottom();
    let cx = screen.grid.cursor_x();
    let cy = screen.grid.cursor_y();
    // Exit alt without entering — should be completely ignored
    screen.process(b"\x1b[?1049l");
    assert!(!screen.in_alt_screen());
    assert_eq!(
        screen.grid.scroll_top(),
        sr_top,
        "scroll region top must not change"
    );
    assert_eq!(
        screen.grid.scroll_bottom(),
        sr_bot,
        "scroll region bottom must not change"
    );
    assert_eq!(screen.grid.cursor_x(), cx, "cursor x must not change");
    assert_eq!(screen.grid.cursor_y(), cy, "cursor y must not change");
}

#[test]
fn hts_sets_tab_stop() {
    let mut screen = Screen::new(80, 3, 100);
    screen.process(b"\x1b[1;5H"); // move to col 5
    screen.process(b"\x1bH"); // HTS — set tab stop at col 4
    screen.process(b"\x1b[1;1H"); // move home
    screen.process(b"\t"); // tab should stop at col 4 (our custom stop)
    assert_eq!(screen.grid.cursor_x(), 4);
}

#[test]
fn tbc_clear_current_tab_stop() {
    let mut screen = Screen::new(80, 3, 100);
    // Default tab stop at col 8
    screen.process(b"\x1b[1;9H"); // move to col 9 (0-based: col 8)
    screen.process(b"\x1b[0g"); // TBC 0 — clear tab stop at current col (8)
    screen.process(b"\x1b[1;1H"); // move home
    screen.process(b"\t"); // tab should skip col 8, go to col 16
    assert_eq!(screen.grid.cursor_x(), 16);
}

#[test]
fn tbc_clear_all_tab_stops() {
    let mut screen = Screen::new(80, 3, 100);
    screen.process(b"\x1b[3g"); // TBC 3 — clear all tab stops
    screen.process(b"\t"); // no tab stops → clamp to right margin
    assert_eq!(screen.grid.cursor_x(), 79);
}

#[test]
fn scroll_region_top_equals_bottom_accepted() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;5r"); // top == bottom → single-row region is valid
    assert_eq!(screen.grid.scroll_top(), 4);
    assert_eq!(screen.grid.scroll_bottom(), 4);
}

#[test]
fn scroll_region_reversed_params_rejected() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[15;5r"); // top > bottom → should be ignored
    assert_eq!(screen.grid.scroll_top(), 0);
    assert_eq!(screen.grid.scroll_bottom(), 23);
}

#[test]
fn ech_count_exceeds_remaining_columns() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ");
    screen.process(b"\x1b[1;6H"); // col 6 (0-based: 5)
    screen.process(b"\x1b[100X"); // ECH 100 — should clamp
                                  // Cells 5-9 should be erased, cells 0-4 intact
    for i in 0..5 {
        assert_ne!(screen.grid.visible_row(0)[i].c, ' ');
    }
    for i in 5..10 {
        assert_eq!(
            screen.grid.visible_row(0)[i].c,
            ' ',
            "col {} should be erased",
            i
        );
    }
}

#[test]
fn dch_at_end_of_line() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ");
    screen.process(b"\x1b[1;10H"); // last column (0-based: 9)
    screen.process(b"\x1b[P"); // DCH 1 at end
                               // Last cell should be blank, rest intact
    assert_eq!(screen.grid.visible_row(0)[8].c, 'I');
    assert_eq!(screen.grid.visible_row(0)[9].c, ' ');
}

#[test]
fn dch_count_exceeds_remaining_columns() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ");
    screen.process(b"\x1b[1;6H"); // col 6 (0-based: 5)
    screen.process(b"\x1b[100P"); // DCH 100 — should clamp
                                  // Cols 5-9 should be blank, 0-4 intact
    for (i, ch) in "ABCDE".chars().enumerate() {
        assert_eq!(screen.grid.visible_row(0)[i].c, ch);
    }
    for i in 5..10 {
        assert_eq!(
            screen.grid.visible_row(0)[i].c,
            ' ',
            "col {} should be blank after large DCH",
            i
        );
    }
}

#[test]
fn ich_count_exceeds_remaining_columns() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ");
    screen.process(b"\x1b[1;1H"); // col 1 (0-based: 0)
    screen.process(b"\x1b[100@"); // ICH 100 — should clamp
                                  // All cells should be blank (original content pushed off)
    for i in 0..10 {
        assert_eq!(
            screen.grid.visible_row(0)[i].c,
            ' ',
            "col {} should be blank after large ICH",
            i
        );
    }
}

#[test]
fn ind_esc_d_within_scroll_region_nonzero_top() {
    // ESC D (IND) when cursor is at scroll_bottom of a non-full-screen region
    let mut screen = Screen::new(10, 6, 100);
    for row in 0..6 {
        screen.process(format!("\x1b[{};1HR{}", row + 1, row).as_bytes());
    }
    // Set scroll region rows 2-4 (0-based: 1-3)
    screen.process(b"\x1b[2;4r");
    // Move cursor to scroll_bottom (row 4, 0-based: 3)
    screen.process(b"\x1b[4;1H");
    assert_eq!(screen.grid.cursor_y(), 3);
    // IND should scroll within region only
    screen.process(b"\x1bD");
    // Row 0 (outside region) should be unchanged
    assert_eq!(screen.grid.visible_row(0)[0].c, 'R');
    assert_eq!(screen.grid.visible_row(0)[1].c, '0');
    // Row 5 (outside region) should be unchanged
    assert_eq!(screen.grid.visible_row(5)[0].c, 'R');
    assert_eq!(screen.grid.visible_row(5)[1].c, '5');
    // Within region, rows should have shifted up
    // Row 1 was R1, now should be R2 (shifted up)
    assert_eq!(screen.grid.visible_row(1)[1].c, '2');
}

#[test]
fn ed_0_cursor_on_wide_char_continuation() {
    // Erase from cursor when cursor is on the continuation cell of a wide char
    let mut screen = Screen::new(10, 3, 100);
    screen.process("AB你CD".as_bytes());
    // 你 is at cols 2-3, cursor is at col 6
    // Move cursor to col 3 (continuation of 你)
    screen.process(b"\x1b[1;4H"); // 0-based: col 3
    screen.process(b"\x1b[J"); // ED 0 — erase from cursor
                               // The first half of 你 should also be blanked (fixup_wide_char)
    assert_eq!(
        screen.grid.visible_row(0)[2].c,
        ' ',
        "first half of wide char should be blanked"
    );
    assert_eq!(
        screen.grid.visible_row(0)[3].c,
        ' ',
        "continuation cell should be blanked"
    );
}

#[test]
fn el_1_cursor_on_wide_char_continuation() {
    // Erase to cursor when cursor is on continuation cell of a wide char
    let mut screen = Screen::new(10, 3, 100);
    screen.process("你BCDE".as_bytes());
    // 你 is at cols 0-1
    screen.process(b"\x1b[1;2H"); // 0-based: col 1 (continuation of 你)
    screen.process(b"\x1b[1K"); // EL 1 — erase to cursor
                                // Both halves of 你 should be erased
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(0)[1].c, ' ');
    // B at col 2 should be intact
    assert_eq!(screen.grid.visible_row(0)[2].c, 'B');
}

#[test]
fn ris_clears_scrollback() {
    // ESC c (full reset) should clear scrollback, matching xterm/kitty/iTerm2 behaviour
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"A\r\nB\r\nC\r\nD\r\nE");
    let _ = screen.take_pending_scrollback();
    let hist_before = screen.get_history().len();
    assert!(hist_before > 0);
    screen.process(b"\x1bc"); // RIS
    assert_eq!(
        screen.get_history().len(),
        0,
        "ESC c should clear scrollback history"
    );
    assert_eq!(screen.grid.scrollback_len(), 0);
    assert_eq!(screen.grid.pending_start(), 0);
}

#[test]
fn ris_forwards_clear_scrollback_passthrough() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"A\r\nB\r\nC\r\nD\r\nE");
    let _ = screen.take_passthrough(); // drain
    screen.process(b"\x1bc"); // RIS
    let pt = screen.take_passthrough();
    assert_eq!(pt.len(), 1, "RIS should produce one passthrough entry");
    assert_eq!(pt[0], b"\x1b[3J", "RIS should forward \\e[3J, not \\ec");
}

#[test]
fn ris_during_alt_screen_restores_scrollback_limit() {
    // RIS during alt screen must restore scrollback_limit from the saved grid.
    // Without the fix, scrollback_limit would stay 0 permanently.
    let mut screen = Screen::new(10, 3, 100);
    // Generate some scrollback to confirm it works before alt screen
    screen.process(b"A\r\nB\r\nC\r\nD\r\nE");
    let _ = screen.take_pending_scrollback();
    assert!(
        screen.grid.scrollback_len() > 0,
        "should have scrollback before alt screen"
    );

    // Enter alt screen (sets scrollback_limit to 0)
    screen.process(b"\x1b[?1049h");
    assert_eq!(
        screen.grid.scrollback_limit(),
        0,
        "alt screen should disable scrollback"
    );

    // RIS while in alt screen
    screen.process(b"\x1bc");
    assert!(!screen.in_alt_screen(), "RIS should exit alt screen");
    assert_eq!(
        screen.grid.scrollback_limit(),
        100,
        "RIS should restore scrollback_limit from saved grid"
    );

    // Verify scrollback still works after RIS
    screen.process(b"X\r\nY\r\nZ\r\nW");
    let _ = screen.take_pending_scrollback();
    // New lines should be capturable as scrollback
    assert!(
        screen.grid.scrollback_len() > 0,
        "scrollback should work after RIS during alt screen"
    );
}

#[test]
fn scrollback_limit_zero() {
    // With scrollback_limit=0, scrollback should be completely disabled
    let mut screen = Screen::new(10, 3, 0);
    screen.process(b"A\r\nB\r\nC\r\nD\r\nE");
    let hist = screen.get_history();
    assert_eq!(
        hist.len(),
        0,
        "scrollback with limit=0 should store nothing, got {}",
        hist.len()
    );
    let pending_rows = screen.take_pending_scrollback();
    let pending = AnsiRenderer::new().render_rows(&screen, &pending_rows);
    assert!(
        pending.is_empty(),
        "pending scrollback with limit=0 should be empty"
    );
}

#[test]
fn csi_f_is_alias_for_cup() {
    // CSI f should work the same as CSI H
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;10f"); // HVP
    assert_eq!(screen.grid.cursor_y(), 4);
    assert_eq!(screen.grid.cursor_x(), 9);
}

#[test]
fn csi_cup_zero_params_default_to_home() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[5;10H"); // move away
    screen.process(b"\x1b[H"); // CUP with no params → (1,1)
    assert_eq!(screen.grid.cursor_y(), 0);
    assert_eq!(screen.grid.cursor_x(), 0);
}

#[test]
fn csi_cup_params_beyond_screen_clamp() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[999;999H");
    assert_eq!(screen.grid.cursor_y(), 23);
    assert_eq!(screen.grid.cursor_x(), 79);
}

#[test]
fn dsr_at_boundary_positions() {
    // CPR at (1,1) — home position
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[1;1H");
    screen.process(b"\x1b[6n");
    let r = screen.take_responses();
    assert_eq!(r[0], b"\x1b[1;1R");

    // CPR at bottom-right corner
    screen.process(b"\x1b[24;80H");
    screen.process(b"\x1b[6n");
    let r = screen.take_responses();
    assert_eq!(r[0], b"\x1b[24;80R");
}

#[test]
fn responses_drained_after_take() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[6n");
    let r1 = screen.take_responses();
    assert_eq!(r1.len(), 1);
    let r2 = screen.take_responses();
    assert!(r2.is_empty(), "responses should be empty after drain");
}

#[test]
fn cursor_movement_with_zero_params_defaults() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[10;10H"); // start at (10,10)
    screen.process(b"\x1b[A"); // CUU default 1
    assert_eq!(screen.grid.cursor_y(), 8);
    screen.process(b"\x1b[B"); // CUD default 1
    assert_eq!(screen.grid.cursor_y(), 9);
    screen.process(b"\x1b[C"); // CUF default 1
    assert_eq!(screen.grid.cursor_x(), 10);
    screen.process(b"\x1b[D"); // CUB default 1
    assert_eq!(screen.grid.cursor_x(), 9);
}

#[test]
fn cursor_movement_beyond_bounds_clamps() {
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"\x1b[3;5H"); // center
    screen.process(b"\x1b[999A"); // CUU way past top
    assert_eq!(screen.grid.cursor_y(), 0);
    screen.process(b"\x1b[999B"); // CUD way past bottom
    assert_eq!(screen.grid.cursor_y(), 4);
    screen.process(b"\x1b[999D"); // CUB way past left
    assert_eq!(screen.grid.cursor_x(), 0);
    screen.process(b"\x1b[999C"); // CUF way past right
    assert_eq!(screen.grid.cursor_x(), 9);
}

#[test]
fn overwrite_wide_char_first_half() {
    // Writing a narrow char on the first half of a wide char should blank continuation
    let mut screen = Screen::new(10, 3, 100);
    screen.process("你好".as_bytes()); // cols 0-1: 你, cols 2-3: 好
    screen.process(b"\x1b[1;1H"); // back to col 0
    screen.process(b"X"); // overwrite first half of 你
    assert_eq!(screen.grid.visible_row(0)[0].c, 'X');
    assert_eq!(screen.grid.visible_row(0)[0].width, 1);
    assert_eq!(
        screen.grid.visible_row(0)[1].c,
        ' ',
        "continuation should be blanked"
    );
    assert_eq!(screen.grid.visible_row(0)[1].width, 1);
}

#[test]
fn overwrite_wide_char_second_half() {
    // Writing a narrow char on the continuation cell should blank the first half
    let mut screen = Screen::new(10, 3, 100);
    screen.process("你好".as_bytes());
    screen.process(b"\x1b[1;2H"); // col 2 (0-based: 1, the continuation of 你)
    screen.process(b"X"); // overwrite continuation
    assert_eq!(
        screen.grid.visible_row(0)[0].c,
        ' ',
        "first half should be blanked"
    );
    assert_eq!(screen.grid.visible_row(0)[0].width, 1);
    assert_eq!(screen.grid.visible_row(0)[1].c, 'X');
    assert_eq!(screen.grid.visible_row(0)[1].width, 1);
}

#[test]
fn lf_at_last_row_without_scroll_region() {
    // LF when cursor is at the absolute last row (no scroll region) should scroll
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"\x1b[3;1H"); // row 3 (last row)
    screen.process(b"X");
    screen.process(b"\n"); // should scroll up
                           // Cursor stays at row 2 (scroll_bottom), content shifted
    assert_eq!(screen.grid.cursor_y(), 2);
}

#[test]
fn cr_does_not_scroll() {
    // CR should never cause scrolling
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"ABCDEFGHIJ"); // fill row 0, wrap pending
    screen.process(b"\r"); // CR
    assert_eq!(screen.grid.cursor_x(), 0);
    assert_eq!(screen.grid.cursor_y(), 0, "CR should stay on same row");
}

#[test]
fn sgr_color_reset_39_49() {
    let mut screen = Screen::new(80, 3, 100);
    screen.process(b"\x1b[31;42m"); // red fg, green bg
    screen.process(b"A");
    assert!(screen.cell_style(0, 0).fg.is_some());
    assert!(screen.cell_style(0, 0).bg.is_some());
    screen.process(b"\x1b[39m"); // reset fg to default
    screen.process(b"B");
    assert!(screen.cell_style(0, 1).fg.is_none(), "fg should be reset");
    assert!(screen.cell_style(0, 1).bg.is_some(), "bg should remain");
    screen.process(b"\x1b[49m"); // reset bg to default
    screen.process(b"C");
    assert!(screen.cell_style(0, 2).fg.is_none());
    assert!(screen.cell_style(0, 2).bg.is_none(), "bg should be reset");
}

#[test]
fn scroll_down_within_region_does_not_produce_scrollback() {
    // CSI T (scroll down) should never produce scrollback
    let mut screen = Screen::new(10, 5, 100);
    screen.process(b"\x1b[2;4r"); // scroll region rows 2-4
    screen.process(b"\x1b[2;1H"); // inside region
    screen.process(b"\x1b[3T"); // scroll down 3 lines within region
    let pending_rows = screen.take_pending_scrollback();
    let pending = AnsiRenderer::new().render_rows(&screen, &pending_rows);
    assert!(
        pending.is_empty(),
        "scroll down should never produce scrollback"
    );
}

#[test]
fn mouse_mode_per_mode_toggle() {
    // Each mouse mode is independently toggled (xterm behavior)
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[?1000h");
    assert!(screen.grid.modes().mouse_modes.click);
    assert!(!screen.grid.modes().mouse_modes.button);
    screen.process(b"\x1b[?1000l");
    assert!(!screen.grid.modes().mouse_modes.click);
}

#[test]
fn mouse_mode_multiple_simultaneous() {
    // Multiple modes can be enabled simultaneously
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[?1000h");
    screen.process(b"\x1b[?1003h");
    assert!(screen.grid.modes().mouse_modes.click);
    assert!(screen.grid.modes().mouse_modes.any);
    // Effective is highest priority
    assert_eq!(
        screen.grid.modes().mouse_modes.effective(),
        super::grid::MouseMode::Any
    );
}

#[test]
fn mouse_mode_disable_own_mode_only() {
    // Disabling one mode doesn't affect others
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[?1000h");
    screen.process(b"\x1b[?1002h");
    screen.process(b"\x1b[?1000l"); // disable only click
    assert!(!screen.grid.modes().mouse_modes.click);
    assert!(screen.grid.modes().mouse_modes.button);
    assert_eq!(
        screen.grid.modes().mouse_modes.effective(),
        super::grid::MouseMode::Button
    );
}

#[test]
fn mouse_mode_priority_resolution() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[?1000h");
    screen.process(b"\x1b[?1002h");
    screen.process(b"\x1b[?1003h");
    assert_eq!(
        screen.grid.modes().mouse_modes.effective(),
        super::grid::MouseMode::Any
    );
    screen.process(b"\x1b[?1003l");
    assert_eq!(
        screen.grid.modes().mouse_modes.effective(),
        super::grid::MouseMode::Button
    );
    screen.process(b"\x1b[?1002l");
    assert_eq!(
        screen.grid.modes().mouse_modes.effective(),
        super::grid::MouseMode::Click
    );
    screen.process(b"\x1b[?1000l");
    assert_eq!(
        screen.grid.modes().mouse_modes.effective(),
        super::grid::MouseMode::Off
    );
}

#[test]
fn mouse_encoding_disable_resets_to_x10() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[?1006h"); // SGR encoding
    assert_eq!(
        screen.grid.modes().mouse_encoding,
        super::grid::MouseEncoding::Sgr
    );
    screen.process(b"\x1b[?1006l");
    assert_eq!(
        screen.grid.modes().mouse_encoding,
        super::grid::MouseEncoding::X10
    );
}

#[test]
fn cursor_visibility_toggle() {
    let mut screen = Screen::new(80, 24, 100);
    assert!(screen.grid.cursor_visible());
    screen.process(b"\x1b[?25l"); // hide
    assert!(!screen.grid.cursor_visible());
    screen.process(b"\x1b[?25h"); // show
    assert!(screen.grid.cursor_visible());
}

#[test]
fn dl_il_outside_scroll_region_no_op() {
    // DL/IL when cursor is outside the scroll region should be no-op
    let mut screen = Screen::new(10, 6, 100);
    for row in 0..6 {
        screen.process(format!("\x1b[{};1HR{}", row + 1, row).as_bytes());
    }
    screen.process(b"\x1b[2;4r"); // region rows 2-4 (0-based: 1-3)
    screen.process(b"\x1b[6;1H"); // row 6 (0-based: 5), outside region
    screen.process(b"\x1b[M"); // DL — should be no-op
    screen.process(b"\x1b[L"); // IL — should be no-op
    let lines = screen_lines(&screen);
    for row in 0..6 {
        assert_eq!(
            lines[row],
            format!("R{}", row),
            "row {} should be unchanged after DL/IL outside region",
            row
        );
    }
}

#[test]
fn dl_clears_wrap_pending() {
    let mut screen = Screen::new(5, 3, 100);
    screen.process(b"ABCDE"); // wrap_pending = true
    assert!(screen.grid.wrap_pending());
    screen.process(b"\x1b[M"); // DL
    assert!(!screen.grid.wrap_pending());
}

#[test]
fn il_clears_wrap_pending() {
    let mut screen = Screen::new(5, 3, 100);
    screen.process(b"ABCDE");
    assert!(screen.grid.wrap_pending());
    screen.process(b"\x1b[L"); // IL
    assert!(!screen.grid.wrap_pending());
}

#[test]
fn erase_display_preserves_cursor_position() {
    for mode in [0u8, 1, 2] {
        let mut screen = Screen::new(20, 10, 100);
        screen.process(b"ABCDEFGHIJ\r\nXYZ");
        screen.process(b"\x1b[3;5H"); // move to row 3, col 5
        let (cx, cy) = (screen.grid.cursor_x(), screen.grid.cursor_y());
        let seq = format!("\x1b[{}J", mode);
        screen.process(seq.as_bytes()); // ED 0/1/2
        assert_eq!(
            screen.grid.cursor_x(),
            cx,
            "ED {} should preserve cursor_x",
            mode
        );
        assert_eq!(
            screen.grid.cursor_y(),
            cy,
            "ED {} should preserve cursor_y",
            mode
        );
    }
}

#[test]
fn erase_line_preserves_cursor_position() {
    for mode in [0u8, 1, 2] {
        let mut screen = Screen::new(20, 10, 100);
        screen.process(b"ABCDEFGHIJ\r\nXYZ");
        screen.process(b"\x1b[2;7H"); // move to row 2, col 7
        let (cx, cy) = (screen.grid.cursor_x(), screen.grid.cursor_y());
        let seq = format!("\x1b[{}K", mode);
        screen.process(seq.as_bytes()); // EL 0/1/2
        assert_eq!(
            screen.grid.cursor_x(),
            cx,
            "EL {} should preserve cursor_x",
            mode
        );
        assert_eq!(
            screen.grid.cursor_y(),
            cy,
            "EL {} should preserve cursor_y",
            mode
        );
    }
}

#[test]
fn rep_repeats_wide_char() {
    let mut screen = Screen::new(20, 3, 100);
    // Print '世' (width 2)
    screen.process("".as_bytes());
    assert_eq!(screen.grid.visible_row(0)[0].c, '');
    assert_eq!(screen.grid.visible_row(0)[0].width, 2);
    // REP: repeat 2 more times (CSI 2 b)
    screen.process(b"\x1b[2b");
    // Should have 3 wide chars occupying 6 cells
    assert_eq!(screen.grid.visible_row(0)[0].c, '');
    assert_eq!(screen.grid.visible_row(0)[0].width, 2);
    assert_eq!(screen.grid.visible_row(0)[2].c, '');
    assert_eq!(screen.grid.visible_row(0)[2].width, 2);
    assert_eq!(screen.grid.visible_row(0)[4].c, '');
    assert_eq!(screen.grid.visible_row(0)[4].width, 2);
    // Continuation cells
    assert_eq!(screen.grid.visible_row(0)[1].width, 0);
    assert_eq!(screen.grid.visible_row(0)[3].width, 0);
    assert_eq!(screen.grid.visible_row(0)[5].width, 0);
}

// --- StyleTable GC integration tests ---

#[test]
fn compact_styles_reclaims_unused() {
    let mut screen = Screen::new(10, 3, 0);
    // Intern styles and place one in a cell
    let s1 = style::Style {
        bold: true,
        ..style::Style::default()
    };
    let s2 = style::Style {
        italic: true,
        ..style::Style::default()
    };
    let id1 = screen.grid.style_table_mut().intern(s1);
    let id2 = screen.grid.style_table_mut().intern(s2);
    // Only s1 is referenced by a cell
    screen.grid.visible_row_mut(0)[0].style_id = id1;

    screen.compact_styles();

    // s1 is still valid
    assert_eq!(screen.grid.style_table().get(id1), s1);
    // s2's slot should be reusable
    let s3 = style::Style {
        dim: true,
        ..style::Style::default()
    };
    let id3 = screen.grid.style_table_mut().intern(s3);
    assert_eq!(id3, id2, "should reuse freed slot");
    assert_eq!(screen.grid.style_table().get(id3), s3);
}

#[test]
fn compact_styles_preserves_scrollback_styles() {
    let mut screen = Screen::new(5, 3, 100);
    // Write styled text then scroll it into scrollback
    screen.process(b"\x1b[1mBold\x1b[0m");
    let scrollback_style_id = screen.grid.visible_row(0)[0].style_id;
    assert!(
        !scrollback_style_id.is_default(),
        "styled cell should have non-default style_id"
    );

    // Scroll text into scrollback
    screen.process(b"\n\n\n\n");

    // Compact should preserve the scrollback style
    screen.compact_styles();
    let style = screen.grid.style_table().get(scrollback_style_id);
    assert!(style.bold, "scrollback style should still be bold");
}

#[test]
fn compact_styles_preserves_saved_grid_styles() {
    let mut screen = Screen::new(10, 3, 0);
    // Write styled text on main screen
    screen.process(b"\x1b[1mHello\x1b[0m");
    let main_style_id = screen.grid.visible_row(0)[0].style_id;

    // Enter alt screen — main grid saved
    screen.process(b"\x1b[?1049h");

    // Intern a new style only on alt screen
    let alt_style = style::Style {
        italic: true,
        ..style::Style::default()
    };
    let alt_id = screen.grid.style_table_mut().intern(alt_style);
    // Don't put alt_id in any cell — it should be reclaimable

    // Compact while in alt screen — main screen styles in saved_grid should survive
    screen.compact_styles();

    // Main screen style should still be valid (it's in saved_grid)
    let style = screen.grid.style_table().get(main_style_id);
    assert!(style.bold, "saved grid style should survive compaction");

    // alt_id was unreferenced, should be freed
    let new_style = style::Style {
        dim: true,
        ..style::Style::default()
    };
    let new_id = screen.grid.style_table_mut().intern(new_style);
    assert_eq!(
        new_id, alt_id,
        "unreferenced alt style slot should be reused"
    );
}

#[test]
fn alt_screen_exit_gc_trigger() {
    let mut screen = Screen::new(10, 3, 0);

    // Enter alt screen
    screen.process(b"\x1b[?1049h");

    // Create unique styles during alt screen (without placing in cells)
    for i in 0..50u16 {
        let style = style::Style {
            fg: Some(style::Color::Rgb(i as u8, 0, 0)),
            ..style::Style::default()
        };
        screen.grid.style_table_mut().intern(style);
    }
    let pre_exit_len = screen.grid.style_table().len();

    // Exit alt screen — should trigger GC unconditionally
    screen.process(b"\x1b[?1049l");

    // After GC, alt-screen-only styles should be reclaimed
    assert!(
        screen.grid.style_table().len() < pre_exit_len,
        "GC should have reclaimed styles: {} should be < {}",
        screen.grid.style_table().len(),
        pre_exit_len
    );
}

// --- Notification queue tests ---

#[test]
fn osc_777_queued_as_notification() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]777;notify;Title;Body\x1b\\");
    let notifications = screen.take_queued_notifications();
    assert_eq!(notifications.len(), 1);
    assert!(notifications[0].starts_with(b"\x1b]777;"));
}

#[test]
fn osc_9_queued_as_notification() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]9;Hello\x1b\\");
    let notifications = screen.take_queued_notifications();
    assert_eq!(notifications.len(), 1);
    assert!(notifications[0].starts_with(b"\x1b]9;"));
}

#[test]
fn osc_99_queued_as_notification() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]99;Body text\x07");
    let notifications = screen.take_queued_notifications();
    assert_eq!(notifications.len(), 1);
    assert!(notifications[0].starts_with(b"\x1b]99;"));
}

#[test]
fn bell_not_queued_as_notification() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x07");
    let notifications = screen.take_queued_notifications();
    assert!(
        notifications.is_empty(),
        "BEL should not be queued as notification"
    );
}

#[test]
fn ed3_not_queued_as_notification() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b[3J");
    let notifications = screen.take_queued_notifications();
    assert!(
        notifications.is_empty(),
        "ED3 should not be queued as notification"
    );
}

#[test]
fn osc_52_not_queued_as_notification() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]52;c;SGVsbG8=\x1b\\");
    let notifications = screen.take_queued_notifications();
    assert!(
        notifications.is_empty(),
        "OSC 52 (clipboard) should not be queued"
    );
}

#[test]
fn notification_queue_respects_limit() {
    let mut screen = Screen::new(80, 24, 100);
    // Push 55 notifications — only the last 50 should remain
    for i in 0..55u32 {
        let osc = format!("\x1b]777;notify;Title;msg{}\x1b\\", i);
        screen.process(osc.as_bytes());
    }
    let notifications = screen.take_queued_notifications();
    assert_eq!(notifications.len(), 50);
    // First notification should be #5 (oldest 5 were dropped)
    let first = String::from_utf8_lossy(&notifications[0]);
    assert!(
        first.contains("msg5"),
        "oldest should be msg5, got: {}",
        first
    );
    let last = String::from_utf8_lossy(&notifications[49]);
    assert!(
        last.contains("msg54"),
        "newest should be msg54, got: {}",
        last
    );
}

#[test]
fn take_queued_notifications_drains() {
    let mut screen = Screen::new(80, 24, 100);
    screen.process(b"\x1b]777;notify;Title;Body\x1b\\");
    let first = screen.take_queued_notifications();
    assert_eq!(first.len(), 1);
    let second = screen.take_queued_notifications();
    assert!(second.is_empty(), "second take should be empty after drain");
}

// ─── Combining marks: operations that move/erase cells ──────────────────────

#[test]
fn combining_survives_scroll_into_scrollback() {
    let mut screen = Screen::new(10, 3, 100);
    // Write combining char on row 0
    screen.process("e\u{0301}".as_bytes());
    // Scroll it off screen into scrollback
    screen.process(b"\n\n\n");
    // Scrollback row should have the combining mark
    assert_eq!(screen.grid.scrollback_len(), 1);
    let row = screen.grid.scrollback_row(0);
    assert_eq!(row[0].c, 'e');
    assert_eq!(row.combining(0), &['\u{0301}']);
}

#[test]
fn combining_in_scrollback_renders_correctly() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process("e\u{0301}".as_bytes());
    screen.process(b"\n\n\n");
    let pending_rows = screen.take_pending_scrollback();
    let pending = AnsiRenderer::new().render_rows(&screen, &pending_rows);
    assert_eq!(pending.len(), 1);
    let text = String::from_utf8_lossy(&pending[0]);
    assert!(
        text.contains("e\u{0301}"),
        "scrollback render must include combining mark, got: {}",
        text
    );
}

#[test]
fn combining_in_reattach_history() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process("e\u{0301}".as_bytes());
    screen.process(b"\n\n\n");
    let _ = screen.take_pending_scrollback();
    let history = screen.get_history();
    assert!(!history.is_empty());
    let text = String::from_utf8_lossy(&history[0]);
    assert!(
        text.contains("e\u{0301}"),
        "history render must include combining mark, got: {}",
        text
    );
}

#[test]
fn combining_erased_by_erase_in_line() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process("e\u{0301}".as_bytes());
    assert_eq!(screen.grid.visible_row(0).combining(0), &['\u{0301}']);
    // EL — erase from cursor to end of line (cursor is at col 1 after 'e')
    // Move to col 0 first, then erase
    screen.process(b"\x1b[1G"); // CHA col 1 (1-indexed)
    screen.process(b"\x1b[K"); // EL 0 (erase to end)
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(0).combining(0), &[] as &[char]);
}

#[test]
fn combining_erased_by_erase_character() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process("e\u{0301}".as_bytes());
    // Move cursor back to col 0
    screen.process(b"\x1b[1G");
    // ECH — erase 1 character
    screen.process(b"\x1b[X");
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(0).combining(0), &[] as &[char]);
}

#[test]
fn combining_erased_by_erase_display() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process("e\u{0301}".as_bytes());
    // ED 2 — erase entire display
    screen.process(b"\x1b[2J");
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(0).combining(0), &[] as &[char]);
}

#[test]
fn combining_shifted_by_insert_character() {
    let mut screen = Screen::new(10, 3, 100);
    // Write "Ae\u{0301}" — A at col 0, e+combining at col 1
    screen.process("Ae\u{0301}".as_bytes());
    assert_eq!(screen.grid.visible_row(0)[1].c, 'e');
    assert_eq!(screen.grid.visible_row(0).combining(1), &['\u{0301}']);
    // Move cursor to col 0
    screen.process(b"\x1b[1G");
    // ICH — insert 1 blank character, shifting everything right
    screen.process(b"\x1b[@");
    // Col 0 should be blank, col 1 should be 'A', col 2 should be 'e' with combining
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(0)[1].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[2].c, 'e');
    assert_eq!(
        screen.grid.visible_row(0).combining(2),
        &['\u{0301}'],
        "combining mark should shift with its cell during ICH"
    );
}

#[test]
fn combining_shifted_by_delete_character() {
    let mut screen = Screen::new(10, 3, 100);
    // Write "Ae\u{0301}" — A at col 0, e+combining at col 1
    screen.process("Ae\u{0301}".as_bytes());
    // Move cursor to col 0
    screen.process(b"\x1b[1G");
    // DCH — delete 1 character at col 0, shifting everything left
    screen.process(b"\x1b[P");
    // Col 0 should now be 'e' with combining mark
    assert_eq!(screen.grid.visible_row(0)[0].c, 'e');
    assert_eq!(
        screen.grid.visible_row(0).combining(0),
        &['\u{0301}'],
        "combining mark should shift with its cell during DCH"
    );
}

#[test]
fn combining_overwritten_by_new_char() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process("e\u{0301}".as_bytes());
    assert_eq!(screen.grid.visible_row(0).combining(0), &['\u{0301}']);
    // Move cursor back and overwrite with 'X'
    screen.process(b"\x1b[1G");
    screen.process(b"X");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'X');
    assert_eq!(
        screen.grid.visible_row(0).combining(0),
        &[] as &[char],
        "overwriting a cell must clear its combining marks"
    );
}

#[test]
fn combining_survives_alt_screen_round_trip() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process("e\u{0301}".as_bytes());
    // Enter alt screen
    screen.process(b"\x1b[?1049h");
    // Leave alt screen
    screen.process(b"\x1b[?1049l");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'e');
    assert_eq!(
        screen.grid.visible_row(0).combining(0),
        &['\u{0301}'],
        "combining marks must survive alt screen round trip"
    );
}

#[test]
fn combining_in_delete_lines() {
    let mut screen = Screen::new(10, 3, 100);
    // Row 0: empty, row 1: e+combining
    screen.process(b"\x1b[2;1H"); // move to row 2
    screen.process("e\u{0301}".as_bytes());
    assert_eq!(screen.grid.visible_row(1).combining(0), &['\u{0301}']);
    // Move to row 1 and delete it — row 1 (with combining) should move up
    screen.process(b"\x1b[1;1H");
    screen.process(b"\x1b[M"); // DL
                               // Now row 0 should have the combining char (was row 1)
    assert_eq!(screen.grid.visible_row(0)[0].c, 'e');
    assert_eq!(
        screen.grid.visible_row(0).combining(0),
        &['\u{0301}'],
        "combining marks should move with row during DL"
    );
}

#[test]
fn combining_in_insert_lines() {
    let mut screen = Screen::new(10, 3, 100);
    // Row 0: e+combining
    screen.process("e\u{0301}".as_bytes());
    // Move to row 0 and insert a line — row 0 should push down to row 1
    screen.process(b"\x1b[1;1H");
    screen.process(b"\x1b[L"); // IL
                               // Row 0 should be blank, row 1 should have combining
    assert_eq!(screen.grid.visible_row(0)[0].c, ' ');
    assert_eq!(screen.grid.visible_row(1)[0].c, 'e');
    assert_eq!(
        screen.grid.visible_row(1).combining(0),
        &['\u{0301}'],
        "combining marks should move with row during IL"
    );
}

#[test]
fn combining_in_full_render_output() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process("e\u{0301}".as_bytes());
    let mut cache = AnsiRenderer::new();
    let output = cache.render(&screen, true);
    let text = String::from_utf8_lossy(&output);
    assert!(
        text.contains("e\u{0301}"),
        "full render must include combining mark"
    );
}

#[test]
fn combining_in_incremental_render_output() {
    let mut screen = Screen::new(10, 3, 100);
    let mut cache = AnsiRenderer::new();
    // First render to populate cache
    let _ = cache.render(&screen, true);
    // Now add combining mark
    screen.process("e\u{0301}".as_bytes());
    // Incremental render should pick up the change
    let output = cache.render(&screen, false);
    let text = String::from_utf8_lossy(&output);
    assert!(
        text.contains("e\u{0301}"),
        "incremental render must include combining mark"
    );
}

#[test]
fn combining_dirty_tracking_detects_change() {
    let mut screen = Screen::new(10, 3, 100);
    let mut cache = AnsiRenderer::new();
    // Write 'e' and render
    screen.process(b"e");
    let _ = cache.render(&screen, true);
    // Move back to col 0 and add combining mark to existing 'e'
    screen.process(b"\x1b[1G");
    screen.process("e\u{0301}".as_bytes()); // overwrite 'e' with 'e'+combining
                                            // Incremental render should detect the row changed
    let output = cache.render(&screen, false);
    let text = String::from_utf8_lossy(&output);
    assert!(
        text.contains("e\u{0301}"),
        "dirty tracking must detect combining mark addition"
    );
}

// --- Phase 2: Missing Escape Sequences ---

#[test]
fn nel_next_line() {
    let mut screen = Screen::new(10, 3, 0);
    screen.process(b"AB\x1bECD");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'A');
    assert_eq!(screen.grid.visible_row(0)[1].c, 'B');
    assert_eq!(screen.grid.visible_row(1)[0].c, 'C');
    assert_eq!(screen.grid.visible_row(1)[1].c, 'D');
}

#[test]
fn nel_at_scroll_bottom_scrolls() {
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"Line1\r\nLine2\r\nLine3");
    screen.process(b"\x1bE");
    assert_eq!(screen.grid.visible_row(0)[0].c, 'L'); // Line2
    assert_eq!(screen.grid.visible_row(2)[0].c, ' '); // blank new line
}

#[test]
fn decaln_fills_screen_with_e() {
    let mut screen = Screen::new(5, 3, 0);
    screen.process(b"Hello\r\nWorld");
    screen.process(b"\x1b#8");
    for y in 0..3 {
        for x in 0..5 {
            assert_eq!(
                screen.grid.visible_row(y)[x].c,
                'E',
                "expected 'E' at ({}, {})",
                x,
                y
            );
        }
    }
    assert_eq!(screen.grid.cursor_pos(), (0, 0));
}

#[test]
fn rep_with_line_drawing_charset() {
    let mut screen = Screen::new(10, 1, 0);
    // ESC(0 enters line drawing, 'q' maps to '─', CSI 3 b = repeat 3x
    screen.process(b"\x1b(0q\x1b[3b");
    for x in 0..4 {
        assert_eq!(
            screen.grid.visible_row(0)[x].c,
            '\u{2500}',
            "expected '\u{2500}' at col {}, got '{}'",
            x,
            screen.grid.visible_row(0)[x].c
        );
    }
}

#[test]
fn title_push_pop() {
    let mut screen = Screen::new(10, 3, 0);
    screen.process(b"\x1b]2;First\x07");
    assert_eq!(screen.title(), "First");
    screen.process(b"\x1b[22;0t");
    screen.process(b"\x1b]2;Second\x07");
    assert_eq!(screen.title(), "Second");
    screen.process(b"\x1b[23;0t");
    assert_eq!(screen.title(), "First");
}

#[test]
fn title_pop_empty_stack_noop() {
    let mut screen = Screen::new(10, 3, 0);
    screen.process(b"\x1b]2;Title\x07");
    screen.process(b"\x1b[23;0t");
    assert_eq!(screen.title(), "Title");
}

#[test]
fn decom_cursor_position_relative_to_scroll_region() {
    let mut screen = Screen::new(10, 10, 0);
    screen.process(b"\x1b[3;7r"); // scroll region rows 3-7
    screen.process(b"\x1b[?6h"); // enable origin mode
    screen.process(b"\x1b[1;1H"); // CUP 1;1 → top of scroll region
    assert_eq!(screen.grid.cursor_pos(), (0, 2)); // 0-indexed: col 0, row 2
}

#[test]
fn decom_cursor_clamped_to_scroll_region() {
    let mut screen = Screen::new(10, 10, 0);
    screen.process(b"\x1b[3;7r");
    screen.process(b"\x1b[?6h");
    screen.process(b"\x1b[99;1H"); // CUP 99;1 → clamp to bottom
    assert_eq!(screen.grid.cursor_pos(), (0, 6)); // col 0, row 6 (scroll bottom)
}

#[test]
fn decom_off_cursor_absolute() {
    let mut screen = Screen::new(10, 10, 0);
    screen.process(b"\x1b[3;7r");
    screen.process(b"\x1b[1;1H"); // origin mode OFF (default)
    assert_eq!(screen.grid.cursor_pos(), (0, 0)); // absolute row 0
}

#[test]
fn decom_set_scrolling_region_homes_to_origin() {
    let mut screen = Screen::new(10, 10, 0);
    screen.process(b"\x1b[?6h");
    screen.process(b"\x1b[5;5H");
    screen.process(b"\x1b[3;7r"); // set scroll region → cursor to origin
    assert_eq!(screen.grid.cursor_pos(), (0, 2)); // top of scroll region
}

#[test]
fn decom_saved_and_restored() {
    let mut screen = Screen::new(10, 10, 0);
    screen.process(b"\x1b[3;7r");
    screen.process(b"\x1b[?6h");
    screen.process(b"\x1b[2;3H");
    screen.process(b"\x1b7"); // DECSC save
    screen.process(b"\x1b[?6l"); // turn off
    screen.process(b"\x1b[1;1H");
    assert_eq!(screen.grid.cursor_pos(), (0, 0));
    screen.process(b"\x1b8"); // DECRC restore
    assert!(screen.grid.modes().origin_mode);
}

// Regression test for cursor-at-top-left bug after Enter press with scrollback.
// On full renders (triggered by scrollback), emit_mode() emits \x1b[?6l (DECOM
// reset). The VT220 spec and xterm both home the cursor when DECOM state changes.
// So if CUP appears BEFORE \x1b[?6l, the cursor ends up at (1,1) instead of the
// correct position. On incremental renders, emit_mode_delta skips DECOM when
// unchanged, so the bug only appears after Enter (when scrollback triggers a full
// render). Pressing any key triggers another render (incremental, no DECOM) which
// restores the cursor — exactly matching the reported symptom.
#[test]
fn render_cup_appears_after_decom_on_full_render() {
    let mut screen = Screen::new(80, 24, 1000);

    // Fill screen to generate scrollback: 24 lines scrolls row 0 into scrollback
    for _ in 0..24 {
        screen.process(b"Line\r\n");
    }
    screen.process(b"$ "); // cursor at (col=2, row=23), i.e. 1-indexed (24, 3)

    let mut cache = AnsiRenderer::new();
    let scrollback_rows = screen.take_pending_scrollback();
    let scrollback = cache.render_rows(&screen, &scrollback_rows);
    assert!(!scrollback.is_empty(), "should have pending scrollback");

    let output = cache.render_with_scrollback(&screen, &scrollback);
    let text = String::from_utf8_lossy(&output);

    // The cursor CUP for position (row=23, col=2) in 0-indexed = \x1b[24;3H
    let cup_seq = "\x1b[24;3H";
    // DECOM reset sequence — xterm/VTE home cursor on both set and reset
    let decom_seq = "\x1b[?6l";

    let cup_pos = text
        .find(cup_seq)
        .unwrap_or_else(|| panic!("cursor CUP {cup_seq:?} not found in render output:\n{text}"));
    let decom_pos = text
        .find(decom_seq)
        .unwrap_or_else(|| panic!("DECOM reset {decom_seq:?} not found in render output:\n{text}"));

    // CUP must appear AFTER DECOM, so DECOM's cursor-homing is overridden by CUP
    assert!(
        cup_pos > decom_pos,
        "CUP({cup_seq:?} at byte {cup_pos}) must appear after DECOM reset \
         ({decom_seq:?} at byte {decom_pos}), otherwise DECOM homes cursor to (1,1)"
    );
}

// ─── Bug-fix tests: rendering bugs found during code audit ───

#[test]
fn dsr_reports_relative_position_in_origin_mode() {
    // Bug 1: DSR (CSI 6n) should report cursor position relative to
    // the scroll region when DECOM (origin mode, ?6) is enabled.
    let mut screen = Screen::new(80, 24, 100);

    // Set scroll region to rows 5..15 (1-indexed: 5;15r)
    screen.process(b"\x1b[5;15r");
    // Enable origin mode
    screen.process(b"\x1b[?6h");
    // Move cursor to row 3, col 10 within the region (relative coords)
    screen.process(b"\x1b[3;10H");

    // Request DSR
    screen.process(b"\x1b[6n");
    let responses = screen.take_responses();
    assert_eq!(responses.len(), 1);
    // In origin mode, DSR should report position relative to scroll region.
    // Row 3 within region, col 10 → "\x1b[3;10R"
    assert_eq!(
        responses[0],
        b"\x1b[3;10R",
        "DSR in origin mode should report position relative to scroll region, \
         got: {:?}",
        String::from_utf8_lossy(&responses[0])
    );
}

#[test]
fn insert_character_blanks_orphaned_wide_char_base_at_right_margin() {
    // Bug 2: csi_insert_character should blank the base cell (width==2)
    // at last-1 when its continuation (width==0) ends up at last.
    let mut screen = Screen::new(6, 3, 100);

    // Place a wide char at columns 3-4 (0-indexed): base at 3, cont at 4
    screen.process(b"\x1b[1;4H"); // move to col 4 (1-indexed) = col 3 (0-indexed)
    screen.process("".as_bytes()); // occupies cols 3,4 (0-indexed)

    assert_eq!(screen.grid.visible_row(0)[3].c, '');
    assert_eq!(screen.grid.visible_row(0)[3].width, 2);
    assert_eq!(screen.grid.visible_row(0)[4].width, 0);

    // Move cursor to col 0 and insert 1 char — shifts everything right by 1.
    // pop() removes col 5 (blank), insert adds blank at col 0.
    // After: base at col 4 (width==2), continuation at col 5 (width==0, last col).
    // The code blanks continuation at col 5 but should ALSO blank base at col 4.
    screen.process(b"\x1b[1;1H");
    screen.process(b"\x1b[1@"); // ICH — insert 1 character

    let last = 5usize; // cols - 1
                       // The continuation at last col should be blanked (code already does this)
    assert_eq!(
        screen.grid.visible_row(0)[last].c,
        ' ',
        "orphaned continuation at last column should be blanked"
    );

    // The base at last-1 should also be blanked since its continuation was removed
    assert_eq!(
        screen.grid.visible_row(0)[last - 1].c,
        ' ',
        "orphaned wide char base at last-1 should be blanked"
    );
    assert_ne!(
        screen.grid.visible_row(0)[last - 1].width,
        2,
        "orphaned wide char base should not remain width==2"
    );
}

#[test]
fn ind_clears_wrap_pending() {
    // Bug 4: IND (ESC D) should clear wrap_pending flag.
    let mut screen = Screen::new(5, 3, 100);

    // Fill line to trigger deferred wrap
    screen.process(b"ABCDE");
    assert!(
        screen.grid.wrap_pending(),
        "wrap should be pending after filling line"
    );
    assert_eq!(screen.grid.cursor_y(), 0);

    // Send IND (ESC D) — should clear wrap_pending and move cursor down
    screen.process(b"\x1bD");
    assert!(!screen.grid.wrap_pending(), "IND should clear wrap_pending");
    assert_eq!(
        screen.grid.cursor_y(),
        1,
        "IND should move cursor down one row"
    );

    // Cursor x stays at col 4 (last col) — IND only moves vertically.
    assert_eq!(
        screen.grid.cursor_x(),
        4,
        "IND should not change cursor x position"
    );

    // Next printed char should NOT wrap — it should overwrite at cursor pos
    screen.process(b"F");
    assert_eq!(
        screen.grid.cursor_y(),
        1,
        "after IND cleared wrap_pending, print should stay on row 1"
    );
    assert_eq!(
        screen.grid.visible_row(1)[4].c,
        'F',
        "F should be at col 4 of row 1 (IND moved cursor down, no wrap)"
    );
}

#[test]
fn csi_gt_m_does_not_set_underline() {
    // CSI > 4 ; 2 m (xterm modifyOtherKeys) must NOT be treated as SGR.
    // Without the intermediates guard this sets underline + dim.
    let mut screen = Screen::new(20, 3, 100);
    screen.process(b"\x1b[>4;2m");
    screen.process(b"hello");

    let style = screen
        .grid
        .style_table()
        .get(screen.grid.visible_row(0)[0].style_id);
    assert_eq!(
        style.underline,
        style::UnderlineStyle::None,
        "CSI > 4 ; 2 m should not set underline"
    );
    assert!(!style.dim, "CSI > 4 ; 2 m should not set dim");
}

#[test]
fn irm_insert_mode_shifts_text_right() {
    // Reproduces the nano bug: typing at the start of a line in insert mode
    // (CSI 4 h) must push existing text to the right, not overwrite it.
    let mut screen = Screen::new(20, 3, 100);
    screen.process(b"world");
    // Move cursor to column 0
    screen.process(b"\r");
    // Enter insert/replace mode IRM (CSI 4 h) and type
    screen.process(b"\x1b[4h");
    screen.process(b"hi ");
    // Existing "world" should have shifted right, not been overwritten
    let row: String = (0..8).map(|x| screen.grid.visible_row(0)[x].c).collect();
    assert_eq!(
        row, "hi world",
        "IRM insert mode should shift existing text right"
    );
}

#[test]
fn irm_reset_returns_to_replace_mode() {
    // After CSI 4 l, printing must overwrite again (replace mode is the default).
    let mut screen = Screen::new(20, 3, 100);
    screen.process(b"world");
    screen.process(b"\r");
    screen.process(b"\x1b[4h"); // insert mode on
    screen.process(b"\x1b[4l"); // insert mode off
    screen.process(b"HI");
    let row: String = (0..5).map(|x| screen.grid.visible_row(0)[x].c).collect();
    assert_eq!(
        row, "HIrld",
        "after IRM reset, printing overwrites in place"
    );
}

#[test]
fn ri_clears_pending_wrap() {
    // Reverse Index (ESC M) must clear the deferred-wrap flag, like IND/NEL/LF.
    // Otherwise a spurious wrap fires on the next print.
    let mut screen = Screen::new(5, 3, 100);
    // Move down a row so RI does not scroll
    screen.process(b"\r\n");
    // Fill the line to set wrap_pending
    screen.process(b"ABCDE");
    assert!(screen.grid.wrap_pending());
    assert_eq!(screen.grid.cursor_y(), 1);
    // RI — moves cursor up one row, must clear wrap_pending
    screen.process(b"\x1bM");
    assert!(!screen.grid.wrap_pending());
    assert_eq!(screen.grid.cursor_y(), 0);
    // Next print must land at the current position (col 4 on row 0),
    // not trigger a deferred wrap to row 1.
    screen.process(b"X");
    assert_eq!(screen.grid.cursor_y(), 0);
    assert_eq!(screen.grid.visible_row(0)[4].c, 'X');
}

#[test]
fn dsr_5_reports_terminal_ok() {
    // CSI 5 n (DSR) must answer "terminal OK" (CSI 0 n), otherwise programs block.
    let mut screen = Screen::new(10, 3, 100);
    screen.process(b"\x1b[5n");
    let responses = screen.take_responses();
    assert_eq!(responses.len(), 1, "DSR 5 should produce one response");
    assert_eq!(responses[0], b"\x1b[0n");
}

#[test]
fn dch_clears_combining_on_orphan_blank() {
    // Deleting characters that strand a wide-char orphan must also clear the
    // Row-level combining marks for the blanked cell.
    let mut screen = Screen::new(6, 3, 100);
    // Print a wide char (CJK) with a combining mark attached at column 0.
    screen.process("".as_bytes());
    screen.process("\u{0301}".as_bytes()); // combining acute on the wide char
    assert!(!screen.grid.visible_row(0).combining(0).is_empty());
    // Cursor back to column 0, delete one char (DCH). The wide char's
    // continuation cell becomes an orphan and gets blanked.
    screen.process(b"\r");
    screen.process(b"\x1b[P");
    assert!(
        screen.grid.visible_row(0).combining(0).is_empty(),
        "DCH orphan-blank must clear stale combining marks"
    );
    assert!(screen.grid.visible_row(0).combining(1).is_empty());
}

#[test]
fn ich_clears_combining_on_orphan_blank() {
    // Inserting characters that push a wide char off the row's last column
    // must clear the combining marks for the blanked trailing cell.
    let mut screen = Screen::new(4, 3, 100);
    // Fill row: narrow 'a' then wide '世' at the end (cols 1-2), col 3 empty.
    screen.process(b"a");
    screen.process("".as_bytes());
    // Attach combining mark to the wide char base (col 1).
    screen.process("\u{0301}".as_bytes());
    assert!(!screen.grid.visible_row(0).combining(1).is_empty());
    // Cursor to column 0, insert one char (ICH). The wide char shifts right;
    // its base lands at the last column with no continuation and is blanked.
    screen.process(b"\r");
    screen.process(b"\x1b[@");
    let last = 3u16;
    assert!(
        screen.grid.visible_row(0).combining(last).is_empty(),
        "ICH orphan-blank must clear stale combining marks at last col"
    );
    assert!(
        screen.grid.visible_row(0).combining(2).is_empty(),
        "ICH must clear combining marks for blanked base cell"
    );
}