ooxml-wml 0.1.0

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

use crate::parsers::{FromXml, ParseError};
use crate::types;
use quick_xml::Reader;
use quick_xml::events::Event;
use std::io::Cursor;

// =============================================================================
// Helpers (private)
// =============================================================================

/// Check if a `OnOffElement` field represents "on" (ECMA-376 §17.17.4).
///
/// An omitted `val` attribute means "true" (the element's presence is the toggle).
/// Explicit values: "1", "true", "on" → true; "0", "false", "off" → false.
#[cfg_attr(
    not(any(feature = "wml-styling", feature = "wml-layout")),
    allow(dead_code)
)]
fn is_on(field: &Option<Box<types::OnOffElement>>) -> bool {
    match field {
        None => false,
        Some(ct) => match &ct.value {
            None => true, // element present with no val → on
            Some(v) => matches!(v.as_str(), "1" | "true" | "on"),
        },
    }
}

/// Tri-state check for style resolution: `None` = not specified, `Some(true/false)` = explicit.
#[cfg_attr(not(feature = "wml-styling"), allow(dead_code))]
fn check_toggle(field: &Option<Box<types::OnOffElement>>) -> Option<bool> {
    field.as_ref().map(|ct| match &ct.value {
        None => true,
        Some(v) => matches!(v.as_str(), "1" | "true" | "on"),
    })
}

/// Parse a half-point measurement string (e.g., "24" → 24 half-points = 12pt).
#[cfg_attr(not(feature = "wml-styling"), allow(dead_code))]
fn parse_half_points(s: &str) -> Option<u32> {
    s.parse::<u32>().ok()
}

/// Parse a twips measurement string (signed or unsigned).
#[cfg(feature = "wml-styling")]
fn parse_twips(s: &str) -> Option<i64> {
    s.parse::<i64>().ok()
}

// =============================================================================
// DocumentExt
// =============================================================================

/// Extension methods for `Document`.
pub trait DocumentExt {
    /// Get the document body (if present).
    fn body(&self) -> Option<&types::Body>;
}

impl DocumentExt for types::Document {
    fn body(&self) -> Option<&types::Body> {
        self.body.as_deref()
    }
}

// =============================================================================
// Table of Contents types
// =============================================================================

/// A single entry in a Table of Contents (ECMA-376 §17.12).
///
/// TOC entries use paragraph styles "TOC 1" through "TOC 9" (or "toc1"–"toc9").
/// The `level` is derived from the numeral in the style name.
#[derive(Debug, Clone, PartialEq)]
pub struct TocEntry {
    /// Heading level (1–9), derived from the paragraph style name.
    pub level: u8,
    /// Display text of the entry, extracted from paragraph runs.
    pub text: String,
    /// Page number, if present as the last numeric token in the paragraph.
    /// May be `None` or `0` for unsaved or newly-created documents.
    pub page: Option<u32>,
    /// Bookmark name if the entry is hyperlinked to a heading.
    /// Found in `ParagraphContent::BookmarkStart` inside the paragraph.
    pub bookmark: Option<String>,
}

/// A parsed Table of Contents (ECMA-376 §17.12.1).
///
/// Returned by [`BodyExt::table_of_contents`].
#[derive(Debug, Clone, PartialEq)]
pub struct TableOfContents {
    /// Ordered list of entries extracted from TOC-style paragraphs.
    pub entries: Vec<TocEntry>,
}

// =============================================================================
// BodyExt
// =============================================================================

/// Extension methods for `Body`.
pub trait BodyExt {
    /// Get all paragraphs in the body.
    fn paragraphs(&self) -> Vec<&types::Paragraph>;

    /// Get all tables in the body.
    fn tables(&self) -> Vec<&types::Table>;

    /// Extract all text content from the body.
    fn text(&self) -> String;

    /// Get the document-level section properties (layout info).
    #[cfg(feature = "wml-layout")]
    fn section_properties(&self) -> Option<&types::SectionProperties>;

    /// Extract all Tables of Contents from this body.
    ///
    /// Scans the body for both SDT-wrapped and field-based TOCs.
    /// Each group of contiguous TOC-style paragraphs (or paragraphs inside
    /// an SDT that contains TOC entries) is returned as a separate
    /// [`TableOfContents`].
    ///
    /// TOC paragraphs use styles "TOC 1"–"TOC 9" or "toc1"–"toc9"
    /// (ECMA-376 §17.12.1).  Requires the `wml-styling` feature to
    /// detect paragraph styles; without it this always returns an empty vec.
    #[cfg(feature = "wml-styling")]
    fn table_of_contents(&self) -> Vec<TableOfContents>;

    /// Extract all form fields from this body (ECMA-376 §17.5.2).
    ///
    /// Walks all block content recursively (including table cells) and
    /// collects every SDT that has a recognisable form-field type.
    /// Requires the `wml-settings` feature; without it always returns an
    /// empty vec.
    #[cfg(feature = "wml-settings")]
    fn form_fields(&self) -> Vec<FormField>;
}

impl BodyExt for types::Body {
    fn paragraphs(&self) -> Vec<&types::Paragraph> {
        self.block_content
            .iter()
            .filter_map(|elt| match elt {
                types::BlockContent::P(p) => Some(p.as_ref()),
                _ => None,
            })
            .collect()
    }

    fn tables(&self) -> Vec<&types::Table> {
        self.block_content
            .iter()
            .filter_map(|elt| match elt {
                types::BlockContent::Tbl(t) => Some(t.as_ref()),
                _ => None,
            })
            .collect()
    }

    fn text(&self) -> String {
        let texts: Vec<String> = self
            .block_content
            .iter()
            .filter_map(|elt| match elt {
                types::BlockContent::P(p) => Some(p.text()),
                types::BlockContent::Tbl(t) => Some(t.text()),
                _ => None,
            })
            .collect();
        texts.join("\n")
    }

    #[cfg(feature = "wml-layout")]
    fn section_properties(&self) -> Option<&types::SectionProperties> {
        self.sect_pr.as_deref()
    }

    #[cfg(feature = "wml-styling")]
    fn table_of_contents(&self) -> Vec<TableOfContents> {
        collect_tocs_from_block_content(&self.block_content)
    }

    #[cfg(feature = "wml-settings")]
    fn form_fields(&self) -> Vec<FormField> {
        collect_form_fields_from_block_content(&self.block_content)
    }
}

// =============================================================================
// TOC helpers (private)
// =============================================================================

/// Return the TOC level (1–9) for a paragraph style name, or `None` if not a
/// TOC style.
///
/// Recognises both display names ("TOC 1"–"TOC 9") and style IDs
/// ("toc1"–"toc9"), case-insensitively.
#[cfg(feature = "wml-styling")]
fn toc_style_level(style: &str) -> Option<u8> {
    let s = style.trim();

    // "TOC 1" … "TOC 9"  (display name, space-separated)
    if let Some(rest) = s.strip_prefix("TOC ").or_else(|| s.strip_prefix("toc "))
        && let Ok(n) = rest.trim().parse::<u8>()
        && (1..=9).contains(&n)
    {
        return Some(n);
    }

    // "toc1" … "toc9"  (style ID, no space)
    if let Some(rest) = s
        .strip_prefix("TOC")
        .or_else(|| s.strip_prefix("toc"))
        .filter(|r| r.len() == 1)
        && let Ok(n) = rest.parse::<u8>()
        && (1..=9).contains(&n)
    {
        return Some(n);
    }

    None
}

/// Return the TOC level for a paragraph, or `None` if it is not a TOC entry.
#[cfg(feature = "wml-styling")]
fn paragraph_toc_level(para: &types::Paragraph) -> Option<u8> {
    let style = para.p_pr.as_ref()?.paragraph_style.as_ref()?.value.as_str();
    toc_style_level(style)
}

/// Extract the text of a paragraph, stripping the trailing page number.
///
/// TOC paragraphs typically look like:  "Heading text\t42"
/// The page number is the last tab-separated token if it parses as a number.
/// Returns the trimmed text before the page number and the page number itself.
#[cfg(feature = "wml-styling")]
fn extract_toc_text_and_page(para: &types::Paragraph) -> (String, Option<u32>) {
    // Collect all run text first.
    let mut full = String::new();
    for content in &para.paragraph_content {
        collect_text_from_paragraph_content(content, &mut full);
    }

    // Split on the last tab and try to parse the tail as a page number.
    if let Some(tab_pos) = full.rfind('\t') {
        let tail = full[tab_pos + 1..].trim();
        if let Ok(page) = tail.parse::<u32>() {
            let text = full[..tab_pos].trim().to_string();
            return (text, Some(page));
        }
    }

    (full.trim().to_string(), None)
}

/// Find the first bookmark name embedded in a paragraph's content.
///
/// Hyperlinked TOC entries wrap their content in a `<w:hyperlink>` whose
/// anchor points to a bookmark on the heading.  The bookmark name is stored
/// in a `BookmarkStart` item at the paragraph level.
#[cfg(feature = "wml-styling")]
fn paragraph_bookmark(para: &types::Paragraph) -> Option<String> {
    for content in &para.paragraph_content {
        if let types::ParagraphContent::BookmarkStart(bm) = content {
            let name = bm.name.clone();
            if !name.is_empty() {
                return Some(name);
            }
        }
    }
    None
}

/// Convert a paragraph with a TOC style into a [`TocEntry`].
#[cfg(feature = "wml-styling")]
fn paragraph_to_toc_entry(para: &types::Paragraph, level: u8) -> TocEntry {
    let (text, page) = extract_toc_text_and_page(para);
    let bookmark = paragraph_bookmark(para);
    TocEntry {
        level,
        text,
        page,
        bookmark,
    }
}

/// Collect all TOC entries from a flat slice of [`BlockContent`] items.
///
/// Both SDT-wrapped and bare (field-based) TOC entries are detected.
/// Contiguous runs of TOC paragraphs (or SDTs containing TOC paragraphs) are
/// each returned as a separate [`TableOfContents`].
#[cfg(feature = "wml-styling")]
fn collect_tocs_from_block_content(blocks: &[types::BlockContent]) -> Vec<TableOfContents> {
    let mut result: Vec<TableOfContents> = Vec::new();
    // Accumulator for the current run of bare (non-SDT) TOC paragraphs.
    let mut current_entries: Vec<TocEntry> = Vec::new();

    for block in blocks {
        match block {
            types::BlockContent::P(para) => {
                if let Some(level) = paragraph_toc_level(para) {
                    current_entries.push(paragraph_to_toc_entry(para, level));
                } else {
                    // Non-TOC paragraph: flush any accumulated entries.
                    flush_toc(&mut current_entries, &mut result);
                }
            }
            types::BlockContent::Sdt(sdt) => {
                // Flush bare entries before handling the SDT.
                flush_toc(&mut current_entries, &mut result);

                // Extract TOC entries from the SDT content.
                let sdt_entries = collect_toc_entries_from_sdt(sdt);
                if !sdt_entries.is_empty() {
                    result.push(TableOfContents {
                        entries: sdt_entries,
                    });
                }
            }
            _ => {
                // Any other block (table, custom XML, …) ends a bare TOC run.
                flush_toc(&mut current_entries, &mut result);
            }
        }
    }

    // Flush any trailing bare entries.
    flush_toc(&mut current_entries, &mut result);

    result
}

/// Flush accumulated TOC entries into the result list.
#[cfg(feature = "wml-styling")]
fn flush_toc(entries: &mut Vec<TocEntry>, result: &mut Vec<TableOfContents>) {
    if !entries.is_empty() {
        result.push(TableOfContents {
            entries: std::mem::take(entries),
        });
    }
}

/// Collect all TOC entries from the content of an SDT block.
///
/// The `sdt_content` field holds [`BlockContentChoice`] items.  We walk those,
/// extracting paragraphs with TOC styles.
#[cfg(feature = "wml-styling")]
fn collect_toc_entries_from_sdt(sdt: &types::CTSdtBlock) -> Vec<TocEntry> {
    let content = match &sdt.sdt_content {
        Some(c) => c,
        None => return Vec::new(),
    };

    content
        .block_content
        .iter()
        .filter_map(|bc| match bc {
            types::BlockContentChoice::P(para) => {
                paragraph_toc_level(para).map(|lvl| paragraph_to_toc_entry(para, lvl))
            }
            _ => None,
        })
        .collect()
}

// =============================================================================
// ParagraphExt
// =============================================================================

/// Extension methods for `Paragraph`.
pub trait ParagraphExt {
    /// Get all runs in this paragraph (including runs inside hyperlinks and simple fields).
    fn runs(&self) -> Vec<&types::Run>;

    /// Extract all text from this paragraph.
    fn text(&self) -> String;

    /// Get hyperlinks in this paragraph.
    fn hyperlinks(&self) -> Vec<&types::Hyperlink>;

    /// Get paragraph properties.
    #[cfg(feature = "wml-styling")]
    fn properties(&self) -> Option<&types::ParagraphProperties>;

    /// Get paragraph alignment (justification). ECMA-376 §17.3.1.13.
    #[cfg(feature = "wml-styling")]
    fn alignment(&self) -> Option<types::STJc>;

    /// Get left indent in twips. ECMA-376 §17.3.1.12.
    ///
    /// Prefers `w:start` (OOXML) and falls back to `w:left` (compatibility).
    #[cfg(feature = "wml-styling")]
    fn indent_left(&self) -> Option<i64>;

    /// Get right indent in twips.
    ///
    /// Prefers `w:end` (OOXML) and falls back to `w:right` (compatibility).
    #[cfg(feature = "wml-styling")]
    fn indent_right(&self) -> Option<i64>;

    /// Get first-line additional indent in twips (positive = first line further right).
    ///
    /// Mutually exclusive with [`indent_hanging`].
    #[cfg(feature = "wml-styling")]
    fn indent_first_line(&self) -> Option<i64>;

    /// Get hanging indent in twips (positive = first line is that many twips to the *left* of the rest).
    ///
    /// Mutually exclusive with [`indent_first_line`].
    #[cfg(feature = "wml-styling")]
    fn indent_hanging(&self) -> Option<i64>;

    /// Get space before paragraph in twips. ECMA-376 §17.3.1.33.
    #[cfg(feature = "wml-styling")]
    fn space_before(&self) -> Option<i64>;

    /// Get space after paragraph in twips.
    #[cfg(feature = "wml-styling")]
    fn space_after(&self) -> Option<i64>;

    /// Get line spacing value in twips (240 = single, 360 = 1.5×, 480 = double for `auto` rule).
    #[cfg(feature = "wml-styling")]
    fn line_spacing(&self) -> Option<i64>;

    /// Get the line spacing rule, if set.
    #[cfg(feature = "wml-styling")]
    fn line_spacing_rule(&self) -> Option<types::STLineSpacingRule>;

    /// Get numbering (list) properties as `(num_id, ilvl)`. ECMA-376 §17.9.
    ///
    /// Returns `None` if this paragraph is not part of a list.
    #[cfg(feature = "wml-numbering")]
    fn numbering(&self) -> Option<(i64, i64)>;
}

impl ParagraphExt for types::Paragraph {
    fn runs(&self) -> Vec<&types::Run> {
        collect_runs_from_paragraph_content(&self.paragraph_content)
    }

    fn text(&self) -> String {
        let mut out = String::new();
        for content in &self.paragraph_content {
            collect_text_from_paragraph_content(content, &mut out);
        }
        out
    }

    fn hyperlinks(&self) -> Vec<&types::Hyperlink> {
        self.paragraph_content
            .iter()
            .filter_map(|c| match c {
                types::ParagraphContent::Hyperlink(h) => Some(h.as_ref()),
                _ => None,
            })
            .collect()
    }

    #[cfg(feature = "wml-styling")]
    fn properties(&self) -> Option<&types::ParagraphProperties> {
        self.p_pr.as_deref()
    }

    #[cfg(feature = "wml-styling")]
    fn alignment(&self) -> Option<types::STJc> {
        self.p_pr
            .as_deref()?
            .justification
            .as_deref()
            .map(|j| j.value)
    }

    #[cfg(feature = "wml-styling")]
    fn indent_left(&self) -> Option<i64> {
        let ind = self.p_pr.as_deref()?.indentation.as_deref()?;
        ind.start
            .as_deref()
            .or(ind.left.as_deref())
            .and_then(parse_twips)
    }

    #[cfg(feature = "wml-styling")]
    fn indent_right(&self) -> Option<i64> {
        let ind = self.p_pr.as_deref()?.indentation.as_deref()?;
        ind.end
            .as_deref()
            .or(ind.right.as_deref())
            .and_then(parse_twips)
    }

    #[cfg(feature = "wml-styling")]
    fn indent_first_line(&self) -> Option<i64> {
        let ind = self.p_pr.as_deref()?.indentation.as_deref()?;
        ind.first_line.as_deref().and_then(parse_twips)
    }

    #[cfg(feature = "wml-styling")]
    fn indent_hanging(&self) -> Option<i64> {
        let ind = self.p_pr.as_deref()?.indentation.as_deref()?;
        ind.hanging.as_deref().and_then(parse_twips)
    }

    #[cfg(feature = "wml-styling")]
    fn space_before(&self) -> Option<i64> {
        let spacing = self.p_pr.as_deref()?.spacing.as_deref()?;
        spacing.before.as_deref().and_then(parse_twips)
    }

    #[cfg(feature = "wml-styling")]
    fn space_after(&self) -> Option<i64> {
        let spacing = self.p_pr.as_deref()?.spacing.as_deref()?;
        spacing.after.as_deref().and_then(parse_twips)
    }

    #[cfg(feature = "wml-styling")]
    fn line_spacing(&self) -> Option<i64> {
        let spacing = self.p_pr.as_deref()?.spacing.as_deref()?;
        spacing.line.as_deref().and_then(parse_twips)
    }

    #[cfg(feature = "wml-styling")]
    fn line_spacing_rule(&self) -> Option<types::STLineSpacingRule> {
        self.p_pr.as_deref()?.spacing.as_deref()?.line_rule
    }

    #[cfg(feature = "wml-numbering")]
    fn numbering(&self) -> Option<(i64, i64)> {
        let num_pr = self.p_pr.as_deref()?.num_pr.as_deref()?;
        let num_id = num_pr.num_id.as_deref()?.value;
        let ilvl = num_pr.ilvl.as_deref()?.value;
        Some((num_id, ilvl))
    }
}

/// Collect runs from paragraph content, including nested runs in hyperlinks and simple fields.
fn collect_runs_from_paragraph_content(content: &[types::ParagraphContent]) -> Vec<&types::Run> {
    let mut runs = Vec::new();
    for item in content {
        match item {
            types::ParagraphContent::R(r) => runs.push(r.as_ref()),
            types::ParagraphContent::Hyperlink(h) => {
                runs.extend(collect_runs_from_paragraph_content(&h.paragraph_content));
            }
            types::ParagraphContent::FldSimple(f) => {
                runs.extend(collect_runs_from_paragraph_content(&f.paragraph_content));
            }
            _ => {}
        }
    }
    runs
}

/// Collect text from a single paragraph content item.
fn collect_text_from_paragraph_content(content: &types::ParagraphContent, out: &mut String) {
    match content {
        types::ParagraphContent::R(r) => out.push_str(&r.text()),
        types::ParagraphContent::Hyperlink(h) => {
            for item in &h.paragraph_content {
                collect_text_from_paragraph_content(item, out);
            }
        }
        types::ParagraphContent::FldSimple(f) => {
            for item in &f.paragraph_content {
                collect_text_from_paragraph_content(item, out);
            }
        }
        _ => {}
    }
}

// =============================================================================
// RunExt
// =============================================================================

/// Extension methods for `Run`.
pub trait RunExt {
    /// Extract text from this run.
    ///
    /// Collects `T` (text), `Tab` (→ `\t`), `Cr`/`Br`(non-page) (→ `\n`).
    fn text(&self) -> String;

    /// Get run properties.
    #[cfg(feature = "wml-styling")]
    fn properties(&self) -> Option<&types::RunProperties>;

    /// Check if this run contains a page break.
    fn has_page_break(&self) -> bool;

    /// Get all drawings in this run.
    #[cfg(feature = "wml-drawings")]
    fn drawings(&self) -> Vec<&types::CTDrawing>;

    /// Convenience: check if bold (delegates to properties).
    #[cfg(feature = "wml-styling")]
    fn is_bold(&self) -> bool;

    /// Convenience: check if italic (delegates to properties).
    #[cfg(feature = "wml-styling")]
    fn is_italic(&self) -> bool;

    /// Convenience: check if underlined (delegates to properties).
    #[cfg(feature = "wml-styling")]
    fn is_underline(&self) -> bool;

    /// Convenience: check if strikethrough (delegates to properties).
    #[cfg(feature = "wml-styling")]
    fn is_strikethrough(&self) -> bool;

    /// Check if this run contains any drawing elements (images).
    #[cfg(feature = "wml-drawings")]
    fn has_images(&self) -> bool;

    /// Get the footnote reference in this run, if any.
    fn footnote_ref(&self) -> Option<&types::FootnoteEndnoteRef>;

    /// Get the endnote reference in this run, if any.
    fn endnote_ref(&self) -> Option<&types::FootnoteEndnoteRef>;
}

impl RunExt for types::Run {
    fn text(&self) -> String {
        let mut out = String::new();
        for item in &self.run_content {
            match item {
                types::RunContent::T(t) => {
                    if let Some(ref text) = t.text {
                        out.push_str(text);
                    }
                }
                types::RunContent::Tab(_) => out.push('\t'),
                types::RunContent::Cr(_) => out.push('\n'),
                types::RunContent::Br(br) => {
                    // Page/column breaks aren't text; only text-wrapping breaks produce newlines
                    if !matches!(
                        br.r#type,
                        Some(types::STBrType::Page) | Some(types::STBrType::Column)
                    ) {
                        out.push('\n');
                    }
                }
                _ => {}
            }
        }
        out
    }

    #[cfg(feature = "wml-styling")]
    fn properties(&self) -> Option<&types::RunProperties> {
        self.r_pr.as_deref()
    }

    fn has_page_break(&self) -> bool {
        self.run_content.iter().any(|item| {
            matches!(
                item,
                types::RunContent::Br(br) if br.r#type == Some(types::STBrType::Page)
            )
        })
    }

    #[cfg(feature = "wml-drawings")]
    fn drawings(&self) -> Vec<&types::CTDrawing> {
        self.run_content
            .iter()
            .filter_map(|item| match item {
                types::RunContent::Drawing(d) => Some(d.as_ref()),
                _ => None,
            })
            .collect()
    }

    #[cfg(feature = "wml-styling")]
    fn is_bold(&self) -> bool {
        self.properties().is_some_and(|p| p.is_bold())
    }

    #[cfg(feature = "wml-styling")]
    fn is_italic(&self) -> bool {
        self.properties().is_some_and(|p| p.is_italic())
    }

    #[cfg(feature = "wml-styling")]
    fn is_underline(&self) -> bool {
        self.properties().is_some_and(|p| p.is_underline())
    }

    #[cfg(feature = "wml-styling")]
    fn is_strikethrough(&self) -> bool {
        self.properties().is_some_and(|p| p.is_strikethrough())
    }

    #[cfg(feature = "wml-drawings")]
    fn has_images(&self) -> bool {
        self.run_content
            .iter()
            .any(|item| matches!(item, types::RunContent::Drawing(_)))
    }

    fn footnote_ref(&self) -> Option<&types::FootnoteEndnoteRef> {
        self.run_content.iter().find_map(|item| match item {
            types::RunContent::FootnoteReference(r) => Some(r.as_ref()),
            _ => None,
        })
    }

    fn endnote_ref(&self) -> Option<&types::FootnoteEndnoteRef> {
        self.run_content.iter().find_map(|item| match item {
            types::RunContent::EndnoteReference(r) => Some(r.as_ref()),
            _ => None,
        })
    }
}

// =============================================================================
// DrawingExt
// =============================================================================

/// Extension methods for `CTDrawing` — extract image relationship IDs from raw XML.
///
/// Since `CTDrawing` captures its children as raw XML, this trait walks the tree
/// to find `<a:blip r:embed="..."/>` inside `<wp:inline>` and `<wp:anchor>` elements.
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
pub trait DrawingExt {
    /// Get relationship IDs for inline images (`<wp:inline>` → `<a:blip r:embed="rId"/>`).
    fn inline_image_rel_ids(&self) -> Vec<&str>;

    /// Get relationship IDs for anchored images (`<wp:anchor>` → `<a:blip r:embed="rId"/>`).
    fn anchored_image_rel_ids(&self) -> Vec<&str>;

    /// Get all image relationship IDs (inline + anchored).
    fn all_image_rel_ids(&self) -> Vec<&str>;
}

#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
impl DrawingExt for types::CTDrawing {
    fn inline_image_rel_ids(&self) -> Vec<&str> {
        let mut ids = Vec::new();
        for child in &self.extra_children {
            if let ooxml_xml::RawXmlNode::Element(elem) = &child.node
                && local_name_of(&elem.name) == "inline"
            {
                collect_blip_rel_ids(elem, &mut ids);
            }
        }
        ids
    }

    fn anchored_image_rel_ids(&self) -> Vec<&str> {
        let mut ids = Vec::new();
        for child in &self.extra_children {
            if let ooxml_xml::RawXmlNode::Element(elem) = &child.node
                && local_name_of(&elem.name) == "anchor"
            {
                collect_blip_rel_ids(elem, &mut ids);
            }
        }
        ids
    }

    fn all_image_rel_ids(&self) -> Vec<&str> {
        let mut ids = self.inline_image_rel_ids();
        ids.extend(self.anchored_image_rel_ids());
        ids
    }
}

/// Extract the local name from a possibly-namespaced XML element name.
/// e.g. "wp:inline" → "inline", "a:blip" → "blip", "blip" → "blip".
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
fn local_name_of(name: &str) -> &str {
    name.rsplit(':').next().unwrap_or(name)
}

/// Recursively walk a raw XML element tree and collect `r:embed` attribute values
/// from `<a:blip>` elements.
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
fn collect_blip_rel_ids<'a>(elem: &'a ooxml_xml::RawXmlElement, ids: &mut Vec<&'a str>) {
    if local_name_of(&elem.name) == "blip" {
        for (attr_name, attr_val) in &elem.attributes {
            if attr_name == "r:embed" || local_name_of(attr_name) == "embed" {
                ids.push(attr_val.as_str());
            }
        }
    }
    for child in &elem.children {
        if let ooxml_xml::RawXmlNode::Element(child_elem) = child {
            collect_blip_rel_ids(child_elem, ids);
        }
    }
}

// =============================================================================
// DrawingChartExt — extract chart relationship IDs from CTDrawing
// =============================================================================

/// Extension methods for `CTDrawing` — extract chart relationship IDs from raw XML.
///
/// Charts in DOCX appear in `<wp:inline>` or `<wp:anchor>` elements inside
/// `<a:graphic>` → `<a:graphicData>` → `<c:chart r:id="rId..."/>`.
///
/// ECMA-376 Part 1, §20.4.2.8 (inline), §20.4.2.3 (anchor), §21.2.2.27 (chart).
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
pub trait DrawingChartExt {
    /// Get relationship IDs for charts in inline drawings (`<wp:inline>`).
    fn inline_chart_rel_ids(&self) -> Vec<&str>;

    /// Get relationship IDs for charts in anchored drawings (`<wp:anchor>`).
    fn anchored_chart_rel_ids(&self) -> Vec<&str>;

    /// Get all chart relationship IDs (inline + anchored).
    fn all_chart_rel_ids(&self) -> Vec<&str>;
}

#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
impl DrawingChartExt for types::CTDrawing {
    fn inline_chart_rel_ids(&self) -> Vec<&str> {
        let mut ids = Vec::new();
        for child in &self.extra_children {
            if let ooxml_xml::RawXmlNode::Element(elem) = &child.node
                && local_name_of(&elem.name) == "inline"
            {
                collect_chart_rel_ids(elem, &mut ids);
            }
        }
        ids
    }

    fn anchored_chart_rel_ids(&self) -> Vec<&str> {
        let mut ids = Vec::new();
        for child in &self.extra_children {
            if let ooxml_xml::RawXmlNode::Element(elem) = &child.node
                && local_name_of(&elem.name) == "anchor"
            {
                collect_chart_rel_ids(elem, &mut ids);
            }
        }
        ids
    }

    fn all_chart_rel_ids(&self) -> Vec<&str> {
        let mut ids = self.inline_chart_rel_ids();
        ids.extend(self.anchored_chart_rel_ids());
        ids
    }
}

/// Recursively walk a raw XML element tree and collect `r:id` attribute values
/// from `<c:chart>` elements.
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
fn collect_chart_rel_ids<'a>(elem: &'a ooxml_xml::RawXmlElement, ids: &mut Vec<&'a str>) {
    if local_name_of(&elem.name) == "chart" {
        for (attr_name, attr_val) in &elem.attributes {
            if attr_name == "r:id" || local_name_of(attr_name) == "id" {
                ids.push(attr_val.as_str());
            }
        }
    }
    for child in &elem.children {
        if let ooxml_xml::RawXmlNode::Element(child_elem) = child {
            collect_chart_rel_ids(child_elem, ids);
        }
    }
}

// =============================================================================
// TextBoxExt (DrawingML — modern text boxes)
// =============================================================================

/// Extension methods for `CTDrawing` — extract text from DrawingML text boxes.
///
/// Modern DOCX text boxes live inside `<wp:anchor>` elements within a `<w:drawing>`.
/// The content path is:
/// `<w:drawing>` → `<wp:anchor>` → `<a:graphic>` → `<a:graphicData>` →
/// `<wps:wsp>` → `<wps:txbx>` → `<w:txbxContent>` → paragraphs
///
/// Since `CTDrawing` captures all children as raw XML (`extra_children`), this trait
/// walks the tree recursively to find `w:txbxContent` elements and parses them.
///
/// ECMA-376 Part 1, §20.4.2.3 (anchor) and §20.1.2.2.19 (graphic).
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
pub trait DrawingTextBoxExt {
    /// Extract the plain text of all text boxes in this drawing.
    ///
    /// Returns one `String` per text box found (anchored or inline).
    /// Each string contains the text of all paragraphs in that text box,
    /// joined with newlines.
    fn text_box_texts(&self) -> Vec<String>;
}

#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
impl DrawingTextBoxExt for types::CTDrawing {
    fn text_box_texts(&self) -> Vec<String> {
        let mut results = Vec::new();
        for child in &self.extra_children {
            if let ooxml_xml::RawXmlNode::Element(elem) = &child.node {
                collect_txbx_texts_from_raw(elem, &mut results);
            }
        }
        results
    }
}

/// Recursively walk a raw XML element tree and collect text from every
/// `w:txbxContent` element found anywhere in the subtree.
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
fn collect_txbx_texts_from_raw(elem: &ooxml_xml::RawXmlElement, out: &mut Vec<String>) {
    if local_name_of(&elem.name) == "txbxContent" {
        // Found a text box content element — parse it and extract text.
        match elem.parse_as::<types::CTTxbxContent>() {
            Ok(content) => {
                let text = txbx_content_text(&content);
                out.push(text);
            }
            Err(_) => {
                // Parsing failed; skip this element silently.
            }
        }
        // Don't recurse into txbxContent children — we already parsed the whole subtree.
        return;
    }

    for child in &elem.children {
        if let ooxml_xml::RawXmlNode::Element(child_elem) = child {
            collect_txbx_texts_from_raw(child_elem, out);
        }
    }
}

/// Extract plain text from a `CTTxbxContent` by walking its block content.
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
fn txbx_content_text(content: &types::CTTxbxContent) -> String {
    use crate::ext::{ParagraphExt, TableExt};
    let parts: Vec<String> = content
        .block_content
        .iter()
        .filter_map(|bc| match bc {
            types::BlockContent::P(p) => Some(p.text()),
            types::BlockContent::Tbl(t) => Some(t.text()),
            _ => None,
        })
        .collect();
    parts.join("\n")
}

// =============================================================================
// PictExt (VML — legacy text boxes)
// =============================================================================

/// Extension methods for `CTPicture` — extract text from VML text boxes.
///
/// Legacy DOCX text boxes (VML) appear as:
/// `<w:pict>` → `<v:shape>` → `<v:textbox>` → `<w:txbxContent>` → paragraphs
///
/// Since `CTPicture` captures all children as raw XML (`extra_children`), this
/// trait walks the tree to find `w:txbxContent` and parses it.
///
/// ECMA-376 Part 1, §17.3.3.21 (pict).
#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
pub trait PictExt {
    /// Extract the plain text of the first text box inside this picture element.
    ///
    /// VML picture elements typically contain at most one text box.
    /// Returns `None` if no text box content is found.
    fn text_box_text(&self) -> Option<String>;

    /// Extract the plain text of all text boxes inside this picture element.
    fn text_box_texts(&self) -> Vec<String>;
}

#[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
impl PictExt for types::CTPicture {
    fn text_box_text(&self) -> Option<String> {
        self.text_box_texts().into_iter().next()
    }

    fn text_box_texts(&self) -> Vec<String> {
        let mut results = Vec::new();
        for child in &self.extra_children {
            if let ooxml_xml::RawXmlNode::Element(elem) = &child.node {
                collect_txbx_texts_from_raw(elem, &mut results);
            }
        }
        results
    }
}

// =============================================================================
// MathExt (OMML — Office Math Markup Language)
// =============================================================================

/// A math expression extracted from an `<m:oMath>` element (ECMA-376 Part 1 §22.1).
///
#[cfg(feature = "extra-children")]
#[derive(Debug, Clone)]
pub struct MathExpression {
    /// `true` for display (block) math (`<m:oMathPara>`), `false` for inline (`<m:oMath>`).
    pub is_display: bool,
    /// The parsed OMML math zone containing the structured math content.
    #[cfg(feature = "wml-math")]
    pub zone: ooxml_omml::MathZone,
}

#[cfg(all(feature = "extra-children", feature = "wml-math"))]
impl MathExpression {
    /// Extract plain text representation of the math content.
    pub fn text(&self) -> String {
        self.zone.text()
    }
}

/// Extension methods for types that may contain OMML math (ECMA-376 Part 1 §22.1).
///
/// Math in DOCX uses `<m:oMath>` (inline) or `<m:oMathPara>` (display/block)
/// elements from the namespace
/// `http://schemas.openxmlformats.org/officeDocument/2006/math`.
/// Because the OMML namespace is separate from the WordprocessingML namespace,
/// the generated parser stores these elements in `extra_children` on
/// `Paragraph`.  This trait walks those raw nodes to detect and extract math.
#[cfg(feature = "extra-children")]
pub trait MathExt {
    /// Return all math expressions contained in this element.
    fn math_expressions(&self) -> Vec<MathExpression>;

    /// Return `true` if this element contains at least one math expression.
    fn has_math(&self) -> bool {
        !self.math_expressions().is_empty()
    }
}

#[cfg(feature = "extra-children")]
impl MathExt for types::Paragraph {
    fn math_expressions(&self) -> Vec<MathExpression> {
        let mut out = Vec::new();
        for child in &self.extra_children {
            if let ooxml_xml::RawXmlNode::Element(elem) = &child.node {
                collect_math_from_raw(elem, &mut out);
            }
        }
        out
    }
}

#[cfg(feature = "extra-children")]
impl MathExt for types::Body {
    fn math_expressions(&self) -> Vec<MathExpression> {
        let mut out = Vec::new();
        for item in &self.block_content {
            if let types::BlockContent::P(p) = item {
                out.extend(p.math_expressions());
            }
        }
        out
    }
}

/// Walk a raw XML element and, when an `<m:oMath>` or `<m:oMathPara>` root is
/// found, collect a `MathExpression` and append it to `out`.
///
/// The function does **not** recurse into `<m:oMath>` children once the root
/// is identified — instead it hands the entire subtree to
/// [`collect_math_text`] to gather text leaves.
#[cfg(all(feature = "extra-children", feature = "wml-math"))]
fn parse_math_zone_from_element(elem: &ooxml_xml::RawXmlElement) -> ooxml_omml::MathZone {
    elem.parse_as::<ooxml_omml::MathZone>().unwrap_or_default()
}

#[cfg(feature = "extra-children")]
fn collect_math_from_raw(elem: &ooxml_xml::RawXmlElement, out: &mut Vec<MathExpression>) {
    let local = math_local_name(&elem.name);
    match local {
        "oMathPara" => {
            out.push(MathExpression {
                is_display: true,
                #[cfg(feature = "wml-math")]
                zone: {
                    // Display math: find the inner oMath child and parse it.
                    elem.children
                        .iter()
                        .filter_map(|c| match c {
                            ooxml_xml::RawXmlNode::Element(e)
                                if math_local_name(&e.name) == "oMath" =>
                            {
                                Some(parse_math_zone_from_element(e))
                            }
                            _ => None,
                        })
                        .next()
                        .unwrap_or_default()
                },
            });
        }
        "oMath" => {
            out.push(MathExpression {
                is_display: false,
                #[cfg(feature = "wml-math")]
                zone: parse_math_zone_from_element(elem),
            });
        }
        _ => {
            // Recurse into unrecognised wrapper elements.
            for child in &elem.children {
                if let ooxml_xml::RawXmlNode::Element(child_elem) = child {
                    collect_math_from_raw(child_elem, out);
                }
            }
        }
    }
}

/// Return the local name of a possibly-namespaced element name.
///
/// Handles both `m:oMath` (→ `"oMath"`) and bare `oMath`.  Strips any
/// namespace prefix; does **not** validate that the prefix is actually `m:`.
#[cfg(feature = "extra-children")]
#[inline]
fn math_local_name(name: &str) -> &str {
    name.rsplit(':').next().unwrap_or(name)
}

// =============================================================================
// RunPropertiesExt
// =============================================================================

/// Extension methods for `RunProperties` (ECMA-376 §17.3.2).
///
/// All toggle property checks follow the OOXML convention: element present
/// without `val` attribute means "on"; explicit `val` of "1"/"true"/"on" means on.
#[cfg(feature = "wml-styling")]
pub trait RunPropertiesExt {
    /// Check if bold is enabled.
    fn is_bold(&self) -> bool;

    /// Check if italic is enabled.
    fn is_italic(&self) -> bool;

    /// Check if any underline is set (not `none`).
    fn is_underline(&self) -> bool;

    /// Get the underline style.
    fn underline_style(&self) -> Option<&types::STUnderline>;

    /// Check if single strikethrough is enabled.
    fn is_strikethrough(&self) -> bool;

    /// Check if double strikethrough is enabled.
    fn is_double_strikethrough(&self) -> bool;

    /// Check if all-caps is enabled.
    fn is_all_caps(&self) -> bool;

    /// Check if small-caps is enabled.
    fn is_small_caps(&self) -> bool;

    /// Check if text is hidden (`<w:vanish/>`).
    fn is_hidden(&self) -> bool;

    /// Get highlight color.
    fn highlight_color(&self) -> Option<&types::STHighlightColor>;

    /// Get vertical alignment (superscript/subscript/baseline).
    fn vertical_alignment(&self) -> Option<&types::STVerticalAlignRun>;

    /// Check if superscript.
    fn is_superscript(&self) -> bool;

    /// Check if subscript.
    fn is_subscript(&self) -> bool;

    /// Get font size in half-points (e.g., 24 = 12pt).
    fn font_size_half_points(&self) -> Option<u32>;

    /// Get font size in points (e.g., 12.0).
    fn font_size_points(&self) -> Option<f64>;

    /// Get text color as hex string (e.g., "FF0000").
    fn color_hex(&self) -> Option<&str>;

    /// Get the referenced character style ID.
    fn style_id(&self) -> Option<&str>;

    /// Get the ASCII font name.
    fn font_ascii(&self) -> Option<&str>;

    /// Check if right-to-left text.
    fn is_rtl(&self) -> bool;

    /// Check if outline text effect is enabled. ECMA-376 §17.3.2.23.
    fn is_outline(&self) -> bool;

    /// Check if shadow text effect is enabled. ECMA-376 §17.3.2.31.
    fn is_shadow(&self) -> bool;

    /// Check if emboss text effect is enabled. ECMA-376 §17.3.2.13.
    fn is_emboss(&self) -> bool;

    /// Check if imprint (engrave) text effect is enabled. ECMA-376 §17.3.2.18.
    fn is_imprint(&self) -> bool;

    /// Check if spell/grammar check is suppressed for this run. ECMA-376 §17.3.2.22.
    fn is_no_proof(&self) -> bool;

    /// Check if content snaps to document grid. ECMA-376 §17.3.2.34.
    fn is_snap_to_grid(&self) -> bool;

    /// Check if text is hidden when rendered for the web view. ECMA-376 §17.3.2.44.
    fn is_web_hidden(&self) -> bool;

    /// Get character spacing adjustment in twips (positive = expand, negative = condense). ECMA-376 §17.3.2.35.
    fn character_spacing(&self) -> Option<i64>;

    /// Get text scale as a percentage (100 = normal width). ECMA-376 §17.3.2.43.
    fn text_scale_percent(&self) -> Option<u32>;

    /// Get kerning threshold in half-points. ECMA-376 §17.3.2.19.
    fn kerning(&self) -> Option<u32>;

    /// Get baseline shift in half-points (positive = raise, negative = lower). ECMA-376 §17.3.2.28.
    fn baseline_shift(&self) -> Option<i64>;

    /// Get language tag for this run. ECMA-376 §17.3.2.20.
    fn language(&self) -> Option<&types::LanguageElement>;
}

#[cfg(feature = "wml-styling")]
impl RunPropertiesExt for types::RunProperties {
    fn is_bold(&self) -> bool {
        is_on(&self.bold)
    }

    fn is_italic(&self) -> bool {
        is_on(&self.italic)
    }

    fn is_underline(&self) -> bool {
        self.underline
            .as_ref()
            .is_some_and(|u| !matches!(u.value, Some(types::STUnderline::None)))
    }

    fn underline_style(&self) -> Option<&types::STUnderline> {
        self.underline.as_ref().and_then(|u| u.value.as_ref())
    }

    fn is_strikethrough(&self) -> bool {
        is_on(&self.strikethrough)
    }

    fn is_double_strikethrough(&self) -> bool {
        is_on(&self.dstrike)
    }

    fn is_all_caps(&self) -> bool {
        is_on(&self.caps)
    }

    fn is_small_caps(&self) -> bool {
        is_on(&self.small_caps)
    }

    fn is_hidden(&self) -> bool {
        is_on(&self.vanish)
    }

    fn highlight_color(&self) -> Option<&types::STHighlightColor> {
        self.highlight.as_ref().map(|h| &h.value)
    }

    fn vertical_alignment(&self) -> Option<&types::STVerticalAlignRun> {
        self.vert_align.as_ref().map(|va| &va.value)
    }

    fn is_superscript(&self) -> bool {
        matches!(
            self.vert_align.as_ref().map(|va| &va.value),
            Some(types::STVerticalAlignRun::Superscript)
        )
    }

    fn is_subscript(&self) -> bool {
        matches!(
            self.vert_align.as_ref().map(|va| &va.value),
            Some(types::STVerticalAlignRun::Subscript)
        )
    }

    fn font_size_half_points(&self) -> Option<u32> {
        self.size
            .as_ref()
            .and_then(|sz| parse_half_points(&sz.value))
    }

    fn font_size_points(&self) -> Option<f64> {
        self.font_size_half_points().map(|hp| hp as f64 / 2.0)
    }

    fn color_hex(&self) -> Option<&str> {
        self.color.as_ref().map(|c| c.value.as_str())
    }

    fn style_id(&self) -> Option<&str> {
        self.run_style.as_ref().map(|s| s.value.as_str())
    }

    fn font_ascii(&self) -> Option<&str> {
        self.fonts.as_ref().and_then(|f| f.ascii.as_deref())
    }

    fn is_rtl(&self) -> bool {
        is_on(&self.rtl)
    }

    fn is_outline(&self) -> bool {
        is_on(&self.outline)
    }

    fn is_shadow(&self) -> bool {
        is_on(&self.shadow)
    }

    fn is_emboss(&self) -> bool {
        is_on(&self.emboss)
    }

    fn is_imprint(&self) -> bool {
        is_on(&self.imprint)
    }

    fn is_no_proof(&self) -> bool {
        is_on(&self.no_proof)
    }

    fn is_snap_to_grid(&self) -> bool {
        is_on(&self.snap_to_grid)
    }

    fn is_web_hidden(&self) -> bool {
        is_on(&self.web_hidden)
    }

    fn character_spacing(&self) -> Option<i64> {
        self.spacing
            .as_ref()
            .and_then(|s| s.value.parse::<i64>().ok())
    }

    fn text_scale_percent(&self) -> Option<u32> {
        self.width.as_ref()?.value.as_deref()?.parse::<u32>().ok()
    }

    fn kerning(&self) -> Option<u32> {
        self.kern.as_ref().and_then(|k| parse_half_points(&k.value))
    }

    fn baseline_shift(&self) -> Option<i64> {
        self.position
            .as_ref()
            .and_then(|p| p.value.parse::<i64>().ok())
    }

    fn language(&self) -> Option<&types::LanguageElement> {
        self.lang.as_deref()
    }
}

// =============================================================================
// HyperlinkExt
// =============================================================================

/// Extension methods for `Hyperlink`.
pub trait HyperlinkExt {
    /// Get runs contained in this hyperlink.
    fn runs(&self) -> Vec<&types::Run>;

    /// Extract text from this hyperlink.
    fn text(&self) -> String;

    /// Get the anchor string (in-document bookmark reference).
    fn anchor_str(&self) -> Option<&str>;

    /// Get the relationship ID (`r:id` attribute) for external hyperlinks.
    fn rel_id(&self) -> Option<&str>;

    /// Check if this is an external hyperlink (has a relationship ID).
    fn is_external(&self) -> bool;
}

impl HyperlinkExt for types::Hyperlink {
    fn runs(&self) -> Vec<&types::Run> {
        collect_runs_from_paragraph_content(&self.paragraph_content)
    }

    fn text(&self) -> String {
        let mut out = String::new();
        for item in &self.paragraph_content {
            collect_text_from_paragraph_content(item, &mut out);
        }
        out
    }

    fn anchor_str(&self) -> Option<&str> {
        #[cfg(feature = "wml-hyperlinks")]
        {
            self.anchor.as_deref()
        }
        #[cfg(not(feature = "wml-hyperlinks"))]
        {
            None
        }
    }

    fn rel_id(&self) -> Option<&str> {
        #[cfg(feature = "wml-hyperlinks")]
        {
            self.id.as_deref()
        }
        #[cfg(not(feature = "wml-hyperlinks"))]
        {
            None
        }
    }

    fn is_external(&self) -> bool {
        #[cfg(feature = "wml-hyperlinks")]
        {
            self.id.is_some()
        }
        #[cfg(not(feature = "wml-hyperlinks"))]
        {
            false
        }
    }
}

// =============================================================================
// TableExt
// =============================================================================

/// Extension methods for `Table`.
pub trait TableExt {
    /// Get all rows in this table.
    fn rows(&self) -> Vec<&types::CTRow>;

    /// Get the number of rows.
    fn row_count(&self) -> usize;

    /// Get table properties.
    fn properties(&self) -> &types::TableProperties;

    /// Extract all text from the table.
    fn text(&self) -> String;
}

impl TableExt for types::Table {
    fn rows(&self) -> Vec<&types::CTRow> {
        self.rows
            .iter()
            .filter_map(|c| match c {
                types::RowContent::Tr(row) => Some(row.as_ref()),
                _ => None,
            })
            .collect()
    }

    fn row_count(&self) -> usize {
        self.rows().len()
    }

    fn properties(&self) -> &types::TableProperties {
        &self.table_properties
    }

    fn text(&self) -> String {
        let row_texts: Vec<String> = self.rows().iter().map(|r| r.text()).collect();
        row_texts.join("\n")
    }
}

// =============================================================================
// RowExt
// =============================================================================

/// Extension methods for `CTRow`.
pub trait RowExt {
    /// Get all cells in this row.
    fn cells(&self) -> Vec<&types::TableCell>;

    /// Get row properties.
    #[cfg(feature = "wml-tables")]
    fn properties(&self) -> Option<&types::TableRowProperties>;

    /// Extract all text from the row.
    fn text(&self) -> String;
}

impl RowExt for types::CTRow {
    fn cells(&self) -> Vec<&types::TableCell> {
        self.cells
            .iter()
            .filter_map(|c| match c {
                types::CellContent::Tc(cell) => Some(cell.as_ref()),
                _ => None,
            })
            .collect()
    }

    #[cfg(feature = "wml-tables")]
    fn properties(&self) -> Option<&types::TableRowProperties> {
        self.row_properties.as_deref()
    }

    fn text(&self) -> String {
        let cell_texts: Vec<String> = self.cells().iter().map(|c| c.text()).collect();
        cell_texts.join("\t")
    }
}

// =============================================================================
// CellExt
// =============================================================================

/// Extension methods for `TableCell`.
pub trait CellExt {
    /// Get all paragraphs in this cell.
    fn paragraphs(&self) -> Vec<&types::Paragraph>;

    /// Get cell properties.
    #[cfg(feature = "wml-tables")]
    fn properties(&self) -> Option<&types::TableCellProperties>;

    /// Extract all text from the cell.
    fn text(&self) -> String;
}

impl CellExt for types::TableCell {
    fn paragraphs(&self) -> Vec<&types::Paragraph> {
        self.block_content
            .iter()
            .filter_map(|elt| match elt {
                types::BlockContent::P(p) => Some(p.as_ref()),
                _ => None,
            })
            .collect()
    }

    #[cfg(feature = "wml-tables")]
    fn properties(&self) -> Option<&types::TableCellProperties> {
        self.cell_properties.as_deref()
    }

    fn text(&self) -> String {
        let texts: Vec<String> = self.paragraphs().iter().map(|p| p.text()).collect();
        texts.join("\n")
    }
}

// =============================================================================
// SectionPropertiesExt
// =============================================================================

/// Extension methods for `SectionProperties` (ECMA-376 §17.6.17).
#[cfg(feature = "wml-layout")]
pub trait SectionPropertiesExt {
    /// Get the page size element.
    fn page_size(&self) -> Option<&types::PageSize>;

    /// Get the page margins element.
    fn page_margins(&self) -> Option<&types::PageMargins>;

    /// Get page width in twips.
    fn page_width_twips(&self) -> Option<u64>;

    /// Get page height in twips.
    fn page_height_twips(&self) -> Option<u64>;

    /// Get page orientation.
    fn page_orientation(&self) -> Option<&types::STPageOrientation>;

    /// Check if the section has a distinct title (first) page.
    fn has_title_page(&self) -> bool;

    /// Get header references (type + relationship ID from extra_attrs).
    #[cfg(feature = "extra-attrs")]
    fn header_references(&self) -> Vec<(&types::STHdrFtr, &str)>;

    /// Get footer references (type + relationship ID from extra_attrs).
    #[cfg(feature = "extra-attrs")]
    fn footer_references(&self) -> Vec<(&types::STHdrFtr, &str)>;
}

#[cfg(feature = "wml-layout")]
impl SectionPropertiesExt for types::SectionProperties {
    fn page_size(&self) -> Option<&types::PageSize> {
        self.pg_sz.as_deref()
    }

    fn page_margins(&self) -> Option<&types::PageMargins> {
        self.pg_mar.as_deref()
    }

    fn page_width_twips(&self) -> Option<u64> {
        self.pg_sz
            .as_ref()
            .and_then(|sz| sz.width.as_ref())
            .and_then(|w| w.parse::<u64>().ok())
    }

    fn page_height_twips(&self) -> Option<u64> {
        self.pg_sz
            .as_ref()
            .and_then(|sz| sz.height.as_ref())
            .and_then(|h| h.parse::<u64>().ok())
    }

    fn page_orientation(&self) -> Option<&types::STPageOrientation> {
        self.pg_sz.as_ref().and_then(|sz| sz.orient.as_ref())
    }

    fn has_title_page(&self) -> bool {
        is_on(&self.title_pg)
    }

    #[cfg(feature = "extra-attrs")]
    fn header_references(&self) -> Vec<(&types::STHdrFtr, &str)> {
        self.header_footer_refs
            .iter()
            .filter_map(|r| match r {
                types::HeaderFooterRef::HeaderReference(h) => {
                    h.extra_attrs.get("r:id").map(|id| (&h.r#type, id.as_str()))
                }
                _ => None,
            })
            .collect()
    }

    #[cfg(feature = "extra-attrs")]
    fn footer_references(&self) -> Vec<(&types::STHdrFtr, &str)> {
        self.header_footer_refs
            .iter()
            .filter_map(|r| match r {
                types::HeaderFooterRef::FooterReference(f) => {
                    f.extra_attrs.get("r:id").map(|id| (&f.r#type, id.as_str()))
                }
                _ => None,
            })
            .collect()
    }
}

// =============================================================================
// Style Resolution
// =============================================================================

/// Context for resolving run properties through the style inheritance chain.
///
/// OOXML styles form a `basedOn` chain. Resolution order (ECMA-376 §17.7.2):
/// 1. Direct run properties on the run
/// 2. Character style (referenced by `rPr/rStyle`)
/// 3. Walk the `basedOn` chain of the character style
/// 4. Document defaults (`docDefaults/rPrDefault/rPr`)
#[cfg(feature = "wml-styling")]
#[derive(Debug, Clone, Default)]
pub struct StyleContext {
    /// Styles indexed by styleId.
    pub styles: std::collections::HashMap<String, types::Style>,
    /// Default run properties from `docDefaults`.
    pub default_run_properties: Option<types::RunProperties>,
}

#[cfg(feature = "wml-styling")]
impl StyleContext {
    /// Build a `StyleContext` from a parsed `Styles` document.
    pub fn from_styles(styles_doc: &types::Styles) -> Self {
        let mut styles = std::collections::HashMap::new();
        for style in &styles_doc.style {
            if let Some(ref id) = style.style_id {
                styles.insert(id.clone(), style.clone());
            }
        }

        let default_run_properties = styles_doc
            .doc_defaults
            .as_ref()
            .and_then(|dd| dd.r_pr_default.as_ref())
            .and_then(|rpd| rpd.r_pr.as_ref())
            .map(|rp| rp.as_ref().clone());

        Self {
            styles,
            default_run_properties,
        }
    }

    /// Look up a style by its ID.
    pub fn style(&self, id: &str) -> Option<&types::Style> {
        self.styles.get(id)
    }

    /// Walk the `basedOn` chain for a style, collecting run properties.
    /// Returns properties in order from most derived to least derived.
    /// Depth-limited to 20 to prevent infinite loops.
    fn collect_style_chain_rpr(&self, style_id: &str) -> Vec<&types::RunProperties> {
        let mut result = Vec::new();
        let mut current_id = Some(style_id.to_string());
        let mut depth = 0;

        while let Some(ref id) = current_id {
            if depth >= 20 {
                break;
            }
            if let Some(style) = self.styles.get(id) {
                if let Some(ref rpr) = style.r_pr {
                    result.push(rpr.as_ref());
                }
                current_id = style.based_on.as_ref().map(|b| b.value.clone());
            } else {
                break;
            }
            depth += 1;
        }
        result
    }
}

/// Extension methods for `Run` that resolve formatting through the style chain.
#[cfg(feature = "wml-styling")]
pub trait RunResolveExt {
    /// Resolve bold through direct → style chain → defaults.
    fn resolved_is_bold(&self, ctx: &StyleContext) -> bool;

    /// Resolve italic through direct → style chain → defaults.
    fn resolved_is_italic(&self, ctx: &StyleContext) -> bool;

    /// Resolve font size in half-points through direct → style chain → defaults.
    fn resolved_font_size_half_points(&self, ctx: &StyleContext) -> Option<u32>;

    /// Resolve ASCII font name through direct → style chain → defaults.
    fn resolved_font_ascii(&self, ctx: &StyleContext) -> Option<String>;

    /// Resolve text color hex through direct → style chain → defaults.
    fn resolved_color_hex(&self, ctx: &StyleContext) -> Option<String>;

    /// Resolve underline through direct → style chain → defaults.
    fn resolved_is_underline(&self, ctx: &StyleContext) -> bool;

    /// Resolve single strikethrough through direct → style chain → defaults.
    fn resolved_is_strikethrough(&self, ctx: &StyleContext) -> bool;

    /// Resolve double strikethrough through direct → style chain → defaults.
    fn resolved_is_double_strikethrough(&self, ctx: &StyleContext) -> bool;

    /// Resolve all-caps through direct → style chain → defaults.
    fn resolved_is_all_caps(&self, ctx: &StyleContext) -> bool;

    /// Resolve small-caps through direct → style chain → defaults.
    fn resolved_is_small_caps(&self, ctx: &StyleContext) -> bool;

    /// Resolve hidden (`<w:vanish>`) through direct → style chain → defaults.
    fn resolved_is_hidden(&self, ctx: &StyleContext) -> bool;

    /// Resolve highlight color through direct → style chain → defaults.
    fn resolved_highlight_color(&self, ctx: &StyleContext) -> Option<types::STHighlightColor>;

    /// Resolve vertical alignment through direct → style chain → defaults.
    fn resolved_vertical_alignment(&self, ctx: &StyleContext) -> Option<types::STVerticalAlignRun>;
}

#[cfg(feature = "wml-styling")]
impl RunResolveExt for types::Run {
    fn resolved_is_bold(&self, ctx: &StyleContext) -> bool {
        resolve_toggle(&self.r_pr, ctx, |rpr| &rpr.bold)
    }

    fn resolved_is_italic(&self, ctx: &StyleContext) -> bool {
        resolve_toggle(&self.r_pr, ctx, |rpr| &rpr.italic)
    }

    fn resolved_font_size_half_points(&self, ctx: &StyleContext) -> Option<u32> {
        resolve_option(&self.r_pr, ctx, |rpr| {
            rpr.size
                .as_ref()
                .and_then(|sz| parse_half_points(&sz.value))
        })
    }

    fn resolved_font_ascii(&self, ctx: &StyleContext) -> Option<String> {
        resolve_option(&self.r_pr, ctx, |rpr| {
            rpr.fonts.as_ref().and_then(|f| f.ascii.clone())
        })
    }

    fn resolved_color_hex(&self, ctx: &StyleContext) -> Option<String> {
        resolve_option(&self.r_pr, ctx, |rpr| {
            rpr.color.as_ref().map(|c| c.value.clone())
        })
    }

    fn resolved_is_underline(&self, ctx: &StyleContext) -> bool {
        resolve_option(&self.r_pr, ctx, |rpr| {
            rpr.underline
                .as_ref()
                .map(|u| !matches!(u.value, Some(types::STUnderline::None)))
        })
        .unwrap_or(false)
    }

    fn resolved_is_strikethrough(&self, ctx: &StyleContext) -> bool {
        resolve_toggle(&self.r_pr, ctx, |rpr| &rpr.strikethrough)
    }

    fn resolved_is_double_strikethrough(&self, ctx: &StyleContext) -> bool {
        resolve_toggle(&self.r_pr, ctx, |rpr| &rpr.dstrike)
    }

    fn resolved_is_all_caps(&self, ctx: &StyleContext) -> bool {
        resolve_toggle(&self.r_pr, ctx, |rpr| &rpr.caps)
    }

    fn resolved_is_small_caps(&self, ctx: &StyleContext) -> bool {
        resolve_toggle(&self.r_pr, ctx, |rpr| &rpr.small_caps)
    }

    fn resolved_is_hidden(&self, ctx: &StyleContext) -> bool {
        resolve_toggle(&self.r_pr, ctx, |rpr| &rpr.vanish)
    }

    fn resolved_highlight_color(&self, ctx: &StyleContext) -> Option<types::STHighlightColor> {
        resolve_option(&self.r_pr, ctx, |rpr| {
            rpr.highlight.as_ref().map(|h| h.value)
        })
    }

    fn resolved_vertical_alignment(&self, ctx: &StyleContext) -> Option<types::STVerticalAlignRun> {
        resolve_option(&self.r_pr, ctx, |rpr| {
            rpr.vert_align.as_ref().map(|va| va.value)
        })
    }
}

/// Resolve a toggle property through the style chain.
#[cfg(feature = "wml-styling")]
fn resolve_toggle(
    direct_rpr: &Option<Box<types::RunProperties>>,
    ctx: &StyleContext,
    accessor: impl Fn(&types::RunProperties) -> &Option<Box<types::OnOffElement>>,
) -> bool {
    // 1. Direct run properties
    if let Some(rpr) = direct_rpr {
        if let Some(val) = check_toggle(accessor(rpr)) {
            return val;
        }

        // 2. Style chain via rStyle
        if let Some(style_ref) = &rpr.run_style {
            for chain_rpr in ctx.collect_style_chain_rpr(&style_ref.value) {
                if let Some(val) = check_toggle(accessor(chain_rpr)) {
                    return val;
                }
            }
        }
    }

    // 3. Document defaults
    if let Some(defaults) = &ctx.default_run_properties
        && let Some(val) = check_toggle(accessor(defaults))
    {
        return val;
    }

    false
}

/// Resolve an optional property through the style chain.
#[cfg(feature = "wml-styling")]
fn resolve_option<T>(
    direct_rpr: &Option<Box<types::RunProperties>>,
    ctx: &StyleContext,
    accessor: impl Fn(&types::RunProperties) -> Option<T>,
) -> Option<T> {
    // 1. Direct run properties
    if let Some(rpr) = direct_rpr {
        if let val @ Some(_) = accessor(rpr) {
            return val;
        }

        // 2. Style chain via rStyle
        if let Some(style_ref) = &rpr.run_style {
            for chain_rpr in ctx.collect_style_chain_rpr(&style_ref.value) {
                if let val @ Some(_) = accessor(chain_rpr) {
                    return val;
                }
            }
        }
    }

    // 3. Document defaults
    if let Some(defaults) = &ctx.default_run_properties
        && let val @ Some(_) = accessor(defaults)
    {
        return val;
    }

    None
}

// =============================================================================
// Parsing Functions
// =============================================================================

/// Parse a `Document` from XML bytes using the generated `FromXml` parser.
///
/// This is the recommended way to parse document.xml content.
pub fn parse_document(xml: &[u8]) -> Result<types::Document, ParseError> {
    let mut reader = Reader::from_reader(Cursor::new(xml));
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => return types::Document::from_xml(&mut reader, &e, false),
            Ok(Event::Empty(e)) => return types::Document::from_xml(&mut reader, &e, true),
            Ok(Event::Eof) => break,
            Err(e) => return Err(ParseError::Xml(e)),
            _ => {}
        }
        buf.clear();
    }
    Err(ParseError::UnexpectedElement(
        "no document element found".to_string(),
    ))
}

/// Parse a `Styles` document from XML bytes using the generated `FromXml` parser.
///
/// This is the recommended way to parse styles.xml content.
pub fn parse_styles(xml: &[u8]) -> Result<types::Styles, ParseError> {
    let mut reader = Reader::from_reader(Cursor::new(xml));
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => return types::Styles::from_xml(&mut reader, &e, false),
            Ok(Event::Empty(e)) => return types::Styles::from_xml(&mut reader, &e, true),
            Ok(Event::Eof) => break,
            Err(e) => return Err(ParseError::Xml(e)),
            _ => {}
        }
        buf.clear();
    }
    Err(ParseError::UnexpectedElement(
        "no styles element found".to_string(),
    ))
}

/// Parse a header or footer from XML bytes using the generated `FromXml` parser.
pub fn parse_hdr_ftr(xml: &[u8]) -> Result<types::HeaderFooter, ParseError> {
    let mut reader = Reader::from_reader(Cursor::new(xml));
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => return types::HeaderFooter::from_xml(&mut reader, &e, false),
            Ok(Event::Empty(e)) => return types::HeaderFooter::from_xml(&mut reader, &e, true),
            Ok(Event::Eof) => break,
            Err(e) => return Err(ParseError::Xml(e)),
            _ => {}
        }
        buf.clear();
    }
    Err(ParseError::UnexpectedElement(
        "no header/footer element found".to_string(),
    ))
}

/// Parse footnotes from XML bytes using the generated `FromXml` parser.
pub fn parse_footnotes(xml: &[u8]) -> Result<types::Footnotes, ParseError> {
    let mut reader = Reader::from_reader(Cursor::new(xml));
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => return types::Footnotes::from_xml(&mut reader, &e, false),
            Ok(Event::Empty(e)) => return types::Footnotes::from_xml(&mut reader, &e, true),
            Ok(Event::Eof) => break,
            Err(e) => return Err(ParseError::Xml(e)),
            _ => {}
        }
        buf.clear();
    }
    Err(ParseError::UnexpectedElement(
        "no footnotes element found".to_string(),
    ))
}

/// Parse endnotes from XML bytes using the generated `FromXml` parser.
pub fn parse_endnotes(xml: &[u8]) -> Result<types::Endnotes, ParseError> {
    let mut reader = Reader::from_reader(Cursor::new(xml));
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => return types::Endnotes::from_xml(&mut reader, &e, false),
            Ok(Event::Empty(e)) => return types::Endnotes::from_xml(&mut reader, &e, true),
            Ok(Event::Eof) => break,
            Err(e) => return Err(ParseError::Xml(e)),
            _ => {}
        }
        buf.clear();
    }
    Err(ParseError::UnexpectedElement(
        "no endnotes element found".to_string(),
    ))
}

/// Parse comments from XML bytes using the generated `FromXml` parser.
pub fn parse_comments(xml: &[u8]) -> Result<types::Comments, ParseError> {
    let mut reader = Reader::from_reader(Cursor::new(xml));
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => return types::Comments::from_xml(&mut reader, &e, false),
            Ok(Event::Empty(e)) => return types::Comments::from_xml(&mut reader, &e, true),
            Ok(Event::Eof) => break,
            Err(e) => return Err(ParseError::Xml(e)),
            _ => {}
        }
        buf.clear();
    }
    Err(ParseError::UnexpectedElement(
        "no comments element found".to_string(),
    ))
}

/// Parse a chart part from XML bytes using the `ooxml_dml` generated `FromXml` parser.
///
/// This is used by `Document::get_chart()` to parse `word/charts/chartN.xml` parts.
/// Requires the `wml-charts` feature.
///
/// ECMA-376 Part 1, §21.2.2.27 (chartSpace).
#[cfg(feature = "wml-charts")]
pub(crate) fn parse_chart(xml: &[u8]) -> Result<ooxml_dml::types::ChartSpace, ParseError> {
    use ooxml_dml::parsers::FromXml as DmlFromXml;
    let mut reader = Reader::from_reader(Cursor::new(xml));
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => {
                return ooxml_dml::types::ChartSpace::from_xml(&mut reader, &e, false)
                    .map_err(|e| ParseError::UnexpectedElement(e.to_string()));
            }
            Ok(Event::Empty(e)) => {
                return ooxml_dml::types::ChartSpace::from_xml(&mut reader, &e, true)
                    .map_err(|e| ParseError::UnexpectedElement(e.to_string()));
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(ParseError::Xml(e)),
            _ => {}
        }
        buf.clear();
    }
    Err(ParseError::UnexpectedElement(
        "no chartSpace element found".to_string(),
    ))
}

// =============================================================================
// ResolvedDocument
// =============================================================================

/// A document with bound style context for convenient resolved access.
///
/// Wraps a generated `types::Document` and provides methods that automatically
/// resolve formatting through the style chain.
///
/// # Example
///
/// ```ignore
/// use ooxml_wml::ext::{ResolvedDocument, parse_document, parse_styles};
///
/// let doc = parse_document(doc_xml)?;
/// let styles = parse_styles(styles_xml)?;
/// let resolved = ResolvedDocument::new(doc, styles);
///
/// if let Some(body) = resolved.body() {
///     for para in body.paragraphs() {
///         println!("{}", para.text());
///     }
/// }
/// ```
#[cfg(feature = "wml-styling")]
pub struct ResolvedDocument {
    document: types::Document,
    context: StyleContext,
}

#[cfg(feature = "wml-styling")]
impl ResolvedDocument {
    /// Create a new resolved document from a parsed document and styles.
    pub fn new(document: types::Document, styles: types::Styles) -> Self {
        let context = StyleContext::from_styles(&styles);
        Self { document, context }
    }

    /// Create from a document with an existing style context.
    pub fn with_context(document: types::Document, context: StyleContext) -> Self {
        Self { document, context }
    }

    /// Get the underlying document.
    pub fn document(&self) -> &types::Document {
        &self.document
    }

    /// Get the style context.
    pub fn context(&self) -> &StyleContext {
        &self.context
    }

    /// Get the document body.
    pub fn body(&self) -> Option<&types::Body> {
        self.document.body()
    }

    /// Extract all text from the document.
    pub fn text(&self) -> String {
        self.document.body().map(|b| b.text()).unwrap_or_default()
    }

    /// Check if a run is bold (resolved through style chain).
    pub fn is_bold(&self, run: &types::Run) -> bool {
        run.resolved_is_bold(&self.context)
    }

    /// Check if a run is italic (resolved through style chain).
    pub fn is_italic(&self, run: &types::Run) -> bool {
        run.resolved_is_italic(&self.context)
    }

    /// Get resolved font size in half-points.
    pub fn font_size_half_points(&self, run: &types::Run) -> Option<u32> {
        run.resolved_font_size_half_points(&self.context)
    }

    /// Get resolved ASCII font name.
    pub fn font_ascii(&self, run: &types::Run) -> Option<String> {
        run.resolved_font_ascii(&self.context)
    }

    /// Get resolved text color hex.
    pub fn color_hex(&self, run: &types::Run) -> Option<String> {
        run.resolved_color_hex(&self.context)
    }

    /// Check if a run is underlined (resolved through style chain).
    pub fn is_underline(&self, run: &types::Run) -> bool {
        run.resolved_is_underline(&self.context)
    }

    /// Check if a run is struck through (resolved through style chain).
    pub fn is_strikethrough(&self, run: &types::Run) -> bool {
        run.resolved_is_strikethrough(&self.context)
    }

    /// Check if a run is double struck through (resolved through style chain).
    pub fn is_double_strikethrough(&self, run: &types::Run) -> bool {
        run.resolved_is_double_strikethrough(&self.context)
    }

    /// Check if a run is all-caps (resolved through style chain).
    pub fn is_all_caps(&self, run: &types::Run) -> bool {
        run.resolved_is_all_caps(&self.context)
    }

    /// Check if a run is small-caps (resolved through style chain).
    pub fn is_small_caps(&self, run: &types::Run) -> bool {
        run.resolved_is_small_caps(&self.context)
    }

    /// Check if a run is hidden (resolved through style chain).
    pub fn is_hidden(&self, run: &types::Run) -> bool {
        run.resolved_is_hidden(&self.context)
    }

    /// Get resolved highlight color.
    pub fn highlight_color(&self, run: &types::Run) -> Option<types::STHighlightColor> {
        run.resolved_highlight_color(&self.context)
    }

    /// Get resolved vertical alignment.
    pub fn vertical_alignment(&self, run: &types::Run) -> Option<types::STVerticalAlignRun> {
        run.resolved_vertical_alignment(&self.context)
    }
}

// =============================================================================
// RevisionExt / BodyRevisionExt
// =============================================================================

/// The type of a tracked change (ECMA-376 §17.13).
#[cfg(feature = "wml-track-changes")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TrackChangeType {
    /// Content that was inserted (`<w:ins>`).
    Insertion,
    /// Content that was deleted (`<w:del>`).
    Deletion,
    /// Content that was moved away from this location (`<w:moveFrom>`).
    MoveFrom,
    /// Content that was moved to this location (`<w:moveTo>`).
    MoveTo,
}

/// A single tracked change in a paragraph (ECMA-376 §17.13.5).
#[cfg(feature = "wml-track-changes")]
#[derive(Debug, Clone)]
pub struct TrackChange {
    /// Revision ID (`w:id` attribute).
    pub id: i64,
    /// Author string (`w:author` attribute).
    pub author: String,
    /// Optional ISO 8601 date/time string (`w:date` attribute).
    pub date: Option<String>,
    /// The kind of change.
    pub change_type: TrackChangeType,
    /// Plain text extracted from the run content inside the change.
    pub text: String,
}

/// Extension methods for reading tracked changes from a paragraph (ECMA-376 §17.13).
#[cfg(feature = "wml-track-changes")]
pub trait RevisionExt {
    /// All tracked changes in this paragraph.
    fn track_changes(&self) -> Vec<TrackChange>;

    /// Text produced by accepting all tracked changes: insertions are kept,
    /// deletions are removed, normal runs are kept.
    fn accepted_text(&self) -> String;

    /// Text produced by rejecting all tracked changes: insertions are removed,
    /// deletions are restored, normal runs are kept.
    fn rejected_text(&self) -> String;

    /// Whether this paragraph contains any tracked changes.
    fn has_track_changes(&self) -> bool;
}

/// Extract plain text from a `CTRunTrackChange`'s `run_content` field.
#[cfg(feature = "wml-track-changes")]
fn text_from_run_track_change(tc: &types::CTRunTrackChange) -> String {
    let mut out = String::new();
    for item in &tc.run_content {
        if let types::RunContentChoice::R(run) = item {
            for rc in &run.run_content {
                match rc {
                    types::RunContent::T(t) => {
                        if let Some(ref s) = t.text {
                            out.push_str(s);
                        }
                    }
                    types::RunContent::Tab(_) => out.push('\t'),
                    types::RunContent::Cr(_) => out.push('\n'),
                    types::RunContent::Br(br) => {
                        if !matches!(
                            br.r#type,
                            Some(types::STBrType::Page) | Some(types::STBrType::Column)
                        ) {
                            out.push('\n');
                        }
                    }
                    // Also capture del-text for deletion change content
                    types::RunContent::DelText(t) => {
                        if let Some(ref s) = t.text {
                            out.push_str(s);
                        }
                    }
                    _ => {}
                }
            }
        }
    }
    out
}

#[cfg(feature = "wml-track-changes")]
impl RevisionExt for types::Paragraph {
    fn track_changes(&self) -> Vec<TrackChange> {
        let mut result = Vec::new();
        for item in &self.paragraph_content {
            let (tc, change_type) = match item {
                types::ParagraphContent::Ins(tc) => (tc.as_ref(), TrackChangeType::Insertion),
                types::ParagraphContent::Del(tc) => (tc.as_ref(), TrackChangeType::Deletion),
                types::ParagraphContent::MoveFrom(tc) => (tc.as_ref(), TrackChangeType::MoveFrom),
                types::ParagraphContent::MoveTo(tc) => (tc.as_ref(), TrackChangeType::MoveTo),
                _ => continue,
            };
            result.push(TrackChange {
                id: tc.id,
                author: tc.author.clone(),
                date: tc.date.clone(),
                change_type,
                text: text_from_run_track_change(tc),
            });
        }
        result
    }

    fn accepted_text(&self) -> String {
        let mut out = String::new();
        for item in &self.paragraph_content {
            match item {
                // Normal runs always included
                types::ParagraphContent::R(r) => {
                    out.push_str(&r.text());
                }
                // Insertions accepted → include text
                types::ParagraphContent::Ins(tc) | types::ParagraphContent::MoveTo(tc) => {
                    out.push_str(&text_from_run_track_change(tc));
                }
                // Deletions rejected → skip
                types::ParagraphContent::Del(_) | types::ParagraphContent::MoveFrom(_) => {}
                // Hyperlinks and simple fields: walk their paragraph_content
                types::ParagraphContent::Hyperlink(h) => {
                    for inner in &h.paragraph_content {
                        collect_text_from_paragraph_content(inner, &mut out);
                    }
                }
                types::ParagraphContent::FldSimple(f) => {
                    for inner in &f.paragraph_content {
                        collect_text_from_paragraph_content(inner, &mut out);
                    }
                }
                _ => {}
            }
        }
        out
    }

    fn rejected_text(&self) -> String {
        let mut out = String::new();
        for item in &self.paragraph_content {
            match item {
                // Normal runs always included
                types::ParagraphContent::R(r) => {
                    out.push_str(&r.text());
                }
                // Insertions rejected → skip
                types::ParagraphContent::Ins(_) | types::ParagraphContent::MoveTo(_) => {}
                // Deletions restored → include text
                types::ParagraphContent::Del(tc) | types::ParagraphContent::MoveFrom(tc) => {
                    out.push_str(&text_from_run_track_change(tc));
                }
                // Hyperlinks and simple fields: walk their paragraph_content
                types::ParagraphContent::Hyperlink(h) => {
                    for inner in &h.paragraph_content {
                        collect_text_from_paragraph_content(inner, &mut out);
                    }
                }
                types::ParagraphContent::FldSimple(f) => {
                    for inner in &f.paragraph_content {
                        collect_text_from_paragraph_content(inner, &mut out);
                    }
                }
                _ => {}
            }
        }
        out
    }

    fn has_track_changes(&self) -> bool {
        self.paragraph_content.iter().any(|item| {
            matches!(
                item,
                types::ParagraphContent::Ins(_)
                    | types::ParagraphContent::Del(_)
                    | types::ParagraphContent::MoveFrom(_)
                    | types::ParagraphContent::MoveTo(_)
            )
        })
    }
}

/// Extension methods for reading tracked changes from a document body (ECMA-376 §17.13).
#[cfg(feature = "wml-track-changes")]
pub trait BodyRevisionExt {
    /// All tracked changes in the document body across all paragraphs.
    fn all_track_changes(&self) -> Vec<TrackChange>;

    /// Full document text with all insertions accepted and deletions removed.
    fn accepted_text(&self) -> String;

    /// Full document text with all insertions rejected and deletions restored.
    fn rejected_text(&self) -> String;
}

/// Collect paragraphs from `BlockContent` items recursively (handles SDTs, custom XML, etc.).
#[cfg(feature = "wml-track-changes")]
fn paragraphs_from_block_content(blocks: &[types::BlockContent]) -> Vec<&types::Paragraph> {
    let mut result = Vec::new();
    for block in blocks {
        match block {
            types::BlockContent::P(p) => result.push(p.as_ref()),
            types::BlockContent::Tbl(t) => {
                for row in &t.rows {
                    if let types::RowContent::Tr(tr) = row {
                        for cell in &tr.cells {
                            if let types::CellContent::Tc(tc) = cell {
                                result.extend(paragraphs_from_block_content(&tc.block_content));
                            }
                        }
                    }
                }
            }
            types::BlockContent::Sdt(sdt) => {
                if let Some(content) = &sdt.sdt_content {
                    for inner in &content.block_content {
                        if let types::BlockContentChoice::P(p) = inner {
                            result.push(p.as_ref());
                        }
                    }
                }
            }
            _ => {}
        }
    }
    result
}

#[cfg(feature = "wml-track-changes")]
impl BodyRevisionExt for types::Body {
    fn all_track_changes(&self) -> Vec<TrackChange> {
        paragraphs_from_block_content(&self.block_content)
            .into_iter()
            .flat_map(|p| p.track_changes())
            .collect()
    }

    fn accepted_text(&self) -> String {
        let paras = paragraphs_from_block_content(&self.block_content);
        paras
            .iter()
            .map(|p| p.accepted_text())
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn rejected_text(&self) -> String {
        let paras = paragraphs_from_block_content(&self.block_content);
        paras
            .iter()
            .map(|p| p.rejected_text())
            .collect::<Vec<_>>()
            .join("\n")
    }
}

// =============================================================================
// Form Fields (ECMA-376 §17.5.2)
// =============================================================================

/// The kind of a Structured Document Tag form control (ECMA-376 §17.5.2).
///
/// Determined by which child element is present inside `<w:sdtPr>`.
#[cfg(feature = "wml-settings")]
#[derive(Debug, Clone, PartialEq)]
pub enum FormFieldType {
    /// Plain-text input control (`<w:text>`).
    ///
    /// `multi_line` is `true` when `w:multiLine` is "1", "true", or "on".
    PlainText { multi_line: bool },
    /// Rich-text area (`<w:richText>`).
    RichText,
    /// Combo box with a fixed list of choices (`<w:comboBox>`).
    ComboBox { choices: Vec<String> },
    /// Drop-down list (`<w:dropDownList>`).
    DropDownList { choices: Vec<String> },
    /// Date picker (`<w:date>`).
    DatePicker { format: Option<String> },
    /// SDT whose type was not recognised by this library.
    Unknown,
}

/// A form field extracted from a Structured Document Tag (ECMA-376 §17.5.2).
///
/// Returned by [`FormFieldExt::form_field`] and collected by
/// [`BodyExt::form_fields`].
#[cfg(feature = "wml-settings")]
#[derive(Debug, Clone)]
pub struct FormField {
    /// Human-readable label (`<w:alias w:val="…"/>`).
    pub alias: Option<String>,
    /// Machine-readable tag (`<w:tag w:val="…"/>`).
    pub tag: Option<String>,
    /// The kind of control inferred from `<w:sdtPr>`.
    pub field_type: FormFieldType,
    /// Current text content of the SDT, extracted from its `sdtContent`.
    pub current_value: String,
}

/// Extract a [`FormField`] from an SDT properties block and its content text.
///
/// The `sdt_pr` argument must already be `Some`; call sites gate on that.
#[cfg(feature = "wml-settings")]
fn sdt_pr_to_form_field(sdt_pr: &types::CTSdtPr, current_value: String) -> FormField {
    let alias = sdt_pr.alias.as_ref().map(|a| a.value.clone());
    let tag = sdt_pr.tag.as_ref().map(|t| t.value.clone());

    let field_type = if let Some(text_elem) = &sdt_pr.text {
        let multi_line = text_elem
            .multi_line
            .as_deref()
            .map(|v| matches!(v, "1" | "true" | "on"))
            .unwrap_or(false);
        FormFieldType::PlainText { multi_line }
    } else if sdt_pr.rich_text.is_some() {
        FormFieldType::RichText
    } else if let Some(cb) = &sdt_pr.combo_box {
        let choices = cb
            .list_item
            .iter()
            .map(|item| {
                item.display_text
                    .clone()
                    .or_else(|| item.value.clone())
                    .unwrap_or_default()
            })
            .collect();
        FormFieldType::ComboBox { choices }
    } else if let Some(dd) = &sdt_pr.drop_down_list {
        let choices = dd
            .list_item
            .iter()
            .map(|item| {
                item.display_text
                    .clone()
                    .or_else(|| item.value.clone())
                    .unwrap_or_default()
            })
            .collect();
        FormFieldType::DropDownList { choices }
    } else if let Some(date) = &sdt_pr.date {
        let format = date.date_format.as_ref().map(|df| df.value.clone());
        FormFieldType::DatePicker { format }
    } else {
        FormFieldType::Unknown
    };

    FormField {
        alias,
        tag,
        field_type,
        current_value,
    }
}

/// Extension trait for extracting a [`FormField`] from an SDT element.
///
/// Implemented for both block-level (`CTSdtBlock`) and inline (`CTSdtRun`)
/// SDT variants. Returns `Some` whenever `sdt_pr` is present; returns `None`
/// if there are no properties at all (which is unusual but spec-legal).
///
/// ECMA-376 §17.5.2.
#[cfg(feature = "wml-settings")]
pub trait FormFieldExt {
    /// Extract a [`FormField`] if this SDT has `<w:sdtPr>` properties.
    fn form_field(&self) -> Option<FormField>;
}

#[cfg(feature = "wml-settings")]
impl FormFieldExt for types::CTSdtBlock {
    fn form_field(&self) -> Option<FormField> {
        let sdt_pr = self.sdt_pr.as_deref()?;
        let value = extract_text_from_block_sdt_content(self.sdt_content.as_deref());
        Some(sdt_pr_to_form_field(sdt_pr, value))
    }
}

#[cfg(feature = "wml-settings")]
impl FormFieldExt for types::CTSdtRun {
    fn form_field(&self) -> Option<FormField> {
        let sdt_pr = self.sdt_pr.as_deref()?;
        let value = extract_text_from_run_sdt_content(self.sdt_content.as_deref());
        Some(sdt_pr_to_form_field(sdt_pr, value))
    }
}

/// Extract plain text from `CTSdtContentBlock` by walking its block content
/// choices (paragraphs and nested tables).
#[cfg(feature = "wml-settings")]
fn extract_text_from_block_sdt_content(content: Option<&types::CTSdtContentBlock>) -> String {
    let content = match content {
        Some(c) => c,
        None => return String::new(),
    };
    let parts: Vec<String> = content
        .block_content
        .iter()
        .filter_map(|bc| match bc {
            types::BlockContentChoice::P(p) => Some(p.text()),
            types::BlockContentChoice::Tbl(t) => Some(t.text()),
            _ => None,
        })
        .collect();
    parts.join("\n")
}

/// Extract plain text from `CTSdtContentRun` by walking its paragraph content.
#[cfg(feature = "wml-settings")]
fn extract_text_from_run_sdt_content(content: Option<&types::CTSdtContentRun>) -> String {
    let content = match content {
        Some(c) => c,
        None => return String::new(),
    };
    let mut out = String::new();
    for item in &content.paragraph_content {
        collect_text_from_paragraph_content(item, &mut out);
    }
    out
}

/// Collect all form fields from a slice of [`types::BlockContent`] items,
/// recursing into tables and SDT block content.
#[cfg(feature = "wml-settings")]
fn collect_form_fields_from_block_content(blocks: &[types::BlockContent]) -> Vec<FormField> {
    let mut result = Vec::new();
    for block in blocks {
        match block {
            types::BlockContent::Sdt(sdt) => {
                if let Some(field) = sdt.form_field() {
                    result.push(field);
                }
                // Also look inside the SDT's block content for nested SDTs.
                if let Some(content) = &sdt.sdt_content {
                    for inner in &content.block_content {
                        collect_form_fields_from_block_content_choice(inner, &mut result);
                    }
                }
            }
            types::BlockContent::Tbl(t) => {
                for row in &t.rows {
                    if let types::RowContent::Tr(tr) = row {
                        for cell_content in &tr.cells {
                            if let types::CellContent::Tc(tc) = cell_content {
                                result.extend(collect_form_fields_from_block_content(
                                    &tc.block_content,
                                ));
                            }
                        }
                    }
                }
            }
            types::BlockContent::P(para) => {
                // Inline (run-level) SDTs inside paragraphs.
                for item in &para.paragraph_content {
                    if let types::ParagraphContent::Sdt(sdt_run) = item
                        && let Some(field) = sdt_run.form_field()
                    {
                        result.push(field);
                    }
                }
            }
            _ => {}
        }
    }
    result
}

/// Helper: collect form fields from a single [`types::BlockContentChoice`].
#[cfg(feature = "wml-settings")]
fn collect_form_fields_from_block_content_choice(
    item: &types::BlockContentChoice,
    result: &mut Vec<FormField>,
) {
    match item {
        types::BlockContentChoice::Sdt(sdt) => {
            if let Some(field) = sdt.form_field() {
                result.push(field);
            }
        }
        types::BlockContentChoice::P(para) => {
            for pc in &para.paragraph_content {
                if let types::ParagraphContent::Sdt(sdt_run) = pc
                    && let Some(field) = sdt_run.form_field()
                {
                    result.push(field);
                }
            }
        }
        _ => {}
    }
}

// =============================================================================
// Tests
// =============================================================================

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

    // -------------------------------------------------------------------------
    // Helper tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_is_on_none() {
        assert!(!is_on(&None));
    }

    #[test]
    fn test_is_on_present_no_val() {
        // Element present with no val attribute → on
        let field = Some(Box::new(types::OnOffElement {
            value: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        assert!(is_on(&field));
    }

    #[test]
    fn test_is_on_explicit_true() {
        for val in &["1", "true", "on"] {
            let field = Some(Box::new(types::OnOffElement {
                value: Some(val.to_string()),
                #[cfg(feature = "extra-attrs")]
                extra_attrs: Default::default(),
            }));
            assert!(is_on(&field), "expected is_on for val={val}");
        }
    }

    #[test]
    fn test_is_on_explicit_false() {
        for val in &["0", "false", "off"] {
            let field = Some(Box::new(types::OnOffElement {
                value: Some(val.to_string()),
                #[cfg(feature = "extra-attrs")]
                extra_attrs: Default::default(),
            }));
            assert!(!is_on(&field), "expected !is_on for val={val}");
        }
    }

    #[test]
    fn test_check_toggle_none() {
        assert_eq!(check_toggle(&None), None);
    }

    #[test]
    fn test_check_toggle_present() {
        let field = Some(Box::new(types::OnOffElement {
            value: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        assert_eq!(check_toggle(&field), Some(true));
    }

    #[test]
    fn test_parse_half_points() {
        assert_eq!(parse_half_points("24"), Some(24));
        assert_eq!(parse_half_points("0"), Some(0));
        assert_eq!(parse_half_points("abc"), None);
        assert_eq!(parse_half_points(""), None);
    }

    // -------------------------------------------------------------------------
    // RunPropertiesExt tests
    // -------------------------------------------------------------------------

    #[cfg(feature = "wml-styling")]
    fn make_run_properties() -> types::RunProperties {
        types::RunProperties {
            run_style: None,
            fonts: None,
            bold: None,
            b_cs: None,
            italic: None,
            i_cs: None,
            caps: None,
            small_caps: None,
            strikethrough: None,
            dstrike: None,
            outline: None,
            shadow: None,
            emboss: None,
            imprint: None,
            no_proof: None,
            snap_to_grid: None,
            vanish: None,
            web_hidden: None,
            color: None,
            spacing: None,
            width: None,
            kern: None,
            position: None,
            size: None,
            size_complex_script: None,
            highlight: None,
            underline: None,
            effect: None,
            bdr: None,
            shading: None,
            fit_text: None,
            vert_align: None,
            rtl: None,
            cs: None,
            em: None,
            lang: None,
            east_asian_layout: None,
            spec_vanish: None,
            o_math: None,
            r_pr_change: None,
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }
    }

    #[cfg(feature = "wml-styling")]
    fn on_off(val: Option<&str>) -> Option<Box<types::OnOffElement>> {
        Some(Box::new(types::OnOffElement {
            value: val.map(|v| v.to_string()),
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }))
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_rpr_bold_italic() {
        let mut rpr = make_run_properties();
        assert!(!rpr.is_bold());
        assert!(!rpr.is_italic());

        rpr.bold = on_off(None); // present, no val → on
        rpr.italic = on_off(Some("true"));
        assert!(rpr.is_bold());
        assert!(rpr.is_italic());
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_rpr_underline() {
        let mut rpr = make_run_properties();
        assert!(!rpr.is_underline());
        assert!(rpr.underline_style().is_none());

        rpr.underline = Some(Box::new(types::CTUnderline {
            value: Some(types::STUnderline::Single),
            color: None,
            theme_color: None,
            theme_tint: None,
            theme_shade: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        assert!(rpr.is_underline());
        assert_eq!(rpr.underline_style(), Some(&types::STUnderline::Single));

        // "none" underline should not count as underlined
        rpr.underline = Some(Box::new(types::CTUnderline {
            value: Some(types::STUnderline::None),
            color: None,
            theme_color: None,
            theme_tint: None,
            theme_shade: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        assert!(!rpr.is_underline());
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_rpr_strikethrough() {
        let mut rpr = make_run_properties();
        rpr.strikethrough = on_off(None);
        assert!(rpr.is_strikethrough());
        assert!(!rpr.is_double_strikethrough());

        rpr.strikethrough = None;
        rpr.dstrike = on_off(Some("1"));
        assert!(!rpr.is_strikethrough());
        assert!(rpr.is_double_strikethrough());
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_rpr_caps_hidden() {
        let mut rpr = make_run_properties();
        rpr.caps = on_off(None);
        rpr.vanish = on_off(Some("1"));
        assert!(rpr.is_all_caps());
        assert!(!rpr.is_small_caps());
        assert!(rpr.is_hidden());
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_rpr_font_size() {
        let mut rpr = make_run_properties();
        assert!(rpr.font_size_half_points().is_none());

        rpr.size = Some(Box::new(types::HpsMeasureElement {
            value: "24".to_string(),
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        assert_eq!(rpr.font_size_half_points(), Some(24));
        assert_eq!(rpr.font_size_points(), Some(12.0));
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_rpr_color() {
        let mut rpr = make_run_properties();
        assert!(rpr.color_hex().is_none());

        rpr.color = Some(Box::new(types::CTColor {
            value: "FF0000".to_string(),
            theme_color: None,
            theme_tint: None,
            theme_shade: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        assert_eq!(rpr.color_hex(), Some("FF0000"));
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_rpr_vertical_alignment() {
        let mut rpr = make_run_properties();
        assert!(!rpr.is_superscript());
        assert!(!rpr.is_subscript());

        rpr.vert_align = Some(Box::new(types::CTVerticalAlignRun {
            value: types::STVerticalAlignRun::Superscript,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        assert!(rpr.is_superscript());
        assert!(!rpr.is_subscript());
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_rpr_font_ascii() {
        let mut rpr = make_run_properties();
        assert!(rpr.font_ascii().is_none());

        rpr.fonts = Some(Box::new(types::Fonts {
            hint: None,
            ascii: Some("Arial".to_string()),
            h_ansi: None,
            east_asia: None,
            cs: None,
            ascii_theme: None,
            h_ansi_theme: None,
            east_asia_theme: None,
            cstheme: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        assert_eq!(rpr.font_ascii(), Some("Arial"));
    }

    // -------------------------------------------------------------------------
    // RunExt tests
    // -------------------------------------------------------------------------

    fn make_text(s: &str) -> types::RunContent {
        types::RunContent::T(Box::new(types::Text {
            text: Some(s.to_string()),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }))
    }

    fn make_tab() -> types::RunContent {
        types::RunContent::Tab(Box::new(types::CTEmpty))
    }

    fn make_br(br_type: Option<types::STBrType>) -> types::RunContent {
        types::RunContent::Br(Box::new(types::CTBr {
            r#type: br_type,
            clear: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }))
    }

    fn make_cr() -> types::RunContent {
        types::RunContent::Cr(Box::new(types::CTEmpty))
    }

    fn make_run(content: Vec<types::RunContent>) -> types::Run {
        types::Run {
            rsid_r_pr: None,
            rsid_del: None,
            rsid_r: None,
            #[cfg(feature = "wml-styling")]
            r_pr: None,
            run_content: content,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }
    }

    #[test]
    fn test_run_text_simple() {
        let run = make_run(vec![make_text("Hello"), make_text(" World")]);
        assert_eq!(run.text(), "Hello World");
    }

    #[test]
    fn test_run_text_with_tab_and_break() {
        let run = make_run(vec![
            make_text("A"),
            make_tab(),
            make_text("B"),
            make_br(None), // text wrapping break → newline
            make_text("C"),
        ]);
        assert_eq!(run.text(), "A\tB\nC");
    }

    #[test]
    fn test_run_text_page_break_not_text() {
        let run = make_run(vec![
            make_text("Before"),
            make_br(Some(types::STBrType::Page)),
            make_text("After"),
        ]);
        // Page breaks should not produce text
        assert_eq!(run.text(), "BeforeAfter");
        assert!(run.has_page_break());
    }

    #[test]
    fn test_run_text_cr() {
        let run = make_run(vec![make_text("A"), make_cr(), make_text("B")]);
        assert_eq!(run.text(), "A\nB");
    }

    #[test]
    fn test_run_no_page_break() {
        let run = make_run(vec![make_text("Hello")]);
        assert!(!run.has_page_break());
    }

    // -------------------------------------------------------------------------
    // ParagraphExt tests
    // -------------------------------------------------------------------------

    fn make_p_run(text: &str) -> types::ParagraphContent {
        types::ParagraphContent::R(Box::new(make_run(vec![make_text(text)])))
    }

    fn make_paragraph(content: Vec<types::ParagraphContent>) -> types::Paragraph {
        types::Paragraph {
            rsid_r_pr: None,
            rsid_r: None,
            rsid_del: None,
            rsid_p: None,
            rsid_r_default: None,
            #[cfg(feature = "wml-styling")]
            p_pr: None,
            paragraph_content: content,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }
    }

    #[test]
    fn test_paragraph_runs_and_text() {
        let para = make_paragraph(vec![make_p_run("Hello "), make_p_run("World")]);
        assert_eq!(para.runs().len(), 2);
        assert_eq!(para.text(), "Hello World");
    }

    #[test]
    fn test_paragraph_with_hyperlink() {
        let hyperlink = types::ParagraphContent::Hyperlink(Box::new(types::Hyperlink {
            id: None,
            tgt_frame: None,
            tooltip: None,
            doc_location: None,
            history: None,
            anchor: Some("bookmark1".to_string()),
            paragraph_content: vec![make_p_run("link text")],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }));
        let para = make_paragraph(vec![make_p_run("Click "), hyperlink]);
        assert_eq!(para.runs().len(), 2);
        assert_eq!(para.text(), "Click link text");
        assert_eq!(para.hyperlinks().len(), 1);
        assert_eq!(para.hyperlinks()[0].anchor_str(), Some("bookmark1"));
    }

    #[test]
    fn test_paragraph_with_fld_simple() {
        let fld = types::ParagraphContent::FldSimple(Box::new(types::CTSimpleField {
            instr: "PAGE".to_string(),
            fld_lock: None,
            dirty: None,
            fld_data: None,
            paragraph_content: vec![make_p_run("1")],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }));
        let para = make_paragraph(vec![make_p_run("Page "), fld]);
        assert_eq!(para.runs().len(), 2);
        assert_eq!(para.text(), "Page 1");
    }

    // -------------------------------------------------------------------------
    // BodyExt tests
    // -------------------------------------------------------------------------

    fn make_body(content: Vec<types::BlockContent>) -> types::Body {
        types::Body {
            block_content: content,
            #[cfg(feature = "wml-layout")]
            sect_pr: None,
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }
    }

    #[test]
    fn test_body_paragraphs() {
        let p1 = types::BlockContent::P(Box::new(make_paragraph(vec![make_p_run("First")])));
        let p2 = types::BlockContent::P(Box::new(make_paragraph(vec![make_p_run("Second")])));
        let body = make_body(vec![p1, p2]);
        assert_eq!(body.paragraphs().len(), 2);
        assert_eq!(body.text(), "First\nSecond");
    }

    #[test]
    fn test_body_tables() {
        let tbl = types::BlockContent::Tbl(Box::new(types::Table {
            range_markup: vec![],
            table_properties: Box::default(),
            tbl_grid: Box::default(),
            rows: vec![],
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }));
        let body = make_body(vec![tbl]);
        assert_eq!(body.tables().len(), 1);
        assert_eq!(body.paragraphs().len(), 0);
    }

    // -------------------------------------------------------------------------
    // DocumentExt tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_document_ext_body() {
        let doc = types::Document {
            background: None,
            body: Some(Box::new(make_body(vec![]))),
            conformance: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };
        assert!(doc.body().is_some());

        let doc_no_body = types::Document {
            background: None,
            body: None,
            conformance: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };
        assert!(doc_no_body.body().is_none());
    }

    // -------------------------------------------------------------------------
    // HyperlinkExt tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_hyperlink_ext() {
        let h = types::Hyperlink {
            id: None,
            tgt_frame: None,
            tooltip: None,
            doc_location: None,
            history: None,
            anchor: Some("top".to_string()),
            paragraph_content: vec![make_p_run("click"), make_p_run(" here")],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };
        assert_eq!(h.runs().len(), 2);
        assert_eq!(h.text(), "click here");
        assert_eq!(h.anchor_str(), Some("top"));
    }

    // -------------------------------------------------------------------------
    // Table/Row/Cell tests
    // -------------------------------------------------------------------------

    fn make_table_cell(text: &str) -> types::CellContent {
        types::CellContent::Tc(Box::new(types::TableCell {
            id: None,
            cell_properties: None,
            block_content: vec![types::BlockContent::P(Box::new(make_paragraph(vec![
                make_p_run(text),
            ])))],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }))
    }

    fn make_table_row(cells: Vec<types::CellContent>) -> types::RowContent {
        types::RowContent::Tr(Box::new(types::CTRow {
            rsid_r_pr: None,
            rsid_r: None,
            rsid_del: None,
            rsid_tr: None,
            tbl_pr_ex: None,
            row_properties: None,
            cells,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }))
    }

    fn make_table(rows: Vec<types::RowContent>) -> types::Table {
        types::Table {
            range_markup: vec![],
            table_properties: Box::default(),
            tbl_grid: Box::default(),
            rows,
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }
    }

    #[test]
    fn test_table_rows_and_text() {
        let tbl = make_table(vec![
            make_table_row(vec![make_table_cell("A1"), make_table_cell("B1")]),
            make_table_row(vec![make_table_cell("A2"), make_table_cell("B2")]),
        ]);
        assert_eq!(tbl.row_count(), 2);
        assert_eq!(tbl.rows().len(), 2);
        assert_eq!(tbl.text(), "A1\tB1\nA2\tB2");
    }

    #[test]
    fn test_row_cells_and_text() {
        let row = types::CTRow {
            rsid_r_pr: None,
            rsid_r: None,
            rsid_del: None,
            rsid_tr: None,
            tbl_pr_ex: None,
            row_properties: None,
            cells: vec![make_table_cell("X"), make_table_cell("Y")],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };
        assert_eq!(row.cells().len(), 2);
        assert_eq!(row.text(), "X\tY");
    }

    #[test]
    fn test_cell_paragraphs_and_text() {
        let cell = types::TableCell {
            id: None,
            cell_properties: None,
            block_content: vec![
                types::BlockContent::P(Box::new(make_paragraph(vec![make_p_run("Line 1")]))),
                types::BlockContent::P(Box::new(make_paragraph(vec![make_p_run("Line 2")]))),
            ],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };
        assert_eq!(cell.paragraphs().len(), 2);
        assert_eq!(cell.text(), "Line 1\nLine 2");
    }

    // -------------------------------------------------------------------------
    // SectionPropertiesExt tests
    // -------------------------------------------------------------------------

    #[test]
    #[cfg(feature = "wml-layout")]
    fn test_section_properties_ext() {
        let sect_pr = types::SectionProperties {
            rsid_r_pr: None,
            rsid_del: None,
            rsid_r: None,
            rsid_sect: None,
            header_footer_refs: vec![],
            footnote_pr: None,
            endnote_pr: None,
            r#type: None,
            pg_sz: Some(Box::new(types::PageSize {
                width: Some("12240".to_string()),
                height: Some("15840".to_string()),
                orient: Some(types::STPageOrientation::Portrait),
                code: None,
                #[cfg(feature = "extra-attrs")]
                extra_attrs: Default::default(),
            })),
            pg_mar: Some(Box::new(types::PageMargins {
                top: "1440".to_string(),
                right: "1440".to_string(),
                bottom: "1440".to_string(),
                left: "1440".to_string(),
                header: "720".to_string(),
                footer: "720".to_string(),
                gutter: "0".to_string(),
                #[cfg(feature = "extra-attrs")]
                extra_attrs: Default::default(),
            })),
            paper_src: None,
            pg_borders: None,
            ln_num_type: None,
            pg_num_type: None,
            cols: None,
            form_prot: None,
            v_align: None,
            no_endnote: None,
            title_pg: on_off(None),
            text_direction: None,
            bidi: None,
            rtl_gutter: None,
            doc_grid: None,
            printer_settings: None,
            sect_pr_change: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };

        assert_eq!(sect_pr.page_width_twips(), Some(12240));
        assert_eq!(sect_pr.page_height_twips(), Some(15840));
        assert_eq!(
            sect_pr.page_orientation(),
            Some(&types::STPageOrientation::Portrait)
        );
        assert!(sect_pr.has_title_page());
        assert!(sect_pr.page_size().is_some());
        assert!(sect_pr.page_margins().is_some());
    }

    // -------------------------------------------------------------------------
    // Parsing tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_parse_document_simple() {
        // Generated parsers match on unprefixed element names, so use default namespace
        let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
        <document xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <body>
                <p>
                    <r>
                        <t>Hello World</t>
                    </r>
                </p>
            </body>
        </document>"#;

        let doc = parse_document(xml).expect("parse_document failed");
        let body = doc.body().expect("body should exist");
        let paragraphs = body.paragraphs();
        assert_eq!(paragraphs.len(), 1);
        assert_eq!(paragraphs[0].text(), "Hello World");
    }

    #[test]
    fn test_parse_document_multiple_paragraphs() {
        let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
        <document xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <body>
                <p>
                    <r><t>First</t></r>
                </p>
                <p>
                    <r><t>Second</t></r>
                </p>
            </body>
        </document>"#;

        let doc = parse_document(xml).expect("parse failed");
        let body = doc.body().expect("body");
        assert_eq!(body.paragraphs().len(), 2);
        assert_eq!(body.text(), "First\nSecond");
    }

    #[test]
    fn test_parse_styles_basic() {
        let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
        <styles xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <style type="character" styleId="BoldStyle">
                <name val="Bold Style"/>
                <rPr>
                    <b/>
                </rPr>
            </style>
        </styles>"#;

        let styles = parse_styles(xml).expect("parse_styles failed");
        assert_eq!(styles.style.len(), 1);
        assert_eq!(styles.style[0].style_id.as_deref(), Some("BoldStyle"));
    }

    #[test]
    fn test_parse_document_no_element() {
        let xml = br#"<?xml version="1.0" encoding="UTF-8"?>"#;
        assert!(parse_document(xml).is_err());
    }

    // -------------------------------------------------------------------------
    // StyleContext + RunResolveExt tests
    // -------------------------------------------------------------------------

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_style_context_from_styles() {
        let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
        <styles xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <docDefaults>
                <rPrDefault>
                    <rPr>
                        <sz val="24"/>
                    </rPr>
                </rPrDefault>
            </docDefaults>
            <style type="character" styleId="Strong">
                <name val="Strong"/>
                <rPr>
                    <b/>
                </rPr>
            </style>
        </styles>"#;

        let styles = parse_styles(xml).expect("parse");
        let ctx = StyleContext::from_styles(&styles);

        assert!(ctx.style("Strong").is_some());
        assert!(ctx.style("Nonexistent").is_none());
        assert!(ctx.default_run_properties.is_some());
        assert_eq!(
            ctx.default_run_properties
                .as_ref()
                .unwrap()
                .font_size_half_points(),
            Some(24)
        );
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_resolve_bold_from_direct() {
        let run = types::Run {
            rsid_r_pr: None,
            rsid_del: None,
            rsid_r: None,
            r_pr: Some(Box::new({
                let mut rpr = make_run_properties();
                rpr.bold = on_off(None);
                rpr
            })),
            run_content: vec![make_text("bold")],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };

        let ctx = StyleContext::default();
        assert!(run.resolved_is_bold(&ctx));
        assert!(!run.resolved_is_italic(&ctx));
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_resolve_bold_from_style_chain() {
        // Set up: run references style "Emphasis" which is basedOn "Strong" which has bold
        let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
        <styles xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <style type="character" styleId="Strong">
                <name val="Strong"/>
                <rPr>
                    <b/>
                    <sz val="28"/>
                </rPr>
            </style>
            <style type="character" styleId="Emphasis">
                <name val="Emphasis"/>
                <basedOn val="Strong"/>
                <rPr>
                    <i/>
                </rPr>
            </style>
        </styles>"#;

        let styles = parse_styles(xml).expect("parse");
        let ctx = StyleContext::from_styles(&styles);

        // Run references "Emphasis" style (which has italic, inherits bold from Strong)
        let run = types::Run {
            rsid_r_pr: None,
            rsid_del: None,
            rsid_r: None,
            r_pr: Some(Box::new({
                let mut rpr = make_run_properties();
                rpr.run_style = Some(Box::new(types::CTString {
                    value: "Emphasis".to_string(),
                    #[cfg(feature = "extra-attrs")]
                    extra_attrs: Default::default(),
                }));
                rpr
            })),
            run_content: vec![make_text("styled")],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };

        assert!(run.resolved_is_bold(&ctx));
        assert!(run.resolved_is_italic(&ctx));
        assert_eq!(run.resolved_font_size_half_points(&ctx), Some(28));
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_resolve_from_doc_defaults() {
        let xml = br#"<?xml version="1.0" encoding="UTF-8"?>
        <styles xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <docDefaults>
                <rPrDefault>
                    <rPr>
                        <sz val="22"/>
                        <rFonts ascii="Calibri"/>
                    </rPr>
                </rPrDefault>
            </docDefaults>
        </styles>"#;

        let styles = parse_styles(xml).expect("parse");
        let ctx = StyleContext::from_styles(&styles);

        // Run with no direct properties or style reference
        let run = types::Run {
            rsid_r_pr: None,
            rsid_del: None,
            rsid_r: None,
            r_pr: None,
            run_content: vec![make_text("default")],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };

        assert!(!run.resolved_is_bold(&ctx));
        assert_eq!(run.resolved_font_size_half_points(&ctx), Some(22));
        assert_eq!(run.resolved_font_ascii(&ctx), Some("Calibri".to_string()));
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_resolved_document() {
        let doc_xml = br#"<?xml version="1.0" encoding="UTF-8"?>
        <document xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <body>
                <p>
                    <r>
                        <rPr><b/></rPr>
                        <t>Bold text</t>
                    </r>
                </p>
            </body>
        </document>"#;

        let styles_xml = br#"<?xml version="1.0" encoding="UTF-8"?>
        <styles xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
        </styles>"#;

        let doc = parse_document(doc_xml).expect("parse doc");
        let styles = parse_styles(styles_xml).expect("parse styles");
        let resolved = ResolvedDocument::new(doc, styles);

        assert_eq!(resolved.text(), "Bold text");

        let body = resolved.body().expect("body");
        let paras = body.paragraphs();
        let runs = paras[0].runs();
        assert!(resolved.is_bold(runs[0]));
        assert!(!resolved.is_italic(runs[0]));
    }

    // -------------------------------------------------------------------------
    // DrawingChartExt tests
    // -------------------------------------------------------------------------

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_drawing_chart_rel_ids() {
        use super::DrawingChartExt;
        use ooxml_xml::{PositionedNode, RawXmlElement, RawXmlNode};

        // Build: wp:anchor → a:graphic → a:graphicData → c:chart r:id="rId5"
        let chart = RawXmlElement {
            name: "c:chart".to_string(),
            attributes: vec![("r:id".to_string(), "rId5".to_string())],
            children: vec![],
            self_closing: true,
        };
        let graphic_data = RawXmlElement {
            name: "a:graphicData".to_string(),
            attributes: vec![(
                "uri".to_string(),
                "http://schemas.openxmlformats.org/drawingml/2006/chart".to_string(),
            )],
            children: vec![RawXmlNode::Element(chart)],
            self_closing: false,
        };
        let graphic = RawXmlElement {
            name: "a:graphic".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(graphic_data)],
            self_closing: false,
        };
        let anchor = RawXmlElement {
            name: "wp:anchor".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(graphic)],
            self_closing: false,
        };

        let drawing = types::CTDrawing {
            extra_children: vec![PositionedNode::new(0, RawXmlNode::Element(anchor))],
        };

        let ids = drawing.all_chart_rel_ids();
        assert_eq!(ids, vec!["rId5"]);

        // anchored_chart_rel_ids should also return it
        assert_eq!(drawing.anchored_chart_rel_ids(), vec!["rId5"]);
        // inline should be empty
        assert!(drawing.inline_chart_rel_ids().is_empty());
    }

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_drawing_no_charts() {
        use super::DrawingChartExt;
        use ooxml_xml::{PositionedNode, RawXmlElement, RawXmlNode};

        // Build an anchor with a blip (image), but no chart
        let blip = RawXmlElement {
            name: "a:blip".to_string(),
            attributes: vec![("r:embed".to_string(), "rId1".to_string())],
            children: vec![],
            self_closing: true,
        };
        let anchor = RawXmlElement {
            name: "wp:anchor".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(blip)],
            self_closing: false,
        };

        let drawing = types::CTDrawing {
            extra_children: vec![PositionedNode::new(0, RawXmlNode::Element(anchor))],
        };

        assert!(drawing.all_chart_rel_ids().is_empty());
    }

    // -------------------------------------------------------------------------
    // DrawingTextBoxExt tests
    // -------------------------------------------------------------------------

    /// Build a minimal `CTDrawing` whose `extra_children` contains a `<wp:anchor>`
    /// that holds a `<w:txbxContent>` with the given paragraph text.
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn make_drawing_with_textbox(text: &str) -> types::CTDrawing {
        use ooxml_xml::{PositionedNode, RawXmlElement, RawXmlNode};

        // Build the element tree bottom-up:
        // <wp:anchor>
        //   <wps:wsp>
        //     <wps:txbx>
        //       <w:txbxContent>
        //         <w:p>
        //           <w:r>
        //             <w:t>text</w:t>
        //           </w:r>
        //         </w:p>
        //       </w:txbxContent>
        //     </wps:txbx>
        //   </wps:wsp>
        // </wp:anchor>

        let t = RawXmlElement {
            name: "w:t".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Text(text.to_string())],
            self_closing: false,
        };
        let r = RawXmlElement {
            name: "w:r".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(t)],
            self_closing: false,
        };
        let p = RawXmlElement {
            name: "w:p".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(r)],
            self_closing: false,
        };
        let txbx_content = RawXmlElement {
            name: "w:txbxContent".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(p)],
            self_closing: false,
        };
        let txbx = RawXmlElement {
            name: "wps:txbx".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(txbx_content)],
            self_closing: false,
        };
        let wsp = RawXmlElement {
            name: "wps:wsp".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(txbx)],
            self_closing: false,
        };
        let anchor = RawXmlElement {
            name: "wp:anchor".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(wsp)],
            self_closing: false,
        };

        types::CTDrawing {
            extra_children: vec![PositionedNode::new(0, RawXmlNode::Element(anchor))],
        }
    }

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_drawing_text_box_texts_single() {
        use super::DrawingTextBoxExt;
        let drawing = make_drawing_with_textbox("Hello from text box");
        let texts = drawing.text_box_texts();
        assert_eq!(texts.len(), 1);
        assert_eq!(texts[0], "Hello from text box");
    }

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_drawing_text_box_texts_empty() {
        use super::DrawingTextBoxExt;
        let drawing = types::CTDrawing {
            extra_children: vec![],
        };
        let texts = drawing.text_box_texts();
        assert!(texts.is_empty());
    }

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_drawing_text_box_texts_multiple() {
        use super::DrawingTextBoxExt;
        use ooxml_xml::{PositionedNode, RawXmlElement, RawXmlNode};

        // Build two anchors each with a text box.
        fn make_anchor(text: &str) -> RawXmlElement {
            let t = RawXmlElement {
                name: "w:t".to_string(),
                attributes: vec![],
                children: vec![RawXmlNode::Text(text.to_string())],
                self_closing: false,
            };
            let r = RawXmlElement {
                name: "w:r".to_string(),
                attributes: vec![],
                children: vec![RawXmlNode::Element(t)],
                self_closing: false,
            };
            let p = RawXmlElement {
                name: "w:p".to_string(),
                attributes: vec![],
                children: vec![RawXmlNode::Element(r)],
                self_closing: false,
            };
            let txbx_content = RawXmlElement {
                name: "w:txbxContent".to_string(),
                attributes: vec![],
                children: vec![RawXmlNode::Element(p)],
                self_closing: false,
            };
            RawXmlElement {
                name: "wp:anchor".to_string(),
                attributes: vec![],
                children: vec![RawXmlNode::Element(txbx_content)],
                self_closing: false,
            }
        }

        let drawing = types::CTDrawing {
            extra_children: vec![
                PositionedNode::new(0, RawXmlNode::Element(make_anchor("First box"))),
                PositionedNode::new(1, RawXmlNode::Element(make_anchor("Second box"))),
            ],
        };

        let texts = drawing.text_box_texts();
        assert_eq!(texts.len(), 2);
        assert_eq!(texts[0], "First box");
        assert_eq!(texts[1], "Second box");
    }

    // -------------------------------------------------------------------------
    // PictExt tests (VML text boxes)
    // -------------------------------------------------------------------------

    /// Build a minimal `CTPicture` whose `extra_children` contains a `<v:shape>`
    /// that holds a `<v:textbox>` which holds a `<w:txbxContent>`.
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn make_pict_with_textbox(text: &str) -> types::CTPicture {
        use ooxml_xml::{PositionedNode, RawXmlElement, RawXmlNode};

        let t = RawXmlElement {
            name: "w:t".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Text(text.to_string())],
            self_closing: false,
        };
        let r = RawXmlElement {
            name: "w:r".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(t)],
            self_closing: false,
        };
        let p = RawXmlElement {
            name: "w:p".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(r)],
            self_closing: false,
        };
        let txbx_content = RawXmlElement {
            name: "w:txbxContent".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(p)],
            self_closing: false,
        };
        let textbox = RawXmlElement {
            name: "v:textbox".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(txbx_content)],
            self_closing: false,
        };
        let shape = RawXmlElement {
            name: "v:shape".to_string(),
            attributes: vec![("id".to_string(), "TextBox1".to_string())],
            children: vec![RawXmlNode::Element(textbox)],
            self_closing: false,
        };

        types::CTPicture {
            #[cfg(feature = "wml-drawings")]
            movie: None,
            #[cfg(feature = "wml-drawings")]
            control: None,
            extra_children: vec![PositionedNode::new(0, RawXmlNode::Element(shape))],
        }
    }

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_pict_text_box_text() {
        use super::PictExt;
        let pict = make_pict_with_textbox("VML text box content");
        assert_eq!(
            pict.text_box_text(),
            Some("VML text box content".to_string())
        );
    }

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_pict_text_box_text_none_when_empty() {
        use super::PictExt;
        let pict = types::CTPicture {
            #[cfg(feature = "wml-drawings")]
            movie: None,
            #[cfg(feature = "wml-drawings")]
            control: None,
            extra_children: vec![],
        };
        assert_eq!(pict.text_box_text(), None);
    }

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_pict_text_box_texts() {
        use super::PictExt;
        let pict = make_pict_with_textbox("Hello");
        let texts = pict.text_box_texts();
        assert_eq!(texts.len(), 1);
        assert_eq!(texts[0], "Hello");
    }

    #[test]
    #[cfg(all(feature = "wml-drawings", feature = "extra-children"))]
    fn test_drawing_text_box_via_xml_parse() {
        // Integration test: build the drawing from raw XML, then extract text.
        use super::DrawingTextBoxExt;

        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<document xmlns="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
          xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
          xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">
  <body>
    <p>
      <r>
        <drawing>
          <wp:anchor>
            <wps:wsp>
              <wps:txbx>
                <txbxContent>
                  <p><r><t>Anchored box text</t></r></p>
                </txbxContent>
              </wps:txbx>
            </wps:wsp>
          </wp:anchor>
        </drawing>
      </r>
    </p>
  </body>
</document>"#;

        let doc = parse_document(xml.as_bytes()).expect("parse");
        let body = doc.body().expect("body");
        let paras = body.paragraphs();
        assert!(!paras.is_empty());

        let run = &paras[0].runs()[0];
        let drawings = run.drawings();
        assert_eq!(drawings.len(), 1);

        let texts = drawings[0].text_box_texts();
        assert_eq!(texts.len(), 1);
        assert_eq!(texts[0], "Anchored box text");
    }

    // =========================================================================
    // TOC tests
    // =========================================================================

    /// Build a minimal paragraph XML with the given style name and run text.
    #[cfg(feature = "wml-styling")]
    fn toc_para_xml(style: &str, text: &str) -> String {
        format!(
            r#"<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:pPr><w:pStyle w:val="{style}"/></w:pPr>
  <w:r><w:t>{text}</w:t></w:r>
</w:p>"#,
        )
    }

    /// Build a document XML with the given body XML (pre-formatted).
    #[cfg(feature = "wml-styling")]
    fn doc_with_body(body_inner: &str) -> String {
        format!(
            r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:body>
    {body_inner}
  </w:body>
</w:document>"#,
        )
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_toc_no_entries() {
        // A body with no TOC-style paragraphs returns an empty vec.
        let xml = doc_with_body(
            r#"<w:p><w:pPr><w:pStyle w:val="Normal"/></w:pPr><w:r><w:t>Hello</w:t></w:r></w:p>"#,
        );
        let doc = parse_document(xml.as_bytes()).expect("parse");
        let body = doc.body().expect("body");
        let tocs = body.table_of_contents();
        assert!(tocs.is_empty(), "expected no TOCs, got: {tocs:?}");
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_toc_levels() {
        // Three consecutive TOC-style paragraphs form a single TOC with correct levels.
        let p1 = toc_para_xml("TOC 1", "Chapter One");
        let p2 = toc_para_xml("TOC 2", "Section 1.1");
        let p3 = toc_para_xml("TOC 3", "Subsection 1.1.1");
        let xml = doc_with_body(&format!("{p1}{p2}{p3}"));
        let doc = parse_document(xml.as_bytes()).expect("parse");
        let body = doc.body().expect("body");
        let tocs = body.table_of_contents();
        assert_eq!(tocs.len(), 1);
        let toc = &tocs[0];
        assert_eq!(toc.entries.len(), 3);
        assert_eq!(toc.entries[0].level, 1);
        assert_eq!(toc.entries[0].text, "Chapter One");
        assert_eq!(toc.entries[1].level, 2);
        assert_eq!(toc.entries[1].text, "Section 1.1");
        assert_eq!(toc.entries[2].level, 3);
        assert_eq!(toc.entries[2].text, "Subsection 1.1.1");
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_toc_style_id_form() {
        // Style IDs "toc1"/"toc2" (no space) are also recognised.
        let p1 = toc_para_xml("toc1", "First");
        let p2 = toc_para_xml("toc2", "Second");
        let xml = doc_with_body(&format!("{p1}{p2}"));
        let doc = parse_document(xml.as_bytes()).expect("parse");
        let body = doc.body().expect("body");
        let tocs = body.table_of_contents();
        assert_eq!(tocs.len(), 1);
        assert_eq!(tocs[0].entries[0].level, 1);
        assert_eq!(tocs[0].entries[1].level, 2);
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_toc_entry_from_sdt() {
        // TOC entries inside an SDT block are extracted as a separate TableOfContents.
        let xml = doc_with_body(
            r#"<w:sdt xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:sdtContent>
    <w:p><w:pPr><w:pStyle w:val="TOC 1"/></w:pPr><w:r><w:t>Alpha</w:t></w:r></w:p>
    <w:p><w:pPr><w:pStyle w:val="TOC 2"/></w:pPr><w:r><w:t>Beta</w:t></w:r></w:p>
  </w:sdtContent>
</w:sdt>"#,
        );
        let doc = parse_document(xml.as_bytes()).expect("parse");
        let body = doc.body().expect("body");
        let tocs = body.table_of_contents();
        assert_eq!(tocs.len(), 1, "expected 1 TOC from SDT, got: {tocs:?}");
        assert_eq!(tocs[0].entries.len(), 2);
        assert_eq!(tocs[0].entries[0].level, 1);
        assert_eq!(tocs[0].entries[0].text, "Alpha");
        assert_eq!(tocs[0].entries[1].level, 2);
        assert_eq!(tocs[0].entries[1].text, "Beta");
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_toc_page_number_extraction() {
        // A page number after a tab stop is extracted as `page`.
        let xml = doc_with_body(
            r#"<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:pPr><w:pStyle w:val="TOC 1"/></w:pPr>
  <w:r><w:t>My Chapter</w:t></w:r>
  <w:r><w:tab/></w:r>
  <w:r><w:t>42</w:t></w:r>
</w:p>"#,
        );
        let doc = parse_document(xml.as_bytes()).expect("parse");
        let body = doc.body().expect("body");
        let tocs = body.table_of_contents();
        assert_eq!(tocs.len(), 1);
        let entry = &tocs[0].entries[0];
        assert_eq!(entry.text, "My Chapter");
        assert_eq!(entry.page, Some(42));
    }

    #[test]
    #[cfg(feature = "wml-styling")]
    fn test_toc_non_toc_para_splits_groups() {
        // A non-TOC paragraph between two TOC runs produces two separate TOCs.
        let p1 = toc_para_xml("TOC 1", "First TOC entry");
        let normal = r#"<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:pPr><w:pStyle w:val="Normal"/></w:pPr>
  <w:r><w:t>Regular text</w:t></w:r>
</w:p>"#;
        let p2 = toc_para_xml("TOC 1", "Second TOC entry");
        let xml = doc_with_body(&format!("{p1}{normal}{p2}"));
        let doc = parse_document(xml.as_bytes()).expect("parse");
        let body = doc.body().expect("body");
        let tocs = body.table_of_contents();
        assert_eq!(tocs.len(), 2, "expected 2 separate TOCs");
        assert_eq!(tocs[0].entries[0].text, "First TOC entry");
        assert_eq!(tocs[1].entries[0].text, "Second TOC entry");
    }

    // -------------------------------------------------------------------------
    // RevisionExt / BodyRevisionExt tests
    // -------------------------------------------------------------------------

    /// Build a paragraph with an `<w:ins>` wrapping a run with `text`, plus an
    /// additional normal run with `suffix`.
    #[cfg(feature = "wml-track-changes")]
    fn make_para_with_ins(ins_text: &str, suffix: &str) -> types::Paragraph {
        use crate::convenience::ins_run;
        let mut para = types::Paragraph::default();
        para.paragraph_content
            .push(ins_run(1, "Alice", Some("2026-01-01T00:00:00Z"), ins_text));
        // Normal run
        let t = types::Text {
            text: Some(suffix.to_string()),
            #[cfg(feature = "extra-children")]
            extra_children: Vec::new(),
        };
        let run = types::Run {
            #[cfg(feature = "wml-track-changes")]
            rsid_r_pr: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_del: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r: None,
            #[cfg(feature = "wml-styling")]
            r_pr: None,
            run_content: vec![types::RunContent::T(Box::new(t))],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Vec::new(),
        };
        para.paragraph_content
            .push(types::ParagraphContent::R(Box::new(run)));
        para
    }

    /// Build a paragraph with a `<w:del>` wrapping a run with `del_text`, plus a
    /// normal run with `suffix`.
    #[cfg(feature = "wml-track-changes")]
    fn make_para_with_del(del_text: &str, suffix: &str) -> types::Paragraph {
        use crate::convenience::del_run;
        let mut para = types::Paragraph::default();
        para.paragraph_content
            .push(del_run(2, "Bob", None, del_text));
        let t = types::Text {
            text: Some(suffix.to_string()),
            #[cfg(feature = "extra-children")]
            extra_children: Vec::new(),
        };
        let run = types::Run {
            #[cfg(feature = "wml-track-changes")]
            rsid_r_pr: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_del: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r: None,
            #[cfg(feature = "wml-styling")]
            r_pr: None,
            run_content: vec![types::RunContent::T(Box::new(t))],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Vec::new(),
        };
        para.paragraph_content
            .push(types::ParagraphContent::R(Box::new(run)));
        para
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_track_changes_accepted_text() {
        use super::RevisionExt;
        // Ins("hello") + Run(" world") → accepted = "hello world"
        let para = make_para_with_ins("hello", " world");
        assert_eq!(para.accepted_text(), "hello world");
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_track_changes_rejected_text() {
        use super::RevisionExt;
        // Del("old") + Run(" word") → rejected = "old word"
        let para = make_para_with_del("old", " word");
        assert_eq!(para.rejected_text(), "old word");
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_track_changes_accepted_text_excludes_deletions() {
        use super::RevisionExt;
        // Del("old") + Run(" word") → accepted = " word" (deletion excluded)
        let para = make_para_with_del("old", " word");
        assert_eq!(para.accepted_text(), " word");
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_track_changes_rejected_text_excludes_insertions() {
        use super::RevisionExt;
        // Ins("hello") + Run(" world") → rejected = " world" (insertion excluded)
        let para = make_para_with_ins("hello", " world");
        assert_eq!(para.rejected_text(), " world");
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_has_track_changes() {
        use super::RevisionExt;
        let para_with = make_para_with_ins("text", "");
        assert!(para_with.has_track_changes());

        // A plain paragraph with no tracked changes
        let plain = types::Paragraph::default();
        assert!(!plain.has_track_changes());
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_track_changes_list() {
        use super::{RevisionExt, TrackChangeType};
        let para = make_para_with_ins("hello", " world");
        let changes = para.track_changes();
        assert_eq!(changes.len(), 1);
        let tc = &changes[0];
        assert_eq!(tc.id, 1);
        assert_eq!(tc.author, "Alice");
        assert_eq!(tc.date.as_deref(), Some("2026-01-01T00:00:00Z"));
        assert_eq!(tc.change_type, TrackChangeType::Insertion);
        assert_eq!(tc.text, "hello");
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_track_changes_deletion_list() {
        use super::{RevisionExt, TrackChangeType};
        let para = make_para_with_del("old", " text");
        let changes = para.track_changes();
        assert_eq!(changes.len(), 1);
        let tc = &changes[0];
        assert_eq!(tc.id, 2);
        assert_eq!(tc.author, "Bob");
        assert_eq!(tc.date, None);
        assert_eq!(tc.change_type, TrackChangeType::Deletion);
        assert_eq!(tc.text, "old");
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_body_revision_ext_all_track_changes() {
        use super::{BodyRevisionExt, TrackChangeType};
        let para1 = make_para_with_ins("inserted", "");
        let para2 = make_para_with_del("deleted", "");

        let body = types::Body {
            block_content: vec![
                types::BlockContent::P(Box::new(para1)),
                types::BlockContent::P(Box::new(para2)),
            ],
            #[cfg(feature = "wml-layout")]
            sect_pr: None,
            #[cfg(feature = "extra-children")]
            extra_children: Vec::new(),
        };
        let all = body.all_track_changes();
        assert_eq!(all.len(), 2);
        assert_eq!(all[0].change_type, TrackChangeType::Insertion);
        assert_eq!(all[0].text, "inserted");
        assert_eq!(all[1].change_type, TrackChangeType::Deletion);
        assert_eq!(all[1].text, "deleted");
    }

    #[test]
    #[cfg(feature = "wml-track-changes")]
    fn test_body_revision_ext_accepted_text() {
        use super::BodyRevisionExt;
        // Para 1: Ins("hello") + Run(" world")  → accepted = "hello world"
        // Para 2: Del("old") + Run(" text")     → accepted = " text"
        // joined with "\n"
        let para1 = make_para_with_ins("hello", " world");
        let para2 = make_para_with_del("old", " text");

        let body = types::Body {
            block_content: vec![
                types::BlockContent::P(Box::new(para1)),
                types::BlockContent::P(Box::new(para2)),
            ],
            #[cfg(feature = "wml-layout")]
            sect_pr: None,
            #[cfg(feature = "extra-children")]
            extra_children: Vec::new(),
        };
        assert_eq!(body.accepted_text(), "hello world\n text");
    }

    // -------------------------------------------------------------------------
    // FormFieldExt / BodyExt::form_fields tests
    // -------------------------------------------------------------------------

    /// Build a minimal `CTSdtPr` with only alias/tag set.
    #[cfg(feature = "wml-settings")]
    fn make_sdt_pr_base(alias: Option<&str>, tag: Option<&str>) -> types::CTSdtPr {
        types::CTSdtPr {
            r_pr: None,
            alias: alias.map(|s| {
                Box::new(types::CTString {
                    value: s.to_string(),
                    #[cfg(feature = "extra-attrs")]
                    extra_attrs: Default::default(),
                })
            }),
            tag: tag.map(|s| {
                Box::new(types::CTString {
                    value: s.to_string(),
                    #[cfg(feature = "extra-attrs")]
                    extra_attrs: Default::default(),
                })
            }),
            id: None,
            lock: None,
            placeholder: None,
            temporary: None,
            showing_plc_hdr: None,
            data_binding: None,
            label: None,
            tab_index: None,
            equation: None,
            combo_box: None,
            date: None,
            doc_part_obj: None,
            doc_part_list: None,
            drop_down_list: None,
            picture: None,
            rich_text: None,
            text: None,
            citation: None,
            group: None,
            bibliography: None,
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }
    }

    /// Build a `CTSdtRun` containing a run with the given text.
    #[cfg(feature = "wml-settings")]
    fn make_sdt_run(sdt_pr: types::CTSdtPr, value_text: &str) -> types::CTSdtRun {
        let content = types::CTSdtContentRun {
            paragraph_content: vec![types::ParagraphContent::R(Box::new(make_run(vec![
                make_text(value_text),
            ])))],
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };
        types::CTSdtRun {
            sdt_pr: Some(Box::new(sdt_pr)),
            sdt_end_pr: None,
            sdt_content: Some(Box::new(content)),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }
    }

    /// Build a `CTSdtBlock` containing a paragraph with the given text.
    #[cfg(feature = "wml-settings")]
    fn make_sdt_block(sdt_pr: types::CTSdtPr, value_text: &str) -> types::CTSdtBlock {
        let para = make_paragraph(vec![make_p_run(value_text)]);
        let content = types::CTSdtContentBlock {
            block_content: vec![types::BlockContentChoice::P(Box::new(para))],
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };
        types::CTSdtBlock {
            sdt_pr: Some(Box::new(sdt_pr)),
            sdt_end_pr: None,
            sdt_content: Some(Box::new(content)),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_field_plain_text() {
        use super::{FormFieldExt, FormFieldType};
        let mut sdt_pr = make_sdt_pr_base(None, None);
        sdt_pr.text = Some(Box::new(types::CTSdtText {
            multi_line: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        let sdt_run = make_sdt_run(sdt_pr, "my value");
        let field = sdt_run.form_field().expect("should have form field");
        assert_eq!(
            field.field_type,
            FormFieldType::PlainText { multi_line: false }
        );
        assert_eq!(field.current_value, "my value");
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_field_plain_text_multiline() {
        use super::{FormFieldExt, FormFieldType};
        let mut sdt_pr = make_sdt_pr_base(None, None);
        sdt_pr.text = Some(Box::new(types::CTSdtText {
            multi_line: Some("1".to_string()),
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        let sdt_run = make_sdt_run(sdt_pr, "line1");
        let field = sdt_run.form_field().expect("should have form field");
        assert_eq!(
            field.field_type,
            FormFieldType::PlainText { multi_line: true }
        );
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_field_combo_box() {
        use super::{FormFieldExt, FormFieldType};
        let mut sdt_pr = make_sdt_pr_base(None, None);
        sdt_pr.combo_box = Some(Box::new(types::CTSdtComboBox {
            last_value: Some("Option A".to_string()),
            list_item: vec![
                types::CTSdtListItem {
                    display_text: Some("Option A".to_string()),
                    value: Some("a".to_string()),
                    #[cfg(feature = "extra-attrs")]
                    extra_attrs: Default::default(),
                },
                types::CTSdtListItem {
                    display_text: Some("Option B".to_string()),
                    value: Some("b".to_string()),
                    #[cfg(feature = "extra-attrs")]
                    extra_attrs: Default::default(),
                },
            ],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }));
        let sdt_block = make_sdt_block(sdt_pr, "Option A");
        let field = sdt_block.form_field().expect("should have form field");
        match &field.field_type {
            FormFieldType::ComboBox { choices } => {
                assert_eq!(
                    choices,
                    &vec!["Option A".to_string(), "Option B".to_string()]
                );
            }
            other => panic!("expected ComboBox, got {other:?}"),
        }
        assert_eq!(field.current_value, "Option A");
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_field_dropdown() {
        use super::{FormFieldExt, FormFieldType};
        let mut sdt_pr = make_sdt_pr_base(None, None);
        sdt_pr.drop_down_list = Some(Box::new(types::CTSdtDropDownList {
            last_value: None,
            list_item: vec![
                types::CTSdtListItem {
                    display_text: Some("Red".to_string()),
                    value: Some("red".to_string()),
                    #[cfg(feature = "extra-attrs")]
                    extra_attrs: Default::default(),
                },
                types::CTSdtListItem {
                    display_text: Some("Blue".to_string()),
                    value: Some("blue".to_string()),
                    #[cfg(feature = "extra-attrs")]
                    extra_attrs: Default::default(),
                },
            ],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }));
        let sdt_block = make_sdt_block(sdt_pr, "Red");
        let field = sdt_block.form_field().expect("should have form field");
        match &field.field_type {
            FormFieldType::DropDownList { choices } => {
                assert_eq!(choices, &vec!["Red".to_string(), "Blue".to_string()]);
            }
            other => panic!("expected DropDownList, got {other:?}"),
        }
        assert_eq!(field.current_value, "Red");
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_field_alias_and_tag() {
        use super::{FormFieldExt, FormFieldType};
        let mut sdt_pr = make_sdt_pr_base(Some("Full Name"), Some("fullName"));
        sdt_pr.text = Some(Box::new(types::CTSdtText {
            multi_line: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
        }));
        let sdt_run = make_sdt_run(sdt_pr, "Jane Doe");
        let field = sdt_run.form_field().expect("should have form field");
        assert_eq!(field.alias.as_deref(), Some("Full Name"));
        assert_eq!(field.tag.as_deref(), Some("fullName"));
        assert_eq!(
            field.field_type,
            FormFieldType::PlainText { multi_line: false }
        );
        assert_eq!(field.current_value, "Jane Doe");
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_field_rich_text() {
        use super::{FormFieldExt, FormFieldType};
        let mut sdt_pr = make_sdt_pr_base(None, None);
        sdt_pr.rich_text = Some(Box::new(types::CTEmpty));
        let sdt_block = make_sdt_block(sdt_pr, "rich content here");
        let field = sdt_block.form_field().expect("should have form field");
        assert_eq!(field.field_type, FormFieldType::RichText);
        assert_eq!(field.current_value, "rich content here");
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_field_date_picker() {
        use super::{FormFieldExt, FormFieldType};
        let mut sdt_pr = make_sdt_pr_base(None, None);
        sdt_pr.date = Some(Box::new(types::CTSdtDate {
            full_date: Some("2026-02-24T00:00:00Z".to_string()),
            date_format: Some(Box::new(types::CTString {
                value: "yyyy-MM-dd".to_string(),
                #[cfg(feature = "extra-attrs")]
                extra_attrs: Default::default(),
            })),
            lid: None,
            store_mapped_data_as: None,
            calendar: None,
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        }));
        let sdt_block = make_sdt_block(sdt_pr, "2026-02-24");
        let field = sdt_block.form_field().expect("should have form field");
        match &field.field_type {
            FormFieldType::DatePicker { format } => {
                assert_eq!(format.as_deref(), Some("yyyy-MM-dd"));
            }
            other => panic!("expected DatePicker, got {other:?}"),
        }
        assert_eq!(field.current_value, "2026-02-24");
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_fields_from_body() {
        use super::{BodyExt, FormFieldType};

        // SDT 1: block-level plain text
        let sdt_pr1 = {
            let mut pr = make_sdt_pr_base(Some("First Name"), Some("firstName"));
            pr.text = Some(Box::new(types::CTSdtText {
                multi_line: None,
                #[cfg(feature = "extra-attrs")]
                extra_attrs: Default::default(),
            }));
            pr
        };
        let block_sdt = make_sdt_block(sdt_pr1, "John");

        // SDT 2: inline (run-level) combo box inside a paragraph
        let sdt_pr2 = {
            let mut pr = make_sdt_pr_base(Some("Color"), None);
            pr.combo_box = Some(Box::new(types::CTSdtComboBox {
                last_value: Some("Red".to_string()),
                list_item: vec![types::CTSdtListItem {
                    display_text: Some("Red".to_string()),
                    value: Some("red".to_string()),
                    #[cfg(feature = "extra-attrs")]
                    extra_attrs: Default::default(),
                }],
                #[cfg(feature = "extra-attrs")]
                extra_attrs: Default::default(),
                #[cfg(feature = "extra-children")]
                extra_children: Default::default(),
            }));
            pr
        };
        let inline_sdt = make_sdt_run(sdt_pr2, "Red");
        let para_with_sdt =
            make_paragraph(vec![types::ParagraphContent::Sdt(Box::new(inline_sdt))]);

        let body = make_body(vec![
            types::BlockContent::Sdt(Box::new(block_sdt)),
            types::BlockContent::P(Box::new(para_with_sdt)),
        ]);

        let fields = body.form_fields();
        assert_eq!(fields.len(), 2);

        assert_eq!(fields[0].alias.as_deref(), Some("First Name"));
        assert_eq!(fields[0].tag.as_deref(), Some("firstName"));
        assert_eq!(
            fields[0].field_type,
            FormFieldType::PlainText { multi_line: false }
        );
        assert_eq!(fields[0].current_value, "John");

        assert_eq!(fields[1].alias.as_deref(), Some("Color"));
        assert!(
            matches!(&fields[1].field_type, FormFieldType::ComboBox { choices } if choices == &["Red"])
        );
        assert_eq!(fields[1].current_value, "Red");
    }

    #[test]
    #[cfg(feature = "wml-settings")]
    fn test_form_field_no_sdt_pr_returns_none() {
        use super::FormFieldExt;
        let sdt_run = types::CTSdtRun {
            sdt_pr: None,
            sdt_end_pr: None,
            sdt_content: None,
            #[cfg(feature = "extra-children")]
            extra_children: Default::default(),
        };
        assert!(sdt_run.form_field().is_none());
    }

    // -------------------------------------------------------------------------
    // MathExt tests
    // -------------------------------------------------------------------------

    /// Build a `Paragraph` whose `extra_children` contains a minimal
    /// `<m:oMath>` element with the supplied math text.
    ///
    /// Structure:
    /// ```xml
    /// <m:oMath>
    ///   <m:r>
    ///     <m:t>text</m:t>
    ///   </m:r>
    /// </m:oMath>
    /// ```
    #[cfg(feature = "extra-children")]
    fn make_paragraph_with_inline_math(math_text: &str) -> types::Paragraph {
        use ooxml_xml::{PositionedNode, RawXmlElement, RawXmlNode};

        let t = RawXmlElement {
            name: "m:t".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Text(math_text.to_string())],
            self_closing: false,
        };
        let r = RawXmlElement {
            name: "m:r".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(t)],
            self_closing: false,
        };
        let o_math = RawXmlElement {
            name: "m:oMath".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(r)],
            self_closing: false,
        };

        types::Paragraph {
            #[cfg(feature = "wml-track-changes")]
            rsid_r_pr: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_del: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_p: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r_default: None,
            #[cfg(feature = "wml-styling")]
            p_pr: None,
            paragraph_content: vec![],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            extra_children: vec![PositionedNode::new(0, RawXmlNode::Element(o_math))],
        }
    }

    /// Build a `Paragraph` whose `extra_children` contains a display
    /// `<m:oMathPara>` wrapping a `<m:oMath>`.
    ///
    /// Structure:
    /// ```xml
    /// <m:oMathPara>
    ///   <m:oMath>
    ///     <m:r><m:t>text</m:t></m:r>
    ///   </m:oMath>
    /// </m:oMathPara>
    /// ```
    #[cfg(feature = "extra-children")]
    fn make_paragraph_with_display_math(math_text: &str) -> types::Paragraph {
        use ooxml_xml::{PositionedNode, RawXmlElement, RawXmlNode};

        let t = RawXmlElement {
            name: "m:t".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Text(math_text.to_string())],
            self_closing: false,
        };
        let r = RawXmlElement {
            name: "m:r".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(t)],
            self_closing: false,
        };
        let o_math = RawXmlElement {
            name: "m:oMath".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(r)],
            self_closing: false,
        };
        let o_math_para = RawXmlElement {
            name: "m:oMathPara".to_string(),
            attributes: vec![],
            children: vec![RawXmlNode::Element(o_math)],
            self_closing: false,
        };

        types::Paragraph {
            #[cfg(feature = "wml-track-changes")]
            rsid_r_pr: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_del: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_p: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r_default: None,
            #[cfg(feature = "wml-styling")]
            p_pr: None,
            paragraph_content: vec![],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            extra_children: vec![PositionedNode::new(0, RawXmlNode::Element(o_math_para))],
        }
    }

    #[test]
    #[cfg(feature = "extra-children")]
    fn test_math_expression_inline() {
        use super::MathExt;
        let para = make_paragraph_with_inline_math("x+y");
        let exprs = para.math_expressions();
        assert_eq!(exprs.len(), 1);
        assert!(!exprs[0].is_display);
        #[cfg(feature = "wml-math")]
        assert_eq!(exprs[0].text(), "x+y");
    }

    #[test]
    #[cfg(feature = "extra-children")]
    fn test_math_expression_display() {
        use super::MathExt;
        let para = make_paragraph_with_display_math("E=mc²");
        let exprs = para.math_expressions();
        assert_eq!(exprs.len(), 1);
        assert!(exprs[0].is_display);
        #[cfg(feature = "wml-math")]
        assert_eq!(exprs[0].text(), "E=mc²");
    }

    #[test]
    #[cfg(feature = "extra-children")]
    fn test_has_math_true() {
        use super::MathExt;
        let para = make_paragraph_with_inline_math("a²+b²=c²");
        assert!(para.has_math());
    }

    #[test]
    #[cfg(feature = "extra-children")]
    fn test_has_math_false() {
        use super::MathExt;
        // A paragraph with no math in extra_children.
        let para = types::Paragraph {
            #[cfg(feature = "wml-track-changes")]
            rsid_r_pr: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_del: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_p: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r_default: None,
            #[cfg(feature = "wml-styling")]
            p_pr: None,
            paragraph_content: vec![],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            extra_children: vec![],
        };
        assert!(!para.has_math());
    }

    #[test]
    #[cfg(feature = "extra-children")]
    fn test_body_math_expressions() {
        use super::MathExt;

        let para1 = make_paragraph_with_inline_math("x+y");
        let para2 = make_paragraph_with_display_math("∫f(x)dx");
        // A paragraph without math.
        let para3 = types::Paragraph {
            #[cfg(feature = "wml-track-changes")]
            rsid_r_pr: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_del: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_p: None,
            #[cfg(feature = "wml-track-changes")]
            rsid_r_default: None,
            #[cfg(feature = "wml-styling")]
            p_pr: None,
            paragraph_content: vec![],
            #[cfg(feature = "extra-attrs")]
            extra_attrs: Default::default(),
            extra_children: vec![],
        };

        let body = types::Body {
            block_content: vec![
                types::BlockContent::P(Box::new(para1)),
                types::BlockContent::P(Box::new(para3)),
                types::BlockContent::P(Box::new(para2)),
            ],
            #[cfg(feature = "wml-layout")]
            sect_pr: None,
            extra_children: vec![],
        };

        let exprs = body.math_expressions();
        assert_eq!(exprs.len(), 2);
        assert!(!exprs[0].is_display);
        assert!(exprs[1].is_display);
    }
}