makefuture / games / nordschleife / index.html
13,788 words
   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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>NORDSCHLEIFE 3D — Make Future</title>
    <style>
        *,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
        html,body{background:#000;color:#fff;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif;height:100%;width:100%;overflow:hidden;-webkit-font-smoothing:antialiased;touch-action:none;user-select:none}
        body{display:flex;align-items:center;justify-content:center}
        .hdr{position:fixed;top:0;left:0;right:0;padding:clamp(.6rem,1.5vw,1.2rem) clamp(.8rem,2.5vw,2rem);display:flex;justify-content:center;align-items:center;z-index:100}
        .wm{position:absolute;left:clamp(.8rem,2.5vw,2rem);font-size:.55rem;font-weight:500;letter-spacing:.3em;text-transform:uppercase;color:#222;text-decoration:none;transition:color .5s ease}
        .wm:hover{color:#666}
        .scores{display:flex;gap:1.2rem;font-size:.55rem;font-weight:500;letter-spacing:.2em;text-transform:uppercase;opacity:0;transition:opacity .5s ease}
        .scores.show{opacity:1}
        .sc{color:#666}
        .sc b{font-weight:600;color:#fff}
        .g{display:grid;gap:0;position:fixed;inset:0}
        .c{position:relative}
        .f{background:#fff;opacity:0;transform:scale(0);animation:enter .7s cubic-bezier(.16,1,.3,1) forwards;animation-delay:var(--d,0s)}
        @keyframes enter{to{opacity:1;transform:scale(1)}}
        .f.out{animation:flipOut .45s cubic-bezier(.55,.085,.68,.53) forwards!important;animation-delay:var(--fd,0s)!important}
        @keyframes flipOut{0%{opacity:1;transform:scale(1) rotateX(0)}100%{opacity:0;transform:scale(.3) rotateX(90deg)}}
        #three-container{position:fixed;inset:0;display:none;z-index:1}
        #three-container.show{display:block}
        #three-container canvas{display:block;width:100%!important;height:100%!important}
        .prompt{position:fixed;bottom:18%;left:0;right:0;text-align:center;font-size:.55rem;font-weight:400;letter-spacing:.35em;text-transform:uppercase;color:#333;animation:blink 1.2s steps(1) infinite;z-index:200;transition:opacity .3s}
        .prompt.hidden{opacity:0;pointer-events:none;animation:none}
        @keyframes blink{0%,45%{opacity:1}50%,95%{opacity:0}100%{opacity:1}}
        #hud-section{position:fixed;bottom:12%;left:0;right:0;text-align:center;font-size:clamp(.5rem,.8vw,.7rem);font-weight:500;letter-spacing:.2em;text-transform:uppercase;color:#444;z-index:100;opacity:0;transition:opacity .3s}
        #hud-flash{position:fixed;top:35%;left:0;right:0;text-align:center;font-size:clamp(1rem,2.5vw,1.8rem);font-weight:600;letter-spacing:.15em;z-index:100;opacity:0;pointer-events:none}
        #vignette{position:fixed;inset:0;z-index:2;pointer-events:none;opacity:0;transition:opacity .3s;box-shadow:inset 0 0 150px 40px rgba(0,0,0,0.8)}
        #speed-lines{position:fixed;inset:0;z-index:2;pointer-events:none;opacity:0}
        #progress-bar{position:fixed;bottom:0;left:0;height:2px;background:rgba(255,255,255,0.15);z-index:3;transition:width .1s linear}
        #race-banner{position:fixed;top:clamp(3rem,8vh,5rem);left:0;right:0;text-align:center;font-size:.65rem;font-weight:600;letter-spacing:.25em;text-transform:uppercase;color:#888;z-index:100;pointer-events:none;display:none}
        #race-banner.show{display:block}
        #minimap-wrap{position:fixed;bottom:clamp(3rem,10vh,5rem);right:clamp(.6rem,2vw,1.2rem);width:120px;height:120px;border:1px solid rgba(255,255,255,0.12);border-radius:4px;overflow:hidden;z-index:100;display:none;background:rgba(0,0,0,0.35)}
        #minimap-wrap.show{display:block}
        #minimap{position:absolute;inset:0;width:100%;height:100%}
        #standings-strip{position:fixed;top:clamp(2.2rem,6vh,3.5rem);right:clamp(.6rem,2vw,1.2rem);max-width:min(220px,40vw);font-size:.45rem;font-weight:500;letter-spacing:.12em;text-transform:uppercase;color:#555;z-index:100;display:none;text-align:right;line-height:1.5}
        #standings-strip.show{display:block}
        #menu-overlay{position:fixed;inset:0;background:rgba(0,0,0,0.56);z-index:220;display:none;align-items:center;justify-content:center;padding:1rem}
        #menu-overlay.show{display:flex}
        #menu-card{width:min(560px,92vw);background:rgba(10,12,18,0.94);border:1px solid rgba(255,255,255,0.18);padding:1rem 1.1rem;color:#d9deea}
        #menu-title{font-size:.72rem;letter-spacing:.2em;text-transform:uppercase;color:#a9b4c8;margin-bottom:.8rem}
        .menu-row{display:flex;gap:.6rem;flex-wrap:wrap;margin-bottom:.8rem}
        .menu-btn{background:#151a24;border:1px solid rgba(255,255,255,0.2);color:#d9deea;padding:.45rem .6rem;font-size:.55rem;letter-spacing:.12em;text-transform:uppercase;cursor:pointer}
        .menu-btn:hover{background:#1d2533}
        #menu-info{font-size:.56rem;line-height:1.5;letter-spacing:.05em;color:#aeb9cf;white-space:pre-line}
        .ftr{position:fixed;bottom:0;left:0;right:0;padding:clamp(.6rem,1.5vw,1.2rem) clamp(.8rem,2.5vw,2rem);display:flex;justify-content:space-between;align-items:center;z-index:100}
        .ftr span{font-size:.4rem;font-weight:300;letter-spacing:.2em;text-transform:uppercase;color:#181818}
        ::selection{background:#fff;color:#000}
    </style>
    <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' fill='%23000'/%3E%3Crect x='14' y='14' width='4' height='4' fill='%23fff'/%3E%3C/svg%3E">
    <!-- Three.js v0.162.0 via jsdelivr CDN -->
    <script type="importmap">
    { "imports": {
        "three": "https://cdn.jsdelivr.net/npm/three@0.162.0/build/three.module.js",
        "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.162.0/examples/jsm/"
    }}
    </script>
</head>
<body>

<header class="hdr">
    <a href="/" class="wm">Make Future</a>
    <div class="scores" id="scores">
        <div class="sc">Lap <b id="ltv">0:00.0</b></div>
        <div class="sc">Best <b id="btv">--</b></div>
        <div class="sc"><b id="spdv">0</b> km/h</div>
        <div class="sc"><b id="altv">520</b>m</div>
        <div class="sc">G<b id="gearv">1</b></div>
        <div class="sc" id="mp-status" style="display:none"><b id="mp-count">0</b> online</div>
    </div>
</header>

<div class="g" id="g"></div>
<div id="three-container"></div>

<div class="prompt" id="prompt">Nordschleife 3D — Press any key</div>
<div id="hud-section"></div>
<div id="hud-flash"></div>
<div id="vignette"></div>
<canvas id="speed-lines"></canvas>
<div id="progress-bar"></div>
<div id="race-banner"></div>
<div id="minimap-wrap"><canvas id="minimap" width="120" height="120"></canvas></div>
<div id="standings-strip"></div>
<div id="menu-overlay">
    <div id="menu-card">
        <div id="menu-title">Menu</div>
        <div class="menu-row">
            <button id="menu-resume" class="menu-btn">Resume (M)</button>
            <button id="menu-reset" class="menu-btn">Reset Car</button>
            <button id="menu-mode" class="menu-btn">Current Round</button>
            <button id="menu-guide" class="menu-btn">How To Play</button>
        </div>
        <div id="menu-info"></div>
    </div>
</div>

<footer class="ftr">
    <span>Arrows / WASD · M = Menu · T = race/solo sprint (Nords)</span>
    <span>Nordschleife 20.8km</span>
</footer>

<script>window.NORD_MP_RELAY_URL = 'wss://makefuture.ro/ws';</script>
<script type="module">
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

// =====================================================================
// ZzFX - Zuper Zmall Zound Zynth v1.3.2 ~ MIT License ~ Frank Force
// =====================================================================
const zzfxV=.3;let zzfxX;
function zzfx(v,r,f,a,s,re,sh,sc,sl,ds,pj,pjt,rt,n,m,bc,d,sv,dc,tr){
    try{if(!zzfxX)zzfxX=new(window.AudioContext||window.webkitAudioContext);if(zzfxX.state==='suspended')zzfxX.resume();
    const P=Math.PI*2,R=44100;let b=[],i=0,j=0,T=0,F=0,c=0,q=1;v=(v!=null?v:1)*zzfxV;r=r||.05;a=a||0;s=s||0;re=re||.1;sh=sh||0;sc=sc||1;sl=sl||0;ds=ds||0;pj=pj||0;pjt=pjt||0;rt=rt||0;n=n||0;m=m||0;bc=bc||0;d=d||0;sv=sv!=null?sv:1;dc=dc||0;tr=tr||0;let S=sl,O=f=f||220;
    f*=(1+r*2*Math.random()-r)*P/R;sl*=500*P/R/R;ds*=500*P/R/R/R;pj*=P/R;m*=P/R;pjt*=R;rt=rt*R|0;a=a*R+9;dc*=R;s*=R;re*=R;d*=R;
    for(let L=a+dc+s+re+d|0;i<L;b[i++]=T*v){if(!(++c%(bc*100|0))){T=sh?sh>1?sh>2?sh>3?sh>4?Math.sin((F%P)**3):Math.max(Math.min(Math.tan(F),1),-1):1-(2*F/P%2+2)%2:1-4*Math.abs(Math.round(F/P)-F/P):Math.sin(F):Math.sin(F);T=(rt?1-tr+tr*Math.sin(P*i/rt):1)*(sh>4?T:Math.abs(T)**sc*(T<0?-1:1))*(i<a?i/a:i<a+dc?1-((i-a)/dc)*(1-sv):i<a+dc+s?sv:i<L-d?(L-i-d)/re*sv:0);T=d?T/2+(d>i?0:(i<L-d?1:(L-i)/d)*b[i-d|0]/2/v):T}f+=sl+=ds;F+=f+f*n*Math.sin(i**5);if(q&&++q>pjt){f+=pj;O+=pj;q=0}if(rt&&!(++j%rt)){f=O;sl=S;q=q||1}}
    const buf=zzfxX.createBuffer(1,b.length,R);buf.getChannelData(0).set(b);const src=zzfxX.createBufferSource();src.buffer=buf;src.connect(zzfxX.destination);src.start()}catch(e){}}

// =====================================================================
// MAKE FUTURE INTRO (shared across all experiments)
// =====================================================================
const FONT={M:[[1,1,1,1,1],[1,0,1,0,1],[1,0,0,0,1]],A:[[1,1,1],[1,1,1],[1,0,1]],K:[[1,0,1],[1,1,0],[1,0,1]],E:[[1,1,1],[1,1,0],[1,1,1]],F:[[1,1,1],[1,1,0],[1,0,0]],U:[[1,0,1],[1,0,1],[1,1,1]],T_:[[1,1,1],[0,1,0],[0,1,0]],R:[[1,1,0],[1,1,0],[1,0,1]]};
const vw=window.innerWidth,vh=window.innerHeight;
let tCS=Math.round(Math.min(vw,vh)/16);tCS=Math.max(tCS,24);tCS=Math.min(tCS,60);
const COLS=Math.max(25,Math.floor(vw/tCS)),ROWS=Math.max(9,Math.floor(vh/tCS));
const cs=Math.min(vw/COLS,vh/ROWS);
const tOX=Math.floor((COLS-23)/2),tOY=Math.floor((ROWS-7)/2),mI=Math.floor((23-17)/2);
const FILLED={};
[{c:'M',o:0},{c:'A',o:6},{c:'K',o:10},{c:'E',o:14}].forEach(l=>{FONT[l.c].forEach((row,ri)=>{row.forEach((p,ci)=>{if(p)FILLED[(tOY+ri)+','+(tOX+mI+l.o+ci)]=true})})});
[{c:'F',o:0},{c:'U',o:4},{c:'T_',o:8},{c:'U',o:12},{c:'R',o:16},{c:'E',o:20}].forEach(l=>{FONT[l.c].forEach((row,ri)=>{row.forEach((p,ci)=>{if(p)FILLED[(tOY+4+ri)+','+(tOX+l.o+ci)]=true})})});
const gridEl=document.getElementById('g');
gridEl.style.cssText=`grid-template-columns:repeat(${COLS},${cs}px);grid-template-rows:repeat(${ROWS},${cs}px);width:${COLS*cs}px;height:${ROWS*cs}px;left:${Math.floor((vw-COLS*cs)/2)}px;top:${Math.floor((vh-ROWS*cs)/2)}px`;
const board=[];
{const f=document.createDocumentFragment();
for(let r=0;r<ROWS;r++){board[r]=[];for(let c=0;c<COLS;c++){const el=document.createElement('div');
if(FILLED[r+','+c]){el.className='c f';el.style.cssText=`--d:${(.3+Math.random()*.8).toFixed(3)}s;--fd:${(Math.random()*.7).toFixed(3)}s`}
else el.className='c';board[r][c]=el;f.appendChild(el)}}gridEl.appendChild(f)}

// =====================================================================
// NORDSCHLEIFE TRACK — loaded from data/*.json (see scripts/build-nordschleife-data.mjs)
// =====================================================================
let spline;
let splineLen = 0;
let splinePoints = [];
let trackSamples = [];
let nordSectors = [];
let nordCheckpoints = [];
let nordLandmarks = [];
let nordTerrainCfg = null;
let nordProps = [];
let nordsWorldGroup = null;
let trackReady = false;
let trackLoadError = null;
let trackMeta = { lengthM: 20800, name: 'Nordschleife' };
let minimapBounds = { minX: -1, maxX: 1, minZ: -1, maxZ: 1 };
let nordRoadMesh = null;
let nordTerrainMesh = null;
let nordDriveMeshes = [];
let nordGroundMeshes = [];
let lastNearestTrack = null;
let lastGroundSource = 'track';
let lastSurfaceKind = 'road';
let lastRoadY = 0;
let lastTerrainY = 0;
let lastGripBudget = 0;
let lastSlipAmount = 0;
const debugTrackMode = new URLSearchParams(location.search).get('debug') === 'track';
const debugGuideMode = debugTrackMode && new URLSearchParams(location.search).get('guides') === '1';
let trackDebugEl = null;
let sessionPerf = { netIn: 0, netOut: 0, lastUiTs: 0, msgIn: 0, msgOut: 0 };

function getSectionAt(t) {
    const u = ((t % 1) + 1) % 1;
    for (const s of nordSectors) {
        if (u >= s.t0 && u < s.t1) return { name: s.name, alt: String(s.altM), grip: s.grip };
    }
    const last = nordSectors[nordSectors.length - 1];
    return last ? { name: last.name, alt: String(last.altM), grip: last.grip } : { name: 'Track', alt: '520', grip: 1 };
}

function getSectionOverrideAt(t) {
    const overrides = nordTerrainCfg?.sectionOverrides || [];
    const u = ((t % 1) + 1) % 1;
    for (const o of overrides) {
        if (u >= o.t0 && u < o.t1) return o;
    }
    return null;
}

// Tire screech
let screechCD = 0;
function sfxScreech() { if (screechCD > 0) return; zzfx(.12, .1, 80, .01, .06, .04, 4, 0, 0, 0, 0, 0, 0, .3); screechCD = 0.5; }

// Crash sound: metallic bang with falling pitch and crunch noise
// vol scaled by impact severity (0-1)
function sfxCrash(vol) {
    const v = Math.max(0.05, Math.min(0.8, vol));
    zzfx(v, 0.35, 130, 0.001, 0.06, 0.35, 0, 0.4, -0.5, 0, 0, 0, 0, 0.7, 0, 6, 0, 0.35);
}

// Effective collision sphere radius per car (meters)
const CRASH_DIST = 5.0;
const CRASH_DIST_SQ = CRASH_DIST * CRASH_DIST;

const PAL = ['#ff3d00','#0066ff','#b8ff00','#ff006e','#00f5d4','#9d4edd','#ffbe0b','#ff6d00','#20c997','#7b68ee','#00ff41','#ff2d95','#00d4aa','#ff8a00','#ef476f'];

// =====================================================================
// THREE.JS SETUP
// =====================================================================
const container = document.getElementById('three-container');
const promptEl = document.getElementById('prompt');
const scoresEl = document.getElementById('scores');
const flashEl = document.getElementById('hud-flash');
const sectionEl = document.getElementById('hud-section');

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(vw, vh);
renderer.setClearColor(0x080810);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.8;
container.appendChild(renderer.domElement);

const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x060810, 150, 900);

const camera = new THREE.PerspectiveCamera(65, vw / vh, 0.5, 3000);

// Post-processing: bloom for emissive glow
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
const bloomPass = new UnrealBloomPass(new THREE.Vector2(vw, vh), 0.35, 0.4, 0.88);
composer.addPass(bloomPass);

// Lighting
scene.add(new THREE.AmbientLight(0x8899aa, 1.5));
const sun = new THREE.DirectionalLight(0xccddee, 2.0);
sun.position.set(300, 500, 200);
scene.add(sun);
scene.add(new THREE.HemisphereLight(0x556677, 0x222233, 1.0));

// Sky dome with stars
const skyGeo = new THREE.SphereGeometry(2000, 32, 16);
const skyMat = new THREE.ShaderMaterial({
    side: THREE.BackSide, uniforms: {},
    vertexShader: `varying vec3 vPos; void main(){ vPos=position; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0); }`,
    fragmentShader: `varying vec3 vPos;
    float hash(vec2 p){ return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453123); }
    void main(){
        vec3 dir=normalize(vPos); float h=dir.y;
        // Rich night sky gradient
        vec3 zenith=vec3(0.005,0.008,0.03);
        vec3 mid=vec3(0.01,0.015,0.04);
        vec3 horizon=vec3(0.025,0.02,0.04);
        vec3 below=vec3(0.01,0.01,0.015);
        vec3 col;
        if(h>0.3) col=mix(mid,zenith,(h-0.3)/0.7);
        else if(h>0.0) col=mix(horizon,mid,h/0.3);
        else col=mix(horizon,below,min(1.0,-h*3.0));
        // Stars: only above horizon, multiple layers
        if(h>0.02){
            vec2 st=dir.xz/(h+0.15)*150.0;
            float s1=hash(floor(st));
            if(s1>0.995) col+=vec3(smoothstep(0.995,1.0,s1)*0.6); // bright stars
            vec2 st2=dir.xz/(h+0.2)*300.0;
            float s2=hash(floor(st2)+vec2(31.7,17.3));
            if(s2>0.997) col+=vec3(smoothstep(0.997,1.0,s2)*0.3); // dim stars
        }
        // Subtle warm horizon glow
        float glow=exp(-abs(h)*6.0)*0.015;
        col+=vec3(glow*1.5,glow*0.8,glow*0.5);
        gl_FragColor=vec4(col,1.0);
    }`
});
const skyMesh = new THREE.Mesh(skyGeo, skyMat);
scene.add(skyMesh);
const moonMesh = new THREE.Mesh(new THREE.SphereGeometry(12,16,16), new THREE.MeshBasicMaterial({color:0xddddcc}));
moonMesh.position.set(500, 800, -300); // relative to sky center
scene.add(moonMesh);

nordsWorldGroup = new THREE.Group();
scene.add(nordsWorldGroup);

// =====================================================================
// BUILD TRACK GEOMETRY (after GPX pipeline loads spline + JSON)
// =====================================================================
const ROAD_W = 8; // half-width
const SEGS = 3000;
const CAR_CLEARANCE = 0.06;

function sampleTrackAt(t) {
    if (!trackSamples.length) return new THREE.Vector3();
    const u = ((t % 1) + 1) % 1;
    const f = u * trackSamples.length;
    const i = Math.floor(f) % trackSamples.length;
    const j = (i + 1) % trackSamples.length;
    const mix = f - i;
    const a = trackSamples[i];
    const b = trackSamples[j];
    return new THREE.Vector3(
        a.x + (b.x - a.x) * mix,
        a.y + (b.y - a.y) * mix,
        a.z + (b.z - a.z) * mix
    );
}

function sampleTrackTangentAt(t) {
    if (trackSamples.length < 2) return new THREE.Vector3(0, 0, 1);
    const step = 1 / trackSamples.length;
    return sampleTrackAt(t + step).sub(sampleTrackAt(t - step)).normalize();
}

function getRightAt(t) {
    const tan = spline.getTangentAt(((t % 1) + 1) % 1).normalize();
    const up = new THREE.Vector3(0, 1, 0);
    return new THREE.Vector3().crossVectors(tan, up).normalize();
}

function getTrackSurface(offsetM) {
    const abs = Math.abs(offsetM);
    if (abs <= ROAD_W) return { kind: 'road', grip: 1, drag: 0 };
    if (abs <= ROAD_W + 0.8) return { kind: 'curb', grip: 0.74, drag: 0.2 };
    if (abs <= ROAD_W + 5) return { kind: 'shoulder', grip: 0.52, drag: 0.58 };
    return { kind: 'grass', grip: 0.28, drag: 1.45 };
}

function getRoadRibbonY(nearest) {
    if (!nearest) return 0;
    return getTrackFrameY(nearest.t, nearest.signedOffset || 0);
}

function getTrackFrameY(t, offsetM) {
    const pos = spline.getPointAt(t);
    const ov = getSectionOverrideAt(t);
    const roadLift = Number(ov?.roadYOffset) || 0;
    const roadBank = Number(ov?.bank) || 0;
    const lateral = Math.max(-1, Math.min(1, offsetM / ROAD_W));
    return pos.y + 0.05 + roadLift + roadBank * lateral;
}

function findNearestOnSamples(wx, wz, samples) {
    if (!samples.length) return { t: 0, dist: 1e9, y: 0, signedOffset: 0, progressM: 0, tangentX: 0, tangentZ: 1 };
    let bestD = Infinity;
    let best = null;
    const n = samples.length;
    for (let i = 0; i < n; i++) {
        const a = samples[i];
        const b = samples[(i + 1) % n];
        const vx = b.x - a.x;
        const vz = b.z - a.z;
        const lenSq = vx * vx + vz * vz;
        const u = lenSq > 0 ? Math.max(0, Math.min(1, ((wx - a.x) * vx + (wz - a.z) * vz) / lenSq)) : 0;
        const x = a.x + vx * u;
        const z = a.z + vz * u;
        const dx = wx - x;
        const dz = wz - z;
        const d = dx * dx + dz * dz;
        if (d < bestD) {
            const distM = a.distanceM != null && b.distanceM != null
                ? (i === n - 1 ? a.distanceM + (trackMeta.lengthM - a.distanceM) * u : a.distanceM + (b.distanceM - a.distanceM) * u)
                : ((i + u) / n) * trackMeta.lengthM;
            const t = ((distM / Math.max(1, trackMeta.lengthM)) % 1 + 1) % 1;
            const y = a.y + (b.y - a.y) * u;
            const len = Math.max(1e-6, Math.sqrt(lenSq));
            const tx = vx / len;
            const tz = vz / len;
            const rx = -tz;
            const rz = tx;
            bestD = d;
            best = {
                t,
                dist: Math.sqrt(d),
                y,
                signedOffset: (wx - x) * rx + (wz - z) * rz,
                progressM: distM,
                tangentX: tx,
                tangentZ: tz,
                rightX: rx,
                rightZ: rz,
                centerX: x,
                centerZ: z,
            };
        }
    }
    return best;
}

function _disposeObject3D(root) {
    root.traverse((ch) => {
        if (ch.geometry) ch.geometry.dispose();
        if (ch.material) {
            const mats = Array.isArray(ch.material) ? ch.material : [ch.material];
            for (const m of mats) {
                if (m.map) m.map.dispose();
                m.dispose();
            }
        }
    });
}

function buildNordschleifeWorld() {
    if (!spline || !nordsWorldGroup) return;
    while (nordsWorldGroup.children.length) {
        const ch = nordsWorldGroup.children[0];
        nordsWorldGroup.remove(ch);
        _disposeObject3D(ch);
    }

    nordRoadMesh = null;
    nordTerrainMesh = null;
    nordDriveMeshes = [];
    nordGroundMeshes = [];

    const add = (o) => { nordsWorldGroup.add(o); return o; };
    const addGround = (o) => {
        o.userData.nordGround = true;
        nordGroundMeshes.push(o);
        return add(o);
    };
    const addDrive = (o) => {
        o.userData.nordDrive = true;
        nordDriveMeshes.push(o);
        return addGround(o);
    };

    // --- Road mesh (CLOSED LOOP) with vertex color variation ---
    {
        const verts = [], idx = [], uvs = [], colors = [];
        for (let i = 0; i <= SEGS; i++) {
            const t = i / SEGS;
            const pos = spline.getPointAt(t % 1);
            const right = getRightAt(t % 1);
            const ov = getSectionOverrideAt(t);
            const roadLift = Number(ov?.roadYOffset) || 0;
            const roadBank = Number(ov?.bank) || 0;
            const L = pos.clone().addScaledVector(right, -ROAD_W);
            const R = pos.clone().addScaledVector(right, ROAD_W);
            L.y += 0.05 + roadLift - roadBank;
            R.y += 0.05 + roadLift + roadBank;
            verts.push(L.x, L.y, L.z, R.x, R.y, R.z);
            uvs.push(0, t * 500, 1, t * 500);
            const base = 0.25 + Math.sin(t * 200) * 0.02;
            colors.push(base * 0.85, base * 0.85, base * 0.88);
            colors.push(base * 0.85, base * 0.85, base * 0.88);
            if (i < SEGS) {
                const a = i * 2, b = i * 2 + 1, c = (i + 1) * 2, d = (i + 1) * 2 + 1;
                idx.push(a, b, c, b, d, c);
            }
        }
        const last = SEGS * 2;
        idx.push(last, last + 1, 0, last + 1, 1, 0);
        const geo = new THREE.BufferGeometry();
        geo.setAttribute('position', new THREE.Float32BufferAttribute(verts, 3));
        geo.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
        geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
        geo.setIndex(idx);
        geo.computeVertexNormals();
        nordRoadMesh = addDrive(new THREE.Mesh(geo, new THREE.MeshStandardMaterial({
            vertexColors: true, roughness: 0.85, side: THREE.DoubleSide,
        })));
    }

    function buildCurb(sideSign) {
        const w = 0.5;
        const verts = [], colors = [], idx = [];
        for (let i = 0; i <= SEGS; i++) {
            const t = i / SEGS;
            const pos = spline.getPointAt(t % 1);
            const right = getRightAt(t % 1);
            const ov = getSectionOverrideAt(t);
            const roadLift = Number(ov?.roadYOffset) || 0;
            const roadBank = Number(ov?.bank) || 0;
            const center = pos.clone().addScaledVector(right, sideSign * (ROAD_W + w * 0.5));
            const inner = center.clone().addScaledVector(right, -w * 0.5);
            const outer = center.clone().addScaledVector(right, w * 0.5);
            inner.y += 0.08 + roadLift + (sideSign < 0 ? -roadBank : roadBank);
            outer.y += 0.08 + roadLift + (sideSign < 0 ? -roadBank : roadBank);
            verts.push(inner.x, inner.y, inner.z, outer.x, outer.y, outer.z);
            const alt = Math.floor(i / 6) % 2;
            const c = alt ? [1, 0.2, 0] : [1, 1, 1];
            colors.push(c[0], c[1], c[2], c[0], c[1], c[2]);
            if (i < SEGS) {
                const a = i * 2, b = i * 2 + 1, c2 = (i + 1) * 2, d = (i + 1) * 2 + 1;
                idx.push(a, b, c2, b, d, c2);
            }
        }
        const last = SEGS * 2;
        idx.push(last, last + 1, 0, last + 1, 1, 0);
        const geo = new THREE.BufferGeometry();
        geo.setAttribute('position', new THREE.Float32BufferAttribute(verts, 3));
        geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
        geo.setIndex(idx);
        geo.computeVertexNormals();
        addGround(new THREE.Mesh(geo, new THREE.MeshStandardMaterial({
            vertexColors: true, emissive: 0x441100, emissiveIntensity: 0.4,
            roughness: 0.6, side: THREE.DoubleSide,
        })));
    }
    buildCurb(-1);
    buildCurb(1);

    function buildShoulder(sideSign) {
        const shoulderW = 4.5;
        const verts = [], colors = [], idx = [];
        for (let i = 0; i <= SEGS; i++) {
            const t = i / SEGS;
            const pos = spline.getPointAt(t % 1);
            const right = getRightAt(t % 1);
            const ov = getSectionOverrideAt(t);
            const roadLift = Number(ov?.roadYOffset) || 0;
            const roadBank = Number(ov?.bank) || 0;
            const bankY = roadLift + (sideSign < 0 ? -roadBank : roadBank);
            const inner = pos.clone().addScaledVector(right, sideSign * (ROAD_W + 0.55));
            const outer = pos.clone().addScaledVector(right, sideSign * (ROAD_W + shoulderW));
            inner.y += 0.025 + bankY;
            outer.y += -0.18 + bankY;
            verts.push(inner.x, inner.y, inner.z, outer.x, outer.y, outer.z);
            colors.push(0.11, 0.11, 0.1, 0.06, 0.09, 0.04);
            if (i < SEGS) {
                const a = i * 2, b = i * 2 + 1, c = (i + 1) * 2, d = (i + 1) * 2 + 1;
                idx.push(a, b, c, b, d, c);
            }
        }
        const last = SEGS * 2;
        idx.push(last, last + 1, 0, last + 1, 1, 0);
        const geo = new THREE.BufferGeometry();
        geo.setAttribute('position', new THREE.Float32BufferAttribute(verts, 3));
        geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
        geo.setIndex(idx);
        geo.computeVertexNormals();
        addGround(new THREE.Mesh(geo, new THREE.MeshStandardMaterial({
            vertexColors: true, roughness: 0.95, side: THREE.DoubleSide,
        })));
    }
    buildShoulder(-1);
    buildShoulder(1);

    function buildTerrainCorridor(sideSign) {
        const offsets = [ROAD_W + 4.5, 18, 34, 60, 95, 135];
        const drops = [0.22, 0.65, 1.2, 2.0, 3.0, 4.2];
        const verts = [], colors = [], idx = [];
        for (let i = 0; i <= SEGS; i++) {
            const t = i / SEGS;
            const pos = spline.getPointAt(t % 1);
            const right = getRightAt(t % 1);
            for (let k = 0; k < offsets.length; k++) {
                const off = sideSign * offsets[k];
                const p = pos.clone().addScaledVector(right, off);
                const wave = Math.sin(t * Math.PI * 80 + k * 1.7) * 0.06 + Math.cos(t * Math.PI * 31 + sideSign * 0.8) * 0.04;
                p.y = getTrackFrameY(t, off) - drops[k] + wave * Math.min(1, k / 2);
                verts.push(p.x, p.y, p.z);
                const shade = Math.max(0, Math.min(1, k / (offsets.length - 1)));
                colors.push(0.03 + shade * 0.02, 0.10 + shade * 0.05, 0.035 + shade * 0.015);
            }
            if (i < SEGS) {
                const row = i * offsets.length;
                const next = (i + 1) * offsets.length;
                for (let k = 0; k < offsets.length - 1; k++) {
                    const a = row + k, b = row + k + 1, c = next + k, d = next + k + 1;
                    idx.push(a, b, c, b, d, c);
                }
            }
        }
        const last = SEGS * offsets.length;
        for (let k = 0; k < offsets.length - 1; k++) {
            idx.push(last + k, last + k + 1, k, last + k + 1, k + 1, k);
        }
        const geo = new THREE.BufferGeometry();
        geo.setAttribute('position', new THREE.Float32BufferAttribute(verts, 3));
        geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
        geo.setIndex(idx);
        geo.computeVertexNormals();
        addGround(new THREE.Mesh(geo, new THREE.MeshStandardMaterial({
            vertexColors: true, roughness: 1, side: THREE.DoubleSide,
        })));
    }
    buildTerrainCorridor(-1);
    buildTerrainCorridor(1);

    // --- Center line (dashed white) ---
    {
        const lineW = 0.15;
        const dashLenM = 7.5;
        const dashGapM = 7.5;
        const verts = [], idx = [];
        const dashStep = (dashLenM + dashGapM) / Math.max(1, trackMeta.lengthM || 20700);
        const dashT = dashLenM / Math.max(1, trackMeta.lengthM || 20700);
        for (let t0 = 0; t0 < 1; t0 += dashStep) {
            const t1 = Math.min(1, t0 + dashT);
            const base = verts.length / 3;
            for (const t of [t0, t1]) {
                const pos = spline.getPointAt(t % 1);
                const right = getRightAt(t % 1);
                const L = pos.clone().addScaledVector(right, -lineW);
                const R = pos.clone().addScaledVector(right, lineW);
                L.y = getTrackFrameY(t, -lineW) + 0.025;
                R.y = getTrackFrameY(t, lineW) + 0.025;
                verts.push(L.x, L.y, L.z, R.x, R.y, R.z);
            }
            idx.push(base, base + 1, base + 2, base + 1, base + 3, base + 2);
        }
        const geo = new THREE.BufferGeometry();
        geo.setAttribute('position', new THREE.Float32BufferAttribute(verts, 3));
        geo.setIndex(idx);
        geo.computeVertexNormals();
        addGround(new THREE.Mesh(geo, new THREE.MeshStandardMaterial({
            color: 0xdddddd, emissive: 0x333333, emissiveIntensity: 0.3,
            roughness: 0.5, side: THREE.DoubleSide,
        })));
    }

    if (debugGuideMode) {
        const makeLine = (offset, color) => {
            const pts = [];
            for (let i = 0; i < Math.min(SEGS, 1200); i++) {
                const t = i / Math.min(SEGS, 1200);
                const p = spline.getPointAt(t);
                const r = getRightAt(t);
                pts.push(p.x + r.x * offset, getTrackFrameY(t, offset) + 0.06, p.z + r.z * offset);
            }
            const geo = new THREE.BufferGeometry();
            geo.setAttribute('position', new THREE.Float32BufferAttribute(pts, 3));
            add(new THREE.LineLoop(geo, new THREE.LineBasicMaterial({
                color, transparent: true, opacity: 0.45, depthWrite: false,
            })));
        };
        makeLine(0, 0x00f5d4);
        makeLine(-ROAD_W, 0xffbe0b);
        makeLine(ROAD_W, 0xffbe0b);
        makeLine(-(ROAD_W + 4.5), 0x66ff88);
        makeLine(ROAD_W + 4.5, 0x66ff88);
        makeLine(-135, 0x337744);
        makeLine(135, 0x337744);
    }

    // --- Terrain: macro envelope + procedural detail (see terrain.json) ---
    {
        const proc = (nordTerrainCfg && nordTerrainCfg.procedural) || {};
        const terrainSize = proc.terrainSize ?? 8000;
        const terrainSegs = proc.terrainSegs ?? 120;
        const shoulderBlendM = proc.shoulderBlendM ?? 100;
        const farNoiseAmp = proc.farNoiseAmp ?? 14;
        const farNoiseFreq = proc.farNoiseFreq ?? 0.0022;
        const macroRadialBoost = proc.macroRadialBoost ?? 1.12;

        const geo = new THREE.PlaneGeometry(terrainSize, terrainSize, terrainSegs, terrainSegs);
        geo.rotateX(-Math.PI / 2);
        const posAttr = geo.getAttribute('position');

        const TRACK_SAMPLE_STEP = 1;
        const terrainTrackSamples = [];
        let cx = 0, cz = 0;
        const terrainSource = trackSamples.length ? trackSamples : splinePts;
        for (let i = 0; i < terrainSource.length; i += TRACK_SAMPLE_STEP) {
            const p = terrainSource[i];
            terrainTrackSamples.push({ x: p.x, y: p.y, z: p.z, t: p.t, distanceM: p.distanceM });
            cx += p.x; cz += p.z;
        }
        cx /= terrainTrackSamples.length; cz /= terrainTrackSamples.length;
        const avgY = terrainTrackSamples.reduce((s, p) => s + p.y, 0) / terrainTrackSamples.length;

        function noise2d(x, z) {
            return Math.sin(x * farNoiseFreq) * Math.cos(z * farNoiseFreq * 1.36) * farNoiseAmp
                + Math.sin(x * farNoiseFreq * 3.2 + 1.3) * Math.cos(z * farNoiseFreq * 2.3 + 0.7) * (farNoiseAmp * 0.35);
        }

        const colors = [];
        for (let i = 0; i < posAttr.count; i++) {
            const x = posAttr.getX(i), z = posAttr.getZ(i);
            const nearestTerrain = findNearestOnSamples(x, z, terrainTrackSamples);
            const nearDist = nearestTerrain.dist;
            const nearT = nearestTerrain.t;
            const radial = Math.min(1, Math.hypot(x - cx, z - cz) / (terrainSize * 0.45));
            const macroLift = (radial * radial) * 6 * macroRadialBoost;
            const roadY = getTrackFrameY(nearT, nearestTerrain.signedOffset || 0);
            const farY = avgY + noise2d(x, z) + macroLift;
            const corridorClearM = 140;

            let y;
            if (nearDist < corridorClearM) {
                y = roadY - 5.5;
            } else if (nearDist < corridorClearM + shoulderBlendM) {
                const blend = (nearDist - corridorClearM) / Math.max(1e-3, shoulderBlendM);
                const eased = blend * blend * (3 - 2 * blend);
                y = (roadY - 5.5) * (1 - eased) + farY * eased;
            } else {
                y = farY;
            }
            posAttr.setY(i, y);
            const g = 0.04 + Math.sin(x * 0.01 + z * 0.01) * 0.015;
            colors.push(0.02, Math.max(0.03, g), 0.01);
        }
        geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
        geo.computeVertexNormals();
        nordTerrainMesh = addGround(new THREE.Mesh(geo, new THREE.MeshStandardMaterial({
            vertexColors: true, roughness: 1, flatShading: true,
        })));
    }

    // --- Trees (instanced cone+cylinder) ---
    {
        const trunkGeo = new THREE.CylinderGeometry(0.15, 0.2, 2.5, 5);
        const foliageGeo = new THREE.ConeGeometry(1.5, 4, 6);
        foliageGeo.translate(0, 4, 0);
        trunkGeo.translate(0, 1.25, 0);
        const treeMat = new THREE.MeshStandardMaterial({ color: 0x1a3a1a, roughness: 0.9, flatShading: true });
        const treeCount = 2500;
        const treeMesh = new THREE.InstancedMesh(foliageGeo, treeMat, treeCount);
        const trunkMat = new THREE.MeshStandardMaterial({ color: 0x3a2a1a, roughness: 1 });
        const trunkMesh = new THREE.InstancedMesh(trunkGeo, trunkMat, treeCount);
        const dm = new THREE.Object3D();
        const treeCol = new THREE.Color();
        let placed = 0;
        for (let i = 0; i < treeCount * 3 && placed < treeCount; i++) {
            const t = Math.random();
            const pos = spline.getPointAt(t);
            const right = getRightAt(t);
            const side = Math.random() < 0.5 ? -1 : 1;
            const dist = ROAD_W + 4 + Math.random() * 35;
            const sec = getSectionAt(t);
            const isForest = sec && (sec.name.includes('Forst') || sec.name.includes('Fuchsrohre') || sec.name.includes('Kesselchen') || sec.name.includes('Klostertal') || sec.name.includes('Breidscheid') || sec.name.includes('Tiergarten'));
            if (!isForest && dist > 15 && Math.random() > 0.3) continue;
            if (sec && sec.name.includes('Dottinger') && Math.random() > 0.15) continue;
            dm.position.copy(pos).addScaledVector(right, side * dist);
            dm.position.y = pos.y - 1 + Math.random() * 0.5;
            const scale = 0.6 + Math.random() * 0.8;
            dm.scale.set(scale, scale * (0.8 + Math.random() * 0.4), scale);
            dm.rotation.y = Math.random() * Math.PI * 2;
            dm.updateMatrix();
            treeMesh.setMatrixAt(placed, dm.matrix);
            trunkMesh.setMatrixAt(placed, dm.matrix);
            const g = 0.1 + Math.random() * 0.15;
            treeCol.setRGB(0.02 + Math.random() * 0.03, g, 0.02 + Math.random() * 0.02);
            treeMesh.setColorAt(placed, treeCol);
            treeCol.setRGB(0.15, 0.1, 0.05);
            trunkMesh.setColorAt(placed, treeCol);
            placed++;
        }
        treeMesh.count = placed;
        trunkMesh.count = placed;
        treeMesh.instanceMatrix.needsUpdate = true;
        treeMesh.instanceColor.needsUpdate = true;
        trunkMesh.instanceMatrix.needsUpdate = true;
        trunkMesh.instanceColor.needsUpdate = true;
        add(treeMesh);
        add(trunkMesh);
    }

    // --- Trackside markers (instanced) ---
    {
        const geo = new THREE.BoxGeometry(0.2, 1.8, 0.2);
        const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: 0xffffff, emissiveIntensity: 0.6 });
        const count = 600;
        const mesh = new THREE.InstancedMesh(geo, mat, count);
        const dummy = new THREE.Object3D();
        const col = new THREE.Color();
        for (let i = 0; i < count; i++) {
            const t = (i / count + Math.random() * 0.0003) % 1;
            const pos = spline.getPointAt(t);
            const right = getRightAt(t);
            const side = Math.random() < 0.5 ? -1 : 1;
            const offset = ROAD_W + 1.5 + Math.random() * 1.5;
            dummy.position.copy(pos).addScaledVector(right, side * offset);
            dummy.position.y += 0.9;
            dummy.updateMatrix();
            mesh.setMatrixAt(i, dummy.matrix);
            col.set(PAL[Math.floor(Math.random() * PAL.length)]);
            mesh.setColorAt(i, col);
        }
        mesh.instanceMatrix.needsUpdate = true;
        mesh.instanceColor.needsUpdate = true;
        add(mesh);
    }

    // --- Barriers on tight corners ---
    {
        const barrierGeo = new THREE.BoxGeometry(0.4, 0.7, 3);
        const barrierMat = new THREE.MeshStandardMaterial({ color: 0x888888, roughness: 0.8 });
        const barrierCount = 400;
        const barriers = new THREE.InstancedMesh(barrierGeo, barrierMat, barrierCount);
        const dm = new THREE.Object3D();
        const bc = new THREE.Color();
        let bPlaced = 0;
        for (let i = 0; i < 3000 && bPlaced < barrierCount; i++) {
            const t = i / 3000;
            const t1 = (t + 0.001) % 1, t0 = ((t - 0.001) + 1) % 1;
            const tan0 = spline.getTangentAt(t0), tan1 = spline.getTangentAt(t1);
            const curvature = Math.abs(new THREE.Vector3().crossVectors(tan0, tan1).y);
            if (curvature < 0.0001) continue;
            const pos = spline.getPointAt(t);
            const right = getRightAt(t);
            const tangent = spline.getTangentAt(t);
            const side = new THREE.Vector3().crossVectors(tan0, tan1).y > 0 ? 1 : -1;
            dm.position.copy(pos).addScaledVector(right, side * (ROAD_W + 1.2));
            dm.position.y += 0.35;
            dm.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), tangent.normalize());
            dm.updateMatrix();
            barriers.setMatrixAt(bPlaced, dm.matrix);
            bc.setRGB(0.5 + (bPlaced % 2) * 0.3, 0.5 + (bPlaced % 2) * 0.3, 0.5 + (bPlaced % 2) * 0.3);
            barriers.setColorAt(bPlaced, bc);
            bPlaced++;
        }
        barriers.count = bPlaced;
        barriers.instanceMatrix.needsUpdate = true;
        barriers.instanceColor.needsUpdate = true;
        add(barriers);
    }

    // --- Landmarks from generated landmarks.json ---
    for (const lm of nordLandmarks) {
        const tt = ((Number(lm.t) % 1) + 1) % 1;
        const pos = spline.getPointAt(tt);
        const right = getRightAt(tt);
        const tan = spline.getTangentAt(tt).normalize();
        const off = Number(lm.offset) || 0;
        const sc = Number(lm.scale) || 1;
        const base = pos.clone().addScaledVector(right, off);
        const kind = lm.kind || 'sign';
        if (kind === 'gantry') {
            const mat = new THREE.MeshStandardMaterial({ color: 0x333344, metalness: 0.4, roughness: 0.5 });
            const leg = new THREE.Mesh(new THREE.BoxGeometry(0.35, 5, 0.35), mat);
            leg.position.copy(base).addScaledVector(right, -4);
            leg.position.y += 2.5;
            add(leg);
            const leg2 = leg.clone();
            leg2.position.copy(base).addScaledVector(right, 4);
            leg2.position.y += 2.5;
            add(leg2);
            const beam = new THREE.Mesh(new THREE.BoxGeometry(9, 0.25, 0.5), mat);
            beam.position.copy(base);
            beam.position.y += 5;
            beam.quaternion.setFromUnitVectors(new THREE.Vector3(1, 0, 0), right);
            add(beam);
        } else if (kind === 'sign') {
            const m = new THREE.Mesh(new THREE.BoxGeometry(2.2 * sc, 1.1 * sc, 0.08), new THREE.MeshStandardMaterial({
                color: 0xeeeeff, emissive: 0x222244, emissiveIntensity: 0.5,
            }));
            m.position.copy(base).addScaledVector(right, ROAD_W + 3);
            m.position.y += 2;
            m.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), tan.clone().multiplyScalar(-1).add(new THREE.Vector3(0, 0.4, 0)).normalize());
            add(m);
        } else if (kind === 'banked') {
            const m = new THREE.Mesh(new THREE.BoxGeometry(10 * sc, 0.4, 4 * sc), new THREE.MeshStandardMaterial({ color: 0x555560, roughness: 0.85 }));
            m.position.copy(base);
            m.position.y -= 0.2;
            m.rotation.z = 0.35;
            m.rotation.y = Math.atan2(tan.x, tan.z);
            add(m);
        } else if (kind === 'spectator') {
            const g = new THREE.InstancedMesh(new THREE.BoxGeometry(0.35, 1.2, 0.25), new THREE.MeshStandardMaterial({ color: 0x223344, roughness: 0.9 }), 24);
            const d = new THREE.Object3D();
            let n = 0;
            for (let k = 0; k < 24; k++) {
                d.position.copy(base).addScaledVector(right, (k % 6 - 2.5) * 1.2).addScaledVector(tan, (Math.floor(k / 6) - 1) * 1.5);
                d.position.y += 0.6;
                d.rotation.y = Math.random() * 0.5;
                d.updateMatrix();
                g.setMatrixAt(n++, d.matrix);
            }
            g.count = n;
            g.instanceMatrix.needsUpdate = true;
            add(g);
        } else if (kind === 'jump') {
            const m = new THREE.Mesh(new THREE.BoxGeometry(6 * sc, 0.35, 3 * sc), new THREE.MeshStandardMaterial({ color: 0x444455, roughness: 0.7 }));
            m.position.copy(base);
            m.position.y += 0.15;
            m.rotation.x = -0.45;
            m.rotation.y = Math.atan2(tan.x, tan.z);
            add(m);
        }
    }

    // --- Data-driven props (props.json) ---
    if (Array.isArray(nordProps) && nordProps.length > 0) {
        const byKind = new Map();
        for (const p of nordProps) {
            const kind = String(p.kind || 'post');
            if (!byKind.has(kind)) byKind.set(kind, []);
            byKind.get(kind).push(p);
        }
        for (const [kind, items] of byKind) {
            let geo;
            let mat;
            if (kind === 'lamp') {
                geo = new THREE.CylinderGeometry(0.08, 0.1, 5.2, 6);
                mat = new THREE.MeshStandardMaterial({ color: 0x666c74, roughness: 0.8 });
            } else if (kind === 'barrier') {
                geo = new THREE.BoxGeometry(1.4, 0.6, 0.24);
                mat = new THREE.MeshStandardMaterial({ color: 0x8b8f95, roughness: 0.85 });
            } else if (kind === 'spectator') {
                geo = new THREE.BoxGeometry(0.32, 1.25, 0.26);
                mat = new THREE.MeshStandardMaterial({ color: 0x293142, roughness: 0.9 });
            } else {
                geo = new THREE.BoxGeometry(0.16, 1.8, 0.16);
                mat = new THREE.MeshStandardMaterial({ color: 0xdedede, roughness: 0.7 });
            }
            const mesh = new THREE.InstancedMesh(geo, mat, items.length);
            const d = new THREE.Object3D();
            const col = new THREE.Color();
            let n = 0;
            for (const it of items) {
                const tt = ((Number(it.t) % 1) + 1) % 1;
                const pos = spline.getPointAt(tt);
                const right = getRightAt(tt);
                const tan = spline.getTangentAt(tt).normalize();
                const off = Number(it.offset) || 0;
                d.position.copy(pos).addScaledVector(right, off);
                d.position.y += Number(it.yOffset) || 0;
                d.scale.setScalar(Number(it.scale) || 1);
                d.rotation.y = Math.atan2(tan.x, tan.z);
                d.updateMatrix();
                mesh.setMatrixAt(n, d.matrix);
                if (it.color) {
                    try { col.set(it.color); mesh.setColorAt(n, col); } catch (_) {}
                }
                n++;
            }
            mesh.count = n;
            mesh.instanceMatrix.needsUpdate = true;
            if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
            add(mesh);
        }
    }

    // --- Selective side areas: pull-offs/service pads at key sectors ---
    const sideAreas = [
        { t: 0.01, side: -1, len: 36, depth: 20, yaw: 0 },
        { t: 0.22, side: 1, len: 26, depth: 16, yaw: 0.08 },
        { t: 0.84, side: -1, len: 32, depth: 18, yaw: -0.06 },
    ];
    for (const area of sideAreas) {
        const tt = ((area.t % 1) + 1) % 1;
        const pos = spline.getPointAt(tt);
        const right = getRightAt(tt);
        const tan = spline.getTangentAt(tt).normalize();
        const ctr = pos.clone().addScaledVector(right, area.side * (ROAD_W + area.depth * 0.5 + 6));
        const padGeo = new THREE.BoxGeometry(area.len, 0.25, area.depth);
        const pad = new THREE.Mesh(padGeo, new THREE.MeshStandardMaterial({ color: 0x3d3f44, roughness: 0.85 }));
        pad.position.copy(ctr);
        pad.position.y = pos.y - 0.45;
        pad.rotation.y = Math.atan2(tan.x, tan.z) + area.yaw;
        addGround(pad);

        const lane = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, area.depth * 0.5), new THREE.MeshStandardMaterial({ color: 0x484a50, roughness: 0.8 }));
        lane.position.copy(pos).addScaledVector(right, area.side * (ROAD_W + 2.5));
        lane.position.y = pos.y - 0.4;
        lane.rotation.y = Math.atan2(tan.x, tan.z);
        addGround(lane);
    }

    chaosPickupPos = [];
    for (let i = 0; i < 28; i++) {
        const tt = (i * 0.037 + 0.02) % 1;
        const p = spline.getPointAt(tt);
        const right = getRightAt(tt);
        chaosPickupPos.push({
            x: p.x + right.x * (ROAD_W + 7),
            z: p.z + right.z * (ROAD_W + 7),
            hit: false,
        });
    }
}

// =====================================================================
// CAR
// =====================================================================
// =====================================================================
// CAR — Load GLB model, fallback to simple box
// =====================================================================
const carGroup = new THREE.Group();
scene.add(carGroup);
let brakeLightMat = null;

// Blob shadow: soft radial gradient, sits on road independently of car Y
const _shadowCanvas = document.createElement('canvas');
_shadowCanvas.width = 64; _shadowCanvas.height = 64;
{const sc = _shadowCanvas.getContext('2d');
const g = sc.createRadialGradient(32,32,0,32,32,32);
g.addColorStop(0,'rgba(0,0,0,0.3)');g.addColorStop(0.5,'rgba(0,0,0,0.1)');g.addColorStop(1,'rgba(0,0,0,0)');
sc.fillStyle=g;sc.fillRect(0,0,64,64);}
const shadowTex = new THREE.CanvasTexture(_shadowCanvas);
const shadowPlane = new THREE.Mesh(
    new THREE.PlaneGeometry(4.5, 6),
    new THREE.MeshBasicMaterial({ map: shadowTex, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -1 })
);
shadowPlane.geometry.rotateX(-Math.PI / 2);
shadowPlane.renderOrder = -1;
scene.add(shadowPlane);

// Dust particle system (simple pooled points)
const DUST_MAX = 200;
const dustPositions = new Float32Array(DUST_MAX * 3);
const dustAlphas = new Float32Array(DUST_MAX);
const dustVelocities = [];
for (let i = 0; i < DUST_MAX; i++) dustVelocities.push({ x: 0, y: 0, z: 0, life: 0 });
const dustGeo = new THREE.BufferGeometry();
dustGeo.setAttribute('position', new THREE.Float32BufferAttribute(dustPositions, 3));
const dustMat = new THREE.PointsMaterial({ color: 0x886644, size: 1.5, transparent: true, opacity: 0.4, depthWrite: false, sizeAttenuation: true });
const dustPoints = new THREE.Points(dustGeo, dustMat);
scene.add(dustPoints);
let dustIdx = 0;

function spawnDust(x, y, z, speed) {
    const i = dustIdx % DUST_MAX;
    dustPositions[i*3] = x + (Math.random()-0.5) * 2;
    dustPositions[i*3+1] = y + Math.random() * 0.3;
    dustPositions[i*3+2] = z + (Math.random()-0.5) * 2;
    dustVelocities[i] = { x: (Math.random()-0.5)*speed*0.1, y: 0.5+Math.random()*1.5, z: (Math.random()-0.5)*speed*0.1, life: 1.0 };
    dustIdx++;
}

function updateDust(dt) {
    for (let i = 0; i < DUST_MAX; i++) {
        const v = dustVelocities[i];
        if (v.life <= 0) continue;
        v.life -= dt * 1.5;
        dustPositions[i*3] += v.x * dt;
        dustPositions[i*3+1] += v.y * dt;
        dustPositions[i*3+2] += v.z * dt;
        v.y -= 0.5 * dt; // gravity
        if (v.life <= 0) { dustPositions[i*3+1] = -1000; } // hide
    }
    dustGeo.getAttribute('position').needsUpdate = true;
}

// Wind noise removed — was annoying

// Fallback car (simple white box while model loads)
const fallbackCar = new THREE.Group();
{
    const mat = new THREE.MeshStandardMaterial({ color: 0xf0f0f0, roughness: 0.3, metalness: 0.4 });
    const body = new THREE.Mesh(new THREE.BoxGeometry(2, 0.5, 4.5), mat);
    body.position.y = 0.4;
    fallbackCar.add(body);
    const cabin = new THREE.Mesh(new THREE.BoxGeometry(1.6, 0.4, 2), new THREE.MeshStandardMaterial({ color: 0x334455, roughness: 0.2 }));
    cabin.position.set(0, 0.85, -0.3);
    fallbackCar.add(cabin);
    // Tail light
    const tl = new THREE.Mesh(new THREE.BoxGeometry(1.6, 0.08, 0.04), new THREE.MeshStandardMaterial({ color: 0xff0000, emissive: 0xff0000, emissiveIntensity: 1.5 }));
    tl.position.set(0, 0.45, -2.25);
    fallbackCar.add(tl);
}
carGroup.add(fallbackCar);

// Headlight
const carSpot = new THREE.SpotLight(0xffffdd, 10, 150, Math.PI / 8, 0.5);
carSpot.position.set(0, 0.6, 2.5);
carSpot.target.position.set(0, -2, 40);
carGroup.add(carSpot);
carGroup.add(carSpot.target);

/** Build a remote player's car. Shows a procedural box immediately, swaps in
 *  the GLB model (same random index that player sent on join) once loaded. */
function createRemoteCar(name, colorStr, modelIdx) {
    const g = new THREE.Group();

    // Procedural stand-in (shown until/if GLB loads)
    let bodyColor = 0x888888;
    try { bodyColor = new THREE.Color(colorStr).getHex(); } catch (_) {}
    const bodyMat = new THREE.MeshStandardMaterial({ color: bodyColor, roughness: 0.3, metalness: 0.4 });
    const body = new THREE.Mesh(new THREE.BoxGeometry(2, 0.5, 4.5), bodyMat);
    body.position.y = 0.4;
    g.add(body);
    const cabin = new THREE.Mesh(new THREE.BoxGeometry(1.6, 0.4, 2), new THREE.MeshStandardMaterial({ color: 0x334455, roughness: 0.2 }));
    cabin.position.set(0, 0.85, -0.3);
    g.add(cabin);
    const tl = new THREE.Mesh(new THREE.BoxGeometry(1.6, 0.08, 0.04), new THREE.MeshStandardMaterial({ color: 0xff0000, emissive: 0xff0000, emissiveIntensity: 1.5 }));
    tl.position.set(0, 0.45, -2.25);
    g.add(tl);
    const hl = new THREE.Mesh(new THREE.BoxGeometry(0.35, 0.12, 0.08), new THREE.MeshStandardMaterial({ color: 0xffffdd, emissive: 0xffffdd, emissiveIntensity: 2.2 }));
    hl.position.set(0, 0.45, 2.2);
    g.add(hl);
    const proceduralParts = [body, cabin, tl, hl];

    // Name label (always kept above car)
    const cnv = document.createElement('canvas');
    cnv.width = 256; cnv.height = 64;
    const cx = cnv.getContext('2d');
    cx.fillStyle = 'rgba(0,0,0,0.55)';
    cx.fillRect(12, 10, 232, 44);
    cx.fillStyle = '#fff';
    cx.font = '600 26px system-ui,-apple-system,sans-serif';
    cx.textAlign = 'center'; cx.textBaseline = 'middle';
    cx.fillText(String(name).slice(0, 16), 128, 32);
    const tex = new THREE.CanvasTexture(cnv);
    tex.needsUpdate = true;
    const spr = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, transparent: true, depthTest: true }));
    spr.scale.set(4.2, 1.05, 1);
    spr.position.set(0, 2.5, 0);
    g.add(spr);

    // Async load GLB model, remove procedural stand-in when ready
    if (modelIdx !== undefined && modelIdx !== null && CAR_MODEL_DEFS[modelIdx]) {
        loadCarModelInto(g, modelIdx, (loaded) => {
            if (loaded) {
                proceduralParts.forEach(m => {
                    g.remove(m);
                    if (m.geometry) m.geometry.dispose();
                    if (m.material) m.material.dispose();
                });
            }
        });
    }

    scene.add(g);
    return g;
}

// =====================================================================
// CAR MODELS — 6 GLB models randomly assigned per session
// yRot: rotation to make car face +Z (game forward). Adjust if a model
// loads facing the wrong direction.
// =====================================================================
const CAR_MODEL_DEFS = [
    { url: '/assets/cars/race.glb',             targetLen: 4.2, yRot: 0 },
    { url: '/assets/cars/race-future.glb',      targetLen: 4.2, yRot: 0 },
    { url: '/assets/cars/sedan-sports.glb',     targetLen: 4.5, yRot: 0 },
    { url: '/assets/cars/hatchback-sports.glb', targetLen: 4.2, yRot: 0 },
    { url: '/assets/cars/nissan-gtr.glb',       targetLen: 4.5, yRot: 0 },
    { url: '/assets/cars/lambo.glb',            targetLen: 4.5, yRot: 0 },
    { url: '/assets/cars/ferrari-f40.glb',      targetLen: 4.2, yRot: 0 },
    { url: '/assets/cars/rx7.glb',              targetLen: 4.3, yRot: 0 },
    { url: '/assets/cars/sportster.glb',        targetLen: 4.3, yRot: 0 },
    { url: '/assets/cars/charger.glb',          targetLen: 4.8, yRot: 0 },
];
const myCarModelIdx = Math.floor(Math.random() * CAR_MODEL_DEFS.length);
const _glbLoader = new GLTFLoader();
const _modelCache = new Map(); // url -> normalized scene (source, never added to scene graph)

function _normalizeGltfScene(gltfScene, def) {
    gltfScene.rotation.y = def.yRot;
    gltfScene.updateMatrixWorld(true);
    const box = new THREE.Box3().setFromObject(gltfScene);
    const size = box.getSize(new THREE.Vector3());
    const longestH = Math.max(size.x, size.z);
    if (longestH > 0) gltfScene.scale.setScalar(def.targetLen / longestH);
    gltfScene.updateMatrixWorld(true);
    const box2 = new THREE.Box3().setFromObject(gltfScene);
    const center = box2.getCenter(new THREE.Vector3());
    gltfScene.position.x -= center.x;
    gltfScene.position.z -= center.z;
    gltfScene.position.y -= box2.min.y;
}

function loadCarModelInto(targetGroup, idx, onDone) {
    const def = CAR_MODEL_DEFS[idx] || CAR_MODEL_DEFS[0];
    const cached = _modelCache.get(def.url);
    if (cached) {
        const clone = cached.clone();
        targetGroup.add(clone);
        if (onDone) onDone(clone);
        return;
    }
    _glbLoader.load(def.url, (gltf) => {
        _normalizeGltfScene(gltf.scene, def);
        _modelCache.set(def.url, gltf.scene);
        const clone = gltf.scene.clone();
        targetGroup.add(clone);
        if (onDone) onDone(clone);
    }, undefined, (err) => {
        console.warn('[car] Failed to load', def.url, err);
        if (onDone) onDone(null);
    });
}

// Load player's own model; swap out procedural fallback when ready
loadCarModelInto(carGroup, myCarModelIdx, (loaded) => {
    if (loaded) {
        carGroup.remove(fallbackCar);
        fallbackCar.traverse(c => {
            if (c.geometry) c.geometry.dispose();
            if (c.material) c.material.dispose();
        });
    }
});

// =====================================================================
// =====================================================================
// CLUJ-NAPOCA MAP DATA (secret map — type "cluj" on intro)
// =====================================================================
const CLUJ_ROADS = [
  {n:'Piața Ștefan cel Mare',t:'p',c:[[624.6,-321.4],[628.3,-337.8],[628.7,-340.0]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[524.3,-61.0],[526.8,-66.9],[529.1,-73.0],[545.5,-114.7]]},
  {n:'Strada Posada',t:'p',c:[[716.1,-278.0],[706.6,-282.4],[697.6,-286.7],[683.7,-293.3],[639.2,-314.5],[634.6,-316.6],[624.6,-321.4]]},
  {n:'Piața Avram Iancu',t:'p',c:[[524.3,-61.0],[541.2,-54.4],[546.0,-52.2],[550.6,-50.5],[556.7,-48.3],[562.1,-46.0],[567.9,-43.7],[578.8,-39.3],[582.9,-37.8],[586.0,-36.5],[597.6,-31.9]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[716.1,-278.0],[711.6,-267.1],[710.9,-265.6],[709.2,-262.0]]},
  {n:'',t:'p',c:[[635.1,-392.7],[641.3,-396.6],[645.6,-399.9],[654.3,-406.9]]},
  {n:'Strada Napoca',t:'p',c:[[-224.3,-415.2],[-193.0,-397.9],[-102.2,-345.3],[-92.2,-339.0],[-22.8,-293.1],[-3.8,-280.6],[-2.1,-279.5],[6.2,-273.9]]},
  {n:'Calea Dorobanților',t:'p',c:[[597.6,-31.9],[609.6,-27.7],[629.8,-21.0],[670.8,-8.4],[721.9,7.3],[739.7,12.9]]},
  {n:'Calea Turzii',t:'p',c:[[655.6,-476.2],[655.5,-473.8],[656.4,-465.8],[658.2,-460.6],[661.0,-456.0],[666.0,-451.1],[673.0,-445.8],[681.0,-441.7],[684.2,-440.3],[697.2,-436.7]]},
  {n:'Strada Memorandumului',t:'p',c:[[-93.2,-105.4],[-101.4,-109.9],[-106.3,-113.0],[-177.9,-157.2],[-179.7,-158.3],[-213.3,-178.3],[-227.7,-186.9],[-254.5,-202.7]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[436.8,149.0],[424.7,143.2],[417.6,140.3],[409.2,136.9],[400.9,133.6],[358.7,117.2],[266.6,81.9],[263.7,80.8],[256.7,78.1]]},
  {n:'Bulevardul Eroilor',t:'p',c:[[81.5,-236.8],[98.2,-229.8],[107.5,-225.8],[205.6,-183.1],[222.9,-175.8],[253.8,-163.0],[470.0,-82.0],[476.6,-79.7]]},
  {n:'Strada Regele Ferdinand',t:'p',c:[[-119.8,273.3],[-126.9,287.5]]},
  {n:'Strada Horea',t:'p',c:[[-182.4,392.3],[-178.6,383.8]]},
  {n:'Strada Horea',t:'p',c:[[-149.1,324.1],[-161.9,349.2],[-170.1,365.3]]},
  {n:'Piața Unirii',t:'p',c:[[6.2,-273.9],[13.1,-269.2],[19.0,-265.6],[25.5,-262.0],[34.4,-257.6],[81.5,-236.8]]},
  {n:'Strada Milton Lehrer',t:'p',c:[[697.2,-436.7],[711.3,-433.0],[727.3,-428.0],[739.9,-423.7],[743.0,-422.6]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[1171.8,531.1],[1169.6,530.0],[1168.5,529.4],[1167.3,528.9],[1164.9,527.7],[1158.7,524.4],[1143.3,517.3]]},
  {n:'Strada Horea',t:'p',c:[[-184.5,992.8],[-186.6,958.4],[-189.4,916.5],[-190.3,897.4],[-190.6,863.9],[-191.2,781.4]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[520.9,190.3],[502.9,180.8]]},
  {n:'Piața Unirii',t:'p',c:[[24.4,-21.7],[9.3,-35.8]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[746.9,314.5],[739.2,310.3],[662.5,269.1],[585.5,226.2]]},
  {n:'Calea Turzii',t:'p',c:[[635.1,-392.7],[636.5,-414.5],[637.2,-420.9],[638.8,-434.7],[640.2,-446.4],[642.6,-458.6],[645.2,-470.6],[647.0,-476.2],[649.8,-481.8],[659.2,-497.3]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[1115.1,504.0],[1077.9,486.7],[1068.0,482.0],[1050.9,474.1],[991.8,445.9],[939.1,417.7],[924.2,409.5],[857.3,374.4],[841.4,365.9],[825.6,357.5],[779.9,333.2],[754.2,318.8],[751.1,317.8],[746.9,314.5]]},
  {n:'Piața Avram Iancu',t:'p',c:[[436.8,149.0],[437.8,147.1],[439.2,143.7],[443.1,134.8],[484.3,40.1],[516.8,-42.2]]},
  {n:'Strada Milton Lehrer',t:'p',c:[[743.0,-422.6],[749.9,-417.7],[755.5,-411.1],[758.5,-404.3],[761.4,-398.8]]},
  {n:'Calea Moților',t:'p',c:[[-1139.2,-731.4],[-1133.7,-727.8],[-1127.3,-723.8],[-1119.0,-719.0]]},
  {n:'Strada Regele Ferdinand',t:'p',c:[[24.4,-21.7],[20.6,-12.0],[18.7,-7.0],[14.3,5.2],[11.8,11.6],[-16.5,87.0]]},
  {n:'Calea Moților',t:'p',c:[[-630.4,-469.1],[-616.1,-458.8],[-587.8,-438.4]]},
  {n:'Piața Unirii',t:'p',c:[[81.5,-236.8],[86.0,-231.2],[87.8,-225.2],[87.3,-217.1],[84.5,-208.9],[82.6,-204.0],[51.0,-127.7],[34.6,-91.7]]},
  {n:'Strada Petru Maior',t:'p',c:[[-357.2,-273.6],[-353.4,-282.6],[-350.4,-289.3],[-328.8,-337.5],[-298.6,-404.7],[-297.1,-408.1],[-294.4,-414.1],[-292.4,-419.5],[-291.8,-420.7]]},
  {n:'Calea Moților',t:'p',c:[[-929.1,-631.5],[-893.2,-614.2],[-891.9,-613.6],[-858.0,-597.5],[-835.2,-586.4],[-805.6,-572.2],[-775.1,-556.7],[-763.5,-550.6],[-735.6,-535.8],[-719.2,-526.1],[-690.4,-508.4],[-668.2,-494.1],[-658.2,-488.0],[-650.5,-483.5]]},
  {n:'Piața Avram Iancu',t:'p',c:[[597.6,-31.9],[594.1,-25.1],[592.5,-22.3],[574.7,19.5]]},
  {n:'Calea Turzii',t:'p',c:[[640.7,-854.2],[642.8,-845.3],[659.9,-761.6]]},
  {n:'Calea Turzii',t:'p',c:[[638.4,-865.7],[640.7,-854.2]]},
  {n:'Piața Unirii',t:'p',c:[[34.6,-91.7],[18.5,-55.5],[16.3,-50.8],[11.8,-41.3],[11.3,-40.1],[9.3,-35.8]]},
  {n:'Calea Turzii',t:'p',c:[[632.3,-353.0],[633.3,-358.9],[634.1,-365.4],[634.8,-378.6],[634.7,-383.8],[635.1,-392.7]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[632.3,-353.0],[637.4,-364.4],[644.0,-380.9],[646.6,-386.9],[647.6,-389.5],[654.3,-406.9]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[654.3,-406.9],[671.3,-421.8],[678.3,-426.9],[680.9,-428.8],[688.7,-432.9],[697.2,-436.7]]},
  {n:'Piața Timotei Cipariu',t:'p',c:[[761.8,-379.8],[730.4,-311.3],[726.5,-301.7]]},
  {n:'Strada Regele Ferdinand',t:'p',c:[[-97.2,232.0],[-101.2,239.1],[-111.9,257.2],[-114.7,262.4],[-118.4,270.4],[-119.8,273.3]]},
  {n:'Piața Avram Iancu',t:'p',c:[[506.0,173.1],[505.5,174.3],[502.9,180.8]]},
  {n:'Calea Moților',t:'p',c:[[-427.3,-321.0],[-381.7,-286.8],[-376.4,-282.8],[-375.1,-281.9],[-369.5,-277.7]]},
  {n:'Strada Horea',t:'p',c:[[-188.8,499.5],[-183.3,407.0],[-182.4,392.3]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[604.7,-269.2],[616.2,-299.3],[618.6,-305.8],[624.6,-321.4]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[502.9,180.8],[475.1,167.4],[451.4,156.0],[439.5,150.3],[436.8,149.0]]},
  {n:'Calea Turzii',t:'p',c:[[704.2,-599.4],[704.0,-590.2],[702.4,-581.3],[697.6,-569.4],[692.3,-559.3],[681.2,-538.5],[674.8,-526.7],[663.5,-505.4],[659.2,-497.3]]},
  {n:'Piața Avram Iancu',t:'p',c:[[574.7,19.5],[549.2,77.3],[522.7,134.9]]},
  {n:'Piața Timotei Cipariu',t:'p',c:[[726.5,-301.7],[724.0,-295.3],[718.3,-282.7],[716.1,-278.0]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[545.5,-114.7],[556.8,-145.6]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[556.8,-145.6],[567.4,-174.0]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[1143.3,517.3],[1128.6,510.2],[1124.9,508.4],[1115.1,504.0]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[585.5,226.2],[554.5,209.5]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[146.5,33.6],[130.6,26.9],[124.7,24.5],[116.8,21.2]]},
  {n:'Strada Horea',t:'p',c:[[-196.1,603.0],[-192.5,550.5],[-190.1,518.1]]},
  {n:'Strada Memorandumului',t:'p',c:[[-324.6,-246.3],[-358.9,-269.8]]},
  {n:'Strada Horea',t:'p',c:[[-196.6,627.1],[-194.2,632.6],[-191.6,639.5],[-189.2,680.7],[-189.0,683.9],[-187.6,697.8]]},
  {n:'Piața Unirii',t:'p',c:[[9.3,-35.8],[-1.2,-44.2],[-5.5,-47.0]]},
  {n:'Calea Turzii',t:'p',c:[[659.9,-761.6],[667.4,-732.7],[670.0,-724.5],[680.0,-689.1],[683.5,-676.7],[692.3,-647.1]]},
  {n:'Calea Turzii',t:'p',c:[[692.3,-647.1],[695.9,-634.6],[699.4,-622.8],[702.1,-612.7],[703.5,-606.0],[704.2,-599.4]]},
  {n:'Calea Turzii',t:'p',c:[[613.2,-1129.7],[610.7,-1118.1],[608.1,-1102.3],[607.0,-1086.5],[606.5,-1072.3]]},
  {n:'Calea Turzii',t:'p',c:[[656.0,-1281.6],[638.5,-1220.3],[631.2,-1194.5],[629.6,-1188.9],[628.5,-1184.9],[624.8,-1171.8],[619.9,-1154.3],[613.2,-1129.7]]},
  {n:'Calea Turzii',t:'p',c:[[609.3,-1022.5],[611.5,-1008.6],[614.5,-992.3]]},
  {n:'Strada Horea',t:'p',c:[[-187.6,697.8],[-185.5,722.9],[-185.3,731.5],[-184.6,751.3],[-185.3,754.9],[-189.1,773.6],[-191.2,781.4]]},
  {n:'Strada Horea',t:'p',c:[[-191.2,781.4],[-192.9,773.3],[-195.6,752.9],[-197.5,724.0],[-198.7,709.5],[-200.8,692.9]]},
  {n:'Strada Horea',t:'p',c:[[-196.6,627.1],[-196.6,622.6],[-196.3,609.3],[-196.1,603.0]]},
  {n:'Strada Horea',t:'p',c:[[-200.8,692.9],[-201.1,689.0],[-201.3,684.6],[-201.9,639.8],[-198.3,631.6],[-196.6,627.1]]},
  {n:'Strada Horea',t:'p',c:[[-126.9,287.5],[-132.2,295.5],[-149.1,324.1]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[256.7,78.1],[220.9,63.8],[146.5,33.6]]},
  {n:'Calea Turzii',t:'p',c:[[614.5,-992.3],[621.1,-957.8],[638.4,-865.7]]},
  {n:'Strada Regele Ferdinand',t:'p',c:[[-75.3,196.0],[-76.5,197.9],[-77.3,199.2],[-78.6,201.4],[-97.2,232.0]]},
  {n:'Strada Regele Ferdinand',t:'p',c:[[-16.5,87.0],[-21.7,100.5]]},
  {n:'Strada Regele Ferdinand',t:'p',c:[[-21.7,100.5],[-22.2,101.7],[-24.8,107.4],[-27.7,113.8],[-43.6,145.2],[-56.3,166.5],[-74.9,195.3],[-75.3,196.0]]},
  {n:'Calea Turzii',t:'p',c:[[606.5,-1072.3],[606.8,-1051.6],[607.0,-1044.7],[609.3,-1022.5]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[653.0,-143.3],[605.4,-47.9],[602.8,-42.7],[597.6,-31.9]]},
  {n:'Piața Lucian Blaga',t:'p',c:[[-284.0,-440.9],[-282.7,-440.4],[-248.4,-426.0]]},
  {n:'Strada Petru Maior',t:'p',c:[[-291.8,-420.7],[-285.6,-436.8],[-284.0,-440.9]]},
  {n:'Calea Moților',t:'p',c:[[-1119.0,-719.0],[-1114.8,-716.6],[-1110.4,-714.7],[-1100.6,-710.6],[-1082.6,-703.3],[-1073.8,-699.6],[-1067.4,-696.7],[-1050.2,-689.2]]},
  {n:'Bulevardul Eroilor',t:'p',c:[[476.6,-79.7],[509.1,-66.9],[514.7,-64.7],[517.4,-63.6],[524.3,-61.0]]},
  {n:'Piața Avram Iancu',t:'p',c:[[516.8,-42.2],[521.5,-54.0],[522.7,-57.0],[524.3,-61.0]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[567.4,-174.0],[570.9,-183.0],[604.7,-269.2]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[116.8,21.2],[40.5,-12.0],[35.3,-15.2],[29.8,-18.5],[24.4,-21.7]]},
  {n:'Strada Memorandumului',t:'p',c:[[-254.5,-202.7],[-284.9,-221.0]]},
  {n:'Strada Memorandumului',t:'p',c:[[-284.9,-221.0],[-314.8,-240.1],[-320.6,-243.9],[-324.6,-246.3]]},
  {n:'Calea Moților',t:'p',c:[[-650.5,-483.5],[-643.0,-478.2],[-630.4,-469.1]]},
  {n:'Calea Moților',t:'p',c:[[-1050.2,-689.2],[-1010.9,-670.9]]},
  {n:'Strada Horea',t:'p',c:[[-182.0,1029.4],[-182.7,1022.0]]},
  {n:'Strada Horea',t:'p',c:[[-178.1,1099.0],[-181.7,1039.0],[-182.0,1029.4]]},
  {n:'Bulevardul 21 Decembrie 1989',t:'p',c:[[554.5,209.5],[526.0,193.2],[525.1,192.7],[524.3,192.3],[520.9,190.3]]},
  {n:'Piața Avram Iancu',t:'p',c:[[522.7,134.9],[511.4,160.4],[509.0,166.2],[506.0,173.1]]},
  {n:'Calea Dorobanților',t:'p',c:[[1136.4,151.5],[1199.1,180.8],[1217.3,190.4],[1228.6,196.7],[1236.8,201.3],[1243.4,205.0],[1244.4,205.5],[1248.4,207.7],[1257.5,212.5],[1283.4,226.6]]},
  {n:'Calea Turzii',t:'p',c:[[659.2,-497.3],[655.6,-476.2]]},
  {n:'Calea Dorobanților',t:'p',c:[[739.7,12.9],[777.4,25.1],[837.6,45.6],[855.9,51.6],[875.8,58.2],[881.3,59.9],[898.2,65.3],[920.5,72.9],[931.8,76.8],[978.5,92.7],[1015.4,105.3],[1047.4,116.3],[1051.2,117.6],[1061.3,121.2],[1070.6,124.5]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[628.7,-340.0],[632.3,-353.0]]},
  {n:'Piața Unirii',t:'p',c:[[-5.5,-47.0],[-7.5,-48.4],[-91.2,-104.1],[-93.2,-105.4]]},
  {n:'Calea Moților',t:'p',c:[[-1010.9,-670.9],[-999.9,-665.6],[-956.4,-644.6],[-929.1,-631.5]]},
  {n:'Calea Dorobanților',t:'p',c:[[1070.6,124.5],[1081.5,129.0],[1085.4,130.5],[1092.2,133.3],[1136.4,151.5]]},
  {n:'Piața Ștefan cel Mare',t:'p',c:[[709.2,-262.0],[693.5,-227.9],[686.8,-214.0],[671.5,-182.0],[659.0,-155.8],[654.2,-145.9],[653.0,-143.3]]},
  {n:'Strada Horea',t:'p',c:[[-174.6,1160.2],[-175.3,1147.3],[-178.1,1099.0]]},
  {n:'Strada Horea',t:'p',c:[[-169.0,1274.7],[-169.9,1257.7],[-171.7,1220.2],[-174.6,1160.2]]},
  {n:'Strada Horea',t:'p',c:[[-190.1,518.1],[-188.8,499.5]]},
  {n:'Calea Moților',t:'p',c:[[-369.5,-277.7],[-363.8,-273.5],[-358.9,-269.8]]},
  {n:'Calea Moților',t:'p',c:[[-527.1,-394.7],[-494.4,-371.2]]},
  {n:'Calea Moților',t:'p',c:[[-430.5,-323.3],[-427.3,-321.0]]},
  {n:'Calea Moților',t:'p',c:[[-494.4,-371.2],[-485.3,-364.6],[-475.2,-357.0],[-430.5,-323.3]]},
  {n:'Strada Milton Lehrer',t:'p',c:[[761.4,-398.8],[761.8,-388.8],[761.8,-379.8]]},
  {n:'Calea Moților',t:'p',c:[[-587.8,-438.4],[-573.9,-428.4]]},
  {n:'Calea Moților',t:'p',c:[[-567.6,-423.9],[-529.8,-396.6],[-527.1,-394.7]]},
  {n:'Calea Moților',t:'p',c:[[-573.9,-428.4],[-567.6,-423.9]]},
  {n:'Strada Horea',t:'p',c:[[-178.6,383.8],[-170.1,365.3]]},
  {n:'Strada Horea',t:'p',c:[[-182.7,1022.0],[-184.5,992.8]]},
  {n:'Strada Petru Maior',t:'p',c:[[-358.9,-269.8],[-357.2,-273.6]]},
  {n:'Strada Napoca',t:'p',c:[[-229.0,-418.0],[-224.3,-415.2]]},
  {n:'Piața Lucian Blaga',t:'p',c:[[-248.4,-426.0],[-239.6,-422.3],[-235.1,-420.5],[-230.4,-418.6],[-229.0,-418.0]]},
];

let clujGroundMeshes = []; // for raycast Y detection
const _raycaster = new THREE.Raycaster();
const _downDir = new THREE.Vector3(0, -1, 0);

function buildClujScene() {
    if (nordsWorldGroup) nordsWorldGroup.visible = false;

    clujGroundMeshes = [];

    // Terrain: flat plane at ~0 elevation (Cluj center ~380m, scaled to 0)
    const terrGeo = new THREE.PlaneGeometry(4000, 4000, 20, 20);
    terrGeo.rotateX(-Math.PI / 2);
    const terrMesh = new THREE.Mesh(terrGeo, new THREE.MeshStandardMaterial({
        color: 0x1a2a1a, roughness: 1, flatShading: true
    }));
    terrMesh.position.y = -0.1;
    scene.add(terrMesh);
    clujGroundMeshes.push(terrMesh);

    // Roads: flat ribbons from OSM data
    const roadVerts = [], roadIdx = [];
    let vOff = 0;
    for (const road of CLUJ_ROADS) {
        const w = road.t === 'p' ? 8 : road.t === 's' ? 6 : 4; // width by road type
        for (let i = 0; i < road.c.length - 1; i++) {
            const [x1, z1] = road.c[i];
            const [x2, z2] = road.c[i + 1];
            const dx = x2 - x1, dz = z2 - z1;
            const len = Math.sqrt(dx*dx + dz*dz);
            if (len < 0.1) continue;
            const nx = -dz / len * w / 2, nz = dx / len * w / 2;
            roadVerts.push(
                x1+nx, 0.02, z1+nz, x1-nx, 0.02, z1-nz,
                x2+nx, 0.02, z2+nz, x2-nx, 0.02, z2-nz
            );
            const v = vOff;
            roadIdx.push(v, v+1, v+2, v+1, v+3, v+2);
            vOff += 4;
        }
    }
    const roadGeo = new THREE.BufferGeometry();
    roadGeo.setAttribute('position', new THREE.Float32BufferAttribute(roadVerts, 3));
    roadGeo.setIndex(roadIdx);
    roadGeo.computeVertexNormals();
    const roadMesh = new THREE.Mesh(roadGeo, new THREE.MeshStandardMaterial({
        color: 0x444444, roughness: 0.85, side: THREE.DoubleSide
    }));
    scene.add(roadMesh);
    clujGroundMeshes.push(roadMesh);

    // Procedural buildings along roads
    const boxGeo = new THREE.BoxGeometry(1, 1, 1);
    const buildingCount = Math.min(800, CLUJ_ROADS.length * 6);
    const buildingMesh = new THREE.InstancedMesh(boxGeo,
        new THREE.MeshStandardMaterial({ color: 0x445566, roughness: 0.8, flatShading: true }),
        buildingCount);
    const bDummy = new THREE.Object3D();
    const bColor = new THREE.Color();
    let bIdx = 0;
    for (const road of CLUJ_ROADS) {
        if (bIdx >= buildingCount) break;
        for (let i = 0; i < road.c.length - 1 && bIdx < buildingCount; i += 2) {
            const [x1, z1] = road.c[i];
            const [x2, z2] = road.c[i + 1] || road.c[i];
            const dx = x2 - x1, dz = z2 - z1;
            const len = Math.sqrt(dx*dx + dz*dz);
            if (len < 5) continue;
            const nx = -dz / len, nz = dx / len;
            // Place buildings on both sides
            for (const side of [-1, 1]) {
                if (bIdx >= buildingCount) break;
                const offset = 12 + Math.random() * 8;
                const bw = 8 + Math.random() * 15;
                const bd = 8 + Math.random() * 12;
                const bh = 8 + Math.random() * 20;
                bDummy.position.set(
                    (x1+x2)/2 + nx * side * offset,
                    bh / 2,
                    (z1+z2)/2 + nz * side * offset
                );
                bDummy.scale.set(bw, bh, bd);
                bDummy.rotation.y = Math.atan2(dx, dz) + (Math.random()-0.5)*0.3;
                bDummy.updateMatrix();
                buildingMesh.setMatrixAt(bIdx, bDummy.matrix);
                // Color by height
                const hNorm = bh / 28;
                bColor.setRGB(0.2+hNorm*0.1, 0.25+hNorm*0.1, 0.3+hNorm*0.15);
                buildingMesh.setColorAt(bIdx, bColor);
                bIdx++;
            }
        }
    }
    buildingMesh.count = bIdx;
    buildingMesh.instanceMatrix.needsUpdate = true;
    buildingMesh.instanceColor.needsUpdate = true;
    scene.add(buildingMesh);

    // Someș River: blue plane crossing E-W
    const riverGeo = new THREE.PlaneGeometry(3000, 40);
    riverGeo.rotateX(-Math.PI / 2);
    const river = new THREE.Mesh(riverGeo, new THREE.MeshStandardMaterial({
        color: 0x112244, roughness: 0.3, metalness: 0.5
    }));
    river.position.set(0, -0.05, 180); // river is ~180m north of center
    scene.add(river);

    // Street lights along major roads
    const lightGeo = new THREE.CylinderGeometry(0.1, 0.15, 5, 6);
    const lightMat = new THREE.MeshStandardMaterial({ color: 0x666666, roughness: 0.7 });
    const lightTopGeo = new THREE.SphereGeometry(0.3, 6, 6);
    const lightTopMat = new THREE.MeshStandardMaterial({ color: 0xffffaa, emissive: 0xffdd66, emissiveIntensity: 1.0 });
    for (const road of CLUJ_ROADS) {
        if (road.t !== 'p') continue; // only primary roads
        for (let i = 0; i < road.c.length; i += 3) {
            const [x, z] = road.c[i];
            const pole = new THREE.Mesh(lightGeo, lightMat);
            pole.position.set(x + 6, 2.5, z);
            scene.add(pole);
            const top = new THREE.Mesh(lightTopGeo, lightTopMat);
            top.position.set(x + 6, 5.2, z);
            scene.add(top);
        }
    }

    // Piața Unirii: large lighter ground at center
    const squareGeo = new THREE.PlaneGeometry(220, 160);
    squareGeo.rotateX(-Math.PI / 2);
    const square = new THREE.Mesh(squareGeo, new THREE.MeshStandardMaterial({
        color: 0x555555, roughness: 0.7
    }));
    square.position.set(-20, 0.03, -45); // approximate Piata Unirii position
    scene.add(square);
    clujGroundMeshes.push(square);

    // St. Michael's Church: tall spire at Piata Unirii
    const churchBase = new THREE.Mesh(new THREE.BoxGeometry(25, 20, 40),
        new THREE.MeshStandardMaterial({ color: 0x998866, roughness: 0.7 }));
    churchBase.position.set(-20, 10, -45);
    scene.add(churchBase);
    const spire = new THREE.Mesh(new THREE.ConeGeometry(4, 60, 8),
        new THREE.MeshStandardMaterial({ color: 0x887755, roughness: 0.6 }));
    spire.position.set(-20, 50, -45);
    scene.add(spire);

    console.log('Cluj scene built:', bIdx, 'buildings,', CLUJ_ROADS.length, 'roads');
}

function getClujGroundY(x, z) {
    _raycaster.set(new THREE.Vector3(x, 50, z), _downDir);
    const hits = _raycaster.intersectObjects(clujGroundMeshes, false);
    return hits.length > 0 ? hits[0].point.y : 0;
}

function getNordGroundY(x, z, fallbackY) {
    if (!nordGroundMeshes.length) return fallbackY;
    _raycaster.set(new THREE.Vector3(x, 160, z), _downDir);
    const driveHits = _raycaster.intersectObjects(nordDriveMeshes, false);
    if (driveHits.length > 0) {
        lastGroundSource = 'road';
        lastTerrainY = driveHits[0].point.y;
        return driveHits[0].point.y;
    }
    const hits = _raycaster.intersectObjects(nordGroundMeshes, false);
    if (hits.length > 0) {
        lastGroundSource = hits[0].object === nordTerrainMesh ? 'terrain' : 'trackside';
        lastTerrainY = hits[0].point.y;
        return hits[0].point.y;
    }
    lastGroundSource = 'fallback';
    lastTerrainY = fallbackY;
    return fallbackY;
}

function getClujStreetName(x, z) {
    let bestDist = Infinity, bestName = '';
    for (const road of CLUJ_ROADS) {
        for (const [rx, rz] of road.c) {
            const d = (x-rx)*(x-rx) + (z-rz)*(z-rz);
            if (d < bestDist) { bestDist = d; bestName = road.n; }
        }
    }
    return bestName;
}

// =====================================================================
// ENGINE AUDIO
// =====================================================================
// Engine: 3 oscillators for richer flat-6 sound + low-pass filter for warmth
let engineCtx, engineOscs=[], engineGains=[], engineLPF, engineOn=false;
let lastEngineGear = 0;

function engineStart() {
    if (engineOn) return;
    try {
        if (!engineCtx) engineCtx = new (window.AudioContext || window.webkitAudioContext)();
        if (engineCtx.state === 'suspended') engineCtx.resume();

        // Low-pass filter for warmth (removes harsh high frequencies)
        engineLPF = engineCtx.createBiquadFilter();
        engineLPF.type = 'lowpass';
        engineLPF.frequency.value = 400;
        engineLPF.Q.value = 1;
        engineLPF.connect(engineCtx.destination);

        // Oscillator 1: deep rumble (sawtooth, fundamental)
        const o1 = engineCtx.createOscillator(); o1.type = 'sawtooth'; o1.frequency.value = 35;
        const g1 = engineCtx.createGain(); g1.gain.value = 0;
        o1.connect(g1); g1.connect(engineLPF); o1.start();

        // Oscillator 2: mid tone (triangle, octave up)
        const o2 = engineCtx.createOscillator(); o2.type = 'triangle'; o2.frequency.value = 70;
        const g2 = engineCtx.createGain(); g2.gain.value = 0;
        o2.connect(g2); g2.connect(engineLPF); o2.start();

        // Oscillator 3: high harmonic (sine, adds character at high RPM)
        const o3 = engineCtx.createOscillator(); o3.type = 'sine'; o3.frequency.value = 105;
        const g3 = engineCtx.createGain(); g3.gain.value = 0;
        o3.connect(g3); g3.connect(engineLPF); o3.start();

        engineOscs = [o1, o2, o3];
        engineGains = [g1, g2, g3];
        engineOn = true;
    } catch (e) {}
}
function engineStop() {
    if (!engineOn) return;
    try { engineOscs.forEach(o => o.stop()); } catch (e) {}
    engineOn = false;
}
function engineUpdate(sp) {
    if (!engineOn) return;
    try {
        const speed = sp * MAX_SPEED;
        let g = 0;
        for (g = 0; g < GEAR_TABLE.length; g++) if (speed < GEAR_TABLE[g][0]) break;
        g = Math.min(g, GEAR_TABLE.length - 1);

        // Gear shift click
        if (g > lastEngineGear && speed > 2) zzfx(.05,.02,45,.005,.02,.01,2,0,0,0,0,0,0,0,0,0,0,.2);
        lastEngineGear = g;

        // RPM within gear
        const gBottom = g > 0 ? GEAR_TABLE[g-1][0] : 0;
        const gTop = GEAR_TABLE[g][0];
        const rpm = gTop > gBottom ? Math.max(0, Math.min(1, (speed - gBottom) / (gTop - gBottom))) : 0;

        // Frequencies: base rises with speed, RPM adds within-gear climb
        const base = 35 + sp * 45; // 35Hz idle → 80Hz max
        const rpmAdd = rpm * 20;   // 0-20Hz per gear
        const f = base + rpmAdd;

        engineOscs[0].frequency.value = f;           // fundamental
        engineOscs[1].frequency.value = f * 2.01;    // octave (slightly detuned)
        engineOscs[2].frequency.value = f * 3.02;    // 3rd harmonic (adds bite at high RPM)

        // Volume: deeper at idle, louder and brighter at speed
        engineGains[0].gain.value = 0.012 + sp * 0.018;  // rumble always present
        engineGains[1].gain.value = 0.004 + sp * 0.012;  // mid grows with speed
        engineGains[2].gain.value = rpm * sp * 0.008;     // high harmonic only at high RPM

        // Open the filter as RPM/speed increases (brighter sound at high RPM)
        engineLPF.frequency.value = 300 + rpm * 400 + sp * 200;
    } catch (e) {}
}

// =====================================================================
// GAME STATE — Free world-space driving
// =====================================================================
const MAX_SPEED = 82;          // m/s hard safety cap; real top speed is drag-limited below this.
const BRAKING = 42;            // m/s² peak braking before grip limits.
const AERO_DRAG = 0.00082;
const ROLLING_DRAG = 0.42;
const WHEELBASE_M = 2.8;
const BASE_GRIP_MS2 = 15.2;
const STEER_LIMIT = 0.66;

// Gear-based acceleration: each gear has a speed range and power curve
// [maxSpeedForGear_ms, acceleration_ms2]
// Real 911 GT3: 0-100 in 3.4s, 0-200 in ~11s, top 318 km/h
const GEAR_TABLE = [
    [15,  35],  // 1st: hard launch
    [28,  28],  // 2nd
    [40,  20],  // 3rd
    [53,  14],  // 4th
    [66,  9],   // 5th
    [82,  6.5], // 6th: drag-limited, not a hard limiter
];

// Pre-bake spline samples for fast nearest-point lookup + minimap bounds
const SPLINE_SAMPLES = 4096;
const splinePts = [];
function rebakeSplinePts() {
    splinePts.length = 0;
    if (!spline) return;
    let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
    const sourceSamples = trackSamples.length ? trackSamples : null;
    const count = sourceSamples ? sourceSamples.length : SPLINE_SAMPLES;
    for (let i = 0; i < count; i++) {
        const t = i / count;
        const src = sourceSamples ? sourceSamples[i] : null;
        const p = src || spline.getPointAt(t);
        const q = {
            t: src?.t ?? t,
            distanceM: src?.distanceM ?? t * trackMeta.lengthM,
            x: p.x,
            y: p.y,
            z: p.z,
        };
        splinePts.push(q);
        if (p.x < minX) minX = p.x;
        if (p.x > maxX) maxX = p.x;
        if (p.z < minZ) minZ = p.z;
        if (p.z > maxZ) maxZ = p.z;
    }
    const pad = 220;
    minimapBounds = { minX: minX - pad, maxX: maxX + pad, minZ: minZ - pad, maxZ: maxZ + pad };
}

function findNearestT(wx, wz) {
    const nearest = findNearestOnSamples(wx, wz, trackSamples.length ? trackSamples : splinePts);
    lastNearestTrack = nearest;
    return nearest;
}

const NORD_DATA_BASE = new URL('./data/', import.meta.url);
async function loadNordschleifeTrack() {
    const [trackJ, secJ, cpJ, lmJ, terrJ, propsJ] = await Promise.all([
        fetch(new URL('track.json', NORD_DATA_BASE).href).then((r) => r.json()),
        fetch(new URL('sectors.json', NORD_DATA_BASE).href).then((r) => r.json()),
        fetch(new URL('checkpoints.json', NORD_DATA_BASE).href).then((r) => r.json()),
        fetch(new URL('landmarks.json', NORD_DATA_BASE).href).then((r) => r.json()),
        fetch(new URL('terrain.json', NORD_DATA_BASE).href).then((r) => r.json()),
        fetch(new URL('props.json', NORD_DATA_BASE).href)
            .then((r) => (r.ok ? r.json() : { props: [] }))
            .catch(() => ({ props: [] })),
    ]);
    nordSectors = secJ.sectors || [];
    nordCheckpoints = cpJ.checkpoints || [];
    nordLandmarks = lmJ.landmarks || [];
    nordTerrainCfg = terrJ;
    nordProps = propsJ.props || [];
    const samples = trackJ.samples || [];
    if (samples.length < 8) throw new Error('track.json: not enough samples');
    trackMeta = { lengthM: trackJ.lengthM || 20800, name: trackJ.name || 'Nordschleife' };
    trackSamples = samples.map((s, i) => ({
        i,
        t: Number.isFinite(s.t) ? s.t : i / samples.length,
        distanceM: Number.isFinite(s.distanceM) ? s.distanceM : (i / samples.length) * trackMeta.lengthM,
        x: Number(s.x) || 0,
        y: Number(s.y) || 0,
        z: Number(s.z) || 0,
        widthM: Number(s.widthM) || ROAD_W * 2,
    }));
    splinePoints = trackSamples.map((s) => new THREE.Vector3(s.x, s.y, s.z));
    // The generated data is already arc-length sampled from OSM. Interpolate it directly so tight corners
    // cannot be rounded or cut by Catmull-Rom overshoot.
    spline = {
        closed: true,
        getPointAt: sampleTrackAt,
        getTangentAt: sampleTrackTangentAt,
    };
    spline.closed = true;
    splineLen = trackMeta.lengthM;
    buildNordschleifeWorld();
    rebakeSplinePts();
    trackReady = true;
    const ft = document.querySelector('.ftr span:last-child');
    if (ft) ft.textContent = `${trackMeta.name} ${(trackMeta.lengthM / 1000).toFixed(1)}km`;
}

// Car state in WORLD SPACE
let carX = 0, carZ = 0, carY = 0;  // world position
let carAngle = 0;                     // heading in world space (radians)
let carSpeed = 0;                     // forward speed (m/s)
let carVelX = 0, carVelZ = 0;
let steerAmount = 0;
let yawRate = 0;
let prevSector = 0;                   // for lap detection

let lapTime = 0, currentLap = 0, lapFlashAlpha = 0;
let currentSection = '', sectionFade = 0;
let STATE = 'intro';
let activeMap = 'nordschleife'; // 'nordschleife' or 'cluj'
let cheatBuffer = '';
let raceResetHold = 0;
let crashShakeT = 0;

// --- Multiplayer presence (optional relay; zero impact when disabled/unreachable) ---
function getMpRelayUrl() {
    if (typeof window.NORD_MP_RELAY_URL === 'string' && window.NORD_MP_RELAY_URL.length > 0) return window.NORD_MP_RELAY_URL;
    if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') return 'ws://localhost:8090';
    return '';
}
const mpName = 'Racer' + Math.floor(1000 + Math.random() * 9000);
const mpColor = PAL[Math.floor(Math.random() * PAL.length)];
let mpSocket = null;
let mpPeerId = null;
let mpConnected = false;
let mpBackoffMs = 1000;
let mpReconnectTimer = null;
const mpPlayers = new Map();
/** Server-driven session (tourist vs race); client also tracks local checkpoint progress */
let mpSession = { mode: 'tourist', phase: 'idle', countdown: null, totalLaps: 1, hostId: null };
let roundState = { roundType: 'checkpoint_sprint', roundPhase: 'idle', roundIndex: 0, roundEndsAt: 0, roundLiveAt: 0 };
let mpStandings = [];
let localRaceNextCp = 1;
let localRaceFinished = false;
let chaosScore = 0;
/** @type {{ x: number, z: number, hit: boolean }[]} */
let chaosPickupPos = [];
let lastCpGateHover = -1;
let soloRace = { phase: 'tourist', countdown: 0, nextCp: 1, laps: 1, totalLaps: 1, finished: false };
let menuOpen = false;
const perfOverlay = document.createElement('div');
perfOverlay.style.cssText = 'position:fixed;left:8px;bottom:8px;z-index:200;font:500 10px/1.25 ui-monospace,Menlo,monospace;color:#8fa;background:rgba(0,0,0,0.32);padding:4px 6px;border:1px solid rgba(255,255,255,0.12);display:none;pointer-events:none;';
document.body.appendChild(perfOverlay);
if (debugTrackMode) {
    trackDebugEl = document.createElement('div');
    trackDebugEl.style.cssText = 'position:fixed;left:8px;top:8px;z-index:210;font:500 11px/1.35 ui-monospace,Menlo,monospace;color:#d7f7ff;background:rgba(0,0,0,0.55);padding:7px 8px;border:1px solid rgba(255,255,255,0.18);white-space:pre;pointer-events:none;';
    document.body.appendChild(trackDebugEl);
}

function mpRound(v, places) {
    const m = Math.pow(10, places);
    return Math.round(v * m) / m;
}

function mpSend(payload) {
    if (!mpSocket || mpSocket.readyState !== 1) return false;
    const raw = JSON.stringify(payload);
    sessionPerf.netOut += raw.length;
    sessionPerf.msgOut++;
    mpSocket.send(raw);
    return true;
}

function mpHudRefresh() {
    try {
        const st = document.getElementById('mp-status');
        const cnt = document.getElementById('mp-count');
        if (!st || !cnt) return;
        const open = mpSocket && mpSocket.readyState === 1;
        st.style.display = open ? '' : 'none';
        if (open) cnt.textContent = String(mpPlayers.size);
    } catch (_) {}
}

const raceBannerEl = document.getElementById('race-banner');
const minimapWrapEl = document.getElementById('minimap-wrap');
const standingsStripEl = document.getElementById('standings-strip');
const minimapCanvasEl = document.getElementById('minimap');
const menuOverlayEl = document.getElementById('menu-overlay');
const menuInfoEl = document.getElementById('menu-info');
const menuResumeBtn = document.getElementById('menu-resume');
const menuResetBtn = document.getElementById('menu-reset');
const menuModeBtn = document.getElementById('menu-mode');
const menuGuideBtn = document.getElementById('menu-guide');

function escapeHtml(str) {
    return String(str).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}

function roundLabel(rt) {
    return 'Checkpoint Sprint';
}

function roundObjective(rt) {
    return 'Race checkpoints in order; finish fastest.';
}

function getRoundSummaryText() {
    const liveRt = roundState.roundType || 'checkpoint_sprint';
    const phase = roundState.roundPhase || 'idle';
    return `Round ${roundState.roundIndex || 0}: ${roundLabel(liveRt)}\nPhase: ${phase}\nObjective: ${roundObjective(liveRt)}`;
}

function setMenuInfoMode() {
    if (!menuInfoEl) return;
    menuInfoEl.textContent = getRoundSummaryText();
}

function setMenuInfoGuide() {
    if (!menuInfoEl) return;
    menuInfoEl.textContent = [
        'Drive: WASD / Arrows',
        'Press T to request a multiplayer race (host-controlled).',
        'Checkpoint Sprint: pass each gate in order and finish cleanly.',
        'Tourist mode stays open when the relay is unavailable.',
        'Use this menu for reset and quick help.',
    ].join('\n');
}

function toggleMenu(open) {
    menuOpen = open === undefined ? !menuOpen : !!open;
    if (menuOverlayEl) menuOverlayEl.classList.toggle('show', menuOpen && STATE === 'playing');
    if (menuOpen) {
        keysHeld.clear();
        setMenuInfoMode();
    }
}

function mpRaceUiRefresh() {
    try {
        const n = activeMap === 'nordschleife';
        const cpLast = Math.max(1, nordCheckpoints.length - 1);
        const mpRaceUi = n && (mpSession.mode === 'race' || mpSession.phase === 'countdown' || mpSession.phase === 'results');
        const soloRaceUi = n && (soloRace.phase === 'countdown' || soloRace.phase === 'live' || soloRace.phase === 'results');
        const raceUi = mpRaceUi || soloRaceUi;
        if (raceBannerEl) {
            raceBannerEl.classList.toggle('show', raceUi);
            const amHost = !!mpPeerId && mpSession.hostId === mpPeerId;
            if (soloRace.phase === 'countdown') {
                raceBannerEl.textContent = String(Math.max(1, Math.ceil(soloRace.countdown)));
            } else if (soloRace.phase === 'live') {
                raceBannerEl.textContent = `SOLO CHECKPOINT SPRINT · lap ${soloRace.laps}/${soloRace.totalLaps} · cp ${soloRace.nextCp}/${cpLast}`;
            } else if (soloRace.phase === 'results') {
                raceBannerEl.textContent = 'SOLO RACE FINISHED · T = restart';
            } else if (mpSession.phase === 'countdown' && mpSession.countdown != null) {
                raceBannerEl.textContent = `${mpSession.countdown > 0 ? String(mpSession.countdown) : 'GO'} · ${roundLabel(roundState.roundType)}`;
            } else if (mpSession.phase === 'live' && mpSession.mode === 'race') {
                raceBannerEl.textContent = `${roundLabel(roundState.roundType).toUpperCase()} · cp ${localRaceNextCp}/${cpLast}${amHost ? ' · HOST' : ''}`;
            } else if (mpSession.phase === 'results') {
                raceBannerEl.textContent = `ROUND RESULTS · ${roundLabel(roundState.roundType).toUpperCase()}`;
            } else {
                raceBannerEl.textContent = mpConnected ? `TOURIST DRIVE · T = race${amHost ? ' (host)' : ''}` : 'TOURIST DRIVE · T = solo race';
            }
        }
        const showMap = n && ((mpSession.mode === 'race' && (mpSession.phase === 'live' || mpSession.phase === 'countdown')) || soloRace.phase === 'live' || soloRace.phase === 'countdown');
        if (minimapWrapEl) minimapWrapEl.classList.toggle('show', showMap && trackReady);
        if (standingsStripEl) {
            standingsStripEl.classList.toggle('show', raceUi && (mpStandings.length > 0 || soloRaceUi));
            if (mpRaceUi && mpStandings.length) {
                standingsStripEl.innerHTML = mpStandings.map((r) => `<div>${r.place}. ${escapeHtml(String(r.name || r.id || '?').slice(0, 14))} · L${r.laps || 1} · CP${r.nextCp || 1}/${cpLast} ${r.finished ? '✓' : ''}</div>`).join('');
            } else if (soloRaceUi) {
                standingsStripEl.innerHTML = `<div>1. YOU · L${soloRace.laps}/${soloRace.totalLaps}${soloRace.finished ? ' ✓' : ''}</div>`;
            }
        }
        if (menuOpen) setMenuInfoMode();
    } catch (_) {}
}

function drawMinimap() {
    if (!minimapCanvasEl || !splinePts.length || activeMap !== 'nordschleife') return;
    if (!((mpSession.mode === 'race' && (mpSession.phase === 'live' || mpSession.phase === 'countdown')) || soloRace.phase === 'live' || soloRace.phase === 'countdown')) return;
    const ctx = minimapCanvasEl.getContext('2d');
    const W = minimapCanvasEl.width;
    const H = minimapCanvasEl.height;
    const { minX, maxX, minZ, maxZ } = minimapBounds;
    const rw = Math.max(1e-3, maxX - minX);
    const rh = Math.max(1e-3, maxZ - minZ);
    const mx = (x) => ((x - minX) / rw) * W;
    const mz = (z) => ((z - minZ) / rh) * H;
    ctx.fillStyle = 'rgba(0,0,0,0.55)';
    ctx.fillRect(0, 0, W, H);
    ctx.strokeStyle = 'rgba(255,255,255,0.22)';
    ctx.lineWidth = 1.2;
    ctx.beginPath();
    for (let i = 0; i < splinePts.length; i++) {
        const q = splinePts[i];
        const px = mx(q.x);
        const py = H - mz(q.z);
        if (i === 0) ctx.moveTo(px, py);
        else ctx.lineTo(px, py);
    }
    ctx.closePath();
    ctx.stroke();
    ctx.fillStyle = 'rgba(0,255,120,0.4)';
    for (const cp of nordCheckpoints) {
        ctx.beginPath();
        ctx.arc(mx(cp.x), H - mz(cp.z), 2.2, 0, Math.PI * 2);
        ctx.fill();
    }
    ctx.fillStyle = '#ffbe0b';
    ctx.beginPath();
    ctx.arc(mx(carX), H - mz(carZ), 3.2, 0, Math.PI * 2);
    ctx.fill();
    for (const [, e] of mpPlayers) {
        if (!e.group.visible) continue;
        ctx.fillStyle = '#00f5d4';
        ctx.beginPath();
        ctx.arc(mx(e.group.position.x), H - mz(e.group.position.z), 2.4, 0, Math.PI * 2);
        ctx.fill();
    }
}


function mpDisposeObject3D(obj) {
    obj.traverse((ch) => {
        if (ch.geometry) ch.geometry.dispose();
        if (ch.material) {
            if (Array.isArray(ch.material)) ch.material.forEach((m) => { if (m.map) m.map.dispose(); m.dispose(); });
            else { if (ch.material.map) ch.material.map.dispose(); ch.material.dispose(); }
        }
    });
}

function mpRemovePlayer(id) {
    try {
        const e = mpPlayers.get(id);
        if (!e) return;
        scene.remove(e.group);
        mpDisposeObject3D(e.group);
        mpPlayers.delete(id);
        mpHudRefresh();
    } catch (_) {}
}

function mpAddPlayer(p) {
    try {
        if (!p || !p.id || p.id === mpPeerId) return;
        if (mpPlayers.has(p.id)) mpRemovePlayer(p.id);
        const group = createRemoteCar(p.name || 'Racer', p.color || '#888', p.carModel);
        group.visible = true;
        const ts = performance.now();
        const x = Number(p.x) || 0, z = Number(p.z) || 0, y = Number(p.y) || 0, a = Number(p.a) || 0, s = Number(p.s) || 0;
        const st = { x, y, z, a, s, ts };
        mpPlayers.set(p.id, { group, prev: { ...st }, curr: { ...st } });
        group.position.set(x, y, z);
        group.rotation.y = a;
        mpHudRefresh();
    } catch (_) {}
}

function mpOnUpdated(msg) {
    try {
        const id = msg.id;
        if (!id || id === mpPeerId) return;
        let e = mpPlayers.get(id);
        if (!e) {
            mpAddPlayer({ id, name: msg.name || 'Racer', color: msg.color || '#888', carModel: msg.carModel, x: msg.x, z: msg.z, y: msg.y, a: msg.a, s: msg.s });
            e = mpPlayers.get(id);
            if (!e) return;
        }
        const ts = performance.now();
        const x = Number(msg.x) || 0, z = Number(msg.z) || 0, y = Number(msg.y) || 0, a = Number(msg.a) || 0, s = Number(msg.s) || 0;
        e.prev = { ...e.curr };
        e.curr = { x, y, z, a, s, ts };
    } catch (_) {}
}

function mpShortestAngleDelta(from, to) {
    const TAU = Math.PI * 2;
    return ((to - from + Math.PI * 3) % TAU) - Math.PI;
}

function mpUpdateRemoteCars() {
    if (mpPlayers.size === 0) return;
    const now = performance.now();
    for (const [id, e] of mpPlayers) {
        const age = now - e.curr.ts;
        if (age > 15000) { mpRemovePlayer(id); continue; }
        if (age > 5000) { e.group.visible = false; continue; }
        e.group.visible = true;
        const span = Math.max(1, e.curr.ts - e.prev.ts);
        const renderTs = now - 120;
        let u = span > 0 ? (renderTs - e.prev.ts) / span : 1;
        let ex = 0, ez = 0, ey = 0;
        if (u > 1 && age > 220) {
            const late = Math.min(0.35, (age - 220) / 1000);
            const dist = Math.max(0, e.curr.s) * late;
            ex = Math.sin(e.curr.a) * dist;
            ez = Math.cos(e.curr.a) * dist;
            ey = 0;
        }
        u = Math.max(0, Math.min(1, u));
        const x = e.prev.x + (e.curr.x - e.prev.x) * u + ex;
        const y = e.prev.y + (e.curr.y - e.prev.y) * u + ey;
        const z = e.prev.z + (e.curr.z - e.prev.z) * u + ez;
        e.group.position.set(x, y, z);
        const a0 = e.prev.a, a1 = e.curr.a;
        let ang = a0 + mpShortestAngleDelta(a0, a1) * u;
        if (u > 1 && age > 150) ang = e.curr.a;
        e.group.rotation.y = ang;
    }
}

function mpSendJoin() {
    try {
        mpSend({ t: 'join', map: activeMap, name: mpName, color: mpColor, carModel: myCarModelIdx });
    } catch (_) {}
}

function mpScheduleReconnect() {
    try {
        if (mpReconnectTimer) return;
        const url = getMpRelayUrl();
        if (!url) return;
        mpReconnectTimer = setTimeout(() => {
            mpReconnectTimer = null;
            mpOpenSocket();
        }, mpBackoffMs);
        mpBackoffMs = Math.min(15000, Math.round(mpBackoffMs * 2));
    } catch (_) {}
}

function mpOpenSocket() {
    try {
        const url = getMpRelayUrl();
        if (!url) return;
        if (mpSocket && (mpSocket.readyState === 0 || mpSocket.readyState === 1)) return;
        mpSocket = new WebSocket(url);
        mpSocket.onopen = () => {
            mpBackoffMs = 1000;
            mpSendJoin();
        };
        mpSocket.onmessage = (ev) => {
            try {
                sessionPerf.netIn += String(ev.data || '').length;
                sessionPerf.msgIn++;
                const msg = JSON.parse(ev.data);
                const t = msg.t;
                if (t === 'welcome') {
                    mpPeerId = msg.id;
                    mpConnected = true;
                    mpHudRefresh();
                    return;
                }
                if (t === 'snapshot') {
                    for (const pl of msg.players || []) mpAddPlayer(pl);
                    mpHudRefresh();
                    return;
                }
                if (t === 'joined') { mpAddPlayer(msg); mpHudRefresh(); return; }
                if (t === 'updated') { mpOnUpdated(msg); return; }
                if (t === 'departed') { mpRemovePlayer(msg.id); mpHudRefresh(); return; }
                if (t === 'session_state') {
                    mpSession = {
                        mode: msg.mode || 'tourist',
                        phase: msg.phase || 'idle',
                        countdown: msg.countdown ?? null,
                        totalLaps: msg.totalLaps ?? 1,
                        hostId: msg.hostId || null,
                    };
                    mpRaceUiRefresh();
                    return;
                }
                if (t === 'host_changed') {
                    mpSession.hostId = msg.id || null;
                    mpRaceUiRefresh();
                    return;
                }
                if (t === 'round_state') {
                    roundState = {
                        roundType: msg.roundType || 'checkpoint_sprint',
                        roundPhase: msg.roundPhase || 'idle',
                        roundIndex: Number(msg.roundIndex) || 0,
                        roundEndsAt: Number(msg.roundEndsAt) || 0,
                        roundLiveAt: Number(msg.roundLiveAt) || 0,
                    };
                    mpRaceUiRefresh();
                    return;
                }
                if (t === 'countdown_tick') {
                    mpSession.phase = 'countdown';
                    mpSession.countdown = msg.n;
                    soloRace.phase = 'tourist';
                    mpRaceUiRefresh();
                    return;
                }
                if (t === 'race_go') {
                    mpSession.mode = 'race';
                    mpSession.phase = 'live';
                    mpSession.countdown = null;
                    localRaceNextCp = 1;
                    localRaceFinished = false;
                    lastCpGateHover = -1;
                    chaosScore = 0;
                    soloRace.phase = 'tourist';
                    for (const p of chaosPickupPos) p.hit = false;
                    mpRaceUiRefresh();
                    return;
                }
                if (t === 'standings') {
                    mpStandings = Array.isArray(msg.rows) ? msg.rows : [];
                    if (mpPeerId) {
                        const row = mpStandings.find((r) => r.id === mpPeerId);
                        if (row && Number.isFinite(row.nextCp)) {
                            localRaceNextCp = Math.min(Math.max(1, nordCheckpoints.length - 1), Math.max(0, row.nextCp));
                            localRaceFinished = !!row.finished;
                        }
                    }
                    mpRaceUiRefresh();
                    return;
                }
                if (t === 'race_finish') {
                    mpSession.phase = 'results';
                    mpRaceUiRefresh();
                    return;
                }
                if (t === 'chaos_score') {
                    if (!msg.id || msg.id === mpPeerId) chaosScore = Number(msg.score) || 0;
                    mpRaceUiRefresh();
                    return;
                }
            } catch (_) {}
        };
        mpSocket.onclose = () => {
            mpConnected = false;
            mpPeerId = null;
            for (const pid of [...mpPlayers.keys()]) mpRemovePlayer(pid);
            mpHudRefresh();
            mpScheduleReconnect();
        };
        mpSocket.onerror = () => { try { mpSocket.close(); } catch (_) {} };
    } catch (_) {
        mpScheduleReconnect();
    }
}

function mpEnsureRaceJoin() {
    try {
        const url = getMpRelayUrl();
        if (!url) return;
        if (mpSocket && mpSocket.readyState === 1) mpSendJoin();
        else mpOpenSocket();
    } catch (_) {}
}

setInterval(() => {
    try {
        if (!mpConnected || STATE !== 'playing' || !mpSocket || mpSocket.readyState !== 1) return;
        mpSend({
            t: 'update',
            x: mpRound(carX, 1),
            z: mpRound(carZ, 1),
            y: mpRound(carY, 1),
            a: mpRound(carAngle, 3),
            s: mpRound(carSpeed, 1),
        });
    } catch (_) {}
}, 100);

let bestLap = null;
try { const bl = parseFloat(localStorage.getItem('mf_nord3d_best_v2')); if (bl > 0) bestLap = bl; } catch (e) {}
if (bestLap) document.getElementById('btv').textContent = formatTime(bestLap);

const keysHeld = new Set();
let touchLeft = false, touchRight = false, touchAccel = false;
let touchSteerAmount = 0; // -1 to 1, proportional

// Orbit camera: mouse drag to look around car, auto-centers back
let orbitYaw = 0, orbitPitch = 0;  // current orbit angles
let orbitDragging = false;
let orbitLastX = 0, orbitLastY = 0;
const isMobile = 'ontouchstart' in window || navigator.maxTouchPoints > 0;

function formatTime(t) {
    const m = Math.floor(t / 60), s = Math.floor(t - m * 60), ms = Math.floor((t - Math.floor(t)) * 10);
    return m + ':' + (s < 10 ? '0' : '') + s + '.' + ms;
}

// Smooth camera target
const _camLook = new THREE.Vector3();

// =====================================================================
// UPDATE — Free world-space car physics
// =====================================================================
function update(dt) {
    const inputFrozen = raceResetHold > 0 || menuOpen;
    if (raceResetHold > 0) {
        if (flashEl) {
            flashEl.style.opacity = '1';
            if (raceResetHold > 1.1) { flashEl.textContent = 'RESET'; flashEl.style.color = '#00ff41'; }
            else if (raceResetHold > 0.7) { flashEl.textContent = '3'; flashEl.style.color = '#fff'; }
            else if (raceResetHold > 0.3) { flashEl.textContent = '2'; flashEl.style.color = '#fff'; }
            else { flashEl.textContent = '1'; flashEl.style.color = '#fff'; }
        }
        raceResetHold = Math.max(0, raceResetHold - dt);
        if (raceResetHold <= 0 && flashEl) flashEl.style.opacity = '0';
        carSpeed = 0;
        carVelX = 0;
        carVelZ = 0;
        yawRate = 0;
        steerAmount = 0;
    }
    const goFwd = !inputFrozen && (keysHeld.has('up') || touchAccel);
    const goBack = !inputFrozen && keysHeld.has('down');
    const goLeft = !inputFrozen && (keysHeld.has('left') || touchLeft);
    const goRight = !inputFrozen && (keysHeld.has('right') || touchRight);

    // --- 1. Simcade traction-limited velocity model ---
    let steerInput = 0;
    if (goLeft) steerInput = 1;
    if (goRight) steerInput = -1;
    if (Math.abs(touchSteerAmount) > 0.05) steerInput = touchSteerAmount;

    let preNearest = { t: 0, signedOffset: 0 };
    let surfaceGrip = 1;
    let sectionGrip = 1;
    if (activeMap !== 'cluj' && splinePts.length) {
        preNearest = findNearestT(carX, carZ);
        const surface = getTrackSurface(preNearest.signedOffset || 0);
        surfaceGrip = surface.grip;
        sectionGrip = getSectionAt(preNearest.t).grip ?? 1;
        lastSurfaceKind = surface.kind;
    }

    const fwdX = Math.sin(carAngle);
    const fwdZ = Math.cos(carAngle);
    const rightX = Math.cos(carAngle);
    const rightZ = -Math.sin(carAngle);
    let localForward = carVelX * fwdX + carVelZ * fwdZ;
    let localSide = carVelX * rightX + carVelZ * rightZ;
    if (localForward < 0) localForward *= 0.94;

    let curGearIdx = 0;
    const speedAbs = Math.max(0, localForward);
    for (let g = 0; g < GEAR_TABLE.length; g++) {
        if (speedAbs < GEAR_TABLE[g][0]) { curGearIdx = g; break; }
        curGearIdx = g;
    }
    const gearTop = GEAR_TABLE[curGearIdx][0];
    const gearBottom = curGearIdx > 0 ? GEAR_TABLE[curGearIdx - 1][0] : 0;
    const gearFraction = gearTop > gearBottom ? Math.max(0, Math.min(1, (speedAbs - gearBottom) / (gearTop - gearBottom))) : 0;
    const engineAccel = GEAR_TABLE[curGearIdx][1] * Math.max(0.16, 1 - gearFraction * 0.86);
    const throttle = goFwd ? 1 : 0;
    const brake = goBack ? 1 : 0;
    const drag = AERO_DRAG * localForward * Math.abs(localForward) + ROLLING_DRAG + (throttle ? 0 : 2.2);
    const gripBudget = BASE_GRIP_MS2 * sectionGrip * surfaceGrip;
    const longDemand = throttle * engineAccel - brake * BRAKING - Math.sign(localForward || 1) * drag;
    const maxLong = gripBudget * (brake ? 1.15 : 1.05);
    const longAccel = Math.max(-maxLong, Math.min(maxLong, longDemand));
    localForward = Math.max(0, Math.min(MAX_SPEED, localForward + longAccel * dt));

    const speedNorm = Math.min(1, localForward / 70);
    const steerLimit = STEER_LIMIT * (1 - 0.34 * speedNorm);
    const steerTarget = steerInput * steerLimit;
    steerAmount += (steerTarget - steerAmount) * (1 - Math.exp(-7.5 * dt));
    const desiredYaw = Math.tan(steerAmount) * localForward / WHEELBASE_M;
    const lateralDemand = Math.abs(desiredYaw * localForward) * 0.72;
    const gripRatio = lateralDemand > gripBudget && lateralDemand > 0 ? gripBudget / lateralDemand : 1;
    const steerAuthority = 0.32 + 0.68 * gripRatio;
    const targetYawRate = desiredYaw * steerAuthority;
    yawRate += (targetYawRate - yawRate) * (1 - Math.exp(-8.5 * dt));
    carAngle += yawRate * dt;

    const lateralGrip = gripBudget * (0.75 + 0.25 * gripRatio);
    const sideSign = Math.sign(localSide);
    localSide -= sideSign * Math.min(Math.abs(localSide), lateralGrip * dt);
    const slipExcess = Math.max(0, lateralDemand - gripBudget);
    if (slipExcess > 0) {
        localSide += -Math.sign(steerAmount || 1) * Math.min(3.2, slipExcess * 0.008) * dt;
        localForward *= Math.max(0, 1 - Math.min(0.18, slipExcess * 0.002) * dt);
    }
    lastGripBudget = gripBudget;
    lastSlipAmount = Math.abs(localSide) + slipExcess * 0.02;

    const newFwdX = Math.sin(carAngle);
    const newFwdZ = Math.cos(carAngle);
    const newRightX = Math.cos(carAngle);
    const newRightZ = -Math.sin(carAngle);
    carVelX = newFwdX * localForward + newRightX * localSide;
    carVelZ = newFwdZ * localForward + newRightZ * localSide;
    const velMag = Math.hypot(carVelX, carVelZ);
    if (velMag > MAX_SPEED) {
        carVelX *= MAX_SPEED / velMag;
        carVelZ *= MAX_SPEED / velMag;
    }
    carX += carVelX * dt;
    carZ += carVelZ * dt;
    carSpeed = Math.hypot(carVelX, carVelZ);

    // --- 4. Find road surface ---
    let nearest, onRoad, surfaceY;
    if (activeMap === 'cluj') {
        const groundY = getClujGroundY(carX, carZ);
        lastRoadY = groundY;
        lastTerrainY = groundY;
        const targetY = groundY + CAR_CLEARANCE;
        carY += (targetY - carY) * (1 - Math.exp(-16 * dt));
        onRoad = true; // in open world, all roads are meshes
        nearest = { t: 0, dist: 0, y: groundY };
        surfaceY = groundY;
    } else {
        nearest = findNearestT(carX, carZ);
        const surface = getTrackSurface(nearest.signedOffset || 0);
        lastSurfaceKind = surface.kind;
        onRoad = Math.abs(nearest.signedOffset || 0) <= ROAD_W;
        const roadY = getRoadRibbonY(nearest);
        const groundY = onRoad ? roadY : getNordGroundY(carX, carZ, nearest.y);
        lastRoadY = roadY;
        lastTerrainY = groundY;
        if (onRoad) lastGroundSource = 'road-analytic';
        const targetY = groundY + CAR_CLEARANCE;
        const yDelta = targetY - carY;
        const yFollow = Math.abs(yDelta) > 1.5 ? 1 : (1 - Math.exp(-18 * dt));
        carY += yDelta * yFollow;
        surfaceY = groundY;
    }

    // Surface drag: curbs and shoulders are recoverable; deep grass slows the car decisively.
    if (activeMap !== 'cluj') {
        const surface = getTrackSurface(nearest.signedOffset || 0);
        if (surface.drag > 0) {
            const offAmount = Math.min(1, Math.max(0, (Math.abs(nearest.signedOffset || 0) - ROAD_W) / 20));
            const dragMul = Math.max(0, 1 - (surface.drag + offAmount * 2.2) * dt);
            carVelX *= dragMul;
            carVelZ *= dragMul;
            carSpeed = Math.hypot(carVelX, carVelZ);
        }
        const headingDot = Math.max(-1, Math.min(1, newFwdX * (nearest.tangentX || 0) + newFwdZ * (nearest.tangentZ || 1)));
        const headingError = Math.acos(headingDot);
        if (carSpeed > 18 && headingError > 0.55) {
            const headingMul = Math.max(0, 1 - (headingError - 0.55) * 0.9 * dt);
            carVelX *= headingMul;
            carVelZ *= headingMul;
            carSpeed = Math.hypot(carVelX, carVelZ);
        }
        const limit = ROAD_W + 24;
        const offAbs = Math.abs(nearest.signedOffset || 0);
        if (offAbs > limit && nearest.centerX != null) {
            const side = nearest.signedOffset < 0 ? -1 : 1;
            carX = nearest.centerX + nearest.rightX * side * limit;
            carZ = nearest.centerZ + nearest.rightZ * side * limit;
            carVelX *= 0.7;
            carVelZ *= 0.7;
            carSpeed *= Math.max(0.35, 1 - 2.5 * dt);
            carSpeed = Math.hypot(carVelX, carVelZ);
            crashShakeT = Math.max(crashShakeT, 0.12);
        }
    }

    // Turning at speed: slight grip cost (understeer feel)
    if (steerInput !== 0 && carSpeed > 15) {
        const steerScrub = (1 - 0.018 * Math.abs(speedNorm) * dt);
        carVelX *= steerScrub;
        carVelZ *= steerScrub;
        carSpeed = Math.hypot(carVelX, carVelZ);
    }

    // --- 5. Lap/checkpoint progression ---
    if (activeMap !== 'cluj') {
        if (soloRace.phase === 'countdown') {
            soloRace.countdown = Math.max(0, soloRace.countdown - dt);
            if (soloRace.countdown <= 0) {
                soloRace.phase = 'live';
                soloRace.nextCp = 1;
                soloRace.laps = 1;
                soloRace.finished = false;
                lapTime = 0;
            }
            mpRaceUiRefresh();
        }
        const curSector = Math.floor(nearest.t * 100);
        const touristMode = mpSession.mode !== 'race' && soloRace.phase === 'tourist';
        if (touristMode && prevSector > 90 && curSector < 10 && carSpeed > 5 && lapTime > 20) completeLap();
        prevSector = curSector;
    }

    // --- 5b. Race progression: multiplayer + solo checkpoint model ---
    if (activeMap !== 'cluj' && mpSession.mode === 'race' && mpSession.phase === 'live' && mpSocket && mpSocket.readyState === 1) {
        if (!localRaceFinished && nordCheckpoints.length) {
            const cp = nordCheckpoints.find((c) => c.index === localRaceNextCp);
            if (cp) {
                const rad = Number(cp.radiusM) || 45;
                const dx = carX - cp.x;
                const dz = carZ - cp.z;
                const inside = dx * dx + dz * dz < rad * rad;
                if (inside) {
                    if (lastCpGateHover !== localRaceNextCp) {
                        lastCpGateHover = localRaceNextCp;
                        mpSend({ t: 'checkpoint_hit', index: localRaceNextCp });
                    }
                } else if (lastCpGateHover === localRaceNextCp) {
                    lastCpGateHover = -1;
                }
            }
        }
    }
    if (activeMap !== 'cluj' && soloRace.phase === 'live' && !soloRace.finished && nordCheckpoints.length) {
        const finishCp = Math.max(1, nordCheckpoints.length - 1);
        const cp = nordCheckpoints.find((c) => c.index === soloRace.nextCp);
        if (cp) {
            const rad = Number(cp.radiusM) || 45;
            const dx = carX - cp.x;
            const dz = carZ - cp.z;
            const inside = dx * dx + dz * dz < rad * rad;
            if (inside && lastCpGateHover !== soloRace.nextCp) {
                lastCpGateHover = soloRace.nextCp;
                if (soloRace.nextCp === finishCp) {
                    completeLap();
                    if (soloRace.laps >= soloRace.totalLaps) {
                        soloRace.finished = true;
                        soloRace.phase = 'results';
                    } else {
                        soloRace.laps += 1;
                        soloRace.nextCp = 1;
                    }
                } else {
                    soloRace.nextCp += 1;
                }
                mpRaceUiRefresh();
            } else if (!inside && lastCpGateHover === soloRace.nextCp) {
                lastCpGateHover = -1;
            }
        }
    }

    // --- 6. Position car mesh ---
    carGroup.position.set(carX, carY, carZ);
    carGroup.rotation.y = carAngle;

    // Shadow on road surface (not tied to car Y — prevents bumping)
    shadowPlane.position.set(carX, surfaceY + 0.05, carZ);
    shadowPlane.rotation.y = carAngle;

    // Wheel spinning removed — was spinning wrong parts


    // Dust particles when off-road or hard cornering
    if (!onRoad && carSpeed > 5) {
        for (let d = 0; d < 2; d++) spawnDust(carX, surfaceY, carZ, carSpeed);
    }
    if ((steerInput !== 0 && carSpeed > 30) || lastSlipAmount > 1.2) {
        spawnDust(carX - newFwdX * 2, surfaceY, carZ - newFwdZ * 2, carSpeed * 0.3);
        crashShakeT = Math.max(crashShakeT, Math.min(0.08, lastSlipAmount * 0.01));
    }
    updateDust(dt);

    // --- 7. Camera with orbit support ---
    const sp = speedNorm;
    const mobOff = isMobile ? 2.0 : 0;
    const camDist = 5.5 + mobOff + sp * 0.8;
    const camH = 2.5 + mobOff * 0.5 + sp * 0.25;

    // Auto-center orbit when not dragging
    if (!orbitDragging) {
        orbitYaw *= 0.92;   // smooth return to center
        orbitPitch *= 0.92;
    }

    // Apply orbit: rotate camera offset around car by orbitYaw
    const cosO = Math.cos(orbitYaw), sinO = Math.sin(orbitYaw);
    const baseBackX = -newFwdX * camDist;
    const baseBackZ = -newFwdZ * camDist;
    const orbitX = baseBackX * cosO - baseBackZ * sinO;
    const orbitZ = baseBackX * sinO + baseBackZ * cosO;

    const idealCamPos = new THREE.Vector3(
        carX + orbitX,
        carY + camH + orbitPitch * camDist, // pitch tilts height
        carZ + orbitZ
    );

    // Look at the car (orbit rotates the view around the car)
    const lookDist = 2 + sp * 0.4;
    const idealLook = new THREE.Vector3(
        carX + newFwdX * lookDist * (1 - Math.abs(orbitYaw)),
        carY + 0.8,
        carZ + newFwdZ * lookDist * (1 - Math.abs(orbitYaw))
    );

    // Split smoothing: fast forward/back, smooth lateral, all in XZ plane
    const posFast = 1 - Math.exp(-20 * dt);
    const posSlow = 1 - Math.exp(-(isMobile ? 5 : 8) * dt);
    // Work in XZ only to avoid Y tilt issues
    const dxCam = idealCamPos.x - camera.position.x;
    const dzCam = idealCamPos.z - camera.position.z;
    // Project delta onto forward axis (XZ only)
    const fwdDot = dxCam * newFwdX + dzCam * newFwdZ;
    // Forward component (fast)
    camera.position.x += newFwdX * fwdDot * posFast;
    camera.position.z += newFwdZ * fwdDot * posFast;
    // Lateral component = remainder (slow)
    const latX = dxCam - newFwdX * fwdDot;
    const latZ = dzCam - newFwdZ * fwdDot;
    camera.position.x += latX * posSlow;
    camera.position.z += latZ * posSlow;
    // Y: fast follow, completely separate
    camera.position.y += (idealCamPos.y - camera.position.y) * posFast;

    // Crash camera shake
    if (crashShakeT > 0) {
        const sh = crashShakeT * 0.5;
        camera.position.x += (Math.random() - 0.5) * sh;
        camera.position.y += (Math.random() - 0.5) * sh * 0.3;
        camera.position.z += (Math.random() - 0.5) * sh;
        crashShakeT = Math.max(0, crashShakeT - dt * 2.5);
    }

    _camLook.lerp(idealLook, posFast); // must match camera position speed to prevent tilt
    camera.lookAt(_camLook);

    // Sky dome + moon follow camera so sky is always visible
    skyMesh.position.copy(camera.position);
    moonMesh.position.set(camera.position.x + 500, camera.position.y + 800, camera.position.z - 300);

    // FOV: enough expansion to make 200+ km/h read as fast without going fisheye.
    camera.fov = (isMobile ? 72 : 65) + sp * 7;
    camera.updateProjectionMatrix();

    // --- 8. Speed effects ---
    // Vignette: darken edges at high speed
    const vig = document.getElementById('vignette');
    if (vig) vig.style.opacity = String(Math.min(0.15, sp * 0.15)); // very subtle

    // Speed lines canvas
    const slCanvas = document.getElementById('speed-lines');
    if (slCanvas && sp > 0.4) {
        if (slCanvas.width !== vw) { slCanvas.width = vw; slCanvas.height = vh; }
        slCanvas.style.opacity = String(Math.min(0.85, (sp - 0.4) * 1.9));
        const slCtx = slCanvas.getContext('2d');
        slCtx.clearRect(0, 0, vw, vh);
        slCtx.strokeStyle = 'rgba(255,255,255,0.08)';
        slCtx.lineWidth = 1;
        const n = Math.floor((sp - 0.4) * 42);
        for (let i = 0; i < n; i++) {
            const side = Math.random() < 0.5 ? 0 : 1;
            const x = side ? vw * 0.85 + Math.random() * vw * 0.15 : Math.random() * vw * 0.15;
            const y = vh * 0.2 + Math.random() * vh * 0.6;
            const len = 30 + sp * 80;
            slCtx.beginPath();
            slCtx.moveTo(x, y);
            slCtx.lineTo(x + (side ? 1 : -1) * len * 0.2, y + len);
            slCtx.stroke();
        }
    } else if (slCanvas) {
        slCanvas.style.opacity = '0';
    }

    // Speed number color
    const spdEl = document.getElementById('spdv');
    if (spdEl) {
        if (sp > 0.8) spdEl.style.color = '#ff3d00';
        else if (sp > 0.5) spdEl.style.color = '#ffbe0b';
        else spdEl.style.color = '#fff';
    }

    // --- 9. Engine + audio ---
    engineUpdate(sp);

    // Tire screech removed — sounded bad

    // Brake lights: brighten when braking
    if (brakeLightMat) {
        brakeLightMat.emissiveIntensity = goBack ? 3.0 : (goFwd ? 0.5 : 1.5);
    }

    // Progress bar
    const progBar = document.getElementById('progress-bar');
    if (progBar) progBar.style.width = (nearest.t * 100) + '%';

    // --- 10. HUD ---
    if (!inputFrozen) lapTime += dt;
    document.getElementById('ltv').textContent = formatTime(lapTime);
    document.getElementById('spdv').textContent = Math.round(carSpeed * 3.6);
    // Gear indicator (from physics gear table)
    document.getElementById('gearv').textContent = curGearIdx + 1;
    if (activeMap === 'cluj') {
        // Show nearest street name
        const streetName = getClujStreetName(carX, carZ);
        document.getElementById('altv').textContent = '380m';
        if (streetName && streetName !== currentSection) {
            currentSection = streetName;
            sectionFade = 1;
            sectionEl.textContent = currentSection.toUpperCase();
            sectionEl.style.opacity = '1';
        }
    } else {
        const sec = getSectionAt(nearest.t);
        if (sec) {
            document.getElementById('altv').textContent = sec.alt;
            if (sec.name !== currentSection) {
                currentSection = sec.name;
                sectionFade = 1;
                sectionEl.textContent = currentSection.toUpperCase();
                sectionEl.style.opacity = '1';
            }
        }
    }
    if (sectionFade > 0) { sectionFade -= dt * 0.4; if (sectionFade <= 0) sectionEl.style.opacity = '0'; }
    if (lapFlashAlpha > 0) { lapFlashAlpha -= dt * 0.3; flashEl.style.opacity = String(Math.max(0, lapFlashAlpha)); }

    mpUpdateRemoteCars();

    // --- Collision with remote players ---
    // Remote positions are already interpolated by mpUpdateRemoteCars above.
    // We use a simple repulsion sphere: if two cars overlap, push local car away
    // and play a crash sound scaled by impact severity.
    if (mpPlayers.size > 0 && !inputFrozen) {
        let collided = false;
        for (const [, rp] of mpPlayers) {
            if (!rp.group.visible) continue;
            const dx = carX - rp.group.position.x;
            const dz = carZ - rp.group.position.z;
            const distSq = dx * dx + dz * dz;
            if (distSq < CRASH_DIST_SQ && distSq > 0.01) {
                const dist = Math.sqrt(distSq);
                const overlap = CRASH_DIST - dist;
                const nx = dx / dist, nz = dz / dist; // repulsion normal (local car away)

                // Push local car out of overlap
                carX += nx * overlap * 0.6;
                carZ += nz * overlap * 0.6;

                // Relative closing speed: positive = approaching
                const closingSpd = carSpeed - (rp.curr.s * (nx * Math.sin(rp.curr.a) + nz * Math.cos(rp.curr.a)));
                const impactMag = Math.max(0, closingSpd) * (overlap / CRASH_DIST);

                if (!(rp.crashCD > 0)) {
                    // Reduce speed by impact fraction (harder hits slow you more)
                    const speedLoss = Math.min(0.6, impactMag * 0.03);
                    carVelX *= (1 - speedLoss);
                    carVelZ *= (1 - speedLoss);
                    carSpeed = Math.hypot(carVelX, carVelZ);

                    // Sound: volume proportional to impact
                    sfxCrash(0.1 + impactMag * 0.04);

                    rp.crashCD = 1.2;
                    collided = true;
                }
            }
            if (rp.crashCD > 0) rp.crashCD -= dt;
        }

        if (collided) {
            // Screen flash: brief orange tint
            if (flashEl && lapFlashAlpha <= 0 && !raceResetHold) {
                flashEl.textContent = '';
                flashEl.style.color = 'transparent';
                flashEl.style.backgroundColor = 'rgba(255,100,0,0.25)';
                flashEl.style.opacity = '1';
                setTimeout(() => {
                    if (flashEl) { flashEl.style.opacity = '0'; flashEl.style.backgroundColor = ''; }
                }, 250);
            }
            // Camera shake
            crashShakeT = Math.max(crashShakeT, 0.35);
            // Re-apply car position after collision displacement
            carGroup.position.set(carX, carY, carZ);
            shadowPlane.position.set(carX, carY - 0.25, carZ);
        }
    }

    if (trackDebugEl && activeMap !== 'cluj') {
        const nt = lastNearestTrack || nearest;
        const cpTarget = soloRace.phase === 'live' ? soloRace.nextCp : localRaceNextCp;
        trackDebugEl.textContent = [
            `track ${(nt.t * 100).toFixed(2)}%  ${Math.round(nt.progressM || 0)}m/${Math.round(trackMeta.lengthM)}m`,
            `offset ${(nt.signedOffset || 0).toFixed(2)}m  dist ${(nt.dist || 0).toFixed(2)}m  surface ${lastSurfaceKind}`,
            `ground ${lastGroundSource}  roadY ${lastRoadY.toFixed(2)}  groundY ${lastTerrainY.toFixed(2)}  carY ${carY.toFixed(2)}`,
            `speed ${Math.round(carSpeed * 3.6)}km/h  grip ${lastGripBudget.toFixed(1)}  slip ${lastSlipAmount.toFixed(2)}`,
            `section ${currentSection || '-'}  checkpoint ${cpTarget}/${Math.max(1, nordCheckpoints.length - 1)}`,
        ].join('\n');
    }

    drawMinimap();
}

function completeLap() {
    const isNew = !bestLap || lapTime < bestLap;
    if (isNew) {
        bestLap = lapTime;
        document.getElementById('btv').textContent = formatTime(bestLap);
        try { localStorage.setItem('mf_nord3d_best_v2', bestLap); } catch (e) {}
        flashEl.textContent = 'NEW BEST  ' + formatTime(lapTime);
        flashEl.style.color = '#ffbe0b';
    } else {
        flashEl.textContent = 'LAP  ' + formatTime(lapTime);
        flashEl.style.color = '#00ff41';
    }
    lapFlashAlpha = 1; flashEl.style.opacity = '1';
    currentLap++; lapTime = 0;
}

function resetCarToStart() {
    try {
        if (activeMap === 'cluj') {
            carX = -20; carZ = -45; carY = CAR_CLEARANCE;
            carAngle = 0;
            currentSection = 'Piața Unirii'; sectionFade = 1;
            sectionEl.textContent = 'PIAȚA UNIRII';
            sectionEl.style.opacity = '1';
        } else {
            const startPos = spline.getPointAt(0);
            const startTan = spline.getTangentAt(0).normalize();
            const startNearest = findNearestT(startPos.x, startPos.z);
            carX = startPos.x; carZ = startPos.z; carY = getRoadRibbonY(startNearest) + CAR_CLEARANCE;
            carAngle = Math.atan2(startTan.x, startTan.z);
            currentSection = ''; sectionFade = 0;
        }
        carSpeed = 0; carVelX = 0; carVelZ = 0; yawRate = 0; steerAmount = 0;
        lapTime = 0; prevSector = 0; lapFlashAlpha = 0;
        raceResetHold = 1.2;
    } catch (_) {}
}

// GAME LOOP
// =====================================================================
const STEP = 1 / 60;
let lastTime = 0, gdt = 0, loopId = null;

let _frameCount = 0, _updateCount = 0;
function gameLoop() {
    if (STATE !== 'playing') {
        loopId = requestAnimationFrame(gameLoop);
        return;
    }
    _frameCount++;
    try {
        const now = performance.now();
        const dt = Math.min(0.1, (now - lastTime) / 1000);
        lastTime = now;
        gdt += dt;
        while (gdt > STEP) { gdt -= STEP; _updateCount++; update(STEP); }
        composer.render();
        if (location.search.includes('perf=1')) {
            perfOverlay.style.display = 'block';
            if (!sessionPerf.lastUiTs || now - sessionPerf.lastUiTs > 500) {
                const elapsed = Math.max(0.001, (now - (sessionPerf.lastUiTs || now)) / 1000);
                const fps = (_frameCount / Math.max(1, (now - (sessionPerf.lastUiTs || now)) / 1000)) | 0;
                const inRate = (sessionPerf.netIn / elapsed) | 0;
                const outRate = (sessionPerf.netOut / elapsed) | 0;
                perfOverlay.textContent = `fps~${fps} in:${inRate}B/s out:${outRate}B/s msgs:${sessionPerf.msgIn}/${sessionPerf.msgOut}`;
                sessionPerf.lastUiTs = now;
                sessionPerf.netIn = 0;
                sessionPerf.netOut = 0;
                sessionPerf.msgIn = 0;
                sessionPerf.msgOut = 0;
                _frameCount = 0;
            }
        } else {
            perfOverlay.style.display = 'none';
        }
    } catch (e) {
        console.error('Game loop error:', e);
        document.title = 'ERR:' + e.message;
    }
    loopId = requestAnimationFrame(gameLoop);
}

function transitionToRace() {
    if (activeMap === 'nordschleife' && !trackReady) return;
    toggleMenu(false);
    STATE = 'transition';
    promptEl.classList.add('hidden');
    for (let r = 0; r < ROWS; r++) for (let c = 0; c < COLS; c++)
        if (FILLED[r + ',' + c]) board[r][c].className = 'c f out';
    setTimeout(() => {
        try {
            gridEl.style.display = 'none';
            container.classList.add('show');
            scoresEl.classList.add('show');
            // Initialize car at start of track in world space
            if (activeMap === 'cluj') {
                buildClujScene();
                // Start at Piata Unirii area
                carX = -20; carZ = -45; carY = CAR_CLEARANCE;
                carAngle = 0; carSpeed = 0; carVelX = 0; carVelZ = 0; yawRate = 0; steerAmount = 0; lapTime = 0;
                currentSection = 'Piața Unirii'; sectionFade = 1;
                sectionEl.textContent = 'PIAȚA UNIRII';
                sectionEl.style.opacity = '1';
            } else {
                if (nordsWorldGroup) nordsWorldGroup.visible = true;
                const startPos = spline.getPointAt(0);
                const startTan = spline.getTangentAt(0).normalize();
                const startNearest = findNearestT(startPos.x, startPos.z);
                carX = startPos.x; carZ = startPos.z; carY = getRoadRibbonY(startNearest) + CAR_CLEARANCE;
                carAngle = Math.atan2(startTan.x, startTan.z);
            }
            carSpeed = 0; carVelX = 0; carVelZ = 0; yawRate = 0; steerAmount = 0;
            lapTime = 0; prevSector = 0;
            currentSection = ''; sectionFade = 0; lapFlashAlpha = 0;
            soloRace = { phase: 'tourist', countdown: 0, nextCp: 1, laps: 1, totalLaps: 1, finished: false };
            // Position camera behind car
            const camBack = 5.5;
            camera.position.set(carX, carY + 2.5, carZ - camBack);
            _camLook.set(carX, carY + 1.5, carZ);
            camera.lookAt(_camLook);
            STATE = 'playing';
            engineStart();
            lastTime = performance.now(); gdt = 0;
            if (loopId) cancelAnimationFrame(loopId);
            loopId = requestAnimationFrame(gameLoop);
            try { mpEnsureRaceJoin(); } catch (_) {}
            console.log('Transition complete, gameLoop requested, loopId:', loopId);
        } catch(e) {
            console.error('Transition error:', e);
            document.title = 'TRANS_ERR:' + e.message;
        }
    }, 900);
}

// =====================================================================
// INPUT
// =====================================================================
if (menuResumeBtn) menuResumeBtn.addEventListener('click', () => toggleMenu(false));
if (menuResetBtn) menuResetBtn.addEventListener('click', () => { resetCarToStart(); toggleMenu(false); });
if (menuModeBtn) menuModeBtn.addEventListener('click', () => setMenuInfoMode());
if (menuGuideBtn) menuGuideBtn.addEventListener('click', () => setMenuInfoGuide());

function keyAction(k) {
    if (k === 'ArrowUp' || k === 'w' || k === 'W') return 'up';
    if (k === 'ArrowDown' || k === 's' || k === 'S') return 'down';
    if (k === 'ArrowLeft' || k === 'a' || k === 'A') return 'left';
    if (k === 'ArrowRight' || k === 'd' || k === 'D') return 'right';
    return null;
}
document.addEventListener('keydown', e => {
    if (STATE === 'intro') {
        // Cheat code detection: type "cluj" to unlock secret map
        if (e.key.length === 1) {
            cheatBuffer += e.key.toLowerCase();
            if (cheatBuffer.length > 10) cheatBuffer = cheatBuffer.slice(-10);
            if (cheatBuffer.endsWith('cluj')) {
                activeMap = 'cluj';
                promptEl.textContent = 'CLUJ-NAPOCA — Press any key';
                promptEl.style.color = '#ffbe0b';
                cheatBuffer = '';
                e.preventDefault();
                return;
            }
        }
        // Any non-letter key or after cheat: start the game
        if (e.key.length > 1 || e.key === ' ') {
            if (activeMap === 'nordschleife' && !trackReady) {
                promptEl.textContent = trackLoadError ? 'Track load failed — refresh' : 'Loading track…';
                e.preventDefault();
                return;
            }
            transitionToRace(); e.preventDefault(); return;
        }
        return;
    }
    if (STATE !== 'playing') return;
    if ((e.key === 'm' || e.key === 'M') && !e.repeat) {
        e.preventDefault();
        toggleMenu();
        return;
    }
    if (menuOpen) {
        if (e.key === 'Escape') { e.preventDefault(); toggleMenu(false); }
        return;
    }
    if ((e.key === 't' || e.key === 'T') && !e.repeat && activeMap === 'nordschleife') {
        e.preventDefault();
        try {
            if (mpSocket && mpSocket.readyState === 1) {
                mpSend({ t: 'race_request', map: activeMap });
            } else if (soloRace.phase === 'tourist' || soloRace.phase === 'results') {
                soloRace = { phase: 'countdown', countdown: 3, nextCp: 1, laps: 1, totalLaps: 1, finished: false };
                chaosScore = 0;
                lastCpGateHover = -1;
                mpRaceUiRefresh();
            }
        } catch (_) {}
        return;
    }
    const a = keyAction(e.key);
    if (a) { e.preventDefault(); keysHeld.add(a); }
});
document.addEventListener('keyup', e => { const a = keyAction(e.key); if (a) keysHeld.delete(a); });
window.addEventListener('blur', () => keysHeld.clear());

// Touch
const activeTouches = {};
function updateTouch() {
    touchLeft = false; touchRight = false; touchAccel = false;
    touchSteerAmount = 0;
    const ids = Object.keys(activeTouches);
    if (ids.length > 0) {
        touchAccel = true;
        for (const id of ids) {
            const tx = activeTouches[id];
            // Proportional steering: center = 0, edges = ±1
            const center = vw * 0.5;
            const range = vw * 0.4; // 40% from center to full steer
            const steer = -(tx - center) / range; // negative = left side = steer left
            touchSteerAmount = Math.max(-1, Math.min(1, steer));
            if (touchSteerAmount < -0.1) touchLeft = true;
            else if (touchSteerAmount > 0.1) touchRight = true;
        }
    }
}
document.addEventListener('touchstart', e => {
    if (STATE === 'intro') {
        if (activeMap === 'nordschleife' && !trackReady) {
            promptEl.textContent = trackLoadError ? 'Track load failed — refresh' : 'Loading track…';
            e.preventDefault();
            return;
        }
        transitionToRace(); e.preventDefault(); return;
    }
    if (STATE === 'playing') {
        e.preventDefault();
        for (const t of e.changedTouches) activeTouches[t.identifier] = t.clientX;
        updateTouch();
    }
}, { passive: false });
document.addEventListener('touchmove', e => {
    if (STATE !== 'playing') return;
    e.preventDefault();
    for (const t of e.changedTouches) activeTouches[t.identifier] = t.clientX;
    updateTouch();
}, { passive: false });
document.addEventListener('touchend', e => {
    for (const t of e.changedTouches) delete activeTouches[t.identifier];
    updateTouch();
});
document.addEventListener('touchcancel', e => {
    for (const t of e.changedTouches) delete activeTouches[t.identifier];
    updateTouch();
});

// Orbit camera: right-click drag or shift+left-click
document.addEventListener('mousedown', e => {
    if (STATE !== 'playing') return;
    if (e.button === 2 || (e.button === 0 && e.shiftKey)) {
        orbitDragging = true;
        orbitLastX = e.clientX;
        orbitLastY = e.clientY;
        e.preventDefault();
    }
});
document.addEventListener('mousemove', e => {
    if (!orbitDragging) return;
    const dx = e.clientX - orbitLastX;
    const dy = e.clientY - orbitLastY;
    orbitYaw += dx * 0.005;
    orbitPitch = Math.max(-0.5, Math.min(0.5, orbitPitch - dy * 0.003));
    orbitLastX = e.clientX;
    orbitLastY = e.clientY;
});
document.addEventListener('mouseup', e => { if (e.button === 2 || e.button === 0) orbitDragging = false; });
document.addEventListener('contextmenu', e => e.preventDefault()); // prevent right-click menu

loadNordschleifeTrack()
    .then(() => {
        if (STATE === 'intro' && activeMap === 'nordschleife') {
            promptEl.textContent = 'Nordschleife 3D — Press any key';
        }
    })
    .catch((err) => {
        trackLoadError = err && err.message ? err.message : String(err);
        console.error('[nord] track load', err);
        if (STATE === 'intro' && activeMap === 'nordschleife') {
            promptEl.textContent = 'Track load failed — refresh page';
        }
    });

</script>
</body>
</html>

static mirror of HEAD · about · clone: git clone https://git.makefuture.ro/makefuture.git