drawingml 1.0.0

Shared DrawingML content model (shapes, fills, colors, lines) for the WordprocessingML/SpreadsheetML/PresentationML crates.
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
//! In-memory model for the shared DrawingML content this crate covers — shape geometry, colors,
//! fills, and line/stroke properties. Structurally, this is `CT_ShapeProperties` (`dml-main.xsd`,
//! ECMA-376/ISO-IEC 29500-1), the type behind `<a:spPr>` wherever it appears (`<xdr:spPr>` in
//! SpreadsheetML, `<wps:spPr>`/`<pic:spPr>` in WordprocessingML, `<p:spPr>` in PresentationML) —
//! see the crate-level doc comment in `lib.rs` for why only this content is modeled here, never the
//! surrounding anchor/container, which stays host-specific.
//!
//! Covers geometry, colors, fills, lines, text-in-shape, and image fills (`blipFill`) — see
//! `lib.rs`'s crate-level doc comment for exactly what is/isn't modeled.

/// A shape's visual properties (`<a:spPr>`, `CT_ShapeProperties`): local position/size, geometry,
/// fill, and line. Everything about how a shape *looks*, independent of where it is anchored in its
/// host document (that part is never modeled here — see the crate-level doc comment).
///
/// Not modeled: 3D (`a:scene3d`/`a:sp3d`) — `EG_EffectProperties`'s `<a:effectLst>` choice
/// (shadow/glow/reflection/soft edge) *is* modeled, see [`EffectList`], point 10; its sibling
/// choice `<a:effectDag>` (an effect *graph*, letting effects reference each other's output — a
/// materially more complex, rarely-authored mechanism) is not. `bwMode` (black-and-white print
/// override) is not modeled either — a rarely-used printing hint.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ShapeProperties {
    /// `<a:xfrm>` — position, size, rotation, flipping.
    pub transform: Option<Transform2D>,
    /// `EG_Geometry` (`<a:prstGeom>`/`<a:custGeom>`) — the shape's outline.
    pub geometry: Option<Geometry>,
    /// `EG_FillProperties` (`<a:noFill>`/`<a:solidFill>`/`<a:gradFill>`/
    /// `<a:pattFill>`/`<a:blipFill>`/`<a:grpFill>`) — how the shape's interior is painted.
    pub fill: Option<Fill>,
    /// `<a:ln>` — the shape's outline stroke.
    pub line: Option<Line>,
    /// `<a:effectLst>` — shadow/glow/reflection/soft-edge effects.
    pub effects: Option<EffectList>,
    /// `<a:prstGeom>`'s own `<a:avLst>` (`CT_GeomGuideList`) — adjustment handle values for a
    /// preset shape (a rounded rectangle's corner radius, an arrow's head size.). Only meaningful,
    /// and only ever written, when `geometry` is `Some(Geometry::Preset(_))` — kept as a sibling
    /// field here (rather than inside [`Geometry::Preset`] itself) to avoid a breaking change to
    /// that enum's existing tuple-variant shape, used at dozens of call sites across every host
    /// crate. Empty (the default) omits `<a:avLst>` entirely for a preset shape — schema- valid,
    /// meaning "use this preset's own built-in default handles". Grounded against a real fixture (a
    /// smiley-face preset with an explicit `adj` guide).
    pub geometry_adjustments: Vec<GeometryAdjustment>,
}

impl ShapeProperties {
    /// Creates an empty set of shape properties (every field unset — a shape that inherits
    /// everything from its host's defaults).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the shape's position/size/rotation (`<a:xfrm>`).
    pub fn with_transform(mut self, transform: Transform2D) -> Self {
        self.transform = Some(transform);
        self
    }

    /// Sets the shape's outline (`EG_Geometry`).
    pub fn with_geometry(mut self, geometry: Geometry) -> Self {
        self.geometry = Some(geometry);
        self
    }

    /// Sets the shape's interior fill (`EG_FillProperties`).
    pub fn with_fill(mut self, fill: Fill) -> Self {
        self.fill = Some(fill);
        self
    }

    /// Sets the shape's outline stroke (`<a:ln>`).
    pub fn with_line(mut self, line: Line) -> Self {
        self.line = Some(line);
        self
    }

    /// Sets the shape's visual effects (`<a:effectLst>`).
    pub fn with_effects(mut self, effects: EffectList) -> Self {
        self.effects = Some(effects);
        self
    }

    /// Sets a preset shape's adjustment handle values (`<a:avLst>`); no effect unless `geometry` is
    /// also `Some(Geometry::Preset(_))`.
    pub fn with_geometry_adjustments(mut self, adjustments: Vec<GeometryAdjustment>) -> Self {
        self.geometry_adjustments = adjustments;
        self
    }
}

/// One `<a:gd name=".." fmla=".."/>` (`CT_GeomGuide`) inside a preset shape's `<a:avLst>` — an
/// adjustment handle's current value. `name` is the handle's identifier (`"adj"` for a shape with a
/// single handle, `"adj1"`/`"adj2"`/. for shapes with several); `formula` is the raw guide formula
/// string PowerPoint itself writes (almost always `"val N"` for a literal value — the small
/// expression language `CT_GeomGuide` otherwise allows, e.g. referencing other guides, is not
/// interpreted here, only stored/round-tripped verbatim).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GeometryAdjustment {
    pub name: String,
    pub formula: String,
}

impl GeometryAdjustment {
    pub fn new(name: impl Into<String>, formula: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            formula: formula.into(),
        }
    }
}

/// `<a:effectLst>` (`CT_EffectList`). Only the four effects real-world decks overwhelmingly use are
/// modeled (outer shadow, glow, reflection, soft edge); `CT_EffectList`'s other choices
/// (`innerShdw`/`prstShdw`, `blur`, `fillOverlay`, alpha/color/duotone/ luminance-modulation effect
/// *filters* rather than genuine visual effects) are not, matching the "common case first" posture
/// already used for e.g. `Geometry::Custom`'s draw-command subset. Grounded against real fixtures
/// covering `outerShdw`, `glow`/`softEdge`, and `reflection`.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct EffectList {
    pub outer_shadow: Option<OuterShadow>,
    pub glow: Option<Glow>,
    pub reflection: Option<Reflection>,
    pub soft_edge: Option<SoftEdge>,
}

impl EffectList {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_outer_shadow(mut self, shadow: OuterShadow) -> Self {
        self.outer_shadow = Some(shadow);
        self
    }

    pub fn with_glow(mut self, glow: Glow) -> Self {
        self.glow = Some(glow);
        self
    }

    pub fn with_reflection(mut self, reflection: Reflection) -> Self {
        self.reflection = Some(reflection);
        self
    }

    pub fn with_soft_edge(mut self, soft_edge: SoftEdge) -> Self {
        self.soft_edge = Some(soft_edge);
        self
    }
}

/// `<a:outerShdw>` (`CT_OuterShadowEffect`) — a drop shadow cast outward from the shape.
/// `algn`/`rotWithShape`/`kx`/`ky`/`sx`/`sy` (fine-grained skew/scale/anchor controls) are not
/// modeled — a scope reduction, not a fixture gap (all `CT_OuterShadowEffect`'s own attributes
/// beyond the ones here are optional). `color`'s own alpha modifier (`<a:alpha val="..">`, seen
/// alongside `<a:srgbClr>`/`<a:schemeClr>` in real fixtures, e.g. `60810.pptx`'s `<a:srgbClr
/// val="000000"><a:alpha val="41000"/></a:srgbClr>`) is not preserved either — [`Color`] itself has
/// never modeled color transforms (see its own doc comment), not a new limitation.
#[derive(Debug, Clone, PartialEq)]
pub struct OuterShadow {
    /// `blurRad`, in EMUs.
    pub blur_radius_emu: Option<i64>,
    /// `dist`, in EMUs — how far the shadow is offset from the shape.
    pub distance_emu: Option<i64>,
    /// `dir` — the offset direction, in 60,000ths of a degree.
    pub direction_60000ths: Option<i32>,
    pub color: Color,
}

impl OuterShadow {
    /// Creates a shadow with the given color and no other attribute set.
    pub fn new(color: Color) -> Self {
        Self {
            blur_radius_emu: None,
            distance_emu: None,
            direction_60000ths: None,
            color,
        }
    }

    pub fn with_blur_radius_emu(mut self, blur_radius_emu: i64) -> Self {
        self.blur_radius_emu = Some(blur_radius_emu);
        self
    }

    pub fn with_distance_emu(mut self, distance_emu: i64) -> Self {
        self.distance_emu = Some(distance_emu);
        self
    }

    /// Sets the shadow's offset direction, given in ordinary degrees.
    pub fn with_direction_degrees(mut self, degrees: f64) -> Self {
        self.direction_60000ths = Some((degrees * 60_000.0).round() as i32);
        self
    }
}

/// `<a:glow rad="..">{color}</a:glow>` (`CT_GlowEffect`) — a soft colored halo around the shape's
/// outline. Unlike [`OuterShadow`], `rad` is required (`CT_GlowEffect`'s only attribute).
#[derive(Debug, Clone, PartialEq)]
pub struct Glow {
    /// `rad`, in EMUs.
    pub radius_emu: i64,
    pub color: Color,
}

impl Glow {
    pub fn new(radius_emu: i64, color: Color) -> Self {
        Self { radius_emu, color }
    }
}

/// `<a:reflection>` (`CT_ReflectionEffect`) — a faded mirror image below the shape.
/// `endPos`/`sx`/`sy`/`kx`/`ky`/`algn`/`fadeDir`/`rotWithShape` (fine- grained
/// scale/skew/anchor/fade-direction controls) are not modeled — the same scope-reduction posture as
/// [`OuterShadow`]; only the four attributes that dominate real-world usage (blur, distance,
/// direction, and the start/end fade transparency) are kept. Grounded against a real fixture
/// (`<a:reflection blurRad="12700" stA="48000" endA="300" endPos="55000" dir="5400000" sy="-90000"
/// algn="bl" rotWithShape="0"/>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Reflection {
    /// `blurRad`, in EMUs.
    pub blur_radius_emu: Option<i64>,
    /// `dist`, in EMUs.
    pub distance_emu: Option<i64>,
    /// `dir`, in 60,000ths of a degree.
    pub direction_60000ths: Option<i32>,
    /// `stA` — the reflection's own starting transparency, in thousandths of a percent (`100000` =
    /// fully opaque). Defaults to `100000` per the schema when unset.
    pub start_alpha_1000ths_percent: Option<i32>,
    /// `endA` — the reflection's ending transparency (it fades out toward its far edge in
    /// real-world usage). Defaults to `0` per the schema when unset.
    pub end_alpha_1000ths_percent: Option<i32>,
}

impl Reflection {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_blur_radius_emu(mut self, blur_radius_emu: i64) -> Self {
        self.blur_radius_emu = Some(blur_radius_emu);
        self
    }

    pub fn with_distance_emu(mut self, distance_emu: i64) -> Self {
        self.distance_emu = Some(distance_emu);
        self
    }

    /// Sets the reflection's offset direction, given in ordinary degrees.
    pub fn with_direction_degrees(mut self, degrees: f64) -> Self {
        self.direction_60000ths = Some((degrees * 60_000.0).round() as i32);
        self
    }

    /// Sets the reflection's starting transparency, given as an ordinary percentage (`0.0.=100.0`).
    pub fn with_start_alpha_percent(mut self, percent: f64) -> Self {
        self.start_alpha_1000ths_percent = Some((percent * 1000.0).round() as i32);
        self
    }

    /// Sets the reflection's ending transparency, given as an ordinary percentage.
    pub fn with_end_alpha_percent(mut self, percent: f64) -> Self {
        self.end_alpha_1000ths_percent = Some((percent * 1000.0).round() as i32);
        self
    }
}

/// `<a:softEdge rad=".."/>` (`CT_SoftEdgesEffect`) — blurs the shape's own outline edge. `rad` is
/// required (its only attribute).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SoftEdge {
    /// `rad`, in EMUs.
    pub radius_emu: i64,
}

impl SoftEdge {
    pub fn new(radius_emu: i64) -> Self {
        Self { radius_emu }
    }
}

/// Position, size, rotation, and flipping (`<a:xfrm>`, `CT_Transform2D`). Both `offset`/`extent`
/// are optional in the schema (a shape can rely entirely on its host anchor for placement, e.g. a
/// picture inside a `xdr:twoCellAnchor` with no local `xfrm` at all) — `None` here means the
/// element itself is either absent or written with only the attributes present, matching that
/// flexibility rather than forcing a fixed size.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Transform2D {
    /// `<a:off x=".." y="..">`, in EMUs (English Metric Units; 914,400 EMU per inch — same unit
    /// `word-ooxml::Image` already uses).
    pub offset: Option<(i64, i64)>,
    /// `<a:ext cx=".." cy="..">`, in EMUs.
    pub extent: Option<(i64, i64)>,
    /// `<a:xfrm rot="..">` — `ST_Angle`, in 60,000ths of a degree, positive clockwise. Defaults to
    /// `0` (no rotation) when unset, matching the schema's own default.
    pub rotation_60000ths: i32,
    /// `<a:xfrm flipH="..">` — mirrors the shape horizontally before rotation is applied.
    pub flip_horizontal: bool,
    /// `<a:xfrm flipV="..">` — mirrors the shape vertically before rotation is applied.
    pub flip_vertical: bool,
}

impl Transform2D {
    /// Creates a transform with every field at its schema default (no offset/extent, no rotation,
    /// no flipping).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the shape's position, in EMUs.
    pub fn with_offset(mut self, x_emu: i64, y_emu: i64) -> Self {
        self.offset = Some((x_emu, y_emu));
        self
    }

    /// Sets the shape's size, in EMUs.
    pub fn with_extent(mut self, width_emu: i64, height_emu: i64) -> Self {
        self.extent = Some((width_emu, height_emu));
        self
    }

    /// Sets the shape's rotation, given in ordinary degrees (converted to the schema's
    /// 60,000ths-of-a-degree unit internally).
    pub fn with_rotation_degrees(mut self, degrees: f64) -> Self {
        self.rotation_60000ths = (degrees * 60_000.0).round() as i32;
        self
    }

    /// Mirrors the shape horizontally.
    pub fn with_flip_horizontal(mut self, flip: bool) -> Self {
        self.flip_horizontal = flip;
        self
    }

    /// Mirrors the shape vertically.
    pub fn with_flip_vertical(mut self, flip: bool) -> Self {
        self.flip_vertical = flip;
        self
    }
}

/// A shape's outline (`EG_Geometry`, the choice between `<a:custGeom>` and `<a:prstGeom>`).
///
/// [`Geometry::Custom`] only models `<a:custGeom>`'s own required `<a:pathLst>` — a single
/// `<a:path>`'s `moveTo`/`lnTo`/`cubicBezTo`/`close` draw commands, the vocabulary explicitly asked
/// for by plan. Not modeled: guides (`<a:avLst>`/`<a:gdLst>`, formula-driven adjust-handle values),
/// adjust handles (`<a:ahLst>`), connection sites (`<a:cxnLst>`), the optional bounding `<a:rect>`,
/// `quadBezTo`/`arcTo` draw commands, and multiple `<a:path>` elements within one `<a:pathLst>`
/// (`CT_Path2DList` allows several — e.g. for a shape made of disjoint outlines — only the first is
/// read back, matching the single-path case every real custom shape this crate has been asked to
/// support so far actually needs). All of the above are `minOccurs="0"` on `CT_CustomGeometry`
/// except `pathLst` itself, so omitting them entirely still produces a schema-valid element.
///
/// Grounded against a real fixture (`ppt/slides/slide6.xml`), which confirmed the assumed element
/// order and nesting exactly. That same fixture also revealed a real reading gap: its `<a:pt>`
/// coordinates are guide-name references (`<a:pt x="f2" y="f2"/>`, resolved via `<a:gd name="f2"
/// fmla=".."/>` entries in the `<a:gdLst>` this crate doesn't model) rather than literal integers —
/// `ST_AdjCoordinate` allows either. Since [`crate::reader`]'s path-point parser expects a literal
/// integer, a shape using formula-referenced coordinates currently round-trips its points back as
/// `(0, 0)` instead of erroring loudly. This crate's own writer is unaffected (it only ever emits
/// literal integers), so the gap only bites when *reading* a complex shape authored by real
/// PowerPoint with adjustable guides — accepted as an out-of-scope corner of the
/// "literal-coordinate common case" this crate targets, rather than implementing a formula
/// evaluator for `<a:gdLst>`.
#[derive(Debug, Clone, PartialEq)]
pub enum Geometry {
    Preset(PresetShape),
    Custom(CustomGeometry),
}

/// `<a:custGeom><a:pathLst><a:path w=".." h="..">`'s own draw commands (`CT_Path2D`) — see
/// [`Geometry::Custom`]'s doc comment for scope.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CustomGeometry {
    /// `<a:path w="..">` — the path's own coordinate space width. Distinct from the shape's actual
    /// on-slide size (`ShapeProperties::transform`'s own `extent`) — real PowerPoint scales the
    /// path's coordinates to fit whatever size the shape is actually drawn at, exactly like a
    /// group's `chExt` scaling its children (see `ShapeGroup`'s own doc comment in
    /// `powerpoint-ooxml` for the same underlying idea).
    pub width_emu: i64,
    /// `<a:path h="..">`.
    pub height_emu: i64,
    /// The path's draw commands, in order. The schema requires at least a `moveTo` before any
    /// `lnTo`/`cubicBezTo`/`close` — not enforced at the model level, same best-effort posture used
    /// elsewhere in this crate.
    pub commands: Vec<PathCommand>,
}

impl CustomGeometry {
    /// Creates an empty custom path (no commands) with the given coordinate space size.
    pub fn new(width_emu: i64, height_emu: i64) -> Self {
        Self {
            width_emu,
            height_emu,
            commands: Vec::new(),
        }
    }

    /// Appends one draw command.
    pub fn with_command(mut self, command: PathCommand) -> Self {
        self.commands.push(command);
        self
    }
}

/// One draw command inside a custom path (`EG_Path2DList`'s children within a single `<a:path>` —
/// `moveTo`/`lnTo`/`cubicBezTo`/`close` only, see [`Geometry::Custom`]'s doc comment for what else
/// exists but isn't modeled). Coordinates are in the enclosing `<a:path>`'s own coordinate space
/// (`0.=width_emu`/`0.=height_emu`), not absolute EMUs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathCommand {
    /// `<a:moveTo><a:pt x=".." y=".."/></a:moveTo>` — starts a new subpath at `(x, y)` without
    /// drawing.
    MoveTo { x: i64, y: i64 },
    /// `<a:lnTo><a:pt x=".." y=".."/></a:lnTo>` — a straight line to `(x, y)`.
    LineTo { x: i64, y: i64 },
    /// `<a:cubicBezTo>` — a cubic Bézier curve to `(x, y)`, via the two control points `(x1,
    /// y1)`/`(x2, y2)`.
    CubicBezierTo {
        x1: i64,
        y1: i64,
        x2: i64,
        y2: i64,
        x: i64,
        y: i64,
    },
    /// `<a:close/>` — closes the current subpath back to its own `moveTo`.
    Close,
}

/// A useful subset of `ST_ShapeType`'s ~185 preset shape names — the ones most commonly authored by
/// real tools (basic shapes, arrows, a handful of callouts/symbols). [`PresetShape::Other`]
/// preserves round-trip fidelity for any preset name not explicitly modeled here, the same "closed
/// enum + escape hatch" posture this workspace already uses for open-ended, large-but-finite value
/// sets (e.g. font family names) rather than exhaustively enumerating every value up front for a
/// feature not yet needed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PresetShape {
    Rectangle,
    RoundedRectangle,
    Ellipse,
    Triangle,
    RightTriangle,
    Diamond,
    Parallelogram,
    Trapezoid,
    Pentagon,
    Hexagon,
    Heptagon,
    Octagon,
    Decagon,
    Dodecagon,
    Star4,
    Star5,
    Star6,
    Star8,
    Star10,
    Star12,
    Line,
    Plaque,
    Teardrop,
    HomePlate,
    Chevron,
    Pie,
    Donut,
    BlockArc,
    NoSmoking,
    RightArrow,
    LeftArrow,
    UpArrow,
    DownArrow,
    LeftRightArrow,
    UpDownArrow,
    BentArrow,
    UturnArrow,
    Heart,
    Sun,
    Moon,
    SmileyFace,
    Cube,
    Can,
    LightningBolt,
    FoldedCorner,
    Bevel,
    Frame,
    Arc,
    Chord,
    LeftBrace,
    RightBrace,
    BracePair,
    /// Any `ST_ShapeType` token not covered by the variants above, kept verbatim (e.g.
    /// `"irregularSeal1"`, `"mathDivide"`, `"gear9"`..).
    Other(String),
}

impl PresetShape {
    /// The exact `ST_ShapeType` token this variant writes as `<a:prstGeom prst="..">`.
    pub(crate) fn xml_token(&self) -> &str {
        match self {
            PresetShape::Rectangle => "rect",
            PresetShape::RoundedRectangle => "roundRect",
            PresetShape::Ellipse => "ellipse",
            PresetShape::Triangle => "triangle",
            PresetShape::RightTriangle => "rtTriangle",
            PresetShape::Diamond => "diamond",
            PresetShape::Parallelogram => "parallelogram",
            PresetShape::Trapezoid => "trapezoid",
            PresetShape::Pentagon => "pentagon",
            PresetShape::Hexagon => "hexagon",
            PresetShape::Heptagon => "heptagon",
            PresetShape::Octagon => "octagon",
            PresetShape::Decagon => "decagon",
            PresetShape::Dodecagon => "dodecagon",
            PresetShape::Star4 => "star4",
            PresetShape::Star5 => "star5",
            PresetShape::Star6 => "star6",
            PresetShape::Star8 => "star8",
            PresetShape::Star10 => "star10",
            PresetShape::Star12 => "star12",
            PresetShape::Line => "line",
            PresetShape::Plaque => "plaque",
            PresetShape::Teardrop => "teardrop",
            PresetShape::HomePlate => "homePlate",
            PresetShape::Chevron => "chevron",
            PresetShape::Pie => "pie",
            PresetShape::Donut => "donut",
            PresetShape::BlockArc => "blockArc",
            PresetShape::NoSmoking => "noSmoking",
            PresetShape::RightArrow => "rightArrow",
            PresetShape::LeftArrow => "leftArrow",
            PresetShape::UpArrow => "upArrow",
            PresetShape::DownArrow => "downArrow",
            PresetShape::LeftRightArrow => "leftRightArrow",
            PresetShape::UpDownArrow => "upDownArrow",
            PresetShape::BentArrow => "bentArrow",
            PresetShape::UturnArrow => "uturnArrow",
            PresetShape::Heart => "heart",
            PresetShape::Sun => "sun",
            PresetShape::Moon => "moon",
            PresetShape::SmileyFace => "smileyFace",
            PresetShape::Cube => "cube",
            PresetShape::Can => "can",
            PresetShape::LightningBolt => "lightningBolt",
            PresetShape::FoldedCorner => "foldedCorner",
            PresetShape::Bevel => "bevel",
            PresetShape::Frame => "frame",
            PresetShape::Arc => "arc",
            PresetShape::Chord => "chord",
            PresetShape::LeftBrace => "leftBrace",
            PresetShape::RightBrace => "rightBrace",
            PresetShape::BracePair => "bracePair",
            PresetShape::Other(token) => token,
        }
    }

    /// Resolves an `ST_ShapeType` token read from `<a:prstGeom prst="..">` back to a
    /// [`PresetShape`], falling back to [`PresetShape::Other`] for anything not explicitly modeled.
    pub(crate) fn from_xml_token(token: &str) -> Self {
        match token {
            "rect" => PresetShape::Rectangle,
            "roundRect" => PresetShape::RoundedRectangle,
            "ellipse" => PresetShape::Ellipse,
            "triangle" => PresetShape::Triangle,
            "rtTriangle" => PresetShape::RightTriangle,
            "diamond" => PresetShape::Diamond,
            "parallelogram" => PresetShape::Parallelogram,
            "trapezoid" => PresetShape::Trapezoid,
            "pentagon" => PresetShape::Pentagon,
            "hexagon" => PresetShape::Hexagon,
            "heptagon" => PresetShape::Heptagon,
            "octagon" => PresetShape::Octagon,
            "decagon" => PresetShape::Decagon,
            "dodecagon" => PresetShape::Dodecagon,
            "star4" => PresetShape::Star4,
            "star5" => PresetShape::Star5,
            "star6" => PresetShape::Star6,
            "star8" => PresetShape::Star8,
            "star10" => PresetShape::Star10,
            "star12" => PresetShape::Star12,
            "line" => PresetShape::Line,
            "plaque" => PresetShape::Plaque,
            "teardrop" => PresetShape::Teardrop,
            "homePlate" => PresetShape::HomePlate,
            "chevron" => PresetShape::Chevron,
            "pie" => PresetShape::Pie,
            "donut" => PresetShape::Donut,
            "blockArc" => PresetShape::BlockArc,
            "noSmoking" => PresetShape::NoSmoking,
            "rightArrow" => PresetShape::RightArrow,
            "leftArrow" => PresetShape::LeftArrow,
            "upArrow" => PresetShape::UpArrow,
            "downArrow" => PresetShape::DownArrow,
            "leftRightArrow" => PresetShape::LeftRightArrow,
            "upDownArrow" => PresetShape::UpDownArrow,
            "bentArrow" => PresetShape::BentArrow,
            "uturnArrow" => PresetShape::UturnArrow,
            "heart" => PresetShape::Heart,
            "sun" => PresetShape::Sun,
            "moon" => PresetShape::Moon,
            "smileyFace" => PresetShape::SmileyFace,
            "cube" => PresetShape::Cube,
            "can" => PresetShape::Can,
            "lightningBolt" => PresetShape::LightningBolt,
            "foldedCorner" => PresetShape::FoldedCorner,
            "bevel" => PresetShape::Bevel,
            "frame" => PresetShape::Frame,
            "arc" => PresetShape::Arc,
            "chord" => PresetShape::Chord,
            "leftBrace" => PresetShape::LeftBrace,
            "rightBrace" => PresetShape::RightBrace,
            "bracePair" => PresetShape::BracePair,
            other => PresetShape::Other(other.to_string()),
        }
    }
}

/// A color (`EG_ColorChoice`): the choice DrawingML offers wherever a color is needed (fills,
/// lines, gradient stops..).
///
/// Not modeled: scheme-relative colors (`<a:schemeClr>`, `ST_SchemeColorVal` — a reference into a
/// theme's 12-color palette) — deferred until a host crate can resolve a theme (see the project
/// notes plan,: `excel-ooxml` has no configurable `Theme` model at all yet, and `word-ooxml`'s own
/// `Theme`/`Style`/`Run` never reference a theme slot either — `drawing` has nothing to resolve
/// against today). Color transforms (`EG_ColorTransform` — `alpha`/`lumMod`/`lumOff`/`shade`/
/// `tint`/., applicable to every variant below) are not modeled either — each variant here is
/// always a literal, unmodified color.
#[derive(Debug, Clone, PartialEq)]
pub enum Color {
    /// `<a:srgbClr val="RRGGBB">` — a literal RGB color, hex-encoded with no leading `#`. The
    /// overwhelmingly common case, same representation `excel-ooxml`/`word-ooxml` already use for
    /// their own literal colors.
    Rgb(String),
    /// `<a:scrgbClr r=".." g=".." b="..">` — a literal RGB color given as percentages, each in
    /// thousandths of a percent (`ST_Percentage`; `100000` = 100%).
    RgbPercent { red: i64, green: i64, blue: i64 },
    /// `<a:hslClr hue=".." sat=".." lum="..">`. `hue` is `ST_PositiveFixedAngle` (60,000ths of a
    /// degree, `0.=21_600_000`); `saturation`/`luminance` are `ST_Percentage` (thousandths of a
    /// percent).
    Hsl {
        hue_60000ths: i32,
        saturation_1000ths_percent: i64,
        luminance_1000ths_percent: i64,
    },
    /// `<a:sysClr val=".." lastClr="..">` — one of the ~30 legacy Windows UI colors
    /// (`ST_SystemColorVal`, e.g. `"windowText"`, `"btnFace"`). `value` is kept as the raw token
    /// rather than a closed enum (rarely used in real documents, same "not enumerated" posture as
    /// `Preset` below); `last_color` is the RGB fallback Office itself resolved it to at authoring
    /// time.
    System {
        value: String,
        last_color: Option<String>,
    },
    /// `<a:prstClr val="..">` — one of `ST_PresetColorVal`'s ~140 CSS-like named colors (e.g.
    /// `"aliceBlue"`, `"tomato"`). Kept as the raw token rather than a closed enum, for the same
    /// reason as [`Color::System`] — see [`Color::Rgb`] for the common, literal-hex case.
    Preset(String),
}

/// How a shape's (or a line's) interior is painted (`EG_FillProperties`).
///
/// Not modeled: `<a:grpFill>` (inherit the parent group's fill — only meaningful for a shape inside
/// a group, which this crate doesn't model).
#[derive(Debug, Clone, PartialEq)]
pub enum Fill {
    /// `<a:noFill/>` — an explicitly transparent interior (distinct from `None` at the Rust level
    /// on [`ShapeProperties::fill`], which means "inherit from the host's shape defaults" instead).
    None,
    /// `<a:solidFill>` — a single flat color.
    Solid(Color),
    /// `<a:gradFill>` — a multi-stop gradient.
    Gradient(GradientFill),
    /// `<a:pattFill>` — a two-color repeating pattern.
    Pattern(PatternFill),
    /// `<a:blipFill>` — an image fill. The same `CT_BlipFillProperties` type also appears, always
    /// present rather than optional, as `<pic:pic>`'s own dedicated fill (`dml-picture.xsd`'s
    /// `CT_Picture`, alongside `spPr` — a real picture shape, not just a shape textured with an
    /// image) — see [`BlipFill`]'s doc comment.
    Image(BlipFill),
}

/// A gradient fill (`<a:gradFill>`, `CT_GradientFillProperties`).
///
/// Only linear shading (`<a:lin ang="..">`) is modeled — `EG_ShadeProperties`'s other choice,
/// path-based shading (`<a:path path="circle"/"rect"/"shape">`, radiating from a point or rectangle
/// rather than along a straight line), is deferred; `tileRect`/`flip`/`rotWithShape` (fine-grained
/// tiling controls) are not modeled either.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct GradientFill {
    /// `<a:gsLst><a:gs>..` — the gradient's color stops. The schema requires at least 2; not
    /// enforced at the model level (same best-effort posture as e.g.
    /// `ExcelTable::table_style_name`).
    pub stops: Vec<GradientStop>,
    /// `<a:lin ang="..">` — the gradient's direction, in 60,000ths of a degree. `None` omits
    /// `<a:lin>` entirely (an unspecified/default direction).
    pub angle_60000ths: Option<i32>,
}

impl GradientFill {
    /// Creates an empty gradient (no stops, no angle).
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends one color stop.
    pub fn with_stop(mut self, stop: GradientStop) -> Self {
        self.stops.push(stop);
        self
    }

    /// Sets the gradient's linear direction, given in ordinary degrees.
    pub fn with_angle_degrees(mut self, degrees: f64) -> Self {
        self.angle_60000ths = Some((degrees * 60_000.0).round() as i32);
        self
    }
}

/// One color stop in a gradient (`<a:gs pos="..">`, `CT_GradientStop`).
#[derive(Debug, Clone, PartialEq)]
pub struct GradientStop {
    /// `pos` — the stop's position along the gradient, in thousandths of a percent
    /// (`ST_PositiveFixedPercentage`, `0.=100_000`).
    pub position_1000ths_percent: i64,
    pub color: Color,
}

impl GradientStop {
    /// Creates a stop at the given position, given as an ordinary percentage (`0.0.=100.0`).
    pub fn new(position_percent: f64, color: Color) -> Self {
        Self {
            position_1000ths_percent: (position_percent * 1000.0).round() as i64,
            color,
        }
    }
}

/// A two-color repeating pattern fill (`<a:pattFill>`, `CT_PatternFillProperties`).
#[derive(Debug, Clone, PartialEq)]
pub struct PatternFill {
    pub preset: PresetPattern,
    /// `<a:fgClr>` — the pattern's foreground (the color the pattern's "on" pixels are drawn in).
    pub foreground: Option<Color>,
    /// `<a:bgClr>` — the pattern's background (the color showing through its "off" pixels).
    pub background: Option<Color>,
}

impl PatternFill {
    pub fn new(preset: PresetPattern) -> Self {
        Self {
            preset,
            foreground: None,
            background: None,
        }
    }

    pub fn with_foreground(mut self, color: Color) -> Self {
        self.foreground = Some(color);
        self
    }

    pub fn with_background(mut self, color: Color) -> Self {
        self.background = Some(color);
        self
    }
}

/// `ST_PresetPatternVal`'s full, finite set of 54 named patterns — unlike
/// [`PresetShape`]/[`Color::Preset`], small enough to enumerate exhaustively (no `Other` escape
/// hatch needed).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PresetPattern {
    Percent5,
    Percent10,
    Percent20,
    Percent25,
    Percent30,
    Percent40,
    Percent50,
    Percent60,
    Percent70,
    Percent75,
    Percent80,
    Percent90,
    Horizontal,
    Vertical,
    LightHorizontal,
    LightVertical,
    DarkHorizontal,
    DarkVertical,
    NarrowHorizontal,
    NarrowVertical,
    DashedHorizontal,
    DashedVertical,
    Cross,
    DiagonalDown,
    DiagonalUp,
    LightDiagonalDown,
    LightDiagonalUp,
    DarkDiagonalDown,
    DarkDiagonalUp,
    WideDiagonalDown,
    WideDiagonalUp,
    DashedDiagonalDown,
    DashedDiagonalUp,
    DiagonalCross,
    SmallCheckerBoard,
    LargeCheckerBoard,
    SmallGrid,
    LargeGrid,
    DottedGrid,
    SmallConfetti,
    LargeConfetti,
    HorizontalBrick,
    DiagonalBrick,
    SolidDiamond,
    OpenDiamond,
    DottedDiamond,
    Plaid,
    Sphere,
    Weave,
    Divot,
    Shingle,
    Wave,
    Trellis,
    ZigZag,
}

impl PresetPattern {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            PresetPattern::Percent5 => "pct5",
            PresetPattern::Percent10 => "pct10",
            PresetPattern::Percent20 => "pct20",
            PresetPattern::Percent25 => "pct25",
            PresetPattern::Percent30 => "pct30",
            PresetPattern::Percent40 => "pct40",
            PresetPattern::Percent50 => "pct50",
            PresetPattern::Percent60 => "pct60",
            PresetPattern::Percent70 => "pct70",
            PresetPattern::Percent75 => "pct75",
            PresetPattern::Percent80 => "pct80",
            PresetPattern::Percent90 => "pct90",
            PresetPattern::Horizontal => "horz",
            PresetPattern::Vertical => "vert",
            PresetPattern::LightHorizontal => "ltHorz",
            PresetPattern::LightVertical => "ltVert",
            PresetPattern::DarkHorizontal => "dkHorz",
            PresetPattern::DarkVertical => "dkVert",
            PresetPattern::NarrowHorizontal => "narHorz",
            PresetPattern::NarrowVertical => "narVert",
            PresetPattern::DashedHorizontal => "dashHorz",
            PresetPattern::DashedVertical => "dashVert",
            PresetPattern::Cross => "cross",
            PresetPattern::DiagonalDown => "dnDiag",
            PresetPattern::DiagonalUp => "upDiag",
            PresetPattern::LightDiagonalDown => "ltDnDiag",
            PresetPattern::LightDiagonalUp => "ltUpDiag",
            PresetPattern::DarkDiagonalDown => "dkDnDiag",
            PresetPattern::DarkDiagonalUp => "dkUpDiag",
            PresetPattern::WideDiagonalDown => "wdDnDiag",
            PresetPattern::WideDiagonalUp => "wdUpDiag",
            PresetPattern::DashedDiagonalDown => "dashDnDiag",
            PresetPattern::DashedDiagonalUp => "dashUpDiag",
            PresetPattern::DiagonalCross => "diagCross",
            PresetPattern::SmallCheckerBoard => "smCheck",
            PresetPattern::LargeCheckerBoard => "lgCheck",
            PresetPattern::SmallGrid => "smGrid",
            PresetPattern::LargeGrid => "lgGrid",
            PresetPattern::DottedGrid => "dotGrid",
            PresetPattern::SmallConfetti => "smConfetti",
            PresetPattern::LargeConfetti => "lgConfetti",
            PresetPattern::HorizontalBrick => "horzBrick",
            PresetPattern::DiagonalBrick => "diagBrick",
            PresetPattern::SolidDiamond => "solidDmnd",
            PresetPattern::OpenDiamond => "openDmnd",
            PresetPattern::DottedDiamond => "dotDmnd",
            PresetPattern::Plaid => "plaid",
            PresetPattern::Sphere => "sphere",
            PresetPattern::Weave => "weave",
            PresetPattern::Divot => "divot",
            PresetPattern::Shingle => "shingle",
            PresetPattern::Wave => "wave",
            PresetPattern::Trellis => "trellis",
            PresetPattern::ZigZag => "zigZag",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "pct5" => PresetPattern::Percent5,
            "pct10" => PresetPattern::Percent10,
            "pct20" => PresetPattern::Percent20,
            "pct25" => PresetPattern::Percent25,
            "pct30" => PresetPattern::Percent30,
            "pct40" => PresetPattern::Percent40,
            "pct50" => PresetPattern::Percent50,
            "pct60" => PresetPattern::Percent60,
            "pct70" => PresetPattern::Percent70,
            "pct75" => PresetPattern::Percent75,
            "pct80" => PresetPattern::Percent80,
            "pct90" => PresetPattern::Percent90,
            "horz" => PresetPattern::Horizontal,
            "vert" => PresetPattern::Vertical,
            "ltHorz" => PresetPattern::LightHorizontal,
            "ltVert" => PresetPattern::LightVertical,
            "dkHorz" => PresetPattern::DarkHorizontal,
            "dkVert" => PresetPattern::DarkVertical,
            "narHorz" => PresetPattern::NarrowHorizontal,
            "narVert" => PresetPattern::NarrowVertical,
            "dashHorz" => PresetPattern::DashedHorizontal,
            "dashVert" => PresetPattern::DashedVertical,
            "cross" => PresetPattern::Cross,
            "dnDiag" => PresetPattern::DiagonalDown,
            "upDiag" => PresetPattern::DiagonalUp,
            "ltDnDiag" => PresetPattern::LightDiagonalDown,
            "ltUpDiag" => PresetPattern::LightDiagonalUp,
            "dkDnDiag" => PresetPattern::DarkDiagonalDown,
            "dkUpDiag" => PresetPattern::DarkDiagonalUp,
            "wdDnDiag" => PresetPattern::WideDiagonalDown,
            "wdUpDiag" => PresetPattern::WideDiagonalUp,
            "dashDnDiag" => PresetPattern::DashedDiagonalDown,
            "dashUpDiag" => PresetPattern::DashedDiagonalUp,
            "diagCross" => PresetPattern::DiagonalCross,
            "smCheck" => PresetPattern::SmallCheckerBoard,
            "lgCheck" => PresetPattern::LargeCheckerBoard,
            "smGrid" => PresetPattern::SmallGrid,
            "lgGrid" => PresetPattern::LargeGrid,
            "dotGrid" => PresetPattern::DottedGrid,
            "smConfetti" => PresetPattern::SmallConfetti,
            "lgConfetti" => PresetPattern::LargeConfetti,
            "horzBrick" => PresetPattern::HorizontalBrick,
            "diagBrick" => PresetPattern::DiagonalBrick,
            "solidDmnd" => PresetPattern::SolidDiamond,
            "openDmnd" => PresetPattern::OpenDiamond,
            "dotDmnd" => PresetPattern::DottedDiamond,
            "plaid" => PresetPattern::Plaid,
            "sphere" => PresetPattern::Sphere,
            "weave" => PresetPattern::Weave,
            "divot" => PresetPattern::Divot,
            "shingle" => PresetPattern::Shingle,
            "wave" => PresetPattern::Wave,
            "trellis" => PresetPattern::Trellis,
            "zigZag" => PresetPattern::ZigZag,
            _ => return None,
        })
    }
}

/// A shape's outline stroke (`<a:ln>`, `CT_LineProperties`).
///
/// Not modeled: `<a:extLst>` (extension list) and the pen-alignment (`algn` — center/inset)
/// attribute — a rare, cosmetic refinement. The compound-line attribute (`cmpd`) *is* modeled, see
/// [`LineCompound`].
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Line {
    /// `w` — the stroke's width, in EMUs.
    pub width_emu: Option<i64>,
    /// `EG_LineFillProperties` — how the stroke itself is painted (the same fill choices as a
    /// shape's interior, minus image/group fills, which aren't valid here per the schema).
    pub fill: Option<Fill>,
    /// `<a:prstDash val="..">` — one of the 11 preset dash patterns. Custom dash patterns
    /// (`<a:custDash>`, an explicit dash/space stop list) are deferred.
    pub dash: Option<PresetLineDash>,
    /// `cap` — the stroke's end-cap style.
    pub cap: Option<LineCap>,
    /// `EG_LineJoinProperties` — how the stroke's corners are drawn.
    pub join: Option<LineJoin>,
    /// `<a:headEnd>` — the arrowhead (or other decoration) at the line's start.
    pub head_end: Option<LineEnd>,
    /// `<a:tailEnd>` — the arrowhead (or other decoration) at the line's end.
    pub tail_end: Option<LineEnd>,
    /// `cmpd` — the stroke's compound-line style (single/double/thick-thin/ thin-thick/triple).
    /// `None` omits the attribute (`ST_CompoundLine`'s own schema default, `"sng"`, applies).
    /// Grounded against a real fixture's slide master border (`cmpd="sng"`).
    pub compound: Option<LineCompound>,
}

impl Line {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_compound(mut self, compound: LineCompound) -> Self {
        self.compound = Some(compound);
        self
    }

    pub fn with_width_emu(mut self, width_emu: i64) -> Self {
        self.width_emu = Some(width_emu);
        self
    }

    pub fn with_fill(mut self, fill: Fill) -> Self {
        self.fill = Some(fill);
        self
    }

    pub fn with_dash(mut self, dash: PresetLineDash) -> Self {
        self.dash = Some(dash);
        self
    }

    pub fn with_cap(mut self, cap: LineCap) -> Self {
        self.cap = Some(cap);
        self
    }

    pub fn with_join(mut self, join: LineJoin) -> Self {
        self.join = Some(join);
        self
    }

    pub fn with_head_end(mut self, end: LineEnd) -> Self {
        self.head_end = Some(end);
        self
    }

    pub fn with_tail_end(mut self, end: LineEnd) -> Self {
        self.tail_end = Some(end);
        self
    }
}

/// `ST_PresetLineDashVal`'s full set of 11 named dash patterns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PresetLineDash {
    Solid,
    Dot,
    Dash,
    LargeDash,
    DashDot,
    LargeDashDot,
    LargeDashDotDot,
    SystemDash,
    SystemDot,
    SystemDashDot,
    SystemDashDotDot,
}

impl PresetLineDash {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            PresetLineDash::Solid => "solid",
            PresetLineDash::Dot => "dot",
            PresetLineDash::Dash => "dash",
            PresetLineDash::LargeDash => "lgDash",
            PresetLineDash::DashDot => "dashDot",
            PresetLineDash::LargeDashDot => "lgDashDot",
            PresetLineDash::LargeDashDotDot => "lgDashDotDot",
            PresetLineDash::SystemDash => "sysDash",
            PresetLineDash::SystemDot => "sysDot",
            PresetLineDash::SystemDashDot => "sysDashDot",
            PresetLineDash::SystemDashDotDot => "sysDashDotDot",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "solid" => PresetLineDash::Solid,
            "dot" => PresetLineDash::Dot,
            "dash" => PresetLineDash::Dash,
            "lgDash" => PresetLineDash::LargeDash,
            "dashDot" => PresetLineDash::DashDot,
            "lgDashDot" => PresetLineDash::LargeDashDot,
            "lgDashDotDot" => PresetLineDash::LargeDashDotDot,
            "sysDash" => PresetLineDash::SystemDash,
            "sysDot" => PresetLineDash::SystemDot,
            "sysDashDot" => PresetLineDash::SystemDashDot,
            "sysDashDotDot" => PresetLineDash::SystemDashDotDot,
            _ => return None,
        })
    }
}

/// `ST_LineCap` — a stroke's end-cap style.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineCap {
    Round,
    Square,
    Flat,
}

impl LineCap {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            LineCap::Round => "rnd",
            LineCap::Square => "sq",
            LineCap::Flat => "flat",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "rnd" => LineCap::Round,
            "sq" => LineCap::Square,
            "flat" => LineCap::Flat,
            _ => return None,
        })
    }
}

/// `ST_CompoundLine` — a stroke's compound-line style.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineCompound {
    Simple,
    Double,
    /// `"thickThin"` — a thick line above a thin one.
    ThickThin,
    /// `"thinThick"` — a thin line above a thick one.
    ThinThick,
    Triple,
}

impl LineCompound {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            LineCompound::Simple => "sng",
            LineCompound::Double => "dbl",
            LineCompound::ThickThin => "thickThin",
            LineCompound::ThinThick => "thinThick",
            LineCompound::Triple => "tri",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "sng" => LineCompound::Simple,
            "dbl" => LineCompound::Double,
            "thickThin" => LineCompound::ThickThin,
            "thinThick" => LineCompound::ThinThick,
            "tri" => LineCompound::Triple,
            _ => return None,
        })
    }
}

/// `EG_LineJoinProperties` — how a stroke's corners are drawn.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LineJoin {
    Round,
    Bevel,
    /// `<a:miter lim="..">` — `lim` is the miter limit, in thousandths of a percent
    /// (`ST_PositivePercentage`).
    Miter {
        limit_1000ths_percent: Option<i64>,
    },
}

/// One end of a line/connector (`<a:headEnd>`/`<a:tailEnd>`, `CT_LineEndProperties`) — e.g. an
/// arrowhead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LineEnd {
    pub kind: Option<LineEndType>,
    pub width: Option<LineEndSize>,
    pub length: Option<LineEndSize>,
}

impl LineEnd {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_kind(mut self, kind: LineEndType) -> Self {
        self.kind = Some(kind);
        self
    }

    pub fn with_width(mut self, width: LineEndSize) -> Self {
        self.width = Some(width);
        self
    }

    pub fn with_length(mut self, length: LineEndSize) -> Self {
        self.length = Some(length);
        self
    }
}

/// `ST_LineEndType` — the shape of a line end decoration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineEndType {
    None,
    Triangle,
    Stealth,
    Diamond,
    Oval,
    Arrow,
}

impl LineEndType {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            LineEndType::None => "none",
            LineEndType::Triangle => "triangle",
            LineEndType::Stealth => "stealth",
            LineEndType::Diamond => "diamond",
            LineEndType::Oval => "oval",
            LineEndType::Arrow => "arrow",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "none" => LineEndType::None,
            "triangle" => LineEndType::Triangle,
            "stealth" => LineEndType::Stealth,
            "diamond" => LineEndType::Diamond,
            "oval" => LineEndType::Oval,
            "arrow" => LineEndType::Arrow,
            _ => return None,
        })
    }
}

/// `ST_LineEndWidth`/`ST_LineEndLength` — both share the same three-value small/medium/large scale.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineEndSize {
    Small,
    Medium,
    Large,
}

impl LineEndSize {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            LineEndSize::Small => "sm",
            LineEndSize::Medium => "med",
            LineEndSize::Large => "lg",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "sm" => LineEndSize::Small,
            "med" => LineEndSize::Medium,
            "lg" => LineEndSize::Large,
            _ => return None,
        })
    }
}

// ================================================================================================
// Text-in-shape and image fills
// ================================================================================================

/// An image fill (`<a:blipFill>`, `CT_BlipFillProperties`). Confirmed against `dml-picture.xsd`'s
/// `CT_Picture` (`nvPicPr`/ `blipFill`/`spPr`) that this is the same type PowerPoint/Word/Excel all
/// use both for a real picture shape's own always-present fill *and* for texturing an ordinary
/// shape with an image (`EG_FillProperties`'s `blipFill` choice, alongside `noFill`/`solidFill`/..)
/// — one model, [`Fill::Image`], covers both uses.
///
/// The embedded-image reference, the stretch/tile choice, and cropping (`<a:srcRect>`, point 6) are
/// modeled. Not modeled: `<a:duotone>`/`<a:lum>`/other `<a:blip>` image effects, `dpi`/
/// `rotWithShape` attributes, and `EG_FillModeProperties`'s own fine-grained tiling/stretching
/// sub-rects (`<a:tile>`'s `tx`/`ty`/`sx`/ `sy`/`flip`/`algn`, `<a:stretch>`'s `<a:fillRect>`) —
/// all cosmetic refinements on top of "which image, does it stretch or tile, and is it cropped".
///
/// Resolving the embedded image's actual bytes is deliberately **not** this crate's job: `<a:blip
/// r:embed="..">`'s value is a bare relationship id (`AG_Blob`, confirmed in `dml-main.xsd`) —
/// `drawing` carries that id as a plain string, the same way it carries every other host-specific
/// reference (none, so far), and leaves resolving it through an actual OPC package/relationship set
/// to whichever host crate ends up consuming this (see `word-ooxml::Image`'s own `r:embed` handling
/// for the precedent this will eventually be generalized from).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BlipFill {
    /// `<a:blip r:embed="..">` — the embedded image's relationship id. `None` omits `<a:blip>`
    /// entirely (a `blipFill` with no image set — unusual, but not schema-invalid, `blip` being
    /// `minOccurs="0"`).
    pub relationship_id: Option<String>,
    /// `EG_FillModeProperties` — `<a:stretch/>` or `<a:tile/>`. `None` omits the choice entirely
    /// (Office's own default is an implicit stretch-to-fill).
    pub mode: Option<BlipFillMode>,
    /// `<a:srcRect>` (`CT_RelativeRect`) — crops the source image before it's stretched/tiled into
    /// the shape. `None` omits the element entirely (no cropping — the whole image is used), the
    /// common case.
    pub crop: Option<CropRect>,
}

impl BlipFill {
    /// Creates an image fill referencing the given relationship id.
    pub fn new(relationship_id: impl Into<String>) -> Self {
        Self {
            relationship_id: Some(relationship_id.into()),
            mode: None,
            crop: None,
        }
    }

    pub fn with_mode(mut self, mode: BlipFillMode) -> Self {
        self.mode = Some(mode);
        self
    }

    /// Crops the source image before it's stretched/tiled into the shape.
    pub fn with_crop(mut self, crop: CropRect) -> Self {
        self.crop = Some(crop);
        self
    }
}

/// `<a:srcRect l=".." t=".." r=".." b=".."/>` (`CT_RelativeRect`) — how much of a [`BlipFill`]'s
/// source image to crop from each edge, before stretching/tiling the remainder into the shape. Each
/// side is independently optional (`ST_Percentage`, thousandths of a percent of the image's own
/// width/height; can be negative, which *zooms out* rather than cropping — real PowerPoint uses
/// this for "fill the shape, source image too small" cases). Grounded against a real fixture (e.g.
/// `<a:srcRect l="2878" t="2522" r="21582" b="46217"/>`, and `<a:srcRect t="52941" b="-17647"/>`
/// for the negative case).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CropRect {
    pub left_1000ths_percent: Option<i32>,
    pub top_1000ths_percent: Option<i32>,
    pub right_1000ths_percent: Option<i32>,
    pub bottom_1000ths_percent: Option<i32>,
}

impl CropRect {
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets each side's crop, given as ordinary percentages of the image's own width/height
    /// (`0.0.=100.0` for a normal crop; negative values zoom out instead).
    pub fn with_percent(mut self, left: f64, top: f64, right: f64, bottom: f64) -> Self {
        self.left_1000ths_percent = Some((left * 1000.0).round() as i32);
        self.top_1000ths_percent = Some((top * 1000.0).round() as i32);
        self.right_1000ths_percent = Some((right * 1000.0).round() as i32);
        self.bottom_1000ths_percent = Some((bottom * 1000.0).round() as i32);
        self
    }
}

/// `EG_FillModeProperties` — how an image fill is fitted to its shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlipFillMode {
    /// `<a:stretch/>` — the image is scaled to exactly fill the shape.
    Stretch,
    /// `<a:tile/>` — the image is repeated at its natural size.
    Tile,
}

/// The text content of a shape (`<a:txBody>`, `CT_TextBody`). Structurally a **sibling** of
/// [`ShapeProperties`], not a field on it: confirmed against `dml-spreadsheetDrawing.xsd`'s
/// `CT_Shape` (`nvSpPr`/`spPr`/`style?`/`txBody?`, `txBody` a sibling of `spPr`, both direct
/// children of the host's own `<*:sp>` wrapper) — a future host crate combines the two itself,
/// `drawing` never nests one inside the other.
///
/// Not modeled: `<a:lstStyle>` (per-outline-level default paragraph properties, the mechanism
/// PowerPoint's placeholder text boxes use to inherit formatting from a slide layout — a materially
/// larger feature, same "deferred" posture as bullets below, which `lstStyle` also configures per
/// level) and `EG_TextAutofit`/`<a:scene3d>`/text-3D (shrink-to-fit/WordArt-style effects).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TextBody {
    /// `<a:bodyPr>` — always present in the schema (`minOccurs="1"`), even if empty
    /// (`<a:bodyPr/>`); this struct mirrors that by never being `Option` itself, only its own
    /// fields are.
    pub properties: TextBodyProperties,
    /// `<a:p>` — one or more paragraphs (schema requires at least one; not enforced at the model
    /// level, same best-effort posture used elsewhere in this crate).
    pub paragraphs: Vec<TextParagraph>,
}

impl TextBody {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_properties(mut self, properties: TextBodyProperties) -> Self {
        self.properties = properties;
        self
    }

    pub fn with_paragraph(mut self, paragraph: TextParagraph) -> Self {
        self.paragraphs.push(paragraph);
        self
    }
}

/// `<a:bodyPr>`'s attributes (`CT_TextBodyProperties`) — text wrapping, vertical anchor, horizontal
/// centering, inset margins, and autofit. See [`TextBody`]'s doc comment for what else
/// `CT_TextBodyProperties` allows but isn't modeled here (3D, preset text warp/WordArt).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TextBodyProperties {
    /// `wrap` — whether text wraps at the shape's edge.
    pub wrap: Option<TextWrap>,
    /// `anchor` — vertical alignment of the text block within the shape.
    pub anchor: Option<TextAnchor>,
    /// `anchorCtr` — additionally centers the text block horizontally within the shape (on top of
    /// whatever `anchor` does vertically). Grounded against a real fixture.
    pub anchor_center: bool,
    /// `lIns`, in EMUs.
    pub inset_left_emu: Option<i64>,
    /// `tIns`, in EMUs.
    pub inset_top_emu: Option<i64>,
    /// `rIns`, in EMUs.
    pub inset_right_emu: Option<i64>,
    /// `bIns`, in EMUs.
    pub inset_bottom_emu: Option<i64>,
    /// `EG_TextAutofit` (`<a:noAutofit/>`/`<a:normAutofit/>`/ `<a:spAutoFit/>`) — how the text body
    /// reacts to content that doesn't fit its shape. `None` omits the choice entirely (Office's own
    /// implicit default, which real PowerPoint UI actually treats as equivalent to
    /// `TextAutofit::None`).
    pub autofit: Option<TextAutofit>,
    /// `vert` (`ST_TextVerticalType`) — the text's reading direction within its shape (horizontal,
    /// stacked vertically, rotated 270°.). `None` omits the attribute (`"horz"`, ordinary
    /// left-to-right text, is the schema default). Grounded against a real fixture's placeholder
    /// (`vert="eaVert"`).
    pub vertical_direction: Option<TextVerticalType>,
    /// `rot` (`ST_Angle`, 60,000ths of a degree) — rotates the text *within* its shape, independent
    /// of the shape's own rotation (`Transform2D::rotation_degrees`, on the surrounding
    /// `<a:xfrm>`). `0` (the default) omits the attribute. Grounded against a real fixture's
    /// `<a:bodyPr rot="0".>`.
    pub rotation_60000ths: i32,
}

impl TextBodyProperties {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_wrap(mut self, wrap: TextWrap) -> Self {
        self.wrap = Some(wrap);
        self
    }

    pub fn with_anchor(mut self, anchor: TextAnchor) -> Self {
        self.anchor = Some(anchor);
        self
    }

    /// Additionally centers the text block horizontally (`anchorCtr="1"`).
    pub fn with_anchor_center(mut self, anchor_center: bool) -> Self {
        self.anchor_center = anchor_center;
        self
    }

    /// Sets all four insets at once, in EMUs.
    pub fn with_insets_emu(mut self, left: i64, top: i64, right: i64, bottom: i64) -> Self {
        self.inset_left_emu = Some(left);
        self.inset_top_emu = Some(top);
        self.inset_right_emu = Some(right);
        self.inset_bottom_emu = Some(bottom);
        self
    }

    /// Sets how this text body reacts to overflowing content.
    pub fn with_autofit(mut self, autofit: TextAutofit) -> Self {
        self.autofit = Some(autofit);
        self
    }

    /// Sets the text's reading direction within its shape.
    pub fn with_vertical_direction(mut self, direction: TextVerticalType) -> Self {
        self.vertical_direction = Some(direction);
        self
    }

    /// Rotates the text within its shape, given in ordinary degrees (converted to the schema's
    /// 60,000ths-of-a-degree unit internally).
    pub fn with_rotation_degrees(mut self, degrees: f64) -> Self {
        self.rotation_60000ths = (degrees * 60_000.0).round() as i32;
        self
    }
}

/// `ST_TextVerticalType`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextVerticalType {
    Horizontal,
    /// `"vert"` — stacked top-to-bottom, each line reading top-to-bottom.
    Vertical,
    /// `"vert270"` — text rotated 270°, still stacked.
    Vertical270,
    /// `"wordArtVert"` — WordArt-style vertical stacking (one letter per line, upright).
    WordArtVertical,
    /// `"eaVert"` — East Asian vertical text layout.
    EastAsianVertical,
    /// `"mongolianVert"` — Mongolian vertical text layout.
    MongolianVertical,
    /// `"wordArtVertRtl"` — WordArt-style vertical stacking, right-to-left.
    WordArtVerticalRightToLeft,
}

impl TextVerticalType {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            TextVerticalType::Horizontal => "horz",
            TextVerticalType::Vertical => "vert",
            TextVerticalType::Vertical270 => "vert270",
            TextVerticalType::WordArtVertical => "wordArtVert",
            TextVerticalType::EastAsianVertical => "eaVert",
            TextVerticalType::MongolianVertical => "mongolianVert",
            TextVerticalType::WordArtVerticalRightToLeft => "wordArtVertRtl",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "horz" => TextVerticalType::Horizontal,
            "vert" => TextVerticalType::Vertical,
            "vert270" => TextVerticalType::Vertical270,
            "wordArtVert" => TextVerticalType::WordArtVertical,
            "eaVert" => TextVerticalType::EastAsianVertical,
            "mongolianVert" => TextVerticalType::MongolianVertical,
            "wordArtVertRtl" => TextVerticalType::WordArtVerticalRightToLeft,
            _ => return None,
        })
    }
}

/// `EG_TextAutofit` — how a text body reacts to content that doesn't fit its shape. Grounded
/// against real fixtures exercising all three variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextAutofit {
    /// `<a:noAutofit/>` — text overflows the shape rather than being resized (explicitly opts out,
    /// distinct from the field itself being `None`, which omits the element and inherits instead).
    None,
    /// `<a:spAutoFit/>` — the shape itself resizes to fit its text (a text box's own common
    /// default).
    Shape,
    /// `<a:normAutofit fontScale=".." lnSpcReduction=".."/>` — the text itself shrinks (font size
    /// scaled down, line spacing reduced) to fit the shape. Both attributes are
    /// `ST_TextFontScalePercentOrPercentString`/ `ST_TextSpacingPercentOrPercentString` in
    /// thousandths of a percent; `None` on either omits that attribute (a bare `<a:normAutofit/>`,
    /// also valid and commonly seen, meaning "shrink as needed, exact amount left to the
    /// renderer").
    Normal {
        font_scale_1000ths_percent: Option<i32>,
        line_spacing_reduction_1000ths_percent: Option<i32>,
    },
}

/// `ST_TextWrappingType`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextWrap {
    None,
    Square,
}

impl TextWrap {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            TextWrap::None => "none",
            TextWrap::Square => "square",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "none" => TextWrap::None,
            "square" => TextWrap::Square,
            _ => return None,
        })
    }
}

/// `ST_TextAnchoringType` — vertical anchor of a text body within its shape.
/// `Justified`/`Distributed` (`just`/`dist`) stretch line spacing to fill the shape's height rather
/// than anchoring to one edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextAnchor {
    Top,
    Center,
    Bottom,
    Justified,
    Distributed,
}

impl TextAnchor {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            TextAnchor::Top => "t",
            TextAnchor::Center => "ctr",
            TextAnchor::Bottom => "b",
            TextAnchor::Justified => "just",
            TextAnchor::Distributed => "dist",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "t" => TextAnchor::Top,
            "ctr" => TextAnchor::Center,
            "b" => TextAnchor::Bottom,
            "just" => TextAnchor::Justified,
            "dist" => TextAnchor::Distributed,
            _ => return None,
        })
    }
}

/// One paragraph of text (`<a:p>`, `CT_TextParagraph`).
///
/// Not modeled: `<a:endParaRPr>` (the formatting a UI would apply to text typed at this paragraph's
/// very end — a cosmetic authoring aid with no effect on existing content).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TextParagraph {
    /// `<a:pPr>`.
    pub properties: Option<TextParagraphProperties>,
    /// `EG_TextRun` — this crate only models the `r`/`br` choices (regular text and line breaks);
    /// `fld` (a field, e.g. a slide-number placeholder) is deferred — see [`TextRun`]'s doc
    /// comment.
    pub runs: Vec<TextRun>,
}

impl TextParagraph {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_properties(mut self, properties: TextParagraphProperties) -> Self {
        self.properties = Some(properties);
        self
    }

    pub fn with_run(mut self, run: TextRun) -> Self {
        self.runs.push(run);
        self
    }
}

/// `<a:pPr>`'s attributes (`CT_TextParagraphProperties`) — alignment, margins/indent, tab stops
/// (`tabLst`), paragraph spacing, indent/outline level, default run formatting, and bullets.
///
/// Not modeled: `<a:lstStyle>` (a text body's own per-level default paragraph styles, distinct from
/// any individual paragraph's own `pPr` modeled here — see [`TextBody`]'s doc comment).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TextParagraphProperties {
    /// `algn`.
    pub alignment: Option<TextAlign>,
    /// `marL`, in EMUs.
    pub margin_left_emu: Option<i64>,
    /// `marR`, in EMUs.
    pub margin_right_emu: Option<i64>,
    /// `indent` (first-line indent, can be negative for a hanging indent), in EMUs.
    pub indent_emu: Option<i64>,
    /// `lvl` (`ST_TextIndentLevelType`, `0.=8`) — this paragraph's indent/outline level, the
    /// mechanism real PowerPoint uses for multi-level bulleted/numbered lists (each level typically
    /// resolves its own bullet/indent/font size from the placeholder's `<a:lstStyle>` when not
    /// overridden directly on the paragraph, as here). `None` omits the attribute, equivalent to
    /// level `0`. Grounded against a real fixture.
    pub level: Option<u8>,
    /// `<a:tabLst><a:tab pos=".." algn=".."/>*</a:tabLst>` — this paragraph's own explicit tab
    /// stops, overriding whatever default tab spacing the host application would otherwise use. An
    /// empty `Vec` (the default) omits `<a:tabLst>` entirely, same "only write what was actually
    /// set" convention as every other optional child in this crate.
    pub tab_stops: Vec<TabStop>,
    /// `<a:lnSpc>` — line spacing. `None` inherits the host application's default.
    pub line_spacing: Option<TextSpacing>,
    /// `<a:spcBef>` — space before the paragraph.
    pub space_before: Option<TextSpacing>,
    /// `<a:spcAft>` — space after the paragraph.
    pub space_after: Option<TextSpacing>,
    /// `<a:buClrTx/>`/`<a:buClr>` — this paragraph's bullet color. `None` omits the element
    /// entirely (the bullet's color follows whatever the list style/master otherwise resolves,
    /// PowerPoint's actual default), distinct from `Some(BulletColor::FollowText)` (`<a:buClrTx/>`,
    /// explicitly "follow the text run's own color").
    pub bullet_color: Option<BulletColor>,
    /// `<a:buSzTx/>`/`<a:buSzPct>`/`<a:buSzPts>` — this paragraph's bullet size. Same
    /// `None`-omits-the-element posture as `bullet_color`.
    pub bullet_size: Option<BulletSize>,
    /// `<a:buFontTx/>`/`<a:buFont typeface=".">` — this paragraph's bullet font. Same
    /// `None`-omits-the-element posture as `bullet_color`. Only `typeface` is modeled (not
    /// `panose`/ `pitchFamily`/`charset`, all optional cosmetic hints).
    pub bullet_font: Option<BulletFont>,
    /// `<a:buNone/>`/`<a:buChar char=".">`/`<a:buAutoNum type=".">` — this paragraph's own
    /// bullet/numbering marker. `None` omits the element entirely (inherits from the list
    /// style/master, PowerPoint's actual default — usually a bullet for body text). Grounded
    /// against real fixtures covering both `buChar` and `buAutoNum`.
    pub bullet: Option<BulletKind>,
    /// `<a:defRPr>` — this paragraph's own default run formatting, used by any run that doesn't set
    /// the matching property itself, and by an empty paragraph's own end-of-paragraph mark. `None`
    /// omits the element entirely. Reuses [`TextRunProperties`] verbatim, the same vocabulary an
    /// individual run's own `<a:rPr>` uses.
    pub default_run_properties: Option<Box<TextRunProperties>>,
}

impl TextParagraphProperties {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_alignment(mut self, alignment: TextAlign) -> Self {
        self.alignment = Some(alignment);
        self
    }

    pub fn with_margins_emu(mut self, left: i64, right: i64) -> Self {
        self.margin_left_emu = Some(left);
        self.margin_right_emu = Some(right);
        self
    }

    pub fn with_indent_emu(mut self, indent: i64) -> Self {
        self.indent_emu = Some(indent);
        self
    }

    /// Sets the indent/outline level (`0.=8`).
    pub fn with_level(mut self, level: u8) -> Self {
        self.level = Some(level);
        self
    }

    /// Appends one explicit tab stop.
    pub fn with_tab_stop(mut self, tab_stop: TabStop) -> Self {
        self.tab_stops.push(tab_stop);
        self
    }

    pub fn with_line_spacing(mut self, spacing: TextSpacing) -> Self {
        self.line_spacing = Some(spacing);
        self
    }

    pub fn with_space_before(mut self, spacing: TextSpacing) -> Self {
        self.space_before = Some(spacing);
        self
    }

    pub fn with_space_after(mut self, spacing: TextSpacing) -> Self {
        self.space_after = Some(spacing);
        self
    }

    pub fn with_bullet_color(mut self, color: BulletColor) -> Self {
        self.bullet_color = Some(color);
        self
    }

    pub fn with_bullet_size(mut self, size: BulletSize) -> Self {
        self.bullet_size = Some(size);
        self
    }

    pub fn with_bullet_font(mut self, font: BulletFont) -> Self {
        self.bullet_font = Some(font);
        self
    }

    pub fn with_bullet(mut self, bullet: BulletKind) -> Self {
        self.bullet = Some(bullet);
        self
    }

    pub fn with_default_run_properties(mut self, properties: TextRunProperties) -> Self {
        self.default_run_properties = Some(Box::new(properties));
        self
    }
}

/// Paragraph-level spacing (`CT_TextSpacing`, the choice behind `<a:lnSpc>`/
/// `<a:spcBef>`/`<a:spcAft>`). Grounded against a real fixture exercising both variants side by
/// side (`<a:lnSpc><a:spcPct val="100000"/></a:lnSpc>`, `<a:spcBef><a:spcPts
/// val="0"/></a:spcBef>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextSpacing {
    /// `<a:spcPct val="..">` — a percentage of a single line's height, in thousandths of a percent
    /// (`100000` = 100%).
    Percent(i32),
    /// `<a:spcPts val="..">` — an absolute size in hundredths of a point (`1200` = 12pt).
    Points(i32),
}

/// This paragraph's bullet color (`EG_TextBulletColor`).
#[derive(Debug, Clone, PartialEq)]
pub enum BulletColor {
    /// `<a:buClrTx/>` — follows the text run's own color.
    FollowText,
    /// `<a:buClr>{color}</a:buClr>` — an explicit color, reusing [`Color`] verbatim. Like the rest
    /// of this crate's own `Color` usage, a theme-relative `<a:schemeClr>` reference isn't modeled
    /// — only literal colors (see [`Color`]'s own doc comment).
    Explicit(Color),
}

/// This paragraph's bullet size (`EG_TextBulletSize`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BulletSize {
    /// `<a:buSzTx/>` — follows the text run's own size.
    FollowText,
    /// `<a:buSzPct val="..">` — a percentage of the text's own size, in thousandths of a percent
    /// (`100000` = 100%).
    Percent(i32),
    /// `<a:buSzPts val="..">` — an absolute size in hundredths of a point.
    Points(i32),
}

/// This paragraph's bullet font (`EG_TextBulletTypeface`).
#[derive(Debug, Clone, PartialEq)]
pub enum BulletFont {
    /// `<a:buFontTx/>` — follows the text run's own font.
    FollowText,
    /// `<a:buFont typeface="..">` — an explicit font family name. Only `typeface` is modeled (not
    /// `panose`/`pitchFamily`/`charset`, all optional cosmetic hints real PowerPoint sets but
    /// doesn't require).
    Typeface(String),
}

/// This paragraph's bullet/numbering marker (`EG_TextBullet`).
#[derive(Debug, Clone, PartialEq)]
pub enum BulletKind {
    /// `<a:buNone/>` — explicitly no bullet (distinct from the field itself being `None`, which
    /// omits the element and inherits instead).
    None,
    /// `<a:buChar char="..">` — a literal bullet character (often from a symbol font like
    /// Wingdings, e.g. `"•"`/`"–"`/`"»"`).
    Character(String),
    /// `<a:buAutoNum type=".." startAt="..">` — an automatically incrementing number/letter.
    /// `scheme` is kept as the raw `ST_TextAutonumberScheme` token (e.g. `"arabicPeriod"`,
    /// `"romanUcPeriod"`, `"alphaLcParenR"` — ~20 values) rather than a closed enum, the same
    /// "large but finite token set, not enumerated" posture as [`Color::Preset`]. `start_at`
    /// (`None` defaults to `1` per the schema) overrides the starting number.
    AutoNumber {
        scheme: String,
        start_at: Option<i32>,
    },
}

/// One explicit tab stop (`<a:tab pos="." algn=".">`, `CT_TextTabStop`). Grounded against a real
/// fixture, which confirmed the `tabLst`/`tab` element shape and attribute names exactly as modeled
/// here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TabStop {
    /// `pos`, in EMUs, measured from the paragraph's left edge.
    pub position_emu: i64,
    /// `algn` — how text aligns to this stop. `None` omits the attribute, matching
    /// `ST_TextTabAlignType`'s own default (`"l"`, left).
    pub alignment: Option<TabAlignment>,
}

impl TabStop {
    /// Creates a left-aligned tab stop at the given position.
    pub fn new(position_emu: i64) -> Self {
        Self {
            position_emu,
            alignment: None,
        }
    }

    pub fn with_alignment(mut self, alignment: TabAlignment) -> Self {
        self.alignment = Some(alignment);
        self
    }
}

/// `ST_TextTabAlignType`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabAlignment {
    Left,
    Center,
    Right,
    Decimal,
}

impl TabAlignment {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            TabAlignment::Left => "l",
            TabAlignment::Center => "ctr",
            TabAlignment::Right => "r",
            TabAlignment::Decimal => "dec",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "l" => TabAlignment::Left,
            "ctr" => TabAlignment::Center,
            "r" => TabAlignment::Right,
            "dec" => TabAlignment::Decimal,
            _ => return None,
        })
    }
}

/// `ST_TextAlignType`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextAlign {
    Left,
    Center,
    Right,
    Justified,
    JustifiedLow,
    Distributed,
    ThaiDistributed,
}

impl TextAlign {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            TextAlign::Left => "l",
            TextAlign::Center => "ctr",
            TextAlign::Right => "r",
            TextAlign::Justified => "just",
            TextAlign::JustifiedLow => "justLow",
            TextAlign::Distributed => "dist",
            TextAlign::ThaiDistributed => "thaiDist",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "l" => TextAlign::Left,
            "ctr" => TextAlign::Center,
            "r" => TextAlign::Right,
            "just" => TextAlign::Justified,
            "justLow" => TextAlign::JustifiedLow,
            "dist" => TextAlign::Distributed,
            "thaiDist" => TextAlign::ThaiDistributed,
            _ => return None,
        })
    }
}

/// One run of text within a paragraph (`EG_TextRun`'s `r`/`br`/`fld` choices — see
/// [`TextRun::Field`]).
#[derive(Debug, Clone, PartialEq)]
pub enum TextRun {
    /// `<a:r><a:rPr../><a:t>..</a:t></a:r>`, `CT_RegularTextRun`.
    Regular {
        text: String,
        properties: TextRunProperties,
    },
    /// `<a:br><a:rPr../></a:br>`, `CT_TextLineBreak` — an explicit line break within a paragraph
    /// (distinct from starting a new `<a:p>`, which also resets paragraph-level properties).
    LineBreak {
        properties: Option<TextRunProperties>,
    },
    /// `<a:fld id="{GUID}" type=".."><a:rPr../><a:t>..</a:t></a:fld>`, `CT_TextField` — a dynamic,
    /// PowerPoint-updated value (slide number, current date..) rendered inline with a run's own
    /// text. Grounded against a real fixture's slide-number/date placeholders
    /// (`type="slidenum"`/`"datetimeFigureOut"`). `CT_TextField`'s own `pPr` child (paragraph
    /// properties duplicated onto the field, rarely populated in practice) is not modeled.
    Field {
        /// `id` — a GUID (`ST_Guid`, e.g. `"{5C4A1234-..}"`) uniquely identifying this field
        /// *within its host part*; real PowerPoint generates and preserves these itself.
        /// Stored/round-tripped verbatim, never generated or validated here.
        id: String,
        /// `type` — a free-form hint of what this field represents (real PowerPoint writes e.g.
        /// `"slidenum"`, `"datetime1"` through `"datetime13"`, `"datetimeFigureOut"` — this crate
        /// neither enumerates nor computes any of these, only stores whatever string is present).
        /// `None` omits the attribute (schema-valid, `type` is optional).
        field_type: Option<String>,
        /// `<a:t>` — the field's *cached* rendered text, exactly as PowerPoint last computed it
        /// (e.g. an actual date string, or `"‹N°›"` as a slide-number placeholder). Real PowerPoint
        /// recomputes and rewrites this text itself whenever the presentation is opened/printed;
        /// this crate never recomputes it.
        cached_text: String,
        properties: TextRunProperties,
    },
}

impl TextRun {
    /// A plain run of text with default (unset) formatting.
    pub fn text(text: impl Into<String>) -> Self {
        TextRun::Regular {
            text: text.into(),
            properties: TextRunProperties::new(),
        }
    }

    /// A run of text with explicit formatting.
    pub fn text_with_properties(text: impl Into<String>, properties: TextRunProperties) -> Self {
        TextRun::Regular {
            text: text.into(),
            properties,
        }
    }

    /// An explicit line break, inheriting the surrounding text's formatting.
    pub fn line_break() -> Self {
        TextRun::LineBreak { properties: None }
    }

    /// A dynamic field (slide number, date..), given its id, optional type hint, and current cached
    /// text, with default (unset) formatting.
    pub fn field(
        id: impl Into<String>,
        field_type: Option<String>,
        cached_text: impl Into<String>,
    ) -> Self {
        TextRun::Field {
            id: id.into(),
            field_type,
            cached_text: cached_text.into(),
            properties: TextRunProperties::new(),
        }
    }
}

/// A run's character formatting (`<a:rPr>`/`<a:defRPr>`/`<a:endParaRPr>`,
/// `CT_TextCharacterProperties`) — this crate only ever writes/reads it as `<a:rPr>` (on
/// `<a:r>`/`<a:br>`), not the other two contexts.
///
/// Not modeled: `lang`/`altLang` (spell-check locale), `kern`/`normalizeH` (kerning threshold,
/// auto-condensing East Asian punctuation — narrow cosmetic refinements; `spc`/`cap` *are* modeled,
/// see [`TextRunProperties::character_spacing_100ths_point`]/[`TextRunProperties::text_caps`];
/// `baseline`/`highlight` are also modeled, see
/// [`TextRunProperties::baseline_1000ths_percent`]/[`TextRunProperties::highlight`]),
/// `hlinkMouseOver` (a separate, rarely-authored hover-only link — only `hlinkClick` is modeled,
/// see [`Hyperlink`]), underline's own independent line/fill overrides (`EG_TextUnderlineLine`/
/// `Fill` — `u`'s color here always follows the text's own `fill`, matching most real-world usage),
/// and `ea`/`cs`/`sym` (East Asian/complex-script/ symbol font overrides — `latin` alone is
/// modeled, same "one font, not a per-script set" simplification `word-ooxml::Run::font_family`
/// already makes).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct TextRunProperties {
    /// `b` (`<a:rPr b="1">`).
    pub bold: bool,
    /// `i`.
    pub italic: bool,
    /// `u`.
    pub underline: Option<TextUnderline>,
    /// `strike`.
    pub strike: Option<TextStrike>,
    /// `EG_FillProperties` — the run's text color (or gradient/pattern/ image, though a flat
    /// [`Fill::Solid`] color covers the overwhelming majority of real documents). Reuses [`Fill`]
    /// directly rather than a narrower color-only field, since the schema itself allows the full
    /// fill choice here, not just `<a:solidFill>`.
    pub fill: Option<Fill>,
    /// `sz`, in hundredths of a point (`ST_TextFontSize`, `100.=400000` — i.e. 1pt to 4,000pt).
    pub font_size_100ths_point: Option<i32>,
    /// `<a:latin typeface="..">` — the run's font family/typeface, e.g. `"Calibri"`. Mirrors
    /// `word-ooxml::Run::font_family` by name for cross-crate consistency (same real-world
    /// concept).
    pub font_family: Option<String>,
    /// `<a:hlinkClick r:id="..">` (`CT_Hyperlink`, point 3) — a clickable hyperlink on this run.
    /// See [`Hyperlink`]'s own doc comment for why this carries an already-resolved relationship id
    /// rather than a raw URL.
    pub hyperlink: Option<Hyperlink>,
    /// `baseline` (`ST_Percentage`, thousandths of a percent) — raises (positive) or lowers
    /// (negative) the run's glyphs relative to the baseline, real PowerPoint's own
    /// superscript/subscript mechanism (its UI writes `30000` for superscript, `-25000` for
    /// subscript). `None` omits the attribute (no offset). Grounded against a real fixture
    /// exercising both signs.
    pub baseline_1000ths_percent: Option<i32>,
    /// `<a:highlight>{color}</a:highlight>` — the run's text-highlight color (like a highlighter
    /// pen), distinct from `fill`, which colors the glyphs themselves. `None` omits the element (no
    /// highlight). Grounded against a real fixture.
    pub highlight: Option<Color>,
    /// `cap` (`ST_TextCapsType`) — forces the run's glyphs to render as small caps or all caps,
    /// independent of the text actually typed (unlike literally typing uppercase letters, the
    /// underlying text stays whatever case it was entered in). `None` omits the attribute (no
    /// forced case). Grounded against a real fixture's slide text (`cap="none"`, PowerPoint's own
    /// explicit "no caps override" — distinct from omitting the attribute, though both render
    /// identically).
    pub text_caps: Option<TextCaps>,
    /// `spc` (`ST_TextSpacingPoint`, hundredths of a, may be negative to tighten spacing) — extra
    /// space inserted between characters. `None` omits the attribute (no adjustment). Grounded
    /// against a real fixture (`spc="70"`, 0.7pt extra tracking).
    pub character_spacing_100ths_point: Option<i32>,
}

impl TextRunProperties {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_bold(mut self, bold: bool) -> Self {
        self.bold = bold;
        self
    }

    pub fn with_italic(mut self, italic: bool) -> Self {
        self.italic = italic;
        self
    }

    pub fn with_underline(mut self, underline: TextUnderline) -> Self {
        self.underline = Some(underline);
        self
    }

    pub fn with_strike(mut self, strike: TextStrike) -> Self {
        self.strike = Some(strike);
        self
    }

    pub fn with_fill(mut self, fill: Fill) -> Self {
        self.fill = Some(fill);
        self
    }

    /// Sets the font size, given in ordinary points (converted to the schema's
    /// hundredths-of-a-point unit internally).
    pub fn with_font_size_points(mut self, points: f64) -> Self {
        self.font_size_100ths_point = Some((points * 100.0).round() as i32);
        self
    }

    pub fn with_font_family(mut self, font_family: impl Into<String>) -> Self {
        self.font_family = Some(font_family.into());
        self
    }

    /// Attaches a hyperlink to this run.
    pub fn with_hyperlink(mut self, hyperlink: Hyperlink) -> Self {
        self.hyperlink = Some(hyperlink);
        self
    }

    /// Sets the run's baseline offset (superscript/subscript), given as an ordinary percentage
    /// (e.g. `30.0` for real PowerPoint's own superscript, `-25.0` for its subscript).
    pub fn with_baseline_percent(mut self, percent: f64) -> Self {
        self.baseline_1000ths_percent = Some((percent * 1000.0).round() as i32);
        self
    }

    /// Sets the run's text-highlight color.
    pub fn with_highlight(mut self, color: Color) -> Self {
        self.highlight = Some(color);
        self
    }

    /// Sets the run's forced letter case (small caps/all caps).
    pub fn with_text_caps(mut self, caps: TextCaps) -> Self {
        self.text_caps = Some(caps);
        self
    }

    /// Sets the run's extra inter-character spacing, given in ordinary points (converted to the
    /// schema's hundredths-of-a-point unit internally; negative tightens spacing).
    pub fn with_character_spacing_points(mut self, points: f64) -> Self {
        self.character_spacing_100ths_point = Some((points * 100.0).round() as i32);
        self
    }
}

/// `ST_TextCapsType`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextCaps {
    /// `"none"` — no forced case (explicitly written, distinct from the field itself being `None`,
    /// which omits the attribute entirely).
    None,
    /// `"small"` — small capital letters.
    Small,
    /// `"all"` — full-size capital letters.
    All,
}

impl TextCaps {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            TextCaps::None => "none",
            TextCaps::Small => "small",
            TextCaps::All => "all",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "none" => TextCaps::None,
            "small" => TextCaps::Small,
            "all" => TextCaps::All,
            _ => return None,
        })
    }
}

/// A clickable hyperlink (`<a:hlinkClick>`, `CT_Hyperlink`).
///
/// Unlike `word_ooxml::Hyperlink` (which stores the actual target URL, or bookmark anchor, and lets
/// its own writer create the relationship at write time), this crate has no access to a
/// host-specific relationship accumulator from within a plain data model or from
/// [`crate::writer::write_text_run`] — resolving `r:id` against an actual OPC package/relationship
/// set is host-specific, the same posture already established for [`BlipFill::relationship_id`]
/// (see that field's own doc comment for the full rationale). `relationship_id` here is therefore
/// an **already-resolved** relationship id (e.g. `"rId4"`), which the host crate must obtain by
/// registering an external relationship (target mode external, pointing at the real URL) itself
/// before constructing this value — see `powerpoint-ooxml::AutoShape::hyperlink` for the
/// shape-level equivalent, which — being entirely host-owned — *does* take a plain URL directly,
/// since that crate's own writer controls relationship registration end to end for that field.
///
/// Grounded against real fixtures confirming `<a:hlinkClick r:id=".."/>` living directly inside
/// `<p:cNvPr>` (the shape-level placement this crate's own writer uses) as well as inside `<a:rPr>`
/// for run-level links.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Hyperlink {
    /// `r:id` — `None` omits the attribute (schema-valid: `CT_Hyperlink` allows a bare
    /// `<a:hlinkClick/>` with only `action`/other attributes set, though this crate has no use for
    /// that case today).
    pub relationship_id: Option<String>,
    /// `tooltip` — text shown in a tooltip when hovering the link.
    pub tooltip: Option<String>,
}

impl Hyperlink {
    /// Creates a hyperlink referencing the given (already-resolved) relationship id.
    pub fn new(relationship_id: impl Into<String>) -> Self {
        Self {
            relationship_id: Some(relationship_id.into()),
            tooltip: None,
        }
    }

    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }
}

/// `ST_TextUnderlineType`'s full set of 18 named underline styles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextUnderline {
    None,
    Words,
    Single,
    Double,
    Heavy,
    Dotted,
    DottedHeavy,
    Dash,
    DashHeavy,
    DashLong,
    DashLongHeavy,
    DotDash,
    DotDashHeavy,
    DotDotDash,
    DotDotDashHeavy,
    Wavy,
    WavyHeavy,
    WavyDouble,
}

impl TextUnderline {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            TextUnderline::None => "none",
            TextUnderline::Words => "words",
            TextUnderline::Single => "sng",
            TextUnderline::Double => "dbl",
            TextUnderline::Heavy => "heavy",
            TextUnderline::Dotted => "dotted",
            TextUnderline::DottedHeavy => "dottedHeavy",
            TextUnderline::Dash => "dash",
            TextUnderline::DashHeavy => "dashHeavy",
            TextUnderline::DashLong => "dashLong",
            TextUnderline::DashLongHeavy => "dashLongHeavy",
            TextUnderline::DotDash => "dotDash",
            TextUnderline::DotDashHeavy => "dotDashHeavy",
            TextUnderline::DotDotDash => "dotDotDash",
            TextUnderline::DotDotDashHeavy => "dotDotDashHeavy",
            TextUnderline::Wavy => "wavy",
            TextUnderline::WavyHeavy => "wavyHeavy",
            TextUnderline::WavyDouble => "wavyDbl",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "none" => TextUnderline::None,
            "words" => TextUnderline::Words,
            "sng" => TextUnderline::Single,
            "dbl" => TextUnderline::Double,
            "heavy" => TextUnderline::Heavy,
            "dotted" => TextUnderline::Dotted,
            "dottedHeavy" => TextUnderline::DottedHeavy,
            "dash" => TextUnderline::Dash,
            "dashHeavy" => TextUnderline::DashHeavy,
            "dashLong" => TextUnderline::DashLong,
            "dashLongHeavy" => TextUnderline::DashLongHeavy,
            "dotDash" => TextUnderline::DotDash,
            "dotDashHeavy" => TextUnderline::DotDashHeavy,
            "dotDotDash" => TextUnderline::DotDotDash,
            "dotDotDashHeavy" => TextUnderline::DotDotDashHeavy,
            "wavy" => TextUnderline::Wavy,
            "wavyHeavy" => TextUnderline::WavyHeavy,
            "wavyDbl" => TextUnderline::WavyDouble,
            _ => return None,
        })
    }
}

/// `ST_TextStrikeType`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextStrike {
    None,
    Single,
    Double,
}

impl TextStrike {
    pub(crate) fn xml_token(&self) -> &'static str {
        match self {
            TextStrike::None => "noStrike",
            TextStrike::Single => "sngStrike",
            TextStrike::Double => "dblStrike",
        }
    }

    pub(crate) fn from_xml_token(token: &str) -> Option<Self> {
        Some(match token {
            "noStrike" => TextStrike::None,
            "sngStrike" => TextStrike::Single,
            "dblStrike" => TextStrike::Double,
            _ => return None,
        })
    }
}