tsrun 0.1.23

A TypeScript interpreter designed for embedding in applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
//! JavaScript value representation.
//!
//! This module contains [`JsValue`], the core type representing JavaScript values at runtime.
//!
//! # JsValue Variants
//!
//! | Variant | JS Type | Example |
//! |---------|---------|---------|
//! | `Undefined` | `undefined` | `undefined` |
//! | `Null` | `null` | `null` |
//! | `Boolean` | `boolean` | `true`, `false` |
//! | `Number` | `number` | `42`, `3.14`, `NaN` |
//! | `String` | `string` | `"hello"` |
//! | `Symbol` | `symbol` | `Symbol("desc")` |
//! | `Object` | `object`/`function` | `{}`, `[]`, `function(){}` |
//!
//! # Creating Values
//!
//! ```
//! use tsrun::JsValue;
//!
//! // From primitives
//! let num: JsValue = 42.into();
//! let text: JsValue = "hello".into();
//! let flag: JsValue = true.into();
//!
//! // Type checking
//! assert!(num.is_number());
//! assert!(text.is_string());
//! assert!(flag.is_boolean());
//!
//! // Value extraction
//! assert_eq!(num.as_number(), Some(42.0));
//! assert_eq!(text.as_str(), Some("hello"));
//! assert_eq!(flag.as_bool(), Some(true));
//! ```
//!
//! # Nullish Values
//!
//! ```
//! use tsrun::JsValue;
//!
//! assert!(JsValue::Undefined.is_nullish());
//! assert!(JsValue::Null.is_nullish());
//! assert!(!JsValue::from(0).is_nullish()); // 0 is not nullish
//! ```

use crate::platform::CompiledRegex;
use crate::prelude::*;

/// Convert a JavaScript number to its canonical string representation.
///
/// According to ECMAScript spec (7.1.12.1 NumberToString):
/// - Very small numbers (< 1e-6) use exponential notation
/// - Very large numbers (>= 1e21) use exponential notation
/// - Otherwise use decimal notation
/// - Integer values are printed without decimal point
pub fn number_to_string(n: f64) -> String {
    if n.is_nan() {
        return "NaN".to_string();
    }
    if n.is_infinite() {
        return if n > 0.0 {
            "Infinity".to_string()
        } else {
            "-Infinity".to_string()
        };
    }
    if n == 0.0 {
        return "0".to_string();
    }

    let abs_n = n.abs();

    // Check if it's an integer that can be represented exactly
    if math::trunc(n) == n && abs_n < 1e21 {
        // Format as integer (no decimal point)
        return format!("{:.0}", n);
    }

    // Very small numbers (absolute value < 1e-6) use exponential notation
    // Very large numbers (absolute value >= 1e21) use exponential notation
    if !(1e-6..1e21).contains(&abs_n) {
        // Use exponential notation
        format_exponential(n)
    } else {
        // Use decimal notation
        // We need to produce the shortest representation that round-trips
        format_decimal(n)
    }
}

/// Format a number in exponential notation matching JavaScript's output
fn format_exponential(n: f64) -> String {
    // Get the exponent
    let abs_n = n.abs();
    let exponent = math::floor(math::log10(abs_n)) as i32;
    let mantissa = n / math::powi(10_f64, exponent);

    // Format mantissa - remove trailing zeros after decimal point
    let mantissa_str = if math::trunc(mantissa) == mantissa {
        format!("{:.0}", mantissa)
    } else {
        let s = format!("{}", mantissa);
        // Remove trailing zeros but keep at least one digit after decimal
        s.trim_end_matches('0').to_string()
    };

    // Format exponent with sign
    if exponent >= 0 {
        format!("{}e+{}", mantissa_str, exponent)
    } else {
        format!("{}e{}", mantissa_str, exponent)
    }
}

/// Format a number in decimal notation matching JavaScript's output
fn format_decimal(n: f64) -> String {
    // Use Rust's default formatting which handles most cases
    let s = format!("{}", n);

    // Remove trailing zeros after decimal point (but keep at least one digit)
    if s.contains('.') {
        let trimmed = s.trim_end_matches('0');
        if trimmed.ends_with('.') {
            format!("{}0", trimmed)
        } else {
            trimmed.to_string()
        }
    } else {
        s
    }
}

/// Convert a JavaScript string to a number according to ECMAScript ToNumber.
///
/// The string is first trimmed of leading and trailing whitespace.
/// Then it is parsed as a numeric literal:
/// - Empty string → 0
/// - "Infinity", "+Infinity", "-Infinity" → Infinity, +Infinity, -Infinity
/// - "0x" or "0X" prefix → hexadecimal
/// - "0o" or "0O" prefix → octal
/// - "0b" or "0B" prefix → binary
/// - Otherwise → decimal (with optional sign, exponent)
/// - Invalid → NaN
pub fn string_to_number(s: &str) -> f64 {
    // ECMAScript whitespace includes more than just ASCII whitespace
    // Trim using a custom function that matches JS behavior
    let trimmed = trim_js_whitespace(s);

    // Empty string → 0
    if trimmed.is_empty() {
        return 0.0;
    }

    // Handle Infinity (case-sensitive)
    if trimmed == "Infinity" || trimmed == "+Infinity" {
        return f64::INFINITY;
    }
    if trimmed == "-Infinity" {
        return f64::NEG_INFINITY;
    }

    // Check for hex/octal/binary prefixes (case-insensitive)
    if trimmed.len() >= 2 {
        let bytes = trimmed.as_bytes();
        if bytes.first() == Some(&b'0') {
            match bytes.get(1) {
                Some(b'x' | b'X') => {
                    // Hexadecimal: 0x...
                    let hex_part = trimmed.get(2..).unwrap_or("");
                    if hex_part.is_empty() {
                        return f64::NAN;
                    }
                    return match u64::from_str_radix(hex_part, 16) {
                        Ok(n) => n as f64,
                        Err(_) => f64::NAN,
                    };
                }
                Some(b'o' | b'O') => {
                    // Octal: 0o...
                    let oct_part = trimmed.get(2..).unwrap_or("");
                    if oct_part.is_empty() {
                        return f64::NAN;
                    }
                    return match u64::from_str_radix(oct_part, 8) {
                        Ok(n) => n as f64,
                        Err(_) => f64::NAN,
                    };
                }
                Some(b'b' | b'B') => {
                    // Binary: 0b...
                    let bin_part = trimmed.get(2..).unwrap_or("");
                    if bin_part.is_empty() {
                        return f64::NAN;
                    }
                    return match u64::from_str_radix(bin_part, 2) {
                        Ok(n) => n as f64,
                        Err(_) => f64::NAN,
                    };
                }
                _ => {}
            }
        }
    }

    // Reject case-insensitive infinity variants (Rust accepts them, JS doesn't)
    // We already handled "Infinity", "+Infinity", "-Infinity" above
    let lower = trimmed.to_lowercase();
    if lower.contains("infinity") || lower.contains("inf") {
        return f64::NAN;
    }

    // Reject NaN (Rust accepts "NaN", "nan", etc., but JS Number() returns NaN for all)
    // This is subtle: JS parses the string "NaN" as NaN, but so does Rust, so this is fine.
    // Actually, we need to check if it's a non-standard casing
    if lower == "nan" && trimmed != "NaN" {
        // Non-standard casing of NaN - return NaN (which is correct anyway)
        return f64::NAN;
    }

    // Try to parse as a decimal number
    // Rust's parse::<f64> handles most cases, but we need to ensure
    // the entire string is consumed and matches JS semantics
    trimmed.parse::<f64>().unwrap_or(f64::NAN)
}

/// Trim JavaScript whitespace from both ends of a string.
/// JavaScript whitespace includes:
/// - ASCII whitespace: space, tab, LF, CR, form feed, vertical tab
/// - Unicode: no-break space (00A0), BOM (FEFF), line separator (2028), paragraph separator (2029)
/// - And other Unicode space separators
fn trim_js_whitespace(s: &str) -> &str {
    fn is_js_whitespace(c: char) -> bool {
        matches!(
            c,
            ' ' | '\t'
                | '\n'
                | '\r'
                | '\x0B'
                | '\x0C'
                | '\u{00A0}'
                | '\u{FEFF}'
                | '\u{2028}'
                | '\u{2029}'
                | '\u{1680}'
                | '\u{2000}'
                | '\u{2001}'
                | '\u{2002}'
                | '\u{2003}'
                | '\u{2004}'
                | '\u{2005}'
                | '\u{2006}'
                | '\u{2007}'
                | '\u{2008}'
                | '\u{2009}'
                | '\u{200A}'
                | '\u{202F}'
                | '\u{205F}'
                | '\u{3000}'
        )
    }

    s.trim_matches(is_js_whitespace)
}

use crate::ast::{BlockStatement, FunctionParam};
use crate::error::JsError;
use crate::gc::{Gc, GcPtr, Guard, Heap, Reset, Traceable};

/// Trait for types that have cheap (O(1), reference-counted) clones.
///
/// This trait makes it explicit when a clone is cheap (just incrementing a reference count)
/// vs when it might be expensive (copying data). Types implementing this trait should have
/// O(1) clone operations, typically because they use `Rc` or similar reference counting.
///
/// # Examples
/// - `JsObjectRef` (Rc<RefCell<JsObject>>) - cheap clone
/// - `JsString` (Rc<str>) - cheap clone
/// - `Environment` (contains Rc) - cheap clone
///
/// Regular `.clone()` should still work but requires a comment explaining why the clone
/// is necessary when the type doesn't implement `CheapClone`.
pub trait CheapClone: Clone {
    /// Create a cheap (reference-counted) clone of this value.
    ///
    /// This is semantically identical to `clone()` but makes it explicit that
    /// the operation is O(1) and only increments a reference count.
    fn cheap_clone(&self) -> Self {
        self.clone()
    }
}

// Implement CheapClone for Rc-based types (Rc<RefCell<T>> is covered by this)
impl<T: ?Sized> CheapClone for Rc<T> {}
impl<T: CheapClone> CheapClone for Option<T> {}

/// A JavaScript value.
///
/// This is the primary type for representing all JavaScript values in the interpreter.
/// Size-optimized to 16 bytes by boxing the rare Symbol variant.
///
/// # Conversions
///
/// ```
/// use tsrun::JsValue;
///
/// // Numbers
/// let n: JsValue = 42.into();
/// let f: JsValue = 3.14.into();
///
/// // Strings
/// let s: JsValue = "hello".into();
/// let owned: JsValue = String::from("world").into();
///
/// // Booleans
/// let t: JsValue = true.into();
///
/// // Unit converts to undefined
/// let u: JsValue = ().into();
/// assert!(u.is_undefined());
/// ```
///
/// # Type Coercion
///
/// Use `to_boolean()`, `to_number()`, `to_string_value()` for JS coercion:
///
/// ```
/// use tsrun::JsValue;
///
/// // Falsy values
/// assert!(!JsValue::from(0).to_boolean());
/// assert!(!JsValue::from("").to_boolean());
/// assert!(!JsValue::Null.to_boolean());
/// assert!(!JsValue::Undefined.to_boolean());
/// assert!(!JsValue::from(f64::NAN).to_boolean());
///
/// // Truthy values
/// assert!(JsValue::from(1).to_boolean());
/// assert!(JsValue::from("x").to_boolean());
/// ```
#[derive(Clone, Default)]
pub enum JsValue {
    #[default]
    Undefined,
    Null,
    Boolean(bool),
    Number(f64),
    String(JsString),
    Symbol(Box<JsSymbol>),
    Object(JsObjectRef),
}

/// A JsValue bundled with a Guard that keeps it alive.
///
/// IMPORTANT: Access the value through destructuring ONLY to ensure the guard
/// stays alive for the correct duration. See CLAUDE.md for rules.
///
/// The fields are public to allow struct destructuring pattern, which is the
/// ONLY approved way to access the contents.
pub struct Guarded {
    pub value: JsValue,
    pub guard: Option<Guard<JsObject>>,
}

impl fmt::Debug for Guarded {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Guarded")
            .field("value", &self.value)
            .field("guard", &self.guard.as_ref().map(|_| "<guard>"))
            .finish()
    }
}

impl Guarded {
    /// Create a guarded value with a guard.
    /// If the value is a primitive, the guard is dropped and `guard` will be `None`.
    /// NOTE: You must call `value.guard_by(&guard)` before this if the value is an object.
    pub fn with_guard(value: JsValue, guard: Guard<JsObject>) -> Self {
        if matches!(value, JsValue::Object(_)) {
            Self {
                value,
                guard: Some(guard),
            }
        } else {
            // Primitives don't need guarding - drop the guard
            drop(guard);
            Self { value, guard: None }
        }
    }

    /// Create an unguarded value (for primitives or already-owned objects)
    pub fn unguarded(value: JsValue) -> Self {
        Self { value, guard: None }
    }

    /// Create a guarded value for returning from the VM.
    /// Creates a new guard from the heap if the value is an object.
    /// For primitives, returns an unguarded value.
    pub fn from_value(value: JsValue, heap: &Heap<JsObject>) -> Self {
        if let JsValue::Object(obj) = &value {
            let guard = heap.create_guard();
            guard.guard(obj.cheap_clone());
            Self {
                value,
                guard: Some(guard),
            }
        } else {
            Self { value, guard: None }
        }
    }

    /// Return a new value with the same guard (for derived values)
    ///
    /// Use this when you derive a value from a guarded input and want to
    /// propagate the guard to keep the original object alive.
    pub fn with_value(self, value: JsValue) -> Self {
        Self {
            value,
            guard: self.guard,
        }
    }
}

impl JsValue {
    /// Check if this value is null or undefined
    pub fn is_null_or_undefined(&self) -> bool {
        matches!(self, JsValue::Null | JsValue::Undefined)
    }

    /// Check if this value is callable (a function)
    pub fn is_callable(&self) -> bool {
        match self {
            JsValue::Object(obj) => {
                matches!(obj.borrow().exotic, ExoticObject::Function(_))
            }
            _ => false,
        }
    }

    /// Check if this is a string value
    pub fn is_string(&self) -> bool {
        matches!(self, JsValue::String(_))
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // Type Check Methods
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Check if this is undefined
    pub fn is_undefined(&self) -> bool {
        matches!(self, JsValue::Undefined)
    }

    /// Check if this is null
    pub fn is_null(&self) -> bool {
        matches!(self, JsValue::Null)
    }

    /// Check if this is null or undefined (alias for is_null_or_undefined)
    pub fn is_nullish(&self) -> bool {
        matches!(self, JsValue::Null | JsValue::Undefined)
    }

    /// Check if this is a boolean
    pub fn is_boolean(&self) -> bool {
        matches!(self, JsValue::Boolean(_))
    }

    /// Check if this is a number
    pub fn is_number(&self) -> bool {
        matches!(self, JsValue::Number(_))
    }

    /// Check if this is an object
    pub fn is_object(&self) -> bool {
        matches!(self, JsValue::Object(_))
    }

    /// Check if this is a symbol
    pub fn is_symbol(&self) -> bool {
        matches!(self, JsValue::Symbol(_))
    }

    // ═══════════════════════════════════════════════════════════════════════════════
    // Value Extraction Methods
    // ═══════════════════════════════════════════════════════════════════════════════

    /// Returns the boolean value if this is a Boolean, otherwise None
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            JsValue::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    /// Returns the numeric value if this is a Number, otherwise None
    pub fn as_number(&self) -> Option<f64> {
        match self {
            JsValue::Number(n) => Some(*n),
            _ => None,
        }
    }

    /// Returns the string slice if this is a String, otherwise None
    pub fn as_str(&self) -> Option<&str> {
        match self {
            JsValue::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    /// Returns a reference to the JsString if this is a String, otherwise None
    pub fn as_js_string(&self) -> Option<&JsString> {
        match self {
            JsValue::String(s) => Some(s),
            _ => None,
        }
    }

    /// Returns a reference to the object if this is an Object, otherwise None
    pub fn as_object(&self) -> Option<&Gc<JsObject>> {
        match self {
            JsValue::Object(obj) => Some(obj),
            _ => None,
        }
    }

    /// Returns a reference to the symbol if this is a Symbol, otherwise None
    pub fn as_symbol(&self) -> Option<&JsSymbol> {
        match self {
            JsValue::Symbol(s) => Some(s),
            _ => None,
        }
    }

    /// If this value is an object, add it to the guard.
    /// This keeps the object alive as long as the guard exists.
    pub fn guard_by(&self, guard: &Guard<JsObject>) {
        if let JsValue::Object(obj) = self {
            guard.guard(obj.cheap_clone());
        }
    }

    /// Convert to boolean (ToBoolean)
    pub fn to_boolean(&self) -> bool {
        match self {
            JsValue::Undefined | JsValue::Null => false,
            JsValue::Boolean(b) => *b,
            JsValue::Number(n) => *n != 0.0 && !n.is_nan(),
            JsValue::String(s) => !s.is_empty(),
            JsValue::Symbol(_) => true, // Symbols are always truthy
            JsValue::Object(_) => true,
        }
    }

    /// Convert to number (ToNumber)
    pub fn to_number(&self) -> f64 {
        match self {
            JsValue::Undefined => f64::NAN,
            JsValue::Null => 0.0,
            JsValue::Boolean(true) => 1.0,
            JsValue::Boolean(false) => 0.0,
            JsValue::Number(n) => *n,
            JsValue::String(s) => string_to_number(s.as_str()),
            JsValue::Symbol(_) => f64::NAN, // Cannot convert Symbol to number
            JsValue::Object(obj) => {
                // Handle wrapper objects with primitives
                let borrowed = obj.borrow();
                match &borrowed.exotic {
                    ExoticObject::Number(n) => *n,
                    ExoticObject::Boolean(b) => {
                        if *b {
                            1.0
                        } else {
                            0.0
                        }
                    }
                    ExoticObject::StringObj(s) => string_to_number(s.as_str()),
                    _ => f64::NAN, // Other objects would need ToPrimitive
                }
            }
        }
    }

    /// Convert to string (ToString)
    /// Note: Prefer using `Interpreter::to_js_string()` which uses interned strings.
    /// This method is kept for internal use in value.rs, Debug impl, and tests.
    pub fn to_js_string(&self) -> JsString {
        match self {
            JsValue::Undefined => JsString::from("undefined"),
            JsValue::Null => JsString::from("null"),
            JsValue::Boolean(true) => JsString::from("true"),
            JsValue::Boolean(false) => JsString::from("false"),
            JsValue::Number(n) => JsString::from(number_to_string(*n)),
            JsValue::String(s) => s.clone(),
            JsValue::Symbol(s) => {
                // Symbol.prototype.toString returns "Symbol(description)"
                match &s.description {
                    Some(desc) => JsString::from(format!("Symbol({})", desc.as_str())),
                    None => JsString::from("Symbol()"),
                }
            }
            JsValue::Object(obj) => {
                // Check for wrapper objects that have primitive values
                let borrowed = obj.borrow();
                match &borrowed.exotic {
                    ExoticObject::Number(n) => {
                        // Number wrapper - convert the primitive to string
                        JsValue::Number(*n).to_js_string()
                    }
                    ExoticObject::StringObj(s) => {
                        // String wrapper - return the wrapped string
                        s.clone()
                    }
                    ExoticObject::Boolean(b) => {
                        // Boolean wrapper - convert the primitive to string
                        if *b {
                            JsString::from("true")
                        } else {
                            JsString::from("false")
                        }
                    }
                    ExoticObject::Array { elements } => {
                        // Array.prototype.toString joins elements with comma
                        let strings: Vec<String> = elements
                            .iter()
                            .map(|v| {
                                // null and undefined become empty strings in join
                                match v {
                                    JsValue::Null | JsValue::Undefined => String::new(),
                                    _ => v.to_js_string().to_string(),
                                }
                            })
                            .collect();
                        JsString::from(strings.join(","))
                    }
                    _ => JsString::from("[object Object]"),
                }
            }
        }
    }

    /// Strict equality (===)
    pub fn strict_equals(&self, other: &JsValue) -> bool {
        match (self, other) {
            (JsValue::Undefined, JsValue::Undefined) => true,
            (JsValue::Null, JsValue::Null) => true,
            (JsValue::Boolean(a), JsValue::Boolean(b)) => a == b,
            (JsValue::Number(a), JsValue::Number(b)) => {
                // NaN !== NaN
                if a.is_nan() || b.is_nan() {
                    false
                } else {
                    a == b
                }
            }
            (JsValue::String(a), JsValue::String(b)) => a == b,
            (JsValue::Symbol(a), JsValue::Symbol(b)) => a == b, // Symbols compare by id
            (JsValue::Object(a), JsValue::Object(b)) => Gc::ptr_eq(a, b),
            _ => false,
        }
    }
}

/// Helper function for Debug impl to format a value as a string (without using to_js_string)
fn format_value_for_debug(value: &JsValue) -> String {
    match value {
        JsValue::Undefined => "undefined".to_string(),
        JsValue::Null => "null".to_string(),
        JsValue::Boolean(b) => {
            if *b {
                "true".to_string()
            } else {
                "false".to_string()
            }
        }
        JsValue::Number(n) => number_to_string(*n),
        JsValue::String(s) => s.to_string(),
        JsValue::Symbol(_) => "Symbol()".to_string(),
        JsValue::Object(_) => "[object Object]".to_string(),
    }
}

impl fmt::Display for JsValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JsValue::Undefined => write!(f, "undefined"),
            JsValue::Null => write!(f, "null"),
            JsValue::Boolean(b) => write!(f, "{}", b),
            JsValue::Number(n) => write!(f, "{}", number_to_string(*n)),
            JsValue::String(s) => write!(f, "{}", s.as_str()),
            JsValue::Symbol(s) => match &s.description {
                Some(desc) => write!(f, "Symbol({})", desc.as_str()),
                None => write!(f, "Symbol()"),
            },
            JsValue::Object(_) => write!(f, "[object Object]"),
        }
    }
}

impl fmt::Debug for JsValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JsValue::Undefined => write!(f, "undefined"),
            JsValue::Null => write!(f, "null"),
            JsValue::Boolean(b) => write!(f, "{}", b),
            JsValue::Number(n) => write!(f, "{}", n),
            JsValue::String(s) => write!(f, "\"{}\"", s.as_ref()),
            JsValue::Symbol(s) => match &s.description {
                Some(desc) => write!(f, "Symbol({})", desc.as_str()),
                None => write!(f, "Symbol()"),
            },
            JsValue::Object(obj) => {
                let obj = obj.borrow();
                match &obj.exotic {
                    ExoticObject::Ordinary => {
                        // Check if this is an Error object (has name and message properties)
                        let name_key = PropertyKey::String(JsString::from("name"));
                        let message_key = PropertyKey::String(JsString::from("message"));

                        if let (Some(name_prop), Some(message_prop)) = (
                            obj.properties.get(&name_key),
                            obj.properties.get(&message_key),
                        ) {
                            let name = format_value_for_debug(&name_prop.value);
                            let msg = format_value_for_debug(&message_prop.value);
                            write!(f, "{}: {}", name, msg)
                        } else {
                            write!(f, "{{...}}")
                        }
                    }
                    ExoticObject::Array { .. } => write!(f, "[...]"),
                    ExoticObject::Function(func) => {
                        let name = func.name().unwrap_or("anonymous");
                        write!(f, "[Function: {}]", name)
                    }
                    ExoticObject::Map { entries } => write!(f, "Map({})", entries.len()),
                    ExoticObject::Set { entries } => write!(f, "Set({})", entries.len()),
                    ExoticObject::Date { timestamp } => write!(f, "Date({})", timestamp),
                    ExoticObject::RegExp { pattern, flags, .. } => {
                        write!(f, "/{}/{}", pattern, flags)
                    }
                    ExoticObject::Generator(_) => write!(f, "[object Generator]"),
                    ExoticObject::BytecodeGenerator(_) => write!(f, "[object Generator]"),
                    ExoticObject::Promise(state) => {
                        let status = match state.borrow().status {
                            PromiseStatus::Pending => "pending",
                            PromiseStatus::Fulfilled => "fulfilled",
                            PromiseStatus::Rejected => "rejected",
                        };
                        write!(f, "Promise {{{}}}", status)
                    }
                    ExoticObject::Environment(env_data) => {
                        write!(f, "[Environment {} bindings]", env_data.bindings.len())
                    }
                    ExoticObject::Enum(data) => {
                        write!(f, "enum {}", data.name)
                    }
                    ExoticObject::Proxy(proxy_data) => {
                        if proxy_data.revoked {
                            write!(f, "[Proxy (revoked)]")
                        } else {
                            write!(f, "[Proxy]")
                        }
                    }
                    ExoticObject::Boolean(b) => write!(f, "[Boolean: {}]", b),
                    ExoticObject::Number(n) => write!(f, "[Number: {}]", n),
                    ExoticObject::StringObj(s) => write!(f, "[String: \"{}\"]", s),
                    ExoticObject::Symbol(sym) => match &sym.description {
                        Some(desc) => write!(f, "[Symbol: Symbol({})]", desc.as_str()),
                        None => write!(f, "[Symbol: Symbol()]"),
                    },
                    ExoticObject::RawJSON(raw) => write!(f, "[RawJSON: {}]", raw),
                    ExoticObject::PendingOrder { id, .. } => write!(f, "[PendingOrder: {}]", id),
                }
            }
        }
    }
}

impl PartialEq for JsValue {
    fn eq(&self, other: &Self) -> bool {
        self.strict_equals(other)
    }
}

// Conversions from Rust types

impl From<bool> for JsValue {
    fn from(b: bool) -> Self {
        JsValue::Boolean(b)
    }
}

impl From<f64> for JsValue {
    fn from(n: f64) -> Self {
        JsValue::Number(n)
    }
}

impl From<i32> for JsValue {
    fn from(n: i32) -> Self {
        JsValue::Number(n as f64)
    }
}

impl From<i64> for JsValue {
    fn from(n: i64) -> Self {
        JsValue::Number(n as f64)
    }
}

impl From<u32> for JsValue {
    fn from(n: u32) -> Self {
        JsValue::Number(n as f64)
    }
}

impl From<u64> for JsValue {
    fn from(n: u64) -> Self {
        JsValue::Number(n as f64)
    }
}

impl From<usize> for JsValue {
    fn from(n: usize) -> Self {
        JsValue::Number(n as f64)
    }
}

impl From<()> for JsValue {
    fn from(_: ()) -> Self {
        JsValue::Undefined
    }
}

impl From<&str> for JsValue {
    fn from(s: &str) -> Self {
        JsValue::String(JsString::from(s))
    }
}

impl From<String> for JsValue {
    fn from(s: String) -> Self {
        JsValue::String(JsString::from(s))
    }
}

impl From<JsString> for JsValue {
    fn from(s: JsString) -> Self {
        JsValue::String(s)
    }
}

impl JsValue {
    /// Returns a string describing the type of this value
    pub fn type_name(&self) -> &'static str {
        match self {
            JsValue::Undefined => "undefined",
            JsValue::Null => "null",
            JsValue::Boolean(_) => "boolean",
            JsValue::Number(_) => "number",
            JsValue::String(_) => "string",
            JsValue::Symbol(_) => "symbol",
            JsValue::Object(_) => "object",
        }
    }
}

/// Reference-counted string for efficient string handling
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct JsString(Rc<str>);

/// A key for variable lookups that uses pointer-based hashing.
///
/// This wrapper around JsString uses the pointer address for hashing and equality,
/// which is O(1) instead of O(n) for content-based hashing. This is safe because
/// all variable names are interned through StringDict, so identical names share
/// the same Rc allocation.
///
/// WARNING: Only use this for interned strings! Using non-interned strings will
/// cause incorrect lookups (two equal strings might not be found).
#[derive(Clone)]
pub struct VarKey(pub JsString);

impl Hash for VarKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Hash the pointer address, not the content
        // Use the data pointer from the fat pointer (Rc<str> is a fat pointer)
        let ptr = Rc::as_ptr(&self.0.0) as *const () as usize;
        ptr.hash(state);
    }
}

impl PartialEq for VarKey {
    fn eq(&self, other: &Self) -> bool {
        // Compare pointer addresses, not content
        Rc::ptr_eq(&self.0.0, &other.0.0)
    }
}

impl Eq for VarKey {}

impl fmt::Debug for VarKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "VarKey({:?})", self.0)
    }
}

impl fmt::Display for VarKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<JsString> for VarKey {
    fn from(s: JsString) -> Self {
        VarKey(s)
    }
}

/// Unique identifier for a private field/method.
///
/// Private fields in JavaScript are "branded" - two classes can both have
/// a field named `#x`, but they are different fields. Each class gets a unique
/// ClassBrandId, and a PrivateFieldKey combines this with the field name.
pub type ClassBrandId = u32;

/// Key for looking up private fields in an object.
///
/// This combines a class brand (unique per class definition) with the field name.
/// The field_name includes the # prefix (e.g., "#count").
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PrivateFieldKey {
    /// Unique identifier for the class that defined this private field
    pub class_brand: ClassBrandId,
    /// The private field name (including # prefix)
    pub field_name: JsString,
}

impl PrivateFieldKey {
    pub fn new(class_brand: ClassBrandId, field_name: JsString) -> Self {
        Self {
            class_brand,
            field_name,
        }
    }
}

// JsString wraps Rc<str>, so clone is cheap (just reference count increment)
impl CheapClone for JsString {}

impl JsString {
    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn parse<F: core::str::FromStr>(&self) -> Result<F, F::Err> {
        self.0.parse()
    }
}

impl AsRef<str> for JsString {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl core::borrow::Borrow<str> for JsString {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for JsString {
    fn eq(&self, other: &str) -> bool {
        self.0.as_ref() == other
    }
}

impl PartialEq<&str> for JsString {
    fn eq(&self, other: &&str) -> bool {
        self.0.as_ref() == *other
    }
}

impl From<&str> for JsString {
    fn from(s: &str) -> Self {
        JsString(s.into())
    }
}

impl From<String> for JsString {
    fn from(s: String) -> Self {
        JsString(s.into())
    }
}

impl fmt::Debug for JsString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"{}\"", self.0)
    }
}

impl fmt::Display for JsString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl core::ops::Add<&str> for JsString {
    type Output = JsString;

    fn add(self, other: &str) -> JsString {
        let mut s = String::from(&*self.0);
        s.push_str(other);
        JsString::from(s)
    }
}

impl core::ops::Add<&JsString> for JsString {
    type Output = JsString;

    fn add(self, other: &JsString) -> JsString {
        let mut s = String::from(&*self.0);
        s.push_str(&other.0);
        JsString::from(s)
    }
}

/// JavaScript Symbol primitive
/// Symbols are unique identifiers, optionally with a description
#[derive(Clone, Debug)]
pub struct JsSymbol {
    /// Unique identifier for this symbol
    id: u64,
    /// Optional description (from Symbol('description'))
    pub description: Option<JsString>,
}

impl JsSymbol {
    /// Create a new unique symbol with an optional description
    pub fn new(id: u64, description: Option<JsString>) -> Self {
        Self { id, description }
    }

    /// Get the symbol's unique ID
    pub fn id(&self) -> u64 {
        self.id
    }
}

impl PartialEq for JsSymbol {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Eq for JsSymbol {}

impl Hash for JsSymbol {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

/// Reference to a heap-allocated object (GC-managed)
///
/// This is now `Gc<JsObject>` which gives us `Ref<'_, JsObject>` directly
/// from `borrow()` calls, matching the old `Rc<RefCell<JsObject>>` API.
pub type JsObjectRef = Gc<JsObject>;

// Implement CheapClone for Gc<T> (clone is just Copy)
impl<T: Default + Reset + Traceable> CheapClone for Gc<T> {}

/// Reset implementation for JsObject - used by new GC for object pooling.
///
/// When an object is collected, it can be reset and reused instead of
/// being dropped. This is more efficient than allocating new objects.
impl Reset for JsObject {
    fn reset(&mut self) {
        self.prototype = None;
        self.extensible = true;
        self.frozen = false;
        self.sealed = false;
        self.null_prototype = false;
        // clear() preserves capacity, avoiding reallocation for reused objects
        self.properties.clear();
        self.exotic = ExoticObject::Ordinary;
        self.private_fields = None;
    }
}

impl Traceable for JsObject {
    fn trace<F: FnMut(GcPtr<Self>)>(&self, mut visitor: F) {
        // Trace prototype - use copy_ref to avoid incrementing ref_count during tracing
        if let Some(proto) = &self.prototype {
            visitor(proto.copy_ref());
        }

        // Trace properties (both data values and accessor functions)
        for prop in self.properties.values() {
            if let JsValue::Object(obj) = &prop.value {
                visitor(obj.copy_ref());
            }
            // Trace accessor getter/setter functions
            if let Some(accessor) = &prop.accessor {
                if let Some(getter) = &accessor.getter {
                    visitor(getter.copy_ref());
                }
                if let Some(setter) = &accessor.setter {
                    visitor(setter.copy_ref());
                }
            }
        }

        // Trace exotic object references
        match &self.exotic {
            ExoticObject::Function(func) => {
                match func {
                    JsFunction::Bound(bound) => {
                        visitor(bound.target.copy_ref());
                        if let JsValue::Object(obj) = &bound.this_arg {
                            visitor(obj.copy_ref());
                        }
                        for arg in &bound.bound_args {
                            if let JsValue::Object(obj) = arg {
                                visitor(obj.copy_ref());
                            }
                        }
                    }
                    JsFunction::PromiseResolve(promise) | JsFunction::PromiseReject(promise) => {
                        visitor(promise.copy_ref());
                    }
                    JsFunction::PromiseAllFulfill { state, .. } => {
                        // Trace the result promise and all results
                        visitor(state.result_promise.copy_ref());
                        for result in state.results.borrow().iter() {
                            if let JsValue::Object(obj) = result {
                                visitor(obj.copy_ref());
                            }
                        }
                    }
                    JsFunction::PromiseAllReject(state) => {
                        // Trace the result promise and all results
                        visitor(state.result_promise.copy_ref());
                        for result in state.results.borrow().iter() {
                            if let JsValue::Object(obj) = result {
                                visitor(obj.copy_ref());
                            }
                        }
                    }
                    JsFunction::PromiseRaceSettle { state, .. } => {
                        // Trace the result promise
                        visitor(state.result_promise.copy_ref());
                    }
                    JsFunction::Bytecode(bc)
                    | JsFunction::BytecodeGenerator(bc)
                    | JsFunction::BytecodeAsync(bc)
                    | JsFunction::BytecodeAsyncGenerator(bc) => {
                        // Trace the closure environment
                        visitor(bc.closure.copy_ref());
                        // Trace captured this (for arrow functions)
                        if let Some(this) = &bc.captured_this
                            && let JsValue::Object(obj) = this.as_ref()
                        {
                            visitor(obj.copy_ref());
                        }
                    }
                    JsFunction::ModuleExportGetter { module_env, .. } => {
                        // Trace the module environment for live bindings
                        visitor(module_env.copy_ref());
                    }
                    JsFunction::ModuleReExportGetter { source_module, .. } => {
                        // Trace the source module for re-export live bindings
                        visitor(source_module.copy_ref());
                    }
                    JsFunction::ProxyRevoke(proxy) => {
                        // Trace the associated proxy object
                        visitor(proxy.copy_ref());
                    }
                    JsFunction::Native(_)
                    | JsFunction::AccessorGetter
                    | JsFunction::AccessorSetter => {}
                }
            }
            ExoticObject::Map { entries } => {
                for (k, v) in entries {
                    if let JsValue::Object(obj) = &k.0 {
                        visitor(obj.copy_ref());
                    }
                    if let JsValue::Object(obj) = v {
                        visitor(obj.copy_ref());
                    }
                }
            }
            ExoticObject::Set { entries } => {
                for entry in entries {
                    if let JsValue::Object(obj) = &entry.0 {
                        visitor(obj.copy_ref());
                    }
                }
            }
            ExoticObject::Promise(state) => {
                let state = state.borrow();
                if let Some(JsValue::Object(obj)) = &state.result {
                    visitor(obj.copy_ref());
                }
                for handler in &state.handlers {
                    if let Some(JsValue::Object(obj)) = &handler.on_fulfilled {
                        visitor(obj.copy_ref());
                    }
                    if let Some(JsValue::Object(obj)) = &handler.on_rejected {
                        visitor(obj.copy_ref());
                    }
                    visitor(handler.result_promise.copy_ref());
                }
            }
            ExoticObject::Generator(state) => {
                let state = state.borrow();
                // Trace closure environment
                visitor(state.closure.copy_ref());
                // Trace arguments that might be objects
                for arg in &state.args {
                    if let JsValue::Object(obj) = arg {
                        visitor(obj.copy_ref());
                    }
                }
                // Trace sent value if it's an object
                if let JsValue::Object(obj) = &state.sent_value {
                    visitor(obj.copy_ref());
                }
            }
            ExoticObject::BytecodeGenerator(state) => {
                let state = state.borrow();
                // Trace closure environment
                visitor(state.closure.copy_ref());
                // Trace arguments
                for arg in &state.args {
                    if let JsValue::Object(obj) = arg {
                        visitor(obj.copy_ref());
                    }
                }
                // Trace this_value if it's an object
                if let JsValue::Object(obj) = &state.this_value {
                    visitor(obj.copy_ref());
                }
                // Trace saved register values
                for reg in &state.saved_registers {
                    if let JsValue::Object(obj) = reg {
                        visitor(obj.copy_ref());
                    }
                }
                // Trace sent value if it's an object
                if let JsValue::Object(obj) = &state.sent_value {
                    visitor(obj.copy_ref());
                }
                // Trace function environment
                if let Some(env) = &state.func_env {
                    visitor(env.copy_ref());
                }
                // Trace current environment at yield point
                if let Some(env) = &state.current_env {
                    visitor(env.copy_ref());
                }
                // Trace delegated iterator for yield*
                if let Some((iter_obj, next_method)) = &state.delegated_iterator {
                    visitor(iter_obj.copy_ref());
                    if let JsValue::Object(obj) = next_method {
                        visitor(obj.copy_ref());
                    }
                }
                // Trace throw value for generator.throw()
                if let Some(JsValue::Object(obj)) = &state.throw_value {
                    visitor(obj.copy_ref());
                }
            }
            ExoticObject::Environment(env_data) => {
                // Trace all bindings in the environment
                for binding in env_data.bindings.values() {
                    if let JsValue::Object(obj) = &binding.value {
                        visitor(obj.copy_ref());
                    }
                }
                // Trace outer environment if any
                if let Some(outer) = &env_data.outer {
                    visitor(outer.copy_ref());
                }
            }
            ExoticObject::Array { elements } => {
                // Trace all array elements that are objects
                for elem in elements {
                    if let JsValue::Object(obj) = elem {
                        visitor(obj.copy_ref());
                    }
                }
            }
            ExoticObject::Ordinary
            | ExoticObject::Date { .. }
            | ExoticObject::RegExp { .. }
            | ExoticObject::Enum(_)
            | ExoticObject::Boolean(_)
            | ExoticObject::Number(_)
            | ExoticObject::StringObj(_)
            | ExoticObject::Symbol(_)
            | ExoticObject::RawJSON(_)
            | ExoticObject::PendingOrder { .. } => {
                // These exotic types don't contain object references that need tracing
            }
            ExoticObject::Proxy(proxy_data) => {
                // Trace target and handler objects
                visitor(proxy_data.target.copy_ref());
                visitor(proxy_data.handler.copy_ref());
            }
        }

        // Trace private fields (may contain object references)
        if let Some(private_fields) = &self.private_fields {
            for value in private_fields.values() {
                if let JsValue::Object(obj) = value {
                    visitor(obj.copy_ref());
                }
            }
        }
    }
}

/// A JavaScript object
#[derive(Debug)]
pub struct JsObject {
    /// Prototype link
    pub prototype: Option<JsObjectRef>,
    /// Whether the object can have properties added
    pub extensible: bool,
    /// Whether the object is frozen (no modifications allowed)
    pub frozen: bool,
    /// Whether the object is sealed (no new properties, but existing can be modified)
    pub sealed: bool,
    /// Whether this object was explicitly created with null prototype (Object.create(null))
    pub null_prototype: bool,
    /// Object properties (optimized for small objects)
    pub properties: PropertyStorage,
    /// Exotic object behavior
    pub exotic: ExoticObject,
    /// Private fields storage (only used by instances of classes with private members)
    /// Key is (ClassBrandId, field_name), value is the private field/method value
    pub private_fields: Option<FxHashMap<PrivateFieldKey, JsValue>>,
}

impl JsObject {
    /// Create a new ordinary object
    pub fn new() -> Self {
        Self {
            prototype: None,
            extensible: true,
            frozen: false,
            sealed: false,
            null_prototype: false,
            properties: PropertyStorage::new(),
            exotic: ExoticObject::Ordinary,
            private_fields: None,
        }
    }

    /// Create a new ordinary object with pre-allocated property capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            prototype: None,
            extensible: true,
            frozen: false,
            sealed: false,
            null_prototype: false,
            properties: PropertyStorage::with_capacity(capacity),
            exotic: ExoticObject::Ordinary,
            private_fields: None,
        }
    }

    /// Create a new ordinary object with a prototype
    pub fn with_prototype(prototype: JsObjectRef) -> Self {
        Self {
            prototype: Some(prototype),
            extensible: true,
            frozen: false,
            sealed: false,
            null_prototype: false,
            properties: PropertyStorage::new(),
            exotic: ExoticObject::Ordinary,
            private_fields: None,
        }
    }

    /// Get a private field value
    pub fn get_private_field(&self, key: &PrivateFieldKey) -> Option<&JsValue> {
        self.private_fields.as_ref().and_then(|pf| pf.get(key))
    }

    /// Set a private field value
    pub fn set_private_field(&mut self, key: PrivateFieldKey, value: JsValue) {
        self.private_fields
            .get_or_insert_with(FxHashMap::default)
            .insert(key, value);
    }

    /// Check if an object has a specific private field
    pub fn has_private_field(&self, key: &PrivateFieldKey) -> bool {
        self.private_fields
            .as_ref()
            .is_some_and(|pf| pf.contains_key(key))
    }

    /// Check if this object is callable
    pub fn is_callable(&self) -> bool {
        match &self.exotic {
            ExoticObject::Function(_) => true,
            ExoticObject::Proxy(data) => {
                // A proxy is callable if its target is callable
                !data.revoked && data.target.borrow().is_callable()
            }
            _ => false,
        }
    }

    /// Get an own property
    pub fn get_own_property(&self, key: &PropertyKey) -> Option<&Property> {
        self.properties.get(key)
    }

    /// Get a property, searching the prototype chain
    pub fn get_property(&self, key: &PropertyKey) -> Option<JsValue> {
        // For arrays, handle index access and length from elements Vec
        if let ExoticObject::Array { ref elements } = self.exotic {
            match key {
                PropertyKey::Index(idx) => {
                    return elements.get(*idx as usize).cloned();
                }
                PropertyKey::String(s) if s.as_str() == "length" => {
                    return Some(JsValue::Number(elements.len() as f64));
                }
                _ => {}
            }
        }

        // For functions, handle name and length properties
        if let ExoticObject::Function(ref func) = self.exotic
            && let PropertyKey::String(s) = key
        {
            match s.as_str() {
                "name" => {
                    // First check if there's an own property (for SetFunctionName override)
                    if let Some(prop) = self.properties.get(key) {
                        return Some(prop.value.clone());
                    }
                    let name = match func {
                        JsFunction::Native(f) => Some(f.name.clone()),
                        JsFunction::Bytecode(bc)
                        | JsFunction::BytecodeGenerator(bc)
                        | JsFunction::BytecodeAsync(bc)
                        | JsFunction::BytecodeAsyncGenerator(bc) => bc
                            .chunk
                            .function_info
                            .as_ref()
                            .and_then(|info| info.name.clone()),
                        JsFunction::Bound(b) => {
                            // Bound functions have name "bound <target name>"
                            if let ExoticObject::Function(target_func) = &b.target.borrow().exotic {
                                match target_func {
                                    JsFunction::Native(f) => {
                                        Some(JsString::from(format!("bound {}", f.name)))
                                    }
                                    JsFunction::Bytecode(bc)
                                    | JsFunction::BytecodeGenerator(bc)
                                    | JsFunction::BytecodeAsync(bc)
                                    | JsFunction::BytecodeAsyncGenerator(bc) => {
                                        bc.chunk.function_info.as_ref().and_then(|info| {
                                            info.name
                                                .as_ref()
                                                .map(|n| JsString::from(format!("bound {}", n)))
                                        })
                                    }
                                    _ => Some(JsString::from("bound ")),
                                }
                            } else {
                                Some(JsString::from("bound "))
                            }
                        }
                        _ => None,
                    };
                    return Some(match name {
                        Some(n) => JsValue::String(n),
                        None => JsValue::String(JsString::from("")),
                    });
                }
                "length" => {
                    let arity = match func {
                        JsFunction::Native(f) => f.arity,
                        JsFunction::Bytecode(bc)
                        | JsFunction::BytecodeGenerator(bc)
                        | JsFunction::BytecodeAsync(bc)
                        | JsFunction::BytecodeAsyncGenerator(bc) => bc
                            .chunk
                            .function_info
                            .as_ref()
                            .map(|info| info.param_count)
                            .unwrap_or(0),
                        JsFunction::Bound(b) => {
                            // Bound functions have length = target.length - bound_args.length (min 0)
                            if let ExoticObject::Function(target_func) = &b.target.borrow().exotic {
                                let target_length = match target_func {
                                    JsFunction::Native(f) => f.arity,
                                    JsFunction::Bytecode(bc)
                                    | JsFunction::BytecodeGenerator(bc)
                                    | JsFunction::BytecodeAsync(bc)
                                    | JsFunction::BytecodeAsyncGenerator(bc) => bc
                                        .chunk
                                        .function_info
                                        .as_ref()
                                        .map(|info| info.param_count)
                                        .unwrap_or(0),
                                    _ => 0,
                                };
                                target_length.saturating_sub(b.bound_args.len())
                            } else {
                                0
                            }
                        }
                        _ => 0,
                    };
                    return Some(JsValue::Number(arity as f64));
                }
                _ => {}
            }
        }

        // For enums, handle member lookups from EnumData
        if let ExoticObject::Enum(ref data) = self.exotic {
            match key {
                PropertyKey::String(s) => {
                    // Forward mapping: member name -> value
                    if let Some(val) = data.get_by_name(s.as_str()) {
                        return Some(val);
                    }
                    // Also check if this is a numeric string for reverse mapping
                    if let Ok(n) = s.as_str().parse::<f64>()
                        && let Some(name) = data.get_by_value(n)
                    {
                        return Some(JsValue::String(name));
                    }
                }
                PropertyKey::Index(idx) => {
                    // Reverse mapping: numeric index -> member name
                    if let Some(name) = data.get_by_value(*idx as f64) {
                        return Some(JsValue::String(name));
                    }
                }
                PropertyKey::Symbol(_) => {}
            }
        }

        if let Some(prop) = self.properties.get(key) {
            return Some(prop.value.clone());
        }

        if let Some(ref proto) = self.prototype {
            return proto.borrow().get_property(key);
        }

        None
    }

    /// Get a property descriptor, searching the prototype chain
    /// Returns (property, found_in_prototype)
    pub fn get_property_descriptor(&self, key: &PropertyKey) -> Option<(Property, bool)> {
        // For arrays, handle index access and length from elements Vec
        if let ExoticObject::Array { ref elements } = self.exotic {
            match key {
                PropertyKey::Index(idx) => {
                    if let Some(val) = elements.get(*idx as usize) {
                        return Some((Property::data(val.clone()), false));
                    }
                    // Index out of bounds - return None (falls through to prototype)
                }
                PropertyKey::String(s) if s.as_str() == "length" => {
                    return Some((
                        Property::data(JsValue::Number(elements.len() as f64)),
                        false,
                    ));
                }
                _ => {}
            }
        }

        // For Maps, compute size from entries
        if let ExoticObject::Map { ref entries } = self.exotic
            && let PropertyKey::String(s) = key
            && s.as_str() == "size"
        {
            return Some((Property::data(JsValue::Number(entries.len() as f64)), false));
        }

        // For Sets, compute size from entries
        if let ExoticObject::Set { ref entries } = self.exotic
            && let PropertyKey::String(s) = key
            && s.as_str() == "size"
        {
            return Some((Property::data(JsValue::Number(entries.len() as f64)), false));
        }

        // For functions, handle name and length properties
        if let ExoticObject::Function(ref func) = self.exotic
            && let PropertyKey::String(s) = key
        {
            match s.as_str() {
                "name" => {
                    let name = match func {
                        JsFunction::Native(f) => Some(f.name.clone()),
                        JsFunction::Bytecode(bc)
                        | JsFunction::BytecodeGenerator(bc)
                        | JsFunction::BytecodeAsync(bc)
                        | JsFunction::BytecodeAsyncGenerator(bc) => bc
                            .chunk
                            .function_info
                            .as_ref()
                            .and_then(|info| info.name.clone()),
                        JsFunction::Bound(b) => {
                            // Bound functions have name "bound <target name>"
                            if let ExoticObject::Function(target_func) = &b.target.borrow().exotic {
                                match target_func {
                                    JsFunction::Native(f) => {
                                        Some(JsString::from(format!("bound {}", f.name)))
                                    }
                                    JsFunction::Bytecode(bc)
                                    | JsFunction::BytecodeGenerator(bc)
                                    | JsFunction::BytecodeAsync(bc)
                                    | JsFunction::BytecodeAsyncGenerator(bc) => {
                                        bc.chunk.function_info.as_ref().and_then(|info| {
                                            info.name
                                                .as_ref()
                                                .map(|n| JsString::from(format!("bound {}", n)))
                                        })
                                    }
                                    _ => Some(JsString::from("bound ")),
                                }
                            } else {
                                Some(JsString::from("bound "))
                            }
                        }
                        _ => None,
                    };
                    // Per ES spec, function name is: writable: false, enumerable: false, configurable: true
                    return Some((
                        Property::with_attributes(
                            match name {
                                Some(n) => JsValue::String(n),
                                None => JsValue::String(JsString::from("")),
                            },
                            false, // writable
                            false, // enumerable
                            true,  // configurable
                        ),
                        false,
                    ));
                }
                "length" => {
                    let arity = match func {
                        JsFunction::Native(f) => f.arity,
                        JsFunction::Bytecode(bc)
                        | JsFunction::BytecodeGenerator(bc)
                        | JsFunction::BytecodeAsync(bc)
                        | JsFunction::BytecodeAsyncGenerator(bc) => bc
                            .chunk
                            .function_info
                            .as_ref()
                            .map(|info| info.param_count)
                            .unwrap_or(0),
                        JsFunction::Bound(b) => {
                            // Bound functions have length = target.length - bound_args.length (min 0)
                            if let ExoticObject::Function(target_func) = &b.target.borrow().exotic {
                                let target_length = match target_func {
                                    JsFunction::Native(f) => f.arity,
                                    JsFunction::Bytecode(bc)
                                    | JsFunction::BytecodeGenerator(bc)
                                    | JsFunction::BytecodeAsync(bc)
                                    | JsFunction::BytecodeAsyncGenerator(bc) => bc
                                        .chunk
                                        .function_info
                                        .as_ref()
                                        .map(|info| info.param_count)
                                        .unwrap_or(0),
                                    _ => 0,
                                };
                                target_length.saturating_sub(b.bound_args.len())
                            } else {
                                0
                            }
                        }
                        _ => 0,
                    };
                    // Per ES spec, function length is: writable: false, enumerable: false, configurable: true
                    return Some((
                        Property::with_attributes(
                            JsValue::Number(arity as f64),
                            false, // writable
                            false, // enumerable
                            true,  // configurable
                        ),
                        false,
                    ));
                }
                _ => {}
            }
        }

        // For enums, handle member lookups from EnumData
        if let ExoticObject::Enum(ref data) = self.exotic {
            match key {
                PropertyKey::String(s) => {
                    // Forward mapping: member name -> value
                    if let Some(val) = data.get_by_name(s.as_str()) {
                        return Some((Property::data(val), false));
                    }
                    // Also check if this is a numeric string for reverse mapping
                    if let Ok(n) = s.as_str().parse::<f64>()
                        && let Some(name) = data.get_by_value(n)
                    {
                        return Some((Property::data(JsValue::String(name)), false));
                    }
                }
                PropertyKey::Index(idx) => {
                    // Reverse mapping: numeric index -> member name
                    if let Some(name) = data.get_by_value(*idx as f64) {
                        return Some((Property::data(JsValue::String(name)), false));
                    }
                }
                PropertyKey::Symbol(_) => {}
            }
        }

        if let Some(prop) = self.properties.get(key) {
            return Some((prop.clone(), false));
        }

        if let Some(ref proto) = self.prototype
            && let Some((prop, _)) = proto.borrow().get_property_descriptor(key)
        {
            return Some((prop, true));
        }

        None
    }

    /// Set a property
    pub fn set_property(&mut self, key: PropertyKey, value: JsValue) {
        // Frozen objects cannot be modified at all
        if self.frozen {
            return;
        }

        // For arrays, handle index access via elements Vec
        if let ExoticObject::Array { ref mut elements } = self.exotic {
            if let PropertyKey::Index(idx) = key {
                let idx = idx as usize;
                // Extend array with undefined if needed (dense array)
                if idx >= elements.len() {
                    elements.resize(idx + 1, JsValue::Undefined);
                }
                // Safe: we just resized to ensure idx is in bounds
                if let Some(slot) = elements.get_mut(idx) {
                    *slot = value;
                }
                return;
            }
            // Setting length truncates or extends the array
            if let PropertyKey::String(ref s) = key
                && s.as_str() == "length"
            {
                if let JsValue::Number(n) = value {
                    let new_len = n as usize;
                    elements.resize(new_len, JsValue::Undefined);
                }
                return;
            }
        }

        // For enums, handle member access via EnumData
        if let ExoticObject::Enum(ref mut data) = self.exotic
            && let PropertyKey::String(ref s) = key
        {
            // Update existing member or add new one
            if data.set_by_name(s.as_str(), value.clone()) {
                // Also update reverse mapping if value is numeric
                if let JsValue::Number(n) = &value {
                    // Find and update the reverse mapping entry
                    let reverse_key =
                        if math::fract(*n) == 0.0 && *n >= 0.0 && *n <= u32::MAX as f64 {
                            PropertyKey::Index(*n as u32)
                        } else {
                            PropertyKey::String(JsString::from(ToString::to_string(n)))
                        };
                    self.properties.insert(
                        reverse_key,
                        Property::data(JsValue::String(s.cheap_clone())),
                    );
                }
                return;
            }
            // If not an existing member, allow adding new properties
        }

        if let Some(prop) = self.properties.get_mut(&key) {
            // Only set if writable
            if prop.writable() {
                prop.value = value;
            }
        } else if self.extensible && !self.sealed {
            // Sealed objects cannot have new properties added
            self.properties.insert(key, Property::data(value));
        }
    }

    /// Define a property with attributes
    pub fn define_property(&mut self, key: PropertyKey, prop: Property) {
        self.properties.insert(key, prop);
    }

    /// Check if object has own property
    pub fn has_own_property(&self, key: &PropertyKey) -> bool {
        self.properties.contains_key(key)
    }

    /// Get own property keys
    pub fn own_keys(&self) -> Vec<PropertyKey> {
        self.properties.keys().cloned().collect()
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Array-specific methods for efficient element access
    // ═══════════════════════════════════════════════════════════════════════════

    /// Get array length if this is an array, None otherwise
    #[inline]
    pub fn array_length(&self) -> Option<u32> {
        if let ExoticObject::Array { ref elements } = self.exotic {
            Some(elements.len() as u32)
        } else {
            None
        }
    }

    /// Get array elements slice if this is an array
    #[inline]
    pub fn array_elements(&self) -> Option<&[JsValue]> {
        if let ExoticObject::Array { ref elements } = self.exotic {
            Some(elements)
        } else {
            None
        }
    }

    /// Get mutable array elements if this is an array
    #[inline]
    pub fn array_elements_mut(&mut self) -> Option<&mut Vec<JsValue>> {
        if let ExoticObject::Array { ref mut elements } = self.exotic {
            Some(elements)
        } else {
            None
        }
    }

    /// Check if this is an array
    #[inline]
    pub fn is_array(&self) -> bool {
        matches!(self.exotic, ExoticObject::Array { .. })
    }
}

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

/// Property key (string, index, or symbol)
///
/// Size-optimized: JsSymbol is boxed since symbol keys are rare.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PropertyKey {
    String(JsString),
    Index(u32),
    Symbol(Box<JsSymbol>),
}

impl PropertyKey {
    pub fn from_value(value: &JsValue) -> Self {
        match value {
            JsValue::Number(n) => {
                let idx = *n as u32;
                if idx as f64 == *n && *n >= 0.0 {
                    PropertyKey::Index(idx)
                } else {
                    PropertyKey::String(value.to_js_string())
                }
            }
            JsValue::String(s) => {
                // Check if it's a valid array index
                if let Ok(idx) = s.parse::<u32>()
                    && idx.to_string() == s.as_str()
                {
                    return PropertyKey::Index(idx);
                }
                PropertyKey::String(s.cheap_clone())
            }
            JsValue::Symbol(s) => PropertyKey::Symbol(s.clone()),
            _ => PropertyKey::String(value.to_js_string()),
        }
    }

    /// Check if this is a symbol key
    pub fn is_symbol(&self) -> bool {
        matches!(self, PropertyKey::Symbol(_))
    }

    /// Check if this key equals a string literal (avoids allocation)
    #[inline]
    pub fn eq_str(&self, s: &str) -> bool {
        match self {
            PropertyKey::String(js_str) => js_str.as_str() == s,
            PropertyKey::Index(_) | PropertyKey::Symbol(_) => false,
        }
    }
}

impl fmt::Display for PropertyKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PropertyKey::String(s) => write!(f, "{}", s),
            PropertyKey::Index(i) => write!(f, "{}", i),
            PropertyKey::Symbol(s) => match &s.description {
                Some(desc) => write!(f, "Symbol({})", desc.as_str()),
                None => write!(f, "Symbol()"),
            },
        }
    }
}

/// Property attribute flags (packed into a single byte)
mod property_flags {
    pub const WRITABLE: u8 = 0b001;
    pub const ENUMERABLE: u8 = 0b010;
    pub const CONFIGURABLE: u8 = 0b100;
    pub const ALL: u8 = WRITABLE | ENUMERABLE | CONFIGURABLE;
}

/// Accessor functions (getter and/or setter) - boxed to save space for data properties
#[derive(Debug, Clone)]
pub struct Accessor {
    pub getter: Option<JsObjectRef>,
    pub setter: Option<JsObjectRef>,
}

/// A property descriptor - optimized for size.
/// Most properties are simple data properties, so we optimize for that case.
#[derive(Debug, Clone)]
pub struct Property {
    pub value: JsValue,
    /// Packed flags: bit 0 = writable, bit 1 = enumerable, bit 2 = configurable
    flags: u8,
    /// Accessor functions (boxed, rarely used) - None for data properties
    accessor: Option<Box<Accessor>>,
}

impl Property {
    /// Create a data property with default attributes (writable, enumerable, configurable)
    #[inline]
    pub fn data(value: JsValue) -> Self {
        Self {
            value,
            flags: property_flags::ALL,
            accessor: None,
        }
    }

    /// Create a read-only data property (enumerable, configurable, but not writable)
    #[inline]
    pub fn data_readonly(value: JsValue) -> Self {
        Self {
            value,
            flags: property_flags::ENUMERABLE | property_flags::CONFIGURABLE,
            accessor: None,
        }
    }

    /// Create an accessor property with getter and/or setter
    pub fn accessor(getter: Option<JsObjectRef>, setter: Option<JsObjectRef>) -> Self {
        Self {
            value: JsValue::Undefined,
            flags: property_flags::ENUMERABLE | property_flags::CONFIGURABLE,
            accessor: Some(Box::new(Accessor { getter, setter })),
        }
    }

    /// Check if this is an accessor property (has getter or setter)
    #[inline]
    pub fn is_accessor(&self) -> bool {
        self.accessor.is_some()
    }

    /// Create a property with custom attributes
    #[inline]
    pub fn with_attributes(
        value: JsValue,
        writable: bool,
        enumerable: bool,
        configurable: bool,
    ) -> Self {
        let mut flags = 0;
        if writable {
            flags |= property_flags::WRITABLE;
        }
        if enumerable {
            flags |= property_flags::ENUMERABLE;
        }
        if configurable {
            flags |= property_flags::CONFIGURABLE;
        }
        Self {
            value,
            flags,
            accessor: None,
        }
    }

    // Attribute getters
    #[inline]
    pub fn writable(&self) -> bool {
        (self.flags & property_flags::WRITABLE) != 0
    }

    #[inline]
    pub fn enumerable(&self) -> bool {
        (self.flags & property_flags::ENUMERABLE) != 0
    }

    #[inline]
    pub fn configurable(&self) -> bool {
        (self.flags & property_flags::CONFIGURABLE) != 0
    }

    // Attribute setters
    #[inline]
    pub fn set_writable(&mut self, writable: bool) {
        if writable {
            self.flags |= property_flags::WRITABLE;
        } else {
            self.flags &= !property_flags::WRITABLE;
        }
    }

    #[inline]
    pub fn set_enumerable(&mut self, enumerable: bool) {
        if enumerable {
            self.flags |= property_flags::ENUMERABLE;
        } else {
            self.flags &= !property_flags::ENUMERABLE;
        }
    }

    #[inline]
    pub fn set_configurable(&mut self, configurable: bool) {
        if configurable {
            self.flags |= property_flags::CONFIGURABLE;
        } else {
            self.flags &= !property_flags::CONFIGURABLE;
        }
    }

    /// Get the getter function (if this is an accessor property)
    #[inline]
    pub fn getter(&self) -> Option<&JsObjectRef> {
        self.accessor.as_ref().and_then(|a| a.getter.as_ref())
    }

    /// Get the setter function (if this is an accessor property)
    #[inline]
    pub fn setter(&self) -> Option<&JsObjectRef> {
        self.accessor.as_ref().and_then(|a| a.setter.as_ref())
    }

    /// Set the getter function
    pub fn set_getter(&mut self, getter: Option<JsObjectRef>) {
        if let Some(ref mut acc) = self.accessor {
            acc.getter = getter;
        } else if getter.is_some() {
            self.accessor = Some(Box::new(Accessor {
                getter,
                setter: None,
            }));
        }
    }

    /// Set the setter function
    pub fn set_setter(&mut self, setter: Option<JsObjectRef>) {
        if let Some(ref mut acc) = self.accessor {
            acc.setter = setter;
        } else if setter.is_some() {
            self.accessor = Some(Box::new(Accessor {
                getter: None,
                setter,
            }));
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Property Storage - optimized for small objects
// ═══════════════════════════════════════════════════════════════════════════════

/// Maximum number of properties stored inline before switching to a HashMap.
/// 2 properties covers most small objects like `{ a, b }` or `{ x: 1, y: 2 }`.
const INLINE_PROPERTY_CAPACITY: usize = 2;

/// Optimized property storage that uses inline storage for small objects.
///
/// Most JavaScript objects have only a few properties. By storing up to 2 properties
/// inline (without heap allocation), we avoid the overhead of a HashMap for common cases.
/// When the object grows beyond 2 properties, we transparently switch to a HashMap.
#[derive(Debug)]
pub enum PropertyStorage {
    /// Inline storage for small objects (≤2 properties).
    /// Uses a fixed-size array with a length counter.
    Inline {
        len: u8,
        entries: [(PropertyKey, Property); INLINE_PROPERTY_CAPACITY],
    },
    /// HashMap storage for larger objects.
    Map(FxHashMap<PropertyKey, Property>),
}

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

impl PropertyStorage {
    /// Create empty inline storage.
    #[inline]
    pub fn new() -> Self {
        PropertyStorage::Inline {
            len: 0,
            entries: core::array::from_fn(|_| {
                (PropertyKey::Index(0), Property::data(JsValue::Undefined))
            }),
        }
    }

    /// Create storage with pre-allocated capacity.
    /// If capacity > INLINE_PROPERTY_CAPACITY, creates a HashMap.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        if capacity <= INLINE_PROPERTY_CAPACITY {
            Self::new()
        } else {
            PropertyStorage::Map(FxHashMap::with_capacity_and_hasher(
                capacity,
                Default::default(),
            ))
        }
    }

    /// Reserve capacity. Only meaningful for Map variant.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        if let PropertyStorage::Map(map) = self {
            map.reserve(additional);
        }
        // For Inline, we'll convert to Map when needed during insert
    }

    /// Get a property by key.
    #[inline]
    pub fn get(&self, key: &PropertyKey) -> Option<&Property> {
        match self {
            PropertyStorage::Inline { len, entries } => {
                for entry in entries.get(..(*len as usize)).unwrap_or_default() {
                    if &entry.0 == key {
                        return Some(&entry.1);
                    }
                }
                None
            }
            PropertyStorage::Map(map) => map.get(key),
        }
    }

    /// Get a mutable reference to a property by key.
    #[inline]
    pub fn get_mut(&mut self, key: &PropertyKey) -> Option<&mut Property> {
        match self {
            PropertyStorage::Inline { len, entries } => {
                for entry in entries.get_mut(..(*len as usize)).unwrap_or_default() {
                    if &entry.0 == key {
                        return Some(&mut entry.1);
                    }
                }
                None
            }
            PropertyStorage::Map(map) => map.get_mut(key),
        }
    }

    /// Insert or update a property. Returns the old value if the key existed.
    pub fn insert(&mut self, key: PropertyKey, value: Property) -> Option<Property> {
        match self {
            PropertyStorage::Inline { len, entries } => {
                let current_len = *len as usize;

                // Check if key already exists
                for entry in entries.get_mut(..current_len).unwrap_or_default() {
                    if entry.0 == key {
                        let old = mem::replace(&mut entry.1, value);
                        return Some(old);
                    }
                }

                // Key doesn't exist - try to add inline
                if let Some(slot) = entries.get_mut(current_len) {
                    *slot = (key, value);
                    *len += 1;
                    return None;
                }

                // Need to convert to Map (current_len == INLINE_PROPERTY_CAPACITY)
                let mut map = FxHashMap::with_capacity_and_hasher(
                    INLINE_PROPERTY_CAPACITY + 1,
                    Default::default(),
                );
                for entry in entries.iter_mut() {
                    let (k, v) = mem::replace(
                        entry,
                        (PropertyKey::Index(0), Property::data(JsValue::Undefined)),
                    );
                    map.insert(k, v);
                }
                map.insert(key, value);
                *self = PropertyStorage::Map(map);
                None
            }
            PropertyStorage::Map(map) => map.insert(key, value),
        }
    }

    /// Check if a key exists.
    #[inline]
    pub fn contains_key(&self, key: &PropertyKey) -> bool {
        match self {
            PropertyStorage::Inline { len, entries } => {
                for entry in entries.get(..(*len as usize)).unwrap_or_default() {
                    if &entry.0 == key {
                        return true;
                    }
                }
                false
            }
            PropertyStorage::Map(map) => map.contains_key(key),
        }
    }

    /// Remove a property by key. Returns the removed value if it existed.
    pub fn remove(&mut self, key: &PropertyKey) -> Option<Property> {
        match self {
            PropertyStorage::Inline { len, entries } => {
                let current_len = *len as usize;
                let mut found_idx = None;
                for (i, entry) in entries
                    .get(..current_len)
                    .unwrap_or_default()
                    .iter()
                    .enumerate()
                {
                    if &entry.0 == key {
                        found_idx = Some(i);
                        break;
                    }
                }
                if let Some(i) = found_idx {
                    // Swap with last element and decrement len
                    let removed = if let Some(entry) = entries.get_mut(i) {
                        mem::replace(
                            entry,
                            (PropertyKey::Index(0), Property::data(JsValue::Undefined)),
                        )
                    } else {
                        return None;
                    };
                    if i < current_len - 1 {
                        entries.swap(i, current_len - 1);
                    }
                    *len -= 1;
                    Some(removed.1)
                } else {
                    None
                }
            }
            PropertyStorage::Map(map) => map.remove(key),
        }
    }

    /// Clear all properties.
    #[inline]
    pub fn clear(&mut self) {
        match self {
            PropertyStorage::Inline { len, entries } => {
                // Reset entries to avoid holding references
                for entry in entries.get_mut(..(*len as usize)).unwrap_or_default() {
                    *entry = (PropertyKey::Index(0), Property::data(JsValue::Undefined));
                }
                *len = 0;
            }
            PropertyStorage::Map(map) => map.clear(),
        }
    }

    /// Get the number of properties.
    #[inline]
    pub fn len(&self) -> usize {
        match self {
            PropertyStorage::Inline { len, .. } => *len as usize,
            PropertyStorage::Map(map) => map.len(),
        }
    }

    /// Check if empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Iterate over all (key, value) pairs.
    pub fn iter(&self) -> PropertyStorageIter<'_> {
        match self {
            PropertyStorage::Inline { len, entries } => PropertyStorageIter::Inline {
                entries,
                index: 0,
                len: *len as usize,
            },
            PropertyStorage::Map(map) => PropertyStorageIter::Map(map.iter()),
        }
    }

    /// Iterate over all (key, value) pairs mutably.
    pub fn iter_mut(&mut self) -> PropertyStorageIterMut<'_> {
        match self {
            PropertyStorage::Inline { len, entries } => {
                let len = *len as usize;
                PropertyStorageIterMut::Inline {
                    entries: entries.get_mut(..len).unwrap_or_default(),
                }
            }
            PropertyStorage::Map(map) => PropertyStorageIterMut::Map(map.iter_mut()),
        }
    }

    /// Iterate over all keys.
    pub fn keys(&self) -> impl Iterator<Item = &PropertyKey> {
        self.iter().map(|(k, _)| k)
    }

    /// Iterate over all values.
    pub fn values(&self) -> impl Iterator<Item = &Property> {
        self.iter().map(|(_, v)| v)
    }
}

/// Iterator over PropertyStorage entries.
pub enum PropertyStorageIter<'a> {
    Inline {
        entries: &'a [(PropertyKey, Property); INLINE_PROPERTY_CAPACITY],
        index: usize,
        len: usize,
    },
    #[cfg(feature = "std")]
    Map(std::collections::hash_map::Iter<'a, PropertyKey, Property>),
    #[cfg(not(feature = "std"))]
    Map(hashbrown::hash_map::Iter<'a, PropertyKey, Property>),
}

impl<'a> Iterator for PropertyStorageIter<'a> {
    type Item = (&'a PropertyKey, &'a Property);

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            PropertyStorageIter::Inline {
                entries,
                index,
                len,
            } => {
                if *index < *len {
                    let i = *index;
                    *index += 1;
                    entries.get(i).map(|e| (&e.0, &e.1))
                } else {
                    None
                }
            }
            PropertyStorageIter::Map(iter) => iter.next(),
        }
    }
}

/// Mutable iterator over PropertyStorage entries.
pub enum PropertyStorageIterMut<'a> {
    Inline {
        entries: &'a mut [(PropertyKey, Property)],
    },
    #[cfg(feature = "std")]
    Map(std::collections::hash_map::IterMut<'a, PropertyKey, Property>),
    #[cfg(not(feature = "std"))]
    Map(hashbrown::hash_map::IterMut<'a, PropertyKey, Property>),
}

impl<'a> Iterator for PropertyStorageIterMut<'a> {
    type Item = (&'a PropertyKey, &'a mut Property);

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            PropertyStorageIterMut::Inline { entries } => {
                // Take the slice and split off the first element
                if entries.is_empty() {
                    None
                } else {
                    // Split the slice: take first element, keep the rest
                    let (first, rest) = mem::take(entries).split_at_mut(1);
                    *entries = rest;
                    first.first_mut().map(|e| (&e.0, &mut e.1))
                }
            }
            PropertyStorageIterMut::Map(iter) => iter.next(),
        }
    }
}

/// Environment data stored in Environment exotic objects.
///
/// This is used to store variable bindings in the GC-managed object graph,
/// allowing the GC to trace and collect environments that form cycles.
#[derive(Debug)]
pub struct EnvironmentData {
    /// Variable bindings in this scope
    /// Uses VarKey for O(1) pointer-based lookups (all var names are interned)
    pub bindings: FxHashMap<VarKey, Binding>,
    /// Parent environment (if any) - now a GC reference
    pub outer: Option<JsObjectRef>,
}

impl EnvironmentData {
    /// Create a new environment with no outer scope (for global environment)
    pub fn new() -> Self {
        Self {
            bindings: FxHashMap::default(),
            outer: None,
        }
    }

    /// Create a new environment with the given outer environment as parent
    pub fn with_outer(outer: Option<JsObjectRef>) -> Self {
        Self {
            bindings: FxHashMap::default(),
            outer,
        }
    }

    /// Create a new environment with the given outer environment and pre-allocated capacity
    /// for bindings. This reduces HashMap resizing during function execution.
    pub fn with_outer_and_capacity(outer: Option<JsObjectRef>, capacity: usize) -> Self {
        Self {
            bindings: FxHashMap::with_capacity_and_hasher(capacity, Default::default()),
            outer,
        }
    }
}

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

/// A wrapper around JsValue that implements Hash and Eq using SameValueZero semantics.
///
/// This is used as the key type for Map and Set to provide O(1) lookup while
/// preserving JavaScript's SameValueZero comparison semantics:
/// - NaN equals NaN (unlike IEEE 754)
/// - -0 equals +0
/// - Objects are compared by identity (pointer equality)
#[derive(Debug, Clone)]
pub struct JsMapKey(pub JsValue);

impl JsMapKey {
    /// Check SameValueZero equality (used by Map/Set for key comparison)
    fn same_value_zero(a: &JsValue, b: &JsValue) -> bool {
        match (a, b) {
            (JsValue::Number(x), JsValue::Number(y)) => {
                // NaN equals NaN, -0 equals +0
                if x.is_nan() && y.is_nan() {
                    return true;
                }
                x == y
            }
            (JsValue::String(x), JsValue::String(y)) => x == y,
            (JsValue::Boolean(x), JsValue::Boolean(y)) => x == y,
            (JsValue::Null, JsValue::Null) => true,
            (JsValue::Undefined, JsValue::Undefined) => true,
            (JsValue::Object(x), JsValue::Object(y)) => x.id() == y.id(),
            (JsValue::Symbol(x), JsValue::Symbol(y)) => x.id == y.id,
            _ => false,
        }
    }
}

impl PartialEq for JsMapKey {
    fn eq(&self, other: &Self) -> bool {
        Self::same_value_zero(&self.0, &other.0)
    }
}

impl Eq for JsMapKey {}

impl Hash for JsMapKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Hash discriminant first to differentiate types
        mem::discriminant(&self.0).hash(state);

        match &self.0 {
            JsValue::Undefined | JsValue::Null => {
                // No additional data to hash
            }
            JsValue::Boolean(b) => b.hash(state),
            JsValue::Number(n) => {
                // NaN must hash consistently (all NaNs are equal in SameValueZero)
                // -0 and +0 must hash the same (they're equal in SameValueZero)
                if n.is_nan() {
                    0x7FF8_0000_0000_0000u64.hash(state); // Canonical NaN bits
                } else if *n == 0.0 {
                    0u64.hash(state); // Both -0 and +0 hash to 0
                } else {
                    n.to_bits().hash(state);
                }
            }
            JsValue::String(s) => s.hash(state),
            JsValue::Symbol(sym) => sym.id.hash(state),
            JsValue::Object(obj) => obj.id().hash(state),
        }
    }
}

/// Exotic object behavior
#[derive(Debug)]
pub enum ExoticObject {
    /// Ordinary object
    Ordinary,
    /// Array exotic object - stores elements directly for O(1) indexed access
    Array { elements: Vec<JsValue> },
    /// Boolean wrapper object - stores primitive boolean value
    Boolean(bool),
    /// Number wrapper object - stores primitive number value
    Number(f64),
    /// String wrapper object - stores primitive string value
    StringObj(JsString),
    /// Symbol wrapper object - stores primitive symbol value
    Symbol(Box<JsSymbol>),
    /// Function exotic object
    Function(JsFunction),
    /// Map exotic object - stores key-value pairs preserving insertion order
    /// Uses IndexMap for O(1) lookup with SameValueZero key comparison
    Map {
        entries: IndexMap<JsMapKey, JsValue>,
    },
    /// Set exotic object - stores unique values preserving insertion order
    /// Uses IndexSet for O(1) lookup with SameValueZero comparison
    Set { entries: IndexSet<JsMapKey> },
    /// Date exotic object - stores timestamp in milliseconds since Unix epoch
    Date { timestamp: f64 },
    /// RegExp exotic object - stores pattern, flags, and cached compiled regex
    RegExp {
        pattern: String,
        flags: String,
        /// Cached compiled regex. Lazily compiled on first use.
        compiled: Option<Rc<dyn CompiledRegex>>,
    },
    /// Generator exotic object - stores generator state (AST-based)
    Generator(Rc<RefCell<GeneratorState>>),
    /// Bytecode generator exotic object - stores bytecode generator state
    BytecodeGenerator(Rc<RefCell<BytecodeGeneratorState>>),
    /// Promise exotic object - stores promise state
    Promise(Rc<RefCell<PromiseState>>),
    /// Environment exotic object - stores variable bindings
    Environment(EnvironmentData),
    /// Enum exotic object - stores enum metadata
    Enum(EnumData),
    /// Proxy exotic object - wraps target with handler traps
    Proxy(ProxyData),
    /// Raw JSON exotic object - stores a JSON string for literal insertion in JSON.stringify
    RawJSON(JsString),
    /// Pending order marker - triggers immediate VM suspension
    /// The id is the OrderId that will be used to match the response from host
    /// When detected, VM suspends and waits for host to provide a value via fulfill_orders()
    PendingOrder { id: u64 },
}

/// Proxy internal state
///
/// Stores the target object and handler object for the proxy.
/// If revoked is true, all operations on the proxy will throw TypeError.
#[derive(Debug, Clone)]
pub struct ProxyData {
    /// The wrapped target object
    pub target: JsObjectRef,
    /// The handler object containing traps
    pub handler: JsObjectRef,
    /// Whether this proxy has been revoked
    pub revoked: bool,
}

/// Enum member - stores name and value
#[derive(Debug, Clone)]
pub struct EnumMember {
    /// Member name (e.g., "Up", "Down")
    pub name: JsString,
    /// Member value (number or string)
    pub value: JsValue,
}

/// Enum internal state
///
/// Stores enum members directly for efficient access.
/// Forward mappings (name → value) and reverse mappings (numeric value → name)
/// are computed from the members list.
#[derive(Debug, Clone)]
pub struct EnumData {
    /// Enum name (for debugging/toString)
    pub name: JsString,
    /// Whether this is a const enum
    pub const_: bool,
    /// Enum members in declaration order
    pub members: Vec<EnumMember>,
}

impl EnumData {
    /// Get value by member name (forward mapping)
    pub fn get_by_name(&self, name: &str) -> Option<JsValue> {
        self.members
            .iter()
            .find(|m| m.name.as_str() == name)
            .map(|m| m.value.clone())
    }

    /// Get member name by numeric value (reverse mapping)
    /// Only works for numeric values, returns None for string values
    pub fn get_by_value(&self, value: f64) -> Option<JsString> {
        self.members.iter().find_map(|m| {
            if let JsValue::Number(n) = &m.value
                && *n == value
            {
                return Some(m.name.cheap_clone());
            }
            None
        })
    }

    /// Get all property keys (member names + reverse mapping keys for numeric values)
    pub fn keys(&self) -> Vec<PropertyKey> {
        let mut keys = Vec::with_capacity(self.members.len() * 2);

        for member in &self.members {
            // Forward mapping key (member name)
            keys.push(PropertyKey::String(member.name.cheap_clone()));

            // Reverse mapping key for numeric values
            if let JsValue::Number(_) = &member.value {
                keys.push(PropertyKey::from_value(&member.value));
            }
        }

        keys
    }

    /// Get all values (member values + reverse mapping values)
    pub fn values(&self) -> Vec<JsValue> {
        let mut values = Vec::with_capacity(self.members.len() * 2);

        for member in &self.members {
            // Forward mapping value
            values.push(member.value.clone());

            // Reverse mapping value for numeric values (the member name)
            if let JsValue::Number(_) = &member.value {
                values.push(JsValue::String(member.name.cheap_clone()));
            }
        }

        values
    }

    /// Get all entries as (key_string, value) pairs for Object.entries
    pub fn entries(&self) -> Vec<(String, JsValue)> {
        let mut entries = Vec::with_capacity(self.members.len() * 2);

        for member in &self.members {
            // Forward mapping entry (member name -> value)
            entries.push((member.name.to_string(), member.value.clone()));

            // Reverse mapping entry for numeric values (value string -> name)
            if let JsValue::Number(n) = &member.value {
                entries.push((n.to_string(), JsValue::String(member.name.cheap_clone())));
            }
        }

        entries
    }

    /// Check if the enum has a property with the given key
    pub fn has_property(&self, key: &PropertyKey) -> bool {
        match key {
            PropertyKey::String(s) => {
                // Check forward mapping
                if self.members.iter().any(|m| m.name.as_str() == s.as_str()) {
                    return true;
                }
                // Check reverse mapping for numeric string keys
                if let Ok(n) = s.as_str().parse::<f64>() {
                    return self.get_by_value(n).is_some();
                }
                false
            }
            PropertyKey::Index(idx) => self.get_by_value(*idx as f64).is_some(),
            PropertyKey::Symbol(_) => false,
        }
    }

    /// Set a member value by name (for mutability support)
    /// Returns true if the member was found and updated
    pub fn set_by_name(&mut self, name: &str, value: JsValue) -> bool {
        if let Some(member) = self.members.iter_mut().find(|m| m.name.as_str() == name) {
            member.value = value;
            true
        } else {
            false
        }
    }
}

/// Promise internal state
#[derive(Debug, Clone)]
pub struct PromiseState {
    /// Current state of the promise
    pub status: PromiseStatus,
    /// Resolved value or rejection reason
    pub result: Option<JsValue>,
    /// Handlers to call when promise settles
    pub handlers: Vec<PromiseHandler>,
    /// Order ID if this is a host-created Promise (for cancellation tracking)
    pub order_id: Option<crate::OrderId>,
}

/// Promise status
#[derive(Debug, Clone, PartialEq)]
pub enum PromiseStatus {
    /// Promise is pending
    Pending,
    /// Promise is fulfilled
    Fulfilled,
    /// Promise is rejected
    Rejected,
}

/// Handler attached via .then()/.catch()
#[derive(Debug, Clone)]
pub struct PromiseHandler {
    /// Callback for fulfilled state
    pub on_fulfilled: Option<JsValue>,
    /// Callback for rejected state
    pub on_rejected: Option<JsValue>,
    /// The promise returned by .then()/.catch()
    pub result_promise: JsObjectRef,
}

/// Saved frame state for generators
/// This stores the frames and values that need to be restored when resuming
#[derive(Debug, Clone)]
pub struct SavedFrameState {
    /// Serialized frame data - stored as a clonable representation
    pub frame_data: Vec<u8>,
    /// Number of frames
    pub frame_count: usize,
}

/// Generator state for suspended generators
///
/// Note: This struct intentionally does NOT derive Clone because it may hold
/// a saved ExecutionState which contains Guards that cannot be cloned.
/// The struct is always wrapped in Rc<RefCell<>> for shared access.
pub struct GeneratorState {
    /// The generator function's body (Rc for cheap cloning)
    pub body: Rc<BlockStatement>,
    /// Parameters of the generator function (Rc for cheap cloning)
    pub params: Rc<[FunctionParam]>,
    /// Arguments passed to the generator
    pub args: Vec<JsValue>,
    /// The captured closure environment (GC-managed)
    pub closure: JsObjectRef,
    /// Current execution status
    pub status: GeneratorStatus,
    /// Value passed in via next(value)
    pub sent_value: JsValue,
    /// Function name for debugging
    pub name: Option<JsString>,
    /// Unique ID for this generator (used to look up saved execution state)
    pub id: u64,
    /// Whether this generator has started execution
    pub started: bool,
}

impl fmt::Debug for GeneratorState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GeneratorState")
            .field("status", &self.status)
            .field("id", &self.id)
            .field("started", &self.started)
            .finish()
    }
}

/// Status of generator execution
#[derive(Debug, Clone, PartialEq)]
pub enum GeneratorStatus {
    /// Not yet started
    Suspended,
    /// Completed (returned or exhausted)
    Completed,
}

/// Generator state for bytecode-based generators
///
/// This stores the bytecode chunk and VM state needed to resume execution.
pub struct BytecodeGeneratorState {
    /// The bytecode chunk for the generator function
    pub chunk: Rc<crate::compiler::BytecodeChunk>,
    /// The captured closure environment
    pub closure: JsObjectRef,
    /// Arguments passed to the generator function
    pub args: Vec<JsValue>,
    /// The `this` value passed when the generator function was called
    pub this_value: JsValue,
    /// Current execution status
    pub status: GeneratorStatus,
    /// Value passed in via next(value)
    pub sent_value: JsValue,
    /// Unique ID for this generator
    pub id: u64,
    /// Whether this generator has started execution
    pub started: bool,
    /// Saved instruction pointer (for resumption)
    pub saved_ip: usize,
    /// Saved register values (for resumption)
    pub saved_registers: Vec<JsValue>,
    /// Saved call stack (for resumption)
    pub saved_call_stack: Vec<crate::interpreter::bytecode_vm::CallFrame>,
    /// Saved try stack (for resumption)
    pub saved_try_stack: Vec<crate::interpreter::bytecode_vm::TryHandler>,
    /// Register to store the result of yield
    pub yield_result_register: Option<u8>,
    /// The function environment (created on first call, reused on subsequent calls)
    pub func_env: Option<JsObjectRef>,
    /// The current environment at yield time (may be nested within func_env)
    pub current_env: Option<JsObjectRef>,
    /// Delegated iterator for yield* (iterator object and its next method)
    pub delegated_iterator: Option<(JsObjectRef, JsValue)>,
    /// Whether this is an async generator (next() returns Promise)
    pub is_async: bool,
    /// Exception to throw when resuming (for generator.throw())
    pub throw_value: Option<JsValue>,
}

impl fmt::Debug for BytecodeGeneratorState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BytecodeGeneratorState")
            .field("status", &self.status)
            .field("id", &self.id)
            .field("started", &self.started)
            .field("saved_ip", &self.saved_ip)
            .finish()
    }
}

/// Function representation
#[derive(Debug, Clone)]
pub enum JsFunction {
    /// Bytecode function (compiled from source)
    Bytecode(BytecodeFunction),
    /// Bytecode generator function (creates a generator when called)
    BytecodeGenerator(BytecodeFunction),
    /// Bytecode async function (returns Promise when called)
    BytecodeAsync(BytecodeFunction),
    /// Bytecode async generator function (creates async generator when called)
    BytecodeAsyncGenerator(BytecodeFunction),
    /// Native Rust function
    Native(NativeFunction),
    /// Bound function (created by Function.prototype.bind)
    Bound(Box<BoundFunctionData>),
    /// Promise resolve function (has internal [[Promise]] slot)
    PromiseResolve(JsObjectRef),
    /// Promise reject function (has internal [[Promise]] slot)
    PromiseReject(JsObjectRef),
    /// Promise.all fulfill handler (tracks shared state for aggregation)
    /// Contains (shared_state, index) - index is which promise slot to fill
    PromiseAllFulfill {
        state: Rc<PromiseAllSharedState>,
        index: usize,
    },
    /// Promise.all reject handler (rejects on first failure)
    PromiseAllReject(Rc<PromiseAllSharedState>),
    /// Promise.race settle handler (settles on first settlement, either fulfill or reject)
    PromiseRaceSettle {
        state: Rc<PromiseRaceSharedState>,
        /// true = on_fulfilled handler, false = on_rejected handler
        is_fulfill: bool,
        /// Index of this Promise in the race inputs (for identifying winner)
        index: usize,
    },
    /// Auto-accessor getter (metadata stored in object properties)
    AccessorGetter,
    /// Auto-accessor setter (metadata stored in object properties)
    AccessorSetter,
    /// Module export getter for live bindings
    /// Contains (module_environment, binding_name)
    ModuleExportGetter {
        module_env: JsObjectRef,
        binding_name: JsString,
    },
    /// Re-export getter for live bindings through re-exports
    /// Delegates to another module's namespace object property
    ModuleReExportGetter {
        source_module: JsObjectRef,
        source_key: PropertyKey,
    },
    /// Proxy revoke function - revokes the associated proxy
    /// Contains the proxy object reference
    ProxyRevoke(JsObjectRef),
}

/// Shared state for Promise.all tracking
/// This is shared across all handlers via Rc
#[derive(Debug)]
pub struct PromiseAllSharedState {
    /// Number of promises still pending
    pub remaining: Cell<usize>,
    /// Results array (indexed by original position)
    pub results: RefCell<Vec<JsValue>>,
    /// The result promise to fulfill when all complete
    pub result_promise: JsObjectRef,
    /// Whether any promise has already rejected
    pub rejected: Cell<bool>,
}

/// Shared state for Promise.race tracking
/// First promise to settle wins
#[derive(Debug)]
pub struct PromiseRaceSharedState {
    /// The result promise to settle
    pub result_promise: JsObjectRef,
    /// Whether the race has already been settled
    pub settled: Cell<bool>,
    /// Order IDs of input Promises (indexed by position, None for non-host Promises)
    pub input_order_ids: Vec<Option<crate::OrderId>>,
}

/// Data for a bound function
#[derive(Debug, Clone)]
pub struct BoundFunctionData {
    /// The target function to call
    pub target: JsObjectRef,
    /// The bound this value
    pub this_arg: JsValue,
    /// Pre-filled arguments
    pub bound_args: Vec<JsValue>,
}

impl JsFunction {
    pub fn name(&self) -> Option<&str> {
        match self {
            JsFunction::Bytecode(f)
            | JsFunction::BytecodeGenerator(f)
            | JsFunction::BytecodeAsync(f)
            | JsFunction::BytecodeAsyncGenerator(f) => f
                .chunk
                .function_info
                .as_ref()
                .and_then(|info| info.name.as_ref())
                .map(|s| s.as_str()),
            JsFunction::Native(f) => Some(f.name.as_ref()),
            JsFunction::Bound(_) => Some("bound"),
            JsFunction::PromiseResolve(_) => Some("resolve"),
            JsFunction::PromiseReject(_) => Some("reject"),
            JsFunction::PromiseAllFulfill { .. } => Some("promiseAllFulfill"),
            JsFunction::PromiseAllReject(_) => Some("promiseAllReject"),
            JsFunction::PromiseRaceSettle { .. } => Some("promiseRaceSettle"),
            JsFunction::AccessorGetter => Some("get"),
            JsFunction::AccessorSetter => Some("set"),
            JsFunction::ModuleExportGetter { .. } => Some("get"),
            JsFunction::ModuleReExportGetter { .. } => Some("get"),
            JsFunction::ProxyRevoke(_) => Some("revoke"),
        }
    }
}

/// Bytecode-compiled function
#[derive(Debug, Clone)]
pub struct BytecodeFunction {
    /// The compiled bytecode chunk
    pub chunk: Rc<crate::compiler::BytecodeChunk>,
    /// The captured closure environment (GC-managed)
    pub closure: JsObjectRef,
    /// Captured `this` value for arrow functions (None for regular functions)
    pub captured_this: Option<Box<JsValue>>,
}

/// Native function signature type
/// Returns Guarded to keep newly created objects alive until ownership is transferred.
pub type NativeFn =
    fn(&mut crate::interpreter::Interpreter, JsValue, &[JsValue]) -> Result<Guarded, JsError>;

/// Native function wrapper
#[derive(Clone)]
pub struct NativeFunction {
    pub name: JsString,
    pub func: NativeFn,
    pub arity: usize,
    /// FFI callback ID (0 = not an FFI callback, non-zero = lookup key in FFI registry)
    pub ffi_id: usize,
}

impl fmt::Debug for NativeFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NativeFunction")
            .field("name", &self.name)
            .field("arity", &self.arity)
            .finish()
    }
}

/// Variable binding
#[derive(Debug, Clone)]
pub struct Binding {
    pub value: JsValue,
    pub mutable: bool,
    pub initialized: bool,
    /// For import bindings: reference to module object and property key for live bindings.
    /// When set, `value` is ignored and the actual value is read from the module object.
    pub import_binding: Option<ImportBinding>,
}

/// Reference to a module export for live bindings
#[derive(Debug, Clone)]
pub struct ImportBinding {
    pub module_obj: JsObjectRef,
    pub property_key: PropertyKey,
}

/// Represents a module export entry - either a direct export from this module's
/// environment, or a re-export from another module.
#[derive(Debug, Clone)]
pub enum ModuleExport {
    /// Direct export: the binding exists in this module's environment
    /// The value is stored but the actual live value comes from the environment
    Direct { name: JsString, value: JsValue },
    /// Re-export: delegates to another module's export
    /// Contains the source module namespace object and the property key
    ReExport {
        source_module: JsObjectRef,
        source_key: PropertyKey,
    },
}

// ═══════════════════════════════════════════════════════════════════════════════
// Environment GC Integration
// ═══════════════════════════════════════════════════════════════════════════════

/// Environment reference - a GC-managed environment object.
///
/// This is an alias for `JsObjectRef` where the object has `ExoticObject::Environment`.
/// Using this type makes it clear when a reference is expected to be an environment.
pub type EnvRef = JsObjectRef;

/// A guarded environment that keeps itself alive via its guard.
///
/// This bundles an environment reference with the guard that keeps it rooted.
/// Used for `self.env` in the interpreter to ensure environments aren't collected
/// while they're the current execution environment.
pub struct GuardedEnv {
    /// The environment object
    pub env: EnvRef,
    /// Guard keeping this environment alive (None for root_guard-allocated envs)
    pub guard: Option<Guard<JsObject>>,
}

impl GuardedEnv {
    /// Create a guarded environment with an explicit guard
    pub fn with_guard(env: EnvRef, guard: Guard<JsObject>) -> Self {
        Self {
            env,
            guard: Some(guard),
        }
    }

    /// Create an unguarded environment (for envs already rooted via root_guard)
    pub fn unguarded(env: EnvRef) -> Self {
        Self { env, guard: None }
    }

    /// Get the environment reference
    pub fn get(&self) -> &EnvRef {
        &self.env
    }

    /// Clone the environment reference (for passing to outer, etc.)
    pub fn clone_ref(&self) -> EnvRef {
        self.env.clone()
    }
}

/// Create a new environment object with a temporary guard.
///
/// The environment is created with an optional outer environment reference.
/// The outer environment holds a reference to the new env via EnvironmentData::outer,
/// which increments ref_count via clone.
/// Returns the environment object. Caller is responsible for ownership transfer.
pub fn create_environment_with_guard(guard: &Guard<JsObject>, outer: Option<EnvRef>) -> EnvRef {
    let env = guard.alloc();
    {
        let mut env_ref = env.borrow_mut();
        env_ref.null_prototype = true;
        // The outer clone (if any) in EnvironmentData automatically increments ref_count
        env_ref.exotic = ExoticObject::Environment(EnvironmentData::with_outer(outer));
    }
    env
}

/// Create a new environment object with its own temporary guard.
///
/// This is used for per-iteration loop environments that should NOT be added to root_guard.
/// The guard is returned so it can be kept alive until the environment is safely stored
/// (e.g., in self.env), after which the guard can be dropped.
///
/// Returns (environment, guard) - caller must keep guard alive until env is owned elsewhere.
pub fn create_environment_unrooted(
    heap: &Heap<JsObject>,
    outer: Option<EnvRef>,
) -> (EnvRef, Guard<JsObject>) {
    let guard = heap.create_guard();
    let env = guard.alloc();
    {
        let mut env_ref = env.borrow_mut();
        env_ref.null_prototype = true;
        env_ref.exotic = ExoticObject::Environment(EnvironmentData::with_outer(outer));
    }
    (env, guard)
}

/// Create a new environment object with pre-allocated capacity for bindings.
///
/// Like `create_environment_unrooted`, but pre-sizes the bindings HashMap to avoid
/// resizing during function execution. Use when the number of bindings is known
/// (e.g., from FunctionInfo::binding_count).
///
/// Returns (environment, guard) - caller must keep guard alive until env is owned elsewhere.
pub fn create_environment_unrooted_with_capacity(
    heap: &Heap<JsObject>,
    outer: Option<EnvRef>,
    capacity: usize,
) -> (EnvRef, Guard<JsObject>) {
    let guard = heap.create_guard();
    let env = guard.alloc();
    {
        let mut env_ref = env.borrow_mut();
        env_ref.null_prototype = true;
        env_ref.exotic =
            ExoticObject::Environment(EnvironmentData::with_outer_and_capacity(outer, capacity));
    }
    (env, guard)
}

/// Create a new guarded environment.
///
/// This creates an environment with its own guard that keeps it alive.
/// Used for creating environments that will be stored in `self.env`.
pub fn create_guarded_env(heap: &Heap<JsObject>, outer: Option<EnvRef>) -> GuardedEnv {
    let (env, guard) = create_environment_unrooted(heap, outer);
    GuardedEnv::with_guard(env, guard)
}

impl JsObject {
    /// Get environment data if this is an environment object
    pub fn as_environment(&self) -> Option<&EnvironmentData> {
        match &self.exotic {
            ExoticObject::Environment(data) => Some(data),
            _ => None,
        }
    }

    /// Get mutable environment data if this is an environment object
    pub fn as_environment_mut(&mut self) -> Option<&mut EnvironmentData> {
        match &mut self.exotic {
            ExoticObject::Environment(data) => Some(data),
            _ => None,
        }
    }

    /// Check if this object is an environment
    pub fn is_environment(&self) -> bool {
        matches!(self.exotic, ExoticObject::Environment(_))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_to_boolean() {
        assert!(!JsValue::Undefined.to_boolean());
        assert!(!JsValue::Null.to_boolean());
        assert!(!JsValue::Boolean(false).to_boolean());
        assert!(JsValue::Boolean(true).to_boolean());
        assert!(!JsValue::Number(0.0).to_boolean());
        assert!(JsValue::Number(1.0).to_boolean());
        assert!(!JsValue::Number(f64::NAN).to_boolean());
        assert!(!JsValue::String(JsString::from("")).to_boolean());
        assert!(JsValue::String(JsString::from("hello")).to_boolean());
    }

    #[test]
    fn test_to_number() {
        assert!(JsValue::Undefined.to_number().is_nan());
        assert_eq!(JsValue::Null.to_number(), 0.0);
        assert_eq!(JsValue::Boolean(true).to_number(), 1.0);
        assert_eq!(JsValue::Boolean(false).to_number(), 0.0);
        assert_eq!(JsValue::Number(42.0).to_number(), 42.0);
        assert_eq!(JsValue::String(JsString::from("42")).to_number(), 42.0);
        assert!(
            JsValue::String(JsString::from("hello"))
                .to_number()
                .is_nan()
        );
    }

    #[test]
    fn test_strict_equals() {
        assert!(JsValue::Undefined.strict_equals(&JsValue::Undefined));
        assert!(JsValue::Null.strict_equals(&JsValue::Null));
        assert!(!JsValue::Undefined.strict_equals(&JsValue::Null));
        assert!(JsValue::Number(1.0).strict_equals(&JsValue::Number(1.0)));
        assert!(!JsValue::Number(f64::NAN).strict_equals(&JsValue::Number(f64::NAN)));
    }

    #[test]
    fn test_to_js_string_number_canonical() {
        // JavaScript uses canonical string representations for numbers
        // Very small numbers use exponential notation
        assert_eq!(
            JsValue::Number(0.0000001).to_js_string().as_str(),
            "1e-7",
            "0.0000001 should be '1e-7'"
        );

        // Normal decimals
        assert_eq!(
            JsValue::Number(0.1).to_js_string().as_str(),
            "0.1",
            "0.1 should be '0.1'"
        );

        // Very large numbers use exponential notation
        assert_eq!(
            JsValue::Number(1e21).to_js_string().as_str(),
            "1e+21",
            "1e21 should be '1e+21'"
        );
    }

    #[test]
    fn test_property_key_from_decimal() {
        // PropertyKey::from_value should use canonical string representation
        let key = PropertyKey::from_value(&JsValue::Number(0.1));
        match key {
            PropertyKey::String(s) => assert_eq!(s.as_str(), "0.1"),
            PropertyKey::Index(_) => panic!("0.1 should not be an index"),
            PropertyKey::Symbol(_) => panic!("0.1 should not be a symbol"),
        }
    }

    #[test]
    fn test_rust_parse_leading_decimal() {
        // Check what Rust does with ".1"
        let parsed: f64 = ".1".parse().unwrap();
        assert_eq!(parsed, 0.1);
    }

    #[test]
    fn test_property_key_from_value_decimal_debug() {
        let n = 0.1_f64;
        let key = PropertyKey::from_value(&JsValue::Number(n));
        match key {
            PropertyKey::String(s) => {
                assert_eq!(s.as_str(), "0.1");
            }
            PropertyKey::Index(_) => {
                panic!("0.1 should not be an index!");
            }
            PropertyKey::Symbol(_) => panic!("0.1 should not be a symbol"),
        }
    }
}