undoc 0.1.19

High-performance Microsoft Office document extraction to Markdown
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
//! DOCX parser implementation.

use std::collections::HashMap;

use crate::charts;
use crate::container::OoxmlContainer;
use crate::error::{Error, Result};
use crate::model::{
    Block, Cell, CellAlignment, Document, ListInfo, ListType, Metadata, Paragraph, Resource,
    ResourceType, RevisionType, Row, Section, Table, TextAlignment, TextRun, TextStyle,
    VerticalAlignment,
};

use super::numbering::NumberingMap;
use super::styles::StyleMap;

/// Parser for DOCX (Word) documents.
pub struct DocxParser {
    container: OoxmlContainer,
    styles: StyleMap,
    numbering: NumberingMap,
    relationships: crate::container::Relationships,
    /// Footnote id → plain text content
    footnotes: HashMap<String, String>,
    /// Endnote id → plain text content
    endnotes: HashMap<String, String>,
}

impl DocxParser {
    /// Open a DOCX file for parsing.
    pub fn open(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let container = OoxmlContainer::open(path)?;
        Self::from_container(container)
    }

    /// Create a parser from bytes.
    pub fn from_bytes(data: Vec<u8>) -> Result<Self> {
        let container = OoxmlContainer::from_bytes(data)?;
        Self::from_container(container)
    }

    /// Create a parser from a container.
    fn from_container(container: OoxmlContainer) -> Result<Self> {
        // Parse styles
        let styles = if let Ok(xml) = container.read_xml("word/styles.xml") {
            StyleMap::parse(&xml)?
        } else {
            StyleMap::default()
        };

        // Parse numbering
        let numbering = if let Ok(xml) = container.read_xml("word/numbering.xml") {
            NumberingMap::parse(&xml)?
        } else {
            NumberingMap::default()
        };

        // Parse document relationships
        let relationships = container
            .read_relationships("word/document.xml")
            .unwrap_or_default();

        // Parse footnotes
        let footnotes = if let Ok(xml) = container.read_xml("word/footnotes.xml") {
            parse_notes_xml(&xml, b"w:footnote")
        } else {
            HashMap::new()
        };

        // Parse endnotes
        let endnotes = if let Ok(xml) = container.read_xml("word/endnotes.xml") {
            parse_notes_xml(&xml, b"w:endnote")
        } else {
            HashMap::new()
        };

        Ok(Self {
            container,
            styles,
            numbering,
            relationships,
            footnotes,
            endnotes,
        })
    }

    /// Parse the document and return a Document model.
    pub fn parse(&mut self) -> Result<Document> {
        let mut doc = Document::new();

        // Parse metadata
        doc.metadata = self.parse_metadata()?;

        // Parse main document content
        let mut main_section = self.parse_document_xml()?;

        // Parse charts and add as tables for RAG-ready output
        let chart_tables = self.parse_charts()?;
        for table in chart_tables {
            main_section.add_block(Block::Table(table));
        }

        // Append footnote definitions at end of section
        if !self.footnotes.is_empty() {
            let mut ids: Vec<&String> = self.footnotes.keys().collect();
            ids.sort_by(|a, b| {
                a.parse::<u64>()
                    .unwrap_or(u64::MAX)
                    .cmp(&b.parse::<u64>().unwrap_or(u64::MAX))
            });
            for id in ids {
                if let Some(text) = self.footnotes.get(id) {
                    let para = Paragraph::with_text(format!("[^{}]: {}", id, text));
                    main_section.add_block(Block::Paragraph(para));
                }
            }
        }

        // Append endnote definitions at end of section
        if !self.endnotes.is_empty() {
            let mut ids: Vec<&String> = self.endnotes.keys().collect();
            ids.sort_by(|a, b| {
                a.parse::<u64>()
                    .unwrap_or(u64::MAX)
                    .cmp(&b.parse::<u64>().unwrap_or(u64::MAX))
            });
            for id in ids {
                if let Some(text) = self.endnotes.get(id) {
                    let para = Paragraph::with_text(format!("[^e{}]: {}", id, text));
                    main_section.add_block(Block::Paragraph(para));
                }
            }
        }

        doc.add_section(main_section);

        // Extract resources (images)
        self.extract_resources(&mut doc)?;

        Ok(doc)
    }

    /// Parse document metadata from docProps/core.xml.
    fn parse_metadata(&self) -> Result<Metadata> {
        // Use shared metadata parsing from container
        self.container.parse_core_metadata()
    }

    /// Parse charts from word/charts/ and convert to tables for RAG-ready output.
    fn parse_charts(&self) -> Result<Vec<Table>> {
        let mut tables = Vec::new();

        // Find chart relationships in document.xml.rels
        for (rel_type, rels) in &self.relationships.by_type {
            if !rel_type.contains("chart") {
                continue;
            }

            for rel in rels {
                // Resolve chart path relative to document.xml
                // Target is like "charts/chart1.xml"
                let chart_path = if rel.target.starts_with('/') {
                    rel.target[1..].to_string()
                } else {
                    format!("word/{}", rel.target)
                };

                // Read and parse chart XML
                if let Ok(chart_xml) = self.container.read_xml(&chart_path) {
                    match charts::parse_chart_xml(&chart_xml) {
                        Ok(chart_data) => {
                            if !chart_data.is_empty() {
                                let mut table = chart_data.to_table();
                                // Add chart title if available
                                if let Some(ref title) = chart_data.title {
                                    if !title.is_empty() {
                                        if let Some(first_row) = table.rows.first_mut() {
                                            if let Some(first_cell) = first_row.cells.first_mut() {
                                                let original = first_cell.plain_text();
                                                first_cell.content.clear();
                                                first_cell.content.push(Paragraph::with_text(
                                                    format!("{} ({})", original, title),
                                                ));
                                            }
                                        }
                                    }
                                }
                                tables.push(table);
                            }
                        }
                        Err(_) => {
                            // Chart parsing failed, skip
                        }
                    }
                }
            }
        }

        Ok(tables)
    }

    /// Parse the main document.xml content.
    fn parse_document_xml(&mut self) -> Result<Section> {
        let xml = self.container.read_xml("word/document.xml")?;
        let mut section = Section::new(0);

        let mut reader = quick_xml::Reader::from_str(&xml);
        // IMPORTANT: Don't trim text - preserve whitespace from xml:space="preserve" elements
        // This fixes the "DATE OF BIRTH" -> "DATEOFBIRTH" bug (GitHub Issue #2)
        reader.config_mut().trim_text(false);

        let mut buf = Vec::new();
        let mut in_body = false;
        let mut paragraph_xml = String::new();
        let mut table_xml = String::new();
        let mut in_paragraph = false;
        let mut para_depth: u32 = 0; // Track nested w:p depth (for text boxes)
        let mut table_depth: u32 = 0; // Track nested table depth
        let mut in_sect_pr = false; // Track w:sectPr for header/footer references
        let mut default_header_rid: Option<String> = None;
        let mut default_footer_rid: Option<String> = None;

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(quick_xml::events::Event::Start(ref e)) => {
                    let name = e.name();
                    match name.as_ref() {
                        b"w:body" => {
                            in_body = true;
                        }
                        b"w:p" if in_body && table_depth == 0 && !in_paragraph => {
                            in_paragraph = true;
                            paragraph_xml.clear();
                            paragraph_xml.push_str("<w:p");
                            for attr in e.attributes().flatten() {
                                paragraph_xml.push_str(&format!(
                                    " {}=\"{}\"",
                                    String::from_utf8_lossy(attr.key.as_ref()),
                                    String::from_utf8_lossy(&attr.value)
                                ));
                            }
                            paragraph_xml.push('>');
                        }
                        b"w:sectPr" if in_body && !in_paragraph && table_depth == 0 => {
                            in_sect_pr = true;
                        }
                        b"w:tbl" if in_body => {
                            if table_depth == 0 {
                                // Start collecting table XML
                                table_xml.clear();
                            }
                            table_depth += 1;
                            table_xml.push_str("<w:tbl>");
                        }
                        _ => {
                            if in_paragraph {
                                // Track nested w:p depth for text boxes
                                if name.as_ref() == b"w:p" {
                                    para_depth += 1;
                                }
                                paragraph_xml.push('<');
                                paragraph_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                                for attr in e.attributes().flatten() {
                                    paragraph_xml.push_str(&format!(
                                        " {}=\"{}\"",
                                        String::from_utf8_lossy(attr.key.as_ref()),
                                        String::from_utf8_lossy(&attr.value)
                                    ));
                                }
                                paragraph_xml.push('>');
                            } else if table_depth > 0 {
                                table_xml.push('<');
                                table_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                                for attr in e.attributes().flatten() {
                                    table_xml.push_str(&format!(
                                        " {}=\"{}\"",
                                        String::from_utf8_lossy(attr.key.as_ref()),
                                        String::from_utf8_lossy(&attr.value)
                                    ));
                                }
                                table_xml.push('>');
                            }
                        }
                    }
                }
                Ok(quick_xml::events::Event::Empty(ref e)) => {
                    // Handle header/footer references inside w:sectPr
                    if in_sect_pr {
                        let name = e.name();
                        match name.as_ref() {
                            b"w:headerReference" | b"w:footerReference" => {
                                let mut ref_type = String::new();
                                let mut r_id = String::new();
                                for attr in e.attributes().flatten() {
                                    match attr.key.as_ref() {
                                        b"w:type" => {
                                            ref_type =
                                                String::from_utf8_lossy(&attr.value).to_string();
                                        }
                                        b"r:id" => {
                                            r_id = String::from_utf8_lossy(&attr.value).to_string();
                                        }
                                        _ => {}
                                    }
                                }
                                if ref_type == "default" && !r_id.is_empty() {
                                    if name.as_ref() == b"w:headerReference" {
                                        default_header_rid = Some(r_id);
                                    } else {
                                        default_footer_rid = Some(r_id);
                                    }
                                }
                            }
                            _ => {}
                        }
                    } else if in_paragraph {
                        let name = e.name();
                        paragraph_xml.push('<');
                        paragraph_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                        for attr in e.attributes().flatten() {
                            paragraph_xml.push_str(&format!(
                                " {}=\"{}\"",
                                String::from_utf8_lossy(attr.key.as_ref()),
                                String::from_utf8_lossy(&attr.value)
                            ));
                        }
                        paragraph_xml.push_str("/>");
                    } else if table_depth > 0 {
                        let name = e.name();
                        table_xml.push('<');
                        table_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                        for attr in e.attributes().flatten() {
                            table_xml.push_str(&format!(
                                " {}=\"{}\"",
                                String::from_utf8_lossy(attr.key.as_ref()),
                                String::from_utf8_lossy(&attr.value)
                            ));
                        }
                        table_xml.push_str("/>");
                    }
                }
                Ok(quick_xml::events::Event::Text(ref e)) => {
                    if in_paragraph {
                        let text = e.unescape().unwrap_or_default();
                        paragraph_xml.push_str(&escape_xml(&text));
                    } else if table_depth > 0 {
                        let text = e.unescape().unwrap_or_default();
                        table_xml.push_str(&escape_xml(&text));
                    }
                }
                Ok(quick_xml::events::Event::End(ref e)) => {
                    let name = e.name();
                    match name.as_ref() {
                        b"w:body" => {
                            in_body = false;
                        }
                        b"w:sectPr" if in_sect_pr => {
                            in_sect_pr = false;
                        }
                        b"w:p" if in_paragraph && table_depth == 0 && para_depth == 0 => {
                            paragraph_xml.push_str("</w:p>");
                            // Extract text box paragraphs before parsing the main paragraph
                            let textbox_paras = self.extract_textbox_paragraphs(&paragraph_xml);
                            if let Ok(para) = self.parse_paragraph(&paragraph_xml) {
                                section.add_block(Block::Paragraph(para));
                            }
                            // Add text box paragraphs as separate blocks
                            for tb_para in textbox_paras {
                                section.add_block(Block::Paragraph(tb_para));
                            }
                            in_paragraph = false;
                        }
                        b"w:tbl" if table_depth > 0 => {
                            table_xml.push_str("</w:tbl>");
                            table_depth -= 1;
                            if table_depth == 0 {
                                // Finished collecting outermost table - now parse it
                                if let Ok(table) = self.parse_table(&table_xml) {
                                    section.add_block(Block::Table(table));
                                }
                            }
                        }
                        _ => {
                            if in_paragraph {
                                // Track nested w:p depth for text boxes
                                if name.as_ref() == b"w:p" {
                                    para_depth = para_depth.saturating_sub(1);
                                }
                                paragraph_xml.push_str("</");
                                paragraph_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                                paragraph_xml.push('>');
                            } else if table_depth > 0 {
                                table_xml.push_str("</");
                                table_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                                table_xml.push('>');
                            }
                        }
                    }
                }
                Ok(quick_xml::events::Event::Eof) => break,
                Err(e) => {
                    return Err(Error::xml_parse_with_context(
                        e.to_string(),
                        "word/document.xml",
                    ))
                }
                _ => {}
            }
            buf.clear();
        }

        // Resolve and parse header/footer from sectPr references
        if let Some(rid) = default_header_rid {
            if let Some(paragraphs) = self.parse_header_footer_by_rid(&rid) {
                if !paragraphs.is_empty() {
                    section.header = Some(paragraphs);
                }
            }
        }
        if let Some(rid) = default_footer_rid {
            if let Some(paragraphs) = self.parse_header_footer_by_rid(&rid) {
                if !paragraphs.is_empty() {
                    section.footer = Some(paragraphs);
                }
            }
        }

        Ok(section)
    }

    /// Resolve a relationship ID to a header/footer XML path and parse its paragraphs.
    fn parse_header_footer_by_rid(&self, rid: &str) -> Option<Vec<Paragraph>> {
        let rel = self.relationships.get(rid)?;
        let path = OoxmlContainer::resolve_path("word/document.xml", &rel.target);
        let xml = self.container.read_xml(&path).ok()?;
        Some(parse_header_footer_xml(&xml))
    }

    /// Parse a single paragraph element.
    fn parse_paragraph(&mut self, xml: &str) -> Result<Paragraph> {
        use crate::model::InlineImage;

        let mut para = Paragraph::new();
        let mut reader = quick_xml::Reader::from_str(xml);
        // Don't trim text - preserve whitespace from xml:space="preserve" elements
        reader.config_mut().trim_text(false);

        let mut buf = Vec::new();
        let mut in_ppr = false;
        let mut in_rpr = false;
        let mut in_run = false;
        let mut in_text = false; // Track w:t elements (regular text)
        let mut in_instr_text = false; // Track w:instrText elements (field codes to skip)
        let mut in_drawing = false; // Track w:drawing elements for images
        let mut in_ins = false; // Track w:ins elements (tracked changes - insertions)
        let mut in_del = false; // Track w:del elements (tracked changes - deletions)
        let mut txbx_content_depth: u32 = 0; // Track w:txbxContent nesting (suppress text capture)
        let mut mc_fallback_depth: u32 = 0; // Track mc:Fallback nesting (skip entirely)
        let mut current_style = TextStyle::default();
        let mut current_hyperlink: Option<String> = None;
        let mut current_image_alt: Option<String> = None;

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(quick_xml::events::Event::Start(ref e)) => match e.name().as_ref() {
                    // Skip mc:Fallback branches to avoid duplicating text box content
                    b"mc:Fallback" => {
                        mc_fallback_depth += 1;
                    }
                    // Track w:txbxContent to suppress text capture (extracted separately)
                    b"w:txbxContent" if mc_fallback_depth == 0 => {
                        txbx_content_depth += 1;
                    }
                    _ if mc_fallback_depth > 0 => {} // Skip everything inside mc:Fallback
                    _ if txbx_content_depth > 0 => {} // Skip everything inside w:txbxContent
                    b"w:pPr" => in_ppr = true,
                    b"w:rPr" => in_rpr = true,
                    b"w:r" => {
                        in_run = true;
                        current_style = TextStyle::default();
                    }
                    b"w:t" => in_text = true,
                    b"w:instrText" => in_instr_text = true,
                    b"w:drawing" => {
                        in_drawing = true;
                        current_image_alt = None;
                    }
                    // Tracked changes - insertions
                    b"w:ins" => in_ins = true,
                    // Tracked changes - deletions
                    b"w:del" => in_del = true,
                    b"w:hyperlink" => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"r:id" {
                                let rel_id = String::from_utf8_lossy(&attr.value);
                                if let Some(rel) = self.relationships.get(&rel_id) {
                                    current_hyperlink = Some(rel.target.clone());
                                }
                            }
                        }
                    }
                    _ => {}
                },
                Ok(quick_xml::events::Event::Empty(ref e)) => match e.name().as_ref() {
                    _ if mc_fallback_depth > 0 || txbx_content_depth > 0 => {} // Skip
                    b"w:pStyle" if in_ppr => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:val" {
                                let style_id = String::from_utf8_lossy(&attr.value);
                                para.style_id = Some(style_id.to_string());
                                para.heading = self.styles.get_heading_level(&style_id);
                                // Also get style name from StyleMap
                                if let Some(style) = self.styles.styles.get(style_id.as_ref()) {
                                    if !style.name.is_empty() {
                                        para.style_name = Some(style.name.clone());
                                    }
                                }
                            }
                        }
                    }
                    b"w:jc" if in_ppr => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:val" {
                                let val = String::from_utf8_lossy(&attr.value);
                                para.alignment = match val.as_ref() {
                                    "center" => TextAlignment::Center,
                                    "right" => TextAlignment::Right,
                                    "both" | "distribute" => TextAlignment::Justify,
                                    _ => TextAlignment::Left,
                                };
                            }
                        }
                    }
                    b"w:b" if in_rpr => {
                        let val = get_bool_attr(e, b"w:val");
                        current_style.bold = val.unwrap_or(true);
                    }
                    b"w:i" if in_rpr => {
                        let val = get_bool_attr(e, b"w:val");
                        current_style.italic = val.unwrap_or(true);
                    }
                    b"w:u" if in_rpr => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:val" {
                                let val = String::from_utf8_lossy(&attr.value);
                                current_style.underline = val != "none";
                            }
                        }
                    }
                    b"w:strike" if in_rpr => {
                        let val = get_bool_attr(e, b"w:val");
                        current_style.strikethrough = val.unwrap_or(true);
                    }
                    b"w:vertAlign" if in_rpr => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:val" {
                                let val = String::from_utf8_lossy(&attr.value);
                                match val.as_ref() {
                                    "superscript" => current_style.superscript = true,
                                    "subscript" => current_style.subscript = true,
                                    _ => {}
                                }
                            }
                        }
                    }
                    b"w:sz" if in_rpr => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:val" {
                                let val = String::from_utf8_lossy(&attr.value);
                                current_style.size = val.parse().ok();
                            }
                        }
                    }
                    b"w:color" if in_rpr => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:val" {
                                let val = String::from_utf8_lossy(&attr.value);
                                if val != "auto" {
                                    current_style.color = Some(val.to_string());
                                }
                            }
                        }
                    }
                    b"w:highlight" if in_rpr => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:val" {
                                current_style.highlight =
                                    Some(String::from_utf8_lossy(&attr.value).to_string());
                            }
                        }
                    }
                    b"w:rFonts" if in_rpr => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:ascii" {
                                current_style.font =
                                    Some(String::from_utf8_lossy(&attr.value).to_string());
                                break;
                            }
                        }
                    }
                    // Image handling: wp:docPr contains alt text
                    b"wp:docPr" if in_drawing => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"descr" {
                                current_image_alt =
                                    Some(String::from_utf8_lossy(&attr.value).to_string());
                            }
                        }
                    }
                    // Image handling: a:blip contains the image reference
                    b"a:blip" if in_drawing => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"r:embed" {
                                let rel_id = String::from_utf8_lossy(&attr.value).to_string();
                                // Create inline image with the relationship ID
                                let image = InlineImage {
                                    resource_id: rel_id,
                                    alt_text: current_image_alt.clone(),
                                    width: None,
                                    height: None,
                                };
                                para.images.push(image);
                            }
                        }
                    }
                    // Break handling - line break or page break
                    b"w:br" if in_run => {
                        // Check for break type: page, column, or text wrapping (default)
                        let mut is_page_break = false;
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:type" {
                                let break_type = String::from_utf8_lossy(&attr.value);
                                is_page_break = break_type == "page";
                            }
                        }

                        // Compute current revision type
                        let current_revision = if in_del {
                            RevisionType::Deleted
                        } else if in_ins {
                            RevisionType::Inserted
                        } else {
                            RevisionType::None
                        };

                        if is_page_break {
                            // Page break - mark run with page_break flag
                            if let Some(last_run) = para.runs.last_mut() {
                                last_run.page_break = true;
                            } else {
                                para.runs.push(TextRun {
                                    text: String::new(),
                                    style: current_style.clone(),
                                    hyperlink: None,
                                    line_break: false,
                                    page_break: true,
                                    revision: current_revision,
                                });
                            }
                        } else {
                            // Line break (text wrapping or column break treated as line break)
                            if let Some(last_run) = para.runs.last_mut() {
                                last_run.line_break = true;
                            } else {
                                para.runs.push(TextRun {
                                    text: String::new(),
                                    style: current_style.clone(),
                                    hyperlink: None,
                                    line_break: true,
                                    page_break: false,
                                    revision: current_revision,
                                });
                            }
                        }
                    }
                    // Tab character handling - convert <w:tab/> to tab character
                    b"w:tab" if in_run => {
                        let current_revision = if in_del {
                            RevisionType::Deleted
                        } else if in_ins {
                            RevisionType::Inserted
                        } else {
                            RevisionType::None
                        };
                        para.runs.push(TextRun {
                            text: "\t".to_string(),
                            style: current_style.clone(),
                            hyperlink: current_hyperlink.clone(),
                            line_break: false,
                            page_break: false,
                            revision: current_revision,
                        });
                    }
                    // Carriage return handling - convert <w:cr/> to newline
                    b"w:cr" if in_run => {
                        if let Some(last_run) = para.runs.last_mut() {
                            last_run.line_break = true;
                        } else {
                            let current_revision = if in_del {
                                RevisionType::Deleted
                            } else if in_ins {
                                RevisionType::Inserted
                            } else {
                                RevisionType::None
                            };
                            para.runs.push(TextRun {
                                text: String::new(),
                                style: current_style.clone(),
                                hyperlink: None,
                                line_break: true,
                                page_break: false,
                                revision: current_revision,
                            });
                        }
                    }
                    // Non-breaking hyphen handling
                    b"w:noBreakHyphen" if in_run => {
                        let current_revision = if in_del {
                            RevisionType::Deleted
                        } else if in_ins {
                            RevisionType::Inserted
                        } else {
                            RevisionType::None
                        };
                        para.runs.push(TextRun {
                            text: "\u{2011}".to_string(), // Non-breaking hyphen Unicode
                            style: current_style.clone(),
                            hyperlink: current_hyperlink.clone(),
                            line_break: false,
                            page_break: false,
                            revision: current_revision,
                        });
                    }
                    // Soft hyphen handling (optional hyphen, usually invisible)
                    b"w:softHyphen" if in_run => {
                        let current_revision = if in_del {
                            RevisionType::Deleted
                        } else if in_ins {
                            RevisionType::Inserted
                        } else {
                            RevisionType::None
                        };
                        para.runs.push(TextRun {
                            text: "\u{00AD}".to_string(), // Soft hyphen Unicode
                            style: current_style.clone(),
                            hyperlink: current_hyperlink.clone(),
                            line_break: false,
                            page_break: false,
                            revision: current_revision,
                        });
                    }
                    // Non-breaking space handling
                    b"w:noBreakSpace" if in_run => {
                        let current_revision = if in_del {
                            RevisionType::Deleted
                        } else if in_ins {
                            RevisionType::Inserted
                        } else {
                            RevisionType::None
                        };
                        para.runs.push(TextRun {
                            text: "\u{00A0}".to_string(), // Non-breaking space Unicode
                            style: current_style.clone(),
                            hyperlink: current_hyperlink.clone(),
                            line_break: false,
                            page_break: false,
                            revision: current_revision,
                        });
                    }
                    // Footnote reference handling
                    b"w:footnoteReference" if in_run => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:id" {
                                let id = String::from_utf8_lossy(&attr.value).to_string();
                                // Only insert marker if this footnote has content
                                if self.footnotes.contains_key(&id) {
                                    para.runs.push(TextRun::plain(format!("[^{}]", id)));
                                }
                            }
                        }
                    }
                    // Endnote reference handling
                    b"w:endnoteReference" if in_run => {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"w:id" {
                                let id = String::from_utf8_lossy(&attr.value).to_string();
                                // Only insert marker if this endnote has content
                                if self.endnotes.contains_key(&id) {
                                    para.runs.push(TextRun::plain(format!("[^e{}]", id)));
                                }
                            }
                        }
                    }
                    _ => {}
                },
                Ok(quick_xml::events::Event::Text(ref e)) => {
                    // Only extract text from w:t elements, skip w:instrText (field codes)
                    // Also skip text inside mc:Fallback and w:txbxContent (extracted separately)
                    if in_run
                        && in_text
                        && !in_instr_text
                        && mc_fallback_depth == 0
                        && txbx_content_depth == 0
                    {
                        let text = e.unescape().unwrap_or_default().to_string();
                        if !text.is_empty() {
                            let current_revision = if in_del {
                                RevisionType::Deleted
                            } else if in_ins {
                                RevisionType::Inserted
                            } else {
                                RevisionType::None
                            };
                            let run = TextRun {
                                text,
                                style: current_style.clone(),
                                hyperlink: current_hyperlink.clone(),
                                line_break: false,
                                page_break: false,
                                revision: current_revision,
                            };
                            para.runs.push(run);
                        }
                    }
                }
                Ok(quick_xml::events::Event::End(ref e)) => match e.name().as_ref() {
                    b"mc:Fallback" if mc_fallback_depth > 0 => {
                        mc_fallback_depth -= 1;
                    }
                    b"w:txbxContent" if txbx_content_depth > 0 => {
                        txbx_content_depth -= 1;
                    }
                    _ if mc_fallback_depth > 0 || txbx_content_depth > 0 => {} // Skip
                    b"w:pPr" => in_ppr = false,
                    b"w:rPr" => in_rpr = false,
                    b"w:r" => in_run = false,
                    b"w:t" => in_text = false,
                    b"w:instrText" => in_instr_text = false,
                    b"w:hyperlink" => current_hyperlink = None,
                    b"w:drawing" => {
                        in_drawing = false;
                        current_image_alt = None;
                    }
                    b"w:ins" => in_ins = false,
                    b"w:del" => in_del = false,
                    _ => {}
                },
                Ok(quick_xml::events::Event::Eof) => break,
                Err(e) => return Err(Error::xml_parse_with_context(e.to_string(), "paragraph")),
                _ => {}
            }
            buf.clear();
        }

        // Parse numbering (list info)
        para.list_info = self.parse_list_info(xml);

        Ok(para)
    }

    /// Extract paragraphs from `w:txbxContent` elements (text boxes/shapes).
    ///
    /// Text boxes in DOCX appear inside `w:drawing` or `mc:AlternateContent` elements.
    /// This method finds all `w:txbxContent` sections (skipping those inside `mc:Fallback`
    /// to avoid duplication) and parses the inner `<w:p>` elements as regular paragraphs.
    fn extract_textbox_paragraphs(&mut self, xml: &str) -> Vec<Paragraph> {
        let mut paragraphs = Vec::new();
        let mut reader = quick_xml::Reader::from_str(xml);
        reader.config_mut().trim_text(false);

        let mut buf = Vec::new();
        let mut mc_fallback_depth: u32 = 0;
        let mut txbx_content_depth: u32 = 0;
        let mut in_txbx_para = false;
        let mut txbx_para_xml = String::new();
        let mut txbx_para_depth: u32 = 0; // Track nested elements inside the text box <w:p>

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(quick_xml::events::Event::Start(ref e)) => {
                    let name = e.name();
                    match name.as_ref() {
                        b"mc:Fallback" => {
                            mc_fallback_depth += 1;
                        }
                        b"w:txbxContent" if mc_fallback_depth == 0 => {
                            txbx_content_depth += 1;
                        }
                        b"w:p" if txbx_content_depth > 0 && !in_txbx_para => {
                            in_txbx_para = true;
                            txbx_para_depth = 0;
                            txbx_para_xml.clear();
                            txbx_para_xml.push_str("<w:p");
                            for attr in e.attributes().flatten() {
                                txbx_para_xml.push_str(&format!(
                                    " {}=\"{}\"",
                                    String::from_utf8_lossy(attr.key.as_ref()),
                                    String::from_utf8_lossy(&attr.value)
                                ));
                            }
                            txbx_para_xml.push('>');
                        }
                        _ if in_txbx_para => {
                            txbx_para_depth += 1;
                            txbx_para_xml.push('<');
                            txbx_para_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                            for attr in e.attributes().flatten() {
                                txbx_para_xml.push_str(&format!(
                                    " {}=\"{}\"",
                                    String::from_utf8_lossy(attr.key.as_ref()),
                                    String::from_utf8_lossy(&attr.value)
                                ));
                            }
                            txbx_para_xml.push('>');
                        }
                        _ => {}
                    }
                }
                Ok(quick_xml::events::Event::Empty(ref e)) => {
                    if in_txbx_para {
                        let name = e.name();
                        txbx_para_xml.push('<');
                        txbx_para_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                        for attr in e.attributes().flatten() {
                            txbx_para_xml.push_str(&format!(
                                " {}=\"{}\"",
                                String::from_utf8_lossy(attr.key.as_ref()),
                                String::from_utf8_lossy(&attr.value)
                            ));
                        }
                        txbx_para_xml.push_str("/>");
                    }
                }
                Ok(quick_xml::events::Event::Text(ref e)) => {
                    if in_txbx_para {
                        let text = e.unescape().unwrap_or_default();
                        txbx_para_xml.push_str(&escape_xml(&text));
                    }
                }
                Ok(quick_xml::events::Event::End(ref e)) => {
                    let name = e.name();
                    match name.as_ref() {
                        b"mc:Fallback" if mc_fallback_depth > 0 => {
                            mc_fallback_depth -= 1;
                        }
                        b"w:txbxContent" if txbx_content_depth > 0 => {
                            txbx_content_depth -= 1;
                        }
                        b"w:p" if in_txbx_para && txbx_para_depth == 0 => {
                            txbx_para_xml.push_str("</w:p>");
                            if let Ok(para) = self.parse_paragraph(&txbx_para_xml) {
                                if !para.plain_text().is_empty() {
                                    paragraphs.push(para);
                                }
                            }
                            in_txbx_para = false;
                        }
                        _ if in_txbx_para => {
                            txbx_para_depth = txbx_para_depth.saturating_sub(1);
                            txbx_para_xml.push_str("</");
                            txbx_para_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                            txbx_para_xml.push('>');
                        }
                        _ => {}
                    }
                }
                Ok(quick_xml::events::Event::Eof) => break,
                Err(_) => break,
                _ => {}
            }
            buf.clear();
        }

        paragraphs
    }

    /// Parse list info from paragraph XML.
    fn parse_list_info(&mut self, xml: &str) -> Option<ListInfo> {
        let mut reader = quick_xml::Reader::from_str(xml);
        reader.config_mut().trim_text(true);

        let mut buf = Vec::new();
        let mut num_id: Option<String> = None;
        let mut level: u8 = 0;
        let mut in_num_pr = false;

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(quick_xml::events::Event::Start(ref e)) => {
                    if e.name().as_ref() == b"w:numPr" {
                        in_num_pr = true;
                    }
                }
                Ok(quick_xml::events::Event::Empty(ref e)) => {
                    if in_num_pr {
                        match e.name().as_ref() {
                            b"w:numId" => {
                                for attr in e.attributes().flatten() {
                                    if attr.key.as_ref() == b"w:val" {
                                        num_id =
                                            Some(String::from_utf8_lossy(&attr.value).to_string());
                                    }
                                }
                            }
                            b"w:ilvl" => {
                                for attr in e.attributes().flatten() {
                                    if attr.key.as_ref() == b"w:val" {
                                        let val = String::from_utf8_lossy(&attr.value);
                                        level = val.parse().unwrap_or(0);
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
                Ok(quick_xml::events::Event::End(ref e)) => {
                    if e.name().as_ref() == b"w:numPr" {
                        in_num_pr = false;
                    }
                }
                Ok(quick_xml::events::Event::Eof) => break,
                _ => {}
            }
            buf.clear();
        }

        if let Some(ref nid) = num_id {
            if let Some((list_type, number)) = self.numbering.get_list_info(nid, level) {
                return Some(ListInfo {
                    list_type,
                    level,
                    number: if list_type == ListType::Numbered {
                        Some(number)
                    } else {
                        None
                    },
                });
            }
        }

        None
    }

    /// Parse a table element.
    #[allow(clippy::only_used_in_recursion)] // &self needed for recursive nested table parsing
    fn parse_table(&self, xml: &str) -> Result<Table> {
        use crate::model::InlineImage;

        let mut table = Table::new();
        let mut reader = quick_xml::Reader::from_str(xml);
        // Don't trim text - preserve whitespace from xml:space="preserve" elements
        reader.config_mut().trim_text(false);

        let mut buf = Vec::new();
        let mut in_row = false;
        let mut in_cell = false;
        let mut in_paragraph = false;
        let mut in_run = false;
        let mut in_rpr = false; // Track w:rPr (run properties for formatting)
        let mut in_text = false; // Track w:t elements (regular text)
        let mut in_instr_text = false; // Track w:instrText elements (field codes to skip)
        let mut in_drawing = false; // Track w:drawing elements for images
        let mut current_image_alt: Option<String> = None;
        let mut current_row: Option<Row> = None;
        let mut cell_paragraphs: Vec<Paragraph> = Vec::new();
        let mut cell_nested_tables: Vec<Table> = Vec::new();
        let mut current_paragraph: Option<Paragraph> = None;
        let mut current_style = TextStyle::default();
        let mut is_header_row = false;
        let mut col_span = 1u32;
        let mut row_span = 1u32;
        let mut cell_alignment = CellAlignment::Left;
        let mut in_tc_pr = false; // Track w:tcPr (table cell properties)

        // Track nested table depth (0 = we're at the main table level)
        // 1+ = we're inside a nested table and should collect its XML
        let mut nested_table_depth: u32 = 0;
        let mut nested_table_xml = String::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(quick_xml::events::Event::Start(ref e)) => {
                    let name = e.name();

                    // If we're inside a nested table, just collect XML
                    if nested_table_depth > 0 {
                        nested_table_xml.push('<');
                        nested_table_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                        for attr in e.attributes().flatten() {
                            nested_table_xml.push_str(&format!(
                                " {}=\"{}\"",
                                String::from_utf8_lossy(attr.key.as_ref()),
                                String::from_utf8_lossy(&attr.value)
                            ));
                        }
                        nested_table_xml.push('>');
                        if name.as_ref() == b"w:tbl" {
                            nested_table_depth += 1;
                        }
                        continue;
                    }

                    match name.as_ref() {
                        b"w:tbl" if in_cell => {
                            // Start collecting nested table
                            nested_table_depth = 1;
                            nested_table_xml.clear();
                            nested_table_xml.push_str("<w:tbl>");
                        }
                        b"w:tr" => {
                            in_row = true;
                            current_row = Some(Row {
                                cells: Vec::new(),
                                is_header: false,
                                height: None,
                            });
                            is_header_row = false;
                        }
                        b"w:tc" => {
                            in_cell = true;
                            cell_paragraphs.clear();
                            cell_nested_tables.clear();
                            col_span = 1;
                            row_span = 1;
                            cell_alignment = CellAlignment::Left;
                        }
                        b"w:tcPr" if in_cell => {
                            in_tc_pr = true;
                        }
                        b"w:p" if in_cell => {
                            in_paragraph = true;
                            current_paragraph = Some(Paragraph::new());
                        }
                        b"w:r" if in_paragraph => {
                            in_run = true;
                            current_style = TextStyle::default();
                        }
                        b"w:rPr" if in_run => in_rpr = true,
                        b"w:t" => in_text = true,
                        b"w:instrText" => in_instr_text = true,
                        b"w:drawing" => {
                            in_drawing = true;
                            current_image_alt = None;
                        }
                        _ => {}
                    }
                }
                Ok(quick_xml::events::Event::Empty(ref e)) => {
                    let name = e.name();

                    // If we're inside a nested table, just collect XML
                    if nested_table_depth > 0 {
                        nested_table_xml.push('<');
                        nested_table_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                        for attr in e.attributes().flatten() {
                            nested_table_xml.push_str(&format!(
                                " {}=\"{}\"",
                                String::from_utf8_lossy(attr.key.as_ref()),
                                String::from_utf8_lossy(&attr.value)
                            ));
                        }
                        nested_table_xml.push_str("/>");
                        continue;
                    }

                    match name.as_ref() {
                        b"w:tblHeader" if in_row => {
                            is_header_row = true;
                        }
                        b"w:gridSpan" if in_cell => {
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"w:val" {
                                    let val = String::from_utf8_lossy(&attr.value);
                                    col_span = val.parse().unwrap_or(1);
                                }
                            }
                        }
                        b"w:vMerge" if in_cell => {
                            let mut has_val = false;
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"w:val" {
                                    has_val = true;
                                }
                            }
                            if !has_val {
                                row_span = 0;
                            }
                        }
                        b"w:jc" if in_tc_pr => {
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"w:val" {
                                    let val = String::from_utf8_lossy(&attr.value);
                                    cell_alignment = match val.as_ref() {
                                        "center" => CellAlignment::Center,
                                        "right" | "end" => CellAlignment::Right,
                                        _ => CellAlignment::Left,
                                    };
                                }
                            }
                        }
                        // Handle formatting in run properties
                        b"w:b" if in_rpr => {
                            let val = get_bool_attr(e, b"w:val");
                            current_style.bold = val.unwrap_or(true);
                        }
                        b"w:i" if in_rpr => {
                            let val = get_bool_attr(e, b"w:val");
                            current_style.italic = val.unwrap_or(true);
                        }
                        b"w:u" if in_rpr => {
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"w:val" {
                                    let val = String::from_utf8_lossy(&attr.value);
                                    current_style.underline = val != "none";
                                }
                            }
                        }
                        b"w:strike" if in_rpr => {
                            let val = get_bool_attr(e, b"w:val");
                            current_style.strikethrough = val.unwrap_or(true);
                        }
                        // Image handling: wp:docPr contains alt text
                        b"wp:docPr" if in_drawing => {
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"descr" {
                                    current_image_alt =
                                        Some(String::from_utf8_lossy(&attr.value).to_string());
                                }
                            }
                        }
                        // Image handling: a:blip contains the image reference
                        b"a:blip" if in_drawing => {
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"r:embed" {
                                    let rel_id = String::from_utf8_lossy(&attr.value).to_string();
                                    // Create inline image with the relationship ID
                                    let image = InlineImage {
                                        resource_id: rel_id,
                                        alt_text: current_image_alt.clone(),
                                        width: None,
                                        height: None,
                                    };
                                    if let Some(ref mut para) = current_paragraph {
                                        para.images.push(image);
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                }
                Ok(quick_xml::events::Event::Text(ref e)) => {
                    // If we're inside a nested table, just collect XML
                    if nested_table_depth > 0 {
                        let text = e.unescape().unwrap_or_default();
                        nested_table_xml.push_str(&escape_xml(&text));
                        continue;
                    }

                    // Only extract text from w:t elements, skip w:instrText (field codes)
                    if in_run && in_text && !in_instr_text {
                        let text = e.unescape().unwrap_or_default().to_string();
                        if !text.is_empty() {
                            if let Some(ref mut para) = current_paragraph {
                                let run = TextRun {
                                    text,
                                    style: current_style.clone(),
                                    hyperlink: None,
                                    line_break: false,
                                    page_break: false,
                                    revision: RevisionType::None,
                                };
                                para.runs.push(run);
                            }
                        }
                    }
                }
                Ok(quick_xml::events::Event::End(ref e)) => {
                    let name = e.name();

                    // If we're inside a nested table, collect XML and check for end
                    if nested_table_depth > 0 {
                        if name.as_ref() == b"w:tbl" {
                            nested_table_xml.push_str("</w:tbl>");
                            nested_table_depth -= 1;
                            if nested_table_depth == 0 {
                                // Finished collecting nested table - parse recursively
                                if let Ok(nested_table) = self.parse_table(&nested_table_xml) {
                                    cell_nested_tables.push(nested_table);
                                }
                            }
                        } else {
                            nested_table_xml.push_str("</");
                            nested_table_xml.push_str(&String::from_utf8_lossy(name.as_ref()));
                            nested_table_xml.push('>');
                        }
                        continue;
                    }

                    match name.as_ref() {
                        b"w:tr" => {
                            if let Some(mut row) = current_row.take() {
                                row.is_header = is_header_row;
                                table.add_row(row);
                            }
                            in_row = false;
                        }
                        b"w:tcPr" => {
                            in_tc_pr = false;
                        }
                        b"w:tc" => {
                            if row_span > 0 {
                                // Use collected paragraphs, or empty paragraph if none
                                // Deduplicate repeated paragraph blocks within cell
                                // Word may store the same paragraph block twice but only displays once
                                let content = if cell_paragraphs.is_empty() {
                                    vec![Paragraph::new()]
                                } else {
                                    let paragraphs = std::mem::take(&mut cell_paragraphs);
                                    deduplicate_paragraph_block(paragraphs)
                                };
                                let cell = Cell {
                                    content,
                                    nested_tables: std::mem::take(&mut cell_nested_tables),
                                    col_span,
                                    row_span,
                                    alignment: cell_alignment,
                                    vertical_alignment: VerticalAlignment::default(),
                                    is_header: is_header_row,
                                    background: None,
                                };
                                if let Some(ref mut row) = current_row {
                                    row.cells.push(cell);
                                }
                            }
                            in_cell = false;
                        }
                        b"w:p" if in_cell => {
                            // Save the completed paragraph
                            if let Some(para) = current_paragraph.take() {
                                // Only add non-empty paragraphs
                                if !para.is_empty() {
                                    // Skip duplicate paragraphs (same text content as previous)
                                    // Word may store duplicate paragraphs in same cell but only displays one
                                    let is_duplicate = cell_paragraphs
                                        .last()
                                        .map(|last| last.plain_text() == para.plain_text())
                                        .unwrap_or(false);

                                    if !is_duplicate {
                                        cell_paragraphs.push(para);
                                    }
                                }
                            }
                            in_paragraph = false;
                        }
                        b"w:r" => {
                            in_run = false;
                        }
                        b"w:rPr" => in_rpr = false,
                        b"w:t" => in_text = false,
                        b"w:instrText" => in_instr_text = false,
                        b"w:drawing" => {
                            in_drawing = false;
                            current_image_alt = None;
                        }
                        _ => {}
                    }
                }
                Ok(quick_xml::events::Event::Eof) => break,
                Err(e) => return Err(Error::xml_parse_with_context(e.to_string(), "table")),
                _ => {}
            }
            buf.clear();
        }

        Ok(table)
    }

    /// Extract embedded resources (images, etc.).
    fn extract_resources(&self, doc: &mut Document) -> Result<()> {
        for (id, rel) in &self.relationships.by_id {
            if rel.rel_type.contains("/image") && !rel.external {
                let path = OoxmlContainer::resolve_path("word/document.xml", &rel.target);
                if let Ok(data) = self.container.read_binary(&path) {
                    let size = data.len();
                    let ext = std::path::Path::new(&path)
                        .extension()
                        .and_then(|e| e.to_str())
                        .unwrap_or("");
                    let resource = Resource {
                        resource_type: ResourceType::from_extension(ext),
                        filename: Some(
                            std::path::Path::new(&path)
                                .file_name()
                                .unwrap_or_default()
                                .to_string_lossy()
                                .to_string(),
                        ),
                        mime_type: guess_mime_type(&path),
                        data,
                        size,
                        width: None,
                        height: None,
                        alt_text: None,
                    };
                    doc.resources.insert(id.clone(), resource);
                }
            }
        }

        Ok(())
    }

    /// Get a reference to the container.
    pub fn container(&self) -> &OoxmlContainer {
        &self.container
    }
}

/// Parse footnotes.xml or endnotes.xml into a map of id → plain text.
///
/// `note_tag` should be `b"w:footnote"` or `b"w:endnote"`.
/// Entries with `w:type="separator"` or `w:type="continuationSeparator"` are skipped.
fn parse_notes_xml(xml: &str, note_tag: &[u8]) -> HashMap<String, String> {
    let mut notes = HashMap::new();
    let mut reader = quick_xml::Reader::from_str(xml);
    reader.config_mut().trim_text(false);

    let mut buf = Vec::new();
    let mut current_id: Option<String> = None;
    let mut current_text = String::new();
    let mut in_note = false;
    let mut in_text = false;

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(quick_xml::events::Event::Start(ref e)) => {
                if e.name().as_ref() == note_tag {
                    let mut id = None;
                    let mut note_type = None;
                    for attr in e.attributes().flatten() {
                        match attr.key.as_ref() {
                            b"w:id" => {
                                id = Some(String::from_utf8_lossy(&attr.value).to_string());
                            }
                            b"w:type" => {
                                note_type = Some(String::from_utf8_lossy(&attr.value).to_string());
                            }
                            _ => {}
                        }
                    }
                    // Skip separator and continuationSeparator types
                    if let Some(ref t) = note_type {
                        if t == "separator" || t == "continuationSeparator" {
                            // Don't set in_note, so content is ignored
                            buf.clear();
                            continue;
                        }
                    }
                    if let Some(id_val) = id {
                        in_note = true;
                        current_id = Some(id_val);
                        current_text.clear();
                    }
                } else if in_note && e.name().as_ref() == b"w:t" {
                    in_text = true;
                }
            }
            Ok(quick_xml::events::Event::Text(ref e)) => {
                if in_note && in_text {
                    if let Ok(text) = e.unescape() {
                        current_text.push_str(&text);
                    }
                }
            }
            Ok(quick_xml::events::Event::End(ref e)) => {
                if e.name().as_ref() == note_tag {
                    if in_note {
                        if let Some(id) = current_id.take() {
                            let trimmed = current_text.trim().to_string();
                            if !trimmed.is_empty() {
                                notes.insert(id, trimmed);
                            }
                        }
                        in_note = false;
                    }
                } else if e.name().as_ref() == b"w:t" {
                    in_text = false;
                }
            }
            Ok(quick_xml::events::Event::Eof) => break,
            Err(_) => break,
            _ => {}
        }
        buf.clear();
    }

    notes
}

/// Parse a header or footer XML file (w:hdr or w:ftr) into a list of paragraphs.
///
/// Header/footer XML has the same structure as the document body:
/// `<w:hdr>` or `<w:ftr>` containing `<w:p>` paragraphs with `<w:r>` runs and `<w:t>` text.
/// This function extracts plain text only (no styles or formatting).
fn parse_header_footer_xml(xml: &str) -> Vec<Paragraph> {
    let mut paragraphs = Vec::new();
    let mut reader = quick_xml::Reader::from_str(xml);
    reader.config_mut().trim_text(false);

    let mut buf = Vec::new();
    let mut in_paragraph = false;
    let mut in_text = false;
    let mut current_text = String::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(quick_xml::events::Event::Start(ref e)) => match e.name().as_ref() {
                b"w:p" => {
                    in_paragraph = true;
                    current_text.clear();
                }
                b"w:t" if in_paragraph => {
                    in_text = true;
                }
                _ => {}
            },
            Ok(quick_xml::events::Event::Text(ref e)) => {
                if in_paragraph && in_text {
                    if let Ok(text) = e.unescape() {
                        current_text.push_str(&text);
                    }
                }
            }
            Ok(quick_xml::events::Event::End(ref e)) => match e.name().as_ref() {
                b"w:p" => {
                    if in_paragraph {
                        let trimmed = current_text.trim().to_string();
                        if !trimmed.is_empty() {
                            paragraphs.push(Paragraph::with_text(trimmed));
                        }
                        in_paragraph = false;
                    }
                }
                b"w:t" => {
                    in_text = false;
                }
                _ => {}
            },
            Ok(quick_xml::events::Event::Eof) => break,
            Err(_) => break,
            _ => {}
        }
        buf.clear();
    }

    paragraphs
}

/// Helper to get a boolean attribute value.
fn get_bool_attr(e: &quick_xml::events::BytesStart, key: &[u8]) -> Option<bool> {
    for attr in e.attributes().flatten() {
        if attr.key.as_ref() == key {
            let val = String::from_utf8_lossy(&attr.value);
            return Some(val != "0" && val != "false");
        }
    }
    None
}

/// Escape XML special characters.
fn escape_xml(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

/// Guess MIME type from file extension.
fn guess_mime_type(path: &str) -> Option<String> {
    let ext = std::path::Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_lowercase())?;

    Some(
        match ext.as_str() {
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            "gif" => "image/gif",
            "bmp" => "image/bmp",
            "tiff" | "tif" => "image/tiff",
            "svg" => "image/svg+xml",
            "emf" => "image/x-emf",
            "wmf" => "image/x-wmf",
            _ => return None,
        }
        .to_string(),
    )
}

/// Deduplicate repeated paragraph blocks within a table cell.
/// Word may store the same paragraph block twice but only displays one.
/// This function checks if the first half and second half are identical
/// and returns only the first half if so.
fn deduplicate_paragraph_block(paragraphs: Vec<Paragraph>) -> Vec<Paragraph> {
    let len = paragraphs.len();
    if len < 2 {
        return paragraphs;
    }

    // Check if paragraphs form a duplicated block (first half == second half)
    if len.is_multiple_of(2) {
        let half = len / 2;
        let first_half = &paragraphs[..half];
        let second_half = &paragraphs[half..];

        let is_duplicate = first_half
            .iter()
            .zip(second_half.iter())
            .all(|(a, b)| a.plain_text() == b.plain_text());

        if is_duplicate {
            return paragraphs.into_iter().take(half).collect();
        }
    }

    paragraphs
}

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

    #[test]
    fn test_open_docx() {
        let path = "test-files/file-sample_1MB.docx";
        if std::path::Path::new(path).exists() {
            let parser = DocxParser::open(path);
            assert!(parser.is_ok());
        }
    }

    #[test]
    fn test_parse_docx() {
        let path = "test-files/file-sample_1MB.docx";
        if std::path::Path::new(path).exists() {
            let mut parser = DocxParser::open(path).unwrap();
            let doc = parser.parse().unwrap();

            assert!(!doc.sections.is_empty());

            let text = doc.plain_text();
            assert!(!text.is_empty());
            assert!(text.contains("Lorem ipsum"));
        }
    }

    #[test]
    fn test_parse_headings() {
        let path = "test-files/file-sample_1MB.docx";
        if std::path::Path::new(path).exists() {
            let mut parser = DocxParser::open(path).unwrap();
            let doc = parser.parse().unwrap();

            let headings: Vec<_> = doc.sections[0]
                .content
                .iter()
                .filter_map(|block| {
                    if let Block::Paragraph(p) = block {
                        if p.is_heading() {
                            return Some(p);
                        }
                    }
                    None
                })
                .collect();

            assert!(!headings.is_empty());
        }
    }

    #[test]
    fn test_extract_resources() {
        let path = "test-files/file-sample_1MB.docx";
        if std::path::Path::new(path).exists() {
            let mut parser = DocxParser::open(path).unwrap();
            let doc = parser.parse().unwrap();

            if !doc.resources.is_empty() {
                let resource = doc.resources.values().next().unwrap();
                assert!(resource.is_image());
            }
        }
    }

    // =========================================================================
    // Whitespace Preservation Tests (GitHub Issue #2)
    // =========================================================================

    #[test]
    fn test_whitespace_preserved_between_runs() {
        // Test case from GitHub Issue #2: "DATE OF BIRTH" was becoming "DATEOFBIRTH"
        // When xml:space="preserve" is used, spaces must be preserved
        let xml = r#"<w:p>
            <w:r><w:t>DATE</w:t></w:r>
            <w:r><w:t xml:space="preserve"> </w:t></w:r>
            <w:r><w:t>OF</w:t></w:r>
            <w:r><w:t xml:space="preserve"> </w:t></w:r>
            <w:r><w:t>BIRTH</w:t></w:r>
        </w:p>"#;

        // Create a minimal container just for testing paragraph parsing
        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            // Can't create empty container, skip test
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();
        let text = para.plain_text();

        // The text should have spaces preserved
        assert!(
            text.contains("DATE") && text.contains("OF") && text.contains("BIRTH"),
            "Expected 'DATE OF BIRTH' with spaces, got: '{}'",
            text
        );
        // Check that spaces are actually there
        assert!(
            text.contains(' '),
            "Expected spaces between words, got: '{}'",
            text
        );
    }

    #[test]
    fn test_whitespace_leading_trailing_preserved() {
        // Test leading/trailing whitespace with xml:space="preserve"
        let xml = r#"<w:p>
            <w:r><w:t xml:space="preserve">  Hello World  </w:t></w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();
        let text = para.plain_text();

        // Leading/trailing spaces should be preserved
        assert!(
            text.starts_with("  ") || text.contains("  Hello"),
            "Expected leading spaces, got: '{}'",
            text
        );
    }

    #[test]
    fn test_tab_character_handling() {
        // Test <w:tab/> element is converted to tab character
        let xml = r#"<w:p>
            <w:r>
                <w:t>Column1</w:t>
            </w:r>
            <w:r>
                <w:tab/>
            </w:r>
            <w:r>
                <w:t>Column2</w:t>
            </w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();
        let text = para.plain_text();

        assert!(
            text.contains('\t'),
            "Expected tab character between columns, got: '{}'",
            text
        );
        assert!(
            text.contains("Column1") && text.contains("Column2"),
            "Expected both column texts, got: '{}'",
            text
        );
    }

    #[test]
    fn test_multiple_spaces_preserved() {
        // Test multiple consecutive spaces are preserved
        let xml = r#"<w:p>
            <w:r><w:t xml:space="preserve">Word1     Word2</w:t></w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();
        let text = para.plain_text();

        // Multiple spaces should be preserved
        assert!(
            text.contains("     "),
            "Expected 5 consecutive spaces, got: '{}'",
            text
        );
    }

    #[test]
    fn test_carriage_return_handling() {
        // Test <w:cr/> element creates line break
        let xml = r#"<w:p>
            <w:r>
                <w:t>Line1</w:t>
                <w:cr/>
                <w:t>Line2</w:t>
            </w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();

        // Check that we have a line break somewhere
        let has_line_break = para.runs.iter().any(|r| r.line_break);
        assert!(has_line_break, "Expected line break from <w:cr/>");
    }

    #[test]
    fn test_non_breaking_hyphen() {
        // Test <w:noBreakHyphen/> is converted to non-breaking hyphen Unicode
        let xml = r#"<w:p>
            <w:r>
                <w:t>non</w:t>
                <w:noBreakHyphen/>
                <w:t>breaking</w:t>
            </w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();
        let text = para.plain_text();

        // Should contain non-breaking hyphen (U+2011) or at least the text parts
        assert!(
            text.contains("non") && text.contains("breaking"),
            "Expected 'non' and 'breaking' text, got: '{}'",
            text
        );
        assert!(
            text.contains('\u{2011}'),
            "Expected non-breaking hyphen U+2011, got: '{}'",
            text
        );
    }

    // =========================================================================
    // Tracked Changes Tests (Revisions)
    // =========================================================================

    #[test]
    fn test_tracked_changes_insertion() {
        // Test <w:ins> element marks text as inserted
        let xml = r#"<w:p>
            <w:r><w:t>Original </w:t></w:r>
            <w:ins>
                <w:r><w:t>inserted </w:t></w:r>
            </w:ins>
            <w:r><w:t>text</w:t></w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();

        // Check that we have an inserted revision
        let has_inserted = para
            .runs
            .iter()
            .any(|r| r.revision == RevisionType::Inserted);
        assert!(has_inserted, "Expected to find inserted revision");

        // The inserted text should be marked
        let inserted_text: String = para
            .runs
            .iter()
            .filter(|r| r.revision == RevisionType::Inserted)
            .map(|r| r.text.as_str())
            .collect();
        assert!(
            inserted_text.contains("inserted"),
            "Expected 'inserted' text in revision, got: '{}'",
            inserted_text
        );
    }

    #[test]
    fn test_tracked_changes_deletion() {
        // Test <w:del> element marks text as deleted
        let xml = r#"<w:p>
            <w:r><w:t>Keep this </w:t></w:r>
            <w:del>
                <w:r><w:t>deleted </w:t></w:r>
            </w:del>
            <w:r><w:t>text</w:t></w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();

        // Check that we have a deleted revision
        let has_deleted = para
            .runs
            .iter()
            .any(|r| r.revision == RevisionType::Deleted);
        assert!(has_deleted, "Expected to find deleted revision");

        // The deleted text should be marked
        let deleted_text: String = para
            .runs
            .iter()
            .filter(|r| r.revision == RevisionType::Deleted)
            .map(|r| r.text.as_str())
            .collect();
        assert!(
            deleted_text.contains("deleted"),
            "Expected 'deleted' text in revision, got: '{}'",
            deleted_text
        );
    }

    // =========================================================================
    // Footnote / Endnote Tests
    // =========================================================================

    #[test]
    fn test_parse_footnotes_xml() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
        <w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:footnote w:id="0" w:type="separator">
                <w:p><w:r><w:t>___</w:t></w:r></w:p>
            </w:footnote>
            <w:footnote w:id="1" w:type="continuationSeparator">
                <w:p><w:r><w:t>---</w:t></w:r></w:p>
            </w:footnote>
            <w:footnote w:id="2">
                <w:p><w:r><w:t>This is footnote two.</w:t></w:r></w:p>
            </w:footnote>
            <w:footnote w:id="3">
                <w:p><w:r><w:t>Another footnote.</w:t></w:r></w:p>
            </w:footnote>
        </w:footnotes>"#;

        let notes = parse_notes_xml(xml, b"w:footnote");

        // Separator and continuationSeparator should be skipped
        assert!(!notes.contains_key("0"), "separator should be skipped");
        assert!(
            !notes.contains_key("1"),
            "continuationSeparator should be skipped"
        );

        // Content footnotes should be parsed
        assert_eq!(notes.get("2").unwrap(), "This is footnote two.");
        assert_eq!(notes.get("3").unwrap(), "Another footnote.");
        assert_eq!(notes.len(), 2);
    }

    #[test]
    fn test_parse_endnotes_xml() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
        <w:endnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:endnote w:id="0" w:type="separator">
                <w:p><w:r><w:t>___</w:t></w:r></w:p>
            </w:endnote>
            <w:endnote w:id="1">
                <w:p><w:r><w:t>Endnote content here.</w:t></w:r></w:p>
            </w:endnote>
        </w:endnotes>"#;

        let notes = parse_notes_xml(xml, b"w:endnote");

        assert!(!notes.contains_key("0"), "separator should be skipped");
        assert_eq!(notes.get("1").unwrap(), "Endnote content here.");
        assert_eq!(notes.len(), 1);
    }

    #[test]
    fn test_footnote_multi_run_text() {
        // Footnote with multiple runs should concatenate text
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
        <w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:footnote w:id="1">
                <w:p>
                    <w:r><w:t>First </w:t></w:r>
                    <w:r><w:t>second </w:t></w:r>
                    <w:r><w:t>third.</w:t></w:r>
                </w:p>
            </w:footnote>
        </w:footnotes>"#;

        let notes = parse_notes_xml(xml, b"w:footnote");
        assert_eq!(notes.get("1").unwrap(), "First second third.");
    }

    #[test]
    fn test_footnote_reference_in_paragraph() {
        // Test that w:footnoteReference inserts [^N] marker
        let xml = r#"<w:p>
            <w:r><w:t>Some text</w:t></w:r>
            <w:r><w:footnoteReference w:id="2"/></w:r>
            <w:r><w:t> more text</w:t></w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut footnotes = HashMap::new();
        footnotes.insert("2".to_string(), "Footnote content".to_string());

        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes,
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();
        let text = para.plain_text();

        assert!(
            text.contains("[^2]"),
            "Expected footnote reference [^2], got: '{}'",
            text
        );
        assert!(
            text.contains("Some text"),
            "Expected original text, got: '{}'",
            text
        );
    }

    #[test]
    fn test_endnote_reference_in_paragraph() {
        // Test that w:endnoteReference inserts [^eN] marker
        let xml = r#"<w:p>
            <w:r><w:t>Text with endnote</w:t></w:r>
            <w:r><w:endnoteReference w:id="1"/></w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut endnotes = HashMap::new();
        endnotes.insert("1".to_string(), "Endnote content".to_string());

        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(),
            endnotes,
        };

        let para = parser.parse_paragraph(xml).unwrap();
        let text = para.plain_text();

        assert!(
            text.contains("[^e1]"),
            "Expected endnote reference [^e1], got: '{}'",
            text
        );
    }

    #[test]
    fn test_footnote_reference_skipped_when_no_content() {
        // If the footnote id doesn't exist in the map, no marker should be inserted
        let xml = r#"<w:p>
            <w:r><w:t>Text</w:t></w:r>
            <w:r><w:footnoteReference w:id="99"/></w:r>
        </w:p>"#;

        let container = crate::container::OoxmlContainer::from_bytes(Vec::new());
        if container.is_err() {
            return;
        }
        let container = container.unwrap();
        let mut parser = DocxParser {
            container,
            styles: StyleMap::default(),
            numbering: NumberingMap::default(),
            relationships: crate::container::Relationships::default(),
            footnotes: HashMap::new(), // No footnotes
            endnotes: HashMap::new(),
        };

        let para = parser.parse_paragraph(xml).unwrap();
        let text = para.plain_text();

        assert!(
            !text.contains("[^"),
            "Should not insert marker for unknown footnote, got: '{}'",
            text
        );
    }

    #[test]
    fn test_empty_footnote_skipped() {
        // Footnotes with only whitespace should not be included
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
        <w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:footnote w:id="1">
                <w:p><w:r><w:t>   </w:t></w:r></w:p>
            </w:footnote>
            <w:footnote w:id="2">
                <w:p><w:r><w:t>Real content.</w:t></w:r></w:p>
            </w:footnote>
        </w:footnotes>"#;

        let notes = parse_notes_xml(xml, b"w:footnote");
        assert!(
            !notes.contains_key("1"),
            "Whitespace-only note should be skipped"
        );
        assert_eq!(notes.get("2").unwrap(), "Real content.");
    }

    #[test]
    fn test_parse_header_footer_xml_basic() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
        <w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:p>
                <w:r><w:t>Company Name</w:t></w:r>
            </w:p>
            <w:p>
                <w:r><w:t>Confidential</w:t></w:r>
            </w:p>
        </w:hdr>"#;

        let paragraphs = parse_header_footer_xml(xml);
        assert_eq!(paragraphs.len(), 2);
        assert_eq!(paragraphs[0].plain_text(), "Company Name");
        assert_eq!(paragraphs[1].plain_text(), "Confidential");
    }

    #[test]
    fn test_parse_header_footer_xml_empty_paragraphs_skipped() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
        <w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:p></w:p>
            <w:p>
                <w:r><w:t>Page 1</w:t></w:r>
            </w:p>
            <w:p>
                <w:r><w:t>   </w:t></w:r>
            </w:p>
        </w:ftr>"#;

        let paragraphs = parse_header_footer_xml(xml);
        assert_eq!(paragraphs.len(), 1);
        assert_eq!(paragraphs[0].plain_text(), "Page 1");
    }

    #[test]
    fn test_parse_header_footer_xml_multiple_runs() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
        <w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:p>
                <w:r><w:t>Draft - </w:t></w:r>
                <w:r><w:t>Do Not Distribute</w:t></w:r>
            </w:p>
        </w:hdr>"#;

        let paragraphs = parse_header_footer_xml(xml);
        assert_eq!(paragraphs.len(), 1);
        assert_eq!(paragraphs[0].plain_text(), "Draft - Do Not Distribute");
    }

    #[test]
    fn test_parse_header_footer_xml_empty() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
        <w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
        </w:hdr>"#;

        let paragraphs = parse_header_footer_xml(xml);
        assert!(paragraphs.is_empty());
    }

    // =========================================================================
    // Text Box Content Extraction Tests (w:txbxContent)
    // =========================================================================

    /// Helper to create a minimal DOCX in memory with given document.xml content.
    fn create_minimal_docx(document_xml: &str) -> Vec<u8> {
        use std::io::{Cursor, Write};
        let buf = Cursor::new(Vec::new());
        let mut zip = zip::ZipWriter::new(buf);
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);

        // [Content_Types].xml
        zip.start_file("[Content_Types].xml", options).unwrap();
        zip.write_all(br#"<?xml version="1.0" encoding="UTF-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
  <Default Extension="xml" ContentType="application/xml"/>
  <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>"#).unwrap();

        // _rels/.rels
        zip.start_file("_rels/.rels", options).unwrap();
        zip.write_all(br#"<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>"#).unwrap();

        // word/_rels/document.xml.rels
        zip.start_file("word/_rels/document.xml.rels", options)
            .unwrap();
        zip.write_all(
            br#"<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
</Relationships>"#,
        )
        .unwrap();

        // word/document.xml
        zip.start_file("word/document.xml", options).unwrap();
        zip.write_all(document_xml.as_bytes()).unwrap();

        zip.finish().unwrap().into_inner()
    }

    #[test]
    fn test_textbox_content_extracted() {
        // Text box via w:drawing > wps:txbx > w:txbxContent
        let doc_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
            xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">
  <w:body>
    <w:p>
      <w:r>
        <w:t>Normal paragraph</w:t>
      </w:r>
    </w:p>
    <w:p>
      <w:r>
        <w:drawing>
          <wps:wsp>
            <wps:txbx>
              <w:txbxContent>
                <w:p>
                  <w:r><w:t>Text box content here</w:t></w:r>
                </w:p>
              </w:txbxContent>
            </wps:txbx>
          </wps:wsp>
        </w:drawing>
      </w:r>
    </w:p>
  </w:body>
</w:document>"#;

        let data = create_minimal_docx(doc_xml);
        let mut parser = DocxParser::from_bytes(data).unwrap();
        let doc = parser.parse().unwrap();
        let text = doc.plain_text();

        assert!(
            text.contains("Normal paragraph"),
            "Should contain normal paragraph text"
        );
        assert!(
            text.contains("Text box content here"),
            "Should contain text box content, got: {}",
            text
        );
    }

    #[test]
    fn test_textbox_mc_alternate_content_no_duplication() {
        // mc:AlternateContent with text box in both Choice and Fallback
        // Should only extract once (from Choice branch)
        let doc_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
            xmlns:v="urn:schemas-microsoft-com:vml">
  <w:body>
    <w:p>
      <w:r>
        <mc:AlternateContent>
          <mc:Choice>
            <w:drawing>
              <wps:wsp>
                <wps:txbx>
                  <w:txbxContent>
                    <w:p>
                      <w:r><w:t>Unique text box</w:t></w:r>
                    </w:p>
                  </w:txbxContent>
                </wps:txbx>
              </wps:wsp>
            </w:drawing>
          </mc:Choice>
          <mc:Fallback>
            <w:pict>
              <v:shape>
                <v:textbox>
                  <w:txbxContent>
                    <w:p>
                      <w:r><w:t>Unique text box</w:t></w:r>
                    </w:p>
                  </w:txbxContent>
                </v:textbox>
              </v:shape>
            </w:pict>
          </mc:Fallback>
        </mc:AlternateContent>
      </w:r>
    </w:p>
  </w:body>
</w:document>"#;

        let data = create_minimal_docx(doc_xml);
        let mut parser = DocxParser::from_bytes(data).unwrap();
        let doc = parser.parse().unwrap();
        let text = doc.plain_text();

        // Count occurrences - should appear exactly once
        let count = text.matches("Unique text box").count();
        assert_eq!(
            count, 1,
            "Text box content should appear exactly once, not duplicated. Full text: {}",
            text
        );
    }

    #[test]
    fn test_textbox_multiple_paragraphs() {
        // Text box with multiple paragraphs
        let doc_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
            xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">
  <w:body>
    <w:p>
      <w:r>
        <w:drawing>
          <wps:wsp>
            <wps:txbx>
              <w:txbxContent>
                <w:p>
                  <w:r><w:t>First text box paragraph</w:t></w:r>
                </w:p>
                <w:p>
                  <w:r><w:t>Second text box paragraph</w:t></w:r>
                </w:p>
              </w:txbxContent>
            </wps:txbx>
          </wps:wsp>
        </w:drawing>
      </w:r>
    </w:p>
  </w:body>
</w:document>"#;

        let data = create_minimal_docx(doc_xml);
        let mut parser = DocxParser::from_bytes(data).unwrap();
        let doc = parser.parse().unwrap();
        let text = doc.plain_text();

        assert!(
            text.contains("First text box paragraph"),
            "Should contain first text box paragraph"
        );
        assert!(
            text.contains("Second text box paragraph"),
            "Should contain second text box paragraph"
        );
    }
}