rustypyxl 0.7.1

Fast, dependency-light Rust library for reading and writing Excel (XLSX) files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
use crate::autofilter::FilterType;
use crate::cell::CellValue;
use crate::cell::InternedString;
use crate::conditional::{ConditionalColor, ConditionalFormat, ConditionalFormatType};
use crate::error::Result;
use crate::pagesetup::Orientation;
use crate::rich_text::{RichText, RunFont};
use crate::style::StyleRegistry;
use crate::utils::column_to_letter;
use crate::worksheet::{cell_key, decode_cell_key, CellData, SheetVisibility, Worksheet};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::Writer;
use rayon::prelude::*;
use std::collections::HashMap;
use std::io::{Cursor, Seek, Write};
use zip::write::{ExtendedFileOptions, FileOptions};
use zip::ZipWriter;

/// Returns true for C0 control characters that are illegal in XML 1.0
/// (everything below 0x20 except tab, line feed, and carriage return).
#[inline]
fn is_illegal_xml_char(b: u8) -> bool {
    b < 0x20 && !matches!(b, b'\t' | b'\n' | b'\r')
}

/// Strip control characters that are illegal in XML 1.0 without escaping.
/// Used before handing text to quick-xml, which performs entity escaping itself.
#[inline]
pub(crate) fn strip_illegal_xml_chars(s: &str) -> std::borrow::Cow<'_, str> {
    if s.bytes().any(is_illegal_xml_char) {
        std::borrow::Cow::Owned(
            s.chars()
                .filter(|&c| (c as u32) >= 0x20 || !is_illegal_xml_char(c as u8))
                .collect(),
        )
    } else {
        std::borrow::Cow::Borrowed(s)
    }
}

/// True when `<t>` text needs `xml:space="preserve"`. Without it a conforming
/// consumer is free to collapse the surrounding whitespace, so `<t>  hi  </t>`
/// may come back trimmed.
#[inline]
fn needs_space_preserve(s: &str) -> bool {
    s.starts_with(|c: char| c.is_whitespace()) || s.ends_with(|c: char| c.is_whitespace())
}

/// Write an element whose content is user-supplied text: strip the control
/// characters quick-xml's entity escaping leaves behind (they are illegal in
/// XML 1.0 even as entities, and Excel rejects the file as corrupt) and add
/// `xml:space="preserve"` when the whitespace is significant.
fn write_text_element<W: Write>(writer: &mut Writer<W>, name: &str, text: &str) -> Result<()> {
    let clean = strip_illegal_xml_chars(text);
    let mut start = BytesStart::new(name);
    if needs_space_preserve(&clean) {
        start.push_attribute(("xml:space", "preserve"));
    }
    writer.write_event(Event::Start(start))?;
    writer.write_event(Event::Text(BytesText::new(&clean)))?;
    writer.write_event(Event::End(BytesEnd::new(name)))?;
    Ok(())
}

/// Compute the legacy 16-bit Excel sheet-protection password verifier
/// (CreatePasswordVerifier_Method1 from MS-XLS 2.2.9), as stored in the
/// `password` attribute of `sheetProtection`.
pub(crate) fn legacy_password_hash(password: &str) -> u16 {
    let bytes = password.as_bytes();
    let mut verifier: u16 = 0;
    for &b in bytes
        .iter()
        .rev()
        .chain(std::iter::once(&(bytes.len() as u8)))
    {
        verifier = ((verifier >> 14) & 0x0001) | ((verifier << 1) & 0x7fff);
        verifier ^= b as u16;
    }
    verifier ^ 0xCE4B
}

/// Escape XML special characters in text content.
/// Control characters that are illegal in XML 1.0 are stripped, since
/// emitting them produces files Excel refuses to open.
#[inline]
pub fn escape_xml(s: &str) -> std::borrow::Cow<'_, str> {
    if s.bytes()
        .any(|b| matches!(b, b'<' | b'>' | b'&' | b'"' | b'\'') || is_illegal_xml_char(b))
    {
        let mut escaped = String::with_capacity(s.len() + 8);
        for c in s.chars() {
            match c {
                '<' => escaped.push_str("&lt;"),
                '>' => escaped.push_str("&gt;"),
                '&' => escaped.push_str("&amp;"),
                '"' => escaped.push_str("&quot;"),
                '\'' => escaped.push_str("&apos;"),
                c if (c as u32) < 0x20 && is_illegal_xml_char(c as u8) => {}
                _ => escaped.push(c),
            }
        }
        std::borrow::Cow::Owned(escaped)
    } else {
        std::borrow::Cow::Borrowed(s)
    }
}

/// Format a cell value directly to a string buffer (for streaming writes).
/// Uses inline strings instead of shared strings for simplicity.
#[inline]
pub fn format_cell_value(buf: &mut String, coord: &str, value: &CellValue) {
    match value {
        CellValue::String(s) => {
            let escaped = escape_xml(s.as_ref());
            buf.push_str("<c r=\"");
            buf.push_str(coord);
            buf.push_str("\" t=\"inlineStr\"><is>");
            if needs_space_preserve(&escaped) {
                buf.push_str("<t xml:space=\"preserve\">");
            } else {
                buf.push_str("<t>");
            }
            buf.push_str(&escaped);
            buf.push_str("</t></is></c>");
        }
        CellValue::Number(n) => {
            if !n.is_finite() {
                // NaN/Infinity are not valid SpreadsheetML numbers; emit an error cell.
                buf.push_str("<c r=\"");
                buf.push_str(coord);
                buf.push_str("\" t=\"e\"><v>#NUM!</v></c>");
                return;
            }
            buf.push_str("<c r=\"");
            buf.push_str(coord);
            buf.push_str("\"><v>");
            buf.push_str(ryu::Buffer::new().format(*n));
            buf.push_str("</v></c>");
        }
        CellValue::Boolean(b) => {
            buf.push_str("<c r=\"");
            buf.push_str(coord);
            buf.push_str("\" t=\"b\"><v>");
            buf.push_str(if *b { "1" } else { "0" });
            buf.push_str("</v></c>");
        }
        CellValue::Formula(f) => {
            let escaped = escape_xml(f);
            buf.push_str("<c r=\"");
            buf.push_str(coord);
            buf.push_str("\"><f>");
            buf.push_str(&escaped);
            buf.push_str("</f></c>");
        }
        CellValue::Date(d) => {
            let escaped = escape_xml(d);
            buf.push_str("<c r=\"");
            buf.push_str(coord);
            buf.push_str("\" t=\"d\"><v>");
            buf.push_str(&escaped);
            buf.push_str("</v></c>");
        }
        CellValue::Empty => {
            // Skip empty cells in streaming mode
        }
    }
}

/// Write `<c r="A1" s="3"` -- every cell starts this way. The closing bracket
/// is left to the caller, which may still need a `t` attribute.
#[inline]
fn write_cell_open(buf: &mut String, row: u32, col: u32, style_index: Option<u32>) {
    buf.push_str("<c r=\"");
    crate::utils::push_coordinate(buf, row, col);
    buf.push('"');
    if let Some(style) = style_index {
        buf.push_str(" s=\"");
        buf.push_str(itoa::Buffer::new().format(style));
        buf.push('"');
    }
}

/// Write the `<r>` runs of a rich-text string into an `<is>`/`<si>` body.
fn write_rich_runs(buf: &mut String, rich: &RichText) {
    for run in &rich.runs {
        buf.push_str("<r>");
        if let Some(font) = &run.font {
            write_run_props(buf, font);
        }
        let escaped = escape_xml(&run.text);
        if needs_space_preserve(&escaped) {
            buf.push_str("<t xml:space=\"preserve\">");
        } else {
            buf.push_str("<t>");
        }
        buf.push_str(&escaped);
        buf.push_str("</t></r>");
    }
}

/// Write an `<rPr>` run-property block. Child order follows the OOXML
/// CT_RPrElt schema (rFont, b, i, strike, color, sz, u, vertAlign).
fn write_run_props(buf: &mut String, font: &RunFont) {
    buf.push_str("<rPr>");
    if let Some(name) = &font.name {
        buf.push_str(&format!(r#"<rFont val="{}"/>"#, escape_xml(name)));
    }
    if font.bold {
        buf.push_str("<b/>");
    }
    if font.italic {
        buf.push_str("<i/>");
    }
    if font.strike {
        buf.push_str("<strike/>");
    }
    if let Some(color) = &font.color {
        write_color_attr(buf, "color", color);
    }
    if let Some(sz) = font.size {
        buf.push_str(&format!(r#"<sz val="{}"/>"#, sz));
    }
    if let Some(u) = &font.underline {
        if u == "single" {
            buf.push_str("<u/>");
        } else {
            buf.push_str(&format!(r#"<u val="{}"/>"#, u));
        }
    }
    if let Some(va) = &font.vert_align {
        buf.push_str(&format!(r#"<vertAlign val="{}"/>"#, va));
    }
    buf.push_str("</rPr>");
}

/// Write cell data directly to a string buffer (fast path, no quick_xml overhead).
/// Uses itoa/ryu for fast number formatting. The coordinate and style attribute
/// go straight into the buffer: building them as owned Strings first cost three
/// heap allocations per cell, which dominates on a million-cell sheet.
#[inline]
fn write_cell_direct(
    buf: &mut String,
    row: u32,
    col: u32,
    cell_data: &CellData,
    style_index: Option<u32>,
    shared_string_map: &HashMap<InternedString, usize>,
) {
    match &cell_data.value {
        CellValue::String(s) => {
            if let Some(rich) = &cell_data.rich_text {
                // Rich text: emit the runs inline (t="inlineStr"), preserving the
                // per-run formatting that a plain shared string cannot hold.
                write_cell_open(buf, row, col, style_index);
                buf.push_str(" t=\"inlineStr\"><is>");
                write_rich_runs(buf, rich);
                buf.push_str("</is></c>");
            } else if let Some(&idx) = shared_string_map.get(s) {
                // Shared string reference - use itoa for fast integer formatting
                write_cell_open(buf, row, col, style_index);
                buf.push_str(" t=\"s\"><v>");
                buf.push_str(itoa::Buffer::new().format(idx));
                buf.push_str("</v></c>");
            } else {
                // Inline string
                let escaped = escape_xml(s.as_ref());
                write_cell_open(buf, row, col, style_index);
                buf.push_str(" t=\"inlineStr\"><is>");
                if needs_space_preserve(&escaped) {
                    buf.push_str("<t xml:space=\"preserve\">");
                } else {
                    buf.push_str("<t>");
                }
                buf.push_str(&escaped);
                buf.push_str("</t></is></c>");
            }
        }
        CellValue::Number(n) => {
            if !n.is_finite() {
                // NaN/Infinity are not valid SpreadsheetML numbers; emit an error cell.
                write_cell_open(buf, row, col, style_index);
                buf.push_str(" t=\"e\"><v>#NUM!</v></c>");
                return;
            }
            // Use ryu for fast float formatting
            write_cell_open(buf, row, col, style_index);
            buf.push_str("><v>");
            buf.push_str(ryu::Buffer::new().format(*n));
            buf.push_str("</v></c>");
        }
        CellValue::Boolean(b) => {
            write_cell_open(buf, row, col, style_index);
            buf.push_str(" t=\"b\"><v>");
            buf.push_str(if *b { "1" } else { "0" });
            buf.push_str("</v></c>");
        }
        CellValue::Formula(f) => {
            let escaped = escape_xml(f);
            write_cell_open(buf, row, col, style_index);
            // The cached result's type rides on the t attribute (numeric when absent)
            if cell_data.cached_formula_value.is_some() {
                if let Some(t) = cell_data.data_type {
                    if matches!(t, "str" | "b" | "e") {
                        buf.push_str(" t=\"");
                        buf.push_str(t);
                        buf.push('"');
                    }
                }
            }
            buf.push_str("><f>");
            buf.push_str(&escaped);
            buf.push_str("</f>");
            if let Some(ref cached) = cell_data.cached_formula_value {
                buf.push_str("<v>");
                buf.push_str(&escape_xml(cached));
                buf.push_str("</v>");
            }
            buf.push_str("</c>");
        }
        CellValue::Date(d) => {
            let escaped = escape_xml(d);
            write_cell_open(buf, row, col, style_index);
            buf.push_str(" t=\"d\"><v>");
            buf.push_str(&escaped);
            buf.push_str("</v></c>");
        }
        CellValue::Empty => {
            // Skip empty cells without styles, but include if there's a style
            let Some(style) = style_index else {
                return;
            };
            write_cell_open(buf, row, col, Some(style));
            buf.push_str("/>");
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub fn write_content_types<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    sheet_count: usize,
    has_shared_strings: bool,
    comment_sheet_ids: &[u32],
    table_count: usize,
    chart_ids: &[u32],
    drawing_sheet_ids: &[u32],
    image_extensions: &[&str],
    pivot_part_paths: &[String],
) -> Result<()> {
    zip.start_file("[Content_Types].xml", options.clone())?;

    let mut writer = Writer::new(Cursor::new(Vec::new()));
    let mut types_start = BytesStart::new("Types");
    types_start.push_attribute((
        "xmlns",
        "http://schemas.openxmlformats.org/package/2006/content-types",
    ));
    writer.write_event(quick_xml::events::Event::Start(types_start))?;

    // Default overrides
    let mut default1 = BytesStart::new("Default");
    default1.push_attribute(("Extension", "rels"));
    default1.push_attribute((
        "ContentType",
        "application/vnd.openxmlformats-package.relationships+xml",
    ));
    writer.write_event(quick_xml::events::Event::Empty(default1))?;

    let mut default2 = BytesStart::new("Default");
    default2.push_attribute(("Extension", "xml"));
    default2.push_attribute(("ContentType", "application/xml"));
    writer.write_event(quick_xml::events::Event::Empty(default2))?;

    if !comment_sheet_ids.is_empty() {
        // Comment boxes are anchored by legacy VML drawings
        let mut default3 = BytesStart::new("Default");
        default3.push_attribute(("Extension", "vml"));
        default3.push_attribute((
            "ContentType",
            "application/vnd.openxmlformats-officedocument.vmlDrawing",
        ));
        writer.write_event(quick_xml::events::Event::Empty(default3))?;
    }

    // Embedded images are stored by extension in xl/media; each distinct
    // extension needs a Default content-type mapping.
    for ext in image_extensions {
        let content_type = match *ext {
            "png" => "image/png",
            "jpeg" | "jpg" => "image/jpeg",
            "gif" => "image/gif",
            "bmp" => "image/bmp",
            "tiff" | "tif" => "image/tiff",
            "emf" => "image/x-emf",
            "wmf" => "image/x-wmf",
            _ => continue,
        };
        let mut default_img = BytesStart::new("Default");
        default_img.push_attribute(("Extension", *ext));
        default_img.push_attribute(("ContentType", content_type));
        writer.write_event(quick_xml::events::Event::Empty(default_img))?;
    }

    // Overrides
    let mut override1 = BytesStart::new("Override");
    override1.push_attribute(("PartName", "/xl/workbook.xml"));
    override1.push_attribute((
        "ContentType",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
    ));
    writer.write_event(quick_xml::events::Event::Empty(override1))?;

    for i in 1..=sheet_count {
        let part_name = format!("/xl/worksheets/sheet{}.xml", i);
        let mut override_elem = BytesStart::new("Override");
        override_elem.push_attribute(("PartName", part_name.as_str()));
        override_elem.push_attribute((
            "ContentType",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
        ));
        writer.write_event(quick_xml::events::Event::Empty(override_elem))?;
    }

    // Only include sharedStrings if there are strings
    if has_shared_strings {
        let mut override2 = BytesStart::new("Override");
        override2.push_attribute(("PartName", "/xl/sharedStrings.xml"));
        override2.push_attribute((
            "ContentType",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
        ));
        writer.write_event(quick_xml::events::Event::Empty(override2))?;
    }

    let mut override3 = BytesStart::new("Override");
    override3.push_attribute(("PartName", "/xl/styles.xml"));
    override3.push_attribute((
        "ContentType",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
    ));
    writer.write_event(quick_xml::events::Event::Empty(override3))?;

    for sheet_id in comment_sheet_ids {
        let part_name = format!("/xl/comments/comment{}.xml", sheet_id);
        let mut override_elem = BytesStart::new("Override");
        override_elem.push_attribute(("PartName", part_name.as_str()));
        override_elem.push_attribute((
            "ContentType",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
        ));
        writer.write_event(quick_xml::events::Event::Empty(override_elem))?;
    }

    for table_id in 1..=table_count {
        let part_name = format!("/xl/tables/table{}.xml", table_id);
        let mut override_elem = BytesStart::new("Override");
        override_elem.push_attribute(("PartName", part_name.as_str()));
        override_elem.push_attribute((
            "ContentType",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
        ));
        writer.write_event(quick_xml::events::Event::Empty(override_elem))?;
    }

    for drawing_id in drawing_sheet_ids {
        let part_name = format!("/xl/drawings/drawing{}.xml", drawing_id);
        let mut override_elem = BytesStart::new("Override");
        override_elem.push_attribute(("PartName", part_name.as_str()));
        override_elem.push_attribute((
            "ContentType",
            "application/vnd.openxmlformats-officedocument.drawing+xml",
        ));
        writer.write_event(quick_xml::events::Event::Empty(override_elem))?;
    }

    for chart_id in chart_ids {
        let part_name = format!("/xl/charts/chart{}.xml", chart_id);
        let mut override_elem = BytesStart::new("Override");
        override_elem.push_attribute(("PartName", part_name.as_str()));
        override_elem.push_attribute((
            "ContentType",
            "application/vnd.openxmlformats-officedocument.drawingml.chart+xml",
        ));
        writer.write_event(quick_xml::events::Event::Empty(override_elem))?;
    }

    // Preserved pivot parts. Derive each part's content type from its path;
    // .rels parts use the already-declared default and are skipped here.
    for path in pivot_part_paths {
        let content_type = if path.ends_with(".rels") {
            continue;
        } else if path.contains("pivotCacheDefinition") {
            "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml"
        } else if path.contains("pivotCacheRecords") {
            "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml"
        } else if path.contains("pivotTable") {
            "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml"
        } else {
            continue;
        };
        let part_name = format!("/{}", path);
        let mut override_elem = BytesStart::new("Override");
        override_elem.push_attribute(("PartName", part_name.as_str()));
        override_elem.push_attribute(("ContentType", content_type));
        writer.write_event(quick_xml::events::Event::Empty(override_elem))?;
    }

    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("Types")))?;

    let result = writer.into_inner().into_inner();
    zip.write_all(&result)?;
    Ok(())
}

pub fn write_rels<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
) -> Result<()> {
    zip.start_file("_rels/.rels", options.clone())?;

    let content = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
</Relationships>"#;

    zip.write_all(content.as_bytes())?;
    Ok(())
}

pub fn write_doc_props<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
) -> Result<()> {
    // Write docProps/core.xml
    zip.start_file("docProps/core.xml", options.clone())?;
    let core_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</cp:coreProperties>"#;
    zip.write_all(core_xml.as_bytes())?;

    // Write docProps/app.xml
    zip.start_file("docProps/app.xml", options.clone())?;
    let app_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
<Application>RustyPyXL</Application>
</Properties>"#;
    zip.write_all(app_xml.as_bytes())?;

    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub fn write_workbook_xml<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    sheets: &[(String, SheetVisibility)],
    named_ranges: &[crate::workbook::NamedRange],
    active_tab: usize,
    date1904: bool,
    pivot_caches_xml: Option<&str>,
) -> Result<()> {
    zip.start_file("xl/workbook.xml", options.clone())?;

    let mut writer = Writer::new(Cursor::new(Vec::new()));
    let mut workbook_start = BytesStart::new("workbook");
    workbook_start.push_attribute((
        "xmlns",
        "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
    ));
    workbook_start.push_attribute((
        "xmlns:r",
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
    ));
    writer.write_event(quick_xml::events::Event::Start(workbook_start))?;

    // workbookPr
    let mut workbook_pr = BytesStart::new("workbookPr");
    if date1904 {
        workbook_pr.push_attribute(("date1904", "1"));
    }
    writer.write_event(quick_xml::events::Event::Empty(workbook_pr))?;

    // bookViews
    writer.write_event(quick_xml::events::Event::Start(BytesStart::new(
        "bookViews",
    )))?;
    let mut view = BytesStart::new("workbookView");
    view.push_attribute(("visibility", "visible"));
    view.push_attribute(("minimized", "0"));
    view.push_attribute(("showHorizontalScroll", "1"));
    view.push_attribute(("showVerticalScroll", "1"));
    view.push_attribute(("showSheetTabs", "1"));
    view.push_attribute(("tabRatio", "600"));
    view.push_attribute(("firstSheet", "0"));
    let active_tab = active_tab.min(sheets.len().saturating_sub(1));
    view.push_attribute(("activeTab", active_tab.to_string().as_str()));
    writer.write_event(quick_xml::events::Event::Empty(view))?;
    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("bookViews")))?;

    // sheets
    writer.write_event(quick_xml::events::Event::Start(BytesStart::new("sheets")))?;
    for (idx, (name, visibility)) in sheets.iter().enumerate() {
        let sheet_id = (idx + 1) as u32;
        let r_id = format!("rId{}", idx + 1);
        let mut sheet = BytesStart::new("sheet");
        sheet.push_attribute(("name", strip_illegal_xml_chars(name).as_ref()));
        sheet.push_attribute(("sheetId", sheet_id.to_string().as_str()));
        sheet.push_attribute(("state", visibility.as_str()));
        sheet.push_attribute(("r:id", r_id.as_str()));
        writer.write_event(quick_xml::events::Event::Empty(sheet))?;
    }
    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("sheets")))?;

    // definedNames (named ranges), preserving sheet scope and visibility
    if !named_ranges.is_empty() {
        writer.write_event(quick_xml::events::Event::Start(BytesStart::new(
            "definedNames",
        )))?;
        for nr in named_ranges {
            let mut defined_name = BytesStart::new("definedName");
            defined_name.push_attribute(("name", strip_illegal_xml_chars(&nr.name).as_ref()));
            if let Some(sheet_id) = nr.local_sheet_id {
                defined_name.push_attribute(("localSheetId", sheet_id.to_string().as_str()));
            }
            if nr.hidden {
                defined_name.push_attribute(("hidden", "1"));
            }
            writer.write_event(quick_xml::events::Event::Start(defined_name))?;
            writer.write_event(quick_xml::events::Event::Text(BytesText::new(
                &strip_illegal_xml_chars(&nr.range),
            )))?;
            writer.write_event(quick_xml::events::Event::End(BytesEnd::new("definedName")))?;
        }
        writer.write_event(quick_xml::events::Event::End(BytesEnd::new("definedNames")))?;
    }

    // pivotCaches (preserved verbatim) belongs after definedNames in the schema.
    if let Some(caches) = pivot_caches_xml {
        writer.get_mut().write_all(caches.as_bytes())?;
    }

    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("workbook")))?;

    let result = writer.into_inner().into_inner();
    zip.write_all(&result)?;
    Ok(())
}

pub fn write_workbook_rels<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    sheet_count: usize,
    has_shared_strings: bool,
    pivot_cache_rels: &[(String, String)],
) -> Result<()> {
    zip.start_file("xl/_rels/workbook.xml.rels", options.clone())?;

    let mut content = String::from(
        r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
"#,
    );

    for i in 1..=sheet_count {
        content.push_str(&format!(
            r#"<Relationship Id="rId{}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet{}.xml"/>
"#,
            i, i
        ));
    }

    // Only include sharedStrings if there are strings
    if has_shared_strings {
        content.push_str(r#"<Relationship Id="rIdSharedStrings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>
"#);
    }

    content.push_str(r#"<Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
"#);

    // Preserved pivotCacheDefinition relationships (renumbered ids).
    for (id, target) in pivot_cache_rels {
        content.push_str(&format!(
            r#"<Relationship Id="{}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition" Target="{}"/>
"#,
            id,
            escape_xml(target)
        ));
    }

    content.push_str("</Relationships>");

    zip.write_all(content.as_bytes())?;
    Ok(())
}

/// Returns (ordered list of strings, map from string -> index for O(1) lookup)
/// Returns the unique strings, the value-to-index map, and the total number of
/// cells referencing them (the sst `count`, as distinct from `uniqueCount`).
pub fn collect_shared_strings(
    worksheets: &[Worksheet],
) -> (Vec<InternedString>, HashMap<InternedString, usize>, usize) {
    // Estimate capacity: count string cells across all worksheets
    let estimated_strings: usize = worksheets
        .iter()
        .map(|ws| {
            ws.cells
                .values()
                .filter(|c| matches!(c.value, CellValue::String(_)))
                .count()
        })
        .sum();

    let mut strings = Vec::with_capacity(estimated_strings);
    let mut string_map = HashMap::with_capacity(estimated_strings);
    let mut total_refs = 0usize;

    for worksheet in worksheets {
        for cell_data in worksheet.cells.values() {
            // Rich-text cells are written inline (they carry per-run formatting a
            // shared plain string cannot hold), so they never reference the table.
            if cell_data.rich_text.is_some() {
                continue;
            }
            if let CellValue::String(s) = &cell_data.value {
                total_refs += 1;
                if !string_map.contains_key(s) {
                    string_map.insert(s.clone(), strings.len());
                    strings.push(s.clone());
                }
            }
        }
    }

    (strings, string_map, total_refs)
}

pub fn write_shared_strings<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    strings: &[InternedString],
    total_refs: usize,
) -> Result<()> {
    zip.start_file("xl/sharedStrings.xml", options.clone())?;

    // Pre-allocate buffer: ~50 bytes per string for XML overhead
    let estimated_size = strings.len() * 50 + 200;
    let mut writer = Writer::new(Cursor::new(Vec::with_capacity(estimated_size)));
    let mut sst = BytesStart::new("sst");
    sst.push_attribute((
        "xmlns",
        "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
    ));
    // count is the number of cells pointing into the table; uniqueCount the
    // number of entries in it.
    sst.push_attribute(("count", total_refs.to_string().as_str()));
    sst.push_attribute(("uniqueCount", strings.len().to_string().as_str()));
    writer.write_event(quick_xml::events::Event::Start(sst))?;

    for s in strings {
        writer.write_event(quick_xml::events::Event::Start(BytesStart::new("si")))?;
        write_text_element(&mut writer, "t", s.as_ref())?;
        writer.write_event(quick_xml::events::Event::End(BytesEnd::new("si")))?;
    }

    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("sst")))?;

    let result = writer.into_inner().into_inner();
    zip.write_all(&result)?;
    Ok(())
}

/// Write a color element to the XML string, handling theme and RGB colors.
///
/// Write a `<color>`/`<fgColor>`/`<bgColor>` element.
///
/// Exactly one of rgb, theme, or indexed identifies the color, and any of them
/// may carry a tint. rgb wins when more than one is set, since an explicit
/// value is the least surprising thing to honour.
fn write_color_attr(xml: &mut String, element: &str, color: &crate::style::Color) {
    xml.push('<');
    xml.push_str(element);

    if let Some(argb) = color.argb() {
        xml.push_str(&format!(r#" rgb="{}""#, escape_xml(&argb)));
    } else if let Some(theme) = color.theme {
        xml.push_str(&format!(r#" theme="{}""#, theme));
    } else if let Some(indexed) = color.indexed {
        xml.push_str(&format!(r#" indexed="{}""#, indexed));
    }

    if let Some(tint) = color.tint {
        if tint != 0.0 {
            xml.push_str(&format!(r#" tint="{}""#, tint));
        }
    }

    xml.push_str("/>");
}

/// Write a single font element to the XML string.
fn write_font_xml(xml: &mut String, font: &crate::style::Font) {
    xml.push_str("<font>");
    if font.bold {
        xml.push_str("<b/>");
    }
    if font.italic {
        xml.push_str("<i/>");
    }
    if let Some(ref u) = font.underline {
        if u == "single" {
            xml.push_str("<u/>");
        } else {
            xml.push_str(&format!(r#"<u val="{}"/>"#, u));
        }
    }
    if font.strike {
        xml.push_str("<strike/>");
    }
    if let Some(ref va) = font.vert_align {
        xml.push_str(&format!(r#"<vertAlign val="{}"/>"#, va));
    }
    if let Some(size) = font.size {
        xml.push_str(&format!(r#"<sz val="{}"/>"#, size));
    }
    if let Some(ref color) = font.color {
        write_color_attr(xml, "color", color);
    } else {
        xml.push_str(r#"<color theme="1"/>"#);
    }
    if let Some(ref name) = font.name {
        xml.push_str(&format!(r#"<name val="{}"/>"#, escape_xml(name)));
    } else {
        xml.push_str(r#"<name val="Calibri"/>"#);
    }
    xml.push_str(r#"<family val="2"/>"#);
    xml.push_str("</font>");
}

/// Write a single fill element to the XML string.
fn write_fill_xml(xml: &mut String, fill: &crate::style::Fill) {
    xml.push_str("<fill>");
    if let Some(ref pattern) = fill.pattern_type {
        xml.push_str(&format!(r#"<patternFill patternType="{}">"#, pattern));
        if let Some(ref fg) = fill.fg_color {
            write_color_attr(xml, "fgColor", fg);
        }
        if let Some(ref bg) = fill.bg_color {
            write_color_attr(xml, "bgColor", bg);
        }
        xml.push_str("</patternFill>");
    } else {
        xml.push_str("<patternFill/>");
    }
    xml.push_str("</fill>");
}

/// Write alignment element to the XML string.
fn write_alignment_xml(xml: &mut String, align: &crate::style::Alignment) {
    xml.push_str("<alignment");
    if let Some(ref h) = align.horizontal {
        xml.push_str(&format!(r#" horizontal="{}""#, h));
    }
    if let Some(ref v) = align.vertical {
        xml.push_str(&format!(r#" vertical="{}""#, v));
    }
    if align.wrap_text {
        xml.push_str(r#" wrapText="1""#);
    }
    if let Some(rot) = align.text_rotation {
        xml.push_str(&format!(r#" textRotation="{}""#, rot));
    }
    if align.shrink_to_fit {
        xml.push_str(r#" shrinkToFit="1""#);
    }
    xml.push_str("/>");
}

/// Write protection element to the XML string.
fn write_protection_xml(xml: &mut String, prot: &crate::style::Protection) {
    xml.push_str("<protection");
    xml.push_str(&format!(
        r#" locked="{}""#,
        if prot.locked { "1" } else { "0" }
    ));
    if prot.hidden {
        xml.push_str(r#" hidden="1""#);
    }
    xml.push_str("/>");
}

/// Write a single cellXf element to the XML string.
fn write_cell_xf_xml(xml: &mut String, xf: &crate::style::CellXf) {
    xml.push_str(&format!(
        r#"<xf numFmtId="{}" fontId="{}" fillId="{}" borderId="{}""#,
        xf.num_fmt_id, xf.font_id, xf.fill_id, xf.border_id
    ));
    if xf.apply_font {
        xml.push_str(r#" applyFont="1""#);
    }
    if xf.apply_fill {
        xml.push_str(r#" applyFill="1""#);
    }
    if xf.apply_border {
        xml.push_str(r#" applyBorder="1""#);
    }
    if xf.apply_number_format {
        xml.push_str(r#" applyNumberFormat="1""#);
    }
    if xf.alignment.is_some() {
        xml.push_str(r#" applyAlignment="1""#);
    }
    if xf.protection.is_some() {
        xml.push_str(r#" applyProtection="1""#);
    }

    let has_children = xf.alignment.is_some() || xf.protection.is_some();
    if has_children {
        xml.push('>');
        if let Some(ref align) = xf.alignment {
            write_alignment_xml(xml, align);
        }
        if let Some(ref prot) = xf.protection {
            write_protection_xml(xml, prot);
        }
        xml.push_str("</xf>");
    } else {
        xml.push_str("/>");
    }
}

/// Collect the deduplicated differential formats (dxf entries) used by all
/// conditional-formatting rules, in deterministic order. The index of a
/// format in this list is its dxfId, shared between styles.xml and each
/// worksheet's cfRule elements.
pub fn collect_dxfs(worksheets: &[Worksheet]) -> Vec<ConditionalFormat> {
    let mut dxfs: Vec<ConditionalFormat> = Vec::new();
    for ws in worksheets {
        for cf in &ws.conditional_formatting {
            for rule in &cf.rules {
                if let Some(fmt) = &rule.format {
                    if !dxfs.contains(fmt) {
                        dxfs.push(fmt.clone());
                    }
                }
            }
        }
    }
    dxfs
}

/// Write one color element for a dxf child (font color / bgColor / border color).
fn write_dxf_color(xml: &mut String, element: &str, color: &ConditionalColor) {
    xml.push('<');
    xml.push_str(element);
    if let Some(ref rgb) = color.rgb {
        let hex = rgb.strip_prefix('#').unwrap_or(rgb);
        if hex.len() >= 8 {
            xml.push_str(&format!(r#" rgb="{}""#, escape_xml(hex)));
        } else {
            xml.push_str(&format!(r#" rgb="FF{}""#, escape_xml(hex)));
        }
    } else if let Some(theme) = color.theme {
        xml.push_str(&format!(r#" theme="{}""#, theme));
    }
    if let Some(tint) = color.tint {
        xml.push_str(&format!(r#" tint="{}""#, tint));
    }
    xml.push_str("/>");
}

/// Write the dxfs (differential formats) section referenced by cfRule dxfId.
/// CT_Dxf child order: font, numFmt, fill, alignment, border, protection.
///
/// `next_num_fmt_id` is the first free id in the workbook's number-format
/// space; dxf formats are allocated from it so they cannot collide with the
/// workbook's custom formats.
fn write_dxfs_xml(xml: &mut String, dxfs: &[ConditionalFormat], mut next_num_fmt_id: usize) {
    if dxfs.is_empty() {
        xml.push_str(r#"<dxfs count="0"/>"#);
        return;
    }
    xml.push_str(&format!(r#"<dxfs count="{}">"#, dxfs.len()));
    for fmt in dxfs.iter() {
        xml.push_str("<dxf>");

        let has_font = fmt.font_color.is_some()
            || fmt.bold.is_some()
            || fmt.italic.is_some()
            || fmt.underline.is_some()
            || fmt.strikethrough.is_some();
        if has_font {
            xml.push_str("<font>");
            if let Some(b) = fmt.bold {
                xml.push_str(if b { "<b/>" } else { r#"<b val="0"/>"# });
            }
            if let Some(i) = fmt.italic {
                xml.push_str(if i { "<i/>" } else { r#"<i val="0"/>"# });
            }
            if let Some(st) = fmt.strikethrough {
                xml.push_str(if st {
                    "<strike/>"
                } else {
                    r#"<strike val="0"/>"#
                });
            }
            if let Some(u) = fmt.underline {
                xml.push_str(if u { "<u/>" } else { r#"<u val="none"/>"# });
            }
            if let Some(ref color) = fmt.font_color {
                write_dxf_color(xml, "color", color);
            }
            xml.push_str("</font>");
        }

        if let Some(ref code) = fmt.number_format {
            xml.push_str(&format!(
                r#"<numFmt numFmtId="{}" formatCode="{}"/>"#,
                next_num_fmt_id,
                escape_xml(code)
            ));
            next_num_fmt_id += 1;
        }

        if let Some(ref fill) = fmt.fill_color {
            // In a dxf, the highlight color of a solid pattern goes in bgColor
            xml.push_str("<fill><patternFill>");
            write_dxf_color(xml, "bgColor", fill);
            xml.push_str("</patternFill></fill>");
        }

        if let Some(ref border) = fmt.border_color {
            xml.push_str("<border>");
            for side in ["left", "right", "top", "bottom"] {
                xml.push_str(&format!(r#"<{} style="thin">"#, side));
                write_dxf_color(xml, "color", border);
                xml.push_str(&format!("</{}>", side));
            }
            xml.push_str("</border>");
        }

        xml.push_str("</dxf>");
    }
    xml.push_str("</dxfs>");
}

pub fn write_styles_xml<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    styles: &StyleRegistry,
    dxfs: &[ConditionalFormat],
) -> Result<()> {
    zip.start_file("xl/styles.xml", options.clone())?;

    let mut xml = String::with_capacity(4096);
    xml.push_str(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>"#);
    xml.push_str(
        r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">"#,
    );

    // Number formats
    if !styles.num_fmts.is_empty() {
        xml.push_str(&format!(r#"<numFmts count="{}">"#, styles.num_fmts.len()));
        for (id, code) in &styles.num_fmts {
            xml.push_str(&format!(
                r#"<numFmt numFmtId="{}" formatCode="{}"/>"#,
                id,
                escape_xml(code)
            ));
        }
        xml.push_str("</numFmts>");
    } else {
        xml.push_str(r#"<numFmts count="0"/>"#);
    }

    // Fonts
    xml.push_str(&format!(r#"<fonts count="{}">"#, styles.fonts.len()));
    for font in &styles.fonts {
        write_font_xml(&mut xml, font);
    }
    xml.push_str("</fonts>");

    // Fills
    xml.push_str(&format!(r#"<fills count="{}">"#, styles.fills.len()));
    for fill in &styles.fills {
        write_fill_xml(&mut xml, fill);
    }
    xml.push_str("</fills>");

    // Borders
    xml.push_str(&format!(r#"<borders count="{}">"#, styles.borders.len()));
    for border in &styles.borders {
        xml.push_str("<border>");
        write_border_side(&mut xml, "left", &border.left);
        write_border_side(&mut xml, "right", &border.right);
        write_border_side(&mut xml, "top", &border.top);
        write_border_side(&mut xml, "bottom", &border.bottom);
        write_border_side(&mut xml, "diagonal", &border.diagonal);
        xml.push_str("</border>");
    }
    xml.push_str("</borders>");

    // Cell style XFs (just one default)
    xml.push_str(r#"<cellStyleXfs count="1">"#);
    xml.push_str(r#"<xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>"#);
    xml.push_str("</cellStyleXfs>");

    // Cell XFs
    xml.push_str(&format!(r#"<cellXfs count="{}">"#, styles.cell_xfs.len()));
    for xf in &styles.cell_xfs {
        write_cell_xf_xml(&mut xml, xf);
    }
    xml.push_str("</cellXfs>");

    // Cell styles (just Normal)
    xml.push_str(r#"<cellStyles count="1">"#);
    xml.push_str(r#"<cellStyle name="Normal" xfId="0" builtinId="0"/>"#);
    xml.push_str("</cellStyles>");

    // Differential formats for conditional formatting (referenced by dxfId)
    // Custom number formats start at 164 (0-163 are builtins); dxf formats
    // continue above whatever the workbook already uses.
    let next_num_fmt_id = styles
        .num_fmts
        .iter()
        .map(|(id, _)| id + 1)
        .max()
        .unwrap_or(164)
        .max(164);
    write_dxfs_xml(&mut xml, dxfs, next_num_fmt_id);

    xml.push_str("</styleSheet>");

    zip.write_all(xml.as_bytes())?;
    Ok(())
}

/// Helper to write a border side element.
fn write_border_side(xml: &mut String, name: &str, side: &Option<crate::style::BorderStyle>) {
    if let Some(ref s) = side {
        xml.push_str(&format!(r#"<{} style="{}">"#, name, s.style));
        if let Some(ref color) = s.color {
            write_color_attr(xml, "color", color);
        }
        xml.push_str(&format!("</{}>", name));
    } else {
        xml.push_str(&format!("<{}/>", name));
    }
}

/// External (URL) hyperlinks in deterministic cell order. The position in
/// this list defines the relationship id (`rIdHL{i+1}`) shared between the
/// worksheet XML and its .rels part, so both must derive it from here.
pub fn collect_external_hyperlinks(worksheet: &Worksheet) -> Vec<((u32, u32), String)> {
    let mut links: Vec<((u32, u32), String)> = worksheet
        .cells
        .iter()
        .filter_map(|(key, cd)| {
            cd.hyperlink
                .as_ref()
                .filter(|url| !url.starts_with('#'))
                .map(|url| (decode_cell_key(*key), url.clone()))
        })
        .collect();
    links.sort_by_key(|(coord, _)| *coord);
    links
}

#[allow(clippy::too_many_arguments)]
pub fn write_worksheet_xml<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    worksheet: &Worksheet,
    sheet_id: u32,
    shared_string_map: &HashMap<InternedString, usize>,
    table_rel_ids: &[String],
    dxfs: &[ConditionalFormat],
    has_comments: bool,
    style_overrides: &HashMap<u64, u32>,
    drawing_rel_id: Option<&str>,
) -> Result<()> {
    let path = format!("xl/worksheets/sheet{}.xml", sheet_id);
    zip.start_file(&path, options.clone())?;

    // Pre-allocate buffer based on estimated size (rough estimate: 100 bytes per cell)
    let estimated_size = worksheet.cells.len() * 100;
    let mut writer = Writer::new(Cursor::new(Vec::with_capacity(estimated_size)));
    let mut worksheet_start = BytesStart::new("worksheet");
    worksheet_start.push_attribute((
        "xmlns",
        "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
    ));
    worksheet_start.push_attribute((
        "xmlns:r",
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
    ));
    writer.write_event(quick_xml::events::Event::Start(worksheet_start))?;

    // sheetPr
    writer.write_event(quick_xml::events::Event::Start(BytesStart::new("sheetPr")))?;
    let mut outline = BytesStart::new("outlinePr");
    outline.push_attribute(("summaryBelow", "1"));
    outline.push_attribute(("summaryRight", "1"));
    writer.write_event(quick_xml::events::Event::Empty(outline))?;
    writer.write_event(quick_xml::events::Event::Empty(BytesStart::new(
        "pageSetUpPr",
    )))?;
    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("sheetPr")))?;

    // dimension (if we have cells)
    if worksheet.max_row > 0 && worksheet.max_column > 0 {
        let start = "A1";
        let end = format!(
            "{}{}",
            column_to_letter(worksheet.max_column),
            worksheet.max_row
        );
        let mut dim = BytesStart::new("dimension");
        dim.push_attribute(("ref", format!("{}:{}", start, end).as_str()));
        writer.write_event(quick_xml::events::Event::Empty(dim))?;
    }

    // sheetViews
    writer.write_event(quick_xml::events::Event::Start(BytesStart::new(
        "sheetViews",
    )))?;
    let frozen = worksheet
        .freeze_panes
        .as_deref()
        .and_then(|cell| {
            crate::utils::parse_coordinate(cell)
                .ok()
                .map(|(row, col)| (cell, row, col))
        })
        .filter(|&(_, row, col)| row > 1 || col > 1);
    if let Some((cell, row, col)) = frozen {
        let x_split = col - 1;
        let y_split = row - 1;
        let active_pane = if x_split > 0 && y_split > 0 {
            "bottomRight"
        } else if y_split > 0 {
            "bottomLeft"
        } else {
            "topRight"
        };
        let mut view = BytesStart::new("sheetView");
        view.push_attribute(("workbookViewId", "0"));
        writer.write_event(quick_xml::events::Event::Start(view))?;
        let mut pane = BytesStart::new("pane");
        if x_split > 0 {
            pane.push_attribute(("xSplit", x_split.to_string().as_str()));
        }
        if y_split > 0 {
            pane.push_attribute(("ySplit", y_split.to_string().as_str()));
        }
        pane.push_attribute(("topLeftCell", cell));
        pane.push_attribute(("activePane", active_pane));
        pane.push_attribute(("state", "frozen"));
        writer.write_event(quick_xml::events::Event::Empty(pane))?;
        let mut selection = BytesStart::new("selection");
        selection.push_attribute(("pane", active_pane));
        selection.push_attribute(("activeCell", cell));
        selection.push_attribute(("sqref", cell));
        writer.write_event(quick_xml::events::Event::Empty(selection))?;
        writer.write_event(quick_xml::events::Event::End(BytesEnd::new("sheetView")))?;
    } else {
        let mut view = BytesStart::new("sheetView");
        view.push_attribute(("workbookViewId", "0"));
        writer.write_event(quick_xml::events::Event::Empty(view))?;
    }
    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("sheetViews")))?;

    // sheetFormatPr
    let mut format_pr = BytesStart::new("sheetFormatPr");
    format_pr.push_attribute(("baseColWidth", "8"));
    format_pr.push_attribute(("defaultRowHeight", "15"));
    writer.write_event(quick_xml::events::Event::Empty(format_pr))?;

    // cols (column dimensions)
    if !worksheet.column_dimensions.is_empty() {
        writer.write_event(quick_xml::events::Event::Start(BytesStart::new("cols")))?;
        for (&col, &width) in &worksheet.column_dimensions {
            let mut col_elem = BytesStart::new("col");
            col_elem.push_attribute(("min", col.to_string().as_str()));
            col_elem.push_attribute(("max", col.to_string().as_str()));
            col_elem.push_attribute(("width", width.to_string().as_str()));
            col_elem.push_attribute(("customWidth", "1"));
            writer.write_event(quick_xml::events::Event::Empty(col_elem))?;
        }
        writer.write_event(quick_xml::events::Event::End(BytesEnd::new("cols")))?;
    }

    // sheetData
    writer.write_event(quick_xml::events::Event::Start(BytesStart::new(
        "sheetData",
    )))?;

    // Group cells by row. Size by the populated-cell count, not max_row: a
    // sparse sheet with one cell at row 1,000,000 would otherwise reserve a
    // million buckets for a handful of entries.
    let estimated_rows = (worksheet.max_row as usize).min(worksheet.cells.len());
    type RowCells<'a> = HashMap<u32, Vec<((u32, u32), &'a CellData)>>;
    let mut rows: RowCells = HashMap::with_capacity(estimated_rows);
    for (key, cell_data) in &worksheet.cells {
        let (row, col) = decode_cell_key(*key);
        rows.entry(row).or_default().push(((row, col), cell_data));
    }

    // Write rows in order
    let mut row_numbers: Vec<u32> = rows.keys().copied().collect();
    row_numbers.sort();

    // Use Rayon to generate XML for rows in parallel
    // Each row is processed independently, then results are concatenated in order
    let cell_buf: String = if row_numbers.len() > 1000 {
        // For large worksheets, use parallel processing
        // Process in chunks to balance parallelism overhead vs benefit
        const CHUNK_SIZE: usize = 5000;

        let chunks: Vec<_> = row_numbers.chunks(CHUNK_SIZE).collect();
        let chunk_results: Vec<String> = chunks
            .par_iter()
            .map(|chunk| {
                let mut buf = String::with_capacity(chunk.len() * 200);
                let mut itoa_buf = itoa::Buffer::new();
                let mut ryu_buf = ryu::Buffer::new();

                for &row_num in *chunk {
                    let cells = rows.get(&row_num).unwrap();

                    // Sort cells by column (need to clone since we're in parallel)
                    let mut sorted_cells: Vec<_> = cells.to_vec();
                    sorted_cells.sort_by_key(|((_, col), _)| *col);

                    // Write row start
                    if let Some(height) = worksheet.row_dimensions.get(&row_num) {
                        buf.push_str("<row r=\"");
                        buf.push_str(itoa_buf.format(row_num));
                        buf.push_str("\" ht=\"");
                        buf.push_str(ryu_buf.format(*height));
                        buf.push_str("\" customHeight=\"1\">");
                    } else {
                        buf.push_str("<row r=\"");
                        buf.push_str(itoa_buf.format(row_num));
                        buf.push_str("\">");
                    }

                    // Write cells
                    for &((row, col), cell_data) in &sorted_cells {
                        let style_index = cell_data
                            .style_index
                            .or_else(|| style_overrides.get(&cell_key(row, col)).copied());
                        write_cell_direct(
                            &mut buf,
                            row,
                            col,
                            cell_data,
                            style_index,
                            shared_string_map,
                        );
                    }

                    buf.push_str("</row>");
                }
                buf
            })
            .collect();

        // Concatenate all chunks in order
        let total_len: usize = chunk_results.iter().map(|s| s.len()).sum();
        let mut result = String::with_capacity(total_len);
        for chunk in chunk_results {
            result.push_str(&chunk);
        }
        result
    } else {
        // For small worksheets, use sequential processing (less overhead)
        let mut buf = String::with_capacity(worksheet.cells.len() * 40);
        let mut itoa_buf = itoa::Buffer::new();
        let mut ryu_buf = ryu::Buffer::new();

        for row_num in row_numbers {
            let cells = rows.get_mut(&row_num).unwrap();
            cells.sort_by_key(|((_, col), _)| *col);

            if let Some(height) = worksheet.row_dimensions.get(&row_num) {
                buf.push_str("<row r=\"");
                buf.push_str(itoa_buf.format(row_num));
                buf.push_str("\" ht=\"");
                buf.push_str(ryu_buf.format(*height));
                buf.push_str("\" customHeight=\"1\">");
            } else {
                buf.push_str("<row r=\"");
                buf.push_str(itoa_buf.format(row_num));
                buf.push_str("\">");
            }

            for &((row, col), cell_data) in cells.iter() {
                let style_index = cell_data
                    .style_index
                    .or_else(|| style_overrides.get(&cell_key(row, col)).copied());
                write_cell_direct(
                    &mut buf,
                    row,
                    col,
                    cell_data,
                    style_index,
                    shared_string_map,
                );
            }

            buf.push_str("</row>");
        }
        buf
    };

    // Write the cell buffer to the XML writer
    writer.get_mut().write_all(cell_buf.as_bytes())?;

    writer.write_event(Event::End(BytesEnd::new("sheetData")))?;

    // sheetProtection (per CT_Worksheet schema order: directly after sheetData)
    if let Some(ref protection) = worksheet.protection {
        if protection.sheet {
            let mut sheet_protection = BytesStart::new("sheetProtection");
            sheet_protection.push_attribute(("sheet", "1"));
            sheet_protection.push_attribute((
                "selectLockedCells",
                if protection.select_locked_cells {
                    "1"
                } else {
                    "0"
                },
            ));
            sheet_protection.push_attribute((
                "selectUnlockedCells",
                if protection.select_unlocked_cells {
                    "1"
                } else {
                    "0"
                },
            ));
            sheet_protection.push_attribute((
                "formatCells",
                if protection.format_cells { "1" } else { "0" },
            ));
            sheet_protection.push_attribute((
                "formatColumns",
                if protection.format_columns { "1" } else { "0" },
            ));
            sheet_protection
                .push_attribute(("formatRows", if protection.format_rows { "1" } else { "0" }));
            sheet_protection.push_attribute((
                "insertColumns",
                if protection.insert_columns { "1" } else { "0" },
            ));
            sheet_protection
                .push_attribute(("insertRows", if protection.insert_rows { "1" } else { "0" }));
            sheet_protection.push_attribute((
                "insertHyperlinks",
                if protection.insert_hyperlinks {
                    "1"
                } else {
                    "0"
                },
            ));
            sheet_protection.push_attribute((
                "deleteColumns",
                if protection.delete_columns { "1" } else { "0" },
            ));
            sheet_protection
                .push_attribute(("deleteRows", if protection.delete_rows { "1" } else { "0" }));
            sheet_protection.push_attribute(("sort", if protection.sort { "1" } else { "0" }));
            sheet_protection
                .push_attribute(("autoFilter", if protection.auto_filter { "1" } else { "0" }));
            sheet_protection.push_attribute((
                "pivotTables",
                if protection.pivot_tables { "1" } else { "0" },
            ));
            sheet_protection
                .push_attribute(("objects", if protection.objects { "1" } else { "0" }));
            sheet_protection
                .push_attribute(("scenarios", if protection.scenarios { "1" } else { "0" }));
            // The password attribute holds the legacy 16-bit verifier hash, never
            // the plaintext. A value loaded from an existing file is already hashed.
            if let Some(ref hash) = protection.password_hash {
                sheet_protection.push_attribute(("password", hash.as_str()));
            } else if let Some(ref pwd) = protection.password {
                let hash = format!("{:04X}", legacy_password_hash(pwd));
                sheet_protection.push_attribute(("password", hash.as_str()));
            }
            writer.write_event(quick_xml::events::Event::Empty(sheet_protection))?;
        }
    }

    // autoFilter
    if let Some(ref auto_filter) = worksheet.auto_filter {
        write_auto_filter(&mut writer, auto_filter)?;
    }

    // mergeCells
    if !worksheet.merged_cells.is_empty() {
        let mut merge_cells = BytesStart::new("mergeCells");
        merge_cells.push_attribute(("count", worksheet.merged_cells.len().to_string().as_str()));
        writer.write_event(quick_xml::events::Event::Start(merge_cells))?;
        for (start, end) in &worksheet.merged_cells {
            let mut merge_cell = BytesStart::new("mergeCell");
            merge_cell.push_attribute(("ref", format!("{}:{}", start, end).as_str()));
            writer.write_event(quick_xml::events::Event::Empty(merge_cell))?;
        }
        writer.write_event(Event::End(BytesEnd::new("mergeCells")))?;
    }

    // conditionalFormatting
    if !worksheet.conditional_formatting.is_empty() {
        for cf in &worksheet.conditional_formatting {
            write_conditional_formatting(&mut writer, cf, dxfs)?;
        }
    }

    // dataValidations (per schema order: after conditionalFormatting, before hyperlinks)
    if !worksheet.data_validations.is_empty() {
        let mut data_validations = BytesStart::new("dataValidations");
        data_validations.push_attribute((
            "count",
            worksheet.data_validations.len().to_string().as_str(),
        ));
        writer.write_event(quick_xml::events::Event::Start(data_validations))?;

        for ((row, col), validation) in &worksheet.data_validations {
            let coord = format!("{}{}", column_to_letter(*col), row);
            let mut dv = BytesStart::new("dataValidation");
            dv.push_attribute((
                "type",
                strip_illegal_xml_chars(&validation.validation_type).as_ref(),
            ));
            if let Some(ref operator) = validation.operator {
                dv.push_attribute(("operator", strip_illegal_xml_chars(operator).as_ref()));
            }
            dv.push_attribute(("allowBlank", if validation.allow_blank { "1" } else { "0" }));
            dv.push_attribute((
                "showErrorMessage",
                if validation.show_error { "1" } else { "0" },
            ));
            dv.push_attribute((
                "showInputMessage",
                if validation.show_input { "1" } else { "0" },
            ));
            // The dialog text: without these, showErrorMessage="1" only gets
            // Excel's generic message, and the rule's own wording is lost.
            if let Some(ref style) = validation.error_style {
                dv.push_attribute(("errorStyle", strip_illegal_xml_chars(style).as_ref()));
            }
            if let Some(ref title) = validation.error_title {
                dv.push_attribute(("errorTitle", strip_illegal_xml_chars(title).as_ref()));
            }
            if let Some(ref message) = validation.error_message {
                dv.push_attribute(("error", strip_illegal_xml_chars(message).as_ref()));
            }
            if let Some(ref title) = validation.prompt_title {
                dv.push_attribute(("promptTitle", strip_illegal_xml_chars(title).as_ref()));
            }
            if let Some(ref message) = validation.prompt_message {
                dv.push_attribute(("prompt", strip_illegal_xml_chars(message).as_ref()));
            }
            // A loaded rule may span multiple cells; fall back to the key cell
            dv.push_attribute((
                "sqref",
                strip_illegal_xml_chars(validation.sqref.as_deref().unwrap_or(coord.as_str()))
                    .as_ref(),
            ));
            writer.write_event(quick_xml::events::Event::Start(dv))?;
            if let Some(ref f1) = validation.formula1 {
                write_text_element(&mut writer, "formula1", f1)?;
            }
            if let Some(ref f2) = validation.formula2 {
                write_text_element(&mut writer, "formula2", f2)?;
            }
            writer.write_event(quick_xml::events::Event::End(BytesEnd::new(
                "dataValidation",
            )))?;
        }
        writer.write_event(quick_xml::events::Event::End(BytesEnd::new(
            "dataValidations",
        )))?;
    }

    // hyperlinks: external URLs reference the sheet rels via r:id; internal
    // links (stored with a '#' prefix) use the location attribute.
    let external_links = collect_external_hyperlinks(worksheet);
    let mut internal_links: Vec<((u32, u32), String)> = worksheet
        .cells
        .iter()
        .filter_map(|(key, cd)| {
            cd.hyperlink
                .as_ref()
                .filter(|url| url.starts_with('#'))
                .map(|url| (decode_cell_key(*key), url.clone()))
        })
        .collect();
    internal_links.sort_by_key(|(coord, _)| *coord);

    if !external_links.is_empty() || !internal_links.is_empty() {
        // CT_Hyperlinks has no count attribute, unlike mergeCells/dataValidations
        let hyperlinks = BytesStart::new("hyperlinks");
        writer.write_event(quick_xml::events::Event::Start(hyperlinks))?;

        for (i, ((row, col), _url)) in external_links.iter().enumerate() {
            let coord = format!("{}{}", column_to_letter(*col), row);
            let rel_id = format!("rIdHL{}", i + 1);
            let mut hyperlink = BytesStart::new("hyperlink");
            hyperlink.push_attribute(("ref", coord.as_str()));
            hyperlink.push_attribute(("r:id", rel_id.as_str()));
            writer.write_event(quick_xml::events::Event::Empty(hyperlink))?;
        }

        for ((row, col), url) in internal_links {
            let coord = format!("{}{}", column_to_letter(col), row);
            let mut hyperlink = BytesStart::new("hyperlink");
            hyperlink.push_attribute(("ref", coord.as_str()));
            // The location attribute holds the anchor without the '#' prefix
            hyperlink.push_attribute((
                "location",
                strip_illegal_xml_chars(url.trim_start_matches('#')).as_ref(),
            ));
            writer.write_event(quick_xml::events::Event::Empty(hyperlink))?;
        }

        writer.write_event(quick_xml::events::Event::End(BytesEnd::new("hyperlinks")))?;
    }

    // printOptions (per schema order: after hyperlinks, before pageMargins)
    if let Some(ref ps) = worksheet.page_setup {
        write_print_options(&mut writer, ps)?;
    }

    // pageMargins - use PageSetup values if available
    let mut margins = BytesStart::new("pageMargins");
    if let Some(ref ps) = worksheet.page_setup {
        margins.push_attribute(("left", ps.margins.left.to_string().as_str()));
        margins.push_attribute(("right", ps.margins.right.to_string().as_str()));
        margins.push_attribute(("top", ps.margins.top.to_string().as_str()));
        margins.push_attribute(("bottom", ps.margins.bottom.to_string().as_str()));
        margins.push_attribute(("header", ps.margins.header.to_string().as_str()));
        margins.push_attribute(("footer", ps.margins.footer.to_string().as_str()));
    } else {
        margins.push_attribute(("left", "0.75"));
        margins.push_attribute(("right", "0.75"));
        margins.push_attribute(("top", "1"));
        margins.push_attribute(("bottom", "1"));
        margins.push_attribute(("header", "0.5"));
        margins.push_attribute(("footer", "0.5"));
    }
    writer.write_event(Event::Empty(margins))?;

    // pageSetup
    if let Some(ref ps) = worksheet.page_setup {
        write_page_setup(&mut writer, ps)?;
    }

    // drawing anchors the part holding this sheet's charts/images
    if let Some(rel) = drawing_rel_id {
        let mut drawing = BytesStart::new("drawing");
        drawing.push_attribute(("r:id", rel));
        writer.write_event(quick_xml::events::Event::Empty(drawing))?;
    }

    // legacyDrawing anchors the VML part Excel needs to display comments
    if has_comments {
        let mut legacy = BytesStart::new("legacyDrawing");
        legacy.push_attribute(("r:id", "rIdVml"));
        writer.write_event(quick_xml::events::Event::Empty(legacy))?;
    }

    // tableParts (near the end of CT_Worksheet)
    if !table_rel_ids.is_empty() {
        let mut table_parts = BytesStart::new("tableParts");
        table_parts.push_attribute(("count", table_rel_ids.len().to_string().as_str()));
        writer.write_event(quick_xml::events::Event::Start(table_parts))?;
        for rel_id in table_rel_ids {
            let mut part = BytesStart::new("tablePart");
            part.push_attribute(("r:id", rel_id.as_str()));
            writer.write_event(quick_xml::events::Event::Empty(part))?;
        }
        writer.write_event(quick_xml::events::Event::End(BytesEnd::new("tableParts")))?;
    }

    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("worksheet")))?;

    let result = writer.into_inner().into_inner();
    zip.write_all(&result)?;
    Ok(())
}

pub fn write_comments_xml<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    worksheet: &Worksheet,
    sheet_id: u32,
) -> Result<bool> {
    // Collect comments
    let comment_cells: Vec<((u32, u32), String)> = worksheet
        .cells
        .iter()
        .filter_map(|(key, cell_data)| {
            cell_data.comment.as_ref().map(|comment| {
                let (row, col) = decode_cell_key(*key);
                ((row, col), comment.clone())
            })
        })
        .collect();

    if comment_cells.is_empty() {
        return Ok(false); // No comments to write
    }

    let path = format!("xl/comments/comment{}.xml", sheet_id);
    zip.start_file(&path, options.clone())?;

    let mut writer = Writer::new(Cursor::new(Vec::new()));
    let mut comments_start = BytesStart::new("comments");
    comments_start.push_attribute((
        "xmlns",
        "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
    ));
    writer.write_event(quick_xml::events::Event::Start(comments_start))?;

    // authors
    writer.write_event(quick_xml::events::Event::Start(BytesStart::new("authors")))?;
    writer.write_event(quick_xml::events::Event::Start(BytesStart::new("author")))?;
    writer.write_event(quick_xml::events::Event::Text(BytesText::new("RustyPyXL")))?;
    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("author")))?;
    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("authors")))?;

    // commentList
    let mut comment_list = BytesStart::new("commentList");
    comment_list.push_attribute(("count", comment_cells.len().to_string().as_str()));
    writer.write_event(quick_xml::events::Event::Start(comment_list))?;

    for ((row, col), comment_text) in comment_cells {
        let coord = format!("{}{}", column_to_letter(col), row);
        let mut comment = BytesStart::new("comment");
        comment.push_attribute(("ref", coord.as_str()));
        comment.push_attribute(("authorId", "0"));
        comment.push_attribute(("shapeId", "0"));
        writer.write_event(quick_xml::events::Event::Start(comment))?;

        // text
        writer.write_event(quick_xml::events::Event::Start(BytesStart::new("text")))?;
        write_text_element(&mut writer, "t", &comment_text)?;
        writer.write_event(quick_xml::events::Event::End(BytesEnd::new("text")))?;

        writer.write_event(quick_xml::events::Event::End(BytesEnd::new("comment")))?;
    }

    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("commentList")))?;
    writer.write_event(quick_xml::events::Event::End(BytesEnd::new("comments")))?;

    let result = writer.into_inner().into_inner();
    zip.write_all(&result)?;
    Ok(true) // Comments were written
}

/// Write autoFilter element.
fn write_auto_filter<W: std::io::Write>(
    writer: &mut Writer<W>,
    auto_filter: &crate::autofilter::AutoFilter,
) -> Result<()> {
    let mut af = BytesStart::new("autoFilter");
    af.push_attribute(("ref", auto_filter.range.as_str()));

    if auto_filter.columns.is_empty() {
        writer.write_event(Event::Empty(af))?;
    } else {
        writer.write_event(Event::Start(af))?;

        for col_filter in &auto_filter.columns {
            let mut filter_col = BytesStart::new("filterColumn");
            filter_col.push_attribute(("colId", col_filter.column_id.to_string().as_str()));
            if !col_filter.show_button {
                filter_col.push_attribute(("hiddenButton", "1"));
            }
            writer.write_event(Event::Start(filter_col))?;

            match &col_filter.filter {
                FilterType::Values(values) => {
                    writer.write_event(Event::Start(BytesStart::new("filters")))?;
                    for value in values {
                        let mut filter = BytesStart::new("filter");
                        filter.push_attribute(("val", value.as_str()));
                        writer.write_event(Event::Empty(filter))?;
                    }
                    writer.write_event(Event::End(BytesEnd::new("filters")))?;
                }
                FilterType::Custom(custom) => {
                    let mut custom_filters = BytesStart::new("customFilters");
                    if !custom.and {
                        custom_filters.push_attribute(("and", "0"));
                    }
                    writer.write_event(Event::Start(custom_filters))?;

                    let mut cf1 = BytesStart::new("customFilter");
                    cf1.push_attribute(("operator", custom.operator1.xml_value()));
                    cf1.push_attribute(("val", custom.value1.as_str()));
                    writer.write_event(Event::Empty(cf1))?;

                    if let (Some(op2), Some(val2)) = (&custom.operator2, &custom.value2) {
                        let mut cf2 = BytesStart::new("customFilter");
                        cf2.push_attribute(("operator", op2.xml_value()));
                        cf2.push_attribute(("val", val2.as_str()));
                        writer.write_event(Event::Empty(cf2))?;
                    }

                    writer.write_event(Event::End(BytesEnd::new("customFilters")))?;
                }
                FilterType::DynamicFilter(df) => {
                    let mut dyn_filter = BytesStart::new("dynamicFilter");
                    dyn_filter.push_attribute(("type", df.xml_type()));
                    writer.write_event(Event::Empty(dyn_filter))?;
                }
                FilterType::Top10Filter(top10) => {
                    let mut t10 = BytesStart::new("top10");
                    t10.push_attribute(("top", if top10.top { "1" } else { "0" }));
                    t10.push_attribute(("percent", if top10.percent { "1" } else { "0" }));
                    t10.push_attribute(("val", top10.value.to_string().as_str()));
                    writer.write_event(Event::Empty(t10))?;
                }
                FilterType::ColorFilter(cf) => {
                    let mut color_filter = BytesStart::new("colorFilter");
                    color_filter
                        .push_attribute(("cellColor", if cf.cell_color { "1" } else { "0" }));
                    // The color itself is a dxf reference, not a literal value
                    if !cf.color.is_empty() {
                        color_filter
                            .push_attribute(("dxfId", strip_illegal_xml_chars(&cf.color).as_ref()));
                    }
                    writer.write_event(Event::Empty(color_filter))?;
                }
            }

            writer.write_event(Event::End(BytesEnd::new("filterColumn")))?;
        }

        // Sort state
        if let Some(sort_col) = auto_filter.sort_column {
            let mut sort_state = BytesStart::new("sortState");
            sort_state.push_attribute(("ref", auto_filter.range.as_str()));
            writer.write_event(Event::Start(sort_state))?;

            let mut sort_cond = BytesStart::new("sortCondition");
            if auto_filter.sort_descending {
                sort_cond.push_attribute(("descending", "1"));
            }
            sort_cond.push_attribute((
                "ref",
                format!(
                    "{}:{}",
                    column_to_letter(sort_col + 1),
                    column_to_letter(sort_col + 1)
                )
                .as_str(),
            ));
            writer.write_event(Event::Empty(sort_cond))?;

            writer.write_event(Event::End(BytesEnd::new("sortState")))?;
        }

        writer.write_event(Event::End(BytesEnd::new("autoFilter")))?;
    }

    Ok(())
}

/// Write a conditional color element.
fn write_conditional_color<W: std::io::Write>(
    writer: &mut Writer<W>,
    color: &crate::conditional::ConditionalColor,
) -> Result<()> {
    let mut color_elem = BytesStart::new("color");
    if let Some(ref rgb) = color.rgb {
        color_elem.push_attribute(("rgb", rgb.as_str()));
    }
    if let Some(theme) = color.theme {
        color_elem.push_attribute(("theme", theme.to_string().as_str()));
    }
    if let Some(tint) = color.tint {
        color_elem.push_attribute(("tint", tint.to_string().as_str()));
    }
    writer.write_event(Event::Empty(color_elem))?;
    Ok(())
}

/// Write conditionalFormatting element.
/// Excel evaluates text/blank/error/time-period rules through a hidden
/// formula anchored at the top-left cell of the rule's range; without it
/// the rule never matches. Returns None for rule types that don't need one
/// or when the caller supplied formula1 explicitly.
fn implied_rule_formula(
    rule: &crate::conditional::ConditionalRule,
    anchor: &str,
) -> Option<String> {
    if rule.formula1.is_some() {
        return None;
    }
    let text = rule.text.as_deref().unwrap_or("");
    // Embedded quotes in the matched text are doubled in Excel formulas
    let quoted = format!("\"{}\"", text.replace('"', "\"\""));
    match rule.rule_type {
        ConditionalFormatType::ContainsText => {
            Some(format!("NOT(ISERROR(SEARCH({},{})))", quoted, anchor))
        }
        ConditionalFormatType::NotContainsText => {
            Some(format!("ISERROR(SEARCH({},{}))", quoted, anchor))
        }
        ConditionalFormatType::BeginsWith => {
            Some(format!("LEFT({},LEN({}))={}", anchor, quoted, quoted))
        }
        ConditionalFormatType::EndsWith => {
            Some(format!("RIGHT({},LEN({}))={}", anchor, quoted, quoted))
        }
        ConditionalFormatType::ContainsBlanks => Some(format!("LEN(TRIM({}))=0", anchor)),
        ConditionalFormatType::NotContainsBlanks => Some(format!("LEN(TRIM({}))>0", anchor)),
        ConditionalFormatType::ContainsErrors => Some(format!("ISERROR({})", anchor)),
        ConditionalFormatType::NotContainsErrors => Some(format!("NOT(ISERROR({}))", anchor)),
        ConditionalFormatType::TimePeriod => {
            let period = rule.time_period.as_deref()?;
            Some(match period {
                "today" => format!("FLOOR({},1)=TODAY()", anchor),
                "yesterday" => format!("FLOOR({},1)=TODAY()-1", anchor),
                "tomorrow" => format!("FLOOR({},1)=TODAY()+1", anchor),
                "last7Days" => format!(
                    "AND(TODAY()-FLOOR({},1)<=6,FLOOR({},1)<=TODAY())",
                    anchor, anchor
                ),
                "thisWeek" => format!(
                    "AND(TODAY()-ROUNDDOWN({},0)<=WEEKDAY(TODAY())-1,ROUNDDOWN({},0)-TODAY()<=7-WEEKDAY(TODAY()))",
                    anchor, anchor
                ),
                "lastWeek" => format!(
                    "AND(TODAY()-ROUNDDOWN({},0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN({},0)<(WEEKDAY(TODAY())+7))",
                    anchor, anchor
                ),
                "nextWeek" => format!(
                    "AND(ROUNDDOWN({},0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN({},0)-TODAY()<(15-WEEKDAY(TODAY())))",
                    anchor, anchor
                ),
                "thisMonth" => format!(
                    "AND(MONTH({})=MONTH(TODAY()),YEAR({})=YEAR(TODAY()))",
                    anchor, anchor
                ),
                "lastMonth" => format!(
                    "AND(MONTH({})=MONTH(EDATE(TODAY(),0-1)),YEAR({})=YEAR(EDATE(TODAY(),0-1)))",
                    anchor, anchor
                ),
                "nextMonth" => format!(
                    "AND(MONTH({})=MONTH(EDATE(TODAY(),0+1)),YEAR({})=YEAR(EDATE(TODAY(),0+1)))",
                    anchor, anchor
                ),
                _ => return None,
            })
        }
        _ => None,
    }
}

/// Default icon-set thresholds: N icons split the range into N equal
/// percent bands (Excel's own defaults), e.g. 3 icons -> 0/33/67.
fn default_icon_thresholds(icon_count: u32) -> Vec<(String, String)> {
    (0..icon_count)
        .map(|i| ("percent".to_string(), ((100 * i) / icon_count).to_string()))
        .collect()
}

fn write_conditional_formatting<W: std::io::Write>(
    writer: &mut Writer<W>,
    cf: &crate::conditional::ConditionalFormatting,
    dxfs: &[ConditionalFormat],
) -> Result<()> {
    let mut cond_fmt = BytesStart::new("conditionalFormatting");
    cond_fmt.push_attribute(("sqref", cf.range.as_str()));
    writer.write_event(Event::Start(cond_fmt))?;

    // Top-left cell of the range, used to anchor implied formulas
    let anchor: String = cf
        .range
        .split([':', ' '])
        .next()
        .unwrap_or("A1")
        .replace('$', "");

    for rule in &cf.rules {
        let mut cf_rule = BytesStart::new("cfRule");
        cf_rule.push_attribute(("type", rule.rule_type.xml_value()));

        // dxfId ties the rule to its differential format in styles.xml;
        // without it the rule matches but applies no formatting
        if let Some(ref fmt) = rule.format {
            if let Some(dxf_id) = dxfs.iter().position(|d| d == fmt) {
                cf_rule.push_attribute(("dxfId", dxf_id.to_string().as_str()));
            }
        }

        cf_rule.push_attribute(("priority", rule.priority.to_string().as_str()));

        // Operator for cellIs rules
        if rule.rule_type == ConditionalFormatType::CellIs {
            if let Some(ref op) = rule.operator {
                cf_rule.push_attribute(("operator", op.xml_value()));
            }
        }

        // Top10 attributes
        if rule.rule_type == ConditionalFormatType::Top10 {
            if let Some(rank) = rule.rank {
                cf_rule.push_attribute(("rank", rank.to_string().as_str()));
            }
            if rule.percent {
                cf_rule.push_attribute(("percent", "1"));
            }
            if rule.bottom {
                cf_rule.push_attribute(("bottom", "1"));
            }
        }

        // AboveAverage attributes
        if rule.rule_type == ConditionalFormatType::AboveAverage {
            if !rule.above_average {
                cf_rule.push_attribute(("aboveAverage", "0"));
            }
            if rule.equal_average {
                cf_rule.push_attribute(("equalAverage", "1"));
            }
            if let Some(std_dev) = rule.std_dev {
                cf_rule.push_attribute(("stdDev", std_dev.to_string().as_str()));
            }
        }

        // Required timePeriod attribute for date rules
        if rule.rule_type == ConditionalFormatType::TimePeriod {
            if let Some(ref period) = rule.time_period {
                cf_rule.push_attribute(("timePeriod", period.as_str()));
            }
        }

        // Text value for text rules
        if let Some(ref text) = rule.text {
            cf_rule.push_attribute(("text", text.as_str()));
        }

        if rule.stop_if_true {
            cf_rule.push_attribute(("stopIfTrue", "1"));
        }

        writer.write_event(Event::Start(cf_rule))?;

        // Write formula if present, or the formula Excel requires for
        // text/blank/error/time-period rules
        let implied = implied_rule_formula(rule, &anchor);
        if let Some(formula) = rule.formula1.as_deref().or(implied.as_deref()) {
            write_text_element(writer, "formula", formula)?;
        }
        if let Some(ref formula) = rule.formula2 {
            write_text_element(writer, "formula", formula)?;
        }

        // ColorScale
        if let Some(ref cs) = rule.color_scale {
            writer.write_event(Event::Start(BytesStart::new("colorScale")))?;

            // cfvo elements
            let mut cfvo1 = BytesStart::new("cfvo");
            cfvo1.push_attribute(("type", cs.min_type.as_str()));
            if let Some(ref val) = cs.min_value {
                cfvo1.push_attribute(("val", val.as_str()));
            }
            writer.write_event(Event::Empty(cfvo1))?;

            if let (Some(ref mid_type), Some(_)) = (&cs.mid_type, &cs.mid_color) {
                let mut cfvo2 = BytesStart::new("cfvo");
                cfvo2.push_attribute(("type", mid_type.as_str()));
                if let Some(ref val) = cs.mid_value {
                    cfvo2.push_attribute(("val", val.as_str()));
                }
                writer.write_event(Event::Empty(cfvo2))?;
            }

            let mut cfvo3 = BytesStart::new("cfvo");
            cfvo3.push_attribute(("type", cs.max_type.as_str()));
            if let Some(ref val) = cs.max_value {
                cfvo3.push_attribute(("val", val.as_str()));
            }
            writer.write_event(Event::Empty(cfvo3))?;

            // color elements
            write_conditional_color(&mut *writer, &cs.min_color)?;

            if let Some(ref mid_color) = cs.mid_color {
                write_conditional_color(&mut *writer, mid_color)?;
            }

            write_conditional_color(&mut *writer, &cs.max_color)?;

            writer.write_event(Event::End(BytesEnd::new("colorScale")))?;
        }

        // DataBar
        if let Some(ref db) = rule.data_bar {
            let mut data_bar = BytesStart::new("dataBar");
            if !db.show_value {
                data_bar.push_attribute(("showValue", "0"));
            }
            writer.write_event(Event::Start(data_bar))?;

            let mut cfvo1 = BytesStart::new("cfvo");
            cfvo1.push_attribute(("type", db.min_type.as_str()));
            if let Some(ref val) = db.min_value {
                cfvo1.push_attribute(("val", val.as_str()));
            }
            writer.write_event(Event::Empty(cfvo1))?;

            let mut cfvo2 = BytesStart::new("cfvo");
            cfvo2.push_attribute(("type", db.max_type.as_str()));
            if let Some(ref val) = db.max_value {
                cfvo2.push_attribute(("val", val.as_str()));
            }
            writer.write_event(Event::Empty(cfvo2))?;

            write_conditional_color(&mut *writer, &db.fill_color)?;

            writer.write_event(Event::End(BytesEnd::new("dataBar")))?;
        }

        // IconSet
        if let Some(ref is) = rule.icon_set {
            let mut icon_set = BytesStart::new("iconSet");
            icon_set.push_attribute(("iconSet", is.style.xml_type()));
            if !is.show_value {
                icon_set.push_attribute(("showValue", "0"));
            }
            if is.reverse {
                icon_set.push_attribute(("reverse", "1"));
            }
            writer.write_event(Event::Start(icon_set))?;

            // CT_IconSet requires one cfvo per icon (>= 2); an empty
            // thresholds list previously produced files Excel repairs away
            let icon_count: u32 = is
                .style
                .xml_type()
                .chars()
                .next()
                .and_then(|c| c.to_digit(10))
                .unwrap_or(3);
            let defaults;
            let thresholds: &[(String, String)] = if is.thresholds.is_empty() {
                defaults = default_icon_thresholds(icon_count);
                &defaults
            } else {
                &is.thresholds
            };

            for (threshold_type, threshold_val) in thresholds {
                let mut cfvo = BytesStart::new("cfvo");
                cfvo.push_attribute(("type", threshold_type.as_str()));
                if !threshold_val.is_empty() {
                    cfvo.push_attribute(("val", threshold_val.as_str()));
                }
                writer.write_event(Event::Empty(cfvo))?;
            }

            writer.write_event(Event::End(BytesEnd::new("iconSet")))?;
        }

        writer.write_event(Event::End(BytesEnd::new("cfRule")))?;
    }

    writer.write_event(Event::End(BytesEnd::new("conditionalFormatting")))?;

    Ok(())
}

/// Write pageSetup element.
fn write_page_setup<W: std::io::Write>(
    writer: &mut Writer<W>,
    ps: &crate::pagesetup::PageSetup,
) -> Result<()> {
    let mut page_setup = BytesStart::new("pageSetup");
    page_setup.push_attribute(("paperSize", ps.paper_size.code().to_string().as_str()));

    if ps.orientation == Orientation::Landscape {
        page_setup.push_attribute(("orientation", "landscape"));
    } else {
        page_setup.push_attribute(("orientation", "portrait"));
    }

    if ps.scale != 100 {
        page_setup.push_attribute(("scale", ps.scale.to_string().as_str()));
    }

    if let Some(fit_w) = ps.fit_to_width {
        page_setup.push_attribute(("fitToWidth", fit_w.to_string().as_str()));
    }
    if let Some(fit_h) = ps.fit_to_height {
        page_setup.push_attribute(("fitToHeight", fit_h.to_string().as_str()));
    }

    if let Some(first_page) = ps.first_page_number {
        page_setup.push_attribute(("firstPageNumber", first_page.to_string().as_str()));
        page_setup.push_attribute(("useFirstPageNumber", "1"));
    }

    if ps.black_and_white {
        page_setup.push_attribute(("blackAndWhite", "1"));
    }
    if ps.draft {
        page_setup.push_attribute(("draft", "1"));
    }

    if let Some(hdpi) = ps.horizontal_dpi {
        page_setup.push_attribute(("horizontalDpi", hdpi.to_string().as_str()));
    }
    if let Some(vdpi) = ps.vertical_dpi {
        page_setup.push_attribute(("verticalDpi", vdpi.to_string().as_str()));
    }

    if ps.copies > 1 {
        page_setup.push_attribute(("copies", ps.copies.to_string().as_str()));
    }

    writer.write_event(Event::Empty(page_setup))?;

    // headerFooter
    let hf = &ps.header_footer;
    if hf.odd_header.is_some() || hf.odd_footer.is_some() {
        let mut header_footer = BytesStart::new("headerFooter");
        if hf.different_odd_even {
            header_footer.push_attribute(("differentOddEven", "1"));
        }
        if hf.different_first {
            header_footer.push_attribute(("differentFirst", "1"));
        }
        writer.write_event(Event::Start(header_footer))?;

        if let Some(ref h) = hf.odd_header {
            write_text_element(writer, "oddHeader", &h.to_string())?;
        }
        if let Some(ref f) = hf.odd_footer {
            write_text_element(writer, "oddFooter", &f.to_string())?;
        }

        writer.write_event(Event::End(BytesEnd::new("headerFooter")))?;
    }

    Ok(())
}

/// Write the printOptions element (per CT_Worksheet schema order it must
/// precede pageMargins, so it cannot live inside write_page_setup).
fn write_print_options<W: std::io::Write>(
    writer: &mut Writer<W>,
    ps: &crate::pagesetup::PageSetup,
) -> Result<()> {
    if ps.print_gridlines || ps.print_headings || ps.center_horizontally || ps.center_vertically {
        let mut print_options = BytesStart::new("printOptions");
        if ps.print_gridlines {
            print_options.push_attribute(("gridLines", "1"));
        }
        if ps.print_headings {
            print_options.push_attribute(("headings", "1"));
        }
        if ps.center_horizontally {
            print_options.push_attribute(("horizontalCentered", "1"));
        }
        if ps.center_vertically {
            print_options.push_attribute(("verticalCentered", "1"));
        }
        writer.write_event(Event::Empty(print_options))?;
    }

    Ok(())
}

/// Write the legacy VML drawing part that anchors comment boxes.
/// Excel ignores comments entirely without one Note shape per comment.
pub fn write_vml_drawing<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    worksheet: &Worksheet,
    sheet_id: u32,
) -> Result<()> {
    let path = format!("xl/drawings/vmlDrawing{}.vml", sheet_id);
    zip.start_file(&path, options.clone())?;

    let mut comment_cells: Vec<(u32, u32)> = worksheet
        .cells
        .iter()
        .filter(|(_, cd)| cd.comment.is_some())
        .map(|(key, _)| decode_cell_key(*key))
        .collect();
    comment_cells.sort_unstable();

    let mut xml = String::with_capacity(1024 + comment_cells.len() * 768);
    xml.push_str(
        r#"<xml xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel">
<o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout>
<v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe">
<v:stroke joinstyle="miter"/><v:path gradientshapeok="t" o:connecttype="rect"/></v:shapetype>"#,
    );

    for (i, (row, col)) in comment_cells.iter().enumerate() {
        // VML anchors are 0-based; place the box one column to the right
        let r0 = row.saturating_sub(1);
        let c0 = col.saturating_sub(1);
        xml.push_str(&format!(
            r##"
<v:shape id="_x0000_s{id}" type="#_x0000_t202" style="position:absolute;margin-left:59.25pt;margin-top:1.5pt;width:108pt;height:59.25pt;z-index:{z};visibility:hidden" fillcolor="#ffffe1" o:insetmode="auto">
<v:fill color2="#ffffe1"/><v:shadow color="black" obscured="t"/><v:path o:connecttype="none"/>
<v:textbox style="mso-direction-alt:auto"><div style="text-align:left"/></v:textbox>
<x:ClientData ObjectType="Note"><x:MoveWithCells/><x:SizeWithCells/>
<x:Anchor>{a1}, 15, {a2}, 2, {a3}, 31, {a4}, 9</x:Anchor>
<x:AutoFill>False</x:AutoFill><x:Row>{r}</x:Row><x:Column>{c}</x:Column></x:ClientData>
</v:shape>"##,
            id = 1025 + i,
            z = i + 1,
            a1 = c0 + 1,
            a2 = r0,
            a3 = c0 + 3,
            a4 = r0 + 4,
            r = r0,
            c = c0,
        ));
    }

    xml.push_str("\n</xml>");
    zip.write_all(xml.as_bytes())?;
    Ok(())
}

/// Write a table XML file.
pub fn write_table_xml<W: Write + Seek>(
    zip: &mut ZipWriter<W>,
    options: &FileOptions<'static, ExtendedFileOptions>,
    table: &crate::table::Table,
    table_id: u32,
) -> Result<()> {
    let path = format!("xl/tables/table{}.xml", table_id);
    zip.start_file(&path, options.clone())?;

    let mut writer = Writer::new(Cursor::new(Vec::new()));
    let mut table_start = BytesStart::new("table");
    table_start.push_attribute((
        "xmlns",
        "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
    ));
    // Use the workbook-assigned id, not table.id, to guarantee uniqueness
    table_start.push_attribute(("id", table_id.to_string().as_str()));
    table_start.push_attribute(("name", strip_illegal_xml_chars(&table.name).as_ref()));
    table_start.push_attribute((
        "displayName",
        strip_illegal_xml_chars(&table.display_name).as_ref(),
    ));
    table_start.push_attribute(("ref", strip_illegal_xml_chars(&table.range).as_ref()));

    if !table.header_row {
        table_start.push_attribute(("headerRowCount", "0"));
    }
    if table.totals_row {
        table_start.push_attribute(("totalsRowCount", "1"));
    }

    writer.write_event(Event::Start(table_start))?;

    // autoFilter: the filter range must exclude the totals row
    if table.auto_filter {
        let filter_ref = if table.totals_row {
            match crate::utils::parse_range(&table.range) {
                Ok(((r1, c1), (r2, c2))) if r2 > r1 => format!(
                    "{}{}:{}{}",
                    column_to_letter(c1),
                    r1,
                    column_to_letter(c2),
                    r2 - 1
                ),
                _ => table.range.clone(),
            }
        } else {
            table.range.clone()
        };
        let mut af = BytesStart::new("autoFilter");
        af.push_attribute(("ref", filter_ref.as_str()));
        writer.write_event(Event::Empty(af))?;
    }

    // tableColumns
    let mut table_columns = BytesStart::new("tableColumns");
    table_columns.push_attribute(("count", table.columns.len().to_string().as_str()));
    writer.write_event(Event::Start(table_columns))?;

    for col in &table.columns {
        let mut tc = BytesStart::new("tableColumn");
        tc.push_attribute(("id", col.id.to_string().as_str()));
        tc.push_attribute(("name", strip_illegal_xml_chars(&col.name).as_ref()));

        if let Some(xml_name) = col.totals_row_function.xml_name() {
            tc.push_attribute(("totalsRowFunction", xml_name));
        }
        if let Some(ref label) = col.totals_row_label {
            tc.push_attribute(("totalsRowLabel", strip_illegal_xml_chars(label).as_ref()));
        }

        if let Some(ref formula) = col.calculated_column_formula {
            writer.write_event(Event::Start(tc))?;
            write_text_element(&mut writer, "calculatedColumnFormula", formula)?;
            writer.write_event(Event::End(BytesEnd::new("tableColumn")))?;
        } else {
            writer.write_event(Event::Empty(tc))?;
        }
    }

    writer.write_event(Event::End(BytesEnd::new("tableColumns")))?;

    // tableStyleInfo
    let mut style_info = BytesStart::new("tableStyleInfo");
    style_info.push_attribute(("name", table.style.style_name().as_str()));
    style_info.push_attribute((
        "showFirstColumn",
        if table.show_first_column { "1" } else { "0" },
    ));
    style_info.push_attribute((
        "showLastColumn",
        if table.show_last_column { "1" } else { "0" },
    ));
    style_info.push_attribute((
        "showRowStripes",
        if table.show_row_stripes { "1" } else { "0" },
    ));
    style_info.push_attribute((
        "showColumnStripes",
        if table.show_column_stripes { "1" } else { "0" },
    ));
    writer.write_event(Event::Empty(style_info))?;

    writer.write_event(Event::End(BytesEnd::new("table")))?;

    let result = writer.into_inner().into_inner();
    zip.write_all(&result)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::style::{BorderStyle, Color, Fill};

    #[test]
    fn test_escape_xml_strips_illegal_control_chars() {
        assert_eq!(escape_xml("a\x01b\x08c\x0bd\x1fe"), "abcde");
        assert_eq!(escape_xml("tab\tnl\ncr\r"), "tab\tnl\ncr\r");
        assert_eq!(escape_xml("a<b\x02&c"), "a&lt;b&amp;c");
    }

    #[test]
    fn test_strip_illegal_xml_chars() {
        assert_eq!(strip_illegal_xml_chars("a\x00b\x1fc"), "abc");
        assert_eq!(strip_illegal_xml_chars("plain <kept> &"), "plain <kept> &");
    }

    #[test]
    fn test_legacy_password_hash_known_vectors() {
        // Reference values from openpyxl's hash_password / MS-XLS Method1.
        assert_eq!(legacy_password_hash("test"), 0xCBEB);
        assert_eq!(legacy_password_hash(""), 0xCE4B);
        assert_eq!(legacy_password_hash("password"), 0x83AF);
    }

    #[test]
    fn test_non_finite_numbers_become_error_cells() {
        let map = HashMap::new();
        for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let mut buf = String::new();
            let cell = CellData {
                value: CellValue::Number(v),
                ..Default::default()
            };
            write_cell_direct(&mut buf, 1, 1, &cell, cell.style_index, &map);
            assert_eq!(buf, r#"<c r="A1" t="e"><v>#NUM!</v></c>"#);

            let mut buf2 = String::new();
            format_cell_value(&mut buf2, "A1", &CellValue::Number(v));
            assert_eq!(buf2, r#"<c r="A1" t="e"><v>#NUM!</v></c>"#);
        }
    }

    #[test]
    fn test_date_value_is_escaped() {
        let mut buf = String::new();
        format_cell_value(&mut buf, "A1", &CellValue::Date("<bad>&".to_string()));
        assert_eq!(buf, r#"<c r="A1" t="d"><v>&lt;bad&gt;&amp;</v></c>"#);
    }

    #[test]
    fn test_write_color_attr_theme() {
        let mut xml = String::new();
        write_color_attr(&mut xml, "fgColor", &Color::theme(0));
        assert_eq!(xml, r#"<fgColor theme="0"/>"#);
    }

    #[test]
    fn test_write_color_attr_theme_with_index() {
        let mut xml = String::new();
        write_color_attr(&mut xml, "color", &Color::theme(4));
        assert_eq!(xml, r#"<color theme="4"/>"#);
    }

    #[test]
    fn test_write_color_attr_rgb_hex() {
        let mut xml = String::new();
        write_color_attr(&mut xml, "fgColor", &Color::rgb("FF0000"));
        assert_eq!(xml, r#"<fgColor rgb="FFFF0000"/>"#);
    }

    #[test]
    fn test_write_color_attr_rgb_with_hash() {
        let mut xml = String::new();
        write_color_attr(&mut xml, "bgColor", &Color::rgb("#00FF00"));
        assert_eq!(xml, r#"<bgColor rgb="FF00FF00"/>"#);
    }

    #[test]
    fn test_write_color_attr_argb_8char() {
        // 8-char aRGB values from XML roundtrip should not get double-prefixed
        let mut xml = String::new();
        write_color_attr(&mut xml, "fgColor", &Color::rgb("#0000FF00"));
        assert_eq!(xml, r#"<fgColor rgb="0000FF00"/>"#);
    }

    #[test]
    fn test_write_color_attr_argb_8char_no_hash() {
        let mut xml = String::new();
        write_color_attr(&mut xml, "fgColor", &Color::rgb("FF00FF00"));
        assert_eq!(xml, r#"<fgColor rgb="FF00FF00"/>"#);
    }

    /// tint rides along with whichever of rgb/theme/indexed identifies the color.
    #[test]
    fn test_write_color_attr_tint_and_indexed() {
        let mut xml = String::new();
        write_color_attr(&mut xml, "color", &Color::theme(1).with_tint(-0.25));
        assert_eq!(xml, r#"<color theme="1" tint="-0.25"/>"#);

        xml.clear();
        write_color_attr(&mut xml, "color", &Color::indexed(5));
        assert_eq!(xml, r#"<color indexed="5"/>"#);

        xml.clear();
        write_color_attr(&mut xml, "color", &Color::rgb("FF0000").with_tint(0.4));
        assert_eq!(xml, r#"<color rgb="FFFF0000" tint="0.4"/>"#);

        // A zero tint is the default; don't write it out
        xml.clear();
        write_color_attr(&mut xml, "color", &Color::theme(2).with_tint(0.0));
        assert_eq!(xml, r#"<color theme="2"/>"#);
    }

    #[test]
    fn test_write_fill_xml_theme_fg_color() {
        let fill = Fill {
            pattern_type: Some("solid".to_string()),
            fg_color: Some(Color::theme(0)),
            bg_color: None,
        };
        let mut xml = String::new();
        write_fill_xml(&mut xml, &fill);
        assert!(xml.contains(r#"<fgColor theme="0"/>"#));
        assert!(!xml.contains("FFtheme"));
    }

    #[test]
    fn test_write_fill_xml_theme_bg_color() {
        let fill = Fill {
            pattern_type: Some("solid".to_string()),
            fg_color: None,
            bg_color: Some(Color::theme(2)),
        };
        let mut xml = String::new();
        write_fill_xml(&mut xml, &fill);
        assert!(xml.contains(r#"<bgColor theme="2"/>"#));
        assert!(!xml.contains("FFtheme"));
    }

    #[test]
    fn test_write_fill_xml_rgb_color() {
        let fill = Fill {
            pattern_type: Some("solid".to_string()),
            fg_color: Some(Color::rgb("FFFF00")),
            bg_color: None,
        };
        let mut xml = String::new();
        write_fill_xml(&mut xml, &fill);
        assert!(xml.contains(r#"<fgColor rgb="FFFFFF00"/>"#));
    }

    #[test]
    fn test_write_border_side_theme_color() {
        let side = Some(BorderStyle {
            style: "thin".to_string(),
            color: Some(Color::theme(1)),
        });
        let mut xml = String::new();
        write_border_side(&mut xml, "left", &side);
        assert!(xml.contains(r#"<color theme="1"/>"#));
        assert!(!xml.contains("FFtheme"));
    }

    #[test]
    fn test_write_border_side_rgb_color() {
        let side = Some(BorderStyle {
            style: "thick".to_string(),
            color: Some(Color::rgb("FF0000")),
        });
        let mut xml = String::new();
        write_border_side(&mut xml, "left", &side);
        assert!(xml.contains(r#"<color rgb="FFFF0000"/>"#));
    }
}