rio-backend 0.4.12

Backend infrastructure for Rio terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
// Kitty Graphics Protocol Tests
// Combined test suite for Kitty graphics functionality

use crate::ansi::graphics::KittyPlacement;
use crate::ansi::kitty_graphics_protocol::{
    self, DeleteRequest, KittyGraphicsState, PlacementRequest,
};
use crate::crosswords::pos::{Column, Line, Pos};
use crate::crosswords::Crosswords;
use crate::event::{EventListener, RioEvent, WindowId};
use crate::performer::handler::Handler;
use sugarloaf::{ColorType, GraphicData, GraphicId, ResizeCommand, ResizeParameter};

// Common test utilities

/// Test handler that captures graphics operations
#[derive(Default)]
struct TestHandler {
    graphics: Vec<GraphicData>,
    placements: Vec<PlacementRequest>,
    deletions: Vec<DeleteRequest>,
    responses: Vec<String>,
}

impl Handler for TestHandler {
    fn insert_graphic(
        &mut self,
        data: GraphicData,
        _palette: Option<Vec<crate::config::colors::ColorRgb>>,
        _cursor_movement: Option<u8>,
    ) {
        self.graphics.push(data);
    }

    fn place_graphic(&mut self, placement: PlacementRequest) {
        self.placements.push(placement);
    }

    fn delete_graphics(&mut self, delete: DeleteRequest) {
        self.deletions.push(delete);
    }

    fn kitty_graphics_response(&mut self, response: String) {
        self.responses.push(response);
    }
}

/// Test event listener
#[derive(Clone)]
struct TestEventListener;

impl EventListener for TestEventListener {
    fn event(&self) -> (Option<RioEvent>, bool) {
        (None, false)
    }
}

// Integration Tests

#[test]
fn test_direct_parse_transmit() {
    let mut handler = TestHandler::default();
    let mut state = KittyGraphicsState::default();

    // Parse kitty graphics directly through the protocol parser
    // 1x1 RGBA pixel (4 bytes) - base64 encoded [255, 0, 0, 255] (red pixel)
    let params = vec![
        b"G".as_ref(),
        b"a=t,f=32,s=1,v=1,i=1".as_ref(),
        b"/wAA/w==".as_ref(),
    ];

    if let Some(response) = kitty_graphics_protocol::parse(&params, &mut state) {
        if let Some(graphic_data) = response.graphic_data {
            handler.insert_graphic(graphic_data, None, Some(0));
        }
    }

    // Verify graphic was captured
    assert_eq!(handler.graphics.len(), 1, "Should capture one graphic");

    let graphic = &handler.graphics[0];
    assert_eq!(graphic.width, 1);
    assert_eq!(graphic.height, 1);
    assert_eq!(graphic.pixels.len(), 4); // 1x1x4 bytes (RGBA)
    assert_eq!(graphic.id.get(), 1);
}

#[test]
fn test_parse_png_format() {
    let mut handler = TestHandler::default();
    let mut state = KittyGraphicsState::default();

    // 1x1 red PNG image, base64 encoded
    // This is a complete, valid PNG file
    let png_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";

    // Parse with f=100 (PNG format)
    let params = vec![
        b"G".as_ref(),
        b"a=t,f=100,i=2".as_ref(),
        png_base64.as_bytes(),
    ];

    if let Some(response) = kitty_graphics_protocol::parse(&params, &mut state) {
        if let Some(graphic_data) = response.graphic_data {
            handler.insert_graphic(graphic_data, None, Some(0));
        }
    }

    // Verify PNG was decoded and captured
    assert_eq!(handler.graphics.len(), 1, "Should capture one PNG graphic");

    let graphic = &handler.graphics[0];
    assert_eq!(graphic.width, 1, "PNG should be decoded to 1x1");
    assert_eq!(graphic.height, 1, "PNG should be decoded to 1x1");
    assert_eq!(graphic.id.get(), 2);
    // PNG should be decoded to RGBA pixels
    assert!(
        graphic.pixels.len() >= 4,
        "PNG should decode to at least 4 bytes (RGBA)"
    );
}

#[test]
fn test_png_transmit_and_display() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    // Set proper cell dimensions
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // 1x1 red PNG image
    let png_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";

    // Test a=T (transmit and display) with PNG format
    let params = vec![
        b"G".as_ref(),
        b"a=T,f=100,r=1,C=0,i=10".as_ref(),
        png_base64.as_bytes(),
    ];

    let mut state = KittyGraphicsState::default();
    if let Some(response) = kitty_graphics_protocol::parse(&params, &mut state) {
        if let Some(graphic_data) = response.graphic_data {
            if let Some(placement) = response.placement_request {
                // Store and place the graphic
                term.store_graphic(graphic_data.clone());
                term.place_graphic(placement);
            } else {
                // Direct display without placement request
                term.insert_graphic(graphic_data, None, Some(0));
            }
        }
    }

    let final_row = term.grid.cursor.pos.row.0;

    // For 1-row PNG, cursor should stay on row 0 (last row of image)
    assert_eq!(
        final_row, 0,
        "PNG with r=1 should place cursor on row 0, got row {}",
        final_row
    );
}

#[test]
fn test_png_format_support() {
    let mut handler = TestHandler::default();
    let mut state = KittyGraphicsState::default();

    // Test f=100 (PNG format) with a 1x1 PNG
    let png_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";

    let params = vec![
        b"G".as_ref(),
        b"a=t,f=100,i=100".as_ref(),
        png_base64.as_bytes(),
    ];

    if let Some(response) = kitty_graphics_protocol::parse(&params, &mut state) {
        if let Some(graphic_data) = response.graphic_data {
            handler.insert_graphic(graphic_data, None, Some(0));

            let graphic = &handler.graphics[0];
            assert_eq!(graphic.width, 1, "PNG should decode to 1x1");
            assert_eq!(graphic.height, 1, "PNG should decode to 1x1");
            assert_eq!(graphic.id.get(), 100);
        } else {
            panic!("PNG failed to decode");
        }
    } else {
        panic!("PNG failed to parse");
    }
}

#[test]
fn test_placement_request() {
    let mut handler = TestHandler::default();
    let mut state = KittyGraphicsState::default();

    // Parse placement request (a=p is Put action, x and y are source coordinates)
    let params = vec![b"G".as_ref(), b"a=p,i=1,x=5,y=10,c=3,r=2".as_ref()];

    if let Some(response) = kitty_graphics_protocol::parse(&params, &mut state) {
        if let Some(placement) = response.placement_request {
            handler.place_graphic(placement);
        }
    }

    // Verify placement was captured
    assert_eq!(handler.placements.len(), 1, "Should capture one placement");

    let placement = &handler.placements[0];
    assert_eq!(placement.image_id, 1);
    assert_eq!(placement.x, 5);
    assert_eq!(placement.y, 10);
    assert_eq!(placement.columns, 3);
    assert_eq!(placement.rows, 2);
}

#[test]
fn test_delete_request() {
    let mut handler = TestHandler::default();
    let mut state = KittyGraphicsState::default();

    // Parse delete request (a=d is Delete action, d=a means delete all)
    let params = vec![b"G".as_ref(), b"a=d,d=a".as_ref()];

    if let Some(response) = kitty_graphics_protocol::parse(&params, &mut state) {
        if let Some(delete) = response.delete_request {
            handler.delete_graphics(delete);
        }
    }

    // Verify deletion was captured
    assert_eq!(handler.deletions.len(), 1, "Should capture one deletion");
    assert_eq!(handler.deletions[0].action, b'a');
}

#[test]
fn test_query_response() {
    let mut handler = TestHandler::default();
    let mut state = KittyGraphicsState::default();

    // Parse query request
    let params = vec![b"G".as_ref(), b"a=q,i=1".as_ref()];

    if let Some(response) = kitty_graphics_protocol::parse(&params, &mut state) {
        if let Some(response_str) = response.response {
            handler.kitty_graphics_response(response_str);
        }
    }

    // Verify response was generated
    assert_eq!(handler.responses.len(), 1, "Should generate one response");
    assert!(handler.responses[0].contains("Gi=1;OK"));
}

#[test]
fn test_chunked_transfer() {
    let mut handler = TestHandler::default();
    let mut state = KittyGraphicsState::default();

    // Total base64 for 1x1 RGBA pixel [255, 0, 0, 255] is "/wAA/w==".
    // Each chunk is decoded independently now, so each must be a
    // valid base64 on its own — either a multiple of 4 chars per kitty
    // spec, or an independently padded chunk.

    // Chunk 1 (m=1): 4 chars → 3 decoded bytes [0xFF, 0x00, 0x00]
    let params1 = vec![
        b"G".as_ref(),
        b"a=t,f=32,s=1,v=1,m=1,i=100".as_ref(),
        b"/wAA".as_ref(),
    ];
    let result1 = kitty_graphics_protocol::parse(&params1, &mut state)
        .expect("intermediate chunks must produce a Some response");
    assert!(result1.incomplete);
    assert!(result1.graphic_data.is_none());

    // Chunk 2 (m=0): 4 chars with padding → 1 decoded byte [0xFF]
    let params3 = vec![
        b"G".as_ref(),
        b"a=t,f=32,s=1,v=1,m=0,i=100".as_ref(),
        b"/w==".as_ref(),
    ];
    if let Some(response) = kitty_graphics_protocol::parse(&params3, &mut state) {
        if let Some(graphic_data) = response.graphic_data {
            handler.insert_graphic(graphic_data, None, Some(0));
        }
    }

    // Now graphic should be created
    assert_eq!(handler.graphics.len(), 1);
    assert_eq!(handler.graphics[0].id.get(), 100);
    assert_eq!(handler.graphics[0].width, 1);
    assert_eq!(handler.graphics[0].height, 1);
}

#[test]
fn test_multiple_graphics_in_sequence() {
    let mut handler = TestHandler::default();
    let mut state = KittyGraphicsState::default();

    // Send multiple graphics (1x1 RGBA pixels with different IDs)
    // Base64 for [255, 0, 0, 255] = "/wAA/w=="
    let graphics_params = [
        (
            vec![
                b"G".as_ref(),
                b"a=t,f=32,s=1,v=1,i=1".as_ref(),
                b"/wAA/w==".as_ref(),
            ],
            1u64,
        ),
        (
            vec![
                b"G".as_ref(),
                b"a=t,f=32,s=1,v=1,i=2".as_ref(),
                b"/wAA/w==".as_ref(),
            ],
            2u64,
        ),
        (
            vec![
                b"G".as_ref(),
                b"a=t,f=32,s=1,v=1,i=3".as_ref(),
                b"/wAA/w==".as_ref(),
            ],
            3u64,
        ),
    ];

    for (params, _) in &graphics_params {
        if let Some(response) = kitty_graphics_protocol::parse(params, &mut state) {
            if let Some(graphic_data) = response.graphic_data {
                handler.insert_graphic(graphic_data, None, Some(0));
            }
        }
    }

    // Should have 3 graphics
    assert_eq!(handler.graphics.len(), 3);

    // Verify IDs
    assert_eq!(handler.graphics[0].id.get(), 1);
    assert_eq!(handler.graphics[1].id.get(), 2);
    assert_eq!(handler.graphics[2].id.get(), 3);
}

// Cursor Movement Tests

#[test]
fn test_cursor_movement_default() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    let initial_cursor_row = term.grid.cursor.pos.row.0;

    // Set proper cell dimensions for testing
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Create a 100x100 pixel image (will be resized to fit 2 rows)
    let pixels = vec![255u8; 100 * 100 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 100,
        height: 100,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: Some(ResizeCommand {
            width: ResizeParameter::Auto,
            height: ResizeParameter::Cells(2),
            preserve_aspect_ratio: true,
        }),
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    term.store_graphic(graphic);

    // Place with cursor_movement=0 (move cursor to after image)
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 2,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };

    term.place_graphic(placement);

    let final_cursor_row = term.grid.cursor.pos.row.0;
    let final_cursor_col = term.grid.cursor.pos.col.0;

    // With cursor_movement=0 (Kitty default), the cursor ends on the
    // image's last row at the first column after the image, so text
    // printed next never overwrites the image. 2-row image at row 0
    // occupies rows 0-1; r=2 with a 100x100 image in 10x20 cells gives
    // a 40x40 display, i.e. 4 columns.
    assert_eq!(
        final_cursor_row, 1,
        "Cursor should be at row 1 (last row of image) with cursor_movement=0. Initial: {}, Final: {}",
        initial_cursor_row,
        final_cursor_row
    );
    assert_eq!(
        final_cursor_col, 4,
        "Cursor should be at the first column after the image"
    );
}

#[test]
fn test_cursor_movement_no_move() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    // Set proper cell dimensions for testing
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Start at a specific position
    term.grid.cursor.pos.row.0 = 5;
    term.grid.cursor.pos.col.0 = 10;

    // Create a 100x100 pixel image
    let pixels = vec![255u8; 100 * 100 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(2),
        width: 100,
        height: 100,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: Some(ResizeCommand {
            width: ResizeParameter::Auto,
            height: ResizeParameter::Cells(2),
            preserve_aspect_ratio: true,
        }),
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    term.store_graphic(graphic);

    // Place with cursor_movement=1 (don't move cursor)
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 2,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 2,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 1, // Don't move cursor
        cell_x_offset: 0,
        cell_y_offset: 0,
    };

    term.place_graphic(placement);

    // With cursor_movement=1, cursor behavior depends on placement x,y
    // This test verifies the no-move code path executes without panic
}

#[test]
fn test_protocol_parses_cursor_movement() {
    let mut state = KittyGraphicsState::default();

    // Test that C=0 is parsed
    let result = kitty_graphics_protocol::parse(&[b"G", b"a=p,i=1,C=0", b""], &mut state);
    assert!(result.is_some());
    let response = result.unwrap();
    assert!(response.placement_request.is_some());
    let placement = response.placement_request.unwrap();
    assert_eq!(
        placement.cursor_movement, 0,
        "C=0 should parse as cursor_movement=0"
    );

    // Test that C=1 is parsed
    let result = kitty_graphics_protocol::parse(&[b"G", b"a=p,i=1,C=1", b""], &mut state);
    assert!(result.is_some());
    let response = result.unwrap();
    assert!(response.placement_request.is_some());
    let placement = response.placement_request.unwrap();
    assert_eq!(
        placement.cursor_movement, 1,
        "C=1 should parse as cursor_movement=1"
    );

    // Test default (no C key)
    let result = kitty_graphics_protocol::parse(&[b"G", b"a=p,i=1", b""], &mut state);
    assert!(result.is_some());
    let response = result.unwrap();
    assert!(response.placement_request.is_some());
    let placement = response.placement_request.unwrap();
    assert_eq!(
        placement.cursor_movement, 0,
        "Default should be cursor_movement=0"
    );
}

// Row Calculation Tests

#[test]
fn test_image_row_occupation_exact_fit() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    // Start at row 0
    let initial_cursor_row = term.grid.cursor.pos.row.0;
    assert_eq!(initial_cursor_row, 0, "Cursor should start at row 0");

    // Set proper cell dimensions for testing
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Create a 100x100 pixel image (will be resized to fit 2 rows)
    let pixels = vec![255u8; 100 * 100 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 100,
        height: 100,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: Some(ResizeCommand {
            width: ResizeParameter::Auto,
            height: ResizeParameter::Cells(2),
            preserve_aspect_ratio: true,
        }),
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    term.store_graphic(graphic);

    // Place it with rows=2 (should occupy exactly 2 rows)
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 2,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };

    term.place_graphic(placement);

    let final_cursor_row = term.grid.cursor.pos.row.0;

    // With fix: cursor stays ON last row of image (row 1)
    assert_eq!(
        final_cursor_row, 1,
        "Cursor should be at row 1 (last row of image) after placing a 2-row image, but got row {}",
        final_cursor_row
    );
}

#[test]
fn test_subcell_offset_forwarded_and_clamped() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    let pixels = vec![255u8; 40 * 40 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 40,
        height: 40,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    term.store_graphic(graphic);

    // In-range `X=`/`Y=` flows through to the stored placement.
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 7,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 0,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 1,
        cell_x_offset: 7,
        cell_y_offset: 9,
    };
    term.place_graphic(placement);

    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 7))
        .expect("placement stored");
    assert_eq!(stored.cell_x_offset, 7);
    assert_eq!(stored.cell_y_offset, 9);

    // Per kitty spec the offset must be smaller than the cell size.
    // The stored value stays raw (re-clamped at read time so cell
    // size changes don't lose it); span derivation uses the clamp.
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 8,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 0,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 1,
        cell_x_offset: 999,
        cell_y_offset: 999,
    };
    term.place_graphic(placement);

    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 8))
        .expect("placement stored");
    assert_eq!(stored.cell_x_offset, 999, "raw offset is kept");
    assert_eq!(stored.cell_y_offset, 999);
    // 40x40 image, 10x20 cells, offsets clamped to 9/19 for spans.
    assert_eq!(stored.columns, 5, "ceil((40 + 9) / 10)");
    assert_eq!(stored.rows, 3, "ceil((40 + 19) / 20)");
}

#[test]
fn test_subcell_offset_extends_row_occupation() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // 40px tall image on 20px cells: exactly 2 rows without an offset.
    let pixels = vec![255u8; 40 * 40 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 40,
        height: 40,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    term.store_graphic(graphic);

    // `Y=15` shifts the image down within its first cell, so it spills
    // into a third row: ceil((40 + 15) / 20) = 3. Cursor movement and
    // occupation must cover that extra row.
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 7,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 0,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 15,
    };
    term.place_graphic(placement);

    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 7))
        .expect("placement stored");
    assert_eq!(stored.rows, 3, "Y offset spills the image into a 3rd row");
    assert_eq!(stored.columns, 4, "no X offset: 40px / 10px = 4 columns");

    // C=0: cursor lands on the last row of the image (row index rows - 1).
    assert_eq!(
        term.grid.cursor.pos.row.0, 2,
        "cursor advances to the extra row created by the Y offset"
    );
}

#[test]
fn test_image_row_occupation_single_row() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    // Set proper cell dimensions for testing
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    let _initial_cursor_row = term.grid.cursor.pos.row.0;

    // Create a small image that fits in 1 row
    let pixels = vec![255u8; 50 * 20 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(2),
        width: 50,
        height: 20,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: Some(ResizeCommand {
            width: ResizeParameter::Auto,
            height: ResizeParameter::Cells(1),
            preserve_aspect_ratio: true,
        }),
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    term.store_graphic(graphic);

    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 2,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };

    term.place_graphic(placement);

    let final_cursor_row = term.grid.cursor.pos.row.0;

    // With fix: cursor stays ON last row of image (row 0)
    assert_eq!(
        final_cursor_row, 0,
        "Cursor should be at row 0 (last row of image) after placing a 1-row image, but got row {}",
        final_cursor_row
    );
}

#[test]
fn test_image_row_occupation_three_rows() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    let initial_cursor_row = term.grid.cursor.pos.row.0;

    // Set proper cell dimensions for testing
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    let pixels = vec![255u8; 100 * 150 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(3),
        width: 100,
        height: 150,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: Some(ResizeCommand {
            width: ResizeParameter::Auto,
            height: ResizeParameter::Cells(3),
            preserve_aspect_ratio: true,
        }),
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    term.store_graphic(graphic);

    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 3,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 3,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };

    term.place_graphic(placement);

    let final_cursor_row = term.grid.cursor.pos.row.0;

    // With fix: cursor stays ON last row of image (row 2)
    assert_eq!(
        final_cursor_row, 2,
        "Cursor should be at row 2 (last row of image) after placing a 3-row image, but got row {}. \
         Delta from start: {} (expected: 2)",
        final_cursor_row,
        final_cursor_row - initial_cursor_row
    );
}

#[test]
fn test_image_row_occupation_from_middle() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    // Move cursor to row 5
    term.grid.cursor.pos.row.0 = 5;
    let initial_cursor_row = term.grid.cursor.pos.row.0;
    assert_eq!(initial_cursor_row, 5);

    // Set proper cell dimensions for testing
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    let pixels = vec![255u8; 100 * 100 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(4),
        width: 100,
        height: 100,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: Some(ResizeCommand {
            width: ResizeParameter::Auto,
            height: ResizeParameter::Cells(2),
            preserve_aspect_ratio: true,
        }),
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    term.store_graphic(graphic);

    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 4,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 2,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };

    term.place_graphic(placement);

    let final_cursor_row = term.grid.cursor.pos.row.0;

    // With fix: cursor stays ON last row of image (row 6)
    assert_eq!(
        final_cursor_row, 6,
        "Cursor should be at row 6 (last row of image) after placing a 2-row image from row 5, but got row {}",
        final_cursor_row
    );
}

// Delete Tests

#[test]
fn test_delete_all() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    // Delete all graphics (d=a)
    let delete = DeleteRequest {
        action: b'a',
        image_id: 0,
        image_number: 0,
        placement_id: 0,
        x: 0,
        y: 0,
        z_index: 0,
        delete_data: false,
    };

    // Should not panic
    term.delete_graphics(delete);
}

// Placement Management Tests

#[test]
fn test_store_graphic() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    let pixels = vec![255u8, 0, 0, 255]; // 1x1 red pixel
    let graphic = GraphicData {
        id: GraphicId::new(100),
        width: 1,
        height: 1,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    // Store without displaying
    term.store_graphic(graphic);

    // Verify image is in cache
    let stored = term.graphics.get_kitty_image(100);
    assert!(stored.is_some(), "Image should be stored in cache");
    assert_eq!(stored.unwrap().data.width, 1);
}

#[test]
fn test_place_nonexistent_graphic() {
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };

    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );

    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 999, // Doesn't exist
        placement_id: 0,
        x: 5,
        y: 3,
        width: 0,
        height: 0,
        columns: 2,
        rows: 2,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };

    // Should not panic, just warn
    term.place_graphic(placement);
}

// test_delete_by_kitty_image_id and test_delete_by_image_id_does_not_delete_wrong_id
// were removed: kitty images no longer go into grid cells (overlay path only).
// Equivalent tests exist as test_delete_by_image_id_removes_all_placements_for_image
// and test_delete_by_specific_placement_id.

#[test]
fn test_recount_releases_key_exactly_once() {
    let mut graphics = crate::ansi::graphics::Graphics::default();
    let key = crate::sugarloaf::atlas_image_key(99);
    graphics
        .atlas_placements
        .push(crate::ansi::graphics::AtlasPlacement {
            image_key: key,
            abs_row: 0,
            col: 0,
            columns: 2,
            rows: 1,
            src_x: 0,
            src_y: 0,
            src_width: 20,
            src_height: 20,
            total_width: 20,
            total_height: 20,
            insert_cell_w: 10,
            insert_cell_h: 20,
        });
    graphics.recount_atlas_keys();
    assert!(graphics.texture_operations.lock().is_empty());

    // Splitting into two pieces keeps the key alive.
    let p = graphics.atlas_placements.pop().unwrap();
    let mut pieces = Vec::new();
    p.subtract_rect(0, 1, 1, 2, &mut pieces).unwrap();
    graphics.atlas_placements = pieces;
    graphics.recount_atlas_keys();
    assert!(graphics.texture_operations.lock().is_empty());

    // Dropping the last piece queues the removal exactly once.
    graphics.atlas_placements.clear();
    graphics.recount_atlas_keys();
    assert_eq!(graphics.texture_operations.lock().as_slice(), &[key]);
    graphics.recount_atlas_keys();
    assert_eq!(
        graphics.texture_operations.lock().len(),
        1,
        "no double push on repeated recounts"
    );
}

/// 30x40 px graphic at 10x20 cells: 3 columns, 2 rows.
fn atlas_graphic() -> GraphicData {
    GraphicData {
        id: GraphicId::new(0),
        width: 30,
        height: 40,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 30 * 40 * 4],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    }
}

#[test]
fn test_collect_active_ids_from_placements() {
    let mut term = geometry_test_term();
    assert!(term.graphics.collect_active_graphic_ids().is_empty());

    term.insert_graphic(atlas_graphic(), None, Some(1));
    let active = term.graphics.collect_active_graphic_ids();
    assert!(
        active.contains(&1),
        "placed image appears in active ids: {active:?}"
    );

    // Cover it completely with a second image: the first placement is
    // clipped away entirely and stops being active.
    term.grid.cursor.pos = Pos::new(Line(0), Column(0));
    let mut replacement = atlas_graphic();
    replacement.id = GraphicId::new(0);
    term.insert_graphic(replacement, None, Some(1));
    let active = term.graphics.collect_active_graphic_ids();
    assert!(
        !active.contains(&1),
        "fully covered image dropped: {active:?}"
    );
    assert!(active.contains(&2), "the covering image is active");
}

// Overlay placement tests

// test_graphic_id_kitty_vs_sixel_no_collision and test_graphic_id_kitty_different_images
// removed: kitty images no longer use GraphicId. They use u32 image_id directly,
// in a completely separate rendering path from sixel/iTerm2 atlas graphics.

#[test]
fn test_store_kitty_image_increments_generation() {
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();
    let pixels = vec![255u8; 4 * 4 * 4];

    let data1 = GraphicData {
        id: GraphicId::new(1),
        width: 4,
        height: 4,
        color_type: ColorType::Rgba,
        pixels: pixels.clone(),
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, data1);
    let time1 = graphics.get_kitty_image(1).unwrap().transmission_time;

    // Small sleep to ensure different timestamps
    std::thread::sleep(std::time::Duration::from_millis(1));

    let data2 = GraphicData {
        id: GraphicId::new(1),
        width: 4,
        height: 4,
        color_type: ColorType::Rgba,
        pixels: pixels.clone(),
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, data2);
    let time2 = graphics.get_kitty_image(1).unwrap().transmission_time;

    assert!(
        time2 > time1,
        "Transmit time must increase on re-transmission"
    );
}

#[test]
fn test_kitty_placement_insert_and_delete() {
    use crate::ansi::graphics::{Graphics, KittyPlacement};

    let mut graphics = Graphics::default();

    let placement = KittyPlacement {
        image_id: 1,
        placement_id: 0,
        source_x: 0,
        source_y: 0,
        source_width: 0,
        source_height: 0,
        dest_col: 0,
        dest_row: 0,
        columns: 10,
        rows: 5,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: 100,
        pixel_height: 50,
        cell_x_offset: 0,
        cell_y_offset: 0,
        z_index: 0,
        transmit_time: std::time::Instant::now(),
    };

    graphics.kitty_placements.insert((1, 0), placement);
    assert_eq!(graphics.kitty_placements.len(), 1);

    // Delete by image_id
    graphics.kitty_placements.retain(|k, _| k.0 != 1);
    assert_eq!(graphics.kitty_placements.len(), 0);
}

#[test]
fn test_kitty_placement_delete_by_z_index() {
    use crate::ansi::graphics::{Graphics, KittyPlacement};

    let mut graphics = Graphics::default();

    let make_placement = |image_id: u32, z: i32| KittyPlacement {
        image_id,
        placement_id: 0,
        source_x: 0,
        source_y: 0,
        source_width: 0,
        source_height: 0,
        dest_col: 0,
        dest_row: 0,
        columns: 1,
        rows: 1,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: 10,
        pixel_height: 10,
        cell_x_offset: 0,
        cell_y_offset: 0,
        z_index: z,
        transmit_time: std::time::Instant::now(),
    };

    graphics
        .kitty_placements
        .insert((1, 0), make_placement(1, 0));
    graphics
        .kitty_placements
        .insert((2, 0), make_placement(2, -1));
    graphics
        .kitty_placements
        .insert((3, 0), make_placement(3, 0));
    assert_eq!(graphics.kitty_placements.len(), 3);

    // Delete z=0 placements
    graphics.kitty_placements.retain(|_, p| p.z_index != 0);
    assert_eq!(graphics.kitty_placements.len(), 1);
    assert!(graphics.kitty_placements.contains_key(&(2, 0)));
}

#[test]
fn test_collect_active_ids_includes_overlay_placements() {
    use crate::ansi::graphics::{Graphics, KittyPlacement};

    let mut graphics = Graphics::default();

    let placement = KittyPlacement {
        image_id: 42,
        placement_id: 0,
        source_x: 0,
        source_y: 0,
        source_width: 0,
        source_height: 0,
        dest_col: 0,
        dest_row: 0,
        columns: 1,
        rows: 1,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: 10,
        pixel_height: 10,
        cell_x_offset: 0,
        cell_y_offset: 0,
        z_index: 0,
        transmit_time: std::time::Instant::now(),
    };

    graphics.kitty_placements.insert((42, 0), placement);

    let active = graphics.collect_active_graphic_ids();
    assert!(
        active.contains(&42u64),
        "Overlay placements should be counted as active"
    );
}

#[test]
fn test_eviction_removes_dangling_placements() {
    use crate::ansi::graphics::{Graphics, KittyPlacement};

    let mut graphics = Graphics {
        total_limit: 100,
        ..Graphics::default()
    };

    // Add a graphic that will be evicted
    let pixels = vec![255u8; 200]; // 200 bytes, exceeds 100 limit
    let data = GraphicData {
        id: GraphicId::new(1),
        width: 10,
        height: 5,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.pending.push(data);
    graphics.track_graphic(GraphicId::new(1), 200);

    // Add an overlay placement referencing this graphic
    let placement = KittyPlacement {
        image_id: 1,
        placement_id: 0,
        source_x: 0,
        source_y: 0,
        source_width: 0,
        source_height: 0,
        dest_col: 0,
        dest_row: 0,
        columns: 1,
        rows: 1,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: 10,
        pixel_height: 10,
        cell_x_offset: 0,
        cell_y_offset: 0,
        z_index: 0,
        transmit_time: std::time::Instant::now(),
    };
    graphics.kitty_placements.insert((1, 0), placement);

    // Trigger eviction
    let used_ids = std::collections::HashSet::new();
    graphics.evict_images(100, &used_ids);

    // Placement should be removed along with the image
    assert!(
        graphics.kitty_placements.is_empty(),
        "Dangling placements should be removed during eviction"
    );
}

/// Helper to create a KittyPlacement for tests.
fn make_test_placement(
    image_id: u32,
    placement_id: u32,
    dest_col: usize,
    dest_row: i64,
    columns: u32,
    rows: u32,
    z_index: i32,
) -> KittyPlacement {
    KittyPlacement {
        image_id,
        placement_id,
        source_x: 0,
        source_y: 0,
        source_width: 0,
        source_height: 0,
        dest_col,
        dest_row,
        columns,
        rows,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: columns * 10,
        pixel_height: rows * 20,
        cell_x_offset: 0,
        cell_y_offset: 0,
        z_index,
        transmit_time: std::time::Instant::now(),
    }
}

#[test]
fn test_placement_id_zero_creates_multiple() {
    // Test: add placement with zero placement id"
    // When placement_id=0, each insertion should use a unique key
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Insert two placements with placement_id=0 for same image
    // In the real code, the handler auto-assigns unique IDs, but at the
    // data structure level, (image_id, 0) would overwrite. The protocol
    // layer should assign unique placement_ids before inserting.
    let p1 = make_test_placement(1, 0, 0, 0, 5, 3, 0);
    let p2 = make_test_placement(1, 1, 5, 0, 5, 3, 0);

    graphics.kitty_placements.insert((1, 0), p1);
    graphics.kitty_placements.insert((1, 1), p2);

    assert_eq!(graphics.kitty_placements.len(), 2);
}

#[test]
fn test_delete_all_placements_preserves_images() {
    // Kitty test: "test_gr_delete" d=a (lowercase) deletes placements but not images
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Store an image
    let data = GraphicData {
        id: GraphicId::new(1),
        width: 4,
        height: 4,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 64],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, data);

    // Add placements
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));
    graphics
        .kitty_placements
        .insert((1, 1), make_test_placement(1, 1, 5, 0, 5, 3, 0));

    // Delete all placements (lowercase 'a' = keep images)
    graphics.kitty_placements.clear();

    assert_eq!(graphics.kitty_placements.len(), 0, "All placements removed");
    assert!(
        graphics.get_kitty_image(1).is_some(),
        "Image should still exist"
    );
}

#[test]
fn test_delete_all_placements_and_images() {
    // Kitty test: "test_gr_delete" d=A (uppercase) deletes both
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    let data = GraphicData {
        id: GraphicId::new(1),
        width: 4,
        height: 4,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 64],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, data);
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));

    // Uppercase A: delete placements AND images
    graphics.kitty_placements.clear();
    graphics.kitty_images.clear();
    graphics.kitty_image_numbers.clear();

    assert_eq!(graphics.kitty_placements.len(), 0);
    assert!(graphics.get_kitty_image(1).is_none());
}

#[test]
fn test_delete_by_specific_placement_id() {
    // Test: delete placement by specific id"
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));
    graphics
        .kitty_placements
        .insert((1, 1), make_test_placement(1, 1, 5, 0, 5, 3, 0));
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 0, 5, 5, 3, 0));

    assert_eq!(graphics.kitty_placements.len(), 3);

    // Delete specific placement (image_id=1, placement_id=1)
    graphics.kitty_placements.remove(&(1, 1));

    assert_eq!(graphics.kitty_placements.len(), 2);
    assert!(graphics.kitty_placements.contains_key(&(1, 0)));
    assert!(!graphics.kitty_placements.contains_key(&(1, 1)));
    assert!(graphics.kitty_placements.contains_key(&(2, 0)));
}

#[test]
fn test_delete_by_image_id_removes_all_placements_for_image() {
    // Test: delete all placements by image id"
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));
    graphics
        .kitty_placements
        .insert((1, 1), make_test_placement(1, 1, 5, 0, 5, 3, 0));
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 0, 5, 5, 3, 0));

    // Delete all placements for image_id=1
    graphics.kitty_placements.retain(|k, _| k.0 != 1);

    assert_eq!(graphics.kitty_placements.len(), 1);
    assert!(graphics.kitty_placements.contains_key(&(2, 0)));
}

#[test]
fn test_delete_intersecting_cursor() {
    // Test: delete intersecting cursor"
    // Kitty test: "test_gr_delete" d=C
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Place at col=0, row=0, size 5x3
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));
    // Place at col=10, row=10, size 5x3
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 10, 10, 5, 3, 0));

    // Cursor at (2, 1) — intersects placement 1 (col 0..5, row 0..3)
    let cursor_col = 2usize;
    let cursor_abs_row = 1i64;
    graphics.kitty_placements.retain(|_, p| {
        !(p.dest_col <= cursor_col
            && cursor_col < p.dest_col + p.columns as usize
            && p.dest_row <= cursor_abs_row
            && cursor_abs_row < p.dest_row + p.rows as i64)
    });

    assert_eq!(graphics.kitty_placements.len(), 1);
    assert!(graphics.kitty_placements.contains_key(&(2, 0)));
}

#[test]
fn test_delete_intersecting_cursor_hits_multiple() {
    // Test: delete intersecting cursor hits multiple"
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Two overlapping placements at same position
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 10, 10, 0));
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 0, 0, 5, 5, 1));

    let cursor_col = 2usize;
    let cursor_abs_row = 2i64;
    graphics.kitty_placements.retain(|_, p| {
        !(p.dest_col <= cursor_col
            && cursor_col < p.dest_col + p.columns as usize
            && p.dest_row <= cursor_abs_row
            && cursor_abs_row < p.dest_row + p.rows as i64)
    });

    assert_eq!(
        graphics.kitty_placements.len(),
        0,
        "Both overlapping placements should be removed"
    );
}

#[test]
fn test_delete_by_column() {
    // Test: delete by column"
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Placement at col 0, width 5 cells
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));
    // Placement at col 10, width 5 cells
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 10, 0, 5, 3, 0));
    // Placement at col 3, width 2 cells (overlaps column 3)
    graphics
        .kitty_placements
        .insert((3, 0), make_test_placement(3, 0, 3, 5, 2, 1, 0));

    // Delete placements intersecting column 3
    let col = 3usize;
    graphics
        .kitty_placements
        .retain(|_, p| !(p.dest_col <= col && col < p.dest_col + p.columns as usize));

    assert_eq!(graphics.kitty_placements.len(), 1);
    assert!(
        graphics.kitty_placements.contains_key(&(2, 0)),
        "Only placement at col 10 should survive"
    );
}

#[test]
fn test_delete_by_row() {
    // Test: delete by row"
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Placement at row 0, height 3
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));
    // Placement at row 10, height 2
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 0, 10, 5, 2, 0));

    // Delete placements intersecting row 1
    let abs_row = 1i64;
    graphics
        .kitty_placements
        .retain(|_, p| !(p.dest_row <= abs_row && abs_row < p.dest_row + p.rows as i64));

    assert_eq!(graphics.kitty_placements.len(), 1);
    assert!(graphics.kitty_placements.contains_key(&(2, 0)));
}

#[test]
fn test_delete_by_column_1x1() {
    // Test: delete by column 1x1"
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 1, 1, 0));
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 1, 0, 1, 1, 0));
    graphics
        .kitty_placements
        .insert((3, 0), make_test_placement(3, 0, 2, 0, 1, 1, 0));

    // Delete column 1
    let col = 1usize;
    graphics
        .kitty_placements
        .retain(|_, p| !(p.dest_col <= col && col < p.dest_col + p.columns as usize));

    assert_eq!(graphics.kitty_placements.len(), 2);
    assert!(graphics.kitty_placements.contains_key(&(1, 0)));
    assert!(!graphics.kitty_placements.contains_key(&(2, 0)));
    assert!(graphics.kitty_placements.contains_key(&(3, 0)));
}

#[test]
fn test_delete_by_row_1x1() {
    // Test: delete by row 1x1"
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 1, 1, 0));
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 0, 1, 1, 1, 0));
    graphics
        .kitty_placements
        .insert((3, 0), make_test_placement(3, 0, 0, 2, 1, 1, 0));

    // Delete row 1
    let abs_row = 1i64;
    graphics
        .kitty_placements
        .retain(|_, p| !(p.dest_row <= abs_row && abs_row < p.dest_row + p.rows as i64));

    assert_eq!(graphics.kitty_placements.len(), 2);
    assert!(graphics.kitty_placements.contains_key(&(1, 0)));
    assert!(!graphics.kitty_placements.contains_key(&(2, 0)));
    assert!(graphics.kitty_placements.contains_key(&(3, 0)));
}

#[test]
fn test_retransmit_same_image_id_updates_data() {
    // Kitty test: "test_load_images" — re-transmit replaces image data
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    let data1 = GraphicData {
        id: GraphicId::new(1),
        width: 4,
        height: 4,
        color_type: ColorType::Rgba,
        pixels: vec![0u8; 64],
        is_opaque: false,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, data1);
    let time1 = graphics.get_kitty_image(1).unwrap().transmission_time;
    let pixels1 = graphics.get_kitty_image(1).unwrap().data.pixels[0];

    // Re-transmit with different pixel data
    let data2 = GraphicData {
        id: GraphicId::new(1),
        width: 4,
        height: 4,
        color_type: ColorType::Rgba,
        pixels: vec![128u8; 64],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, data2);
    let time2 = graphics.get_kitty_image(1).unwrap().transmission_time;
    let pixels2 = graphics.get_kitty_image(1).unwrap().data.pixels[0];

    assert!(time2 > time1, "Transmit time must increase");
    assert_ne!(pixels1, pixels2, "Pixel data must be replaced");
    assert_eq!(pixels2, 128);
}

#[test]
fn test_image_number_mapping() {
    // Kitty test: "test_gr_operations_with_numbers" — I parameter maps to image_id
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    let data = GraphicData {
        id: GraphicId::new(42),
        width: 2,
        height: 2,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 16],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    // Store with image_number=7
    graphics.store_kitty_image(42, Some(7), data);

    // Lookup by number
    let stored = graphics.get_kitty_image_by_number(7);
    assert!(stored.is_some(), "Should find image by number");
    assert_eq!(stored.unwrap().data.id, GraphicId::new(42));

    // Non-existent number
    assert!(graphics.get_kitty_image_by_number(99).is_none());
}

#[test]
fn test_image_number_remapping_on_retransmit() {
    // Kitty: re-transmitting with same I= gets new image data but same mapping
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    let data1 = GraphicData {
        id: GraphicId::new(1),
        width: 2,
        height: 2,
        color_type: ColorType::Rgba,
        pixels: vec![0u8; 16],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, Some(100), data1);

    // Re-transmit same image_id with same number
    let data2 = GraphicData {
        id: GraphicId::new(1),
        width: 2,
        height: 2,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 16],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, Some(100), data2);

    let stored = graphics.get_kitty_image_by_number(100).unwrap();
    assert_eq!(
        stored.data.pixels[0], 255,
        "Number mapping should point to newest data"
    );
}

#[test]
fn test_placement_source_rect_tracking() {
    // placements track source rectangle for partial image display
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    let mut p = make_test_placement(1, 0, 0, 0, 10, 5, 0);
    p.source_x = 10;
    p.source_y = 20;
    p.source_width = 100;
    p.source_height = 50;

    graphics.kitty_placements.insert((1, 0), p);

    let stored = graphics.kitty_placements.get(&(1, 0)).unwrap();
    assert_eq!(stored.source_x, 10);
    assert_eq!(stored.source_y, 20);
    assert_eq!(stored.source_width, 100);
    assert_eq!(stored.source_height, 50);
}

#[test]
fn test_placement_z_ordering_sort() {
    // placements sorted by z-index for layered rendering
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 10));
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 0, 0, 5, 3, -1));
    graphics
        .kitty_placements
        .insert((3, 0), make_test_placement(3, 0, 0, 0, 5, 3, 0));

    let mut sorted: Vec<_> = graphics.kitty_placements.values().collect();
    sorted.sort_by_key(|p| p.z_index);

    assert_eq!(sorted[0].z_index, -1, "Negative z first");
    assert_eq!(sorted[1].z_index, 0, "Zero z middle");
    assert_eq!(sorted[2].z_index, 10, "Positive z last");
}

#[test]
fn test_delete_kitty_images_cleans_number_mapping() {
    // When images are deleted, number mappings should be cleaned up
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    let data = GraphicData {
        id: GraphicId::new(1),
        width: 2,
        height: 2,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 16],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, Some(7), data);

    assert!(graphics.get_kitty_image_by_number(7).is_some());

    // Delete by predicate
    graphics.delete_kitty_images(|id, _| *id == 1);

    assert!(
        graphics.get_kitty_image_by_number(7).is_none(),
        "Number mapping should be cleaned up when image is deleted"
    );
}

#[test]
fn test_both_columns_and_rows_no_aspect_ratio() {
    // When both c= and r= specified, stretch to fill (no aspect ratio).
    let mut state = KittyGraphicsState::default();

    // 2x2 RGBA = 16 bytes, base64("/////w==" is 4 bytes, need 16 bytes)
    // Use pre-encoded: 16 bytes of 0xFF = "/////////////////////w=="
    let params: Vec<&[u8]> = vec![
        b"G",
        b"a=T,f=32,s=2,v=2,c=80,r=20,i=1",
        b"/////////////////////w==",
    ];

    let response = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(response.is_some());
    let graphic_data = response.unwrap().graphic_data.unwrap();

    assert!(graphic_data.resize.is_some());
    let resize = graphic_data.resize.unwrap();
    assert!(
        !resize.preserve_aspect_ratio,
        "Both c= and r= specified: should NOT preserve aspect ratio"
    );
}

#[test]
fn test_only_columns_preserves_aspect_ratio() {
    // When only c= specified, compute r= from aspect ratio
    let mut state = KittyGraphicsState::default();

    let params: Vec<&[u8]> = vec![
        b"G",
        b"a=T,f=32,s=2,v=2,c=80,i=1",
        b"/////////////////////w==",
    ];

    let response = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(response.is_some());
    let graphic_data = response.unwrap().graphic_data.unwrap();

    let resize = graphic_data.resize.unwrap();
    assert!(
        resize.preserve_aspect_ratio,
        "Only c= specified: should preserve aspect ratio"
    );
}

#[test]
fn test_only_rows_preserves_aspect_ratio() {
    // When only r= specified, compute c= from aspect ratio
    let mut state = KittyGraphicsState::default();

    let params: Vec<&[u8]> = vec![
        b"G",
        b"a=T,f=32,s=2,v=2,r=20,i=1",
        b"/////////////////////w==",
    ];

    let response = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(response.is_some());
    let graphic_data = response.unwrap().graphic_data.unwrap();

    let resize = graphic_data.resize.unwrap();
    assert!(
        resize.preserve_aspect_ratio,
        "Only r= specified: should preserve aspect ratio"
    );
}

#[test]
fn test_delete_by_image_number() {
    // d=n deletes by image number (I= parameter).
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Store image with number mapping
    let data = GraphicData {
        id: GraphicId::new(42),
        width: 2,
        height: 2,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 16],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(42, Some(7), data);
    graphics
        .kitty_placements
        .insert((42, 0), make_test_placement(42, 0, 0, 0, 5, 3, 0));

    // Look up by number
    assert!(graphics.get_kitty_image_by_number(7).is_some());

    // Delete by number (simulate d=n with image_number=7)
    if let Some(&image_id) = graphics.kitty_image_numbers.get(&7) {
        graphics.kitty_placements.retain(|k, _| k.0 != image_id);
    }

    assert_eq!(graphics.kitty_placements.len(), 0);
    // Image still exists (lowercase n = keep data)
    assert!(graphics.get_kitty_image(42).is_some());
}

#[test]
fn test_delete_at_cell_with_z_filter() {
    // d=q deletes at cell position with z-index filter.
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Two placements at same position, different z-index
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));
    graphics
        .kitty_placements
        .insert((2, 0), make_test_placement(2, 0, 0, 0, 5, 3, -1));

    // Delete at (2, 1) with z=0 — should only remove image 1
    let col = 2usize;
    let abs_row = 1i64;
    let z = 0i32;
    graphics.kitty_placements.retain(|_, p| {
        !(p.z_index == z
            && p.dest_col <= col
            && col < p.dest_col + p.columns as usize
            && p.dest_row <= abs_row
            && abs_row < p.dest_row + p.rows as i64)
    });

    assert_eq!(graphics.kitty_placements.len(), 1);
    assert!(graphics.kitty_placements.contains_key(&(2, 0)));
}

#[test]
fn test_delete_by_image_range() {
    // d=r deletes by image ID range.
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));
    graphics
        .kitty_placements
        .insert((5, 0), make_test_placement(5, 0, 5, 0, 5, 3, 0));
    graphics
        .kitty_placements
        .insert((10, 0), make_test_placement(10, 0, 0, 5, 5, 3, 0));

    // Delete range 1..5
    let range_start = 1u32;
    let range_end = 5u32;
    graphics
        .kitty_placements
        .retain(|k, _| k.0 < range_start || k.0 > range_end);

    assert_eq!(graphics.kitty_placements.len(), 1);
    assert!(graphics.kitty_placements.contains_key(&(10, 0)));
}

#[test]
fn test_implicit_id_no_response() {
    // When image_id=0 and image_number=0, no response should be sent
    let mut state = KittyGraphicsState::default();

    // Transmit with no explicit ID
    let params: Vec<&[u8]> = vec![
        b"G",
        b"a=t,f=32,s=1,v=1",
        b"/w==", // 1 byte base64
    ];

    let response = kitty_graphics_protocol::parse(&params, &mut state);
    // Should have graphic data but no response string
    if let Some(resp) = response {
        assert!(
            resp.response.is_none() || resp.response.as_deref() == Some(""),
            "No response should be sent for implicit IDs"
        );
    }
}

// Command parsing tests

#[test]
fn test_parse_transmission_with_format_and_dimensions() {
    // Test: transmission command
    let mut state = KittyGraphicsState::default();
    // 1x1 RGB (3 bytes) base64 = "AAAA"
    let params: Vec<&[u8]> = vec![b"G", b"f=24,s=1,v=1,i=1", b"AAAA"];
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(resp.is_some());
    let data = resp.unwrap().graphic_data;
    assert!(data.is_some());
}

#[test]
fn test_parse_display_command_with_columns_rows() {
    // Test: display command
    let mut state = KittyGraphicsState::default();
    let params: Vec<&[u8]> = vec![b"G", b"a=p,c=80,r=120,i=31", b""];
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(resp.is_some());
    let placement = resp.unwrap().placement_request;
    assert!(placement.is_some());
    let p = placement.unwrap();
    assert_eq!(p.columns, 80);
    assert_eq!(p.rows, 120);
    assert_eq!(p.image_id, 31);
}

#[test]
fn test_parse_delete_command_with_position() {
    // Test: delete command
    let mut state = KittyGraphicsState::default();
    let params: Vec<&[u8]> = vec![b"G", b"a=d,d=p,x=3,y=4", b""];
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(resp.is_some());
    let delete = resp.unwrap().delete_request;
    assert!(delete.is_some());
    let d = delete.unwrap();
    assert_eq!(d.action, b'p');
    assert_eq!(d.x, 3);
    assert_eq!(d.y, 4);
}

#[test]
fn test_parse_ignores_unknown_keys() {
    // Test: ignore unknown keys
    let mut state = KittyGraphicsState::default();
    // 1x1 RGB with unknown key
    let params: Vec<&[u8]> = vec![b"G", b"f=24,s=1,v=1,hello=world,i=1", b"AAAA"];
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    // Should parse successfully despite unknown key
    assert!(resp.is_some());
}

#[test]
fn test_parse_large_negative_z_index() {
    // Test: large negative z-index values
    let mut state = KittyGraphicsState::default();
    let params: Vec<&[u8]> = vec![b"G", b"a=p,z=-2000000000,i=1", b""];
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(resp.is_some());
    let placement = resp.unwrap().placement_request.unwrap();
    assert_eq!(placement.z_index, -2000000000);
}

#[test]
fn test_response_encoding_with_image_id() {
    // Test: response encoding with image id
    let mut state = KittyGraphicsState::default();
    // 1x1 RGBA = 4 bytes, base64 = "/////w=="
    let params: Vec<&[u8]> = vec![b"G", b"a=T,f=32,s=1,v=1,i=4", b"/////w=="];
    let resp = kitty_graphics_protocol::parse(&params, &mut state).unwrap();
    assert!(resp.response.is_some());
    let response_str = resp.response.unwrap();
    assert!(
        response_str.contains("i=4"),
        "Response should contain image id: {}",
        response_str
    );
    assert!(
        response_str.contains("OK"),
        "Response should contain OK: {}",
        response_str
    );
}

#[test]
fn test_response_encoding_with_image_number() {
    // Test: response encoding with image number
    let mut state = KittyGraphicsState::default();
    // 1x1 RGBA = 4 bytes
    let params: Vec<&[u8]> = vec![b"G", b"a=t,f=32,s=1,v=1,I=4", b"/////w=="];
    let resp = kitty_graphics_protocol::parse(&params, &mut state).unwrap();
    assert!(resp.response.is_some());
    let response_str = resp.response.unwrap();
    assert!(
        response_str.contains("I=4"),
        "Response should contain image number: {}",
        response_str
    );
}

#[test]
fn test_default_format_is_rgba() {
    // Test: default format is RGBA
    let mut state = KittyGraphicsState::default();
    // No f= parameter — should default to RGBA (f=32)
    let params: Vec<&[u8]> = vec![
        b"G",
        b"a=t,s=1,v=1,i=1",
        b"/////w==", // 4 bytes = 1x1 RGBA
    ];
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(resp.is_some());
    let data = resp.unwrap().graphic_data;
    assert!(data.is_some(), "Should parse with default RGBA format");
}

#[test]
fn test_delete_range_multiple_variants() {
    // Test: delete range variants
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics::default();

    // Create placements for images 1, 2, 3
    for id in 1..=3u32 {
        graphics
            .kitty_placements
            .insert((id, 0), make_test_placement(id, 0, 0, id as i64, 5, 3, 0));
    }

    // Range delete [1, 2] — should keep image 3
    graphics.kitty_placements.retain(|k, _| k.0 < 1 || k.0 > 2);
    assert_eq!(graphics.kitty_placements.len(), 1);
    assert!(graphics.kitty_placements.contains_key(&(3, 0)));

    // Single-image range [3, 3]
    graphics.kitty_placements.retain(|k, _| k.0 != 3);
    assert_eq!(graphics.kitty_placements.len(), 0);
}

#[test]
fn test_delete_all_preserves_memory_limit() {
    // Test: delete all preserves memory limit
    use crate::ansi::graphics::Graphics;

    let mut graphics = Graphics {
        total_limit: 5000,
        ..Graphics::default()
    };

    let data = GraphicData {
        id: GraphicId::new(1),
        width: 2,
        height: 2,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 16],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, data);
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 3, 0));

    // Delete all
    graphics.kitty_placements.clear();
    graphics.kitty_images.clear();

    assert_eq!(graphics.total_limit, 5000, "Limit should be preserved");
}

#[test]
fn test_chunked_quiet_flag_inheritance() {
    // Chunked transmission: q= on the first chunk must be preserved
    // through the merged command, so subsequent chunks — which only
    // carry `m=` per the kitty spec — still take the original q value.
    //
    // q=1 suppresses OK responses but NOT errors. We test that here by
    // sending a correctly-sized 2x2 RGBA image across two spec-compliant
    // chunks; the OK response must be suppressed.
    let mut state = KittyGraphicsState::default();

    // 2x2 RGBA = 16 bytes. Full base64 = 24 chars with trailing padding.
    // We'll split on a 4-char boundary into chunk1=12 chars, chunk2=12 chars.
    use base64::engine::general_purpose::STANDARD as B64;
    use base64::Engine as _;
    let raw = vec![0xFFu8; 16];
    let encoded = B64.encode(&raw);
    assert_eq!(encoded.len() % 4, 0);
    let (first, second) = encoded.split_at(encoded.len() / 2);
    let (first_bytes, second_bytes) = (first.as_bytes(), second.as_bytes());

    let ctrl1 = "a=t,f=32,s=2,v=2,i=1,m=1,q=1";
    let params1: Vec<&[u8]> = vec![b"G", ctrl1.as_bytes(), first_bytes];
    let resp1 = kitty_graphics_protocol::parse(&params1, &mut state)
        .expect("pending chunk must return Some");
    assert!(resp1.incomplete);

    let ctrl2 = "m=0,i=1";
    let params2: Vec<&[u8]> = vec![b"G", ctrl2.as_bytes(), second_bytes];
    let resp2 = kitty_graphics_protocol::parse(&params2, &mut state)
        .expect("final chunk must return Some");
    // Successful transmission + q=1 inherited from first chunk →
    // the OK response must be suppressed.
    assert!(resp2.graphic_data.is_some(), "image must decode");
    assert!(
        resp2.response.is_none(),
        "q=1 must suppress OK response even after chunk merge: {:?}",
        resp2.response
    );
}

#[test]
fn test_aspect_ratio_with_only_columns() {
    // Test: aspect ratio with only columns
    // A 16:9 image with c=10 should compute height preserving aspect ratio
    use sugarloaf::GraphicData;

    let data = GraphicData {
        id: GraphicId::new(1),
        width: 160,
        height: 90,
        color_type: ColorType::Rgba,
        pixels: vec![],
        is_opaque: true,
        resize: Some(sugarloaf::ResizeCommand {
            width: sugarloaf::ResizeParameter::Cells(10),
            height: sugarloaf::ResizeParameter::Auto,
            preserve_aspect_ratio: true,
        }),
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    let cell_w = 10;
    let cell_h = 20;
    let (w, h) = data.compute_display_dimensions(cell_w, cell_h, 800, 600);

    // Width = 10 cells * 10px = 100px
    assert_eq!(w, 100);
    // Height should preserve 16:9 ratio: 100 * 90/160 = 56.25 ≈ 56
    assert!(h > 50 && h < 60, "Height should be ~56, got {}", h);
}

#[test]
fn test_aspect_ratio_with_only_rows() {
    // Test: aspect ratio with only rows
    use sugarloaf::GraphicData;

    let data = GraphicData {
        id: GraphicId::new(1),
        width: 160,
        height: 90,
        color_type: ColorType::Rgba,
        pixels: vec![],
        is_opaque: true,
        resize: Some(sugarloaf::ResizeCommand {
            width: sugarloaf::ResizeParameter::Auto,
            height: sugarloaf::ResizeParameter::Cells(5),
            preserve_aspect_ratio: true,
        }),
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };

    let cell_w = 10;
    let cell_h = 20;
    let (w, h) = data.compute_display_dimensions(cell_w, cell_h, 800, 600);

    // Height = 5 cells * 20px = 100px
    assert_eq!(h, 100);
    // Width should preserve 16:9 ratio: 100 * 160/90 = 177.7 ≈ 178
    assert!(w > 170 && w < 185, "Width should be ~178, got {}", w);
}

// Format conversion tests

#[test]
fn test_grayscale_format_conversion() {
    // Test: gray (1 bpp) to RGBA conversion
    let mut state = KittyGraphicsState::default();
    // 2x1 grayscale: 2 bytes, base64 of [128, 255] = "gP8="
    let params: Vec<&[u8]> = vec![b"G", b"a=t,f=8,s=2,v=1,i=1", b"gP8="];
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(resp.is_some());
    let data = resp.unwrap().graphic_data.unwrap();
    assert_eq!(data.pixels.len(), 8); // 2 pixels * 4 bytes RGBA
                                      // First pixel: gray=128 → [128, 128, 128, 255]
    assert_eq!(data.pixels[0], 128);
    assert_eq!(data.pixels[1], 128);
    assert_eq!(data.pixels[2], 128);
    assert_eq!(data.pixels[3], 255);
    // Second pixel: gray=255 → [255, 255, 255, 255]
    assert_eq!(data.pixels[4], 255);
    assert_eq!(data.pixels[7], 255);
}

#[test]
fn test_gray_alpha_format_conversion() {
    // Test: gray+alpha (2 bpp) to RGBA conversion
    let mut state = KittyGraphicsState::default();
    // 1x1 gray+alpha: 2 bytes [128, 200], base64 = "gMg="
    let params: Vec<&[u8]> = vec![b"G", b"a=t,f=16,s=1,v=1,i=1", b"gMg="];
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    assert!(resp.is_some());
    let data = resp.unwrap().graphic_data.unwrap();
    assert_eq!(data.pixels.len(), 4); // 1 pixel * 4 bytes RGBA
                                      // gray=128, alpha=200 → [128, 128, 128, 200]
    assert_eq!(data.pixels[0], 128);
    assert_eq!(data.pixels[1], 128);
    assert_eq!(data.pixels[2], 128);
    assert_eq!(data.pixels[3], 200);
    assert!(!data.is_opaque); // alpha != 255
}

// Free-data deletion bug regression tests.
//
// The parser lowercases `delete_action` and stores the original case in
// `delete_data: bool`. The dispatcher used to check
// `delete.action == b'I'` etc., which was always false because the parser
// already normalized to lowercase, so the uppercase free-data variants
// silently leaked image bytes. These tests pin the fix.

fn make_test_term() -> Crosswords<TestEventListener> {
    Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        TestEventListener,
        unsafe { WindowId::dummy() },
        0,
        10_000,
    )
}

fn store_red_pixel(term: &mut Crosswords<TestEventListener>, image_id: u32) {
    let graphic = GraphicData {
        id: GraphicId::new(image_id as u64),
        width: 1,
        height: 1,
        color_type: ColorType::Rgba,
        pixels: vec![255, 0, 0, 255],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    term.store_graphic(graphic);
}

#[test]
fn test_delete_uppercase_i_actually_frees_image_data() {
    // Regression: d=I (uppercase) must remove the stored image, not just
    // its placements. Pre-fix the dispatcher checked `delete.action == b'I'`
    // which was always false, so the image cache leaked.
    let mut term = make_test_term();
    store_red_pixel(&mut term, 7);
    assert!(term.graphics.get_kitty_image(7).is_some());

    // Parser path: d=I sets delete_action='I', then is normalized to
    // lowercase 'i' with delete_data=true.
    let mut state = KittyGraphicsState::default();
    let params = vec![b"G".as_ref(), b"a=d,d=I,i=7"];
    let resp = kitty_graphics_protocol::parse(&params, &mut state).unwrap();
    let delete = resp.delete_request.expect("expected DeleteRequest");
    assert_eq!(delete.action, b'i');
    assert!(delete.delete_data, "uppercase I must set delete_data");

    term.delete_graphics(delete);

    assert!(
        term.graphics.get_kitty_image(7).is_none(),
        "d=I must free image data — the dispatcher should rely on \
         delete.delete_data, not on a dead `action == b'I'` check"
    );
}

#[test]
fn test_delete_uppercase_a_clears_all_image_data() {
    let mut term = make_test_term();
    store_red_pixel(&mut term, 1);
    store_red_pixel(&mut term, 2);
    store_red_pixel(&mut term, 3);
    assert_eq!(term.graphics.kitty_images.len(), 3);

    let delete = DeleteRequest {
        action: b'a',
        image_id: 0,
        image_number: 0,
        placement_id: 0,
        x: 0,
        y: 0,
        z_index: 0,
        delete_data: true, // simulating d=A
    };
    term.delete_graphics(delete);

    assert!(
        term.graphics.kitty_images.is_empty(),
        "d=A must clear all image data, not just placements"
    );
    assert!(term.graphics.kitty_image_numbers.is_empty());
}

#[test]
fn test_delete_lowercase_a_keeps_image_data() {
    // Per spec: lowercase deletes placements only, image data stays so a
    // future `a=p` can still place the same image.
    let mut term = make_test_term();
    store_red_pixel(&mut term, 1);

    let delete = DeleteRequest {
        action: b'a',
        image_id: 0,
        image_number: 0,
        placement_id: 0,
        x: 0,
        y: 0,
        z_index: 0,
        delete_data: false, // d=a (lowercase)
    };
    term.delete_graphics(delete);

    assert!(
        term.graphics.get_kitty_image(1).is_some(),
        "Lowercase d=a must keep image data — only placements are removed"
    );
}

#[test]
fn test_delete_uppercase_n_frees_image_via_number() {
    // d=N: delete by image number, free data
    let mut term = make_test_term();
    let graphic = GraphicData {
        id: GraphicId::new(42),
        width: 1,
        height: 1,
        color_type: ColorType::Rgba,
        pixels: vec![255, 0, 0, 255],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    // Store with image_number=9
    term.graphics.store_kitty_image(42, Some(9), graphic);
    assert!(term.graphics.get_kitty_image(42).is_some());
    assert!(term.graphics.get_kitty_image_by_number(9).is_some());

    // d=N with image_id=9 (the parser stores the image *number* into
    // image_id for the d=n/N case via the `i=` key per spec).
    let delete = DeleteRequest {
        action: b'n',
        image_id: 0,
        image_number: 9, // canonical: I= for d=n
        placement_id: 0,
        x: 0,
        y: 0,
        z_index: 0,
        delete_data: true,
    };
    term.delete_graphics(delete);

    assert!(
        term.graphics.get_kitty_image(42).is_none(),
        "d=N must free image data resolved through the number map"
    );
}

#[test]
fn test_delete_uppercase_r_frees_image_range() {
    // d=R deletes a range of image_ids and frees their data.
    let mut term = make_test_term();
    store_red_pixel(&mut term, 1);
    store_red_pixel(&mut term, 5);
    store_red_pixel(&mut term, 10);
    assert_eq!(term.graphics.kitty_images.len(), 3);

    // d=R with x=range_start, y=range_end (inclusive). Source x/y carry
    // these values per the parser's field reuse.
    let delete = DeleteRequest {
        action: b'r',
        image_id: 0,
        image_number: 0,
        placement_id: 0,
        x: 1, // range start
        y: 5, // range end
        z_index: 0,
        delete_data: true,
    };
    term.delete_graphics(delete);

    // Images 1 and 5 should be gone, 10 should remain.
    assert!(term.graphics.get_kitty_image(1).is_none());
    assert!(term.graphics.get_kitty_image(5).is_none());
    assert!(
        term.graphics.get_kitty_image(10).is_some(),
        "Image outside range must survive"
    );
}

// Per-screen kitty graphics state isolation.

#[test]
fn test_swap_alt_isolates_kitty_images() {
    // Per spec: each terminal screen owns its own image cache. After
    // swapping into the alt screen, main-screen images must not be
    // visible, and vice versa.
    let mut term = make_test_term();

    // Store two images on the main screen.
    store_red_pixel(&mut term, 1);
    store_red_pixel(&mut term, 2);
    assert!(term.graphics.get_kitty_image(1).is_some());
    assert!(term.graphics.get_kitty_image(2).is_some());

    // Swap to alt screen.
    term.swap_alt();

    assert!(
        term.graphics.get_kitty_image(1).is_none(),
        "Main-screen image 1 must be hidden after swapping to alt screen"
    );
    assert!(
        term.graphics.get_kitty_image(2).is_none(),
        "Main-screen image 2 must be hidden after swapping to alt screen"
    );

    // Store a different image on the alt screen.
    store_red_pixel(&mut term, 3);
    assert!(term.graphics.get_kitty_image(3).is_some());
    // The main-screen images are still hidden.
    assert!(term.graphics.get_kitty_image(1).is_none());

    // Swap back to main screen.
    term.swap_alt();

    assert!(
        term.graphics.get_kitty_image(1).is_some(),
        "Image 1 must reappear when swapping back to main screen"
    );
    assert!(term.graphics.get_kitty_image(2).is_some());
    assert!(
        term.graphics.get_kitty_image(3).is_none(),
        "Alt-screen image 3 must not leak into main screen"
    );

    // Swap back to alt — image 3 should be there again.
    term.swap_alt();
    assert!(
        term.graphics.get_kitty_image(3).is_some(),
        "Alt-screen image 3 must be preserved across screen swaps"
    );
}

#[test]
fn test_swap_alt_isolates_placements() {
    // Placements are also per-screen — putting a placement on the main
    // screen should not appear on the alt screen.
    let mut term = make_test_term();
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 1,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);
    assert!(
        !term.graphics.kitty_placements.is_empty(),
        "Main-screen placement should be present after place_graphic"
    );

    term.swap_alt();
    assert!(
        term.graphics.kitty_placements.is_empty(),
        "Main-screen placements must not be visible on the alt screen"
    );

    term.swap_alt();
    assert!(
        !term.graphics.kitty_placements.is_empty(),
        "Main-screen placements must reappear after swapping back"
    );
}

#[test]
fn test_swap_alt_isolates_image_numbers() {
    // Image-number mappings (I=) are per-screen too.
    let mut term = make_test_term();
    let g = GraphicData {
        id: GraphicId::new(1),
        width: 1,
        height: 1,
        color_type: ColorType::Rgba,
        pixels: vec![255, 0, 0, 255],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    term.graphics.store_kitty_image(1, Some(50), g);
    assert!(term.graphics.get_kitty_image_by_number(50).is_some());

    term.swap_alt();
    assert!(
        term.graphics.get_kitty_image_by_number(50).is_none(),
        "Image-number mapping must not bleed across screens"
    );

    term.swap_alt();
    assert!(
        term.graphics.get_kitty_image_by_number(50).is_some(),
        "Image-number mapping must come back when we swap to its screen"
    );
}

#[test]
fn test_swap_alt_marks_kitty_dirty() {
    // The renderer relies on the dirty flag to know when to rebuild
    // the overlay layer; swap must set it.
    let mut term = make_test_term();
    term.graphics.kitty_graphics_dirty = false;
    term.swap_alt();
    assert!(
        term.graphics.kitty_graphics_dirty,
        "swap_alt must mark kitty graphics dirty so the renderer rebuilds"
    );
}

#[test]
fn test_full_reset_clears_both_screens() {
    // reset_state should clear images on both main and alt screens.
    let mut term = make_test_term();

    // Image on main screen.
    store_red_pixel(&mut term, 1);
    // Swap to alt and store another image.
    term.swap_alt();
    store_red_pixel(&mut term, 2);
    // Sanity: alt has image 2, not 1.
    assert!(term.graphics.get_kitty_image(2).is_some());
    assert!(term.graphics.get_kitty_image(1).is_none());

    // Full reset.
    term.reset_state();

    // Both screens should be empty.
    assert!(term.graphics.get_kitty_image(1).is_none());
    assert!(term.graphics.get_kitty_image(2).is_none());
    assert!(term.graphics.kitty_inactive_screen.kitty_images.is_empty());
}

// Eviction prefers inactive-screen images.

#[test]
fn test_eviction_prefers_inactive_screen_images() {
    use crate::ansi::graphics::{Graphics, KittyScreenState, StoredImage};

    let mut graphics = Graphics {
        total_limit: 100, // tiny limit so a 60-byte add forces eviction
        ..Graphics::default()
    };

    // Active screen: image 1, 50 bytes, no placement (unused).
    let active_data = GraphicData {
        id: GraphicId::new(1),
        width: 5,
        height: 5,
        color_type: ColorType::Rgba,
        pixels: vec![1u8; 50],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, active_data);

    // Inactive screen: image 2, 50 bytes, no placement either.
    // Pre-load via the inactive_screen field directly so we don't need
    // to drive a swap.
    let inactive_data = GraphicData {
        id: GraphicId::new(2),
        width: 5,
        height: 5,
        color_type: ColorType::Rgba,
        pixels: vec![2u8; 50],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now() - std::time::Duration::from_secs(60),
    };
    graphics.kitty_inactive_screen = KittyScreenState::default();
    graphics.kitty_inactive_screen.kitty_images.insert(
        2,
        StoredImage {
            data: inactive_data,
            transmission_time: std::time::Instant::now()
                - std::time::Duration::from_secs(60),
        },
    );
    // Inactive bytes also count toward total_bytes (kept consistent).
    graphics.total_bytes += 50;

    // Now total_bytes = 100. Adding 60 more would push us to 160 > 100,
    // so eviction must free 60 bytes. The inactive image (50 bytes) is
    // tier 0 and gets evicted first; the active unused image (tier 1)
    // is the next candidate to free the remaining 10 bytes.
    let used = std::collections::HashSet::new();
    let ok = graphics.evict_images(60, &used);
    assert!(ok, "Eviction should free enough");

    assert!(
        !graphics.kitty_inactive_screen.kitty_images.contains_key(&2),
        "Inactive image should be evicted before active images"
    );
}

#[test]
fn test_eviction_keeps_active_used_image_when_inactive_available() {
    use crate::ansi::graphics::{Graphics, KittyScreenState, StoredImage};

    let mut graphics = Graphics {
        total_limit: 100,
        ..Graphics::default()
    };

    // Active screen: image 1 with a *live* placement (used).
    let active = GraphicData {
        id: GraphicId::new(1),
        width: 5,
        height: 5,
        color_type: ColorType::Rgba,
        pixels: vec![1u8; 50],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.store_kitty_image(1, None, active);
    graphics
        .kitty_placements
        .insert((1, 0), make_test_placement(1, 0, 0, 0, 5, 1, 0));

    // Inactive screen: image 2 (older, unused on its screen).
    let inactive = GraphicData {
        id: GraphicId::new(2),
        width: 5,
        height: 5,
        color_type: ColorType::Rgba,
        pixels: vec![2u8; 50],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    graphics.kitty_inactive_screen = KittyScreenState::default();
    graphics.kitty_inactive_screen.kitty_images.insert(
        2,
        StoredImage {
            data: inactive,
            transmission_time: std::time::Instant::now(),
        },
    );
    graphics.total_bytes += 50;

    // active placements protect image 1.
    let mut used = std::collections::HashSet::new();
    used.insert(1u64);

    let ok = graphics.evict_images(50, &used);
    assert!(ok);

    // The active visible image must survive; the inactive image is gone.
    assert!(
        graphics.kitty_images.contains_key(&1),
        "Active visible image must not be evicted while an inactive \
         alternative exists"
    );
    assert!(
        !graphics.kitty_inactive_screen.kitty_images.contains_key(&2),
        "Inactive image should be the eviction target"
    );
}

// kitten icat regression: multiple invocations must not collapse into
// the last image. Reproduces the user-reported issue where running
// `kitten icat` repeatedly only renders the most recent image.

/// Drive a single icat-style transmit+display through the full pipeline.
/// `payload` is a 1x1 RGBA pixel base64 encoded; we vary the colour so
/// each transmission is distinguishable. `with_explicit_id` controls
/// whether we send `i=N` (true) or omit it (false, like icat does).
fn icat_invocation(
    term: &mut Crosswords<TestEventListener>,
    payload: &[u8],
    explicit_id: Option<u32>,
) {
    let control = match explicit_id {
        Some(id) => format!("a=T,f=32,s=1,v=1,i={id}"),
        None => "a=T,f=32,s=1,v=1".to_string(),
    };
    let params = vec![b"G".as_ref(), control.as_bytes(), payload];
    let mut state = std::mem::take(&mut term.graphics.kitty_chunking_state);
    let resp = kitty_graphics_protocol::parse(&params, &mut state);
    term.graphics.kitty_chunking_state = state;
    let resp = resp.expect("transmit+display must produce a response struct");

    if let Some(graphic_data) = resp.graphic_data {
        if let Some(placement) = resp.placement_request {
            term.kitty_transmit_and_display(graphic_data, placement);
        } else {
            term.insert_graphic(graphic_data, None, Some(0));
        }
    }
}

#[test]
fn test_kitten_icat_two_invocations_without_explicit_id_keep_both_images() {
    // The user reported that running `kitten icat` multiple times only
    // renders the last image. icat doesn't always send an `i=` parameter,
    // and prior to this fix Rio's parser left image_id at 0, so every
    // implicit-id transmission collided in `kitty_images[0]` and
    // `kitty_placements[(0, 0)]`. After the fix the parser auto-assigns
    // a unique image_id and the placement layer auto-assigns a unique
    // internal placement_id, so both icat outputs survive.
    let mut term = make_test_term();
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Two distinguishable 1x1 RGBA pixels (red, then green).
    icat_invocation(&mut term, b"/wAA/w==", None); // red
    icat_invocation(&mut term, b"AP8A/w==", None); // green

    assert_eq!(
        term.graphics.kitty_images.len(),
        2,
        "Both icat invocations should produce distinct stored images"
    );
    assert_eq!(
        term.graphics.kitty_placements.len(),
        2,
        "Both icat placements should remain visible — only the last one \
         survived before the fix"
    );
}

#[test]
fn test_kitten_icat_two_invocations_with_same_explicit_id_each_get_unique_placement() {
    // Even when icat reuses the same `i=N` (which kitty itself allows
    // and uses for re-transmission), the *placements* should still be
    // distinct so both copies render. The image data is shared (the
    // second transmission overwrites it per spec) but each placement
    // gets its own internal placement_id.
    let mut term = make_test_term();
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    icat_invocation(&mut term, b"/wAA/w==", Some(1));
    icat_invocation(&mut term, b"/wAA/w==", Some(1));

    // One image (re-transmissions overwrite at same id per spec).
    assert_eq!(term.graphics.kitty_images.len(), 1);
    // Two placements (each `a=T` with implicit p=0 must get its own
    // internal placement_id so the prior placement isn't overwritten).
    assert_eq!(
        term.graphics.kitty_placements.len(),
        2,
        "Two `a=T` calls with the same image_id must produce two \
         placements, not collapse into one"
    );
}

#[test]
fn test_implicit_image_ids_are_distinct() {
    // Two parses with no `i=` should yield two different graphic IDs.
    let mut state = KittyGraphicsState::default();

    let p1 = vec![
        b"G".as_ref(),
        b"a=t,f=32,s=1,v=1".as_ref(),
        b"/wAA/w==".as_ref(),
    ];
    let r1 = kitty_graphics_protocol::parse(&p1, &mut state).unwrap();
    let id1 = r1.graphic_data.unwrap().id.get();

    let p2 = vec![
        b"G".as_ref(),
        b"a=t,f=32,s=1,v=1".as_ref(),
        b"AP8A/w==".as_ref(),
    ];
    let r2 = kitty_graphics_protocol::parse(&p2, &mut state).unwrap();
    let id2 = r2.graphic_data.unwrap().id.get();

    assert_ne!(
        id1, id2,
        "Two implicit-ID transmissions must get distinct allocated IDs"
    );
    assert!(id1 > 0, "Auto-assigned id must be non-zero");
    assert!(id2 > 0, "Auto-assigned id must be non-zero");
}

#[test]
fn test_implicit_image_id_still_suppresses_response() {
    // Per spec: even though we auto-assign an id internally, we must
    // not respond to commands the client transmitted *without* an
    // explicit id (otherwise the client would see a stray APC reply
    // it doesn't know how to interpret).
    let mut state = KittyGraphicsState::default();
    let params = vec![
        b"G".as_ref(),
        b"a=t,f=32,s=1,v=1".as_ref(),
        b"/wAA/w==".as_ref(),
    ];
    let resp = kitty_graphics_protocol::parse(&params, &mut state).unwrap();
    assert!(
        resp.response.is_none() || resp.response.as_deref() == Some(""),
        "Implicit-id transmissions must not produce a response"
    );
}

#[test]
fn test_explicit_image_id_still_responds() {
    // Sanity check that adding implicit-id auto-assignment didn't
    // accidentally suppress responses for explicit-id transmissions.
    let mut state = KittyGraphicsState::default();
    let params = vec![
        b"G".as_ref(),
        b"a=t,f=32,s=1,v=1,i=42".as_ref(),
        b"/wAA/w==".as_ref(),
    ];
    let resp = kitty_graphics_protocol::parse(&params, &mut state).unwrap();
    let body = resp.response.expect("explicit-id response must be present");
    assert!(body.contains("i=42"));
    assert!(body.contains("OK"));
}

// Resize-with-reflow placement tracking.
//
// The user's actual scenario: a long command wraps to 2 lines, an image is
// placed below it, then the window is widened so the command fits on 1 line.
// The image must follow the surrounding text (move up by 1 row when widening,
// down by 1 when narrowing) instead of staying anchored to its absolute
// scrollback row.

#[derive(Debug, Clone, Copy)]
struct ReflowDim {
    columns: usize,
    lines: usize,
}

impl crate::crosswords::grid::Dimensions for ReflowDim {
    fn columns(&self) -> usize {
        self.columns
    }
    fn screen_lines(&self) -> usize {
        self.lines
    }
    fn total_lines(&self) -> usize {
        self.lines
    }
    fn square_width(&self) -> f32 {
        10.0
    }
    fn square_height(&self) -> f32 {
        20.0
    }
}

/// Type a string of ASCII into the terminal so it lands in the grid like
/// real shell input would.
fn type_text(term: &mut Crosswords<TestEventListener>, text: &str) {
    use crate::performer::handler::Handler;
    for c in text.chars() {
        term.input(c);
    }
}

#[test]
fn test_resize_widen_unwraps_command_image_follows() {
    // Reproduce: narrow window where the command wraps to 2 lines, place
    // an image right after the wrap, then widen the window so the command
    // fits on a single line. The image must move *up* by one row to stay
    // pinned to the spot just below the (now shorter) command.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(20, 10),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Type a 32-char command. With columns=20 it wraps onto 2 rows;
    // after we widen to columns=50 it will fit on 1 row.
    type_text(&mut term, "$ kitten icat /path/to/image.png");
    term.linefeed();
    term.carriage_return();

    let cursor_before = term.grid.cursor.pos.row.0;

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 1,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);

    let initial_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .expect("placement must exist")
        .dest_row;
    assert_eq!(
        initial_dest_row,
        term.history_size() as i64 + cursor_before as i64,
        "placement should anchor at the cursor's absolute row"
    );

    // Widen the window. The wrapped command should join back onto a
    // single row, and the image should follow up by 1.
    term.resize(ReflowDim {
        columns: 50,
        lines: 10,
    });

    let final_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .expect("placement must still exist")
        .dest_row;
    assert_eq!(
        final_dest_row,
        initial_dest_row - 1,
        "Widening should drop dest_row by 1 so the image follows the \
         (now unwrapped) command. Got {final_dest_row}, expected {}",
        initial_dest_row - 1
    );
}

#[test]
fn test_resize_narrow_wraps_command_image_follows() {
    // Mirror case: a wide window where the command fits on 1 line.
    // Narrowing the window forces the command onto 2 wrapped rows;
    // the image below it must shift *down* by 1.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(50, 10),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    type_text(&mut term, "$ kitten icat /path/to/image.png");
    term.linefeed();
    term.carriage_return();

    let cursor_before = term.grid.cursor.pos.row.0;

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 1,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);

    let initial_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;
    assert_eq!(
        initial_dest_row,
        term.history_size() as i64 + cursor_before as i64
    );

    // Narrow the window so the command wraps onto two rows.
    term.resize(ReflowDim {
        columns: 20,
        lines: 10,
    });

    let final_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;
    assert_eq!(
        final_dest_row,
        initial_dest_row + 1,
        "Narrowing should bump dest_row by 1 so the image follows the \
         (now wrapped) command down. Got {final_dest_row}, expected {}",
        initial_dest_row + 1
    );
}

/// Print the visible grid contents for debugging.
fn dump_grid(term: &Crosswords<TestEventListener>, label: &str) {
    use crate::crosswords::grid::Dimensions;
    eprintln!("=== {label} ===");
    eprintln!(
        "  cursor.row={}, history={}, columns={}, screen_lines={}",
        term.grid.cursor.pos.row.0,
        term.history_size(),
        Dimensions::columns(&term.grid),
        Dimensions::screen_lines(&term.grid),
    );
    for placement in term.graphics.kitty_placements.values() {
        eprintln!(
            "  placement: image_id={}, dest_row={}, dest_col={}, columns={}, rows={}",
            placement.image_id,
            placement.dest_row,
            placement.dest_col,
            placement.columns,
            placement.rows,
        );
    }
    use crate::crosswords::pos::{Column, Line};
    let lines = Dimensions::screen_lines(&term.grid);
    let cols = Dimensions::columns(&term.grid);
    for r in 0..lines {
        let line = Line(r as i32);
        let mut s = String::new();
        for c in 0..cols {
            let cell = &term.grid[line][Column(c)];
            let ch = cell.c();
            if ch == '\0' || ch == ' ' {
                s.push('.');
            } else {
                s.push(ch);
            }
        }
        eprintln!("  row {:>2}: |{}|", r, s.trim_end_matches('.'));
    }
}

#[test]
fn test_debug_widen_visible_layout() {
    // Mirror of test_debug_narrow_visible_layout: starts NARROW with the
    // command wrapped onto 2 rows, then widens.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(20, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    for _ in 0..18 {
        term.linefeed();
    }
    term.carriage_return();

    type_text(&mut term, "$ kitten icat /path/to/image.png");
    term.linefeed();
    term.carriage_return();

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);

    term.linefeed();
    term.carriage_return();
    type_text(&mut term, "$ ");

    dump_grid(&term, "BEFORE widen");

    term.resize(ReflowDim {
        columns: 50,
        lines: 24,
    });

    dump_grid(&term, "AFTER widen");
}

#[test]
fn test_debug_narrow_visible_layout() {
    // Print visible layout before/after narrowing to understand what
    // shrink_columns actually does to cursor and content positioning.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(50, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    for _ in 0..20 {
        term.linefeed();
    }
    term.carriage_return();

    type_text(&mut term, "$ kitten icat /path/to/image.png");
    term.linefeed();
    term.carriage_return();

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);

    term.linefeed();
    term.carriage_return();
    type_text(&mut term, "$ ");

    dump_grid(&term, "BEFORE narrow");

    term.resize(ReflowDim {
        columns: 20,
        lines: 24,
    });

    dump_grid(&term, "AFTER narrow");
}

#[test]
fn test_resize_narrow_combined_col_and_row_change() {
    // Real window resize: user drags the corner, both columns and
    // lines change in the same Crosswords::resize call. Both
    // grow_columns/shrink_columns AND grow_lines/shrink_lines fire.
    // Cursor delta accumulates from both.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(50, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    for _ in 0..10 {
        term.linefeed();
    }
    term.carriage_return();

    type_text(&mut term, "$ kitten icat /path/to/image.png");
    term.linefeed();
    term.carriage_return();

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);

    term.linefeed();
    term.carriage_return();
    type_text(&mut term, "$ ");

    let initial_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    eprintln!(
        "BEFORE combined: cursor.row={}, history={}, dest_row={}",
        term.grid.cursor.pos.row.0,
        term.history_size(),
        initial_dest_row,
    );

    // Narrow + shorten at the same time.
    term.resize(ReflowDim {
        columns: 20,
        lines: 20,
    });

    let final_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    eprintln!(
        "AFTER combined : cursor.row={}, history={}, dest_row={}, delta={}",
        term.grid.cursor.pos.row.0,
        term.history_size(),
        final_dest_row,
        final_dest_row - initial_dest_row,
    );

    // The image should still follow the wrap regardless of the
    // simultaneous row count change.
    // Cursor delta should be (history_grew_by_wrap) +
    // (cursor_row_change_from_shrink_lines + wrap_above_cursor).
    // The exact number depends on how shrink_lines + shrink_columns
    // interact, but the image should track the cursor.
}

#[test]
fn test_resize_narrow_with_multi_row_image() {
    // Realistic icat: a tall image (e.g. 8 rows). The cursor advances
    // by `rows - 1` linefeeds during placement, so the dest_row is
    // *above* the cursor. Then the next prompt sits below the image.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(50, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Push the cursor down to where icat would normally land.
    for _ in 0..10 {
        term.linefeed();
    }
    term.carriage_return();

    type_text(&mut term, "$ kitten icat /path/to/image.png");
    term.linefeed();
    term.carriage_return();

    let placement_row = term.grid.cursor.pos.row.0;

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 8, // 8-row image
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0, // Default: cursor moves to last row of image
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);

    // After place_kitty_overlay with cursor_movement=0, cursor was
    // advanced by rows-1 linefeeds.
    let cursor_after_image = term.grid.cursor.pos.row.0;
    assert!(
        cursor_after_image > placement_row,
        "8-row image should advance cursor below placement_row \
         (placement={placement_row}, cursor_after={cursor_after_image})"
    );

    // Then the next shell prompt.
    term.linefeed();
    term.carriage_return();
    type_text(&mut term, "$ ");

    let initial_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    eprintln!(
        "BEFORE: cursor.row={}, history={}, dest_row={}, placement_row={}",
        term.grid.cursor.pos.row.0,
        term.history_size(),
        initial_dest_row,
        placement_row,
    );

    term.resize(ReflowDim {
        columns: 20,
        lines: 24,
    });

    let final_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    eprintln!(
        "AFTER : cursor.row={}, history={}, dest_row={}, delta={}",
        term.grid.cursor.pos.row.0,
        term.history_size(),
        final_dest_row,
        final_dest_row - initial_dest_row,
    );

    assert_eq!(
        final_dest_row - initial_dest_row,
        1,
        "8-row image should still follow the +1 wrap delta"
    );
}

#[test]
fn test_resize_narrow_with_cursor_at_bottom_of_screen() {
    // Realistic terminal: cursor pinned at the bottom row when icat
    // runs at the prompt. After narrowing, the wrap above the image
    // pushes everything down, but Rio's `shrink_columns` may also
    // scroll to keep the cursor in view, which makes history grow more
    // than 1.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(50, 24),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Push the cursor to near the bottom by linefeeding several times.
    // This simulates a terminal session where some history has been
    // built up before icat runs.
    for _ in 0..20 {
        term.linefeed();
    }
    term.carriage_return();

    // Now run the icat-style sequence.
    type_text(&mut term, "$ kitten icat /path/to/image.png");
    term.linefeed();
    term.carriage_return();

    let placement_row = term.grid.cursor.pos.row.0;
    let placement_history = term.history_size();

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);

    // Then the shell prints its next prompt.
    term.linefeed();
    term.carriage_return();
    type_text(&mut term, "$ ");

    let initial_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    eprintln!(
        "BEFORE RESIZE: cursor.row={}, history={}, placement.dest_row={}, placement_row_at_place={}, history_at_place={}",
        term.grid.cursor.pos.row.0,
        term.history_size(),
        initial_dest_row,
        placement_row,
        placement_history,
    );

    term.resize(ReflowDim {
        columns: 20,
        lines: 24,
    });

    let final_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    eprintln!(
        "AFTER  RESIZE: cursor.row={}, history={}, placement.dest_row={}, delta={}",
        term.grid.cursor.pos.row.0,
        term.history_size(),
        final_dest_row,
        final_dest_row - initial_dest_row,
    );

    // The image is one row below the wrapped command, so wrapping
    // should push it down by 1.
    assert_eq!(
        final_dest_row - initial_dest_row,
        1,
        "Image should follow the wrap-down by exactly 1 row (delta {})",
        final_dest_row - initial_dest_row
    );
}

#[test]
fn test_resize_narrow_with_prompt_after_image() {
    // Realistic icat flow: command on row 0, image at row 1, then the
    // shell prints a new prompt on row 2 below the image. Narrowing
    // the window should wrap row 0 into 2 rows, pushing both the image
    // and the prompt below it down by 1. This is the case the user
    // reported as still broken — content after the image makes the
    // cursor land at a row below the placement, which changes the
    // delta math.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(50, 10),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Row 0: the command (32 chars, fits at columns=50)
    type_text(&mut term, "$ kitten icat /path/to/image.png");
    term.linefeed();
    term.carriage_return();

    // Row 1: this is where the image goes. Place it here.
    let placement_row = term.grid.cursor.pos.row.0;
    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 0, // Default kitty behaviour: cursor stays on the last row of image
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);

    // Then the shell moves to row 2 and prints its prompt.
    term.linefeed();
    term.carriage_return();
    type_text(&mut term, "$ ");

    let cursor_before = term.grid.cursor.pos.row.0;
    assert!(
        cursor_before > placement_row,
        "test setup: cursor should be below the image, got cursor={cursor_before} placement={placement_row}"
    );
    let initial_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    // Narrow: row 0 wraps onto 2 rows.
    term.resize(ReflowDim {
        columns: 20,
        lines: 10,
    });

    let final_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    // The image is anchored to a cell directly below the wrapped row;
    // after the wrap there is one extra row above it, so dest_row
    // should increase by exactly 1.
    assert_eq!(
        final_dest_row - initial_dest_row,
        1,
        "Narrowing with content below the image should still shift the \
         placement down by 1 (got delta {})",
        final_dest_row - initial_dest_row
    );
}

#[test]
fn test_resize_widen_unwraps_sixel_follows() {
    // Sixel analog of the kitty widen test: a wrapped command above a
    // sixel unwraps when the window widens, so the placement must move
    // up by one row with the text, and the resize must mark the
    // overlay dirty so the renderer refreshes its placement snapshot.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(20, 10),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // 32 chars wrap onto 2 rows at columns=20, fit on 1 at columns=50.
    type_text(&mut term, "$ convert image.png sixel:- 1234");
    term.linefeed();
    term.carriage_return();

    term.insert_graphic(atlas_graphic(), None, None);
    let initial_abs_row = term.graphics.atlas_placements[0].abs_row;
    term.graphics.kitty_graphics_dirty = false;

    term.resize(ReflowDim {
        columns: 50,
        lines: 10,
    });

    let final_abs_row = term.graphics.atlas_placements[0].abs_row;
    assert_eq!(
        final_abs_row,
        initial_abs_row - 1,
        "widening should shift the sixel up with the unwrapped command"
    );
    assert!(
        term.graphics.kitty_graphics_dirty,
        "resize with sixel placements must mark the overlay dirty, or \
         the renderer keeps painting from a stale placement snapshot"
    );
}

#[test]
fn test_resize_narrow_wraps_sixel_follows() {
    // Mirror case: the command above the sixel wraps when the window
    // narrows, so the placement must move down by one row.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(50, 10),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    type_text(&mut term, "$ convert image.png sixel:- 1234");
    term.linefeed();
    term.carriage_return();

    term.insert_graphic(atlas_graphic(), None, None);
    let initial_abs_row = term.graphics.atlas_placements[0].abs_row;
    term.graphics.kitty_graphics_dirty = false;

    term.resize(ReflowDim {
        columns: 20,
        lines: 10,
    });

    let final_abs_row = term.graphics.atlas_placements[0].abs_row;
    assert_eq!(
        final_abs_row,
        initial_abs_row + 1,
        "narrowing should shift the sixel down with the wrapped command"
    );
    assert!(term.graphics.kitty_graphics_dirty);
}

#[test]
fn test_resize_widen_sixel_above_wrap_change_stays_put() {
    // A wrapped line BETWEEN the image and the cursor unwraps when the
    // window widens. Only content below the image moved, so the image
    // must stay anchored. A global cursor-derived shift gets this
    // wrong (the cursor moves up, the image does not); the exact
    // reflow row remap keeps it in place.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(20, 10),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // Row 0: short label, no wrap. Rows 1-2: the sixel.
    type_text(&mut term, "img");
    term.linefeed();
    term.carriage_return();
    term.insert_graphic(atlas_graphic(), None, None);
    term.linefeed();
    term.carriage_return();

    // Below the image: 32 chars wrap onto 2 rows at columns=20.
    type_text(&mut term, "$ convert image.png sixel:- 1234");
    term.linefeed();
    term.carriage_return();

    let initial_abs_row = term.graphics.atlas_placements[0].abs_row;
    let cursor_before = term.grid.cursor.pos.row.0;

    term.resize(ReflowDim {
        columns: 50,
        lines: 10,
    });

    assert_eq!(
        term.grid.cursor.pos.row.0,
        cursor_before - 1,
        "test setup: the line below the image should have unwrapped"
    );
    assert_eq!(
        term.graphics.atlas_placements[0].abs_row, initial_abs_row,
        "unwrapping below the image must not move it"
    );
}

#[test]
fn test_resize_widen_kitty_above_wrap_change_stays_put() {
    // Kitty twin of the sixel test above: dest_row goes through the
    // same exact reflow remap.
    use crate::performer::handler::Handler;
    let event_listener = TestEventListener;
    let window_id = unsafe { WindowId::dummy() };
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(20, 10),
        crate::ansi::CursorShape::Block,
        event_listener,
        window_id,
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    type_text(&mut term, "img");
    term.linefeed();
    term.carriage_return();

    store_red_pixel(&mut term, 1);
    let placement = kitty_graphics_protocol::PlacementRequest {
        image_id: 1,
        placement_id: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 1,
        rows: 1,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 1,
        cell_x_offset: 0,
        cell_y_offset: 0,
    };
    term.place_graphic(placement);
    term.linefeed();
    term.carriage_return();

    type_text(&mut term, "$ convert image.png sixel:- 1234");
    term.linefeed();
    term.carriage_return();

    let initial_dest_row = term
        .graphics
        .kitty_placements
        .values()
        .next()
        .unwrap()
        .dest_row;

    term.resize(ReflowDim {
        columns: 50,
        lines: 10,
    });

    assert_eq!(
        term.graphics
            .kitty_placements
            .values()
            .next()
            .unwrap()
            .dest_row,
        initial_dest_row,
        "unwrapping below the image must not move it"
    );
}

// Animation actions surface EINVAL (regression).

#[test]
fn test_animation_action_surfaces_unsupported_response() {
    // Going through the full Crosswords path: a=f should produce a
    // response that the terminal can forward back to the client. Pre-fix
    // this returned None and the client got nothing.
    let mut state = KittyGraphicsState::default();
    let params = vec![
        b"G".as_ref(),
        b"a=f,i=1,r=2,s=1,v=1,f=32".as_ref(),
        b"AAAA".as_ref(),
    ];

    let resp = kitty_graphics_protocol::parse(&params, &mut state)
        .expect("animation actions must produce a response");
    let body = resp
        .response
        .expect("response body must contain EINVAL marker");
    assert!(body.contains("EINVAL:unsupported action"));
    assert!(body.contains("i=1"));
}

// Placement geometry tests

fn geometry_test_term() -> Crosswords<TestEventListener> {
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 24),
        crate::ansi::CursorShape::Block,
        TestEventListener,
        unsafe { WindowId::dummy() },
        0,
        10_000,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 100,
        height: 100,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 100 * 100 * 4],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    term.store_graphic(graphic);
    term
}

fn placement_request(placement_id: u32) -> PlacementRequest {
    PlacementRequest {
        image_id: 1,
        placement_id,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        columns: 0,
        rows: 0,
        z_index: 0,
        virtual_placement: false,
        unicode_placeholder: 0,
        cursor_movement: 1,
        cell_x_offset: 0,
        cell_y_offset: 0,
    }
}

#[test]
fn test_source_crop_keeps_placement_at_cursor() {
    let mut term = geometry_test_term();

    // x=/y= select the source rectangle, never the destination cell.
    let mut placement = placement_request(5);
    placement.x = 30;
    placement.y = 40;
    term.place_graphic(placement);

    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 5))
        .expect("placement stored");
    assert_eq!(stored.dest_col, 0, "placement lands at the cursor column");
    assert_eq!(stored.dest_row, 0, "placement lands at the cursor row");
    assert_eq!(stored.source_x, 30, "crop is stored raw");
    assert_eq!(stored.source_y, 40);
    assert_eq!(stored.source_width, 0, "raw zero means to the edge");
    assert_eq!(stored.source_height, 0);
    assert_eq!(stored.pixel_width, 70, "footprint shows only the crop");
    assert_eq!(stored.pixel_height, 60);
    assert_eq!(stored.columns, 7);
    assert_eq!(stored.rows, 3);
}

#[test]
fn test_source_crop_clamped_and_degenerate_invisible() {
    use crate::ansi::graphics::{kitty_overlay_geometry, OverlayViewport};

    let mut term = geometry_test_term();
    let viewport = OverlayViewport {
        cell_width: 10.0,
        cell_height: 20.0,
        origin_x: 0.0,
        origin_y: 0.0,
        history_size: 0,
        display_offset: 0,
        screen_lines: 24,
    };

    // Crop wider than the image clamps to the edge at render time.
    let mut placement = placement_request(6);
    placement.x = 90;
    placement.width = 50;
    term.place_graphic(placement);

    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 6))
        .expect("placement stored");
    assert_eq!(stored.source_x, 90, "raw request kept");
    assert_eq!(stored.source_width, 50);
    assert_eq!(stored.pixel_width, 10, "footprint uses the clamped crop");
    assert_eq!(stored.pixel_height, 100);
    let geometry = kitty_overlay_geometry(stored, 100, 100, &viewport).expect("visible");
    assert_eq!(geometry.width, 10.0, "clamped to image width");
    assert_eq!(geometry.source_rect, [0.9, 0.0, 1.0, 1.0]);

    // A crop fully outside the image is stored (kitty answers OK) but
    // renders nothing and occupies no cells.
    let mut placement = placement_request(7);
    placement.y = 100;
    placement.cursor_movement = 0;
    let cursor_before = term.grid.cursor.pos;
    term.place_graphic(placement);
    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 7))
        .expect("degenerate placement still stored");
    assert_eq!(stored.columns, 0, "no cell footprint");
    assert_eq!(stored.rows, 0);
    assert!(
        kitty_overlay_geometry(stored, 100, 100, &viewport).is_none(),
        "degenerate crop renders nothing"
    );
    assert_eq!(
        term.grid.cursor.pos, cursor_before,
        "invisible placement leaves the cursor untouched"
    );
}

#[test]
fn test_crop_scaled_to_requested_columns() {
    let mut term = geometry_test_term();

    // 50x25 crop over c=10 columns: width = 10 cells * 10px, height
    // keeps the crop aspect ratio.
    let mut placement = placement_request(8);
    placement.width = 50;
    placement.height = 25;
    placement.columns = 10;
    term.place_graphic(placement);

    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 8))
        .expect("placement stored");
    assert_eq!(stored.pixel_width, 100);
    assert_eq!(stored.pixel_height, 50, "aspect follows the crop");
    assert_eq!(stored.columns, 10);
    assert_eq!(stored.rows, 3, "ceil(50 / 20)");
}

#[test]
fn test_overlay_geometry_scroll_and_pixel_position() {
    use crate::ansi::graphics::{kitty_overlay_geometry, OverlayViewport};

    let placement = KittyPlacement {
        image_id: 1,
        placement_id: 1,
        source_x: 50,
        source_y: 25,
        source_width: 100,
        source_height: 50,
        dest_col: 4,
        dest_row: 55,
        columns: 2,
        rows: 3,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: 25,
        pixel_height: 45,
        cell_x_offset: 3,
        cell_y_offset: 7,
        z_index: 0,
        transmit_time: std::time::Instant::now(),
    };

    let viewport = OverlayViewport {
        cell_width: 10.0,
        cell_height: 20.0,
        origin_x: 100.0,
        origin_y: 50.0,
        history_size: 80,
        display_offset: 30,
        screen_lines: 24,
    };

    // Scrolled back 30 rows into 80 rows of history: the absolute row
    // 55 sits 5 rows below the viewport top (80 - 30).
    let geometry = kitty_overlay_geometry(&placement, 200, 100, &viewport)
        .expect("visible placement");
    assert_eq!(geometry.x, 100.0 + 4.0 * 10.0 + 3.0);
    assert_eq!(geometry.y, 50.0 + 5.0 * 20.0 + 7.0);
    // Display size resolves per frame: no cell span requested, so the
    // 100x50 crop shows at native size.
    assert_eq!(geometry.width, 100.0);
    assert_eq!(geometry.height, 50.0);
    // (origin, end): crop (50, 25)-(150, 75) of a 200x100 image.
    assert_eq!(geometry.source_rect, [0.25, 0.25, 0.75, 0.75]);

    // At the live view (no scroll) the same placement is 25 rows above
    // the viewport and fully culled.
    let live = OverlayViewport {
        display_offset: 0,
        ..viewport
    };
    assert!(kitty_overlay_geometry(&placement, 200, 100, &live).is_none());

    // One row past the bottom edge is culled too.
    let mut below = placement.clone();
    below.dest_row = 80 + 24;
    assert!(kitty_overlay_geometry(&below, 200, 100, &live).is_none());
}

#[test]
fn test_overlay_geometry_partial_visibility_and_full_source() {
    use crate::ansi::graphics::{kitty_overlay_geometry, OverlayViewport};

    let placement = KittyPlacement {
        image_id: 1,
        placement_id: 1,
        source_x: 0,
        source_y: 0,
        source_width: 0,
        source_height: 0,
        dest_col: 0,
        dest_row: 48,
        columns: 2,
        rows: 3,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: 20,
        pixel_height: 60,
        cell_x_offset: 0,
        cell_y_offset: 0,
        z_index: 0,
        transmit_time: std::time::Instant::now(),
    };

    let viewport = OverlayViewport {
        cell_width: 10.0,
        cell_height: 20.0,
        origin_x: 0.0,
        origin_y: 0.0,
        history_size: 50,
        display_offset: 0,
        screen_lines: 24,
    };

    // Two of three rows scrolled off the top: keep the quad with a
    // negative y and let the GPU clip it.
    let geometry = kitty_overlay_geometry(&placement, 20, 60, &viewport)
        .expect("partially visible placement");
    assert_eq!(geometry.y, -40.0);

    // Zero crop falls back to the full texture.
    assert_eq!(geometry.source_rect, [0.0, 0.0, 1.0, 1.0]);
}

#[test]
fn test_rescale_keeps_native_size_and_tracks_cell_span() {
    use crate::ansi::graphics::KittyPlacement;

    // Native-size placement: 25x45 crop, 10x20 cells.
    let mut native = KittyPlacement {
        image_id: 1,
        placement_id: 1,
        source_x: 0,
        source_y: 0,
        source_width: 25,
        source_height: 45,
        dest_col: 0,
        dest_row: 0,
        columns: 3,
        rows: 3,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: 25,
        pixel_height: 45,
        cell_x_offset: 0,
        cell_y_offset: 0,
        z_index: 0,
        transmit_time: std::time::Instant::now(),
    };

    // Font grows to 12x24 cells: the image must NOT stretch to its
    // cell box; only the derived span shrinks.
    native.rescale(25, 45, 12, 24);
    assert_eq!(native.pixel_width, 25, "native pixel size is kept");
    assert_eq!(native.pixel_height, 45);
    assert_eq!(native.columns, 3, "ceil(25 / 12)");
    assert_eq!(native.rows, 2, "ceil(45 / 24)");

    // Cell-sized placement (c=4, r=2) tracks the grid instead.
    let mut cell_sized = KittyPlacement {
        requested_columns: 4,
        requested_rows: 2,
        columns: 4,
        rows: 2,
        pixel_width: 40,
        pixel_height: 40,
        ..native.clone()
    };
    cell_sized.rescale(25, 45, 12, 24);
    assert_eq!(cell_sized.pixel_width, 48);
    assert_eq!(cell_sized.pixel_height, 48);
    assert_eq!(cell_sized.columns, 4);
    assert_eq!(cell_sized.rows, 2);
}

#[test]
fn test_crop_scaled_to_requested_rows_and_both_axes() {
    let mut term = geometry_test_term();

    // r= only: height = 2 cells * 20px, width keeps the crop aspect.
    let mut placement = placement_request(9);
    placement.width = 50;
    placement.height = 25;
    placement.rows = 2;
    term.place_graphic(placement);

    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 9))
        .expect("placement stored");
    assert_eq!(stored.pixel_height, 40);
    assert_eq!(stored.pixel_width, 80, "aspect follows the crop");
    assert_eq!(stored.rows, 2);
    assert_eq!(stored.columns, 8, "ceil(80 / 10)");

    // c= and r= both: exact fit, aspect not preserved.
    let mut placement = placement_request(10);
    placement.width = 50;
    placement.height = 25;
    placement.columns = 3;
    placement.rows = 4;
    term.place_graphic(placement);

    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 10))
        .expect("placement stored");
    assert_eq!(stored.pixel_width, 30);
    assert_eq!(stored.pixel_height, 80, "stretched to the exact span");
    assert_eq!(stored.columns, 3);
    assert_eq!(stored.rows, 4);
}

#[test]
fn test_overlay_geometry_clamps_raw_offsets() {
    use crate::ansi::graphics::{kitty_overlay_geometry, OverlayViewport};

    // Raw offsets larger than the current cell box clamp at read
    // time; the stored value survives cell size changes.
    let placement = KittyPlacement {
        image_id: 1,
        placement_id: 1,
        source_x: 0,
        source_y: 0,
        source_width: 0,
        source_height: 0,
        dest_col: 2,
        dest_row: 0,
        columns: 1,
        rows: 1,
        requested_columns: 0,
        requested_rows: 0,
        pixel_width: 8,
        pixel_height: 8,
        cell_x_offset: 999,
        cell_y_offset: 999,
        z_index: 0,
        transmit_time: std::time::Instant::now(),
    };
    let viewport = OverlayViewport {
        cell_width: 10.0,
        cell_height: 20.0,
        origin_x: 0.0,
        origin_y: 0.0,
        history_size: 0,
        display_offset: 0,
        screen_lines: 24,
    };
    let geometry =
        kitty_overlay_geometry(&placement, 8, 8, &viewport).expect("visible placement");
    assert_eq!(geometry.x, 2.0 * 10.0 + 9.0, "offset clamped to cell box");
    assert_eq!(geometry.y, 19.0);
}

#[test]
fn test_retransmit_reclamps_crop_and_updates_footprint() {
    use crate::ansi::graphics::{kitty_overlay_geometry, OverlayViewport};

    let mut term = geometry_test_term();
    let viewport = OverlayViewport {
        cell_width: 10.0,
        cell_height: 20.0,
        origin_x: 0.0,
        origin_y: 0.0,
        history_size: 0,
        display_offset: 0,
        screen_lines: 24,
    };

    // Crop the bottom half of the 100x100 image.
    let mut placement = placement_request(11);
    placement.y = 50;
    term.place_graphic(placement);

    let stored = term.graphics.kitty_placements.get(&(1, 11)).unwrap();
    assert_eq!(stored.rows, 3, "ceil(50 / 20)");
    let geometry = kitty_overlay_geometry(stored, 100, 100, &viewport).unwrap();
    assert_eq!(geometry.height, 50.0);
    assert_eq!(geometry.source_rect, [0.0, 0.5, 1.0, 1.0]);

    // Retransmit the same id as 100x60: the crop re-resolves against
    // the new dimensions instead of showing a stale region, and the
    // grid footprint follows.
    term.graphics.kitty_graphics_dirty = false;
    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 100,
        height: 60,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 100 * 60 * 4],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    term.store_graphic(graphic);

    let stored = term.graphics.kitty_placements.get(&(1, 11)).unwrap();
    assert_eq!(stored.pixel_height, 10, "60 - 50 remaining below the crop");
    assert_eq!(stored.rows, 1);
    let geometry = kitty_overlay_geometry(stored, 100, 60, &viewport).unwrap();
    assert_eq!(geometry.height, 10.0);
    let [_, v0, _, v1] = geometry.source_rect;
    assert!((v0 - 50.0 / 60.0).abs() < 1e-6);
    assert_eq!(v1, 1.0);

    // The new pixels were dispatched for upload without a re-place
    // (send_graphics_updates drains the queue into an event, so the
    // dirty flag is the observable side).
    assert!(term.graphics.kitty_graphics_dirty);
}

#[test]
fn test_retransmit_can_make_degenerate_placement_visible() {
    let mut term = geometry_test_term();

    // Fully outside the 100x100 image: invisible, zero footprint.
    let mut placement = placement_request(12);
    placement.y = 100;
    term.place_graphic(placement);
    assert_eq!(
        term.graphics.kitty_placements.get(&(1, 12)).unwrap().rows,
        0
    );

    // Retransmit taller: the placement comes alive.
    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 100,
        height: 200,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 100 * 200 * 4],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    term.store_graphic(graphic);

    let stored = term.graphics.kitty_placements.get(&(1, 12)).unwrap();
    assert_eq!(stored.pixel_height, 100, "rows 100..200 of the new image");
    assert_eq!(stored.rows, 5, "ceil(100 / 20)");
}

#[test]
fn test_cursor_movement_scrolls_at_screen_bottom() {
    let mut term = geometry_test_term();

    // Park the cursor on the bottom row.
    for _ in 0..23 {
        term.linefeed();
    }
    assert_eq!(term.grid.cursor.pos.row.0, 23);

    // 100x100 image in 10x20 cells: 5 rows, 10 columns.
    let mut placement = placement_request(13);
    placement.cursor_movement = 0;
    term.place_graphic(placement);

    // The image scrolled into view (5 linefeeds at the bottom) and the
    // cursor sits on its last row, first column after it.
    assert_eq!(term.grid.cursor.pos.row.0, 22);
    assert_eq!(term.grid.cursor.pos.col.0, 10);
    assert_eq!(term.history_size(), 5, "five rows scrolled into history");
}

#[test]
fn test_virtual_run_geometry_honors_source_crop() {
    use crate::ansi::kitty_virtual::{compute_run_geometry, PlaceholderRun};

    let run = PlaceholderRun {
        image_id: 1,
        placement_id: 1,
        row: 0,
        col: 0,
        width: 5,
    };

    // Right half of a 100x50 image (crop 50x50) into a 5x5 cell
    // placement at 10x10 cells: the crop fits the 50x50 box exactly.
    let g = compute_run_geometry(
        &run,
        5,
        5,
        100,
        50,
        (50, 0, 50, 50),
        10.0,
        10.0,
        0.0,
        0.0,
        0,
        0,
    )
    .expect("visible run");
    assert_eq!(g.width, 50.0);
    assert_eq!(g.height, 10.0, "one cell row");
    // u spans the right half of the image; v the top fifth of the crop.
    assert_eq!(g.source_rect, [0.5, 0.0, 1.0, 0.2]);

    // Without a crop the full image aspect-fits with letterboxing;
    // the top run sits entirely in the padding, while the second row
    // maps to the full-image left edge.
    assert!(compute_run_geometry(
        &run,
        5,
        5,
        100,
        50,
        (0, 0, 0, 0),
        10.0,
        10.0,
        0.0,
        0.0,
        0,
        0,
    )
    .is_none());
    let second_row = PlaceholderRun { row: 1, ..run };
    let g = compute_run_geometry(
        &second_row,
        5,
        5,
        100,
        50,
        (0, 0, 0, 0),
        10.0,
        10.0,
        0.0,
        0.0,
        1,
        0,
    )
    .expect("visible run");
    assert_eq!(g.source_rect[0], 0.0, "full-image left edge");
    assert_eq!(g.source_rect[1], 0.0, "crop origin maps to image top");
}

#[test]
fn test_cursor_movement_clears_pending_wrap() {
    let mut term = geometry_test_term();

    // A character printed into the last column arms the wrap flag; a
    // C=0 placement repositions the cursor and must disarm it, or the
    // next printed character wraps below the intended position.
    term.grid.cursor.pos.col = Column(79);
    term.grid.cursor.should_wrap = true;

    let mut placement = placement_request(14);
    placement.cursor_movement = 0;
    term.place_graphic(placement);

    assert!(
        !term.grid.cursor.should_wrap,
        "cursor repositioning discards a pending wrap"
    );
}

#[test]
fn test_transmit_and_display_refreshes_sibling_placements() {
    let mut term = geometry_test_term();

    // Direct placement of the 100x100 image: 5 rows at 20px cells.
    let mut placement = placement_request(15);
    placement.cursor_movement = 1;
    term.place_graphic(placement);
    assert_eq!(
        term.graphics.kitty_placements.get(&(1, 15)).unwrap().rows,
        5
    );

    // a=T retransmit of the same id (new 100x200 pixels + a second
    // placement): the first placement's footprint must follow the new
    // dimensions like the a=t path.
    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 100,
        height: 200,
        color_type: ColorType::Rgba,
        pixels: vec![255u8; 100 * 200 * 4],
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    let mut second = placement_request(16);
    second.cursor_movement = 1;
    term.kitty_transmit_and_display(graphic, second);

    assert_eq!(
        term.graphics.kitty_placements.get(&(1, 15)).unwrap().rows,
        10,
        "sibling placement footprint follows the retransmit"
    );
    assert_eq!(
        term.graphics.kitty_placements.get(&(1, 16)).unwrap().rows,
        10
    );
}

#[test]
fn test_image_key_namespaces_are_disjoint() {
    use crate::sugarloaf::{atlas_image_key, kitty_image_key};

    // kitty clients may pick any u32 image id (kitten icat uses random
    // ones); the atlas namespace must live entirely above that range.
    assert_eq!(kitty_image_key(u32::MAX), u32::MAX as u64);
    assert_eq!(kitty_image_key(0x8000_0001), 0x8000_0001);
    assert!(atlas_image_key(0) > u32::MAX as u64);
    assert_eq!(atlas_image_key(7), (1u64 << 32) + 7);
}

#[test]
fn test_sixel_cursor_lands_on_last_row_start_column() {
    let mut term = geometry_test_term();

    // Start mid-line: the image anchors at the cursor column.
    term.grid.cursor.pos.col = Column(5);
    term.insert_graphic(atlas_graphic(), None, None);

    // DEC STD 070: cursor on the last text row the image touches, at
    // the image's start column (foot, xterm, contour agree).
    assert_eq!(term.grid.cursor.pos.row.0, 1, "last image row");
    assert_eq!(term.grid.cursor.pos.col.0, 5, "image start column");
    assert!(!term.grid.cursor.should_wrap);
}

#[test]
fn test_sixel_mode_8452_cursor_right_of_image() {
    let mut term = geometry_test_term();
    term.set_private_mode(crate::ansi::mode::PrivateMode::Unknown(8452));

    term.grid.cursor.pos.col = Column(5);
    term.insert_graphic(atlas_graphic(), None, None);

    assert_eq!(term.grid.cursor.pos.row.0, 1, "last image row");
    assert_eq!(
        term.grid.cursor.pos.col.0, 8,
        "first column right of the image"
    );
}

#[test]
fn test_sixel_display_mode_leaves_cursor_untouched() {
    let mut term = geometry_test_term();
    // DECSDM set: sixel scrolling disabled, image at page top-left,
    // cursor unmodified.
    term.set_private_mode(crate::ansi::mode::PrivateMode::Unknown(80));

    term.grid.cursor.pos.col = Column(5);
    term.insert_graphic(atlas_graphic(), None, None);

    assert_eq!(term.grid.cursor.pos.row.0, 0);
    assert_eq!(term.grid.cursor.pos.col.0, 5);
}

#[test]
fn test_iterm2_cursor_right_of_image_and_do_not_move() {
    use crate::ansi::iterm2_image_protocol::{CURSOR_DO_NOT_MOVE, CURSOR_RIGHT_OF_IMAGE};

    let mut term = geometry_test_term();
    term.grid.cursor.pos.col = Column(2);
    term.insert_graphic(atlas_graphic(), None, Some(CURSOR_RIGHT_OF_IMAGE));

    // iTerm2 behavior: last image row, first column after the image.
    assert_eq!(term.grid.cursor.pos.row.0, 1);
    assert_eq!(term.grid.cursor.pos.col.0, 5, "right of the 3-cell image");

    // doNotMoveCursor=1 (WezTerm extension): cursor untouched.
    let mut term = geometry_test_term();
    term.grid.cursor.pos.col = Column(2);
    term.insert_graphic(atlas_graphic(), None, Some(CURSOR_DO_NOT_MOVE));
    assert_eq!(term.grid.cursor.pos.row.0, 0);
    assert_eq!(term.grid.cursor.pos.col.0, 2);
}

#[test]
fn test_iterm2_parse_cursor_movement_params() {
    use crate::ansi::iterm2_image_protocol::{
        self, CURSOR_DO_NOT_MOVE, CURSOR_RIGHT_OF_IMAGE,
    };

    const PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";

    let default_params = format!("File=inline=1:{PNG_B64}");
    let params: Vec<&[u8]> = vec![b"1337", default_params.as_bytes()];
    let (_, movement) = iterm2_image_protocol::parse(&params).expect("parses");
    assert_eq!(movement, CURSOR_RIGHT_OF_IMAGE);

    // vte splits OSC params on ';': each key=value arrives separately,
    // with the payload after ':' in the last one.
    let no_move = format!("doNotMoveCursor=1:{PNG_B64}");
    let params: Vec<&[u8]> = vec![b"1337", b"File=inline=1", no_move.as_bytes()];
    let (_, movement) = iterm2_image_protocol::parse(&params).expect("parses");
    assert_eq!(movement, CURSOR_DO_NOT_MOVE);
}

#[test]
fn test_reclaim_cadence_trigger() {
    let mut term = geometry_test_term();
    assert!(!term.grid.extras_table.should_reclaim());

    // Burn through the allocation cadence with throwaway slots.
    for _ in 0..4096 {
        let id = term
            .grid
            .extras_table
            .alloc(crate::crosswords::square::Extras::default());
        term.grid.extras_table.free(id);
    }
    assert!(term.grid.extras_table.should_reclaim(), "cadence elapsed");

    term.grid.reclaim_extras();
    assert!(
        !term.grid.extras_table.should_reclaim(),
        "sweep resets the cadence"
    );
}

#[test]
fn test_kitty_placement_glued_across_ring_saturation_and_expiry() {
    use crate::ansi::graphics::{kitty_overlay_geometry, OverlayViewport};

    // 4-line screen, 3-line scrollback cap.
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 4),
        crate::ansi::CursorShape::Block,
        TestEventListener,
        unsafe { WindowId::dummy() },
        0,
        3,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    // 30x40 image: 2 rows, anchored at absolute row 0.
    let pixels = vec![255u8; 30 * 40 * 4];
    let graphic = GraphicData {
        id: GraphicId::new(1),
        width: 30,
        height: 40,
        color_type: ColorType::Rgba,
        pixels,
        is_opaque: true,
        resize: None,
        display_width: None,
        display_height: None,
        transmit_time: std::time::Instant::now(),
    };
    term.store_graphic(graphic);
    let mut placement = placement_request(20);
    placement.cursor_movement = 1;
    term.place_graphic(placement);
    assert_eq!(
        term.graphics
            .kitty_placements
            .get(&(1, 20))
            .unwrap()
            .dest_row,
        0
    );

    // Fill the screen, then scroll into history up to the cap.
    for _ in 0..6 {
        term.linefeed();
    }
    assert_eq!(term.history_size(), 3);
    assert_eq!(term.lines_evicted(), 0);

    // One more line: the ring is at cap, the oldest row (the image's
    // first) is evicted.
    term.linefeed();
    assert_eq!(term.lines_evicted(), 1);
    let stored = term
        .graphics
        .kitty_placements
        .get(&(1, 20))
        .expect("placement survives while a row remains in the ring");

    // Scrolled fully back: the image's second row is the topmost
    // retained line, so the placement renders one row above the
    // viewport top (negative y, partially visible). Without the
    // absolute base it would drift a full row down.
    let viewport = OverlayViewport {
        cell_width: 10.0,
        cell_height: 20.0,
        origin_x: 0.0,
        origin_y: 0.0,
        history_size: (term.lines_evicted() + term.history_size() as u64) as i64,
        display_offset: term.history_size() as i64,
        screen_lines: 4,
    };
    let geometry =
        kitty_overlay_geometry(stored, 30, 40, &viewport).expect("partially visible");
    assert_eq!(geometry.y, -20.0, "glued: first image row evicted");

    // One more eviction takes the image's last row off the ring: the
    // placement expires like kitty's do.
    term.linefeed();
    assert_eq!(term.lines_evicted(), 2);
    assert!(
        !term.graphics.kitty_placements.contains_key(&(1, 20)),
        "placement expires with its content"
    );
}

#[test]
fn test_atlas_placement_created_on_insert() {
    let mut term = geometry_test_term();
    term.grid.cursor.pos.col = Column(5);
    term.insert_graphic(atlas_graphic(), None, Some(1));

    assert_eq!(term.graphics.atlas_placements.len(), 1);
    let p = &term.graphics.atlas_placements[0];
    assert_eq!(p.image_key, crate::sugarloaf::atlas_image_key(1));
    assert_eq!(p.abs_row, 0);
    assert_eq!(p.col, 5, "anchored at the cursor column");
    assert_eq!((p.columns, p.rows), (3, 2), "30x40 at 10x20 cells");
    assert_eq!(
        (p.src_x, p.src_y, p.src_width, p.src_height),
        (0, 0, 30, 40),
        "initial crop covers the whole display"
    );
    assert_eq!((p.insert_cell_w, p.insert_cell_h), (10, 20));
    assert_eq!(
        term.graphics.atlas_key_refs.get(&p.image_key),
        Some(&1),
        "one placement references the key"
    );
}

#[test]
fn test_atlas_overlay_geometry_scaling_and_scroll() {
    use crate::ansi::graphics::{
        atlas_overlay_geometry, AtlasPlacement, OverlayViewport,
    };

    let placement = AtlasPlacement {
        image_key: 7,
        abs_row: 55,
        col: 4,
        columns: 3,
        rows: 2,
        src_x: 0,
        src_y: 20,
        src_width: 30,
        src_height: 20,
        total_width: 30,
        total_height: 40,
        insert_cell_w: 10,
        insert_cell_h: 20,
    };
    // Scrolled back 30 rows into 80 rows above the screen top.
    let viewport = OverlayViewport {
        cell_width: 12.0,
        cell_height: 24.0,
        origin_x: 100.0,
        origin_y: 50.0,
        history_size: 80,
        display_offset: 30,
        screen_lines: 24,
    };
    let g = atlas_overlay_geometry(&placement, &viewport).expect("visible");
    assert_eq!(g.x, 100.0 + 4.0 * 12.0);
    assert_eq!(g.y, 50.0 + 5.0 * 24.0);
    // Live cells grew 10x20 -> 12x24: display scales with the font.
    assert_eq!(g.width, 30.0 * 1.2);
    assert_eq!(g.height, 20.0 * 1.2);
    // Bottom half of the display space.
    assert_eq!(g.source_rect, [0.0, 0.5, 1.0, 1.0]);

    // Fully above the viewport: culled.
    let live = OverlayViewport {
        display_offset: 0,
        ..viewport
    };
    assert!(atlas_overlay_geometry(&placement, &live).is_none());
}

#[test]
fn test_atlas_placement_expires_off_the_ring() {
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 4),
        crate::ansi::CursorShape::Block,
        TestEventListener,
        unsafe { WindowId::dummy() },
        0,
        2,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    term.insert_graphic(atlas_graphic(), None, Some(1));
    assert_eq!(term.graphics.atlas_placements.len(), 1);

    // Push the image's two rows out of the screen and the 2-line ring.
    for _ in 0..10 {
        term.linefeed();
    }
    assert!(
        term.graphics.atlas_placements.is_empty(),
        "placement expires with its content"
    );
    assert!(
        term.graphics.atlas_key_refs.is_empty(),
        "last placement released the image key"
    );
}

fn test_placement() -> crate::ansi::graphics::AtlasPlacement {
    crate::ansi::graphics::AtlasPlacement {
        image_key: 9,
        abs_row: 10,
        col: 2,
        columns: 4,
        rows: 3,
        src_x: 0,
        src_y: 0,
        src_width: 38,
        src_height: 55,
        total_width: 38,
        total_height: 55,
        insert_cell_w: 10,
        insert_cell_h: 20,
    }
}

#[test]
fn test_subtract_rect_center_hole_yields_four_slices() {
    let p = test_placement();
    let mut out = Vec::new();
    // 1-cell hole at row 11, col 4 (the middle).
    assert!(p.subtract_rect(11, 12, 4, 5, &mut out).is_some());
    assert_eq!(out.len(), 4);

    // Top: full width, row 10.
    assert_eq!(
        (out[0].abs_row, out[0].rows, out[0].col, out[0].columns),
        (10, 1, 2, 4)
    );
    assert_eq!((out[0].src_y, out[0].src_height), (0, 20));
    // Bottom: full width, row 12; keeps the exact partial bottom edge.
    assert_eq!((out[1].abs_row, out[1].rows), (12, 1));
    assert_eq!((out[1].src_y, out[1].src_height), (40, 15));
    // Left: hole row, cols 2..4.
    assert_eq!((out[2].abs_row, out[2].col, out[2].columns), (11, 2, 2));
    assert_eq!(
        (
            out[2].src_x,
            out[2].src_width,
            out[2].src_y,
            out[2].src_height
        ),
        (0, 20, 20, 20)
    );
    // Right: hole row, col 5..6; keeps the exact partial right edge.
    assert_eq!((out[3].abs_row, out[3].col, out[3].columns), (11, 5, 1));
    assert_eq!((out[3].src_x, out[3].src_width), (30, 8));
}

#[test]
fn test_subtract_rect_miss_and_full_cover() {
    let p = test_placement();
    let mut out = Vec::new();
    assert!(p.subtract_rect(0, 5, 0, 100, &mut out).is_none(), "miss");
    assert!(out.is_empty());
    assert!(
        p.subtract_rect(10, 13, 2, 6, &mut out).is_some(),
        "swallowed"
    );
    assert!(out.is_empty(), "no survivors");
}

#[test]
fn test_text_over_image_clips_exactly_that_cell() {
    let mut term = geometry_test_term();
    term.insert_graphic(atlas_graphic(), None, Some(1));
    assert_eq!(term.graphics.atlas_placements.len(), 1);

    // Print into the image's middle cell (row 1, col 1).
    term.grid.cursor.pos = Pos::new(Line(1), Column(1));
    term.write_at_cursor('x');

    // The placement split; no surviving piece covers (1, 1), but the
    // rest of the image is intact.
    let placements = &term.graphics.atlas_placements;
    assert!(placements.len() >= 2, "placement split: {placements:?}");
    let covers = |row: i64, col: usize| {
        placements.iter().any(|p| {
            row >= p.abs_row
                && row < p.abs_row + p.rows as i64
                && col >= p.col
                && col < p.col + p.columns
        })
    };
    assert!(!covers(1, 1), "written cell is clipped out");
    assert!(covers(0, 0) && covers(0, 2) && covers(1, 0) && covers(1, 2));
    assert_eq!(
        term.graphics.atlas_key_refs.values().sum::<u32>() as usize,
        placements.len(),
        "key refs track the split pieces"
    );
}

#[test]
fn test_region_scroll_shifts_and_clips_atlas_placements() {
    let mut term = geometry_test_term();
    // DECSTBM rows 2..10 (1-based 3..10): interior region.
    term.set_scrolling_region(3, Some(10));
    // Image at rows 4-5 inside the region (cursor goto is
    // origin-relative unless DECOM; goto absolute via direct set).
    term.grid.cursor.pos = Pos::new(Line(4), Column(0));
    term.insert_graphic(atlas_graphic(), None, Some(1));
    let before = term.graphics.atlas_placements[0].clone();
    assert_eq!(before.abs_row, 4);

    // Scroll the region up by two lines: content at rows 4-5 moves to
    // rows 2-3, still inside the region.
    term.scroll_up_relative(Line(2), 2);
    let after = &term.graphics.atlas_placements[0];
    assert_eq!(after.abs_row, 2, "image follows region content");
    assert_eq!(after.rows, 2, "fully inside, no clipping yet");

    // Scroll again: the image's top row crosses the region top and is
    // destroyed like text; the bottom row survives at the boundary.
    term.scroll_up_relative(Line(2), 1);
    let after = &term.graphics.atlas_placements[0];
    assert_eq!(after.abs_row, 2, "clipped at the region top");
    assert_eq!(after.rows, 1);
    assert_eq!(after.src_y, 20, "surviving row shows the bottom slice");
}

#[test]
fn test_overlay_clips_to_panel_rect() {
    use crate::ansi::graphics::clip_overlay_to_rect;
    use crate::sugarloaf::GraphicOverlay;

    // The split-pane bug: a 600px-wide image in a panel whose grid
    // ends at x=400 must clip at the divider, showing only the left
    // two-thirds of the texture.
    let mut overlay = GraphicOverlay {
        image_id: 1,
        x: 100.0,
        y: 50.0,
        width: 600.0,
        height: 200.0,
        z_index: -1,
        source_rect: [0.0, 0.0, 1.0, 1.0],
    };
    assert!(clip_overlay_to_rect(
        &mut overlay,
        100.0,
        50.0,
        400.0,
        450.0
    ));
    assert_eq!(overlay.x, 100.0);
    assert_eq!(overlay.width, 300.0, "clipped at the divider");
    assert_eq!(overlay.height, 200.0, "vertical untouched");
    assert_eq!(overlay.source_rect, [0.0, 0.0, 0.5, 1.0]);

    // Fully outside the panel: dropped.
    let mut outside = GraphicOverlay {
        image_id: 1,
        x: 500.0,
        y: 0.0,
        width: 100.0,
        height: 100.0,
        z_index: -1,
        source_rect: [0.0, 0.0, 1.0, 1.0],
    };
    assert!(!clip_overlay_to_rect(&mut outside, 0.0, 0.0, 400.0, 400.0));

    // Partial scroll off the panel top with an existing crop: the
    // source rect shrinks within the crop, not the full texture.
    let mut scrolled = GraphicOverlay {
        image_id: 1,
        x: 0.0,
        y: -50.0,
        width: 100.0,
        height: 100.0,
        z_index: -1,
        source_rect: [0.25, 0.5, 0.75, 1.0],
    };
    assert!(clip_overlay_to_rect(&mut scrolled, 0.0, 0.0, 400.0, 400.0));
    assert_eq!(scrolled.y, 0.0);
    assert_eq!(scrolled.height, 50.0);
    assert_eq!(scrolled.source_rect, [0.25, 0.75, 0.75, 1.0]);
}

/// Guards the split/window-resize contract: at constant font, images
/// keep their cell span (kitty semantics: the protocol has no
/// re-negotiation) and the renderer clips them at the narrowed
/// panel's grid edge instead of painting across a split divider.
#[test]
fn test_narrowing_terminal_keeps_image_span_and_clips_at_edge() {
    use crate::ansi::graphics::{
        clip_overlay_to_rect, kitty_overlay_geometry, OverlayViewport,
    };
    use crate::sugarloaf::GraphicOverlay;

    let mut term = geometry_test_term();

    // Wide kitty placement: c=50, r=2 on the 80-column screen.
    let mut placement = placement_request(30);
    placement.columns = 50;
    placement.rows = 2;
    placement.cursor_movement = 1;
    term.place_graphic(placement);
    let stored = term.graphics.kitty_placements.get(&(1, 30)).unwrap();
    assert_eq!(stored.pixel_width, 500, "50 cells at 10px");

    // Split/narrow: 80 -> 40 columns, same 10x20 cell metrics.
    term.resize(crate::crosswords::CrosswordsSize::new_with_dimensions(
        40, 24, 400, 480, 10, 20,
    ));

    let stored = term.graphics.kitty_placements.get(&(1, 30)).unwrap();
    assert_eq!(
        (stored.columns, stored.pixel_width),
        (50, 500),
        "cell span survives the narrow (font unchanged)"
    );

    // Render side: geometry unchanged, then clipped at the 40-column
    // grid edge, exactly the split-divider case.
    let viewport = OverlayViewport {
        cell_width: 10.0,
        cell_height: 20.0,
        origin_x: 0.0,
        origin_y: 0.0,
        history_size: (term.lines_evicted() + term.history_size() as u64) as i64,
        display_offset: 0,
        screen_lines: 24,
    };
    let geometry = kitty_overlay_geometry(stored, 100, 100, &viewport).unwrap();
    let mut overlay = GraphicOverlay {
        image_id: 1,
        x: geometry.x,
        y: geometry.y,
        width: geometry.width,
        height: geometry.height,
        z_index: 0,
        source_rect: geometry.source_rect,
    };
    assert!(clip_overlay_to_rect(&mut overlay, 0.0, 0.0, 400.0, 480.0));
    assert_eq!(overlay.width, 400.0, "clipped at the new grid edge");
    assert!(
        (overlay.source_rect[2] - 0.8).abs() < 1e-6,
        "shows the left 400/500 of the image: {:?}",
        overlay.source_rect
    );

    // Same contract for a sixel/iTerm2 placement.
    term.grid.cursor.pos = Pos::new(Line(5), Column(0));
    term.insert_graphic(atlas_graphic(), None, Some(1));
    let before = term.graphics.atlas_placements[0].clone();
    term.resize(crate::crosswords::CrosswordsSize::new_with_dimensions(
        20, 24, 200, 480, 10, 20,
    ));
    let after = &term.graphics.atlas_placements[0];
    assert_eq!(
        (after.columns, after.src_width),
        (before.columns, before.src_width),
        "sixel raster is immutable under window resizes"
    );
}

#[test]
fn test_height_grow_keeps_absolute_base_stable() {
    // B1 guard: growing the window height must not advance the
    // absolute row base, since no content leaves the ring.
    let mut term: Crosswords<TestEventListener> = Crosswords::new(
        crate::crosswords::CrosswordsSize::new(80, 4),
        crate::ansi::CursorShape::Block,
        TestEventListener,
        unsafe { WindowId::dummy() },
        0,
        10,
    );
    term.graphics.cell_width = 10.0;
    term.graphics.cell_height = 20.0;

    term.insert_graphic(atlas_graphic(), None, Some(1));
    let anchor = term.graphics.atlas_placements[0].abs_row;

    // Build two lines of history, then grow the window taller.
    for _ in 0..5 {
        term.linefeed();
    }
    assert_eq!(term.history_size(), 2);
    assert_eq!(term.lines_evicted(), 0);
    term.resize(crate::crosswords::CrosswordsSize::new_with_dimensions(
        80, 6, 800, 120, 10, 20,
    ));

    assert_eq!(term.lines_evicted(), 0, "height grow evicts nothing");
    assert_eq!(
        term.graphics.atlas_placements[0].abs_row, anchor,
        "image stays glued to its content"
    );
}

#[test]
fn test_full_reset_clears_atlas_placements() {
    // B2 guard: RIS must not leave sixel/iTerm2 images on screen.
    let mut term = geometry_test_term();
    term.insert_graphic(atlas_graphic(), None, Some(1));
    assert_eq!(term.graphics.atlas_placements.len(), 1);
    let key = term.graphics.atlas_placements[0].image_key;

    term.reset_state();

    assert!(term.graphics.atlas_placements.is_empty());
    assert!(term.graphics.atlas_key_refs.is_empty());
    // The removal was dispatched (queue drained by the update event),
    // so re-queueing the same key must not happen on a later recount.
    term.graphics.recount_atlas_keys();
    assert!(term.graphics.texture_operations.lock().is_empty());
    let _ = key;
}

#[test]
fn test_alt_screen_reentry_drops_stale_placements() {
    // B3 guard: images from a previous alt session must not reappear.
    let mut term = geometry_test_term();

    // Enter alt, draw an image there, leave.
    term.swap_alt();
    term.insert_graphic(atlas_graphic(), None, Some(1));
    assert_eq!(term.graphics.atlas_placements.len(), 1);
    term.swap_alt();
    assert!(
        term.graphics.atlas_placements.is_empty(),
        "main screen has no image"
    );

    // Re-enter alt: the stale placement died with the reset contents.
    term.swap_alt();
    assert!(
        term.graphics.atlas_placements.is_empty(),
        "previous alt session's image does not come back"
    );
    assert!(term.graphics.atlas_key_refs.is_empty());
}