hwpforge-smithy-hwpx 0.1.1

HWPX format codec (encoder + decoder) for HwpForge
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
//! HWPX-specific style storage.
//!
//! [`HwpxStyleStore`] is the **smithy-hwpx** analogue of Blueprint's
//! `StyleRegistry`, but much simpler: it stores only what was actually
//! found in `header.xml`, with zero inheritance logic.
//!
//! All fields use Foundation types (`Color`, `HwpUnit`, `Alignment`)
//! so downstream code never touches raw XML strings.

use hwpforge_blueprint::registry::StyleRegistry;
use hwpforge_core::{NumberingDef, TabDef};
use hwpforge_foundation::{
    Alignment, BorderFillIndex, BreakType, CharShapeIndex, Color, EmbossType, EmphasisType,
    EngraveType, FontIndex, HeadingType, HwpUnit, LineSpacingType, OutlineType, ParaShapeIndex,
    ShadowType, StrikeoutShape, UnderlineType, VerticalPosition, WordBreakType,
};

use crate::default_styles::HancomStyleSet;
use crate::error::{HwpxError, HwpxResult};

// ── Font ─────────────────────────────────────────────────────────

/// A resolved font from `<hh:fontface>` → `<hh:font>`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HwpxFont {
    /// Original `id` attribute from XML.
    pub id: u32,
    /// Face name (e.g. `"함초롬돋움"`, `"Times New Roman"`).
    pub face_name: String,
    /// Language group this font belongs to (e.g. `"HANGUL"`, `"LATIN"`).
    pub lang: String,
}

impl HwpxFont {
    /// Creates a new font entry.
    pub fn new(id: u32, face_name: impl Into<String>, lang: impl Into<String>) -> Self {
        Self { id, face_name: face_name.into(), lang: lang.into() }
    }
}

// ── Per-language font references ─────────────────────────────────

/// Per-language font index references from `<hh:fontRef>`.
///
/// Each field is a [`FontIndex`] pointing into the store's font list
/// for that language group.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct HwpxFontRef {
    /// Hangul (한글) font index.
    pub hangul: FontIndex,
    /// Latin font index.
    pub latin: FontIndex,
    /// Hanja (한자) font index.
    pub hanja: FontIndex,
    /// Japanese (日本語) font index.
    pub japanese: FontIndex,
    /// Other scripts font index.
    pub other: FontIndex,
    /// Symbol font index.
    pub symbol: FontIndex,
    /// User-defined font index.
    pub user: FontIndex,
}

impl Default for HwpxFontRef {
    fn default() -> Self {
        let zero = FontIndex::new(0);
        Self {
            hangul: zero,
            latin: zero,
            hanja: zero,
            japanese: zero,
            other: zero,
            symbol: zero,
            user: zero,
        }
    }
}

// ── Character Shape ──────────────────────────────────────────────

/// Resolved character properties from `<hh:charPr>`.
///
/// All raw XML strings have been converted to Foundation types.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HwpxCharShape {
    /// Per-language font references.
    pub font_ref: HwpxFontRef,
    /// Font height in HwpUnit (height attribute × 1, already HWPUNIT).
    pub height: HwpUnit,
    /// Text color (from `textColor` attribute, e.g. `"#000000"`).
    pub text_color: Color,
    /// Background shade color (from `shadeColor`, `"none"` → None).
    pub shade_color: Option<Color>,
    /// Bold formatting.
    pub bold: bool,
    /// Italic formatting.
    pub italic: bool,
    /// Underline type (e.g. `None`, `Bottom`).
    pub underline_type: UnderlineType,
    /// Underline color (None = inherit text color).
    pub underline_color: Option<Color>,
    /// Strikeout shape (e.g. `None`, `Continuous`).
    pub strikeout_shape: StrikeoutShape,
    /// Strikeout color (None = inherit text color).
    pub strikeout_color: Option<Color>,
    /// Vertical position (Normal/Superscript/Subscript).
    pub vertical_position: VerticalPosition,
    /// Text outline type.
    pub outline_type: OutlineType,
    /// Drop shadow type.
    pub shadow_type: ShadowType,
    /// Emboss effect type.
    pub emboss_type: EmbossType,
    /// Engrave effect type.
    pub engrave_type: EngraveType,
    /// Emphasis mark type (from `symMark` attribute).
    pub emphasis: EmphasisType,
    /// Character width ratio (uniform, from `ratio` child element).
    pub ratio: i32,
    /// Inter-character spacing (uniform, from `spacing` child element).
    pub spacing: i32,
    /// Relative font size (uniform, from `relSz` child element).
    pub rel_sz: i32,
    /// Vertical position offset (uniform, from `offset` child element).
    pub char_offset: i32,
    /// Enable kerning (from `useKerning` attribute, 0/1).
    pub use_kerning: bool,
    /// Use font space (from `useFontSpace` attribute, 0/1).
    pub use_font_space: bool,
    /// Border/fill reference for character border (`borderFillIDRef`).
    ///
    /// `None` means use the default value of `2` (한글 default char background).
    /// Set to `Some(id)` to reference a custom `HwpxBorderFill` entry.
    pub border_fill_id: Option<u32>,
}

impl Default for HwpxCharShape {
    fn default() -> Self {
        Self {
            font_ref: HwpxFontRef::default(),
            height: HwpUnit::new(1000).unwrap(), // 10pt default (한글 compatible)
            text_color: Color::BLACK,
            shade_color: None,
            bold: false,
            italic: false,
            underline_type: UnderlineType::None,
            underline_color: None,
            strikeout_shape: StrikeoutShape::None,
            strikeout_color: None,
            vertical_position: VerticalPosition::Normal,
            outline_type: OutlineType::None,
            shadow_type: ShadowType::None,
            emboss_type: EmbossType::None,
            engrave_type: EngraveType::None,
            emphasis: EmphasisType::None,
            ratio: 100,
            spacing: 0,
            rel_sz: 100,
            char_offset: 0,
            use_kerning: false,
            use_font_space: false,
            border_fill_id: None,
        }
    }
}

// ── Style ────────────────────────────────────────────────────────

/// Resolved style definition from `<hh:style>`.
///
/// Stores style metadata like names and references to character/paragraph
/// properties. This enables full roundtrip of style names like "바탕글",
/// "본문", etc.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HwpxStyle {
    /// Style ID (from `id` attribute).
    pub id: u32,
    /// Style type (e.g. `"PARA"`, `"CHAR"`).
    pub style_type: String,
    /// Korean style name (e.g. `"바탕글"`).
    pub name: String,
    /// English style name (e.g. `"Normal"`).
    pub eng_name: String,
    /// Reference to paragraph properties (from `paraPrIDRef`).
    pub para_pr_id_ref: u32,
    /// Reference to character properties (from `charPrIDRef`).
    pub char_pr_id_ref: u32,
    /// Reference to next style (from `nextStyleIDRef`).
    pub next_style_id_ref: u32,
    /// Language ID (from `langID`).
    pub lang_id: u32,
}

// ── Paragraph Shape ──────────────────────────────────────────────

/// Resolved paragraph properties from `<hh:paraPr>`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HwpxParaShape {
    /// Horizontal alignment.
    pub alignment: Alignment,
    /// Left indent (from `<hc:left value="..."/>`).
    pub margin_left: HwpUnit,
    /// Right indent.
    pub margin_right: HwpUnit,
    /// Paragraph indent (from `<hc:intent value="..."/>`).
    pub indent: HwpUnit,
    /// Space before paragraph (from `<hc:prev value="..."/>`).
    pub spacing_before: HwpUnit,
    /// Space after paragraph (from `<hc:next value="..."/>`).
    pub spacing_after: HwpUnit,
    /// Line spacing value.
    pub line_spacing: i32,
    /// Line spacing type.
    pub line_spacing_type: LineSpacingType,

    // Advanced paragraph controls (NEW - Phase 6.2)
    /// Page/column break type before paragraph.
    pub break_type: BreakType,
    /// Keep paragraph with next (prevent page break between).
    pub keep_with_next: bool,
    /// Keep lines together (prevent page break within paragraph).
    pub keep_lines_together: bool,
    /// Widow/orphan control (minimum 2 lines at page boundaries).
    pub widow_orphan: bool,
    /// Word-breaking rule for Latin text (default: KeepWord).
    pub break_latin_word: WordBreakType,
    /// Word-breaking rule for non-Latin text including Korean (default: KeepWord).
    pub break_non_latin_word: WordBreakType,
    /// Border/fill reference (None = no border/fill).
    pub border_fill_id: Option<BorderFillIndex>,
    /// Heading type for this paragraph.
    pub heading_type: HeadingType,
    /// Heading numbering reference (idRef in heading element, 0 = none).
    pub heading_id_ref: u32,
    /// Heading outline level (0 = none, 1-10 for outline levels).
    pub heading_level: u32,
    /// Tab property reference (tabPrIDRef, 0 = default).
    pub tab_pr_id_ref: u32,
    /// Condense value for tight outline spacing.
    pub condense: u32,
}

impl Default for HwpxParaShape {
    fn default() -> Self {
        Self {
            alignment: Alignment::Left,
            margin_left: HwpUnit::ZERO,
            margin_right: HwpUnit::ZERO,
            indent: HwpUnit::ZERO,
            spacing_before: HwpUnit::ZERO,
            spacing_after: HwpUnit::ZERO,
            line_spacing: 160,
            line_spacing_type: LineSpacingType::Percentage,
            break_type: BreakType::None,
            keep_with_next: false,
            keep_lines_together: false,
            widow_orphan: true, // Enabled by default in HWPX
            break_latin_word: WordBreakType::KeepWord,
            break_non_latin_word: WordBreakType::KeepWord,
            border_fill_id: None,
            heading_type: HeadingType::None,
            heading_id_ref: 0,
            heading_level: 0,
            tab_pr_id_ref: 0,
            condense: 0,
        }
    }
}

// ── Border Fill ──────────────────────────────────────────────────

/// Resolved border/fill definition from `<hh:borderFill>`.
///
/// Stores border line styles for all 4 sides plus diagonal borders,
/// 3D/shadow flags, and optional fill configuration.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct HwpxBorderFill {
    /// Border fill ID (1-based, matching `borderFillIDRef` in charPr/paraPr).
    pub id: u32,
    /// Whether 3D border effect is enabled.
    pub three_d: bool,
    /// Whether shadow effect is enabled.
    pub shadow: bool,
    /// Center line type string (e.g. `"NONE"`).
    pub center_line: String,
    /// Left border line.
    pub left: HwpxBorderLine,
    /// Right border line.
    pub right: HwpxBorderLine,
    /// Top border line.
    pub top: HwpxBorderLine,
    /// Bottom border line.
    pub bottom: HwpxBorderLine,
    /// Diagonal border line.
    pub diagonal: HwpxBorderLine,
    /// Slash diagonal type string.
    pub slash_type: String,
    /// Back-slash diagonal type string.
    pub back_slash_type: String,
    /// Fill brush configuration (None = no fill / transparent).
    pub fill: Option<HwpxFill>,
}

/// A single border line configuration.
#[derive(Debug, Clone, PartialEq)]
pub struct HwpxBorderLine {
    /// Border line type (e.g. `"NONE"`, `"SOLID"`).
    pub line_type: String,
    /// Width string (e.g. `"0.1 mm"`).
    pub width: String,
    /// Color string (e.g. `"#000000"`).
    pub color: String,
}

impl Default for HwpxBorderLine {
    fn default() -> Self {
        Self { line_type: "NONE".into(), width: "0.1 mm".into(), color: "#000000".into() }
    }
}

/// Fill brush configuration for a [`HwpxBorderFill`].
#[derive(Debug, Clone, PartialEq)]
pub enum HwpxFill {
    /// Solid or hatch fill via `<hc:winBrush>`.
    WinBrush {
        /// Face color string (e.g. `"none"`, `"#RRGGBB"`).
        face_color: String,
        /// Hatch pattern color string.
        hatch_color: String,
        /// Alpha transparency string.
        alpha: String,
    },
}

impl HwpxBorderFill {
    /// Default border fill id=1: empty borders, no fill (used for page borders).
    ///
    /// Matches the first entry of the legacy `BORDER_FILLS_XML` constant.
    pub fn default_page_border() -> Self {
        let none_border = HwpxBorderLine::default(); // NONE, 0.1 mm, #000000
        Self {
            id: 1,
            three_d: false,
            shadow: false,
            center_line: "NONE".into(),
            left: none_border.clone(),
            right: none_border.clone(),
            top: none_border.clone(),
            bottom: none_border.clone(),
            diagonal: HwpxBorderLine { line_type: "SOLID".into(), ..HwpxBorderLine::default() },
            slash_type: "NONE".into(),
            back_slash_type: "NONE".into(),
            fill: None,
        }
    }

    /// Default border fill id=2: char background with `winBrush` fill.
    ///
    /// This is referenced by every `<hh:charPr borderFillIDRef="2">`.
    /// Matches the second entry of the legacy `BORDER_FILLS_XML` constant.
    pub fn default_char_background() -> Self {
        let none_border = HwpxBorderLine::default();
        Self {
            id: 2,
            three_d: false,
            shadow: false,
            center_line: "NONE".into(),
            left: none_border.clone(),
            right: none_border.clone(),
            top: none_border.clone(),
            bottom: none_border.clone(),
            diagonal: HwpxBorderLine { line_type: "SOLID".into(), ..HwpxBorderLine::default() },
            slash_type: "NONE".into(),
            back_slash_type: "NONE".into(),
            fill: Some(HwpxFill::WinBrush {
                face_color: "none".into(),
                hatch_color: "#FF000000".into(),
                alpha: "0".into(),
            }),
        }
    }

    /// Default border fill id=3: SOLID borders on all 4 sides (used for table cells).
    ///
    /// Matches the third entry of the legacy `BORDER_FILLS_XML` constant.
    pub fn default_table_border() -> Self {
        let solid_border = HwpxBorderLine {
            line_type: "SOLID".into(),
            width: "0.12 mm".into(),
            color: "#000000".into(),
        };
        Self {
            id: 3,
            three_d: false,
            shadow: false,
            center_line: "NONE".into(),
            left: solid_border.clone(),
            right: solid_border.clone(),
            top: solid_border.clone(),
            bottom: solid_border.clone(),
            diagonal: HwpxBorderLine { line_type: "SOLID".into(), ..HwpxBorderLine::default() },
            slash_type: "NONE".into(),
            back_slash_type: "NONE".into(),
            fill: None,
        }
    }
}

// ── Default shape definitions ────────────────────────────────────

/// Returns the 7 default character shapes for Modern (한글 2022+).
///
/// Extracted from golden fixture `tests/fixtures/textbox.hwpx` `Contents/header.xml`.
///
/// ```text
/// id=0: 함초롬바탕 10pt #000000  (바탕글/본문/개요1-7/캡션)
/// id=1: 함초롬돋움 10pt #000000  (쪽 번호)
/// id=2: 함초롬돋움  9pt #000000  (머리말)
/// id=3: 함초롬바탕  9pt #000000  (각주/미주)
/// id=4: 함초롬돋움  9pt #000000  (메모)
/// id=5: 함초롬돋움 16pt #2E74B5  (차례 제목)
/// id=6: 함초롬돋움 11pt #000000  (차례 1-3)
/// ```
///
/// Font indices: 0 = 함초롬돋움, 1 = 함초롬바탕 (as in fixture font table).
pub(crate) fn default_char_shapes_modern() -> [HwpxCharShape; 7] {
    let batang = FontIndex::new(1); // 함초롬바탕
    let dotum = FontIndex::new(0); // 함초롬돋움

    let batang_ref = HwpxFontRef {
        hangul: batang,
        latin: batang,
        hanja: batang,
        japanese: batang,
        other: batang,
        symbol: batang,
        user: batang,
    };
    let dotum_ref = HwpxFontRef {
        hangul: dotum,
        latin: dotum,
        hanja: dotum,
        japanese: dotum,
        other: dotum,
        symbol: dotum,
        user: dotum,
    };

    let base = HwpxCharShape {
        font_ref: batang_ref,
        height: HwpUnit::new(1000).unwrap(), // 10pt
        text_color: Color::BLACK,
        shade_color: None,
        bold: false,
        italic: false,
        underline_type: UnderlineType::None,
        underline_color: None,
        strikeout_shape: StrikeoutShape::None,
        strikeout_color: None,
        vertical_position: VerticalPosition::Normal,
        outline_type: OutlineType::None,
        shadow_type: ShadowType::None,
        emboss_type: EmbossType::None,
        engrave_type: EngraveType::None,
        emphasis: EmphasisType::None,
        ratio: 100,
        spacing: 0,
        rel_sz: 100,
        char_offset: 0,
        use_kerning: false,
        use_font_space: false,
        border_fill_id: None,
    };

    [
        // id=0: 함초롬바탕 10pt black (바탕글/본문/개요1-7/캡션)
        base.clone(),
        // id=1: 함초롬돋움 10pt black (쪽 번호)
        HwpxCharShape { font_ref: dotum_ref, ..base.clone() },
        // id=2: 함초롬돋움 9pt black (머리말)
        HwpxCharShape { font_ref: dotum_ref, height: HwpUnit::new(900).unwrap(), ..base.clone() },
        // id=3: 함초롬바탕 9pt black (각주/미주)
        HwpxCharShape { height: HwpUnit::new(900).unwrap(), ..base.clone() },
        // id=4: 함초롬돋움 9pt black (메모)
        HwpxCharShape { font_ref: dotum_ref, height: HwpUnit::new(900).unwrap(), ..base.clone() },
        // id=5: 함초롬돋움 16pt #2E74B5 (차례 제목)
        HwpxCharShape {
            font_ref: dotum_ref,
            height: HwpUnit::new(1600).unwrap(),
            text_color: Color::from_rgb(0x2E, 0x74, 0xB5),
            ..base.clone()
        },
        // id=6: 함초롬돋움 11pt black (차례 1-3)
        HwpxCharShape { font_ref: dotum_ref, height: HwpUnit::new(1100).unwrap(), ..base },
    ]
}

/// Returns the 20 default paragraph shapes for Modern (한글 2022+).
///
/// Extracted from golden fixture `tests/fixtures/textbox.hwpx` `Contents/header.xml`.
///
/// Values are in HWPUNIT (1pt = 100 HWPUNIT).
pub(crate) fn default_para_shapes_modern() -> [HwpxParaShape; 20] {
    let justify = Alignment::Justify;
    let left = Alignment::Left;

    // Base: JUSTIFY, no margins/indent, 160% line spacing, no widow/orphan
    let base = HwpxParaShape {
        alignment: justify,
        margin_left: HwpUnit::ZERO,
        margin_right: HwpUnit::ZERO,
        indent: HwpUnit::ZERO,
        spacing_before: HwpUnit::ZERO,
        spacing_after: HwpUnit::ZERO,
        line_spacing: 160,
        line_spacing_type: LineSpacingType::Percentage,
        break_type: BreakType::None,
        keep_with_next: false,
        keep_lines_together: false,
        widow_orphan: false,
        break_latin_word: WordBreakType::KeepWord,
        break_non_latin_word: WordBreakType::KeepWord,
        border_fill_id: None,
        heading_type: HeadingType::None,
        heading_id_ref: 0,
        heading_level: 0,
        tab_pr_id_ref: 0,
        condense: 0,
    };

    [
        //  0: 바탕글 — JUSTIFY left=0 160%
        base.clone(),
        //  1: 본문 — JUSTIFY left=1500 160%
        HwpxParaShape { margin_left: HwpUnit::new(1500).unwrap(), ..base.clone() },
        //  2: 개요 1 — JUSTIFY left=1000 160% OUTLINE level=1
        HwpxParaShape {
            margin_left: HwpUnit::new(1000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 1,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        //  3: 개요 2 — JUSTIFY left=2000 160% OUTLINE level=2
        HwpxParaShape {
            margin_left: HwpUnit::new(2000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 2,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        //  4: 개요 3 — JUSTIFY left=3000 160% OUTLINE level=3
        HwpxParaShape {
            margin_left: HwpUnit::new(3000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 3,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        //  5: 개요 4 — JUSTIFY left=4000 160% OUTLINE level=4
        HwpxParaShape {
            margin_left: HwpUnit::new(4000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 4,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        //  6: 개요 5 — JUSTIFY left=5000 160% OUTLINE level=5
        HwpxParaShape {
            margin_left: HwpUnit::new(5000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 5,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        //  7: 개요 6 — JUSTIFY left=6000 160% OUTLINE level=6
        HwpxParaShape {
            margin_left: HwpUnit::new(6000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 6,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        //  8: 개요 7 — JUSTIFY left=7000 160% OUTLINE level=7
        HwpxParaShape {
            margin_left: HwpUnit::new(7000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 7,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        //  9: 머리말 — JUSTIFY left=0 150%
        HwpxParaShape { line_spacing: 150, ..base.clone() },
        // 10: 각주/미주 — JUSTIFY indent=-1310 130%
        HwpxParaShape { indent: HwpUnit::new(-1310).unwrap(), line_spacing: 130, ..base.clone() },
        // 11: 메모 — LEFT left=0 130%
        HwpxParaShape { alignment: left, line_spacing: 130, ..base.clone() },
        // 12: 차례 제목 — LEFT left=0 prev=1200 next=300 160%
        HwpxParaShape {
            alignment: left,
            spacing_before: HwpUnit::new(1200).unwrap(),
            spacing_after: HwpUnit::new(300).unwrap(),
            ..base.clone()
        },
        // 13: 차례 1 — LEFT left=0 next=700 160%
        HwpxParaShape {
            alignment: left,
            spacing_after: HwpUnit::new(700).unwrap(),
            ..base.clone()
        },
        // 14: 차례 2 — LEFT left=1100 next=700 160%
        HwpxParaShape {
            alignment: left,
            margin_left: HwpUnit::new(1100).unwrap(),
            spacing_after: HwpUnit::new(700).unwrap(),
            ..base.clone()
        },
        // 15: 차례 3 — LEFT left=2200 next=700 160%
        HwpxParaShape {
            alignment: left,
            margin_left: HwpUnit::new(2200).unwrap(),
            spacing_after: HwpUnit::new(700).unwrap(),
            ..base.clone()
        },
        // 16: 개요 9 (style 10→paraPr 16) — JUSTIFY left=9000 160% OUTLINE level=9
        HwpxParaShape {
            margin_left: HwpUnit::new(9000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 9,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        // 17: 개요 10 (style 11→paraPr 17) — JUSTIFY left=10000 160% OUTLINE level=10
        HwpxParaShape {
            margin_left: HwpUnit::new(10000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 10,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        // 18: 개요 8 (style 9→paraPr 18) — JUSTIFY left=8000 160% OUTLINE level=8
        HwpxParaShape {
            margin_left: HwpUnit::new(8000).unwrap(),
            heading_type: HeadingType::Outline,
            heading_id_ref: 1,
            heading_level: 8,
            tab_pr_id_ref: 1,
            condense: 20,
            ..base.clone()
        },
        // 19: 캡션 — JUSTIFY left=0 next=800 150%
        HwpxParaShape { line_spacing: 150, spacing_after: HwpUnit::new(800).unwrap(), ..base },
    ]
}

// ── Style Store ──────────────────────────────────────────────────

/// HWPX-specific style storage populated from `header.xml`.
///
/// Unlike Blueprint's `StyleRegistry`, this has no inheritance or
/// template merging — it holds exactly what was parsed from the file.
///
/// # Index Safety
///
/// All accessors return `HwpxResult<&T>` to guard against invalid
/// indices from malformed HWPX files.
///
/// # Examples
///
/// ```
/// use hwpforge_smithy_hwpx::HwpxStyleStore;
/// use hwpforge_foundation::CharShapeIndex;
///
/// let store = HwpxStyleStore::new();
/// assert!(store.char_shape(CharShapeIndex::new(0)).is_err());
/// ```
#[derive(Debug, Clone, Default)]
pub struct HwpxStyleStore {
    /// The 한글 version style set used when injecting default styles.
    style_set: HancomStyleSet,
    fonts: Vec<HwpxFont>,
    char_shapes: Vec<HwpxCharShape>,
    para_shapes: Vec<HwpxParaShape>,
    styles: Vec<HwpxStyle>,
    border_fills: Vec<HwpxBorderFill>,
    numberings: Vec<NumberingDef>,
    tabs: Vec<TabDef>,
}

impl HwpxStyleStore {
    /// Creates an empty store.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new style store with the given font registered for all 7 language groups
    /// (HANGUL, LATIN, HANJA, JAPANESE, OTHER, SYMBOL, USER).
    ///
    /// This eliminates the common boilerplate of manually pushing fonts for each language.
    ///
    /// # Examples
    ///
    /// ```
    /// use hwpforge_smithy_hwpx::style_store::HwpxStyleStore;
    ///
    /// let store = HwpxStyleStore::with_default_fonts("함초롬돋움");
    /// assert_eq!(store.font_count(), 7);
    /// ```
    pub fn with_default_fonts(font_name: &str) -> Self {
        let mut store: Self = Self::new();
        let langs: [&str; 7] = ["HANGUL", "LATIN", "HANJA", "JAPANESE", "OTHER", "SYMBOL", "USER"];
        for (idx, &lang) in langs.iter().enumerate() {
            store.push_font(HwpxFont::new(idx as u32, font_name, lang));
        }
        store
    }

    /// Returns the style set used by this store.
    pub fn style_set(&self) -> HancomStyleSet {
        self.style_set
    }

    /// Creates a store from a Blueprint [`StyleRegistry`] using the default
    /// style set ([`HancomStyleSet::Modern`]).
    ///
    /// This is the **bridge** that lets the MD → Core → HWPX pipeline
    /// carry resolved styles all the way through to the HWPX encoder.
    ///
    /// To target a specific 한글 version, use [`from_registry_with`][Self::from_registry_with].
    pub fn from_registry(registry: &StyleRegistry) -> Self {
        Self::from_registry_with(registry, HancomStyleSet::default())
    }

    /// Creates a store from a Blueprint [`StyleRegistry`] with a specific style set.
    ///
    /// The `style_set` controls which default styles are injected:
    /// - [`Classic`][HancomStyleSet::Classic] — 18 styles (한글 2014–2020)
    /// - [`Modern`][HancomStyleSet::Modern] — 22 styles (한글 2022+)
    /// - [`Latest`][HancomStyleSet::Latest] — 23 styles (한글 2025+)
    ///
    /// Mapping:
    /// - `registry.fonts` → [`HwpxFont`] (assigned to HANGUL group)
    /// - `registry.char_shapes` → [`HwpxCharShape`] (font ref mirrors same index for all lang groups)
    /// - `registry.para_shapes` → [`HwpxParaShape`]
    /// - `registry.style_entries` → [`HwpxStyle`] (PARA type, Korean langID)
    pub fn from_registry_with(registry: &StyleRegistry, style_set: HancomStyleSet) -> Self {
        let mut store = Self { style_set, ..Self::default() };

        // Step 1: Ensure 한글-compatible fonts exist
        // If registry has no fonts, inject default Korean fonts
        let has_fonts = !registry.fonts.is_empty();
        let default_font = if has_fonts {
            registry.fonts[0].as_str()
        } else {
            "함초롬바탕" // Fallback if no fonts in registry
        };

        // Fonts: FontId → HwpxFont (mirrored across all 7 language groups)
        // 한글 expects identical font entries for each language group.
        const FONT_LANGS: &[&str] =
            &["HANGUL", "LATIN", "HANJA", "JAPANESE", "OTHER", "SYMBOL", "USER"];

        if has_fonts {
            for &lang in FONT_LANGS {
                for (i, font_id) in registry.fonts.iter().enumerate() {
                    store.push_font(HwpxFont {
                        id: i as u32,
                        face_name: font_id.as_str().to_string(),
                        lang: lang.to_string(),
                    });
                }
            }
        } else {
            // No fonts in registry - inject minimal default
            for &lang in FONT_LANGS {
                store.push_font(HwpxFont {
                    id: 0,
                    face_name: default_font.to_string(),
                    lang: lang.to_string(),
                });
            }
        }

        // Step 2: Inject 7 default charShapes and 20 default paraShapes (Modern).
        //
        // These MUST come first so that default styles can reference them by
        // group index (char_pr_group / para_pr_group from DefaultStyleEntry).
        // User shapes are pushed after and start at offset 7 / 20.
        //
        // Classic and Latest share the same shape definitions (only the style
        // table and its charPr/paraPr references differ).
        for cs in default_char_shapes_modern() {
            store.push_char_shape(cs);
        }
        for ps in default_para_shapes_modern() {
            store.push_para_shape(ps);
        }

        // Offsets for user-defined shapes (placed after the 7+20 defaults).
        let char_shape_offset = store.char_shape_count(); // 7
        let para_shape_offset = store.para_shape_count(); // 20

        // Step 3: Push user charShapes from Blueprint (indices start at offset).
        for cs in &registry.char_shapes {
            let font_idx = registry
                .fonts
                .iter()
                .position(|f| f.as_str() == cs.font)
                .map(FontIndex::new)
                .unwrap_or(FontIndex::new(0));
            let font_ref = HwpxFontRef {
                hangul: font_idx,
                latin: font_idx,
                hanja: font_idx,
                japanese: font_idx,
                other: font_idx,
                symbol: font_idx,
                user: font_idx,
            };
            store.push_char_shape(HwpxCharShape {
                font_ref,
                height: cs.size,
                text_color: cs.color,
                shade_color: cs.shade_color,
                bold: cs.bold,
                italic: cs.italic,
                underline_type: cs.underline_type,
                underline_color: cs.underline_color,
                strikeout_shape: cs.strikeout_shape,
                strikeout_color: cs.strikeout_color,
                vertical_position: cs.vertical_position,
                outline_type: cs.outline,
                shadow_type: cs.shadow,
                emboss_type: cs.emboss,
                engrave_type: cs.engrave,
                emphasis: cs.emphasis,
                ratio: cs.ratio,
                spacing: cs.spacing,
                rel_sz: cs.rel_sz,
                char_offset: cs.offset,
                use_kerning: cs.use_kerning,
                use_font_space: cs.use_font_space,
                border_fill_id: cs.char_border_fill_id,
            });
        }

        // Step 4: Push user paraShapes from Blueprint (indices start at offset).
        for ps in &registry.para_shapes {
            store.push_para_shape(HwpxParaShape {
                alignment: ps.alignment,
                margin_left: ps.indent_left,
                margin_right: ps.indent_right,
                indent: ps.indent_first_line,
                spacing_before: ps.space_before,
                spacing_after: ps.space_after,
                line_spacing: ps.line_spacing_value.round() as i32,
                line_spacing_type: ps.line_spacing_type,
                break_type: ps.break_type,
                keep_with_next: ps.keep_with_next,
                keep_lines_together: ps.keep_lines_together,
                widow_orphan: ps.widow_orphan,
                break_latin_word: WordBreakType::KeepWord,
                break_non_latin_word: WordBreakType::KeepWord,
                border_fill_id: ps.border_fill_id,
                heading_type: HeadingType::None,
                heading_id_ref: 0,
                heading_level: 0,
                tab_pr_id_ref: 0,
                condense: 0,
            });
        }

        // Step 4.5: Inject 3 default border fills for backward compatibility.
        // These must always be present; user-defined fills get id=4+.
        store.push_border_fill(HwpxBorderFill::default_page_border()); // id=1
        store.push_border_fill(HwpxBorderFill::default_char_background()); // id=2
        store.push_border_fill(HwpxBorderFill::default_table_border()); // id=3

        // Step 5: Inject default styles with per-style charPr/paraPr group refs.
        // The group indices are verified against golden fixture textbox.hwpx.
        let defaults = store.style_set.default_styles();
        for (idx, entry) in defaults.iter().enumerate() {
            let next_style_id_ref = if entry.is_char_style() { 0 } else { idx as u32 };
            store.push_style(HwpxStyle {
                id: idx as u32,
                style_type: entry.style_type.to_string(),
                name: entry.name.to_string(),
                eng_name: entry.eng_name.to_string(),
                para_pr_id_ref: entry.para_pr_group as u32,
                char_pr_id_ref: entry.char_pr_group as u32,
                next_style_id_ref,
                lang_id: 1042, // Korean
            });
        }

        // Step 6: Add user's styles from registry (starting after defaults).
        // User charPr/paraPr refs are offset-adjusted so they point at the
        // user shapes in the store (which start after the 7/20 defaults).
        let style_offset = defaults.len();
        for (i, (name, entry)) in registry.style_entries.iter().enumerate() {
            store.push_style(HwpxStyle {
                id: (style_offset + i) as u32,
                style_type: "PARA".to_string(),
                name: name.clone(),
                eng_name: name.clone(),
                para_pr_id_ref: (entry.para_shape_id.get() + para_shape_offset) as u32,
                char_pr_id_ref: (entry.char_shape_id.get() + char_shape_offset) as u32,
                next_style_id_ref: 0,
                lang_id: 1042, // Korean
            });
        }

        store
    }

    // ── Fonts ────────────────────────────────────────────────────

    /// Adds a font and returns its index.
    pub fn push_font(&mut self, font: HwpxFont) -> FontIndex {
        let idx = FontIndex::new(self.fonts.len());
        self.fonts.push(font);
        idx
    }

    /// Returns the font at `index`.
    pub fn font(&self, index: FontIndex) -> HwpxResult<&HwpxFont> {
        self.fonts.get(index.get()).ok_or_else(|| HwpxError::IndexOutOfBounds {
            kind: "font",
            index: index.get() as u32,
            max: self.fonts.len() as u32,
        })
    }

    /// Returns the number of fonts.
    pub fn font_count(&self) -> usize {
        self.fonts.len()
    }

    // ── Character Shapes ─────────────────────────────────────────

    /// Adds a char shape and returns its index.
    pub fn push_char_shape(&mut self, shape: HwpxCharShape) -> CharShapeIndex {
        let idx = CharShapeIndex::new(self.char_shapes.len());
        self.char_shapes.push(shape);
        idx
    }

    /// Returns the char shape at `index`.
    pub fn char_shape(&self, index: CharShapeIndex) -> HwpxResult<&HwpxCharShape> {
        self.char_shapes.get(index.get()).ok_or_else(|| HwpxError::IndexOutOfBounds {
            kind: "char_shape",
            index: index.get() as u32,
            max: self.char_shapes.len() as u32,
        })
    }

    /// Returns the number of char shapes.
    pub fn char_shape_count(&self) -> usize {
        self.char_shapes.len()
    }

    // ── Paragraph Shapes ─────────────────────────────────────────

    /// Adds a para shape and returns its index.
    pub fn push_para_shape(&mut self, shape: HwpxParaShape) -> ParaShapeIndex {
        let idx = ParaShapeIndex::new(self.para_shapes.len());
        self.para_shapes.push(shape);
        idx
    }

    /// Returns the para shape at `index`.
    pub fn para_shape(&self, index: ParaShapeIndex) -> HwpxResult<&HwpxParaShape> {
        self.para_shapes.get(index.get()).ok_or_else(|| HwpxError::IndexOutOfBounds {
            kind: "para_shape",
            index: index.get() as u32,
            max: self.para_shapes.len() as u32,
        })
    }

    /// Returns the number of para shapes.
    pub fn para_shape_count(&self) -> usize {
        self.para_shapes.len()
    }

    // ── Iterators ────────────────────────────────────────────────

    /// Returns an iterator over all fonts in the store.
    pub fn iter_fonts(&self) -> impl Iterator<Item = &HwpxFont> {
        self.fonts.iter()
    }

    /// Returns an iterator over all character shapes in the store.
    pub fn iter_char_shapes(&self) -> impl Iterator<Item = &HwpxCharShape> {
        self.char_shapes.iter()
    }

    /// Returns an iterator over all paragraph shapes in the store.
    pub fn iter_para_shapes(&self) -> impl Iterator<Item = &HwpxParaShape> {
        self.para_shapes.iter()
    }

    // ── Styles ───────────────────────────────────────────────────

    /// Adds a style definition.
    pub fn push_style(&mut self, style: HwpxStyle) {
        self.styles.push(style);
    }

    /// Returns the style at `index`.
    pub fn style(&self, index: usize) -> HwpxResult<&HwpxStyle> {
        self.styles.get(index).ok_or(HwpxError::IndexOutOfBounds {
            kind: "style",
            index: index as u32,
            max: self.styles.len() as u32,
        })
    }

    /// Returns the number of styles.
    pub fn style_count(&self) -> usize {
        self.styles.len()
    }

    /// Returns an iterator over all styles in the store.
    pub fn iter_styles(&self) -> impl Iterator<Item = &HwpxStyle> {
        self.styles.iter()
    }

    // ── Border Fills ─────────────────────────────────────────────

    /// Adds a border fill to the store and returns its 1-based ID.
    ///
    /// Border fill IDs in HWPX are 1-based (unlike other indices which are 0-based).
    pub fn push_border_fill(&mut self, bf: HwpxBorderFill) -> u32 {
        let id = bf.id;
        self.border_fills.push(bf);
        id
    }

    /// Returns the border fill with the given 1-based ID.
    ///
    /// # Errors
    ///
    /// Returns [`HwpxError::IndexOutOfBounds`] if no border fill with that ID exists.
    pub fn border_fill(&self, id: u32) -> HwpxResult<&HwpxBorderFill> {
        self.border_fills.iter().find(|bf| bf.id == id).ok_or(HwpxError::IndexOutOfBounds {
            kind: "border_fill",
            index: id,
            max: self.border_fills.len() as u32,
        })
    }

    /// Returns the number of border fills in the store.
    pub fn border_fill_count(&self) -> usize {
        self.border_fills.len()
    }

    /// Returns an iterator over all border fills in the store.
    pub fn iter_border_fills(&self) -> impl Iterator<Item = &HwpxBorderFill> {
        self.border_fills.iter()
    }

    /// Adds a numbering definition to the store.
    pub fn push_numbering(&mut self, ndef: NumberingDef) {
        self.numberings.push(ndef);
    }

    /// Adds a tab property definition to the store.
    pub fn push_tab(&mut self, tab: TabDef) {
        self.tabs.push(tab);
    }

    /// Returns the number of numbering definitions in the store.
    pub fn numbering_count(&self) -> u32 {
        self.numberings.len() as u32
    }

    /// Returns the number of tab property definitions in the store.
    pub fn tab_count(&self) -> u32 {
        self.tabs.len() as u32
    }

    /// Returns an iterator over all numbering definitions in the store.
    pub fn iter_numberings(&self) -> impl Iterator<Item = &NumberingDef> {
        self.numberings.iter()
    }

    /// Returns an iterator over all tab property definitions in the store.
    pub fn iter_tabs(&self) -> impl Iterator<Item = &TabDef> {
        self.tabs.iter()
    }
}

// ── Thread safety assertions ─────────────────────────────────────

#[allow(dead_code)]
const _: () = {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}
    fn assertions() {
        assert_send::<HwpxStyleStore>();
        assert_sync::<HwpxStyleStore>();
    }
};

// ── Color parsing helper ─────────────────────────────────────────

/// Parses a HWPX hex color string (`"#RRGGBB"`) into a [`Color`].
///
/// Returns `Color::BLACK` for `"none"`, empty strings, or invalid formats.
/// This is intentionally lenient: real-world HWPX files sometimes contain
/// non-standard color values, and rejecting them would make the decoder
/// unusable for slightly malformed documents.
pub(crate) fn parse_hex_color(s: &str) -> Color {
    let s = s.trim();
    if s.is_empty() || s.eq_ignore_ascii_case("none") {
        return Color::BLACK;
    }
    let hex = s.strip_prefix('#').unwrap_or(s);
    if hex.len() != 6 {
        return Color::BLACK;
    }
    let Ok(rgb) = u32::from_str_radix(hex, 16) else {
        return Color::BLACK;
    };
    let r = ((rgb >> 16) & 0xFF) as u8;
    let g = ((rgb >> 8) & 0xFF) as u8;
    let b = (rgb & 0xFF) as u8;
    Color::from_rgb(r, g, b)
}

/// Parses a HWPX alignment string into an [`Alignment`].
///
/// Defaults to `Alignment::Left` for unknown values.
pub(crate) fn parse_alignment(s: &str) -> Alignment {
    if s.eq_ignore_ascii_case("LEFT") {
        Alignment::Left
    } else if s.eq_ignore_ascii_case("BOTH") || s.eq_ignore_ascii_case("JUSTIFY") {
        Alignment::Justify
    } else if s.eq_ignore_ascii_case("CENTER") {
        Alignment::Center
    } else if s.eq_ignore_ascii_case("RIGHT") {
        Alignment::Right
    } else if s.eq_ignore_ascii_case("DISTRIBUTE") {
        Alignment::Distribute
    } else if s.eq_ignore_ascii_case("DISTRIBUTE_FLUSH") {
        Alignment::DistributeFlush
    } else {
        Alignment::Left
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hwpforge_blueprint::builtins::builtin_default;
    use hwpforge_foundation::{CharShapeIndex, FontIndex, ParaShapeIndex};

    // ── HwpxStyleStore basic operations ──────────────────────────

    #[test]
    fn empty_store_returns_errors() {
        let store = HwpxStyleStore::new();
        assert!(store.font(FontIndex::new(0)).is_err());
        assert!(store.char_shape(CharShapeIndex::new(0)).is_err());
        assert!(store.para_shape(ParaShapeIndex::new(0)).is_err());
    }

    #[test]
    fn push_and_get_font() {
        let mut store = HwpxStyleStore::new();
        let idx = store.push_font(HwpxFont {
            id: 0,
            face_name: "함초롬돋움".into(),
            lang: "HANGUL".into(),
        });
        assert_eq!(idx.get(), 0);
        let font = store.font(idx).unwrap();
        assert_eq!(font.face_name, "함초롬돋움");
        assert_eq!(font.lang, "HANGUL");
    }

    #[test]
    fn push_and_get_char_shape() {
        let mut store = HwpxStyleStore::new();
        let shape = HwpxCharShape {
            height: HwpUnit::new(1000).unwrap(),
            text_color: Color::from_rgb(255, 0, 0),
            bold: true,
            ..Default::default()
        };
        let idx = store.push_char_shape(shape);
        let cs = store.char_shape(idx).unwrap();
        assert_eq!(cs.height.as_i32(), 1000);
        assert_eq!(cs.text_color.red(), 255);
        assert!(cs.bold);
        assert!(!cs.italic);
    }

    #[test]
    fn push_and_get_para_shape() {
        let mut store = HwpxStyleStore::new();
        let shape =
            HwpxParaShape { alignment: Alignment::Center, line_spacing: 200, ..Default::default() };
        let idx = store.push_para_shape(shape);
        let ps = store.para_shape(idx).unwrap();
        assert_eq!(ps.alignment, Alignment::Center);
        assert_eq!(ps.line_spacing, 200);
    }

    #[test]
    fn index_out_of_bounds_error() {
        let store = HwpxStyleStore::new();
        let err = store.char_shape(CharShapeIndex::new(42)).unwrap_err();
        match err {
            HwpxError::IndexOutOfBounds { kind, index, max } => {
                assert_eq!(kind, "char_shape");
                assert_eq!(index, 42);
                assert_eq!(max, 0);
            }
            _ => panic!("expected IndexOutOfBounds"),
        }
    }

    #[test]
    fn multiple_items_sequential_indices() {
        let mut store = HwpxStyleStore::new();
        for i in 0..5 {
            let idx = store.push_font(HwpxFont {
                id: i,
                face_name: format!("Font{i}"),
                lang: "LATIN".into(),
            });
            assert_eq!(idx.get(), i as usize);
        }
        assert_eq!(store.font_count(), 5);
        assert_eq!(store.font(FontIndex::new(3)).unwrap().face_name, "Font3");
    }

    #[test]
    fn count_methods() {
        let mut store = HwpxStyleStore::new();
        assert_eq!(store.font_count(), 0);
        assert_eq!(store.char_shape_count(), 0);
        assert_eq!(store.para_shape_count(), 0);

        store.push_font(HwpxFont { id: 0, face_name: "A".into(), lang: "LATIN".into() });
        store.push_char_shape(HwpxCharShape::default());
        store.push_char_shape(HwpxCharShape::default());
        store.push_para_shape(HwpxParaShape::default());

        assert_eq!(store.font_count(), 1);
        assert_eq!(store.char_shape_count(), 2);
        assert_eq!(store.para_shape_count(), 1);
    }

    // ── Iterator methods ───────────────────────────────────────────

    #[test]
    fn iter_fonts_yields_all() {
        let mut store = HwpxStyleStore::new();
        for i in 0..3 {
            store.push_font(HwpxFont {
                id: i,
                face_name: format!("Font{i}"),
                lang: "LATIN".into(),
            });
        }
        let names: Vec<&str> = store.iter_fonts().map(|f| f.face_name.as_str()).collect();
        assert_eq!(names, vec!["Font0", "Font1", "Font2"]);
    }

    #[test]
    fn iter_char_shapes_yields_all() {
        let mut store = HwpxStyleStore::new();
        store.push_char_shape(HwpxCharShape { bold: true, ..Default::default() });
        store.push_char_shape(HwpxCharShape { italic: true, ..Default::default() });
        let styles: Vec<(bool, bool)> =
            store.iter_char_shapes().map(|c| (c.bold, c.italic)).collect();
        assert_eq!(styles, vec![(true, false), (false, true)]);
    }

    #[test]
    fn iter_para_shapes_yields_all() {
        let mut store = HwpxStyleStore::new();
        store.push_para_shape(HwpxParaShape { line_spacing: 130, ..Default::default() });
        store.push_para_shape(HwpxParaShape { line_spacing: 200, ..Default::default() });
        let spacings: Vec<i32> = store.iter_para_shapes().map(|p| p.line_spacing).collect();
        assert_eq!(spacings, vec![130, 200]);
    }

    #[test]
    fn iter_empty_store() {
        let store = HwpxStyleStore::new();
        assert_eq!(store.iter_fonts().count(), 0);
        assert_eq!(store.iter_char_shapes().count(), 0);
        assert_eq!(store.iter_para_shapes().count(), 0);
    }

    // ── HwpxFontRef default ──────────────────────────────────────

    #[test]
    fn font_ref_default_all_zero() {
        let r = HwpxFontRef::default();
        assert_eq!(r.hangul.get(), 0);
        assert_eq!(r.latin.get(), 0);
        assert_eq!(r.hanja.get(), 0);
        assert_eq!(r.japanese.get(), 0);
        assert_eq!(r.other.get(), 0);
        assert_eq!(r.symbol.get(), 0);
        assert_eq!(r.user.get(), 0);
    }

    // ── HwpxCharShape default ────────────────────────────────────

    #[test]
    fn char_shape_default_values() {
        let cs = HwpxCharShape::default();
        assert_eq!(cs.height, HwpUnit::new(1000).unwrap()); // 10pt default
        assert_eq!(cs.text_color, Color::BLACK);
        assert_eq!(cs.shade_color, None);
        assert!(!cs.bold);
        assert!(!cs.italic);
        assert_eq!(cs.underline_type, UnderlineType::None);
        assert_eq!(cs.underline_color, None);
        assert_eq!(cs.strikeout_shape, StrikeoutShape::None);
        assert_eq!(cs.strikeout_color, None);
    }

    // ── HwpxParaShape default ────────────────────────────────────

    #[test]
    fn para_shape_default_values() {
        let ps = HwpxParaShape::default();
        assert_eq!(ps.alignment, Alignment::Left);
        assert_eq!(ps.margin_left, HwpUnit::ZERO);
        assert_eq!(ps.indent, HwpUnit::ZERO);
        assert_eq!(ps.line_spacing, 160);
        assert_eq!(ps.line_spacing_type, LineSpacingType::Percentage);
    }

    // ── parse_hex_color ──────────────────────────────────────────

    #[test]
    fn parse_hex_color_valid() {
        let c = parse_hex_color("#FF0000");
        assert_eq!(c.red(), 255);
        assert_eq!(c.green(), 0);
        assert_eq!(c.blue(), 0);
    }

    #[test]
    fn parse_hex_color_lowercase() {
        let c = parse_hex_color("#00ff00");
        assert_eq!(c.green(), 255);
    }

    #[test]
    fn parse_hex_color_no_hash() {
        let c = parse_hex_color("0000FF");
        assert_eq!(c.blue(), 255);
    }

    #[test]
    fn parse_hex_color_none_returns_black() {
        assert_eq!(parse_hex_color("none"), Color::BLACK);
        assert_eq!(parse_hex_color("NONE"), Color::BLACK);
    }

    #[test]
    fn parse_hex_color_empty_returns_black() {
        assert_eq!(parse_hex_color(""), Color::BLACK);
    }

    #[test]
    fn parse_hex_color_invalid_returns_black() {
        assert_eq!(parse_hex_color("#GGHHII"), Color::BLACK);
        assert_eq!(parse_hex_color("#FFF"), Color::BLACK); // too short
        assert_eq!(parse_hex_color("garbage"), Color::BLACK);
    }

    #[test]
    fn parse_hex_color_white() {
        let c = parse_hex_color("#FFFFFF");
        assert_eq!(c, Color::WHITE);
    }

    // ── parse_alignment ──────────────────────────────────────────

    #[test]
    fn parse_alignment_standard() {
        assert_eq!(parse_alignment("LEFT"), Alignment::Left);
        assert_eq!(parse_alignment("CENTER"), Alignment::Center);
        assert_eq!(parse_alignment("RIGHT"), Alignment::Right);
        assert_eq!(parse_alignment("JUSTIFY"), Alignment::Justify);
    }

    #[test]
    fn parse_alignment_both_maps_to_justify() {
        // HWPX: "BOTH" means 양쪽 맞춤 (Justify), not Left
        assert_eq!(parse_alignment("BOTH"), Alignment::Justify);
    }

    #[test]
    fn parse_alignment_case_insensitive() {
        assert_eq!(parse_alignment("center"), Alignment::Center);
        assert_eq!(parse_alignment("Right"), Alignment::Right);
    }

    #[test]
    fn parse_alignment_distribute() {
        assert_eq!(parse_alignment("DISTRIBUTE"), Alignment::Distribute);
        assert_eq!(parse_alignment("distribute"), Alignment::Distribute);
        assert_eq!(parse_alignment("DISTRIBUTE_FLUSH"), Alignment::DistributeFlush);
        assert_eq!(parse_alignment("distribute_flush"), Alignment::DistributeFlush);
    }

    #[test]
    fn parse_alignment_unknown_defaults_left() {
        assert_eq!(parse_alignment("DISTRIBUTED"), Alignment::Left);
        assert_eq!(parse_alignment(""), Alignment::Left);
    }

    // ── HwpxStyle operations ────────────────────────────────────

    #[test]
    fn push_and_get_style() {
        let mut store = HwpxStyleStore::new();
        let style = HwpxStyle {
            id: 0,
            style_type: "PARA".into(),
            name: "바탕글".into(),
            eng_name: "Normal".into(),
            para_pr_id_ref: 0,
            char_pr_id_ref: 0,
            next_style_id_ref: 0,
            lang_id: 1042,
        };
        store.push_style(style);
        assert_eq!(store.style_count(), 1);
        let s = store.style(0).unwrap();
        assert_eq!(s.name, "바탕글");
        assert_eq!(s.eng_name, "Normal");
        assert_eq!(s.style_type, "PARA");
    }

    #[test]
    fn style_index_out_of_bounds() {
        let store = HwpxStyleStore::new();
        let err = store.style(0).unwrap_err();
        match err {
            HwpxError::IndexOutOfBounds { kind, index, max } => {
                assert_eq!(kind, "style");
                assert_eq!(index, 0);
                assert_eq!(max, 0);
            }
            _ => panic!("expected IndexOutOfBounds"),
        }
    }

    #[test]
    fn iter_styles_yields_all() {
        let mut store = HwpxStyleStore::new();
        store.push_style(HwpxStyle {
            id: 0,
            style_type: "PARA".into(),
            name: "바탕글".into(),
            eng_name: "Normal".into(),
            para_pr_id_ref: 0,
            char_pr_id_ref: 0,
            next_style_id_ref: 0,
            lang_id: 1042,
        });
        store.push_style(HwpxStyle {
            id: 1,
            style_type: "CHAR".into(),
            name: "본문".into(),
            eng_name: "Body".into(),
            para_pr_id_ref: 1,
            char_pr_id_ref: 1,
            next_style_id_ref: 1,
            lang_id: 1042,
        });
        let names: Vec<&str> = store.iter_styles().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["바탕글", "본문"]);
    }

    // ── from_registry bridge tests ──────────────────────────────

    #[test]
    fn from_registry_empty_produces_empty_store() {
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry(&registry);

        // Empty registry injects 한글-compatible defaults:
        // 1 font × 7 language groups, 7 default charShapes, 20 default paraShapes,
        // 22 required styles (Modern default set)
        assert_eq!(store.font_count(), 7);
        assert_eq!(store.char_shape_count(), 7); // 7 default charPr groups
        assert_eq!(store.para_shape_count(), 20); // 20 default paraPr groups
        assert_eq!(store.style_count(), 22);
    }

    #[test]
    fn from_registry_preserves_counts() {
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);

        // Fonts are mirrored across 7 language groups (HANGUL, LATIN, HANJA, JAPANESE, OTHER, SYMBOL, USER)
        assert_eq!(store.font_count(), registry.font_count() * 7);
        // 7 default charShapes + user charShapes; 20 default paraShapes + user paraShapes
        assert_eq!(store.char_shape_count(), 7 + registry.char_shape_count());
        assert_eq!(store.para_shape_count(), 20 + registry.para_shape_count());
        // +22 for injected Modern default styles (the default HancomStyleSet)
        assert_eq!(store.style_count(), registry.style_count() + 22);
    }

    #[test]
    fn from_registry_font_face_names_match() {
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);

        let font_count = registry.font_count();
        let langs = ["HANGUL", "LATIN", "HANJA", "JAPANESE", "OTHER", "SYMBOL", "USER"];
        // Fonts are stored as: lang0[font0, font1, ...], lang1[font0, font1, ...], ...
        for (lang_idx, &lang) in langs.iter().enumerate() {
            for (font_idx, font_id) in registry.fonts.iter().enumerate() {
                let store_idx = lang_idx * font_count + font_idx;
                let hwpx_font = store.font(FontIndex::new(store_idx)).unwrap();
                assert_eq!(hwpx_font.face_name, font_id.as_str());
                assert_eq!(hwpx_font.lang, lang);
            }
        }
    }

    #[test]
    fn from_registry_char_shape_properties() {
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);

        // User charShapes start at index 7 (after 7 default charPr groups)
        for (i, bp_cs) in registry.char_shapes.iter().enumerate() {
            let hwpx_cs = store.char_shape(CharShapeIndex::new(7 + i)).unwrap();
            assert_eq!(hwpx_cs.height, bp_cs.size);
            assert_eq!(hwpx_cs.text_color, bp_cs.color);
            assert_eq!(hwpx_cs.shade_color, bp_cs.shade_color);
            assert_eq!(hwpx_cs.bold, bp_cs.bold);
            assert_eq!(hwpx_cs.italic, bp_cs.italic);
            assert_eq!(hwpx_cs.underline_type, bp_cs.underline_type);
            assert_eq!(hwpx_cs.underline_color, bp_cs.underline_color);
            assert_eq!(hwpx_cs.strikeout_shape, bp_cs.strikeout_shape);
            assert_eq!(hwpx_cs.strikeout_color, bp_cs.strikeout_color);
            assert_eq!(hwpx_cs.vertical_position, bp_cs.vertical_position);
            assert_eq!(hwpx_cs.outline_type, bp_cs.outline);
            assert_eq!(hwpx_cs.shadow_type, bp_cs.shadow);
            assert_eq!(hwpx_cs.emboss_type, bp_cs.emboss);
            assert_eq!(hwpx_cs.engrave_type, bp_cs.engrave);
        }
    }

    #[test]
    fn from_registry_para_shape_properties() {
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);

        // User paraShapes start at index 20 (after 20 default paraPr groups)
        for (i, bp_ps) in registry.para_shapes.iter().enumerate() {
            let hwpx_ps = store.para_shape(ParaShapeIndex::new(20 + i)).unwrap();
            assert_eq!(hwpx_ps.alignment, bp_ps.alignment);
            assert_eq!(hwpx_ps.margin_left, bp_ps.indent_left);
            assert_eq!(hwpx_ps.margin_right, bp_ps.indent_right);
            assert_eq!(hwpx_ps.indent, bp_ps.indent_first_line);
            assert_eq!(hwpx_ps.spacing_before, bp_ps.space_before);
            assert_eq!(hwpx_ps.spacing_after, bp_ps.space_after);
            assert_eq!(hwpx_ps.line_spacing, bp_ps.line_spacing_value.round() as i32);
        }
    }

    #[test]
    fn from_registry_style_entries_reference_valid_indices() {
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);

        for i in 0..store.style_count() {
            let style = store.style(i).unwrap();
            // Style type is either "PARA" or "CHAR" (default styles include both)
            assert!(
                style.style_type == "PARA" || style.style_type == "CHAR",
                "unexpected style_type '{}' for style '{}'",
                style.style_type,
                style.name
            );
            assert!(
                (style.char_pr_id_ref as usize) < store.char_shape_count(),
                "char_pr_id_ref {} out of bounds for style '{}'",
                style.char_pr_id_ref,
                style.name
            );
            assert!(
                (style.para_pr_id_ref as usize) < store.para_shape_count(),
                "para_pr_id_ref {} out of bounds for style '{}'",
                style.para_pr_id_ref,
                style.name
            );
        }
    }

    // ── HancomStyleSet count tests ──────────────────────────────

    #[test]
    fn default_style_set_classic_count() {
        assert_eq!(HancomStyleSet::Classic.count(), 18);
    }

    #[test]
    fn default_style_set_modern_count() {
        assert_eq!(HancomStyleSet::Modern.count(), 22);
    }

    #[test]
    fn default_style_set_latest_count() {
        assert_eq!(HancomStyleSet::Latest.count(), 23);
    }

    #[test]
    fn default_style_set_modern_is_default() {
        assert_eq!(HancomStyleSet::default(), HancomStyleSet::Modern);
    }

    // ── with_default_fonts ───────────────────────────────────────

    #[test]
    fn with_default_fonts_creates_seven_fonts() {
        let store = HwpxStyleStore::with_default_fonts("함초롬돋움");
        assert_eq!(store.font_count(), 7);
    }

    #[test]
    fn with_default_fonts_all_names_match() {
        let font_name = "나눔고딕";
        let store = HwpxStyleStore::with_default_fonts(font_name);
        for font in store.iter_fonts() {
            assert_eq!(font.face_name, font_name);
        }
    }

    #[test]
    fn with_default_fonts_lang_groups_correct() {
        let store = HwpxStyleStore::with_default_fonts("함초롬바탕");
        let langs: Vec<&str> = store.iter_fonts().map(|f| f.lang.as_str()).collect();
        assert_eq!(langs, vec!["HANGUL", "LATIN", "HANJA", "JAPANESE", "OTHER", "SYMBOL", "USER"]);
    }

    #[test]
    fn from_registry_with_classic_style_set() {
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry_with(&registry, HancomStyleSet::Classic);
        assert_eq!(store.style_set(), HancomStyleSet::Classic);
        // Classic injects exactly 18 default styles
        assert_eq!(store.style_count(), 18);
        // 쪽 번호 at Classic position (id=9)
        assert_eq!(store.style(9).unwrap().name, "쪽 번호");
    }

    #[test]
    fn modern_styles_match_golden_fixture() {
        // Verified from golden fixture tests/fixtures/textbox.hwpx (한글 2022+)
        let styles = HancomStyleSet::Modern.default_styles();
        // 개요 8-10 inserted at 9-11
        assert_eq!(styles[9].name, "개요 8");
        assert_eq!(styles[10].name, "개요 9");
        assert_eq!(styles[11].name, "개요 10");
        // 쪽 번호 shifted to 12
        assert_eq!(styles[12].name, "쪽 번호");
        assert_eq!(styles[12].style_type, "CHAR");
        // 캡션 at 21
        assert_eq!(styles[21].name, "캡션");
        assert_eq!(styles[21].style_type, "PARA");
    }

    // ── Border Fill tests ─────────────────────────────────────────

    #[test]
    fn default_border_fills_count() {
        use hwpforge_blueprint::{builtins::builtin_default, registry::StyleRegistry};
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        assert_eq!(store.border_fill_count(), 3, "from_registry produces exactly 3 default fills");
    }

    #[test]
    fn default_border_fill_page() {
        // id=1: page border — empty borders, no fill
        let bf = HwpxBorderFill::default_page_border();
        assert_eq!(bf.id, 1);
        assert!(!bf.three_d);
        assert!(!bf.shadow);
        assert_eq!(bf.center_line, "NONE");
        assert_eq!(bf.left.line_type, "NONE");
        assert_eq!(bf.right.line_type, "NONE");
        assert_eq!(bf.top.line_type, "NONE");
        assert_eq!(bf.bottom.line_type, "NONE");
        assert_eq!(bf.diagonal.line_type, "SOLID");
        assert!(bf.fill.is_none());
    }

    #[test]
    fn default_border_fill_char() {
        // id=2: char background — must have WinBrush fill
        let bf = HwpxBorderFill::default_char_background();
        assert_eq!(bf.id, 2);
        assert!(bf.fill.is_some(), "char background must have a fill brush");
        match bf.fill.as_ref().unwrap() {
            HwpxFill::WinBrush { face_color, hatch_color, alpha } => {
                assert_eq!(face_color, "none");
                assert_eq!(hatch_color, "#FF000000");
                assert_eq!(alpha, "0");
            }
        }
    }

    #[test]
    fn default_border_fill_table() {
        // id=3: table border — SOLID on all 4 sides, 0.12 mm
        let bf = HwpxBorderFill::default_table_border();
        assert_eq!(bf.id, 3);
        assert_eq!(bf.left.line_type, "SOLID");
        assert_eq!(bf.left.width, "0.12 mm");
        assert_eq!(bf.right.line_type, "SOLID");
        assert_eq!(bf.top.line_type, "SOLID");
        assert_eq!(bf.bottom.line_type, "SOLID");
        assert_eq!(bf.diagonal.line_type, "SOLID");
        assert_eq!(bf.diagonal.width, "0.1 mm");
        assert!(bf.fill.is_none());
    }

    #[test]
    fn push_user_border_fill() {
        let mut store = HwpxStyleStore::new();
        let bf = HwpxBorderFill {
            id: 4,
            three_d: false,
            shadow: false,
            center_line: "NONE".into(),
            left: HwpxBorderLine {
                line_type: "DASH".into(),
                width: "0.2 mm".into(),
                color: "#FF0000".into(),
            },
            right: HwpxBorderLine::default(),
            top: HwpxBorderLine::default(),
            bottom: HwpxBorderLine::default(),
            diagonal: HwpxBorderLine::default(),
            slash_type: "NONE".into(),
            back_slash_type: "NONE".into(),
            fill: None,
        };
        let returned_id = store.push_border_fill(bf);
        assert_eq!(returned_id, 4);
        assert_eq!(store.border_fill_count(), 1);
        let fetched = store.border_fill(4).unwrap();
        assert_eq!(fetched.left.line_type, "DASH");
        assert_eq!(fetched.left.width, "0.2 mm");
    }

    #[test]
    fn border_fill_not_found_returns_error() {
        let store = HwpxStyleStore::new();
        assert!(store.border_fill(1).is_err());
    }

    #[test]
    fn from_registry_border_fills_have_correct_ids() {
        use hwpforge_blueprint::{builtins::builtin_default, registry::StyleRegistry};
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        // IDs are 1-based
        assert_eq!(store.border_fill(1).unwrap().id, 1);
        assert_eq!(store.border_fill(2).unwrap().id, 2);
        assert_eq!(store.border_fill(3).unwrap().id, 3);
    }

    // ── 7.3 per-style shape injection tests ──────────────────────

    #[test]
    fn from_registry_injects_7_default_char_shapes() {
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        assert_eq!(store.char_shape_count(), 7, "must have exactly 7 default charPr groups");
    }

    #[test]
    fn from_registry_injects_20_default_para_shapes() {
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        assert_eq!(store.para_shape_count(), 20, "must have exactly 20 default paraPr groups");
    }

    #[test]
    fn default_char_shape_0_is_batang_10pt_black() {
        // charPr 0 = 함초롬바탕 10pt #000000 (바탕글/본문/개요1-7/캡션)
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        let cs = store.char_shape(CharShapeIndex::new(0)).unwrap();
        assert_eq!(cs.height.as_i32(), 1000); // 10pt
        assert_eq!(cs.text_color, Color::BLACK);
        assert!(!cs.bold);
        assert!(!cs.italic);
    }

    #[test]
    fn default_char_shape_5_is_toc_heading() {
        // charPr 5 = 함초롬돋움 16pt #2E74B5 (차례 제목)
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        let cs = store.char_shape(CharShapeIndex::new(5)).unwrap();
        assert_eq!(cs.height.as_i32(), 1600); // 16pt
        assert_eq!(cs.text_color, Color::from_rgb(0x2E, 0x74, 0xB5));
    }

    #[test]
    fn from_registry_user_shapes_offset() {
        // User charShapes must start at index 7, user paraShapes at index 20
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        // First user charShape is at index 7
        assert!(store.char_shape(CharShapeIndex::new(7)).is_ok());
        // First user paraShape is at index 20
        assert!(store.para_shape(ParaShapeIndex::new(20)).is_ok());
    }

    #[test]
    fn from_registry_default_style_refs_match_groups() {
        // Default styles must reference the correct charPr/paraPr group indices
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        let defaults = HancomStyleSet::Modern.default_styles();
        for (idx, entry) in defaults.iter().enumerate() {
            let style = store.style(idx).unwrap();
            assert_eq!(
                style.char_pr_id_ref, entry.char_pr_group as u32,
                "charPr ref mismatch for style '{}'",
                entry.name
            );
            assert_eq!(
                style.para_pr_id_ref, entry.para_pr_group as u32,
                "paraPr ref mismatch for style '{}'",
                entry.name
            );
        }
    }

    #[test]
    fn from_registry_user_style_refs_are_offset_adjusted() {
        // User styles' charPr/paraPr refs must be offset by 7/20
        let template = builtin_default().unwrap();
        let registry = StyleRegistry::from_template(&template).unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        let defaults_len = HancomStyleSet::Modern.count();
        for (i, (_, entry)) in registry.style_entries.iter().enumerate() {
            let style = store.style(defaults_len + i).unwrap();
            assert_eq!(
                style.char_pr_id_ref,
                (entry.char_shape_id.get() + 7) as u32,
                "user charPr ref not offset-adjusted for style index {i}"
            );
            assert_eq!(
                style.para_pr_id_ref,
                (entry.para_shape_id.get() + 20) as u32,
                "user paraPr ref not offset-adjusted for style index {i}"
            );
        }
    }

    #[test]
    fn default_para_shape_0_is_batanggeul() {
        // paraPr 0 = JUSTIFY, left=0, 160% line spacing (바탕글)
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        let ps = store.para_shape(ParaShapeIndex::new(0)).unwrap();
        assert_eq!(ps.alignment, Alignment::Justify);
        assert_eq!(ps.margin_left.as_i32(), 0);
        assert_eq!(ps.line_spacing, 160);
    }

    #[test]
    fn default_para_shape_2_is_outline1() {
        // paraPr 2 = JUSTIFY, left=1000 (개요 1 with OUTLINE heading)
        let registry: StyleRegistry = serde_json::from_str(
            r#"{"fonts":[],"char_shapes":[],"para_shapes":[],"style_entries":{}}"#,
        )
        .unwrap();
        let store = HwpxStyleStore::from_registry(&registry);
        let ps = store.para_shape(ParaShapeIndex::new(2)).unwrap();
        assert_eq!(ps.alignment, Alignment::Justify);
        assert_eq!(ps.margin_left.as_i32(), 1000);
        assert_eq!(ps.line_spacing, 160);
    }
}