leptonica 0.1.0

Rust port of Leptonica image processing library
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
//! Rotation and flip operations
//!
//! This module provides:
//! - Orthogonal rotations (90/180/270 degrees)
//! - Arbitrary angle rotations (with multiple algorithms)
//! - Horizontal and vertical flips
//!
//! # Rotation Methods
//!
//! - **Sampling**: Fastest, uses nearest-neighbor interpolation. Best for speed.
//! - **AreaMap**: Highest quality, uses area-weighted averaging. Best for quality.
//! - **Shear**: Good for 1bpp images, uses 2 or 3 shear operations.
//! - **Bilinear**: Good balance of speed and quality.

use crate::core::{Pix, PixMut, PixelDepth, pixel};
use crate::transform::shear::{ShearFill, h_shear_ip, v_shear_ip};
use crate::transform::{TransformError, TransformResult};

// ============================================================================
// Constants from Leptonica
// ============================================================================

/// Minimum angle to actually rotate (below this, just clone)
const MIN_ANGLE_TO_ROTATE: f32 = 0.001; // radians, ~0.06 degrees
/// Maximum angle for 2-shear rotation
const MAX_TWO_SHEAR_ANGLE: f32 = 0.06; // radians, ~3 degrees
/// Maximum angle for 3-shear rotation (warning threshold)
#[allow(dead_code)]
const MAX_THREE_SHEAR_ANGLE: f32 = 0.35; // radians, ~20 degrees
/// Maximum angle for shear rotation
const MAX_SHEAR_ANGLE: f32 = 0.50; // radians, ~29 degrees
/// Angle threshold for switching 1bpp from shear to sampling
const MAX_1BPP_SHEAR_ANGLE: f32 = 0.06; // radians, ~3 degrees

// ============================================================================
// Rotation method enumeration
// ============================================================================

/// Rotation algorithm to use
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RotateMethod {
    /// Sampling (nearest-neighbor) - fastest, lowest quality
    Sampling,
    /// Area mapping - highest quality, uses 16x16 sub-pixel grid
    AreaMap,
    /// Shear-based rotation - good for 1bpp images
    Shear,
    /// Bilinear interpolation - good balance of speed and quality
    Bilinear,
    /// Automatic selection based on depth and angle
    #[default]
    Auto,
}

/// Background fill color for rotation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RotateFill {
    /// Fill with white pixels
    #[default]
    White,
    /// Fill with black pixels
    Black,
    /// Fill with a specific color value (interpretation depends on depth)
    Color(u32),
}

impl RotateFill {
    /// Get the fill value for a specific pixel depth
    pub fn to_value(self, depth: PixelDepth) -> u32 {
        match self {
            RotateFill::White => match depth {
                PixelDepth::Bit1 => 0, // 0 = white for binary (foreground is black)
                PixelDepth::Bit2 => 3,
                PixelDepth::Bit4 => 15,
                PixelDepth::Bit8 => 255,
                PixelDepth::Bit16 => 65535,
                PixelDepth::Bit32 => 0xFFFFFF00,
            },
            RotateFill::Black => match depth {
                PixelDepth::Bit1 => 1, // 1 = black for binary
                PixelDepth::Bit32 => 0x00000000,
                _ => 0,
            },
            RotateFill::Color(val) => val,
        }
    }
}

/// Options for rotation operations
#[derive(Debug, Clone)]
pub struct RotateOptions {
    /// Rotation algorithm to use
    pub method: RotateMethod,
    /// Background fill color
    pub fill: RotateFill,
    /// Custom rotation center X (None = image center)
    pub center_x: Option<f32>,
    /// Custom rotation center Y (None = image center)
    pub center_y: Option<f32>,
    /// Expand output to fit all rotated pixels
    pub expand: bool,
}

impl Default for RotateOptions {
    fn default() -> Self {
        Self {
            method: RotateMethod::Auto,
            fill: RotateFill::White,
            center_x: None,
            center_y: None,
            expand: true,
        }
    }
}

impl RotateOptions {
    /// Create options with a specific method
    pub fn with_method(method: RotateMethod) -> Self {
        Self {
            method,
            ..Default::default()
        }
    }

    /// Create options with a specific fill color
    pub fn with_fill(fill: RotateFill) -> Self {
        Self {
            fill,
            ..Default::default()
        }
    }

    /// Set the rotation center
    pub fn center(mut self, x: f32, y: f32) -> Self {
        self.center_x = Some(x);
        self.center_y = Some(y);
        self
    }

    /// Set whether to expand output dimensions
    pub fn expand(mut self, expand: bool) -> Self {
        self.expand = expand;
        self
    }
}

/// Rotate an image by 90-degree increments
///
/// # Arguments
/// * `pix` - Input image
/// * `quads` - Number of 90-degree clockwise rotations (0-3)
///
/// # Returns
/// The rotated image
pub fn rotate_orth(pix: &Pix, quads: u32) -> TransformResult<Pix> {
    match quads % 4 {
        0 => Ok(pix.deep_clone()),
        1 => rotate_90(pix, true),
        2 => rotate_180(pix),
        3 => rotate_90(pix, false),
        _ => unreachable!(),
    }
}

/// Rotate an image 90 degrees
///
/// # Arguments
/// * `pix` - Input image
/// * `clockwise` - If true, rotate clockwise; otherwise counterclockwise
pub fn rotate_90(pix: &Pix, clockwise: bool) -> TransformResult<Pix> {
    let w = pix.width();
    let h = pix.height();
    let depth = pix.depth();

    // Output dimensions are swapped
    let out_pix = Pix::new(h, w, depth)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    if let Some(cmap) = pix.colormap() {
        let _ = out_mut.set_colormap(Some(cmap.clone()));
    }

    rotate_90_impl(pix, &mut out_mut, clockwise, w, h);

    Ok(out_mut.into())
}

/// Internal implementation of 90 degree rotation
fn rotate_90_impl(src: &Pix, dst: &mut PixMut, clockwise: bool, w: u32, h: u32) {
    for y in 0..h {
        for x in 0..w {
            let val = src.get_pixel_unchecked(x, y);
            let (nx, ny) = if clockwise {
                (h - 1 - y, x)
            } else {
                (y, w - 1 - x)
            };
            dst.set_pixel_unchecked(nx, ny, val);
        }
    }
}

/// Rotate an image 180 degrees
pub fn rotate_180(pix: &Pix) -> TransformResult<Pix> {
    // 180 rotation = horizontal flip + vertical flip
    let flipped_h = flip_lr(pix)?;
    flip_tb(&flipped_h)
}

/// Flip an image left-right (horizontal mirror)
pub fn flip_lr(pix: &Pix) -> TransformResult<Pix> {
    let w = pix.width();
    let h = pix.height();
    let depth = pix.depth();

    let out_pix = Pix::new(w, h, depth)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    if let Some(cmap) = pix.colormap() {
        let _ = out_mut.set_colormap(Some(cmap.clone()));
    }

    for y in 0..h {
        for x in 0..w {
            let val = pix.get_pixel_unchecked(x, y);
            let nx = w - 1 - x;
            out_mut.set_pixel_unchecked(nx, y, val);
        }
    }

    Ok(out_mut.into())
}

/// Flip an image top-bottom (vertical mirror)
pub fn flip_tb(pix: &Pix) -> TransformResult<Pix> {
    let w = pix.width();
    let h = pix.height();
    let depth = pix.depth();

    let out_pix = Pix::new(w, h, depth)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    if let Some(cmap) = pix.colormap() {
        let _ = out_mut.set_colormap(Some(cmap.clone()));
    }

    for y in 0..h {
        for x in 0..w {
            let val = pix.get_pixel_unchecked(x, y);
            let ny = h - 1 - y;
            out_mut.set_pixel_unchecked(x, ny, val);
        }
    }

    Ok(out_mut.into())
}

/// Rotate an image in-place by 180 degrees
pub fn rotate_180_in_place(pix: &mut PixMut) -> TransformResult<()> {
    let w = pix.width();
    let h = pix.height();

    // Swap pixels from opposite corners
    let total_pixels = (w as u64) * (h as u64);
    let half = total_pixels / 2;

    for i in 0..half {
        let x1 = (i % (w as u64)) as u32;
        let y1 = (i / (w as u64)) as u32;
        let x2 = w - 1 - x1;
        let y2 = h - 1 - y1;

        let val1 = pix.get_pixel_unchecked(x1, y1);
        let val2 = pix.get_pixel_unchecked(x2, y2);

        pix.set_pixel_unchecked(x1, y1, val2);
        pix.set_pixel_unchecked(x2, y2, val1);
    }

    Ok(())
}

// ============================================================================
// Arbitrary angle rotation
// ============================================================================

/// Rotate an image by an arbitrary angle in degrees
///
/// Uses bilinear interpolation for smooth results. The output image size
/// is adjusted to contain the entire rotated image.
///
/// # Arguments
/// * `pix` - Input image
/// * `angle` - Rotation angle in degrees (positive = counterclockwise)
///
/// # Returns
/// The rotated image with white background
///
/// # Example
/// ```no_run
/// use leptonica::transform::rotate_by_angle;
/// use leptonica::core::{Pix, PixelDepth};
///
/// let pix = Pix::new(100, 100, PixelDepth::Bit8).unwrap();
/// let rotated = rotate_by_angle(&pix, 45.0).unwrap();
/// ```
pub fn rotate_by_angle(pix: &Pix, angle: f32) -> TransformResult<Pix> {
    let fill_value = get_default_fill_value(pix.depth());
    rotate_by_angle_with_options(pix, angle, fill_value)
}

/// Rotate an image by an arbitrary angle in radians
///
/// Uses bilinear interpolation for smooth results.
///
/// # Arguments
/// * `pix` - Input image
/// * `radians` - Rotation angle in radians (positive = counterclockwise)
pub fn rotate_by_radians(pix: &Pix, radians: f32) -> TransformResult<Pix> {
    let angle = radians.to_degrees();
    rotate_by_angle(pix, angle)
}

/// Rotate an image by an arbitrary angle with custom fill value
///
/// Uses bilinear interpolation for 8-bit and 32-bit images,
/// nearest neighbor for 1-bit images.
///
/// # Arguments
/// * `pix` - Input image
/// * `angle` - Rotation angle in degrees (positive = counterclockwise)
/// * `fill_value` - Value to fill pixels outside the original image
pub fn rotate_by_angle_with_options(
    pix: &Pix,
    angle: f32,
    fill_value: u32,
) -> TransformResult<Pix> {
    // Normalize angle to [0, 360)
    let angle = angle % 360.0;
    let angle = if angle < 0.0 { angle + 360.0 } else { angle };

    // Handle special cases for orthogonal rotations
    if (angle - 0.0).abs() < 0.001 || (angle - 360.0).abs() < 0.001 {
        return Ok(pix.deep_clone());
    }
    if (angle - 90.0).abs() < 0.001 {
        return rotate_90(pix, false); // counterclockwise
    }
    if (angle - 180.0).abs() < 0.001 {
        return rotate_180(pix);
    }
    if (angle - 270.0).abs() < 0.001 {
        return rotate_90(pix, true); // clockwise = 270 CCW
    }

    // General rotation
    let radians = angle.to_radians();
    let cos_a = radians.cos();
    let sin_a = radians.sin();

    let w = pix.width() as f32;
    let h = pix.height() as f32;

    // Calculate new dimensions to fit the rotated image
    let (new_w, new_h) = calculate_rotated_bounds(w, h, cos_a, sin_a);
    let new_w = new_w as u32;
    let new_h = new_h as u32;

    let out_pix = Pix::new(new_w, new_h, pix.depth())?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    // Copy colormap if present
    if let Some(cmap) = pix.colormap() {
        let _ = out_mut.set_colormap(Some(cmap.clone()));
    }

    // Fill with background
    fill_image(&mut out_mut, fill_value);

    // Center of original and new images
    let cx_src = w / 2.0;
    let cy_src = h / 2.0;
    let cx_dst = new_w as f32 / 2.0;
    let cy_dst = new_h as f32 / 2.0;

    // Apply rotation with appropriate interpolation
    match pix.depth() {
        PixelDepth::Bit1 => {
            rotate_nearest_neighbor(
                pix,
                &mut out_mut,
                cos_a,
                sin_a,
                cx_src,
                cy_src,
                cx_dst,
                cy_dst,
            );
        }
        PixelDepth::Bit8 | PixelDepth::Bit16 | PixelDepth::Bit32 => {
            rotate_bilinear(
                pix,
                &mut out_mut,
                cos_a,
                sin_a,
                cx_src,
                cy_src,
                cx_dst,
                cy_dst,
            );
        }
        _ => {
            // For 2-bit and 4-bit, use nearest neighbor
            rotate_nearest_neighbor(
                pix,
                &mut out_mut,
                cos_a,
                sin_a,
                cx_src,
                cy_src,
                cx_dst,
                cy_dst,
            );
        }
    }

    Ok(out_mut.into())
}

/// Get default fill value (white) for a given pixel depth
fn get_default_fill_value(depth: PixelDepth) -> u32 {
    match depth {
        PixelDepth::Bit1 => 0, // 0 = white for binary (foreground is black)
        PixelDepth::Bit2 => 3,
        PixelDepth::Bit4 => 15,
        PixelDepth::Bit8 => 255,
        PixelDepth::Bit16 => 65535,
        PixelDepth::Bit32 => 0xFFFFFFFF,
    }
}

/// Calculate the bounding box dimensions after rotation
fn calculate_rotated_bounds(w: f32, h: f32, cos_a: f32, sin_a: f32) -> (f32, f32) {
    // Corners of original image (relative to center)
    let corners = [
        (-w / 2.0, -h / 2.0),
        (w / 2.0, -h / 2.0),
        (w / 2.0, h / 2.0),
        (-w / 2.0, h / 2.0),
    ];

    let mut min_x = f32::MAX;
    let mut max_x = f32::MIN;
    let mut min_y = f32::MAX;
    let mut max_y = f32::MIN;

    for (x, y) in corners {
        let rx = x * cos_a - y * sin_a;
        let ry = x * sin_a + y * cos_a;
        min_x = min_x.min(rx);
        max_x = max_x.max(rx);
        min_y = min_y.min(ry);
        max_y = max_y.max(ry);
    }

    ((max_x - min_x).ceil(), (max_y - min_y).ceil())
}

/// Fill an image with a constant value
fn fill_image(pix: &mut PixMut, value: u32) {
    let w = pix.width();
    let h = pix.height();
    for y in 0..h {
        for x in 0..w {
            pix.set_pixel_unchecked(x, y, value);
        }
    }
}

/// Nearest neighbor rotation (for 1-bit images)
#[allow(clippy::too_many_arguments)]
fn rotate_nearest_neighbor(
    src: &Pix,
    dst: &mut PixMut,
    cos_a: f32,
    sin_a: f32,
    cx_src: f32,
    cy_src: f32,
    cx_dst: f32,
    cy_dst: f32,
) {
    let src_w = src.width() as i32;
    let src_h = src.height() as i32;
    let dst_w = dst.width();
    let dst_h = dst.height();

    for dy in 0..dst_h {
        for dx in 0..dst_w {
            // Transform destination coordinates to source
            let x_rel = dx as f32 - cx_dst;
            let y_rel = dy as f32 - cy_dst;

            // Inverse rotation
            let sx = x_rel * cos_a + y_rel * sin_a + cx_src;
            let sy = -x_rel * sin_a + y_rel * cos_a + cy_src;

            // Nearest neighbor
            let sx_i = sx.round() as i32;
            let sy_i = sy.round() as i32;

            if sx_i >= 0 && sx_i < src_w && sy_i >= 0 && sy_i < src_h {
                let val = src.get_pixel_unchecked(sx_i as u32, sy_i as u32);
                dst.set_pixel_unchecked(dx, dy, val);
            }
        }
    }
}

/// Bilinear interpolation rotation (for 8-bit and 32-bit images)
#[allow(clippy::too_many_arguments)]
fn rotate_bilinear(
    src: &Pix,
    dst: &mut PixMut,
    cos_a: f32,
    sin_a: f32,
    cx_src: f32,
    cy_src: f32,
    cx_dst: f32,
    cy_dst: f32,
) {
    let src_w = src.width() as i32;
    let src_h = src.height() as i32;
    let dst_w = dst.width();
    let dst_h = dst.height();
    let depth = src.depth();

    for dy in 0..dst_h {
        for dx in 0..dst_w {
            // Transform destination coordinates to source
            let x_rel = dx as f32 - cx_dst;
            let y_rel = dy as f32 - cy_dst;

            // Inverse rotation
            let sx = x_rel * cos_a + y_rel * sin_a + cx_src;
            let sy = -x_rel * sin_a + y_rel * cos_a + cy_src;

            // Bilinear interpolation
            let x0 = sx.floor() as i32;
            let y0 = sy.floor() as i32;
            let x1 = x0 + 1;
            let y1 = y0 + 1;

            if x0 >= 0 && x1 < src_w && y0 >= 0 && y1 < src_h {
                let fx = sx - x0 as f32;
                let fy = sy - y0 as f32;

                let val = interpolate_pixel(
                    src, depth, x0 as u32, y0 as u32, x1 as u32, y1 as u32, fx, fy,
                );
                dst.set_pixel_unchecked(dx, dy, val);
            } else if x0 >= -1 && x1 <= src_w && y0 >= -1 && y1 <= src_h {
                // Edge case: partially outside, use available pixels
                let val = interpolate_edge_pixel(src, depth, x0, y0, x1, y1, sx, sy, src_w, src_h);
                dst.set_pixel_unchecked(dx, dy, val);
            }
        }
    }
}

/// Bilinear interpolation of a single pixel
#[allow(clippy::too_many_arguments)]
fn interpolate_pixel(
    src: &Pix,
    depth: PixelDepth,
    x0: u32,
    y0: u32,
    x1: u32,
    y1: u32,
    fx: f32,
    fy: f32,
) -> u32 {
    let p00 = src.get_pixel_unchecked(x0, y0);
    let p10 = src.get_pixel_unchecked(x1, y0);
    let p01 = src.get_pixel_unchecked(x0, y1);
    let p11 = src.get_pixel_unchecked(x1, y1);

    match depth {
        PixelDepth::Bit32 => {
            // Interpolate each channel separately
            let r = interpolate_channel(
                (p00 >> 24) & 0xFF,
                (p10 >> 24) & 0xFF,
                (p01 >> 24) & 0xFF,
                (p11 >> 24) & 0xFF,
                fx,
                fy,
            );
            let g = interpolate_channel(
                (p00 >> 16) & 0xFF,
                (p10 >> 16) & 0xFF,
                (p01 >> 16) & 0xFF,
                (p11 >> 16) & 0xFF,
                fx,
                fy,
            );
            let b = interpolate_channel(
                (p00 >> 8) & 0xFF,
                (p10 >> 8) & 0xFF,
                (p01 >> 8) & 0xFF,
                (p11 >> 8) & 0xFF,
                fx,
                fy,
            );
            let a = interpolate_channel(p00 & 0xFF, p10 & 0xFF, p01 & 0xFF, p11 & 0xFF, fx, fy);
            (r << 24) | (g << 16) | (b << 8) | a
        }
        _ => {
            // Single channel interpolation
            interpolate_channel(p00, p10, p01, p11, fx, fy)
        }
    }
}

/// Interpolate a single channel value
fn interpolate_channel(p00: u32, p10: u32, p01: u32, p11: u32, fx: f32, fy: f32) -> u32 {
    let top = p00 as f32 * (1.0 - fx) + p10 as f32 * fx;
    let bottom = p01 as f32 * (1.0 - fx) + p11 as f32 * fx;
    let result = top * (1.0 - fy) + bottom * fy;
    result.round() as u32
}

/// Handle edge pixels with partial interpolation
#[allow(clippy::too_many_arguments)]
fn interpolate_edge_pixel(
    src: &Pix,
    depth: PixelDepth,
    x0: i32,
    y0: i32,
    x1: i32,
    y1: i32,
    sx: f32,
    sy: f32,
    src_w: i32,
    src_h: i32,
) -> u32 {
    // Get available pixels, using nearest valid pixel for out-of-bounds
    let clamp_x = |x: i32| x.clamp(0, src_w - 1) as u32;
    let clamp_y = |y: i32| y.clamp(0, src_h - 1) as u32;

    let p00 = src.get_pixel_unchecked(clamp_x(x0), clamp_y(y0));
    let p10 = src.get_pixel_unchecked(clamp_x(x1), clamp_y(y0));
    let p01 = src.get_pixel_unchecked(clamp_x(x0), clamp_y(y1));
    let p11 = src.get_pixel_unchecked(clamp_x(x1), clamp_y(y1));

    let fx = sx - x0 as f32;
    let fy = sy - y0 as f32;

    match depth {
        PixelDepth::Bit32 => {
            let r = interpolate_channel(
                (p00 >> 24) & 0xFF,
                (p10 >> 24) & 0xFF,
                (p01 >> 24) & 0xFF,
                (p11 >> 24) & 0xFF,
                fx,
                fy,
            );
            let g = interpolate_channel(
                (p00 >> 16) & 0xFF,
                (p10 >> 16) & 0xFF,
                (p01 >> 16) & 0xFF,
                (p11 >> 16) & 0xFF,
                fx,
                fy,
            );
            let b = interpolate_channel(
                (p00 >> 8) & 0xFF,
                (p10 >> 8) & 0xFF,
                (p01 >> 8) & 0xFF,
                (p11 >> 8) & 0xFF,
                fx,
                fy,
            );
            let a = interpolate_channel(p00 & 0xFF, p10 & 0xFF, p01 & 0xFF, p11 & 0xFF, fx, fy);
            (r << 24) | (g << 16) | (b << 8) | a
        }
        _ => interpolate_channel(p00, p10, p01, p11, fx, fy),
    }
}

// ============================================================================
// New rotation API with multiple algorithms
// ============================================================================

/// Rotate an image by an arbitrary angle using specified options
///
/// This is the most flexible rotation function, supporting multiple algorithms
/// and custom rotation centers.
///
/// # Arguments
/// * `pix` - Input image
/// * `angle` - Rotation angle in radians (positive = clockwise, like Leptonica)
/// * `options` - Rotation options including method, fill color, and center
///
/// # Example
/// ```no_run
/// use leptonica::transform::{rotate, RotateOptions, RotateMethod, RotateFill};
/// use leptonica::core::{Pix, PixelDepth};
///
/// let pix = Pix::new(100, 100, PixelDepth::Bit8).unwrap();
/// let options = RotateOptions::with_method(RotateMethod::AreaMap);
/// let rotated = rotate(&pix, 0.5, &options).unwrap();
/// ```
pub fn rotate(pix: &Pix, angle: f32, options: &RotateOptions) -> TransformResult<Pix> {
    // For very small angles, just clone
    if angle.abs() < MIN_ANGLE_TO_ROTATE {
        return Ok(pix.deep_clone());
    }

    let depth = pix.depth();
    let fill_value = options.fill.to_value(depth);

    // Select method (auto-select based on depth and angle if needed)
    let method = select_rotate_method(options.method, depth, angle);

    // Calculate dimensions and centers
    let w = pix.width() as f32;
    let h = pix.height() as f32;
    let cos_a = angle.cos();
    let sin_a = angle.sin();

    let (out_w, out_h) = if options.expand {
        let (nw, nh) = calculate_rotated_bounds(w, h, cos_a, sin_a);
        (nw as u32, nh as u32)
    } else {
        (pix.width(), pix.height())
    };

    let cx_src = options.center_x.unwrap_or(w / 2.0);
    let cy_src = options.center_y.unwrap_or(h / 2.0);
    let cx_dst = if options.expand {
        out_w as f32 / 2.0
    } else {
        cx_src
    };
    let cy_dst = if options.expand {
        out_h as f32 / 2.0
    } else {
        cy_src
    };

    // Create output image
    let out_pix = Pix::new(out_w, out_h, depth)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    // Copy colormap if present
    if let Some(cmap) = pix.colormap() {
        let _ = out_mut.set_colormap(Some(cmap.clone()));
    }

    // Fill with background
    fill_image(&mut out_mut, fill_value);

    // Perform rotation with selected method
    match method {
        RotateMethod::Sampling => {
            rotate_by_sampling_impl(
                pix,
                &mut out_mut,
                cos_a,
                sin_a,
                cx_src,
                cy_src,
                cx_dst,
                cy_dst,
                fill_value,
            );
        }
        RotateMethod::AreaMap => {
            rotate_area_map_impl(
                pix,
                &mut out_mut,
                cos_a,
                sin_a,
                cx_src,
                cy_src,
                cx_dst,
                cy_dst,
                fill_value,
            );
        }
        RotateMethod::Shear => {
            rotate_shear_impl(
                pix,
                &mut out_mut,
                angle,
                cx_src as i32,
                cy_src as i32,
                fill_value,
            );
        }
        RotateMethod::Bilinear => {
            rotate_bilinear(
                pix,
                &mut out_mut,
                cos_a,
                sin_a,
                cx_src,
                cy_src,
                cx_dst,
                cy_dst,
            );
        }
        RotateMethod::Auto => unreachable!(),
    }

    Ok(out_mut.into())
}

/// Rotate an image using a specific method (simple API)
///
/// # Arguments
/// * `pix` - Input image
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `method` - Rotation algorithm to use
pub fn rotate_with_method(pix: &Pix, angle: f32, method: RotateMethod) -> TransformResult<Pix> {
    let options = RotateOptions {
        method,
        ..Default::default()
    };
    rotate(pix, angle, &options)
}

/// Rotate an image about a specified center point
///
/// # Arguments
/// * `pix` - Input image
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `center_x` - X coordinate of rotation center
/// * `center_y` - Y coordinate of rotation center
/// * `fill` - Background fill color
pub fn rotate_about_center(
    pix: &Pix,
    angle: f32,
    center_x: f32,
    center_y: f32,
    fill: RotateFill,
) -> TransformResult<Pix> {
    let options = RotateOptions {
        fill,
        center_x: Some(center_x),
        center_y: Some(center_y),
        expand: false, // Don't expand when using custom center
        ..Default::default()
    };
    rotate(pix, angle, &options)
}

/// Select the best rotation method based on depth and angle
fn select_rotate_method(method: RotateMethod, depth: PixelDepth, angle: f32) -> RotateMethod {
    match method {
        RotateMethod::Auto => {
            let abs_angle = angle.abs();

            // For 1bpp, use shear for small angles, sampling for large
            if depth == PixelDepth::Bit1 {
                if abs_angle > MAX_1BPP_SHEAR_ANGLE {
                    RotateMethod::Sampling
                } else {
                    RotateMethod::Shear
                }
            }
            // For other depths, use area mapping for best quality
            // unless angle is very large
            else if abs_angle > MAX_SHEAR_ANGLE {
                RotateMethod::Sampling
            } else {
                match depth {
                    PixelDepth::Bit8 | PixelDepth::Bit32 => RotateMethod::AreaMap,
                    _ => RotateMethod::Sampling,
                }
            }
        }
        // Validate requested method is appropriate
        RotateMethod::AreaMap => {
            if depth == PixelDepth::Bit1
                || depth == PixelDepth::Bit2
                || depth == PixelDepth::Bit4
                || depth == PixelDepth::Bit16
            {
                // Fall back to sampling for unsupported depths
                RotateMethod::Sampling
            } else {
                RotateMethod::AreaMap
            }
        }
        RotateMethod::Shear => {
            if angle.abs() > MAX_SHEAR_ANGLE {
                // Angle too large for shear
                RotateMethod::Sampling
            } else {
                RotateMethod::Shear
            }
        }
        other => other,
    }
}

// ============================================================================
// Sampling rotation implementation (pixRotateBySampling equivalent)
// ============================================================================

/// Rotation by sampling (nearest neighbor) - like pixRotateBySampling
#[allow(clippy::too_many_arguments)]
fn rotate_by_sampling_impl(
    src: &Pix,
    dst: &mut PixMut,
    cos_a: f32,
    sin_a: f32,
    cx_src: f32,
    cy_src: f32,
    cx_dst: f32,
    cy_dst: f32,
    _fill_value: u32,
) {
    let src_w = src.width() as i32;
    let src_h = src.height() as i32;
    let dst_w = dst.width();
    let dst_h = dst.height();
    let wm1 = src_w - 1;
    let hm1 = src_h - 1;

    for i in 0..dst_h {
        let ydif = cy_dst - i as f32;
        for j in 0..dst_w {
            let xdif = cx_dst - j as f32;

            // Inverse rotation (Leptonica convention: clockwise positive)
            let x = (cx_src + (-xdif * cos_a - ydif * sin_a)).round() as i32;
            let y = (cy_src + (-ydif * cos_a + xdif * sin_a)).round() as i32;

            if x >= 0 && x <= wm1 && y >= 0 && y <= hm1 {
                let val = src.get_pixel_unchecked(x as u32, y as u32);
                dst.set_pixel_unchecked(j, i, val);
            }
            // Pixels outside bounds keep the fill value set earlier
        }
    }
}

// ============================================================================
// Area mapping rotation implementation (pixRotateAM equivalent)
// ============================================================================

/// Rotation by area mapping - like pixRotateAMGray/pixRotateAMColor
///
/// Uses 16x16 sub-pixel grid for high-quality interpolation
#[allow(clippy::too_many_arguments)]
fn rotate_area_map_impl(
    src: &Pix,
    dst: &mut PixMut,
    cos_a: f32,
    sin_a: f32,
    cx_src: f32,
    cy_src: f32,
    cx_dst: f32,
    cy_dst: f32,
    fill_value: u32,
) {
    let depth = src.depth();
    match depth {
        PixelDepth::Bit8 => {
            rotate_area_map_gray(
                src,
                dst,
                cos_a,
                sin_a,
                cx_src,
                cy_src,
                cx_dst,
                cy_dst,
                fill_value as u8,
            );
        }
        PixelDepth::Bit32 => {
            rotate_area_map_color(
                src, dst, cos_a, sin_a, cx_src, cy_src, cx_dst, cy_dst, fill_value,
            );
        }
        _ => {
            // Fall back to sampling for other depths
            rotate_by_sampling_impl(
                src, dst, cos_a, sin_a, cx_src, cy_src, cx_dst, cy_dst, fill_value,
            );
        }
    }
}

/// Area mapping rotation for 8bpp grayscale
#[allow(clippy::too_many_arguments)]
fn rotate_area_map_gray(
    src: &Pix,
    dst: &mut PixMut,
    cos_a: f32,
    sin_a: f32,
    cx_src: f32,
    cy_src: f32,
    cx_dst: f32,
    cy_dst: f32,
    grayval: u8,
) {
    let src_w = src.width() as i32;
    let src_h = src.height() as i32;
    let dst_w = dst.width();
    let dst_h = dst.height();
    let wm2 = src_w - 2;
    let hm2 = src_h - 2;

    // Scale sin/cos by 16 for sub-pixel precision
    let sina = 16.0 * sin_a;
    let cosa = 16.0 * cos_a;

    for i in 0..dst_h {
        let ydif = cy_dst - i as f32;
        for j in 0..dst_w {
            let xdif = cx_dst - j as f32;

            // Sub-pixel position (scaled by 16)
            let xpm = (-xdif * cosa - ydif * sina) as i32;
            let ypm = (-ydif * cosa + xdif * sina) as i32;

            // Integer and fractional parts
            let xp = (cx_src as i32) + (xpm >> 4);
            let yp = (cy_src as i32) + (ypm >> 4);
            let xf = xpm & 0x0f;
            let yf = ypm & 0x0f;

            // Check bounds
            if xp < 0 || yp < 0 || xp > wm2 || yp > hm2 {
                dst.set_pixel_unchecked(j, i, grayval as u32);
                continue;
            }

            // Get four neighboring pixels
            let v00 = src.get_pixel_unchecked(xp as u32, yp as u32);
            let v10 = src.get_pixel_unchecked((xp + 1) as u32, yp as u32);
            let v01 = src.get_pixel_unchecked(xp as u32, (yp + 1) as u32);
            let v11 = src.get_pixel_unchecked((xp + 1) as u32, (yp + 1) as u32);

            // Area-weighted interpolation
            let val = ((16 - xf) * (16 - yf) * v00 as i32
                + xf * (16 - yf) * v10 as i32
                + (16 - xf) * yf * v01 as i32
                + xf * yf * v11 as i32
                + 128)
                / 256;

            dst.set_pixel_unchecked(j, i, val as u32);
        }
    }
}

/// Area mapping rotation for 32bpp color
#[allow(clippy::too_many_arguments)]
fn rotate_area_map_color(
    src: &Pix,
    dst: &mut PixMut,
    cos_a: f32,
    sin_a: f32,
    cx_src: f32,
    cy_src: f32,
    cx_dst: f32,
    cy_dst: f32,
    colorval: u32,
) {
    let src_w = src.width() as i32;
    let src_h = src.height() as i32;
    let dst_w = dst.width();
    let dst_h = dst.height();
    let wm2 = src_w - 2;
    let hm2 = src_h - 2;

    // Scale sin/cos by 16 for sub-pixel precision
    let sina = 16.0 * sin_a;
    let cosa = 16.0 * cos_a;

    for i in 0..dst_h {
        let ydif = cy_dst - i as f32;
        for j in 0..dst_w {
            let xdif = cx_dst - j as f32;

            // Sub-pixel position (scaled by 16)
            let xpm = (-xdif * cosa - ydif * sina) as i32;
            let ypm = (-ydif * cosa + xdif * sina) as i32;

            // Integer and fractional parts
            let xp = (cx_src as i32) + (xpm >> 4);
            let yp = (cy_src as i32) + (ypm >> 4);
            let xf = xpm & 0x0f;
            let yf = ypm & 0x0f;

            // Check bounds
            if xp < 0 || yp < 0 || xp > wm2 || yp > hm2 {
                dst.set_pixel_unchecked(j, i, colorval);
                continue;
            }

            // Get four neighboring pixels
            let word00 = src.get_pixel_unchecked(xp as u32, yp as u32);
            let word10 = src.get_pixel_unchecked((xp + 1) as u32, yp as u32);
            let word01 = src.get_pixel_unchecked(xp as u32, (yp + 1) as u32);
            let word11 = src.get_pixel_unchecked((xp + 1) as u32, (yp + 1) as u32);

            // Extract and interpolate each channel (RGBA format)
            let (r00, g00, b00, a00) = pixel::extract_rgba(word00);
            let (r10, g10, b10, a10) = pixel::extract_rgba(word10);
            let (r01, g01, b01, a01) = pixel::extract_rgba(word01);
            let (r11, g11, b11, a11) = pixel::extract_rgba(word11);

            let rval = area_interp(r00, r10, r01, r11, xf, yf);
            let gval = area_interp(g00, g10, g01, g11, xf, yf);
            let bval = area_interp(b00, b10, b01, b11, xf, yf);
            let aval = area_interp(a00, a10, a01, a11, xf, yf);

            let pixel = pixel::compose_rgba(rval, gval, bval, aval);
            dst.set_pixel_unchecked(j, i, pixel);
        }
    }
}

/// Area interpolation helper for a single channel
#[inline]
fn area_interp(v00: u8, v10: u8, v01: u8, v11: u8, xf: i32, yf: i32) -> u8 {
    let val = ((16 - xf) * (16 - yf) * v00 as i32
        + xf * (16 - yf) * v10 as i32
        + (16 - xf) * yf * v01 as i32
        + xf * yf * v11 as i32
        + 128)
        / 256;
    val.clamp(0, 255) as u8
}

// ============================================================================
// Shear-based rotation implementation (pixRotateShear equivalent)
// ============================================================================

/// Rotation by shear - like pixRotateShear
///
/// Uses 2-shear for small angles (< ~3 degrees) or 3-shear for larger angles
#[allow(clippy::too_many_arguments)]
fn rotate_shear_impl(
    src: &Pix,
    dst: &mut PixMut,
    angle: f32,
    xcen: i32,
    ycen: i32,
    fill_value: u32,
) {
    let abs_angle = angle.abs();

    if abs_angle <= MAX_TWO_SHEAR_ANGLE {
        rotate_2_shear(src, dst, angle, xcen, ycen, fill_value);
    } else {
        rotate_3_shear(src, dst, angle, xcen, ycen, fill_value);
    }
}

/// 2-shear rotation (for small angles)
///
/// x' = x + tan(angle) * (y - ycen)
/// y' = y + tan(angle) * (x - xcen)
fn rotate_2_shear(src: &Pix, dst: &mut PixMut, angle: f32, xcen: i32, ycen: i32, fill_value: u32) {
    let w = src.width() as i32;
    let h = src.height() as i32;
    let tan_a = angle.tan();

    // First pass: horizontal shear into temporary
    let temp_pix = Pix::new(src.width(), src.height(), src.depth()).unwrap();
    let mut temp = temp_pix.try_into_mut().unwrap();
    fill_image(&mut temp, fill_value);

    for y in 0..h {
        let shift = ((y - ycen) as f32 * tan_a).round() as i32;
        for x in 0..w {
            let new_x = x + shift;
            if new_x >= 0 && new_x < w {
                let val = src.get_pixel_unchecked(x as u32, y as u32);
                temp.set_pixel_unchecked(new_x as u32, y as u32, val);
            }
        }
    }

    // Second pass: vertical shear from temp to dst
    let temp_ref: Pix = temp.into();
    for x in 0..w {
        let shift = ((x - xcen) as f32 * tan_a).round() as i32;
        for y in 0..h {
            let new_y = y + shift;
            if new_y >= 0 && new_y < h {
                let val = temp_ref.get_pixel_unchecked(x as u32, y as u32);
                dst.set_pixel_unchecked(x as u32, new_y as u32, val);
            }
        }
    }
}

// ============================================================================
// Phase 6: Corner area-map rotations
// ============================================================================

/// Rotate an image by area-map about the upper-left corner (dispatcher)
///
/// Dispatches to `rotate_am_color_corner` for 32bpp, `rotate_am_gray_corner`
/// for 8bpp, and clones for other depths.
///
/// # Arguments
/// * `pix` - Input image (8bpp or 32bpp)
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `fill` - Background fill color
pub fn rotate_am_corner(pix: &Pix, angle: f32, fill: RotateFill) -> TransformResult<Pix> {
    match pix.depth() {
        PixelDepth::Bit32 => rotate_am_color_corner(pix, angle, fill),
        PixelDepth::Bit8 => rotate_am_gray_corner(pix, angle, fill),
        _ => Ok(pix.deep_clone()),
    }
}

/// Rotate a 32bpp color image by area-map about the upper-left corner
///
/// # Arguments
/// * `pix` - 32bpp input image
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `fill` - Background fill color
pub fn rotate_am_color_corner(pix: &Pix, angle: f32, fill: RotateFill) -> TransformResult<Pix> {
    if pix.depth() != PixelDepth::Bit32 {
        return Err(TransformError::UnsupportedDepth(format!(
            "{:?}",
            pix.depth()
        )));
    }
    if angle.abs() < MIN_ANGLE_TO_ROTATE {
        return Ok(pix.deep_clone());
    }

    let w = pix.width();
    let h = pix.height();
    let colorval = fill.to_value(PixelDepth::Bit32);

    let out_pix = Pix::new(w, h, PixelDepth::Bit32)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    let cos_a = angle.cos();
    let sin_a = angle.sin();
    rotate_area_map_color(
        pix,
        &mut out_mut,
        cos_a,
        sin_a,
        0.0,
        0.0,
        0.0,
        0.0,
        colorval,
    );

    Ok(out_mut.into())
}

/// Rotate an 8bpp grayscale image by area-map about the upper-left corner
///
/// # Arguments
/// * `pix` - 8bpp input image
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `fill` - Background fill color
pub fn rotate_am_gray_corner(pix: &Pix, angle: f32, fill: RotateFill) -> TransformResult<Pix> {
    if pix.depth() != PixelDepth::Bit8 {
        return Err(TransformError::UnsupportedDepth(format!(
            "{:?}",
            pix.depth()
        )));
    }
    if angle.abs() < MIN_ANGLE_TO_ROTATE {
        return Ok(pix.deep_clone());
    }

    let w = pix.width();
    let h = pix.height();
    let grayval = fill.to_value(PixelDepth::Bit8) as u8;

    let out_pix = Pix::new(w, h, PixelDepth::Bit8)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    let cos_a = angle.cos();
    let sin_a = angle.sin();
    rotate_area_map_gray(pix, &mut out_mut, cos_a, sin_a, 0.0, 0.0, 0.0, 0.0, grayval);

    Ok(out_mut.into())
}

// ============================================================================
// Phase 6: Public shear rotation API
// ============================================================================

/// Rotate an image by shear about an arbitrary center point
///
/// Uses 2-shear for small angles (|angle| <= ~0.06 rad) and 3-shear otherwise.
/// The output is the same size as the input.
///
/// # Arguments
/// * `pix` - Input image
/// * `cx` - X coordinate of rotation center
/// * `cy` - Y coordinate of rotation center
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `fill` - Background fill color
pub fn rotate_shear(
    pix: &Pix,
    cx: i32,
    cy: i32,
    angle: f32,
    fill: ShearFill,
) -> TransformResult<Pix> {
    if angle.abs() < MIN_ANGLE_TO_ROTATE {
        return Ok(pix.deep_clone());
    }

    let w = pix.width();
    let h = pix.height();
    let depth = pix.depth();
    let fill_value = fill.to_value(depth);

    let out_pix = Pix::new(w, h, depth)?;
    let mut out_mut = out_pix.try_into_mut().unwrap();

    if let Some(cmap) = pix.colormap() {
        let _ = out_mut.set_colormap(Some(cmap.clone()));
    }
    fill_image(&mut out_mut, fill_value);
    rotate_shear_impl(pix, &mut out_mut, angle, cx, cy, fill_value);

    Ok(out_mut.into())
}

/// Rotate an image in-place by 3-shear about an arbitrary center point
///
/// Uses the H-V-H 3-shear sequence (Paeth's algorithm).
/// The image must not have a colormap.
///
/// # Arguments
/// * `pix` - Image to rotate in place (must not have colormap)
/// * `cx` - X coordinate of rotation center
/// * `cy` - Y coordinate of rotation center
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `fill` - Background fill color
pub fn rotate_shear_ip(
    pix: &mut PixMut,
    cx: i32,
    cy: i32,
    angle: f32,
    fill: ShearFill,
) -> TransformResult<()> {
    if angle.abs() < MIN_ANGLE_TO_ROTATE {
        return Ok(());
    }

    let hangle = angle.sin().atan();
    let half_angle = angle / 2.0;

    // H-V-H 3-shear sequence (matches pixRotateShearIP in C leptonica)
    h_shear_ip(pix, cy, half_angle, fill)?;
    v_shear_ip(pix, cx, hangle, fill)?;
    h_shear_ip(pix, cy, half_angle, fill)?;

    Ok(())
}

/// Rotate an image by shear about the image center
///
/// Equivalent to `rotate_shear` with center = (w/2, h/2).
///
/// # Arguments
/// * `pix` - Input image
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `fill` - Background fill color
pub fn rotate_shear_center(pix: &Pix, angle: f32, fill: ShearFill) -> TransformResult<Pix> {
    let cx = (pix.width() / 2) as i32;
    let cy = (pix.height() / 2) as i32;
    rotate_shear(pix, cx, cy, angle, fill)
}

/// Rotate an image in-place by shear about the image center
///
/// Equivalent to `rotate_shear_ip` with center = (w/2, h/2).
/// The image must not have a colormap.
///
/// # Arguments
/// * `pix` - Image to rotate in place (must not have colormap)
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `fill` - Background fill color
pub fn rotate_shear_center_ip(
    pix: &mut PixMut,
    angle: f32,
    fill: ShearFill,
) -> TransformResult<()> {
    let cx = (pix.width() / 2) as i32;
    let cy = (pix.height() / 2) as i32;
    rotate_shear_ip(pix, cx, cy, angle, fill)
}

// ============================================================================
// Phase 6: Alpha-channel rotation
// ============================================================================

/// Rotate a 32bpp image with alpha channel handling
///
/// Rotates the RGB channels with area-map interpolation, then separately
/// rotates the alpha channel and combines the results.
///
/// # Arguments
/// * `pix` - 32bpp input image
/// * `angle` - Rotation angle in radians (positive = clockwise)
/// * `alpha_pix` - Optional 8bpp alpha channel; if None, a uniform alpha
///   derived from `fract` is used
/// * `fract` - Alpha fill fraction in [0.0, 1.0] when `alpha_pix` is None
///   (0.0 = fully transparent, 1.0 = fully opaque)
pub fn rotate_with_alpha(
    pix: &Pix,
    angle: f32,
    alpha_pix: Option<&Pix>,
    fract: f32,
) -> TransformResult<Pix> {
    if pix.depth() != PixelDepth::Bit32 {
        return Err(TransformError::UnsupportedDepth(format!(
            "{:?}",
            pix.depth()
        )));
    }

    let w = pix.width();
    let h = pix.height();

    // Create or validate alpha channel
    let alpha_owned;
    let alpha = if let Some(a) = alpha_pix {
        if a.depth() != PixelDepth::Bit8 {
            return Err(TransformError::UnsupportedDepth(format!("{:?}", a.depth())));
        }
        if a.width() != w || a.height() != h {
            return Err(TransformError::InvalidParameters(format!(
                "alpha image dimensions ({}x{}) must match source image dimensions ({}x{})",
                a.width(),
                a.height(),
                w,
                h
            )));
        }
        a
    } else {
        let a_pix = Pix::new(w, h, PixelDepth::Bit8)?;
        let mut a_mut = a_pix.try_into_mut().unwrap();
        let alpha_val = (255.0 * fract.clamp(0.0, 1.0) + 0.5) as u32;
        for y in 0..h {
            for x in 0..w {
                a_mut.set_pixel_unchecked(x, y, alpha_val);
            }
        }
        alpha_owned = Pix::from(a_mut);
        &alpha_owned
    };

    // Rotate the RGB image (area map, same size as input)
    let options = RotateOptions {
        method: RotateMethod::AreaMap,
        fill: RotateFill::White,
        expand: false,
        ..Default::default()
    };
    let rotated = rotate(pix, angle, &options)?;

    if angle.abs() < MIN_ANGLE_TO_ROTATE {
        // No rotation: just copy alpha into result
        let mut out_mut = rotated.try_into_mut().unwrap();
        for y in 0..h {
            for x in 0..w {
                let pixel = out_mut.get_pixel_unchecked(x, y);
                let a = alpha.get_pixel_unchecked(x, y) & 0xFF;
                out_mut.set_pixel_unchecked(x, y, (pixel & 0xFFFFFF00) | a);
            }
        }
        return Ok(out_mut.into());
    }

    // Rotate the alpha channel separately with area-map (same size, white border)
    let cos_a = angle.cos();
    let sin_a = angle.sin();
    let cx = w as f32 / 2.0;
    let cy = h as f32 / 2.0;

    let alpha_out_pix = Pix::new(w, h, PixelDepth::Bit8)?;
    let mut alpha_out = alpha_out_pix.try_into_mut().unwrap();
    rotate_area_map_gray(alpha, &mut alpha_out, cos_a, sin_a, cx, cy, cx, cy, 255);
    let rotated_alpha: Pix = alpha_out.into();

    // Set alpha channel in rotated RGB result
    let mut out_mut = rotated.try_into_mut().unwrap();
    for y in 0..h {
        for x in 0..w {
            let pixel = out_mut.get_pixel_unchecked(x, y);
            let a = rotated_alpha.get_pixel_unchecked(x, y) & 0xFF;
            out_mut.set_pixel_unchecked(x, y, (pixel & 0xFFFFFF00) | a);
        }
    }

    Ok(out_mut.into())
}

/// 3-shear rotation (Paeth's algorithm)
///
/// y' = y + tan(angle/2) * (x - xcen)  [first V-shear]
/// x' = x + sin(angle) * (y - ycen)    [H-shear]
/// y' = y + tan(angle/2) * (x - xcen)  [second V-shear]
fn rotate_3_shear(src: &Pix, dst: &mut PixMut, angle: f32, xcen: i32, ycen: i32, fill_value: u32) {
    let w = src.width() as i32;
    let h = src.height() as i32;
    let half_tan = (angle / 2.0).tan();
    let hangle = (angle.sin()).atan(); // atan(sin(angle))

    // Create two temporary images
    let temp1_pix = Pix::new(src.width(), src.height(), src.depth()).unwrap();
    let mut temp1 = temp1_pix.try_into_mut().unwrap();
    fill_image(&mut temp1, fill_value);

    let temp2_pix = Pix::new(src.width(), src.height(), src.depth()).unwrap();
    let mut temp2 = temp2_pix.try_into_mut().unwrap();
    fill_image(&mut temp2, fill_value);

    // First V-shear
    for x in 0..w {
        let shift = ((x - xcen) as f32 * half_tan).round() as i32;
        for y in 0..h {
            let new_y = y + shift;
            if new_y >= 0 && new_y < h {
                let val = src.get_pixel_unchecked(x as u32, y as u32);
                temp1.set_pixel_unchecked(x as u32, new_y as u32, val);
            }
        }
    }

    // H-shear
    let temp1_ref: Pix = temp1.into();
    for y in 0..h {
        let shift = ((y - ycen) as f32 * hangle).round() as i32;
        for x in 0..w {
            let new_x = x + shift;
            if new_x >= 0 && new_x < w {
                let val = temp1_ref.get_pixel_unchecked(x as u32, y as u32);
                temp2.set_pixel_unchecked(new_x as u32, y as u32, val);
            }
        }
    }

    // Second V-shear
    let temp2_ref: Pix = temp2.into();
    for x in 0..w {
        let shift = ((x - xcen) as f32 * half_tan).round() as i32;
        for y in 0..h {
            let new_y = y + shift;
            if new_y >= 0 && new_y < h {
                let val = temp2_ref.get_pixel_unchecked(x as u32, y as u32);
                dst.set_pixel_unchecked(x as u32, new_y as u32, val);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{PixelDepth, pixel};

    #[test]
    fn test_rotate_90_clockwise() {
        // 2x3 grayscale image
        let pix = Pix::new(2, 3, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // Set pattern:
        // [1, 2]
        // [3, 4]
        // [5, 6]
        pix_mut.set_pixel_unchecked(0, 0, 1);
        pix_mut.set_pixel_unchecked(1, 0, 2);
        pix_mut.set_pixel_unchecked(0, 1, 3);
        pix_mut.set_pixel_unchecked(1, 1, 4);
        pix_mut.set_pixel_unchecked(0, 2, 5);
        pix_mut.set_pixel_unchecked(1, 2, 6);

        let pix: Pix = pix_mut.into();
        let rotated = rotate_90(&pix, true).unwrap();

        // After 90 CW rotation: 3x2
        // [5, 3, 1]
        // [6, 4, 2]
        assert_eq!((rotated.width(), rotated.height()), (3, 2));
        assert_eq!(rotated.get_pixel_unchecked(0, 0), 5);
        assert_eq!(rotated.get_pixel_unchecked(1, 0), 3);
        assert_eq!(rotated.get_pixel_unchecked(2, 0), 1);
        assert_eq!(rotated.get_pixel_unchecked(0, 1), 6);
        assert_eq!(rotated.get_pixel_unchecked(1, 1), 4);
        assert_eq!(rotated.get_pixel_unchecked(2, 1), 2);
    }

    #[test]
    fn test_rotate_90_counterclockwise() {
        // 2x3 grayscale image
        let pix = Pix::new(2, 3, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        pix_mut.set_pixel_unchecked(0, 0, 1);
        pix_mut.set_pixel_unchecked(1, 0, 2);
        pix_mut.set_pixel_unchecked(0, 1, 3);
        pix_mut.set_pixel_unchecked(1, 1, 4);
        pix_mut.set_pixel_unchecked(0, 2, 5);
        pix_mut.set_pixel_unchecked(1, 2, 6);

        let pix: Pix = pix_mut.into();
        let rotated = rotate_90(&pix, false).unwrap();

        // After 90 CCW rotation: 3x2
        // [2, 4, 6]
        // [1, 3, 5]
        assert_eq!((rotated.width(), rotated.height()), (3, 2));
        assert_eq!(rotated.get_pixel_unchecked(0, 0), 2);
        assert_eq!(rotated.get_pixel_unchecked(1, 0), 4);
        assert_eq!(rotated.get_pixel_unchecked(2, 0), 6);
        assert_eq!(rotated.get_pixel_unchecked(0, 1), 1);
        assert_eq!(rotated.get_pixel_unchecked(1, 1), 3);
        assert_eq!(rotated.get_pixel_unchecked(2, 1), 5);
    }

    #[test]
    fn test_rotate_180() {
        let pix = Pix::new(2, 2, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // [1, 2]
        // [3, 4]
        pix_mut.set_pixel_unchecked(0, 0, 1);
        pix_mut.set_pixel_unchecked(1, 0, 2);
        pix_mut.set_pixel_unchecked(0, 1, 3);
        pix_mut.set_pixel_unchecked(1, 1, 4);

        let pix: Pix = pix_mut.into();
        let rotated = rotate_180(&pix).unwrap();

        // After 180 rotation:
        // [4, 3]
        // [2, 1]
        assert_eq!(rotated.get_pixel_unchecked(0, 0), 4);
        assert_eq!(rotated.get_pixel_unchecked(1, 0), 3);
        assert_eq!(rotated.get_pixel_unchecked(0, 1), 2);
        assert_eq!(rotated.get_pixel_unchecked(1, 1), 1);
    }

    #[test]
    fn test_flip_lr() {
        let pix = Pix::new(3, 2, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // [1, 2, 3]
        // [4, 5, 6]
        pix_mut.set_pixel_unchecked(0, 0, 1);
        pix_mut.set_pixel_unchecked(1, 0, 2);
        pix_mut.set_pixel_unchecked(2, 0, 3);
        pix_mut.set_pixel_unchecked(0, 1, 4);
        pix_mut.set_pixel_unchecked(1, 1, 5);
        pix_mut.set_pixel_unchecked(2, 1, 6);

        let pix: Pix = pix_mut.into();
        let flipped = flip_lr(&pix).unwrap();

        // After LR flip:
        // [3, 2, 1]
        // [6, 5, 4]
        assert_eq!(flipped.get_pixel_unchecked(0, 0), 3);
        assert_eq!(flipped.get_pixel_unchecked(1, 0), 2);
        assert_eq!(flipped.get_pixel_unchecked(2, 0), 1);
        assert_eq!(flipped.get_pixel_unchecked(0, 1), 6);
        assert_eq!(flipped.get_pixel_unchecked(1, 1), 5);
        assert_eq!(flipped.get_pixel_unchecked(2, 1), 4);
    }

    #[test]
    fn test_flip_tb() {
        let pix = Pix::new(2, 3, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // [1, 2]
        // [3, 4]
        // [5, 6]
        pix_mut.set_pixel_unchecked(0, 0, 1);
        pix_mut.set_pixel_unchecked(1, 0, 2);
        pix_mut.set_pixel_unchecked(0, 1, 3);
        pix_mut.set_pixel_unchecked(1, 1, 4);
        pix_mut.set_pixel_unchecked(0, 2, 5);
        pix_mut.set_pixel_unchecked(1, 2, 6);

        let pix: Pix = pix_mut.into();
        let flipped = flip_tb(&pix).unwrap();

        // After TB flip:
        // [5, 6]
        // [3, 4]
        // [1, 2]
        assert_eq!(flipped.get_pixel_unchecked(0, 0), 5);
        assert_eq!(flipped.get_pixel_unchecked(1, 0), 6);
        assert_eq!(flipped.get_pixel_unchecked(0, 1), 3);
        assert_eq!(flipped.get_pixel_unchecked(1, 1), 4);
        assert_eq!(flipped.get_pixel_unchecked(0, 2), 1);
        assert_eq!(flipped.get_pixel_unchecked(1, 2), 2);
    }

    #[test]
    fn test_rotate_orth_all_quadrants() {
        let pix = Pix::new(2, 2, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        pix_mut.set_pixel_unchecked(0, 0, 1);
        pix_mut.set_pixel_unchecked(1, 0, 2);
        pix_mut.set_pixel_unchecked(0, 1, 3);
        pix_mut.set_pixel_unchecked(1, 1, 4);

        let pix: Pix = pix_mut.into();

        // 0 quads = no rotation
        let r0 = rotate_orth(&pix, 0).unwrap();
        assert_eq!(r0.get_pixel_unchecked(0, 0), 1);

        // 4 quads = back to original (mod 4)
        let r4 = rotate_orth(&pix, 4).unwrap();
        assert_eq!(r4.get_pixel_unchecked(0, 0), 1);
    }

    #[test]
    fn test_rotate_32bpp() {
        let pix = Pix::new(2, 2, PixelDepth::Bit32).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        let red = pixel::compose_rgb(255, 0, 0);
        let green = pixel::compose_rgb(0, 255, 0);
        let blue = pixel::compose_rgb(0, 0, 255);
        let white = pixel::compose_rgb(255, 255, 255);

        // [R, G]
        // [B, W]
        pix_mut.set_pixel_unchecked(0, 0, red);
        pix_mut.set_pixel_unchecked(1, 0, green);
        pix_mut.set_pixel_unchecked(0, 1, blue);
        pix_mut.set_pixel_unchecked(1, 1, white);

        let pix: Pix = pix_mut.into();
        let rotated = rotate_90(&pix, true).unwrap();

        // After 90 CW:
        // [B, R]
        // [W, G]
        assert_eq!(rotated.get_pixel_unchecked(0, 0), blue);
        assert_eq!(rotated.get_pixel_unchecked(1, 0), red);
        assert_eq!(rotated.get_pixel_unchecked(0, 1), white);
        assert_eq!(rotated.get_pixel_unchecked(1, 1), green);
    }

    // ========================================================================
    // Arbitrary angle rotation tests
    // ========================================================================

    #[test]
    fn test_rotate_by_angle_zero() {
        let pix = Pix::new(10, 10, PixelDepth::Bit8).unwrap();
        let rotated = rotate_by_angle(&pix, 0.0).unwrap();
        assert_eq!(rotated.width(), 10);
        assert_eq!(rotated.height(), 10);
    }

    #[test]
    fn test_rotate_by_angle_90() {
        let pix = Pix::new(20, 10, PixelDepth::Bit8).unwrap();
        let rotated = rotate_by_angle(&pix, 90.0).unwrap();
        // 90 degree rotation swaps dimensions
        assert_eq!(rotated.width(), 10);
        assert_eq!(rotated.height(), 20);
    }

    #[test]
    fn test_rotate_by_angle_180() {
        let pix = Pix::new(20, 10, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();
        pix_mut.set_pixel_unchecked(0, 0, 100);
        let pix: Pix = pix_mut.into();

        let rotated = rotate_by_angle(&pix, 180.0).unwrap();
        assert_eq!(rotated.width(), 20);
        assert_eq!(rotated.height(), 10);
        // Top-left becomes bottom-right
        assert_eq!(rotated.get_pixel_unchecked(19, 9), 100);
    }

    #[test]
    fn test_rotate_by_angle_45() {
        let pix = Pix::new(100, 100, PixelDepth::Bit8).unwrap();
        let rotated = rotate_by_angle(&pix, 45.0).unwrap();

        // 45 degree rotation should expand dimensions by ~sqrt(2)
        let expected_size = (100.0 * 2.0_f32.sqrt()).ceil() as u32;
        assert!(rotated.width() >= expected_size - 2 && rotated.width() <= expected_size + 2);
        assert!(rotated.height() >= expected_size - 2 && rotated.height() <= expected_size + 2);
    }

    #[test]
    fn test_rotate_by_radians() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let rotated_deg = rotate_by_angle(&pix, 45.0).unwrap();
        let rotated_rad = rotate_by_radians(&pix, std::f32::consts::FRAC_PI_4).unwrap();

        // Both should produce same dimensions
        assert_eq!(rotated_deg.width(), rotated_rad.width());
        assert_eq!(rotated_deg.height(), rotated_rad.height());
    }

    #[test]
    fn test_rotate_negative_angle() {
        let pix = Pix::new(100, 50, PixelDepth::Bit8).unwrap();
        let rotated_pos = rotate_by_angle(&pix, 30.0).unwrap();
        let rotated_neg = rotate_by_angle(&pix, -330.0).unwrap(); // -330 = +30

        assert_eq!(rotated_pos.width(), rotated_neg.width());
        assert_eq!(rotated_pos.height(), rotated_neg.height());
    }

    #[test]
    fn test_rotate_1bpp() {
        // 1-bit image uses nearest neighbor
        let pix = Pix::new(50, 50, PixelDepth::Bit1).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();
        // Set some pixels (1 = black in 1bpp)
        for i in 10..40 {
            pix_mut.set_pixel_unchecked(i, 25, 1);
        }
        let pix: Pix = pix_mut.into();

        let rotated = rotate_by_angle(&pix, 15.0).unwrap();
        assert!(rotated.width() > 50);
        assert!(rotated.height() > 50);
    }

    #[test]
    fn test_calculate_rotated_bounds() {
        // 45 degree rotation of a square
        let cos_45 = std::f32::consts::FRAC_PI_4.cos();
        let sin_45 = std::f32::consts::FRAC_PI_4.sin();
        let (w, h) = calculate_rotated_bounds(100.0, 100.0, cos_45, sin_45);

        // Diagonal of 100x100 square is ~141.4
        let expected = 100.0 * 2.0_f32.sqrt();
        assert!((w - expected).abs() < 2.0);
        assert!((h - expected).abs() < 2.0);
    }

    // ========================================================================
    // New API tests
    // ========================================================================

    #[test]
    fn test_rotate_with_options_sampling() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let options = RotateOptions::with_method(RotateMethod::Sampling);
        let rotated = rotate(&pix, 0.5, &options).unwrap();
        assert!(rotated.width() > 0);
        assert!(rotated.height() > 0);
    }

    #[test]
    fn test_rotate_with_options_area_map() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let options = RotateOptions::with_method(RotateMethod::AreaMap);
        let rotated = rotate(&pix, 0.2, &options).unwrap();
        assert!(rotated.width() > 0);
        assert!(rotated.height() > 0);
    }

    #[test]
    fn test_rotate_with_options_shear() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let options = RotateOptions::with_method(RotateMethod::Shear);
        let rotated = rotate(&pix, 0.05, &options).unwrap();
        assert!(rotated.width() > 0);
        assert!(rotated.height() > 0);
    }

    #[test]
    fn test_rotate_with_fill_black() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let options = RotateOptions::with_fill(RotateFill::Black);
        let rotated = rotate(&pix, 0.3, &options).unwrap();
        assert!(rotated.width() > 0);
    }

    #[test]
    fn test_rotate_with_custom_center() {
        let pix = Pix::new(100, 100, PixelDepth::Bit8).unwrap();
        let rotated = rotate_about_center(&pix, 0.2, 25.0, 25.0, RotateFill::White).unwrap();
        // Should have same dimensions when not expanding
        assert_eq!(rotated.width(), 100);
        assert_eq!(rotated.height(), 100);
    }

    #[test]
    fn test_rotate_method_auto_selection() {
        // 1bpp should use shear for small angles
        let method_1bpp = select_rotate_method(RotateMethod::Auto, PixelDepth::Bit1, 0.02);
        assert_eq!(method_1bpp, RotateMethod::Shear);

        // 1bpp should use sampling for large angles
        let method_1bpp_large = select_rotate_method(RotateMethod::Auto, PixelDepth::Bit1, 0.1);
        assert_eq!(method_1bpp_large, RotateMethod::Sampling);

        // 8bpp should use area mapping
        let method_8bpp = select_rotate_method(RotateMethod::Auto, PixelDepth::Bit8, 0.2);
        assert_eq!(method_8bpp, RotateMethod::AreaMap);

        // 32bpp should use area mapping
        let method_32bpp = select_rotate_method(RotateMethod::Auto, PixelDepth::Bit32, 0.2);
        assert_eq!(method_32bpp, RotateMethod::AreaMap);
    }

    #[test]
    fn test_rotate_32bpp_area_map() {
        let pix = Pix::new(30, 30, PixelDepth::Bit32).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // Create a simple gradient
        for y in 0..30 {
            for x in 0..30 {
                let val = pixel::compose_rgb(x as u8 * 8, y as u8 * 8, 128);
                pix_mut.set_pixel_unchecked(x, y, val);
            }
        }

        let pix: Pix = pix_mut.into();
        let options = RotateOptions::with_method(RotateMethod::AreaMap);
        let rotated = rotate(&pix, 0.3, &options).unwrap();

        assert!(rotated.width() > 30);
        assert!(rotated.height() > 30);
    }

    #[test]
    fn test_rotate_very_small_angle() {
        // Angles below MIN_ANGLE_TO_ROTATE should just clone
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let options = RotateOptions::default();
        let rotated = rotate(&pix, 0.0001, &options).unwrap();

        // Should be same dimensions (cloned)
        assert_eq!(rotated.width(), 50);
        assert_eq!(rotated.height(), 50);
    }

    #[test]
    fn test_rotate_fill_to_value() {
        // Test RotateFill::to_value for different depths
        assert_eq!(RotateFill::White.to_value(PixelDepth::Bit1), 0);
        assert_eq!(RotateFill::Black.to_value(PixelDepth::Bit1), 1);
        assert_eq!(RotateFill::White.to_value(PixelDepth::Bit8), 255);
        assert_eq!(RotateFill::Black.to_value(PixelDepth::Bit8), 0);
        assert_eq!(RotateFill::Color(128).to_value(PixelDepth::Bit8), 128);
    }

    #[test]
    fn test_rotate_options_builder() {
        let options = RotateOptions::with_method(RotateMethod::Sampling)
            .center(25.0, 30.0)
            .expand(false);

        assert_eq!(options.method, RotateMethod::Sampling);
        assert_eq!(options.center_x, Some(25.0));
        assert_eq!(options.center_y, Some(30.0));
        assert!(!options.expand);
    }

    #[test]
    fn test_rotate_with_method_convenience() {
        let pix = Pix::new(40, 40, PixelDepth::Bit8).unwrap();
        let rotated = rotate_with_method(&pix, 0.25, RotateMethod::Bilinear).unwrap();
        assert!(rotated.width() > 0);
    }

    #[test]
    fn test_shear_rotation_2_shear() {
        // Small angle should use 2-shear
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let options = RotateOptions {
            method: RotateMethod::Shear,
            expand: false, // Don't expand output
            ..Default::default()
        };
        let rotated = rotate(&pix, 0.03, &options).unwrap(); // ~1.7 degrees
        assert_eq!(rotated.width(), 50); // No expansion
    }

    #[test]
    fn test_shear_rotation_3_shear() {
        // Larger angle should use 3-shear
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let options = RotateOptions {
            method: RotateMethod::Shear,
            expand: false,
            ..Default::default()
        };
        let rotated = rotate(&pix, 0.15, &options).unwrap(); // ~8.5 degrees
        assert_eq!(rotated.width(), 50);
    }

    // ========================================================================
    // Phase 6: Rotation拡張テスト
    // ========================================================================

    #[test]
    fn test_rotate_am_gray_corner_smoke() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let rotated = rotate_am_gray_corner(&pix, 0.2, RotateFill::White).unwrap();
        assert_eq!(rotated.width(), 50);
        assert_eq!(rotated.height(), 50);
        assert_eq!(rotated.depth(), PixelDepth::Bit8);
    }

    #[test]
    fn test_rotate_am_gray_corner_small_angle_clones() {
        let pix = Pix::new(30, 30, PixelDepth::Bit8).unwrap();
        let rotated = rotate_am_gray_corner(&pix, 0.0, RotateFill::White).unwrap();
        assert_eq!(rotated.width(), 30);
    }

    #[test]
    fn test_rotate_am_color_corner_smoke() {
        let pix = Pix::new(50, 50, PixelDepth::Bit32).unwrap();
        let rotated = rotate_am_color_corner(&pix, 0.2, RotateFill::White).unwrap();
        assert_eq!(rotated.width(), 50);
        assert_eq!(rotated.height(), 50);
        assert_eq!(rotated.depth(), PixelDepth::Bit32);
    }

    #[test]
    fn test_rotate_am_corner_dispatches_gray() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let rotated = rotate_am_corner(&pix, 0.2, RotateFill::White).unwrap();
        assert_eq!(rotated.depth(), PixelDepth::Bit8);
        assert_eq!(rotated.width(), 50);
    }

    #[test]
    fn test_rotate_am_corner_dispatches_color() {
        let pix = Pix::new(50, 50, PixelDepth::Bit32).unwrap();
        let rotated = rotate_am_corner(&pix, 0.2, RotateFill::White).unwrap();
        assert_eq!(rotated.depth(), PixelDepth::Bit32);
        assert_eq!(rotated.width(), 50);
    }

    #[test]
    fn test_rotate_shear_pub_smoke() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let rotated = rotate_shear(&pix, 25, 25, 0.1, ShearFill::White).unwrap();
        assert_eq!(rotated.width(), 50);
        assert_eq!(rotated.height(), 50);
    }

    #[test]
    fn test_rotate_shear_center_smoke() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let rotated = rotate_shear_center(&pix, 0.1, ShearFill::White).unwrap();
        assert_eq!(rotated.width(), 50);
        assert_eq!(rotated.height(), 50);
    }

    #[test]
    fn test_rotate_shear_ip_smoke() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();
        rotate_shear_ip(&mut pix_mut, 25, 25, 0.1, ShearFill::White).unwrap();
        assert_eq!(pix_mut.width(), 50);
        assert_eq!(pix_mut.height(), 50);
    }

    #[test]
    fn test_rotate_shear_center_ip_smoke() {
        let pix = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();
        rotate_shear_center_ip(&mut pix_mut, 0.1, ShearFill::White).unwrap();
        assert_eq!(pix_mut.width(), 50);
        assert_eq!(pix_mut.height(), 50);
    }

    #[test]
    fn test_rotate_with_alpha_uniform() {
        let pix = Pix::new(50, 50, PixelDepth::Bit32).unwrap();
        let rotated = rotate_with_alpha(&pix, 0.2, None, 0.5).unwrap();
        assert_eq!(rotated.depth(), PixelDepth::Bit32);
        assert_eq!(rotated.width(), 50);
        assert_eq!(rotated.height(), 50);
    }

    #[test]
    fn test_rotate_with_alpha_custom_alpha() {
        let pix = Pix::new(50, 50, PixelDepth::Bit32).unwrap();
        let alpha = Pix::new(50, 50, PixelDepth::Bit8).unwrap();
        let rotated = rotate_with_alpha(&pix, 0.2, Some(&alpha), 1.0).unwrap();
        assert_eq!(rotated.depth(), PixelDepth::Bit32);
    }
}