lib-epub 0.2.1

A Rust library for reading and manipulating EPUB files.
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
//! Types and data structures for EPUB processing
//!
//! This module defines all the core data structures used throughout the EPUB library.
//! These structures represent the various components of an EPUB publication according to
//! the EPUB specification, including metadata, manifest items, spine items, navigation points,
//! and encryption information.
//!
//! The types in this module are designed to be compatible with both EPUB 2 and EPUB 3
//! specifications, providing a unified interface for working with different versions
//! of EPUB publications.
//!
//! ## Builder Pattern
//!
//! Many of these types implement a builder pattern for easier construction when the
//! `builder` feature is enabled. See individual type documentation for details.

use std::path::PathBuf;

#[cfg(feature = "builder")]
use crate::{
    error::{EpubBuilderError, EpubError},
    utils::ELEMENT_IN_DC_NAMESPACE,
};

/// Represents the EPUB version
///
/// This enum is used to distinguish between different versions of the EPUB specification.
#[derive(Debug, PartialEq, Eq)]
pub enum EpubVersion {
    Version2_0,
    Version3_0,
}

/// Represents a metadata item in the EPUB publication
///
/// The `MetadataItem` structure represents a single piece of metadata from the EPUB publication.
/// Metadata items contain information about the publication such as title, author, identifier,
/// language, and other descriptive information.
///
/// In EPUB 3.0, metadata items can have refinements that provide additional details about
/// the main metadata item. For example, a title metadata item might have refinements that
/// specify it is the main title of the publication.
///
/// ## Builder Methods
///
/// When the `builder` feature is enabled, this struct provides convenient builder methods:
///
/// ```rust
/// # #[cfg(feature = "builder")] {
/// use lib_epub::types::MetadataItem;
///
/// let metadata = MetadataItem::new("title", "Sample Book")
///     .with_id("title-1")
///     .with_lang("en")
///     .build();
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct MetadataItem {
    /// Optional unique identifier for this metadata item
    ///
    /// Used to reference this metadata item from other elements or refinements.
    /// In EPUB 3.0, this ID is particularly important for linking with metadata refinements.
    pub id: Option<String>,

    /// The metadata property name
    ///
    /// This field specifies the type of metadata this item represents. Common properties
    /// include "title", "creator", "identifier", "language", "publisher", etc.
    /// These typically correspond to Dublin Core metadata terms.
    pub property: String,

    /// The metadata value
    pub value: String,

    /// Optional language code for this metadata item
    pub lang: Option<String>,

    /// Refinements of this metadata item
    ///
    /// In EPUB 3.x, metadata items can have associated refinements that provide additional
    /// information about the main metadata item. For example, a creator metadata item might
    /// have refinements specifying the creator's role (author, illustrator, etc.) or file-as.
    ///
    /// In EPUB 2.x, metadata items may contain custom attributes, which will also be parsed as refinement.
    pub refined: Vec<MetadataRefinement>,
}

#[cfg(feature = "builder")]
impl MetadataItem {
    /// Creates a new metadata item with the given property and value
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `property` - The metadata property name (e.g., "title", "creator")
    /// - `value` - The metadata value
    pub fn new(property: &str, value: &str) -> Self {
        Self {
            id: None,
            property: property.to_string(),
            value: value.to_string(),
            lang: None,
            refined: vec![],
        }
    }

    /// Sets the ID of the metadata item
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `id` - The ID to assign to this metadata item
    pub fn with_id(&mut self, id: &str) -> &mut Self {
        self.id = Some(id.to_string());
        self
    }

    /// Sets the language of the metadata item
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `lang` - The language code (e.g., "en", "fr", "zh-CN")
    pub fn with_lang(&mut self, lang: &str) -> &mut Self {
        self.lang = Some(lang.to_string());
        self
    }

    /// Adds a refinement to this metadata item
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `refine` - The refinement to add
    ///
    /// ## Notes
    /// - The metadata item must have an ID for refinements to be added.
    pub fn append_refinement(&mut self, refine: MetadataRefinement) -> &mut Self {
        if self.id.is_some() {
            self.refined.push(refine);
        } else {
            // TODO: alert warning
        }

        self
    }

    /// Builds the final metadata item
    ///
    /// Requires the `builder` feature.
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }

    /// Gets the XML attributes for this metadata item
    pub(crate) fn attributes(&self) -> Vec<(&str, &str)> {
        let mut attributes = Vec::new();

        if !ELEMENT_IN_DC_NAMESPACE.contains(&self.property.as_str()) {
            attributes.push(("property", self.property.as_str()));
        }

        if let Some(id) = &self.id {
            attributes.push(("id", id.as_str()));
        };

        if let Some(lang) = &self.lang {
            attributes.push(("lang", lang.as_str()));
        };

        attributes
    }
}

/// Represents a refinement of a metadata item in an EPUB 3.0 publication
///
/// The `MetadataRefinement` structure provides additional details about a parent metadata item.
/// Refinements are used in EPUB 3.0 to add granular metadata information that would be difficult
/// to express with the basic metadata structure alone.
///
/// For example, a creator metadata item might have refinements specifying the creator's role
/// or the scheme used for an identifier.
///
/// ## Builder Methods
///
/// When the `builder` feature is enabled, this struct provides convenient builder methods:
///
/// ```rust
/// # #[cfg(feature = "builder")] {
/// use lib_epub::types::MetadataRefinement;
///
/// let refinement = MetadataRefinement::new("creator-1", "role", "author")
///     .with_lang("en")
///     .with_scheme("marc:relators")
///     .build();
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct MetadataRefinement {
    pub refines: String,

    /// The refinement property name
    ///
    /// Specifies what aspect of the parent metadata item this refinement describes.
    /// Common refinement properties include "role", "file-as", "alternate-script", etc.
    pub property: String,

    /// The refinement value
    pub value: String,

    /// Optional language code for this refinement
    pub lang: Option<String>,

    /// Optional scheme identifier for this refinement
    ///
    /// Specifies the vocabulary or scheme used for the refinement value. For example,
    /// "marc:relators" for MARC relator codes, or "onix:codelist5" for ONIX roles.
    pub scheme: Option<String>,
}

#[cfg(feature = "builder")]
impl MetadataRefinement {
    /// Creates a new metadata refinement
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `refines` - The ID of the metadata item being refined
    /// - `property` - The refinement property name
    /// - `value` - The refinement value
    pub fn new(refines: &str, property: &str, value: &str) -> Self {
        Self {
            refines: refines.to_string(),
            property: property.to_string(),
            value: value.to_string(),
            lang: None,
            scheme: None,
        }
    }

    /// Sets the language of the refinement
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `lang` - The language code
    pub fn with_lang(&mut self, lang: &str) -> &mut Self {
        self.lang = Some(lang.to_string());
        self
    }

    /// Sets the scheme of the refinement
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `scheme` - The scheme identifier
    pub fn with_scheme(&mut self, scheme: &str) -> &mut Self {
        self.scheme = Some(scheme.to_string());
        self
    }

    /// Builds the final metadata refinement
    ///
    /// Requires the `builder` feature.
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }

    /// Gets the XML attributes for this refinement
    pub(crate) fn attributes(&self) -> Vec<(&str, &str)> {
        let mut attributes = Vec::new();

        attributes.push(("refines", self.refines.as_str()));
        attributes.push(("property", self.property.as_str()));

        if let Some(lang) = &self.lang {
            attributes.push(("lang", lang.as_str()));
        };

        if let Some(scheme) = &self.scheme {
            attributes.push(("scheme", scheme.as_str()));
        };

        attributes
    }
}

/// Represents a metadata link item in an EPUB publication
///
/// The `MetadataLinkItem` structure represents a link from the publication's metadata to
/// external resources. These links are typically used to associate the publication with
/// external records, alternate editions, or related resources.
///
/// Link metadata items are defined in the OPF file using `<link>` elements in the metadata
/// section and follow the EPUB 3.0 metadata link specification.
#[derive(Debug)]
pub struct MetadataLinkItem {
    /// The URI of the linked resource
    pub href: String,

    /// The relationship between this publication and the linked resource
    pub rel: String,

    /// Optional language of the linked resource
    pub hreflang: Option<String>,

    /// Optional unique identifier for this link item
    ///
    /// Provides an ID that can be used to reference this link from other elements.
    pub id: Option<String>,

    /// Optional MIME type of the linked resource
    pub mime: Option<String>,

    /// Optional properties of this link
    ///
    /// Contains space-separated property values that describe characteristics of the link
    /// or the linked resource. For example, "onix-3.0" to indicate an ONIX 3.0 record.
    pub properties: Option<String>,

    /// Optional reference to another metadata item
    ///
    /// In EPUB 3.0, links can refine other metadata items. This field contains the ID
    /// of the metadata item that this link refines, prefixed with "#".
    pub refines: Option<String>,
}

/// Represents a resource item declared in the EPUB manifest
///
/// The `ManifestItem` structure represents a single resource file declared in the EPUB
/// publication's manifest. Each manifest item describes a resource that is part of the
/// publication, including its location, media type, and optional properties or fallback
/// relationships.
///
/// The manifest serves as a comprehensive inventory of all resources in an EPUB publication.
/// Every resource that is part of the publication must be declared in the manifest, and
/// resources not listed in the manifest should not be accessed by reading systems.
///
/// Manifest items support the fallback mechanism, allowing alternative versions of a resource
/// to be specified. This is particularly important for foreign resources (resources with
/// non-core media types) that may not be supported by all reading systems.
///
/// ## Builder Methods
///
/// When the `builder` feature is enabled, this struct provides convenient builder methods:
///
/// ```
/// # #[cfg(feature = "builder")] {
/// use lib_epub::types::ManifestItem;
///
/// let manifest_item = ManifestItem::new("cover", "images/cover.jpg")
///     .unwrap()
///     .append_property("cover-image")
///     .with_fallback("cover-fallback")
///     .build();
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ManifestItem {
    /// The unique identifier for this resource item
    pub id: String,

    /// The path to the resource file within the EPUB container
    ///
    /// This field contains the normalized path to the resource file relative to the
    /// root of the EPUB container. The path is processed during parsing to handle
    /// various EPUB path conventions (absolute paths, relative paths, etc.).
    pub path: PathBuf,

    /// The media type of the resource
    pub mime: String,

    /// Optional properties associated with this resource
    ///
    /// This field contains a space-separated list of properties that apply to this
    /// resource. Properties provide additional information about how the resource
    /// should be treated.
    pub properties: Option<String>,

    /// Optional fallback resource identifier
    ///
    /// This field specifies the ID of another manifest item that serves as a fallback
    /// for this resource. Fallbacks are used when a reading system does not support
    /// the media type of the primary resource. The fallback chain allows publications
    /// to include foreign resources while maintaining compatibility with older or
    /// simpler reading systems.
    ///
    /// The value is the ID of another manifest item, which must exist in the manifest.
    /// If `None`, this resource has no fallback.
    pub fallback: Option<String>,
}

#[cfg(feature = "builder")]
impl ManifestItem {
    /// Creates a new manifest item
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `id` - The unique identifier for this resource
    /// - `path` - The path to the resource file
    ///
    /// ## Errors
    /// Returns an error if the path starts with "../" which is not allowed.
    pub fn new(id: &str, path: &str) -> Result<Self, EpubError> {
        if path.starts_with("../") {
            return Err(
                EpubBuilderError::IllegalManifestPath { manifest_id: id.to_string() }.into(),
            );
        }

        Ok(Self {
            id: id.to_string(),
            path: PathBuf::from(path),
            mime: String::new(),
            properties: None,
            fallback: None,
        })
    }

    /// Sets the MIME type of the manifest item
    pub(crate) fn set_mime(self, mime: &str) -> Self {
        Self {
            id: self.id,
            path: self.path,
            mime: mime.to_string(),
            properties: self.properties,
            fallback: self.fallback,
        }
    }

    /// Appends a property to the manifest item
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `property` - The property to add
    pub fn append_property(&mut self, property: &str) -> &mut Self {
        let new_properties = if let Some(properties) = &self.properties {
            format!("{} {}", properties, property)
        } else {
            property.to_string()
        };

        self.properties = Some(new_properties);
        self
    }

    /// Sets the fallback for this manifest item
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `fallback` - The ID of the fallback manifest item
    pub fn with_fallback(&mut self, fallback: &str) -> &mut Self {
        self.fallback = Some(fallback.to_string());
        self
    }

    /// Builds the final manifest item
    ///
    /// Requires the `builder` feature.
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }

    /// Gets the XML attributes for this manifest item
    pub fn attributes(&self) -> Vec<(&str, &str)> {
        let mut attributes = Vec::new();

        attributes.push(("id", self.id.as_str()));
        attributes.push(("href", self.path.to_str().unwrap()));
        attributes.push(("media-type", self.mime.as_str()));

        if let Some(properties) = &self.properties {
            attributes.push(("properties", properties.as_str()));
        }

        if let Some(fallback) = &self.fallback {
            attributes.push(("fallback", fallback.as_str()));
        }

        attributes
    }
}

/// Represents an item in the EPUB spine, defining the reading order of the publication
///
/// The `SpineItem` structure represents a single item in the EPUB spine, which defines
/// the linear reading order of the publication's content documents. Each spine item
/// references a resource declared in the manifest and indicates whether it should be
/// included in the linear reading sequence.
///
/// The spine is a crucial component of an EPUB publication as it determines the recommended
/// reading order of content documents. Items can be marked as linear (part of the main reading
/// flow) or non-linear (supplementary content that may be accessed out of sequence).
///
/// ## Builder Methods
///
/// When the `builder` feature is enabled, this struct provides convenient builder methods:
///
/// ```
/// # #[cfg(feature = "builder")] {
/// use lib_epub::types::SpineItem;
///
/// let spine_item = SpineItem::new("content-1")
///     .with_id("spine-1")
///     .append_property("page-spread-right")
///     .set_linear(false)
///     .build();
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct SpineItem {
    /// The ID reference to a manifest item
    ///
    /// This field contains the ID of the manifest item that this spine item references.
    /// It establishes the connection between the reading order (spine) and the actual
    /// content resources (manifest). The referenced ID must exist in the manifest.
    pub idref: String,

    /// Optional identifier for this spine item
    pub id: Option<String>,

    /// Optional properties associated with this spine item
    ///
    /// This field contains a space-separated list of properties that apply to this
    /// spine item. These properties can indicate special handling requirements,
    /// layout preferences, or other characteristics.
    pub properties: Option<String>,

    /// Indicates whether this item is part of the linear reading order
    ///
    /// When `true`, this spine item is part of the main linear reading sequence.
    /// When `false`, this item represents supplementary content that may be accessed
    /// out of the normal reading order (e.g., through hyperlinks).
    ///
    /// Non-linear items are typically used for content like footnotes, endnotes,
    /// appendices, or other supplementary materials that readers might access
    /// on-demand rather than sequentially.
    pub linear: bool,
}

#[cfg(feature = "builder")]
impl SpineItem {
    /// Creates a new spine item referencing a manifest item
    ///
    /// Requires the `builder` feature.
    ///
    /// By default, spine items are linear.
    ///
    /// ## Parameters
    /// - `idref` - The ID of the manifest item this spine item references
    pub fn new(idref: &str) -> Self {
        Self {
            idref: idref.to_string(),
            id: None,
            properties: None,
            linear: true,
        }
    }

    /// Sets the ID of the spine item
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `id` - The ID to assign to this spine item
    pub fn with_id(&mut self, id: &str) -> &mut Self {
        self.id = Some(id.to_string());
        self
    }

    /// Appends a property to the spine item
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `property` - The property to add
    pub fn append_property(&mut self, property: &str) -> &mut Self {
        let new_properties = if let Some(properties) = &self.properties {
            format!("{} {}", properties, property)
        } else {
            property.to_string()
        };

        self.properties = Some(new_properties);
        self
    }

    /// Sets whether this spine item is part of the linear reading order
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `linear` - `true` if the item is part of the linear reading order, `false` otherwise
    pub fn set_linear(&mut self, linear: bool) -> &mut Self {
        self.linear = linear;
        self
    }

    /// Builds the final spine item
    ///
    /// Requires the `builder` feature.
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }

    /// Gets the XML attributes for this spine item
    pub(crate) fn attributes(&self) -> Vec<(&str, &str)> {
        let mut attributes = Vec::new();

        attributes.push(("idref", self.idref.as_str()));
        attributes.push(("linear", if self.linear { "yes" } else { "no" }));

        if let Some(id) = &self.id {
            attributes.push(("id", id.as_str()));
        }

        if let Some(properties) = &self.properties {
            attributes.push(("properties", properties.as_str()));
        }

        attributes
    }
}

/// Represents encryption information for EPUB resources
///
/// This structure holds information about encrypted resources in an EPUB publication,
/// as defined in the META-INF/encryption.xml file according to the EPUB specification.
/// It describes which resources are encrypted and what encryption method was used.
#[derive(Debug, Clone)]
pub struct EncryptionData {
    /// The encryption algorithm URI
    ///
    /// This field specifies the encryption method used for the resource.
    /// Supported encryption methods:
    /// - IDPF font obfuscation: <http://www.idpf.org/2008/embedding>
    /// - Adobe font obfuscation: <http://ns.adobe.com/pdf/enc#RC>
    pub method: String,

    /// The URI of the encrypted resource
    ///
    /// This field contains the path/URI to the encrypted resource within the EPUB container.
    /// The path is relative to the root of the EPUB container.
    pub data: String,
}

/// Represents a navigation point in an EPUB document's table of contents
///
/// The `NavPoint` structure represents a single entry in the hierarchical table of contents
/// of an EPUB publication. Each navigation point corresponds to a section or chapter in
/// the publication and may contain nested child navigation points to represent sub-sections.
///
/// ## Builder Methods
///
/// When the `builder` feature is enabled, this struct provides convenient builder methods:
///
/// ```
/// # #[cfg(feature = "builder")] {
/// use lib_epub::types::NavPoint;
///
/// let nav_point = NavPoint::new("Chapter 1")
///     .with_content("chapter1.xhtml")
///     .append_child(
///         NavPoint::new("Section 1.1")
///             .with_content("section1_1.xhtml")
///             .build()
///     )
///     .build();
/// # }
/// ```
#[derive(Debug, Eq, Clone)]
pub struct NavPoint {
    /// The display label/title of this navigation point
    ///
    /// This is the text that should be displayed to users in the table of contents.
    pub label: String,

    /// The content document path this navigation point references
    ///
    /// Can be `None` for navigation points that no relevant information was
    /// provided in the original data.
    pub content: Option<PathBuf>,

    /// Child navigation points (sub-sections)
    pub children: Vec<NavPoint>,

    /// The reading order position of this navigation point
    ///
    /// It can be `None` for navigation points that no relevant information was
    /// provided in the original data.
    pub play_order: Option<usize>,
}

#[cfg(feature = "builder")]
impl NavPoint {
    /// Creates a new navigation point with the given label
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `label` - The display label for this navigation point
    pub fn new(label: &str) -> Self {
        Self {
            label: label.to_string(),
            content: None,
            children: vec![],
            play_order: None,
        }
    }

    /// Sets the content path for this navigation point
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `content` - The path to the content document
    pub fn with_content(&mut self, content: &str) -> &mut Self {
        self.content = Some(PathBuf::from(content));
        self
    }

    /// Appends a child navigation point
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `child` - The child navigation point to add
    pub fn append_child(&mut self, child: NavPoint) -> &mut Self {
        self.children.push(child);
        self
    }

    /// Sets all child navigation points
    ///
    /// Requires the `builder` feature.
    ///
    /// ## Parameters
    /// - `children` - Vector of child navigation points
    pub fn set_children(&mut self, children: Vec<NavPoint>) -> &mut Self {
        self.children = children;
        self
    }

    /// Builds the final navigation point
    ///
    /// Requires the `builder` feature.
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }
}

impl Ord for NavPoint {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.play_order.cmp(&other.play_order)
    }
}

impl PartialOrd for NavPoint {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for NavPoint {
    fn eq(&self, other: &Self) -> bool {
        self.play_order == other.play_order
    }
}

/// Represents a footnote in an EPUB content document
///
/// This structure represents a footnote in an EPUB content document.
/// It contains the location within the content document and the content of the footnote.
#[cfg(feature = "content-builder")]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Footnote {
    /// The position/location of the footnote reference in the content
    pub locate: usize,

    /// The text content of the footnote
    pub content: String,
}

#[cfg(feature = "content-builder")]
impl Ord for Footnote {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.locate.cmp(&other.locate)
    }
}

#[cfg(feature = "content-builder")]
impl PartialOrd for Footnote {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Represents the type of a block element in the content document
#[cfg(feature = "content-builder")]
#[derive(Debug, Copy, Clone)]
pub enum BlockType {
    /// A text paragraph block
    ///
    /// Standard paragraph content with text styling applied.
    Text,

    /// A quotation block
    ///
    /// Represents quoted or indented text content, typically rendered
    /// with visual distinction from regular paragraphs.
    Quote,

    /// A title or heading block
    ///
    /// Represents chapter or section titles with appropriate heading styling.
    Title,

    /// An image block
    ///
    /// Contains embedded image content with optional caption support.
    Image,

    /// An audio block
    ///
    /// Contains audio content for playback within the document.
    Audio,

    /// A video block
    ///
    /// Contains video content for playback within the document.
    Video,

    /// A MathML block
    ///
    /// Contains mathematical notation using MathML markup for
    /// proper mathematical typesetting.
    MathML,
}

#[cfg(feature = "content-builder")]
impl std::fmt::Display for BlockType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BlockType::Text => write!(f, "Text"),
            BlockType::Quote => write!(f, "Quote"),
            BlockType::Title => write!(f, "Title"),
            BlockType::Image => write!(f, "Image"),
            BlockType::Audio => write!(f, "Audio"),
            BlockType::Video => write!(f, "Video"),
            BlockType::MathML => write!(f, "MathML"),
        }
    }
}

/// Configuration options for document styling
///
/// This struct aggregates all style-related configuration for an EPUB document,
/// including text appearance, color scheme, and page layout settings.
#[cfg(feature = "content-builder")]
#[derive(Debug, Default, Clone)]
pub struct StyleOptions {
    /// Text styling configuration
    pub text: TextStyle,

    /// Color scheme configuration
    ///
    /// Defines the background, text, and link colors for the document.
    pub color_scheme: ColorScheme,

    /// Page layout configuration
    ///
    /// Controls margins, text alignment, and paragraph spacing.
    pub layout: PageLayout,
}

#[cfg(feature = "content-builder")]
#[cfg(feature = "builder")]
impl StyleOptions {
    /// Creates a new style options with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the text style configuration
    pub fn with_text(&mut self, text: TextStyle) -> &mut Self {
        self.text = text;
        self
    }

    /// Sets the color scheme configuration
    pub fn with_color_scheme(&mut self, color_scheme: ColorScheme) -> &mut Self {
        self.color_scheme = color_scheme;
        self
    }

    /// Sets the page layout configuration
    pub fn with_layout(&mut self, layout: PageLayout) -> &mut Self {
        self.layout = layout;
        self
    }

    /// Builds the final style options
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }
}

/// Text styling configuration
///
/// Defines the visual appearance of text content in the document,
/// including font properties, sizing, and spacing.
#[cfg(feature = "content-builder")]
#[derive(Debug, Clone)]
pub struct TextStyle {
    /// The base font size (default: 1.0, unit: rem)
    ///
    /// Relative to the root element, providing consistent sizing
    /// across different viewing contexts.
    pub font_size: f32,

    /// The line height (default: 1.6, unit: em)
    ///
    /// Controls the vertical spacing between lines of text.
    /// Values greater than 1.0 increase spacing, while values
    /// less than 1.0 compress the text.
    pub line_height: f32,

    /// The font family stack (default: "-apple-system, Roboto, sans-serif")
    ///
    /// A comma-separated list of font families to use, with
    /// fallback fonts specified for compatibility.
    pub font_family: String,

    /// The font weight (default: "normal")
    ///
    /// Controls the thickness of the font strokes. Common values
    /// include "normal" and "bold".
    pub font_weight: String,

    /// The font style (default: "normal")
    ///
    /// Controls whether the font is normal, italic, or oblique.
    /// Common values include "normal" and "italic".
    pub font_style: String,

    /// The letter spacing (default: "normal")
    ///
    /// Controls the space between characters. Common values
    /// include "normal" or specific lengths like "0.05em".
    pub letter_spacing: String,

    /// The text indent for paragraphs (default: 2.0, unit: em)
    ///
    /// Controls the indentation of the first line of paragraphs.
    /// A value of 2.0 means the first line is indented by 2 ems.
    pub text_indent: f32,
}

#[cfg(feature = "content-builder")]
impl Default for TextStyle {
    fn default() -> Self {
        Self {
            font_size: 1.0,
            line_height: 1.6,
            font_family: "-apple-system, Roboto, sans-serif".to_string(),
            font_weight: "normal".to_string(),
            font_style: "normal".to_string(),
            letter_spacing: "normal".to_string(),
            text_indent: 2.0,
        }
    }
}

#[cfg(feature = "content-builder")]
impl TextStyle {
    /// Creates a new text style with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the font size
    pub fn with_font_size(&mut self, font_size: f32) -> &mut Self {
        self.font_size = font_size;
        self
    }

    /// Sets the line height
    pub fn with_line_height(&mut self, line_height: f32) -> &mut Self {
        self.line_height = line_height;
        self
    }

    /// Sets the font family
    pub fn with_font_family(&mut self, font_family: &str) -> &mut Self {
        self.font_family = font_family.to_string();
        self
    }

    /// Sets the font weight
    pub fn with_font_weight(&mut self, font_weight: &str) -> &mut Self {
        self.font_weight = font_weight.to_string();
        self
    }

    /// Sets the font style
    pub fn with_font_style(&mut self, font_style: &str) -> &mut Self {
        self.font_style = font_style.to_string();
        self
    }

    /// Sets the letter spacing
    pub fn with_letter_spacing(&mut self, letter_spacing: &str) -> &mut Self {
        self.letter_spacing = letter_spacing.to_string();
        self
    }

    /// Sets the text indent
    pub fn with_text_indent(&mut self, text_indent: f32) -> &mut Self {
        self.text_indent = text_indent;
        self
    }

    /// Builds the final text style
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }
}

/// Color scheme configuration
///
/// Defines the color palette for the document, including background,
/// text, and link colors.
#[cfg(feature = "content-builder")]
#[derive(Debug, Clone)]
pub struct ColorScheme {
    /// The background color (default: "#FFFFFF")
    ///
    /// The fill color for the document body. Specified as a hex color
    /// string (e.g., "#FFFFFF" for white).
    pub background: String,

    /// The text color (default: "#000000")
    ///
    /// The primary color for text content. Specified as a hex color
    /// string (e.g., "#000000" for black).
    pub text: String,

    /// The link color (default: "#6f6f6f")
    ///
    /// The color for hyperlinks in the document. Specified as a hex
    /// color string (e.g., "#6f6f6f" for gray).
    pub link: String,
}

#[cfg(feature = "content-builder")]
impl Default for ColorScheme {
    fn default() -> Self {
        Self {
            background: "#FFFFFF".to_string(),
            text: "#000000".to_string(),
            link: "#6f6f6f".to_string(),
        }
    }
}

#[cfg(feature = "content-builder")]
impl ColorScheme {
    /// Creates a new color scheme with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the background color
    pub fn with_background(&mut self, background: &str) -> &mut Self {
        self.background = background.to_string();
        self
    }

    /// Sets the text color
    pub fn with_text(&mut self, text: &str) -> &mut Self {
        self.text = text.to_string();
        self
    }

    /// Sets the link color
    pub fn with_link(&mut self, link: &str) -> &mut Self {
        self.link = link.to_string();
        self
    }

    /// Builds the final color scheme
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }
}

/// Page layout configuration
///
/// Defines the layout properties for pages in the document, including
/// margins, text alignment, and paragraph spacing.
#[cfg(feature = "content-builder")]
#[derive(Debug, Clone)]
pub struct PageLayout {
    /// The page margin (default: 20, unit: pixels)
    ///
    /// Controls the space around the content area on each page.
    pub margin: usize,

    /// The text alignment mode (default: TextAlign::Left)
    ///
    /// Controls how text is aligned within the content area.
    pub text_align: TextAlign,

    /// The spacing between paragraphs (default: 16, unit: pixels)
    ///
    /// Controls the vertical space between block-level elements.
    pub paragraph_spacing: usize,
}

#[cfg(feature = "content-builder")]
impl Default for PageLayout {
    fn default() -> Self {
        Self {
            margin: 20,
            text_align: Default::default(),
            paragraph_spacing: 16,
        }
    }
}

#[cfg(feature = "content-builder")]
impl PageLayout {
    /// Creates a new page layout with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the page margin
    pub fn with_margin(&mut self, margin: usize) -> &mut Self {
        self.margin = margin;
        self
    }

    /// Sets the text alignment
    pub fn with_text_align(&mut self, text_align: TextAlign) -> &mut Self {
        self.text_align = text_align;
        self
    }

    /// Sets the paragraph spacing
    pub fn with_paragraph_spacing(&mut self, paragraph_spacing: usize) -> &mut Self {
        self.paragraph_spacing = paragraph_spacing;
        self
    }

    /// Builds the final page layout
    pub fn build(&self) -> Self {
        Self { ..self.clone() }
    }
}

/// Text alignment options
///
/// Defines the available text alignment modes for content in the document.
#[cfg(feature = "content-builder")]
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub enum TextAlign {
    /// Left-aligned text
    ///
    /// Text is aligned to the left margin, with the right edge ragged.
    #[default]
    Left,

    /// Right-aligned text
    ///
    /// Text is aligned to the right margin, with the left edge ragged.
    Right,

    /// Justified text
    ///
    /// Text is aligned to both margins by adjusting the spacing between
    /// words. The left and right edges are both straight.
    Justify,

    /// Centered text
    ///
    /// Text is centered within the content area, with both edges ragged.
    Center,
}

#[cfg(feature = "content-builder")]
impl std::fmt::Display for TextAlign {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TextAlign::Left => write!(f, "left"),
            TextAlign::Right => write!(f, "right"),
            TextAlign::Justify => write!(f, "justify"),
            TextAlign::Center => write!(f, "center"),
        }
    }
}

#[cfg(test)]
mod tests {
    mod navpoint_tests {
        use std::path::PathBuf;

        use crate::types::NavPoint;

        /// Testing the equality comparison of NavPoint
        #[test]
        fn test_navpoint_partial_eq() {
            let nav1 = NavPoint {
                label: "Chapter 1".to_string(),
                content: Some(PathBuf::from("chapter1.html")),
                children: vec![],
                play_order: Some(1),
            };

            let nav2 = NavPoint {
                label: "Chapter 1".to_string(),
                content: Some(PathBuf::from("chapter2.html")),
                children: vec![],
                play_order: Some(1),
            };

            let nav3 = NavPoint {
                label: "Chapter 2".to_string(),
                content: Some(PathBuf::from("chapter1.html")),
                children: vec![],
                play_order: Some(2),
            };

            assert_eq!(nav1, nav2); // Same play_order, different contents, should be equal
            assert_ne!(nav1, nav3); // Different play_order, Same contents, should be unequal
        }

        /// Test NavPoint sorting comparison
        #[test]
        fn test_navpoint_ord() {
            let nav1 = NavPoint {
                label: "Chapter 1".to_string(),
                content: Some(PathBuf::from("chapter1.html")),
                children: vec![],
                play_order: Some(1),
            };

            let nav2 = NavPoint {
                label: "Chapter 2".to_string(),
                content: Some(PathBuf::from("chapter2.html")),
                children: vec![],
                play_order: Some(2),
            };

            let nav3 = NavPoint {
                label: "Chapter 3".to_string(),
                content: Some(PathBuf::from("chapter3.html")),
                children: vec![],
                play_order: Some(3),
            };

            // Test function cmp
            assert!(nav1 < nav2);
            assert!(nav2 > nav1);
            assert!(nav1 == nav1);

            // Test function partial_cmp
            assert_eq!(nav1.partial_cmp(&nav2), Some(std::cmp::Ordering::Less));
            assert_eq!(nav2.partial_cmp(&nav1), Some(std::cmp::Ordering::Greater));
            assert_eq!(nav1.partial_cmp(&nav1), Some(std::cmp::Ordering::Equal));

            // Test function sort
            let mut nav_points = vec![nav2.clone(), nav3.clone(), nav1.clone()];
            nav_points.sort();
            assert_eq!(nav_points, vec![nav1, nav2, nav3]);
        }

        /// Test the case of None play_order
        #[test]
        fn test_navpoint_ord_with_none_play_order() {
            let nav_with_order = NavPoint {
                label: "Chapter 1".to_string(),
                content: Some(PathBuf::from("chapter1.html")),
                children: vec![],
                play_order: Some(1),
            };

            let nav_without_order = NavPoint {
                label: "Preface".to_string(),
                content: Some(PathBuf::from("preface.html")),
                children: vec![],
                play_order: None,
            };

            assert!(nav_without_order < nav_with_order);
            assert!(nav_with_order > nav_without_order);

            let nav_without_order2 = NavPoint {
                label: "Introduction".to_string(),
                content: Some(PathBuf::from("intro.html")),
                children: vec![],
                play_order: None,
            };

            assert!(nav_without_order == nav_without_order2);
        }

        /// Test NavPoint containing child nodes
        #[test]
        fn test_navpoint_with_children() {
            let child1 = NavPoint {
                label: "Section 1.1".to_string(),
                content: Some(PathBuf::from("section1_1.html")),
                children: vec![],
                play_order: Some(1),
            };

            let child2 = NavPoint {
                label: "Section 1.2".to_string(),
                content: Some(PathBuf::from("section1_2.html")),
                children: vec![],
                play_order: Some(2),
            };

            let parent1 = NavPoint {
                label: "Chapter 1".to_string(),
                content: Some(PathBuf::from("chapter1.html")),
                children: vec![child1.clone(), child2.clone()],
                play_order: Some(1),
            };

            let parent2 = NavPoint {
                label: "Chapter 1".to_string(),
                content: Some(PathBuf::from("chapter1.html")),
                children: vec![child1.clone(), child2.clone()],
                play_order: Some(1),
            };

            assert!(parent1 == parent2);

            let parent3 = NavPoint {
                label: "Chapter 2".to_string(),
                content: Some(PathBuf::from("chapter2.html")),
                children: vec![child1.clone(), child2.clone()],
                play_order: Some(2),
            };

            assert!(parent1 != parent3);
            assert!(parent1 < parent3);
        }

        /// Test the case where content is None
        #[test]
        fn test_navpoint_with_none_content() {
            let nav1 = NavPoint {
                label: "Chapter 1".to_string(),
                content: None,
                children: vec![],
                play_order: Some(1),
            };

            let nav2 = NavPoint {
                label: "Chapter 1".to_string(),
                content: None,
                children: vec![],
                play_order: Some(1),
            };

            assert!(nav1 == nav2);
        }
    }

    #[cfg(feature = "builder")]
    mod builder_tests {
        mod metadata_item {
            use crate::types::{MetadataItem, MetadataRefinement};

            #[test]
            fn test_metadata_item_new() {
                let metadata_item = MetadataItem::new("title", "EPUB Test Book");

                assert_eq!(metadata_item.property, "title");
                assert_eq!(metadata_item.value, "EPUB Test Book");
                assert_eq!(metadata_item.id, None);
                assert_eq!(metadata_item.lang, None);
                assert_eq!(metadata_item.refined.len(), 0);
            }

            #[test]
            fn test_metadata_item_with_id() {
                let mut metadata_item = MetadataItem::new("creator", "John Doe");
                metadata_item.with_id("creator-1");

                assert_eq!(metadata_item.property, "creator");
                assert_eq!(metadata_item.value, "John Doe");
                assert_eq!(metadata_item.id, Some("creator-1".to_string()));
                assert_eq!(metadata_item.lang, None);
                assert_eq!(metadata_item.refined.len(), 0);
            }

            #[test]
            fn test_metadata_item_with_lang() {
                let mut metadata_item = MetadataItem::new("title", "测试书籍");
                metadata_item.with_lang("zh-CN");

                assert_eq!(metadata_item.property, "title");
                assert_eq!(metadata_item.value, "测试书籍");
                assert_eq!(metadata_item.id, None);
                assert_eq!(metadata_item.lang, Some("zh-CN".to_string()));
                assert_eq!(metadata_item.refined.len(), 0);
            }

            #[test]
            fn test_metadata_item_append_refinement() {
                let mut metadata_item = MetadataItem::new("creator", "John Doe");
                metadata_item.with_id("creator-1"); // ID is required for refinements

                let refinement = MetadataRefinement::new("creator-1", "role", "author");
                metadata_item.append_refinement(refinement);

                assert_eq!(metadata_item.refined.len(), 1);
                assert_eq!(metadata_item.refined[0].refines, "creator-1");
                assert_eq!(metadata_item.refined[0].property, "role");
                assert_eq!(metadata_item.refined[0].value, "author");
            }

            #[test]
            fn test_metadata_item_append_refinement_without_id() {
                let mut metadata_item = MetadataItem::new("title", "Test Book");
                // No ID set

                let refinement = MetadataRefinement::new("title", "title-type", "main");
                metadata_item.append_refinement(refinement);

                // Refinement should not be added because metadata item has no ID
                assert_eq!(metadata_item.refined.len(), 0);
            }

            #[test]
            fn test_metadata_item_build() {
                let mut metadata_item = MetadataItem::new("identifier", "urn:isbn:1234567890");
                metadata_item.with_id("pub-id").with_lang("en");

                let built = metadata_item.build();

                assert_eq!(built.property, "identifier");
                assert_eq!(built.value, "urn:isbn:1234567890");
                assert_eq!(built.id, Some("pub-id".to_string()));
                assert_eq!(built.lang, Some("en".to_string()));
                assert_eq!(built.refined.len(), 0);
            }

            #[test]
            fn test_metadata_item_builder_chaining() {
                let mut metadata_item = MetadataItem::new("title", "EPUB 3.3 Guide");
                metadata_item.with_id("title").with_lang("en");

                let refinement = MetadataRefinement::new("title", "title-type", "main");
                metadata_item.append_refinement(refinement);

                let built = metadata_item.build();

                assert_eq!(built.property, "title");
                assert_eq!(built.value, "EPUB 3.3 Guide");
                assert_eq!(built.id, Some("title".to_string()));
                assert_eq!(built.lang, Some("en".to_string()));
                assert_eq!(built.refined.len(), 1);
            }

            #[test]
            fn test_metadata_item_attributes_dc_namespace() {
                let mut metadata_item = MetadataItem::new("title", "Test Book");
                metadata_item.with_id("title-id");

                let attributes = metadata_item.attributes();

                // For DC namespace properties, no "property" attribute should be added
                assert!(!attributes.iter().any(|(k, _)| k == &"property"));
                assert!(
                    attributes
                        .iter()
                        .any(|(k, v)| k == &"id" && v == &"title-id")
                );
            }

            #[test]
            fn test_metadata_item_attributes_non_dc_namespace() {
                let mut metadata_item = MetadataItem::new("meta", "value");
                metadata_item.with_id("meta-id");

                let attributes = metadata_item.attributes();

                // For non-DC namespace properties, "property" attribute should be added
                assert!(attributes.iter().any(|(k, _)| k == &"property"));
                assert!(
                    attributes
                        .iter()
                        .any(|(k, v)| k == &"id" && v == &"meta-id")
                );
            }

            #[test]
            fn test_metadata_item_attributes_with_lang() {
                let mut metadata_item = MetadataItem::new("title", "Test Book");
                metadata_item.with_id("title-id").with_lang("en");

                let attributes = metadata_item.attributes();

                assert!(
                    attributes
                        .iter()
                        .any(|(k, v)| k == &"id" && v == &"title-id")
                );
                assert!(attributes.iter().any(|(k, v)| k == &"lang" && v == &"en"));
            }
        }

        mod metadata_refinement {
            use crate::types::MetadataRefinement;

            #[test]
            fn test_metadata_refinement_new() {
                let refinement = MetadataRefinement::new("title", "title-type", "main");

                assert_eq!(refinement.refines, "title");
                assert_eq!(refinement.property, "title-type");
                assert_eq!(refinement.value, "main");
                assert_eq!(refinement.lang, None);
                assert_eq!(refinement.scheme, None);
            }

            #[test]
            fn test_metadata_refinement_with_lang() {
                let mut refinement = MetadataRefinement::new("creator", "role", "author");
                refinement.with_lang("en");

                assert_eq!(refinement.refines, "creator");
                assert_eq!(refinement.property, "role");
                assert_eq!(refinement.value, "author");
                assert_eq!(refinement.lang, Some("en".to_string()));
                assert_eq!(refinement.scheme, None);
            }

            #[test]
            fn test_metadata_refinement_with_scheme() {
                let mut refinement = MetadataRefinement::new("creator", "role", "author");
                refinement.with_scheme("marc:relators");

                assert_eq!(refinement.refines, "creator");
                assert_eq!(refinement.property, "role");
                assert_eq!(refinement.value, "author");
                assert_eq!(refinement.lang, None);
                assert_eq!(refinement.scheme, Some("marc:relators".to_string()));
            }

            #[test]
            fn test_metadata_refinement_build() {
                let mut refinement = MetadataRefinement::new("title", "alternate-script", "テスト");
                refinement.with_lang("ja").with_scheme("iso-15924");

                let built = refinement.build();

                assert_eq!(built.refines, "title");
                assert_eq!(built.property, "alternate-script");
                assert_eq!(built.value, "テスト");
                assert_eq!(built.lang, Some("ja".to_string()));
                assert_eq!(built.scheme, Some("iso-15924".to_string()));
            }

            #[test]
            fn test_metadata_refinement_builder_chaining() {
                let mut refinement = MetadataRefinement::new("creator", "file-as", "Doe, John");
                refinement.with_lang("en").with_scheme("dcterms");

                let built = refinement.build();

                assert_eq!(built.refines, "creator");
                assert_eq!(built.property, "file-as");
                assert_eq!(built.value, "Doe, John");
                assert_eq!(built.lang, Some("en".to_string()));
                assert_eq!(built.scheme, Some("dcterms".to_string()));
            }

            #[test]
            fn test_metadata_refinement_attributes() {
                let mut refinement = MetadataRefinement::new("title", "title-type", "main");
                refinement.with_lang("en").with_scheme("onix:codelist5");

                let attributes = refinement.attributes();

                assert!(
                    attributes
                        .iter()
                        .any(|(k, v)| k == &"refines" && v == &"title")
                );
                assert!(
                    attributes
                        .iter()
                        .any(|(k, v)| k == &"property" && v == &"title-type")
                );
                assert!(attributes.iter().any(|(k, v)| k == &"lang" && v == &"en"));
                assert!(
                    attributes
                        .iter()
                        .any(|(k, v)| k == &"scheme" && v == &"onix:codelist5")
                );
            }

            #[test]
            fn test_metadata_refinement_attributes_optional_fields() {
                let refinement = MetadataRefinement::new("creator", "role", "author");
                let attributes = refinement.attributes();

                assert!(
                    attributes
                        .iter()
                        .any(|(k, v)| k == &"refines" && v == &"creator")
                );
                assert!(
                    attributes
                        .iter()
                        .any(|(k, v)| k == &"property" && v == &"role")
                );

                // Should not contain optional attributes when they are None
                assert!(!attributes.iter().any(|(k, _)| k == &"lang"));
                assert!(!attributes.iter().any(|(k, _)| k == &"scheme"));
            }
        }

        mod manifest_item {
            use std::path::PathBuf;

            use crate::types::ManifestItem;

            #[test]
            fn test_manifest_item_new() {
                let manifest_item = ManifestItem::new("cover", "images/cover.jpg");
                assert!(manifest_item.is_ok());

                let manifest_item = manifest_item.unwrap();
                assert_eq!(manifest_item.id, "cover");
                assert_eq!(manifest_item.path, PathBuf::from("images/cover.jpg"));
                assert_eq!(manifest_item.mime, "");
                assert_eq!(manifest_item.properties, None);
                assert_eq!(manifest_item.fallback, None);
            }

            #[test]
            fn test_manifest_item_append_property() {
                let manifest_item = ManifestItem::new("nav", "nav.xhtml");
                assert!(manifest_item.is_ok());

                let mut manifest_item = manifest_item.unwrap();
                manifest_item.append_property("nav");

                assert_eq!(manifest_item.id, "nav");
                assert_eq!(manifest_item.path, PathBuf::from("nav.xhtml"));
                assert_eq!(manifest_item.mime, "");
                assert_eq!(manifest_item.properties, Some("nav".to_string()));
                assert_eq!(manifest_item.fallback, None);
            }

            #[test]
            fn test_manifest_item_append_multiple_properties() {
                let manifest_item = ManifestItem::new("content", "content.xhtml");
                assert!(manifest_item.is_ok());

                let mut manifest_item = manifest_item.unwrap();
                manifest_item
                    .append_property("nav")
                    .append_property("scripted")
                    .append_property("svg");

                assert_eq!(
                    manifest_item.properties,
                    Some("nav scripted svg".to_string())
                );
            }

            #[test]
            fn test_manifest_item_with_fallback() {
                let manifest_item = ManifestItem::new("image", "image.tiff");
                assert!(manifest_item.is_ok());

                let mut manifest_item = manifest_item.unwrap();
                manifest_item.with_fallback("image-fallback");

                assert_eq!(manifest_item.id, "image");
                assert_eq!(manifest_item.path, PathBuf::from("image.tiff"));
                assert_eq!(manifest_item.mime, "");
                assert_eq!(manifest_item.properties, None);
                assert_eq!(manifest_item.fallback, Some("image-fallback".to_string()));
            }

            #[test]
            fn test_manifest_item_set_mime() {
                let manifest_item = ManifestItem::new("style", "style.css");
                assert!(manifest_item.is_ok());

                let manifest_item = manifest_item.unwrap();
                let updated_item = manifest_item.set_mime("text/css");

                assert_eq!(updated_item.id, "style");
                assert_eq!(updated_item.path, PathBuf::from("style.css"));
                assert_eq!(updated_item.mime, "text/css");
                assert_eq!(updated_item.properties, None);
                assert_eq!(updated_item.fallback, None);
            }

            #[test]
            fn test_manifest_item_build() {
                let manifest_item = ManifestItem::new("cover", "images/cover.jpg");
                assert!(manifest_item.is_ok());

                let mut manifest_item = manifest_item.unwrap();
                manifest_item
                    .append_property("cover-image")
                    .with_fallback("cover-fallback");

                let built = manifest_item.build();

                assert_eq!(built.id, "cover");
                assert_eq!(built.path, PathBuf::from("images/cover.jpg"));
                assert_eq!(built.mime, "");
                assert_eq!(built.properties, Some("cover-image".to_string()));
                assert_eq!(built.fallback, Some("cover-fallback".to_string()));
            }

            #[test]
            fn test_manifest_item_builder_chaining() {
                let manifest_item = ManifestItem::new("content", "content.xhtml");
                assert!(manifest_item.is_ok());

                let mut manifest_item = manifest_item.unwrap();
                manifest_item
                    .append_property("scripted")
                    .append_property("svg")
                    .with_fallback("fallback-content");

                let built = manifest_item.build();

                assert_eq!(built.id, "content");
                assert_eq!(built.path, PathBuf::from("content.xhtml"));
                assert_eq!(built.mime, "");
                assert_eq!(built.properties, Some("scripted svg".to_string()));
                assert_eq!(built.fallback, Some("fallback-content".to_string()));
            }

            #[test]
            fn test_manifest_item_attributes() {
                let manifest_item = ManifestItem::new("nav", "nav.xhtml");
                assert!(manifest_item.is_ok());

                let mut manifest_item = manifest_item.unwrap();
                manifest_item
                    .append_property("nav")
                    .with_fallback("fallback-nav");

                // Manually set mime type for testing
                let manifest_item = manifest_item.set_mime("application/xhtml+xml");
                let attributes = manifest_item.attributes();

                // Check that all expected attributes are present
                assert!(attributes.contains(&("id", "nav")));
                assert!(attributes.contains(&("href", "nav.xhtml")));
                assert!(attributes.contains(&("media-type", "application/xhtml+xml")));
                assert!(attributes.contains(&("properties", "nav")));
                assert!(attributes.contains(&("fallback", "fallback-nav")));
            }

            #[test]
            fn test_manifest_item_attributes_optional_fields() {
                let manifest_item = ManifestItem::new("simple", "simple.xhtml");
                assert!(manifest_item.is_ok());

                let manifest_item = manifest_item.unwrap();
                let manifest_item = manifest_item.set_mime("application/xhtml+xml");
                let attributes = manifest_item.attributes();

                // Should contain required attributes
                assert!(attributes.contains(&("id", "simple")));
                assert!(attributes.contains(&("href", "simple.xhtml")));
                assert!(attributes.contains(&("media-type", "application/xhtml+xml")));

                // Should not contain optional attributes when they are None
                assert!(!attributes.iter().any(|(k, _)| k == &"properties"));
                assert!(!attributes.iter().any(|(k, _)| k == &"fallback"));
            }

            #[test]
            fn test_manifest_item_path_handling() {
                let manifest_item = ManifestItem::new("test", "../images/test.png");
                assert!(manifest_item.is_err());

                let err = manifest_item.unwrap_err();
                assert_eq!(
                    err.to_string(),
                    "Epub builder error: A manifest with id 'test' should not use a relative path starting with '../'."
                );
            }
        }

        mod spine_item {
            use crate::types::SpineItem;

            #[test]
            fn test_spine_item_new() {
                let spine_item = SpineItem::new("content_001");

                assert_eq!(spine_item.idref, "content_001");
                assert_eq!(spine_item.id, None);
                assert_eq!(spine_item.properties, None);
                assert_eq!(spine_item.linear, true);
            }

            #[test]
            fn test_spine_item_with_id() {
                let mut spine_item = SpineItem::new("content_001");
                spine_item.with_id("spine1");

                assert_eq!(spine_item.idref, "content_001");
                assert_eq!(spine_item.id, Some("spine1".to_string()));
                assert_eq!(spine_item.properties, None);
                assert_eq!(spine_item.linear, true);
            }

            #[test]
            fn test_spine_item_append_property() {
                let mut spine_item = SpineItem::new("content_001");
                spine_item.append_property("page-spread-left");

                assert_eq!(spine_item.idref, "content_001");
                assert_eq!(spine_item.id, None);
                assert_eq!(spine_item.properties, Some("page-spread-left".to_string()));
                assert_eq!(spine_item.linear, true);
            }

            #[test]
            fn test_spine_item_append_multiple_properties() {
                let mut spine_item = SpineItem::new("content_001");
                spine_item
                    .append_property("page-spread-left")
                    .append_property("rendition:layout-pre-paginated");

                assert_eq!(
                    spine_item.properties,
                    Some("page-spread-left rendition:layout-pre-paginated".to_string())
                );
            }

            #[test]
            fn test_spine_item_set_linear() {
                let mut spine_item = SpineItem::new("content_001");
                spine_item.set_linear(false);

                assert_eq!(spine_item.idref, "content_001");
                assert_eq!(spine_item.id, None);
                assert_eq!(spine_item.properties, None);
                assert_eq!(spine_item.linear, false);
            }

            #[test]
            fn test_spine_item_build() {
                let mut spine_item = SpineItem::new("content_001");
                spine_item
                    .with_id("spine1")
                    .append_property("page-spread-left")
                    .set_linear(false);

                let built = spine_item.build();

                assert_eq!(built.idref, "content_001");
                assert_eq!(built.id, Some("spine1".to_string()));
                assert_eq!(built.properties, Some("page-spread-left".to_string()));
                assert_eq!(built.linear, false);
            }

            #[test]
            fn test_spine_item_builder_chaining() {
                let mut spine_item = SpineItem::new("content_001");
                spine_item
                    .with_id("spine1")
                    .append_property("page-spread-left")
                    .set_linear(false);

                let built = spine_item.build();

                assert_eq!(built.idref, "content_001");
                assert_eq!(built.id, Some("spine1".to_string()));
                assert_eq!(built.properties, Some("page-spread-left".to_string()));
                assert_eq!(built.linear, false);
            }

            #[test]
            fn test_spine_item_attributes() {
                let mut spine_item = SpineItem::new("content_001");
                spine_item
                    .with_id("spine1")
                    .append_property("page-spread-left")
                    .set_linear(false);

                let attributes = spine_item.attributes();

                // Check that all expected attributes are present
                assert!(attributes.contains(&("idref", "content_001")));
                assert!(attributes.contains(&("id", "spine1")));
                assert!(attributes.contains(&("properties", "page-spread-left")));
                assert!(attributes.contains(&("linear", "no"))); // false should become "no"
            }

            #[test]
            fn test_spine_item_attributes_linear_yes() {
                let spine_item = SpineItem::new("content_001");
                let attributes = spine_item.attributes();

                // Linear true should become "yes"
                assert!(attributes.contains(&("linear", "yes")));
            }

            #[test]
            fn test_spine_item_attributes_optional_fields() {
                let spine_item = SpineItem::new("content_001");
                let attributes = spine_item.attributes();

                // Should only contain required attributes when optional fields are None
                assert!(attributes.contains(&("idref", "content_001")));
                assert!(attributes.contains(&("linear", "yes")));

                // Should not contain optional attributes when they are None
                assert!(!attributes.iter().any(|(k, _)| k == &"id"));
                assert!(!attributes.iter().any(|(k, _)| k == &"properties"));
            }
        }

        mod navpoint {

            use std::path::PathBuf;

            use crate::types::NavPoint;

            #[test]
            fn test_navpoint_new() {
                let navpoint = NavPoint::new("Test Chapter");

                assert_eq!(navpoint.label, "Test Chapter");
                assert_eq!(navpoint.content, None);
                assert_eq!(navpoint.children.len(), 0);
            }

            #[test]
            fn test_navpoint_with_content() {
                let mut navpoint = NavPoint::new("Test Chapter");
                navpoint.with_content("chapter1.html");

                assert_eq!(navpoint.label, "Test Chapter");
                assert_eq!(navpoint.content, Some(PathBuf::from("chapter1.html")));
                assert_eq!(navpoint.children.len(), 0);
            }

            #[test]
            fn test_navpoint_append_child() {
                let mut parent = NavPoint::new("Parent Chapter");

                let mut child1 = NavPoint::new("Child Section 1");
                child1.with_content("section1.html");

                let mut child2 = NavPoint::new("Child Section 2");
                child2.with_content("section2.html");

                parent.append_child(child1.build());
                parent.append_child(child2.build());

                assert_eq!(parent.children.len(), 2);
                assert_eq!(parent.children[0].label, "Child Section 1");
                assert_eq!(parent.children[1].label, "Child Section 2");
            }

            #[test]
            fn test_navpoint_set_children() {
                let mut navpoint = NavPoint::new("Main Chapter");
                let children = vec![NavPoint::new("Section 1"), NavPoint::new("Section 2")];

                navpoint.set_children(children);

                assert_eq!(navpoint.children.len(), 2);
                assert_eq!(navpoint.children[0].label, "Section 1");
                assert_eq!(navpoint.children[1].label, "Section 2");
            }

            #[test]
            fn test_navpoint_build() {
                let mut navpoint = NavPoint::new("Complete Chapter");
                navpoint.with_content("complete.html");

                let child = NavPoint::new("Sub Section");
                navpoint.append_child(child.build());

                let built = navpoint.build();

                assert_eq!(built.label, "Complete Chapter");
                assert_eq!(built.content, Some(PathBuf::from("complete.html")));
                assert_eq!(built.children.len(), 1);
                assert_eq!(built.children[0].label, "Sub Section");
            }

            #[test]
            fn test_navpoint_builder_chaining() {
                let mut navpoint = NavPoint::new("Chained Chapter");

                navpoint
                    .with_content("chained.html")
                    .append_child(NavPoint::new("Child 1").build())
                    .append_child(NavPoint::new("Child 2").build());

                let built = navpoint.build();

                assert_eq!(built.label, "Chained Chapter");
                assert_eq!(built.content, Some(PathBuf::from("chained.html")));
                assert_eq!(built.children.len(), 2);
            }

            #[test]
            fn test_navpoint_empty_children() {
                let navpoint = NavPoint::new("No Children Chapter");
                let built = navpoint.build();

                assert_eq!(built.children.len(), 0);
            }

            #[test]
            fn test_navpoint_complex_hierarchy() {
                let mut root = NavPoint::new("Book");

                let mut chapter1 = NavPoint::new("Chapter 1");
                chapter1
                    .with_content("chapter1.html")
                    .append_child(
                        NavPoint::new("Section 1.1")
                            .with_content("sec1_1.html")
                            .build(),
                    )
                    .append_child(
                        NavPoint::new("Section 1.2")
                            .with_content("sec1_2.html")
                            .build(),
                    );

                let mut chapter2 = NavPoint::new("Chapter 2");
                chapter2.with_content("chapter2.html").append_child(
                    NavPoint::new("Section 2.1")
                        .with_content("sec2_1.html")
                        .build(),
                );

                root.append_child(chapter1.build())
                    .append_child(chapter2.build());

                let book = root.build();

                assert_eq!(book.label, "Book");
                assert_eq!(book.children.len(), 2);

                let ch1 = &book.children[0];
                assert_eq!(ch1.label, "Chapter 1");
                assert_eq!(ch1.children.len(), 2);

                let ch2 = &book.children[1];
                assert_eq!(ch2.label, "Chapter 2");
                assert_eq!(ch2.children.len(), 1);
            }
        }
    }

    #[cfg(feature = "content-builder")]
    mod footnote_tests {
        use crate::types::Footnote;

        #[test]
        fn test_footnote_basic_creation() {
            let footnote = Footnote {
                locate: 100,
                content: "Sample footnote".to_string(),
            };

            assert_eq!(footnote.locate, 100);
            assert_eq!(footnote.content, "Sample footnote");
        }

        #[test]
        fn test_footnote_equality() {
            let footnote1 = Footnote {
                locate: 100,
                content: "First note".to_string(),
            };

            let footnote2 = Footnote {
                locate: 100,
                content: "First note".to_string(),
            };

            let footnote3 = Footnote {
                locate: 100,
                content: "Different note".to_string(),
            };

            let footnote4 = Footnote {
                locate: 200,
                content: "First note".to_string(),
            };

            assert_eq!(footnote1, footnote2);
            assert_ne!(footnote1, footnote3);
            assert_ne!(footnote1, footnote4);
        }

        #[test]
        fn test_footnote_ordering() {
            let footnote1 = Footnote {
                locate: 100,
                content: "First".to_string(),
            };

            let footnote2 = Footnote {
                locate: 200,
                content: "Second".to_string(),
            };

            let footnote3 = Footnote {
                locate: 150,
                content: "Middle".to_string(),
            };

            assert!(footnote1 < footnote2);
            assert!(footnote2 > footnote1);
            assert!(footnote1 < footnote3);
            assert!(footnote3 < footnote2);
            assert_eq!(footnote1.cmp(&footnote1), std::cmp::Ordering::Equal);
        }

        #[test]
        fn test_footnote_sorting() {
            let mut footnotes = vec![
                Footnote {
                    locate: 300,
                    content: "Third note".to_string(),
                },
                Footnote {
                    locate: 100,
                    content: "First note".to_string(),
                },
                Footnote {
                    locate: 200,
                    content: "Second note".to_string(),
                },
            ];

            footnotes.sort();

            assert_eq!(footnotes[0].locate, 100);
            assert_eq!(footnotes[1].locate, 200);
            assert_eq!(footnotes[2].locate, 300);

            assert_eq!(footnotes[0].content, "First note");
            assert_eq!(footnotes[1].content, "Second note");
            assert_eq!(footnotes[2].content, "Third note");
        }
    }

    #[cfg(feature = "content-builder")]
    mod block_type_tests {
        use crate::types::BlockType;

        #[test]
        fn test_block_type_variants() {
            let _ = BlockType::Text;
            let _ = BlockType::Quote;
            let _ = BlockType::Title;
            let _ = BlockType::Image;
            let _ = BlockType::Audio;
            let _ = BlockType::Video;
            let _ = BlockType::MathML;
        }

        #[test]
        fn test_block_type_debug() {
            let text = format!("{:?}", BlockType::Text);
            assert_eq!(text, "Text");

            let quote = format!("{:?}", BlockType::Quote);
            assert_eq!(quote, "Quote");

            let image = format!("{:?}", BlockType::Image);
            assert_eq!(image, "Image");
        }
    }

    #[cfg(feature = "content-builder")]
    mod style_options_tests {
        use crate::types::{ColorScheme, PageLayout, StyleOptions, TextAlign, TextStyle};

        #[test]
        fn test_style_options_default() {
            let options = StyleOptions::default();

            assert_eq!(options.text.font_size, 1.0);
            assert_eq!(options.text.line_height, 1.6);
            assert_eq!(
                options.text.font_family,
                "-apple-system, Roboto, sans-serif"
            );
            assert_eq!(options.text.font_weight, "normal");
            assert_eq!(options.text.font_style, "normal");
            assert_eq!(options.text.letter_spacing, "normal");
            assert_eq!(options.text.text_indent, 2.0);

            assert_eq!(options.color_scheme.background, "#FFFFFF");
            assert_eq!(options.color_scheme.text, "#000000");
            assert_eq!(options.color_scheme.link, "#6f6f6f");

            assert_eq!(options.layout.margin, 20);
            assert_eq!(options.layout.text_align, TextAlign::Left);
            assert_eq!(options.layout.paragraph_spacing, 16);
        }

        #[test]
        fn test_style_options_custom_values() {
            let text = TextStyle {
                font_size: 1.5,
                line_height: 2.0,
                font_family: "Georgia, serif".to_string(),
                font_weight: "bold".to_string(),
                font_style: "italic".to_string(),
                letter_spacing: "0.1em".to_string(),
                text_indent: 3.0,
            };

            let color_scheme = ColorScheme {
                background: "#F0F0F0".to_string(),
                text: "#333333".to_string(),
                link: "#0066CC".to_string(),
            };

            let layout = PageLayout {
                margin: 30,
                text_align: TextAlign::Center,
                paragraph_spacing: 20,
            };

            let options = StyleOptions { text, color_scheme, layout };

            assert_eq!(options.text.font_size, 1.5);
            assert_eq!(options.text.font_weight, "bold");
            assert_eq!(options.color_scheme.background, "#F0F0F0");
            assert_eq!(options.layout.text_align, TextAlign::Center);
        }

        #[test]
        fn test_text_style_default() {
            let style = TextStyle::default();

            assert_eq!(style.font_size, 1.0);
            assert_eq!(style.line_height, 1.6);
            assert_eq!(style.font_family, "-apple-system, Roboto, sans-serif");
            assert_eq!(style.font_weight, "normal");
            assert_eq!(style.font_style, "normal");
            assert_eq!(style.letter_spacing, "normal");
            assert_eq!(style.text_indent, 2.0);
        }

        #[test]
        fn test_text_style_custom_values() {
            let style = TextStyle {
                font_size: 2.0,
                line_height: 1.8,
                font_family: "Times New Roman".to_string(),
                font_weight: "bold".to_string(),
                font_style: "italic".to_string(),
                letter_spacing: "0.05em".to_string(),
                text_indent: 0.0,
            };

            assert_eq!(style.font_size, 2.0);
            assert_eq!(style.line_height, 1.8);
            assert_eq!(style.font_family, "Times New Roman");
            assert_eq!(style.font_weight, "bold");
            assert_eq!(style.font_style, "italic");
            assert_eq!(style.letter_spacing, "0.05em");
            assert_eq!(style.text_indent, 0.0);
        }

        #[test]
        fn test_text_style_debug() {
            let style = TextStyle::default();
            let debug_str = format!("{:?}", style);
            assert!(debug_str.contains("TextStyle"));
            assert!(debug_str.contains("font_size"));
        }

        #[test]
        fn test_color_scheme_default() {
            let scheme = ColorScheme::default();

            assert_eq!(scheme.background, "#FFFFFF");
            assert_eq!(scheme.text, "#000000");
            assert_eq!(scheme.link, "#6f6f6f");
        }

        #[test]
        fn test_color_scheme_custom_values() {
            let scheme = ColorScheme {
                background: "#000000".to_string(),
                text: "#FFFFFF".to_string(),
                link: "#00FF00".to_string(),
            };

            assert_eq!(scheme.background, "#000000");
            assert_eq!(scheme.text, "#FFFFFF");
            assert_eq!(scheme.link, "#00FF00");
        }

        #[test]
        fn test_color_scheme_debug() {
            let scheme = ColorScheme::default();
            let debug_str = format!("{:?}", scheme);
            assert!(debug_str.contains("ColorScheme"));
            assert!(debug_str.contains("background"));
        }

        #[test]
        fn test_page_layout_default() {
            let layout = PageLayout::default();

            assert_eq!(layout.margin, 20);
            assert_eq!(layout.text_align, TextAlign::Left);
            assert_eq!(layout.paragraph_spacing, 16);
        }

        #[test]
        fn test_page_layout_custom_values() {
            let layout = PageLayout {
                margin: 40,
                text_align: TextAlign::Justify,
                paragraph_spacing: 24,
            };

            assert_eq!(layout.margin, 40);
            assert_eq!(layout.text_align, TextAlign::Justify);
            assert_eq!(layout.paragraph_spacing, 24);
        }

        #[test]
        fn test_page_layout_debug() {
            let layout = PageLayout::default();
            let debug_str = format!("{:?}", layout);
            assert!(debug_str.contains("PageLayout"));
            assert!(debug_str.contains("margin"));
        }

        #[test]
        fn test_text_align_default() {
            let align = TextAlign::default();
            assert_eq!(align, TextAlign::Left);
        }

        #[test]
        fn test_text_align_display() {
            assert_eq!(TextAlign::Left.to_string(), "left");
            assert_eq!(TextAlign::Right.to_string(), "right");
            assert_eq!(TextAlign::Justify.to_string(), "justify");
            assert_eq!(TextAlign::Center.to_string(), "center");
        }

        #[test]
        fn test_text_align_all_variants() {
            let left = TextAlign::Left;
            let right = TextAlign::Right;
            let justify = TextAlign::Justify;
            let center = TextAlign::Center;

            assert!(matches!(left, TextAlign::Left));
            assert!(matches!(right, TextAlign::Right));
            assert!(matches!(justify, TextAlign::Justify));
            assert!(matches!(center, TextAlign::Center));
        }

        #[test]
        fn test_text_align_debug() {
            assert_eq!(format!("{:?}", TextAlign::Left), "Left");
            assert_eq!(format!("{:?}", TextAlign::Right), "Right");
            assert_eq!(format!("{:?}", TextAlign::Justify), "Justify");
            assert_eq!(format!("{:?}", TextAlign::Center), "Center");
        }

        #[test]
        fn test_style_options_builder_new() {
            let options = StyleOptions::new();
            assert_eq!(options.text.font_size, 1.0);
            assert_eq!(options.color_scheme.background, "#FFFFFF");
            assert_eq!(options.layout.margin, 20);
        }

        #[test]
        fn test_style_options_builder_with_text() {
            let mut options = StyleOptions::new();
            let text_style = TextStyle::new()
                .with_font_size(2.0)
                .with_font_weight("bold")
                .build();
            options.with_text(text_style);

            assert_eq!(options.text.font_size, 2.0);
            assert_eq!(options.text.font_weight, "bold");
        }

        #[test]
        fn test_style_options_builder_with_color_scheme() {
            let mut options = StyleOptions::new();
            let color = ColorScheme::new()
                .with_background("#000000")
                .with_text("#FFFFFF")
                .build();
            options.with_color_scheme(color);

            assert_eq!(options.color_scheme.background, "#000000");
            assert_eq!(options.color_scheme.text, "#FFFFFF");
        }

        #[test]
        fn test_style_options_builder_with_layout() {
            let mut options = StyleOptions::new();
            let layout = PageLayout::new()
                .with_margin(40)
                .with_text_align(TextAlign::Justify)
                .with_paragraph_spacing(24)
                .build();
            options.with_layout(layout);

            assert_eq!(options.layout.margin, 40);
            assert_eq!(options.layout.text_align, TextAlign::Justify);
            assert_eq!(options.layout.paragraph_spacing, 24);
        }

        #[test]
        fn test_style_options_builder_build() {
            let options = StyleOptions::new()
                .with_text(TextStyle::new().with_font_size(1.5).build())
                .with_color_scheme(ColorScheme::new().with_link("#FF0000").build())
                .with_layout(PageLayout::new().with_margin(30).build())
                .build();

            assert_eq!(options.text.font_size, 1.5);
            assert_eq!(options.color_scheme.link, "#FF0000");
            assert_eq!(options.layout.margin, 30);
        }

        #[test]
        fn test_style_options_builder_chaining() {
            let options = StyleOptions::new()
                .with_text(
                    TextStyle::new()
                        .with_font_size(1.5)
                        .with_line_height(2.0)
                        .with_font_family("Arial")
                        .with_font_weight("bold")
                        .with_font_style("italic")
                        .with_letter_spacing("0.1em")
                        .with_text_indent(1.5)
                        .build(),
                )
                .with_color_scheme(
                    ColorScheme::new()
                        .with_background("#CCCCCC")
                        .with_text("#111111")
                        .with_link("#0000FF")
                        .build(),
                )
                .with_layout(
                    PageLayout::new()
                        .with_margin(25)
                        .with_text_align(TextAlign::Right)
                        .with_paragraph_spacing(20)
                        .build(),
                )
                .build();

            assert_eq!(options.text.font_size, 1.5);
            assert_eq!(options.text.line_height, 2.0);
            assert_eq!(options.text.font_family, "Arial");
            assert_eq!(options.text.font_weight, "bold");
            assert_eq!(options.text.font_style, "italic");
            assert_eq!(options.text.letter_spacing, "0.1em");
            assert_eq!(options.text.text_indent, 1.5);

            assert_eq!(options.color_scheme.background, "#CCCCCC");
            assert_eq!(options.color_scheme.text, "#111111");
            assert_eq!(options.color_scheme.link, "#0000FF");

            assert_eq!(options.layout.margin, 25);
            assert_eq!(options.layout.text_align, TextAlign::Right);
            assert_eq!(options.layout.paragraph_spacing, 20);
        }

        #[test]
        fn test_text_style_builder_new() {
            let style = TextStyle::new();
            assert_eq!(style.font_size, 1.0);
            assert_eq!(style.line_height, 1.6);
        }

        #[test]
        fn test_text_style_builder_with_font_size() {
            let mut style = TextStyle::new();
            style.with_font_size(2.5);
            assert_eq!(style.font_size, 2.5);
        }

        #[test]
        fn test_text_style_builder_with_line_height() {
            let mut style = TextStyle::new();
            style.with_line_height(2.0);
            assert_eq!(style.line_height, 2.0);
        }

        #[test]
        fn test_text_style_builder_with_font_family() {
            let mut style = TextStyle::new();
            style.with_font_family("Helvetica, Arial");
            assert_eq!(style.font_family, "Helvetica, Arial");
        }

        #[test]
        fn test_text_style_builder_with_font_weight() {
            let mut style = TextStyle::new();
            style.with_font_weight("bold");
            assert_eq!(style.font_weight, "bold");
        }

        #[test]
        fn test_text_style_builder_with_font_style() {
            let mut style = TextStyle::new();
            style.with_font_style("italic");
            assert_eq!(style.font_style, "italic");
        }

        #[test]
        fn test_text_style_builder_with_letter_spacing() {
            let mut style = TextStyle::new();
            style.with_letter_spacing("0.05em");
            assert_eq!(style.letter_spacing, "0.05em");
        }

        #[test]
        fn test_text_style_builder_with_text_indent() {
            let mut style = TextStyle::new();
            style.with_text_indent(3.0);
            assert_eq!(style.text_indent, 3.0);
        }

        #[test]
        fn test_text_style_builder_build() {
            let style = TextStyle::new()
                .with_font_size(1.8)
                .with_line_height(1.9)
                .build();

            assert_eq!(style.font_size, 1.8);
            assert_eq!(style.line_height, 1.9);
        }

        #[test]
        fn test_text_style_builder_chaining() {
            let style = TextStyle::new()
                .with_font_size(2.0)
                .with_line_height(1.8)
                .with_font_family("Georgia")
                .with_font_weight("bold")
                .with_font_style("italic")
                .with_letter_spacing("0.1em")
                .with_text_indent(0.5)
                .build();

            assert_eq!(style.font_size, 2.0);
            assert_eq!(style.line_height, 1.8);
            assert_eq!(style.font_family, "Georgia");
            assert_eq!(style.font_weight, "bold");
            assert_eq!(style.font_style, "italic");
            assert_eq!(style.letter_spacing, "0.1em");
            assert_eq!(style.text_indent, 0.5);
        }

        #[test]
        fn test_color_scheme_builder_new() {
            let scheme = ColorScheme::new();
            assert_eq!(scheme.background, "#FFFFFF");
            assert_eq!(scheme.text, "#000000");
        }

        #[test]
        fn test_color_scheme_builder_with_background() {
            let mut scheme = ColorScheme::new();
            scheme.with_background("#FF0000");
            assert_eq!(scheme.background, "#FF0000");
        }

        #[test]
        fn test_color_scheme_builder_with_text() {
            let mut scheme = ColorScheme::new();
            scheme.with_text("#333333");
            assert_eq!(scheme.text, "#333333");
        }

        #[test]
        fn test_color_scheme_builder_with_link() {
            let mut scheme = ColorScheme::new();
            scheme.with_link("#0000FF");
            assert_eq!(scheme.link, "#0000FF");
        }

        #[test]
        fn test_color_scheme_builder_build() {
            let scheme = ColorScheme::new().with_background("#123456").build();

            assert_eq!(scheme.background, "#123456");
            assert_eq!(scheme.text, "#000000");
        }

        #[test]
        fn test_color_scheme_builder_chaining() {
            let scheme = ColorScheme::new()
                .with_background("#AABBCC")
                .with_text("#DDEEFF")
                .with_link("#112233")
                .build();

            assert_eq!(scheme.background, "#AABBCC");
            assert_eq!(scheme.text, "#DDEEFF");
            assert_eq!(scheme.link, "#112233");
        }

        #[test]
        fn test_page_layout_builder_new() {
            let layout = PageLayout::new();
            assert_eq!(layout.margin, 20);
            assert_eq!(layout.text_align, TextAlign::Left);
            assert_eq!(layout.paragraph_spacing, 16);
        }

        #[test]
        fn test_page_layout_builder_with_margin() {
            let mut layout = PageLayout::new();
            layout.with_margin(50);
            assert_eq!(layout.margin, 50);
        }

        #[test]
        fn test_page_layout_builder_with_text_align() {
            let mut layout = PageLayout::new();
            layout.with_text_align(TextAlign::Center);
            assert_eq!(layout.text_align, TextAlign::Center);
        }

        #[test]
        fn test_page_layout_builder_with_paragraph_spacing() {
            let mut layout = PageLayout::new();
            layout.with_paragraph_spacing(30);
            assert_eq!(layout.paragraph_spacing, 30);
        }

        #[test]
        fn test_page_layout_builder_build() {
            let layout = PageLayout::new().with_margin(35).build();

            assert_eq!(layout.margin, 35);
            assert_eq!(layout.text_align, TextAlign::Left);
        }

        #[test]
        fn test_page_layout_builder_chaining() {
            let layout = PageLayout::new()
                .with_margin(45)
                .with_text_align(TextAlign::Justify)
                .with_paragraph_spacing(28)
                .build();

            assert_eq!(layout.margin, 45);
            assert_eq!(layout.text_align, TextAlign::Justify);
            assert_eq!(layout.paragraph_spacing, 28);
        }

        #[test]
        fn test_page_layout_builder_all_text_align_variants() {
            let left = PageLayout::new().with_text_align(TextAlign::Left).build();
            assert_eq!(left.text_align, TextAlign::Left);

            let right = PageLayout::new().with_text_align(TextAlign::Right).build();
            assert_eq!(right.text_align, TextAlign::Right);

            let center = PageLayout::new().with_text_align(TextAlign::Center).build();
            assert_eq!(center.text_align, TextAlign::Center);

            let justify = PageLayout::new()
                .with_text_align(TextAlign::Justify)
                .build();
            assert_eq!(justify.text_align, TextAlign::Justify);
        }
    }
}