relateby-pattern 0.4.0

Core pattern data structures
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
//! WASM bindings for Pattern-Core using wasm-bindgen
//!
//! This module provides JavaScript/TypeScript-friendly bindings for pattern-core,
//! enabling web and Node.js developers to programmatically construct and operate
//! on Pattern and Subject instances.
//!
//! # Usage in JavaScript/TypeScript
//!
//! ```javascript
//! import init, { Pattern, Subject, Value } from 'pattern-core';
//!
//! await init();
//!
//! // Create an atomic pattern
//! const atomic = Pattern.point("hello");
//!
//! // Create a pattern with Subject value
//! const subject = Subject.new("alice", ["Person"], { name: Value.string("Alice") });
//! const pattern = Pattern.point(subject);
//!
//! // Validate a pattern
//! const result = pattern.validate({ maxDepth: 10 });
//! if (result._tag === 'Left') {
//!     console.error('Validation failed:', result.left);
//! }
//! ```
//!
//! # Either-like Return Values
//!
//! Fallible operations return an Either-like value compatible with effect-ts:
//! - Success: `{ _tag: 'Right', right: T }`
//! - Failure: `{ _tag: 'Left', left: E }`
//!
//! This enables seamless integration with functional programming libraries
//! without requiring any wrapper code.

use std::collections::HashMap;
use wasm_bindgen::prelude::*;

// Re-export core types for internal use
use crate::pattern::{Pattern, ValidationError};
use crate::subject::{RangeValue, Subject, Symbol, Value};

// ============================================================================
// Module Structure
// ============================================================================
//
// This module is organized into the following sections:
//
// 1. Error/Result Handling (Either-like)
//    - JsEither type for fallible operations
//    - Conversion helpers for Result → Either
//
// 2. Value Conversion Helpers
//    - JsValue ↔ Rust Value conversions
//    - Primitive type handling
//    - Option handling
//
// 3. Value Factories (Phase 3)
//    - JsValue factory methods for all Value variants
//
// 4. Subject Bindings (Phase 3)
//    - Subject constructor and accessors
//
// 5. Pattern Bindings (Phase 3)
//    - Pattern constructors, accessors, and operations
//
// 6. Validation/Analysis Types (Phase 4)
//    - ValidationRules, StructureAnalysis bindings
//
// ============================================================================

// ============================================================================
// Validation/Analysis Types (T016, T017 - Phase 4)
// ============================================================================

/// Configurable validation rules for pattern structure.
///
/// Rules can specify limits on nesting depth, element counts, or other structural properties.
/// All rules are optional (undefined/null means no limit).
///
/// Exported to JavaScript as `WasmValidationRules`.
#[wasm_bindgen]
pub struct WasmValidationRules {
    /// Maximum nesting depth allowed (undefined = no limit)
    #[wasm_bindgen(skip)]
    pub max_depth: Option<usize>,
    /// Maximum element count allowed (undefined = no limit)
    #[wasm_bindgen(skip)]
    pub max_elements: Option<usize>,
}

#[wasm_bindgen]
impl WasmValidationRules {
    /// Create new validation rules.
    ///
    /// # Arguments
    /// * `max_depth` - Maximum nesting depth (undefined for no limit)
    /// * `max_elements` - Maximum element count (undefined for no limit)
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const rules = new ValidationRules(10, 100); // Max depth 10, max elements 100
    /// const noLimits = new ValidationRules(undefined, undefined); // No limits
    /// ```
    #[wasm_bindgen(constructor)]
    pub fn new(max_depth: JsValue, max_elements: JsValue) -> WasmValidationRules {
        let max_depth = js_to_option(&max_depth, js_to_i64).map(|v| v as usize);
        let max_elements = js_to_option(&max_elements, js_to_i64).map(|v| v as usize);

        WasmValidationRules {
            max_depth,
            max_elements,
        }
    }

    /// Get the max_depth value.
    #[wasm_bindgen(getter, js_name = maxDepth)]
    pub fn max_depth(&self) -> JsValue {
        match self.max_depth {
            Some(d) => JsValue::from_f64(d as f64),
            None => JsValue::undefined(),
        }
    }

    /// Get the max_elements value.
    #[wasm_bindgen(getter, js_name = maxElements)]
    pub fn max_elements(&self) -> JsValue {
        match self.max_elements {
            Some(e) => JsValue::from_f64(e as f64),
            None => JsValue::undefined(),
        }
    }
}

impl WasmValidationRules {
    /// Convert to internal ValidationRules type.
    fn to_internal(&self) -> crate::pattern::ValidationRules {
        crate::pattern::ValidationRules {
            max_depth: self.max_depth,
            max_elements: self.max_elements,
            required_fields: vec![], // Not exposed in WASM yet
        }
    }
}

/// Results from structure analysis utilities.
///
/// Provides detailed information about pattern structural characteristics.
///
/// Exported to JavaScript as `WasmStructureAnalysis`.
#[wasm_bindgen]
pub struct WasmStructureAnalysis {
    #[wasm_bindgen(skip)]
    inner: crate::pattern::StructureAnalysis,
}

#[wasm_bindgen]
impl WasmStructureAnalysis {
    /// Get the depth distribution (count of nodes at each depth level).
    ///
    /// # Returns
    /// A JavaScript array where index = depth, value = count
    #[wasm_bindgen(getter, js_name = depthDistribution)]
    pub fn depth_distribution(&self) -> js_sys::Array {
        let arr = js_sys::Array::new();
        for count in &self.inner.depth_distribution {
            arr.push(&JsValue::from_f64(*count as f64));
        }
        arr
    }

    /// Get the element counts at each level.
    ///
    /// # Returns
    /// A JavaScript array where index = level, value = element count
    #[wasm_bindgen(getter, js_name = elementCounts)]
    pub fn element_counts(&self) -> js_sys::Array {
        let arr = js_sys::Array::new();
        for count in &self.inner.element_counts {
            arr.push(&JsValue::from_f64(*count as f64));
        }
        arr
    }

    /// Get the identified nesting patterns.
    ///
    /// # Returns
    /// A JavaScript array of pattern description strings (e.g., "linear", "tree", "balanced")
    #[wasm_bindgen(getter, js_name = nestingPatterns)]
    pub fn nesting_patterns(&self) -> js_sys::Array {
        let arr = js_sys::Array::new();
        for pattern in &self.inner.nesting_patterns {
            arr.push(&JsValue::from_str(pattern));
        }
        arr
    }

    /// Get a human-readable summary of the structure.
    ///
    /// # Returns
    /// A summary string
    #[wasm_bindgen(getter)]
    pub fn summary(&self) -> String {
        self.inner.summary.clone()
    }
}

// ============================================================================
// 1. Either-like Return Shape (T006)
// ============================================================================
//
// Fallible operations return an Either-like value compatible with effect-ts:
// - Success: { _tag: 'Right', right: T }
// - Failure: { _tag: 'Left', left: E }
//
// This matches the shape of Effect's Either type, enabling:
// - Direct use with Either.match, Either.map, etc.
// - Pattern matching on _tag in TypeScript
// - No wrapper code required for effect-ts integration

/// Create an Either-like Right value (success case).
///
/// Returns a JsValue with shape: `{ _tag: 'Right', right: value }`
pub fn either_right(value: JsValue) -> JsValue {
    let obj = js_sys::Object::new();
    js_sys::Reflect::set(
        &obj,
        &JsValue::from_str("_tag"),
        &JsValue::from_str("Right"),
    )
    .expect("set _tag");
    js_sys::Reflect::set(&obj, &JsValue::from_str("right"), &value).expect("set right");
    obj.into()
}

/// Create an Either-like Left value (failure case).
///
/// Returns a JsValue with shape: `{ _tag: 'Left', left: error }`
pub fn either_left(error: JsValue) -> JsValue {
    let obj = js_sys::Object::new();
    js_sys::Reflect::set(&obj, &JsValue::from_str("_tag"), &JsValue::from_str("Left"))
        .expect("set _tag");
    js_sys::Reflect::set(&obj, &JsValue::from_str("left"), &error).expect("set left");
    obj.into()
}

/// Convert a Rust Result into an Either-like JsValue.
///
/// - `Ok(value)` → `{ _tag: 'Right', right: value }`
/// - `Err(error)` → `{ _tag: 'Left', left: error }`
pub fn result_to_either<T, E>(result: Result<T, E>) -> JsValue
where
    T: Into<JsValue>,
    E: Into<JsValue>,
{
    match result {
        Ok(value) => either_right(value.into()),
        Err(error) => either_left(error.into()),
    }
}

/// Convert a ValidationError to a JsValue object.
///
/// Returns: `{ message: string, ruleViolated: string, location: string[] }`
pub fn validation_error_to_js(error: &ValidationError) -> JsValue {
    let obj = js_sys::Object::new();

    // Set message
    js_sys::Reflect::set(
        &obj,
        &JsValue::from_str("message"),
        &JsValue::from_str(&error.message),
    )
    .expect("set message");

    // Set ruleViolated
    js_sys::Reflect::set(
        &obj,
        &JsValue::from_str("ruleViolated"),
        &JsValue::from_str(&error.rule_violated),
    )
    .expect("set ruleViolated");

    // Set location as array of strings
    let location_arr = js_sys::Array::new();
    for loc in &error.location {
        location_arr.push(&JsValue::from_str(loc));
    }
    js_sys::Reflect::set(&obj, &JsValue::from_str("location"), &location_arr)
        .expect("set location");

    obj.into()
}

// ============================================================================
// 2. Value Conversion Helpers (T005)
// ============================================================================
//
// These helpers convert between JavaScript values and Rust types at the
// WASM boundary. They handle:
// - Primitives: string, number (int/float), boolean
// - Option<T>: null/undefined ↔ None
// - Arrays and objects for complex Value types
// - The Value enum with all its variants

/// Convert a JsValue to a Rust String.
///
/// Returns `None` if the value is not a string.
pub fn js_to_string(value: &JsValue) -> Option<String> {
    value.as_string()
}

/// Convert a JsValue to a Rust i64.
///
/// Returns `None` if the value is not a number or cannot be safely converted.
pub fn js_to_i64(value: &JsValue) -> Option<i64> {
    value.as_f64().map(|f| f as i64)
}

/// Convert a JsValue to a Rust f64.
///
/// Returns `None` if the value is not a number.
pub fn js_to_f64(value: &JsValue) -> Option<f64> {
    value.as_f64()
}

/// Convert a JsValue to a Rust bool.
///
/// Returns `None` if the value is not a boolean.
pub fn js_to_bool(value: &JsValue) -> Option<bool> {
    value.as_bool()
}

/// Check if a JsValue is null or undefined.
pub fn js_is_null_or_undefined(value: &JsValue) -> bool {
    value.is_null() || value.is_undefined()
}

/// Convert a JsValue to an Option<T> using a conversion function.
///
/// Returns `None` if the value is null/undefined, otherwise applies the converter.
pub fn js_to_option<T, F>(value: &JsValue, convert: F) -> Option<T>
where
    F: FnOnce(&JsValue) -> Option<T>,
{
    if js_is_null_or_undefined(value) {
        None
    } else {
        convert(value)
    }
}

/// Convert a JsValue (JS object with string keys) to a HashMap<String, Value>.
///
/// Used for Subject properties and Value::VMap.
pub fn js_object_to_value_map(obj: &JsValue) -> Result<HashMap<String, Value>, String> {
    if !obj.is_object() || obj.is_null() {
        return Err("Expected an object".to_string());
    }

    let mut map = HashMap::new();
    let keys = js_sys::Object::keys(obj.unchecked_ref::<js_sys::Object>());

    for i in 0..keys.length() {
        let key = keys.get(i);
        let key_str = key
            .as_string()
            .ok_or_else(|| "Object key is not a string".to_string())?;
        let value = js_sys::Reflect::get(obj, &key).map_err(|_| "Failed to get property")?;
        let rust_value = js_to_value(&value)?;
        map.insert(key_str, rust_value);
    }

    Ok(map)
}

/// Convert a JsValue to a Rust Value enum.
///
/// Handles all Value variants by inspecting the JS value type and structure.
/// For complex types (range, measurement, tagged string), expects objects
/// with specific shapes.
pub fn js_to_value(js: &JsValue) -> Result<Value, String> {
    // Check for null/undefined first
    if js.is_null() || js.is_undefined() {
        return Err("Cannot convert null/undefined to Value".to_string());
    }

    // Check for boolean
    if let Some(b) = js.as_bool() {
        return Ok(Value::VBoolean(b));
    }

    // Check for string
    if let Some(s) = js.as_string() {
        return Ok(Value::VString(s));
    }

    // Check for number (try integer first, then decimal)
    if let Some(n) = js.as_f64() {
        // Check if it's a safe integer
        if n.fract() == 0.0 && n >= i64::MIN as f64 && n <= i64::MAX as f64 {
            return Ok(Value::VInteger(n as i64));
        }
        return Ok(Value::VDecimal(n));
    }

    // Check for array
    if js_sys::Array::is_array(js) {
        let arr: &js_sys::Array = js.unchecked_ref();
        let mut values = Vec::with_capacity(arr.length() as usize);
        for i in 0..arr.length() {
            let item = arr.get(i);
            values.push(js_to_value(&item)?);
        }
        return Ok(Value::VArray(values));
    }

    // Check for object (could be map, range, measurement, or tagged string)
    if js.is_object() {
        let obj: &js_sys::Object = js.unchecked_ref();

        // Check for range: { lower?: number, upper?: number }
        let has_lower = js_sys::Reflect::has(obj, &JsValue::from_str("lower")).unwrap_or(false);
        let has_upper = js_sys::Reflect::has(obj, &JsValue::from_str("upper")).unwrap_or(false);
        if has_lower || has_upper {
            let lower = js_sys::Reflect::get(obj, &JsValue::from_str("lower"))
                .ok()
                .and_then(|v| js_to_option(&v, js_to_f64));
            let upper = js_sys::Reflect::get(obj, &JsValue::from_str("upper"))
                .ok()
                .and_then(|v| js_to_option(&v, js_to_f64));

            // Only treat as range if at least one bound is a number
            if lower.is_some() || upper.is_some() {
                return Ok(Value::VRange(RangeValue { lower, upper }));
            }
        }

        // Check for measurement: { value: number, unit: string }
        let has_value = js_sys::Reflect::has(obj, &JsValue::from_str("value")).unwrap_or(false);
        let has_unit = js_sys::Reflect::has(obj, &JsValue::from_str("unit")).unwrap_or(false);
        if has_value && has_unit {
            let value = js_sys::Reflect::get(obj, &JsValue::from_str("value"))
                .ok()
                .and_then(|v| js_to_f64(&v));
            let unit = js_sys::Reflect::get(obj, &JsValue::from_str("unit"))
                .ok()
                .and_then(|v| js_to_string(&v));

            if let (Some(v), Some(u)) = (value, unit) {
                return Ok(Value::VMeasurement { unit: u, value: v });
            }
        }

        // Check for tagged string: { tag: string, content: string }
        let has_tag = js_sys::Reflect::has(obj, &JsValue::from_str("tag")).unwrap_or(false);
        let has_content = js_sys::Reflect::has(obj, &JsValue::from_str("content")).unwrap_or(false);
        if has_tag && has_content {
            let tag = js_sys::Reflect::get(obj, &JsValue::from_str("tag"))
                .ok()
                .and_then(|v| js_to_string(&v));
            let content = js_sys::Reflect::get(obj, &JsValue::from_str("content"))
                .ok()
                .and_then(|v| js_to_string(&v));

            if let (Some(t), Some(c)) = (tag, content) {
                return Ok(Value::VTaggedString { tag: t, content: c });
            }
        }

        // Check for symbol: { _type: 'symbol', value: string }
        let type_field = js_sys::Reflect::get(obj, &JsValue::from_str("_type"))
            .ok()
            .and_then(|v| js_to_string(&v));
        if type_field.as_deref() == Some("symbol") {
            let symbol_value = js_sys::Reflect::get(obj, &JsValue::from_str("value"))
                .ok()
                .and_then(|v| js_to_string(&v));
            if let Some(s) = symbol_value {
                return Ok(Value::VSymbol(s));
            }
        }

        // Default: treat as VMap
        let map = js_object_to_value_map(js)?;
        return Ok(Value::VMap(map));
    }

    Err(format!("Cannot convert JS value to Value: {:?}", js))
}

/// Convert a Rust Value to a JsValue.
///
/// Handles all Value variants, converting to appropriate JS types.
pub fn value_to_js(value: &Value) -> JsValue {
    match value {
        Value::VString(s) => JsValue::from_str(s),
        Value::VInteger(i) => JsValue::from_f64(*i as f64),
        Value::VDecimal(d) => JsValue::from_f64(*d),
        Value::VBoolean(b) => JsValue::from_bool(*b),
        Value::VSymbol(s) => {
            // Return as { _type: 'symbol', value: string }
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(
                &obj,
                &JsValue::from_str("_type"),
                &JsValue::from_str("symbol"),
            )
            .expect("set _type");
            js_sys::Reflect::set(&obj, &JsValue::from_str("value"), &JsValue::from_str(s))
                .expect("set value");
            obj.into()
        }
        Value::VTaggedString { tag, content } => {
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(&obj, &JsValue::from_str("tag"), &JsValue::from_str(tag))
                .expect("set tag");
            js_sys::Reflect::set(
                &obj,
                &JsValue::from_str("content"),
                &JsValue::from_str(content),
            )
            .expect("set content");
            obj.into()
        }
        Value::VArray(arr) => {
            let js_arr = js_sys::Array::new();
            for item in arr {
                js_arr.push(&value_to_js(item));
            }
            js_arr.into()
        }
        Value::VMap(map) => {
            let obj = js_sys::Object::new();
            for (key, val) in map {
                js_sys::Reflect::set(&obj, &JsValue::from_str(key), &value_to_js(val))
                    .expect("set map entry");
            }
            obj.into()
        }
        Value::VRange(range) => {
            let obj = js_sys::Object::new();
            if let Some(lower) = range.lower {
                js_sys::Reflect::set(&obj, &JsValue::from_str("lower"), &JsValue::from_f64(lower))
                    .expect("set lower");
            }
            if let Some(upper) = range.upper {
                js_sys::Reflect::set(&obj, &JsValue::from_str("upper"), &JsValue::from_f64(upper))
                    .expect("set upper");
            }
            obj.into()
        }
        Value::VMeasurement { unit, value } => {
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(&obj, &JsValue::from_str("unit"), &JsValue::from_str(unit))
                .expect("set unit");
            js_sys::Reflect::set(
                &obj,
                &JsValue::from_str("value"),
                &JsValue::from_f64(*value),
            )
            .expect("set value");
            obj.into()
        }
    }
}

/// Convert a JS array to a Vec<String> (for labels).
pub fn js_array_to_strings(arr: &JsValue) -> Result<Vec<String>, String> {
    if !js_sys::Array::is_array(arr) {
        return Err("Expected an array".to_string());
    }

    let arr: &js_sys::Array = arr.unchecked_ref();
    let mut result = Vec::with_capacity(arr.length() as usize);

    for i in 0..arr.length() {
        let item = arr.get(i);
        let s = item
            .as_string()
            .ok_or_else(|| format!("Array item at index {} is not a string", i))?;
        result.push(s);
    }

    Ok(result)
}

/// Convert a Vec<String> to a JS array.
pub fn strings_to_js_array(strings: &[String]) -> JsValue {
    let arr = js_sys::Array::new();
    for s in strings {
        arr.push(&JsValue::from_str(s));
    }
    arr.into()
}

/// Convert a HashMap<String, Value> to a JS object.
pub fn value_map_to_js(map: &HashMap<String, Value>) -> JsValue {
    let obj = js_sys::Object::new();
    for (key, val) in map {
        js_sys::Reflect::set(&obj, &JsValue::from_str(key), &value_to_js(val))
            .expect("set property");
    }
    obj.into()
}

// ============================================================================
// 3. Value Factories (T009 - Phase 3)
// ============================================================================
//
// These factory methods provide JavaScript-friendly constructors for all Value variants.
// They accept JsValue arguments and convert them to the appropriate Rust Value types.
//
// Exported to JavaScript as `Value` (without the Factory suffix).

#[wasm_bindgen(js_name = Value)]
pub struct ValueFactory;

#[wasm_bindgen]
impl ValueFactory {
    /// Create a VString value.
    ///
    /// # Arguments
    /// * `s` - A JavaScript string
    ///
    /// # Returns
    /// A JsValue representing a Value::VString
    #[wasm_bindgen(js_name = string)]
    pub fn string(s: &str) -> JsValue {
        value_to_js(&Value::VString(s.to_string()))
    }

    /// Create a VInteger value.
    ///
    /// # Arguments
    /// * `n` - A JavaScript number (will be converted to i64)
    ///
    /// # Returns
    /// A JsValue representing a Value::VInteger
    #[wasm_bindgen(js_name = int)]
    pub fn int(n: f64) -> JsValue {
        value_to_js(&Value::VInteger(n as i64))
    }

    /// Create a VDecimal value.
    ///
    /// # Arguments
    /// * `n` - A JavaScript number (f64)
    ///
    /// # Returns
    /// A JsValue representing a Value::VDecimal
    #[wasm_bindgen(js_name = decimal)]
    pub fn decimal(n: f64) -> JsValue {
        value_to_js(&Value::VDecimal(n))
    }

    /// Create a VBoolean value.
    ///
    /// # Arguments
    /// * `b` - A JavaScript boolean
    ///
    /// # Returns
    /// A JsValue representing a Value::VBoolean
    #[wasm_bindgen(js_name = boolean)]
    pub fn boolean(b: bool) -> JsValue {
        value_to_js(&Value::VBoolean(b))
    }

    /// Create a VSymbol value.
    ///
    /// # Arguments
    /// * `s` - A JavaScript string representing the symbol
    ///
    /// # Returns
    /// A JsValue representing a Value::VSymbol
    #[wasm_bindgen(js_name = symbol)]
    pub fn symbol(s: &str) -> JsValue {
        value_to_js(&Value::VSymbol(s.to_string()))
    }

    /// Create a VArray value.
    ///
    /// # Arguments
    /// * `arr` - A JavaScript array of values
    ///
    /// # Returns
    /// A JsValue representing a Value::VArray, or throws an error
    #[wasm_bindgen(js_name = array)]
    pub fn array(arr: &JsValue) -> Result<JsValue, JsValue> {
        if !js_sys::Array::is_array(arr) {
            return Err(JsValue::from_str("Expected an array"));
        }

        let js_arr: &js_sys::Array = arr.unchecked_ref();
        let mut values = Vec::with_capacity(js_arr.length() as usize);

        for i in 0..js_arr.length() {
            let item = js_arr.get(i);
            let val = js_to_value(&item).map_err(|e| JsValue::from_str(&e))?;
            values.push(val);
        }

        Ok(value_to_js(&Value::VArray(values)))
    }

    /// Create a VMap value.
    ///
    /// # Arguments
    /// * `obj` - A JavaScript object with string keys and value values
    ///
    /// # Returns
    /// A JsValue representing a Value::VMap, or throws an error
    #[wasm_bindgen(js_name = map)]
    pub fn map(obj: &JsValue) -> Result<JsValue, JsValue> {
        let map = js_object_to_value_map(obj).map_err(|e| JsValue::from_str(&e))?;
        Ok(value_to_js(&Value::VMap(map)))
    }

    /// Create a VRange value.
    ///
    /// # Arguments
    /// * `lower` - Optional lower bound (null/undefined for unbounded)
    /// * `upper` - Optional upper bound (null/undefined for unbounded)
    ///
    /// # Returns
    /// A JsValue representing a Value::VRange
    #[wasm_bindgen(js_name = range)]
    pub fn range(lower: JsValue, upper: JsValue) -> JsValue {
        let lower_val = js_to_option(&lower, js_to_f64);
        let upper_val = js_to_option(&upper, js_to_f64);
        value_to_js(&Value::VRange(RangeValue {
            lower: lower_val,
            upper: upper_val,
        }))
    }

    /// Create a VMeasurement value.
    ///
    /// # Arguments
    /// * `value` - The numeric value
    /// * `unit` - The unit string (e.g., "kg", "m", "s")
    ///
    /// # Returns
    /// A JsValue representing a Value::VMeasurement
    #[wasm_bindgen(js_name = measurement)]
    pub fn measurement(value: f64, unit: &str) -> JsValue {
        value_to_js(&Value::VMeasurement {
            unit: unit.to_string(),
            value,
        })
    }
}

// ============================================================================
// 4. Subject Bindings (T010 - Phase 3)
// ============================================================================
//
// WASM bindings for Subject constructors and accessors.
// JavaScript/TypeScript developers can create and inspect Subject instances.

/// WASM binding for Subject.
///
/// Provides constructors and accessors for Subject instances from JavaScript/TypeScript.
///
/// Exported to JavaScript as `WasmSubject`.
#[wasm_bindgen]
pub struct WasmSubject {
    inner: Subject,
}

#[wasm_bindgen]
impl WasmSubject {
    /// Create a new Subject.
    ///
    /// # Arguments
    /// * `identity` - A string representing the subject's identity symbol
    /// * `labels` - A JavaScript array of label strings (can be empty)
    /// * `properties` - A JavaScript object with string keys and Value values (can be empty object)
    ///
    /// # Returns
    /// A new Subject instance, or throws an error
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const subject = Subject.new(
    ///     "alice",
    ///     ["Person", "User"],
    ///     { name: Value.string("Alice"), age: Value.int(30) }
    /// );
    /// ```
    #[wasm_bindgen(constructor)]
    pub fn new(
        identity: &str,
        labels: &JsValue,
        properties: &JsValue,
    ) -> Result<WasmSubject, JsValue> {
        // Parse labels
        let labels_vec = js_array_to_strings(labels).map_err(|e| JsValue::from_str(&e))?;
        let labels_set: std::collections::HashSet<String> = labels_vec.into_iter().collect();

        // Parse properties
        let props = js_object_to_value_map(properties).map_err(|e| JsValue::from_str(&e))?;

        Ok(WasmSubject {
            inner: Subject {
                identity: Symbol(identity.to_string()),
                labels: labels_set,
                properties: props,
            },
        })
    }

    /// Get the identity symbol as a string.
    ///
    /// # Returns
    /// The identity symbol string
    #[wasm_bindgen(getter)]
    pub fn identity(&self) -> String {
        self.inner.identity.0.clone()
    }

    /// Get the labels as a JavaScript Set of strings.
    ///
    /// # Returns
    /// A JavaScript Set containing all label strings
    #[wasm_bindgen(getter)]
    pub fn labels(&self) -> js_sys::Set {
        let set = js_sys::Set::new(&JsValue::undefined());
        for label in &self.inner.labels {
            set.add(&JsValue::from_str(label));
        }
        set
    }

    /// Get the properties as a JavaScript object.
    ///
    /// # Returns
    /// A JavaScript object mapping property keys to Value JsValues
    #[wasm_bindgen(getter)]
    pub fn properties(&self) -> JsValue {
        value_map_to_js(&self.inner.properties)
    }
}

// Conversion helpers for WasmSubject ↔ JsValue
impl WasmSubject {
    /// Convert this WasmSubject to a JsValue for use in patterns.
    ///
    /// This allows WasmSubject instances to be stored in Pattern<JsValue>.
    pub fn to_js_value(&self) -> JsValue {
        let obj = js_sys::Object::new();

        // Set identity
        js_sys::Reflect::set(
            &obj,
            &JsValue::from_str("identity"),
            &JsValue::from_str(&self.inner.identity.0),
        )
        .expect("set identity");

        // Set labels as Set
        let labels_set = js_sys::Set::new(&JsValue::undefined());
        for label in &self.inner.labels {
            labels_set.add(&JsValue::from_str(label));
        }
        js_sys::Reflect::set(&obj, &JsValue::from_str("labels"), &labels_set).expect("set labels");

        // Set properties
        js_sys::Reflect::set(
            &obj,
            &JsValue::from_str("properties"),
            &value_map_to_js(&self.inner.properties),
        )
        .expect("set properties");

        // Add a type marker so we can identify Subjects
        js_sys::Reflect::set(
            &obj,
            &JsValue::from_str("_type"),
            &JsValue::from_str("Subject"),
        )
        .expect("set _type");

        obj.into()
    }

    /// Try to convert a JsValue back to a WasmSubject.
    ///
    /// Handles two representations:
    /// 1. Plain JS objects with `_type: "Subject"` (from `to_js_value()`)
    /// 2. WasmSubject WASM instances with `identity`, `labels`, `properties` getters
    ///
    /// Returns None if the JsValue is not a valid Subject representation.
    pub fn from_js_value(value: &JsValue) -> Option<Self> {
        if !value.is_object() {
            return None;
        }

        let obj: &js_sys::Object = value.unchecked_ref();

        // Check for type marker (plain JS object from to_js_value())
        let type_marker = js_sys::Reflect::get(obj, &JsValue::from_str("_type")).ok();
        let is_plain_subject = type_marker
            .as_ref()
            .and_then(|v| v.as_string())
            .map(|s| s == "Subject")
            .unwrap_or(false);

        // Check if it's a WasmSubject WASM instance (has __wbg_ptr and identity getter)
        let has_wbg_ptr = js_sys::Reflect::get(obj, &JsValue::from_str("__wbg_ptr"))
            .ok()
            .map(|v| !v.is_undefined() && !v.is_null())
            .unwrap_or(false);

        if !is_plain_subject && !has_wbg_ptr {
            return None;
        }

        // Extract identity (works for both plain objects and WASM instances)
        let identity_js = js_sys::Reflect::get(obj, &JsValue::from_str("identity")).ok()?;
        let identity = identity_js.as_string()?;

        // Extract labels (works for both plain objects and WASM instances)
        // Labels may be a JS Array or a JS Set
        let labels_js = js_sys::Reflect::get(obj, &JsValue::from_str("labels")).ok()?;
        let labels_set: std::collections::HashSet<String> = if js_sys::Array::is_array(&labels_js) {
            js_array_to_strings(&labels_js).ok()?.into_iter().collect()
        } else {
            // Try as JS Set: iterate via forEach
            let set: &js_sys::Set = labels_js.unchecked_ref();
            let mut result = std::collections::HashSet::new();
            set.for_each(&mut |v, _, _| {
                if let Some(s) = v.as_string() {
                    result.insert(s);
                }
            });
            result
        };

        // Extract properties (works for both plain objects and WASM instances)
        let properties_js = js_sys::Reflect::get(obj, &JsValue::from_str("properties")).ok()?;
        let properties = js_object_to_value_map(&properties_js).ok()?;

        Some(WasmSubject {
            inner: Subject {
                identity: Symbol(identity),
                labels: labels_set,
                properties,
            },
        })
    }

    /// Create a WasmSubject from a Rust Subject.
    ///
    /// This allows other crates (like pattern-wasm) to create WasmSubject instances
    /// from native Rust Subject types, enabling proper type consistency when
    /// converting between Rust Pattern<Subject> and JS Pattern<JsValue>.
    ///
    /// # Arguments
    /// * `subject` - A Rust Subject instance
    ///
    /// # Returns
    /// A new WasmSubject wrapping the given Subject
    pub fn from_subject(subject: Subject) -> Self {
        WasmSubject { inner: subject }
    }

    /// Consume this WasmSubject and return the inner Rust Subject.
    ///
    /// This allows other crates to extract the native Rust Subject from a WasmSubject,
    /// enabling conversion from JS Pattern<JsValue> back to Rust Pattern<Subject>.
    ///
    /// # Returns
    /// The inner Subject
    pub fn into_subject(self) -> Subject {
        self.inner
    }

    /// Get a reference to the inner Rust Subject.
    ///
    /// This allows inspection of the Subject without consuming the WasmSubject.
    ///
    /// # Returns
    /// A reference to the inner Subject
    pub fn as_subject(&self) -> &Subject {
        &self.inner
    }
}

// ============================================================================
// 5. Pattern Bindings (T007, T008, T011 - Phase 3)
// ============================================================================
//
// WASM bindings for Pattern constructors, accessors, and operations.
// JavaScript/TypeScript developers can create and manipulate Pattern<V> instances.
//
// CRITICAL: Pattern<V> is generic over ANY value type V. The Python binding stores
// PyAny (any Python object). The WASM binding MUST mirror this by storing JsValue
// (any JavaScript value). This allows patterns to hold primitives, objects, Subjects,
// or even other Patterns (nesting).

/// WASM binding for Pattern<JsValue>.
///
/// Provides constructors and accessors for Pattern instances from JavaScript/TypeScript.
/// This binding wraps Pattern<JsValue>, allowing patterns to hold any JavaScript value:
/// primitives, objects, Subject instances, or even other Pattern instances (nesting).
///
/// This design matches the Python binding which stores PyAny (any Python object).
///
/// Exported to JavaScript as `WasmPattern`.
#[wasm_bindgen]
#[derive(Clone)]
pub struct WasmPattern {
    inner: Pattern<JsValue>,
}

#[wasm_bindgen]
impl WasmPattern {
    // ========================================================================
    // Constructors (T007)
    // ========================================================================

    /// Create an atomic pattern from any JavaScript value.
    ///
    /// Accepts any JavaScript value: primitives (string, number, boolean),
    /// objects, WasmSubject instances, or even other WasmPattern instances (for nesting).
    ///
    /// This matches the Python binding which accepts PyAny (any Python object).
    ///
    /// # Arguments
    /// * `value` - Any JavaScript value
    ///
    /// # Returns
    /// A new atomic WasmPattern containing that value
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// // Primitives
    /// const p1 = Pattern.point("hello");
    /// const p2 = Pattern.point(42);
    /// const p3 = Pattern.point(true);
    ///
    /// // Subject
    /// const subject = new Subject("alice", [], {});
    /// const p4 = Pattern.point(subject);
    ///
    /// // Nesting - Pattern<Pattern<V>>
    /// const p5 = Pattern.point(p1);
    /// ```
    #[wasm_bindgen(js_name = point)]
    pub fn point(value: JsValue) -> WasmPattern {
        WasmPattern {
            inner: Pattern::point(value),
        }
    }

    /// Alias for point(). Create an atomic pattern from any JavaScript value.
    ///
    /// This is identical to `point()` - just a different name following functional
    /// programming convention where `of` is used to "lift" a value into a functor.
    ///
    /// # Arguments
    /// * `value` - Any JavaScript value
    ///
    /// # Returns
    /// A new atomic WasmPattern containing that value
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p1 = Pattern.of("hello");  // Same as Pattern.point("hello")
    /// const p2 = Pattern.of(42);       // Same as Pattern.point(42)
    /// ```
    #[wasm_bindgen(js_name = of)]
    pub fn of(value: JsValue) -> WasmPattern {
        Self::point(value) // Just delegate to point - identical behavior
    }

    /// Create a pattern with a value and no elements (builder pattern).
    ///
    /// Due to wasm-bindgen limitations with custom types in arrays, this creates
    /// an empty pattern. Use `addElement()` to add children.
    ///
    /// # Arguments
    /// * `value` - Any JavaScript value
    ///
    /// # Returns
    /// A new WasmPattern with the value and no elements
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("parent");
    /// pattern.addElement(Pattern.of("child1"));
    /// pattern.addElement(Pattern.of("child2"));
    /// ```
    #[wasm_bindgen(js_name = pattern)]
    pub fn pattern(value: JsValue) -> WasmPattern {
        WasmPattern {
            inner: Pattern::pattern(value, vec![]),
        }
    }

    /// Add a child pattern element to this pattern.
    ///
    /// This method mutates the pattern by adding a new child element.
    /// Takes a reference so the same JS pattern can be added to multiple parents;
    /// the inner pattern is cloned. Taking ownership would be inconsistent with
    /// typical JS usage where the same element reference is reused.
    ///
    /// # Arguments
    /// * `element` - A WasmPattern to add as a child
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const parent = Pattern.pattern(Subject.new("parent", [], {}));
    /// parent.addElement(Pattern.of("child1"));
    /// parent.addElement(Pattern.of("child2"));
    /// ```
    #[wasm_bindgen(js_name = addElement)]
    pub fn add_element(&mut self, element: &WasmPattern) {
        // Since Pattern is immutable, we need to reconstruct it
        let mut elements = self.inner.elements().to_vec();
        elements.push(element.inner.clone());
        self.inner = Pattern::pattern(self.inner.value().clone(), elements);
    }

    /// Create an array of atomic patterns from an array of values.
    ///
    /// Each value in the input array is lifted to an atomic pattern using `point()`.
    /// Returns a JavaScript array of WasmPattern instances, not a single nested pattern.
    ///
    /// This matches the Python binding's `fromValues` behavior.
    ///
    /// # Arguments
    /// * `values` - A JavaScript array of any values
    ///
    /// # Returns
    /// A JavaScript array of WasmPattern instances (one atomic pattern per value)
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const patterns = Pattern.fromValues([1, 2, 3]);
    /// // Returns [Pattern.point(1), Pattern.point(2), Pattern.point(3)]
    /// console.log(patterns.length); // 3
    /// console.log(patterns[0].value); // 1
    /// ```
    #[wasm_bindgen(js_name = fromValues)]
    pub fn from_values(values: &JsValue) -> Result<js_sys::Array, JsValue> {
        if !js_sys::Array::is_array(values) {
            return Err(JsValue::from_str("Values must be an array"));
        }

        let arr: &js_sys::Array = values.unchecked_ref();
        let result = js_sys::Array::new();

        for i in 0..arr.length() {
            let item = arr.get(i);
            // Create atomic pattern for each value
            let pattern = WasmPattern::point(item);
            // Convert WasmPattern to JsValue and push to result array
            result.push(&JsValue::from(pattern));
        }

        Ok(result)
    }

    // ========================================================================
    // Accessors (T008)
    // ========================================================================

    /// Get the value at the root of this pattern.
    ///
    /// Returns the JavaScript value stored in this pattern (can be any type).
    ///
    /// # Returns
    /// The value as a JsValue
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p1 = Pattern.point("hello");
    /// console.log(p1.value); // "hello"
    ///
    /// const p2 = Pattern.point(42);
    /// console.log(p2.value); // 42
    /// ```
    #[wasm_bindgen(getter)]
    pub fn value(&self) -> JsValue {
        self.inner.value().clone()
    }

    /// Get the identity of this pattern's value if it is a Subject.
    ///
    /// Returns the Subject's identity string, or undefined if the value is not a Subject.
    ///
    /// # Returns
    /// The identity string, or undefined
    #[wasm_bindgen(getter)]
    pub fn identity(&self) -> Option<String> {
        WasmSubject::from_js_value(self.inner.value()).map(|s| s.inner.identity.0.clone())
    }

    /// Get the nested elements (sub-patterns) of this pattern as an array.
    ///
    /// Returns a JavaScript array of WasmPattern instances.
    ///
    /// # Returns
    /// A JavaScript array of WasmPattern instances
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("parent");
    /// pattern.addElement(Pattern.of("child1"));
    /// pattern.addElement(Pattern.of("child2"));
    /// console.log(pattern.elements.length); // 2
    /// console.log(pattern.elements[0].value); // "child1"
    /// ```
    #[wasm_bindgen(getter)]
    pub fn elements(&self) -> js_sys::Array {
        let result = js_sys::Array::new();
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            result.push(&JsValue::from(wasm_elem));
        }
        result
    }

    /// Get a child element by index.
    ///
    /// # Arguments
    /// * `index` - The index of the element to retrieve (0-based)
    ///
    /// # Returns
    /// A WasmPattern if the index is valid, or undefined
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("parent");
    /// pattern.addElement(Pattern.of("child"));
    /// const child = pattern.getElement(0);
    /// ```
    #[wasm_bindgen(js_name = getElement)]
    pub fn get_element(&self, index: usize) -> Option<WasmPattern> {
        self.inner.elements().get(index).map(|elem| WasmPattern {
            inner: elem.clone(),
        })
    }

    /// Get the number of direct child elements.
    ///
    /// # Returns
    /// The number of elements (0 for atomic patterns)
    #[wasm_bindgen(getter)]
    pub fn length(&self) -> usize {
        self.inner.length()
    }

    /// Check if this pattern is atomic (has no children).
    ///
    /// # Returns
    /// true if the pattern has no elements, false otherwise
    #[wasm_bindgen(js_name = isAtomic)]
    pub fn is_atomic(&self) -> bool {
        self.inner.is_atomic()
    }

    // ========================================================================
    // Inspection Methods (T012 - Phase 4)
    // ========================================================================

    /// Get the total number of nodes in the pattern structure (including all nested patterns).
    ///
    /// # Returns
    /// The total number of nodes (root + all nested nodes)
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const atomic = Pattern.point("atom");
    /// console.log(atomic.size()); // 1
    ///
    /// const pattern = Pattern.pattern("root");
    /// pattern.addElement(Pattern.of("child1"));
    /// pattern.addElement(Pattern.of("child2"));
    /// console.log(pattern.size()); // 3 (root + 2 children)
    /// ```
    #[wasm_bindgen(js_name = size)]
    pub fn size(&self) -> usize {
        self.inner.size()
    }

    /// Get the maximum nesting depth of the pattern structure.
    ///
    /// # Returns
    /// The maximum nesting depth (atomic patterns have depth 0)
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const atomic = Pattern.point("hello");
    /// console.log(atomic.depth()); // 0
    ///
    /// const nested = Pattern.pattern("parent");
    /// const child = Pattern.pattern("child");
    /// child.addElement(Pattern.of("grandchild"));
    /// nested.addElement(child);
    /// console.log(nested.depth()); // 2
    /// ```
    #[wasm_bindgen(js_name = depth)]
    pub fn depth(&self) -> usize {
        self.inner.depth()
    }

    /// Extract all values from the pattern as a flat array (pre-order traversal).
    ///
    /// # Returns
    /// A JavaScript array containing all values in pre-order (root first, then elements)
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("root");
    /// pattern.addElement(Pattern.of("child1"));
    /// pattern.addElement(Pattern.of("child2"));
    /// const values = pattern.values();
    /// // Returns ["root", "child1", "child2"]
    /// ```
    #[wasm_bindgen(js_name = values)]
    pub fn values(&self) -> js_sys::Array {
        let mut result = js_sys::Array::new();
        self.values_recursive(&mut result);
        result
    }

    /// Helper for values() - recursively collect values in pre-order.
    fn values_recursive(&self, result: &mut js_sys::Array) {
        result.push(&self.inner.value().clone());
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            wasm_elem.values_recursive(result);
        }
    }

    // ========================================================================
    // Query Methods (T013 - Phase 4)
    // ========================================================================

    /// Check if at least one value in the pattern satisfies the given predicate.
    ///
    /// Traverses in pre-order and short-circuits on first match.
    ///
    /// # Arguments
    /// * `predicate` - A JavaScript function that takes a value and returns boolean
    ///
    /// # Returns
    /// true if at least one value satisfies the predicate, false otherwise
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("hello");
    /// pattern.addElement(Pattern.of("world"));
    /// const hasWorld = pattern.anyValue(v => v === "world"); // true
    /// ```
    #[wasm_bindgen(js_name = anyValue)]
    pub fn any_value(&self, predicate: &js_sys::Function) -> Result<bool, JsValue> {
        self.any_value_recursive(predicate)
    }

    /// Helper for anyValue() - recursive implementation with short-circuit.
    fn any_value_recursive(&self, predicate: &js_sys::Function) -> Result<bool, JsValue> {
        // Check current value
        let this = JsValue::null();
        let result = predicate
            .call1(&this, &self.inner.value().clone())
            .map_err(|e| JsValue::from_str(&format!("Predicate error: {:?}", e)))?;

        if let Some(true) = result.as_bool() {
            return Ok(true);
        }

        // Check elements recursively
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            if wasm_elem.any_value_recursive(predicate)? {
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// Check if all values in the pattern satisfy the given predicate.
    ///
    /// Traverses in pre-order and short-circuits on first failure.
    ///
    /// # Arguments
    /// * `predicate` - A JavaScript function that takes a value and returns boolean
    ///
    /// # Returns
    /// true if all values satisfy the predicate, false otherwise
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("hello");
    /// pattern.addElement(Pattern.of("world"));
    /// const allStrings = pattern.allValues(v => typeof v === "string"); // true
    /// ```
    #[wasm_bindgen(js_name = allValues)]
    pub fn all_values(&self, predicate: &js_sys::Function) -> Result<bool, JsValue> {
        self.all_values_recursive(predicate)
    }

    /// Helper for allValues() - recursive implementation with short-circuit.
    fn all_values_recursive(&self, predicate: &js_sys::Function) -> Result<bool, JsValue> {
        // Check current value
        let this = JsValue::null();
        let result = predicate
            .call1(&this, &self.inner.value().clone())
            .map_err(|e| JsValue::from_str(&format!("Predicate error: {:?}", e)))?;

        if let Some(false) = result.as_bool() {
            return Ok(false);
        }

        // Check elements recursively
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            if !wasm_elem.all_values_recursive(predicate)? {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Filter subpatterns that satisfy the given pattern predicate.
    ///
    /// Traverses in pre-order and collects all matching patterns.
    ///
    /// # Arguments
    /// * `predicate` - A JavaScript function that takes a Pattern and returns boolean
    ///
    /// # Returns
    /// A JavaScript array of Pattern instances that satisfy the predicate
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("root");
    /// pattern.addElement(Pattern.of("leaf1"));
    /// pattern.addElement(Pattern.of("leaf2"));
    /// const leaves = pattern.filter(p => p.isAtomic()); // Returns [leaf1, leaf2]
    /// ```
    #[wasm_bindgen(js_name = filter)]
    pub fn filter(&self, predicate: &js_sys::Function) -> Result<js_sys::Array, JsValue> {
        let result = js_sys::Array::new();
        self.filter_recursive(predicate, &result)?;
        Ok(result)
    }

    /// Helper for filter() - recursive implementation.
    fn filter_recursive(
        &self,
        predicate: &js_sys::Function,
        result: &js_sys::Array,
    ) -> Result<(), JsValue> {
        // Check current pattern
        let this = JsValue::null();
        let wasm_pattern = WasmPattern {
            inner: self.inner.clone(),
        };
        let matches = predicate
            .call1(&this, &JsValue::from(wasm_pattern.clone()))
            .map_err(|e| JsValue::from_str(&format!("Predicate error: {:?}", e)))?;

        if let Some(true) = matches.as_bool() {
            result.push(&JsValue::from(wasm_pattern));
        }

        // Recursively filter elements
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            wasm_elem.filter_recursive(predicate, result)?;
        }

        Ok(())
    }

    /// Find the first subpattern that satisfies the given predicate.
    ///
    /// Performs depth-first pre-order traversal and short-circuits on first match.
    ///
    /// # Arguments
    /// * `predicate` - A JavaScript function that takes a Pattern and returns boolean
    ///
    /// # Returns
    /// The first matching Pattern, or null if no match found
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("root");
    /// pattern.addElement(Pattern.of("target"));
    /// const found = pattern.findFirst(p => p.value === "target");
    /// ```
    #[wasm_bindgen(js_name = findFirst)]
    pub fn find_first(&self, predicate: &js_sys::Function) -> Result<JsValue, JsValue> {
        self.find_first_recursive(predicate)
    }

    /// Helper for findFirst() - recursive implementation with short-circuit.
    fn find_first_recursive(&self, predicate: &js_sys::Function) -> Result<JsValue, JsValue> {
        // Check current pattern
        let this = JsValue::null();
        let wasm_pattern = WasmPattern {
            inner: self.inner.clone(),
        };
        let matches = predicate
            .call1(&this, &JsValue::from(wasm_pattern.clone()))
            .map_err(|e| JsValue::from_str(&format!("Predicate error: {:?}", e)))?;

        if let Some(true) = matches.as_bool() {
            return Ok(JsValue::from(wasm_pattern));
        }

        // Check elements recursively
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            let found = wasm_elem.find_first_recursive(predicate)?;
            if !found.is_null() {
                return Ok(found);
            }
        }

        Ok(JsValue::null())
    }

    /// Check if two patterns have identical structure (same values and same tree structure).
    ///
    /// # Arguments
    /// * `other` - Another Pattern to compare with
    ///
    /// # Returns
    /// true if the patterns match, false otherwise
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p1 = Pattern.pattern("root");
    /// p1.addElement(Pattern.of("child"));
    /// const p2 = Pattern.pattern("root");
    /// p2.addElement(Pattern.of("child"));
    /// console.log(p1.matches(p2)); // true
    /// ```
    #[wasm_bindgen(js_name = matches)]
    pub fn matches(&self, other: &WasmPattern) -> bool {
        self.matches_recursive(&other.inner)
    }

    /// Helper for matches() - recursive implementation.
    fn matches_recursive(&self, other: &Pattern<JsValue>) -> bool {
        // Compare values - use JavaScript equality
        let self_val = self.inner.value();
        let other_val = other.value();

        // Try to compare as strings if both are strings
        if let (Some(s1), Some(s2)) = (self_val.as_string(), other_val.as_string()) {
            if s1 != s2 {
                return false;
            }
        } else if let (Some(n1), Some(n2)) = (self_val.as_f64(), other_val.as_f64()) {
            // Compare as numbers
            if n1 != n2 {
                return false;
            }
        } else if let (Some(b1), Some(b2)) = (self_val.as_bool(), other_val.as_bool()) {
            // Compare as booleans
            if b1 != b2 {
                return false;
            }
        } else {
            // For complex types, use JavaScript equality
            let eq = js_sys::Reflect::get(&js_sys::Object::new(), &JsValue::from_str("equals"))
                .ok()
                .and_then(|_| {
                    // Fallback: convert to JSON strings and compare
                    let s1 = js_sys::JSON::stringify(self_val).ok()?;
                    let s2 = js_sys::JSON::stringify(other_val).ok()?;
                    Some(s1.as_string()? == s2.as_string()?)
                })
                .unwrap_or(false);

            if !eq {
                return false;
            }
        }

        // Compare element count
        if self.inner.elements().len() != other.elements().len() {
            return false;
        }

        // Compare elements recursively
        for (self_elem, other_elem) in self.inner.elements().iter().zip(other.elements().iter()) {
            let wasm_self = WasmPattern {
                inner: self_elem.clone(),
            };
            if !wasm_self.matches_recursive(other_elem) {
                return false;
            }
        }

        true
    }

    /// Check if this pattern contains another pattern as a subpattern.
    ///
    /// # Arguments
    /// * `subpattern` - The pattern to search for
    ///
    /// # Returns
    /// true if this pattern contains the subpattern, false otherwise
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("root");
    /// const child = Pattern.of("child");
    /// pattern.addElement(child);
    /// console.log(pattern.contains(Pattern.of("child"))); // true
    /// ```
    #[wasm_bindgen(js_name = contains)]
    pub fn contains(&self, subpattern: &WasmPattern) -> bool {
        self.contains_recursive(&subpattern.inner)
    }

    /// Helper for contains() - recursive implementation.
    fn contains_recursive(&self, subpattern: &Pattern<JsValue>) -> bool {
        // Check if current pattern matches
        if self.matches_recursive(subpattern) {
            return true;
        }

        // Check elements recursively
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            if wasm_elem.contains_recursive(subpattern) {
                return true;
            }
        }

        false
    }

    // ========================================================================
    // Transformation Methods (T014 - Phase 4)
    // ========================================================================

    /// Transform all values in the pattern using a mapping function.
    ///
    /// Creates a new pattern with the same structure but with values transformed by the function.
    /// The function is applied to each value in the pattern.
    ///
    /// # Arguments
    /// * `f` - A JavaScript function that takes a value and returns a new value
    ///
    /// # Returns
    /// A new Pattern with transformed values
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("hello");
    /// pattern.addElement(Pattern.of("world"));
    /// const upper = pattern.map(v => typeof v === 'string' ? v.toUpperCase() : v);
    /// // Returns Pattern with values ["HELLO", "WORLD"]
    /// ```
    #[wasm_bindgen(js_name = map)]
    pub fn map(&self, f: &js_sys::Function) -> Result<WasmPattern, JsValue> {
        self.map_recursive(f)
    }

    /// Helper for map() - recursive implementation.
    fn map_recursive(&self, f: &js_sys::Function) -> Result<WasmPattern, JsValue> {
        // Transform current value
        let this = JsValue::null();
        let new_value = f
            .call1(&this, &self.inner.value().clone())
            .map_err(|e| JsValue::from_str(&format!("Map function error: {:?}", e)))?;

        // Recursively transform elements
        let mut new_elements = Vec::new();
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            let mapped_elem = wasm_elem.map_recursive(f)?;
            new_elements.push(mapped_elem.inner);
        }

        Ok(WasmPattern {
            inner: Pattern::pattern(new_value, new_elements),
        })
    }

    /// Fold the pattern into a single value by applying a function with an accumulator.
    ///
    /// Processes values in depth-first, root-first order (pre-order traversal).
    /// The accumulator is threaded through all processing steps.
    ///
    /// # Arguments
    /// * `init` - Initial accumulator value
    /// * `f` - A JavaScript function that takes (accumulator, value) and returns new accumulator
    ///
    /// # Returns
    /// The final accumulated value
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern(10);
    /// pattern.addElement(Pattern.of(20));
    /// pattern.addElement(Pattern.of(30));
    /// const sum = pattern.fold(0, (acc, v) => acc + v); // 60
    /// ```
    #[wasm_bindgen(js_name = fold)]
    pub fn fold(&self, init: JsValue, f: &js_sys::Function) -> Result<JsValue, JsValue> {
        self.fold_recursive(init, f)
    }

    /// Helper for fold() - recursive implementation.
    fn fold_recursive(&self, acc: JsValue, f: &js_sys::Function) -> Result<JsValue, JsValue> {
        // Process current value
        let this = JsValue::null();
        let new_acc = f
            .call2(&this, &acc, &self.inner.value().clone())
            .map_err(|e| JsValue::from_str(&format!("Fold function error: {:?}", e)))?;

        // Process elements recursively (left to right)
        let mut acc = new_acc;
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            acc = wasm_elem.fold_recursive(acc, f)?;
        }

        Ok(acc)
    }

    /// Paramorphism: bottom-up fold with access to both pattern and child results.
    ///
    /// This is a powerful recursion scheme that processes the pattern bottom-up,
    /// giving each node access to both its value and the results of processing its children.
    ///
    /// # Arguments
    /// * `f` - A JavaScript function that takes (pattern, childResults array) and returns a result
    ///
    /// # Returns
    /// The result of the paramorphism
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("root");
    /// pattern.addElement(Pattern.of("child1"));
    /// pattern.addElement(Pattern.of("child2"));
    ///
    /// // Count nodes: each node returns 1 + sum of child counts
    /// const count = pattern.para((p, childResults) => {
    ///     return 1 + childResults.reduce((sum, r) => sum + r, 0);
    /// });
    /// // Returns 3 (root + 2 children)
    /// ```
    #[wasm_bindgen(js_name = para)]
    pub fn para(&self, f: &js_sys::Function) -> Result<JsValue, JsValue> {
        self.para_recursive(f)
    }

    /// Helper for para() - recursive implementation.
    fn para_recursive(&self, f: &js_sys::Function) -> Result<JsValue, JsValue> {
        // Recursively compute results for all child elements
        let child_results = js_sys::Array::new();
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            let result = wasm_elem.para_recursive(f)?;
            child_results.push(&result);
        }

        // Apply function to current pattern and child results
        let this = JsValue::null();
        let wasm_pattern = WasmPattern {
            inner: self.inner.clone(),
        };
        f.call2(&this, &JsValue::from(wasm_pattern), &child_results)
            .map_err(|e| JsValue::from_str(&format!("Para function error: {:?}", e)))
    }

    // ========================================================================
    // Combination Methods (T015 - Phase 4)
    // ========================================================================

    /// Combine two patterns associatively.
    ///
    /// For JavaScript values, this uses a custom combiner function to combine the values.
    /// Elements are concatenated (left first, then right).
    ///
    /// # Arguments
    /// * `other` - Another Pattern to combine with
    /// * `combiner` - A JavaScript function that takes (value1, value2) and returns combined value
    ///
    /// # Returns
    /// A new Pattern with combined value and concatenated elements
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p1 = Pattern.pattern("hello");
    /// p1.addElement(Pattern.of("a"));
    /// const p2 = Pattern.pattern(" world");
    /// p2.addElement(Pattern.of("b"));
    /// const combined = p1.combine(p2, (v1, v2) => v1 + v2);
    /// // Result: Pattern("hello world") with elements [a, b]
    /// ```
    #[wasm_bindgen(js_name = combine)]
    pub fn combine(
        &self,
        other: &WasmPattern,
        combiner: &js_sys::Function,
    ) -> Result<WasmPattern, JsValue> {
        // Combine values using the provided function
        let this = JsValue::null();
        let combined_value = combiner
            .call2(
                &this,
                &self.inner.value().clone(),
                &other.inner.value().clone(),
            )
            .map_err(|e| JsValue::from_str(&format!("Combiner function error: {:?}", e)))?;

        // Concatenate elements (left first, then right)
        let mut combined_elements = self.inner.elements().to_vec();
        combined_elements.extend(other.inner.elements().iter().cloned());

        Ok(WasmPattern {
            inner: Pattern::pattern(combined_value, combined_elements),
        })
    }

    // ========================================================================
    // Comonad Methods (T015 - Phase 4)
    // ========================================================================

    /// Extract the decorative value at the current position.
    ///
    /// In Pattern's "decorated sequence" semantics, the value provides information
    /// ABOUT the elements. This operation accesses that decorative information.
    ///
    /// # Returns
    /// The value at this position
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p = Pattern.point("hello");
    /// console.log(p.extract()); // "hello"
    /// ```
    #[wasm_bindgen(js_name = extract)]
    pub fn extract(&self) -> JsValue {
        self.inner.value().clone()
    }

    /// Compute new decorative information at each position based on subpattern context.
    ///
    /// This is a powerful comonad operation that gives each position access to its full
    /// subpattern context, enabling context-aware computation of new decorations.
    ///
    /// # Arguments
    /// * `f` - A JavaScript function that takes a Pattern and returns a new value
    ///
    /// # Returns
    /// A new Pattern with the same structure but with computed decorative values
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p = Pattern.pattern("root");
    /// p.addElement(Pattern.of("child1"));
    /// p.addElement(Pattern.of("child2"));
    ///
    /// // Decorate each position with its size
    /// const sizes = p.extend(subpattern => subpattern.size());
    /// console.log(sizes.extract()); // 3 (root has 3 nodes)
    /// ```
    #[wasm_bindgen(js_name = extend)]
    pub fn extend(&self, f: &js_sys::Function) -> Result<WasmPattern, JsValue> {
        self.extend_recursive(f)
    }

    /// Helper for extend() - recursive implementation.
    fn extend_recursive(&self, f: &js_sys::Function) -> Result<WasmPattern, JsValue> {
        // Compute new decoration for current position
        let this = JsValue::null();
        let wasm_pattern = WasmPattern {
            inner: self.inner.clone(),
        };
        let new_value = f
            .call1(&this, &JsValue::from(wasm_pattern))
            .map_err(|e| JsValue::from_str(&format!("Extend function error: {:?}", e)))?;

        // Recursively extend elements
        let mut new_elements = Vec::new();
        for elem in self.inner.elements() {
            let wasm_elem = WasmPattern {
                inner: elem.clone(),
            };
            let extended_elem = wasm_elem.extend_recursive(f)?;
            new_elements.push(extended_elem.inner);
        }

        Ok(WasmPattern {
            inner: Pattern::pattern(new_value, new_elements),
        })
    }

    /// Decorate each position with its depth (maximum nesting level).
    ///
    /// Uses extend to compute the depth at every position.
    ///
    /// # Returns
    /// A Pattern where each position's value is the depth of that subpattern (as a number)
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p = Pattern.pattern("root");
    /// const child = Pattern.pattern("child");
    /// child.addElement(Pattern.of("grandchild"));
    /// p.addElement(child);
    ///
    /// const depths = p.depthAt();
    /// console.log(depths.extract()); // 2 (root has depth 2)
    /// console.log(depths.elements[0].extract()); // 1 (child has depth 1)
    /// ```
    #[wasm_bindgen(js_name = depthAt)]
    pub fn depth_at(&self) -> WasmPattern {
        // Use extend with a function that computes depth
        let extended = self
            .inner
            .extend(&|subpattern: &Pattern<JsValue>| JsValue::from_f64(subpattern.depth() as f64));

        WasmPattern { inner: extended }
    }

    /// Decorate each position with its subtree size (total node count).
    ///
    /// Uses extend to compute the size at every position.
    ///
    /// # Returns
    /// A Pattern where each position's value is the size of that subpattern (as a number)
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p = Pattern.pattern("root");
    /// p.addElement(Pattern.of("child1"));
    /// p.addElement(Pattern.of("child2"));
    ///
    /// const sizes = p.sizeAt();
    /// console.log(sizes.extract()); // 3 (root + 2 children)
    /// console.log(sizes.elements[0].extract()); // 1
    /// ```
    #[wasm_bindgen(js_name = sizeAt)]
    pub fn size_at(&self) -> WasmPattern {
        // Use extend with a function that computes size
        let extended = self
            .inner
            .extend(&|subpattern: &Pattern<JsValue>| JsValue::from_f64(subpattern.size() as f64));

        WasmPattern { inner: extended }
    }

    /// Decorate each position with its path from root (sequence of element indices).
    ///
    /// # Returns
    /// A Pattern where each position's value is an array representing the path from root
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const p = Pattern.pattern("root");
    /// const child = Pattern.pattern("child");
    /// child.addElement(Pattern.of("grandchild"));
    /// p.addElement(child);
    ///
    /// const paths = p.indicesAt();
    /// console.log(paths.extract()); // [] (root path)
    /// console.log(paths.elements[0].extract()); // [0] (first child path)
    /// console.log(paths.elements[0].elements[0].extract()); // [0, 0] (grandchild path)
    /// ```
    #[wasm_bindgen(js_name = indicesAt)]
    pub fn indices_at(&self) -> WasmPattern {
        fn go(path: Vec<usize>, pattern: &Pattern<JsValue>) -> Pattern<JsValue> {
            // Convert path to JsValue array
            let path_arr = js_sys::Array::new();
            for idx in &path {
                path_arr.push(&JsValue::from_f64(*idx as f64));
            }

            Pattern {
                value: path_arr.into(),
                elements: pattern
                    .elements()
                    .iter()
                    .enumerate()
                    .map(|(i, elem)| {
                        let mut new_path = path.clone();
                        new_path.push(i);
                        go(new_path, elem)
                    })
                    .collect(),
            }
        }

        WasmPattern {
            inner: go(vec![], &self.inner),
        }
    }

    // ========================================================================
    // Validation/Analysis Methods (T016 - Phase 4)
    // ========================================================================

    /// Validate pattern structure against configurable rules.
    ///
    /// Returns an Either-like value:
    /// - Success: `{ _tag: 'Right', right: undefined }`
    /// - Failure: `{ _tag: 'Left', left: ValidationError }`
    ///
    /// This return shape is compatible with effect-ts Either type.
    ///
    /// # Arguments
    /// * `rules` - ValidationRules specifying constraints
    ///
    /// # Returns
    /// An Either-like JsValue (does not throw)
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("root");
    /// pattern.addElement(Pattern.of("child"));
    ///
    /// const rules = new ValidationRules(10, 100);
    /// const result = pattern.validate(rules);
    ///
    /// if (result._tag === 'Left') {
    ///     console.error('Validation failed:', result.left.message);
    /// } else {
    ///     console.log('Pattern is valid');
    /// }
    /// ```
    #[wasm_bindgen(js_name = validate)]
    pub fn validate(&self, rules: &WasmValidationRules) -> JsValue {
        let internal_rules = rules.to_internal();

        match self.inner.validate(&internal_rules) {
            Ok(()) => either_right(JsValue::undefined()),
            Err(error) => either_left(validation_error_to_js(&error)),
        }
    }

    /// Analyze the structural characteristics of the pattern.
    ///
    /// Returns detailed information about depth distribution, element counts,
    /// nesting patterns, and a human-readable summary.
    ///
    /// # Returns
    /// A StructureAnalysis object
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const pattern = Pattern.pattern("root");
    /// pattern.addElement(Pattern.of("child1"));
    /// pattern.addElement(Pattern.of("child2"));
    ///
    /// const analysis = pattern.analyzeStructure();
    /// console.log('Summary:', analysis.summary);
    /// console.log('Depth distribution:', analysis.depthDistribution);
    /// ```
    #[wasm_bindgen(js_name = analyzeStructure)]
    pub fn analyze_structure(&self) -> WasmStructureAnalysis {
        WasmStructureAnalysis {
            inner: self.inner.analyze_structure(),
        }
    }
}

// ============================================================================
// WasmPattern Rust-side helpers (not exposed to JS)
// ============================================================================
//
// These methods allow other Rust crates (like pattern-wasm) to construct
// WasmPattern instances from native Rust types and extract them back.

impl WasmPattern {
    /// Create a WasmPattern from a Rust Pattern<JsValue>.
    ///
    /// This allows other crates to create WasmPattern instances from
    /// Pattern<JsValue> that they've constructed.
    ///
    /// # Arguments
    /// * `pattern` - A Rust Pattern<JsValue>
    ///
    /// # Returns
    /// A new WasmPattern wrapping the given pattern
    pub fn from_pattern(pattern: Pattern<JsValue>) -> Self {
        WasmPattern { inner: pattern }
    }

    /// Consume this WasmPattern and return the inner Pattern<JsValue>.
    ///
    /// This allows other crates to extract the native Rust Pattern from a WasmPattern.
    ///
    /// # Returns
    /// The inner Pattern<JsValue>
    pub fn into_pattern(self) -> Pattern<JsValue> {
        self.inner
    }

    /// Get a reference to the inner Pattern<JsValue>.
    ///
    /// This allows inspection of the Pattern without consuming the WasmPattern.
    ///
    /// # Returns
    /// A reference to the inner Pattern<JsValue>
    pub fn as_pattern(&self) -> &Pattern<JsValue> {
        &self.inner
    }
}

// ============================================================================
// 7. Graph Bindings (T007-T013 - Feature 033)
// ============================================================================
//
// WASM bindings for PatternGraph, ReconciliationPolicy, GraphQuery,
// GraphClass/TraversalDirection constant objects, and algorithm free functions.
//
// All types use the `Native*` JS name prefix to distinguish WASM-backed concrete
// classes from the pure TypeScript interfaces in @relateby/graph.

use crate::graph::graph_classifier::canonical_classifier;
use crate::graph::graph_query::{directed, directed_reverse, undirected, GraphQuery};
use crate::graph::StandardGraph;
use crate::pattern_graph::{from_pattern_graph, from_patterns_with_policy, PatternGraph};
use crate::reconcile::{
    ElementMergeStrategy, LabelMerge, PropertyMerge, ReconciliationPolicy, SubjectMergeStrategy,
};

// ---------------------------------------------------------------------------
// Helper: convert Pattern<Subject> → WasmPattern (via JsValue encoding)
// ---------------------------------------------------------------------------

fn subject_pattern_to_wasm(p: &crate::pattern::Pattern<crate::subject::Subject>) -> WasmPattern {
    let subject_js = WasmSubject::from_subject(p.value.clone()).to_js_value();
    let wasm_p = WasmPattern {
        inner: crate::pattern::Pattern {
            value: subject_js,
            elements: p
                .elements
                .iter()
                .map(|e| subject_pattern_to_wasm(e).inner)
                .collect(),
        },
    };
    wasm_p
}

fn wasm_pattern_to_subject_pattern(
    p: &WasmPattern,
) -> Option<crate::pattern::Pattern<crate::subject::Subject>> {
    let subject = WasmSubject::from_js_value(&p.inner.value)?.into_subject();
    let elements: Vec<_> = p
        .inner
        .elements
        .iter()
        .filter_map(|e| wasm_pattern_to_subject_pattern(&WasmPattern { inner: e.clone() }))
        .collect();
    Some(crate::pattern::Pattern {
        value: subject,
        elements,
    })
}

/// Convert a JsValue (which may be a serialized WasmPattern object) to Pattern<Subject>.
///
/// WasmPattern objects in JS have `value` and `elements` fields. The `value` is a
/// Subject JsValue with `_type: 'Subject'`. This function extracts the Subject and
/// recursively converts child elements.
fn js_value_to_subject_pattern(
    js: &JsValue,
) -> Option<crate::pattern::Pattern<crate::subject::Subject>> {
    if !js.is_object() {
        return None;
    }

    // Extract the `value` field (Subject JsValue)
    let value_js = js_sys::Reflect::get(js, &JsValue::from_str("value")).ok()?;
    let subject = WasmSubject::from_js_value(&value_js)?.into_subject();

    // Extract the `elements` field (array of child patterns)
    let elements_js = js_sys::Reflect::get(js, &JsValue::from_str("elements")).ok()?;
    let elements = if js_sys::Array::is_array(&elements_js) {
        let arr: &js_sys::Array = elements_js.unchecked_ref();
        (0..arr.length())
            .filter_map(|i| js_value_to_subject_pattern(&arr.get(i)))
            .collect()
    } else {
        vec![]
    };

    Some(crate::pattern::Pattern {
        value: subject,
        elements,
    })
}

fn subject_pattern_to_js(p: &crate::pattern::Pattern<crate::subject::Subject>) -> JsValue {
    JsValue::from(subject_pattern_to_wasm(p))
}

fn patterns_to_js_array(
    patterns: &[crate::pattern::Pattern<crate::subject::Subject>],
) -> js_sys::Array {
    let arr = js_sys::Array::new();
    for p in patterns {
        arr.push(&subject_pattern_to_js(p));
    }
    arr
}

// ---------------------------------------------------------------------------
// Helper: parse weight JsValue → TraversalWeight<Subject>
// ---------------------------------------------------------------------------

fn parse_weight(weight_js: &JsValue) -> crate::graph::graph_query::TraversalWeight<Subject> {
    if let Some(s) = weight_js.as_string() {
        match s.as_str() {
            "directed" => directed::<Subject>(),
            "directed_reverse" => directed_reverse::<Subject>(),
            _ => undirected::<Subject>(), // "undirected" or unknown
        }
    } else if weight_js.is_function() {
        let func = js_sys::Function::from(weight_js.clone());
        std::rc::Rc::new(
            move |rel: &crate::pattern::Pattern<Subject>,
                  dir: crate::graph::graph_query::TraversalDirection| {
                let wasm_rel = subject_pattern_to_wasm(rel);
                let dir_str = match dir {
                    crate::graph::graph_query::TraversalDirection::Forward => "forward",
                    crate::graph::graph_query::TraversalDirection::Backward => "backward",
                };
                let result = func.call2(
                    &JsValue::undefined(),
                    &JsValue::from(wasm_rel),
                    &JsValue::from_str(dir_str),
                );
                match result {
                    Ok(v) => v.as_f64().unwrap_or(1.0),
                    Err(_) => 1.0,
                }
            },
        )
    } else {
        undirected::<Subject>()
    }
}

// ---------------------------------------------------------------------------
// WasmReconciliationPolicy (js_name = NativeReconciliationPolicy)
// ---------------------------------------------------------------------------

/// WASM binding for ReconciliationPolicy.
///
/// Governs how identity conflicts are resolved when patterns with the same
/// identity are combined into a PatternGraph.
///
/// Exported to JavaScript as `WasmReconciliationPolicy`.
#[wasm_bindgen]
pub struct WasmReconciliationPolicy {
    #[wasm_bindgen(skip)]
    pub inner: ReconciliationPolicy<SubjectMergeStrategy>,
}

#[wasm_bindgen]
impl WasmReconciliationPolicy {
    /// Incoming pattern replaces existing on identity conflict.
    #[wasm_bindgen(js_name = lastWriteWins)]
    pub fn last_write_wins() -> WasmReconciliationPolicy {
        WasmReconciliationPolicy {
            inner: ReconciliationPolicy::LastWriteWins,
        }
    }

    /// Existing pattern is kept; incoming is discarded on identity conflict.
    #[wasm_bindgen(js_name = firstWriteWins)]
    pub fn first_write_wins() -> WasmReconciliationPolicy {
        WasmReconciliationPolicy {
            inner: ReconciliationPolicy::FirstWriteWins,
        }
    }

    /// Identity conflict is recorded in graph.conflicts; neither wins.
    #[wasm_bindgen(js_name = strict)]
    pub fn strict() -> WasmReconciliationPolicy {
        WasmReconciliationPolicy {
            inner: ReconciliationPolicy::Strict,
        }
    }

    /// Merge labels and properties per strategy.
    ///
    /// # Arguments
    /// * `options` - Optional JS object with `elementStrategy`, `labelMerge`, `propertyMerge`
    #[wasm_bindgen(js_name = merge)]
    pub fn merge_policy(options: JsValue) -> WasmReconciliationPolicy {
        let mut element_strategy = ElementMergeStrategy::UnionElements;
        let mut label_merge = LabelMerge::UnionLabels;
        let mut property_merge = PropertyMerge::ShallowMerge;

        if options.is_object() {
            if let Ok(es) = js_sys::Reflect::get(&options, &JsValue::from_str("elementStrategy")) {
                if let Some(s) = es.as_string() {
                    element_strategy = match s.as_str() {
                        "replace" => ElementMergeStrategy::ReplaceElements,
                        "append" => ElementMergeStrategy::AppendElements,
                        _ => ElementMergeStrategy::UnionElements,
                    };
                }
            }
            if let Ok(lm) = js_sys::Reflect::get(&options, &JsValue::from_str("labelMerge")) {
                if let Some(s) = lm.as_string() {
                    label_merge = match s.as_str() {
                        "intersect" => LabelMerge::IntersectLabels,
                        "left" | "right" => LabelMerge::ReplaceLabels,
                        _ => LabelMerge::UnionLabels,
                    };
                }
            }
            if let Ok(pm) = js_sys::Reflect::get(&options, &JsValue::from_str("propertyMerge")) {
                if let Some(s) = pm.as_string() {
                    property_merge = match s.as_str() {
                        "left" | "right" => PropertyMerge::ReplaceProperties,
                        "merge" => PropertyMerge::ShallowMerge,
                        _ => PropertyMerge::ShallowMerge,
                    };
                }
            }
        }

        let strategy = SubjectMergeStrategy {
            label_merge,
            property_merge,
        };
        WasmReconciliationPolicy {
            inner: ReconciliationPolicy::Merge(element_strategy, strategy),
        }
    }
}

// ---------------------------------------------------------------------------
// WasmPatternGraph (js_name = NativePatternGraph)
// ---------------------------------------------------------------------------

/// WASM binding for PatternGraph<(), Subject>.
///
/// A classified, indexed collection of patterns organized by graph role.
/// Immutable after construction; merge returns a new instance.
///
/// Exported to JavaScript as `WasmPatternGraph`.
#[wasm_bindgen]
pub struct WasmPatternGraph {
    #[wasm_bindgen(skip)]
    pub inner: std::rc::Rc<PatternGraph<(), Subject>>,
}

#[wasm_bindgen]
impl WasmPatternGraph {
    /// Construct a graph from an array of NativePattern instances.
    ///
    /// Patterns whose values are not Subject instances are classified as `other`.
    /// Never throws — unrecognized patterns are silently dropped.
    #[wasm_bindgen(js_name = fromPatterns)]
    pub fn from_patterns(
        patterns: &js_sys::Array,
        policy: Option<WasmReconciliationPolicy>,
    ) -> WasmPatternGraph {
        let classifier = canonical_classifier::<Subject>();
        let policy_inner = policy
            .map(|p| p.inner)
            .unwrap_or(ReconciliationPolicy::LastWriteWins);

        let subject_patterns: Vec<crate::pattern::Pattern<Subject>> = (0..patterns.length())
            .filter_map(|i| {
                let item = patterns.get(i);
                // Items are WasmPattern instances serialized as JS objects.
                // Extract the value field (which is a Subject JsValue) and elements.
                js_value_to_subject_pattern(&item)
            })
            .collect();

        let graph = from_patterns_with_policy(&classifier, &policy_inner, subject_patterns);

        WasmPatternGraph {
            inner: std::rc::Rc::new(graph),
        }
    }

    /// Construct an empty graph.
    #[wasm_bindgen(js_name = empty)]
    pub fn empty() -> WasmPatternGraph {
        WasmPatternGraph {
            inner: std::rc::Rc::new(PatternGraph::empty()),
        }
    }

    /// All node patterns in the graph.
    #[wasm_bindgen(getter)]
    pub fn nodes(&self) -> js_sys::Array {
        patterns_to_js_array(&self.inner.pg_nodes.values().cloned().collect::<Vec<_>>())
    }

    /// All relationship patterns in the graph.
    #[wasm_bindgen(getter)]
    pub fn relationships(&self) -> js_sys::Array {
        patterns_to_js_array(
            &self
                .inner
                .pg_relationships
                .values()
                .cloned()
                .collect::<Vec<_>>(),
        )
    }

    /// All walk patterns in the graph.
    #[wasm_bindgen(getter)]
    pub fn walks(&self) -> js_sys::Array {
        patterns_to_js_array(&self.inner.pg_walks.values().cloned().collect::<Vec<_>>())
    }

    /// All annotation patterns in the graph.
    #[wasm_bindgen(getter)]
    pub fn annotations(&self) -> js_sys::Array {
        patterns_to_js_array(
            &self
                .inner
                .pg_annotations
                .values()
                .cloned()
                .collect::<Vec<_>>(),
        )
    }

    /// Identity conflicts recorded under the strict policy.
    ///
    /// Returns a JS object mapping identity strings to arrays of conflicting patterns.
    #[wasm_bindgen(getter)]
    pub fn conflicts(&self) -> JsValue {
        let obj = js_sys::Object::new();
        for (id, patterns) in &self.inner.pg_conflicts {
            let arr = patterns_to_js_array(patterns);
            js_sys::Reflect::set(&obj, &JsValue::from_str(&id.0), &arr).ok();
        }
        obj.into()
    }

    /// Total count of non-conflict elements.
    #[wasm_bindgen(getter)]
    pub fn size(&self) -> usize {
        self.inner.pg_nodes.len()
            + self.inner.pg_relationships.len()
            + self.inner.pg_walks.len()
            + self.inner.pg_annotations.len()
            + self.inner.pg_other.len()
    }

    /// Merge this graph with another, returning a new graph.
    ///
    /// Uses LastWriteWins policy for the merge.
    #[wasm_bindgen(js_name = merge)]
    pub fn merge(&self, other: &WasmPatternGraph) -> WasmPatternGraph {
        let classifier = canonical_classifier::<Subject>();
        let policy = ReconciliationPolicy::LastWriteWins;

        // Collect all patterns from both graphs and rebuild
        let all_patterns: Vec<crate::pattern::Pattern<Subject>> = self
            .inner
            .pg_nodes
            .values()
            .chain(self.inner.pg_relationships.values())
            .chain(self.inner.pg_walks.values())
            .chain(self.inner.pg_annotations.values())
            .chain(other.inner.pg_nodes.values())
            .chain(other.inner.pg_relationships.values())
            .chain(other.inner.pg_walks.values())
            .chain(other.inner.pg_annotations.values())
            .cloned()
            .collect();

        let graph = from_patterns_with_policy(&classifier, &policy, all_patterns);

        WasmPatternGraph {
            inner: std::rc::Rc::new(graph),
        }
    }

    /// Return patterns in bottom-up shape-class topological order.
    ///
    /// Returns null if the graph contains a cycle.
    /// Used by paraGraph and paraGraphFixed to determine processing order.
    #[wasm_bindgen(js_name = topoSort)]
    pub fn topo_sort(&self) -> JsValue {
        let query = from_pattern_graph(std::rc::Rc::clone(&self.inner));
        match crate::graph::algorithms::topological_sort(&query) {
            Some(sorted) => JsValue::from(patterns_to_js_array(&sorted)),
            None => JsValue::null(),
        }
    }
}

// ---------------------------------------------------------------------------
// WasmGraphQuery (js_name = NativeGraphQuery)
// ---------------------------------------------------------------------------

/// WASM binding for GraphQuery<Subject>.
///
/// A read-only query handle over a PatternGraph. Provides structural navigation
/// without exposing the underlying storage.
///
/// Exported to JavaScript as `WasmGraphQuery`.
#[wasm_bindgen]
pub struct WasmGraphQuery {
    #[wasm_bindgen(skip)]
    pub inner: GraphQuery<Subject>,
}

#[wasm_bindgen]
impl WasmGraphQuery {
    /// Create a query handle from a NativePatternGraph.
    #[wasm_bindgen(js_name = fromPatternGraph)]
    pub fn from_pattern_graph(graph: &WasmPatternGraph) -> WasmGraphQuery {
        WasmGraphQuery {
            inner: from_pattern_graph(std::rc::Rc::clone(&graph.inner)),
        }
    }

    /// All node patterns.
    #[wasm_bindgen(js_name = nodes)]
    pub fn nodes(&self) -> js_sys::Array {
        patterns_to_js_array(&(self.inner.query_nodes)())
    }

    /// All relationship patterns.
    #[wasm_bindgen(js_name = relationships)]
    pub fn relationships(&self) -> js_sys::Array {
        patterns_to_js_array(&(self.inner.query_relationships)())
    }

    /// Source node of a relationship. Returns null if not found.
    #[wasm_bindgen(js_name = source)]
    pub fn source(&self, rel: &WasmPattern) -> JsValue {
        let subject_rel = match wasm_pattern_to_subject_pattern(rel) {
            Some(r) => r,
            None => return JsValue::null(),
        };
        match (self.inner.query_source)(&subject_rel) {
            Some(p) => subject_pattern_to_js(&p),
            None => JsValue::null(),
        }
    }

    /// Target node of a relationship. Returns null if not found.
    #[wasm_bindgen(js_name = target)]
    pub fn target(&self, rel: &WasmPattern) -> JsValue {
        let subject_rel = match wasm_pattern_to_subject_pattern(rel) {
            Some(r) => r,
            None => return JsValue::null(),
        };
        match (self.inner.query_target)(&subject_rel) {
            Some(p) => subject_pattern_to_js(&p),
            None => JsValue::null(),
        }
    }

    /// All relationships incident to a node.
    #[wasm_bindgen(js_name = incidentRels)]
    pub fn incident_rels(&self, node: &WasmPattern) -> js_sys::Array {
        let subject_node = match wasm_pattern_to_subject_pattern(node) {
            Some(n) => n,
            None => return js_sys::Array::new(),
        };
        patterns_to_js_array(&(self.inner.query_incident_rels)(&subject_node))
    }

    /// Count of incident relationships for a node.
    #[wasm_bindgen(js_name = degree)]
    pub fn degree(&self, node: &WasmPattern) -> usize {
        let subject_node = match wasm_pattern_to_subject_pattern(node) {
            Some(n) => n,
            None => return 0,
        };
        (self.inner.query_degree)(&subject_node)
    }

    /// Look up a node by its identity string. Returns null if not found.
    #[wasm_bindgen(js_name = nodeById)]
    pub fn node_by_id(&self, identity: &str) -> JsValue {
        let sym = Symbol(identity.to_string());
        match (self.inner.query_node_by_id)(&sym) {
            Some(p) => subject_pattern_to_js(&p),
            None => JsValue::null(),
        }
    }

    /// Look up a relationship by its identity string. Returns null if not found.
    #[wasm_bindgen(js_name = relationshipById)]
    pub fn relationship_by_id(&self, identity: &str) -> JsValue {
        let sym = Symbol(identity.to_string());
        match (self.inner.query_relationship_by_id)(&sym) {
            Some(p) => subject_pattern_to_js(&p),
            None => JsValue::null(),
        }
    }
}

// ---------------------------------------------------------------------------
// GraphClass constant object (T009)
// ---------------------------------------------------------------------------

/// String constants for graph element classification.
///
/// Exported to JavaScript as a plain object (not a class).
/// Use these constants as discriminants in transform callbacks.
#[wasm_bindgen]
pub fn graph_class_constants() -> JsValue {
    let obj = js_sys::Object::new();
    js_sys::Reflect::set(&obj, &JsValue::from_str("NODE"), &JsValue::from_str("node")).ok();
    js_sys::Reflect::set(
        &obj,
        &JsValue::from_str("RELATIONSHIP"),
        &JsValue::from_str("relationship"),
    )
    .ok();
    js_sys::Reflect::set(
        &obj,
        &JsValue::from_str("ANNOTATION"),
        &JsValue::from_str("annotation"),
    )
    .ok();
    js_sys::Reflect::set(&obj, &JsValue::from_str("WALK"), &JsValue::from_str("walk")).ok();
    js_sys::Reflect::set(
        &obj,
        &JsValue::from_str("OTHER"),
        &JsValue::from_str("other"),
    )
    .ok();
    obj.into()
}

// ---------------------------------------------------------------------------
// TraversalDirection constant object (T011)
// ---------------------------------------------------------------------------

/// String constants for traversal direction.
///
/// Exported to JavaScript as a plain object (not a class).
#[wasm_bindgen]
pub fn traversal_direction_constants() -> JsValue {
    let obj = js_sys::Object::new();
    js_sys::Reflect::set(
        &obj,
        &JsValue::from_str("FORWARD"),
        &JsValue::from_str("forward"),
    )
    .ok();
    js_sys::Reflect::set(
        &obj,
        &JsValue::from_str("BACKWARD"),
        &JsValue::from_str("backward"),
    )
    .ok();
    obj.into()
}

// ---------------------------------------------------------------------------
// Algorithm free functions (T012)
// ---------------------------------------------------------------------------

/// Breadth-first search from a start node.
///
/// Returns patterns in BFS order. Weight defaults to undirected.
#[wasm_bindgen]
pub fn bfs(query: &WasmGraphQuery, start: &WasmPattern, weight: JsValue) -> js_sys::Array {
    let subject_start = match wasm_pattern_to_subject_pattern(start) {
        Some(s) => s,
        None => return js_sys::Array::new(),
    };
    let w = parse_weight(&weight);
    let result = crate::graph::algorithms::bfs(&query.inner, &w, &subject_start);
    patterns_to_js_array(&result)
}

/// Depth-first search from a start node.
///
/// Returns patterns in DFS order. Weight defaults to undirected.
#[wasm_bindgen]
pub fn dfs(query: &WasmGraphQuery, start: &WasmPattern, weight: JsValue) -> js_sys::Array {
    let subject_start = match wasm_pattern_to_subject_pattern(start) {
        Some(s) => s,
        None => return js_sys::Array::new(),
    };
    let w = parse_weight(&weight);
    let result = crate::graph::algorithms::dfs(&query.inner, &w, &subject_start);
    patterns_to_js_array(&result)
}

/// Shortest path between two nodes.
///
/// Returns null if no path exists. Weight defaults to undirected.
#[wasm_bindgen(js_name = shortestPath)]
pub fn shortest_path(
    query: &WasmGraphQuery,
    start: &WasmPattern,
    end: &WasmPattern,
    weight: JsValue,
) -> JsValue {
    let subject_start = match wasm_pattern_to_subject_pattern(start) {
        Some(s) => s,
        None => return JsValue::null(),
    };
    let subject_end = match wasm_pattern_to_subject_pattern(end) {
        Some(e) => e,
        None => return JsValue::null(),
    };
    let w = parse_weight(&weight);
    match crate::graph::algorithms::shortest_path(&query.inner, &w, &subject_start, &subject_end) {
        Some(path) => JsValue::from(patterns_to_js_array(&path)),
        None => JsValue::null(),
    }
}

/// All paths between two nodes.
///
/// Returns an array of path arrays. Weight defaults to undirected.
#[wasm_bindgen(js_name = allPaths)]
pub fn all_paths(
    query: &WasmGraphQuery,
    start: &WasmPattern,
    end: &WasmPattern,
    weight: JsValue,
) -> js_sys::Array {
    let subject_start = match wasm_pattern_to_subject_pattern(start) {
        Some(s) => s,
        None => return js_sys::Array::new(),
    };
    let subject_end = match wasm_pattern_to_subject_pattern(end) {
        Some(e) => e,
        None => return js_sys::Array::new(),
    };
    let w = parse_weight(&weight);
    let paths = crate::graph::algorithms::all_paths(&query.inner, &w, &subject_start, &subject_end);
    let outer = js_sys::Array::new();
    for path in &paths {
        outer.push(&JsValue::from(patterns_to_js_array(path)));
    }
    outer
}

/// Connected components of the graph.
///
/// Returns an array of component arrays. Weight defaults to undirected.
#[wasm_bindgen(js_name = connectedComponents)]
pub fn connected_components(query: &WasmGraphQuery, weight: JsValue) -> js_sys::Array {
    let w = parse_weight(&weight);
    let components = crate::graph::algorithms::connected_components(&query.inner, &w);
    let outer = js_sys::Array::new();
    for component in &components {
        outer.push(&JsValue::from(patterns_to_js_array(component)));
    }
    outer
}

/// Returns true if the graph contains a directed cycle.
#[wasm_bindgen(js_name = hasCycle)]
pub fn has_cycle(query: &WasmGraphQuery) -> bool {
    crate::graph::algorithms::has_cycle(&query.inner)
}

/// Returns true if the graph is connected.
///
/// Weight defaults to undirected.
#[wasm_bindgen(js_name = isConnected)]
pub fn is_connected(query: &WasmGraphQuery, weight: JsValue) -> bool {
    let w = parse_weight(&weight);
    crate::graph::algorithms::is_connected(&query.inner, &w)
}

/// Topological sort of the graph.
///
/// Returns null if the graph contains a cycle.
#[wasm_bindgen(js_name = topologicalSort)]
pub fn topological_sort(query: &WasmGraphQuery) -> JsValue {
    match crate::graph::algorithms::topological_sort(&query.inner) {
        Some(sorted) => JsValue::from(patterns_to_js_array(&sorted)),
        None => JsValue::null(),
    }
}

/// Degree centrality for all nodes.
///
/// Returns a JS object mapping identity strings to normalized scores.
#[wasm_bindgen(js_name = degreeCentrality)]
pub fn degree_centrality(query: &WasmGraphQuery) -> JsValue {
    let scores = crate::graph::algorithms::degree_centrality(&query.inner);
    let obj = js_sys::Object::new();
    for (id, score) in &scores {
        js_sys::Reflect::set(&obj, &JsValue::from_str(&id.0), &JsValue::from_f64(*score)).ok();
    }
    obj.into()
}

/// Betweenness centrality for all nodes.
///
/// Returns a JS object mapping identity strings to scores.
/// Weight defaults to undirected.
#[wasm_bindgen(js_name = betweennessCentrality)]
pub fn betweenness_centrality(query: &WasmGraphQuery, weight: JsValue) -> JsValue {
    let w = parse_weight(&weight);
    let scores = crate::graph::algorithms::betweenness_centrality(&query.inner, &w);
    let obj = js_sys::Object::new();
    for (id, score) in &scores {
        js_sys::Reflect::set(&obj, &JsValue::from_str(&id.0), &JsValue::from_f64(*score)).ok();
    }
    obj.into()
}

/// Minimum spanning tree.
///
/// Returns an array of relationship patterns. Weight defaults to undirected.
#[wasm_bindgen(js_name = minimumSpanningTree)]
pub fn minimum_spanning_tree(query: &WasmGraphQuery, weight: JsValue) -> js_sys::Array {
    let w = parse_weight(&weight);
    let tree = crate::graph::algorithms::minimum_spanning_tree(&query.inner, &w);
    patterns_to_js_array(&tree)
}

/// Returns all walks containing the given node.
#[wasm_bindgen(js_name = queryWalksContaining)]
pub fn query_walks_containing(query: &WasmGraphQuery, node: &WasmPattern) -> js_sys::Array {
    let subject_node = match wasm_pattern_to_subject_pattern(node) {
        Some(n) => n,
        None => return js_sys::Array::new(),
    };
    let classifier = canonical_classifier::<Subject>();
    let walks =
        crate::graph::algorithms::query_walks_containing(&classifier, &query.inner, &subject_node);
    patterns_to_js_array(&walks)
}

/// Returns all elements that share a container with the given node.
#[wasm_bindgen(js_name = queryCoMembers)]
pub fn query_co_members(
    query: &WasmGraphQuery,
    node: &WasmPattern,
    container: &WasmPattern,
) -> js_sys::Array {
    let subject_node = match wasm_pattern_to_subject_pattern(node) {
        Some(n) => n,
        None => return js_sys::Array::new(),
    };
    let subject_container = match wasm_pattern_to_subject_pattern(container) {
        Some(c) => c,
        None => return js_sys::Array::new(),
    };
    let members =
        crate::graph::algorithms::query_co_members(&query.inner, &subject_node, &subject_container);
    patterns_to_js_array(&members)
}

/// Returns all annotations of the given target element.
#[wasm_bindgen(js_name = queryAnnotationsOf)]
pub fn query_annotations_of(query: &WasmGraphQuery, target: &WasmPattern) -> js_sys::Array {
    let subject_target = match wasm_pattern_to_subject_pattern(target) {
        Some(t) => t,
        None => return js_sys::Array::new(),
    };
    let classifier = canonical_classifier::<Subject>();
    let annotations =
        crate::graph::algorithms::query_annotations_of(&classifier, &query.inner, &subject_target);
    patterns_to_js_array(&annotations)
}

// ============================================================================
// StandardGraph WASM Bindings (T004-T013, T037-T038)
// ============================================================================

/// WASM binding for StandardGraph.
///
/// Ergonomic graph builder and query interface. Zero configuration — create,
/// add elements, and query without managing classifiers or policies.
///
/// Exported to JavaScript as `WasmStandardGraph`. Re-exported as `StandardGraph`
/// from `pattern-wasm`.
#[wasm_bindgen]
pub struct WasmStandardGraph {
    #[wasm_bindgen(skip)]
    pub inner: StandardGraph,
}

impl Default for WasmStandardGraph {
    fn default() -> Self {
        Self::new()
    }
}

#[wasm_bindgen]
impl WasmStandardGraph {
    /// Create an empty StandardGraph.
    #[wasm_bindgen(constructor)]
    pub fn new() -> WasmStandardGraph {
        WasmStandardGraph {
            inner: StandardGraph::new(),
        }
    }

    /// Create from an array of Pattern<Subject> instances.
    #[wasm_bindgen(js_name = fromPatterns)]
    pub fn from_patterns(patterns: &js_sys::Array) -> WasmStandardGraph {
        let subject_patterns: Vec<crate::pattern::Pattern<Subject>> = (0..patterns.length())
            .filter_map(|i| js_value_to_subject_pattern(&patterns.get(i)))
            .collect();
        WasmStandardGraph {
            inner: StandardGraph::from_patterns(subject_patterns),
        }
    }

    /// Wrap an existing NativePatternGraph.
    #[wasm_bindgen(js_name = fromPatternGraph)]
    pub fn from_pattern_graph(graph: &WasmPatternGraph) -> WasmStandardGraph {
        // PatternGraph doesn't implement Clone, so collect all patterns and rebuild.
        let all_patterns: Vec<crate::pattern::Pattern<Subject>> = graph
            .inner
            .pg_nodes
            .values()
            .chain(graph.inner.pg_relationships.values())
            .chain(graph.inner.pg_walks.values())
            .chain(graph.inner.pg_annotations.values())
            .cloned()
            .collect();
        WasmStandardGraph {
            inner: StandardGraph::from_patterns(all_patterns),
        }
    }

    // --- Element addition ---

    /// Add a node to the graph.
    #[wasm_bindgen(js_name = addNode)]
    pub fn add_node(&mut self, subject: &WasmSubject) {
        self.inner.add_node(subject.as_subject().clone());
    }

    /// Add a relationship to the graph.
    ///
    /// Pass the actual `Subject` objects for source and target. When you only
    /// have an identity string, use `Subject.fromId("id")`.
    #[wasm_bindgen(js_name = addRelationship)]
    pub fn add_relationship(
        &mut self,
        subject: &WasmSubject,
        source: &WasmSubject,
        target: &WasmSubject,
    ) {
        self.inner.add_relationship(
            subject.as_subject().clone(),
            source.as_subject(),
            target.as_subject(),
        );
    }

    /// Add a walk to the graph.
    ///
    /// Pass a JS Array of `Subject` objects for the relationships. When you only
    /// have identity strings, use `Subject.fromId("id")` for each element.
    #[wasm_bindgen(js_name = addWalk)]
    pub fn add_walk(&mut self, subject: &WasmSubject, relationships: &js_sys::Array) {
        let subjects: Vec<Subject> = (0..relationships.length())
            .filter_map(|i| {
                let item = relationships.get(i);
                // Extract identity from a Subject JS object via its identity property
                let id = js_sys::Reflect::get(&item, &wasm_bindgen::JsValue::from_str("identity"))
                    .ok()?
                    .as_string()?;
                Some(Subject::from_id(id))
            })
            .collect();
        self.inner.add_walk(subject.as_subject().clone(), &subjects);
    }

    /// Add an annotation to the graph.
    ///
    /// Pass the actual `Subject` for the annotated element. When you only have
    /// an identity string, use `Subject.fromId("id")`.
    #[wasm_bindgen(js_name = addAnnotation)]
    pub fn add_annotation(&mut self, subject: &WasmSubject, element: &WasmSubject) {
        self.inner
            .add_annotation(subject.as_subject().clone(), element.as_subject());
    }

    /// Add a single pattern (classified by shape).
    #[wasm_bindgen(js_name = addPattern)]
    pub fn add_pattern(&mut self, pattern: &WasmPattern) {
        if let Some(subject_pattern) = wasm_pattern_to_subject_pattern(pattern) {
            self.inner.add_pattern(subject_pattern);
        }
    }

    /// Add multiple patterns (classified by shape).
    #[wasm_bindgen(js_name = addPatterns)]
    pub fn add_patterns(&mut self, patterns: &js_sys::Array) {
        let subject_patterns: Vec<crate::pattern::Pattern<Subject>> = (0..patterns.length())
            .filter_map(|i| js_value_to_subject_pattern(&patterns.get(i)))
            .collect();
        self.inner.add_patterns(subject_patterns);
    }

    // --- Element access ---

    /// Get a node by identity. Returns undefined if not found.
    #[wasm_bindgen(js_name = node)]
    pub fn node(&self, id: &str) -> Option<WasmPattern> {
        self.inner
            .node(&Symbol(id.to_string()))
            .map(subject_pattern_to_wasm)
    }

    /// Get a relationship by identity. Returns undefined if not found.
    #[wasm_bindgen(js_name = relationship)]
    pub fn relationship(&self, id: &str) -> Option<WasmPattern> {
        self.inner
            .relationship(&Symbol(id.to_string()))
            .map(subject_pattern_to_wasm)
    }

    /// Get a walk by identity. Returns undefined if not found.
    #[wasm_bindgen(js_name = walk)]
    pub fn walk(&self, id: &str) -> Option<WasmPattern> {
        self.inner
            .walk(&Symbol(id.to_string()))
            .map(subject_pattern_to_wasm)
    }

    /// Get an annotation by identity. Returns undefined if not found.
    #[wasm_bindgen(js_name = annotation)]
    pub fn annotation(&self, id: &str) -> Option<WasmPattern> {
        self.inner
            .annotation(&Symbol(id.to_string()))
            .map(subject_pattern_to_wasm)
    }

    // --- Count getters ---

    /// Number of nodes.
    #[wasm_bindgen(getter, js_name = nodeCount)]
    pub fn node_count(&self) -> usize {
        self.inner.node_count()
    }

    /// Number of relationships.
    #[wasm_bindgen(getter, js_name = relationshipCount)]
    pub fn relationship_count(&self) -> usize {
        self.inner.relationship_count()
    }

    /// Number of walks.
    #[wasm_bindgen(getter, js_name = walkCount)]
    pub fn walk_count(&self) -> usize {
        self.inner.walk_count()
    }

    /// Number of annotations.
    #[wasm_bindgen(getter, js_name = annotationCount)]
    pub fn annotation_count(&self) -> usize {
        self.inner.annotation_count()
    }

    /// True if the graph has no elements.
    #[wasm_bindgen(getter, js_name = isEmpty)]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// True if any reconciliation conflicts exist.
    #[wasm_bindgen(getter, js_name = hasConflicts)]
    pub fn has_conflicts(&self) -> bool {
        self.inner.has_conflicts()
    }

    // --- Iteration getters ---

    /// All nodes as array of `{id: string, pattern: Pattern}`.
    #[wasm_bindgen(getter, js_name = nodes)]
    pub fn nodes(&self) -> js_sys::Array {
        let arr = js_sys::Array::new();
        for (id, pattern) in self.inner.nodes() {
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(&obj, &JsValue::from_str("id"), &JsValue::from_str(&id.0))
                .unwrap_or_default();
            js_sys::Reflect::set(
                &obj,
                &JsValue::from_str("pattern"),
                &JsValue::from(subject_pattern_to_wasm(pattern)),
            )
            .unwrap_or_default();
            arr.push(&obj);
        }
        arr
    }

    /// All relationships as array of `{id: string, pattern: Pattern}`.
    #[wasm_bindgen(getter, js_name = relationships)]
    pub fn relationships(&self) -> js_sys::Array {
        let arr = js_sys::Array::new();
        for (id, pattern) in self.inner.relationships() {
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(&obj, &JsValue::from_str("id"), &JsValue::from_str(&id.0))
                .unwrap_or_default();
            js_sys::Reflect::set(
                &obj,
                &JsValue::from_str("pattern"),
                &JsValue::from(subject_pattern_to_wasm(pattern)),
            )
            .unwrap_or_default();
            arr.push(&obj);
        }
        arr
    }

    /// All walks as array of `{id: string, pattern: Pattern}`.
    #[wasm_bindgen(getter, js_name = walks)]
    pub fn walks(&self) -> js_sys::Array {
        let arr = js_sys::Array::new();
        for (id, pattern) in self.inner.walks() {
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(&obj, &JsValue::from_str("id"), &JsValue::from_str(&id.0))
                .unwrap_or_default();
            js_sys::Reflect::set(
                &obj,
                &JsValue::from_str("pattern"),
                &JsValue::from(subject_pattern_to_wasm(pattern)),
            )
            .unwrap_or_default();
            arr.push(&obj);
        }
        arr
    }

    /// All annotations as array of `{id: string, pattern: Pattern}`.
    #[wasm_bindgen(getter, js_name = annotations)]
    pub fn annotations(&self) -> js_sys::Array {
        let arr = js_sys::Array::new();
        for (id, pattern) in self.inner.annotations() {
            let obj = js_sys::Object::new();
            js_sys::Reflect::set(&obj, &JsValue::from_str("id"), &JsValue::from_str(&id.0))
                .unwrap_or_default();
            js_sys::Reflect::set(
                &obj,
                &JsValue::from_str("pattern"),
                &JsValue::from(subject_pattern_to_wasm(pattern)),
            )
            .unwrap_or_default();
            arr.push(&obj);
        }
        arr
    }

    // --- Graph-native queries ---

    /// Get the source node of a relationship. Returns undefined if not found.
    #[wasm_bindgen(js_name = source)]
    pub fn source(&self, rel_id: &str) -> Option<WasmPattern> {
        self.inner
            .source(&Symbol(rel_id.to_string()))
            .map(subject_pattern_to_wasm)
    }

    /// Get the target node of a relationship. Returns undefined if not found.
    #[wasm_bindgen(js_name = target)]
    pub fn target(&self, rel_id: &str) -> Option<WasmPattern> {
        self.inner
            .target(&Symbol(rel_id.to_string()))
            .map(subject_pattern_to_wasm)
    }

    /// Get all neighbor nodes of a node (both directions).
    #[wasm_bindgen(js_name = neighbors)]
    pub fn neighbors(&self, node_id: &str) -> js_sys::Array {
        let neighbors = self.inner.neighbors(&Symbol(node_id.to_string()));
        patterns_to_js_array(&neighbors.into_iter().cloned().collect::<Vec<_>>())
    }

    /// Get the degree of a node (number of incident relationships, both directions).
    #[wasm_bindgen(js_name = degree)]
    pub fn degree(&self, node_id: &str) -> usize {
        self.inner.degree(&Symbol(node_id.to_string()))
    }

    // --- Escape hatches (T037-T038) ---

    /// Convert to NativePatternGraph.
    #[wasm_bindgen(js_name = asPatternGraph)]
    pub fn as_pattern_graph(&self) -> WasmPatternGraph {
        let pg = self.inner.as_pattern_graph();
        WasmPatternGraph {
            inner: std::rc::Rc::new(PatternGraph {
                pg_nodes: pg.pg_nodes.clone(),
                pg_relationships: pg.pg_relationships.clone(),
                pg_walks: pg.pg_walks.clone(),
                pg_annotations: pg.pg_annotations.clone(),
                pg_other: pg.pg_other.clone(),
                pg_conflicts: pg.pg_conflicts.clone(),
            }),
        }
    }

    /// Convert to NativeGraphQuery.
    #[wasm_bindgen(js_name = asQuery)]
    pub fn as_query(&self) -> WasmGraphQuery {
        WasmGraphQuery {
            inner: self.inner.as_query(),
        }
    }
}

// ============================================================================
// SubjectBuilder WASM Bindings (T029, T031)
// ============================================================================

/// Fluent Subject builder for WASM/TypeScript.
///
/// Created via `Subject.build(identity)`. Chain `.label()` and `.property()` calls,
/// then finalize with `.done()`.
///
/// # Example (JavaScript)
/// ```javascript
/// const subject = Subject.build("alice")
///   .label("Person")
///   .property("name", "Alice")
///   .done();
/// ```
#[wasm_bindgen]
pub struct WasmSubjectBuilder {
    #[wasm_bindgen(skip)]
    identity: String,
    #[wasm_bindgen(skip)]
    labels: Vec<String>,
    #[wasm_bindgen(skip)]
    properties: HashMap<String, Value>,
}

#[wasm_bindgen]
impl WasmSubjectBuilder {
    /// Add a label. Returns `this` for chaining.
    #[wasm_bindgen(js_name = label)]
    pub fn label(&mut self, label: &str) {
        self.labels.push(label.to_string());
    }

    /// Add a property. Returns `this` for chaining.
    #[wasm_bindgen(js_name = property)]
    pub fn property(&mut self, key: &str, value: JsValue) -> Result<(), JsValue> {
        let rust_value = js_to_value(&value).map_err(|e| JsValue::from_str(&e))?;
        self.properties.insert(key.to_string(), rust_value);
        Ok(())
    }

    /// Finalize the builder and return a Subject.
    #[wasm_bindgen(js_name = done)]
    pub fn done(&self) -> WasmSubject {
        WasmSubject::from_subject(Subject {
            identity: Symbol(self.identity.clone()),
            labels: self.labels.iter().cloned().collect(),
            properties: self.properties.clone(),
        })
    }
}

/// Add `build` static method to Subject (T031).
#[wasm_bindgen]
impl WasmSubject {
    /// Create an identity-only Subject with no labels or properties.
    ///
    /// Use as a lightweight reference when calling methods that accept a `Subject`
    /// but only need the identity (e.g., `addRelationship` source/target args).
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// g.addRelationship(rel, Subject.fromId("alice"), Subject.fromId("bob"));
    /// ```
    #[wasm_bindgen(js_name = fromId)]
    pub fn from_id(identity: &str) -> WasmSubject {
        WasmSubject::from_subject(Subject::from_id(identity))
    }

    /// Create a SubjectBuilder for fluent subject construction.
    ///
    /// # Example (JavaScript)
    /// ```javascript
    /// const subject = Subject.build("alice").label("Person").done();
    /// ```
    #[wasm_bindgen(js_name = build)]
    pub fn build(identity: &str) -> WasmSubjectBuilder {
        WasmSubjectBuilder {
            identity: identity.to_string(),
            labels: Vec::new(),
            properties: HashMap::new(),
        }
    }
}