rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
//! WASM ↔ JavaScript 공개 API
//!
//! wasm-bindgen을 통해 JavaScript에서 호출 가능한 API를 정의한다.
//! 주요 API:
//! - `HwpDocument::new(data)` - HWP 파일 로드
//! - `HwpDocument::page_count()` - 페이지 수 조회
//! - `HwpDocument::render_page_svg(page_num)` - SVG로 렌더링
//! - `HwpDocument::render_page_html(page_num)` - HTML로 렌더링

// 하위 호환성: tests.rs에서 super::json_escape 등으로 접근 가능하도록 재내보내기
pub(crate) use crate::document_core::helpers::*;

use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
use web_sys::HtmlCanvasElement;

use crate::document_core::helpers::parse_removed_para_meta;
use crate::document_core::{
    DeferredPaginationJobState, DeferredPaginationStepResult, DocumentCore, DEFAULT_FALLBACK_FONT,
};
use crate::error::HwpError;
use crate::model::control::Control;
use crate::model::document::{Document, Section};
use crate::model::page::ColumnDef;
use crate::model::paragraph::Paragraph;
use crate::model::path::{path_from_flat, DocumentPath, PathSegment};
use crate::model::shape::ShapeObject;
use crate::renderer::canvas::CanvasRenderer;
use crate::renderer::composer::{
    compose_paragraph, compose_section, reflow_line_segs, restamp_indentation, ComposedParagraph,
};
use crate::renderer::height_measurer::{HeightMeasurer, MeasuredSection, MeasuredTable};
use crate::renderer::html::HtmlRenderer;
use crate::renderer::layout::LayoutEngine;
use crate::renderer::page_layout::PageLayoutInfo;
use crate::renderer::pagination::{PaginationResult, Paginator};
use crate::renderer::render_tree::PageRenderTree;
use crate::renderer::scheduler::{RenderEvent, RenderObserver, RenderScheduler, Viewport};
use crate::renderer::style_resolver::{
    resolve_font_substitution, resolve_styles, ResolvedStyleSet,
};
use crate::renderer::svg::SvgRenderer;
use crate::renderer::DEFAULT_DPI;

#[cfg(target_arch = "wasm32")]
mod bitmap_raster;
mod canvas_metrics;
mod footnote_shape;
mod form_action;
mod host_font_environment;
mod hyperlink;
mod layout_generation;
#[cfg(all(feature = "pdf-import", target_arch = "wasm32"))]
mod pdf_import;
#[cfg(all(feature = "pdf-import", target_arch = "wasm32"))]
mod pdf_request;
#[cfg(target_arch = "wasm32")]
mod print_image_sampling;
/// 어떤 렌더 export가 교체 가능한 경계 뒤에 있는지 선언하는 곳 (#4577, #4642).
mod render_patch_boundary;
#[cfg(target_arch = "wasm32")]
mod static_svg_raster;
mod table_cell_bboxes;
mod template_automation;

#[cfg(target_arch = "wasm32")]
mod layer_export;

// Preserve the Native facade's existing slice signature while passing a JS
// reference on WASM. No Native dependency on target-specific js-sys is added.
#[cfg(target_arch = "wasm32")]
type PdfImportInput = JsValue;
#[cfg(not(target_arch = "wasm32"))]
type PdfImportInput = [u8];

impl From<HwpError> for JsValue {
    fn from(err: HwpError) -> Self {
        JsValue::from_str(&err.to_string())
    }
}

/// WASM 경계의 u32 행 인덱스를 u16 으로 변환한다. 묵시적 `as u16` 절단은
/// 65537 을 1 로 바꿔 요청 밖 행에서 표를 조작하게 되므로 명시적으로 거부한다.
fn row_index_from_u32(v: u32) -> Result<u16, HwpError> {
    u16::try_from(v)
        .map_err(|_| HwpError::RenderError(format!("행 인덱스 {} 가 최대치(65535)를 넘습니다", v)))
}

fn deferred_pagination_result_json(result: DeferredPaginationStepResult) -> String {
    let status = match result.state {
        DeferredPaginationJobState::None => "none",
        DeferredPaginationJobState::Pending => "pending",
        DeferredPaginationJobState::Complete => "complete",
        DeferredPaginationJobState::Fallback => "fallback",
        DeferredPaginationJobState::Stale => "stale",
    };
    serde_json::json!({
        "ok": true,
        "status": status,
        "revision": result.revision,
        "fragmentsProcessed": result.fragments_processed,
        "pageCount": result.page_count,
    })
    .to_string()
}

/// 셀 경로 덧말·글자 겹침 API의 문단 주소.
fn compose_cell(
    sec: u32,
    parent_para: u32,
    path: &[(usize, usize, usize)],
) -> crate::document_core::ComposeHost<'_> {
    crate::document_core::ComposeHost::Cell {
        sec: sec as usize,
        parent_para: parent_para as usize,
        path,
    }
}

/// 각주·미주 덧말·글자 겹침 API의 문단 주소.
fn compose_note(
    sec: u32,
    para: u32,
    control: u32,
    note_para: u32,
) -> crate::document_core::ComposeHost<'static> {
    crate::document_core::ComposeHost::Note {
        sec: sec as usize,
        para: para as usize,
        control: control as usize,
        note_para: note_para as usize,
    }
}

/// [Task #1161] 클립보드 API 의 cellPath JSON 인자 파싱.
/// 빈 문자열 또는 `"[]"` 면 본문(빈 경로), 그 외에는
/// `[{"controlIndex","cellIndex","cellParaIndex"}, ...]` 를 파싱한다.
fn parse_cell_path_arg(cell_path_json: &str) -> Result<Vec<(usize, usize, usize)>, JsValue> {
    if cell_path_json.is_empty() || cell_path_json == "[]" {
        Ok(Vec::new())
    } else {
        DocumentCore::parse_cell_path(cell_path_json).map_err(JsValue::from)
    }
}

#[cfg(any(target_arch = "wasm32", test))]
const MAX_CANVAS_DIMENSION: f64 = 16_384.0;

#[cfg(any(target_arch = "wasm32", test))]
fn normalize_canvas_scale(
    page_width: f64,
    page_height: f64,
    requested_scale: f64,
) -> Result<f64, &'static str> {
    if !page_width.is_finite()
        || !page_height.is_finite()
        || page_width <= 0.0
        || page_height <= 0.0
    {
        return Err("invalid page dimensions");
    }

    let scale = if requested_scale <= 0.0 || !requested_scale.is_finite() {
        1.0
    } else {
        requested_scale.clamp(0.25, 12.0)
    };

    let scaled_width = page_width * scale;
    let scaled_height = page_height * scale;
    if !scaled_width.is_finite() || !scaled_height.is_finite() {
        return Ok((MAX_CANVAS_DIMENSION / page_width)
            .min(MAX_CANVAS_DIMENSION / page_height)
            .min(scale));
    }

    if scaled_width > MAX_CANVAS_DIMENSION || scaled_height > MAX_CANVAS_DIMENSION {
        Ok((MAX_CANVAS_DIMENSION / page_width)
            .min(MAX_CANVAS_DIMENSION / page_height)
            .min(scale))
    } else {
        Ok(scale)
    }
}

#[cfg(any(target_arch = "wasm32", test))]
fn scaled_canvas_extent(page_extent: f64, scale: f64) -> u32 {
    // Canvas의 bitmap 크기는 정수여야 한다. 절사하면 A4 같은 분수 CSS px 페이지를
    // 고배율로 그릴 때 우·하단 한 줄이 잘린다. 실제 콘텐츠의 scale은 그대로 두고
    // bitmap 경계만 올림해 페이지 전체를 담는다.
    (page_extent * scale)
        .ceil()
        .clamp(1.0, MAX_CANVAS_DIMENSION) as u32
}

#[cfg(target_arch = "wasm32")]
fn canvas_layer_filter(
    layer_kind: &str,
) -> Result<crate::renderer::web_canvas::LayerFilter, JsValue> {
    use crate::model::shape::TextWrap;
    use crate::renderer::web_canvas::LayerFilter;

    match layer_kind {
        "all" => Ok(LayerFilter::All),
        "background" => Ok(LayerFilter::BackgroundOnly),
        "flow" => Ok(LayerFilter::FlowOnly),
        "flow-dynamic" => Ok(LayerFilter::FlowDynamic),
        "flow-static" => Ok(LayerFilter::FlowStatic),
        "behind" => Ok(LayerFilter::WrapOnly(TextWrap::BehindText)),
        "front" => Ok(LayerFilter::WrapOnly(TextWrap::InFrontOfText)),
        _ => Err(JsValue::from_str(
            "invalid layer_kind: 'all' | 'background' | 'flow' | 'flow-dynamic' | 'flow-static' | 'behind' | 'front'",
        )),
    }
}

#[cfg(target_arch = "wasm32")]
fn render_page_to_canvas_filtered_with_profile_impl(
    document: &HwpDocument,
    page_num: u32,
    canvas: &HtmlCanvasElement,
    scale: f64,
    layer_kind: &str,
    profile: &str,
) -> Result<(), JsValue> {
    use crate::paint::RenderProfile;
    use crate::renderer::layer_renderer::LayerRenderer;
    use crate::renderer::web_canvas::WebCanvasRenderer;

    let filter = canvas_layer_filter(layer_kind)?;

    let profile = RenderProfile::parse(profile)
        .ok_or_else(|| JsValue::from_str(&format!("unsupported render profile: {profile}")))?;
    // 레이어 트리의 회색 판정이 디코드한 픽셀을 이 쪽의 캔버스 그리기에 넘긴다.
    crate::renderer::image_resolver::with_decoded_handoff(|| {
        let tree = document
            .build_canvas_page_layer_tree_with_profile(page_num, profile)
            .map_err(JsValue::from)?;

        let scale = normalize_canvas_scale(tree.page_width, tree.page_height, scale)
            .map_err(JsValue::from_str)?;

        canvas.set_width(scaled_canvas_extent(tree.page_width, scale));
        canvas.set_height(scaled_canvas_extent(tree.page_height, scale));

        let mut renderer = WebCanvasRenderer::new(canvas)?;
        renderer.set_hft_outline_fonts(&document.hft_outline_fonts);
        renderer.show_paragraph_marks = document.show_paragraph_marks;
        renderer.show_control_codes = document.show_control_codes;
        renderer.set_scale(scale);
        renderer.set_layer_filter(filter);
        renderer.render_page(&tree).map_err(JsValue::from)?;
        Ok(())
    })
}

/// 부분 재도색 본체.
///
/// `patch` 는 page-space 요청 사각형이다 — `x/y/width/height` 를 편 인자로 받으면 이 함수의
/// 인자가 10개가 되어 `subsecond::HotFn` 이 붙지 못한다(`HotFunction` 은 9개까지). 경계를
/// 유지하려면 사각형을 한 값으로 접어야 한다.
#[cfg(target_arch = "wasm32")]
fn render_page_patch_to_canvas_filtered_with_profile_impl(
    document: &HwpDocument,
    page_num: u32,
    canvas: &HtmlCanvasElement,
    scale: f64,
    layer_kind: &str,
    profile: &str,
    patch: crate::renderer::render_tree::BoundingBox,
) -> Result<(), JsValue> {
    use crate::paint::RenderProfile;
    use crate::renderer::layer_renderer::LayerRenderer;
    use crate::renderer::render_tree::BoundingBox;
    use crate::renderer::web_canvas::WebCanvasRenderer;

    if ![patch.x, patch.y, patch.width, patch.height]
        .into_iter()
        .all(f64::is_finite)
        || patch.width <= 0.0
        || patch.height <= 0.0
    {
        return Err(JsValue::from_str("invalid page patch rectangle"));
    }

    let filter = canvas_layer_filter(layer_kind)?;
    let profile = RenderProfile::parse(profile)
        .ok_or_else(|| JsValue::from_str(&format!("unsupported render profile: {profile}")))?;
    let tree = document
        .build_canvas_page_layer_tree_with_profile(page_num, profile)
        .map_err(JsValue::from)?;
    let scale = normalize_canvas_scale(tree.page_width, tree.page_height, scale)
        .map_err(JsValue::from_str)?;

    let expected_width = scaled_canvas_extent(tree.page_width, scale);
    let expected_height = scaled_canvas_extent(tree.page_height, scale);
    if canvas.width() != expected_width || canvas.height() != expected_height {
        return Err(JsValue::from_str(
            "page patch canvas extent does not match the current page render",
        ));
    }

    let left = patch.x.max(0.0).min(tree.page_width);
    let top = patch.y.max(0.0).min(tree.page_height);
    let right = (patch.x + patch.width).max(left).min(tree.page_width);
    let bottom = (patch.y + patch.height).max(top).min(tree.page_height);
    if right <= left || bottom <= top {
        return Err(JsValue::from_str(
            "page patch rectangle does not intersect the page",
        ));
    }

    let mut renderer = WebCanvasRenderer::new(canvas)?;
    renderer.set_hft_outline_fonts(&document.hft_outline_fonts);
    renderer.show_paragraph_marks = document.show_paragraph_marks;
    renderer.show_control_codes = document.show_control_codes;
    renderer.set_scale(scale);
    renderer.set_layer_filter(filter);
    renderer.set_partial_clip(BoundingBox::new(left, top, right - left, bottom - top));
    renderer.render_page(&tree).map_err(JsValue::from)?;
    Ok(())
}

fn get_page_layer_tree_with_profile_impl(
    document: &HwpDocument,
    page_num: u32,
    profile: &str,
    omit_image_bytes: bool,
    omit_font_bytes: bool,
) -> Result<String, JsValue> {
    let profile = crate::paint::RenderProfile::parse(profile)
        .ok_or_else(|| JsValue::from_str(&format!("unsupported render profile: {profile}")))?;
    document
        .get_page_layer_tree_with_options_native(
            page_num,
            profile,
            crate::paint::LayerJsonOptions {
                omit_image_bytes,
                omit_font_bytes,
            },
        )
        .map_err(|error| error.into())
}

/// 레이어 평면 요약 본체. 합성 판정(`getLayerPlaneSummary`)이 이 결과로 정해지므로 페인트와
/// 같은 패치 세대를 봐야 한다.
fn get_page_overlay_images_impl(document: &HwpDocument, page_num: u32) -> Result<String, JsValue> {
    document
        .get_page_overlay_images_native(page_num)
        .map_err(|error| error.into())
}

/// 본문 그림 배치 본체. 경계 뒤에서 그린 캔버스 위에 DOM `<img>` 로 합성되는 값이다.
fn get_page_flow_image_ops_impl(document: &HwpDocument, page_num: u32) -> Result<String, JsValue> {
    document
        .get_page_flow_image_ops_native(page_num)
        .map_err(|error| error.into())
}

#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct ExternalImageReference {
    key: String,
    bin_data_id: u16,
    original_path: String,
    basename: String,
    extension: String,
    loaded: bool,
}

fn external_path_basename(path: &str) -> &str {
    path.rsplit(|c| c == '/' || c == '\\')
        .find(|part| !part.is_empty())
        .unwrap_or(path)
}

fn external_path_extension(basename: &str) -> String {
    std::path::Path::new(basename)
        .extension()
        .and_then(|ext| ext.to_str())
        .unwrap_or("")
        .to_string()
}

fn parse_external_image_key(key: &str) -> Option<u16> {
    let bin_data_id = key.strip_prefix("binData:")?.parse::<u16>().ok()?;
    (bin_data_id != 0).then_some(bin_data_id)
}

fn collect_external_image_references(document: &Document) -> Vec<ExternalImageReference> {
    let mut references = std::collections::BTreeMap::new();

    for section in &document.sections {
        for para in &section.paragraphs {
            for ctrl in &para.controls {
                let pic = match ctrl {
                    Control::Picture(pic) => pic,
                    Control::Shape(shape) => match shape.as_ref() {
                        ShapeObject::Picture(pic) => pic,
                        _ => continue,
                    },
                    _ => continue,
                };

                let Some(original_path) = pic.image_attr.external_path.as_ref() else {
                    continue;
                };

                let bin_data_id = pic.image_attr.bin_data_id;
                references.entry(bin_data_id).or_insert_with(|| {
                    let basename = external_path_basename(original_path).to_string();
                    ExternalImageReference {
                        key: format!("binData:{bin_data_id}"),
                        bin_data_id,
                        extension: external_path_extension(&basename),
                        basename,
                        original_path: original_path.clone(),
                        loaded: document.external_image_loaded(bin_data_id),
                    }
                });
            }
        }
    }

    references.into_values().collect()
}

/// WASM에서 사용할 HWP 문서 래퍼
///
/// 도메인 로직은 `DocumentCore`에 구현되어 있으며,
/// `Deref`/`DerefMut`를 통해 투명하게 접근한다.
#[wasm_bindgen]
pub struct HwpDocument {
    core: DocumentCore,
}

/// 한 번의 문서 내보내기 결과.
///
/// 바이트와 content-loss 보고서가 같은 객체에 있어 다른 저장의 상태와 섞이지 않는다.
/// `takeBytes()`는 Rust 결과의 바이트 소유권을 한 번만 소비하며, 보고서는 그 전후 어느
/// 순서로든 읽을 수 있다. 바이트를 두 번 꺼내는 것은 명시적 오류다.
#[wasm_bindgen]
pub struct DocumentExport {
    bytes: Option<Vec<u8>>,
    content_loss_json: String,
}

impl From<crate::serializer::SerializedDocument> for DocumentExport {
    fn from(serialized: crate::serializer::SerializedDocument) -> Self {
        let (bytes, content_loss) = serialized.into_parts();
        Self {
            bytes: Some(bytes),
            content_loss_json: content_loss.to_json(),
        }
    }
}

#[wasm_bindgen]
impl DocumentExport {
    /// 이번 산출물의 content-loss 보고서(JSON). `takeBytes()` 뒤에도 읽을 수 있다.
    #[wasm_bindgen(js_name = contentLoss)]
    pub fn content_loss(&self) -> String {
        self.content_loss_json.clone()
    }

    /// 아직 JS로 옮기지 않은 바이트를 소유하는지 반환한다.
    #[wasm_bindgen(js_name = hasBytes)]
    pub fn has_bytes(&self) -> bool {
        self.bytes.is_some()
    }

    /// 산출 바이트 소유권을 한 번 꺼낸다.
    #[wasm_bindgen(js_name = takeBytes)]
    pub fn take_bytes(&mut self) -> Result<Vec<u8>, JsValue> {
        self.bytes
            .take()
            .ok_or_else(|| JsValue::from_str("이 내보내기 결과의 바이트를 이미 가져갔습니다"))
    }
}

impl std::ops::Deref for HwpDocument {
    type Target = DocumentCore;
    fn deref(&self) -> &DocumentCore {
        &self.core
    }
}

impl std::ops::DerefMut for HwpDocument {
    fn deref_mut(&mut self) -> &mut DocumentCore {
        &mut self.core
    }
}

impl From<DocumentCore> for HwpDocument {
    fn from(core: DocumentCore) -> Self {
        Self { core }
    }
}

/// 네이티브(비-WASM) 환경용 래퍼 메서드.
///
/// 테스트 및 CLI 환경에서 `HwpDocument::from_bytes()` 등을 직접 호출할 수 있도록 한다.
impl HwpDocument {
    pub fn from_bytes(data: &[u8]) -> Result<HwpDocument, HwpError> {
        DocumentCore::from_bytes(data).map(|core| HwpDocument { core })
    }

    pub fn from_bytes_with_password(data: &[u8], password: &[u8]) -> Result<HwpDocument, HwpError> {
        DocumentCore::from_bytes_with_password(data, password).map(|core| HwpDocument { core })
    }

    /// 인증 성공 뒤에만 문서를 교체하는 Native/Rust command. 기존 constructor는
    /// 호환용으로 유지하며, 암호 처리와 문서 조회를 분리할 때 이 경로를 사용한다.
    pub fn load_bytes(&mut self, data: &[u8], password: Option<&[u8]>) -> Result<(), HwpError> {
        self.core.load_bytes(data, password)
    }

    pub fn find_initial_column_def(paragraphs: &[Paragraph]) -> ColumnDef {
        DocumentCore::find_initial_column_def(paragraphs)
    }

    pub fn find_column_def_for_paragraph(paragraphs: &[Paragraph], para_idx: usize) -> ColumnDef {
        DocumentCore::find_column_def_for_paragraph(paragraphs, para_idx)
    }

    fn inject_external_image_by_bin_data_id(
        &mut self,
        bin_data_id: u16,
        data: &[u8],
        display_path: &str,
        fallback_basename: Option<&str>,
    ) -> u32 {
        let Some(reference) = collect_external_image_references(self.document())
            .into_iter()
            .find(|reference| reference.bin_data_id == bin_data_id)
        else {
            return 0;
        };

        if reference.loaded {
            return 0;
        }

        if !self.document_mut().inject_external_image_data(
            bin_data_id,
            data.to_vec(),
            reference.extension.clone(),
        ) {
            return 0;
        }

        let basename = fallback_basename.unwrap_or(&reference.basename);
        let resolved = if display_path.is_empty() {
            format!("/samples/{basename}")
        } else {
            display_path.to_string()
        };
        self.document_mut()
            .update_external_image_display_path(bin_data_id, &resolved);

        1
    }
}

fn hml_warning_code(code: crate::parser::hml::HmlWarningCode) -> &'static str {
    use crate::parser::hml::HmlWarningCode;

    match code {
        HmlWarningCode::UnsupportedElement => "UnsupportedElement",
        HmlWarningCode::UnsupportedAttribute => "UnsupportedAttribute",
        HmlWarningCode::UnsupportedEquationSemantics => "UnsupportedEquationSemantics",
        HmlWarningCode::MissingResource => "MissingResource",
        HmlWarningCode::ExternalResourceBlocked => "ExternalResourceBlocked",
        HmlWarningCode::InvalidReference => "InvalidReference",
        HmlWarningCode::LossyConversion => "LossyConversion",
    }
}

fn hml_warning_json(warning: &crate::parser::hml::HmlWarning) -> serde_json::Value {
    serde_json::json!({
        "code": hml_warning_code(warning.code),
        "xmlPath": warning.xml_path,
        "message": warning.message,
        "preserved": warning.preserved,
    })
}

#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct HmlSaveState {
    source_format: &'static str,
    hml_savable: bool,
    blockers: Vec<HmlSaveBlockerDto>,
}

#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct HmlSaveBlockerDto {
    code: String,
    xml_path: String,
    message: String,
    preserved: bool,
}

fn hml_save_state(core: &DocumentCore) -> HmlSaveState {
    let source_format = source_format_name(core.source_format);
    match core.hml_export_preflight() {
        Ok(()) => HmlSaveState {
            source_format,
            hml_savable: true,
            blockers: Vec::new(),
        },
        Err(error) => {
            let blockers = error
                .blockers()
                .iter()
                .map(|blocker| HmlSaveBlockerDto {
                    code: blocker.code.to_string(),
                    xml_path: blocker.xml_path.clone(),
                    message: blocker.message.clone(),
                    preserved: false,
                })
                .collect();
            HmlSaveState {
                source_format,
                hml_savable: false,
                blockers,
            }
        }
    }
}

fn source_format_name(format: crate::parser::FileFormat) -> &'static str {
    match format {
        crate::parser::FileFormat::Hwpx => "hwpx",
        crate::parser::FileFormat::Hml => "hml",
        crate::parser::FileFormat::Pdf => "pdf",
        _ => "hwp",
    }
}

fn format_hml_export_error(error: &crate::serializer::hml::HmlExportError) -> String {
    use std::fmt::Write;

    let mut message = error.to_string();
    for blocker in error.blockers() {
        let _ = write!(
            message,
            "\n[{}] {}: {}",
            blocker.code, blocker.xml_path, blocker.message
        );
    }
    message
}

#[wasm_bindgen]
impl HwpDocument {
    /// HWP 파일 바이트를 로드하여 문서 객체를 생성한다.
    #[wasm_bindgen(constructor)]
    pub fn new(data: &[u8]) -> Result<HwpDocument, JsValue> {
        DocumentCore::from_bytes(data)
            .map(|core| HwpDocument { core })
            .map_err(|e| e.into())
    }

    /// 현재 WASM 빌드에서 PDF 입력을 사용할 수 있는지 문서 생성 전에 조회한다.
    #[wasm_bindgen(js_name = supportsPdfImport)]
    pub fn supports_pdf_import() -> bool {
        cfg!(target_arch = "wasm32") && crate::pdf_support::pdf_import_support().enabled
    }

    /// Compile-time support of this artifact, queryable before opening a PDF.
    #[wasm_bindgen(js_name = getPdfImportSupport)]
    pub fn get_pdf_import_support() -> String {
        serde_json::to_string(&crate::pdf_support::pdf_import_support())
            .expect("compile-time PDF support is serializable")
    }

    /// Worker가 입력을 복사하기 전에 제품의 실제 요청 한도를 조회한다.
    #[wasm_bindgen(js_name = getPdfImportPolicy)]
    pub fn get_pdf_import_policy() -> String {
        #[cfg(feature = "pdf-import")]
        {
            serde_json::to_string(&crate::parser::pdf::PdfImportPolicy::default())
                .expect("PDF policy serialization cannot fail")
        }
        #[cfg(not(feature = "pdf-import"))]
        {
            "null".to_owned()
        }
    }

    /// Resolve the same strict options used by importPdf before copying input.
    /// The zero-argument getPdfImportPolicy() remains the standard profile.
    #[wasm_bindgen(js_name = getPdfImportPolicyWithOptions)]
    pub fn get_pdf_import_policy_with_options(options: JsValue) -> Result<String, JsValue> {
        #[cfg(all(feature = "pdf-import", target_arch = "wasm32"))]
        {
            let (_, policy, _) = pdf_import::options(options)?;
            Ok(serde_json::to_string(&policy).expect("PDF policy is serializable"))
        }
        #[cfg(not(all(feature = "pdf-import", target_arch = "wasm32")))]
        {
            let _ = options;
            Err(JsValue::from_str(
                "PDF_IMPORT_DISABLED: a PDF-enabled WASM runtime is required",
            ))
        }
    }

    /// Host execution requirements, distinct from parser request counters.
    #[wasm_bindgen(js_name = getPdfImportRuntimeCapabilities)]
    pub fn get_pdf_import_runtime_capabilities() -> String {
        serde_json::json!({
            "schemaVersion": 1,
            "executionModel": "synchronous",
            "preCopyPolicyValidation": cfg!(all(feature = "pdf-import", target_arch = "wasm32")),
            "interruption": "hostWorkerTermination",
            "requestTransportReservations": cfg!(all(feature = "pdf-import", target_arch = "wasm32")),
            "editorReopenRemainingCredit": cfg!(all(feature = "pdf-import", target_arch = "wasm32")),
            "editorReopenInterruption": "cooperativeChecksAndPublicationYield",
            "mainThreadPreemption": false,
            "processMemoryLimitEnforced": false,
            "filesystemNetworkSandbox": false,
        })
        .to_string()
    }

    /// PDF 전체 또는 선택 쪽을 공통 IR로 가져온다 (기본 포함 `pdf-import`).
    /// options.sourcePages는 0-based 증가 배열이며 생략하면 전체 쪽이다.
    /// 동기 실행이므로 브라우저에서 취소/시간 제한이 필요하면 Worker에서 호출한다.
    #[wasm_bindgen(js_name = importPdf)]
    pub fn import_pdf(
        #[wasm_bindgen(unchecked_param_type = "Uint8Array")] data: &PdfImportInput,
        options: JsValue,
    ) -> Result<HwpDocument, JsValue> {
        #[cfg(all(feature = "pdf-import", target_arch = "wasm32"))]
        {
            let (options, policy, _) = pdf_import::options(options)?;
            let mut session = crate::PdfImportSession::new(policy)?;
            let data = pdf_import::copy_input(data, &policy, &mut session)?;
            session
                .open(&data, &options)
                .map(|core| HwpDocument { core })
                .map_err(JsValue::from)
        }
        #[cfg(not(all(feature = "pdf-import", target_arch = "wasm32")))]
        {
            let _ = (data, options);
            Err(JsValue::from_str(if cfg!(feature = "pdf-import") {
                "PDF_IMPORT_OPTIONS: JS options require a WASM runtime; use DocumentCore::from_pdf_bytes in Rust"
            } else {
                "PDF_IMPORT_DISABLED: rebuild with --features pdf-import"
            }))
        }
    }

    /// 가져온 PDF의 원본 쪽/출력 구역 대응·경고·임시 문단 정책을 JSON으로 반환한다.
    /// 편집 후 현재 쪽수가 아닌 가져오기 시점의 진단이다. 다른 형식은 `null`이다.
    #[wasm_bindgen(js_name = getPdfImportDiagnostics)]
    pub fn get_pdf_import_diagnostics(&self) -> String {
        #[cfg(feature = "pdf-import")]
        {
            serde_json::to_string(&self.core.pdf_metadata())
                .expect("PDF import metadata serialization cannot fail")
        }
        #[cfg(not(feature = "pdf-import"))]
        {
            "null".to_string()
        }
    }

    /// 비밀번호로 보호된 HWP/HWPX 파일을 비밀번호와 함께 로드한다.
    ///
    /// HWP5 EncryptVersion 4, 압축 HWP3와 ODF AES-256-CBC HWPX를 지원한다.
    /// 구버전/비압축 HWP3 암호화와 DRM은 지원하지 않는다.
    /// 비밀번호가 틀린 경우 JS 측에서 잡을 수 있도록 에러 메시지에
    /// "비밀번호가 일치하지 않"이 포함된 `JsValue` 를 반환한다.
    /// 암호화되지 않은 일반 문서에 비밀번호를 전달해도 정상 로드된다.
    #[wasm_bindgen(js_name = openWithPassword)]
    pub fn open_with_password(data: &[u8], password: &str) -> Result<HwpDocument, JsValue> {
        let mut document = Self::from(DocumentCore::new_empty());
        document.load_bytes(data, Some(password.as_bytes()))?;
        Ok(document)
    }

    /// 빈 문서 생성 (테스트/미리보기용)
    ///
    /// 기본 A4 구역 1개 + 빈 문단 1개를 포함한다. 구역 0개 문서는 모든
    /// 편집/조회 API가 "구역 인덱스 0 범위 초과"로 실패해 사용 불가하므로
    /// 생성 직후 바로 편집 가능한 최소 구조를 보장한다 (#1386).
    ///
    /// 여기서 만든 문단은 **구역 정의·단 정의를 안 진다** — 실제 HWP 문서는 예외 없이 그
    /// 둘을 첫 문단에 지므로 이 문서는 그 점에서 실물과 다르다. 한글 호환이 필요한 자리
    /// (`Clear`)는 번들 템플릿을 쓰는 [`create_blank_document`](Self::create_blank_document)
    /// 를 쓴다. 여기에 그 둘을 넣으면 `char_shapes` 자리가 16칸씩 밀려 기존 호출부가 깨진다.
    #[wasm_bindgen(js_name = createEmpty)]
    pub fn create_empty() -> HwpDocument {
        let mut core = DocumentCore::new_empty();
        let mut section = Section::default();
        // set_document가 styles/composed 재구성 + paginate까지 수행한다.
        section.section_def.page_def = crate::model::page::PageDef::a4_default();
        section.paragraphs.push(Paragraph::new_empty());
        let mut document = Document::default();
        document.sections.push(section);
        core.set_document(document);
        HwpDocument { core }
    }

    /// 내장 템플릿에서 빈 문서를 생성한다.
    ///
    /// saved/blank2010.hwp를 WASM 바이너리에 포함하여 유효한 HWP 문서를 즉시 생성.
    /// DocInfo raw_stream이 온전하므로 FIX-4 워크어라운드와 호환됨.
    #[wasm_bindgen(js_name = createBlankDocument)]
    pub fn create_blank_document(&mut self) -> Result<String, JsValue> {
        self.create_blank_document_native().map_err(|e| e.into())
    }

    /// Browser/host font selection이 확정한 face bytes를 exact layout slot에 등록한다.
    /// family 이름 재탐색 없이 `(charShapeId, languageIndex)`에 직접 결합한다.
    #[wasm_bindgen(js_name = registerExactFontSource)]
    pub fn register_exact_font_source(
        &mut self,
        char_shape_id: u32,
        language_index: u32,
        font_bytes: &[u8],
        face_index: u32,
    ) -> Result<String, JsValue> {
        self.register_exact_font_source_native(
            char_shape_id,
            language_index as usize,
            font_bytes,
            face_index,
        )
        .map_err(JsValue::from)
    }

    /// 실제 FontFace의 원본 HFT 프로그램을 paint 전용으로 등록한다. 재조판하지 않는다.
    #[wasm_bindgen(js_name = registerHftOutlineFont)]
    pub fn register_hft_outline_font(
        &mut self,
        family: &str,
        bytes: &[u8],
        face_index: u32,
    ) -> Result<bool, JsValue> {
        self.register_hft_outline_font_native(family, bytes, face_index)
            .map_err(JsValue::from)
    }

    /// 호스트가 실제 FontFace에 적재한 프로그램의 호환 글리프 지원을 등록한다.
    #[wasm_bindgen(js_name = clearTextFontFamily)]
    pub fn clear_text_font_family_wasm(&mut self, family: &str) {
        self.clear_text_font_family_native(family);
    }

    #[wasm_bindgen(js_name = registerTextFontGlyphCoverage)]
    pub fn register_text_font_glyph_coverage(
        &mut self,
        family: &str,
        bytes: &[u8],
        face_index: u32,
    ) -> Result<bool, JsValue> {
        self.register_text_font_glyph_coverage_native(family, bytes, face_index)
            .map_err(JsValue::from)
    }

    /// 일반 FontFace 전용 기본 윤곽 사본. 원본·컬러 자원·문서 상태는 변경하지 않는다.
    #[wasm_bindgen(js_name = ordinaryTextFontProgram)]
    pub fn ordinary_text_font_program(&self, bytes: &[u8], face_index: u32) -> Option<Vec<u8>> {
        crate::renderer::text_font_presentation::ordinary_text_font_program(bytes, face_index)
    }

    /// 문서 측정 slot과 별도로 SVG/WMF paint에 실제 선택한 font face를 공급한다.
    #[wasm_bindgen(js_name = registerMetafileFont)]
    pub fn register_metafile_font(
        &mut self,
        family: &str,
        bytes: &[u8],
        face_index: u32,
    ) -> Result<bool, JsValue> {
        self.register_metafile_font_native(family, bytes, face_index)
            .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = clearMetafileFonts)]
    pub fn clear_metafile_fonts(&mut self) {
        self.clear_metafile_fonts_native();
    }

    #[wasm_bindgen(js_name = getMetafileFontRequests)]
    pub fn get_metafile_font_requests(&self) -> Result<String, JsValue> {
        self.get_metafile_font_requests_native()
            .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = getPagePaintFontRequests)]
    pub fn get_page_paint_font_requests(&self, page: u32) -> Result<String, JsValue> {
        self.get_page_paint_font_requests_native(page)
            .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = getTextShadowFontRequests)]
    pub fn get_text_shadow_font_requests(&self) -> Result<String, JsValue> {
        self.get_text_shadow_font_requests_native()
            .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = getNativePuaFontRequests)]
    pub fn get_native_pua_font_requests(&self) -> Result<String, JsValue> {
        serde_json::to_string(&self.native_pua_font_requests())
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    #[wasm_bindgen(js_name = getNativeOtfFontRequests)]
    pub fn get_native_otf_font_requests_wasm(&self) -> Result<String, JsValue> {
        serde_json::to_string(&self.native_otf_font_requests())
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// 미리 준비한 실제 face만 동기 공급하고 모든 선택을 한 번에 조판한다.
    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen(js_name = prepareNativeOtfFonts)]
    pub fn prepare_native_otf_fonts_wasm(
        &mut self,
        provider: &js_sys::Function,
    ) -> Result<bool, JsValue> {
        use wasm_bindgen::JsCast;
        let mut prepared = std::collections::BTreeMap::new();
        for request in self.native_otf_font_requests() {
            let key = serde_json::to_string(&request)
                .map_err(|error| JsValue::from_str(&error.to_string()))?;
            let value = provider.call1(&JsValue::NULL, &JsValue::from_str(&key))?;
            if value.is_null() || value.is_undefined() {
                continue;
            }
            let values: Vec<JsValue> = if js_sys::Array::is_array(&value) {
                let array = js_sys::Array::from(&value);
                if array.length() > 256 {
                    return Err(JsValue::from_str(
                        "OTF provider program count exceeds limit",
                    ));
                }
                array.iter().collect()
            } else {
                vec![value]
            };
            let mut programs = Vec::with_capacity(values.len());
            let mut total_bytes = 0usize;
            for value in values {
                if !value.is_instance_of::<js_sys::Uint8Array>() {
                    return Err(JsValue::from_str(
                        "OTF provider must return Uint8Array, an array of Uint8Array, or null",
                    ));
                }
                let array = js_sys::Uint8Array::new(&value);
                let length = array.length() as usize;
                total_bytes = total_bytes.saturating_add(length);
                if length > 32 * 1024 * 1024 || total_bytes > 64 * 1024 * 1024 {
                    return Err(JsValue::from_str("OTF provider program exceeds limit"));
                }
                programs.push((array.to_vec(), 0));
            }
            prepared.insert(
                (
                    request.family,
                    request.bold,
                    request.italic,
                    request.source_ttf,
                ),
                programs,
            );
        }
        self.prepare_native_otf_fonts_multiple_with(|request| {
            prepared
                .remove(&(
                    request.family.clone(),
                    request.bold,
                    request.italic,
                    request.source_ttf,
                ))
                .unwrap_or_default()
        })
        .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = registerNativePuaFont)]
    pub fn register_native_pua_font_wasm(
        &mut self,
        family: &str,
        bold: bool,
        italic: bool,
        bytes: &[u8],
        face_index: u32,
    ) -> Result<bool, JsValue> {
        self.register_native_pua_font(family, bold, italic, bytes, face_index)
            .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = registerNativePuaFontForSource)]
    pub fn register_native_pua_font_for_source_wasm(
        &mut self,
        family: &str,
        bold: bool,
        italic: bool,
        source_ttf: bool,
        bytes: &[u8],
        face_index: u32,
    ) -> Result<bool, JsValue> {
        self.register_native_pua_font_for_source(
            family, bold, italic, source_ttf, bytes, face_index,
        )
        .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = registerLiteralFigureSpaceFont)]
    pub fn register_literal_figure_space_font_wasm(
        &mut self,
        family: &str,
        bold: bool,
        italic: bool,
        bytes: &[u8],
        face_index: u32,
    ) -> Result<bool, JsValue> {
        self.register_literal_figure_space_font(family, bold, italic, bytes, face_index)
            .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = registerLiteralFigureSpaceFontForSource)]
    pub fn register_literal_figure_space_font_for_source_wasm(
        &mut self,
        family: &str,
        bold: bool,
        italic: bool,
        source_ttf: bool,
        bytes: &[u8],
        face_index: u32,
    ) -> Result<bool, JsValue> {
        self.register_literal_figure_space_font_for_source(
            family, bold, italic, source_ttf, bytes, face_index,
        )
        .map_err(JsValue::from)
    }

    #[wasm_bindgen(js_name = clearNativePuaFonts)]
    pub fn clear_native_pua_fonts_wasm(&mut self) {
        self.clear_native_pua_fonts();
    }

    /// 이미 등록된 exact font source slot에 명시 variable-font instance 요청을 설정한다.
    /// JSON DTO의 검증·canonicalization·mutation 권위는 native command 한 곳에만 둔다.
    #[wasm_bindgen(js_name = setExactFontInstance)]
    pub fn set_exact_font_instance(&mut self, options_json: &str) -> Result<String, JsValue> {
        self.set_exact_font_instance_native(options_json)
            .map_err(JsValue::from)
    }

    /// exact slot 하나의 명시 variable-font instance 요청을 제거한다.
    /// 없는 요청의 clear는 멱등이며 다른 slot의 요청을 건드리지 않는다.
    #[wasm_bindgen(js_name = clearExactFontInstance)]
    pub fn clear_exact_font_instance(&mut self, options_json: &str) -> Result<String, JsValue> {
        self.clear_exact_font_instance_native(options_json)
            .map_err(JsValue::from)
    }

    /// 문단부호(¶) 표시 여부를 설정한다.
    #[wasm_bindgen(js_name = setShowParagraphMarks)]
    pub fn set_show_paragraph_marks(&mut self, enabled: bool) {
        self.show_paragraph_marks = enabled;
        self.invalidate_page_tree_cache();
    }

    /// 문단부호(¶) 표시 여부를 반환한다.
    #[wasm_bindgen(js_name = getShowParagraphMarks)]
    pub fn get_show_paragraph_marks(&self) -> bool {
        self.show_paragraph_marks
    }

    /// [#4709] SVG 출력에 배치 메트릭 face 주석을 붙일지 설정한다 (기본 꺼짐).
    ///
    /// 켜면 `renderPageSvg` 계열 출력의 각 `<text>`에 `data-metric-font`,
    /// 루트 `<svg>`에 `data-rhwp-metric-fonts`(쉼표 구분 목록)가 붙는다.
    /// 임베드 호스트가 해당 폰트 설치 여부 확인·대체 폰트 자간 보정에 쓴다.
    /// 배치(레이아웃)에는 영향이 없는 뷰 전용 주석이다.
    #[wasm_bindgen(js_name = setAnnotateMetricFont)]
    pub fn set_annotate_metric_font(&mut self, enabled: bool) {
        self.annotate_metric_font = enabled;
    }

    /// [#4709] SVG 메트릭 face 주석 부착 여부를 반환한다.
    #[wasm_bindgen(js_name = getAnnotateMetricFont)]
    pub fn get_annotate_metric_font(&self) -> bool {
        self.annotate_metric_font
    }

    /// 조판부호 표시 여부를 반환한다.
    #[wasm_bindgen(js_name = getShowControlCodes)]
    pub fn get_show_control_codes(&self) -> bool {
        self.show_control_codes
    }

    /// 조판부호 표시 여부를 설정한다 (개체 마커 + 문단부호 포함).
    #[wasm_bindgen(js_name = setShowControlCodes)]
    pub fn set_show_control_codes(&mut self, enabled: bool) {
        self.show_control_codes = enabled;
        self.invalidate_page_tree_cache();
    }

    /// 투명선 표시 여부를 반환한다.
    #[wasm_bindgen(js_name = getShowTransparentBorders)]
    pub fn get_show_transparent_borders(&self) -> bool {
        self.show_transparent_borders
    }

    /// 투명선 표시 여부를 설정한다.
    #[wasm_bindgen(js_name = setShowTransparentBorders)]
    pub fn set_show_transparent_borders(&mut self, enabled: bool) {
        self.show_transparent_borders = enabled;
        self.invalidate_page_tree_cache();
    }

    #[wasm_bindgen(js_name = setClipEnabled)]
    pub fn set_clip_enabled(&mut self, enabled: bool) {
        self.clip_enabled = enabled;
        self.invalidate_page_tree_cache();
    }

    /// 디버그 오버레이 표시 여부를 설정한다.
    pub fn set_debug_overlay(&mut self, enabled: bool) {
        self.debug_overlay = enabled;
    }

    /// LINE_SEG vpos-reset 강제 분리 적용 여부를 설정한다.
    /// 변경 시 페이지네이션 결과가 달라지므로 모든 섹션을 재페이지네이션한다.
    pub fn set_respect_vpos_reset(&mut self, enabled: bool) {
        if self.respect_vpos_reset != enabled {
            self.respect_vpos_reset = enabled;
            // 모든 섹션 dirty 마킹 후 즉시 재페이지네이션
            for d in self.core.dirty_sections.iter_mut() {
                *d = true;
            }
            self.invalidate_page_tree_cache();
            self.core.paginate();
        }
    }

    /// 총 페이지 수를 반환한다.
    #[wasm_bindgen(js_name = pageCount)]
    pub fn page_count(&self) -> u32 {
        self.core.page_count()
    }

    /// 특정 페이지를 SVG 문자열로 렌더링한다.
    #[wasm_bindgen(js_name = renderPageSvg)]
    pub fn render_page_svg(&self, page_num: u32) -> Result<String, JsValue> {
        self.render_page_svg_native(page_num).map_err(|e| e.into())
    }

    /// 명시적인 출력 profile로 특정 페이지를 SVG 문자열로 렌더링한다.
    #[wasm_bindgen(js_name = renderPageSvgWithProfile)]
    pub fn render_page_svg_with_profile(
        &self,
        page_num: u32,
        profile: &str,
    ) -> Result<String, JsValue> {
        let profile = crate::paint::RenderProfile::parse(profile)
            .ok_or_else(|| JsValue::from_str(&format!("unsupported render profile: {profile}")))?;
        self.render_page_svg_layer_with_profile_native(page_num, profile)
            .map_err(Into::into)
    }

    /// 특정 페이지를 HTML 문자열로 렌더링한다.
    #[wasm_bindgen(js_name = renderPageHtml)]
    pub fn render_page_html(&self, page_num: u32) -> Result<String, JsValue> {
        self.render_page_html_native(page_num).map_err(|e| e.into())
    }

    /// 특정 페이지를 Canvas 명령 수로 반환한다.
    #[wasm_bindgen(js_name = renderPageCanvas)]
    pub fn render_page_canvas(&self, page_num: u32) -> Result<u32, JsValue> {
        self.render_page_canvas_native(page_num)
            .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = renderPageCanvasLegacy)]
    pub fn render_page_canvas_legacy(&self, page_num: u32) -> Result<u32, JsValue> {
        self.render_page_canvas_legacy_native(page_num)
            .map_err(|e| e.into())
    }

    /// 특정 페이지를 Canvas 2D에 직접 렌더링한다.
    ///
    /// WASM 환경에서만 사용 가능하다. Canvas 크기는 페이지 크기 × scale로 설정된다.
    /// scale이 0 이하이면 1.0으로 처리한다 (하위호환).
    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen(js_name = renderPageToCanvas)]
    pub fn render_page_to_canvas(
        &self,
        page_num: u32,
        canvas: &HtmlCanvasElement,
        scale: f64,
    ) -> Result<(), JsValue> {
        use crate::renderer::layer_renderer::LayerRenderer;
        use crate::renderer::web_canvas::WebCanvasRenderer;

        crate::renderer::image_resolver::with_decoded_handoff(|| {
            let tree = self
                .build_canvas_page_layer_tree_with_profile(
                    page_num,
                    crate::paint::RenderProfile::Screen,
                )
                .map_err(JsValue::from)?;

            let scale = normalize_canvas_scale(tree.page_width, tree.page_height, scale)
                .map_err(JsValue::from_str)?;

            // 캔버스 크기 = 페이지 크기 × scale
            canvas.set_width(scaled_canvas_extent(tree.page_width, scale));
            canvas.set_height(scaled_canvas_extent(tree.page_height, scale));

            let mut renderer = WebCanvasRenderer::new(canvas)?;
            renderer.set_hft_outline_fonts(&self.hft_outline_fonts);
            renderer.show_paragraph_marks = self.show_paragraph_marks;
            renderer.show_control_codes = self.show_control_codes;
            renderer.set_scale(scale);
            renderer.render_page(&tree).map_err(JsValue::from)?;
            Ok(())
        })
    }

    /// 구역 첫 페이지에 요청한 머리말/꼬리말 정의를 가상 투영해 Canvas 2D로 렌더링한다.
    ///
    /// 일반 page tree cache와 pagination active target은 바꾸지 않는다. Studio는 결과 canvas를
    /// 머리말/꼬리말 밴드에만 clip해 편집 중 비인쇄 overlay로 사용한다.
    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen(js_name = renderHeaderFooterEditPreviewToCanvas)]
    pub fn render_header_footer_edit_preview_to_canvas(
        &self,
        page_num: u32,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        canvas: &HtmlCanvasElement,
        scale: f64,
    ) -> Result<(), JsValue> {
        use crate::renderer::web_canvas::WebCanvasRenderer;

        let tree = self
            .build_header_footer_edit_preview_tree(
                page_num,
                section_idx as usize,
                is_header,
                apply_to,
            )
            .map_err(JsValue::from)?;
        let scale = normalize_canvas_scale(tree.root.bbox.width, tree.root.bbox.height, scale)
            .map_err(JsValue::from_str)?;

        canvas.set_width(scaled_canvas_extent(tree.root.bbox.width, scale));
        canvas.set_height(scaled_canvas_extent(tree.root.bbox.height, scale));

        let mut renderer = WebCanvasRenderer::new(canvas)?;
        renderer.set_hft_outline_fonts(&self.hft_outline_fonts);
        renderer.show_paragraph_marks = self.show_paragraph_marks;
        renderer.show_control_codes = self.show_control_codes;
        renderer.set_scale(scale);
        renderer.render_tree(&tree);
        Ok(())
    }

    /// 다층 레이어 필터를 적용한 Canvas 렌더링 (Task #516, Stage 5.2).
    ///
    /// `layer_kind`:
    /// - `"all"` → 모든 PaintOp 렌더 (기본 `renderPageToCanvas` 와 동일)
    /// - `"background"` → page background layer
    /// - `"flow"` → 본문 layer (BehindText / InFrontOfText plane 제외)
    /// - `"flow-dynamic"` → 본문 layer 중 Image/RawSvg 제외
    /// - `"flow-static"` → page background + 본문 Image/RawSvg layer
    /// - `"behind"` → BehindText overlay layer
    /// - `"front"` → InFrontOfText overlay layer
    ///
    /// 본문 Canvas 와 overlay 컨테이너를 분리하는 다층 layer 아키텍처에서 사용.
    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen(js_name = renderPageToCanvasFiltered)]
    pub fn render_page_to_canvas_filtered(
        &self,
        page_num: u32,
        canvas: &HtmlCanvasElement,
        scale: f64,
        layer_kind: &str,
    ) -> Result<(), JsValue> {
        self.render_page_to_canvas_filtered_with_profile(
            page_num, canvas, scale, layer_kind, "screen",
        )
    }

    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen(js_name = renderPageToCanvasFilteredWithProfile)]
    pub fn render_page_to_canvas_filtered_with_profile(
        &self,
        page_num: u32,
        canvas: &HtmlCanvasElement,
        scale: f64,
        layer_kind: &str,
        profile: &str,
    ) -> Result<(), JsValue> {
        render_patch_boundary::render_page_to_canvas_filtered_with_profile(
            self, page_num, canvas, scale, layer_kind, profile,
        )
    }

    /// [#3137 Stage 4] 기존 Canvas의 page-space 일부만 다시 재생한다.
    ///
    /// Canvas 크기와 나머지 픽셀은 유지한다. 호출 조건이나 크기가 맞지 않으면 오류를
    /// 반환하며 Studio는 기존 full-page repaint로 폴백한다.
    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen(js_name = renderPagePatchToCanvasFilteredWithProfile)]
    #[allow(clippy::too_many_arguments)]
    pub fn render_page_patch_to_canvas_filtered_with_profile(
        &self,
        page_num: u32,
        canvas: &HtmlCanvasElement,
        scale: f64,
        layer_kind: &str,
        profile: &str,
        x: f64,
        y: f64,
        width: f64,
        height: f64,
    ) -> Result<(), JsValue> {
        use crate::renderer::render_tree::BoundingBox;

        render_patch_boundary::render_page_patch_to_canvas_filtered_with_profile(
            self,
            page_num,
            canvas,
            scale,
            layer_kind,
            profile,
            BoundingBox::new(x, y, width, height),
        )
    }

    /// 특정 페이지를 기존 PageRenderTree 경로로 Canvas 2D에 직접 렌더링한다.
    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen(js_name = renderPageToCanvasLegacy)]
    pub fn render_page_to_canvas_legacy(
        &self,
        page_num: u32,
        canvas: &HtmlCanvasElement,
        scale: f64,
    ) -> Result<(), JsValue> {
        use crate::renderer::web_canvas::WebCanvasRenderer;

        let tree = self
            .build_page_tree_cached(page_num)
            .map_err(|e| JsValue::from(e))?;

        let scale = normalize_canvas_scale(tree.root.bbox.width, tree.root.bbox.height, scale)
            .map_err(JsValue::from_str)?;

        // 캔버스 크기 = 페이지 크기 × scale
        canvas.set_width(scaled_canvas_extent(tree.root.bbox.width, scale));
        canvas.set_height(scaled_canvas_extent(tree.root.bbox.height, scale));

        let mut renderer = WebCanvasRenderer::new(canvas)?;
        renderer.set_hft_outline_fonts(&self.hft_outline_fonts);
        renderer.show_paragraph_marks = self.show_paragraph_marks;
        renderer.show_control_codes = self.show_control_codes;
        renderer.set_scale(scale);
        renderer.render_tree(&tree);
        Ok(())
    }

    /// 페이지 렌더 트리를 JSON 문자열로 반환한다.
    #[wasm_bindgen(js_name = getPageRenderTree)]
    pub fn get_page_render_tree(&self, page_num: u32) -> Result<String, JsValue> {
        let tree = self
            .build_page_tree_cached(page_num)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        Ok(tree.root.to_json())
    }

    /// 페이지 레이어 트리를 JSON 문자열로 반환한다.
    ///
    /// screen profile 기본값이므로 `getPageLayerTreeWithProfile` 로 위임한다 — 같은 핫패치
    /// 경계를 지나야 한다. PageRenderer 가 좁은 질의를 못 쓸 때 되돌아오는 경로다.
    #[wasm_bindgen(js_name = getPageLayerTree)]
    pub fn get_page_layer_tree(&self, page_num: u32) -> Result<String, JsValue> {
        self.get_page_layer_tree_with_profile(page_num, "screen", Some(false), Some(false))
    }

    /// 페이지 레이어 트리를 profile 별로 반환한다.
    ///
    /// [Task #3315] `omit_image_bytes` 를 `true` 로 주면 `sourceImageKey`를 낼 수 있는 그림만
    /// base64를 생략하고, 바이트는 `getSourceImageBytes(key)`로 따로 받는다. 키 없는 합성 그림은
    /// 소비자가 되찾을 방법이 없으므로 같은 `byKey` 요청에서도 인라인 base64를 유지한다.
    /// [Task #4969] 네 번째 `omit_font_bytes`를 `true`로 주면 exact font metadata/key는
    /// 유지하고 `resources.fontBlobs` payload만 생략한다. 바이트는
    /// `getSourceFontBytes(key)`로 현재 document generation에서 따로 받는다.
    /// 인자를 생략하면(`undefined`) 그림 payload는 inline으로 유지하지만, schema minor 21과
    /// 최상위 `imageBytes:"inline"` 메타데이터가 있으므로 JSON 전체의 byte identity는 보장하지 않는다.
    #[wasm_bindgen(js_name = getPageLayerTreeWithProfile)]
    pub fn get_page_layer_tree_with_profile(
        &self,
        page_num: u32,
        profile: &str,
        omit_image_bytes: Option<bool>,
        omit_font_bytes: Option<bool>,
    ) -> Result<String, JsValue> {
        let omit_image_bytes = omit_image_bytes.unwrap_or(false);
        let omit_font_bytes = omit_font_bytes.unwrap_or(false);
        render_patch_boundary::get_page_layer_tree_with_profile(
            self,
            page_num,
            profile,
            omit_image_bytes,
            omit_font_bytes,
        )
    }

    /// 지금 컴파일되어 있는 렌더 코드의 식별자. 값이 바뀌면 코드가 교체된 것이다.
    ///
    /// 소비자는 이 문자열을 해석하지 않고 이전 값과 비교만 한다. 오늘 그 값을 바꾸는 것은
    /// Subsecond 핫패치뿐이지만, 이름은 그 사실이 아니라 소비자가 알아야 하는 것을 말한다 —
    /// 벤더가 바뀌어도 "렌더 코드의 리비전"이라는 질문은 그대로다 (#4580). 벤더를 아는 곳은
    /// 몸통이 부르는 `render_patch_boundary` 하나다.
    ///
    /// 값은 경계 목록(`render_patch_boundary`)에서 바로 나오므로 경계를 더할 때 여기를 같이 고칠
    /// 일이 없다 — 리비전이 경계 하나를 놓쳐 재도색이 안 도는 구멍이 생기지 않는다.
    ///
    /// 아래 재구성과 **한 쌍이다.** 리비전이 바뀐 것을 보고 재구성을 부르는 것이 TS 계약
    /// (`rhwp-studio/src/core/subsecond-runtime.ts`)이므로 한쪽만 있는 빌드는 그 계약을 반만
    /// 만족한다. 그래서 게이트도 둘이 같아야 한다 — 이 함수의 몸통이 wasm32 전용 경계를
    /// 가리키므로 `wasm32` 가 조건에 들어가고, 짝인 재구성도 같은 조건을 쓴다.
    #[cfg(all(feature = "subsecond-dev", target_arch = "wasm32"))]
    #[wasm_bindgen(js_name = getRenderCodeRevision)]
    pub fn get_render_code_revision(&self) -> String {
        render_patch_boundary::patch_revision()
    }

    /// 바이트는 그대로인데 화면용으로 파생해 둔 것이 더는 원본과 대응하지 않을 때 다시 만든다.
    ///
    /// 몸통에 벤더는 없다 — `DocumentCore::rebuild_derived_state` 를 그대로 위임하고, 그 연산
    /// 자체는 렌더 코드 교체 말고도 쓰일 수 있는 것이다. studio 가 같은 사건을 부르는 말도
    /// `document-view-changed`("바이트는 안 바뀌었고 화면용으로 파생한 것이 바뀌었다")다.
    /// 그래서 이름을 벤더가 아니라 그 어휘에 맞춘다 (#4580).
    ///
    /// `&mut self` 여야 한다. 페이지 트리 캐시만 비우면 다시 그리는 값은 새 코드가 내지만
    /// 그 값을 앉히는 페이지 박스와 문단 조합은 `pagination`·`composed`·측정 캐시에 남은
    /// 패치 이전 코드의 결과라, 소스의 어느 버전에도 대응하지 않는 화면이 나온다 (#4576).
    /// 그 셋은 모두 `&mut self` 를 요구하므로 `&self` 로는 계약 자체를 표현할 수 없다.
    ///
    /// 위 리비전 조회와 짝이라 게이트도 같다. 네이티브에는 호출부가 하나도 없다 — 몸통은
    /// 타깃과 무관하지만, 이 export 를 부르는 계약 자체가 브라우저의 것이다 (#4580).
    #[cfg(all(feature = "subsecond-dev", target_arch = "wasm32"))]
    #[wasm_bindgen(js_name = rebuildDerivedState)]
    pub fn rebuild_derived_state(&mut self) {
        self.core.rebuild_derived_state();
    }

    /// 문서가 선언한 실제 프로그램 후보와 현재 환경을 호스트에 전달한다.
    #[wasm_bindgen(js_name = getDocumentFontSelectionPlan)]
    pub fn get_document_font_selection_plan(&self) -> String {
        self.core.get_document_font_selection_plan()
    }

    /// 실제 공급된 프로그램으로 측정·표시의 공통 환경을 계산한다.
    #[wasm_bindgen(js_name = buildFontEnvironmentFromAvailablePrograms)]
    pub fn build_font_environment_from_available_programs(
        &self,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .build_font_environment_from_available_programs(json)
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// 명시적인 조판·표시 글꼴 환경을 설정한다. None이면 기본 환경으로 돌아간다.
    #[wasm_bindgen(js_name = setFontEnvironment)]
    pub fn set_font_environment_json(&mut self, json: Option<String>) -> Result<bool, JsValue> {
        let environment = json
            .as_deref()
            .map(crate::renderer::font_environment::FontEnvironment::from_json)
            .transpose()
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        self.core
            .set_font_environment(environment)
            .map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// CanvasKit direct replay 정책 진단을 JSON 문자열로 반환한다.
    ///
    /// `mode` 는 `"default"` 또는 `"compat"` 를 받는다. 빈 문자열은 `"default"` 로 처리한다.
    /// 현재 두 mode 모두 hidden Canvas2D overlay 없이 direct replay required 정책을 따른다.
    /// `compat` 는 API/URL 호환성과 이후 보수적인 direct replay 튜닝을 위해 남겨 둔 선택지다.
    #[wasm_bindgen(js_name = getCanvasKitReplayPlan)]
    pub fn get_canvaskit_replay_plan(&self, page_num: u32, mode: &str) -> Result<String, JsValue> {
        self.get_canvaskit_replay_plan_native(page_num, mode)
            .map_err(|e| e.into())
    }

    /// 페이지의 bounded layout font decision trace를 JSON으로 반환한다 (#4961).
    #[wasm_bindgen(js_name = getFontDecisionTrace)]
    pub fn get_font_decision_trace(
        &self,
        page_num: u32,
        options_json: &str,
    ) -> Result<String, JsValue> {
        self.get_font_decision_trace_native(page_num, options_json)
            .map_err(Into::into)
    }

    #[wasm_bindgen(js_name = getCanvasKitReplayPlanWithProfile)]
    pub fn get_canvaskit_replay_plan_with_profile(
        &self,
        page_num: u32,
        mode: &str,
        profile: &str,
    ) -> Result<String, JsValue> {
        let profile = crate::paint::RenderProfile::parse(profile)
            .ok_or_else(|| JsValue::from_str(&format!("unsupported render profile: {profile}")))?;
        self.get_canvaskit_replay_plan_with_profile_native(page_num, mode, profile)
            .map_err(|error| error.into())
    }

    /// 문서 전체의 bounded CanvasKit direct replay capability를 compact JSON으로 반환한다.
    #[wasm_bindgen(js_name = getCanvasKitDocumentPreflight)]
    pub fn get_canvaskit_document_preflight(
        &self,
        mode: &str,
        profile: &str,
    ) -> Result<String, JsValue> {
        let profile = crate::paint::RenderProfile::parse(profile)
            .ok_or_else(|| JsValue::from_str(&format!("unsupported render profile: {profile}")))?;
        self.get_canvaskit_document_preflight_native(mode, profile)
            .map_err(|error| error.into())
    }

    /// 페이지 overlay 이미지 정보만 JSON 문자열로 반환한다.
    #[wasm_bindgen(js_name = getPageOverlayImages)]
    pub fn get_page_overlay_images(&self, page_num: u32) -> Result<String, JsValue> {
        render_patch_boundary::get_page_overlay_images(self, page_num)
    }

    /// 페이지가 그리는 그림들의 신원 키만 작은 JSON 으로 반환한다 (Task #3315).
    #[wasm_bindgen(js_name = getPageSourceImageKeys)]
    pub fn get_page_source_image_keys(&self, page_num: u32) -> Result<String, JsValue> {
        self.get_page_source_image_keys_native(page_num)
            .map_err(|e| e.into())
    }

    /// 본문(flow) 그림의 배치 정보만 작은 JSON 으로 반환한다 (Task #3315).
    ///
    /// 전체 레이어 트리를 받아 flow 그림을 걸러내던 studio 경로를 대체한다. 바이트는 빠져
    /// 있고 `sourceImageKey` 로 `getSourceImageBytes` 를 부르면 된다.
    #[wasm_bindgen(js_name = getPageFlowImageOps)]
    pub fn get_page_flow_image_ops(&self, page_num: u32) -> Result<String, JsValue> {
        render_patch_boundary::get_page_flow_image_ops(self, page_num)
    }

    /// 그림 신원 키로 바이트를 Uint8Array 로 반환한다 (Task #3315).
    ///
    /// `getPageLayerTreeWithProfile(page, profile, true)` 로 base64 를 생략했을 때 바이트를
    /// 받는 경로다. mime 은 레이어 트리의 그림 op 이 계속 싣고 있으므로 여기서 되풀이하지
    /// 않는다.
    ///
    /// 키를 풀 수 없으면 던진다 — 세대가 바뀐 낡은 키이거나 없는 그림이다. 호출부는 잡아서
    /// 레이어 트리를 다시 받는 쪽으로 되돌아가면 된다.
    #[wasm_bindgen(js_name = getSourceImageBytes)]
    pub fn get_source_image_bytes(&self, key: &str) -> Result<Vec<u8>, JsValue> {
        match self.get_source_image_bytes_native(key) {
            Some((_mime, bytes)) => Ok(bytes),
            None => Err(JsValue::from_str(&format!(
                "unresolvable source image key: {key}"
            ))),
        }
    }

    /// Portable font resource key로 exact source bytes를 Uint8Array로 반환한다 (Task #4969).
    ///
    /// `getPageLayerTreeWithProfile(page, profile, imageMode, true)`의 opt-in 경로다.
    /// key가 현재 document generation의 registry source와 정확히 일치하지 않으면 던진다.
    #[wasm_bindgen(js_name = getSourceFontBytes)]
    pub fn get_source_font_bytes(&self, key: &str) -> Result<Vec<u8>, JsValue> {
        self.get_source_font_bytes_native(key)
            .ok_or_else(|| JsValue::from_str(&format!("unresolvable source font key: {key}")))
    }

    /// 페이지 정보를 JSON 문자열로 반환한다.
    #[wasm_bindgen(js_name = getPageInfo)]
    pub fn get_page_info(&self, page_num: u32) -> Result<String, JsValue> {
        self.get_page_info_native(page_num).map_err(|e| e.into())
    }

    /// 구역의 용지 설정(PageDef)을 HWPUNIT 원본값으로 반환한다.
    #[wasm_bindgen(js_name = getPageDef)]
    pub fn get_page_def(&self, section_idx: u32) -> Result<String, JsValue> {
        self.get_page_def_native(section_idx as usize)
            .map_err(|e| e.into())
    }

    /// 구역의 용지 설정(PageDef)을 변경하고 재페이지네이션한다.
    #[wasm_bindgen(js_name = setPageDef)]
    pub fn set_page_def(&mut self, section_idx: u32, json: &str) -> Result<String, JsValue> {
        self.set_page_def_native(section_idx as usize, json)
            .map_err(|e| e.into())
    }

    /// 구역 정의(SectionDef)를 JSON으로 반환한다.
    #[wasm_bindgen(js_name = getSectionDef)]
    pub fn get_section_def(&self, section_idx: u32) -> Result<String, JsValue> {
        self.get_section_def_native(section_idx as usize)
            .map_err(|e| e.into())
    }

    /// 구역 정의(SectionDef)를 변경하고 재페이지네이션한다.
    ///
    /// 원고지 키: `lineGrid`·`charGrid`(줄·글자 격자, HWPUNIT, 0은 끔), `wonggojiFormat`(원고지 정서법).
    /// 셋이 모두 켜진 구역은 글 문단을 칸에 맞춰 다시 짠다.
    #[wasm_bindgen(js_name = setSectionDef)]
    pub fn set_section_def(&mut self, section_idx: u32, json: &str) -> Result<String, JsValue> {
        self.set_section_def_native(section_idx as usize, json)
            .map_err(|e| e.into())
    }

    /// 모든 구역의 SectionDef를 일괄 변경하고 재페이지네이션한다.
    #[wasm_bindgen(js_name = setSectionDefAll)]
    pub fn set_section_def_all(&mut self, json: &str) -> Result<String, JsValue> {
        self.set_section_def_all_native(json).map_err(|e| e.into())
    }

    /// 구역의 쪽 테두리/배경 설정을 JSON으로 반환한다.
    #[wasm_bindgen(js_name = getPageBorderFill)]
    pub fn get_page_border_fill(&self, section_idx: u32) -> Result<String, JsValue> {
        self.get_page_border_fill_native(section_idx as usize)
            .map_err(|e| e.into())
    }

    /// 구역의 쪽 테두리/배경 설정을 변경하고 재페이지네이션한다.
    #[wasm_bindgen(js_name = setPageBorderFill)]
    pub fn set_page_border_fill(
        &mut self,
        section_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.set_page_border_fill_native(section_idx as usize, json)
            .map_err(|e| e.into())
    }

    /// 현재 구역의 다단 설정을 JSON으로 반환한다.
    #[wasm_bindgen(js_name = getColumnDef)]
    pub fn get_column_def(&self, section_idx: u32) -> Result<String, JsValue> {
        let sec = self
            .core
            .document
            .sections
            .get(section_idx as usize)
            .ok_or_else(|| JsValue::from_str("구역 인덱스 범위 초과"))?;
        let col_def = HwpDocument::find_initial_column_def(&sec.paragraphs);
        let col_type = match col_def.column_type {
            crate::model::page::ColumnType::Normal => 0,
            crate::model::page::ColumnType::Distribute => 1,
            crate::model::page::ColumnType::Parallel => 2,
        };
        Ok(format!(
            "{{\"columnCount\":{},\"columnType\":{},\"sameWidth\":{},\"spacing\":{}}}",
            col_def.column_count, col_type, col_def.same_width, col_def.spacing,
        ))
    }

    /// 문서 정보를 JSON 문자열로 반환한다.
    #[wasm_bindgen(js_name = getDocumentInfo)]
    pub fn get_document_info(&self) -> String {
        self.core.get_document_info()
    }

    /// 특정 페이지의 텍스트 레이아웃 정보를 JSON 문자열로 반환한다.
    ///
    /// 각 TextRun의 위치, 모델 `text`, 모델 경계 `charX`와 `charStart`를 포함한다.
    /// 표시 치환이 있는 런에는 `displayText`와 `displayCharX`가 추가된다.
    /// 두 X 배열은 런 원점 기준 Unicode scalar 경계(N+1개)이며,
    /// 표시 인덱스는 선택·커서·편집 오프셋으로 사용할 수 없다 (#7909).
    #[wasm_bindgen(js_name = getPageTextLayout)]
    pub fn get_page_text_layout(&self, page_num: u32) -> Result<String, JsValue> {
        self.get_page_text_layout_native(page_num)
            .map_err(|e| e.into())
    }

    /// 컨트롤(표, 이미지 등) 레이아웃 정보를 반환한다.
    #[wasm_bindgen(js_name = getPageControlLayout)]
    pub fn get_page_control_layout(&self, page_num: u32) -> Result<String, JsValue> {
        self.get_page_control_layout_native(page_num)
            .map_err(|e| e.into())
    }

    /// DPI를 설정한다.
    #[wasm_bindgen(js_name = setDpi)]
    pub fn set_dpi(&mut self, dpi: f64) {
        self.core.set_dpi(dpi);
    }

    /// 파일 이름을 설정한다 (머리말/꼬리말 필드 치환용).
    #[wasm_bindgen(js_name = setFileName)]
    pub fn set_file_name(&mut self, name: &str) {
        if self.core.file_name != name {
            self.core.file_name = name.to_string();
            self.core.invalidate_page_tree_cache();
        }
    }

    /// 현재 DPI를 반환한다.
    #[wasm_bindgen(js_name = getDpi)]
    pub fn get_dpi(&self) -> f64 {
        self.dpi
    }

    /// 대체 폰트 경로를 설정한다.
    #[wasm_bindgen(js_name = setFallbackFont)]
    pub fn set_fallback_font(&mut self, path: &str) {
        self.fallback_font = path.to_string();
    }

    /// 현재 대체 폰트 경로를 반환한다.
    #[wasm_bindgen(js_name = getFallbackFont)]
    pub fn get_fallback_font(&self) -> String {
        self.fallback_font.clone()
    }

    /// 문단에 텍스트를 삽입한다.
    ///
    /// 삽입 후 구역을 재구성하고 재페이지네이션한다.
    /// 반환값: JSON `{"ok":true,"charOffset":<new_offset>}`
    #[wasm_bindgen(js_name = insertText)]
    pub fn insert_text(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        self.insert_text_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            text,
        )
        .map_err(|e| e.into())
    }

    /// 논리적 오프셋으로 텍스트를 삽입한다.
    ///
    /// logical_offset: 텍스트 문자 + 인라인 컨트롤을 각각 1로 세는 위치.
    /// 예: "abc[표]XYZ" → a(0) b(1) c(2) [표](3) X(4) Y(5) Z(6)
    /// logical_offset=4이면 표 뒤의 X 앞에 삽입.
    /// 반환값: JSON `{"ok":true,"logicalOffset":<new_logical_offset>}`
    #[wasm_bindgen(js_name = insertTextLogical)]
    pub fn insert_text_logical(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        logical_offset: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        let sec = section_idx as usize;
        let pi = para_idx as usize;
        if sec >= self.document.sections.len() || pi >= self.document.sections[sec].paragraphs.len()
        {
            return Err(JsValue::from_str("인덱스 범위 초과"));
        }
        let (text_offset, after_control) = crate::document_core::helpers::logical_to_text_offset(
            &self.document.sections[sec].paragraphs[pi],
            logical_offset as usize,
        );
        self.insert_text_at_caret_native(sec, pi, text_offset, after_control, text)?;
        // 삽입 후 논리적 오프셋 반환
        let new_text_offset = text_offset + text.chars().count();
        let new_logical = crate::document_core::helpers::text_to_logical_offset(
            &self.document.sections[sec].paragraphs[pi],
            new_text_offset,
        );
        Ok(format!("{{\"ok\":true,\"logicalOffset\":{}}}", new_logical))
    }

    /// 문단의 논리적 길이를 반환한다 (텍스트 문자 + 인라인 컨트롤 수).
    #[wasm_bindgen(js_name = getLogicalLength)]
    pub fn get_logical_length(&self, section_idx: u32, para_idx: u32) -> Result<u32, JsValue> {
        let sec = section_idx as usize;
        let pi = para_idx as usize;
        if sec >= self.document.sections.len() || pi >= self.document.sections[sec].paragraphs.len()
        {
            return Err(JsValue::from_str("인덱스 범위 초과"));
        }
        Ok(crate::document_core::helpers::logical_paragraph_length(
            &self.document.sections[sec].paragraphs[pi],
        ) as u32)
    }

    /// 논리적 오프셋 → 텍스트 오프셋 변환.
    #[wasm_bindgen(js_name = logicalToTextOffset)]
    pub fn logical_to_text_offset(
        &self,
        section_idx: u32,
        para_idx: u32,
        logical_offset: u32,
    ) -> Result<u32, JsValue> {
        let sec = section_idx as usize;
        let pi = para_idx as usize;
        if sec >= self.document.sections.len() || pi >= self.document.sections[sec].paragraphs.len()
        {
            return Err(JsValue::from_str("인덱스 범위 초과"));
        }
        let (text_offset, _) = crate::document_core::helpers::logical_to_text_offset(
            &self.document.sections[sec].paragraphs[pi],
            logical_offset as usize,
        );
        Ok(text_offset as u32)
    }

    /// 텍스트 오프셋 → 논리적 오프셋 변환.
    #[wasm_bindgen(js_name = textToLogicalOffset)]
    pub fn text_to_logical_offset(
        &self,
        section_idx: u32,
        para_idx: u32,
        text_offset: u32,
    ) -> Result<u32, JsValue> {
        let sec = section_idx as usize;
        let pi = para_idx as usize;
        if sec >= self.document.sections.len() || pi >= self.document.sections[sec].paragraphs.len()
        {
            return Err(JsValue::from_str("인덱스 범위 초과"));
        }
        Ok(crate::document_core::helpers::text_to_logical_offset(
            &self.document.sections[sec].paragraphs[pi],
            text_offset as usize,
        ) as u32)
    }

    /// 문단에서 텍스트를 삭제한다.
    ///
    /// 삭제 후 구역을 재구성하고 재페이지네이션한다.
    /// 반환값: JSON `{"ok":true,"charOffset":<offset_after_delete>}`
    #[wasm_bindgen(js_name = deleteText)]
    pub fn delete_text(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        self.delete_text_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = replaceBodyTextLocal)]
    pub fn replace_body_text_local(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        delete_count: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        self.replace_body_text_local_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            delete_count as usize,
            text,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 내부 문단에 텍스트를 삽입한다.
    ///
    /// 반환값: JSON `{"ok":true,"charOffset":<new_offset>}`
    #[wasm_bindgen(js_name = insertTextInCell)]
    pub fn insert_text_in_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        self.insert_text_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            text,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 내부 문단에 텍스트를 삽입하되 전체 페이지네이션은 호출자가 지연한다.
    ///
    /// Studio의 page-local 단일 입력처럼 현재 페이지를 먼저 갱신하고 idle 시점에
    /// 전체 페이지네이션을 한 번만 수행하는 경로에서 사용한다.
    /// 결과 JSON은 `charOffset`과 상대 cell-flow 변화 신호 `cellFlowChanged`를 포함한다.
    #[wasm_bindgen(js_name = insertTextInCellDeferredPagination)]
    pub fn insert_text_in_cell_deferred_pagination(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        self.insert_text_in_cell_native_deferred_pagination(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            text,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 내부 문단에서 텍스트를 삭제하되 전체 페이지네이션은 호출자가 지연한다.
    ///
    /// 결과 JSON은 `charOffset`과 상대 cell-flow 변화 신호 `cellFlowChanged`를 포함한다.
    #[wasm_bindgen(js_name = deleteTextInCellDeferredPagination)]
    pub fn delete_text_in_cell_deferred_pagination(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        self.delete_text_in_cell_native_deferred_pagination(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 내부의 짧은 IME 조합 문자열을 원자적으로 교체하고 전체 페이지네이션은 지연한다.
    #[wasm_bindgen(js_name = replaceTextInCellDeferredPagination)]
    pub fn replace_text_in_cell_deferred_pagination(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        delete_count: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        self.replace_text_in_cell_native_deferred_pagination(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            delete_count as usize,
            text,
        )
        .map_err(|e| e.into())
    }

    /// 대형 표 continuation shadow job을 시작한다. 공개 페이지는 완료 전까지 유지된다.
    #[wasm_bindgen(js_name = beginDeferredPagination)]
    pub fn begin_deferred_pagination(&mut self, fragment_budget: u32) -> Result<String, JsValue> {
        Ok(deferred_pagination_result_json(
            self.core
                .begin_deferred_pagination((fragment_budget as usize).max(1)),
        ))
    }

    /// 대형 표 continuation을 fragment budget만큼 전진한다.
    #[wasm_bindgen(js_name = stepDeferredPagination)]
    pub fn step_deferred_pagination(&mut self, fragment_budget: u32) -> Result<String, JsValue> {
        Ok(deferred_pagination_result_json(
            self.core
                .step_deferred_pagination((fragment_budget as usize).max(1)),
        ))
    }

    #[wasm_bindgen(js_name = cancelDeferredPagination)]
    pub fn cancel_deferred_pagination(&mut self) -> bool {
        self.core.cancel_deferred_pagination()
    }

    /// 지연된 페이지네이션을 동기 barrier로 flush하고 최신 페이지 수를 반환한다.
    #[wasm_bindgen(js_name = flushDeferredPagination)]
    pub fn flush_deferred_pagination(&mut self) -> Result<String, JsValue> {
        Ok(deferred_pagination_result_json(
            self.core.flush_deferred_pagination(),
        ))
    }

    /// `insertTextInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// charOffset?, text: string }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = insertTextInCellEx)]
    pub fn insert_text_in_cell_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_str, json_u32};
        self.insert_text_in_cell_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            &json_str(options_json, "text").unwrap_or_default(),
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 내부 문단에서 텍스트를 삭제한다.
    ///
    /// 반환값: JSON `{"ok":true,"charOffset":<offset_after_delete>}`
    #[wasm_bindgen(js_name = deleteTextInCell)]
    pub fn delete_text_in_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        self.delete_text_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    /// `deleteTextInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// charOffset?, count }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = deleteTextInCellEx)]
    pub fn delete_text_in_cell_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::json_u32;
        self.delete_text_in_cell_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            json_u32(options_json, "count").unwrap_or(0) as usize,
        )
        .map_err(|e| e.into())
    }

    /// 셀 내부 문단을 분할한다 (셀 내 Enter 키).
    ///
    /// 반환값: JSON `{"ok":true,"cellParaIndex":<new_idx>,"charOffset":0}`
    ///
    /// `removed_para_meta` 는 병합 undo 가 되돌려주는 값이다 — 본문 `splitParagraph`
    /// 와 같은 규약이다 (Task #2342).
    #[wasm_bindgen(js_name = splitParagraphInCell)]
    pub fn split_paragraph_in_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        removed_para_meta: Option<String>,
    ) -> Result<String, JsValue> {
        self.split_paragraph_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            parse_removed_para_meta(removed_para_meta)?,
        )
        .map_err(|e| e.into())
    }

    /// 셀 내부 문단을 이전 문단에 병합한다 (셀 내 Backspace at start).
    ///
    /// 반환값: JSON `{"ok":true,"cellParaIndex":<prev_idx>,"charOffset":<merge_point>}`
    #[wasm_bindgen(js_name = mergeParagraphInCell)]
    pub fn merge_paragraph_in_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
    ) -> Result<String, JsValue> {
        self.merge_paragraph_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
        )
        .map_err(|e| e.into())
    }

    // ─── 중첩 표 path 기반 편집 API ──────────────────────────

    #[wasm_bindgen(js_name = insertTextInCellByPath)]
    pub fn insert_text_in_cell_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.insert_text_in_cell_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
            text,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = deleteTextInCellByPath)]
    pub fn delete_text_in_cell_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.delete_text_in_cell_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = deleteRangeInCellByPath)]
    #[allow(clippy::too_many_arguments)]
    pub fn delete_range_in_cell_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        start_para: u32,
        start_offset: u32,
        end_para: u32,
        end_offset: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.delete_range_in_cell_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            start_para as usize,
            start_offset as usize,
            end_para as usize,
            end_offset as usize,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = splitParagraphInCellByPath)]
    pub fn split_paragraph_in_cell_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
        removed_para_meta: Option<String>,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.split_paragraph_in_cell_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
            parse_removed_para_meta(removed_para_meta)?,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = mergeParagraphInCellByPath)]
    pub fn merge_paragraph_in_cell_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.merge_paragraph_in_cell_by_path(section_idx as usize, parent_para_idx as usize, &path)
            .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = getTextInCellByPath)]
    pub fn get_text_in_cell_by_path_api(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.get_text_in_cell_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    // ─── 머리말/꼬리말 API ──────────────────────────────────

    /// 머리말/꼬리말 조회
    ///
    /// 반환: JSON `{"ok":true,"exists":true/false,...}`
    #[wasm_bindgen(js_name = getHeaderFooter)]
    pub fn get_header_footer(
        &self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
    ) -> Result<String, JsValue> {
        self.get_header_footer_native(section_idx as usize, is_header, apply_to)
            .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 생성 (빈 문단 1개 포함)
    ///
    /// 반환: JSON `{"ok":true,"kind":"header/footer","applyTo":N,...}`
    #[wasm_bindgen(js_name = createHeaderFooter)]
    pub fn create_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
    ) -> Result<String, JsValue> {
        self.create_header_footer_native(section_idx as usize, is_header, apply_to)
            .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 내 텍스트 삽입
    ///
    /// 반환: JSON `{"ok":true,"charOffset":<new_offset>}`
    #[wasm_bindgen(js_name = insertTextInHeaderFooter)]
    pub fn insert_text_in_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: u32,
        char_offset: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        self.insert_text_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            hf_para_idx as usize,
            char_offset as usize,
            text,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 내 텍스트 삭제
    ///
    /// 반환: JSON `{"ok":true,"charOffset":<offset>}`
    #[wasm_bindgen(js_name = deleteTextInHeaderFooter)]
    pub fn delete_text_in_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: u32,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        self.delete_text_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            hf_para_idx as usize,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 내 문단 분할 (Enter 키)
    ///
    /// 반환: JSON `{"ok":true,"hfParaIndex":<new_idx>,"charOffset":0}`
    #[wasm_bindgen(js_name = splitParagraphInHeaderFooter)]
    pub fn split_paragraph_in_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: u32,
        char_offset: u32,
        removed_para_meta: Option<String>,
    ) -> Result<String, JsValue> {
        self.split_paragraph_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            hf_para_idx as usize,
            char_offset as usize,
            parse_removed_para_meta(removed_para_meta)?,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 내 문단 병합 (Backspace at start)
    ///
    /// 반환: JSON `{"ok":true,"hfParaIndex":<prev_idx>,"charOffset":<merge_point>}`
    #[wasm_bindgen(js_name = mergeParagraphInHeaderFooter)]
    pub fn merge_paragraph_in_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: u32,
    ) -> Result<String, JsValue> {
        self.merge_paragraph_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            hf_para_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 문단 정보 조회
    ///
    /// 반환: JSON `{"ok":true,"paraCount":N,"charCount":N,"text":"..."}`
    #[wasm_bindgen(js_name = getHeaderFooterParaInfo)]
    pub fn get_header_footer_para_info(
        &self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_header_footer_para_info_native(
            section_idx as usize,
            is_header,
            apply_to,
            hf_para_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 선택 범위를 평문으로 원자 치환한다.
    #[wasm_bindgen(js_name = replaceRangeInHeaderFooter)]
    #[allow(clippy::too_many_arguments)]
    pub fn replace_range_in_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        start_hf_para_idx: u32,
        start_char_offset: u32,
        end_hf_para_idx: u32,
        end_char_offset: u32,
        replacement_text: &str,
    ) -> Result<String, JsValue> {
        self.replace_range_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            start_hf_para_idx as usize,
            start_char_offset as usize,
            end_hf_para_idx as usize,
            end_char_offset as usize,
            replacement_text,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 선택 범위를 내부 클립보드에 복사한다.
    #[wasm_bindgen(js_name = copySelectionInHeaderFooter)]
    #[allow(clippy::too_many_arguments)]
    pub fn copy_selection_in_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        start_hf_para_idx: u32,
        start_char_offset: u32,
        end_hf_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.copy_selection_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            start_hf_para_idx as usize,
            start_char_offset as usize,
            end_hf_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 캐럿 위치의 글자 속성을 조회한다.
    #[wasm_bindgen(js_name = getCharPropertiesInHeaderFooter)]
    pub fn get_char_properties_in_header_footer(
        &self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_char_properties_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            hf_para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 선택 범위에 글자 서식을 적용한다.
    #[wasm_bindgen(js_name = applyCharFormatInHeaderFooter)]
    #[allow(clippy::too_many_arguments)]
    pub fn apply_char_format_in_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        start_hf_para_idx: u32,
        start_char_offset: u32,
        end_hf_para_idx: u32,
        end_char_offset: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_char_format_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            start_hf_para_idx as usize,
            start_char_offset as usize,
            end_hf_para_idx as usize,
            end_char_offset as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// 표를 지정 행에서 두 개로 나눈다 (한컴 [표-표 나누기]).
    ///
    /// 반환값: JSON `{"ok":true,"frontRows":<N>,"backParaIdx":<P>}`
    #[wasm_bindgen(js_name = splitTable)]
    pub fn split_table(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        at_row: u32,
    ) -> Result<String, JsValue> {
        let at_row = row_index_from_u32(at_row)?;
        self.split_table_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            at_row,
        )
        .map_err(|e| e.into())
    }

    /// 현재 표에 다음 표를 이어 붙인다 (한컴 [표-표 붙이기]).
    ///
    /// 반환값: JSON `{"ok":true,"rowCount":<N>}`
    #[wasm_bindgen(js_name = mergeTableWithNext)]
    pub fn merge_table_with_next(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.merge_table_with_next_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표에 행을 삽입한다.
    ///
    /// 반환값: JSON `{"ok":true,"rowCount":<N>,"colCount":<M>}`
    #[wasm_bindgen(js_name = insertTableRow)]
    pub fn insert_table_row(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        row_idx: u32,
        below: bool,
    ) -> Result<String, JsValue> {
        self.insert_table_row_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            row_idx as u16,
            below,
        )
        .map_err(|e| e.into())
    }

    /// 표에 열을 삽입한다.
    ///
    /// 반환값: JSON `{"ok":true,"rowCount":<N>,"colCount":<M>}`
    #[wasm_bindgen(js_name = insertTableColumn)]
    pub fn insert_table_column(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        col_idx: u32,
        right: bool,
    ) -> Result<String, JsValue> {
        self.insert_table_column_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            col_idx as u16,
            right,
        )
        .map_err(|e| e.into())
    }

    /// 표에서 행을 삭제한다.
    ///
    /// 반환값: JSON `{"ok":true,"rowCount":<N>,"colCount":<M>}`
    #[wasm_bindgen(js_name = deleteTableRow)]
    pub fn delete_table_row(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        row_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_table_row_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            row_idx as u16,
        )
        .map_err(|e| e.into())
    }

    /// 표에서 열을 삭제한다.
    ///
    /// 반환값: JSON `{"ok":true,"rowCount":<N>,"colCount":<M>}`
    #[wasm_bindgen(js_name = deleteTableColumn)]
    pub fn delete_table_column(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        col_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_table_column_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            col_idx as u16,
        )
        .map_err(|e| e.into())
    }

    /// 표의 셀을 병합한다.
    ///
    /// 반환값: JSON `{"ok":true,"cellCount":<N>}`
    #[wasm_bindgen(js_name = mergeTableCells)]
    pub fn merge_table_cells(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        start_row: u32,
        start_col: u32,
        end_row: u32,
        end_col: u32,
    ) -> Result<String, JsValue> {
        self.merge_table_cells_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            start_row as u16,
            start_col as u16,
            end_row as u16,
            end_col as u16,
        )
        .map_err(|e| e.into())
    }

    /// `mergeTableCells` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, startRow, startCol,
    /// endRow, endCol }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = mergeTableCellsEx)]
    pub fn merge_table_cells_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::json_u32;
        self.merge_table_cells_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startRow").unwrap_or(0) as u16,
            json_u32(options_json, "startCol").unwrap_or(0) as u16,
            json_u32(options_json, "endRow").unwrap_or(0) as u16,
            json_u32(options_json, "endCol").unwrap_or(0) as u16,
        )
        .map_err(|e| e.into())
    }

    /// 병합된 셀을 나눈다 (split).
    ///
    /// 반환값: JSON `{"ok":true,"cellCount":<N>}`
    #[wasm_bindgen(js_name = splitTableCell)]
    pub fn split_table_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        row: u32,
        col: u32,
    ) -> Result<String, JsValue> {
        self.split_table_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            row as u16,
            col as u16,
        )
        .map_err(|e| e.into())
    }

    /// 셀을 N줄 × M칸으로 분할한다.
    ///
    /// 반환값: JSON `{"ok":true,"cellCount":<N>}`
    #[wasm_bindgen(js_name = splitTableCellInto)]
    pub fn split_table_cell_into(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        row: u32,
        col: u32,
        n_rows: u32,
        m_cols: u32,
        equal_row_height: bool,
        merge_first: bool,
    ) -> Result<String, JsValue> {
        self.split_table_cell_into_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            row as u16,
            col as u16,
            n_rows as u16,
            m_cols as u16,
            equal_row_height,
            merge_first,
        )
        .map_err(|e| e.into())
    }

    /// `splitTableCellInto` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, row, col, nRows, mCols,
    /// equalRowHeight?, mergeFirst? }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = splitTableCellIntoEx)]
    pub fn split_table_cell_into_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_bool, json_u32};
        self.split_table_cell_into_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "row").unwrap_or(0) as u16,
            json_u32(options_json, "col").unwrap_or(0) as u16,
            json_u32(options_json, "nRows").unwrap_or(1) as u16,
            json_u32(options_json, "mCols").unwrap_or(1) as u16,
            json_bool(options_json, "equalRowHeight").unwrap_or(false),
            json_bool(options_json, "mergeFirst").unwrap_or(false),
        )
        .map_err(|e| e.into())
    }

    /// 범위 내 셀들을 각각 N줄 × M칸으로 분할한다.
    ///
    /// 반환값: JSON `{"ok":true,"cellCount":<N>}`
    #[wasm_bindgen(js_name = splitTableCellsInRange)]
    pub fn split_table_cells_in_range(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        start_row: u32,
        start_col: u32,
        end_row: u32,
        end_col: u32,
        n_rows: u32,
        m_cols: u32,
        equal_row_height: bool,
    ) -> Result<String, JsValue> {
        self.split_table_cells_in_range_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            start_row as u16,
            start_col as u16,
            end_row as u16,
            end_col as u16,
            n_rows as u16,
            m_cols as u16,
            equal_row_height,
        )
        .map_err(|e| e.into())
    }

    /// `splitTableCellsInRange` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, startRow, startCol,
    /// endRow, endCol, nRows, mCols, equalRowHeight? }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = splitTableCellsInRangeEx)]
    pub fn split_table_cells_in_range_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_bool, json_u32};
        self.split_table_cells_in_range_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startRow").unwrap_or(0) as u16,
            json_u32(options_json, "startCol").unwrap_or(0) as u16,
            json_u32(options_json, "endRow").unwrap_or(0) as u16,
            json_u32(options_json, "endCol").unwrap_or(0) as u16,
            json_u32(options_json, "nRows").unwrap_or(1) as u16,
            json_u32(options_json, "mCols").unwrap_or(1) as u16,
            json_bool(options_json, "equalRowHeight").unwrap_or(false),
        )
        .map_err(|e| e.into())
    }

    /// 선택된 표 셀 범위를 행/열 바꿈 복사용 내부 버퍼에 저장한다.
    ///
    /// 반환값: JSON `{"ok":true,"sourceRows":N,"sourceCols":N,"targetRows":N,"targetCols":N}`
    #[wasm_bindgen(js_name = copyTableCellsTransposed)]
    pub fn copy_table_cells_transposed(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        start_row: u32,
        start_col: u32,
        end_row: u32,
        end_col: u32,
    ) -> Result<String, JsValue> {
        self.copy_table_cells_transposed_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            start_row as u16,
            start_col as u16,
            end_row as u16,
            end_col as u16,
        )
        .map_err(|e| e.into())
    }

    /// 행/열 바꿈 복사 버퍼를 대상 시작 셀부터 붙여넣는다.
    ///
    /// 반환값: JSON `{"ok":true,"sourceRows":N,"sourceCols":N,"targetRows":N,"targetCols":N}`
    #[wasm_bindgen(js_name = pasteTableCellsTransposed)]
    pub fn paste_table_cells_transposed(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        start_row: u32,
        start_col: u32,
    ) -> Result<String, JsValue> {
        self.paste_table_cells_transposed_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            start_row as u16,
            start_col as u16,
        )
        .map_err(|e| e.into())
    }

    /// 선택된 전체 표를 제자리에서 전치한다.
    ///
    /// 반환값: JSON `{"ok":true,"sourceRows":N,"sourceCols":N,"targetRows":N,"targetCols":N}`
    #[wasm_bindgen(js_name = transposeTableCellsInPlace)]
    pub fn transpose_table_cells_in_place(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.transpose_table_cells_in_place_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 행/열 바꿈 복사 버퍼를 커서 위치에 새 표로 생성해 붙여넣는다.
    ///
    /// 반환값: JSON `{"ok":true,"paraIdx":N,"controlIdx":N,"sourceRows":N,"sourceCols":N,"targetRows":N,"targetCols":N}`
    #[wasm_bindgen(js_name = pasteTableCellsTransposedAsTable)]
    pub fn paste_table_cells_transposed_as_table(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.paste_table_cells_transposed_as_new_table_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 행/열 바꿈 복사 버퍼 보유 여부를 반환한다.
    #[wasm_bindgen(js_name = hasTableTransposeClipboard)]
    pub fn has_table_transpose_clipboard(&self) -> bool {
        self.has_table_transpose_clipboard_native()
    }

    /// 캐럿 위치에서 문단을 분할한다 (Enter 키).
    ///
    /// char_offset 이후의 텍스트가 새 문단으로 이동한다.
    /// 반환값: JSON `{"ok":true,"paraIdx":<new_para_idx>,"charOffset":0}`
    #[wasm_bindgen(js_name = splitParagraph)]
    pub fn split_paragraph(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        removed_para_meta: Option<String>,
    ) -> Result<String, JsValue> {
        self.split_paragraph_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            parse_removed_para_meta(removed_para_meta)?,
        )
        .map_err(|e| e.into())
    }

    /// 강제 쪽 나누기 삽입 (Ctrl+Enter)
    #[wasm_bindgen(js_name = insertPageBreak)]
    pub fn insert_page_break(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.insert_page_break_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 단 나누기 삽입 (Ctrl+Shift+Enter)
    #[wasm_bindgen(js_name = insertColumnBreak)]
    pub fn insert_column_break(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.insert_column_break_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 새 번호 지정 컨트롤 삽입 (쪽 > 새 번호로 시작)
    #[wasm_bindgen(js_name = insertNewNumber)]
    pub fn insert_new_number(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        start_num: u32,
    ) -> Result<String, JsValue> {
        if start_num == 0 || start_num > 65535 {
            return Err(JsValue::from_str("start_num must be 1~65535"));
        }
        self.insert_new_number_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            start_num as u16,
        )
        .map_err(|e| e.into())
    }

    /// 다단 설정 변경
    /// column_type: 0=일반, 1=배분, 2=평행
    /// same_width: 0=다른 너비, 1=같은 너비
    #[wasm_bindgen(js_name = setColumnDef)]
    pub fn set_column_def(
        &mut self,
        section_idx: u32,
        column_count: u32,
        column_type: u32,
        same_width: u32,
        spacing_hu: i32,
    ) -> Result<String, JsValue> {
        self.set_column_def_native(
            section_idx as usize,
            column_count as u16,
            column_type as u8,
            same_width != 0,
            spacing_hu as i16,
        )
        .map_err(|e| e.into())
    }

    /// 현재 문단을 이전 문단에 병합한다 (Backspace at start).
    ///
    /// para_idx의 텍스트가 para_idx-1에 결합되고 para_idx는 삭제된다.
    /// 반환값: JSON `{"ok":true,"paraIdx":<merged_para_idx>,"charOffset":<merge_point>}`
    #[wasm_bindgen(js_name = mergeParagraph)]
    pub fn merge_paragraph(&mut self, section_idx: u32, para_idx: u32) -> Result<String, JsValue> {
        self.merge_paragraph_native(section_idx as usize, para_idx as usize)
            .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = deleteParagraph)]
    pub fn delete_paragraph(&mut self, section_idx: u32, para_idx: u32) -> Result<String, JsValue> {
        self.delete_paragraph_native(section_idx as usize, para_idx as usize)
            .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = insertParagraph)]
    pub fn insert_paragraph(&mut self, section_idx: u32, para_idx: u32) -> Result<String, JsValue> {
        self.insert_paragraph_native(section_idx as usize, para_idx as usize)
            .map_err(|e| e.into())
    }

    // ─── Phase 1: 기본 편집 보조 API ───────────────────────────

    /// 본문 캐럿 자리(`charOffset`은 논리 오프셋)에서 구역을 나눈다 — 한/글 [쪽-구역 나누기].
    /// 새 구역은 앞 구역의 구역 정의와 캐럿 자리의 단 정의를 잇고 새 쪽에서 시작한다.
    ///
    /// 반환: `{"ok":true,"section":<새 구역>,"para":0,"charOffset":0}`
    #[wasm_bindgen(js_name = splitSection)]
    pub fn split_section(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.split_section_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// `sectionIdx` 구역을 앞 구역에 합친다 — 한/글에서 구역 경계를 지울 때와 같다.
    /// 합친 문단은 앞 구역의 모양을 따른다. 두 문단을 잇는 일은 `mergeParagraph`가 한다.
    ///
    /// 반환: `{"ok":true,"section":<앞 구역>,"para":<옮겨 온 첫 문단>}`
    #[wasm_bindgen(js_name = mergeSection)]
    pub fn merge_section(&mut self, section_idx: u32) -> Result<String, JsValue> {
        self.merge_section_native(section_idx as usize)
            .map_err(|e| e.into())
    }

    /// 구역(Section) 수를 반환한다.
    #[wasm_bindgen(js_name = getSectionCount)]
    pub fn get_section_count(&self) -> u32 {
        self.document.sections.len() as u32
    }

    /// 구역 내 문단 수를 반환한다.
    #[wasm_bindgen(js_name = getParagraphCount)]
    pub fn get_paragraph_count(&self, section_idx: u32) -> Result<u32, JsValue> {
        self.get_paragraph_count_native(section_idx as usize)
            .map(|v| v as u32)
            .map_err(|e| e.into())
    }

    /// 문단의 글자 수(char 개수)를 반환한다.
    #[wasm_bindgen(js_name = getParagraphLength)]
    pub fn get_paragraph_length(&self, section_idx: u32, para_idx: u32) -> Result<u32, JsValue> {
        self.get_paragraph_length_native(section_idx as usize, para_idx as usize)
            .map(|v| v as u32)
            .map_err(|e| e.into())
    }

    /// 문단에 텍스트박스가 있는 Shape 컨트롤이 있으면 해당 control_index를 반환한다.
    /// 없으면 -1을 반환한다.
    #[wasm_bindgen(js_name = getTextBoxControlIndex)]
    pub fn get_textbox_control_index(&self, section_idx: u32, para_idx: u32) -> i32 {
        self.get_textbox_control_index_native(section_idx as usize, para_idx as usize)
    }

    /// 문서 트리에서 다음 편집 가능한 컨트롤/본문을 찾는다.
    /// delta=+1(앞), delta=-1(뒤). ctrl_idx=-1이면 본문 텍스트에서 출발.
    #[wasm_bindgen(js_name = findNextEditableControl)]
    pub fn find_next_editable_control(
        &self,
        section_idx: u32,
        para_idx: u32,
        ctrl_idx: i32,
        delta: i32,
    ) -> String {
        self.find_next_editable_control_native(
            section_idx as usize,
            para_idx as usize,
            ctrl_idx,
            delta,
        )
    }

    /// 커서에서 이전 방향으로 가장 가까운 선택 가능 컨트롤을 찾는다 (F11 키).
    #[wasm_bindgen(js_name = findNearestControlBackward)]
    pub fn find_nearest_control_backward(
        &self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> String {
        self.find_nearest_control_backward_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
    }

    /// 현재 위치 이후의 가장 가까운 선택 가능 컨트롤을 찾는다 (Shift+F11).
    #[wasm_bindgen(js_name = findNearestControlForward)]
    pub fn find_nearest_control_forward(
        &self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> String {
        self.find_nearest_control_forward_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
    }

    /// 문단 내 컨트롤의 텍스트 위치 배열을 반환한다.
    #[wasm_bindgen(js_name = getControlTextPositions)]
    pub fn get_control_text_positions(&self, section_idx: u32, para_idx: u32) -> String {
        let sections = &self.document.sections;
        if let Some(sec) = sections.get(section_idx as usize) {
            if let Some(para) = sec.paragraphs.get(para_idx as usize) {
                let positions = crate::document_core::find_control_text_positions(para);
                return format!(
                    "[{}]",
                    positions
                        .iter()
                        .map(|p| p.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );
            }
        }
        "[]".to_string()
    }

    /// 문서 트리 DFS 기반 다음/이전 편집 가능 위치를 반환한다.
    /// context_json: NavContextEntry 배열의 JSON (빈 배열 "[]" = body)
    #[wasm_bindgen(js_name = navigateNextEditable)]
    pub fn navigate_next_editable_wasm(
        &self,
        sec: u32,
        para: u32,
        char_offset: u32,
        delta: i32,
        context_json: &str,
    ) -> String {
        let raw_context = DocumentCore::parse_nav_context(context_json);
        // TypeScript에서 ctrl_text_pos=0으로 전달되므로 실제 값으로 보정
        let context = DocumentCore::fix_context_text_positions(
            &self.core.document.sections,
            sec as usize,
            &raw_context,
        );

        // 오버플로우 링크 계산 (캐시됨)
        let overflow_links = self.core.get_overflow_links(sec as usize);

        // 컨텍스트가 있으면 (컨테이너 내부) 렌더링된 마지막 문단 인덱스를 조회
        let max_para = if !context.is_empty() {
            let last = &context[context.len() - 1];
            self.core.last_rendered_para_in_container(
                sec as usize,
                last.parent_para,
                last.ctrl_idx,
                last.cell_idx,
            )
        } else {
            None
        };

        let result = self.core.navigate_next_editable(
            sec as usize,
            para as usize,
            char_offset as usize,
            delta,
            &context,
            max_para,
            &overflow_links,
        );
        DocumentCore::nav_result_to_json(&result)
    }

    /// 문단에서 텍스트 부분 문자열을 반환한다 (Undo용 텍스트 보존).
    #[wasm_bindgen(js_name = getTextRange)]
    pub fn get_text_range(
        &self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        self.get_text_range_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 내 문단 수를 반환한다.
    #[wasm_bindgen(js_name = getCellParagraphCount)]
    pub fn get_cell_paragraph_count(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
    ) -> Result<u32, JsValue> {
        self.get_cell_paragraph_count_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
        )
        .map(|v| v as u32)
        .map_err(|e| e.into())
    }

    /// 표 셀 내 문단의 글자 수를 반환한다.
    #[wasm_bindgen(js_name = getCellParagraphLength)]
    pub fn get_cell_paragraph_length(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
    ) -> Result<u32, JsValue> {
        self.get_cell_paragraph_length_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
        )
        .map(|v| v as u32)
        .map_err(|e| e.into())
    }

    /// 경로 기반: 셀/글상자 내 문단 수를 반환한다 (중첩 표/글상자 지원).
    #[wasm_bindgen(js_name = getCellParagraphCountByPath)]
    pub fn get_cell_paragraph_count_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
    ) -> Result<u32, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        let count = self
            .resolve_container_para_count_by_path(
                section_idx as usize,
                parent_para_idx as usize,
                &path,
            )
            .map_err(|e| -> JsValue { e.into() })?;
        Ok(count as u32)
    }

    /// 경로 기반: 셀 내 문단의 글자 수를 반환한다 (중첩 표 지원).
    #[wasm_bindgen(js_name = getCellParagraphLengthByPath)]
    pub fn get_cell_paragraph_length_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
    ) -> Result<u32, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        let para = self
            .resolve_paragraph_by_path(section_idx as usize, parent_para_idx as usize, &path)
            .map_err(|e| -> JsValue { e.into() })?;
        Ok(para.text.chars().count() as u32)
    }

    /// 표 셀의 텍스트 방향을 반환한다 (0=가로, 1=세로/영문눕힘, 2=세로/영문세움).
    #[wasm_bindgen(js_name = getCellTextDirection)]
    pub fn get_cell_text_direction(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
    ) -> Result<u32, JsValue> {
        let para = self
            .document
            .sections
            .get(section_idx as usize)
            .ok_or_else(|| JsValue::from_str("구역 인덱스 범위 초과"))?
            .paragraphs
            .get(parent_para_idx as usize)
            .ok_or_else(|| JsValue::from_str("문단 인덱스 범위 초과"))?;
        match para.controls.get(control_idx as usize) {
            Some(Control::Table(table)) => {
                let cell = table
                    .cells
                    .get(cell_idx as usize)
                    .ok_or_else(|| JsValue::from_str("셀 인덱스 범위 초과"))?;
                Ok(cell.text_direction as u32)
            }
            _ => Ok(0), // 글상자 등은 가로쓰기
        }
    }

    /// 표 셀 내 문단에서 텍스트 부분 문자열을 반환한다.
    #[wasm_bindgen(js_name = getTextInCell)]
    pub fn get_text_in_cell(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        self.get_text_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    /// `getTextInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// charOffset?, count }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = getTextInCellEx)]
    pub fn get_text_in_cell_ex(&self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::json_u32;
        self.get_text_in_cell_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            json_u32(options_json, "count").unwrap_or(0) as usize,
        )
        .map_err(|e| e.into())
    }

    // ─── Phase 1 끝 ─────────────────────────────────────────

    // ─── Phase 2: 커서/히트 테스트 API ──────────────────────────

    /// 커서 위치의 픽셀 좌표를 반환한다.
    ///
    /// 반환: JSON `{"pageIndex":N,"x":F,"y":F,"height":F}`
    #[wasm_bindgen(js_name = getCursorRect)]
    pub fn get_cursor_rect(
        &self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_cursor_rect_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 줄 경계 offset을 특정 시각 줄 기준으로 해석한 커서 좌표를 반환한다.
    ///
    /// `at_end=false`이면 lineIndex 줄의 시작, `at_end=true`이면 lineIndex 줄의 끝을 반환한다.
    /// soft-wrap 경계에서는 같은 charOffset이 이전 줄 끝과 다음 줄 시작을 동시에 뜻할 수 있어
    /// Home/End가 이 API로 시각 줄 affinity를 명시한다.
    #[wasm_bindgen(js_name = getCursorRectOnLine)]
    pub fn get_cursor_rect_on_line(
        &self,
        section_idx: u32,
        para_idx: u32,
        line_index: u32,
        at_end: bool,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
    ) -> Result<String, JsValue> {
        let cell_ctx = if parent_para_idx == u32::MAX {
            None
        } else {
            Some((
                parent_para_idx as usize,
                control_idx as usize,
                cell_idx as usize,
                cell_para_idx as usize,
            ))
        };
        self.get_cursor_rect_on_line_native(
            section_idx as usize,
            para_idx as usize,
            line_index as usize,
            at_end,
            cell_ctx,
        )
        .map_err(|e| e.into())
    }

    /// 페이지 좌표에서 문서 위치를 찾는다.
    ///
    /// 반환: JSON `{"sectionIndex":N,"paragraphIndex":N,"charOffset":N}`
    #[wasm_bindgen(js_name = hitTest)]
    pub fn hit_test(&self, page_num: u32, x: f64, y: f64) -> Result<String, JsValue> {
        self.hit_test_native(page_num, x, y).map_err(|e| e.into())
    }

    /// 머리말/꼬리말 내 커서 위치의 픽셀 좌표를 반환한다.
    ///
    /// `preview_page_hint`: 편집 정의를 투영할 대표 페이지 힌트. Studio는 구역의 첫 페이지를
    /// 전달한다. 음수이면 호환 경로로 실제 적용 페이지를 앞에서부터 찾는다.
    /// 반환: JSON `{"pageIndex":N,"x":F,"y":F,"height":F}`
    #[wasm_bindgen(js_name = getCursorRectInHeaderFooter)]
    pub fn get_cursor_rect_in_header_footer(
        &self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: u32,
        char_offset: u32,
        preview_page_hint: i32,
    ) -> Result<String, JsValue> {
        self.get_cursor_rect_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            hf_para_idx as usize,
            char_offset as usize,
            preview_page_hint,
        )
        .map_err(|e| e.into())
    }

    /// 요청한 한 페이지의 머리말/꼬리말 선택 사각형을 반환한다.
    #[wasm_bindgen(js_name = getSelectionRectsInHeaderFooter)]
    #[allow(clippy::too_many_arguments)]
    pub fn get_selection_rects_in_header_footer(
        &self,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        page_num: u32,
        start_hf_para_idx: u32,
        start_char_offset: u32,
        end_hf_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_selection_rects_in_header_footer_native(
            section_idx as usize,
            is_header,
            apply_to,
            page_num,
            start_hf_para_idx as usize,
            start_char_offset as usize,
            end_hf_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 페이지 좌표가 머리말/꼬리말 영역에 해당하는지 판별한다.
    ///
    /// 반환: JSON `{"hit":true/false,"isHeader":bool,"sectionIndex":N,"applyTo":N}`
    #[wasm_bindgen(js_name = hitTestHeaderFooter)]
    pub fn hit_test_header_footer(&self, page_num: u32, x: f64, y: f64) -> Result<String, JsValue> {
        self.hit_test_header_footer_native(page_num, x, y)
            .map_err(|e| e.into())
    }

    /// 이 쪽에서 머리말/꼬리말을 편집할 때 대상이 되는 (구역, applyTo) 를 반환한다.
    ///
    /// 좌표 없이 쪽만으로 묻는 경로(툴바 `머리말`/`꼬리말`)용 — 히트테스트와 같은 답을 쓴다.
    /// 반환: JSON `{"ok":true,"sectionIndex":N,"applyTo":N}`
    #[wasm_bindgen(js_name = getHeaderFooterEditTarget)]
    pub fn get_header_footer_edit_target(
        &self,
        page_num: u32,
        is_header: bool,
    ) -> Result<String, JsValue> {
        self.get_header_footer_edit_target_native(page_num, is_header)
            .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 정의가 속한 구역의 대표 편집 페이지(구역 첫 페이지)를 반환한다.
    #[wasm_bindgen(js_name = getHeaderFooterPreviewPage)]
    pub fn get_header_footer_preview_page(&self, section_idx: u32) -> Result<String, JsValue> {
        self.get_header_footer_preview_page_native(section_idx as usize)
            .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 내부 텍스트 히트테스트.
    ///
    /// 편집 모드에서 클릭한 좌표의 문단·문자 위치를 반환.
    /// 반환: JSON `{"hit":true,"paraIndex":N,"charOffset":N,"cursorRect":{...}}`
    #[wasm_bindgen(js_name = hitTestInHeaderFooter)]
    pub fn hit_test_in_header_footer(
        &self,
        page_num: u32,
        is_header: bool,
        x: f64,
        y: f64,
    ) -> Result<String, JsValue> {
        self.hit_test_in_header_footer_native(page_num, is_header, x, y)
            .map_err(|e| e.into())
    }

    /// 대표 편집 페이지에서 명시한 HF target으로 내부 텍스트를 히트테스트한다.
    #[wasm_bindgen(js_name = hitTestInHeaderFooterTarget)]
    pub fn hit_test_in_header_footer_target(
        &self,
        page_num: u32,
        section_idx: u32,
        is_header: bool,
        apply_to: u8,
        x: f64,
        y: f64,
    ) -> Result<String, JsValue> {
        self.hit_test_in_header_footer_target_native(
            page_num,
            section_idx as usize,
            is_header,
            apply_to,
            x,
            y,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 문단의 문단 속성을 조회한다.
    #[wasm_bindgen(js_name = getParaPropertiesInHf)]
    pub fn get_para_properties_in_hf(
        &self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
    ) -> Result<String, JsValue> {
        self.get_para_properties_in_hf_native(section_idx, is_header, apply_to, hf_para_idx)
            .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 문단에 문단 서식을 적용한다.
    #[wasm_bindgen(js_name = applyParaFormatInHf)]
    pub fn apply_para_format_in_hf(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_para_format_in_hf_native(
            section_idx,
            is_header,
            apply_to,
            hf_para_idx,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 문단에 필드 마커를 삽입한다.
    #[wasm_bindgen(js_name = insertFieldInHf)]
    pub fn insert_field_in_hf(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        hf_para_idx: usize,
        char_offset: usize,
        field_type: u8,
    ) -> Result<String, JsValue> {
        self.insert_field_in_hf_native(
            section_idx,
            is_header,
            apply_to,
            hf_para_idx,
            char_offset,
            field_type,
        )
        .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 마당(템플릿)을 적용한다.
    #[wasm_bindgen(js_name = applyHfTemplate)]
    pub fn apply_hf_template(
        &mut self,
        section_idx: usize,
        is_header: bool,
        apply_to: u8,
        template_id: u8,
    ) -> Result<String, JsValue> {
        self.apply_hf_template_native(section_idx, is_header, apply_to, template_id)
            .map_err(|e| e.into())
    }

    /// 머리말/꼬리말을 삭제한다 (컨트롤 자체 제거).
    #[wasm_bindgen(js_name = deleteHeaderFooter)]
    pub fn delete_header_footer(
        &mut self,
        section_idx: u32,
        is_header: bool,
        apply_to: u32,
    ) -> Result<String, JsValue> {
        self.delete_header_footer_native(section_idx as usize, is_header, apply_to as u8)
            .map_err(|e| e.into())
    }

    /// 문서 전체의 머리말/꼬리말 목록을 반환한다.
    #[wasm_bindgen(js_name = getHeaderFooterList)]
    pub fn get_header_footer_list(
        &self,
        current_section_idx: u32,
        current_is_header: bool,
        current_apply_to: u32,
    ) -> Result<String, JsValue> {
        self.get_header_footer_list_native(
            current_section_idx as usize,
            current_is_header,
            current_apply_to as u8,
        )
        .map_err(|e| e.into())
    }

    /// 페이지 단위로 이전/다음 머리말·꼬리말로 이동한다.
    ///
    /// 반환: JSON `{"ok":true,"pageIndex":N,"sectionIdx":N,"isHeader":bool,"applyTo":N}`
    /// 또는 더 이상 이동할 페이지가 없으면 `{"ok":false}`
    #[wasm_bindgen(js_name = navigateHeaderFooterByPage)]
    pub fn navigate_header_footer_by_page(
        &self,
        current_page: u32,
        is_header: bool,
        direction: i32,
    ) -> Result<String, JsValue> {
        self.navigate_header_footer_by_page_native(current_page, is_header, direction)
            .map_err(|e| e.into())
    }

    /// 머리말/꼬리말 감추기를 토글한다 (현재 쪽만).
    ///
    /// 반환: JSON `{"hidden":true/false}` — 토글 후 상태
    #[wasm_bindgen(js_name = toggleHideHeaderFooter)]
    pub fn toggle_hide_header_footer(
        &mut self,
        page_index: u32,
        is_header: bool,
    ) -> Result<String, JsValue> {
        self.toggle_hide_header_footer_native(page_index, is_header)
            .map_err(|e| e.into())
    }

    /// 표 셀 내부 커서 위치의 픽셀 좌표를 반환한다.
    ///
    /// 반환: JSON `{"pageIndex":N,"x":F,"y":F,"height":F}`
    #[wasm_bindgen(js_name = getCursorRectInCell)]
    pub fn get_cursor_rect_in_cell(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_cursor_rect_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    // ─── Phase 3: 커서 이동 API ──────────────────────────────

    /// 문단 내 줄 정보를 반환한다 (커서 수직 이동/Home/End용).
    ///
    /// 반환: JSON `{"lineIndex":N,"lineCount":N,"charStart":N,"charEnd":N}`
    #[wasm_bindgen(js_name = getLineInfo)]
    pub fn get_line_info(
        &self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_line_info_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 내 문단의 줄 정보를 반환한다.
    ///
    /// 반환: JSON `{"lineIndex":N,"lineCount":N,"charStart":N,"charEnd":N}`
    #[wasm_bindgen(js_name = getLineInfoInCell)]
    pub fn get_line_info_in_cell(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_line_info_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 문서에 저장된 캐럿 위치를 반환한다 (문서 로딩 시 캐럿 자동 배치용).
    ///
    /// 반환: JSON `{"sectionIndex":N,"paragraphIndex":N,"charOffset":N}`
    #[wasm_bindgen(js_name = getCaretPosition)]
    pub fn get_caret_position(&self) -> Result<String, JsValue> {
        self.get_caret_position_native().map_err(|e| e.into())
    }

    /// [#4180] 저장 직전 UI 캐럿을 문서 캐럿 메타데이터에 반영한다
    /// (한컴 의미론: 저장 시점 캐럿). 범위 밖 위치는 무시 — 저장을 막지 않는다.
    #[wasm_bindgen(js_name = setCaretPosition)]
    pub fn set_caret_position(&mut self, section_idx: u32, para_idx: u32, char_offset: u32) {
        self.set_caret_position_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        );
    }

    /// 표의 행/열/셀 수를 반환한다.
    ///
    /// 반환: JSON `{"rowCount":N,"colCount":N,"cellCount":N}`
    #[wasm_bindgen(js_name = getTableDimensions)]
    pub fn get_table_dimensions(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_table_dimensions_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀의 행/열/병합 정보를 반환한다.
    ///
    /// 반환: JSON `{"row":N,"col":N,"rowSpan":N,"colSpan":N}`
    #[wasm_bindgen(js_name = getCellInfo)]
    pub fn get_cell_info(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_cell_info_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 셀 속성을 조회한다.
    ///
    /// 반환: JSON `{width, height, paddingLeft, paddingRight, paddingTop, paddingBottom, applyInnerMargin, verticalAlign, textDirection, isHeader, cellProtect, fieldName, editableInForm, ...borderFill}`
    #[wasm_bindgen(js_name = getCellPropertiesByPath)]
    pub fn get_cell_properties_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        cell_idx: u32,
    ) -> Result<String, JsValue> {
        let path = parse_cell_path_arg(cell_path_json)?;
        self.get_cell_properties_by_cell_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            cell_idx as usize,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = getCellProperties)]
    pub fn get_cell_properties(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_cell_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 셀 고유 속성을 조회한다.
    ///
    /// cellzone overlay를 합성하지 않고 셀 자체의 borderFill만 반환한다.
    #[wasm_bindgen(js_name = getCellOwnProperties)]
    pub fn get_cell_own_properties(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_cell_own_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 셀 속성을 수정한다.
    ///
    /// 반환: JSON `{"ok":true,"changes":[{cellIdx,beforeId,afterId}...],
    /// "borderFillLenBefore":N,"docInfoDirtyBefore":bool}` — changes 는 [#5959]
    /// borderFillId 전환 기록(target+이웃)이다.
    #[wasm_bindgen(js_name = setCellProperties)]
    pub fn set_cell_properties(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.set_cell_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            json,
        )
        .map_err(|e| e.into())
    }

    /// 선택 영역을 하나의 셀처럼 취급하는 cellzone 테두리/배경 속성을 적용한다.
    ///
    /// 반환: JSON `{"ok":true,"startRow":...,"borderFillId":...,"zoneBeforeId":...,
    /// "borderFillLenBefore":...,"docInfoDirtyBefore":...}`
    #[wasm_bindgen(js_name = setCellZoneProperties)]
    pub fn set_cell_zone_properties(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        start_row: u32,
        start_col: u32,
        end_row: u32,
        end_col: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.set_cell_zone_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            start_row as u16,
            start_col as u16,
            end_row as u16,
            end_col as u16,
            json,
        )
        .map_err(|e| e.into())
    }

    /// [#5959] 셀/zone border_fill_id 직접 대입 (undo·redo 전용).
    ///
    /// 스타일 테이블을 건드리지 않고 execute 의 변경 기록을 되돌린다.
    /// json: `{"cells":[{"cellIdx":0,"id":3}],"zones":[{"startRow":..,"startCol":..,
    /// "endRow":..,"endCol":..,"id":5}]}` — zone `id` 가 null 이면 그 범위의 zone 을
    /// 제거한다. 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = applyCellBorderFillIds)]
    pub fn apply_cell_border_fill_ids(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.apply_cell_border_fill_ids_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            json,
        )
        .map_err(|e| e.into())
    }

    /// Discard source-border fragments owned by an evicted undo entry.
    #[wasm_bindgen(js_name = discardBorderPaintUndo)]
    pub fn discard_border_paint_undo(&mut self, id: u32) {
        self.discard_border_paint_undo_native(id);
    }

    /// [#5959] 이번 apply 가 push 한 BorderFill 꼬리 항목을 절단한다.
    ///
    /// json: `{"fromLen":12,"dirtyWas":false}` — `from_len` 위 항목을 모두 잘라내고,
    /// 원래 길이로 돌아왔으면 dirty 플래그를 `dirtyWas` 로 원복한다.
    /// 반환: JSON `{"ok":true,"discarded":N,"fullyDiscarded":bool}`
    #[wasm_bindgen(js_name = removeBorderFillTails)]
    pub fn remove_border_fill_tails(&mut self, json: &str) -> Result<String, JsValue> {
        self.remove_border_fill_tails_native(json)
            .map_err(|e| e.into())
    }

    /// 여러 셀의 width/height를 한 번에 조절한다 (배치).
    ///
    /// json: `[{"cellIdx":0,"widthDelta":150},{"cellIdx":2,"heightDelta":-100}]`
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = resizeTableCells)]
    pub fn resize_table_cells(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.resize_table_cells_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            json,
        )
        .map_err(|e| e.into())
    }

    /// 셀 블록의 너비 또는 높이를 같게 맞춘다 (한컴 [표 - 셀 너비를 같게 / 셀 높이를 같게]).
    ///
    /// 블록은 격자 행·열 범위(양 끝 포함)의 직사각형이고 `axis`는 `"width"` 또는 `"height"`다.
    /// 블록 밖 셀이 제자리를 지키도록 표 격자를 다시 나눈다.
    /// 반환: JSON `{"ok":true,"rowCount":N,"colCount":M,"cellMap":[..]}` — `cellMap[옛 셀 번호]`는 새 셀 번호다.
    #[wasm_bindgen(js_name = equalizeTableCellSizes)]
    #[allow(clippy::too_many_arguments)]
    pub fn equalize_table_cell_sizes(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        start_row: u16,
        start_col: u16,
        end_row: u16,
        end_col: u16,
        axis: &str,
    ) -> Result<String, JsValue> {
        let axis = match axis {
            "width" => crate::model::table::CellSizeAxis::Width,
            "height" => crate::model::table::CellSizeAxis::Height,
            _ => return Err(JsValue::from_str("axis는 width 또는 height입니다")),
        };
        self.equalize_table_cell_sizes_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            (start_row, start_col, end_row, end_col),
            axis,
        )
        .map_err(|e| e.into())
    }

    /// [#7189] 중첩 표의 셀 크기를 셀 경로로 조절한다 (배치).
    ///
    /// `cell_path_json`: `[{"controlIndex":0,"cellIndex":0,"cellParaIndex":9},...]`
    /// 마지막 항목이 조절할 표를 가리킨다. 깊이 1 이면 평면 API 와 같은 경로로 처리한다.
    #[wasm_bindgen(js_name = resizeTableCellsByPath)]
    pub fn resize_table_cells_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        json: &str,
    ) -> Result<String, JsValue> {
        let path = parse_cell_path_arg(cell_path_json)?;
        self.resize_table_cells_by_cell_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            json,
        )
        .map_err(|e| e.into())
    }

    /// 표의 위치 오프셋(vertical_offset, horizontal_offset)을 이동한다.
    ///
    /// delta_h, delta_v: HWPUNIT 단위 이동량 (양수=오른쪽/아래, 음수=왼쪽/위)
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = moveTableOffset)]
    pub fn move_table_offset(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        delta_h: i32,
        delta_v: i32,
    ) -> Result<String, JsValue> {
        self.move_table_offset_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            delta_h,
            delta_v,
        )
        .map_err(|e| e.into())
    }

    /// 표 속성을 조회한다.
    ///
    /// 반환: JSON `{cellSpacing, paddingLeft, paddingRight, paddingTop, paddingBottom, pageBreak, repeatHeader}`
    #[wasm_bindgen(js_name = getTableProperties)]
    pub fn get_table_properties(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_table_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 속성을 수정한다.
    ///
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = setTableProperties)]
    pub fn set_table_properties(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.set_table_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            json,
        )
        .map_err(|e| e.into())
    }

    /// 표의 모든 셀 bbox를 반환한다 (F5 셀 선택 모드용).
    ///
    /// 반환: JSON `[{cellIdx, row, col, rowSpan, colSpan, pageIndex, x, y, w, h}, ...]`
    #[wasm_bindgen(js_name = getTableCellBboxes)]
    pub fn get_table_cell_bboxes(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        page_hint: Option<u32>,
    ) -> Result<String, JsValue> {
        self.get_table_cell_bboxes_from_page(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            page_hint.unwrap_or(0) as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 전체의 바운딩박스를 반환한다.
    ///
    /// 반환: JSON `{"pageIndex":<N>,"x":<f>,"y":<f>,"width":<f>,"height":<f>}`
    #[wasm_bindgen(js_name = getTableBBox)]
    pub fn get_table_bbox(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_table_bbox_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 지정 page 에 배치된 표 fragment 의 바운딩박스를 반환한다 (#2400).
    ///
    /// 반환: JSON `{"pageIndex":<N>,"x":<f>,"y":<f>,"width":<f>,"height":<f>}`
    #[wasm_bindgen(js_name = getTableBBoxAtPage)]
    pub fn get_table_bbox_at_page(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        page_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_table_bbox_at_page_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            page_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// [Task #919] 글상자/도형 컨트롤의 페이지 좌표 바운딩박스를 반환한다.
    ///
    /// 반환: JSON `{"pageIndex":<N>,"x":<f>,"y":<f>,"width":<f>,"height":<f>}`
    /// studio 의 `isShapeBorderClick` 헬퍼에서 외곽 경계선 클릭 판별에 사용.
    #[wasm_bindgen(js_name = getShapeBBox)]
    pub fn get_shape_bbox(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_shape_bbox_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 컨트롤을 문단에서 삭제한다.
    ///
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = deleteTableControl)]
    pub fn delete_table_control(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_table_control_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 커서 위치에 새 표를 삽입한다.
    ///
    /// 반환: JSON `{"ok":true,"paraIdx":<N>,"controlIdx":0}`
    #[wasm_bindgen(js_name = createTable)]
    pub fn create_table(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        row_count: u32,
        col_count: u32,
    ) -> Result<String, JsValue> {
        self.create_table_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            row_count as u16,
            col_count as u16,
        )
        .map_err(|e| e.into())
    }

    /// 커서 위치에 표를 삽입한다 (확장, JSON 옵션).
    ///
    /// options JSON: { sectionIdx, paraIdx, charOffset, rowCount, colCount,
    ///                 treatAsChar?: bool, colWidths?: [u32, ...] }
    #[wasm_bindgen(js_name = createTableEx)]
    pub fn create_table_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_bool, json_u32};
        let section_idx = json_u32(options_json, "sectionIdx").unwrap_or(0) as usize;
        let para_idx = json_u32(options_json, "paraIdx").unwrap_or(0) as usize;
        let char_offset = json_u32(options_json, "charOffset").unwrap_or(0) as usize;
        let row_count = json_u32(options_json, "rowCount").unwrap_or(2) as u16;
        let col_count = json_u32(options_json, "colCount").unwrap_or(2) as u16;
        let treat_as_char = json_bool(options_json, "treatAsChar").unwrap_or(false);
        fn parse_u32_array(json: &str, key: &str) -> Option<Vec<u32>> {
            if let Some(start) = json.find(&format!("\"{}\"", key)) {
                let rest = &json[start..];
                if let Some(arr_start) = rest.find('[') {
                    if let Some(arr_end) = rest[arr_start..].find(']') {
                        let arr_str = &rest[arr_start + 1..arr_start + arr_end];
                        let nums: Vec<u32> = arr_str
                            .split(',')
                            .filter_map(|s| s.trim().parse::<u32>().ok())
                            .collect();
                        if !nums.is_empty() {
                            Some(nums)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                } else {
                    None
                }
            } else {
                None
            }
        }
        let col_widths = parse_u32_array(options_json, "colWidths");
        let row_heights = parse_u32_array(options_json, "rowHeights");

        self.create_table_ex_native(
            section_idx,
            para_idx,
            char_offset,
            row_count,
            col_count,
            treat_as_char,
            col_widths.as_deref(),
            row_heights.as_deref(),
        )
        .map_err(|e| e.into())
    }

    /// [#8262] 표 칸 안 문단에 표를 만든다 — 셀 경로라 깊이에 상관없다.
    ///
    /// `cell_path_json`: 다른 by-path API 와 같은 `[{controlIndex, cellIndex, cellParaIndex}, ...]`.
    /// 마지막 마디의 `cellParaIndex` 가 캐럿이 있는 칸 문단, `char_offset` 은 그 문단의 캐럿 offset.
    ///
    /// options JSON: `{ rowCount, colCount, colWidths?: [u32, ...], rowHeights?: [u32, ...],
    ///                 treatAsChar?: bool }` — `treatAsChar` 기본값은 참(글자처럼 취급)이다.
    /// 거짓이면 한/글 12.30처럼 자리 차지 표를 만든다. 경로의 첫 마디가 머리말·꼬리말
    /// (`{controlIndex: 머리말 컨트롤, cellIndex: 0, cellParaIndex: 머리말 문단}`)이면 그 문단에 만든다.
    ///
    /// 반환: `{"ok":true,"cellParaIdx":N,"controlIdx":0,"cellPath":[..안쪽 표 첫 칸까지]}`
    #[wasm_bindgen(js_name = createTableInCellByPath)]
    pub fn create_table_in_cell_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        char_offset: u32,
        options_json: &str,
    ) -> Result<String, JsValue> {
        let options: serde_json::Value = serde_json::from_str(options_json)
            .map_err(|e| JsValue::from_str(&format!("options JSON 파싱 실패: {}", e)))?;
        let treat_as_char = options
            .get("treatAsChar")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        let count = |key: &str, default: u64| -> u16 {
            options.get(key).and_then(|v| v.as_u64()).unwrap_or(default) as u16
        };
        let hu_list = |key: &str| -> Option<Vec<u32>> {
            let list: Vec<u32> = options
                .get(key)?
                .as_array()?
                .iter()
                .filter_map(|v| v.as_u64().map(|n| n as u32))
                .collect();
            (!list.is_empty()).then_some(list)
        };
        let path = crate::document_core::DocumentCore::parse_cell_path(cell_path_json)
            .map_err(|e| -> JsValue { e.into() })?;
        let col_widths = hu_list("colWidths");
        let row_heights = hu_list("rowHeights");

        self.create_table_in_cell_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
            count("rowCount", 2),
            count("colCount", 2),
            col_widths.as_deref(),
            row_heights.as_deref(),
            treat_as_char,
        )
        .map_err(|e| e.into())
    }

    /// 커서 위치에 그림을 삽입한다.
    ///
    /// image_data: 이미지 바이너리 데이터 (PNG/JPG/GIF/BMP 등)
    /// width, height: HWPUNIT 단위 크기
    /// extension: 파일 확장자 (jpg, png 등)
    ///
    /// 반환:
    /// - 본문 inline: `{"ok":true,"paraIdx":<N>,"controlIdx":0}`
    /// - 셀 floating (#1151): `{"ok":true,"paraIdx":<table_para>,"controlIdx":<new_sibling_idx>}`
    ///
    /// `cell_path_json` 이 빈 문자열 또는 `"[]"` 면 본문 inline 삽입. 그 외에는
    /// 표 셀 영역에 floating picture (한컴 정합) 로 삽입한다.
    /// 예: `[{"controlIndex":0,"cellIndex":2,"cellParaIndex":0}]`
    /// [Task #1151 v8 결함 C] `paper_offset_x_hu / paper_offset_y_hu` 는 사용자가 셀 안에
    /// 클릭/드래그한 위치 (paper-relative HU). studio 의 finishImagePlacement 가 drag 좌표를
    /// 변환하여 전달. JS 측에서 `undefined` 전달 시 (또는 음수) wasm 이 셀 좌상단을 default 사용
    /// — 기존 동작 호환.
    #[wasm_bindgen(js_name = insertPicture)]
    #[allow(clippy::too_many_arguments)]
    pub fn insert_picture(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        cell_path_json: &str,
        image_data: &[u8],
        width: u32,
        height: u32,
        natural_width_px: u32,
        natural_height_px: u32,
        extension: &str,
        description: &str,
        paper_offset_x_hu: Option<i32>,
        paper_offset_y_hu: Option<i32>,
    ) -> Result<String, JsValue> {
        let cell_path: Vec<(usize, usize, usize)> =
            if cell_path_json.is_empty() || cell_path_json == "[]" {
                Vec::new()
            } else {
                DocumentCore::parse_cell_path(cell_path_json).map_err(JsValue::from)?
            };
        self.insert_picture_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            &cell_path,
            image_data,
            width,
            height,
            natural_width_px,
            natural_height_px,
            extension,
            description,
            paper_offset_x_hu,
            paper_offset_y_hu,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 안 문단에 그림을 넣는다 — 서명·도장처럼 셀과 함께 움직여야 하는 그림.
    ///
    /// `insertPicture` 의 셀 분기는 그림을 표 밖 본문 문단에 띄운다. 이 API 는 그림을
    /// `cell_path_json` 이 가리키는 셀 문단의 컨트롤로 넣는다(가로 기준 단, 세로 기준 문단,
    /// 한컴 저장본과 같은 구조). `offset_x_hu`/`offset_y_hu` 는 그 기준의 HWPUNIT(음수 허용).
    /// 반환 `controlIdx` 는 셀 문단 안 번호다 — 속성은 `setCellPicturePropertiesByPath` 로 바꾼다.
    #[wasm_bindgen(js_name = insertPictureInCell)]
    #[allow(clippy::too_many_arguments)]
    pub fn insert_picture_in_cell(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        cell_path_json: &str,
        image_data: &[u8],
        width: u32,
        height: u32,
        natural_width_px: u32,
        natural_height_px: u32,
        extension: &str,
        description: &str,
        offset_x_hu: Option<i32>,
        offset_y_hu: Option<i32>,
    ) -> Result<String, JsValue> {
        let cell_path = DocumentCore::parse_cell_path(cell_path_json).map_err(JsValue::from)?;
        self.insert_picture_in_cell_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            &cell_path,
            image_data,
            width,
            height,
            natural_width_px,
            natural_height_px,
            extension,
            description,
            offset_x_hu,
            offset_y_hu,
        )
        .map_err(|e| e.into())
    }

    /// 띄운 그림을 다른 문단·셀 문단으로 옮겨 붙인다 (다른 쪽으로 끌어 놓기).
    /// 셀 경로 JSON 이 `[]` 이면 본문 문단이다.
    #[wasm_bindgen(js_name = relocateFloatingPicture)]
    #[allow(clippy::too_many_arguments)]
    pub fn relocate_floating_picture(
        &mut self,
        src_section: u32,
        src_para: u32,
        src_cell_path_json: &str,
        src_control: u32,
        dst_section: u32,
        dst_para: u32,
        dst_char_offset: u32,
        dst_cell_path_json: &str,
        horz_offset: i32,
        vert_offset: i32,
    ) -> Result<String, JsValue> {
        let src_path = DocumentCore::parse_cell_path(src_cell_path_json).map_err(JsValue::from)?;
        let dst_path = DocumentCore::parse_cell_path(dst_cell_path_json).map_err(JsValue::from)?;
        self.relocate_floating_picture_native(
            src_section as usize,
            src_para as usize,
            &src_path,
            src_control as usize,
            dst_section as usize,
            dst_para as usize,
            dst_char_offset as usize,
            &dst_path,
            horz_offset,
            vert_offset,
        )
        .map_err(|e| e.into())
    }

    /// 커서 위치에 그림을 삽입한다 (확장, options object — #1413).
    ///
    /// positional `insertPicture` 와 동일 동작의 얇은 어댑터. 이미지 바이너리는 별도
    /// `image_data` 인자(Uint8Array)로 받고, 나머지는 JSON options 로 받는다. 필드 추가/
    /// 순서 변경 시 호출부 영향이 작다.
    ///
    /// options JSON 키 (positional 과 동일 의미, camelCase):
    /// `{ sectionIdx, paraIdx, charOffset?, cellPath?: string, width, height,
    ///    naturalWidthPx, naturalHeightPx, extension?, description?,
    ///    paperOffsetXHu?: number|null, paperOffsetYHu?: number|null }`
    /// - `cellPath` 는 cell_path_json 문자열(빈 문자열/`"[]"` 이면 본문 inline).
    /// - 반환값은 `insertPicture` 와 동일.
    #[wasm_bindgen(js_name = insertPictureEx)]
    pub fn insert_picture_ex(
        &mut self,
        options_json: &str,
        image_data: &[u8],
    ) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_i32, json_str, json_u32};
        let section_idx = json_u32(options_json, "sectionIdx").unwrap_or(0);
        let para_idx = json_u32(options_json, "paraIdx").unwrap_or(0);
        let char_offset = json_u32(options_json, "charOffset").unwrap_or(0);
        let cell_path_json = json_str(options_json, "cellPath").unwrap_or_default();
        let width = json_u32(options_json, "width").unwrap_or(0);
        let height = json_u32(options_json, "height").unwrap_or(0);
        let natural_width_px = json_u32(options_json, "naturalWidthPx").unwrap_or(0);
        let natural_height_px = json_u32(options_json, "naturalHeightPx").unwrap_or(0);
        let extension = json_str(options_json, "extension").unwrap_or_default();
        let description = json_str(options_json, "description").unwrap_or_default();
        // paperOffset 은 키 부재 시 None(셀 좌상단 default) — positional 의 Option 동작과 동일.
        let paper_offset_x_hu = json_i32(options_json, "paperOffsetXHu");
        let paper_offset_y_hu = json_i32(options_json, "paperOffsetYHu");

        let cell_path: Vec<(usize, usize, usize)> =
            if cell_path_json.is_empty() || cell_path_json == "[]" {
                Vec::new()
            } else {
                DocumentCore::parse_cell_path(&cell_path_json).map_err(JsValue::from)?
            };
        self.insert_picture_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            &cell_path,
            image_data,
            width,
            height,
            natural_width_px,
            natural_height_px,
            &extension,
            &description,
            paper_offset_x_hu,
            paper_offset_y_hu,
        )
        .map_err(|e| e.into())
    }

    /// [Task #2230] 기존 Picture 컨트롤에 이미지를 지정한다 — 그림 미지정
    /// placeholder(missing image 컨트롤)의 편집 뷰 그림 삽입.
    ///
    /// `cell_path_json` 이 빈 문자열 또는 `"[]"` 면 본문 문단의 컨트롤,
    /// 그 외에는 셀/글상자 안 문단의 컨트롤을 대상으로 한다. 개체 틀 크기는
    /// 유지되고(한컴 placeholder 는 틀에 그림을 맞춤) BinData 등록 규칙은
    /// insertPicture 와 공유한다.
    ///
    /// 반환: `{"ok":true,"binDataId":<N>}`
    #[wasm_bindgen(js_name = assignPictureImage)]
    #[allow(clippy::too_many_arguments)]
    pub fn assign_picture_image(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        control_idx: u32,
        image_data: &[u8],
        natural_width_px: u32,
        natural_height_px: u32,
        extension: &str,
    ) -> Result<String, JsValue> {
        let cell_path: Vec<(usize, usize, usize)> =
            if cell_path_json.is_empty() || cell_path_json == "[]" {
                Vec::new()
            } else {
                DocumentCore::parse_cell_path(cell_path_json).map_err(JsValue::from)?
            };
        self.assign_picture_image_native(
            section_idx as usize,
            parent_para_idx as usize,
            &cell_path,
            control_idx as usize,
            image_data,
            natural_width_px,
            natural_height_px,
            extension,
        )
        .map_err(|e| e.into())
    }

    /// [Task #1142] 외부 file path 그림 reference 목록을 구조화된 JSON 배열로 반환한다.
    ///
    /// 반환: JSON 배열 `[{ key, binDataId, originalPath, basename, extension, loaded }, ...]`
    #[wasm_bindgen(js_name = getExternalImageReferences)]
    pub fn get_external_image_references(&self) -> String {
        serde_json::to_string(&collect_external_image_references(self.document()))
            .unwrap_or_else(|_| "[]".to_string())
    }

    /// [Task #741 후속] 외부 file path 그림 영역 영역 영역 영역 basename 목록 영역 반환.
    ///
    /// HWP3 파일 영역 image 영역 영역 절대 경로 영역 저장 영역. WASM 환경 영역 영역 file
    /// system access 부재 영역, JS 영역 영역 영역 영역 fetch 영역 영역 영역 file 영역 load
    /// 영역 후 `injectExternalImage` 영역 영역 영역 inject 영역.
    ///
    /// 반환: JSON 배열 `["oracle.gif", "rdb02.gif", ...]` (중복 제거)
    #[wasm_bindgen(js_name = getExternalImageBasenames)]
    pub fn get_external_image_basenames(&self) -> String {
        use std::collections::BTreeSet;

        let mut names: BTreeSet<String> = BTreeSet::new();
        for reference in collect_external_image_references(self.document()) {
            if !reference.loaded {
                names.insert(reference.basename);
            }
        }
        let arr: Vec<String> = names.into_iter().collect();
        serde_json::to_string(&arr).unwrap_or_else(|_| "[]".to_string())
    }

    /// [Task #741 후속] 외부 file path 그림 영역 영역 binary data 영역 inject.
    ///
    /// JS 영역 영역 영역 fetch 영역 영역 영역 file 영역 load 영역 후 본 메서드 영역 호출 영역
    /// IR 영역 영역 영역 image binary 영역 영역 → renderer 영역 영역 표시.
    ///
    /// `basename`: 영역 영역 file 영역 영역 (예: "oracle.gif")
    /// `data`: 영역 영역 binary 영역
    /// `display_path`: dialog 영역 영역 영역 영역 표시 영역 영역 path. 빈 문자열 ("") 영역
    ///                 영역 영역 fallback 영역 영역 `/samples/<basename>` 영역 사용. 한컴 viewer
    ///                 정합 영역 영역 OS 영역 절대 경로 영역 영역 (예: "/Users/.../samples/rdb02.gif")
    #[wasm_bindgen(js_name = injectExternalImage)]
    pub fn inject_external_image(
        &mut self,
        basename: &str,
        data: &[u8],
        display_path: &str,
    ) -> u32 {
        use crate::model::control::Control;
        use crate::model::shape::ShapeObject;
        use std::collections::BTreeSet;

        let mut injected: u32 = 0;
        // 영역 외부 image 영역 영역 영역 영역 basename 매칭 영역 영역 id 수집
        let mut targets: BTreeSet<u16> = BTreeSet::new();
        for section in &self.document().sections {
            for para in &section.paragraphs {
                for ctrl in &para.controls {
                    let pic = match ctrl {
                        Control::Picture(p) => p,
                        Control::Shape(s) => match s.as_ref() {
                            ShapeObject::Picture(p) => p,
                            _ => continue,
                        },
                        _ => continue,
                    };
                    if let Some(ref path) = pic.image_attr.external_path {
                        let path_basename = path
                            .rsplit(|c| c == '/' || c == '\\')
                            .next()
                            .unwrap_or(path);
                        if path_basename != basename {
                            continue;
                        }
                        let id = pic.image_attr.bin_data_id;
                        if self.document().external_image_loaded(id) {
                            continue;
                        }
                        targets.insert(id);
                    }
                }
            }
        }

        for id in targets {
            injected +=
                self.inject_external_image_by_bin_data_id(id, data, display_path, Some(basename));
        }

        if injected > 0 {
            self.invalidate_page_tree_cache();
        }

        injected
    }

    /// [Task #1143] `getExternalImageReferences()` 의 key로 외부 이미지 bytes를 주입한다.
    ///
    /// 지원 key: `binData:<bin_data_id>`.
    /// 잘못된 key, 존재하지 않는 key, 이미 loaded 상태인 reference는 0을 반환한다.
    #[wasm_bindgen(js_name = injectExternalImageByKey)]
    pub fn inject_external_image_by_key(
        &mut self,
        key: &str,
        data: &[u8],
        display_path: &str,
    ) -> u32 {
        let Some(bin_data_id) = parse_external_image_key(key) else {
            return 0;
        };

        let injected =
            self.inject_external_image_by_bin_data_id(bin_data_id, data, display_path, None);
        if injected > 0 {
            self.invalidate_page_tree_cache();
        }
        injected
    }

    /// 그림 컨트롤의 속성을 조회한다.
    ///
    /// 반환: JSON `{ width, height, treatAsChar, ... }`
    #[wasm_bindgen(js_name = getPictureProperties)]
    pub fn get_picture_properties(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_picture_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// [Task #825] 머리말/꼬리말 안 그림의 속성 조회.
    /// path: section[si].paragraphs[outer_para].controls[outer_ctrl] = Header/Footer
    ///       → .paragraphs[inner_para].controls[inner_ctrl] = Picture
    #[wasm_bindgen(js_name = getHeaderFooterPictureProperties)]
    pub fn get_header_footer_picture_properties(
        &self,
        section_idx: u32,
        outer_para_idx: u32,
        outer_control_idx: u32,
        inner_para_idx: u32,
        inner_control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_header_footer_picture_properties_native(
            section_idx as usize,
            outer_para_idx as usize,
            outer_control_idx as usize,
            inner_para_idx as usize,
            inner_control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 그림 컨트롤의 속성을 변경한다.
    ///
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = setPictureProperties)]
    pub fn set_picture_properties(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.set_picture_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// [Task #825] 머리말/꼬리말 안 그림 속성 변경.
    #[wasm_bindgen(js_name = setHeaderFooterPictureProperties)]
    pub fn set_header_footer_picture_properties(
        &mut self,
        section_idx: u32,
        outer_para_idx: u32,
        outer_control_idx: u32,
        inner_para_idx: u32,
        inner_control_idx: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.set_header_footer_picture_properties_native(
            section_idx as usize,
            outer_para_idx as usize,
            outer_control_idx as usize,
            inner_para_idx as usize,
            inner_control_idx as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// 그림 컨트롤을 문단에서 삭제한다.
    ///
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = deletePictureControl)]
    pub fn delete_picture_control(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_picture_control_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// [Task #1171 / PR #1254] 표 셀/글상자 내부 Picture 삭제 (by_path).
    #[wasm_bindgen(js_name = deleteCellPictureControlByPath)]
    pub fn delete_cell_picture_control_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        inner_control_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_cell_picture_control_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            cell_path_json,
            inner_control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀·글상자 안의 도형 하나를 전체 소유 경로로 삭제한다.
    #[wasm_bindgen(js_name = deleteCellShapeControlByPath)]
    pub fn delete_cell_shape_control_by_path(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        cell_path_json: &str,
        inner_control_idx: usize,
    ) -> Result<String, JsValue> {
        self.delete_cell_shape_control_by_path_native(
            section_idx,
            parent_para_idx,
            cell_path_json,
            inner_control_idx,
        )
        .map_err(|e| e.into())
    }

    /// [#6771] 표 셀/글상자 내부 **표** 삭제 (by_path).
    ///
    /// 셀 안 1×1 안내 상자처럼 본문 리스트 밖에 있는 표를 지운다 — `deleteControlAt` 은
    /// 본문만, `deleteTableControl` 은 `(구역, 문단, 컨트롤)` 만 다뤄 짚지 못하던 자리다.
    #[wasm_bindgen(js_name = deleteCellTableControlByPath)]
    pub fn delete_cell_table_control_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        inner_control_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_cell_table_control_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            cell_path_json,
            inner_control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// [#4694] 문서의 모든 차트를 문서 순서로 열거한다.
    ///
    /// 반환: JSON `[{ index, section, paragraph, control, container?, zipPart?, nestedCopy? }]`
    /// studio 는 이 목록을 선택 컨트롤과 대조해 정본 주소(문서 순번)를 얻는다.
    #[wasm_bindgen(js_name = listCharts)]
    pub fn list_charts(&self) -> Result<String, JsValue> {
        self.list_charts_native().map_err(|e| e.into())
    }

    /// [#4694] 본문 직속 차트의 숫자 데이터를 조회한다 (3인자 주소).
    ///
    /// 컨테이너(글상자·표 셀·머리말) 안 차트는 이 주소로 표현할 수 없다 —
    /// `getChartDataByIndex` 를 쓴다.
    #[wasm_bindgen(js_name = getChartData)]
    pub fn get_chart_data(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_chart_data_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// [#4694] 문서 순번(0-based)으로 차트 데이터를 조회한다 — 정본 주소.
    #[wasm_bindgen(js_name = getChartDataByIndex)]
    pub fn get_chart_data_by_index(&self, index: u32) -> Result<String, JsValue> {
        self.get_chart_data_by_index_native(index as usize)
            .map_err(|e| e.into())
    }

    /// [#4694] 본문 직속 차트의 숫자 데이터를 바꾼다 (3인자 주소).
    ///
    /// 반환: `{ok, chart, changedCount, changed[], wrote[]}` 또는 `{ok:false, invalid[]}`.
    #[wasm_bindgen(js_name = setChartData)]
    pub fn set_chart_data(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        edits_json: &str,
    ) -> Result<String, JsValue> {
        self.set_chart_data_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            edits_json,
        )
        .map_err(|e| e.into())
    }

    /// [#4694] 문서 순번(0-based)으로 차트 데이터를 바꾼다 — 정본 주소.
    #[wasm_bindgen(js_name = setChartDataByIndex)]
    pub fn set_chart_data_by_index(
        &mut self,
        index: u32,
        edits_json: &str,
    ) -> Result<String, JsValue> {
        self.set_chart_data_by_index_native(index as usize, edits_json)
            .map_err(|e| e.into())
    }

    /// [Task #1138] 표 셀 내 Shape(글상자/사각형/도형) 속성 조회 (by_path).
    #[wasm_bindgen(js_name = getCellShapePropertiesByPath)]
    pub fn get_cell_shape_properties_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        inner_control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_cell_shape_properties_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            cell_path_json,
            inner_control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// [Task #1151 v4] 표 셀 내 Picture 속성 조회 (by_path). Shape 패턴 정합.
    #[wasm_bindgen(js_name = getCellPicturePropertiesByPath)]
    pub fn get_cell_picture_properties_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        inner_control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_cell_picture_properties_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            cell_path_json,
            inner_control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// [Task #1138] 표 셀 내 Shape 속성 변경 (by_path).
    #[wasm_bindgen(js_name = setCellShapePropertiesByPath)]
    pub fn set_cell_shape_properties_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        inner_control_idx: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.set_cell_shape_properties_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            cell_path_json,
            inner_control_idx as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// [Task #1151 v4] 표 셀 내 Picture 속성 변경 (by_path). Shape 패턴 정합.
    #[wasm_bindgen(js_name = setCellPicturePropertiesByPath)]
    pub fn set_cell_picture_properties_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        cell_path_json: &str,
        inner_control_idx: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.set_cell_picture_properties_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            cell_path_json,
            inner_control_idx as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    // ─── Equation(수식) API ──────────────────────────────

    /// 수식 컨트롤을 문단에서 삭제한다.
    ///
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = deleteEquationControl)]
    pub fn delete_equation_control(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_equation_control_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 수식 컨트롤의 속성을 조회한다.
    ///
    /// 반환: JSON `{ script, fontSize, color, baseline, fontName }`
    #[wasm_bindgen(js_name = getEquationProperties)]
    pub fn get_equation_properties(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: i32,
        cell_para_idx: i32,
    ) -> Result<String, JsValue> {
        let ci = if cell_idx >= 0 {
            Some(cell_idx as usize)
        } else {
            None
        };
        let cpi = if cell_para_idx >= 0 {
            Some(cell_para_idx as usize)
        } else {
            None
        };
        self.get_equation_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            ci,
            cpi,
        )
        .map_err(|e| e.into())
    }

    /// 수식 컨트롤의 속성을 변경한다.
    ///
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = setEquationProperties)]
    pub fn set_equation_properties(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: i32,
        cell_para_idx: i32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        let ci = if cell_idx >= 0 {
            Some(cell_idx as usize)
        } else {
            None
        };
        let cpi = if cell_para_idx >= 0 {
            Some(cell_para_idx as usize)
        } else {
            None
        };
        self.set_equation_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            ci,
            cpi,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// 각주/미주 내부 수식 컨트롤의 속성을 조회한다.
    #[wasm_bindgen(js_name = getNoteEquationProperties)]
    pub fn get_note_equation_properties(
        &self,
        kind: &str,
        section_idx: u32,
        parent_para_idx: u32,
        note_control_idx: u32,
        note_para_idx: u32,
        inner_control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_note_equation_properties_native(
            kind,
            section_idx as usize,
            parent_para_idx as usize,
            note_control_idx as usize,
            note_para_idx as usize,
            inner_control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 각주/미주 내부 수식 컨트롤의 속성을 변경한다.
    #[wasm_bindgen(js_name = setNoteEquationProperties)]
    pub fn set_note_equation_properties(
        &mut self,
        kind: &str,
        section_idx: u32,
        parent_para_idx: u32,
        note_control_idx: u32,
        note_para_idx: u32,
        inner_control_idx: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.set_note_equation_properties_native(
            kind,
            section_idx as usize,
            parent_para_idx as usize,
            note_control_idx as usize,
            note_para_idx as usize,
            inner_control_idx as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// `setNoteEquationProperties` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ kind, sectionIdx, parentParaIdx, noteControlIdx, noteParaIdx,
    /// innerControlIdx, props: object }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = setNoteEquationPropertiesEx)]
    pub fn set_note_equation_properties_ex(
        &mut self,
        options_json: &str,
    ) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_object, json_str, json_u32};
        let props_json = json_object(options_json, "props").unwrap_or_else(|| "{}".to_string());
        self.set_note_equation_properties_native(
            &json_str(options_json, "kind").unwrap_or_default(),
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "noteControlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "noteParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "innerControlIdx").unwrap_or(0) as usize,
            &props_json,
        )
        .map_err(|e| e.into())
    }

    /// 수식 스크립트를 SVG로 렌더링하여 반환한다 (미리보기 전용).
    ///
    /// 반환: 완전한 `<svg>` 문자열
    #[wasm_bindgen(js_name = renderEquationPreview)]
    pub fn render_equation_preview(
        &self,
        script: &str,
        font_size_hwpunit: u32,
        color: u32,
    ) -> Result<String, JsValue> {
        self.render_equation_preview_native(script, font_size_hwpunit, color)
            .map_err(|e| e.into())
    }

    /// JSON에서 polygonPoints 배열 파싱
    fn parse_polygon_points(json: &str) -> Vec<crate::model::Point> {
        // 간단한 파싱: "polygonPoints":[{"x":1,"y":2},{"x":3,"y":4}]
        let key = "\"polygonPoints\":[";
        if let Some(start) = json.find(key) {
            let rest = &json[start + key.len()..];
            if let Some(end) = rest.find(']') {
                let arr = &rest[..end];
                return arr
                    .split("},")
                    .filter_map(|item| {
                        let item = item.trim().trim_start_matches('{').trim_end_matches('}');
                        let x =
                            crate::document_core::helpers::json_i32(&format!("{{{}}}", item), "x")?;
                        let y =
                            crate::document_core::helpers::json_i32(&format!("{{{}}}", item), "y")?;
                        Some(crate::model::Point { x, y })
                    })
                    .collect();
            }
        }
        Vec::new()
    }

    // ─── Shape(글상자) API ───────────────────────────────

    /// 커서 위치에 글상자(Rectangle + TextBox)를 삽입한다.
    ///
    /// json: `{"sectionIdx":N,"paraIdx":N,"charOffset":N,"width":N,"height":N,
    ///         "horzOffset":N,"vertOffset":N,"treatAsChar":bool,"textWrap":"Square"}`
    /// 반환: JSON `{"ok":true,"paraIdx":<N>,"controlIdx":0}`
    #[wasm_bindgen(js_name = createShapeControl)]
    pub fn create_shape_control(&mut self, json: &str) -> Result<String, JsValue> {
        let sec = json_u32(json, "sectionIdx").unwrap_or(0) as usize;
        let para = json_u32(json, "paraIdx").unwrap_or(0) as usize;
        let offset = json_u32(json, "charOffset").unwrap_or(0) as usize;
        let width = json_u32(json, "width").unwrap_or(8504);
        let height = json_u32(json, "height").unwrap_or(8504);
        let horz_offset = json_u32(json, "horzOffset").unwrap_or(0);
        let vert_offset = json_u32(json, "vertOffset").unwrap_or(0);
        let shape_type = json_str(json, "shapeType").unwrap_or_else(|| "rectangle".to_string());
        // 글상자는 기본적으로 treat_as_char=true (한컴 기본값)
        let default_tac = shape_type == "textbox";
        let treat_as_char = json_bool(json, "treatAsChar").unwrap_or(default_tac);
        let text_wrap = json_str(json, "textWrap").unwrap_or_else(|| "Square".to_string());
        let line_flip_x = json_bool(json, "lineFlipX").unwrap_or(false);
        let line_flip_y = json_bool(json, "lineFlipY").unwrap_or(false);
        // 다각형 꼭짓점: "polygonPoints":[{"x":N,"y":N},...]
        let polygon_points: Vec<crate::model::Point> = if shape_type == "polygon" {
            Self::parse_polygon_points(json)
        } else {
            Vec::new()
        };
        let result = self.create_shape_control_native(
            sec,
            para,
            offset,
            width,
            height,
            horz_offset,
            vert_offset,
            treat_as_char,
            &text_wrap,
            &shape_type,
            line_flip_x,
            line_flip_y,
            &polygon_points,
        )?;

        // 연결선: SubjectID + 제어점 라우팅 설정 (생성 후)
        if shape_type.starts_with("connector-") {
            let ssid = json_u32(json, "startSubjectID").unwrap_or(0);
            let ssidx = json_u32(json, "startSubjectIndex").unwrap_or(0);
            let esid = json_u32(json, "endSubjectID").unwrap_or(0);
            let esidx = json_u32(json, "endSubjectIndex").unwrap_or(0);
            let pi = json_u32(&result, "paraIdx");
            let ci = json_u32(&result, "controlIdx");
            if let (Some(pi), Some(ci)) = (pi, ci) {
                self.update_connector_subject_ids(
                    sec,
                    pi as usize,
                    ci as usize,
                    ssid,
                    ssidx,
                    esid,
                    esidx,
                );
                self.recalculate_connector_routing(sec, pi as usize, ci as usize, ssidx, esidx);
            }
        }

        Ok(result)
    }

    /// Shape(글상자) 속성을 조회한다.
    ///
    /// 반환: JSON `{ width, height, treatAsChar, tbMarginLeft, ... }`
    #[wasm_bindgen(js_name = getShapeProperties)]
    pub fn get_shape_properties(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_shape_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// Shape(글상자) 속성을 변경한다.
    ///
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = setShapeProperties)]
    pub fn set_shape_properties(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.set_shape_properties_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// Shape(글상자) 컨트롤을 문단에서 삭제한다.
    ///
    /// 반환: JSON `{"ok":true}`
    #[wasm_bindgen(js_name = deleteShapeControl)]
    pub fn delete_shape_control(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_shape_control_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// Shape z-order 변경
    /// operation: "front" | "back" | "forward" | "backward"
    /// 반환: `{"ok":true,"zOrder":N,"moves":[{"ppi","ci","before","after"}...]}`
    /// [#5769 후속] moves 는 실제로 대입된 (대상+교환 이웃) before/after 쌍이다 —
    /// SetZOrderCommand 가 undo/redo 절대 복원 쌍으로 소비한다.
    #[wasm_bindgen(js_name = changeShapeZOrder)]
    pub fn change_shape_z_order(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        operation: &str,
    ) -> Result<String, JsValue> {
        self.change_shape_z_order_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            operation,
        )
        .map_err(|e| e.into())
    }

    /// Shape z 순서 절대 대입(#5769 후속) — 속성쌍 커맨드의 undo/redo 경로.
    /// pairs_json: `[{"ppi":N,"ci":N,"z":N},...]`
    /// 반환: JSON `{"ok":true,"applied":N}`
    #[wasm_bindgen(js_name = applyShapeZOrderPairs)]
    pub fn apply_shape_z_order_pairs(
        &mut self,
        section_idx: u32,
        pairs_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_shape_z_order_pairs_native(section_idx as usize, pairs_json)
            .map_err(|e| e.into())
    }

    /// 선택된 개체들을 하나의 GroupShape로 묶는다.
    /// json: `{"sectionIdx":N, "targets":[{"paraIdx":N,"controlIdx":N},...]}`
    /// 반환: JSON `{"ok":true, "paraIdx":N, "controlIdx":N}`
    #[wasm_bindgen(js_name = groupShapes)]
    pub fn group_shapes(&mut self, json: &str) -> Result<String, JsValue> {
        let sec = json_u32(json, "sectionIdx").unwrap_or(0) as usize;
        // targets 배열 파싱
        let targets: Vec<(usize, usize)> = {
            let mut result = Vec::new();
            // 간단한 JSON 배열 파싱: "targets":[{"paraIdx":N,"controlIdx":N},...]
            if let Some(start) = json.find("\"targets\"") {
                let rest = &json[start..];
                if let Some(arr_start) = rest.find('[') {
                    if let Some(arr_end) = rest.find(']') {
                        let arr = &rest[arr_start + 1..arr_end];
                        // 각 {} 블록에서 paraIdx, controlIdx 추출
                        let mut pos = 0;
                        while let Some(obj_start) = arr[pos..].find('{') {
                            let obj_start = pos + obj_start;
                            if let Some(obj_end) = arr[obj_start..].find('}') {
                                let obj = &arr[obj_start..obj_start + obj_end + 1];
                                let pi = json_u32(obj, "paraIdx").unwrap_or(0) as usize;
                                let ci = json_u32(obj, "controlIdx").unwrap_or(0) as usize;
                                result.push((pi, ci));
                                pos = obj_start + obj_end + 1;
                            } else {
                                break;
                            }
                        }
                    }
                }
            }
            result
        };
        self.group_shapes_native(sec, &targets)
            .map_err(|e| e.into())
    }

    /// GroupShape를 풀어 자식 개체들을 개별로 복원한다.
    #[wasm_bindgen(js_name = ungroupShape)]
    pub fn ungroup_shape(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.ungroup_shape_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 직선 끝점 이동 (글로벌 HWPUNIT 좌표)
    #[wasm_bindgen(js_name = moveLineEndpoint)]
    pub fn move_line_endpoint(
        &mut self,
        sec: u32,
        para: u32,
        ci: u32,
        sx: i32,
        sy: i32,
        ex: i32,
        ey: i32,
    ) -> Result<String, JsValue> {
        self.move_line_endpoint_native(sec as usize, para as usize, ci as usize, sx, sy, ex, ey)
            .map_err(|e| e.into())
    }

    /// `moveLineEndpoint` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sec, para, ci, sx, sy, ex, ey }` (좌표는 i32). positional 과 동일 동작.
    #[wasm_bindgen(js_name = moveLineEndpointEx)]
    pub fn move_line_endpoint_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_i32, json_u32};
        self.move_line_endpoint_native(
            json_u32(options_json, "sec").unwrap_or(0) as usize,
            json_u32(options_json, "para").unwrap_or(0) as usize,
            json_u32(options_json, "ci").unwrap_or(0) as usize,
            json_i32(options_json, "sx").unwrap_or(0),
            json_i32(options_json, "sy").unwrap_or(0),
            json_i32(options_json, "ex").unwrap_or(0),
            json_i32(options_json, "ey").unwrap_or(0),
        )
        .map_err(|e| e.into())
    }

    /// 구역 내 모든 연결선의 좌표를 연결된 도형 위치에 맞게 갱신한다.
    #[wasm_bindgen(js_name = updateConnectorsInSection)]
    pub fn update_connectors_in_section_wasm(&mut self, section_idx: u32) {
        self.update_connectors_in_section(section_idx as usize);
    }

    /// 각주를 삽입한다.
    #[wasm_bindgen(js_name = insertFootnote)]
    pub fn insert_footnote(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.insert_footnote_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 미주를 삽입한다.
    #[wasm_bindgen(js_name = insertEndnote)]
    pub fn insert_endnote(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.insert_endnote_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 미주 모양을 조회한다.
    #[wasm_bindgen(js_name = getEndnoteShape)]
    pub fn get_endnote_shape(&self, section_idx: u32) -> Result<String, JsValue> {
        self.get_endnote_shape_native(section_idx as usize)
            .map_err(|e| e.into())
    }

    /// 미주 모양을 적용한다.
    #[wasm_bindgen(js_name = applyEndnoteShape)]
    pub fn apply_endnote_shape(
        &mut self,
        section_idx: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_endnote_shape_native(section_idx as usize, props_json)
            .map_err(|e| e.into())
    }

    /// 수식을 삽입한다.
    #[wasm_bindgen(js_name = insertEquation)]
    pub fn insert_equation(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        script: &str,
        font_size: u32,
        color: u32,
    ) -> Result<String, JsValue> {
        self.insert_equation_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            script,
            font_size,
            color,
        )
        .map_err(|e| e.into())
    }

    /// 한/글 5.x/97 OLE 수식을 편집 가능한 native equation으로 변환한다.
    #[wasm_bindgen(js_name = promoteOleEquation)]
    pub fn promote_ole_equation(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.promote_ole_equation_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 각주 정보를 조회한다.
    #[wasm_bindgen(js_name = getFootnoteInfo)]
    pub fn get_footnote_info(
        &self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_footnote_info_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 본문 커서 위치의 각주 마커를 조회한다.
    ///
    /// direction: "backward" 또는 "forward"
    #[wasm_bindgen(js_name = getFootnoteAtCursor)]
    pub fn get_footnote_at_cursor(
        &self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        direction: &str,
    ) -> Result<String, JsValue> {
        self.get_footnote_at_cursor_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            direction,
        )
        .map_err(|e| e.into())
    }

    /// 본문 각주 컨트롤을 삭제한다.
    #[wasm_bindgen(js_name = deleteFootnote)]
    pub fn delete_footnote(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.delete_footnote_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 각주 내 텍스트를 삽입한다.
    #[wasm_bindgen(js_name = insertTextInFootnote)]
    pub fn insert_text_in_footnote(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
        fn_para_idx: u32,
        char_offset: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        self.insert_text_in_footnote_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
            fn_para_idx as usize,
            char_offset as usize,
            text,
        )
        .map_err(|e| e.into())
    }

    /// 각주 내 텍스트를 삭제한다.
    #[wasm_bindgen(js_name = deleteTextInFootnote)]
    pub fn delete_text_in_footnote(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
        fn_para_idx: u32,
        char_offset: u32,
        count: u32,
    ) -> Result<String, JsValue> {
        self.delete_text_in_footnote_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
            fn_para_idx as usize,
            char_offset as usize,
            count as usize,
        )
        .map_err(|e| e.into())
    }

    /// 각주 내 문단을 분할한다 (Enter).
    #[wasm_bindgen(js_name = splitParagraphInFootnote)]
    pub fn split_paragraph_in_footnote(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
        fn_para_idx: u32,
        char_offset: u32,
        removed_para_meta: Option<String>,
    ) -> Result<String, JsValue> {
        self.split_paragraph_in_footnote_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
            fn_para_idx as usize,
            char_offset as usize,
            parse_removed_para_meta(removed_para_meta)?,
        )
        .map_err(|e| e.into())
    }

    /// 각주 내 문단을 병합한다 (Backspace at start).
    #[wasm_bindgen(js_name = mergeParagraphInFootnote)]
    pub fn merge_paragraph_in_footnote(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
        fn_para_idx: u32,
    ) -> Result<String, JsValue> {
        self.merge_paragraph_in_footnote_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
            fn_para_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 페이지에 각주 영역이 있는지 빠르게 확인 (hitTestFootnote fast-reject).
    /// 페이지네이션 메타데이터만 조회하므로 render tree build가 필요 없다 (#2428).
    #[wasm_bindgen(js_name = pageHasFootnoteFootholds)]
    pub fn page_has_footnote_footholds(&self, page_num: u32) -> bool {
        self.page_has_footnote_footholds_native(page_num)
    }

    /// 각주 영역 히트테스트
    #[wasm_bindgen(js_name = hitTestFootnote)]
    pub fn hit_test_footnote(&self, page_num: u32, x: f64, y: f64) -> Result<String, JsValue> {
        self.hit_test_footnote_native(page_num, x, y)
            .map_err(|e| e.into())
    }

    /// 각주 내부 텍스트 히트테스트
    #[wasm_bindgen(js_name = hitTestInFootnote)]
    pub fn hit_test_in_footnote(&self, page_num: u32, x: f64, y: f64) -> Result<String, JsValue> {
        self.hit_test_in_footnote_native(page_num, x, y)
            .map_err(|e| e.into())
    }

    /// 페이지의 각주 참조 정보
    #[wasm_bindgen(js_name = getPageFootnoteInfo)]
    pub fn get_page_footnote_info(
        &self,
        page_num: u32,
        footnote_index: u32,
    ) -> Result<String, JsValue> {
        self.get_page_footnote_info_native(page_num, footnote_index as usize)
            .map_err(|e| e.into())
    }

    /// 각주 내 커서 렉트 계산
    #[wasm_bindgen(js_name = getCursorRectInFootnote)]
    pub fn get_cursor_rect_in_footnote(
        &self,
        page_num: u32,
        footnote_index: u32,
        fn_para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_cursor_rect_in_footnote_native(
            page_num,
            footnote_index as usize,
            fn_para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 각주/미주 편집 모드 진입 대상 조회
    #[wasm_bindgen(js_name = getNoteEditInfo)]
    pub fn get_note_edit_info(
        &self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_note_edit_info_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 각주/미주 내부 커서 렉트 계산
    #[wasm_bindgen(js_name = getCursorRectInNote)]
    pub fn get_cursor_rect_in_note(
        &self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
        note_para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_cursor_rect_in_note_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
            note_para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 각주/미주 내부 문단 속성 조회
    #[wasm_bindgen(js_name = getParaPropertiesInFootnote)]
    pub fn get_para_properties_in_footnote(
        &self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
        fn_para_idx: u32,
    ) -> Result<String, JsValue> {
        self.get_para_properties_in_footnote_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
            fn_para_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 각주/미주 내부 문단 속성 적용
    #[wasm_bindgen(js_name = applyParaFormatInFootnote)]
    pub fn apply_para_format_in_footnote(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        control_idx: u32,
        fn_para_idx: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_para_format_in_footnote_native(
            section_idx as usize,
            para_idx as usize,
            control_idx as usize,
            fn_para_idx as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// 본문 인라인 각주 마커 히트테스트
    #[wasm_bindgen(js_name = hitTestBodyFootnoteMarker)]
    pub fn hit_test_body_footnote_marker(
        &self,
        page_num: u32,
        x: f64,
        y: f64,
    ) -> Result<String, JsValue> {
        self.hit_test_body_footnote_marker_native(page_num, x, y)
            .map_err(|e| e.into())
    }

    /// 수직 커서 이동 (ArrowUp/Down) — 단일 호출로 줄/문단/표/구역 경계를 모두 처리한다.
    ///
    /// delta: -1=위, +1=아래
    /// preferred_x: 이전 반환값의 preferredX (최초 이동 시 -1.0 전달)
    /// 셀 컨텍스트: 본문이면 모두 0xFFFFFFFF 전달
    ///
    /// 반환: JSON `{DocumentPosition + CursorRect + preferredX}`
    #[wasm_bindgen(js_name = moveVertical)]
    pub fn move_vertical(
        &self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        delta: i32,
        preferred_x: f64,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
    ) -> Result<String, JsValue> {
        let cell_ctx = if parent_para_idx == u32::MAX {
            None
        } else {
            Some((
                parent_para_idx as usize,
                control_idx as usize,
                cell_idx as usize,
                cell_para_idx as usize,
            ))
        };
        self.move_vertical_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            delta,
            preferred_x,
            cell_ctx,
        )
        .map_err(|e| e.into())
    }

    /// `moveVertical` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, paraIdx, charOffset?, delta, preferredX,
    /// parentParaIdx?, controlIdx?, cellIdx?, cellParaIdx? }`. cell 컨텍스트 키가 모두
    /// 생략되면 본문 이동(parentParaIdx=MAX 동작과 동일). positional 과 동일 동작.
    #[wasm_bindgen(js_name = moveVerticalEx)]
    pub fn move_vertical_ex(&self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_f64, json_i32, json_u32};
        // parentParaIdx 부재 시 u32::MAX(본문) — positional 분기와 동일.
        let parent_para_idx = json_u32(options_json, "parentParaIdx").unwrap_or(u32::MAX);
        let cell_ctx = if parent_para_idx == u32::MAX {
            None
        } else {
            Some((
                parent_para_idx as usize,
                json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
                json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
                json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            ))
        };
        self.move_vertical_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "paraIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            json_i32(options_json, "delta").unwrap_or(0),
            json_f64(options_json, "preferredX").unwrap_or(0.0),
            cell_ctx,
        )
        .map_err(|e| e.into())
    }

    // ─── 필드 API (Task 230) ─────────────────────────────────

    /// 문서 내 모든 필드 목록을 JSON 배열로 반환한다.
    ///
    /// 반환: `[{fieldId, fieldType, name, guide, command, value, location}]`
    #[wasm_bindgen(js_name = getFieldList)]
    pub fn get_field_list(&self) -> String {
        self.get_field_list_json()
    }

    /// field_id로 필드 값을 조회한다.
    ///
    /// 반환: `{ok, value}`
    #[wasm_bindgen(js_name = getFieldValue)]
    pub fn get_field_value(&self, field_id: u32) -> Result<String, JsValue> {
        self.get_field_value_by_id(field_id).map_err(|e| e.into())
    }

    /// 필드 이름으로 값을 조회한다.
    ///
    /// 반환: `{ok, fieldId, value}`
    #[wasm_bindgen(js_name = getFieldValueByName)]
    pub fn get_field_value_by_name_api(&self, name: &str) -> Result<String, JsValue> {
        self.get_field_value_by_name(name).map_err(|e| e.into())
    }

    /// field_id로 필드 값을 설정한다.
    ///
    /// 반환: `{ok, fieldId, oldValue, newValue}`
    #[wasm_bindgen(js_name = setFieldValue)]
    pub fn set_field_value(&mut self, field_id: u32, value: &str) -> Result<String, JsValue> {
        self.set_field_value_by_id(field_id, value)
            .map_err(|e| e.into())
    }

    /// 필드 이름으로 값을 설정한다.
    ///
    /// 반환: `{ok, fieldId, oldValue, newValue}`
    #[wasm_bindgen(js_name = setFieldValueByName)]
    pub fn set_field_value_by_name_api(
        &mut self,
        name: &str,
        value: &str,
    ) -> Result<String, JsValue> {
        self.set_field_value_by_name(name, value)
            .map_err(|e| e.into())
    }

    /// 현재 본문 위치에 ClickHere 누름틀 필드를 삽입한다.
    #[wasm_bindgen(js_name = insertClickHereField)]
    pub fn insert_click_here_field_api(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> Result<String, JsValue> {
        self.insert_click_here_field_at(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            guide,
            memo,
            name,
            editable,
        )
        .map_err(|e| e.into())
    }

    /// `insertClickHereField` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, paraIdx, charOffset?, guide?, memo?, name?, editable? }`.
    /// positional 과 동일 동작.
    #[wasm_bindgen(js_name = insertClickHereFieldEx)]
    pub fn insert_click_here_field_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_bool, json_str, json_u32};
        self.insert_click_here_field_at(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "paraIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            &json_str(options_json, "guide").unwrap_or_default(),
            &json_str(options_json, "memo").unwrap_or_default(),
            &json_str(options_json, "name").unwrap_or_default(),
            json_bool(options_json, "editable").unwrap_or(false),
        )
        .map_err(|e| e.into())
    }

    /// 현재 셀/글상자 위치에 ClickHere 누름틀 필드를 삽입한다.
    #[wasm_bindgen(js_name = insertClickHereFieldInCell)]
    pub fn insert_click_here_field_in_cell_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        is_textbox: bool,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> Result<String, JsValue> {
        self.insert_click_here_field_at_in_cell(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            is_textbox,
            guide,
            memo,
            name,
            editable,
        )
        .map_err(|e| e.into())
    }

    /// `insertClickHereFieldInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// charOffset?, isTextbox?, guide?, memo?, name?, editable? }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = insertClickHereFieldInCellEx)]
    pub fn insert_click_here_field_in_cell_ex(
        &mut self,
        options_json: &str,
    ) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_bool, json_str, json_u32};
        self.insert_click_here_field_at_in_cell(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            json_bool(options_json, "isTextbox").unwrap_or(false),
            &json_str(options_json, "guide").unwrap_or_default(),
            &json_str(options_json, "memo").unwrap_or_default(),
            &json_str(options_json, "name").unwrap_or_default(),
            json_bool(options_json, "editable").unwrap_or(false),
        )
        .map_err(|e| e.into())
    }

    /// 현재 중첩 표 cellPath 위치에 ClickHere 누름틀 필드를 삽입한다.
    #[wasm_bindgen(js_name = insertClickHereFieldByPath)]
    pub fn insert_click_here_field_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.insert_click_here_field_at_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
            guide,
            memo,
            name,
            editable,
        )
        .map_err(|e| e.into())
    }

    /// `insertClickHereFieldByPath` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, path: string, charOffset?, guide?,
    /// memo?, name?, editable? }`. `path` 는 cell_path JSON 문자열. positional 과 동일 동작.
    #[wasm_bindgen(js_name = insertClickHereFieldByPathEx)]
    pub fn insert_click_here_field_by_path_ex(
        &mut self,
        options_json: &str,
    ) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_bool, json_str, json_u32};
        let path_json = json_str(options_json, "path").unwrap_or_default();
        let path = DocumentCore::parse_cell_path(&path_json)?;
        self.insert_click_here_field_at_by_path(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            &path,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            &json_str(options_json, "guide").unwrap_or_default(),
            &json_str(options_json, "memo").unwrap_or_default(),
            &json_str(options_json, "name").unwrap_or_default(),
            json_bool(options_json, "editable").unwrap_or(false),
        )
        .map_err(|e| e.into())
    }

    // ─────────────────────────────────────────────
    // 메모 API
    // ─────────────────────────────────────────────

    /// 문서의 메모를 문서 순서대로 반환한다.
    ///
    /// 반환: `[{id,index,author,date,text,place,sectionIndex,paraIndex,
    /// startCharIdx,endCharIdx,path,page,editable,readOnlyReason}]`
    #[wasm_bindgen(js_name = getMemoList)]
    pub fn get_memo_list(&self) -> String {
        self.get_memo_list_json()
    }

    /// 한 문단의 범위에 메모를 넣는다. `json` = `{author,text}`.
    ///
    /// 반환: `{"ok":true,"id":N,"index":N}`. 실패는 `{ok:false,code,message}`.
    #[wasm_bindgen(js_name = insertMemo)]
    pub fn insert_memo(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        start_char_idx: u32,
        end_char_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .insert_memo_json_native(
                section_idx as usize,
                para_idx as usize,
                start_char_idx as usize,
                end_char_idx as usize,
                json,
            )
            .map_err(|e| JsValue::from_str(&e.to_json()))
    }

    /// 표 칸·글상자 안의 범위에 메모를 넣는다.
    ///
    /// `path_json` = `[{"controlIndex":N,"cellIndex":N,"cellParaIndex":N}, …]`.
    #[wasm_bindgen(js_name = insertMemoByPath)]
    pub fn insert_memo_by_path(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        path_json: &str,
        start_char_idx: u32,
        end_char_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .insert_memo_by_path_json_native(
                section_idx as usize,
                para_idx as usize,
                path_json,
                start_char_idx as usize,
                end_char_idx as usize,
                json,
            )
            .map_err(|e| JsValue::from_str(&e.to_json()))
    }

    /// 메모 본문을 바꾼다. 작성자·날짜·서식은 그대로다.
    #[wasm_bindgen(js_name = setMemoText)]
    pub fn set_memo_text(&mut self, id: u32, text: &str) -> Result<String, JsValue> {
        self.core
            .set_memo_text(id, text)
            .map_err(|e| JsValue::from_str(&e.to_json()))
    }

    /// 메모를 지운다. 기준 글자는 남긴다.
    #[wasm_bindgen(js_name = removeMemo)]
    pub fn remove_memo(&mut self, id: u32) -> Result<String, JsValue> {
        self.core
            .remove_memo(id)
            .map_err(|e| JsValue::from_str(&e.to_json()))
    }

    // ─────────────────────────────────────────────
    // 양식 개체(Form Object) API
    // ─────────────────────────────────────────────

    /// 페이지 좌표에서 양식 개체를 찾는다.
    ///
    /// 반환: `{found, sec, para, ci, formType, name, value, caption, text, bbox}`
    #[wasm_bindgen(js_name = getFormObjectAt)]
    pub fn get_form_object_at(&self, page_num: u32, x: f64, y: f64) -> Result<String, JsValue> {
        self.core
            .get_form_object_at_native(page_num, x, y)
            .map_err(|e| e.into())
    }

    /// 양식 개체 값을 조회한다.
    ///
    /// 반환: `{ok, formType, name, value, text, caption, enabled}`
    #[wasm_bindgen(js_name = getFormValue)]
    pub fn get_form_value(&self, sec: u32, para: u32, ci: u32) -> Result<String, JsValue> {
        self.core
            .get_form_value_native(sec as usize, para as usize, ci as usize)
            .map_err(|e| e.into())
    }

    /// 양식 개체 값을 설정한다.
    ///
    /// value_json: `{"value":1}` 또는 `{"text":"입력값"}`
    /// 반환: `{ok}`
    #[wasm_bindgen(js_name = setFormValue)]
    pub fn set_form_value(
        &mut self,
        sec: u32,
        para: u32,
        ci: u32,
        value_json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .set_form_value_native(sec as usize, para as usize, ci as usize, value_json)
            .map_err(|e| e.into())
    }

    /// 셀 내부 양식 개체 값을 설정한다.
    ///
    /// table_para: 표를 포함한 최상위 문단 인덱스
    /// table_ci: 표 컨트롤 인덱스
    /// cell_idx: 셀 인덱스
    /// cell_para: 셀 내 문단 인덱스
    /// form_ci: 셀 내 양식 컨트롤 인덱스
    /// value_json: `{"value":1}` 또는 `{"text":"입력값"}`
    /// 반환: `{ok}`
    #[wasm_bindgen(js_name = setFormValueInCell)]
    pub fn set_form_value_in_cell(
        &mut self,
        sec: u32,
        table_para: u32,
        table_ci: u32,
        cell_idx: u32,
        cell_para: u32,
        form_ci: u32,
        value_json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .set_form_value_in_cell_native(
                sec as usize,
                table_para as usize,
                table_ci as usize,
                cell_idx as usize,
                cell_para as usize,
                form_ci as usize,
                value_json,
            )
            .map_err(|e| e.into())
    }

    /// `setFormValueInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sec, tablePara, tableCi, cellIdx, cellPara, formCi, value: object }`.
    /// positional 과 동일 동작.
    #[wasm_bindgen(js_name = setFormValueInCellEx)]
    pub fn set_form_value_in_cell_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_object, json_u32};
        let value_json = json_object(options_json, "value").unwrap_or_else(|| "{}".to_string());
        self.core
            .set_form_value_in_cell_native(
                json_u32(options_json, "sec").unwrap_or(0) as usize,
                json_u32(options_json, "tablePara").unwrap_or(0) as usize,
                json_u32(options_json, "tableCi").unwrap_or(0) as usize,
                json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
                json_u32(options_json, "cellPara").unwrap_or(0) as usize,
                json_u32(options_json, "formCi").unwrap_or(0) as usize,
                &value_json,
            )
            .map_err(|e| e.into())
    }

    /// 양식 개체 상세 정보를 반환한다 (properties 포함).
    ///
    /// 반환: `{ok, formType, name, value, text, caption, enabled, width, height, foreColor, backColor, properties}`
    #[wasm_bindgen(js_name = getFormObjectInfo)]
    pub fn get_form_object_info(&self, sec: u32, para: u32, ci: u32) -> Result<String, JsValue> {
        self.core
            .get_form_object_info_native(sec as usize, para as usize, ci as usize)
            .map_err(|e| e.into())
    }

    // ── 검색/치환 API ──

    /// 문서 텍스트 검색
    ///
    /// [#3865] `include_cells` 를 참으로 주면 표 셀 안의 일반 텍스트 매치도 돌려준다. 그 경우
    /// 결과에 `cellContext`(parentPara·ctrlIdx·cellIdx·cellPara)가 실리므로, 호출자는
    /// 그 좌표로 커서를 옮길 수 있어야 한다. 생략하면 종전대로 본문만 본다.
    #[wasm_bindgen(js_name = searchText)]
    pub fn search_text(
        &self,
        query: &str,
        from_sec: u32,
        from_para: u32,
        from_char: u32,
        forward: bool,
        case_sensitive: bool,
        include_cells: Option<bool>,
    ) -> Result<String, JsValue> {
        self.core
            .search_text_native(
                query,
                from_sec as usize,
                from_para as usize,
                from_char as usize,
                forward,
                case_sensitive,
                // [#3865] 미지정이면 종전 동작(본문만) — 인자를 6개만 넘기던 기존 호출자 무회귀.
                include_cells.unwrap_or(false),
            )
            .map_err(|e| e.into())
    }

    /// 문서 전체 검색 (모든 매치 반환)
    #[wasm_bindgen(js_name = searchAllText)]
    pub fn search_all_text(
        &self,
        query: &str,
        case_sensitive: bool,
        include_cells: bool,
    ) -> Result<String, JsValue> {
        self.core
            .search_all_text_native(query, case_sensitive, include_cells)
            .map_err(|e| e.into())
    }

    /// 텍스트 치환 (단일)
    #[wasm_bindgen(js_name = replaceText)]
    pub fn replace_text(
        &mut self,
        sec: u32,
        para: u32,
        char_offset: u32,
        length: u32,
        new_text: &str,
    ) -> Result<String, JsValue> {
        self.core
            .replace_text_native(
                sec as usize,
                para as usize,
                char_offset as usize,
                length as usize,
                new_text,
            )
            .map_err(|e| e.into())
    }

    /// 단일 치환 (검색어 기반) — 첫 번째 매치만 교체
    #[wasm_bindgen(js_name = replaceOne)]
    pub fn replace_one(
        &mut self,
        query: &str,
        new_text: &str,
        case_sensitive: bool,
    ) -> Result<String, JsValue> {
        self.core
            .replace_one_native(query, new_text, case_sensitive)
            .map_err(|e| e.into())
    }

    /// 전체 치환
    #[wasm_bindgen(js_name = replaceAll)]
    pub fn replace_all(
        &mut self,
        query: &str,
        new_text: &str,
        case_sensitive: bool,
    ) -> Result<String, JsValue> {
        self.core
            .replace_all_native(query, new_text, case_sensitive)
            .map_err(|e| e.into())
    }

    /// 글로벌 쪽 번호에 해당하는 첫 문단 위치 반환
    #[wasm_bindgen(js_name = getPositionOfPage)]
    pub fn get_position_of_page(&self, global_page: u32) -> Result<String, JsValue> {
        self.core
            .get_position_of_page_native(global_page as usize)
            .map_err(|e| e.into())
    }

    /// 위치에 해당하는 글로벌 쪽 번호 반환
    #[wasm_bindgen(js_name = getPageOfPosition)]
    pub fn get_page_of_position(&self, section_idx: u32, para_idx: u32) -> Result<String, JsValue> {
        self.core
            .get_page_of_position_native(section_idx as usize, para_idx as usize)
            .map_err(|e| e.into())
    }

    /// 커서 위치의 필드 범위 정보를 조회한다 (본문 문단).
    ///
    /// 반환: `{inField, fieldId?, startCharIdx?, endCharIdx?, isGuide?, guideName?, editableInForm?}`
    #[wasm_bindgen(js_name = getFieldInfoAt)]
    pub fn get_field_info_at_api(
        &self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> String {
        self.get_field_info_at(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
    }

    /// 커서 위치의 필드 범위 정보를 조회한다 (셀/글상자 내 문단).
    #[wasm_bindgen(js_name = getFieldInfoAtInCell)]
    pub fn get_field_info_at_in_cell_api(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        is_textbox: bool,
    ) -> String {
        self.get_field_info_at_in_cell(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            is_textbox,
        )
    }

    /// `getFieldInfoAtInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// charOffset?, isTextbox? }`. positional 과 동일 동작(String 반환).
    #[wasm_bindgen(js_name = getFieldInfoAtInCellEx)]
    pub fn get_field_info_at_in_cell_ex(&self, options_json: &str) -> String {
        use crate::document_core::helpers::{json_bool, json_u32};
        self.get_field_info_at_in_cell(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            json_bool(options_json, "isTextbox").unwrap_or(false),
        )
    }

    /// 커서 위치의 누름틀 필드를 제거한다 (본문 문단).
    #[wasm_bindgen(js_name = removeFieldAt)]
    pub fn remove_field_at_api(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> String {
        match self.remove_field_at(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        ) {
            Ok(s) => s,
            Err(e) => {
                let escaped = e.to_string().replace('\\', "\\\\").replace('"', "\\\"");
                format!("{{\"ok\":false,\"error\":\"{}\"}}", escaped)
            }
        }
    }

    /// 커서 위치의 누름틀 필드를 제거한다 (셀/글상자 내 문단).
    #[wasm_bindgen(js_name = removeFieldAtInCell)]
    pub fn remove_field_at_in_cell_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        is_textbox: bool,
    ) -> String {
        match self.remove_field_at_in_cell(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            is_textbox,
        ) {
            Ok(s) => s,
            Err(e) => {
                let escaped = e.to_string().replace('\\', "\\\\").replace('"', "\\\"");
                format!("{{\"ok\":false,\"error\":\"{}\"}}", escaped)
            }
        }
    }

    /// `removeFieldAtInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// charOffset?, isTextbox? }`. positional 과 동일 동작(String 반환).
    #[wasm_bindgen(js_name = removeFieldAtInCellEx)]
    pub fn remove_field_at_in_cell_ex(&mut self, options_json: &str) -> String {
        use crate::document_core::helpers::{json_bool, json_u32};
        match self.remove_field_at_in_cell(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            json_bool(options_json, "isTextbox").unwrap_or(false),
        ) {
            Ok(s) => s,
            Err(e) => {
                let escaped = e.to_string().replace('\\', "\\\\").replace('"', "\\\"");
                format!("{{\"ok\":false,\"error\":\"{}\"}}", escaped)
            }
        }
    }

    /// 활성 필드를 설정한다 (본문 문단 — 안내문 숨김용).
    #[wasm_bindgen(js_name = setActiveField)]
    pub fn set_active_field_api(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> bool {
        self.set_active_field(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
    }

    /// 활성 필드를 설정한다 (셀/글상자 내 문단 — 안내문 숨김용).
    /// 변경이 발생하면 true를 반환한다.
    #[wasm_bindgen(js_name = setActiveFieldInCell)]
    pub fn set_active_field_in_cell_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        is_textbox: bool,
    ) -> bool {
        self.set_active_field_in_cell(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            is_textbox,
        )
    }

    /// `setActiveFieldInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// charOffset?, isTextbox? }`. positional 과 동일 동작(bool 반환).
    #[wasm_bindgen(js_name = setActiveFieldInCellEx)]
    pub fn set_active_field_in_cell_ex(&mut self, options_json: &str) -> bool {
        use crate::document_core::helpers::{json_bool, json_u32};
        self.set_active_field_in_cell(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            json_bool(options_json, "isTextbox").unwrap_or(false),
        )
    }

    /// path 기반: 중첩 표 셀의 필드 범위 정보를 조회한다.
    #[wasm_bindgen(js_name = getFieldInfoAtByPath)]
    pub fn get_field_info_at_by_path_api(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
    ) -> String {
        match DocumentCore::parse_cell_path(path_json) {
            Ok(path) => self.get_field_info_at_by_path(
                section_idx as usize,
                parent_para_idx as usize,
                &path,
                char_offset as usize,
            ),
            Err(_) => r#"{"inField":false}"#.to_string(),
        }
    }

    /// path 기반: 중첩 표 셀 내 활성 필드를 설정한다.
    #[wasm_bindgen(js_name = setActiveFieldByPath)]
    pub fn set_active_field_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
    ) -> bool {
        match DocumentCore::parse_cell_path(path_json) {
            Ok(path) => self.set_active_field_by_path(
                section_idx as usize,
                parent_para_idx as usize,
                &path,
                char_offset as usize,
            ),
            Err(_) => false,
        }
    }

    /// 활성 필드를 해제한다 (안내문 다시 표시).
    #[wasm_bindgen(js_name = clearActiveField)]
    pub fn clear_active_field_api(&mut self) {
        self.clear_active_field();
    }

    // ─── 누름틀 속성 조회/수정 API ──────────────────────────────

    /// 누름틀 필드의 속성을 조회한다.
    ///
    /// 반환: JSON `{"ok":true,"guide":"안내문","memo":"메모","name":"이름","editable":true}`
    #[wasm_bindgen(js_name = getClickHereProps)]
    pub fn get_click_here_props(&self, field_id: u32) -> String {
        use crate::model::control::{Control, FieldType};
        // 문서 전체에서 fieldId로 필드 찾기
        for sec in &self.document.sections {
            for para in &sec.paragraphs {
                for ctrl in &para.controls {
                    if let Control::Field(f) = ctrl {
                        if f.field_id == field_id && f.field_type == FieldType::ClickHere {
                            return self.format_click_here_props(f);
                        }
                    }
                }
                // 표/글상자 내부도 탐색
                for ctrl in &para.controls {
                    let paras: Vec<&crate::model::paragraph::Paragraph> = match ctrl {
                        Control::Table(t) => t.cells.iter().flat_map(|c| &c.paragraphs).collect(),
                        Control::Shape(s) => s
                            .drawing()
                            .and_then(|d| d.text_box.as_ref())
                            .map(|tb| tb.paragraphs.iter().collect())
                            .unwrap_or_default(),
                        _ => Vec::new(),
                    };
                    for p in paras {
                        for c in &p.controls {
                            if let Control::Field(f) = c {
                                if f.field_id == field_id && f.field_type == FieldType::ClickHere {
                                    return self.format_click_here_props(f);
                                }
                            }
                        }
                    }
                }
            }
        }
        r#"{"ok":false}"#.to_string()
    }

    /// ClickHere 필드 속성을 JSON으로 포맷한다.
    fn format_click_here_props(&self, f: &crate::model::control::Field) -> String {
        let guide = f.guide_text().unwrap_or("");
        let memo = f.memo_text().unwrap_or("");
        // 필드 이름: ctrl_data_name → command Name: 키 순서
        let name = f
            .ctrl_data_name
            .as_deref()
            .filter(|s| !s.is_empty())
            .or_else(|| f.extract_wstring_value("Name:"))
            .unwrap_or("");
        let editable = f.is_editable_in_form();
        format!(
            "{{\"ok\":true,\"guide\":\"{}\",\"memo\":\"{}\",\"name\":\"{}\",\"editable\":{}}}",
            json_escape(guide),
            json_escape(memo),
            json_escape(name),
            editable,
        )
    }

    /// 누름틀 필드의 속성을 수정한다.
    ///
    /// 반환: JSON `{"ok":true}` 또는 `{"ok":false}`
    #[wasm_bindgen(js_name = updateClickHereProps)]
    pub fn update_click_here_props(
        &mut self,
        field_id: u32,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> String {
        use crate::model::control::{Control, Field, FieldType};

        let new_props_bit = if editable { 1u32 } else { 0u32 };

        // 필드를 찾아 수정하고, ctrl_data_records 바이너리도 갱신
        fn update_field_in_para(
            para: &mut crate::model::paragraph::Paragraph,
            field_id: u32,
            guide: &str,
            memo: &str,
            new_props_bit: u32,
            new_name: &str,
        ) -> bool {
            for (ci, ctrl) in para.controls.iter_mut().enumerate() {
                if let Control::Field(f) = ctrl {
                    if f.field_id == field_id && f.field_type == FieldType::ClickHere {
                        // guide/memo가 원본과 동일하면 command 문자열을 보존한다.
                        // 원본 command에는 trailing space 등이 포함될 수 있으므로
                        // 불필요한 재구축을 피해야 한컴 호환성이 유지된다.
                        let orig_guide = f.guide_text().unwrap_or("").to_string();
                        let orig_memo = f.memo_text().unwrap_or("").to_string();
                        if guide != orig_guide || memo != orig_memo {
                            // guide 또는 memo가 변경되었으므로 command 재구축
                            let new_command = Field::build_clickhere_command(guide, memo);
                            f.command = new_command;
                        }
                        // command가 변경되지 않았으면 원본 보존

                        f.properties = (f.properties & !1) | new_props_bit;
                        f.ctrl_data_name = if new_name.is_empty() {
                            None
                        } else {
                            Some(new_name.to_string())
                        };
                        // ctrl_data_records 바이너리 갱신
                        crate::document_core::queries::field_query::write_ctrl_data_name(
                            &mut para.ctrl_data_records,
                            ci,
                            new_name,
                        );
                        return true;
                    }
                }
            }
            false
        }

        for sec in &mut self.document.sections {
            sec.raw_stream = None;
            for para in &mut sec.paragraphs {
                if update_field_in_para(para, field_id, guide, memo, new_props_bit, name) {
                    self.invalidate_page_tree_cache();
                    return r#"{"ok":true}"#.to_string();
                }
                // 표/글상자 내부
                for ctrl in &mut para.controls {
                    let found = match ctrl {
                        Control::Table(t) => t.cells.iter_mut().any(|c| {
                            c.paragraphs.iter_mut().any(|p| {
                                update_field_in_para(p, field_id, guide, memo, new_props_bit, name)
                            })
                        }),
                        Control::Shape(s) => {
                            if let Some(tb) = s.drawing_mut().and_then(|d| d.text_box.as_mut()) {
                                tb.paragraphs.iter_mut().any(|p| {
                                    update_field_in_para(
                                        p,
                                        field_id,
                                        guide,
                                        memo,
                                        new_props_bit,
                                        name,
                                    )
                                })
                            } else {
                                false
                            }
                        }
                        _ => false,
                    };
                    if found {
                        self.invalidate_page_tree_cache();
                        return r#"{"ok":true}"#.to_string();
                    }
                }
            }
        }
        r#"{"ok":false}"#.to_string()
    }

    /// 커서 좌표(list/para/pos)로 글자 서식을 건다 — 웹한글컨트롤 `Run("CharShape*")`.
    ///
    /// `endPos` 가 문단 길이를 넘으면 끝까지로 자른다. `pos` 는 코드 유닛이다.
    #[wasm_bindgen(js_name = applyCharFormatAtCursor)]
    pub fn apply_char_format_at_cursor_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        start_pos: u32,
        end_pos: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_char_format_at_cursor(
            list_id,
            para_in_list as usize,
            start_pos as usize,
            end_pos as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// 커서 좌표(list/para/pos)로 글자를 지운다 — 웹한글컨트롤 `Run("Delete*")`.
    ///
    /// `pos` 는 코드 유닛이고, 빈 범위면 아무 일도 하지 않는다.
    #[wasm_bindgen(js_name = deleteAtCursor)]
    pub fn delete_at_cursor_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        start_pos: u32,
        end_pos: u32,
    ) -> Result<String, JsValue> {
        self.delete_at_cursor(
            list_id,
            para_in_list as usize,
            start_pos as usize,
            end_pos as usize,
        )
        .map_err(|e| e.into())
    }

    /// 커서가 든 셀을 기준으로 표를 고친다 — 웹한글컨트롤 `Run("TableInsert*"·"TableDelete*")`.
    ///
    /// `op` 는 `insertRowAbove`·`insertRowBelow`·`insertColLeft`·`insertColRight`·
    /// `deleteRow`·`deleteCol`.
    #[wasm_bindgen(js_name = tableEditAtCursor)]
    pub fn table_edit_at_cursor_api(&mut self, list_id: u32, op: &str) -> Result<String, JsValue> {
        self.table_edit_at_cursor(list_id, op).map_err(|e| e.into())
    }

    /// 문서가 담은 컨트롤 사슬 — `HeadCtrl`·`LastCtrl` 과 `Next`·`Prev` 가 딛는다.
    #[wasm_bindgen(js_name = getControls)]
    pub fn get_controls(&self) -> String {
        self.controls_json()
    }

    /// 컨트롤 하나를 지운다 — 웹한글컨트롤 `DeleteCtrl`.
    #[wasm_bindgen(js_name = deleteControlAt)]
    pub fn delete_control_at_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        control_index: u32,
    ) -> Result<String, JsValue> {
        self.delete_control_at(list_id, para_in_list as usize, control_index as usize)
            .map_err(|e| e.into())
    }

    /// 자동 번호 끼우기 — `InsertPageNum`·`InsertCpNo`·`InsertTpNo`. `kind` 는
    /// `page`·`current`·`total`.
    #[wasm_bindgen(js_name = insertAutoNumberAtCursor)]
    pub fn insert_auto_number_at_cursor_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        pos: u32,
        kind: &str,
    ) -> Result<String, JsValue> {
        self.insert_auto_number_at_cursor(list_id, para_in_list as usize, pos as usize, kind)
            .map_err(|e| e.into())
    }

    /// 문서 글 전체 — `GetTextFile("TEXT")`. CP949 수치 참조를 적용한 JSON 문자열이다.
    #[wasm_bindgen(js_name = getTextFileText)]
    pub fn get_text_file_text(&self) -> String {
        self.text_file_json()
    }

    /// 문서 글 전체 — `GetTextFile("UNICODE")`. 원문 Unicode JSON 문자열이다.
    #[wasm_bindgen(js_name = getTextFileUnicode)]
    pub fn get_text_file_unicode(&self) -> String {
        self.text_file_unicode_json()
    }

    /// 문서 글을 한글 스캔 차례로 — `InitScan`·`GetText`·`ReleaseScan` 이 쓴다.
    #[wasm_bindgen(js_name = getScanItems)]
    pub fn get_scan_items(&self) -> String {
        self.scan_items_json()
    }

    /// 구역마다 첫 본문 문단 번호 — `MoveSectionUp`·`MoveSectionDown` 이 딛는다.
    #[wasm_bindgen(js_name = getSectionStarts)]
    pub fn get_section_starts(&self) -> String {
        self.section_starts_json()
    }

    /// 나누기 — 웹한글컨트롤 `Run("BreakPage"·"BreakColumn"·"BreakColDef"·"BreakSection")`.
    ///
    /// `kind` 는 `page`·`column`·`colDef`·`section`.
    #[wasm_bindgen(js_name = breakAtCursor)]
    pub fn break_at_cursor_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        pos: u32,
        kind: &str,
    ) -> Result<String, JsValue> {
        self.break_at_cursor(list_id, para_in_list as usize, pos as usize, kind)
            .map_err(|e| e.into())
    }

    /// 인라인 개체를 논리적 캐럿 위치로 원자적으로 옮긴다.
    #[wasm_bindgen(js_name = moveInlineControl)]
    pub fn move_inline_control_api(
        &mut self,
        source_json: &str,
        destination_json: &str,
    ) -> Result<String, JsValue> {
        let source =
            serde_json::from_str(source_json).map_err(|e| JsValue::from_str(&e.to_string()))?;
        let destination = serde_json::from_str(destination_json)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;
        let result = self
            .move_inline_control_native(&source, &destination)
            .map_err(JsValue::from)?;
        serde_json::to_string(&result).map_err(|e| JsValue::from_str(&e.to_string()))
    }

    /// 개체를 한 걸음 옮긴다 — 웹한글컨트롤 `ShapeObjMove*`(걸음 56 HWPUNIT).
    #[wasm_bindgen(js_name = moveControlAt)]
    pub fn move_control_at_api(
        &mut self,
        para_in_list: u32,
        control_index: u32,
        dx: i32,
        dy: i32,
    ) -> Result<String, JsValue> {
        self.move_control_at(para_in_list as usize, control_index as usize, dx, dy)
            .map_err(|e| e.into())
    }

    /// 개체의 앞뒤 순서를 바꾼다 — 웹한글컨트롤 `Run("ShapeObjBringToFront")` 계열.
    ///
    /// `mode` 는 `front`·`back`·`forward`·`backward`·`inFrontOfText`·`behindText`.
    #[wasm_bindgen(js_name = setControlZOrderAt)]
    pub fn set_control_z_order_at_api(
        &mut self,
        para_in_list: u32,
        control_index: u32,
        mode: &str,
    ) -> Result<String, JsValue> {
        self.set_control_z_order_at(para_in_list as usize, control_index as usize, mode)
            .map_err(|e| e.into())
    }

    /// 개체를 뒤집는다 — 웹한글컨트롤 `Run("ShapeObjHorzFlip")` 계열.
    #[wasm_bindgen(js_name = setControlFlipAt)]
    pub fn set_control_flip_at_api(
        &mut self,
        para_in_list: u32,
        control_index: u32,
        vertical: bool,
        org_state: bool,
    ) -> Result<String, JsValue> {
        self.set_control_flip_at(
            para_in_list as usize,
            control_index as usize,
            vertical,
            org_state,
        )
        .map_err(|e| e.into())
    }

    /// 쪽 하나의 글 — 웹한글컨트롤 `GetPageText`.
    #[wasm_bindgen(js_name = getPageText)]
    pub fn page_text_api(&self, page_index: u32) -> Result<String, JsValue> {
        self.page_text(page_index as usize).map_err(|e| e.into())
    }

    /// 개체 사이를 도는 차례(쪽·z) — 웹한글컨트롤 `Run("ShapeObjNext/PrevObject")` 용.
    #[wasm_bindgen(js_name = getObjectCycle)]
    pub fn object_cycle_api(&self) -> Result<String, JsValue> {
        self.object_cycle_json().map_err(|e| e.into())
    }

    /// 스트림 자리를 글자 번호로 옮긴다 — 글자 번호를 받는 코어 API 에 넘길 때 쓴다.
    #[wasm_bindgen(js_name = getCharIndexAtStreamPos)]
    pub fn char_index_at_api(
        &self,
        list_id: u32,
        para_in_list: u32,
        pos: u32,
    ) -> Result<String, JsValue> {
        self.char_index_at(list_id, para_in_list as usize, pos as usize)
            .map_err(|e| e.into())
    }

    /// 쪽마다 캐럿이 설 수 있는 첫 자리 — 웹한글컨트롤 `Run("MovePage*")` 용.
    #[wasm_bindgen(js_name = getPageCaretStarts)]
    pub fn page_caret_starts_api(&self) -> Result<String, JsValue> {
        self.page_caret_starts().map_err(|e| e.into())
    }

    /// 개체에 글상자를 붙이거나 뗀다 — 웹한글컨트롤 `Run("ShapeObjAttach/DetachTextBox")`.
    #[wasm_bindgen(js_name = setTextBoxAt)]
    pub fn set_text_box_at_api(
        &mut self,
        para_in_list: u32,
        control_index: u32,
        attach: bool,
    ) -> Result<String, JsValue> {
        self.set_text_box_at(para_in_list as usize, control_index as usize, attach)
            .map_err(|e| e.into())
    }

    /// 개체에 캡션을 붙인다 — 웹한글컨트롤 `Run("ShapeObjAttachCaption")`.
    #[wasm_bindgen(js_name = attachCaptionAt)]
    pub fn attach_caption_at_api(
        &mut self,
        para_in_list: u32,
        control_index: u32,
    ) -> Result<String, JsValue> {
        self.attach_caption_at(para_in_list as usize, control_index as usize)
            .map_err(|e| e.into())
    }

    /// 개체에서 캡션을 뗀다 — 웹한글컨트롤 `Run("ShapeObjDetachCaption")`.
    #[wasm_bindgen(js_name = detachCaptionAt)]
    pub fn detach_caption_at_api(
        &mut self,
        para_in_list: u32,
        control_index: u32,
    ) -> Result<String, JsValue> {
        self.detach_caption_at(para_in_list as usize, control_index as usize)
            .map_err(|e| e.into())
    }

    /// 개체 크기를 한 걸음 바꾼다 — 웹한글컨트롤 `ShapeObjResize*`(걸음 283 HWPUNIT).
    #[wasm_bindgen(js_name = resizeControlAt)]
    pub fn resize_control_at_api(
        &mut self,
        para_in_list: u32,
        control_index: u32,
        d_width: i32,
        d_height: i32,
    ) -> Result<String, JsValue> {
        self.resize_control_at(
            para_in_list as usize,
            control_index as usize,
            d_width,
            d_height,
        )
        .map_err(|e| e.into())
    }

    /// 개체의 잠금을 켜고 끈다 — 웹한글컨트롤 `ShapeObjLock`·`ShapeObjUnlockAll`.
    ///
    /// 문단·컨트롤 번호에 `u32::MAX` 를 주면 "모두"라는 뜻이다(모두 풀기가 쓴다).
    #[wasm_bindgen(js_name = setControlLock)]
    pub fn set_control_lock_api(
        &mut self,
        para_in_list: u32,
        control_index: u32,
        locked: bool,
    ) -> Result<String, JsValue> {
        let some = |v: u32| (v != u32::MAX).then_some(v as usize);
        self.set_control_lock(some(para_in_list), some(control_index), locked)
            .map_err(|e| e.into())
    }

    /// 커서가 든 필드의 상태 — 웹한글컨트롤 `CurFieldState`.
    #[wasm_bindgen(js_name = getCurFieldState)]
    pub fn get_cur_field_state(&self, list_id: u32, para_in_list: u32, pos: u32) -> u32 {
        self.cur_field_state(list_id, para_in_list as usize, pos as usize)
    }

    /// 커서가 든 셀의 모양 — 웹한글컨트롤 `CellShape` 파라미터셋.
    #[wasm_bindgen(js_name = getCellShapeSet)]
    pub fn get_cell_shape_set(&self, list_id: u32) -> String {
        self.cell_shape_set_json(list_id)
    }

    /// 본문에 놓인 개체 목록 — `Run("ShapeObjNextObject")` 따위가 딛는다.
    #[wasm_bindgen(js_name = getObjects)]
    pub fn get_objects(&self) -> String {
        self.objects_json()
    }

    /// 커서 자리에서 문단을 가른다 — 웹한글컨트롤 `Run("BreakPara")`.
    #[wasm_bindgen(js_name = splitParaAtCursor)]
    pub fn split_para_at_cursor_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        pos: u32,
    ) -> Result<String, JsValue> {
        self.split_para_at_cursor(list_id, para_in_list as usize, pos as usize)
            .map_err(|e| e.into())
    }

    /// 커서 좌표(list/para/pos)에 글자를 끼운다 — 웹한글컨트롤 `Run("Insert*Space")`.
    #[wasm_bindgen(js_name = insertTextAtCursor)]
    pub fn insert_text_at_cursor_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        pos: u32,
        text: &str,
    ) -> Result<String, JsValue> {
        self.insert_text_at_cursor(list_id, para_in_list as usize, pos as usize, text)
            .map_err(|e| e.into())
    }

    /// 커서가 든 셀에서 `(endRow, endCol)` 까지를 하나로 합친다 — `Run("TableMergeCell")`.
    #[wasm_bindgen(js_name = tableMergeAtCursor)]
    pub fn table_merge_at_cursor_api(
        &mut self,
        list_id: u32,
        end_row: u32,
        end_col: u32,
    ) -> Result<String, JsValue> {
        self.table_merge_at_cursor(list_id, end_row as u16, end_col as u16)
            .map_err(|e| e.into())
    }

    /// 셀 블록이 덮은 칸들의 글을 비운다 — `Run("TableDeleteCell")`. 규약은 merge 와 같다.
    #[wasm_bindgen(js_name = clearTableCellsAtCursor)]
    pub fn clear_table_cells_at_cursor_api(
        &mut self,
        list_id: u32,
        end_row: u32,
        end_col: u32,
    ) -> Result<String, JsValue> {
        self.clear_table_cells_at_cursor(list_id, end_row as u16, end_col as u16)
            .map_err(|e| e.into())
    }

    /// 커서 좌표(list/para)로 문단 서식을 건다 — 웹한글컨트롤 `Run("ParagraphShape*")`.
    #[wasm_bindgen(js_name = applyParaFormatAtCursor)]
    pub fn apply_para_format_at_cursor_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_para_format_at_cursor(list_id, para_in_list as usize, props_json)
            .map_err(|e| e.into())
    }

    /// 지금 단어의 끝 — `MoveWordEnd` 가 가는 자리(다음 공백 글자의 자리).
    #[wasm_bindgen(js_name = getWordEnd)]
    pub fn get_word_end(&self, list_id: u32, para_in_list: u32, pos: u32) -> String {
        self.word_end_json(list_id, para_in_list as usize, pos as usize)
    }

    /// 단어가 시작하는 자리들 — `MoveNextWord` 류가 딛는 눈금(코드 유닛).
    #[wasm_bindgen(js_name = getWordStarts)]
    pub fn get_word_starts(&self, list_id: u32, para_in_list: u32) -> String {
        self.word_starts_json(list_id, para_in_list as usize)
    }

    /// 줄이 시작하는 자리들 — `MoveLineBegin`·`MoveLineEnd` 가 딛는 값(코드 유닛).
    #[wasm_bindgen(js_name = getLineStarts)]
    pub fn get_line_starts(&self, list_id: u32, para_in_list: u32) -> String {
        self.line_starts_json(list_id, para_in_list as usize)
    }

    /// 캐럿이 설 수 있는 자리들 — 한 글자 이동(`MoveNextChar` 류)이 딛는 눈금.
    #[wasm_bindgen(js_name = getCaretStops)]
    pub fn get_caret_stops(&self, list_id: u32, para_in_list: u32) -> String {
        self.caret_stops_json(list_id, para_in_list as usize)
    }

    /// 문단 하나의 캐럿 경계 — `MoveParaBegin`·`MoveParaEnd`·`MoveListBegin/End` 가 딛는 값.
    #[wasm_bindgen(js_name = getParaBounds)]
    pub fn get_para_bounds(&self, list_id: u32, para_in_list: u32) -> String {
        self.para_bounds_json(list_id, para_in_list as usize)
    }

    /// 커서 자리의 글자 모양 — 웹한글컨트롤 `CharShape` 파라미터셋 값(§8.2.2).
    ///
    /// 항목 이름과 단위는 한글 것이다(`Height` 는 HWPUNIT, `AlignType` 은 코드값).
    #[wasm_bindgen(js_name = getCharShapeSet)]
    pub fn get_char_shape_set(&self, list_id: u32, para_in_list: u32, pos: u32) -> String {
        self.char_shape_set_json(list_id, para_in_list as usize, pos as usize)
    }

    /// 커서 자리의 문단 모양 — 웹한글컨트롤 `ParaShape` 파라미터셋 값(§8.2.11).
    #[wasm_bindgen(js_name = getParaShapeSet)]
    pub fn get_para_shape_set(&self, list_id: u32, para_in_list: u32) -> String {
        self.para_shape_set_json(list_id, para_in_list as usize)
    }

    /// 아무 내용도 없는 빈 문서인가 — 웹한글컨트롤 `IsEmpty`(§8.2.7).
    #[wasm_bindgen(js_name = isEmptyDocument)]
    pub fn is_empty_document_api(&self) -> bool {
        self.is_empty_document()
    }

    /// 한글 커서 좌표(list/para/pos)에 누름틀을 넣는다 — 웹한글컨트롤 `CreateField`.
    ///
    /// `pos` 는 코드 유닛이다(확장 컨트롤 하나가 8칸). 글자 번호를 받는
    /// `insertClickHereField` 와 좌표계가 다르다.
    #[wasm_bindgen(js_name = insertClickHereFieldAtCursor)]
    pub fn insert_click_here_field_at_cursor_api(
        &mut self,
        list_id: u32,
        para_in_list: u32,
        pos: u32,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> Result<String, JsValue> {
        self.insert_click_here_field_at_cursor(
            list_id,
            para_in_list as usize,
            pos as usize,
            guide,
            memo,
            name,
            editable,
        )
        .map_err(|e| e.into())
    }

    /// 한글 커서 좌표계(`list`/`para`/`pos`)를 쓰는 데 필요한 문서 사실.
    ///
    /// 리스트 표와 루트 리스트의 시작·끝 위치를 함께 준다. 자세한 계약은
    /// `DocumentCore::get_cursor_model_json`.
    #[wasm_bindgen(js_name = getCursorModel)]
    pub fn get_cursor_model(&self) -> String {
        self.get_cursor_model_json()
    }

    /// 문서에 저장된 캐럿 위치를 **원본 값 그대로** 돌려준다.
    ///
    /// 한글은 문서를 열면 이 자리에 캐럿을 놓는다(`GetPos` 첫 답과 일치). studio 의
    /// `getCaretPosition` 은 이 값을 구역/문단으로 해석하지만, 여기서는 해석하지 않는다 —
    /// `list` 는 구역 번호가 아니라 리스트 아이디다.
    #[wasm_bindgen(js_name = getStoredCaret)]
    pub fn get_stored_caret(&self) -> String {
        let props = &self.document.doc_properties;
        format!(
            "{{\"list\":{},\"para\":{},\"pos\":{}}}",
            props.caret_list_id, props.caret_para_id, props.caret_char_pos,
        )
    }

    /// 필드 이름을 바꾼다 — 누름틀과 셀 필드를 모두 다룬다.
    ///
    /// `updateClickHereProps` 는 누름틀 전용이라 셀 필드에서 `{"ok":false}` 를 돌려준다.
    /// 웹한글컨트롤 `RenameField`(§8.3.36)의 계약은 두 갈래를 가리지 않는다.
    ///
    /// 반환: JSON `{"ok":true,"renamed":N}` / `{"ok":false,"renamed":0}`
    #[wasm_bindgen(js_name = renameField)]
    pub fn rename_field_api(&mut self, oldname: &str, newname: &str) -> String {
        match self.rename_field_by_name(oldname, newname) {
            Ok(json) => json,
            Err(_) => r#"{"ok":false,"renamed":0}"#.to_string(),
        }
    }

    // ─── 경로 기반 중첩 표 API ───────────────────────────────

    /// 경로 기반 커서 좌표 조회 (중첩 표용).
    ///
    /// path_json: `[{"controlIndex":N,"cellIndex":N,"cellParaIndex":N}, ...]`
    /// 반환: JSON `{"pageIndex":N,"x":F,"y":F,"height":F}`
    #[wasm_bindgen(js_name = getCursorRectByPath)]
    pub fn get_cursor_rect_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_cursor_rect_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            path_json,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// [#2021] 경로 기반 커서 좌표 조회 + 페이지 힌트 — 직전 캐럿 페이지를 전달하면
    /// 해당 페이지(±1)를 먼저 탐색해, 거대 표 문서에서 캐시 무효화 직후의 선형 페이지
    /// 재빌드 비용을 피한다. 힌트가 틀려도 종전 전체 탐색으로 fallback (좌표 불변).
    #[wasm_bindgen(js_name = getCursorRectByPathNear)]
    pub fn get_cursor_rect_by_path_near(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
        hint_page: u32,
    ) -> Result<String, JsValue> {
        self.get_cursor_rect_by_path_with_hint(
            section_idx as usize,
            parent_para_idx as usize,
            path_json,
            char_offset as usize,
            Some(hint_page),
        )
        .map_err(|e| e.into())
    }

    /// 경로 기반 셀 정보 조회 (중첩 표용).
    ///
    /// 반환: JSON `{"row":N,"col":N,"rowSpan":N,"colSpan":N}`
    #[wasm_bindgen(js_name = getCellInfoByPath)]
    pub fn get_cell_info_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
    ) -> Result<String, JsValue> {
        self.get_cell_info_by_path_native(section_idx as usize, parent_para_idx as usize, path_json)
            .map_err(|e| e.into())
    }

    /// 경로 기반 표 차원 조회 (중첩 표용).
    ///
    /// 반환: JSON `{"rowCount":N,"colCount":N,"cellCount":N}`
    #[wasm_bindgen(js_name = getTableDimensionsByPath)]
    pub fn get_table_dimensions_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
    ) -> Result<String, JsValue> {
        self.get_table_dimensions_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            path_json,
        )
        .map_err(|e| e.into())
    }

    /// 경로 기반 표 셀 바운딩박스 조회 (중첩 표용).
    ///
    /// 반환: JSON 배열 `[{"cellIdx":N,"row":N,"col":N,...,"x":F,"y":F,"w":F,"h":F}, ...]`
    #[wasm_bindgen(js_name = getTableCellBboxesByPath)]
    pub fn get_table_cell_bboxes_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
    ) -> Result<String, JsValue> {
        self.get_table_cell_bboxes_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            path_json,
        )
        .map_err(|e| e.into())
    }

    /// 경로 기반 수직 커서 이동 (중첩 표용).
    ///
    /// 반환: JSON `{DocumentPosition + CursorRect + preferredX}`
    #[wasm_bindgen(js_name = moveVerticalByPath)]
    pub fn move_vertical_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
        delta: i32,
        preferred_x: f64,
    ) -> Result<String, JsValue> {
        self.move_vertical_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            path_json,
            char_offset as usize,
            delta,
            preferred_x,
        )
        .map_err(|e| e.into())
    }

    // ─── Phase 4: Selection API ──────────────────────────────

    /// 본문 선택 영역의 줄별 사각형을 반환한다.
    ///
    /// 반환: JSON 배열 `[{"pageIndex":N,"x":F,"y":F,"width":F,"height":F}, ...]`
    #[wasm_bindgen(js_name = getSelectionRects)]
    pub fn get_selection_rects(
        &self,
        section_idx: u32,
        start_para_idx: u32,
        start_char_offset: u32,
        end_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_selection_rects_native(
            section_idx as usize,
            start_para_idx as usize,
            start_char_offset as usize,
            end_para_idx as usize,
            end_char_offset as usize,
            None,
            None,
        )
        .map_err(|e| e.into())
    }

    /// 셀 내 선택 영역의 줄별 사각형을 반환한다.
    ///
    /// 반환: JSON 배열 `[{"pageIndex":N,"x":F,"y":F,"width":F,"height":F}, ...]`
    #[wasm_bindgen(js_name = getSelectionRectsInCell)]
    pub fn get_selection_rects_in_cell(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        start_cell_para_idx: u32,
        start_char_offset: u32,
        end_cell_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_selection_rects_native(
            section_idx as usize,
            start_cell_para_idx as usize,
            start_char_offset as usize,
            end_cell_para_idx as usize,
            end_char_offset as usize,
            Some((
                parent_para_idx as usize,
                control_idx as usize,
                cell_idx as usize,
            )),
            None,
        )
        .map_err(|e| e.into())
    }

    /// `getSelectionRectsInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, startCellParaIdx,
    /// startCharOffset, endCellParaIdx, endCharOffset, startPageHint?, endPageHint? }`.
    /// page hint가 누락되거나 유효하지 않으면 positional 과 동일한 전체 탐색을 사용한다.
    #[wasm_bindgen(js_name = getSelectionRectsInCellEx)]
    pub fn get_selection_rects_in_cell_ex(&self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::json_u32;
        self.get_selection_rects_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCharOffset").unwrap_or(0) as usize,
            json_u32(options_json, "endCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "endCharOffset").unwrap_or(0) as usize,
            Some((
                json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
                json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
                json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            )),
            json_u32(options_json, "startPageHint").zip(json_u32(options_json, "endPageHint")),
        )
        .map_err(|e| e.into())
    }

    /// 전체 cellPath로 중첩 셀 선택 영역의 줄별 사각형을 반환한다(#4272).
    ///
    /// `path_json`의 마지막 엔트리는 선택 대상 셀을 지정하며, 시작·끝 문단 인덱스는
    /// 별도 인자로 받아 여러 문단 선택도 같은 컨테이너 경로에서 처리한다.
    #[wasm_bindgen(js_name = getSelectionRectsInCellByPath)]
    pub fn get_selection_rects_in_cell_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        start_cell_para_idx: u32,
        start_char_offset: u32,
        end_cell_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_selection_rects_in_cell_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            path_json,
            start_cell_para_idx as usize,
            start_char_offset as usize,
            end_cell_para_idx as usize,
            end_char_offset as usize,
            None,
        )
        .map_err(|e| e.into())
    }

    /// `getSelectionRectsInCellByPath`의 page hint options 변형(#4272).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, path, startCellParaIdx,
    /// startCharOffset, endCellParaIdx, endCharOffset, startPageHint?, endPageHint? }`.
    /// `path`는 cellPath JSON 문자열이다.
    #[wasm_bindgen(js_name = getSelectionRectsInCellByPathEx)]
    pub fn get_selection_rects_in_cell_by_path_ex(
        &self,
        options_json: &str,
    ) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_str, json_u32};
        let path_json = json_str(options_json, "path").unwrap_or_default();
        self.get_selection_rects_in_cell_by_path_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            &path_json,
            json_u32(options_json, "startCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCharOffset").unwrap_or(0) as usize,
            json_u32(options_json, "endCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "endCharOffset").unwrap_or(0) as usize,
            json_u32(options_json, "startPageHint").zip(json_u32(options_json, "endPageHint")),
        )
        .map_err(|e| e.into())
    }

    /// 각주/미주 내부 선택 영역의 줄별 사각형을 반환한다.
    #[wasm_bindgen(js_name = getSelectionRectsInFootnote)]
    pub fn get_selection_rects_in_footnote(
        &self,
        page_num: u32,
        footnote_index: u32,
        start_fn_para_idx: u32,
        start_char_offset: u32,
        end_fn_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.get_selection_rects_in_footnote_native(
            page_num,
            footnote_index as usize,
            start_fn_para_idx as usize,
            start_char_offset as usize,
            end_fn_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 본문 선택 영역을 삭제한다.
    ///
    /// 본문 선택을 개체·각주 칸을 포함한 캐럿 위치로 지운다.
    #[wasm_bindgen(js_name = deleteRangeLogical)]
    pub fn delete_range_logical(
        &mut self,
        section_idx: u32,
        start_para_idx: u32,
        start_logical: u32,
        end_para_idx: u32,
        end_logical: u32,
    ) -> Result<String, JsValue> {
        self.delete_range_logical_native(
            section_idx as usize,
            start_para_idx as usize,
            start_logical as usize,
            end_para_idx as usize,
            end_logical as usize,
        )
        .map_err(|e| e.into())
    }

    /// 반환: JSON `{"ok":true,"paraIdx":N,"charOffset":N}`
    #[wasm_bindgen(js_name = deleteRange)]
    pub fn delete_range(
        &mut self,
        section_idx: u32,
        start_para_idx: u32,
        start_char_offset: u32,
        end_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.delete_range_native(
            section_idx as usize,
            start_para_idx as usize,
            start_char_offset as usize,
            end_para_idx as usize,
            end_char_offset as usize,
            None,
        )
        .map_err(|e| e.into())
    }

    /// 셀 내 선택 영역을 삭제한다.
    ///
    /// 반환: JSON `{"ok":true,"paraIdx":N,"charOffset":N}`
    #[wasm_bindgen(js_name = deleteRangeInCell)]
    pub fn delete_range_in_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        start_cell_para_idx: u32,
        start_char_offset: u32,
        end_cell_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.delete_range_native(
            section_idx as usize,
            start_cell_para_idx as usize,
            start_char_offset as usize,
            end_cell_para_idx as usize,
            end_char_offset as usize,
            Some((
                parent_para_idx as usize,
                control_idx as usize,
                cell_idx as usize,
            )),
        )
        .map_err(|e| e.into())
    }

    /// `deleteRangeInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, startCellParaIdx,
    /// startCharOffset, endCellParaIdx, endCharOffset }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = deleteRangeInCellEx)]
    pub fn delete_range_in_cell_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::json_u32;
        self.delete_range_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCharOffset").unwrap_or(0) as usize,
            json_u32(options_json, "endCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "endCharOffset").unwrap_or(0) as usize,
            Some((
                json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
                json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
                json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            )),
        )
        .map_err(|e| e.into())
    }

    // ─── Phase 4 끝 ─────────────────────────────────────────

    // ─── Phase 3 끝 ─────────────────────────────────────────

    // ─── Phase 2 끝 ─────────────────────────────────────────

    /// 문서를 HWP 바이너리로 내보낸다.
    ///
    /// Document IR을 HWP 5.0 CFB 바이너리로 직렬화하여 반환한다.
    /// HWPX 출처 문서는 `export_hwp_with_adapter` 를 통해 HWPX→HWP IR 매핑 어댑터를
    /// 자동 적용하여 한컴 호환성과 자기 재로드 페이지 보존을 보장한다 (#178).
    /// HWP 출처는 어댑터가 no-op 이므로 기존 동작과 동일.
    #[wasm_bindgen(js_name = exportHwp)]
    pub fn export_hwp(&self) -> Result<Vec<u8>, JsValue> {
        self.export_hwp_with_adapter_snapshot()
            .map_err(|e| e.into())
    }

    /// HWP 바이트와 이번 산출물의 내용 손실을 같은 결과로 반환한다 (#4430).
    ///
    /// 명시적 Studio 저장은 이 API를 사용한다. 기존 `exportHwp()`는 호환성을 위해
    /// byte-only로 유지되며, autosave/embed/history/compare/hwpctl/digest 등 별도
    /// 소비자는 아직 보고서를 받지 않는다.
    #[wasm_bindgen(js_name = exportHwpWithReport)]
    pub fn export_hwp_with_report(&self) -> Result<DocumentExport, JsValue> {
        self.export_hwp_with_adapter_snapshot_with_report()
            .map(DocumentExport::from)
            .map_err(JsValue::from)
    }

    /// 문서를 HWP5 EncryptVersion 4 비밀번호 문서로 내보낸다.
    ///
    /// browser UI는 암호를 저장하지 않고 저장 시점에만 전달한다. HWPX 출처 문서는 일반
    /// HWP 저장과 동일하게 HWPX-to-HWP adapter를 먼저 적용한다.
    #[wasm_bindgen(js_name = exportHwpWithPassword)]
    pub fn export_hwp_with_password_wasm(&self, password: &str) -> Result<Vec<u8>, JsValue> {
        self.export_hwp_with_adapter_with_password(password.as_bytes())
            .map_err(|e| e.into())
    }

    /// 비밀번호 HWP 바이트 + 내용 손실 보고 (#4430).
    #[wasm_bindgen(js_name = exportHwpWithPasswordAndReport)]
    pub fn export_hwp_with_password_and_report_wasm(
        &self,
        password: &str,
    ) -> Result<DocumentExport, JsValue> {
        self.export_hwp_with_adapter_snapshot_with_password_and_report(password.as_bytes())
            .map(DocumentExport::from)
            .map_err(JsValue::from)
    }

    /// Document IR을 HWPX(ZIP+XML)로 직렬화하여 반환한다.
    #[wasm_bindgen(js_name = exportHwpx)]
    pub fn export_hwpx(&self) -> Result<Vec<u8>, JsValue> {
        self.export_hwpx_native().map_err(|e| e.into())
    }

    /// HWPX 바이트와 이번 산출물의 내용 손실을 같은 결과로 반환한다 (#4430).
    #[wasm_bindgen(js_name = exportHwpxWithReport)]
    pub fn export_hwpx_with_report(&self) -> Result<DocumentExport, JsValue> {
        self.export_hwpx_native_with_report()
            .map(DocumentExport::from)
            .map_err(JsValue::from)
    }

    /// 문서를 ODF AES-256-CBC/PBKDF2 비밀번호 보호 HWPX로 내보낸다.
    #[wasm_bindgen(js_name = exportHwpxWithPassword)]
    pub fn export_hwpx_with_password_wasm(&self, password: &str) -> Result<Vec<u8>, JsValue> {
        self.export_hwpx_native_with_password(password.as_bytes())
            .map_err(|e| e.into())
    }

    /// 비밀번호 HWPX 바이트 + 내용 손실 보고 (#4430).
    #[wasm_bindgen(js_name = exportHwpxWithPasswordAndReport)]
    pub fn export_hwpx_with_password_and_report_wasm(
        &self,
        password: &str,
    ) -> Result<DocumentExport, JsValue> {
        self.export_hwpx_native_with_password_and_report(password.as_bytes())
            .map(DocumentExport::from)
            .map_err(JsValue::from)
    }

    /// HML 원본의 공통 IR을 HWPML 2.91 XML로 직렬화하여 반환한다.
    #[wasm_bindgen(js_name = exportHml)]
    pub fn export_hml(&self) -> Result<Vec<u8>, JsValue> {
        self.export_hml_native()
            .map_err(|error| JsValue::from_str(&format_hml_export_error(&error)))
    }

    /// 어댑터 적용 + HWP 직렬화 + 자기 재로드 검증을 수행하고 결과를 JSON 으로 반환한다 (#178).
    ///
    /// 반환 JSON:
    /// ```json
    /// {
    ///   "bytesLen": 678912,
    ///   "pageCountBefore": 9,
    ///   "pageCountAfter": 9,
    ///   "recovered": true
    /// }
    /// ```
    ///
    /// 본 함수는 검증 메타데이터만 반환하며 bytes 자체는 별도 호출 (`exportHwp`) 로 받아야 한다.
    /// 검증과 실제 사용을 분리하여 호출자가 결과에 따라 다른 동작을 취할 수 있도록 한다.
    #[wasm_bindgen(js_name = exportHwpVerify)]
    pub fn export_hwp_verify(&self) -> Result<String, JsValue> {
        let v = self.serialize_hwp_with_verify().map_err(JsValue::from)?;
        Ok(format!(
            "{{\"bytesLen\":{},\"pageCountBefore\":{},\"pageCountAfter\":{},\"recovered\":{}}}",
            v.bytes_len, v.page_count_before, v.page_count_after, v.recovered
        ))
    }

    /// 원본 파일 형식을 반환한다 ("hwp", "hwpx", "hml", 또는 "pdf").
    #[wasm_bindgen(js_name = getSourceFormat)]
    pub fn get_source_format(&self) -> String {
        source_format_name(self.core.source_format).to_string()
    }

    /// HML 열기 메타데이터와 손실 진단을 JSON으로 반환한다.
    /// 다른 입력 포맷에서는 `null`을 반환한다.
    #[wasm_bindgen(js_name = getHmlOpenMetadata)]
    pub fn get_hml_open_metadata(&self) -> String {
        let Some(metadata) = self.core.hml_metadata() else {
            return "null".to_string();
        };
        let encoding = match metadata.encoding {
            crate::parser::hml::HmlEncoding::Utf8 => "utf-8",
            crate::parser::hml::HmlEncoding::Utf16Le => "utf-16le",
            crate::parser::hml::HmlEncoding::Utf16Be => "utf-16be",
        };
        let warnings = metadata
            .warnings
            .iter()
            .map(hml_warning_json)
            .collect::<Vec<_>>();
        let save_state = hml_save_state(&self.core);
        serde_json::json!({
            "format": "hml",
            "hwpmlVersion": metadata.hwpml_version,
            "encoding": encoding,
            "resourceCount": metadata.resource_count,
            "warnings": warnings,
            "hmlSavable": save_state.hml_savable,
            "saveBlockers": save_state.blockers,
        })
        .to_string()
    }

    /// HML 저장 가능 여부와 모든 차단 진단을 canonical JSON DTO로 반환한다.
    #[wasm_bindgen(js_name = getHmlSaveState)]
    pub fn get_hml_save_state(&self) -> String {
        serde_json::to_string(&hml_save_state(&self.core))
            .expect("HML save-state DTO serialization cannot fail")
    }

    /// HWPX 비표준 감지 경고를 JSON 문자열로 반환한다 (#177).
    ///
    /// ## 반환 형식
    ///
    /// ```json
    /// {
    ///   "count": 3,
    ///   "summary": {
    ///     "lineseg 배열이 비어있음": 1,
    ///     "lineseg 가 미계산 상태 (line_height=0)": 2
    ///   },
    ///   "warnings": [
    ///     {
    ///       "section": 0,
    ///       "paragraph": 5,
    ///       "kind": "LinesegArrayEmpty",
    ///       "cell": null
    ///     },
    ///     {
    ///       "section": 0,
    ///       "paragraph": 10,
    ///       "kind": "LinesegUncomputed",
    ///       "cell": {"ctrl": 0, "row": 0, "col": 1, "innerPara": 0}
    ///     }
    ///   ]
    /// }
    /// ```
    #[wasm_bindgen(js_name = getValidationWarnings)]
    pub fn get_validation_warnings(&self) -> String {
        let report = self.core.validation_report();

        // summary 직렬화 (HashMap 순서 안정화를 위해 키 정렬)
        let mut summary_parts: Vec<String> = Vec::new();
        let mut entries: Vec<(String, usize)> = report.summary().into_iter().collect();
        entries.sort_by(|a, b| a.0.cmp(&b.0));
        for (k, v) in &entries {
            // 경고 메시지는 한국어 고정 문자열이므로 `"` / `\` 만 escape.
            let escaped = k.replace('\\', "\\\\").replace('"', "\\\"");
            summary_parts.push(format!("\"{}\":{}", escaped, v));
        }

        // warnings 직렬화
        let mut warning_parts: Vec<String> = Vec::new();
        for w in &report.warnings {
            let cell_part = match &w.cell_path {
                Some(cp) => format!(
                    r#"{{"ctrl":{},"row":{},"col":{},"innerPara":{}}}"#,
                    cp.table_ctrl_idx, cp.row, cp.col, cp.inner_para_idx,
                ),
                None => "null".to_string(),
            };
            let kind_name = match &w.kind {
                crate::document_core::validation::WarningKind::LinesegArrayEmpty => {
                    "LinesegArrayEmpty"
                }
                crate::document_core::validation::WarningKind::LinesegUncomputed => {
                    "LinesegUncomputed"
                }
                crate::document_core::validation::WarningKind::LinesegTextRunReflow => {
                    "LinesegTextRunReflow"
                }
            };
            warning_parts.push(format!(
                r#"{{"section":{},"paragraph":{},"kind":"{}","cell":{}}}"#,
                w.section_idx, w.paragraph_idx, kind_name, cell_part,
            ));
        }

        format!(
            r#"{{"count":{},"summary":{{{}}},"warnings":[{}]}}"#,
            report.len(),
            summary_parts.join(","),
            warning_parts.join(","),
        )
    }

    /// 사용자 명시 요청에 의한 lineseg 전체 reflow (#177).
    ///
    /// `reflow_zero_height_paragraphs` 의 자동 경로와 달리, "빈 line_segs + text 존재"
    /// 케이스까지 포함해 재계산한다. 반환값은 실제로 reflow 된 문단 개수.
    ///
    /// 호출 이후 렌더 캐시·페이지네이션이 갱신되므로 즉시 렌더링하면 보정된 결과가 보인다.
    #[wasm_bindgen(js_name = reflowLinesegs)]
    pub fn reflow_linesegs(&mut self) -> usize {
        self.core.reflow_linesegs_on_demand()
    }

    /// 배포용(읽기전용) 문서를 편집 가능한 일반 문서로 변환한다.
    ///
    /// 반환값: JSON `{"ok":true,"converted":true}` 또는 `{"ok":true,"converted":false}`
    #[wasm_bindgen(js_name = convertToEditable)]
    pub fn convert_to_editable(&mut self) -> Result<String, JsValue> {
        self.convert_to_editable_native().map_err(|e| e.into())
    }

    /// Batch 모드를 시작한다. 이후 Command 호출 시 paginate()를 건너뛴다.
    #[wasm_bindgen(js_name = beginBatch)]
    pub fn begin_batch(&mut self) -> Result<String, JsValue> {
        self.begin_batch_native().map_err(|e| e.into())
    }

    /// Batch 모드를 종료하고 누적된 이벤트를 반환한다.
    #[wasm_bindgen(js_name = endBatch)]
    pub fn end_batch(&mut self) -> Result<String, JsValue> {
        self.end_batch_native().map_err(|e| e.into())
    }

    /// 현재 이벤트 로그를 JSON으로 반환한다.
    #[wasm_bindgen(js_name = getEventLog)]
    pub fn get_event_log(&self) -> String {
        self.serialize_event_log()
    }

    // ─── Undo/Redo 스냅샷 API ──────────────────────────

    /// Document 스냅샷을 저장하고 ID를 반환한다.
    #[wasm_bindgen(js_name = saveSnapshot)]
    pub fn save_snapshot(&mut self) -> u32 {
        self.save_snapshot_native()
    }

    /// 지정 ID의 스냅샷으로 Document를 복원한다.
    #[wasm_bindgen(js_name = restoreSnapshot)]
    pub fn restore_snapshot(&mut self, id: u32) -> Result<String, JsValue> {
        self.restore_snapshot_native(id).map_err(|e| e.into())
    }

    /// 지정 ID의 스냅샷을 제거하여 메모리를 해제한다.
    #[wasm_bindgen(js_name = discardSnapshot)]
    pub fn discard_snapshot(&mut self, id: u32) {
        self.discard_snapshot_native(id)
    }

    /// undo 스냅샷 저장소의 축출 상한. studio 예산의 유일한 출처다 (#7002 후속).
    ///
    /// studio 는 이 값에서 예산(`상한 - 2`)을 계산한다. 상수를 양쪽에 두면 순 Rust
    /// 변경에서 frontend 레인이 skip 되어 드리프트가 CI 를 통과했다 — 값을 내보내
    /// 사본을 없앤다.
    #[wasm_bindgen(js_name = snapshotCapacity)]
    pub fn snapshot_capacity(&self) -> u32 {
        DocumentCore::MAX_SNAPSHOTS as u32
    }

    /// 삭제 직전 문단 범위 원본을 조각으로 보관한다 (#5769).
    ///
    /// 반드시 `deleteRangeNative` 호출 **전**에 불린다. 반환 조각 ID 는
    /// `restoreDeleteFragment`/`discardDeleteFragment` 에 쓴다.
    #[wasm_bindgen(js_name = captureDeleteRange)]
    pub fn capture_delete_range(
        &mut self,
        section_idx: usize,
        start_para: usize,
        end_para: usize,
    ) -> Result<u32, JsValue> {
        self.capture_delete_range_native(section_idx, start_para, end_para)
            .map_err(|e| e.into())
    }

    /// 삭제 조각을 원래 자리에 되돌려 끼운다 — 삭제의 참 역연산 (#5769).
    ///
    /// 스냅샷 복원과 달리 문서 전체가 아니라 삭제 범위+꼬리 줄 좌표만 되돌린다.
    /// 성공 시 조각은 소비(제거)된다.
    #[wasm_bindgen(js_name = restoreDeleteFragment)]
    pub fn restore_delete_fragment(&mut self, id: u32) -> Result<String, JsValue> {
        self.restore_delete_fragment_native(id)
            .map_err(|e| e.into())
    }

    /// 삭제 조각을 제거하여 메모리를 해제한다 — 히스토리 축출·클리어 시 스냅샷
    /// `discardSnapshot` 과 짝으로 호출한다(#5769).
    #[wasm_bindgen(js_name = discardDeleteFragment)]
    pub fn discard_delete_fragment(&mut self, id: u32) {
        self.discard_delete_fragment_native(id)
    }

    /// 속성 변경 직전 구역 raw 스트림+봉인을 보관한다 (#5769 Stage 4).
    ///
    /// 반드시 `setSectionDef` 호출 **전**에 불린다. 반환 ID 는
    /// `restoreSectionRaw`/`discardSectionRaw` 에 쓴다.
    #[wasm_bindgen(js_name = captureSectionRaw)]
    pub fn capture_section_raw(&mut self, section_idx: usize) -> Result<u32, JsValue> {
        self.capture_section_raw_native(section_idx)
            .map_err(|e| e.into())
    }

    /// 그림 리사이즈 전에 원본 변환만 보관한다.
    #[wasm_bindgen(js_name = capturePictureTransform)]
    pub fn capture_picture_transform(&mut self, target_json: &str) -> Result<u32, JsValue> {
        self.capture_picture_transform_native(target_json)
            .map_err(|e| e.into())
    }

    /// 저장 상태와 현재 상태를 교환한다. 같은 ID로 Undo/Redo를 수행한다.
    #[wasm_bindgen(js_name = swapPictureTransform)]
    pub fn swap_picture_transform(&mut self, id: u32) -> Result<(), JsValue> {
        self.swap_picture_transform_native(id).map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = discardPictureTransform)]
    pub fn discard_picture_transform(&mut self, id: u32) {
        self.discard_picture_transform_native(id);
    }

    /// 캡처한 구역 raw 를 되돌린다 — old 속성 재적용(재무효화) **뒤** 에 불린다 (#5769 Stage 4).
    #[wasm_bindgen(js_name = restoreSectionRaw)]
    pub fn restore_section_raw(&mut self, id: u32) -> Result<String, JsValue> {
        self.restore_section_raw_native(id).map_err(|e| e.into())
    }

    /// 구역 raw 캡처를 제거하여 메모리를 해제한다 — 히스토리 축출·클리어 계약 (#5769 Stage 4).
    #[wasm_bindgen(js_name = discardSectionRaw)]
    pub fn discard_section_raw(&mut self, id: u32) {
        self.discard_section_raw_native(id)
    }

    /// 캐럿 위치의 글자 속성을 조회한다.
    ///
    /// 반환값: JSON 객체 (fontFamily, fontSize, bold, italic, underline, strikethrough, textColor 등)
    #[wasm_bindgen(js_name = getCharPropertiesAt)]
    pub fn get_char_properties_at(
        &self,
        sec_idx: usize,
        para_idx: usize,
        char_offset: usize,
    ) -> Result<String, JsValue> {
        self.get_char_properties_at_native(sec_idx, para_idx, char_offset)
            .map_err(|e| e.into())
    }

    /// 셀 내부 문단의 글자 속성을 조회한다.
    #[wasm_bindgen(js_name = getCellCharPropertiesAt)]
    pub fn get_cell_char_properties_at(
        &self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        char_offset: usize,
    ) -> Result<String, JsValue> {
        self.get_cell_char_properties_at_native(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
            char_offset,
        )
        .map_err(|e| e.into())
    }

    /// 캐럿 위치의 문단 속성을 조회한다.
    ///
    /// 반환값: JSON 객체 (alignment, lineSpacing, marginLeft, marginRight, indent 등)
    #[wasm_bindgen(js_name = getParaPropertiesAt)]
    pub fn get_para_properties_at(
        &self,
        sec_idx: usize,
        para_idx: usize,
    ) -> Result<String, JsValue> {
        self.get_para_properties_at_native(sec_idx, para_idx)
            .map_err(|e| e.into())
    }

    /// 셀 내부 문단의 문단 속성을 조회한다.
    #[wasm_bindgen(js_name = getCellParaPropertiesAt)]
    pub fn get_cell_para_properties_at(
        &self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
    ) -> Result<String, JsValue> {
        self.get_cell_para_properties_at_native(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
        )
        .map_err(|e| e.into())
    }

    /// 문서에 정의된 스타일 목록을 조회한다.
    ///
    /// 반환값: JSON 배열 [{ id, name, englishName, type, paraShapeId, charShapeId }, ...]
    #[wasm_bindgen(js_name = getStyleList)]
    pub fn get_style_list(&self) -> String {
        let styles = &self.core.document.doc_info.styles;
        let mut items = Vec::new();
        for (i, s) in styles.iter().enumerate() {
            items.push(format!(
                "{{\"id\":{},\"name\":\"{}\",\"englishName\":\"{}\",\"type\":{},\"nextStyleId\":{},\"paraShapeId\":{},\"charShapeId\":{}}}",
                i,
                json_escape(&s.local_name),
                json_escape(&s.english_name),
                s.style_type,
                s.next_style_id,
                s.para_shape_id,
                s.char_shape_id
            ));
        }
        format!("[{}]", items.join(","))
    }

    /// 특정 스타일의 CharShape/ParaShape 속성을 상세 조회한다.
    ///
    /// 반환값: JSON { charProps: {...}, paraProps: {...} }
    #[wasm_bindgen(js_name = getStyleDetail)]
    pub fn get_style_detail(&self, style_id: u32) -> String {
        let styles = &self.core.document.doc_info.styles;
        let style = match styles.get(style_id as usize) {
            Some(s) => s,
            None => return "{}".to_string(),
        };
        let char_json = self
            .core
            .build_char_properties_json_by_id(style.char_shape_id);

        // 스타일의 기본 ParaShape에 번호 정보가 없으면,
        // 이 스타일을 사용하는 실제 문단의 ParaShape에서 조회
        let effective_psid =
            self.find_effective_para_shape_for_style(style_id, style.para_shape_id);
        let para_json = self.core.build_para_properties_json(effective_psid, 0);
        format!(
            "{{\"charProps\":{},\"paraProps\":{}}}",
            char_json, para_json
        )
    }

    /// 스타일의 실효 ParaShape ID를 찾는다.
    /// 스타일 정의의 ParaShape에 번호 정보가 없으면, 이 스타일을 사용하는 문단에서 조회한다.
    fn find_effective_para_shape_for_style(&self, style_id: u32, base_psid: u16) -> u16 {
        use crate::model::style::HeadType;
        // 기본 ParaShape에 이미 번호 정보가 있으면 그대로 사용
        if let Some(ps) = self
            .core
            .document
            .doc_info
            .para_shapes
            .get(base_psid as usize)
        {
            if ps.head_type != HeadType::None {
                return base_psid;
            }
        }
        // 이 스타일을 사용하는 첫 번째 문단의 para_shape_id에서 번호 정보 탐색
        let sid = style_id as u8;
        for section in &self.core.document.sections {
            for para in &section.paragraphs {
                if para.style_id == sid {
                    if let Some(ps) = self
                        .core
                        .document
                        .doc_info
                        .para_shapes
                        .get(para.para_shape_id as usize)
                    {
                        if ps.head_type != HeadType::None {
                            return para.para_shape_id;
                        }
                    }
                }
            }
        }
        base_psid
    }

    /// 스타일의 메타 정보(이름/영문이름/nextStyleId)를 수정한다.
    ///
    /// json: {"name":"...", "englishName":"...", "nextStyleId":0}
    #[wasm_bindgen(js_name = updateStyle)]
    pub fn update_style(&mut self, style_id: u32, json: &str) -> bool {
        use crate::document_core::helpers::json_i32;
        let styles = &mut self.core.document.doc_info.styles;
        let style = match styles.get_mut(style_id as usize) {
            Some(s) => s,
            None => return false,
        };
        // 이름 파싱
        if let Some(name) = crate::document_core::helpers::json_str(json, "name") {
            style.local_name = name;
        }
        if let Some(en) = crate::document_core::helpers::json_str(json, "englishName") {
            style.english_name = en;
        }
        if let Some(v) = json_i32(json, "nextStyleId") {
            style.next_style_id = v as u8;
        }
        // raw_data 무효화 (수정됨)
        style.raw_data = None;
        // DocInfo 스트림 무효화. serialize_doc_info 는 raw_stream_dirty 가 false 이면
        // 원본 스트림을 그대로 반환하고(레코드 raw_data 는 그 이전에 단락됨), 이름/nextStyleId
        // 변경이 .hwp 저장에서 유실된다. 형제 update_style_shapes 는 이미 이 플래그를 세운다.
        self.core.document.doc_info.raw_stream_dirty = true;
        true
    }

    /// 스타일의 CharShape/ParaShape를 수정한다.
    ///
    /// charMods/paraMods는 기존 parse_char_shape_mods/parse_para_shape_mods와 동일한 JSON 형식
    #[wasm_bindgen(js_name = updateStyleShapes)]
    pub fn update_style_shapes(
        &mut self,
        style_id: u32,
        char_mods_json: &str,
        para_mods_json: &str,
    ) -> bool {
        use crate::document_core::helpers::{
            build_tab_def_from_json, json_has_border_keys, json_has_tab_keys,
            parse_char_shape_mods, parse_json_i16_array, parse_para_shape_mods,
        };

        let styles = &self.core.document.doc_info.styles;
        let style = match styles.get(style_id as usize) {
            Some(s) => s.clone(),
            None => return false,
        };
        let old_csid = style.char_shape_id as u32;
        let old_psid = style.para_shape_id;
        let style_type = style.style_type;

        // CharShape 수정
        if !char_mods_json.is_empty() && char_mods_json != "{}" {
            let mut char_mods = parse_char_shape_mods(char_mods_json);
            // 테두리/배경은 글자 모양 적용 경로처럼 BorderFill 을 찾거나 만들어 단다.
            if json_has_border_keys(char_mods_json) {
                char_mods.border_fill_id =
                    Some(self.core.create_border_fill_from_json(char_mods_json));
            }
            if let Some(cs) = self
                .core
                .document
                .doc_info
                .char_shapes
                .get(style.char_shape_id as usize)
            {
                let new_cs = char_mods.apply_to(cs);
                // 새 CharShape를 추가하고 스타일에 연결
                self.core.document.doc_info.char_shapes.push(new_cs);
                let new_id = (self.core.document.doc_info.char_shapes.len() - 1) as u16;
                self.core.document.doc_info.styles[style_id as usize].char_shape_id = new_id;
            }
        }

        // ParaShape 수정
        if !para_mods_json.is_empty() && para_mods_json != "{}" {
            let mut para_mods = parse_para_shape_mods(para_mods_json);
            // 탭 정의와 테두리/배경은 문단 모양 적용 경로처럼 찾거나 만들어 달고, 테두리 간격도
            // 넣는다. 탭은 스타일의 지금 탭 정의에서 바뀐 항목만 덮어쓴다.
            if json_has_tab_keys(para_mods_json) {
                let doc_info = &self.core.document.doc_info;
                let base_tab_def_id = doc_info
                    .para_shapes
                    .get(old_psid as usize)
                    .map_or(0, |ps| ps.tab_def_id);
                let tab_def =
                    build_tab_def_from_json(para_mods_json, base_tab_def_id, &doc_info.tab_defs);
                para_mods.tab_def_id = Some(self.core.document.find_or_create_tab_def(tab_def));
            }
            if json_has_border_keys(para_mods_json) {
                para_mods.border_fill_id =
                    Some(self.core.create_border_fill_from_json(para_mods_json));
            }
            if let Some(spacing) = parse_json_i16_array(para_mods_json, "borderSpacing", 4) {
                para_mods.border_spacing = Some([spacing[0], spacing[1], spacing[2], spacing[3]]);
            }
            if let Some(ps) = self
                .core
                .document
                .doc_info
                .para_shapes
                .get(style.para_shape_id as usize)
            {
                let new_ps = para_mods.apply_to(ps);
                self.core.document.doc_info.para_shapes.push(new_ps);
                let new_id = (self.core.document.doc_info.para_shapes.len() - 1) as u16;
                self.core.document.doc_info.styles[style_id as usize].para_shape_id = new_id;
            }
        }

        // raw_data 무효화
        self.core.document.doc_info.styles[style_id as usize].raw_data = None;
        self.core.document.doc_info.raw_stream_dirty = true;

        let sid = style_id as u8;
        let mut body_targets = Vec::new();
        let mut cell_targets = Vec::new();
        for (sec_idx, section) in self.core.document.sections.iter().enumerate() {
            for (para_idx, para) in section.paragraphs.iter().enumerate() {
                if para.style_id == sid {
                    body_targets.push((sec_idx, para_idx));
                }
                for (control_idx, ctrl) in para.controls.iter().enumerate() {
                    if let Control::Table(table) = ctrl {
                        for (cell_idx, cell) in table.cells.iter().enumerate() {
                            for (cell_para_idx, cpara) in cell.paragraphs.iter().enumerate() {
                                if cpara.style_id == sid {
                                    cell_targets.push((
                                        sec_idx,
                                        para_idx,
                                        control_idx,
                                        cell_idx,
                                        cell_para_idx,
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        }

        // ── 스타일 변경을 해당 스타일을 사용하는 모든 문단에 전파 ──
        let updated_style = self.core.document.doc_info.styles[style_id as usize].clone();
        let new_csid = updated_style.char_shape_id as u32;
        let new_psid = updated_style.para_shape_id;
        // [#7490] 셀 문단은 저장 줄 기록을 두고 재조판하므로 bit 20 도 새 들여쓰기로 단다.
        // 본문 문단은 `reflow_body_paragraph` 가 줄을 비우고 다시 짠다.
        let (old_indent, new_indent) = self.core.para_shape_indents(old_psid, new_psid);

        for (sec_idx, para_idx) in body_targets {
            if let Some(para) = self
                .core
                .document
                .sections
                .get_mut(sec_idx)
                .and_then(|s| s.paragraphs.get_mut(para_idx))
            {
                if style_type == 0 && para.para_shape_id == old_psid {
                    para.para_shape_id = new_psid;
                }
                para.replace_style_char_shape_preserving_overrides(old_csid, new_csid);
            }
            self.core.reflow_body_paragraph(sec_idx, para_idx);
            if let Some(section) = self.core.document.sections.get_mut(sec_idx) {
                section.raw_stream = None;
            }
        }

        for (sec_idx, para_idx, control_idx, cell_idx, cell_para_idx) in cell_targets {
            if let Ok(cpara) = self.core.get_cell_paragraph_mut(
                sec_idx,
                para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            ) {
                if style_type == 0 && cpara.para_shape_id == old_psid {
                    cpara.para_shape_id = new_psid;
                    restamp_indentation(&mut cpara.line_segs, old_indent, new_indent);
                }
                cpara.replace_style_char_shape_preserving_overrides(old_csid, new_csid);
            }
            self.core.reflow_cell_paragraph(
                sec_idx,
                para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            );
            self.core
                .mark_cell_control_dirty(sec_idx, para_idx, control_idx);
            if let Some(section) = self.core.document.sections.get_mut(sec_idx) {
                section.raw_stream = None;
            }
        }

        // 스타일 캐시 무효화 + 전체 리빌드
        let num_sections = self.core.document.sections.len();
        for sec_idx in 0..num_sections {
            self.core.rebuild_section(sec_idx);
        }
        true
    }

    /// 새 스타일을 생성한다.
    ///
    /// json: {"name":"...", "englishName":"...", "type":0, "nextStyleId":0, "index":3}
    /// `index`를 주면 그 자리에 끼워 넣고, 그 자리부터 뒤 스타일을 가리키던 모든 참조(문단·덧말·
    /// 바탕쪽·메모·다른 스타일의 다음 스타일)를 한 칸씩 민다. 한컴은 고른 스타일 바로 뒤에 새 스타일을 둔다.
    /// `nextStyleId`는 끼워 넣은 뒤의 번호다. 없으면 목록 끝에 붙인다.
    /// 반환값: 새 스타일 ID (0-based). `index`가 목록 길이보다 크거나, 문단이 스타일 번호를 1바이트로
    /// 저장하므로 256개를 채운 목록 가운데에 끼우면 -1이다.
    #[wasm_bindgen(js_name = createStyle)]
    pub fn create_style(&mut self, json: &str) -> i32 {
        use crate::document_core::helpers::{json_i32, json_str};
        use crate::model::style::Style;

        let count = self.core.document.doc_info.styles.len();
        let index = match json_i32(json, "index") {
            None => count,
            Some(index) => match usize::try_from(index) {
                Ok(index) if index <= count => index,
                _ => return -1,
            },
        };
        // 문단은 스타일 번호를 1바이트로 저장한다. 256개를 채운 목록 가운데에 끼우면 마지막 스타일이
        // 가리킬 수 없는 256번으로 밀리므로 끼우지 않는다. 끝에 붙이기는 예전처럼 막지 않는다.
        if index < count && count > usize::from(u8::MAX) {
            return -1;
        }
        let name = json_str(json, "name").unwrap_or_default();
        let english_name = json_str(json, "englishName").unwrap_or_default();
        let style_type = json_i32(json, "type").unwrap_or(0) as u8;
        let next_style_id = json_i32(json, "nextStyleId").unwrap_or(0) as u8;

        // 한컴 스타일 추가 흐름은 현재 문단의 모양을 기본값으로 삼는다.
        // 호출자가 base ID를 넘기지 않으면 기존 호환성을 위해 바탕글을 사용한다.
        let base_style = self.core.document.doc_info.styles.first();
        let (fallback_char_shape_id, fallback_para_shape_id) = match base_style {
            Some(s) => (s.char_shape_id, s.para_shape_id),
            None => (0, 0),
        };
        let char_shape_id = json_i32(json, "baseCharShapeId")
            .filter(|id| *id >= 0)
            .map(|id| id as u16)
            .filter(|id| (*id as usize) < self.core.document.doc_info.char_shapes.len())
            .unwrap_or(fallback_char_shape_id);
        let para_shape_id = json_i32(json, "baseParaShapeId")
            .filter(|id| *id >= 0)
            .map(|id| id as u16)
            .filter(|id| (*id as usize) < self.core.document.doc_info.para_shapes.len())
            .unwrap_or(fallback_para_shape_id);

        let new_style = Style {
            raw_data: None,
            local_name: name,
            english_name,
            style_type,
            next_style_id,
            lang_id: 1042, // 한국어 default (HWP5 spec 표 47)
            para_shape_id,
            char_shape_id,
            lock_form: false,
        };
        if index < count {
            self.remap_style_ids(|id| if id >= index as u16 { id + 1 } else { id });
        }
        self.core.document.doc_info.styles.insert(index, new_style);
        self.core.document.doc_info.raw_stream_dirty = true;
        // 스타일 캐시 갱신
        self.core.rebuild_resolved_styles();
        index as i32
    }

    /// 스타일을 삭제한다.
    ///
    /// 바탕글(ID 0)은 삭제할 수 없다.
    /// 삭제된 스타일을 사용 중인 문단은 바탕글(ID 0)로 변경된다.
    #[wasm_bindgen(js_name = deleteStyle)]
    pub fn delete_style(&mut self, style_id: u32) -> bool {
        if style_id == 0 {
            return false; // 바탕글은 삭제 불가
        }
        let styles = &self.core.document.doc_info.styles;
        if style_id as usize >= styles.len() {
            return false;
        }
        let sid = style_id as u16;
        self.remap_style_ids(|id| {
            if id == sid {
                0
            } else if id > sid {
                id - 1
            } else {
                id
            }
        });
        // 스타일 삭제 (인덱스 기반이므로 뒤의 ID가 변경됨에 주의)
        self.core.document.doc_info.styles.remove(style_id as usize);
        // 스타일 캐시 갱신
        self.core.rebuild_resolved_styles();
        true
    }

    /// 스타일 번호를 가리키는 모든 참조를 `remap`으로 바꾼다. 스타일 목록 자체는 바꾸지 않는다.
    ///
    /// 문단(본문·표·글상자·머리말·주석·메모·바탕쪽·복사해 둔 문단), 덧말, 다른 스타일의 다음 스타일,
    /// 그리고 원본 레코드로 다시 쓰는 바탕쪽·구역 끝 목록(확장 바탕쪽·메모)의 문단 머리를 함께 고친다.
    fn remap_style_ids(&mut self, remap: impl Fn(u16) -> u16) {
        use crate::model::identity::walk::{walk, Node};

        let remap_records = |records: &mut [crate::model::document::RawRecord]| {
            // 저장된 바탕쪽은 원본 레코드를 다시 쓴다. 문단 머리의 스타일 번호(PARA_HEADER 10번째
            // 바이트)도 옮겨야 저장본이 모델과 같다.
            for record in records {
                if record.tag_id == crate::parser::tags::HWPTAG_PARA_HEADER {
                    if let Some(id) = record.data.get_mut(10) {
                        *id = remap(u16::from(*id)) as u8;
                    }
                }
            }
        };
        let remap_paragraphs = |paragraphs: &mut [Paragraph]| {
            walk(paragraphs, |node| {
                match node {
                    Node::Paragraph(para) => para.style_id = remap(u16::from(para.style_id)) as u8,
                    Node::Control(Control::Ruby(ruby)) => {
                        ruby.style_id_ref = remap(ruby.style_id_ref);
                    }
                    Node::Control(Control::SectionDef(section_def)) => {
                        remap_records(&mut section_def.extra_child_records);
                    }
                    _ => {}
                }
                Ok(())
            })
            .expect("style reference traversal is infallible");
        };
        // 구역 끝 목록은 원본 레코드와 모델 투영이 같을 때만 저장한다. 둘을 함께 고쳤으면 다시 봉인한다.
        let tail_sealed =
            crate::model::section_tail::validate_preservation(&self.core.document).is_ok();
        // 표·글상자·머리말·주석도 같은 스타일 풀을 참조한다. 모양과 원문은 바꾸지 않는다.
        for section in &mut self.core.document.sections {
            remap_paragraphs(&mut section.paragraphs);
            remap_records(&mut section.section_def.extra_child_records);
            for master in &mut section.section_def.master_pages {
                remap_paragraphs(&mut master.paragraphs);
            }
            if let Some(tail) = &mut section.trailing_lists {
                remap_records(&mut tail.records);
            }
            // 본문 원본 스트림을 다시 쓰지 않게 해 문단 스타일 번호 변경이 HWP 저장에 남게 한다.
            section.raw_stream = None;
        }
        if tail_sealed {
            self.core.document.seal_section_tail_provenance();
        }
        // 복사해 둔 문단도 같은 스타일 표를 가리킨다. 붙이면 옮기지 않은 번호의 다른 스타일이 된다.
        if let Some(clipboard) = &mut self.core.clipboard {
            remap_paragraphs(&mut clipboard.paragraphs);
        }
        if let Some(transpose) = &mut self.core.table_transpose_clipboard {
            for paragraphs in transpose.data.cells.iter_mut().flatten() {
                remap_paragraphs(paragraphs);
            }
        }
        for s in &mut self.core.document.doc_info.styles {
            let next = remap(u16::from(s.next_style_id)) as u8;
            if next != s.next_style_id {
                s.next_style_id = next;
                // 원본 레코드 봉인이 없는 기본 문서에서도 이전 연결을 다시 쓰지 않는다.
                s.raw_data = None;
            }
        }
        // 스타일 목록과 문단 스타일 번호가 함께 바뀌므로 DocInfo 원본 스트림도 다시 쓴다.
        self.core.document.doc_info.raw_stream_dirty = true;
    }

    /// 문서에 정의된 문단 번호(Numbering) 목록을 조회한다.
    ///
    /// 반환값: JSON 배열 [{ id, levelFormats: [...] }, ...]
    /// id는 1-based (ParaShape.numbering_id와 동일)
    #[wasm_bindgen(js_name = getNumberingList)]
    pub fn get_numbering_list(&self) -> String {
        let numberings = &self.core.document.doc_info.numberings;
        let mut items = Vec::new();
        for (i, n) in numberings.iter().enumerate() {
            let formats: Vec<String> = n
                .level_formats
                .iter()
                .map(|f| format!("\"{}\"", json_escape(f)))
                .collect();
            items.push(format!(
                "{{\"id\":{},\"levelFormats\":[{}],\"startNumber\":{}}}",
                i + 1,
                formats.join(","),
                n.start_number
            ));
        }
        format!("[{}]", items.join(","))
    }

    /// 문서에 정의된 글머리표(Bullet) 목록을 조회한다.
    ///
    /// 반환값: JSON 배열 [{ id, char }, ...]
    /// id는 1-based (ParaShape.numbering_id와 동일)
    #[wasm_bindgen(js_name = getBulletList)]
    pub fn get_bullet_list(&self) -> String {
        let bullets = &self.core.document.doc_info.bullets;
        let mut items = Vec::new();
        for (i, b) in bullets.iter().enumerate() {
            let mapped = crate::renderer::layout::map_pua_bullet_char(b.bullet_char);
            let raw_code = b.bullet_char as u32;
            items.push(format!(
                "{{\"id\":{},\"char\":\"{}\",\"rawCode\":{}}}",
                i + 1,
                mapped,
                raw_code
            ));
        }
        format!("[{}]", items.join(","))
    }

    /// 문서에 기본 문단 번호 정의가 없으면 생성한다.
    ///
    /// 반환값: Numbering ID (1-based)
    #[wasm_bindgen(js_name = ensureDefaultNumbering)]
    pub fn ensure_default_numbering(&mut self) -> u16 {
        let numberings = &self.core.document.doc_info.numberings;
        if !numberings.is_empty() {
            return 1; // 이미 있으면 첫 번째 반환
        }
        // 기본 7수준 번호 형식 생성 (한컴 기본 패턴)
        use crate::model::style::{Numbering, NumberingHead};
        let mut n = Numbering::default();
        // 1. 가) (1) (가) ① ㄱ) a) — 8~10수준은 비워 둔다.
        let texts = ["^1.", "^2)", "^3)", "^4)", "^5)", "^6)", "^7)"];
        for (format, text) in n.level_formats.iter_mut().zip(texts) {
            *format = text.to_string();
        }
        n.start_number = 1;
        n.level_start_numbers = [1; crate::model::style::NUMBERING_LEVELS];
        // 수준별 번호 형식 코드 설정
        // [#7418] 한/글 기본 머리 모양은 자동 내어쓰기(속성 bit3)다 — 둘째 줄부터 본문 시작에 맞춘다.
        n.heads[0] = NumberingHead {
            number_format: 0,
            attr: 1 << 3,
            ..Default::default()
        }; // 1,2,3
        n.heads[1] = NumberingHead {
            number_format: 8,
            attr: 1 << 3,
            ..Default::default()
        }; // 가,나,다
        n.heads[2] = NumberingHead {
            number_format: 0,
            attr: 1 << 3,
            ..Default::default()
        }; // 1,2,3
        n.heads[3] = NumberingHead {
            number_format: 8,
            attr: 1 << 3,
            ..Default::default()
        }; // 가,나,다
        n.heads[4] = NumberingHead {
            number_format: 1,
            attr: 1 << 3,
            ..Default::default()
        }; // ①②③
        n.heads[5] = NumberingHead {
            number_format: 10,
            attr: 1 << 3,
            ..Default::default()
        }; // ㄱ,ㄴ,ㄷ
        n.heads[6] = NumberingHead {
            number_format: 5,
            attr: 1 << 3,
            ..Default::default()
        }; // a,b,c
        self.core.document.doc_info.numberings.push(n);
        // 새 번호 정의는 DocInfo 원본 스트림에 없어 HWP 저장이 모델에서 다시 쓰게 한다.
        self.core.document.doc_info.raw_stream_dirty = true;
        1
    }

    /// JSON으로 지정된 번호 형식으로 Numbering 정의를 생성한다.
    ///
    /// json: {"levelFormats":["^1.","^2)",...],"numberFormats":[0,8,...],"startNumber":1}
    /// 반환값: Numbering ID (1-based)
    #[wasm_bindgen(js_name = createNumbering)]
    pub fn create_numbering(&mut self, json: &str) -> u16 {
        use crate::document_core::helpers::json_i32;
        use crate::model::style::{Numbering, NumberingHead};

        let mut n = Numbering::default();

        // levelFormats 배열 파싱
        if let Some(arr_start) = json.find("\"levelFormats\"") {
            let rest = &json[arr_start..];
            if let Some(bracket_start) = rest.find('[') {
                if let Some(bracket_end) = rest[bracket_start..].find(']') {
                    let arr_str = &rest[bracket_start + 1..bracket_start + bracket_end];
                    let mut level = 0;
                    for part in arr_str.split(',') {
                        if level >= crate::model::style::NUMBERING_LEVELS {
                            break;
                        }
                        let trimmed = part.trim().trim_matches('"');
                        if !trimmed.is_empty() {
                            n.level_formats[level] = trimmed.to_string();
                            level += 1;
                        }
                    }
                }
            }
        }

        // numberFormats 배열 파싱
        if let Some(arr_start) = json.find("\"numberFormats\"") {
            let rest = &json[arr_start..];
            if let Some(bracket_start) = rest.find('[') {
                if let Some(bracket_end) = rest[bracket_start..].find(']') {
                    let arr_str = &rest[bracket_start + 1..bracket_start + bracket_end];
                    let mut level = 0;
                    for part in arr_str.split(',') {
                        if level >= crate::model::style::NUMBERING_LEVELS {
                            break;
                        }
                        if let Ok(code) = part.trim().parse::<u8>() {
                            n.heads[level] = NumberingHead {
                                number_format: code,
                                attr: 1 << 3, // 자동 내어쓰기 (한/글 기본 머리 모양)
                                ..Default::default()
                            };
                            level += 1;
                        }
                    }
                }
            }
        }

        n.start_number = json_i32(json, "startNumber").unwrap_or(1) as u16;
        n.level_start_numbers = [n.start_number as u32; crate::model::style::NUMBERING_LEVELS];
        self.core.document.doc_info.numberings.push(n);
        // 새 번호 정의는 DocInfo 원본 스트림에 없어 HWP 저장이 모델에서 다시 쓰게 한다.
        self.core.document.doc_info.raw_stream_dirty = true;
        self.core.document.doc_info.numberings.len() as u16
    }

    /// 문단 번호 정의의 한 수준에 번호 글자 모양을 단다(한/글 '문단 번호 사용자 정의 모양'의 글자 모양 지정).
    ///
    /// numberingId는 1부터, level은 0부터다. json은 applyCharFormat의 글자 속성과 바탕 글자 모양
    /// `baseCharShapeId`이고, `fontSize` 0은 '본문 글자 크기 따름'이다. null이면 글자 모양을 뗀다.
    /// 반환값: 단 글자 모양 ID(뗐으면 4294967295)
    #[wasm_bindgen(js_name = setNumberingCharShape)]
    pub fn set_numbering_char_shape(
        &mut self,
        numbering_id: u16,
        level: u32,
        json: Option<String>,
    ) -> Result<u32, JsValue> {
        self.core
            .set_numbering_char_shape_native(numbering_id, level as usize, json.as_deref())
            .map_err(|e| e.into())
    }

    /// 글머리표 정의를 새로 만든다(한/글 '글머리표/그림 글머리표 사용자 정의 모양').
    ///
    /// json: {"char":"❏","align":1,"useInstWidth":false,"autoIndent":false,"widthAdjust":1000,
    /// "textOffset":70,"charShape":{"fontSize":0,"bold":true,"baseCharShapeId":0}}. 빠진 값은 한/글
    /// 기본 머리 모양(왼쪽·자동 내어쓰기·본문과의 간격 50%)이고, charShape가 없으면 본문 글자 모양을
    /// 따른다. imageData(와 extension, 예: "png")를 주면 그 그림을 넣어 그림 글머리표로 만든다.
    /// 반환값: Bullet ID (1-based)
    #[wasm_bindgen(js_name = createBullet)]
    pub fn create_bullet(
        &mut self,
        json: &str,
        image_data: Option<Vec<u8>>,
        extension: Option<String>,
    ) -> Result<u16, JsValue> {
        let image = match (&image_data, &extension) {
            (Some(bytes), Some(extension)) => Some((bytes.as_slice(), extension.as_str())),
            (None, None) => None,
            _ => return Err(JsValue::from_str("그림과 확장자를 함께 주어야 함")),
        };
        self.core
            .create_bullet_native(json, image)
            .map_err(|e| e.into())
    }

    /// 특정 문자의 글머리표 정의가 없으면 생성한다.
    ///
    /// 반환값: Bullet ID (1-based)
    #[wasm_bindgen(js_name = ensureDefaultBullet)]
    pub fn ensure_default_bullet(&mut self, bullet_char_str: &str) -> u16 {
        let bullet_ch = bullet_char_str.chars().next().unwrap_or('●');
        // 이미 해당 문자의 Bullet이 있는지 검색
        let bullets = &self.core.document.doc_info.bullets;
        for (i, b) in bullets.iter().enumerate() {
            let mapped = crate::renderer::layout::map_pua_bullet_char(b.bullet_char);
            if mapped == bullet_ch {
                return (i + 1) as u16;
            }
        }
        // 없으면 새로 생성
        use crate::model::style::Bullet;
        let b = Bullet {
            bullet_char: bullet_ch,
            attr: 1 << 3, // 자동 내어쓰기 (한/글 기본 머리 모양)
            text_distance: 50,
            ..Default::default()
        };
        self.core.document.doc_info.bullets.push(b);
        self.core.document.doc_info.bullets.len() as u16
    }

    /// 특정 문단의 스타일을 조회한다.
    ///
    /// 반환값: JSON { id, name }
    #[wasm_bindgen(js_name = getStyleAt)]
    pub fn get_style_at(&self, sec_idx: u32, para_idx: u32) -> String {
        let sec = sec_idx as usize;
        let para = para_idx as usize;
        let style_id = self
            .core
            .document
            .sections
            .get(sec)
            .and_then(|s| s.paragraphs.get(para))
            .map(|p| p.style_id as usize)
            .unwrap_or(0);
        let name = self
            .core
            .document
            .doc_info
            .styles
            .get(style_id)
            .map(|s| s.local_name.as_str())
            .unwrap_or("");
        format!("{{\"id\":{},\"name\":\"{}\"}}", style_id, json_escape(name))
    }

    /// 셀 내부 문단의 스타일을 조회한다.
    #[wasm_bindgen(js_name = getCellStyleAt)]
    pub fn get_cell_style_at(
        &self,
        sec_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
    ) -> String {
        let style_id = self
            .core
            .get_cell_paragraph_ref(
                sec_idx as usize,
                parent_para_idx as usize,
                control_idx as usize,
                cell_idx as usize,
                cell_para_idx as usize,
            )
            .map(|p| p.style_id as usize)
            .unwrap_or(0);
        let name = self
            .core
            .document
            .doc_info
            .styles
            .get(style_id)
            .map(|s| s.local_name.as_str())
            .unwrap_or("");
        format!("{{\"id\":{},\"name\":\"{}\"}}", style_id, json_escape(name))
    }

    /// 스타일을 적용한다 (본문 문단).
    #[wasm_bindgen(js_name = applyStyle)]
    pub fn apply_style(
        &mut self,
        sec_idx: u32,
        para_idx: u32,
        style_id: u32,
    ) -> Result<String, JsValue> {
        self.core
            .apply_style_native(sec_idx as usize, para_idx as usize, style_id as usize)
            .map_err(|e| e.into())
    }

    /// 스타일을 적용한다 (셀 내 문단).
    #[wasm_bindgen(js_name = applyCellStyle)]
    pub fn apply_cell_style(
        &mut self,
        sec_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        style_id: u32,
    ) -> Result<String, JsValue> {
        self.core
            .apply_cell_style_native(
                sec_idx as usize,
                parent_para_idx as usize,
                control_idx as usize,
                cell_idx as usize,
                cell_para_idx as usize,
                style_id as usize,
            )
            .map_err(|e| e.into())
    }

    /// 표 셀에서 계산식을 실행한다.
    ///
    /// formula: "=SUM(A1:A5)", "=A1+B2*3" 등
    /// write_result: true이면 결과를 셀에 기록
    #[wasm_bindgen(js_name = evaluateTableFormula)]
    pub fn evaluate_table_formula(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        target_row: u32,
        target_col: u32,
        formula: &str,
        write_result: bool,
    ) -> Result<String, JsValue> {
        self.core
            .evaluate_table_formula(
                section_idx as usize,
                parent_para_idx as usize,
                control_idx as usize,
                target_row as usize,
                target_col as usize,
                formula,
                write_result,
            )
            .map_err(|e| e.into())
    }

    /// `evaluateTableFormula` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, targetRow, targetCol,
    /// formula: string, writeResult? }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = evaluateTableFormulaEx)]
    pub fn evaluate_table_formula_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_bool, json_str, json_u32};
        self.core
            .evaluate_table_formula(
                json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
                json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
                json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
                json_u32(options_json, "targetRow").unwrap_or(0) as usize,
                json_u32(options_json, "targetCol").unwrap_or(0) as usize,
                &json_str(options_json, "formula").unwrap_or_default(),
                json_bool(options_json, "writeResult").unwrap_or(false),
            )
            .map_err(|e| e.into())
    }

    /// 셀에 계산식 필드를 넣거나 그 셀 계산식을 바꾼다(한/글 표 > 계산식·쉬운 계산식·블록 계산식).
    ///
    /// result_format: `%g`(기본)·`%.Nf`(소수 N자리), 세 자리 쉼표면 끝에 `,`.
    /// 결과: `{"ok":true,"result":number|null,"text":"…","formula":"…","cells":[{row,col}…]}`.
    #[wasm_bindgen(js_name = setTableCellFormula)]
    pub fn set_table_cell_formula(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        formula: &str,
        result_format: &str,
    ) -> Result<String, JsValue> {
        self.core
            .set_table_cell_formula(
                section_idx as usize,
                parent_para_idx as usize,
                control_idx as usize,
                cell_idx as usize,
                formula,
                result_format,
            )
            .map_err(|e| e.into())
    }

    /// 셀의 계산식 필드를 지우고 결과 글은 일반 글로 남긴다(한/글 계산식 지우기).
    #[wasm_bindgen(js_name = removeTableCellFormulas)]
    pub fn remove_table_cell_formulas(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
    ) -> Result<String, JsValue> {
        self.core
            .remove_table_cell_formulas(
                section_idx as usize,
                parent_para_idx as usize,
                control_idx as usize,
                cell_idx as usize,
            )
            .map_err(|e| e.into())
    }

    /// 표의 계산식 필드를 다시 계산한다. `edited_cell`은 고친 셀이고 음수면 모두 다시 계산한다
    /// (손으로 고친 결과는 그 식이 고친 셀을 쓸 때만 다시 계산한다). `paginate`가 거짓이면 셀 쪽
    /// 나눔을 미룬다. 결과: `{"ok":true,"changed":[셀 번호…],"cellFlowChanged":bool}`.
    #[wasm_bindgen(js_name = recalculateTableFormulas)]
    pub fn recalculate_table_formulas(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        edited_cell: i32,
        paginate: bool,
    ) -> Result<String, JsValue> {
        self.core
            .recalculate_table_formulas(
                section_idx as usize,
                parent_para_idx as usize,
                control_idx as usize,
                usize::try_from(edited_cell).ok(),
                paginate,
            )
            .map_err(|e| e.into())
    }

    /// 글꼴 이름으로 font_id를 조회하거나 새로 생성한다.
    ///
    /// 한글(0번) 카테고리에서 이름 검색 → 없으면 7개 전체 카테고리에 신규 등록.
    /// 반환값: font_id (u16), 실패 시 -1
    #[wasm_bindgen(js_name = findOrCreateFontId)]
    pub fn find_or_create_font_id(&mut self, name: &str) -> i32 {
        self.find_or_create_font_id_native(name)
    }

    /// 특정 언어 카테고리에서 글꼴 이름으로 ID를 찾거나 등록한다.
    #[wasm_bindgen(js_name = findOrCreateFontIdForLang)]
    pub fn wasm_find_or_create_font_id_for_lang(&mut self, lang: u32, name: &str) -> i32 {
        self.core
            .find_or_create_font_id_for_lang(lang as usize, name)
    }

    /// 글자 서식을 적용한다 (본문 문단).
    #[wasm_bindgen(js_name = applyCharFormat)]
    pub fn apply_char_format(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_char_format_native(sec_idx, para_idx, start_offset, end_offset, props_json)
            .map_err(|e| e.into())
    }

    /// 문자 offset 범위의 모양 구간 목록을 조회한다.
    #[wasm_bindgen(js_name = getCharShapeRuns)]
    pub fn get_char_shape_runs(
        &self,
        sec: usize,
        para: usize,
        start: usize,
        end: usize,
    ) -> Result<String, JsValue> {
        self.get_char_shape_runs_native(sec, para, start, end)
            .map_err(Into::into)
    }

    /// 구간 목록 전체를 검사한 뒤 본문 모양을 복원한다.
    #[wasm_bindgen(js_name = setCharShapeRuns)]
    pub fn set_char_shape_runs(
        &mut self,
        sec: usize,
        para: usize,
        start: usize,
        end: usize,
        runs_json: &str,
    ) -> Result<String, JsValue> {
        self.set_char_shape_runs_native(sec, para, start, end, runs_json)
            .map_err(Into::into)
    }

    #[wasm_bindgen(js_name = getCharShapeRunsInCellByPath)]
    pub fn get_char_shape_runs_in_cell_by_path(
        &mut self,
        sec: usize,
        para: usize,
        path_json: &str,
        start: usize,
        end: usize,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.get_char_shape_runs_in_cell_by_path_native(sec, para, &path, start, end)
            .map_err(Into::into)
    }

    #[wasm_bindgen(js_name = setCharShapeRunsInCellByPath)]
    pub fn set_char_shape_runs_in_cell_by_path(
        &mut self,
        sec: usize,
        para: usize,
        path_json: &str,
        start: usize,
        end: usize,
        runs_json: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.set_char_shape_runs_in_cell_by_path_native(sec, para, &path, start, end, runs_json)
            .map_err(Into::into)
    }

    /// 글자 서식 ID를 직접 복원한다 (본문 문단).
    #[wasm_bindgen(js_name = setCharShapeId)]
    pub fn set_char_shape_id(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        char_shape_id: u32,
    ) -> Result<String, JsValue> {
        self.set_char_shape_id_native(sec_idx, para_idx, start_offset, end_offset, char_shape_id)
            .map_err(|e| e.into())
    }

    /// 글자 서식을 적용한다 (셀 내 문단).
    #[wasm_bindgen(js_name = applyCharFormatInCell)]
    pub fn apply_char_format_in_cell(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_char_format_in_cell_native(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
            start_offset,
            end_offset,
            props_json,
        )
        .map_err(|e| e.into())
    }

    /// `applyCharFormatInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ secIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// startOffset, endOffset, props: object }`. `props` 는 글자 서식 JSON 객체(positional
    /// 의 props_json 과 동일). positional 과 동일 동작.
    #[wasm_bindgen(js_name = applyCharFormatInCellEx)]
    pub fn apply_char_format_in_cell_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_object, json_u32};
        let props_json = json_object(options_json, "props").unwrap_or_else(|| "{}".to_string());
        self.apply_char_format_in_cell_native(
            json_u32(options_json, "secIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startOffset").unwrap_or(0) as usize,
            json_u32(options_json, "endOffset").unwrap_or(0) as usize,
            &props_json,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = applyCharFormatInCellByPath)]
    #[allow(clippy::too_many_arguments)]
    pub fn apply_char_format_in_cell_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        start_offset: u32,
        end_offset: u32,
        props_json: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.apply_char_format_in_cell_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            start_offset as usize,
            end_offset as usize,
            props_json,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = getCellCharPropertiesAtByPath)]
    pub fn get_cell_char_properties_at_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.get_cell_char_properties_at_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = setCharShapeIdInCellByPath)]
    #[allow(clippy::too_many_arguments)]
    pub fn set_char_shape_id_in_cell_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        start_offset: u32,
        end_offset: u32,
        char_shape_id: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.set_char_shape_id_in_cell_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            start_offset as usize,
            end_offset as usize,
            char_shape_id,
        )
        .map_err(|e| e.into())
    }

    /// 글자 서식 ID를 직접 복원한다 (셀 내 문단).
    #[wasm_bindgen(js_name = setCharShapeIdInCell)]
    pub fn set_char_shape_id_in_cell(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        char_shape_id: u32,
    ) -> Result<String, JsValue> {
        self.set_char_shape_id_in_cell_native(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
            start_offset,
            end_offset,
            char_shape_id,
        )
        .map_err(|e| e.into())
    }

    /// `setCharShapeIdInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ secIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// startOffset, endOffset, charShapeId }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = setCharShapeIdInCellEx)]
    pub fn set_char_shape_id_in_cell_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::json_u32;
        self.set_char_shape_id_in_cell_native(
            json_u32(options_json, "secIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startOffset").unwrap_or(0) as usize,
            json_u32(options_json, "endOffset").unwrap_or(0) as usize,
            json_u32(options_json, "charShapeId").unwrap_or(0),
        )
        .map_err(|e| e.into())
    }

    /// 감추기 설정
    #[wasm_bindgen(js_name = setPageHide)]
    pub fn set_page_hide(
        &mut self,
        sec: u32,
        para: u32,
        hide_header: bool,
        hide_footer: bool,
        hide_master: bool,
        hide_border: bool,
        hide_fill: bool,
        hide_page_num: bool,
    ) -> Result<String, JsValue> {
        self.set_page_hide_native(
            sec as usize,
            para as usize,
            hide_header,
            hide_footer,
            hide_master,
            hide_border,
            hide_fill,
            hide_page_num,
        )
        .map_err(|e| e.into())
    }

    /// `setPageHide` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sec, para, hideHeader?, hideFooter?, hideMaster?, hideBorder?,
    /// hideFill?, hidePageNum? }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = setPageHideEx)]
    pub fn set_page_hide_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_bool, json_u32};
        self.set_page_hide_native(
            json_u32(options_json, "sec").unwrap_or(0) as usize,
            json_u32(options_json, "para").unwrap_or(0) as usize,
            json_bool(options_json, "hideHeader").unwrap_or(false),
            json_bool(options_json, "hideFooter").unwrap_or(false),
            json_bool(options_json, "hideMaster").unwrap_or(false),
            json_bool(options_json, "hideBorder").unwrap_or(false),
            json_bool(options_json, "hideFill").unwrap_or(false),
            json_bool(options_json, "hidePageNum").unwrap_or(false),
        )
        .map_err(|e| e.into())
    }

    /// 감추기 조회
    #[wasm_bindgen(js_name = getPageHide)]
    pub fn get_page_hide(&self, sec: u32, para: u32) -> Result<String, JsValue> {
        self.get_page_hide_native(sec as usize, para as usize)
            .map_err(|e| e.into())
    }

    /// 구역의 쪽 번호 매기기를 정한다 (쪽 > 쪽 번호 매기기, #7635).
    ///
    /// position: 0 없음, 1~3 위 왼쪽·가운데·오른쪽, 4~6 아래, 7·8 바깥쪽 위·아래, 9·10 안쪽 위·아래.
    /// format: 번호 모양(0 = 1,2,3). dash: 줄표(`- 1 -`).
    /// 결과: `{ok, controlIdx, removed}` — 첫 문단에 넣은 컨트롤 차례와 지운 (문단, 컨트롤 차례)를 지운 차례대로.
    #[wasm_bindgen(js_name = setPageNumberPosition)]
    pub fn set_page_number_position(
        &mut self,
        section_idx: u32,
        position: u32,
        format: u32,
        dash: bool,
    ) -> Result<String, JsValue> {
        self.set_page_number_position_native(
            section_idx as usize,
            u8::try_from(position).unwrap_or(u8::MAX),
            u8::try_from(format).unwrap_or(u8::MAX),
            dash,
        )
        .map_err(|e| e.into())
    }

    /// 구역의 쪽 번호 매기기를 읽는다: `{ok, exists, position?, format?, dash?}` (#7635).
    #[wasm_bindgen(js_name = getPageNumberPosition)]
    pub fn get_page_number_position(&self, section_idx: u32) -> Result<String, JsValue> {
        self.get_page_number_position_native(section_idx as usize)
            .map_err(|e| e.into())
    }

    /// 문단 서식을 적용한다 (본문 문단).
    /// 문단 번호 시작 방식 설정
    #[wasm_bindgen(js_name = setNumberingRestart)]
    pub fn set_numbering_restart(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        mode: u8,
        start_num: u32,
    ) -> Result<String, JsValue> {
        self.set_numbering_restart_native(section_idx as usize, para_idx as usize, mode, start_num)
            .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = applyParaFormat)]
    pub fn apply_para_format(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_para_format_native(sec_idx, para_idx, props_json)
            .map_err(|e| e.into())
    }

    /// 문단의 paraShapeId를 직접 설정한다.
    #[wasm_bindgen(js_name = setParaShapeId)]
    pub fn set_para_shape_id(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        para_shape_id: u16,
    ) -> Result<String, JsValue> {
        self.set_para_shape_id_native(sec_idx, para_idx, para_shape_id)
            .map_err(|e| e.into())
    }

    /// 문단 서식을 적용한다 (셀 내 문단).
    #[wasm_bindgen(js_name = applyParaFormatInCell)]
    pub fn apply_para_format_in_cell(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        props_json: &str,
    ) -> Result<String, JsValue> {
        self.apply_para_format_in_cell_native(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
            props_json,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = getCellParaPropertiesAtByPath)]
    pub fn get_cell_para_properties_at_by_path_api(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.get_cell_para_properties_at_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = applyParaFormatInCellByPath)]
    pub fn apply_para_format_in_cell_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        props_json: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.apply_para_format_in_cell_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            props_json,
        )
        .map_err(|e| e.into())
    }

    #[wasm_bindgen(js_name = setCellParaShapeIdByPath)]
    pub fn set_cell_para_shape_id_by_path_api(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        para_shape_id: u16,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.set_cell_para_shape_id_by_path(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            para_shape_id,
        )
        .map_err(|e| e.into())
    }

    /// 셀 내 문단의 paraShapeId를 직접 설정한다.
    #[wasm_bindgen(js_name = setCellParaShapeId)]
    pub fn set_cell_para_shape_id(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        para_shape_id: u16,
    ) -> Result<String, JsValue> {
        self.set_cell_para_shape_id_native(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
            para_shape_id,
        )
        .map_err(|e| e.into())
    }

    // =====================================================================
    // 클립보드 API (WASM 바인딩)
    // =====================================================================

    /// 내부 클립보드에 데이터가 있는지 확인한다.
    #[wasm_bindgen(js_name = hasInternalClipboard)]
    pub fn has_internal_clipboard(&self) -> bool {
        self.has_internal_clipboard_native()
    }

    /// 실제 내부 클립보드가 글자 모양만 가진 한 문단 조각인지 읽는다.
    #[wasm_bindgen(js_name = clipboardIsSingleText)]
    pub fn clipboard_is_single_text(&self) -> bool {
        self.clipboard_is_single_text_native()
    }

    /// 내부 클립보드의 플레인 텍스트를 반환한다.
    #[wasm_bindgen(js_name = getClipboardText)]
    pub fn get_clipboard_text(&self) -> String {
        self.get_clipboard_text_native()
    }

    /// 내부 클립보드를 초기화한다.
    #[wasm_bindgen(js_name = clearClipboard)]
    pub fn clear_clipboard(&mut self) {
        self.clear_clipboard_native()
    }

    /// 선택 영역을 내부 클립보드에 복사한다.
    ///
    /// 반환값: JSON `{"ok":true,"text":"<plain_text>"}`
    #[wasm_bindgen(js_name = copySelection)]
    pub fn copy_selection(
        &mut self,
        section_idx: u32,
        start_para_idx: u32,
        start_char_offset: u32,
        end_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.copy_selection_native(
            section_idx as usize,
            start_para_idx as usize,
            start_char_offset as usize,
            end_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 선택 영역을 논리적 오프셋(`insertTextLogical` 과 같은 축)으로 받아 내부 클립보드에 복사한다.
    ///
    /// 각주·글자처럼 취급 개체 바로 뒤에서 시작한 선택은 그 개체를 담지 않는다 (#7444).
    /// 반환값: JSON `{"ok":true,"text":"<plain_text>"}`
    #[wasm_bindgen(js_name = copySelectionLogical)]
    pub fn copy_selection_logical(
        &mut self,
        section_idx: u32,
        start_para_idx: u32,
        start_logical_offset: u32,
        end_para_idx: u32,
        end_logical_offset: u32,
    ) -> Result<String, JsValue> {
        self.copy_selection_logical_native(
            section_idx as usize,
            start_para_idx as usize,
            start_logical_offset as usize,
            end_para_idx as usize,
            end_logical_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 표 셀 내부 선택 영역을 내부 클립보드에 복사한다.
    #[wasm_bindgen(js_name = copySelectionInCell)]
    pub fn copy_selection_in_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        start_cell_para_idx: u32,
        start_char_offset: u32,
        end_cell_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.copy_selection_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            start_cell_para_idx as usize,
            start_char_offset as usize,
            end_cell_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// `copySelectionInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, startCellParaIdx,
    /// startCharOffset, endCellParaIdx, endCharOffset }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = copySelectionInCellEx)]
    pub fn copy_selection_in_cell_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::json_u32;
        self.copy_selection_in_cell_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCharOffset").unwrap_or(0) as usize,
            json_u32(options_json, "endCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "endCharOffset").unwrap_or(0) as usize,
        )
        .map_err(|e| e.into())
    }

    /// 전체 cellPath가 가리키는 중첩 셀의 선택 영역을 내부 클립보드에 복사한다(#4272).
    #[wasm_bindgen(js_name = copySelectionInCellByPath)]
    pub fn copy_selection_in_cell_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        start_cell_para_idx: u32,
        start_char_offset: u32,
        end_cell_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.copy_selection_in_cell_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            start_cell_para_idx as usize,
            start_char_offset as usize,
            end_cell_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 컨트롤 객체(표, 이미지, 도형)를 내부 클립보드에 복사한다.
    ///
    /// [Task #1161] `cell_path_json` 이 빈 문자열/`"[]"` 면 본문, 그 외에는 셀/글상자
    /// 경로(`[{"controlIndex","cellIndex","cellParaIndex"}, ...]`)의 컨트롤을 복사한다.
    #[wasm_bindgen(js_name = copyControl)]
    pub fn copy_control(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        cell_path_json: &str,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        let cell_path = parse_cell_path_arg(cell_path_json)?;
        self.copy_control_native(
            section_idx as usize,
            para_idx as usize,
            &cell_path,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 내부 클립보드에 컨트롤(표/그림/도형)이 포함되어 있는지 확인한다.
    #[wasm_bindgen(js_name = clipboardHasControl)]
    pub fn clipboard_has_control(&self) -> bool {
        self.clipboard_has_control_native()
    }

    /// 내부 클립보드의 컨트롤 객체를 캐럿 위치에 붙여넣는다.
    ///
    /// 반환값: JSON `{"ok":true,"paraIdx":<idx>,"controlIdx":0}`
    #[wasm_bindgen(js_name = pasteControl)]
    pub fn paste_control(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.paste_control_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 내부 클립보드의 내용을 캐럿 위치에 붙여넣는다 (본문 문단).
    ///
    /// 반환값: JSON `{"ok":true,"paraIdx":<idx>,"charOffset":<offset>}`
    #[wasm_bindgen(js_name = pasteInternal)]
    pub fn paste_internal(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.paste_internal_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 순수 서식 글 조각을 본문 논리 캐럿의 누름틀 안팎 소속으로 붙인다.
    #[wasm_bindgen(js_name = pasteInternalTextLogical)]
    pub fn paste_internal_text_logical(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        logical_offset: u32,
    ) -> Result<String, JsValue> {
        self.paste_internal_text_logical_native(
            section_idx as usize,
            para_idx as usize,
            logical_offset as usize,
        )
        .map_err(|error| error.into())
    }

    /// 내부 클립보드의 내용을 표 셀 내부에 붙여넣는다.
    ///
    /// 반환값: JSON `{"ok":true,"cellParaIdx":<idx>,"charOffset":<offset>}`
    #[wasm_bindgen(js_name = pasteInternalInCell)]
    pub fn paste_internal_in_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        self.paste_internal_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 내부 클립보드의 내용을 cellPath가 가리키는 중첩 표 셀에 붙여넣는다.
    ///
    /// 반환값: JSON `{"ok":true,"cellParaIdx":<idx>,"charOffset":<offset>}`
    #[wasm_bindgen(js_name = pasteInternalInCellByPath)]
    pub fn paste_internal_in_cell_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.paste_internal_in_cell_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 선택 영역을 HTML 문자열로 변환한다 (본문).
    #[wasm_bindgen(js_name = exportSelectionHtml)]
    pub fn export_selection_html(
        &self,
        section_idx: u32,
        start_para_idx: u32,
        start_char_offset: u32,
        end_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.export_selection_html_native(
            section_idx as usize,
            start_para_idx as usize,
            start_char_offset as usize,
            end_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 선택 영역을 HTML 문자열로 변환한다 (셀 내부).
    #[wasm_bindgen(js_name = exportSelectionInCellHtml)]
    pub fn export_selection_in_cell_html(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        start_cell_para_idx: u32,
        start_char_offset: u32,
        end_cell_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        self.export_selection_in_cell_html_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            start_cell_para_idx as usize,
            start_char_offset as usize,
            end_cell_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// `exportSelectionInCellHtml` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, startCellParaIdx,
    /// startCharOffset, endCellParaIdx, endCharOffset }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = exportSelectionInCellHtmlEx)]
    pub fn export_selection_in_cell_html_ex(&self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::json_u32;
        self.export_selection_in_cell_html_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "startCharOffset").unwrap_or(0) as usize,
            json_u32(options_json, "endCellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "endCharOffset").unwrap_or(0) as usize,
        )
        .map_err(|e| e.into())
    }

    /// 전체 cellPath가 가리키는 중첩 셀 선택을 HTML로 변환한다(#4272).
    #[wasm_bindgen(js_name = exportSelectionInCellHtmlByPath)]
    pub fn export_selection_in_cell_html_by_path(
        &self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        start_cell_para_idx: u32,
        start_char_offset: u32,
        end_cell_para_idx: u32,
        end_char_offset: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.export_selection_in_cell_html_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            start_cell_para_idx as usize,
            start_char_offset as usize,
            end_cell_para_idx as usize,
            end_char_offset as usize,
        )
        .map_err(|e| e.into())
    }

    /// 컨트롤 객체를 HTML 문자열로 변환한다.
    #[wasm_bindgen(js_name = exportControlHtml)]
    pub fn export_control_html(
        &self,
        section_idx: u32,
        para_idx: u32,
        cell_path_json: &str,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        let cell_path = parse_cell_path_arg(cell_path_json)?;
        self.export_control_html_native(
            section_idx as usize,
            para_idx as usize,
            &cell_path,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 컨트롤의 이미지 바이너리 데이터를 반환한다 (Uint8Array).
    #[wasm_bindgen(js_name = getControlImageData)]
    pub fn get_control_image_data(
        &self,
        section_idx: u32,
        para_idx: u32,
        cell_path_json: &str,
        control_idx: u32,
    ) -> Result<Vec<u8>, JsValue> {
        let cell_path = parse_cell_path_arg(cell_path_json)?;
        self.get_control_image_data_native(
            section_idx as usize,
            para_idx as usize,
            &cell_path,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 컨트롤의 이미지 MIME 타입을 반환한다.
    #[wasm_bindgen(js_name = getControlImageMime)]
    pub fn get_control_image_mime(
        &self,
        section_idx: u32,
        para_idx: u32,
        cell_path_json: &str,
        control_idx: u32,
    ) -> Result<String, JsValue> {
        let cell_path = parse_cell_path_arg(cell_path_json)?;
        self.get_control_image_mime_native(
            section_idx as usize,
            para_idx as usize,
            &cell_path,
            control_idx as usize,
        )
        .map_err(|e| e.into())
    }

    /// 한글 클립보드 문서모델(hwpjson)을 캐럿 위치에 삽입한다 (본문).
    ///
    /// 한글은 Ctrl+C 시 클립보드 HTML 끝 주석에 문서 모델 전체를 싣는다. HTML 에는 없는
    /// 글꼴 등록·문단모양·쪽 설정·셀 속성·그림 원본이 여기 있어, 이 경로라야 원본과 같은
    /// 조판이 나온다. 실패하면 호출한 쪽이 종전 `pasteHtml` 로 되돌아가면 된다.
    #[wasm_bindgen(js_name = pasteHwpJson)]
    pub fn paste_hwp_json(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.paste_hwp_json_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            json,
        )
        .map_err(|e| e.into())
    }

    /// HTML 문자열을 파싱하여 캐럿 위치에 삽입한다 (본문).
    ///
    /// `char_offset` 과 반환 `charOffset` 은 논리 위치(`insertTextLogical` 과 같은 축)다.
    #[wasm_bindgen(js_name = pasteHtml)]
    pub fn paste_html(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        char_offset: u32,
        html: &str,
    ) -> Result<String, JsValue> {
        self.paste_html_native(
            section_idx as usize,
            para_idx as usize,
            char_offset as usize,
            html,
        )
        .map_err(|e| e.into())
    }

    /// 순수 HTML 글을 본문 논리 캐럿의 누름틀 안팎 소속으로 붙인다.
    #[wasm_bindgen(js_name = pasteHtmlTextLogical)]
    pub fn paste_html_text_logical(
        &mut self,
        section_idx: u32,
        para_idx: u32,
        logical_offset: u32,
        html: &str,
    ) -> Result<String, JsValue> {
        self.paste_html_text_logical_native(
            section_idx as usize,
            para_idx as usize,
            logical_offset as usize,
            html,
        )
        .map_err(|error| error.into())
    }

    /// HTML 문자열을 파싱하여 셀 내부 캐럿 위치에 삽입한다.
    #[wasm_bindgen(js_name = pasteHtmlInCell)]
    pub fn paste_html_in_cell(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        control_idx: u32,
        cell_idx: u32,
        cell_para_idx: u32,
        char_offset: u32,
        html: &str,
    ) -> Result<String, JsValue> {
        self.paste_html_in_cell_native(
            section_idx as usize,
            parent_para_idx as usize,
            control_idx as usize,
            cell_idx as usize,
            cell_para_idx as usize,
            char_offset as usize,
            html,
        )
        .map_err(|e| e.into())
    }

    /// `pasteHtmlInCell` 의 options object 변형 (#1413).
    ///
    /// options JSON 키: `{ sectionIdx, parentParaIdx, controlIdx, cellIdx, cellParaIdx,
    /// charOffset?, html: string }`. positional 과 동일 동작.
    #[wasm_bindgen(js_name = pasteHtmlInCellEx)]
    pub fn paste_html_in_cell_ex(&mut self, options_json: &str) -> Result<String, JsValue> {
        use crate::document_core::helpers::{json_str, json_u32};
        self.paste_html_in_cell_native(
            json_u32(options_json, "sectionIdx").unwrap_or(0) as usize,
            json_u32(options_json, "parentParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "controlIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellIdx").unwrap_or(0) as usize,
            json_u32(options_json, "cellParaIdx").unwrap_or(0) as usize,
            json_u32(options_json, "charOffset").unwrap_or(0) as usize,
            &json_str(options_json, "html").unwrap_or_default(),
        )
        .map_err(|e| e.into())
    }

    /// HTML 문자열을 파싱하여 cellPath가 가리키는 중첩 표 셀에 삽입한다.
    #[wasm_bindgen(js_name = pasteHtmlInCellByPath)]
    pub fn paste_html_in_cell_by_path(
        &mut self,
        section_idx: u32,
        parent_para_idx: u32,
        path_json: &str,
        char_offset: u32,
        html: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.paste_html_in_cell_by_path_native(
            section_idx as usize,
            parent_para_idx as usize,
            &path,
            char_offset as usize,
            html,
        )
        .map_err(|e| e.into())
    }

    /// 문단별 줄 폭 측정 진단 (WASM)
    #[wasm_bindgen(js_name = measureWidthDiagnostic)]
    pub fn measure_width_diagnostic(
        &self,
        section_idx: u32,
        para_idx: u32,
    ) -> Result<String, JsValue> {
        self.measure_width_diagnostic_native(section_idx as usize, para_idx as usize)
            .map_err(|e| e.into())
    }
}

pub(crate) mod event;

/// WASM 뷰어 컨트롤러 (뷰포트 관리 + 스케줄링)
#[wasm_bindgen]
pub struct HwpViewer {
    /// 문서 참조 (소유)
    document: HwpDocument,
    /// 렌더링 스케줄러
    scheduler: RenderScheduler,
}

#[wasm_bindgen]
impl HwpViewer {
    /// 뷰어 생성
    #[wasm_bindgen(constructor)]
    pub fn new(document: HwpDocument) -> Self {
        let page_count = document.page_count();
        let scheduler = RenderScheduler::new(page_count);
        Self {
            document,
            scheduler,
        }
    }

    /// 뷰포트 업데이트 (스크롤/리사이즈 시 호출)
    #[wasm_bindgen(js_name = updateViewport)]
    pub fn update_viewport(&mut self, scroll_x: f64, scroll_y: f64, width: f64, height: f64) {
        let event = RenderEvent::ViewportChanged(Viewport {
            scroll_x,
            scroll_y,
            width,
            height,
            zoom: self.scheduler_zoom(),
        });
        self.scheduler.on_event(&event);
    }

    /// 줌 변경
    #[wasm_bindgen(js_name = setZoom)]
    pub fn set_zoom(&mut self, zoom: f64) {
        let event = RenderEvent::ZoomChanged(zoom);
        self.scheduler.on_event(&event);
    }

    /// 현재 보이는 페이지 목록 반환
    #[wasm_bindgen(js_name = visiblePages)]
    pub fn visible_pages(&self) -> Vec<u32> {
        self.scheduler.visible_pages()
    }

    /// 대기 중인 렌더링 작업 수
    #[wasm_bindgen(js_name = pendingTaskCount)]
    pub fn pending_task_count(&self) -> u32 {
        self.scheduler.pending_count() as u32
    }

    /// 총 페이지 수
    #[wasm_bindgen(js_name = pageCount)]
    pub fn page_count(&self) -> u32 {
        self.document.page_count()
    }

    /// 특정 페이지 SVG 렌더링
    #[wasm_bindgen(js_name = renderPageSvg)]
    pub fn render_page_svg(&self, page_num: u32) -> Result<String, JsValue> {
        self.document.render_page_svg(page_num)
    }

    /// [#4709] SVG 출력에 배치 메트릭 face 주석을 붙일지 설정한다 (기본 꺼짐).
    #[wasm_bindgen(js_name = setAnnotateMetricFont)]
    pub fn set_annotate_metric_font(&mut self, enabled: bool) {
        self.document.set_annotate_metric_font(enabled);
    }

    /// 명시적인 출력 profile로 특정 페이지 SVG 렌더링
    #[wasm_bindgen(js_name = renderPageSvgWithProfile)]
    pub fn render_page_svg_with_profile(
        &self,
        page_num: u32,
        profile: &str,
    ) -> Result<String, JsValue> {
        self.document
            .render_page_svg_with_profile(page_num, profile)
    }

    /// 특정 페이지 HTML 렌더링
    #[wasm_bindgen(js_name = renderPageHtml)]
    pub fn render_page_html(&self, page_num: u32) -> Result<String, JsValue> {
        self.document.render_page_html(page_num)
    }
}

impl HwpViewer {
    fn scheduler_zoom(&self) -> f64 {
        1.0
    }
}

#[wasm_bindgen]
impl HwpDocument {
    // ── 책갈피 API ──

    /// 문서 내 모든 책갈피 목록 반환
    #[wasm_bindgen(js_name = getBookmarks)]
    pub fn get_bookmarks(&self) -> Result<String, JsValue> {
        self.core.get_bookmarks_native().map_err(|e| e.into())
    }

    /// 문서 구조(개요/조문) 트리를 JSON으로 반환 (사이드바 목차 네비게이션용)
    ///
    /// `mode`: `"auto"` | `"outline"` | `"clause"` (인식 불가 시 `auto`).
    #[wasm_bindgen(js_name = getStructure)]
    pub fn get_structure(&self, mode: &str) -> Result<String, JsValue> {
        self.core.get_structure_native(mode).map_err(|e| e.into())
    }

    /// 문단 모양의 개요 번호만 탐색 정보로 반환한다.
    ///
    /// 일반 문단의 `1.` 같은 텍스트는 분석하지 않는다.
    #[wasm_bindgen(js_name = getOutlineNavigation)]
    pub fn get_outline_navigation(&self) -> Result<String, JsValue> {
        self.core
            .get_outline_navigation_native()
            .map_err(|e| e.into())
    }

    /// 덧말 넣기. `char_offset`은 원문 축 글자 자리다.
    /// `json`: `{"mainText","rubyText","below":bool,"styleId":number|null}`.
    #[wasm_bindgen(js_name = insertRuby)]
    pub fn insert_ruby(
        &mut self,
        sec: u32,
        para: u32,
        char_offset: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .insert_ruby_native(sec as usize, para as usize, char_offset as usize, json)
            .map_err(|e| e.into())
    }

    /// 글자 겹치기 넣기. `char_offset`은 원문 축 글자 자리다.
    /// `json`: `{"text","shape":0~13,"innerSize":-8~2,"overlap":bool}`.
    #[wasm_bindgen(js_name = insertCharOverlap)]
    pub fn insert_char_overlap(
        &mut self,
        sec: u32,
        para: u32,
        char_offset: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .insert_char_overlap_native(sec as usize, para as usize, char_offset as usize, json)
            .map_err(|e| e.into())
    }

    /// 덧말·글자 겹침 하나의 값(겹칠 글자는 친 글 그대로).
    #[wasm_bindgen(js_name = getComposeControl)]
    pub fn get_compose_control(
        &self,
        sec: u32,
        para: u32,
        ctrl_idx: u32,
    ) -> Result<String, JsValue> {
        self.core
            .get_compose_control_native(sec as usize, para as usize, ctrl_idx as usize)
            .map_err(|e| e.into())
    }

    /// 덧말·글자 겹침 하나를 고친다. 입력은 넣을 때와 같다.
    #[wasm_bindgen(js_name = setComposeControl)]
    pub fn set_compose_control(
        &mut self,
        sec: u32,
        para: u32,
        ctrl_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .set_compose_control_native(sec as usize, para as usize, ctrl_idx as usize, json)
            .map_err(|e| e.into())
    }

    /// 덧말·글자 겹침 하나를 지운다. `keep_main_text`면 덧말만 지우고 본말을 글로 남긴다.
    #[wasm_bindgen(js_name = deleteComposeControl)]
    pub fn delete_compose_control(
        &mut self,
        sec: u32,
        para: u32,
        ctrl_idx: u32,
        keep_main_text: bool,
    ) -> Result<String, JsValue> {
        self.core
            .delete_compose_control_native(
                sec as usize,
                para as usize,
                ctrl_idx as usize,
                keep_main_text,
            )
            .map_err(|e| e.into())
    }

    /// 셀 경로(표 셀·중첩 셀·글상자, 머리말·꼬리말 뿌리)의 문단에 덧말을 넣는다. 입력은 `insertRuby`와 같다.
    #[wasm_bindgen(js_name = insertRubyByPath)]
    pub fn insert_ruby_by_path(
        &mut self,
        sec: u32,
        parent_para: u32,
        path_json: &str,
        char_offset: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.core
            .insert_ruby_at(
                compose_cell(sec, parent_para, &path),
                char_offset as usize,
                json,
            )
            .map_err(|e| e.into())
    }

    /// 셀 경로의 문단에 글자 겹침을 넣는다. 입력은 `insertCharOverlap`과 같다.
    #[wasm_bindgen(js_name = insertCharOverlapByPath)]
    pub fn insert_char_overlap_by_path(
        &mut self,
        sec: u32,
        parent_para: u32,
        path_json: &str,
        char_offset: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.core
            .insert_char_overlap_at(
                compose_cell(sec, parent_para, &path),
                char_offset as usize,
                json,
            )
            .map_err(|e| e.into())
    }

    /// 셀 경로 문단의 덧말·글자 겹침 하나의 값.
    #[wasm_bindgen(js_name = getComposeControlByPath)]
    pub fn get_compose_control_by_path(
        &self,
        sec: u32,
        parent_para: u32,
        path_json: &str,
        ctrl_idx: u32,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.core
            .get_compose_control_at(compose_cell(sec, parent_para, &path), ctrl_idx as usize)
            .map_err(|e| e.into())
    }

    /// 셀 경로 문단의 덧말·글자 겹침 하나를 고친다.
    #[wasm_bindgen(js_name = setComposeControlByPath)]
    pub fn set_compose_control_by_path(
        &mut self,
        sec: u32,
        parent_para: u32,
        path_json: &str,
        ctrl_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.core
            .set_compose_control_at(
                compose_cell(sec, parent_para, &path),
                ctrl_idx as usize,
                json,
            )
            .map_err(|e| e.into())
    }

    /// 셀 경로 문단의 덧말·글자 겹침 하나를 지운다. `keep_main_text`면 본말을 글로 남긴다.
    #[wasm_bindgen(js_name = deleteComposeControlByPath)]
    pub fn delete_compose_control_by_path(
        &mut self,
        sec: u32,
        parent_para: u32,
        path_json: &str,
        ctrl_idx: u32,
        keep_main_text: bool,
    ) -> Result<String, JsValue> {
        let path = DocumentCore::parse_cell_path(path_json)?;
        self.core
            .delete_compose_control_at(
                compose_cell(sec, parent_para, &path),
                ctrl_idx as usize,
                keep_main_text,
            )
            .map_err(|e| e.into())
    }

    /// 각주·미주 문단에 덧말을 넣는다. 주소는 `insertTextInFootnote`와 같다.
    #[wasm_bindgen(js_name = insertRubyInFootnote)]
    pub fn insert_ruby_in_footnote(
        &mut self,
        sec: u32,
        para: u32,
        control_idx: u32,
        fn_para: u32,
        char_offset: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .insert_ruby_at(
                compose_note(sec, para, control_idx, fn_para),
                char_offset as usize,
                json,
            )
            .map_err(|e| e.into())
    }

    /// 각주·미주 문단에 글자 겹침을 넣는다.
    #[wasm_bindgen(js_name = insertCharOverlapInFootnote)]
    pub fn insert_char_overlap_in_footnote(
        &mut self,
        sec: u32,
        para: u32,
        control_idx: u32,
        fn_para: u32,
        char_offset: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .insert_char_overlap_at(
                compose_note(sec, para, control_idx, fn_para),
                char_offset as usize,
                json,
            )
            .map_err(|e| e.into())
    }

    /// 각주·미주 문단의 덧말·글자 겹침 하나의 값.
    #[wasm_bindgen(js_name = getComposeControlInFootnote)]
    pub fn get_compose_control_in_footnote(
        &self,
        sec: u32,
        para: u32,
        control_idx: u32,
        fn_para: u32,
        ctrl_idx: u32,
    ) -> Result<String, JsValue> {
        self.core
            .get_compose_control_at(
                compose_note(sec, para, control_idx, fn_para),
                ctrl_idx as usize,
            )
            .map_err(|e| e.into())
    }

    /// 각주·미주 문단의 덧말·글자 겹침 하나를 고친다.
    #[wasm_bindgen(js_name = setComposeControlInFootnote)]
    pub fn set_compose_control_in_footnote(
        &mut self,
        sec: u32,
        para: u32,
        control_idx: u32,
        fn_para: u32,
        ctrl_idx: u32,
        json: &str,
    ) -> Result<String, JsValue> {
        self.core
            .set_compose_control_at(
                compose_note(sec, para, control_idx, fn_para),
                ctrl_idx as usize,
                json,
            )
            .map_err(|e| e.into())
    }

    /// 각주·미주 문단의 덧말·글자 겹침 하나를 지운다. `keep_main_text`면 본말을 글로 남긴다.
    #[wasm_bindgen(js_name = deleteComposeControlInFootnote)]
    pub fn delete_compose_control_in_footnote(
        &mut self,
        sec: u32,
        para: u32,
        control_idx: u32,
        fn_para: u32,
        ctrl_idx: u32,
        keep_main_text: bool,
    ) -> Result<String, JsValue> {
        self.core
            .delete_compose_control_at(
                compose_note(sec, para, control_idx, fn_para),
                ctrl_idx as usize,
                keep_main_text,
            )
            .map_err(|e| e.into())
    }

    /// 책갈피 추가
    #[wasm_bindgen(js_name = addBookmark)]
    pub fn add_bookmark(
        &mut self,
        sec: u32,
        para: u32,
        char_offset: u32,
        name: &str,
    ) -> Result<String, JsValue> {
        self.core
            .add_bookmark_native(sec as usize, para as usize, char_offset as usize, name)
            .map_err(|e| e.into())
    }

    /// 책갈피 삭제
    #[wasm_bindgen(js_name = deleteBookmark)]
    pub fn delete_bookmark(
        &mut self,
        sec: u32,
        para: u32,
        ctrl_idx: u32,
    ) -> Result<String, JsValue> {
        self.core
            .delete_bookmark_native(sec as usize, para as usize, ctrl_idx as usize)
            .map_err(|e| e.into())
    }

    /// 책갈피 이름 변경
    #[wasm_bindgen(js_name = renameBookmark)]
    pub fn rename_bookmark(
        &mut self,
        sec: u32,
        para: u32,
        ctrl_idx: u32,
        new_name: &str,
    ) -> Result<String, JsValue> {
        self.core
            .rename_bookmark_native(sec as usize, para as usize, ctrl_idx as usize, new_name)
            .map_err(|e| e.into())
    }
}

// ─── 독립 함수 (문서 로드 없이 사용 가능) ───────────────

/// HWP 파일에서 썸네일 이미지만 경량 추출 (전체 파싱 없이)
///
/// 반환: JSON `{ "format": "png"|"gif", "base64": "...", "width": N, "height": N }`
/// PrvImage가 없으면 `null` 반환
#[wasm_bindgen(js_name = extractThumbnail)]
pub fn extract_thumbnail(data: &[u8]) -> JsValue {
    match crate::parser::extract_thumbnail_only(data) {
        Some(result) => {
            let base64 = base64_encode(&result.data);
            let mime = match result.format.as_str() {
                "png" => "image/png",
                "bmp" => "image/bmp",
                "gif" => "image/gif",
                _ => "application/octet-stream",
            };
            let json = format!(
                r#"{{"format":"{}","base64":"{}","dataUri":"data:{};base64,{}","width":{},"height":{}}}"#,
                result.format, base64, mime, base64, result.width, result.height
            );
            JsValue::from_str(&json)
        }
        None => JsValue::NULL,
    }
}

fn base64_encode(data: &[u8]) -> String {
    use base64::Engine;
    base64::engine::general_purpose::STANDARD.encode(data)
}

#[cfg(test)]
mod tests;