oxidize-pdf 2.5.1

A pure Rust PDF generation and manipulation library with zero external dependencies
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
pub mod calibrated_color;
pub mod clipping;
mod color;
mod color_profiles;
pub mod devicen_color;
pub mod extraction;
pub mod form_xobject;
mod indexed_color;
pub mod lab_color;
mod path;
mod patterns;
mod pdf_image;
mod png_decoder;
pub mod separation_color;
mod shadings;
pub mod soft_mask;
pub mod state;
pub mod transparency;

pub use calibrated_color::{CalGrayColorSpace, CalRgbColorSpace, CalibratedColor};
pub use clipping::{ClippingPath, ClippingRegion};
pub use color::Color;
pub use color_profiles::{IccColorSpace, IccProfile, IccProfileManager, StandardIccProfile};
pub use devicen_color::{
    AlternateColorSpace as DeviceNAlternateColorSpace, ColorantDefinition, ColorantType,
    DeviceNAttributes, DeviceNColorSpace, LinearTransform, SampledFunction, TintTransformFunction,
};
pub use form_xobject::{
    FormTemplates, FormXObject, FormXObjectBuilder, FormXObjectManager,
    TransparencyGroup as FormTransparencyGroup,
};
pub use indexed_color::{BaseColorSpace, ColorLookupTable, IndexedColorManager, IndexedColorSpace};
pub use lab_color::{LabColor, LabColorSpace};
pub use path::{LineCap, LineJoin, PathBuilder, PathCommand, WindingRule};
pub use patterns::{
    PaintType, PatternGraphicsContext, PatternManager, PatternMatrix, PatternType, TilingPattern,
    TilingType,
};
pub use pdf_image::{ColorSpace, Image, ImageFormat, MaskType};
pub use separation_color::{
    AlternateColorSpace, SeparationColor, SeparationColorSpace, SpotColors, TintTransform,
};
pub use shadings::{
    AxialShading, ColorStop, FunctionBasedShading, Point, RadialShading, ShadingDefinition,
    ShadingManager, ShadingPattern, ShadingType,
};
pub use soft_mask::{SoftMask, SoftMaskState, SoftMaskType};
pub use state::{
    BlendMode, ExtGState, ExtGStateFont, ExtGStateManager, Halftone, LineDashPattern,
    RenderingIntent, TransferFunction,
};
pub use transparency::TransparencyGroup;
use transparency::TransparencyGroupState;

use crate::error::Result;
use crate::text::{ColumnContent, ColumnLayout, Font, FontManager, ListElement, Table};
use std::collections::{HashMap, HashSet};
use std::fmt::Write;
use std::sync::Arc;

/// Saved graphics state for save/restore operations.
/// Using `Arc<str>` for `font_name` makes `Clone` O(1) — only increments the reference count.
#[derive(Clone)]
struct GraphicsState {
    fill_color: Color,
    stroke_color: Color,
    font_name: Option<Arc<str>>,
    font_size: f64,
    is_custom_font: bool,
}

#[derive(Clone)]
pub struct GraphicsContext {
    operations: String,
    current_color: Color,
    stroke_color: Color,
    line_width: f64,
    fill_opacity: f64,
    stroke_opacity: f64,
    // Extended Graphics State support
    extgstate_manager: ExtGStateManager,
    pending_extgstate: Option<ExtGState>,
    current_dash_pattern: Option<LineDashPattern>,
    current_miter_limit: f64,
    current_line_cap: LineCap,
    current_line_join: LineJoin,
    current_rendering_intent: RenderingIntent,
    current_flatness: f64,
    current_smoothness: f64,
    // Clipping support
    clipping_region: ClippingRegion,
    // Font management
    font_manager: Option<Arc<FontManager>>,
    // State stack for save/restore
    state_stack: Vec<GraphicsState>,
    current_font_name: Option<Arc<str>>,
    current_font_size: f64,
    // Whether the current font is a custom (Type0/CID) font requiring Unicode encoding
    is_custom_font: bool,
    // Character tracking for font subsetting
    used_characters: HashSet<char>,
    // Glyph mapping for Unicode fonts (Unicode code point -> Glyph ID)
    glyph_mapping: Option<HashMap<u32, u16>>,
    // Transparency group stack for nested groups
    transparency_stack: Vec<TransparencyGroupState>,
}

/// Encode a Unicode character as a CID hex value for Type0/Identity-H fonts.
/// BMP characters (U+0000..U+FFFF) are written as 4-hex-digit values.
/// Supplementary plane characters (U+10000..U+10FFFF) are written as UTF-16BE surrogate pairs.
fn encode_char_as_cid(ch: char, buf: &mut String) {
    let code = ch as u32;
    if code <= 0xFFFF {
        write!(buf, "{:04X}", code).expect("Writing to string should never fail");
    } else {
        // UTF-16BE surrogate pair for supplementary planes
        let adjusted = code - 0x10000;
        let high = ((adjusted >> 10) & 0x3FF) + 0xD800;
        let low = (adjusted & 0x3FF) + 0xDC00;
        write!(buf, "{:04X}{:04X}", high, low).expect("Writing to string should never fail");
    }
}

impl Default for GraphicsContext {
    fn default() -> Self {
        Self::new()
    }
}

impl GraphicsContext {
    pub fn new() -> Self {
        Self {
            operations: String::new(),
            current_color: Color::black(),
            stroke_color: Color::black(),
            line_width: 1.0,
            fill_opacity: 1.0,
            stroke_opacity: 1.0,
            // Extended Graphics State defaults
            extgstate_manager: ExtGStateManager::new(),
            pending_extgstate: None,
            current_dash_pattern: None,
            current_miter_limit: 10.0,
            current_line_cap: LineCap::Butt,
            current_line_join: LineJoin::Miter,
            current_rendering_intent: RenderingIntent::RelativeColorimetric,
            current_flatness: 1.0,
            current_smoothness: 0.0,
            // Clipping defaults
            clipping_region: ClippingRegion::new(),
            // Font defaults
            font_manager: None,
            state_stack: Vec::new(),
            current_font_name: None,
            current_font_size: 12.0,
            is_custom_font: false,
            used_characters: HashSet::new(),
            glyph_mapping: None,
            transparency_stack: Vec::new(),
        }
    }

    pub fn move_to(&mut self, x: f64, y: f64) -> &mut Self {
        writeln!(&mut self.operations, "{x:.2} {y:.2} m")
            .expect("Writing to string should never fail");
        self
    }

    pub fn line_to(&mut self, x: f64, y: f64) -> &mut Self {
        writeln!(&mut self.operations, "{x:.2} {y:.2} l")
            .expect("Writing to string should never fail");
        self
    }

    pub fn curve_to(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) -> &mut Self {
        writeln!(
            &mut self.operations,
            "{x1:.2} {y1:.2} {x2:.2} {y2:.2} {x3:.2} {y3:.2} c"
        )
        .expect("Writing to string should never fail");
        self
    }

    pub fn rect(&mut self, x: f64, y: f64, width: f64, height: f64) -> &mut Self {
        writeln!(
            &mut self.operations,
            "{x:.2} {y:.2} {width:.2} {height:.2} re"
        )
        .expect("Writing to string should never fail");
        self
    }

    pub fn circle(&mut self, cx: f64, cy: f64, radius: f64) -> &mut Self {
        let k = 0.552284749831;
        let r = radius;

        self.move_to(cx + r, cy);
        self.curve_to(cx + r, cy + k * r, cx + k * r, cy + r, cx, cy + r);
        self.curve_to(cx - k * r, cy + r, cx - r, cy + k * r, cx - r, cy);
        self.curve_to(cx - r, cy - k * r, cx - k * r, cy - r, cx, cy - r);
        self.curve_to(cx + k * r, cy - r, cx + r, cy - k * r, cx + r, cy);
        self.close_path()
    }

    pub fn close_path(&mut self) -> &mut Self {
        self.operations.push_str("h\n");
        self
    }

    pub fn stroke(&mut self) -> &mut Self {
        self.apply_pending_extgstate().unwrap_or_default();
        self.apply_stroke_color();
        self.operations.push_str("S\n");
        self
    }

    pub fn fill(&mut self) -> &mut Self {
        self.apply_pending_extgstate().unwrap_or_default();
        self.apply_fill_color();
        self.operations.push_str("f\n");
        self
    }

    pub fn fill_stroke(&mut self) -> &mut Self {
        self.apply_pending_extgstate().unwrap_or_default();
        self.apply_fill_color();
        self.apply_stroke_color();
        self.operations.push_str("B\n");
        self
    }

    pub fn set_stroke_color(&mut self, color: Color) -> &mut Self {
        self.stroke_color = color;
        self
    }

    pub fn set_fill_color(&mut self, color: Color) -> &mut Self {
        self.current_color = color;
        self
    }

    /// Set fill color using calibrated color space
    pub fn set_fill_color_calibrated(&mut self, color: CalibratedColor) -> &mut Self {
        // Generate a unique color space name
        let cs_name = match &color {
            CalibratedColor::Gray(_, _) => "CalGray1",
            CalibratedColor::Rgb(_, _) => "CalRGB1",
        };

        // Set the color space (this would need to be registered in the PDF resources)
        writeln!(&mut self.operations, "/{} cs", cs_name)
            .expect("Writing to string should never fail");

        // Set color values
        let values = color.values();
        for value in &values {
            write!(&mut self.operations, "{:.4} ", value)
                .expect("Writing to string should never fail");
        }
        writeln!(&mut self.operations, "sc").expect("Writing to string should never fail");

        self
    }

    /// Set stroke color using calibrated color space
    pub fn set_stroke_color_calibrated(&mut self, color: CalibratedColor) -> &mut Self {
        // Generate a unique color space name
        let cs_name = match &color {
            CalibratedColor::Gray(_, _) => "CalGray1",
            CalibratedColor::Rgb(_, _) => "CalRGB1",
        };

        // Set the color space (this would need to be registered in the PDF resources)
        writeln!(&mut self.operations, "/{} CS", cs_name)
            .expect("Writing to string should never fail");

        // Set color values
        let values = color.values();
        for value in &values {
            write!(&mut self.operations, "{:.4} ", value)
                .expect("Writing to string should never fail");
        }
        writeln!(&mut self.operations, "SC").expect("Writing to string should never fail");

        self
    }

    /// Set fill color using Lab color space
    pub fn set_fill_color_lab(&mut self, color: LabColor) -> &mut Self {
        // Set the color space (this would need to be registered in the PDF resources)
        writeln!(&mut self.operations, "/Lab1 cs").expect("Writing to string should never fail");

        // Set color values (normalized for PDF)
        let values = color.values();
        for value in &values {
            write!(&mut self.operations, "{:.4} ", value)
                .expect("Writing to string should never fail");
        }
        writeln!(&mut self.operations, "sc").expect("Writing to string should never fail");

        self
    }

    /// Set stroke color using Lab color space
    pub fn set_stroke_color_lab(&mut self, color: LabColor) -> &mut Self {
        // Set the color space (this would need to be registered in the PDF resources)
        writeln!(&mut self.operations, "/Lab1 CS").expect("Writing to string should never fail");

        // Set color values (normalized for PDF)
        let values = color.values();
        for value in &values {
            write!(&mut self.operations, "{:.4} ", value)
                .expect("Writing to string should never fail");
        }
        writeln!(&mut self.operations, "SC").expect("Writing to string should never fail");

        self
    }

    pub fn set_line_width(&mut self, width: f64) -> &mut Self {
        self.line_width = width;
        writeln!(&mut self.operations, "{width:.2} w")
            .expect("Writing to string should never fail");
        self
    }

    pub fn set_line_cap(&mut self, cap: LineCap) -> &mut Self {
        self.current_line_cap = cap;
        writeln!(&mut self.operations, "{} J", cap as u8)
            .expect("Writing to string should never fail");
        self
    }

    pub fn set_line_join(&mut self, join: LineJoin) -> &mut Self {
        self.current_line_join = join;
        writeln!(&mut self.operations, "{} j", join as u8)
            .expect("Writing to string should never fail");
        self
    }

    /// Set the opacity for both fill and stroke operations (0.0 to 1.0)
    pub fn set_opacity(&mut self, opacity: f64) -> &mut Self {
        let opacity = opacity.clamp(0.0, 1.0);
        self.fill_opacity = opacity;
        self.stroke_opacity = opacity;

        // Create pending ExtGState if opacity is not 1.0
        if opacity < 1.0 {
            let mut state = ExtGState::new();
            state.alpha_fill = Some(opacity);
            state.alpha_stroke = Some(opacity);
            self.pending_extgstate = Some(state);
        }

        self
    }

    /// Set the fill opacity (0.0 to 1.0)
    pub fn set_fill_opacity(&mut self, opacity: f64) -> &mut Self {
        self.fill_opacity = opacity.clamp(0.0, 1.0);

        // Update or create pending ExtGState
        if opacity < 1.0 {
            if let Some(ref mut state) = self.pending_extgstate {
                state.alpha_fill = Some(opacity);
            } else {
                let mut state = ExtGState::new();
                state.alpha_fill = Some(opacity);
                self.pending_extgstate = Some(state);
            }
        }

        self
    }

    /// Set the stroke opacity (0.0 to 1.0)
    pub fn set_stroke_opacity(&mut self, opacity: f64) -> &mut Self {
        self.stroke_opacity = opacity.clamp(0.0, 1.0);

        // Update or create pending ExtGState
        if opacity < 1.0 {
            if let Some(ref mut state) = self.pending_extgstate {
                state.alpha_stroke = Some(opacity);
            } else {
                let mut state = ExtGState::new();
                state.alpha_stroke = Some(opacity);
                self.pending_extgstate = Some(state);
            }
        }

        self
    }

    pub fn save_state(&mut self) -> &mut Self {
        self.operations.push_str("q\n");
        self.save_clipping_state();
        // Save color + font state
        self.state_stack.push(GraphicsState {
            fill_color: self.current_color,
            stroke_color: self.stroke_color,
            font_name: self.current_font_name.clone(),
            font_size: self.current_font_size,
            is_custom_font: self.is_custom_font,
        });
        self
    }

    pub fn restore_state(&mut self) -> &mut Self {
        self.operations.push_str("Q\n");
        self.restore_clipping_state();
        // Restore color + font state
        if let Some(state) = self.state_stack.pop() {
            self.current_color = state.fill_color;
            self.stroke_color = state.stroke_color;
            self.current_font_name = state.font_name;
            self.current_font_size = state.font_size;
            self.is_custom_font = state.is_custom_font;
        }
        self
    }

    /// Begin a transparency group
    /// ISO 32000-1:2008 Section 11.4
    pub fn begin_transparency_group(&mut self, group: TransparencyGroup) -> &mut Self {
        // Save current state
        self.save_state();

        // Mark beginning of transparency group with special comment
        writeln!(&mut self.operations, "% Begin Transparency Group")
            .expect("Writing to string should never fail");

        // Apply group settings via ExtGState
        let mut extgstate = ExtGState::new();
        extgstate = extgstate.with_blend_mode(group.blend_mode.clone());
        extgstate.alpha_fill = Some(group.opacity as f64);
        extgstate.alpha_stroke = Some(group.opacity as f64);

        // Apply the ExtGState
        self.pending_extgstate = Some(extgstate);
        let _ = self.apply_pending_extgstate();

        // Create group state and push to stack
        let mut group_state = TransparencyGroupState::new(group);
        // Save current operations state
        group_state.saved_state = self.operations.as_bytes().to_vec();
        self.transparency_stack.push(group_state);

        self
    }

    /// End a transparency group
    pub fn end_transparency_group(&mut self) -> &mut Self {
        if let Some(_group_state) = self.transparency_stack.pop() {
            // Mark end of transparency group
            writeln!(&mut self.operations, "% End Transparency Group")
                .expect("Writing to string should never fail");

            // Restore state
            self.restore_state();
        }
        self
    }

    /// Check if we're currently inside a transparency group
    pub fn in_transparency_group(&self) -> bool {
        !self.transparency_stack.is_empty()
    }

    /// Get the current transparency group (if any)
    pub fn current_transparency_group(&self) -> Option<&TransparencyGroup> {
        self.transparency_stack.last().map(|state| &state.group)
    }

    pub fn translate(&mut self, tx: f64, ty: f64) -> &mut Self {
        writeln!(&mut self.operations, "1 0 0 1 {tx:.2} {ty:.2} cm")
            .expect("Writing to string should never fail");
        self
    }

    pub fn scale(&mut self, sx: f64, sy: f64) -> &mut Self {
        writeln!(&mut self.operations, "{sx:.2} 0 0 {sy:.2} 0 0 cm")
            .expect("Writing to string should never fail");
        self
    }

    pub fn rotate(&mut self, angle: f64) -> &mut Self {
        let cos = angle.cos();
        let sin = angle.sin();
        writeln!(
            &mut self.operations,
            "{:.6} {:.6} {:.6} {:.6} 0 0 cm",
            cos, sin, -sin, cos
        )
        .expect("Writing to string should never fail");
        self
    }

    pub fn transform(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> &mut Self {
        writeln!(
            &mut self.operations,
            "{a:.2} {b:.2} {c:.2} {d:.2} {e:.2} {f:.2} cm"
        )
        .expect("Writing to string should never fail");
        self
    }

    pub fn rectangle(&mut self, x: f64, y: f64, width: f64, height: f64) -> &mut Self {
        self.rect(x, y, width, height)
    }

    pub fn draw_image(
        &mut self,
        image_name: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> &mut Self {
        // Save graphics state
        self.save_state();

        // Set up transformation matrix for image placement
        // PDF coordinate system has origin at bottom-left, so we need to translate and scale
        writeln!(
            &mut self.operations,
            "{width:.2} 0 0 {height:.2} {x:.2} {y:.2} cm"
        )
        .expect("Writing to string should never fail");

        // Draw the image XObject
        writeln!(&mut self.operations, "/{image_name} Do")
            .expect("Writing to string should never fail");

        // Restore graphics state
        self.restore_state();

        self
    }

    /// Draw an image with transparency support (soft mask)
    /// This method handles images with alpha channels or soft masks
    pub fn draw_image_with_transparency(
        &mut self,
        image_name: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
        mask_name: Option<&str>,
    ) -> &mut Self {
        // Save graphics state
        self.save_state();

        // If we have a mask, we need to set up an ExtGState with SMask
        if let Some(mask) = mask_name {
            // Create an ExtGState for the soft mask
            let mut extgstate = ExtGState::new();
            extgstate.set_soft_mask_name(mask.to_string());

            // Register and apply the ExtGState
            let gs_name = self
                .extgstate_manager
                .add_state(extgstate)
                .unwrap_or_else(|_| "GS1".to_string());
            writeln!(&mut self.operations, "/{} gs", gs_name)
                .expect("Writing to string should never fail");
        }

        // Set up transformation matrix for image placement
        writeln!(
            &mut self.operations,
            "{width:.2} 0 0 {height:.2} {x:.2} {y:.2} cm"
        )
        .expect("Writing to string should never fail");

        // Draw the image XObject
        writeln!(&mut self.operations, "/{image_name} Do")
            .expect("Writing to string should never fail");

        // If we had a mask, reset the soft mask to None
        if mask_name.is_some() {
            // Create an ExtGState that removes the soft mask
            let mut reset_extgstate = ExtGState::new();
            reset_extgstate.set_soft_mask_none();

            let gs_name = self
                .extgstate_manager
                .add_state(reset_extgstate)
                .unwrap_or_else(|_| "GS2".to_string());
            writeln!(&mut self.operations, "/{} gs", gs_name)
                .expect("Writing to string should never fail");
        }

        // Restore graphics state
        self.restore_state();

        self
    }

    fn apply_stroke_color(&mut self) {
        match self.stroke_color {
            Color::Rgb(r, g, b) => {
                writeln!(&mut self.operations, "{r:.3} {g:.3} {b:.3} RG")
                    .expect("Writing to string should never fail");
            }
            Color::Gray(g) => {
                writeln!(&mut self.operations, "{g:.3} G")
                    .expect("Writing to string should never fail");
            }
            Color::Cmyk(c, m, y, k) => {
                writeln!(&mut self.operations, "{c:.3} {m:.3} {y:.3} {k:.3} K")
                    .expect("Writing to string should never fail");
            }
        }
    }

    fn apply_fill_color(&mut self) {
        match self.current_color {
            Color::Rgb(r, g, b) => {
                writeln!(&mut self.operations, "{r:.3} {g:.3} {b:.3} rg")
                    .expect("Writing to string should never fail");
            }
            Color::Gray(g) => {
                writeln!(&mut self.operations, "{g:.3} g")
                    .expect("Writing to string should never fail");
            }
            Color::Cmyk(c, m, y, k) => {
                writeln!(&mut self.operations, "{c:.3} {m:.3} {y:.3} {k:.3} k")
                    .expect("Writing to string should never fail");
            }
        }
    }

    pub(crate) fn generate_operations(&self) -> Result<Vec<u8>> {
        Ok(self.operations.as_bytes().to_vec())
    }

    /// Check if transparency is used (opacity != 1.0)
    pub fn uses_transparency(&self) -> bool {
        self.fill_opacity < 1.0 || self.stroke_opacity < 1.0
    }

    /// Generate the graphics state dictionary for transparency
    pub fn generate_graphics_state_dict(&self) -> Option<String> {
        if !self.uses_transparency() {
            return None;
        }

        let mut dict = String::from("<< /Type /ExtGState");

        if self.fill_opacity < 1.0 {
            write!(&mut dict, " /ca {:.3}", self.fill_opacity)
                .expect("Writing to string should never fail");
        }

        if self.stroke_opacity < 1.0 {
            write!(&mut dict, " /CA {:.3}", self.stroke_opacity)
                .expect("Writing to string should never fail");
        }

        dict.push_str(" >>");
        Some(dict)
    }

    /// Get the current fill color
    pub fn fill_color(&self) -> Color {
        self.current_color
    }

    /// Get the current stroke color
    pub fn stroke_color(&self) -> Color {
        self.stroke_color
    }

    /// Get the current line width
    pub fn line_width(&self) -> f64 {
        self.line_width
    }

    /// Get the current fill opacity
    pub fn fill_opacity(&self) -> f64 {
        self.fill_opacity
    }

    /// Get the current stroke opacity
    pub fn stroke_opacity(&self) -> f64 {
        self.stroke_opacity
    }

    /// Get the operations string
    pub fn operations(&self) -> &str {
        &self.operations
    }

    /// Get the operations string (alias for testing)
    pub fn get_operations(&self) -> &str {
        &self.operations
    }

    /// Clear all operations
    pub fn clear(&mut self) {
        self.operations.clear();
    }

    /// Begin a text object
    pub fn begin_text(&mut self) -> &mut Self {
        self.operations.push_str("BT\n");
        self
    }

    /// End a text object
    pub fn end_text(&mut self) -> &mut Self {
        self.operations.push_str("ET\n");
        self
    }

    /// Set font and size
    pub fn set_font(&mut self, font: Font, size: f64) -> &mut Self {
        writeln!(&mut self.operations, "/{} {} Tf", font.pdf_name(), size)
            .expect("Writing to string should never fail");

        // Track font name, size, and type for Unicode detection and proper font handling
        match &font {
            Font::Custom(name) => {
                self.current_font_name = Some(Arc::from(name.as_str()));
                self.current_font_size = size;
                self.is_custom_font = true;
            }
            _ => {
                self.current_font_name = Some(Arc::from(font.pdf_name().as_str()));
                self.current_font_size = size;
                self.is_custom_font = false;
            }
        }

        self
    }

    /// Set text position
    pub fn set_text_position(&mut self, x: f64, y: f64) -> &mut Self {
        writeln!(&mut self.operations, "{x:.2} {y:.2} Td")
            .expect("Writing to string should never fail");
        self
    }

    /// Show text
    ///
    /// For custom (Type0/CID) fonts, text is encoded as Unicode code points (CIDs).
    /// BMP characters (U+0000..U+FFFF) are written as 4-hex-digit values.
    /// Supplementary plane characters (U+10000..U+10FFFF) use UTF-16BE surrogate pairs.
    /// For standard fonts, text is encoded as literal PDF strings.
    pub fn show_text(&mut self, text: &str) -> Result<&mut Self> {
        // Track used characters for font subsetting
        self.used_characters.extend(text.chars());

        if self.is_custom_font {
            // For custom fonts (CJK/Type0), encode as hex string with Unicode code points as CIDs
            self.operations.push('<');
            for ch in text.chars() {
                encode_char_as_cid(ch, &mut self.operations);
            }
            self.operations.push_str("> Tj\n");
        } else {
            // For standard fonts, escape special characters in PDF literal string
            self.operations.push('(');
            for ch in text.chars() {
                match ch {
                    '(' => self.operations.push_str("\\("),
                    ')' => self.operations.push_str("\\)"),
                    '\\' => self.operations.push_str("\\\\"),
                    '\n' => self.operations.push_str("\\n"),
                    '\r' => self.operations.push_str("\\r"),
                    '\t' => self.operations.push_str("\\t"),
                    _ => self.operations.push(ch),
                }
            }
            self.operations.push_str(") Tj\n");
        }
        Ok(self)
    }

    /// Set word spacing for text justification
    pub fn set_word_spacing(&mut self, spacing: f64) -> &mut Self {
        writeln!(&mut self.operations, "{spacing:.2} Tw")
            .expect("Writing to string should never fail");
        self
    }

    /// Set character spacing
    pub fn set_character_spacing(&mut self, spacing: f64) -> &mut Self {
        writeln!(&mut self.operations, "{spacing:.2} Tc")
            .expect("Writing to string should never fail");
        self
    }

    /// Show justified text with automatic word spacing calculation
    pub fn show_justified_text(&mut self, text: &str, target_width: f64) -> Result<&mut Self> {
        // Split text into words
        let words: Vec<&str> = text.split_whitespace().collect();
        if words.len() <= 1 {
            // Can't justify single word or empty text
            return self.show_text(text);
        }

        // Calculate natural width of text without extra spacing
        let text_without_spaces = words.join("");
        let natural_text_width = self.estimate_text_width_simple(&text_without_spaces);
        let space_width = self.estimate_text_width_simple(" ");
        let natural_width = natural_text_width + (space_width * (words.len() - 1) as f64);

        // Calculate extra spacing needed per word gap
        let extra_space_needed = target_width - natural_width;
        let word_gaps = (words.len() - 1) as f64;

        if word_gaps > 0.0 && extra_space_needed > 0.0 {
            let extra_word_spacing = extra_space_needed / word_gaps;

            // Set word spacing
            self.set_word_spacing(extra_word_spacing);

            // Show text (spaces will be expanded automatically)
            self.show_text(text)?;

            // Reset word spacing to default
            self.set_word_spacing(0.0);
        } else {
            // Fallback to normal text display
            self.show_text(text)?;
        }

        Ok(self)
    }

    /// Simple text width estimation (placeholder implementation)
    fn estimate_text_width_simple(&self, text: &str) -> f64 {
        // This is a simplified estimation. In a full implementation,
        // you would use actual font metrics.
        let font_size = self.current_font_size;
        text.len() as f64 * font_size * 0.6 // Approximate width factor
    }

    /// Render a table
    pub fn render_table(&mut self, table: &Table) -> Result<()> {
        table.render(self)
    }

    /// Render a list
    pub fn render_list(&mut self, list: &ListElement) -> Result<()> {
        match list {
            ListElement::Ordered(ordered) => ordered.render(self),
            ListElement::Unordered(unordered) => unordered.render(self),
        }
    }

    /// Render column layout
    pub fn render_column_layout(
        &mut self,
        layout: &ColumnLayout,
        content: &ColumnContent,
        x: f64,
        y: f64,
        height: f64,
    ) -> Result<()> {
        layout.render(self, content, x, y, height)
    }

    // Extended Graphics State methods

    /// Set line dash pattern
    pub fn set_line_dash_pattern(&mut self, pattern: LineDashPattern) -> &mut Self {
        self.current_dash_pattern = Some(pattern.clone());
        writeln!(&mut self.operations, "{} d", pattern.to_pdf_string())
            .expect("Writing to string should never fail");
        self
    }

    /// Set line dash pattern to solid (no dashes)
    pub fn set_line_solid(&mut self) -> &mut Self {
        self.current_dash_pattern = None;
        self.operations.push_str("[] 0 d\n");
        self
    }

    /// Set miter limit
    pub fn set_miter_limit(&mut self, limit: f64) -> &mut Self {
        self.current_miter_limit = limit.max(1.0);
        writeln!(&mut self.operations, "{:.2} M", self.current_miter_limit)
            .expect("Writing to string should never fail");
        self
    }

    /// Set rendering intent
    pub fn set_rendering_intent(&mut self, intent: RenderingIntent) -> &mut Self {
        self.current_rendering_intent = intent;
        writeln!(&mut self.operations, "/{} ri", intent.pdf_name())
            .expect("Writing to string should never fail");
        self
    }

    /// Set flatness tolerance
    pub fn set_flatness(&mut self, flatness: f64) -> &mut Self {
        self.current_flatness = flatness.clamp(0.0, 100.0);
        writeln!(&mut self.operations, "{:.2} i", self.current_flatness)
            .expect("Writing to string should never fail");
        self
    }

    /// Apply an ExtGState dictionary immediately
    pub fn apply_extgstate(&mut self, state: ExtGState) -> Result<&mut Self> {
        let state_name = self.extgstate_manager.add_state(state)?;
        writeln!(&mut self.operations, "/{state_name} gs")
            .expect("Writing to string should never fail");
        Ok(self)
    }

    /// Store an ExtGState to be applied before the next drawing operation
    #[allow(dead_code)]
    fn set_pending_extgstate(&mut self, state: ExtGState) {
        self.pending_extgstate = Some(state);
    }

    /// Apply any pending ExtGState before drawing
    fn apply_pending_extgstate(&mut self) -> Result<()> {
        if let Some(state) = self.pending_extgstate.take() {
            let state_name = self.extgstate_manager.add_state(state)?;
            writeln!(&mut self.operations, "/{state_name} gs")
                .expect("Writing to string should never fail");
        }
        Ok(())
    }

    /// Create and apply a custom ExtGState
    pub fn with_extgstate<F>(&mut self, builder: F) -> Result<&mut Self>
    where
        F: FnOnce(ExtGState) -> ExtGState,
    {
        let state = builder(ExtGState::new());
        self.apply_extgstate(state)
    }

    /// Set blend mode for transparency
    pub fn set_blend_mode(&mut self, mode: BlendMode) -> Result<&mut Self> {
        let state = ExtGState::new().with_blend_mode(mode);
        self.apply_extgstate(state)
    }

    /// Set alpha for both stroke and fill operations
    pub fn set_alpha(&mut self, alpha: f64) -> Result<&mut Self> {
        let state = ExtGState::new().with_alpha(alpha);
        self.apply_extgstate(state)
    }

    /// Set alpha for stroke operations only
    pub fn set_alpha_stroke(&mut self, alpha: f64) -> Result<&mut Self> {
        let state = ExtGState::new().with_alpha_stroke(alpha);
        self.apply_extgstate(state)
    }

    /// Set alpha for fill operations only
    pub fn set_alpha_fill(&mut self, alpha: f64) -> Result<&mut Self> {
        let state = ExtGState::new().with_alpha_fill(alpha);
        self.apply_extgstate(state)
    }

    /// Set overprint for stroke operations
    pub fn set_overprint_stroke(&mut self, overprint: bool) -> Result<&mut Self> {
        let state = ExtGState::new().with_overprint_stroke(overprint);
        self.apply_extgstate(state)
    }

    /// Set overprint for fill operations
    pub fn set_overprint_fill(&mut self, overprint: bool) -> Result<&mut Self> {
        let state = ExtGState::new().with_overprint_fill(overprint);
        self.apply_extgstate(state)
    }

    /// Set stroke adjustment
    pub fn set_stroke_adjustment(&mut self, adjustment: bool) -> Result<&mut Self> {
        let state = ExtGState::new().with_stroke_adjustment(adjustment);
        self.apply_extgstate(state)
    }

    /// Set smoothness tolerance
    pub fn set_smoothness(&mut self, smoothness: f64) -> Result<&mut Self> {
        self.current_smoothness = smoothness.clamp(0.0, 1.0);
        let state = ExtGState::new().with_smoothness(self.current_smoothness);
        self.apply_extgstate(state)
    }

    // Getters for extended graphics state

    /// Get current line dash pattern
    pub fn line_dash_pattern(&self) -> Option<&LineDashPattern> {
        self.current_dash_pattern.as_ref()
    }

    /// Get current miter limit
    pub fn miter_limit(&self) -> f64 {
        self.current_miter_limit
    }

    /// Get current line cap
    pub fn line_cap(&self) -> LineCap {
        self.current_line_cap
    }

    /// Get current line join
    pub fn line_join(&self) -> LineJoin {
        self.current_line_join
    }

    /// Get current rendering intent
    pub fn rendering_intent(&self) -> RenderingIntent {
        self.current_rendering_intent
    }

    /// Get current flatness tolerance
    pub fn flatness(&self) -> f64 {
        self.current_flatness
    }

    /// Get current smoothness tolerance
    pub fn smoothness(&self) -> f64 {
        self.current_smoothness
    }

    /// Get the ExtGState manager (for advanced usage)
    pub fn extgstate_manager(&self) -> &ExtGStateManager {
        &self.extgstate_manager
    }

    /// Get mutable ExtGState manager (for advanced usage)
    pub fn extgstate_manager_mut(&mut self) -> &mut ExtGStateManager {
        &mut self.extgstate_manager
    }

    /// Generate ExtGState resource dictionary for PDF
    pub fn generate_extgstate_resources(&self) -> Result<String> {
        self.extgstate_manager.to_resource_dictionary()
    }

    /// Check if any extended graphics states are defined
    pub fn has_extgstates(&self) -> bool {
        self.extgstate_manager.count() > 0
    }

    /// Add a command to the operations
    pub fn add_command(&mut self, command: &str) {
        self.operations.push_str(command);
        self.operations.push('\n');
    }

    /// Create clipping path from current path using non-zero winding rule
    pub fn clip(&mut self) -> &mut Self {
        self.operations.push_str("W\n");
        self
    }

    /// Create clipping path from current path using even-odd rule
    pub fn clip_even_odd(&mut self) -> &mut Self {
        self.operations.push_str("W*\n");
        self
    }

    /// Create clipping path and stroke it
    pub fn clip_stroke(&mut self) -> &mut Self {
        self.apply_stroke_color();
        self.operations.push_str("W S\n");
        self
    }

    /// Set a custom clipping path
    pub fn set_clipping_path(&mut self, path: ClippingPath) -> Result<&mut Self> {
        let ops = path.to_pdf_operations()?;
        self.operations.push_str(&ops);
        self.clipping_region.set_clip(path);
        Ok(self)
    }

    /// Clear the current clipping path
    pub fn clear_clipping(&mut self) -> &mut Self {
        self.clipping_region.clear_clip();
        self
    }

    /// Save the current clipping state (called automatically by save_state)
    fn save_clipping_state(&mut self) {
        self.clipping_region.save();
    }

    /// Restore the previous clipping state (called automatically by restore_state)
    fn restore_clipping_state(&mut self) {
        self.clipping_region.restore();
    }

    /// Create a rectangular clipping region
    pub fn clip_rect(&mut self, x: f64, y: f64, width: f64, height: f64) -> Result<&mut Self> {
        let path = ClippingPath::rect(x, y, width, height);
        self.set_clipping_path(path)
    }

    /// Create a circular clipping region
    pub fn clip_circle(&mut self, cx: f64, cy: f64, radius: f64) -> Result<&mut Self> {
        let path = ClippingPath::circle(cx, cy, radius);
        self.set_clipping_path(path)
    }

    /// Create an elliptical clipping region
    pub fn clip_ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64) -> Result<&mut Self> {
        let path = ClippingPath::ellipse(cx, cy, rx, ry);
        self.set_clipping_path(path)
    }

    /// Check if a clipping path is active
    pub fn has_clipping(&self) -> bool {
        self.clipping_region.has_clip()
    }

    /// Get the current clipping path
    pub fn clipping_path(&self) -> Option<&ClippingPath> {
        self.clipping_region.current()
    }

    /// Set the font manager for custom fonts
    pub fn set_font_manager(&mut self, font_manager: Arc<FontManager>) -> &mut Self {
        self.font_manager = Some(font_manager);
        self
    }

    /// Set the current font to a custom font
    pub fn set_custom_font(&mut self, font_name: &str, size: f64) -> &mut Self {
        // Emit Tf operator to the content stream (consistent with set_font)
        writeln!(&mut self.operations, "/{} {} Tf", font_name, size)
            .expect("Writing to string should never fail");

        self.current_font_name = Some(Arc::from(font_name));
        self.current_font_size = size;
        self.is_custom_font = true;

        // Try to get the glyph mapping from the font manager
        if let Some(ref font_manager) = self.font_manager {
            if let Some(mapping) = font_manager.get_font_glyph_mapping(font_name) {
                self.glyph_mapping = Some(mapping);
            }
        }

        self
    }

    /// Set the glyph mapping for Unicode fonts (Unicode -> GlyphID)
    pub fn set_glyph_mapping(&mut self, mapping: HashMap<u32, u16>) -> &mut Self {
        self.glyph_mapping = Some(mapping);
        self
    }

    /// Draw text at the specified position with automatic encoding detection
    pub fn draw_text(&mut self, text: &str, x: f64, y: f64) -> Result<&mut Self> {
        // Track used characters for font subsetting
        self.used_characters.extend(text.chars());

        // Detect if text needs Unicode encoding: custom fonts always use hex,
        // and text with non-Latin-1 characters also needs Unicode encoding
        let needs_unicode = self.is_custom_font || text.chars().any(|c| c as u32 > 255);

        // Use appropriate encoding based on content and font type
        if needs_unicode {
            self.draw_with_unicode_encoding(text, x, y)
        } else {
            self.draw_with_simple_encoding(text, x, y)
        }
    }

    /// Internal: Draw text with simple encoding (WinAnsiEncoding for standard fonts)
    fn draw_with_simple_encoding(&mut self, text: &str, x: f64, y: f64) -> Result<&mut Self> {
        // Check if text contains characters outside Latin-1
        let has_unicode = text.chars().any(|c| c as u32 > 255);

        if has_unicode {
            // Warning: Text contains Unicode characters but no Unicode font is set
            tracing::debug!("Warning: Text contains Unicode characters but using Latin-1 font. Characters will be replaced with '?'");
        }

        // Begin text object
        self.operations.push_str("BT\n");

        // Apply fill color for text rendering (must be inside BT...ET)
        self.apply_fill_color();

        // Set font if available
        if let Some(font_name) = &self.current_font_name {
            writeln!(
                &mut self.operations,
                "/{} {} Tf",
                font_name, self.current_font_size
            )
            .expect("Writing to string should never fail");
        } else {
            writeln!(
                &mut self.operations,
                "/Helvetica {} Tf",
                self.current_font_size
            )
            .expect("Writing to string should never fail");
        }

        // Set text position
        writeln!(&mut self.operations, "{:.2} {:.2} Td", x, y)
            .expect("Writing to string should never fail");

        // Use parentheses encoding for Latin-1 text (standard PDF fonts use WinAnsiEncoding)
        // This allows proper rendering of accented characters
        self.operations.push('(');
        for ch in text.chars() {
            let code = ch as u32;
            if code <= 127 {
                // ASCII characters - handle special characters that need escaping
                match ch {
                    '(' => self.operations.push_str("\\("),
                    ')' => self.operations.push_str("\\)"),
                    '\\' => self.operations.push_str("\\\\"),
                    '\n' => self.operations.push_str("\\n"),
                    '\r' => self.operations.push_str("\\r"),
                    '\t' => self.operations.push_str("\\t"),
                    _ => self.operations.push(ch),
                }
            } else if code <= 255 {
                // Latin-1 characters (128-255)
                // For WinAnsiEncoding, we can use octal notation for high-bit characters
                write!(&mut self.operations, "\\{:03o}", code)
                    .expect("Writing to string should never fail");
            } else {
                // Characters outside Latin-1 - replace with '?'
                self.operations.push('?');
            }
        }
        self.operations.push_str(") Tj\n");

        // End text object
        self.operations.push_str("ET\n");

        Ok(self)
    }

    /// Internal: Draw text with Unicode encoding (Type0/CID)
    fn draw_with_unicode_encoding(&mut self, text: &str, x: f64, y: f64) -> Result<&mut Self> {
        // Begin text object
        self.operations.push_str("BT\n");

        // Apply fill color for text rendering (must be inside BT...ET)
        self.apply_fill_color();

        // Set font - ensure it's a Type0 font for Unicode
        if let Some(font_name) = &self.current_font_name {
            // The font should be converted to Type0 by FontManager if needed
            writeln!(
                &mut self.operations,
                "/{} {} Tf",
                font_name, self.current_font_size
            )
            .expect("Writing to string should never fail");
        } else {
            writeln!(
                &mut self.operations,
                "/Helvetica {} Tf",
                self.current_font_size
            )
            .expect("Writing to string should never fail");
        }

        // Set text position
        writeln!(&mut self.operations, "{:.2} {:.2} Td", x, y)
            .expect("Writing to string should never fail");

        // For Type0 fonts with Identity-H encoding, write Unicode code points as CIDs.
        // The CIDToGIDMap in the font handles the CID → GlyphID conversion.
        self.operations.push('<');
        for ch in text.chars() {
            encode_char_as_cid(ch, &mut self.operations);
        }
        self.operations.push_str("> Tj\n");

        // End text object
        self.operations.push_str("ET\n");

        Ok(self)
    }

    /// Legacy: Draw text with hex encoding (kept for compatibility)
    #[deprecated(note = "Use draw_text() which automatically detects encoding")]
    pub fn draw_text_hex(&mut self, text: &str, x: f64, y: f64) -> Result<&mut Self> {
        // Begin text object
        self.operations.push_str("BT\n");

        // Apply fill color for text rendering (must be inside BT...ET)
        self.apply_fill_color();

        // Set font if available
        if let Some(font_name) = &self.current_font_name {
            writeln!(
                &mut self.operations,
                "/{} {} Tf",
                font_name, self.current_font_size
            )
            .expect("Writing to string should never fail");
        } else {
            // Fallback to Helvetica if no font is set
            writeln!(
                &mut self.operations,
                "/Helvetica {} Tf",
                self.current_font_size
            )
            .expect("Writing to string should never fail");
        }

        // Set text position
        writeln!(&mut self.operations, "{:.2} {:.2} Td", x, y)
            .expect("Writing to string should never fail");

        // Encode text as hex string
        // For TrueType fonts with Identity-H encoding, we need UTF-16BE
        // But we'll use single-byte encoding for now to fix spacing
        self.operations.push('<');
        for ch in text.chars() {
            if ch as u32 <= 255 {
                // For characters in the Latin-1 range, use single byte
                write!(&mut self.operations, "{:02X}", ch as u8)
                    .expect("Writing to string should never fail");
            } else {
                // For characters outside Latin-1, we need proper glyph mapping
                // For now, use a placeholder
                write!(&mut self.operations, "3F").expect("Writing to string should never fail");
                // '?' character
            }
        }
        self.operations.push_str("> Tj\n");

        // End text object
        self.operations.push_str("ET\n");

        Ok(self)
    }

    /// Legacy: Draw text with Type0 font encoding (kept for compatibility)
    #[deprecated(note = "Use draw_text() which automatically detects encoding")]
    pub fn draw_text_cid(&mut self, text: &str, x: f64, y: f64) -> Result<&mut Self> {
        use crate::fonts::needs_type0_font;

        // Begin text object
        self.operations.push_str("BT\n");

        // Apply fill color for text rendering (must be inside BT...ET)
        self.apply_fill_color();

        // Set font if available
        if let Some(font_name) = &self.current_font_name {
            writeln!(
                &mut self.operations,
                "/{} {} Tf",
                font_name, self.current_font_size
            )
            .expect("Writing to string should never fail");
        } else {
            writeln!(
                &mut self.operations,
                "/Helvetica {} Tf",
                self.current_font_size
            )
            .expect("Writing to string should never fail");
        }

        // Set text position
        writeln!(&mut self.operations, "{:.2} {:.2} Td", x, y)
            .expect("Writing to string should never fail");

        // Check if text needs Type0 encoding
        if needs_type0_font(text) {
            // Use 2-byte hex encoding for CIDs with identity mapping
            self.operations.push('<');
            for ch in text.chars() {
                encode_char_as_cid(ch, &mut self.operations);
            }
            self.operations.push_str("> Tj\n");
        } else {
            // Use regular single-byte encoding for Latin-1
            self.operations.push('<');
            for ch in text.chars() {
                if ch as u32 <= 255 {
                    write!(&mut self.operations, "{:02X}", ch as u8)
                        .expect("Writing to string should never fail");
                } else {
                    write!(&mut self.operations, "3F")
                        .expect("Writing to string should never fail");
                }
            }
            self.operations.push_str("> Tj\n");
        }

        // End text object
        self.operations.push_str("ET\n");
        Ok(self)
    }

    /// Legacy: Draw text with UTF-16BE encoding (kept for compatibility)
    #[deprecated(note = "Use draw_text() which automatically detects encoding")]
    pub fn draw_text_unicode(&mut self, text: &str, x: f64, y: f64) -> Result<&mut Self> {
        // Begin text object
        self.operations.push_str("BT\n");

        // Apply fill color for text rendering (must be inside BT...ET)
        self.apply_fill_color();

        // Set font if available
        if let Some(font_name) = &self.current_font_name {
            writeln!(
                &mut self.operations,
                "/{} {} Tf",
                font_name, self.current_font_size
            )
            .expect("Writing to string should never fail");
        } else {
            // Fallback to Helvetica if no font is set
            writeln!(
                &mut self.operations,
                "/Helvetica {} Tf",
                self.current_font_size
            )
            .expect("Writing to string should never fail");
        }

        // Set text position
        writeln!(&mut self.operations, "{:.2} {:.2} Td", x, y)
            .expect("Writing to string should never fail");

        // Encode text as UTF-16BE hex string
        self.operations.push('<');
        let mut utf16_buffer = [0u16; 2];
        for ch in text.chars() {
            let encoded = ch.encode_utf16(&mut utf16_buffer);
            for unit in encoded {
                // Write UTF-16BE (big-endian)
                write!(&mut self.operations, "{:04X}", unit)
                    .expect("Writing to string should never fail");
            }
        }
        self.operations.push_str("> Tj\n");

        // End text object
        self.operations.push_str("ET\n");

        Ok(self)
    }

    /// Get the characters used in this graphics context
    pub(crate) fn get_used_characters(&self) -> Option<HashSet<char>> {
        if self.used_characters.is_empty() {
            None
        } else {
            Some(self.used_characters.clone())
        }
    }
}

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

    #[test]
    fn test_graphics_context_new() {
        let ctx = GraphicsContext::new();
        assert_eq!(ctx.fill_color(), Color::black());
        assert_eq!(ctx.stroke_color(), Color::black());
        assert_eq!(ctx.line_width(), 1.0);
        assert_eq!(ctx.fill_opacity(), 1.0);
        assert_eq!(ctx.stroke_opacity(), 1.0);
        assert!(ctx.operations().is_empty());
    }

    #[test]
    fn test_graphics_context_default() {
        let ctx = GraphicsContext::default();
        assert_eq!(ctx.fill_color(), Color::black());
        assert_eq!(ctx.stroke_color(), Color::black());
        assert_eq!(ctx.line_width(), 1.0);
    }

    #[test]
    fn test_move_to() {
        let mut ctx = GraphicsContext::new();
        ctx.move_to(10.0, 20.0);
        assert!(ctx.operations().contains("10.00 20.00 m\n"));
    }

    #[test]
    fn test_line_to() {
        let mut ctx = GraphicsContext::new();
        ctx.line_to(30.0, 40.0);
        assert!(ctx.operations().contains("30.00 40.00 l\n"));
    }

    #[test]
    fn test_curve_to() {
        let mut ctx = GraphicsContext::new();
        ctx.curve_to(10.0, 20.0, 30.0, 40.0, 50.0, 60.0);
        assert!(ctx
            .operations()
            .contains("10.00 20.00 30.00 40.00 50.00 60.00 c\n"));
    }

    #[test]
    fn test_rect() {
        let mut ctx = GraphicsContext::new();
        ctx.rect(10.0, 20.0, 100.0, 50.0);
        assert!(ctx.operations().contains("10.00 20.00 100.00 50.00 re\n"));
    }

    #[test]
    fn test_rectangle_alias() {
        let mut ctx = GraphicsContext::new();
        ctx.rectangle(10.0, 20.0, 100.0, 50.0);
        assert!(ctx.operations().contains("10.00 20.00 100.00 50.00 re\n"));
    }

    #[test]
    fn test_circle() {
        let mut ctx = GraphicsContext::new();
        ctx.circle(50.0, 50.0, 25.0);

        let ops = ctx.operations();
        // Check that it starts with move to radius point
        assert!(ops.contains("75.00 50.00 m\n"));
        // Check that it contains curve operations
        assert!(ops.contains(" c\n"));
        // Check that it closes the path
        assert!(ops.contains("h\n"));
    }

    #[test]
    fn test_close_path() {
        let mut ctx = GraphicsContext::new();
        ctx.close_path();
        assert!(ctx.operations().contains("h\n"));
    }

    #[test]
    fn test_stroke() {
        let mut ctx = GraphicsContext::new();
        ctx.set_stroke_color(Color::red());
        ctx.rect(0.0, 0.0, 10.0, 10.0);
        ctx.stroke();

        let ops = ctx.operations();
        assert!(ops.contains("1.000 0.000 0.000 RG\n"));
        assert!(ops.contains("S\n"));
    }

    #[test]
    fn test_fill() {
        let mut ctx = GraphicsContext::new();
        ctx.set_fill_color(Color::blue());
        ctx.rect(0.0, 0.0, 10.0, 10.0);
        ctx.fill();

        let ops = ctx.operations();
        assert!(ops.contains("0.000 0.000 1.000 rg\n"));
        assert!(ops.contains("f\n"));
    }

    #[test]
    fn test_fill_stroke() {
        let mut ctx = GraphicsContext::new();
        ctx.set_fill_color(Color::green());
        ctx.set_stroke_color(Color::red());
        ctx.rect(0.0, 0.0, 10.0, 10.0);
        ctx.fill_stroke();

        let ops = ctx.operations();
        assert!(ops.contains("0.000 1.000 0.000 rg\n"));
        assert!(ops.contains("1.000 0.000 0.000 RG\n"));
        assert!(ops.contains("B\n"));
    }

    #[test]
    fn test_set_stroke_color() {
        let mut ctx = GraphicsContext::new();
        ctx.set_stroke_color(Color::rgb(0.5, 0.6, 0.7));
        assert_eq!(ctx.stroke_color(), Color::Rgb(0.5, 0.6, 0.7));
    }

    #[test]
    fn test_set_fill_color() {
        let mut ctx = GraphicsContext::new();
        ctx.set_fill_color(Color::gray(0.5));
        assert_eq!(ctx.fill_color(), Color::Gray(0.5));
    }

    #[test]
    fn test_set_line_width() {
        let mut ctx = GraphicsContext::new();
        ctx.set_line_width(2.5);
        assert_eq!(ctx.line_width(), 2.5);
        assert!(ctx.operations().contains("2.50 w\n"));
    }

    #[test]
    fn test_set_line_cap() {
        let mut ctx = GraphicsContext::new();
        ctx.set_line_cap(LineCap::Round);
        assert!(ctx.operations().contains("1 J\n"));

        ctx.set_line_cap(LineCap::Butt);
        assert!(ctx.operations().contains("0 J\n"));

        ctx.set_line_cap(LineCap::Square);
        assert!(ctx.operations().contains("2 J\n"));
    }

    #[test]
    fn test_set_line_join() {
        let mut ctx = GraphicsContext::new();
        ctx.set_line_join(LineJoin::Round);
        assert!(ctx.operations().contains("1 j\n"));

        ctx.set_line_join(LineJoin::Miter);
        assert!(ctx.operations().contains("0 j\n"));

        ctx.set_line_join(LineJoin::Bevel);
        assert!(ctx.operations().contains("2 j\n"));
    }

    #[test]
    fn test_save_restore_state() {
        let mut ctx = GraphicsContext::new();
        ctx.save_state();
        assert!(ctx.operations().contains("q\n"));

        ctx.restore_state();
        assert!(ctx.operations().contains("Q\n"));
    }

    #[test]
    fn test_translate() {
        let mut ctx = GraphicsContext::new();
        ctx.translate(50.0, 100.0);
        assert!(ctx.operations().contains("1 0 0 1 50.00 100.00 cm\n"));
    }

    #[test]
    fn test_scale() {
        let mut ctx = GraphicsContext::new();
        ctx.scale(2.0, 3.0);
        assert!(ctx.operations().contains("2.00 0 0 3.00 0 0 cm\n"));
    }

    #[test]
    fn test_rotate() {
        let mut ctx = GraphicsContext::new();
        let angle = std::f64::consts::PI / 4.0; // 45 degrees
        ctx.rotate(angle);

        let ops = ctx.operations();
        assert!(ops.contains(" cm\n"));
        // Should contain cos and sin values
        assert!(ops.contains("0.707107")); // Approximate cos(45°)
    }

    #[test]
    fn test_transform() {
        let mut ctx = GraphicsContext::new();
        ctx.transform(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
        assert!(ctx
            .operations()
            .contains("1.00 2.00 3.00 4.00 5.00 6.00 cm\n"));
    }

    #[test]
    fn test_draw_image() {
        let mut ctx = GraphicsContext::new();
        ctx.draw_image("Image1", 10.0, 20.0, 100.0, 150.0);

        let ops = ctx.operations();
        assert!(ops.contains("q\n")); // Save state
        assert!(ops.contains("100.00 0 0 150.00 10.00 20.00 cm\n")); // Transform
        assert!(ops.contains("/Image1 Do\n")); // Draw image
        assert!(ops.contains("Q\n")); // Restore state
    }

    #[test]
    fn test_gray_color_operations() {
        let mut ctx = GraphicsContext::new();
        ctx.set_stroke_color(Color::gray(0.5));
        ctx.set_fill_color(Color::gray(0.7));
        ctx.stroke();
        ctx.fill();

        let ops = ctx.operations();
        assert!(ops.contains("0.500 G\n")); // Stroke gray
        assert!(ops.contains("0.700 g\n")); // Fill gray
    }

    #[test]
    fn test_cmyk_color_operations() {
        let mut ctx = GraphicsContext::new();
        ctx.set_stroke_color(Color::cmyk(0.1, 0.2, 0.3, 0.4));
        ctx.set_fill_color(Color::cmyk(0.5, 0.6, 0.7, 0.8));
        ctx.stroke();
        ctx.fill();

        let ops = ctx.operations();
        assert!(ops.contains("0.100 0.200 0.300 0.400 K\n")); // Stroke CMYK
        assert!(ops.contains("0.500 0.600 0.700 0.800 k\n")); // Fill CMYK
    }

    #[test]
    fn test_method_chaining() {
        let mut ctx = GraphicsContext::new();
        ctx.move_to(0.0, 0.0)
            .line_to(10.0, 0.0)
            .line_to(10.0, 10.0)
            .line_to(0.0, 10.0)
            .close_path()
            .set_fill_color(Color::red())
            .fill();

        let ops = ctx.operations();
        assert!(ops.contains("0.00 0.00 m\n"));
        assert!(ops.contains("10.00 0.00 l\n"));
        assert!(ops.contains("10.00 10.00 l\n"));
        assert!(ops.contains("0.00 10.00 l\n"));
        assert!(ops.contains("h\n"));
        assert!(ops.contains("f\n"));
    }

    #[test]
    fn test_generate_operations() {
        let mut ctx = GraphicsContext::new();
        ctx.rect(0.0, 0.0, 10.0, 10.0);

        let result = ctx.generate_operations();
        assert!(result.is_ok());
        let bytes = result.expect("Writing to string should never fail");
        let ops_string = String::from_utf8(bytes).expect("Writing to string should never fail");
        assert!(ops_string.contains("0.00 0.00 10.00 10.00 re"));
    }

    #[test]
    fn test_clear_operations() {
        let mut ctx = GraphicsContext::new();
        ctx.rect(0.0, 0.0, 10.0, 10.0);
        assert!(!ctx.operations().is_empty());

        ctx.clear();
        assert!(ctx.operations().is_empty());
    }

    #[test]
    fn test_complex_path() {
        let mut ctx = GraphicsContext::new();
        ctx.save_state()
            .translate(100.0, 100.0)
            .rotate(std::f64::consts::PI / 6.0)
            .scale(2.0, 2.0)
            .set_line_width(2.0)
            .set_stroke_color(Color::blue())
            .move_to(0.0, 0.0)
            .line_to(50.0, 0.0)
            .curve_to(50.0, 25.0, 25.0, 50.0, 0.0, 50.0)
            .close_path()
            .stroke()
            .restore_state();

        let ops = ctx.operations();
        assert!(ops.contains("q\n"));
        assert!(ops.contains("cm\n"));
        assert!(ops.contains("2.00 w\n"));
        assert!(ops.contains("0.000 0.000 1.000 RG\n"));
        assert!(ops.contains("S\n"));
        assert!(ops.contains("Q\n"));
    }

    #[test]
    fn test_graphics_context_clone() {
        let mut ctx = GraphicsContext::new();
        ctx.set_fill_color(Color::red());
        ctx.set_stroke_color(Color::blue());
        ctx.set_line_width(3.0);
        ctx.set_opacity(0.5);
        ctx.rect(0.0, 0.0, 10.0, 10.0);

        let ctx_clone = ctx.clone();
        assert_eq!(ctx_clone.fill_color(), Color::red());
        assert_eq!(ctx_clone.stroke_color(), Color::blue());
        assert_eq!(ctx_clone.line_width(), 3.0);
        assert_eq!(ctx_clone.fill_opacity(), 0.5);
        assert_eq!(ctx_clone.stroke_opacity(), 0.5);
        assert_eq!(ctx_clone.operations(), ctx.operations());
    }

    #[test]
    fn test_set_opacity() {
        let mut ctx = GraphicsContext::new();

        // Test setting opacity
        ctx.set_opacity(0.5);
        assert_eq!(ctx.fill_opacity(), 0.5);
        assert_eq!(ctx.stroke_opacity(), 0.5);

        // Test clamping to valid range
        ctx.set_opacity(1.5);
        assert_eq!(ctx.fill_opacity(), 1.0);
        assert_eq!(ctx.stroke_opacity(), 1.0);

        ctx.set_opacity(-0.5);
        assert_eq!(ctx.fill_opacity(), 0.0);
        assert_eq!(ctx.stroke_opacity(), 0.0);
    }

    #[test]
    fn test_set_fill_opacity() {
        let mut ctx = GraphicsContext::new();

        ctx.set_fill_opacity(0.3);
        assert_eq!(ctx.fill_opacity(), 0.3);
        assert_eq!(ctx.stroke_opacity(), 1.0); // Should not affect stroke

        // Test clamping
        ctx.set_fill_opacity(2.0);
        assert_eq!(ctx.fill_opacity(), 1.0);
    }

    #[test]
    fn test_set_stroke_opacity() {
        let mut ctx = GraphicsContext::new();

        ctx.set_stroke_opacity(0.7);
        assert_eq!(ctx.stroke_opacity(), 0.7);
        assert_eq!(ctx.fill_opacity(), 1.0); // Should not affect fill

        // Test clamping
        ctx.set_stroke_opacity(-1.0);
        assert_eq!(ctx.stroke_opacity(), 0.0);
    }

    #[test]
    fn test_uses_transparency() {
        let mut ctx = GraphicsContext::new();

        // Initially no transparency
        assert!(!ctx.uses_transparency());

        // With fill transparency
        ctx.set_fill_opacity(0.5);
        assert!(ctx.uses_transparency());

        // Reset and test stroke transparency
        ctx.set_fill_opacity(1.0);
        assert!(!ctx.uses_transparency());
        ctx.set_stroke_opacity(0.8);
        assert!(ctx.uses_transparency());

        // Both transparent
        ctx.set_fill_opacity(0.5);
        assert!(ctx.uses_transparency());
    }

    #[test]
    fn test_generate_graphics_state_dict() {
        let mut ctx = GraphicsContext::new();

        // No transparency
        assert_eq!(ctx.generate_graphics_state_dict(), None);

        // Fill opacity only
        ctx.set_fill_opacity(0.5);
        let dict = ctx
            .generate_graphics_state_dict()
            .expect("Writing to string should never fail");
        assert!(dict.contains("/Type /ExtGState"));
        assert!(dict.contains("/ca 0.500"));
        assert!(!dict.contains("/CA"));

        // Stroke opacity only
        ctx.set_fill_opacity(1.0);
        ctx.set_stroke_opacity(0.75);
        let dict = ctx
            .generate_graphics_state_dict()
            .expect("Writing to string should never fail");
        assert!(dict.contains("/Type /ExtGState"));
        assert!(dict.contains("/CA 0.750"));
        assert!(!dict.contains("/ca"));

        // Both opacities
        ctx.set_fill_opacity(0.25);
        let dict = ctx
            .generate_graphics_state_dict()
            .expect("Writing to string should never fail");
        assert!(dict.contains("/Type /ExtGState"));
        assert!(dict.contains("/ca 0.250"));
        assert!(dict.contains("/CA 0.750"));
    }

    #[test]
    fn test_opacity_with_graphics_operations() {
        let mut ctx = GraphicsContext::new();

        ctx.set_fill_color(Color::red())
            .set_opacity(0.5)
            .rect(10.0, 10.0, 100.0, 100.0)
            .fill();

        assert_eq!(ctx.fill_opacity(), 0.5);
        assert_eq!(ctx.stroke_opacity(), 0.5);

        let ops = ctx.operations();
        assert!(ops.contains("10.00 10.00 100.00 100.00 re"));
        assert!(ops.contains("1.000 0.000 0.000 rg")); // Red color
        assert!(ops.contains("f")); // Fill
    }

    #[test]
    fn test_begin_end_text() {
        let mut ctx = GraphicsContext::new();
        ctx.begin_text();
        assert!(ctx.operations().contains("BT\n"));

        ctx.end_text();
        assert!(ctx.operations().contains("ET\n"));
    }

    #[test]
    fn test_set_font() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Helvetica, 12.0);
        assert!(ctx.operations().contains("/Helvetica 12 Tf\n"));

        ctx.set_font(Font::TimesBold, 14.5);
        assert!(ctx.operations().contains("/Times-Bold 14.5 Tf\n"));
    }

    #[test]
    fn test_set_text_position() {
        let mut ctx = GraphicsContext::new();
        ctx.set_text_position(100.0, 200.0);
        assert!(ctx.operations().contains("100.00 200.00 Td\n"));
    }

    #[test]
    fn test_show_text() {
        let mut ctx = GraphicsContext::new();
        ctx.show_text("Hello World")
            .expect("Writing to string should never fail");
        assert!(ctx.operations().contains("(Hello World) Tj\n"));
    }

    #[test]
    fn test_show_text_with_escaping() {
        let mut ctx = GraphicsContext::new();
        ctx.show_text("Test (parentheses)")
            .expect("Writing to string should never fail");
        assert!(ctx.operations().contains("(Test \\(parentheses\\)) Tj\n"));

        ctx.clear();
        ctx.show_text("Back\\slash")
            .expect("Writing to string should never fail");
        assert!(ctx.operations().contains("(Back\\\\slash) Tj\n"));

        ctx.clear();
        ctx.show_text("Line\nBreak")
            .expect("Writing to string should never fail");
        assert!(ctx.operations().contains("(Line\\nBreak) Tj\n"));
    }

    #[test]
    fn test_text_operations_chaining() {
        let mut ctx = GraphicsContext::new();
        ctx.begin_text()
            .set_font(Font::Courier, 10.0)
            .set_text_position(50.0, 100.0)
            .show_text("Test")
            .unwrap()
            .end_text();

        let ops = ctx.operations();
        assert!(ops.contains("BT\n"));
        assert!(ops.contains("/Courier 10 Tf\n"));
        assert!(ops.contains("50.00 100.00 Td\n"));
        assert!(ops.contains("(Test) Tj\n"));
        assert!(ops.contains("ET\n"));
    }

    #[test]
    fn test_clip() {
        let mut ctx = GraphicsContext::new();
        ctx.clip();
        assert!(ctx.operations().contains("W\n"));
    }

    #[test]
    fn test_clip_even_odd() {
        let mut ctx = GraphicsContext::new();
        ctx.clip_even_odd();
        assert!(ctx.operations().contains("W*\n"));
    }

    #[test]
    fn test_clipping_with_path() {
        let mut ctx = GraphicsContext::new();

        // Create a rectangular clipping path
        ctx.rect(10.0, 10.0, 100.0, 50.0).clip();

        let ops = ctx.operations();
        assert!(ops.contains("10.00 10.00 100.00 50.00 re\n"));
        assert!(ops.contains("W\n"));
    }

    #[test]
    fn test_clipping_even_odd_with_path() {
        let mut ctx = GraphicsContext::new();

        // Create a complex path and clip with even-odd rule
        ctx.move_to(0.0, 0.0)
            .line_to(100.0, 0.0)
            .line_to(100.0, 100.0)
            .line_to(0.0, 100.0)
            .close_path()
            .clip_even_odd();

        let ops = ctx.operations();
        assert!(ops.contains("0.00 0.00 m\n"));
        assert!(ops.contains("100.00 0.00 l\n"));
        assert!(ops.contains("100.00 100.00 l\n"));
        assert!(ops.contains("0.00 100.00 l\n"));
        assert!(ops.contains("h\n"));
        assert!(ops.contains("W*\n"));
    }

    #[test]
    fn test_clipping_chaining() {
        let mut ctx = GraphicsContext::new();

        // Test method chaining with clipping
        ctx.save_state()
            .rect(20.0, 20.0, 60.0, 60.0)
            .clip()
            .set_fill_color(Color::red())
            .rect(0.0, 0.0, 100.0, 100.0)
            .fill()
            .restore_state();

        let ops = ctx.operations();
        assert!(ops.contains("q\n"));
        assert!(ops.contains("20.00 20.00 60.00 60.00 re\n"));
        assert!(ops.contains("W\n"));
        assert!(ops.contains("1.000 0.000 0.000 rg\n"));
        assert!(ops.contains("0.00 0.00 100.00 100.00 re\n"));
        assert!(ops.contains("f\n"));
        assert!(ops.contains("Q\n"));
    }

    #[test]
    fn test_multiple_clipping_regions() {
        let mut ctx = GraphicsContext::new();

        // Test nested clipping regions
        ctx.save_state()
            .rect(0.0, 0.0, 200.0, 200.0)
            .clip()
            .save_state()
            .circle(100.0, 100.0, 50.0)
            .clip_even_odd()
            .set_fill_color(Color::blue())
            .rect(50.0, 50.0, 100.0, 100.0)
            .fill()
            .restore_state()
            .restore_state();

        let ops = ctx.operations();
        // Check for nested save/restore states
        let q_count = ops.matches("q\n").count();
        let q_restore_count = ops.matches("Q\n").count();
        assert_eq!(q_count, 2);
        assert_eq!(q_restore_count, 2);

        // Check for both clipping operations
        assert!(ops.contains("W\n"));
        assert!(ops.contains("W*\n"));
    }

    // ============= Additional Critical Method Tests =============

    #[test]
    fn test_move_to_and_line_to() {
        let mut ctx = GraphicsContext::new();
        ctx.move_to(100.0, 200.0).line_to(300.0, 400.0).stroke();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("100.00 200.00 m"));
        assert!(ops_str.contains("300.00 400.00 l"));
        assert!(ops_str.contains("S"));
    }

    #[test]
    fn test_bezier_curve() {
        let mut ctx = GraphicsContext::new();
        ctx.move_to(0.0, 0.0)
            .curve_to(10.0, 20.0, 30.0, 40.0, 50.0, 60.0)
            .stroke();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("0.00 0.00 m"));
        assert!(ops_str.contains("10.00 20.00 30.00 40.00 50.00 60.00 c"));
        assert!(ops_str.contains("S"));
    }

    #[test]
    fn test_circle_path() {
        let mut ctx = GraphicsContext::new();
        ctx.circle(100.0, 100.0, 50.0).fill();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        // Circle should use bezier curves (c operator)
        assert!(ops_str.contains(" c"));
        assert!(ops_str.contains("f"));
    }

    #[test]
    fn test_path_closing() {
        let mut ctx = GraphicsContext::new();
        ctx.move_to(0.0, 0.0)
            .line_to(100.0, 0.0)
            .line_to(100.0, 100.0)
            .close_path()
            .stroke();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("h")); // close path operator
        assert!(ops_str.contains("S"));
    }

    #[test]
    fn test_fill_and_stroke() {
        let mut ctx = GraphicsContext::new();
        ctx.rect(10.0, 10.0, 50.0, 50.0).fill_stroke();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("10.00 10.00 50.00 50.00 re"));
        assert!(ops_str.contains("B")); // fill and stroke operator
    }

    #[test]
    fn test_color_settings() {
        let mut ctx = GraphicsContext::new();
        ctx.set_fill_color(Color::rgb(1.0, 0.0, 0.0))
            .set_stroke_color(Color::rgb(0.0, 1.0, 0.0))
            .rect(10.0, 10.0, 50.0, 50.0)
            .fill_stroke(); // This will write the colors

        assert_eq!(ctx.fill_color(), Color::rgb(1.0, 0.0, 0.0));
        assert_eq!(ctx.stroke_color(), Color::rgb(0.0, 1.0, 0.0));

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("1.000 0.000 0.000 rg")); // red fill
        assert!(ops_str.contains("0.000 1.000 0.000 RG")); // green stroke
    }

    #[test]
    fn test_line_styles() {
        let mut ctx = GraphicsContext::new();
        ctx.set_line_width(2.5)
            .set_line_cap(LineCap::Round)
            .set_line_join(LineJoin::Bevel);

        assert_eq!(ctx.line_width(), 2.5);

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("2.50 w")); // line width
        assert!(ops_str.contains("1 J")); // round line cap
        assert!(ops_str.contains("2 j")); // bevel line join
    }

    #[test]
    fn test_opacity_settings() {
        let mut ctx = GraphicsContext::new();
        ctx.set_opacity(0.5);

        assert_eq!(ctx.fill_opacity(), 0.5);
        assert_eq!(ctx.stroke_opacity(), 0.5);
        assert!(ctx.uses_transparency());

        ctx.set_fill_opacity(0.7).set_stroke_opacity(0.3);

        assert_eq!(ctx.fill_opacity(), 0.7);
        assert_eq!(ctx.stroke_opacity(), 0.3);
    }

    #[test]
    fn test_state_save_restore() {
        let mut ctx = GraphicsContext::new();
        ctx.save_state()
            .set_fill_color(Color::rgb(1.0, 0.0, 0.0))
            .restore_state();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("q")); // save state
        assert!(ops_str.contains("Q")); // restore state
    }

    #[test]
    fn test_transformations() {
        let mut ctx = GraphicsContext::new();
        ctx.translate(100.0, 200.0).scale(2.0, 3.0).rotate(45.0);

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("1 0 0 1 100.00 200.00 cm")); // translate
        assert!(ops_str.contains("2.00 0 0 3.00 0 0 cm")); // scale
        assert!(ops_str.contains("cm")); // rotate matrix
    }

    #[test]
    fn test_custom_transform() {
        let mut ctx = GraphicsContext::new();
        ctx.transform(1.0, 0.5, 0.5, 1.0, 10.0, 20.0);

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("1.00 0.50 0.50 1.00 10.00 20.00 cm"));
    }

    #[test]
    fn test_rectangle_path() {
        let mut ctx = GraphicsContext::new();
        ctx.rectangle(25.0, 25.0, 150.0, 100.0).stroke();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("25.00 25.00 150.00 100.00 re"));
        assert!(ops_str.contains("S"));
    }

    #[test]
    fn test_empty_operations() {
        let ctx = GraphicsContext::new();
        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        assert!(ops.is_empty());
    }

    #[test]
    fn test_complex_path_operations() {
        let mut ctx = GraphicsContext::new();
        ctx.move_to(50.0, 50.0)
            .line_to(100.0, 50.0)
            .curve_to(125.0, 50.0, 150.0, 75.0, 150.0, 100.0)
            .line_to(150.0, 150.0)
            .close_path()
            .fill();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("50.00 50.00 m"));
        assert!(ops_str.contains("100.00 50.00 l"));
        assert!(ops_str.contains("125.00 50.00 150.00 75.00 150.00 100.00 c"));
        assert!(ops_str.contains("150.00 150.00 l"));
        assert!(ops_str.contains("h"));
        assert!(ops_str.contains("f"));
    }

    #[test]
    fn test_graphics_state_dict_generation() {
        let mut ctx = GraphicsContext::new();

        // Without transparency, should return None
        assert!(ctx.generate_graphics_state_dict().is_none());

        // With transparency, should generate dict
        ctx.set_opacity(0.5);
        let dict = ctx.generate_graphics_state_dict();
        assert!(dict.is_some());
        let dict_str = dict.expect("Writing to string should never fail");
        assert!(dict_str.contains("/ca 0.5"));
        assert!(dict_str.contains("/CA 0.5"));
    }

    #[test]
    fn test_line_dash_pattern() {
        let mut ctx = GraphicsContext::new();
        let pattern = LineDashPattern {
            array: vec![3.0, 2.0],
            phase: 0.0,
        };
        ctx.set_line_dash_pattern(pattern);

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("[3.00 2.00] 0.00 d"));
    }

    #[test]
    fn test_miter_limit_setting() {
        let mut ctx = GraphicsContext::new();
        ctx.set_miter_limit(4.0);

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("4.00 M"));
    }

    #[test]
    fn test_line_cap_styles() {
        let mut ctx = GraphicsContext::new();

        ctx.set_line_cap(LineCap::Butt);
        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("0 J"));

        let mut ctx = GraphicsContext::new();
        ctx.set_line_cap(LineCap::Round);
        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("1 J"));

        let mut ctx = GraphicsContext::new();
        ctx.set_line_cap(LineCap::Square);
        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("2 J"));
    }

    #[test]
    fn test_transparency_groups() {
        let mut ctx = GraphicsContext::new();

        // Test basic transparency group
        let group = TransparencyGroup::new()
            .with_isolated(true)
            .with_opacity(0.5);

        ctx.begin_transparency_group(group);
        assert!(ctx.in_transparency_group());

        // Draw something in the group
        ctx.rect(10.0, 10.0, 100.0, 100.0);
        ctx.fill();

        ctx.end_transparency_group();
        assert!(!ctx.in_transparency_group());

        // Check that operations contain transparency markers
        let ops = ctx.operations();
        assert!(ops.contains("% Begin Transparency Group"));
        assert!(ops.contains("% End Transparency Group"));
    }

    #[test]
    fn test_nested_transparency_groups() {
        let mut ctx = GraphicsContext::new();

        // First group
        let group1 = TransparencyGroup::isolated().with_opacity(0.8);
        ctx.begin_transparency_group(group1);
        assert!(ctx.in_transparency_group());

        // Nested group
        let group2 = TransparencyGroup::knockout().with_blend_mode(BlendMode::Multiply);
        ctx.begin_transparency_group(group2);

        // Draw in nested group
        ctx.circle(50.0, 50.0, 25.0);
        ctx.fill();

        // End nested group
        ctx.end_transparency_group();
        assert!(ctx.in_transparency_group()); // Still in first group

        // End first group
        ctx.end_transparency_group();
        assert!(!ctx.in_transparency_group());
    }

    #[test]
    fn test_line_join_styles() {
        let mut ctx = GraphicsContext::new();

        ctx.set_line_join(LineJoin::Miter);
        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("0 j"));

        let mut ctx = GraphicsContext::new();
        ctx.set_line_join(LineJoin::Round);
        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("1 j"));

        let mut ctx = GraphicsContext::new();
        ctx.set_line_join(LineJoin::Bevel);
        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("2 j"));
    }

    #[test]
    fn test_rendering_intent() {
        let mut ctx = GraphicsContext::new();

        ctx.set_rendering_intent(RenderingIntent::AbsoluteColorimetric);
        assert_eq!(
            ctx.rendering_intent(),
            RenderingIntent::AbsoluteColorimetric
        );

        ctx.set_rendering_intent(RenderingIntent::Perceptual);
        assert_eq!(ctx.rendering_intent(), RenderingIntent::Perceptual);

        ctx.set_rendering_intent(RenderingIntent::Saturation);
        assert_eq!(ctx.rendering_intent(), RenderingIntent::Saturation);
    }

    #[test]
    fn test_flatness_tolerance() {
        let mut ctx = GraphicsContext::new();

        ctx.set_flatness(0.5);
        assert_eq!(ctx.flatness(), 0.5);

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("0.50 i"));
    }

    #[test]
    fn test_smoothness_tolerance() {
        let mut ctx = GraphicsContext::new();

        let _ = ctx.set_smoothness(0.1);
        assert_eq!(ctx.smoothness(), 0.1);
    }

    #[test]
    fn test_bezier_curves() {
        let mut ctx = GraphicsContext::new();

        // Cubic Bezier
        ctx.move_to(10.0, 10.0);
        ctx.curve_to(20.0, 10.0, 30.0, 20.0, 30.0, 30.0);

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("10.00 10.00 m"));
        assert!(ops_str.contains("c")); // cubic curve
    }

    #[test]
    fn test_clipping_path() {
        let mut ctx = GraphicsContext::new();

        ctx.rectangle(10.0, 10.0, 100.0, 100.0);
        ctx.clip();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("W"));
    }

    #[test]
    fn test_even_odd_clipping() {
        let mut ctx = GraphicsContext::new();

        ctx.rectangle(10.0, 10.0, 100.0, 100.0);
        ctx.clip_even_odd();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("W*"));
    }

    #[test]
    fn test_color_creation() {
        // Test color creation methods
        let gray = Color::gray(0.5);
        assert_eq!(gray, Color::Gray(0.5));

        let rgb = Color::rgb(0.2, 0.4, 0.6);
        assert_eq!(rgb, Color::Rgb(0.2, 0.4, 0.6));

        let cmyk = Color::cmyk(0.1, 0.2, 0.3, 0.4);
        assert_eq!(cmyk, Color::Cmyk(0.1, 0.2, 0.3, 0.4));

        // Test predefined colors
        assert_eq!(Color::black(), Color::Gray(0.0));
        assert_eq!(Color::white(), Color::Gray(1.0));
        assert_eq!(Color::red(), Color::Rgb(1.0, 0.0, 0.0));
    }

    #[test]
    fn test_extended_graphics_state() {
        let ctx = GraphicsContext::new();

        // Test that we can create and use an extended graphics state
        let _extgstate = ExtGState::new();

        // We should be able to create the state without errors
        assert!(ctx.generate_operations().is_ok());
    }

    #[test]
    fn test_path_construction_methods() {
        let mut ctx = GraphicsContext::new();

        // Test basic path construction methods that exist
        ctx.move_to(10.0, 10.0);
        ctx.line_to(20.0, 20.0);
        ctx.curve_to(30.0, 30.0, 40.0, 40.0, 50.0, 50.0);
        ctx.rect(60.0, 60.0, 30.0, 30.0);
        ctx.circle(100.0, 100.0, 25.0);
        ctx.close_path();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        assert!(!ops.is_empty());
    }

    #[test]
    fn test_graphics_context_clone_advanced() {
        let mut ctx = GraphicsContext::new();
        ctx.set_fill_color(Color::rgb(1.0, 0.0, 0.0));
        ctx.set_line_width(5.0);

        let cloned = ctx.clone();
        assert_eq!(cloned.fill_color(), Color::rgb(1.0, 0.0, 0.0));
        assert_eq!(cloned.line_width(), 5.0);
    }

    #[test]
    fn test_basic_drawing_operations() {
        let mut ctx = GraphicsContext::new();

        // Test that we can at least create a basic drawing
        ctx.move_to(50.0, 50.0);
        ctx.line_to(100.0, 100.0);
        ctx.stroke();

        let ops = ctx
            .generate_operations()
            .expect("Writing to string should never fail");
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("m")); // move
        assert!(ops_str.contains("l")); // line
        assert!(ops_str.contains("S")); // stroke
    }

    #[test]
    fn test_graphics_state_stack() {
        let mut ctx = GraphicsContext::new();

        // Initial state
        ctx.set_fill_color(Color::black());

        // Save and change
        ctx.save_state();
        ctx.set_fill_color(Color::red());
        assert_eq!(ctx.fill_color(), Color::red());

        // Save again and change
        ctx.save_state();
        ctx.set_fill_color(Color::blue());
        assert_eq!(ctx.fill_color(), Color::blue());

        // Restore once
        ctx.restore_state();
        assert_eq!(ctx.fill_color(), Color::red());

        // Restore again
        ctx.restore_state();
        assert_eq!(ctx.fill_color(), Color::black());
    }

    #[test]
    fn test_word_spacing() {
        let mut ctx = GraphicsContext::new();
        ctx.set_word_spacing(2.5);

        let ops = ctx.generate_operations().unwrap();
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("2.50 Tw"));
    }

    #[test]
    fn test_character_spacing() {
        let mut ctx = GraphicsContext::new();
        ctx.set_character_spacing(1.0);

        let ops = ctx.generate_operations().unwrap();
        let ops_str = String::from_utf8_lossy(&ops);
        assert!(ops_str.contains("1.00 Tc"));
    }

    #[test]
    fn test_justified_text() {
        let mut ctx = GraphicsContext::new();
        ctx.begin_text();
        ctx.set_text_position(100.0, 200.0);
        ctx.show_justified_text("Hello world from PDF", 200.0)
            .unwrap();
        ctx.end_text();

        let ops = ctx.generate_operations().unwrap();
        let ops_str = String::from_utf8_lossy(&ops);

        // Should contain text operations
        assert!(ops_str.contains("BT")); // Begin text
        assert!(ops_str.contains("ET")); // End text
        assert!(ops_str.contains("100.00 200.00 Td")); // Text position
        assert!(ops_str.contains("(Hello world from PDF) Tj")); // Show text

        // Should contain word spacing operations
        assert!(ops_str.contains("Tw")); // Word spacing
    }

    #[test]
    fn test_justified_text_single_word() {
        let mut ctx = GraphicsContext::new();
        ctx.begin_text();
        ctx.show_justified_text("Hello", 200.0).unwrap();
        ctx.end_text();

        let ops = ctx.generate_operations().unwrap();
        let ops_str = String::from_utf8_lossy(&ops);

        // Single word should just use normal text display
        assert!(ops_str.contains("(Hello) Tj"));
        // Should not contain word spacing since there's only one word
        assert_eq!(ops_str.matches("Tw").count(), 0);
    }

    #[test]
    fn test_text_width_estimation() {
        let ctx = GraphicsContext::new();
        let width = ctx.estimate_text_width_simple("Hello");

        // Should return reasonable estimation based on font size and character count
        assert!(width > 0.0);
        assert_eq!(width, 5.0 * 12.0 * 0.6); // 5 chars * 12pt font * 0.6 factor
    }

    #[test]
    fn test_set_alpha_methods() {
        let mut ctx = GraphicsContext::new();

        // Test that set_alpha methods don't panic and return correctly
        assert!(ctx.set_alpha(0.5).is_ok());
        assert!(ctx.set_alpha_fill(0.3).is_ok());
        assert!(ctx.set_alpha_stroke(0.7).is_ok());

        // Test edge cases - should handle clamping in ExtGState
        assert!(ctx.set_alpha(1.5).is_ok()); // Should not panic
        assert!(ctx.set_alpha(-0.2).is_ok()); // Should not panic
        assert!(ctx.set_alpha_fill(2.0).is_ok()); // Should not panic
        assert!(ctx.set_alpha_stroke(-1.0).is_ok()); // Should not panic

        // Test that methods return self for chaining
        let result = ctx
            .set_alpha(0.5)
            .and_then(|c| c.set_alpha_fill(0.3))
            .and_then(|c| c.set_alpha_stroke(0.7));
        assert!(result.is_ok());
    }

    #[test]
    fn test_alpha_methods_generate_extgstate() {
        let mut ctx = GraphicsContext::new();

        // Set some transparency
        ctx.set_alpha(0.5).unwrap();

        // Draw something to trigger ExtGState generation
        ctx.rect(10.0, 10.0, 50.0, 50.0).fill();

        let ops = ctx.generate_operations().unwrap();
        let ops_str = String::from_utf8_lossy(&ops);

        // Should contain ExtGState reference
        assert!(ops_str.contains("/GS")); // ExtGState name
        assert!(ops_str.contains(" gs\n")); // ExtGState operator

        // Test separate alpha settings
        ctx.clear();
        ctx.set_alpha_fill(0.3).unwrap();
        ctx.set_alpha_stroke(0.8).unwrap();
        ctx.rect(20.0, 20.0, 60.0, 60.0).fill_stroke();

        let ops2 = ctx.generate_operations().unwrap();
        let ops_str2 = String::from_utf8_lossy(&ops2);

        // Should contain multiple ExtGState references
        assert!(ops_str2.contains("/GS")); // ExtGState names
        assert!(ops_str2.contains(" gs\n")); // ExtGState operators
    }

    #[test]
    fn test_add_command() {
        let mut ctx = GraphicsContext::new();

        // Test normal command
        ctx.add_command("1 0 0 1 100 200 cm");
        let ops = ctx.operations();
        assert!(ops.contains("1 0 0 1 100 200 cm\n"));

        // Test that newline is always added
        ctx.clear();
        ctx.add_command("q");
        assert_eq!(ctx.operations(), "q\n");

        // Test empty string
        ctx.clear();
        ctx.add_command("");
        assert_eq!(ctx.operations(), "\n");

        // Test command with existing newline
        ctx.clear();
        ctx.add_command("Q\n");
        assert_eq!(ctx.operations(), "Q\n\n"); // Double newline

        // Test multiple commands
        ctx.clear();
        ctx.add_command("q");
        ctx.add_command("1 0 0 1 50 50 cm");
        ctx.add_command("Q");
        assert_eq!(ctx.operations(), "q\n1 0 0 1 50 50 cm\nQ\n");
    }

    #[test]
    fn test_get_operations() {
        let mut ctx = GraphicsContext::new();
        ctx.rect(10.0, 10.0, 50.0, 50.0);
        let ops1 = ctx.operations();
        let ops2 = ctx.get_operations();
        assert_eq!(ops1, ops2);
    }

    #[test]
    fn test_set_line_solid() {
        let mut ctx = GraphicsContext::new();
        ctx.set_line_dash_pattern(LineDashPattern::new(vec![5.0, 3.0], 0.0));
        ctx.set_line_solid();
        let ops = ctx.operations();
        assert!(ops.contains("[] 0 d\n"));
    }

    #[test]
    fn test_set_custom_font() {
        let mut ctx = GraphicsContext::new();
        ctx.set_custom_font("CustomFont", 14.0);
        assert_eq!(ctx.current_font_name.as_deref(), Some("CustomFont"));
        assert_eq!(ctx.current_font_size, 14.0);
        assert!(ctx.is_custom_font);
    }

    #[test]
    fn test_show_text_standard_font_uses_literal_string() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Helvetica, 12.0);
        assert!(!ctx.is_custom_font);

        ctx.begin_text();
        ctx.set_text_position(10.0, 20.0);
        ctx.show_text("Hello World").unwrap();
        ctx.end_text();

        let ops = ctx.operations();
        assert!(ops.contains("(Hello World) Tj"));
        assert!(!ops.contains("<"));
    }

    #[test]
    fn test_show_text_custom_font_uses_hex_encoding() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Custom("NotoSansCJK".to_string()), 12.0);
        assert!(ctx.is_custom_font);

        ctx.begin_text();
        ctx.set_text_position(10.0, 20.0);
        // CJK characters: 你好 (U+4F60 U+597D)
        ctx.show_text("你好").unwrap();
        ctx.end_text();

        let ops = ctx.operations();
        // Must be hex-encoded, not literal
        assert!(
            ops.contains("<4F60597D> Tj"),
            "Expected hex encoding for CJK text, got: {}",
            ops
        );
        assert!(!ops.contains("(你好)"));
    }

    #[test]
    fn test_show_text_custom_font_ascii_still_hex() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Custom("MyFont".to_string()), 10.0);

        ctx.begin_text();
        ctx.set_text_position(0.0, 0.0);
        // Even ASCII text should be hex-encoded when using custom font
        ctx.show_text("AB").unwrap();
        ctx.end_text();

        let ops = ctx.operations();
        // A=0x0041, B=0x0042
        assert!(
            ops.contains("<00410042> Tj"),
            "Expected hex encoding for ASCII in custom font, got: {}",
            ops
        );
    }

    #[test]
    fn test_show_text_tracks_used_characters() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Custom("CJKFont".to_string()), 12.0);

        ctx.begin_text();
        ctx.show_text("你好A").unwrap();
        ctx.end_text();

        assert!(ctx.used_characters.contains(&''));
        assert!(ctx.used_characters.contains(&''));
        assert!(ctx.used_characters.contains(&'A'));
    }

    #[test]
    fn test_is_custom_font_toggles_correctly() {
        let mut ctx = GraphicsContext::new();
        assert!(!ctx.is_custom_font);

        ctx.set_font(Font::Custom("CJK".to_string()), 12.0);
        assert!(ctx.is_custom_font);

        ctx.set_font(Font::Helvetica, 12.0);
        assert!(!ctx.is_custom_font);

        ctx.set_custom_font("AnotherCJK", 14.0);
        assert!(ctx.is_custom_font);

        ctx.set_font(Font::CourierBold, 10.0);
        assert!(!ctx.is_custom_font);
    }

    #[test]
    fn test_set_glyph_mapping() {
        let mut ctx = GraphicsContext::new();

        // Test initial state
        assert!(ctx.glyph_mapping.is_none());

        // Test normal mapping
        let mut mapping = HashMap::new();
        mapping.insert(65u32, 1u16); // 'A' -> glyph 1
        mapping.insert(66u32, 2u16); // 'B' -> glyph 2
        ctx.set_glyph_mapping(mapping.clone());
        assert!(ctx.glyph_mapping.is_some());
        assert_eq!(ctx.glyph_mapping.as_ref().unwrap().len(), 2);
        assert_eq!(ctx.glyph_mapping.as_ref().unwrap().get(&65), Some(&1));
        assert_eq!(ctx.glyph_mapping.as_ref().unwrap().get(&66), Some(&2));

        // Test empty mapping
        ctx.set_glyph_mapping(HashMap::new());
        assert!(ctx.glyph_mapping.is_some());
        assert_eq!(ctx.glyph_mapping.as_ref().unwrap().len(), 0);

        // Test overwrite existing mapping
        let mut new_mapping = HashMap::new();
        new_mapping.insert(67u32, 3u16); // 'C' -> glyph 3
        ctx.set_glyph_mapping(new_mapping);
        assert_eq!(ctx.glyph_mapping.as_ref().unwrap().len(), 1);
        assert_eq!(ctx.glyph_mapping.as_ref().unwrap().get(&67), Some(&3));
        assert_eq!(ctx.glyph_mapping.as_ref().unwrap().get(&65), None); // Old mapping gone
    }

    #[test]
    fn test_draw_text_basic() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Helvetica, 12.0);

        let result = ctx.draw_text("Hello", 100.0, 200.0);
        assert!(result.is_ok());

        let ops = ctx.operations();
        // Verify text block
        assert!(ops.contains("BT\n"));
        assert!(ops.contains("ET\n"));

        // Verify font is set
        assert!(ops.contains("/Helvetica"));
        assert!(ops.contains("12"));
        assert!(ops.contains("Tf\n"));

        // Verify positioning
        assert!(ops.contains("100"));
        assert!(ops.contains("200"));
        assert!(ops.contains("Td\n"));

        // Verify text content
        assert!(ops.contains("(Hello)") || ops.contains("<48656c6c6f>")); // Text or hex
    }

    #[test]
    fn test_draw_text_with_special_characters() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Helvetica, 12.0);

        // Test with parentheses (must be escaped in PDF)
        let result = ctx.draw_text("Test (with) parens", 50.0, 100.0);
        assert!(result.is_ok());

        let ops = ctx.operations();
        // Should escape parentheses
        assert!(ops.contains("\\(") || ops.contains("\\)") || ops.contains("<"));
        // Either escaped or hex
    }

    #[test]
    fn test_draw_text_unicode_detection() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Helvetica, 12.0);

        // ASCII text should use simple encoding
        ctx.draw_text("ASCII", 0.0, 0.0).unwrap();
        let _ops_ascii = ctx.operations();

        ctx.clear();

        // Unicode text should trigger different encoding
        ctx.set_font(Font::Helvetica, 12.0);
        ctx.draw_text("中文", 0.0, 0.0).unwrap();
        let ops_unicode = ctx.operations();

        // Unicode should produce hex encoding
        assert!(ops_unicode.contains("<") && ops_unicode.contains(">"));
    }

    #[test]
    #[allow(deprecated)]
    fn test_draw_text_hex_encoding() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Helvetica, 12.0);
        let result = ctx.draw_text_hex("Test", 50.0, 100.0);
        assert!(result.is_ok());
        let ops = ctx.operations();
        assert!(ops.contains("<"));
        assert!(ops.contains(">"));
    }

    #[test]
    #[allow(deprecated)]
    fn test_draw_text_cid() {
        let mut ctx = GraphicsContext::new();
        ctx.set_custom_font("CustomCIDFont", 12.0);
        let result = ctx.draw_text_cid("Test", 50.0, 100.0);
        assert!(result.is_ok());
        let ops = ctx.operations();
        assert!(ops.contains("BT\n"));
        assert!(ops.contains("ET\n"));
    }

    #[test]
    #[allow(deprecated)]
    fn test_draw_text_unicode() {
        let mut ctx = GraphicsContext::new();
        ctx.set_custom_font("UnicodeFont", 12.0);
        let result = ctx.draw_text_unicode("Test \u{4E2D}\u{6587}", 50.0, 100.0);
        assert!(result.is_ok());
        let ops = ctx.operations();
        assert!(ops.contains("BT\n"));
        assert!(ops.contains("ET\n"));
    }

    #[test]
    fn test_begin_end_transparency_group() {
        let mut ctx = GraphicsContext::new();

        // Initial state - no transparency group
        assert!(!ctx.in_transparency_group());
        assert!(ctx.current_transparency_group().is_none());

        // Begin transparency group
        let group = TransparencyGroup::new();
        ctx.begin_transparency_group(group);
        assert!(ctx.in_transparency_group());
        assert!(ctx.current_transparency_group().is_some());

        // Verify operations contain transparency marker
        let ops = ctx.operations();
        assert!(ops.contains("% Begin Transparency Group"));

        // End transparency group
        ctx.end_transparency_group();
        assert!(!ctx.in_transparency_group());
        assert!(ctx.current_transparency_group().is_none());

        // Verify end marker
        let ops_after = ctx.operations();
        assert!(ops_after.contains("% End Transparency Group"));
    }

    #[test]
    fn test_transparency_group_nesting() {
        let mut ctx = GraphicsContext::new();

        // Nest 3 levels
        let group1 = TransparencyGroup::new();
        let group2 = TransparencyGroup::new();
        let group3 = TransparencyGroup::new();

        ctx.begin_transparency_group(group1);
        assert_eq!(ctx.transparency_stack.len(), 1);

        ctx.begin_transparency_group(group2);
        assert_eq!(ctx.transparency_stack.len(), 2);

        ctx.begin_transparency_group(group3);
        assert_eq!(ctx.transparency_stack.len(), 3);

        // End all
        ctx.end_transparency_group();
        assert_eq!(ctx.transparency_stack.len(), 2);

        ctx.end_transparency_group();
        assert_eq!(ctx.transparency_stack.len(), 1);

        ctx.end_transparency_group();
        assert_eq!(ctx.transparency_stack.len(), 0);
        assert!(!ctx.in_transparency_group());
    }

    #[test]
    fn test_transparency_group_without_begin() {
        let mut ctx = GraphicsContext::new();

        // Try to end without begin - should not panic, just be no-op
        assert!(!ctx.in_transparency_group());
        ctx.end_transparency_group();
        assert!(!ctx.in_transparency_group());
    }

    #[test]
    fn test_extgstate_manager_access() {
        let ctx = GraphicsContext::new();
        let manager = ctx.extgstate_manager();
        assert_eq!(manager.count(), 0);
    }

    #[test]
    fn test_extgstate_manager_mut_access() {
        let mut ctx = GraphicsContext::new();
        let manager = ctx.extgstate_manager_mut();
        assert_eq!(manager.count(), 0);
    }

    #[test]
    fn test_has_extgstates() {
        let mut ctx = GraphicsContext::new();

        // Initially no extgstates
        assert!(!ctx.has_extgstates());
        assert_eq!(ctx.extgstate_manager().count(), 0);

        // Adding transparency creates extgstate
        ctx.set_alpha(0.5).unwrap();
        ctx.rect(10.0, 10.0, 50.0, 50.0).fill();
        let result = ctx.generate_operations().unwrap();

        assert!(ctx.has_extgstates());
        assert!(ctx.extgstate_manager().count() > 0);

        // Verify extgstate is in PDF output
        let output = String::from_utf8_lossy(&result);
        assert!(output.contains("/GS")); // ExtGState reference
        assert!(output.contains(" gs\n")); // ExtGState operator
    }

    #[test]
    fn test_generate_extgstate_resources() {
        let mut ctx = GraphicsContext::new();
        ctx.set_alpha(0.5).unwrap();
        ctx.rect(10.0, 10.0, 50.0, 50.0).fill();
        ctx.generate_operations().unwrap();

        let resources = ctx.generate_extgstate_resources();
        assert!(resources.is_ok());
    }

    #[test]
    fn test_apply_extgstate() {
        let mut ctx = GraphicsContext::new();

        // Create ExtGState with specific values
        let mut state = ExtGState::new();
        state.alpha_fill = Some(0.5);
        state.alpha_stroke = Some(0.8);
        state.blend_mode = Some(BlendMode::Multiply);

        let result = ctx.apply_extgstate(state);
        assert!(result.is_ok());

        // Verify ExtGState was registered
        assert!(ctx.has_extgstates());
        assert_eq!(ctx.extgstate_manager().count(), 1);

        // Apply different ExtGState
        let mut state2 = ExtGState::new();
        state2.alpha_fill = Some(0.3);
        ctx.apply_extgstate(state2).unwrap();

        // Should have 2 different extgstates
        assert_eq!(ctx.extgstate_manager().count(), 2);
    }

    #[test]
    fn test_with_extgstate() {
        let mut ctx = GraphicsContext::new();
        let result = ctx.with_extgstate(|mut state| {
            state.alpha_fill = Some(0.5);
            state.alpha_stroke = Some(0.8);
            state
        });
        assert!(result.is_ok());
    }

    #[test]
    fn test_set_blend_mode() {
        let mut ctx = GraphicsContext::new();

        // Test different blend modes
        let result = ctx.set_blend_mode(BlendMode::Multiply);
        assert!(result.is_ok());
        assert!(ctx.has_extgstates());

        // Test that different blend modes create different extgstates
        ctx.clear();
        ctx.set_blend_mode(BlendMode::Screen).unwrap();
        ctx.rect(0.0, 0.0, 10.0, 10.0).fill();
        let ops = ctx.generate_operations().unwrap();
        let output = String::from_utf8_lossy(&ops);

        // Should contain extgstate reference
        assert!(output.contains("/GS"));
        assert!(output.contains(" gs\n"));
    }

    #[test]
    fn test_render_table() {
        let mut ctx = GraphicsContext::new();
        let table = Table::with_equal_columns(2, 200.0);
        let result = ctx.render_table(&table);
        assert!(result.is_ok());
    }

    #[test]
    fn test_render_list() {
        let mut ctx = GraphicsContext::new();
        use crate::text::{OrderedList, OrderedListStyle};
        let ordered = OrderedList::new(OrderedListStyle::Decimal);
        let list = ListElement::Ordered(ordered);
        let result = ctx.render_list(&list);
        assert!(result.is_ok());
    }

    #[test]
    fn test_render_column_layout() {
        let mut ctx = GraphicsContext::new();
        use crate::text::ColumnContent;
        let layout = ColumnLayout::new(2, 100.0, 200.0);
        let content = ColumnContent::new("Test content");
        let result = ctx.render_column_layout(&layout, &content, 50.0, 50.0, 400.0);
        assert!(result.is_ok());
    }

    #[test]
    fn test_clip_ellipse() {
        let mut ctx = GraphicsContext::new();

        // No clipping initially
        assert!(!ctx.has_clipping());
        assert!(ctx.clipping_path().is_none());

        // Apply ellipse clipping
        let result = ctx.clip_ellipse(100.0, 100.0, 50.0, 30.0);
        assert!(result.is_ok());
        assert!(ctx.has_clipping());
        assert!(ctx.clipping_path().is_some());

        // Verify clipping operations in PDF
        let ops = ctx.operations();
        assert!(ops.contains("W\n") || ops.contains("W*\n")); // Clipping operator

        // Clear clipping
        ctx.clear_clipping();
        assert!(!ctx.has_clipping());
    }

    #[test]
    fn test_clipping_path_access() {
        let mut ctx = GraphicsContext::new();

        // No clipping initially
        assert!(ctx.clipping_path().is_none());

        // Apply rect clipping
        ctx.clip_rect(10.0, 10.0, 50.0, 50.0).unwrap();
        assert!(ctx.clipping_path().is_some());

        // Apply different clipping - should replace
        ctx.clip_circle(100.0, 100.0, 25.0).unwrap();
        assert!(ctx.clipping_path().is_some());

        // Save/restore should preserve clipping
        ctx.save_state();
        ctx.clear_clipping();
        assert!(!ctx.has_clipping());

        ctx.restore_state();
        // After restore, clipping should be back
        assert!(ctx.has_clipping());
    }

    // ====== QUALITY TESTS: EDGE CASES ======

    #[test]
    fn test_edge_case_move_to_negative() {
        let mut ctx = GraphicsContext::new();
        ctx.move_to(-100.5, -200.25);
        assert!(ctx.operations().contains("-100.50 -200.25 m\n"));
    }

    #[test]
    fn test_edge_case_opacity_out_of_range() {
        let mut ctx = GraphicsContext::new();

        // Above 1.0 - should clamp
        let _ = ctx.set_opacity(2.5);
        assert_eq!(ctx.fill_opacity(), 1.0);

        // Below 0.0 - should clamp
        let _ = ctx.set_opacity(-0.5);
        assert_eq!(ctx.fill_opacity(), 0.0);
    }

    #[test]
    fn test_edge_case_line_width_extremes() {
        let mut ctx = GraphicsContext::new();

        ctx.set_line_width(0.0);
        assert_eq!(ctx.line_width(), 0.0);

        ctx.set_line_width(10000.0);
        assert_eq!(ctx.line_width(), 10000.0);
    }

    // ====== QUALITY TESTS: FEATURE INTERACTIONS ======

    #[test]
    fn test_interaction_transparency_plus_clipping() {
        let mut ctx = GraphicsContext::new();

        ctx.set_alpha(0.5).unwrap();
        ctx.clip_rect(10.0, 10.0, 100.0, 100.0).unwrap();
        ctx.rect(20.0, 20.0, 80.0, 80.0).fill();

        let ops = ctx.generate_operations().unwrap();
        let output = String::from_utf8_lossy(&ops);

        // Both features should be in PDF
        assert!(output.contains("W\n") || output.contains("W*\n"));
        assert!(output.contains("/GS"));
    }

    #[test]
    fn test_interaction_extgstate_plus_text() {
        let mut ctx = GraphicsContext::new();

        let mut state = ExtGState::new();
        state.alpha_fill = Some(0.7);
        ctx.apply_extgstate(state).unwrap();

        ctx.set_font(Font::Helvetica, 14.0);
        ctx.draw_text("Test", 100.0, 200.0).unwrap();

        let ops = ctx.generate_operations().unwrap();
        let output = String::from_utf8_lossy(&ops);

        assert!(output.contains("/GS"));
        assert!(output.contains("BT\n"));
    }

    #[test]
    fn test_interaction_chained_transformations() {
        let mut ctx = GraphicsContext::new();

        ctx.translate(50.0, 100.0);
        ctx.rotate(45.0);
        ctx.scale(2.0, 2.0);

        let ops = ctx.operations();
        assert_eq!(ops.matches("cm\n").count(), 3);
    }

    // ====== QUALITY TESTS: END-TO-END ======

    #[test]
    fn test_e2e_complete_page_with_header() {
        use crate::{Document, Page};

        let mut doc = Document::new();
        let mut page = Page::a4();
        let ctx = page.graphics();

        // Header
        ctx.save_state();
        let _ = ctx.set_fill_opacity(0.3);
        ctx.set_fill_color(Color::rgb(200.0, 200.0, 255.0));
        ctx.rect(0.0, 750.0, 595.0, 42.0).fill();
        ctx.restore_state();

        // Content
        ctx.save_state();
        ctx.clip_rect(50.0, 50.0, 495.0, 692.0).unwrap();
        ctx.rect(60.0, 60.0, 100.0, 100.0).fill();
        ctx.restore_state();

        let ops = ctx.generate_operations().unwrap();
        let output = String::from_utf8_lossy(&ops);

        assert!(output.contains("q\n"));
        assert!(output.contains("Q\n"));
        assert!(output.contains("f\n"));

        doc.add_page(page);
        assert!(doc.to_bytes().unwrap().len() > 0);
    }

    #[test]
    fn test_e2e_watermark_workflow() {
        let mut ctx = GraphicsContext::new();

        ctx.save_state();
        let _ = ctx.set_fill_opacity(0.2);
        ctx.translate(300.0, 400.0);
        ctx.rotate(45.0);
        ctx.set_font(Font::HelveticaBold, 72.0);
        ctx.draw_text("DRAFT", 0.0, 0.0).unwrap();
        ctx.restore_state();

        let ops = ctx.generate_operations().unwrap();
        let output = String::from_utf8_lossy(&ops);

        // Verify watermark structure
        assert!(output.contains("q\n")); // save state
        assert!(output.contains("Q\n")); // restore state
        assert!(output.contains("cm\n")); // transformations
        assert!(output.contains("BT\n")); // text begin
        assert!(output.contains("ET\n")); // text end
    }

    // ====== PHASE 5: set_custom_font emits Tf operator ======

    #[test]
    fn test_set_custom_font_emits_tf_operator() {
        let mut ctx = GraphicsContext::new();
        ctx.set_custom_font("NotoSansCJK", 14.0);

        let ops = ctx.operations();
        assert!(
            ops.contains("/NotoSansCJK 14 Tf"),
            "set_custom_font should emit Tf operator, got: {}",
            ops
        );
    }

    // ====== PHASE 3: unified custom font detection in draw_text ======

    #[test]
    fn test_draw_text_uses_is_custom_font_flag() {
        let mut ctx = GraphicsContext::new();
        // Name matches a standard font, but set via set_custom_font → flag is true
        ctx.set_custom_font("Helvetica", 12.0);
        ctx.clear(); // clear the Tf operator from set_custom_font

        ctx.draw_text("A", 10.0, 20.0).unwrap();
        let ops = ctx.operations();
        // Must use hex encoding because is_custom_font=true
        assert!(
            ops.contains("<0041> Tj"),
            "draw_text with is_custom_font=true should use hex, got: {}",
            ops
        );
    }

    #[test]
    fn test_draw_text_standard_font_uses_literal() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Helvetica, 12.0);
        ctx.clear();

        ctx.draw_text("Hello", 10.0, 20.0).unwrap();
        let ops = ctx.operations();
        assert!(
            ops.contains("(Hello) Tj"),
            "draw_text with standard font should use literal, got: {}",
            ops
        );
    }

    // ====== PHASE 2: surrogate pairs for SMP characters ======

    #[test]
    fn test_show_text_smp_character_uses_surrogate_pairs() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Custom("Emoji".to_string()), 12.0);

        ctx.begin_text();
        ctx.set_text_position(0.0, 0.0);
        // U+1F600 (GRINNING FACE) → surrogate pair: D83D DE00
        ctx.show_text("\u{1F600}").unwrap();
        ctx.end_text();

        let ops = ctx.operations();
        assert!(
            ops.contains("<D83DDE00> Tj"),
            "SMP character should use UTF-16BE surrogate pair, got: {}",
            ops
        );
        assert!(
            !ops.contains("FFFD"),
            "SMP character must NOT be replaced with FFFD"
        );
    }

    // ====== PHASE 1: save/restore font state ======

    #[test]
    fn test_save_restore_preserves_font_state() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Custom("CJK".to_string()), 12.0);
        assert!(ctx.is_custom_font);
        assert_eq!(ctx.current_font_name.as_deref(), Some("CJK"));
        assert_eq!(ctx.current_font_size, 12.0);

        ctx.save_state();
        ctx.set_font(Font::Helvetica, 10.0);
        assert!(!ctx.is_custom_font);
        assert_eq!(ctx.current_font_name.as_deref(), Some("Helvetica"));

        ctx.restore_state();
        assert!(
            ctx.is_custom_font,
            "is_custom_font must be restored after restore_state"
        );
        assert_eq!(ctx.current_font_name.as_deref(), Some("CJK"));
        assert_eq!(ctx.current_font_size, 12.0);
    }

    #[test]
    fn test_save_restore_mixed_font_encoding() {
        let mut ctx = GraphicsContext::new();
        ctx.set_font(Font::Custom("CJK".to_string()), 12.0);

        // Simulate table cell pattern: save → change font → text → restore → text
        ctx.save_state();
        ctx.set_font(Font::Helvetica, 10.0);
        ctx.begin_text();
        ctx.show_text("Hello").unwrap();
        ctx.end_text();
        ctx.restore_state();

        // After restore, CJK font should be active again
        ctx.begin_text();
        ctx.show_text("你好").unwrap();
        ctx.end_text();

        let ops = ctx.operations();
        // After restore, text must be hex-encoded (custom font restored)
        assert!(
            ops.contains("<4F60597D> Tj"),
            "After restore_state, CJK text should use hex encoding, got: {}",
            ops
        );
    }

    #[test]
    fn test_graphics_state_arc_str_save_restore() {
        // Verifies that save/restore correctly round-trips font names stored as Arc<str>,
        // and that the clone is O(1) (no String allocation per save).
        let mut ctx = GraphicsContext::new();

        // Set initial font
        ctx.set_font(Font::Custom("TestFont".to_string()), 14.0);
        assert_eq!(ctx.current_font_name.as_deref(), Some("TestFont"));
        assert!(ctx.is_custom_font);

        // Save state, change font
        ctx.save_state();
        ctx.set_font(Font::Custom("Other".to_string()), 10.0);
        assert_eq!(ctx.current_font_name.as_deref(), Some("Other"));

        // Restore: font must revert to "TestFont"
        ctx.restore_state();
        assert_eq!(
            ctx.current_font_name.as_deref(),
            Some("TestFont"),
            "Font name must be restored to TestFont after restore_state"
        );
        assert_eq!(ctx.current_font_size, 14.0);
        assert!(
            ctx.is_custom_font,
            "is_custom_font must be restored to true"
        );

        // Verify the Arc<str> is actually shared (same pointer after clone)
        if let Some(ref arc) = ctx.current_font_name {
            let cloned = arc.clone();
            assert_eq!(arc.as_ref(), cloned.as_ref());
            // Arc::ptr_eq confirms O(1) clone (same backing allocation)
            assert!(Arc::ptr_eq(arc, &cloned));
        }
    }
}