pixelsrc 0.2.0

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

use crate::models::{Composition, VarOr};
use crate::registry::CompositionRegistry;
use crate::variables::VariableRegistry;
use image::{Rgba, RgbaImage};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use thiserror::Error;

// ============================================================================
// Render Context (NC-3)
// ============================================================================

/// Context for rendering operations with caching support.
///
/// The RenderContext stores rendered compositions to avoid redundant rendering
/// when the same composition is referenced multiple times (e.g., in nested
/// compositions or tiled layouts).
///
/// # Example
///
/// ```ignore
/// use pixelsrc::composition::RenderContext;
/// use image::RgbaImage;
///
/// let mut ctx = RenderContext::new();
///
/// // First render - compute and cache
/// if ctx.get_cached("scene").is_none() {
///     let rendered = render_composition(/* ... */);
///     ctx.cache("scene".to_string(), rendered);
/// }
///
/// // Second reference - get from cache
/// let cached = ctx.get_cached("scene").unwrap();
/// ```
#[derive(Debug, Default, Clone)]
pub struct RenderContext {
    /// Cache of rendered compositions by name
    composition_cache: HashMap<String, RgbaImage>,
    /// Stack of composition names currently being rendered (for cycle detection)
    render_stack: Vec<String>,
}

impl RenderContext {
    /// Create a new empty render context.
    pub fn new() -> Self {
        Self { composition_cache: HashMap::new(), render_stack: Vec::new() }
    }

    /// Get a cached rendered composition by name.
    ///
    /// Returns `None` if the composition has not been cached yet.
    pub fn get_cached(&self, name: &str) -> Option<&RgbaImage> {
        self.composition_cache.get(name)
    }

    /// Cache a rendered composition.
    ///
    /// If a composition with the same name was already cached, it will be replaced.
    pub fn cache(&mut self, name: String, image: RgbaImage) {
        self.composition_cache.insert(name, image);
    }

    /// Check if a composition is already cached.
    pub fn is_cached(&self, name: &str) -> bool {
        self.composition_cache.contains_key(name)
    }

    /// Clear all cached compositions.
    pub fn clear(&mut self) {
        self.composition_cache.clear();
    }

    /// Get the number of cached compositions.
    pub fn len(&self) -> usize {
        self.composition_cache.len()
    }

    /// Check if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.composition_cache.is_empty() && self.render_stack.is_empty()
    }

    /// Push a composition onto the render stack.
    ///
    /// Returns `Ok(())` if successful, or `Err(CompositionError::CycleDetected)`
    /// if the composition is already on the stack (indicating a cycle).
    pub fn push(&mut self, name: impl Into<String>) -> Result<(), CompositionError> {
        let name = name.into();
        if self.render_stack.contains(&name) {
            let mut cycle_path: Vec<String> =
                self.render_stack.iter().skip_while(|n| *n != &name).cloned().collect();
            cycle_path.push(name);
            return Err(CompositionError::CycleDetected { cycle_path });
        }
        self.render_stack.push(name);
        Ok(())
    }

    /// Pop a composition from the render stack.
    pub fn pop(&mut self) -> Option<String> {
        self.render_stack.pop()
    }

    /// Check if a composition is currently being rendered.
    pub fn contains(&self, name: &str) -> bool {
        self.render_stack.iter().any(|n| n == name)
    }

    /// Get the current depth of the render stack.
    pub fn depth(&self) -> usize {
        self.render_stack.len()
    }

    /// Get the current render path as a slice.
    pub fn path(&self) -> &[String] {
        &self.render_stack
    }
}

// ============================================================================
// Blend Modes (ATF-10)
// ============================================================================

/// Blend modes for composition layers
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BlendMode {
    /// Standard alpha compositing (source over destination)
    #[default]
    Normal,
    /// Darkens underlying colors: result = base * blend
    Multiply,
    /// Lightens underlying colors: result = 1 - (1 - base) * (1 - blend)
    Screen,
    /// Combines multiply/screen based on base brightness
    Overlay,
    /// Additive blending: result = min(1, base + blend)
    Add,
    /// Subtractive blending: result = max(0, base - blend)
    Subtract,
    /// Color difference: result = abs(base - blend)
    Difference,
    /// Keeps darker color: result = min(base, blend)
    Darken,
    /// Keeps lighter color: result = max(base, blend)
    Lighten,
}

impl BlendMode {
    /// Parse a blend mode from string
    pub fn from_str(s: &str) -> Option<BlendMode> {
        match s.to_lowercase().as_str() {
            "normal" => Some(BlendMode::Normal),
            "multiply" => Some(BlendMode::Multiply),
            "screen" => Some(BlendMode::Screen),
            "overlay" => Some(BlendMode::Overlay),
            "add" | "additive" => Some(BlendMode::Add),
            "subtract" | "subtractive" => Some(BlendMode::Subtract),
            "difference" => Some(BlendMode::Difference),
            "darken" => Some(BlendMode::Darken),
            "lighten" => Some(BlendMode::Lighten),
            _ => None,
        }
    }

    /// Apply blend mode to a single color channel (values are 0.0-1.0)
    fn blend_channel(&self, base: f32, blend: f32) -> f32 {
        match self {
            BlendMode::Normal => blend,
            BlendMode::Multiply => base * blend,
            BlendMode::Screen => 1.0 - (1.0 - base) * (1.0 - blend),
            BlendMode::Overlay => {
                if base < 0.5 {
                    2.0 * base * blend
                } else {
                    1.0 - 2.0 * (1.0 - base) * (1.0 - blend)
                }
            }
            BlendMode::Add => (base + blend).min(1.0),
            BlendMode::Subtract => (base - blend).max(0.0),
            BlendMode::Difference => (base - blend).abs(),
            BlendMode::Darken => base.min(blend),
            BlendMode::Lighten => base.max(blend),
        }
    }
}

// ============================================================================
// CSS Variable Resolution (CSS-9)
// ============================================================================

/// Resolve a blend mode string, potentially containing a var() reference.
///
/// Returns the resolved blend mode and any warning if resolution failed.
pub fn resolve_blend_mode(
    blend: Option<&str>,
    registry: Option<&VariableRegistry>,
) -> (BlendMode, Option<Warning>) {
    let Some(blend_str) = blend else {
        return (BlendMode::Normal, None);
    };

    // Check if it contains var() and we have a registry
    let resolved = if blend_str.contains("var(") {
        if let Some(reg) = registry {
            match reg.resolve(blend_str) {
                Ok(resolved) => resolved,
                Err(e) => {
                    return (
                        BlendMode::Normal,
                        Some(Warning::new(format!(
                            "Failed to resolve blend mode variable '{}': {}, using normal",
                            blend_str, e
                        ))),
                    );
                }
            }
        } else {
            // No registry provided but var() used - warn and use default
            return (
                BlendMode::Normal,
                Some(Warning::new(format!(
                    "Blend mode '{}' contains var() but no variable registry provided, using normal",
                    blend_str
                ))),
            );
        }
    } else {
        blend_str.to_string()
    };

    // Parse the resolved string
    match BlendMode::from_str(&resolved) {
        Some(mode) => (mode, None),
        None => (
            BlendMode::Normal,
            Some(Warning::new(format!("Unknown blend mode '{}', using normal", resolved))),
        ),
    }
}

/// Resolve an opacity value, potentially containing a var() reference.
///
/// Returns the resolved opacity (clamped to 0.0-1.0) and any warning if resolution failed.
pub fn resolve_opacity(
    opacity: Option<&VarOr<f64>>,
    registry: Option<&VariableRegistry>,
) -> (f64, Option<Warning>) {
    let Some(opacity_val) = opacity else {
        return (1.0, None);
    };

    match opacity_val {
        VarOr::Value(v) => (*v, None),
        VarOr::Var(var_str) => {
            if let Some(reg) = registry {
                match reg.resolve(var_str) {
                    Ok(resolved) => {
                        // Try to parse the resolved string as f64
                        match resolved.trim().parse::<f64>() {
                            Ok(v) => (v.clamp(0.0, 1.0), None),
                            Err(_) => (
                                1.0,
                                Some(Warning::new(format!(
                                    "Opacity variable '{}' resolved to '{}' which is not a valid number, using 1.0",
                                    var_str, resolved
                                ))),
                            ),
                        }
                    }
                    Err(e) => (
                        1.0,
                        Some(Warning::new(format!(
                            "Failed to resolve opacity variable '{}': {}, using 1.0",
                            var_str, e
                        ))),
                    ),
                }
            } else {
                (
                    1.0,
                    Some(Warning::new(format!(
                        "Opacity '{}' contains var() but no variable registry provided, using 1.0",
                        var_str
                    ))),
                )
            }
        }
    }
}

/// A warning generated during composition rendering
#[derive(Debug, Clone, PartialEq)]
pub struct Warning {
    pub message: String,
}

impl Warning {
    pub fn new(message: impl Into<String>) -> Self {
        Self { message: message.into() }
    }
}

/// Error when rendering a composition in strict mode.
#[derive(Debug, Clone, PartialEq, Error)]
pub enum CompositionError {
    /// Sprite dimensions exceed cell size
    #[error("Sprite '{sprite_name}' ({sprite_w}x{sprite_h}) exceeds cell size ({cell_w}x{cell_h}) in composition '{composition_name}'", sprite_w = sprite_size.0, sprite_h = sprite_size.1, cell_w = cell_size.0, cell_h = cell_size.1)]
    SizeMismatch {
        sprite_name: String,
        sprite_size: (u32, u32),
        cell_size: (u32, u32),
        composition_name: String,
    },
    /// Canvas size is not divisible by cell_size
    #[error("Size ({size_w}x{size_h}) is not divisible by cell_size ({cell_w}x{cell_h}) in composition '{composition_name}'", size_w = size.0, size_h = size.1, cell_w = cell_size.0, cell_h = cell_size.1)]
    SizeNotDivisible { size: (u32, u32), cell_size: (u32, u32), composition_name: String },
    /// Map dimensions don't match expected grid size
    #[error("Map dimensions ({actual_w}x{actual_h}) don't match expected grid size ({expected_w}x{expected_h}) for {layer_desc} in composition '{composition_name}'", actual_w = actual_dimensions.0, actual_h = actual_dimensions.1, expected_w = expected_dimensions.0, expected_h = expected_dimensions.1, layer_desc = layer_name.as_ref().map(|n| format!("layer '{}'", n)).unwrap_or_else(|| "unnamed layer".to_string()))]
    MapDimensionMismatch {
        layer_name: Option<String>,
        actual_dimensions: (usize, usize),
        expected_dimensions: (u32, u32),
        composition_name: String,
    },
    /// Cycle detected in nested composition references
    #[error("Cycle detected in composition rendering: {}", cycle_path.join(" -> "))]
    CycleDetected {
        /// The composition names forming the cycle (e.g., ["A", "B", "A"])
        cycle_path: Vec<String>,
    },
}

/// Render a composition to an RGBA image buffer.
///
/// Takes a composition and a map of sprite name -> rendered image.
/// Returns the rendered composition and any warnings generated.
///
/// # Basic Rendering (Task 2.1)
///
/// This implementation supports:
/// - Single layer rendering
/// - cell_size [1, 1] (pixel-perfect placement)
/// - Size inference from layers
///
/// # Cell Size Scaling (Task 2.3)
///
/// The `cell_size` field determines how many pixels each grid character represents:
/// - `cell_size: [4, 4]` means each character in the layer map represents a 4x4 pixel area
/// - Sprites are placed at positions calculated as `(col * cell_size[0], row * cell_size[1])`
/// - Sprite top-left aligns to cell top-left
///
/// # Size Inference
///
/// Canvas size is determined by (in order of priority):
/// 1. `composition.size` if explicitly set
/// 2. `composition.base` sprite dimensions (if base is set and found)
/// 3. Inferred from layer maps and cell_size
///
/// # Size Mismatch Handling (Task 2.5)
///
/// When a sprite's dimensions exceed the cell size:
/// - In lenient mode (strict=false): Emits a warning, sprite anchors top-left and overwrites adjacent cells
/// - In strict mode (strict=true): Returns an error
///
/// # Examples
///
/// # CSS Variable Support (CSS-9)
///
/// Layer `blend` and `opacity` properties can use CSS variable syntax:
/// ```json
/// {
///   "blend": "var(--layer-blend)",
///   "opacity": "var(--layer-opacity, 0.8)"
/// }
/// ```
///
/// Pass a `VariableRegistry` to resolve these references before rendering.
///
/// ```ignore
/// use pixelsrc::composition::render_composition;
/// use pixelsrc::models::Composition;
/// use pixelsrc::variables::VariableRegistry;
/// use std::collections::HashMap;
/// use image::RgbaImage;
///
/// let comp = Composition { /* ... */ };
/// let sprites: HashMap<String, RgbaImage> = HashMap::new();
/// let mut registry = VariableRegistry::new();
/// registry.define("--layer-opacity", "0.5");
///
/// // Lenient mode with variable registry
/// let result = render_composition(&comp, &sprites, false, Some(&registry));
/// assert!(result.is_ok());
/// let (image, warnings) = result.unwrap();
/// ```
pub fn render_composition(
    comp: &Composition,
    sprites: &HashMap<String, RgbaImage>,
    strict: bool,
    variables: Option<&VariableRegistry>,
) -> Result<(RgbaImage, Vec<Warning>), CompositionError> {
    let mut warnings = Vec::new();

    // Determine cell size (default to [1, 1])
    let cell_size = comp.cell_size.unwrap_or([1, 1]);

    // Look up base sprite if specified
    let base_sprite = if let Some(ref base_name) = comp.base {
        match sprites.get(base_name) {
            Some(img) => Some(img),
            None => {
                warnings.push(Warning::new(format!(
                    "Base sprite '{}' not found for composition '{}'",
                    base_name, comp.name
                )));
                None
            }
        }
    } else {
        None
    };

    // Determine canvas size with priority:
    // 1. Explicit size
    // 2. Base sprite dimensions
    // 3. Inferred from layers + cell_size
    let (width, height) = if let Some([w, h]) = comp.size {
        (w, h)
    } else if let Some(base_img) = base_sprite {
        // Infer from base sprite dimensions
        (base_img.width(), base_img.height())
    } else {
        // Infer from layers
        let (inferred_w, inferred_h) = infer_size_from_layers(&comp.layers, cell_size);
        if inferred_w == 0 || inferred_h == 0 {
            warnings.push(Warning::new(format!(
                "Could not infer size for composition '{}', using 1x1",
                comp.name
            )));
            (1, 1)
        } else {
            (inferred_w, inferred_h)
        }
    };

    // Validate size is divisible by cell_size (only meaningful when cell_size > [1,1])
    if cell_size[0] > 1 || cell_size[1] > 1 {
        let width_divisible = width % cell_size[0] == 0;
        let height_divisible = height % cell_size[1] == 0;

        if !width_divisible || !height_divisible {
            if strict {
                return Err(CompositionError::SizeNotDivisible {
                    size: (width, height),
                    cell_size: (cell_size[0], cell_size[1]),
                    composition_name: comp.name.clone(),
                });
            } else {
                warnings.push(Warning::new(format!(
                    "Size ({}x{}) is not divisible by cell_size ({}x{}) in composition '{}'",
                    width, height, cell_size[0], cell_size[1], comp.name
                )));
            }
        }
    }

    // Calculate expected grid dimensions for map validation
    let expected_cols = if cell_size[0] > 0 { width / cell_size[0] } else { width };
    let expected_rows = if cell_size[1] > 0 { height / cell_size[1] } else { height };

    // Create canvas (transparent by default)
    let mut canvas = RgbaImage::from_pixel(width, height, Rgba([0, 0, 0, 0]));

    // Render base sprite first if present
    if let Some(base_img) = base_sprite {
        blit_sprite(&mut canvas, base_img, 0, 0);
    }

    // Render each layer (bottom to top)
    for layer in &comp.layers {
        // Parse layer blend mode and opacity with CSS variable resolution (ATF-10, CSS-9)
        let (blend_mode, blend_warning) = resolve_blend_mode(layer.blend.as_deref(), variables);
        if let Some(w) = blend_warning {
            warnings.push(w);
        }

        let (opacity, opacity_warning) = resolve_opacity(layer.opacity.as_ref(), variables);
        if let Some(w) = opacity_warning {
            warnings.push(w);
        }

        if let Some(ref map) = layer.map {
            // Validate map dimensions match expected grid (only when cell_size > [1,1])
            if cell_size[0] > 1 || cell_size[1] > 1 {
                let actual_rows = map.len();
                let actual_cols = map.iter().map(|r| r.chars().count()).max().unwrap_or(0);

                if actual_rows != expected_rows as usize || actual_cols != expected_cols as usize {
                    if strict {
                        return Err(CompositionError::MapDimensionMismatch {
                            layer_name: layer.name.clone(),
                            actual_dimensions: (actual_cols, actual_rows),
                            expected_dimensions: (expected_cols, expected_rows),
                            composition_name: comp.name.clone(),
                        });
                    } else {
                        let layer_desc = layer
                            .name
                            .as_ref()
                            .map(|n| format!("layer '{}'", n))
                            .unwrap_or_else(|| "unnamed layer".to_string());
                        warnings.push(Warning::new(format!(
                            "Map dimensions ({}x{}) don't match expected grid size ({}x{}) for {} in composition '{}'",
                            actual_cols, actual_rows, expected_cols, expected_rows, layer_desc, comp.name
                        )));
                    }
                }
            }

            for (row_idx, row) in map.iter().enumerate() {
                for (col_idx, char_key) in row.chars().enumerate() {
                    let key = char_key.to_string();

                    // Look up sprite name from sprites map
                    let sprite_name = match comp.sprites.get(&key) {
                        Some(Some(name)) => name,
                        Some(None) => continue, // null means transparent/skip
                        None => {
                            warnings.push(Warning::new(format!(
                                "Unknown sprite key '{}' in composition '{}'",
                                key, comp.name
                            )));
                            continue;
                        }
                    };

                    // Get the rendered sprite image
                    let sprite_image = match sprites.get(sprite_name) {
                        Some(img) => img,
                        None => {
                            warnings.push(Warning::new(format!(
                                "Sprite '{}' not found for composition '{}'",
                                sprite_name, comp.name
                            )));
                            continue;
                        }
                    };

                    // Check for size mismatch (Task 2.5)
                    let sprite_width = sprite_image.width();
                    let sprite_height = sprite_image.height();
                    if sprite_width > cell_size[0] || sprite_height > cell_size[1] {
                        if strict {
                            return Err(CompositionError::SizeMismatch {
                                sprite_name: sprite_name.clone(),
                                sprite_size: (sprite_width, sprite_height),
                                cell_size: (cell_size[0], cell_size[1]),
                                composition_name: comp.name.clone(),
                            });
                        } else {
                            warnings.push(Warning::new(format!(
                                "Sprite '{}' ({}x{}) exceeds cell size ({}x{}) in composition '{}', anchoring from top-left",
                                sprite_name, sprite_width, sprite_height, cell_size[0], cell_size[1], comp.name
                            )));
                        }
                    }

                    // Calculate position
                    let x = (col_idx as u32) * cell_size[0];
                    let y = (row_idx as u32) * cell_size[1];

                    // Blit sprite onto canvas with blend mode and opacity (ATF-10)
                    blit_sprite_blended(&mut canvas, sprite_image, x, y, blend_mode, opacity);
                }
            }
        }
    }

    Ok((canvas, warnings))
}

/// Render a composition with support for nested composition references (NC-4).
///
/// This function extends `render_composition` to support compositions that reference
/// other compositions in their sprite maps. When a sprite name is not found in the
/// `sprites` HashMap, the function checks the `composition_registry` for a composition
/// with that name and recursively renders it.
///
/// # Cycle Detection
/// The function uses `RenderContext` to track which compositions are currently being
/// rendered. If a composition attempts to reference itself (directly or indirectly),
/// a `CycleDetected` error is returned.
///
/// # Caching
/// Rendered compositions are cached in the `RenderContext`. When the same composition
/// is referenced multiple times, the cached result is reused.
pub fn render_composition_nested(
    comp: &Composition,
    sprites: &HashMap<String, RgbaImage>,
    composition_registry: Option<&CompositionRegistry>,
    ctx: &mut RenderContext,
    strict: bool,
    variables: Option<&VariableRegistry>,
) -> Result<(RgbaImage, Vec<Warning>), CompositionError> {
    // Push this composition onto the render stack for cycle detection
    ctx.push(&comp.name)?;

    let result =
        render_composition_inner(comp, sprites, composition_registry, ctx, strict, variables);

    // Pop from render stack when done
    ctx.pop();

    result
}

/// Internal implementation of nested composition rendering.
fn render_composition_inner(
    comp: &Composition,
    sprites: &HashMap<String, RgbaImage>,
    composition_registry: Option<&CompositionRegistry>,
    ctx: &mut RenderContext,
    strict: bool,
    variables: Option<&VariableRegistry>,
) -> Result<(RgbaImage, Vec<Warning>), CompositionError> {
    let mut warnings = Vec::new();

    // Determine cell size (default to [1, 1])
    let cell_size = comp.cell_size.unwrap_or([1, 1]);

    // Look up base sprite/composition if specified (NC-4: supports nested compositions)
    let base_image: Option<std::borrow::Cow<'_, RgbaImage>> = if let Some(ref base_name) = comp.base
    {
        if let Some(img) = sprites.get(base_name) {
            Some(std::borrow::Cow::Borrowed(img))
        } else if let Some(reg) = composition_registry {
            if let Some(nested_comp) = reg.get(base_name) {
                if let Some(cached) = ctx.get_cached(base_name) {
                    Some(std::borrow::Cow::Owned(cached.clone()))
                } else {
                    let (rendered, nested_warnings) = render_composition_nested(
                        nested_comp,
                        sprites,
                        composition_registry,
                        ctx,
                        strict,
                        variables,
                    )?;
                    warnings.extend(nested_warnings);
                    ctx.cache(base_name.to_string(), rendered.clone());
                    Some(std::borrow::Cow::Owned(rendered))
                }
            } else {
                warnings.push(Warning::new(format!(
                    "Base '{}' not found for composition '{}'",
                    base_name, comp.name
                )));
                None
            }
        } else {
            warnings.push(Warning::new(format!(
                "Base sprite '{}' not found for composition '{}'",
                base_name, comp.name
            )));
            None
        }
    } else {
        None
    };

    // Determine canvas size
    let (width, height) = if let Some([w, h]) = comp.size {
        (w, h)
    } else if let Some(ref base_img) = base_image {
        (base_img.width(), base_img.height())
    } else {
        let (w, h) = infer_size_from_layers(&comp.layers, cell_size);
        if w == 0 || h == 0 {
            (1, 1)
        } else {
            (w, h)
        }
    };

    // Create canvas
    let mut canvas = RgbaImage::from_pixel(width, height, Rgba([0, 0, 0, 0]));

    // Render base first
    if let Some(ref base_img) = base_image {
        blit_sprite(&mut canvas, base_img, 0, 0);
    }

    // Render each layer
    for layer in &comp.layers {
        let (blend_mode, blend_warning) = resolve_blend_mode(layer.blend.as_deref(), variables);
        if let Some(w) = blend_warning {
            warnings.push(w);
        }

        let (opacity, opacity_warning) = resolve_opacity(layer.opacity.as_ref(), variables);
        if let Some(w) = opacity_warning {
            warnings.push(w);
        }

        if let Some(ref map) = layer.map {
            for (row_idx, row) in map.iter().enumerate() {
                for (col_idx, char_key) in row.chars().enumerate() {
                    let key = char_key.to_string();

                    let sprite_name = match comp.sprites.get(&key) {
                        Some(Some(name)) => name,
                        Some(None) => continue,
                        None => {
                            warnings.push(Warning::new(format!(
                                "Unknown sprite key '{}' in composition '{}'",
                                key, comp.name
                            )));
                            continue;
                        }
                    };

                    // Get sprite/composition image (NC-4: check compositions too)
                    let sprite_image: std::borrow::Cow<'_, RgbaImage> =
                        if let Some(img) = sprites.get(sprite_name) {
                            std::borrow::Cow::Borrowed(img)
                        } else if let Some(reg) = composition_registry {
                            if let Some(nested_comp) = reg.get(sprite_name) {
                                if let Some(cached) = ctx.get_cached(sprite_name) {
                                    std::borrow::Cow::Owned(cached.clone())
                                } else {
                                    let (rendered, nested_warnings) = render_composition_nested(
                                        nested_comp,
                                        sprites,
                                        composition_registry,
                                        ctx,
                                        strict,
                                        variables,
                                    )?;
                                    warnings.extend(nested_warnings);
                                    ctx.cache(sprite_name.to_string(), rendered.clone());
                                    std::borrow::Cow::Owned(rendered)
                                }
                            } else {
                                warnings.push(Warning::new(format!(
                                    "Sprite '{}' not found for composition '{}'",
                                    sprite_name, comp.name
                                )));
                                continue;
                            }
                        } else {
                            warnings.push(Warning::new(format!(
                                "Sprite '{}' not found for composition '{}'",
                                sprite_name, comp.name
                            )));
                            continue;
                        };

                    let x = (col_idx as u32) * cell_size[0];
                    let y = (row_idx as u32) * cell_size[1];

                    blit_sprite_blended(&mut canvas, &sprite_image, x, y, blend_mode, opacity);
                }
            }
        }
    }

    Ok((canvas, warnings))
}

/// Infer canvas size from layer maps and cell size
fn infer_size_from_layers(
    layers: &[crate::models::CompositionLayer],
    cell_size: [u32; 2],
) -> (u32, u32) {
    let mut max_cols = 0u32;
    let mut max_rows = 0u32;

    for layer in layers {
        if let Some(ref map) = layer.map {
            let rows = map.len() as u32;
            let cols = map.iter().map(|r| r.chars().count() as u32).max().unwrap_or(0);
            max_rows = max_rows.max(rows);
            max_cols = max_cols.max(cols);
        }
    }

    (max_cols * cell_size[0], max_rows * cell_size[1])
}

/// Blit a sprite onto the canvas at the given position.
/// Uses alpha blending for transparent pixels.
fn blit_sprite(canvas: &mut RgbaImage, sprite: &RgbaImage, x: u32, y: u32) {
    blit_sprite_blended(canvas, sprite, x, y, BlendMode::Normal, 1.0);
}

/// Blit a sprite onto the canvas with blend mode and opacity.
///
/// # Arguments
/// * `canvas` - The destination image
/// * `sprite` - The sprite to blit
/// * `x`, `y` - Position on canvas
/// * `blend_mode` - How to blend colors (ATF-10)
/// * `opacity` - Layer opacity (0.0-1.0)
fn blit_sprite_blended(
    canvas: &mut RgbaImage,
    sprite: &RgbaImage,
    x: u32,
    y: u32,
    blend_mode: BlendMode,
    opacity: f64,
) {
    let canvas_width = canvas.width();
    let canvas_height = canvas.height();
    let opacity = opacity.clamp(0.0, 1.0) as f32;

    for (sy, row) in sprite.rows().enumerate() {
        let dest_y = y + sy as u32;
        if dest_y >= canvas_height {
            break;
        }

        for (sx, pixel) in row.enumerate() {
            let dest_x = x + sx as u32;
            if dest_x >= canvas_width {
                break;
            }

            let src = pixel;
            // Fully transparent source, skip
            if src[3] == 0 {
                continue;
            }

            // Apply layer opacity to source alpha
            let src_alpha = (src[3] as f32 / 255.0) * opacity;
            if src_alpha == 0.0 {
                continue;
            }

            let dst = canvas.get_pixel(dest_x, dest_y);
            let blended = blend_pixels(src, dst, blend_mode, src_alpha);
            canvas.put_pixel(dest_x, dest_y, blended);
        }
    }
}

/// Blend source pixel over destination using the specified blend mode and opacity.
fn blend_pixels(src: &Rgba<u8>, dst: &Rgba<u8>, mode: BlendMode, src_alpha: f32) -> Rgba<u8> {
    let dst_alpha = dst[3] as f32 / 255.0;

    // Normalize colors to 0.0-1.0
    let src_r = src[0] as f32 / 255.0;
    let src_g = src[1] as f32 / 255.0;
    let src_b = src[2] as f32 / 255.0;

    let dst_r = dst[0] as f32 / 255.0;
    let dst_g = dst[1] as f32 / 255.0;
    let dst_b = dst[2] as f32 / 255.0;

    // Apply blend mode to get the blended color (before alpha compositing)
    let blended_r = mode.blend_channel(dst_r, src_r);
    let blended_g = mode.blend_channel(dst_g, src_g);
    let blended_b = mode.blend_channel(dst_b, src_b);

    // Now composite the blended color over destination using porter-duff "source over"
    // out_alpha = src_alpha + dst_alpha * (1 - src_alpha)
    let out_alpha = src_alpha + dst_alpha * (1.0 - src_alpha);

    if out_alpha == 0.0 {
        return Rgba([0, 0, 0, 0]);
    }

    // Composite each channel:
    // out_color = (blended_color * src_alpha + dst_color * dst_alpha * (1 - src_alpha)) / out_alpha
    let composite = |blended: f32, dst: f32| -> u8 {
        let result = (blended * src_alpha + dst * dst_alpha * (1.0 - src_alpha)) / out_alpha;
        (result.clamp(0.0, 1.0) * 255.0).round() as u8
    };

    Rgba([
        composite(blended_r, dst_r),
        composite(blended_g, dst_g),
        composite(blended_b, dst_b),
        (out_alpha * 255.0).round() as u8,
    ])
}

/// Alpha blend source over destination (test helper)
#[cfg(test)]
fn alpha_blend(src: &Rgba<u8>, dst: &Rgba<u8>) -> Rgba<u8> {
    let src_a = src[3] as f32 / 255.0;
    let dst_a = dst[3] as f32 / 255.0;
    let out_a = src_a + dst_a * (1.0 - src_a);

    if out_a == 0.0 {
        return Rgba([0, 0, 0, 0]);
    }

    let blend = |s: u8, d: u8| -> u8 {
        let s_f = s as f32 / 255.0;
        let d_f = d as f32 / 255.0;
        let out = (s_f * src_a + d_f * dst_a * (1.0 - src_a)) / out_a;
        (out * 255.0).round() as u8
    };

    Rgba([
        blend(src[0], dst[0]),
        blend(src[1], dst[1]),
        blend(src[2], dst[2]),
        (out_a * 255.0).round() as u8,
    ])
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{Composition, CompositionLayer};

    #[test]
    fn test_render_empty_composition() {
        let comp = Composition {
            name: "empty".to_string(),
            base: None,
            size: Some([8, 8]),
            cell_size: None,
            sprites: HashMap::new(),
            layers: vec![],
        };
        let sprites = HashMap::new();

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert_eq!(image.width(), 8);
        assert_eq!(image.height(), 8);
        assert!(warnings.is_empty());
        // All pixels should be transparent
        assert_eq!(*image.get_pixel(0, 0), Rgba([0, 0, 0, 0]));
    }

    #[test]
    fn test_render_single_layer_composition() {
        let comp = Composition {
            name: "single_layer".to_string(),
            base: None,
            size: Some([2, 2]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("red_pixel".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: Some("main".to_string()),
                fill: None,
                map: Some(vec!["X.".to_string(), ".X".to_string()]),
                ..Default::default()
            }],
        };

        // Create a 1x1 red sprite
        let mut red_sprite = RgbaImage::new(1, 1);
        red_sprite.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("red_pixel".to_string(), red_sprite)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        assert_eq!(image.width(), 2);
        assert_eq!(image.height(), 2);

        // Check diagonal pattern: X at (0,0) and (1,1), transparent at (1,0) and (0,1)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255])); // X
        assert_eq!(*image.get_pixel(1, 0), Rgba([0, 0, 0, 0])); // .
        assert_eq!(*image.get_pixel(0, 1), Rgba([0, 0, 0, 0])); // .
        assert_eq!(*image.get_pixel(1, 1), Rgba([255, 0, 0, 255])); // X
    }

    #[test]
    fn test_infer_size_from_layers() {
        let layers = vec![CompositionLayer {
            name: None,
            fill: None,
            map: Some(vec!["ABC".to_string(), "DEF".to_string()]),
            ..Default::default()
        }];

        let (width, height) = infer_size_from_layers(&layers, [1, 1]);
        assert_eq!(width, 3);
        assert_eq!(height, 2);

        // With cell_size [4, 4]
        let (width, height) = infer_size_from_layers(&layers, [4, 4]);
        assert_eq!(width, 12);
        assert_eq!(height, 8);
    }

    #[test]
    fn test_unknown_sprite_key_warning() {
        let comp = Composition {
            name: "test".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: None,
            sprites: HashMap::new(), // Empty - no keys defined
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["X".to_string()]),
                ..Default::default()
            }],
        };

        let (_, warnings) = render_composition(&comp, &HashMap::new(), false, None).unwrap();

        assert!(!warnings.is_empty());
        assert!(warnings[0].message.contains("Unknown sprite key"));
    }

    #[test]
    fn test_missing_sprite_warning() {
        let comp = Composition {
            name: "test".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: None,
            sprites: HashMap::from([("X".to_string(), Some("missing_sprite".to_string()))]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["X".to_string()]),
                ..Default::default()
            }],
        };

        // Empty sprites map - sprite not provided
        let (_, warnings) = render_composition(&comp, &HashMap::new(), false, None).unwrap();

        assert!(!warnings.is_empty());
        assert!(warnings[0].message.contains("not found"));
    }

    #[test]
    fn test_alpha_blend() {
        // Opaque over transparent
        let src = Rgba([255, 0, 0, 255]);
        let dst = Rgba([0, 0, 0, 0]);
        let result = alpha_blend(&src, &dst);
        assert_eq!(result, Rgba([255, 0, 0, 255]));

        // Semi-transparent over opaque
        let src = Rgba([255, 0, 0, 128]); // ~50% red
        let dst = Rgba([0, 0, 255, 255]); // 100% blue
        let result = alpha_blend(&src, &dst);
        // Result should be roughly purple
        assert!(result[0] > 100); // Some red
        assert!(result[2] > 100); // Some blue
        assert_eq!(result[3], 255); // Fully opaque
    }

    #[test]
    fn test_cell_size_default() {
        let comp = Composition {
            name: "no_cell_size".to_string(),
            base: None,
            size: None,
            cell_size: None, // Should default to [1, 1]
            sprites: HashMap::from([("X".to_string(), Some("pixel".to_string()))]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["XX".to_string(), "XX".to_string()]),
                ..Default::default()
            }],
        };

        let mut pixel = RgbaImage::new(1, 1);
        pixel.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
        let sprites = HashMap::from([("pixel".to_string(), pixel)]);

        let (image, _) = render_composition(&comp, &sprites, false, None).unwrap();

        // Should infer 2x2 from map
        assert_eq!(image.width(), 2);
        assert_eq!(image.height(), 2);
    }

    #[test]
    fn test_render_two_layers_stack() {
        // Layer 1: red at (0,0), transparent elsewhere
        // Layer 2: blue at (0,0), transparent elsewhere
        // Result: blue at (0,0) because layer 2 is on top
        let comp = Composition {
            name: "two_layers".to_string(),
            base: None,
            size: Some([2, 2]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("R".to_string(), Some("red_pixel".to_string())),
                ("B".to_string(), Some("blue_pixel".to_string())),
            ]),
            layers: vec![
                CompositionLayer {
                    name: Some("bottom".to_string()),
                    fill: None,
                    map: Some(vec!["R.".to_string(), "..".to_string()]),
                    ..Default::default()
                },
                CompositionLayer {
                    name: Some("top".to_string()),
                    fill: None,
                    map: Some(vec!["B.".to_string(), "..".to_string()]),
                    ..Default::default()
                },
            ],
        };

        let mut red_sprite = RgbaImage::new(1, 1);
        red_sprite.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let mut blue_sprite = RgbaImage::new(1, 1);
        blue_sprite.put_pixel(0, 0, Rgba([0, 0, 255, 255]));

        let sprites = HashMap::from([
            ("red_pixel".to_string(), red_sprite),
            ("blue_pixel".to_string(), blue_sprite),
        ]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // (0,0) should be blue (layer 2 overwrites layer 1)
        assert_eq!(*image.get_pixel(0, 0), Rgba([0, 0, 255, 255]));
        // Other pixels should be transparent
        assert_eq!(*image.get_pixel(1, 0), Rgba([0, 0, 0, 0]));
        assert_eq!(*image.get_pixel(0, 1), Rgba([0, 0, 0, 0]));
        assert_eq!(*image.get_pixel(1, 1), Rgba([0, 0, 0, 0]));
    }

    #[test]
    fn test_render_two_layers_different_positions() {
        // Layer 1: red at (0,0)
        // Layer 2: blue at (1,1)
        // Result: both visible at their respective positions
        let comp = Composition {
            name: "two_layers_positions".to_string(),
            base: None,
            size: Some([2, 2]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("R".to_string(), Some("red_pixel".to_string())),
                ("B".to_string(), Some("blue_pixel".to_string())),
            ]),
            layers: vec![
                CompositionLayer {
                    name: Some("bottom".to_string()),
                    fill: None,
                    map: Some(vec!["R.".to_string(), "..".to_string()]),
                    ..Default::default()
                },
                CompositionLayer {
                    name: Some("top".to_string()),
                    fill: None,
                    map: Some(vec!["..".to_string(), ".B".to_string()]),
                    ..Default::default()
                },
            ],
        };

        let mut red_sprite = RgbaImage::new(1, 1);
        red_sprite.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let mut blue_sprite = RgbaImage::new(1, 1);
        blue_sprite.put_pixel(0, 0, Rgba([0, 0, 255, 255]));

        let sprites = HashMap::from([
            ("red_pixel".to_string(), red_sprite),
            ("blue_pixel".to_string(), blue_sprite),
        ]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // (0,0) should be red (from layer 1)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
        // (1,1) should be blue (from layer 2)
        assert_eq!(*image.get_pixel(1, 1), Rgba([0, 0, 255, 255]));
        // Other pixels should be transparent
        assert_eq!(*image.get_pixel(1, 0), Rgba([0, 0, 0, 0]));
        assert_eq!(*image.get_pixel(0, 1), Rgba([0, 0, 0, 0]));
    }

    #[test]
    fn test_render_three_layers_stack() {
        // Layer 1: red across all
        // Layer 2: green at (0,0) and (1,0)
        // Layer 3: blue at (0,0) only
        // Result: blue at (0,0), green at (1,0), red at (0,1) and (1,1)
        let comp = Composition {
            name: "three_layers".to_string(),
            base: None,
            size: Some([2, 2]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("R".to_string(), Some("red_pixel".to_string())),
                ("G".to_string(), Some("green_pixel".to_string())),
                ("B".to_string(), Some("blue_pixel".to_string())),
            ]),
            layers: vec![
                CompositionLayer {
                    name: Some("layer1".to_string()),
                    fill: None,
                    map: Some(vec!["RR".to_string(), "RR".to_string()]),
                    ..Default::default()
                },
                CompositionLayer {
                    name: Some("layer2".to_string()),
                    fill: None,
                    map: Some(vec!["GG".to_string(), "..".to_string()]),
                    ..Default::default()
                },
                CompositionLayer {
                    name: Some("layer3".to_string()),
                    fill: None,
                    map: Some(vec!["B.".to_string(), "..".to_string()]),
                    ..Default::default()
                },
            ],
        };

        let mut red_sprite = RgbaImage::new(1, 1);
        red_sprite.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let mut green_sprite = RgbaImage::new(1, 1);
        green_sprite.put_pixel(0, 0, Rgba([0, 255, 0, 255]));

        let mut blue_sprite = RgbaImage::new(1, 1);
        blue_sprite.put_pixel(0, 0, Rgba([0, 0, 255, 255]));

        let sprites = HashMap::from([
            ("red_pixel".to_string(), red_sprite),
            ("green_pixel".to_string(), green_sprite),
            ("blue_pixel".to_string(), blue_sprite),
        ]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // (0,0): red -> green -> blue = blue
        assert_eq!(*image.get_pixel(0, 0), Rgba([0, 0, 255, 255]));
        // (1,0): red -> green = green
        assert_eq!(*image.get_pixel(1, 0), Rgba([0, 255, 0, 255]));
        // (0,1): red only
        assert_eq!(*image.get_pixel(0, 1), Rgba([255, 0, 0, 255]));
        // (1,1): red only
        assert_eq!(*image.get_pixel(1, 1), Rgba([255, 0, 0, 255]));
    }

    #[test]
    fn test_all_dots_layer_renders_nothing() {
        // Layer with all "." should not affect the canvas
        let comp = Composition {
            name: "dots_layer".to_string(),
            base: None,
            size: Some([2, 2]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("R".to_string(), Some("red_pixel".to_string())),
            ]),
            layers: vec![
                CompositionLayer {
                    name: Some("background".to_string()),
                    fill: None,
                    map: Some(vec!["RR".to_string(), "RR".to_string()]),
                    ..Default::default()
                },
                CompositionLayer {
                    name: Some("empty".to_string()),
                    fill: None,
                    map: Some(vec!["..".to_string(), "..".to_string()]),
                    ..Default::default()
                },
            ],
        };

        let mut red_sprite = RgbaImage::new(1, 1);
        red_sprite.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("red_pixel".to_string(), red_sprite)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // All pixels should still be red (empty layer didn't erase anything)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(1, 0), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(0, 1), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(1, 1), Rgba([255, 0, 0, 255]));
    }

    // Task 2.5: Size Mismatch Handling tests

    #[test]
    fn test_sprite_fits_cell_no_warning() {
        // Sprite exactly fits cell - no warning
        let comp = Composition {
            name: "exact_fit".to_string(),
            base: None,
            size: Some([4, 4]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("pixel".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["X.".to_string(), ".X".to_string()]),
                ..Default::default()
            }],
        };

        // 2x2 sprite exactly fits 2x2 cell
        let mut pixel = RgbaImage::new(2, 2);
        pixel.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
        pixel.put_pixel(1, 0, Rgba([255, 0, 0, 255]));
        pixel.put_pixel(0, 1, Rgba([255, 0, 0, 255]));
        pixel.put_pixel(1, 1, Rgba([255, 0, 0, 255]));
        let sprites = HashMap::from([("pixel".to_string(), pixel)]);

        let (_, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        // No size mismatch warnings
        assert!(warnings.is_empty());
    }

    #[test]
    fn test_sprite_smaller_than_cell_no_warning() {
        // Sprite smaller than cell - no warning
        let comp = Composition {
            name: "small_fit".to_string(),
            base: None,
            size: Some([4, 4]),
            cell_size: Some([4, 4]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("pixel".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["X".to_string()]),
                ..Default::default()
            }],
        };

        // 2x2 sprite fits in 4x4 cell
        let mut pixel = RgbaImage::new(2, 2);
        pixel.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
        let sprites = HashMap::from([("pixel".to_string(), pixel)]);

        let (_, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
    }

    #[test]
    fn test_sprite_larger_than_cell_lenient_warning() {
        // Sprite larger than cell - warning in lenient mode
        let comp = Composition {
            name: "oversized".to_string(),
            base: None,
            size: Some([8, 8]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("big_sprite".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec![
                    "X...".to_string(),
                    "....".to_string(),
                    "....".to_string(),
                    "....".to_string(),
                ]),
                ..Default::default()
            }],
        };

        // 4x4 sprite exceeds 2x2 cell
        let mut big_sprite = RgbaImage::new(4, 4);
        for y in 0..4 {
            for x in 0..4 {
                big_sprite.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }
        let sprites = HashMap::from([("big_sprite".to_string(), big_sprite)]);

        let result = render_composition(&comp, &sprites, false, None);

        // Should succeed in lenient mode
        assert!(result.is_ok());
        let (image, warnings) = result.unwrap();

        // Should have a warning
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("exceeds cell size"));
        assert!(warnings[0].message.contains("big_sprite"));
        assert!(warnings[0].message.contains("4x4"));
        assert!(warnings[0].message.contains("2x2"));

        // Sprite should still render (anchored top-left, overwriting adjacent cells)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(3, 3), Rgba([255, 0, 0, 255])); // Overflows into adjacent cells
    }

    #[test]
    fn test_sprite_larger_than_cell_strict_error() {
        // Sprite larger than cell - error in strict mode
        let comp = Composition {
            name: "oversized_strict".to_string(),
            base: None,
            size: Some([8, 8]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("big_sprite".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec![
                    "X...".to_string(),
                    "....".to_string(),
                    "....".to_string(),
                    "....".to_string(),
                ]),
                ..Default::default()
            }],
        };

        // 4x4 sprite exceeds 2x2 cell
        let mut big_sprite = RgbaImage::new(4, 4);
        for y in 0..4 {
            for x in 0..4 {
                big_sprite.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }
        let sprites = HashMap::from([("big_sprite".to_string(), big_sprite)]);

        let result = render_composition(&comp, &sprites, true, None);

        // Should fail in strict mode
        assert!(result.is_err());
        let err = result.unwrap_err();

        match err {
            CompositionError::SizeMismatch {
                sprite_name,
                sprite_size,
                cell_size,
                composition_name,
            } => {
                assert_eq!(sprite_name, "big_sprite");
                assert_eq!(sprite_size, (4, 4));
                assert_eq!(cell_size, (2, 2));
                assert_eq!(composition_name, "oversized_strict");
            }
            _ => panic!("Expected SizeMismatch error, got {:?}", err),
        }
    }

    #[test]
    fn test_large_sprite_overwrites_from_topleft() {
        // Large sprite anchors from top-left and overwrites adjacent cells
        let comp = Composition {
            name: "topleft_anchor".to_string(),
            base: None,
            size: Some([6, 6]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("big_sprite".to_string())),
                ("B".to_string(), Some("blue".to_string())),
            ]),
            layers: vec![
                // First layer: blue everywhere
                CompositionLayer {
                    name: Some("background".to_string()),
                    fill: None,
                    map: Some(vec!["BBB".to_string(), "BBB".to_string(), "BBB".to_string()]),
                    ..Default::default()
                },
                // Second layer: big red sprite at (0,0)
                CompositionLayer {
                    name: Some("foreground".to_string()),
                    fill: None,
                    map: Some(vec!["X..".to_string(), "...".to_string(), "...".to_string()]),
                    ..Default::default()
                },
            ],
        };

        // 4x4 red sprite
        let mut big_sprite = RgbaImage::new(4, 4);
        for y in 0..4 {
            for x in 0..4 {
                big_sprite.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }

        // 2x2 blue sprite
        let mut blue = RgbaImage::new(2, 2);
        for y in 0..2 {
            for x in 0..2 {
                blue.put_pixel(x, y, Rgba([0, 0, 255, 255]));
            }
        }

        let sprites =
            HashMap::from([("big_sprite".to_string(), big_sprite), ("blue".to_string(), blue)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        // Should have 1 size mismatch warning
        assert_eq!(warnings.len(), 1);

        // Top-left 4x4 area should be red (big sprite)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(3, 3), Rgba([255, 0, 0, 255]));

        // Area beyond the big sprite should still be blue
        assert_eq!(*image.get_pixel(4, 0), Rgba([0, 0, 255, 255]));
        assert_eq!(*image.get_pixel(0, 4), Rgba([0, 0, 255, 255]));
        assert_eq!(*image.get_pixel(5, 5), Rgba([0, 0, 255, 255]));
    }

    #[test]
    fn test_width_only_exceeds_cell() {
        // Only width exceeds cell - should warn
        let comp = Composition {
            name: "wide".to_string(),
            base: None,
            size: Some([8, 4]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("wide_sprite".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["X...".to_string(), "....".to_string()]),
                ..Default::default()
            }],
        };

        // 4x2 sprite (width exceeds, height fits)
        let mut wide_sprite = RgbaImage::new(4, 2);
        for y in 0..2 {
            for x in 0..4 {
                wide_sprite.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }
        let sprites = HashMap::from([("wide_sprite".to_string(), wide_sprite)]);

        let (_, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("4x2"));
    }

    #[test]
    fn test_height_only_exceeds_cell() {
        // Only height exceeds cell - should warn
        let comp = Composition {
            name: "tall".to_string(),
            base: None,
            size: Some([4, 8]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("tall_sprite".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec![
                    "X.".to_string(),
                    "..".to_string(),
                    "..".to_string(),
                    "..".to_string(),
                ]),
                ..Default::default()
            }],
        };

        // 2x4 sprite (width fits, height exceeds)
        let mut tall_sprite = RgbaImage::new(2, 4);
        for y in 0..4 {
            for x in 0..2 {
                tall_sprite.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }
        let sprites = HashMap::from([("tall_sprite".to_string(), tall_sprite)]);

        let (_, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("2x4"));
    }

    #[test]
    fn test_multiple_size_mismatches_lenient() {
        // Multiple sprites with size mismatches - all should warn in lenient mode
        let comp = Composition {
            name: "multi_mismatch".to_string(),
            base: None,
            size: Some([8, 8]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("A".to_string(), Some("big_a".to_string())),
                ("B".to_string(), Some("big_b".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec![
                    "A...".to_string(),
                    "....".to_string(),
                    "..B.".to_string(),
                    "....".to_string(),
                ]),
                ..Default::default()
            }],
        };

        let mut big_a = RgbaImage::new(3, 3);
        let mut big_b = RgbaImage::new(4, 4);

        for y in 0..3 {
            for x in 0..3 {
                big_a.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }
        for y in 0..4 {
            for x in 0..4 {
                big_b.put_pixel(x, y, Rgba([0, 255, 0, 255]));
            }
        }

        let sprites = HashMap::from([("big_a".to_string(), big_a), ("big_b".to_string(), big_b)]);

        let (_, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        // Should have 2 warnings
        assert_eq!(warnings.len(), 2);
    }

    #[test]
    fn test_size_mismatch_error_display() {
        let err = CompositionError::SizeMismatch {
            sprite_name: "test_sprite".to_string(),
            sprite_size: (10, 20),
            cell_size: (5, 5),
            composition_name: "test_comp".to_string(),
        };

        let msg = format!("{}", err);
        assert!(msg.contains("test_sprite"));
        assert!(msg.contains("10x20"));
        assert!(msg.contains("5x5"));
        assert!(msg.contains("test_comp"));
    }

    // ========== Task 2.3: Cell Size Scaling Tests ==========

    #[test]
    fn test_cell_size_1x1_pixel_perfect_overlay() {
        // cell_size [1, 1] should place sprites at exact pixel positions
        // This is the pixel-perfect overlay mode
        let comp = Composition {
            name: "pixel_perfect".to_string(),
            base: None,
            size: Some([4, 4]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("R".to_string(), Some("red".to_string())),
                ("G".to_string(), Some("green".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: Some("overlay".to_string()),
                fill: None,
                map: Some(vec![
                    "R.G.".to_string(),
                    ".RG.".to_string(),
                    "..RG".to_string(),
                    "...R".to_string(),
                ]),
                ..Default::default()
            }],
        };

        // 1x1 pixel sprites
        let mut red = RgbaImage::new(1, 1);
        red.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let mut green = RgbaImage::new(1, 1);
        green.put_pixel(0, 0, Rgba([0, 255, 0, 255]));

        let sprites = HashMap::from([("red".to_string(), red), ("green".to_string(), green)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        assert_eq!(image.width(), 4);
        assert_eq!(image.height(), 4);

        // Check diagonal pattern
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255])); // R at (0,0)
        assert_eq!(*image.get_pixel(2, 0), Rgba([0, 255, 0, 255])); // G at (2,0)
        assert_eq!(*image.get_pixel(1, 1), Rgba([255, 0, 0, 255])); // R at (1,1)
        assert_eq!(*image.get_pixel(2, 1), Rgba([0, 255, 0, 255])); // G at (2,1)
        assert_eq!(*image.get_pixel(3, 3), Rgba([255, 0, 0, 255])); // R at (3,3)
                                                                    // Transparent pixels
        assert_eq!(*image.get_pixel(1, 0), Rgba([0, 0, 0, 0]));
        assert_eq!(*image.get_pixel(0, 3), Rgba([0, 0, 0, 0]));
    }

    #[test]
    fn test_cell_size_4x4_grid_cells() {
        // cell_size [4, 4] means each grid character = 4x4 pixel area
        let comp = Composition {
            name: "4x4_grid".to_string(),
            base: None,
            size: Some([16, 16]), // 4 cells x 4 cells = 16x16 pixels
            cell_size: Some([4, 4]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("A".to_string(), Some("tile_a".to_string())),
                ("B".to_string(), Some("tile_b".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: Some("tiles".to_string()),
                fill: None,
                map: Some(vec![
                    "AB..".to_string(),
                    "BA..".to_string(),
                    "....".to_string(),
                    "..AB".to_string(),
                ]),
                ..Default::default()
            }],
        };

        // 4x4 pixel tiles
        let mut tile_a = RgbaImage::new(4, 4);
        for y in 0..4 {
            for x in 0..4 {
                tile_a.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }

        let mut tile_b = RgbaImage::new(4, 4);
        for y in 0..4 {
            for x in 0..4 {
                tile_b.put_pixel(x, y, Rgba([0, 0, 255, 255]));
            }
        }

        let sprites =
            HashMap::from([("tile_a".to_string(), tile_a), ("tile_b".to_string(), tile_b)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        assert_eq!(image.width(), 16);
        assert_eq!(image.height(), 16);

        // Row 0: A at (0,0), B at (4,0)
        // Tile A occupies pixels (0-3, 0-3)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(3, 3), Rgba([255, 0, 0, 255]));
        // Tile B occupies pixels (4-7, 0-3)
        assert_eq!(*image.get_pixel(4, 0), Rgba([0, 0, 255, 255]));
        assert_eq!(*image.get_pixel(7, 3), Rgba([0, 0, 255, 255]));

        // Row 1: B at (0,4), A at (4,4)
        assert_eq!(*image.get_pixel(0, 4), Rgba([0, 0, 255, 255]));
        assert_eq!(*image.get_pixel(4, 4), Rgba([255, 0, 0, 255]));

        // Row 3: A at (8,12), B at (12,12)
        assert_eq!(*image.get_pixel(8, 12), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(12, 12), Rgba([0, 0, 255, 255]));

        // Empty cells should be transparent
        assert_eq!(*image.get_pixel(8, 0), Rgba([0, 0, 0, 0]));
        assert_eq!(*image.get_pixel(0, 8), Rgba([0, 0, 0, 0]));
    }

    #[test]
    fn test_cell_size_16x16_tile_based_scene() {
        // cell_size [16, 16] for tile-based game scenes
        let comp = Composition {
            name: "tile_scene".to_string(),
            base: None,
            size: Some([48, 32]), // 3x2 tiles = 48x32 pixels
            cell_size: Some([16, 16]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("G".to_string(), Some("grass".to_string())),
                ("W".to_string(), Some("water".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: Some("terrain".to_string()),
                fill: None,
                map: Some(vec!["GGW".to_string(), "GWW".to_string()]),
                ..Default::default()
            }],
        };

        // 16x16 pixel tiles
        let mut grass = RgbaImage::new(16, 16);
        for y in 0..16 {
            for x in 0..16 {
                grass.put_pixel(x, y, Rgba([0, 128, 0, 255])); // Green
            }
        }

        let mut water = RgbaImage::new(16, 16);
        for y in 0..16 {
            for x in 0..16 {
                water.put_pixel(x, y, Rgba([0, 0, 200, 255])); // Blue
            }
        }

        let sprites = HashMap::from([("grass".to_string(), grass), ("water".to_string(), water)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        assert_eq!(image.width(), 48);
        assert_eq!(image.height(), 32);

        // Row 0: G at (0,0), G at (16,0), W at (32,0)
        assert_eq!(*image.get_pixel(0, 0), Rgba([0, 128, 0, 255])); // Grass
        assert_eq!(*image.get_pixel(16, 0), Rgba([0, 128, 0, 255])); // Grass
        assert_eq!(*image.get_pixel(32, 0), Rgba([0, 0, 200, 255])); // Water

        // Row 1: G at (0,16), W at (16,16), W at (32,16)
        assert_eq!(*image.get_pixel(0, 16), Rgba([0, 128, 0, 255])); // Grass
        assert_eq!(*image.get_pixel(16, 16), Rgba([0, 0, 200, 255])); // Water
        assert_eq!(*image.get_pixel(32, 16), Rgba([0, 0, 200, 255])); // Water

        // Check tile boundaries
        assert_eq!(*image.get_pixel(15, 15), Rgba([0, 128, 0, 255])); // Last pixel of (0,0) grass
        assert_eq!(*image.get_pixel(47, 31), Rgba([0, 0, 200, 255])); // Last pixel of (2,1) water
    }

    #[test]
    fn test_cell_size_asymmetric() {
        // Non-square cell size: [8, 4]
        let comp = Composition {
            name: "asymmetric".to_string(),
            base: None,
            size: Some([24, 12]), // 3 cols x 3 rows with asymmetric cells
            cell_size: Some([8, 4]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("wide_tile".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["X.X".to_string(), "...".to_string(), "X.X".to_string()]),
                ..Default::default()
            }],
        };

        // 8x4 wide tile
        let mut wide_tile = RgbaImage::new(8, 4);
        for y in 0..4 {
            for x in 0..8 {
                wide_tile.put_pixel(x, y, Rgba([255, 128, 0, 255])); // Orange
            }
        }

        let sprites = HashMap::from([("wide_tile".to_string(), wide_tile)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        assert_eq!(image.width(), 24);
        assert_eq!(image.height(), 12);

        // Tile at (0,0) - covers pixels (0-7, 0-3)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 128, 0, 255]));
        assert_eq!(*image.get_pixel(7, 3), Rgba([255, 128, 0, 255]));

        // Tile at (2,0) - covers pixels (16-23, 0-3)
        assert_eq!(*image.get_pixel(16, 0), Rgba([255, 128, 0, 255]));
        assert_eq!(*image.get_pixel(23, 3), Rgba([255, 128, 0, 255]));

        // Empty middle column at x=8-15
        assert_eq!(*image.get_pixel(8, 0), Rgba([0, 0, 0, 0]));

        // Tile at (0,2) - covers pixels (0-7, 8-11)
        assert_eq!(*image.get_pixel(0, 8), Rgba([255, 128, 0, 255]));
        assert_eq!(*image.get_pixel(7, 11), Rgba([255, 128, 0, 255]));
    }

    // ========== Size Inference Tests ==========

    #[test]
    fn test_size_inference_from_base_sprite() {
        // When size is not specified but base is, use base sprite dimensions
        let comp = Composition {
            name: "base_inference".to_string(),
            base: Some("hero".to_string()),
            size: None, // No explicit size
            cell_size: Some([4, 4]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("H".to_string(), Some("hat".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                // Map 2x2 cells = 8x8 pixels with cell_size 4x4
                map: Some(vec!["H.".to_string(), "..".to_string()]),
                ..Default::default()
            }],
        };

        // Base sprite is 8x8 (2x2 cells with cell_size 4x4)
        let mut hero = RgbaImage::new(8, 8);
        for y in 0..8 {
            for x in 0..8 {
                hero.put_pixel(x, y, Rgba([100, 100, 100, 255])); // Gray
            }
        }

        // Hat is 4x4
        let mut hat = RgbaImage::new(4, 4);
        for y in 0..4 {
            for x in 0..4 {
                hat.put_pixel(x, y, Rgba([255, 0, 0, 255])); // Red
            }
        }

        let sprites = HashMap::from([("hero".to_string(), hero), ("hat".to_string(), hat)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // Canvas size should be inferred from base sprite (8x8)
        assert_eq!(image.width(), 8);
        assert_eq!(image.height(), 8);

        // Base sprite should be rendered first
        assert_eq!(*image.get_pixel(4, 4), Rgba([100, 100, 100, 255]));

        // Hat should be overlaid at (0,0)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(3, 3), Rgba([255, 0, 0, 255]));
    }

    #[test]
    fn test_size_inference_priority_explicit_over_base() {
        // Explicit size should take priority over base sprite
        let comp = Composition {
            name: "explicit_priority".to_string(),
            base: Some("base".to_string()),
            size: Some([10, 10]), // Explicit size different from base
            cell_size: None,
            sprites: HashMap::new(),
            layers: vec![],
        };

        // Base sprite is 32x32, but explicit size is 10x10
        let mut base = RgbaImage::new(32, 32);
        base.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("base".to_string(), base)]);

        let (image, _) = render_composition(&comp, &sprites, false, None).unwrap();

        // Should use explicit size, not base size
        assert_eq!(image.width(), 10);
        assert_eq!(image.height(), 10);
    }

    #[test]
    fn test_size_inference_priority_base_over_layers() {
        // Base sprite size should take priority over layer inference
        // This test uses a base sprite size that differs from what the layer map would suggest
        // With validation, this generates a map dimension warning (expected in lenient mode)
        let comp = Composition {
            name: "base_over_layers".to_string(),
            base: Some("background".to_string()),
            size: None, // No explicit size
            cell_size: Some([4, 4]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("tile".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                // Layer map would infer 8x8 (2x2 cells * 4x4 cell_size)
                // But base sprite is 16x20, so expected grid is 4x5
                map: Some(vec!["X.".to_string(), ".X".to_string()]),
                ..Default::default()
            }],
        };

        // Background sprite is 16x20 (different from layer inference of 8x8)
        let mut background = RgbaImage::new(16, 20);
        for y in 0..20 {
            for x in 0..16 {
                background.put_pixel(x, y, Rgba([50, 50, 50, 255]));
            }
        }

        let mut tile = RgbaImage::new(4, 4);
        tile.put_pixel(0, 0, Rgba([255, 255, 0, 255]));

        let sprites =
            HashMap::from([("background".to_string(), background), ("tile".to_string(), tile)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        // The key assertion: base sprite size (16x20) takes priority over layer-inferred (8x8)
        assert_eq!(image.width(), 16);
        assert_eq!(image.height(), 20);

        // With validation, we expect a map dimension warning since map is 2x2 but expected is 4x5
        let dim_warnings: Vec<_> =
            warnings.iter().filter(|w| w.message.contains("don't match expected")).collect();
        assert_eq!(dim_warnings.len(), 1);
    }

    #[test]
    fn test_size_inference_from_layers_with_cell_size() {
        // When no explicit size and no base, infer from layers + cell_size
        let comp = Composition {
            name: "layer_inference".to_string(),
            base: None,
            size: None, // No explicit size
            cell_size: Some([8, 8]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("tile".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                // 3 cols x 2 rows = 24x16 with cell_size 8x8
                map: Some(vec!["X.X".to_string(), ".X.".to_string()]),
                ..Default::default()
            }],
        };

        let mut tile = RgbaImage::new(8, 8);
        tile.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("tile".to_string(), tile)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // Inferred: 3 cols * 8 = 24, 2 rows * 8 = 16
        assert_eq!(image.width(), 24);
        assert_eq!(image.height(), 16);
    }

    #[test]
    fn test_missing_base_sprite_warning() {
        // When base is specified but not found, should warn and continue
        let comp = Composition {
            name: "missing_base".to_string(),
            base: Some("nonexistent".to_string()),
            size: None,
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("tile".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["XX".to_string()]),
                ..Default::default()
            }],
        };

        let mut tile = RgbaImage::new(2, 2);
        tile.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("tile".to_string(), tile)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        // Should have warning about missing base
        assert!(!warnings.is_empty());
        assert!(warnings[0].message.contains("Base sprite 'nonexistent' not found"));

        // Should still render with size inferred from layers
        assert_eq!(image.width(), 4); // 2 cells * 2 cell_size
        assert_eq!(image.height(), 2); // 1 row * 2 cell_size
    }

    #[test]
    fn test_base_sprite_rendered_as_background() {
        // Base sprite should be rendered first, then layers on top
        let comp = Composition {
            name: "base_background".to_string(),
            base: Some("bg".to_string()),
            size: Some([4, 4]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("X".to_string(), Some("overlay".to_string())),
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                // Overlay at (0,0) only
                map: Some(vec!["X.".to_string(), "..".to_string()]),
                ..Default::default()
            }],
        };

        // Blue 4x4 background
        let mut bg = RgbaImage::new(4, 4);
        for y in 0..4 {
            for x in 0..4 {
                bg.put_pixel(x, y, Rgba([0, 0, 255, 255]));
            }
        }

        // Red 2x2 overlay
        let mut overlay = RgbaImage::new(2, 2);
        for y in 0..2 {
            for x in 0..2 {
                overlay.put_pixel(x, y, Rgba([255, 0, 0, 255]));
            }
        }

        let sprites = HashMap::from([("bg".to_string(), bg), ("overlay".to_string(), overlay)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());

        // Top-left 2x2 should be red (overlay)
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
        assert_eq!(*image.get_pixel(1, 1), Rgba([255, 0, 0, 255]));

        // Rest should be blue (background showing through)
        assert_eq!(*image.get_pixel(2, 0), Rgba([0, 0, 255, 255]));
        assert_eq!(*image.get_pixel(0, 2), Rgba([0, 0, 255, 255]));
        assert_eq!(*image.get_pixel(3, 3), Rgba([0, 0, 255, 255]));
    }

    // ========== Task 2.6: Variant in Composition Test ==========

    #[test]
    fn test_variant_usable_in_composition() {
        // Verify that a variant can be used in a composition's sprites map
        // just like a regular sprite
        use crate::models::{PaletteRef, Sprite, Variant};
        use crate::registry::{PaletteRegistry, SpriteRegistry};
        use crate::renderer::render_resolved;

        // Create base sprite and variant
        let base_sprite = Sprite {
            name: "hero".to_string(),
            size: None,
            palette: PaletteRef::Inline(HashMap::from([
                ("{_}".to_string(), "#00000000".to_string()),
                ("{skin}".to_string(), "#FFCC99".to_string()), // Original skin
            ])),
            grid: vec!["{_}{skin}".to_string(), "{skin}{_}".to_string()],
            metadata: None,
            ..Default::default()
        };

        let variant = Variant {
            name: "hero_red".to_string(),
            base: "hero".to_string(),
            palette: HashMap::from([
                ("{skin}".to_string(), "#FF0000".to_string()), // Red skin
            ]),
            ..Default::default()
        };

        // Build registries and resolve
        let palette_registry = PaletteRegistry::new();
        let mut sprite_registry = SpriteRegistry::new();
        sprite_registry.register_sprite(base_sprite);
        sprite_registry.register_variant(variant);

        // Render both base and variant
        let hero_resolved = sprite_registry.resolve("hero", &palette_registry, false).unwrap();
        let variant_resolved =
            sprite_registry.resolve("hero_red", &palette_registry, false).unwrap();

        let (hero_img, _) = render_resolved(&hero_resolved);
        let (variant_img, _) = render_resolved(&variant_resolved);

        // Build the composition that uses both
        let comp = Composition {
            name: "scene".to_string(),
            base: None,
            size: Some([4, 4]),
            cell_size: Some([2, 2]),
            sprites: HashMap::from([
                (".".to_string(), None),
                ("H".to_string(), Some("hero".to_string())),
                ("R".to_string(), Some("hero_red".to_string())), // Variant reference
            ]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["HR".to_string(), "RH".to_string()]),
                ..Default::default()
            }],
        };

        // Provide both the base sprite and variant as rendered images
        let sprites =
            HashMap::from([("hero".to_string(), hero_img), ("hero_red".to_string(), variant_img)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        assert_eq!(image.width(), 4);
        assert_eq!(image.height(), 4);

        // hero (original skin #FFCC99 = 255, 204, 153) at (0,0) and (2,2)
        // hero_red (red skin #FF0000) at (2,0) and (0,2)

        // (1, 0) is hero's skin pixel (from {_}{skin} grid, skin is at x=1)
        assert_eq!(*image.get_pixel(1, 0), Rgba([255, 204, 153, 255])); // Original skin

        // (3, 0) is hero_red's skin pixel
        assert_eq!(*image.get_pixel(3, 0), Rgba([255, 0, 0, 255])); // Red skin

        // (1, 2) is hero_red's skin pixel (at grid position (0, 1) * cell_size (2,2))
        assert_eq!(*image.get_pixel(1, 2), Rgba([255, 0, 0, 255])); // Red skin

        // (3, 2) is hero's skin pixel (at grid position (1, 1) * cell_size (2,2))
        assert_eq!(*image.get_pixel(3, 2), Rgba([255, 204, 153, 255])); // Original skin
    }

    // ========== Task 14.3: Tiling Validation Tests ==========

    #[test]
    fn test_size_divisible_by_cell_size_valid() {
        // Size 64x64 with cell_size 16x16 = 4x4 grid - valid
        let comp = Composition {
            name: "valid_grid".to_string(),
            base: None,
            size: Some([64, 64]),
            cell_size: Some([16, 16]),
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec![
                    "....".to_string(),
                    "....".to_string(),
                    "....".to_string(),
                    "....".to_string(),
                ]),
                ..Default::default()
            }],
        };

        let (_, warnings) = render_composition(&comp, &HashMap::new(), false, None).unwrap();

        // No divisibility warnings
        let div_warnings: Vec<_> =
            warnings.iter().filter(|w| w.message.contains("not divisible")).collect();
        assert!(div_warnings.is_empty());
    }

    #[test]
    fn test_size_not_divisible_lenient_warning() {
        // Size 65x64 with cell_size 16x16 - width not divisible
        let comp = Composition {
            name: "invalid_width".to_string(),
            base: None,
            size: Some([65, 64]),
            cell_size: Some([16, 16]),
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["....".to_string()]),
                ..Default::default()
            }],
        };

        let result = render_composition(&comp, &HashMap::new(), false, None);

        // Should succeed in lenient mode
        assert!(result.is_ok());
        let (_, warnings) = result.unwrap();

        // Should have divisibility warning
        let div_warnings: Vec<_> =
            warnings.iter().filter(|w| w.message.contains("not divisible")).collect();
        assert_eq!(div_warnings.len(), 1);
        assert!(div_warnings[0].message.contains("65x64"));
        assert!(div_warnings[0].message.contains("16x16"));
    }

    #[test]
    fn test_size_not_divisible_strict_error() {
        // Size 64x65 with cell_size 16x16 - height not divisible
        let comp = Composition {
            name: "invalid_height".to_string(),
            base: None,
            size: Some([64, 65]),
            cell_size: Some([16, 16]),
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["....".to_string()]),
                ..Default::default()
            }],
        };

        let result = render_composition(&comp, &HashMap::new(), true, None);

        // Should fail in strict mode
        assert!(result.is_err());
        let err = result.unwrap_err();

        match err {
            CompositionError::SizeNotDivisible { size, cell_size, composition_name } => {
                assert_eq!(size, (64, 65));
                assert_eq!(cell_size, (16, 16));
                assert_eq!(composition_name, "invalid_height");
            }
            _ => panic!("Expected SizeNotDivisible error"),
        }
    }

    #[test]
    fn test_map_dimensions_match_expected_grid() {
        // Size 32x32 with cell_size 16x16 = 2x2 grid
        // Map has 2x2 = valid
        let comp = Composition {
            name: "valid_map".to_string(),
            base: None,
            size: Some([32, 32]),
            cell_size: Some([16, 16]),
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: Some("terrain".to_string()),
                fill: None,
                map: Some(vec!["..".to_string(), "..".to_string()]),
                ..Default::default()
            }],
        };

        let (_, warnings) = render_composition(&comp, &HashMap::new(), false, None).unwrap();

        // No dimension warnings
        let dim_warnings: Vec<_> =
            warnings.iter().filter(|w| w.message.contains("don't match expected")).collect();
        assert!(dim_warnings.is_empty());
    }

    #[test]
    fn test_map_dimensions_mismatch_lenient_warning() {
        // Size 32x32 with cell_size 16x16 = expected 2x2 grid
        // Map has 3x2 = mismatch
        let comp = Composition {
            name: "map_mismatch".to_string(),
            base: None,
            size: Some([32, 32]),
            cell_size: Some([16, 16]),
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: Some("terrain".to_string()),
                fill: None,
                map: Some(vec!["...".to_string(), "...".to_string()]),
                ..Default::default()
            }],
        };

        let result = render_composition(&comp, &HashMap::new(), false, None);

        // Should succeed in lenient mode
        assert!(result.is_ok());
        let (_, warnings) = result.unwrap();

        // Should have dimension warning
        let dim_warnings: Vec<_> =
            warnings.iter().filter(|w| w.message.contains("don't match expected")).collect();
        assert_eq!(dim_warnings.len(), 1);
        assert!(dim_warnings[0].message.contains("3x2")); // actual
        assert!(dim_warnings[0].message.contains("2x2")); // expected
        assert!(dim_warnings[0].message.contains("layer 'terrain'"));
    }

    #[test]
    fn test_map_dimensions_mismatch_strict_error() {
        // Size 32x32 with cell_size 16x16 = expected 2x2 grid
        // Map has 2x3 = mismatch (too many rows)
        let comp = Composition {
            name: "map_rows_mismatch".to_string(),
            base: None,
            size: Some([32, 32]),
            cell_size: Some([16, 16]),
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: Some("layer1".to_string()),
                fill: None,
                map: Some(vec!["..".to_string(), "..".to_string(), "..".to_string()]),
                ..Default::default()
            }],
        };

        let result = render_composition(&comp, &HashMap::new(), true, None);

        // Should fail in strict mode
        assert!(result.is_err());
        let err = result.unwrap_err();

        match err {
            CompositionError::MapDimensionMismatch {
                layer_name,
                actual_dimensions,
                expected_dimensions,
                composition_name,
            } => {
                assert_eq!(layer_name, Some("layer1".to_string()));
                assert_eq!(actual_dimensions, (2, 3)); // (cols, rows)
                assert_eq!(expected_dimensions, (2, 2));
                assert_eq!(composition_name, "map_rows_mismatch");
            }
            _ => panic!("Expected MapDimensionMismatch error"),
        }
    }

    #[test]
    fn test_map_dimensions_unnamed_layer() {
        // Unnamed layer should say "unnamed layer" in error/warning
        let comp = Composition {
            name: "unnamed_layer_test".to_string(),
            base: None,
            size: Some([32, 32]),
            cell_size: Some([16, 16]),
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: None, // No name
                fill: None,
                map: Some(vec!["...".to_string()]),
                ..Default::default()
            }],
        };

        let (_, warnings) = render_composition(&comp, &HashMap::new(), false, None).unwrap();

        // Should have warning mentioning unnamed layer
        let dim_warnings: Vec<_> =
            warnings.iter().filter(|w| w.message.contains("unnamed layer")).collect();
        assert_eq!(dim_warnings.len(), 1);
    }

    #[test]
    fn test_cell_size_1x1_no_validation() {
        // With default cell_size [1,1], size divisibility doesn't apply
        // Size 65x65 with cell_size [1,1] should be fine
        let comp = Composition {
            name: "default_cell".to_string(),
            base: None,
            size: Some([65, 65]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec![".".to_string()]), // Just 1 cell
                ..Default::default()
            }],
        };

        let (_, warnings) = render_composition(&comp, &HashMap::new(), false, None).unwrap();

        // No divisibility or dimension warnings for cell_size [1,1]
        let validation_warnings: Vec<_> = warnings
            .iter()
            .filter(|w| {
                w.message.contains("not divisible") || w.message.contains("don't match expected")
            })
            .collect();
        assert!(validation_warnings.is_empty());
    }

    #[test]
    fn test_cell_size_none_no_validation() {
        // When cell_size is None (defaults to [1,1]), no validation
        let comp = Composition {
            name: "no_cell_size".to_string(),
            base: None,
            size: Some([65, 65]),
            cell_size: None, // Defaults to [1,1]
            sprites: HashMap::from([(".".to_string(), None)]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec![".".to_string()]),
                ..Default::default()
            }],
        };

        let (_, warnings) = render_composition(&comp, &HashMap::new(), false, None).unwrap();

        // No validation warnings
        let validation_warnings: Vec<_> = warnings
            .iter()
            .filter(|w| {
                w.message.contains("not divisible") || w.message.contains("don't match expected")
            })
            .collect();
        assert!(validation_warnings.is_empty());
    }

    #[test]
    fn test_size_not_divisible_error_display() {
        let err = CompositionError::SizeNotDivisible {
            size: (65, 64),
            cell_size: (16, 16),
            composition_name: "test_comp".to_string(),
        };

        let msg = format!("{}", err);
        assert!(msg.contains("65x64"));
        assert!(msg.contains("16x16"));
        assert!(msg.contains("test_comp"));
        assert!(msg.contains("not divisible"));
    }

    #[test]
    fn test_map_dimension_mismatch_error_display() {
        let err = CompositionError::MapDimensionMismatch {
            layer_name: Some("terrain".to_string()),
            actual_dimensions: (3, 2),
            expected_dimensions: (2, 2),
            composition_name: "test_comp".to_string(),
        };

        let msg = format!("{}", err);
        assert!(msg.contains("3x2"));
        assert!(msg.contains("2x2"));
        assert!(msg.contains("layer 'terrain'"));
        assert!(msg.contains("test_comp"));
    }

    #[test]
    fn test_map_dimension_mismatch_unnamed_error_display() {
        let err = CompositionError::MapDimensionMismatch {
            layer_name: None,
            actual_dimensions: (3, 2),
            expected_dimensions: (2, 2),
            composition_name: "test_comp".to_string(),
        };

        let msg = format!("{}", err);
        assert!(msg.contains("unnamed layer"));
    }

    // ========================================================================
    // Blend Mode Tests (ATF-10)
    // ========================================================================

    #[test]
    fn test_blend_mode_from_str() {
        assert_eq!(BlendMode::from_str("normal"), Some(BlendMode::Normal));
        assert_eq!(BlendMode::from_str("multiply"), Some(BlendMode::Multiply));
        assert_eq!(BlendMode::from_str("screen"), Some(BlendMode::Screen));
        assert_eq!(BlendMode::from_str("overlay"), Some(BlendMode::Overlay));
        assert_eq!(BlendMode::from_str("add"), Some(BlendMode::Add));
        assert_eq!(BlendMode::from_str("additive"), Some(BlendMode::Add));
        assert_eq!(BlendMode::from_str("subtract"), Some(BlendMode::Subtract));
        assert_eq!(BlendMode::from_str("difference"), Some(BlendMode::Difference));
        assert_eq!(BlendMode::from_str("darken"), Some(BlendMode::Darken));
        assert_eq!(BlendMode::from_str("lighten"), Some(BlendMode::Lighten));
        assert_eq!(BlendMode::from_str("NORMAL"), Some(BlendMode::Normal)); // case insensitive
        assert_eq!(BlendMode::from_str("unknown"), None);
    }

    #[test]
    fn test_blend_mode_multiply() {
        // Multiply: result = base * blend
        let mode = BlendMode::Multiply;
        // 0.5 * 0.5 = 0.25
        assert!((mode.blend_channel(0.5, 0.5) - 0.25).abs() < 0.01);
        // 1.0 * 0.5 = 0.5
        assert!((mode.blend_channel(1.0, 0.5) - 0.5).abs() < 0.01);
        // 0.0 * anything = 0.0
        assert!((mode.blend_channel(0.0, 1.0) - 0.0).abs() < 0.01);
    }

    #[test]
    fn test_blend_mode_screen() {
        // Screen: result = 1 - (1 - base) * (1 - blend)
        let mode = BlendMode::Screen;
        // 1 - (1 - 0.5) * (1 - 0.5) = 1 - 0.25 = 0.75
        assert!((mode.blend_channel(0.5, 0.5) - 0.75).abs() < 0.01);
        // Screen with white = white
        assert!((mode.blend_channel(0.5, 1.0) - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_blend_mode_add() {
        // Add: result = min(1, base + blend)
        let mode = BlendMode::Add;
        assert!((mode.blend_channel(0.3, 0.4) - 0.7).abs() < 0.01);
        // Clamped at 1.0
        assert!((mode.blend_channel(0.8, 0.5) - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_blend_mode_subtract() {
        // Subtract: result = max(0, base - blend)
        let mode = BlendMode::Subtract;
        assert!((mode.blend_channel(0.7, 0.3) - 0.4).abs() < 0.01);
        // Clamped at 0.0
        assert!((mode.blend_channel(0.3, 0.7) - 0.0).abs() < 0.01);
    }

    #[test]
    fn test_blend_mode_difference() {
        // Difference: result = abs(base - blend)
        let mode = BlendMode::Difference;
        assert!((mode.blend_channel(0.7, 0.3) - 0.4).abs() < 0.01);
        assert!((mode.blend_channel(0.3, 0.7) - 0.4).abs() < 0.01);
    }

    #[test]
    fn test_blend_mode_darken() {
        // Darken: result = min(base, blend)
        let mode = BlendMode::Darken;
        assert!((mode.blend_channel(0.7, 0.3) - 0.3).abs() < 0.01);
        assert!((mode.blend_channel(0.3, 0.7) - 0.3).abs() < 0.01);
    }

    #[test]
    fn test_blend_mode_lighten() {
        // Lighten: result = max(base, blend)
        let mode = BlendMode::Lighten;
        assert!((mode.blend_channel(0.7, 0.3) - 0.7).abs() < 0.01);
        assert!((mode.blend_channel(0.3, 0.7) - 0.7).abs() < 0.01);
    }

    #[test]
    fn test_blend_pixels_normal() {
        // Normal blend mode should be standard alpha compositing
        let src = Rgba([255, 0, 0, 255]); // Opaque red
        let dst = Rgba([0, 0, 255, 255]); // Opaque blue
        let result = blend_pixels(&src, &dst, BlendMode::Normal, 1.0);
        // Opaque source completely replaces
        assert_eq!(result, Rgba([255, 0, 0, 255]));
    }

    #[test]
    fn test_blend_pixels_multiply() {
        // Multiply should darken
        let src = Rgba([255, 128, 0, 255]); // Orange
        let dst = Rgba([255, 255, 255, 255]); // White
        let result = blend_pixels(&src, &dst, BlendMode::Multiply, 1.0);
        // Multiplying with white gives the original color
        assert_eq!(result[0], 255); // R
        assert_eq!(result[1], 128); // G (approximately)
        assert_eq!(result[2], 0); // B
    }

    #[test]
    fn test_opacity_reduces_effect() {
        // At 50% opacity, the source color should be half-strength
        let src = Rgba([255, 0, 0, 255]); // Opaque red
        let dst = Rgba([0, 0, 255, 255]); // Opaque blue
        let result = blend_pixels(&src, &dst, BlendMode::Normal, 0.5);
        // Should be a blend of red and blue
        assert!(result[0] > 100 && result[0] < 200); // Some red
        assert!(result[2] > 100 && result[2] < 200); // Some blue
    }

    #[test]
    fn test_composition_with_multiply_blend() {
        // Test multiply blend mode in a composition
        let comp = Composition {
            name: "multiply_test".to_string(),
            base: None,
            size: Some([2, 2]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                (".".to_string(), None), // transparent
                ("W".to_string(), Some("white".to_string())),
                ("S".to_string(), Some("shadow".to_string())),
            ]),
            layers: vec![
                CompositionLayer {
                    name: Some("background".to_string()),
                    fill: None,
                    map: Some(vec!["WW".to_string(), "WW".to_string()]),
                    blend: None, // Normal
                    opacity: None,
                    transform: None,
                },
                CompositionLayer {
                    name: Some("shadow".to_string()),
                    fill: None,
                    map: Some(vec!["S.".to_string(), "..".to_string()]),
                    blend: Some("multiply".to_string()),
                    opacity: None,
                    transform: None,
                },
            ],
        };

        // White background
        let mut white = RgbaImage::new(1, 1);
        white.put_pixel(0, 0, Rgba([255, 255, 255, 255]));

        // Gray shadow
        let mut shadow = RgbaImage::new(1, 1);
        shadow.put_pixel(0, 0, Rgba([128, 128, 128, 255]));

        let sprites = HashMap::from([("white".to_string(), white), ("shadow".to_string(), shadow)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // (0,0) should be darkened (white * gray = gray)
        let pixel = image.get_pixel(0, 0);
        assert!(pixel[0] < 200); // Darkened red
        assert!(pixel[1] < 200); // Darkened green
        assert!(pixel[2] < 200); // Darkened blue
                                 // (1,0) should still be white
        assert_eq!(*image.get_pixel(1, 0), Rgba([255, 255, 255, 255]));
    }

    #[test]
    fn test_composition_with_opacity() {
        // Test layer opacity
        let comp = Composition {
            name: "opacity_test".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                ("B".to_string(), Some("blue".to_string())),
                ("R".to_string(), Some("red".to_string())),
            ]),
            layers: vec![
                CompositionLayer {
                    name: Some("base".to_string()),
                    fill: None,
                    map: Some(vec!["B".to_string()]),
                    blend: None,
                    opacity: None, // Full opacity
                    transform: None,
                },
                CompositionLayer {
                    name: Some("overlay".to_string()),
                    fill: None,
                    map: Some(vec!["R".to_string()]),
                    blend: None,
                    opacity: Some(VarOr::Value(0.5)), // 50% opacity
                    transform: None,
                },
            ],
        };

        let mut blue = RgbaImage::new(1, 1);
        blue.put_pixel(0, 0, Rgba([0, 0, 255, 255]));

        let mut red = RgbaImage::new(1, 1);
        red.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("blue".to_string(), blue), ("red".to_string(), red)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // Should be a mix of red and blue (purple-ish)
        let pixel = image.get_pixel(0, 0);
        assert!(pixel[0] > 100); // Has red
        assert!(pixel[2] > 100); // Has blue
        assert!(pixel[0] < 255); // Not fully red
        assert!(pixel[2] < 255); // Not fully blue
    }

    #[test]
    fn test_composition_with_add_blend() {
        // Test additive blend mode (good for glows)
        let comp = Composition {
            name: "add_test".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([
                ("B".to_string(), Some("blue".to_string())),
                ("R".to_string(), Some("red".to_string())),
            ]),
            layers: vec![
                CompositionLayer {
                    name: Some("base".to_string()),
                    fill: None,
                    map: Some(vec!["B".to_string()]),
                    blend: None,
                    opacity: None,
                    transform: None,
                },
                CompositionLayer {
                    name: Some("glow".to_string()),
                    fill: None,
                    map: Some(vec!["R".to_string()]),
                    blend: Some("add".to_string()),
                    opacity: None,
                    transform: None,
                },
            ],
        };

        let mut blue = RgbaImage::new(1, 1);
        blue.put_pixel(0, 0, Rgba([0, 0, 255, 255]));

        let mut red = RgbaImage::new(1, 1);
        red.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("blue".to_string(), blue), ("red".to_string(), red)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // Add mode: blue + red = magenta
        let pixel = image.get_pixel(0, 0);
        assert_eq!(pixel[0], 255); // Full red
        assert_eq!(pixel[2], 255); // Full blue
    }

    #[test]
    fn test_layer_default_blend_and_opacity() {
        // Test that layers without blend/opacity work correctly (use defaults)
        let comp = Composition {
            name: "defaults_test".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([("R".to_string(), Some("red".to_string()))]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["R".to_string()]),
                blend: None,   // Default: normal
                opacity: None, // Default: 1.0
                transform: None,
            }],
        };

        let mut red = RgbaImage::new(1, 1);
        red.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("red".to_string(), red)]);

        let (image, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        assert!(warnings.is_empty());
        // Should be full red
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
    }

    #[test]
    fn test_unknown_blend_mode_uses_normal() {
        // Unknown blend mode should fall back to normal
        let comp = Composition {
            name: "unknown_blend".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([("R".to_string(), Some("red".to_string()))]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["R".to_string()]),
                blend: Some("invalid_blend_mode".to_string()),
                opacity: None,
                transform: None,
            }],
        };

        let mut red = RgbaImage::new(1, 1);
        red.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        let sprites = HashMap::from([("red".to_string(), red)]);

        let (image, _) = render_composition(&comp, &sprites, false, None).unwrap();

        // Should still work, falling back to normal blend
        assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
    }

    // ========================================================================
    // CSS Variable Tests (CSS-9)
    // ========================================================================

    #[test]
    fn test_resolve_blend_mode_with_var() {
        let mut registry = VariableRegistry::new();
        registry.define("--blend", "multiply");

        let (mode, warning) = resolve_blend_mode(Some("var(--blend)"), Some(&registry));
        assert_eq!(mode, BlendMode::Multiply);
        assert!(warning.is_none());
    }

    #[test]
    fn test_resolve_blend_mode_with_var_fallback() {
        let registry = VariableRegistry::new();

        // Missing variable with fallback
        let (mode, warning) = resolve_blend_mode(Some("var(--missing, screen)"), Some(&registry));
        assert_eq!(mode, BlendMode::Screen);
        assert!(warning.is_none());
    }

    #[test]
    fn test_resolve_blend_mode_undefined_var() {
        let registry = VariableRegistry::new();

        // Missing variable without fallback
        let (mode, warning) = resolve_blend_mode(Some("var(--undefined)"), Some(&registry));
        assert_eq!(mode, BlendMode::Normal);
        assert!(warning.is_some());
        assert!(warning.unwrap().message.contains("Failed to resolve"));
    }

    #[test]
    fn test_resolve_blend_mode_no_registry() {
        // var() used but no registry provided
        let (mode, warning) = resolve_blend_mode(Some("var(--blend)"), None);
        assert_eq!(mode, BlendMode::Normal);
        assert!(warning.is_some());
        assert!(warning.unwrap().message.contains("no variable registry"));
    }

    #[test]
    fn test_resolve_opacity_with_var() {
        let mut registry = VariableRegistry::new();
        registry.define("--opacity", "0.5");

        let var_opacity = VarOr::Var("var(--opacity)".to_string());
        let (opacity, warning) = resolve_opacity(Some(&var_opacity), Some(&registry));
        assert!((opacity - 0.5).abs() < 0.001);
        assert!(warning.is_none());
    }

    #[test]
    fn test_resolve_opacity_with_var_fallback() {
        let registry = VariableRegistry::new();

        // Missing variable with numeric fallback
        let var_opacity = VarOr::Var("var(--missing, 0.75)".to_string());
        let (opacity, warning) = resolve_opacity(Some(&var_opacity), Some(&registry));
        assert!((opacity - 0.75).abs() < 0.001);
        assert!(warning.is_none());
    }

    #[test]
    fn test_resolve_opacity_literal() {
        let registry = VariableRegistry::new();

        // Literal value (not var)
        let literal_opacity = VarOr::Value(0.3);
        let (opacity, warning) = resolve_opacity(Some(&literal_opacity), Some(&registry));
        assert!((opacity - 0.3).abs() < 0.001);
        assert!(warning.is_none());
    }

    #[test]
    fn test_resolve_opacity_clamps_values() {
        let mut registry = VariableRegistry::new();
        registry.define("--over", "2.0");
        registry.define("--under", "-0.5");

        // Value over 1.0 should clamp to 1.0
        let over = VarOr::Var("var(--over)".to_string());
        let (opacity, _) = resolve_opacity(Some(&over), Some(&registry));
        assert!((opacity - 1.0).abs() < 0.001);

        // Value under 0.0 should clamp to 0.0
        let under = VarOr::Var("var(--under)".to_string());
        let (opacity, _) = resolve_opacity(Some(&under), Some(&registry));
        assert!(opacity.abs() < 0.001);
    }

    #[test]
    fn test_resolve_opacity_invalid_number() {
        let mut registry = VariableRegistry::new();
        registry.define("--invalid", "not-a-number");

        let var_opacity = VarOr::Var("var(--invalid)".to_string());
        let (opacity, warning) = resolve_opacity(Some(&var_opacity), Some(&registry));
        assert!((opacity - 1.0).abs() < 0.001); // Falls back to 1.0
        assert!(warning.is_some());
        assert!(warning.unwrap().message.contains("not a valid number"));
    }

    #[test]
    fn test_resolve_opacity_no_registry() {
        let var_opacity = VarOr::Var("var(--opacity)".to_string());
        let (opacity, warning) = resolve_opacity(Some(&var_opacity), None);
        assert!((opacity - 1.0).abs() < 0.001); // Falls back to 1.0
        assert!(warning.is_some());
        assert!(warning.unwrap().message.contains("no variable registry"));
    }

    #[test]
    fn test_composition_with_var_opacity() {
        // Full integration test with composition rendering
        let mut registry = VariableRegistry::new();
        registry.define("--layer-opacity", "0.5");

        let comp = Composition {
            name: "var_opacity_test".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([("R".to_string(), Some("red".to_string()))]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["R".to_string()]),
                blend: None,
                opacity: Some(VarOr::Var("var(--layer-opacity)".to_string())),
                transform: None,
            }],
        };

        let mut red = RgbaImage::new(1, 1);
        red.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
        let sprites = HashMap::from([("red".to_string(), red)]);

        let (image, warnings) =
            render_composition(&comp, &sprites, false, Some(&registry)).unwrap();
        assert!(warnings.is_empty());

        // With 50% opacity on transparent background, the alpha should be 127/128
        let pixel = image.get_pixel(0, 0);
        assert_eq!(pixel[0], 255); // Red channel full
        assert!(pixel[3] < 200); // Alpha reduced due to opacity
    }

    #[test]
    fn test_composition_with_var_blend_mode() {
        let mut registry = VariableRegistry::new();
        registry.define("--layer-blend", "add");

        let comp = Composition {
            name: "var_blend_test".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([("R".to_string(), Some("red".to_string()))]),
            layers: vec![
                // Base layer
                CompositionLayer {
                    name: Some("base".to_string()),
                    fill: None,
                    map: Some(vec!["R".to_string()]),
                    blend: None,
                    opacity: Some(VarOr::Value(1.0)),
                    transform: None,
                },
                // Top layer with var blend
                CompositionLayer {
                    name: Some("top".to_string()),
                    fill: None,
                    map: Some(vec!["R".to_string()]),
                    blend: Some("var(--layer-blend)".to_string()),
                    opacity: Some(VarOr::Value(1.0)),
                    transform: None,
                },
            ],
        };

        let mut red = RgbaImage::new(1, 1);
        red.put_pixel(0, 0, Rgba([128, 0, 0, 255]));
        let sprites = HashMap::from([("red".to_string(), red)]);

        let (image, warnings) =
            render_composition(&comp, &sprites, false, Some(&registry)).unwrap();
        assert!(warnings.is_empty());

        // With additive blend mode, 128 + 128 = 255 (clamped)
        let pixel = image.get_pixel(0, 0);
        assert_eq!(pixel[0], 255); // Red should be clamped at 255
    }

    #[test]
    fn test_composition_var_without_registry_warns() {
        let comp = Composition {
            name: "no_registry_test".to_string(),
            base: None,
            size: Some([1, 1]),
            cell_size: Some([1, 1]),
            sprites: HashMap::from([("R".to_string(), Some("red".to_string()))]),
            layers: vec![CompositionLayer {
                name: None,
                fill: None,
                map: Some(vec!["R".to_string()]),
                blend: Some("var(--blend)".to_string()),
                opacity: Some(VarOr::Var("var(--opacity)".to_string())),
                transform: None,
            }],
        };

        let mut red = RgbaImage::new(1, 1);
        red.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
        let sprites = HashMap::from([("red".to_string(), red)]);

        // No registry passed
        let (_, warnings) = render_composition(&comp, &sprites, false, None).unwrap();

        // Should have warnings for both blend and opacity
        assert_eq!(warnings.len(), 2);
        assert!(warnings.iter().any(|w| w.message.contains("blend")));
        assert!(warnings.iter().any(|w| w.message.contains("Opacity")));
    }

    #[test]
    fn test_var_or_deserialization() {
        // Test that VarOr<f64> deserializes correctly from JSON
        use serde_json;

        // Number value
        let num: VarOr<f64> = serde_json::from_str("0.5").unwrap();
        assert!(matches!(num, VarOr::Value(v) if (v - 0.5).abs() < 0.001));

        // String var() reference
        let var: VarOr<f64> = serde_json::from_str(r#""var(--opacity)""#).unwrap();
        assert!(matches!(var, VarOr::Var(s) if s == "var(--opacity)"));

        // String var() with fallback
        let var_fb: VarOr<f64> = serde_json::from_str(r#""var(--opacity, 0.5)""#).unwrap();
        assert!(matches!(var_fb, VarOr::Var(s) if s == "var(--opacity, 0.5)"));
    }

    // ========== RenderContext Tests (NC-2, NC-3) ==========

    #[test]
    fn test_render_context_new() {
        let ctx = RenderContext::new();
        assert!(ctx.is_empty());
        assert_eq!(ctx.len(), 0);
        assert_eq!(ctx.depth(), 0);
        assert!(ctx.path().is_empty());
    }

    #[test]
    fn test_render_context_cache_and_get() {
        let mut ctx = RenderContext::new();

        // Create a test image
        let mut img = RgbaImage::new(2, 2);
        img.put_pixel(0, 0, Rgba([255, 0, 0, 255]));

        // Cache it
        ctx.cache("test_comp".to_string(), img);

        // Verify it's cached
        assert!(ctx.is_cached("test_comp"));
        assert_eq!(ctx.len(), 1);

        // Get it back
        let cached = ctx.get_cached("test_comp");
        assert!(cached.is_some());
        let cached = cached.unwrap();
        assert_eq!(cached.width(), 2);
        assert_eq!(cached.height(), 2);
        assert_eq!(*cached.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
    }

    #[test]
    fn test_render_context_get_cached_not_found() {
        let ctx = RenderContext::new();
        assert!(ctx.get_cached("nonexistent").is_none());
        assert!(!ctx.is_cached("nonexistent"));
    }

    #[test]
    fn test_render_context_cache_overwrites() {
        let mut ctx = RenderContext::new();

        // Cache first image (red)
        let mut img1 = RgbaImage::new(1, 1);
        img1.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
        ctx.cache("comp".to_string(), img1);

        // Cache second image with same name (blue)
        let mut img2 = RgbaImage::new(1, 1);
        img2.put_pixel(0, 0, Rgba([0, 0, 255, 255]));
        ctx.cache("comp".to_string(), img2);

        // Should still have only one entry
        assert_eq!(ctx.len(), 1);

        // Should be the second (blue) image
        let cached = ctx.get_cached("comp").unwrap();
        assert_eq!(*cached.get_pixel(0, 0), Rgba([0, 0, 255, 255]));
    }

    #[test]
    fn test_render_context_multiple_compositions() {
        let mut ctx = RenderContext::new();

        // Cache multiple compositions
        let mut img1 = RgbaImage::new(1, 1);
        img1.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
        ctx.cache("red".to_string(), img1);

        let mut img2 = RgbaImage::new(1, 1);
        img2.put_pixel(0, 0, Rgba([0, 255, 0, 255]));
        ctx.cache("green".to_string(), img2);

        let mut img3 = RgbaImage::new(1, 1);
        img3.put_pixel(0, 0, Rgba([0, 0, 255, 255]));
        ctx.cache("blue".to_string(), img3);

        assert_eq!(ctx.len(), 3);
        assert!(ctx.is_cached("red"));
        assert!(ctx.is_cached("green"));
        assert!(ctx.is_cached("blue"));

        // Verify colors
        assert_eq!(*ctx.get_cached("red").unwrap().get_pixel(0, 0), Rgba([255, 0, 0, 255]));
        assert_eq!(*ctx.get_cached("green").unwrap().get_pixel(0, 0), Rgba([0, 255, 0, 255]));
        assert_eq!(*ctx.get_cached("blue").unwrap().get_pixel(0, 0), Rgba([0, 0, 255, 255]));
    }

    #[test]
    fn test_render_context_clear() {
        let mut ctx = RenderContext::new();

        // Cache some compositions
        ctx.cache("a".to_string(), RgbaImage::new(1, 1));
        ctx.cache("b".to_string(), RgbaImage::new(1, 1));
        assert_eq!(ctx.len(), 2);

        // Clear
        ctx.clear();
        assert!(ctx.is_empty());
        assert_eq!(ctx.len(), 0);
        assert!(!ctx.is_cached("a"));
        assert!(!ctx.is_cached("b"));
    }

    #[test]
    fn test_render_context_cache_hit_avoids_rerender() {
        // This test demonstrates the cache usage pattern
        let mut ctx = RenderContext::new();
        let mut render_count = 0;

        // Simulate rendering "scene" twice with cache
        for _ in 0..2 {
            if ctx.get_cached("scene").is_none() {
                // "Render" the composition (in reality this would call render_composition)
                render_count += 1;
                let mut img = RgbaImage::new(4, 4);
                img.put_pixel(0, 0, Rgba([255, 0, 0, 255]));
                ctx.cache("scene".to_string(), img);
            }
            // Use the cached version
            let _cached = ctx.get_cached("scene").unwrap();
        }

        // Should only have rendered once
        assert_eq!(render_count, 1);
    }

    #[test]
    fn test_render_context_push_pop_basic() {
        let mut ctx = RenderContext::new();

        // Push A
        assert!(ctx.push("A").is_ok());
        assert_eq!(ctx.depth(), 1);
        assert!(ctx.contains("A"));
        assert!(!ctx.is_empty());

        // Push B
        assert!(ctx.push("B").is_ok());
        assert_eq!(ctx.depth(), 2);
        assert!(ctx.contains("A"));
        assert!(ctx.contains("B"));

        // Push C
        assert!(ctx.push("C").is_ok());
        assert_eq!(ctx.depth(), 3);
        assert_eq!(ctx.path(), &["A", "B", "C"]);

        // Pop C
        assert_eq!(ctx.pop(), Some("C".to_string()));
        assert_eq!(ctx.depth(), 2);
        assert!(!ctx.contains("C"));

        // Pop B
        assert_eq!(ctx.pop(), Some("B".to_string()));
        assert_eq!(ctx.depth(), 1);

        // Pop A
        assert_eq!(ctx.pop(), Some("A".to_string()));
        assert!(ctx.is_empty());

        // Pop empty returns None
        assert_eq!(ctx.pop(), None);
    }

    #[test]
    fn test_render_context_a_b_c_renders_ok() {
        // A -> B -> C renders OK (no cycles)
        let mut ctx = RenderContext::new();

        assert!(ctx.push("A").is_ok());
        assert!(ctx.push("B").is_ok());
        assert!(ctx.push("C").is_ok());

        assert_eq!(ctx.depth(), 3);
        assert_eq!(ctx.path(), &["A", "B", "C"]);
    }

    #[test]
    fn test_render_context_cycle_a_b_a() {
        // A -> B -> A returns CycleDetected error
        let mut ctx = RenderContext::new();

        assert!(ctx.push("A").is_ok());
        assert!(ctx.push("B").is_ok());

        let result = ctx.push("A");
        assert!(result.is_err());

        match result {
            Err(CompositionError::CycleDetected { cycle_path }) => {
                assert_eq!(cycle_path, vec!["A", "B", "A"]);
            }
            _ => panic!("Expected CycleDetected error"),
        }
    }

    #[test]
    fn test_render_context_self_reference_cycle() {
        // A -> A (self-reference) returns CycleDetected error
        let mut ctx = RenderContext::new();

        assert!(ctx.push("A").is_ok());

        let result = ctx.push("A");
        assert!(result.is_err());

        match result {
            Err(CompositionError::CycleDetected { cycle_path }) => {
                assert_eq!(cycle_path, vec!["A", "A"]);
            }
            _ => panic!("Expected CycleDetected error"),
        }
    }

    #[test]
    fn test_render_context_longer_cycle() {
        // A -> B -> C -> D -> B returns CycleDetected error with path B -> C -> D -> B
        let mut ctx = RenderContext::new();

        assert!(ctx.push("A").is_ok());
        assert!(ctx.push("B").is_ok());
        assert!(ctx.push("C").is_ok());
        assert!(ctx.push("D").is_ok());

        let result = ctx.push("B");
        assert!(result.is_err());

        match result {
            Err(CompositionError::CycleDetected { cycle_path }) => {
                assert_eq!(cycle_path, vec!["B", "C", "D", "B"]);
            }
            _ => panic!("Expected CycleDetected error"),
        }
    }

    #[test]
    fn test_render_context_cycle_error_message() {
        // Verify the error message format
        let mut ctx = RenderContext::new();
        ctx.push("scene").unwrap();
        ctx.push("background").unwrap();
        ctx.push("overlay").unwrap();

        let result = ctx.push("scene");
        let err = result.unwrap_err();
        let message = err.to_string();

        assert!(message.contains("Cycle detected"));
        assert!(message.contains("scene -> background -> overlay -> scene"));
    }

    #[test]
    fn test_render_context_reuse_after_pop() {
        // After popping, the same name can be pushed again
        let mut ctx = RenderContext::new();

        ctx.push("A").unwrap();
        ctx.push("B").unwrap();
        ctx.pop(); // Pop B

        // B can be pushed again
        assert!(ctx.push("B").is_ok());
        assert_eq!(ctx.path(), &["A", "B"]);
    }

    #[test]
    fn test_render_context_default() {
        // Default trait implementation
        let ctx: RenderContext = Default::default();
        assert!(ctx.is_empty());
        assert_eq!(ctx.depth(), 0);
    }

    #[test]
    fn test_render_context_clone() {
        let mut ctx = RenderContext::new();
        ctx.push("A").unwrap();
        ctx.push("B").unwrap();

        let cloned = ctx.clone();
        assert_eq!(cloned.depth(), 2);
        assert_eq!(cloned.path(), &["A", "B"]);

        // Original and clone are independent
        ctx.push("C").unwrap();
        assert_eq!(ctx.depth(), 3);
        assert_eq!(cloned.depth(), 2);
    }

    // ========== Nested Composition Tests (NC-4) ==========

    mod nested {
        use super::super::{
            render_composition_nested, Composition, CompositionError, RenderContext,
        };
        use crate::registry::CompositionRegistry;
        use image::{Rgba, RgbaImage};
        use std::collections::HashMap;

        /// Helper to create a simple composition
        fn make_composition(
            name: &str,
            sprites_map: HashMap<String, Option<String>>,
            layers: Vec<Vec<String>>,
            size: Option<[u32; 2]>,
        ) -> Composition {
            Composition {
                name: name.to_string(),
                base: None,
                size,
                cell_size: Some([2, 2]),
                sprites: sprites_map,
                layers: layers
                    .into_iter()
                    .map(|map| crate::models::CompositionLayer {
                        name: None,
                        fill: None,
                        map: Some(map),
                        transform: None,
                        blend: None,
                        opacity: None,
                    })
                    .collect(),
            }
        }

        /// Helper to create a 2x2 colored sprite image
        fn make_sprite_image(r: u8, g: u8, b: u8) -> RgbaImage {
            let mut img = RgbaImage::new(2, 2);
            for pixel in img.pixels_mut() {
                *pixel = Rgba([r, g, b, 255]);
            }
            img
        }

        #[test]
        fn test_nested_composition_with_sprite_regression() {
            // Regression test: composition referencing only sprites should still work
            let mut sprites = HashMap::new();
            sprites.insert("red".to_string(), make_sprite_image(255, 0, 0));
            sprites.insert("blue".to_string(), make_sprite_image(0, 0, 255));

            let sprites_map: HashMap<String, Option<String>> = [
                ("R".to_string(), Some("red".to_string())),
                ("B".to_string(), Some("blue".to_string())),
                (".".to_string(), None),
            ]
            .into_iter()
            .collect();

            let comp = make_composition(
                "main",
                sprites_map,
                vec![vec!["RB".to_string(), "BR".to_string()]],
                Some([4, 4]),
            );

            let composition_registry = CompositionRegistry::new();
            let mut ctx = RenderContext::new();

            let result = render_composition_nested(
                &comp,
                &sprites,
                Some(&composition_registry),
                &mut ctx,
                false,
                None,
            );

            assert!(result.is_ok());
            let (image, warnings) = result.unwrap();
            assert!(warnings.is_empty());
            assert_eq!(image.width(), 4);
            assert_eq!(image.height(), 4);

            // Check pixel colors: (0,0) should be red, (2,0) should be blue
            assert_eq!(image.get_pixel(0, 0)[0], 255); // Red
            assert_eq!(image.get_pixel(2, 0)[2], 255); // Blue
        }

        #[test]
        fn test_nested_composition_references_composition() {
            // Test: composition "main" references composition "sub" which uses sprite "pixel"
            let mut sprites = HashMap::new();
            sprites.insert("pixel".to_string(), make_sprite_image(128, 128, 128));

            // Create sub-composition that uses the pixel sprite
            let sub_sprites: HashMap<String, Option<String>> =
                [("P".to_string(), Some("pixel".to_string()))].into_iter().collect();

            let sub_comp =
                make_composition("sub", sub_sprites, vec![vec!["P".to_string()]], Some([2, 2]));

            // Create main composition that references "sub" composition
            let main_sprites: HashMap<String, Option<String>> =
                [("S".to_string(), Some("sub".to_string()))].into_iter().collect();

            let main_comp =
                make_composition("main", main_sprites, vec![vec!["S".to_string()]], Some([2, 2]));

            let mut composition_registry = CompositionRegistry::new();
            composition_registry.register(sub_comp);
            composition_registry.register(main_comp.clone());

            let mut ctx = RenderContext::new();

            let result = render_composition_nested(
                &main_comp,
                &sprites,
                Some(&composition_registry),
                &mut ctx,
                false,
                None,
            );

            assert!(result.is_ok());
            let (image, warnings) = result.unwrap();
            assert!(warnings.is_empty());
            assert_eq!(image.width(), 2);
            assert_eq!(image.height(), 2);

            // All pixels should be gray (from the nested composition)
            assert_eq!(*image.get_pixel(0, 0), Rgba([128, 128, 128, 255]));
        }

        #[test]
        fn test_nested_two_level_nesting() {
            // Test: A -> B -> sprite (two levels of nesting)
            let mut sprites = HashMap::new();
            sprites.insert("green".to_string(), make_sprite_image(0, 255, 0));

            // Level 2: comp_b uses sprite "green"
            let comp_b_sprites: HashMap<String, Option<String>> =
                [("G".to_string(), Some("green".to_string()))].into_iter().collect();

            let comp_b = make_composition(
                "comp_b",
                comp_b_sprites,
                vec![vec!["G".to_string()]],
                Some([2, 2]),
            );

            // Level 1: comp_a references comp_b
            let comp_a_sprites: HashMap<String, Option<String>> =
                [("B".to_string(), Some("comp_b".to_string()))].into_iter().collect();

            let comp_a = make_composition(
                "comp_a",
                comp_a_sprites,
                vec![vec!["B".to_string()]],
                Some([2, 2]),
            );

            // Top level: main references comp_a
            let main_sprites: HashMap<String, Option<String>> =
                [("A".to_string(), Some("comp_a".to_string()))].into_iter().collect();

            let main_comp =
                make_composition("main", main_sprites, vec![vec!["A".to_string()]], Some([2, 2]));

            let mut composition_registry = CompositionRegistry::new();
            composition_registry.register(comp_b);
            composition_registry.register(comp_a);
            composition_registry.register(main_comp.clone());

            let mut ctx = RenderContext::new();

            let result = render_composition_nested(
                &main_comp,
                &sprites,
                Some(&composition_registry),
                &mut ctx,
                false,
                None,
            );

            assert!(result.is_ok());
            let (image, warnings) = result.unwrap();
            assert!(warnings.is_empty());

            // Should have green color from the deeply nested sprite
            assert_eq!(*image.get_pixel(0, 0), Rgba([0, 255, 0, 255]));
        }

        #[test]
        fn test_nested_cycle_detection() {
            // Test: A -> B -> A should trigger cycle detection error
            let sprites = HashMap::new();

            // comp_a references comp_b
            let comp_a_sprites: HashMap<String, Option<String>> =
                [("B".to_string(), Some("comp_b".to_string()))].into_iter().collect();

            let comp_a = make_composition(
                "comp_a",
                comp_a_sprites,
                vec![vec!["B".to_string()]],
                Some([2, 2]),
            );

            // comp_b references comp_a (creates cycle)
            let comp_b_sprites: HashMap<String, Option<String>> =
                [("A".to_string(), Some("comp_a".to_string()))].into_iter().collect();

            let comp_b = make_composition(
                "comp_b",
                comp_b_sprites,
                vec![vec!["A".to_string()]],
                Some([2, 2]),
            );

            let mut composition_registry = CompositionRegistry::new();
            composition_registry.register(comp_a.clone());
            composition_registry.register(comp_b);

            let mut ctx = RenderContext::new();

            let result = render_composition_nested(
                &comp_a,
                &sprites,
                Some(&composition_registry),
                &mut ctx,
                false,
                None,
            );

            assert!(result.is_err());
            let err = result.unwrap_err();
            let message = err.to_string();
            assert!(message.contains("Cycle detected"));
        }

        #[test]
        fn test_nested_self_reference_cycle() {
            // Test: A -> A (self-reference cycle)
            let sprites = HashMap::new();

            let comp_sprites: HashMap<String, Option<String>> =
                [("A".to_string(), Some("self_ref".to_string()))].into_iter().collect();

            let comp = make_composition(
                "self_ref",
                comp_sprites,
                vec![vec!["A".to_string()]],
                Some([2, 2]),
            );

            let mut composition_registry = CompositionRegistry::new();
            composition_registry.register(comp.clone());

            let mut ctx = RenderContext::new();

            let result = render_composition_nested(
                &comp,
                &sprites,
                Some(&composition_registry),
                &mut ctx,
                false,
                None,
            );

            assert!(result.is_err());
            let err = result.unwrap_err();
            assert!(matches!(err, CompositionError::CycleDetected { .. }));
        }

        #[test]
        fn test_nested_cache_reuse() {
            // Test: same nested composition referenced multiple times uses cache
            let mut sprites = HashMap::new();
            sprites.insert("red".to_string(), make_sprite_image(255, 0, 0));

            // sub_comp uses red sprite
            let sub_sprites: HashMap<String, Option<String>> =
                [("R".to_string(), Some("red".to_string()))].into_iter().collect();

            let sub_comp =
                make_composition("sub", sub_sprites, vec![vec!["R".to_string()]], Some([2, 2]));

            // main_comp references "sub" twice in a 2x2 grid
            let main_sprites: HashMap<String, Option<String>> =
                [("S".to_string(), Some("sub".to_string()))].into_iter().collect();

            let main_comp = make_composition(
                "main",
                main_sprites,
                vec![vec!["SS".to_string(), "SS".to_string()]],
                Some([4, 4]),
            );

            let mut composition_registry = CompositionRegistry::new();
            composition_registry.register(sub_comp);
            composition_registry.register(main_comp.clone());

            let mut ctx = RenderContext::new();

            let result = render_composition_nested(
                &main_comp,
                &sprites,
                Some(&composition_registry),
                &mut ctx,
                false,
                None,
            );

            assert!(result.is_ok());
            let (image, _) = result.unwrap();

            // Verify the cache was used - "sub" should be cached
            assert!(ctx.is_cached("sub"));

            // All 4 cells should be red (from the cached sub composition)
            assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
            assert_eq!(*image.get_pixel(2, 0), Rgba([255, 0, 0, 255]));
            assert_eq!(*image.get_pixel(0, 2), Rgba([255, 0, 0, 255]));
            assert_eq!(*image.get_pixel(2, 2), Rgba([255, 0, 0, 255]));
        }

        #[test]
        fn test_nested_base_composition() {
            // Test: base can also be a composition reference
            let mut sprites = HashMap::new();
            sprites.insert("blue".to_string(), make_sprite_image(0, 0, 255));
            sprites.insert("red".to_string(), make_sprite_image(255, 0, 0));

            // background composition is all blue
            let bg_sprites: HashMap<String, Option<String>> =
                [("B".to_string(), Some("blue".to_string()))].into_iter().collect();

            let bg_comp = make_composition(
                "background",
                bg_sprites,
                vec![vec!["BB".to_string(), "BB".to_string()]],
                Some([4, 4]),
            );

            // main composition has background as base, with red overlay
            let main_sprites: HashMap<String, Option<String>> =
                [("R".to_string(), Some("red".to_string())), (".".to_string(), None)]
                    .into_iter()
                    .collect();

            let mut main_comp = make_composition(
                "main",
                main_sprites,
                vec![vec!["R.".to_string(), ".R".to_string()]],
                Some([4, 4]),
            );
            main_comp.base = Some("background".to_string());

            let mut composition_registry = CompositionRegistry::new();
            composition_registry.register(bg_comp);
            composition_registry.register(main_comp.clone());

            let mut ctx = RenderContext::new();

            let result = render_composition_nested(
                &main_comp,
                &sprites,
                Some(&composition_registry),
                &mut ctx,
                false,
                None,
            );

            assert!(result.is_ok());
            let (image, warnings) = result.unwrap();
            assert!(warnings.is_empty());

            // (0,0) should be red (overlay)
            assert_eq!(*image.get_pixel(0, 0), Rgba([255, 0, 0, 255]));
            // (2,0) should be blue (from background)
            assert_eq!(*image.get_pixel(2, 0), Rgba([0, 0, 255, 255]));
            // (2,2) should be red (overlay)
            assert_eq!(*image.get_pixel(2, 2), Rgba([255, 0, 0, 255]));
        }

        #[test]
        fn test_nested_missing_composition_warning() {
            // Test: referencing non-existent composition emits warning
            let sprites = HashMap::new();

            let main_sprites: HashMap<String, Option<String>> =
                [("X".to_string(), Some("nonexistent".to_string()))].into_iter().collect();

            let main_comp =
                make_composition("main", main_sprites, vec![vec!["X".to_string()]], Some([2, 2]));

            let composition_registry = CompositionRegistry::new();
            let mut ctx = RenderContext::new();

            let result = render_composition_nested(
                &main_comp,
                &sprites,
                Some(&composition_registry),
                &mut ctx,
                false,
                None,
            );

            assert!(result.is_ok());
            let (_, warnings) = result.unwrap();
            assert!(!warnings.is_empty());
            assert!(warnings[0].message.contains("not found"));
        }
    }
}