🎮ArcadeLab

VELOCITY X — BEYOND LIMITS

by PlasmaStar57
1463 lines63.8 KB🛠️ Three.js (3D graphics)
▶ Play
<!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, viewport-fit=cover">
<meta name="theme-color" content="#060911">
<title>VELOCITY X — BEYOND LIMITS</title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; user-select: none; -webkit-user-select: none; -webkit-tap-highlight-color: transparent; }
  html, body { position: fixed; inset: 0; width: 100%; height: 100%; overflow: hidden; background: #060911; color: #f8fafc; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; touch-action: none; }
  #canvas-wrap { position: absolute; inset: 0; width: 100%; height: 100%; }
  canvas { display: block; width: 100%; height: 100%; }
  #nitro-vignette { position: absolute; inset: 0; pointer-events: none; z-index: 5; opacity: 0; transition: opacity 0.18s ease; background: radial-gradient(circle at center, transparent 48%, rgba(56, 189, 248, 0.22) 78%, rgba(249, 115, 22, 0.42) 100%); box-shadow: inset 0 0 80px rgba(56, 189, 248, 0.35); }
  #damage-flash { position: absolute; inset: 0; pointer-events: none; z-index: 6; opacity: 0; transition: opacity 0.15s ease; background: radial-gradient(circle at center, transparent 50%, rgba(239, 68, 68, 0.45) 100%); }

  /* HUD & Menus */
  #hud { position: absolute; inset: 0; pointer-events: none; z-index: 10; padding: calc(12px + env(safe-area-inset-top)) calc(16px + env(safe-area-inset-right)) calc(12px + env(safe-area-inset-bottom)) calc(16px + env(safe-area-inset-left)); display: flex; flex-direction: column; justify-content: space-between; }
  .hud-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 10px; }
  .glass { background: rgba(9, 14, 24, 0.72); border: 1px solid rgba(148, 163, 184, 0.22); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-radius: 10px; }
  .hud-card { padding: 10px 14px; }
  .hud-label { font-size: 0.65rem; letter-spacing: 0.16em; text-transform: uppercase; color: #94a3b8; font-weight: 700; }
  .hud-val { font-size: 1.15rem; font-weight: 900; letter-spacing: 0.04em; color: #f8fafc; }
  .hud-sub { font-size: 0.72rem; color: #38bdf8; font-weight: 700; margin-top: 2px; }
  .btn-icon { pointer-events: auto; cursor: pointer; padding: 10px 14px; font-weight: 900; font-size: 0.85rem; letter-spacing: 0.1em; color: #f8fafc; border: 1px solid rgba(148,163,184,0.3); background: rgba(15,23,42,0.82); border-radius: 10px; }
  .btn-icon:active { background: #ef4444; border-color: #ef4444; }

  .hud-bottom { display: flex; justify-content: space-between; align-items: flex-end; gap: 12px; margin-bottom: 6px; }
  .meter-box { width: min(250px, 42vw); padding: 12px 14px; }
  .speed-num { font-size: clamp(1.8rem, 4.5vw, 2.8rem); font-weight: 950; line-height: 1; font-variant-numeric: tabular-nums; }
  .speed-unit { font-size: 0.75rem; color: #94a3b8; font-weight: 800; letter-spacing: 0.14em; margin-left: 4px; }
  .bar-track { height: 9px; background: rgba(30, 41, 59, 0.9); border-radius: 999px; overflow: hidden; margin-top: 8px; border: 1px solid rgba(148,163,184,0.18); }
  .bar-fill { height: 100%; width: 0%; background: linear-gradient(90deg, #0284c7, #38bdf8, #f97316); transition: width 0.08s linear; }

  /* Overlay Screens */
  .screen { position: absolute; inset: 0; z-index: 20; display: flex; flex-direction: column; align-items: center; justify-content: center; background: radial-gradient(circle at 50% 25%, rgba(20, 34, 58, 0.92), rgba(5, 8, 15, 0.98)); padding: calc(18px + env(safe-area-inset-top)) calc(18px + env(safe-area-inset-right)) calc(18px + env(safe-area-inset-bottom)) calc(18px + env(safe-area-inset-left)); }
  .hidden { display: none !important; }
  .brand-kicker { font-size: 0.72rem; letter-spacing: 0.35em; text-transform: uppercase; color: #38bdf8; font-weight: 800; margin-bottom: 6px; text-align: center; }
  h1.game-title { font-size: clamp(2rem, 6vw, 4.2rem); font-weight: 950; letter-spacing: 0.14em; text-transform: uppercase; text-align: center; background: linear-gradient(135deg, #ffffff 15%, #38bdf8 55%, #f97316 95%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; filter: drop-shadow(0 8px 24px rgba(2, 132, 199, 0.35)); }
  .game-sub { font-size: 0.85rem; letter-spacing: 0.28em; color: #cbd5e1; text-transform: uppercase; margin-top: 4px; margin-bottom: 22px; text-align: center; }

  .menu-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(175px, 1fr)); gap: 10px; width: min(680px, 94vw); }
  .menu-btn { background: rgba(15, 23, 42, 0.88); border: 1px solid rgba(148, 163, 184, 0.25); border-left: 4px solid #38bdf8; color: #f8fafc; padding: 14px 16px; border-radius: 10px; font-weight: 800; font-size: 0.88rem; letter-spacing: 0.1em; text-transform: uppercase; cursor: pointer; display: flex; justify-content: space-between; align-items: center; transition: transform 0.14s ease, border-color 0.14s ease, background 0.14s ease; }
  .menu-btn:hover, .menu-btn:active { transform: translateY(-2px); border-color: #f97316; background: rgba(30, 41, 59, 0.96); }
  .menu-btn.primary { grid-column: 1 / -1; background: linear-gradient(90deg, rgba(2,132,199,0.35), rgba(249,115,22,0.3)); border-left-color: #f97316; font-size: 1rem; padding: 16px 20px; }

  .panel { width: min(940px, 95vw); max-height: 86vh; display: flex; flex-direction: column; padding: 18px; border-radius: 14px; }
  .panel-head { display: flex; justify-content: space-between; align-items: center; padding-bottom: 12px; margin-bottom: 14px; border-bottom: 1px solid rgba(148,163,184,0.2); gap: 10px; }
  .panel-title { font-size: 1.25rem; font-weight: 900; letter-spacing: 0.12em; text-transform: uppercase; }
  .panel-body { overflow-y: auto; flex: 1; padding-right: 4px; }
  .close-btn { background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #fecaca; padding: 8px 14px; border-radius: 8px; font-weight: 800; font-size: 0.78rem; letter-spacing: 0.1em; text-transform: uppercase; cursor: pointer; }
  .close-btn:hover { background: #ef4444; color: #fff; }

  .cards-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; }
  .card { background: rgba(15, 23, 42, 0.85); border: 1px solid rgba(148, 163, 184, 0.22); border-radius: 10px; padding: 14px; display: flex; flex-direction: column; justify-content: space-between; gap: 10px; }
  .card.active { border-color: #38bdf8; box-shadow: 0 0 0 1px rgba(56,189,248,0.4); }
  .card.locked { opacity: 0.65; }
  .pill { display: inline-block; font-size: 0.68rem; font-weight: 800; letter-spacing: 0.1em; text-transform: uppercase; padding: 3px 8px; border-radius: 999px; background: rgba(56,189,248,0.16); color: #7dd3fc; border: 1px solid rgba(56,189,248,0.3); }
  .pill.gold { background: rgba(250,204,21,0.16); color: #fde047; border-color: rgba(250,204,21,0.35); }
  .act-btn { background: #0284c7; color: #fff; border: none; border-radius: 7px; padding: 8px 11px; font-weight: 800; font-size: 0.75rem; letter-spacing: 0.08em; text-transform: uppercase; cursor: pointer; }
  .act-btn.warn { background: #ea580c; }
  .act-btn:disabled { background: #334155; color: #94a3b8; cursor: not-allowed; }

  .swatches { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 6px; }
  .swatch { width: 26px; height: 26px; border-radius: 50%; border: 2px solid rgba(255,255,255,0.35); cursor: pointer; }
  .swatch.selected { border-color: #ffffff; transform: scale(1.12); box-shadow: 0 0 10px rgba(255,255,255,0.6); }

  .stat-row { margin-top: 6px; }
  .stat-row label { display: flex; justify-content: space-between; font-size: 0.7rem; color: #94a3b8; font-weight: 700; }
  .mini-bar { height: 5px; background: #1e293b; border-radius: 999px; overflow: hidden; margin-top: 3px; }
  .mini-fill { height: 100%; background: #38bdf8; }

  .setting-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid rgba(148,163,184,0.14); gap: 12px; }
  select, input[type=range] { accent-color: #38bdf8; background: #1e293b; color: #f8fafc; border: 1px solid #475569; border-radius: 6px; padding: 6px 10px; font-size: 0.85rem; }

  /* Touch Controls */
  #touch-layer { position: absolute; inset: 0; pointer-events: none; z-index: 12; padding: calc(14px + env(safe-area-inset-top)) calc(14px + env(safe-area-inset-right)) calc(14px + env(safe-area-inset-bottom)) calc(14px + env(safe-area-inset-left)); display: flex; justify-content: space-between; align-items: flex-end; }
  .touch-group { display: flex; gap: 10px; pointer-events: auto; align-items: flex-end; }
  .t-pad { width: 64px; height: 64px; border-radius: 16px; background: rgba(15, 23, 42, 0.72); border: 2px solid rgba(148, 163, 184, 0.35); color: #f8fafc; font-weight: 900; font-size: 0.78rem; letter-spacing: 0.06em; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(6px); }
  .t-pad.pressed { background: rgba(2, 132, 199, 0.75); border-color: #7dd3fc; transform: scale(0.95); }
  .t-pad.nitro { background: rgba(234, 88, 12, 0.72); border-color: #fdba74; }
  .t-pad.drift { background: rgba(168, 85, 247, 0.68); border-color: #d8b4fe; }
  .t-stack { display: flex; flex-direction: column; gap: 10px; }
  .t-row { display: flex; gap: 10px; }

  #toast { position: absolute; top: calc(74px + env(safe-area-inset-top)); left: 50%; transform: translateX(-50%); z-index: 30; pointer-events: none; background: rgba(15, 23, 42, 0.92); border: 1px solid #38bdf8; color: #f8fafc; padding: 8px 18px; border-radius: 999px; font-weight: 800; font-size: 0.78rem; letter-spacing: 0.12em; text-transform: uppercase; opacity: 0; transition: opacity 0.2s ease; white-space: nowrap; }
  #toast.show { opacity: 1; }
</style>
</head>
<body>
<div id="canvas-wrap"></div>
<div id="nitro-vignette"></div>
<div id="damage-flash"></div>
<div id="toast"></div>

<!-- IN-RACE HUD -->
<div id="hud" class="hidden">
  <div class="hud-top">
    <div class="glass hud-card">
      <div class="hud-label">Position & Lap</div>
      <div class="hud-val"><span id="hud-pos">1/4</span> &nbsp;•&nbsp; <span id="hud-lap">LAP 1/3</span></div>
      <div class="hud-sub" id="hud-mode-info">NEON CITY • CAREER</div>
    </div>

    <div class="glass hud-card" style="text-align:center;">
      <div class="hud-label" id="hud-metric-label">Race Time</div>
      <div class="hud-val" id="hud-metric-val">00:00.0</div>
      <div class="hud-sub" id="hud-score-sub">COINS: 0 • STUNTS: 0</div>
    </div>

    <div style="display:flex;gap:8px;align-items:flex-start;pointer-events:auto;">
      <div class="glass hud-card" style="text-align:right;">
        <div class="hud-label">Cash & Rep</div>
        <div class="hud-val" style="color:#fde047;" id="hud-cash">$0</div>
        <div class="hud-sub" id="hud-drift-badge">DRIFT READY</div>
      </div>
      <button class="btn-icon" id="btn-pause">II</button>
    </div>
  </div>

  <div class="hud-bottom">
    <div class="glass meter-box">
      <div style="display:flex;align-items:baseline;">
        <span class="speed-num" id="hud-speed">0</span>
        <span class="speed-unit">KM/H</span>
      </div>
      <div style="display:flex;justify-content:space-between;font-size:0.68rem;font-weight:800;color:#7dd3fc;margin-top:6px;">
        <span>NITRO OVERDRIVE</span>
        <span id="hud-nitro-pct">100%</span>
      </div>
      <div class="bar-track"><div class="bar-fill" id="hud-nitro-bar" style="width:100%;"></div></div>
    </div>

    <div class="glass hud-card" style="text-align:right;max-width:260px;">
      <div class="hud-label">Active Challenge</div>
      <div style="font-size:0.78rem;font-weight:700;color:#e2e8f0;margin-top:2px;" id="hud-daily-txt">Drift for 8s total</div>
    </div>
  </div>
</div>

<!-- TOUCH CONTROLS -->
<div id="touch-layer" class="hidden">
  <div class="touch-group">
    <div class="t-pad" data-ctrl="left">◀ L</div>
    <div class="t-pad" data-ctrl="right">R ▶</div>
  </div>
  <div class="touch-group">
    <div class="t-stack">
      <div class="t-row">
        <div class="t-pad nitro" data-ctrl="nitro">NITRO</div>
        <div class="t-pad drift" data-ctrl="drift">DRIFT</div>
      </div>
      <div class="t-row">
        <div class="t-pad" data-ctrl="brake">BRAKE</div>
        <div class="t-pad" data-ctrl="gas" style="background:rgba(22,163,74,0.72);border-color:#86efac;">GAS</div>
      </div>
    </div>
  </div>
</div>

<!-- MAIN MENU -->
<div id="menu-screen" class="screen">
  <div class="brand-kicker">3D Arcade Motorsport Engine</div>
  <h1 class="game-title">VELOCITY X</h1>
  <div class="game-sub">BEYOND LIMITS</div>

  <div class="menu-grid">
    <button class="menu-btn primary" id="btn-quick-race"><span>Quick Race / Launch</span><span>►</span></button>
    <button class="menu-btn" id="btn-open-race-setup"><span>Modes & Tracks</span><span>8</span></button>
    <button class="menu-btn" id="btn-open-garage"><span>Garage & Tuning</span><span id="menu-cash-badge" style="color:#fde047;">$0</span></button>
    <button class="menu-btn" id="btn-open-challenges"><span>Daily Challenges</span><span>★</span></button>
    <button class="menu-btn" id="btn-open-settings"><span>Settings</span><span>⚙</span></button>
  </div>

  <div style="margin-top:16px;font-size:0.74rem;color:#94a3b8;text-align:center;max-width:640px;">
    Desktop: <strong>W / ↑</strong> Accelerate • <strong>S / ↓</strong> Brake/Reverse • <strong>A/D or ←/→</strong> Steer • <strong>Space</strong> Drift • <strong>Shift / N</strong> Nitro • <strong>R</strong> Respawn
  </div>
</div>

<!-- RACE SETUP (MODES & 8 ENVIRONMENTS) -->
<div id="setup-screen" class="screen hidden">
  <div class="glass panel">
    <div class="panel-head">
      <div class="panel-title">Race Modes & Environments</div>
      <button class="close-btn" data-back="menu-screen">Back</button>
    </div>
    <div class="panel-body">
      <div class="hud-label" style="margin-bottom:8px;">1. Select Game Mode</div>
      <div class="cards-grid" id="modes-grid" style="margin-bottom:18px;"></div>

      <div class="hud-label" style="margin-bottom:8px;">2. Select Environment (8 Worlds)</div>
      <div class="cards-grid" id="envs-grid" style="margin-bottom:18px;"></div>

      <div style="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;">
        <button class="act-btn warn" style="padding:12px 22px;font-size:0.88rem;" id="btn-start-configured">Start Race ►</button>
      </div>
    </div>
  </div>
</div>

<!-- GARAGE (CARS, COLORS, NEON & UPGRADES) -->
<div id="garage-screen" class="screen hidden">
  <div class="glass panel">
    <div class="panel-head">
      <div>
        <div class="panel-title">Velocity Garage</div>
        <div style="font-size:0.8rem;color:#fde047;font-weight:800;">BALANCE: <span id="garage-cash">$0</span> &nbsp;|&nbsp; REP: <span id="garage-rep">0</span></div>
      </div>
      <button class="close-btn" data-back="menu-screen">Back</button>
    </div>
    <div class="panel-body">
      <div class="glass hud-card" style="margin-bottom:14px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;">
        <div>
          <div class="hud-label">Body Paint & UnderGlow Neon</div>
          <div class="swatches" id="paint-swatches"></div>
        </div>
        <div>
          <div class="hud-label">Performance Tuning (All Cars)</div>
          <div style="display:flex;gap:8px;margin-top:6px;flex-wrap:wrap;">
            <button class="act-btn" id="btn-up-engine">Engine Lv.<span id="lv-engine">1</span> ($350)</button>
            <button class="act-btn" id="btn-up-nitro">Nitro Lv.<span id="lv-nitro">1</span> ($300)</button>
            <button class="act-btn" id="btn-up-grip">Handling Lv.<span id="lv-grip">1</span> ($300)</button>
          </div>
        </div>
      </div>

      <div class="cards-grid" id="cars-grid"></div>
    </div>
  </div>
</div>

<!-- DAILY CHALLENGES -->
<div id="challenges-screen" class="screen hidden">
  <div class="glass panel" style="max-width:640px;">
    <div class="panel-head">
      <div class="panel-title">Daily Challenges</div>
      <button class="close-btn" data-back="menu-screen">Back</button>
    </div>
    <div class="panel-body" id="challenges-list"></div>
  </div>
</div>

<!-- SETTINGS -->
<div id="settings-screen" class="screen hidden">
  <div class="glass panel" style="max-width:560px;">
    <div class="panel-head">
      <div class="panel-title">System Settings</div>
      <button class="close-btn" data-back="menu-screen">Back</button>
    </div>
    <div class="panel-body">
      <div class="setting-row"><span>Engine & SFX Volume</span><input type="range" id="set-sfx" min="0" max="1" step="0.05" value="0.65"></div>
      <div class="setting-row"><span>Synth Soundtrack Volume</span><input type="range" id="set-music" min="0" max="1" step="0.05" value="0.35"></div>
      <div class="setting-row"><span>Camera View</span>
        <select id="set-cam"><option value="chase">Dynamic Chase</option><option value="far">Wide Tactical</option><option value="hood">Hood / Bumper</option></select>
      </div>
      <div class="setting-row"><span>Weather / Time Cycle</span>
        <select id="set-cycle"><option value="auto">Dynamic Cycle</option><option value="day">Clear Daylight</option><option value="night">Midnight Neon</option><option value="storm">Storm & Wet</option></select>
      </div>
      <div class="setting-row"><span>Touch Controls</span>
        <select id="set-touch"><option value="auto">Auto (Mobile / Tablet)</option><option value="on">Always Show</option><option value="off">Hide</option></select>
      </div>
      <div class="setting-row"><span>Graphics Quality</span>
        <select id="set-gfx"><option value="high">High (Shadows & Particles)</option><option value="perf">Balanced (Smooth FPS)</option></select>
      </div>
      <div class="setting-row"><span>Reset Save Data</span><button class="close-btn" id="btn-reset-save">Reset Progress</button></div>
    </div>
  </div>
</div>

<!-- PAUSE / RESULTS MODAL -->
<div id="modal-screen" class="screen hidden" style="background:rgba(4,7,14,0.86);z-index:25;">
  <div class="glass panel" style="max-width:500px;text-align:center;">
    <div class="panel-title" id="modal-title" style="margin-bottom:10px;color:#38bdf8;">PAUSED</div>
    <div id="modal-body" style="color:#e2e8f0;font-size:0.92rem;line-height:1.65;margin-bottom:18px;"></div>
    <div id="modal-buttons" style="display:flex;flex-direction:column;gap:10px;"></div>
  </div>
</div>

<script type="module">
import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';

/* ============================================================================
   1. GAME CATALOG, SAVE DATA & DAILY CHALLENGES
   ============================================================================ */
const MODES = [
  { id: 'career', name: 'Career Mode', desc: '3-lap championship race vs 3 AI rivals. Win cash & reputation.' },
  { id: 'quick', name: 'Quick Race', desc: 'Fast 2-lap arcade sprint with ramps, coins, obstacles & AI.' },
  { id: 'time', name: 'Time Attack', desc: 'Beat the target lap time on a clean solo run.' },
  { id: 'drift', name: 'Drift Challenge', desc: 'Rack up high drift combos & nitro overdrive boosts.' },
  { id: 'stunt', name: 'Stunt Challenge', desc: 'Launch off ramps & earn big air/stunt score multipliers.' },
  { id: 'survival', name: 'Survival Mode', desc: 'Survive escalating hazards & push your distance/time score.' }
];

const ENVIRONMENTS = [
  { id: 'neon', name: 'Neon City', sky: 0x090d1f, fog: 0x131b3a, road: 0x141926, stripe: 0x38bdf8, accent: 0xf43f5e, prop: 'tower', wet: true, targetSec: 52 },
  { id: 'ocean', name: 'Ocean Drive', sky: 0x0c4a6e, fog: 0x38bdf8, road: 0x1e293b, stripe: 0xfef08a, accent: 0x06b6d4, prop: 'palm', wet: false, targetSec: 50 },
  { id: 'frozen', name: 'Frozen Peaks', sky: 0x1e3a5f, fog: 0xbae6fd, road: 0x334155, stripe: 0xe0f2fe, accent: 0x7dd3fc, prop: 'pine', wet: true, targetSec: 54 },
  { id: 'desert', name: 'Desert Storm', sky: 0x7c2d12, fog: 0xd97706, road: 0x3f2e21, stripe: 0xfde68a, accent: 0xf59e0b, prop: 'rock', wet: false, targetSec: 51 },
  { id: 'jungle', name: 'Wild Jungle', sky: 0x064e3b, fog: 0x10b981, road: 0x1a2e22, stripe: 0xa7f3d0, accent: 0x22c55e, prop: 'tree', wet: true, targetSec: 53 },
  { id: 'sky', name: 'Sky Circuit', sky: 0x1d4ed8, fog: 0x93c5fd, road: 0x1e293b, stripe: 0xf8fafc, accent: 0x38bdf8, prop: 'pylon', wet: false, targetSec: 49 },
  { id: 'tunnel', name: 'Dark Tunnel', sky: 0x05070c, fog: 0x0f172a, road: 0x111827, stripe: 0xf97316, accent: 0xf97316, prop: 'arch', wet: true, targetSec: 48 },
  { id: 'inferno', name: 'Inferno Island', sky: 0x2a0808, fog: 0x7f1d1d, road: 0x1c1414, stripe: 0xfb7185, accent: 0xef4444, prop: 'volcano', wet: true, targetSec: 52 }
];

const CARS = [
  { id: 'apex', name: 'Apex GT-R', cls: 'Street Tuner', price: 0, topSpeed: 225, accel: 118, grip: 1.0, nitroCap: 100, color: 0x38bdf8 },
  { id: 'vortex', name: 'Vortex Spyder', cls: 'Track Roadster', price: 650, topSpeed: 242, accel: 132, grip: 1.08, nitroCap: 110, color: 0x22c55e },
  { id: 'valkyrie', name: 'Valkyrie V8', cls: 'Muscle Interceptor', price: 1300, topSpeed: 258, accel: 146, grip: 1.04, nitroCap: 120, color: 0xf97316 },
  { id: 'phantom', name: 'Phantom RS', cls: 'Aero Coupe', price: 2100, topSpeed: 274, accel: 158, grip: 1.14, nitroCap: 130, color: 0xa855f7 },
  { id: 'titan', name: 'Titan X9', cls: 'Apex Hypercar', price: 3200, topSpeed: 292, accel: 172, grip: 1.18, nitroCap: 145, color: 0xef4444 },
  { id: 'omega', name: 'Omega Wraith', cls: 'Prototype Overdrive', price: 4500, topSpeed: 312, accel: 188, grip: 1.24, nitroCap: 160, color: 0xfacc15 }
];

const PAINTS = [0x38bdf8, 0xef4444, 0x22c55e, 0xf97316, 0xa855f7, 0xfacc15, 0xec4899, 0xf8fafc];

const DEFAULT_SAVE = {
  cash: 500,
  rep: 0,
  unlockedCars: ['apex'],
  selectedCar: 'apex',
  paint: 0x38bdf8,
  upgrades: { engine: 1, nitro: 1, grip: 1 },
  selectedMode: 'career',
  selectedEnv: 'neon',
  bestTimes: {},
  challengeDate: new Date().toISOString().slice(0, 10),
  challenges: [
    { id: 'drift', text: 'Accumulate 1,500 Drift Points', target: 1500, progress: 0, reward: 350, claimed: false },
    { id: 'coins', text: 'Collect 25 Coins across races', target: 25, progress: 0, reward: 300, claimed: false },
    { id: 'stunts', text: 'Perform 5 Ramp Stunt Jumps', target: 5, progress: 0, reward: 400, claimed: false }
  ],
  settings: { sfx: 0.65, music: 0.35, cam: 'chase', cycle: 'auto', touch: 'auto', gfx: 'high' }
};

let Save = loadSave();
function loadSave() {
  try {
    const raw = localStorage.getItem('velocity_x_save_v1');
    if (!raw) return structuredClone(DEFAULT_SAVE);
    const parsed = JSON.parse(raw);
    const merged = { ...structuredClone(DEFAULT_SAVE), ...parsed, upgrades: { ...DEFAULT_SAVE.upgrades, ...(parsed.upgrades || {}) }, settings: { ...DEFAULT_SAVE.settings, ...(parsed.settings || {}) } };
    const today = new Date().toISOString().slice(0, 10);
    if (merged.challengeDate !== today) {
      merged.challengeDate = today;
      merged.challenges = structuredClone(DEFAULT_SAVE.challenges);
    }
    return merged;
  } catch {
    return structuredClone(DEFAULT_SAVE);
  }
}
function persistSave() {
  try { localStorage.setItem('velocity_x_save_v1', JSON.stringify(Save)); } catch {}
}

function showToast(msg) {
  const el = document.getElementById('toast');
  el.textContent = msg;
  el.classList.add('show');
  clearTimeout(showToast._t);
  showToast._t = setTimeout(() => el.classList.remove('show'), 2100);
}

/* ============================================================================
   2. PROCEDURAL WEB AUDIO ENGINE (ENGINE, TURBO, DRIFT, NITRO, COLLISION, MUSIC)
   ============================================================================ */
const Sound = (() => {
  let ctx = null, engOsc1 = null, engOsc2 = null, engGain = null, driftNoise = null, driftGain = null, musicTimer = null, step = 0;

  function unlock() {
    if (!ctx) {
      const AC = window.AudioContext || window.webkitAudioContext;
      if (!AC) return;
      ctx = new AC();
      // Continuous dual-oscillator engine note
      engOsc1 = ctx.createOscillator();
      engOsc2 = ctx.createOscillator();
      const filter = ctx.createBiquadFilter();
      engGain = ctx.createGain();
      engOsc1.type = 'sawtooth';
      engOsc2.type = 'triangle';
      filter.type = 'lowpass';
      filter.frequency.value = 520;
      engGain.gain.value = 0.0001;
      engOsc1.connect(filter);
      engOsc2.connect(filter);
      filter.connect(engGain);
      engGain.connect(ctx.destination);
      engOsc1.start();
      engOsc2.start();

      // Continuous tire screech / drift filtered noise
      const buf = ctx.createBuffer(1, ctx.sampleRate * 1.5, ctx.sampleRate);
      const data = buf.getChannelData(0);
      for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
      driftNoise = ctx.createBufferSource();
      driftNoise.buffer = buf;
      driftNoise.loop = true;
      const bp = ctx.createBiquadFilter();
      bp.type = 'bandpass';
      bp.frequency.value = 1850;
      bp.Q.value = 4.5;
      driftGain = ctx.createGain();
      driftGain.gain.value = 0.0001;
      driftNoise.connect(bp);
      bp.connect(driftGain);
      driftGain.connect(ctx.destination);
      driftNoise.start();

      startMusicLoop();
    }
    if (ctx && ctx.state === 'suspended') ctx.resume().catch(() => {});
  }

  function updateContinuous(speedRatio, isDrifting, isNitro, active) {
    if (!ctx || !engGain) return;
    const sfxVol = Save.settings.sfx;
    if (!active || sfxVol <= 0) {
      engGain.gain.setTargetAtTime(0.0001, ctx.currentTime, 0.08);
      driftGain.gain.setTargetAtTime(0.0001, ctx.currentTime, 0.06);
      return;
    }
    const baseFreq = 54 + speedRatio * 145 + (isNitro ? 38 : 0);
    engOsc1.frequency.setTargetAtTime(baseFreq, ctx.currentTime, 0.05);
    engOsc2.frequency.setTargetAtTime(baseFreq * 1.5, ctx.currentTime, 0.05);
    engGain.gain.setTargetAtTime((0.035 + speedRatio * 0.06) * sfxVol, ctx.currentTime, 0.06);

    const screech = isDrifting && speedRatio > 0.25 ? 0.06 * sfxVol : 0.0001;
    driftGain.gain.setTargetAtTime(screech, ctx.currentTime, 0.05);
  }

  function oneShot(freq, type, dur, vol, slide = 0) {
    unlock();
    if (!ctx || Save.settings.sfx <= 0) return;
    const osc = ctx.createOscillator();
    const g = ctx.createGain();
    osc.type = type;
    osc.frequency.setValueAtTime(freq, ctx.currentTime);
    if (slide) osc.frequency.exponentialRampToValueAtTime(Math.max(25, freq + slide), ctx.currentTime + dur);
    g.gain.setValueAtTime(vol * Save.settings.sfx, ctx.currentTime);
    g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + dur);
    osc.connect(g);
    g.connect(ctx.destination);
    osc.start();
    osc.stop(ctx.currentTime + dur);
  }

  function startMusicLoop() {
    if (musicTimer) clearInterval(musicTimer);
    const notes = [110, 110, 130.81, 146.83, 164.81, 146.83, 130.81, 98];
    musicTimer = setInterval(() => {
      if (!ctx || Save.settings.music <= 0) return;
      const n = notes[step % notes.length];
      const osc = ctx.createOscillator();
      const g = ctx.createGain();
      osc.type = 'triangle';
      osc.frequency.setValueAtTime(n, ctx.currentTime);
      g.gain.setValueAtTime(0.045 * Save.settings.music, ctx.currentTime);
      g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.18);
      osc.connect(g);
      g.connect(ctx.destination);
      osc.start();
      osc.stop(ctx.currentTime + 0.19);
      step++;
    }, 175);
  }

  return {
    unlock,
    updateContinuous,
    coin: () => oneShot(980, 'sine', 0.14, 0.22, 320),
    boost: () => oneShot(220, 'sawtooth', 0.28, 0.25, 440),
    crash: () => oneShot(115, 'sawtooth', 0.24, 0.35, -80),
    jump: () => oneShot(280, 'triangle', 0.22, 0.22, 180),
    ui: () => oneShot(620, 'sine', 0.08, 0.15, 120)
  };
})();

/* ============================================================================
   3. PROCEDURAL PBR-STYLE CANVAS TEXTURES & 3D CAR / TRACK BUILDER
   ============================================================================ */
function makeAsphaltTexture(stripeHex, wet) {
  const c = document.createElement('canvas');
  c.width = 512;
  c.height = 512;
  const g = c.getContext('2d');
  g.fillStyle = wet ? '#0e1522' : '#1b2230';
  g.fillRect(0, 0, 512, 512);

  // Asphalt grain noise
  for (let i = 0; i < 4500; i++) {
    const x = Math.random() * 512;
    const y = Math.random() * 512;
    const v = 22 + Math.floor(Math.random() * 28);
    g.fillStyle = `rgb(${v},${v + 3},${v + 8})`;
    g.fillRect(x, y, 2, 2);
  }

  // Edge rumble curbs
  const hex = '#' + stripeHex.toString(16).padStart(6, '0');
  g.fillStyle = hex;
  g.fillRect(14, 0, 12, 512);
  g.fillRect(486, 0, 12, 512);

  // Center dashed lane line
  g.fillStyle = 'rgba(248, 250, 252, 0.72)';
  for (let y = 16; y < 512; y += 64) {
    g.fillRect(251, y, 10, 34);
  }

  const tex = new THREE.CanvasTexture(c);
  tex.wrapS = THREE.RepeatWrapping;
  tex.wrapT = THREE.RepeatWrapping;
  tex.repeat.set(1, 36);
  tex.colorSpace = THREE.SRGBColorSpace;
  return tex;
}

function buildSportsCar(bodyColor, neonColor, isPlayer = false) {
  const root = new THREE.Group();

  const bodyMat = new THREE.MeshStandardMaterial({
    color: bodyColor,
    metalness: 0.72,
    roughness: 0.24
  });
  const cabinMat = new THREE.MeshStandardMaterial({
    color: 0x090d16,
    metalness: 0.9,
    roughness: 0.12
  });
  const trimMat = new THREE.MeshStandardMaterial({
    color: 0x111827,
    metalness: 0.5,
    roughness: 0.55
  });
  const neonMat = new THREE.MeshBasicMaterial({ color: neonColor });
  const headlightMat = new THREE.MeshBasicMaterial({ color: 0xe0f2fe });
  const taillightMat = new THREE.MeshBasicMaterial({ color: 0xff1e42 });

  // Lower chassis & sculpted hood
  const lower = new THREE.Mesh(new THREE.BoxGeometry(2.05, 0.52, 4.3), bodyMat);
  lower.position.set(0, 0.52, 0);
  lower.castShadow = true;
  lower.receiveShadow = true;
  root.add(lower);

  // Sloped cabin / greenhouse
  const cabin = new THREE.Mesh(new THREE.BoxGeometry(1.66, 0.48, 2.05), cabinMat);
  cabin.position.set(0, 0.98, -0.18);
  cabin.castShadow = true;
  root.add(cabin);

  // Front splitter & rear diffuser
  const splitter = new THREE.Mesh(new THREE.BoxGeometry(2.12, 0.12, 0.45), trimMat);
  splitter.position.set(0, 0.28, 2.05);
  root.add(splitter);

  // Rear GT spoiler wing
  const wingStanchionL = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.36, 0.22), trimMat);
  wingStanchionL.position.set(-0.62, 0.92, -1.85);
  const wingStanchionR = wingStanchionL.clone();
  wingStanchionR.position.x = 0.62;
  const wingBlade = new THREE.Mesh(new THREE.BoxGeometry(2.16, 0.08, 0.38), bodyMat);
  wingBlade.position.set(0, 1.12, -1.9);
  wingBlade.castShadow = true;
  root.add(wingStanchionL, wingStanchionR, wingBlade);

  // Under-glow neon strips
  const glowL = new THREE.Mesh(new THREE.BoxGeometry(0.08, 0.06, 3.4), neonMat);
  glowL.position.set(-1.04, 0.22, 0);
  const glowR = glowL.clone();
  glowR.position.x = 1.04;
  root.add(glowL, glowR);

  // Headlights & taillights
  [-0.72, 0.72].forEach(x => {
    const hl = new THREE.Mesh(new THREE.BoxGeometry(0.36, 0.14, 0.08), headlightMat);
    hl.position.set(x, 0.62, 2.16);
    const tl = new THREE.Mesh(new THREE.BoxGeometry(0.42, 0.14, 0.08), taillightMat);
    tl.position.set(x, 0.68, -2.16);
    root.add(hl, tl);
  });

  // Wheels
  const wheelGeo = new THREE.CylinderGeometry(0.42, 0.42, 0.34, 18);
  wheelGeo.rotateZ(Math.PI / 2);
  const tireMat = new THREE.MeshStandardMaterial({ color: 0x0f172a, roughness: 0.85, metalness: 0.1 });
  const rimMat = new THREE.MeshStandardMaterial({ color: 0xcbd5e1, metalness: 0.85, roughness: 0.25 });

  const wheels = [];
  const wheelCoords = [
    [-1.06, 0.42, 1.32],
    [1.06, 0.42, 1.32],
    [-1.08, 0.42, -1.32],
    [1.08, 0.42, -1.32]
  ];
  wheelCoords.forEach(([wx, wy, wz]) => {
    const wg = new THREE.Group();
    wg.position.set(wx, wy, wz);
    const tire = new THREE.Mesh(wheelGeo, tireMat);
    tire.castShadow = true;
    const rim = new THREE.Mesh(new THREE.CylinderGeometry(0.24, 0.24, 0.36, 12).rotateZ(Math.PI / 2), rimMat);
    wg.add(tire, rim);
    root.add(wg);
    wheels.push(wg);
  });

  // Twin Nitro Exhaust Flames
  const flameGeo = new THREE.ConeGeometry(0.18, 1.25, 10);
  flameGeo.rotateX(-Math.PI / 2);
  const flameMat = new THREE.MeshBasicMaterial({ color: 0x38bdf8, transparent: true, opacity: 0.9 });
  const flames = [];
  [-0.45, 0.45].forEach(fx => {
    const fl = new THREE.Mesh(flameGeo, flameMat);
    fl.position.set(fx, 0.45, -2.75);
    fl.visible = false;
    root.add(fl);
    flames.push(fl);
  });

  let spotLight = null;
  if (isPlayer) {
    spotLight = new THREE.SpotLight(0xe0f2fe, 14, 55, Math.PI / 5, 0.45, 1.2);
    spotLight.position.set(0, 1.1, 1.8);
    const targetObj = new THREE.Object3D();
    targetObj.position.set(0, 0.2, 24);
    root.add(targetObj);
    spotLight.target = targetObj;
    root.add(spotLight);
  }

  return { root, wheels, flames, spotLight, bodyMat, glowL, glowR };
}

/* ============================================================================
   4. THREE.JS WORLD & GAME LOOP
   ============================================================================ */
const container = document.getElementById('canvas-wrap');
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, Save.settings.gfx === 'high' ? 2 : 1.5));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = Save.settings.gfx === 'high';
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
container.appendChild(renderer.domElement);

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(62, window.innerWidth / window.innerHeight, 0.2, 320);

const hemiLight = new THREE.HemisphereLight(0x93c5fd, 0x1e293b, 1.1);
scene.add(hemiLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 2.1);
dirLight.position.set(28, 45, 22);
dirLight.castShadow = true;
dirLight.shadow.mapSize.set(1024, 1024);
scene.add(dirLight);

const TRACK_LENGTH = 720;
const ROAD_WIDTH = 22;
let roadMesh = null, trackGroup = new THREE.Group();
scene.add(trackGroup);

let playerCar = null;
let aiCars = [];
let coins = [];
let obstacles = [];
let ramps = [];
let particles = [];

const State = {
  phase: 'menu', // menu | racing | paused | finished
  speed: 0,      // km/h scaled
  zPos: 0,
  xPos: 0,
  yPos: 0,
  vy: 0,
  steerAngle: 0,
  driftCharge: 0,
  driftScore: 0,
  stuntScore: 0,
  coinsCollected: 0,
  nitro: 100,
  isDrifting: false,
  isNitro: false,
  lap: 1,
  maxLaps: 3,
  raceTime: 0,
  survivalDistance: 0,
  cycleClock: 0,
  shake: 0
};

function clearTrackGroup() {
  while (trackGroup.children.length > 0) {
    trackGroup.remove(trackGroup.children[0]);
  }
  coins = [];
  obstacles = [];
  ramps = [];
  aiCars = [];
  particles = [];
}

function buildEnvironmentAndTrack(envId, modeId) {
  clearTrackGroup();
  const env = ENVIRONMENTS.find(e => e.id === envId) || ENVIRONMENTS[0];
  scene.background = new THREE.Color(env.sky);
  scene.fog = new THREE.FogExp2(env.fog, envId === 'tunnel' ? 0.016 : 0.0055);

  const roadTex = makeAsphaltTexture(env.stripe, env.wet);
  const roadMat = new THREE.MeshStandardMaterial({
    map: roadTex,
    roughness: env.wet ? 0.16 : 0.65,
    metalness: env.wet ? 0.45 : 0.12
  });
  roadMesh = new THREE.Mesh(new THREE.PlaneGeometry(ROAD_WIDTH, TRACK_LENGTH), roadMat);
  roadMesh.rotation.x = -Math.PI / 2;
  roadMesh.position.set(0, 0, TRACK_LENGTH / 2 - 20);
  roadMesh.receiveShadow = true;
  trackGroup.add(roadMesh);

  // Side barriers & scenery props
  const barrierMat = new THREE.MeshStandardMaterial({ color: 0x334155, roughness: 0.5, metalness: 0.4 });
  const propMat = new THREE.MeshStandardMaterial({ color: env.accent, roughness: 0.45, metalness: 0.35 });
  const darkPropMat = new THREE.MeshStandardMaterial({ color: 0x0f172a, roughness: 0.7 });

  for (let z = 10; z < TRACK_LENGTH - 20; z += 26) {
    [-ROAD_WIDTH / 2 - 0.6, ROAD_WIDTH / 2 + 0.6].forEach(bx => {
      const post = new THREE.Mesh(new THREE.BoxGeometry(0.6, 1.1, 22), barrierMat);
      post.position.set(bx, 0.55, z);
      trackGroup.add(post);
    });

    [-16, 16].forEach((sx, idx) => {
      const h = 10 + ((z * 13 + idx * 19) % 28);
      const mesh = new THREE.Mesh(
        env.prop === 'pine' || env.prop === 'tree'
          ? new THREE.ConeGeometry(3.4, h * 0.65, 7)
          : new THREE.BoxGeometry(5.5, h, 5.5),
        idx % 2 === 0 ? darkPropMat : propMat
      );
      mesh.position.set(sx + (idx === 0 ? -4 : 4), h / 2, z);
      trackGroup.add(mesh);
    });
  }

  // Ramps
  const rampMat = new THREE.MeshStandardMaterial({ color: 0xf97316, emissive: 0x7c2d12, roughness: 0.35 });
  for (let z = 110; z < TRACK_LENGTH - 90; z += 165) {
    const rx = ((z / 165) % 2 === 0) ? -4.5 : 4.5;
    const ramp = new THREE.Mesh(new THREE.BoxGeometry(5.5, 0.9, 9), rampMat);
    ramp.position.set(rx, 0.45, z);
    ramp.rotation.x = -0.11;
    trackGroup.add(ramp);
    ramps.push({ x: rx, z, w: 5.5, l: 9 });
  }

  // Coins
  const coinGeo = new THREE.TorusGeometry(0.65, 0.2, 10, 20);
  const coinMat = new THREE.MeshStandardMaterial({ color: 0xfacc15, emissive: 0x854d0e, metalness: 0.85, roughness: 0.2 });
  for (let z = 55; z < TRACK_LENGTH - 50; z += 36) {
    const cx = Math.sin(z * 0.04) * 6.5;
    const cMesh = new THREE.Mesh(coinGeo, coinMat);
    cMesh.position.set(cx, 1.35, z);
    trackGroup.add(cMesh);
    coins.push({ mesh: cMesh, x: cx, z, taken: false });
  }

  // Obstacles (barricades / cones)
  const obsMat = new THREE.MeshStandardMaterial({ color: 0xef4444, roughness: 0.45 });
  const step = modeId === 'survival' ? 38 : 68;
  for (let z = 85; z < TRACK_LENGTH - 70; z += step) {
    const ox = Math.cos(z * 0.03) * 6.8;
    const obs = new THREE.Mesh(new THREE.BoxGeometry(2.6, 1.2, 1.3), obsMat);
    obs.position.set(ox, 0.6, z);
    obs.castShadow = true;
    trackGroup.add(obs);
    obstacles.push({ mesh: obs, x: ox, z, hit: false });
  }

  // Player Car
  const carSpec = CARS.find(c => c.id === Save.selectedCar) || CARS[0];
  playerCar = buildSportsCar(Save.paint, Save.paint, true);
  playerCar.root.position.set(0, 0, 0);
  trackGroup.add(playerCar.root);

  // AI Rivals in Career / Quick / Drift / Stunt
  if (modeId !== 'time' && modeId !== 'survival') {
    const rivalColors = [0xf43f5e, 0xa855f7, 0x22c55e];
    const lanes = [-5.2, 0, 5.2];
    for (let i = 0; i < 3; i++) {
      const ai = buildSportsCar(rivalColors[i], rivalColors[i], false);
      const startZ = 18 + i * 14;
      ai.root.position.set(lanes[i], 0, startZ);
      trackGroup.add(ai.root);
      aiCars.push({
        model: ai,
        x: lanes[i],
        z: startZ,
        lap: 1,
        baseSpeed: 165 + i * 14 + Math.random() * 10
      });
    }
  }
}

/* ============================================================================
   5. INPUT HANDLING (KEYBOARD + MOBILE TOUCH)
   ============================================================================ */
const Keys = { up: false, down: false, left: false, right: false, drift: false, nitro: false };

window.addEventListener('keydown', e => {
  Sound.unlock();
  const k = e.key.toLowerCase();
  if (k === 'w' || k === 'arrowup') Keys.up = true;
  if (k === 's' || k === 'arrowdown') Keys.down = true;
  if (k === 'a' || k === 'arrowleft') Keys.left = true;
  if (k === 'd' || k === 'arrowright') Keys.right = true;
  if (k === ' ') Keys.drift = true;
  if (k === 'shift' || k === 'n') Keys.nitro = true;
  if (k === 'r' && State.phase === 'racing') respawnCar();
  if (k === 'escape' && State.phase === 'racing') togglePause();
});

window.addEventListener('keyup', e => {
  const k = e.key.toLowerCase();
  if (k === 'w' || k === 'arrowup') Keys.up = false;
  if (k === 's' || k === 'arrowdown') Keys.down = false;
  if (k === 'a' || k === 'arrowleft') Keys.left = false;
  if (k === 'd' || k === 'arrowright') Keys.right = false;
  if (k === ' ') Keys.drift = false;
  if (k === 'shift' || k === 'n') Keys.nitro = false;
});

document.querySelectorAll('.t-pad').forEach(btn => {
  const ctrl = btn.dataset.ctrl;
  const onDown = e => {
    e.preventDefault();
    Sound.unlock();
    btn.classList.add('pressed');
    if (ctrl === 'left') Keys.left = true;
    if (ctrl === 'right') Keys.right = true;
    if (ctrl === 'gas') Keys.up = true;
    if (ctrl === 'brake') Keys.down = true;
    if (ctrl === 'drift') Keys.drift = true;
    if (ctrl === 'nitro') Keys.nitro = true;
  };
  const onUp = e => {
    e.preventDefault();
    btn.classList.remove('pressed');
    if (ctrl === 'left') Keys.left = false;
    if (ctrl === 'right') Keys.right = false;
    if (ctrl === 'gas') Keys.up = false;
    if (ctrl === 'brake') Keys.down = false;
    if (ctrl === 'drift') Keys.drift = false;
    if (ctrl === 'nitro') Keys.nitro = false;
  };
  btn.addEventListener('touchstart', onDown, { passive: false });
  btn.addEventListener('touchend', onUp, { passive: false });
  btn.addEventListener('touchcancel', onUp, { passive: false });
  btn.addEventListener('mousedown', onDown);
  btn.addEventListener('mouseup', onUp);
  btn.addEventListener('mouseleave', onUp);
});

function respawnCar() {
  State.xPos = 0;
  State.yPos = 0;
  State.vy = 0;
  State.speed = Math.max(40, State.speed * 0.45);
  showToast('Car Reset to Center Lane');
}

/* ============================================================================
   6. SIMULATION, WEATHER / DAY-NIGHT & HUD UPDATE
   ============================================================================ */
function startRace() {
  Sound.unlock();
  const mode = MODES.find(m => m.id === Save.selectedMode) || MODES[0];
  const env = ENVIRONMENTS.find(e => e.id === Save.selectedEnv) || ENVIRONMENTS[0];

  buildEnvironmentAndTrack(env.id, mode.id);

  State.phase = 'racing';
  State.speed = 0;
  State.zPos = 0;
  State.xPos = 0;
  State.yPos = 0;
  State.vy = 0;
  State.steerAngle = 0;
  State.driftCharge = 0;
  State.driftScore = 0;
  State.stuntScore = 0;
  State.coinsCollected = 0;
  State.nitro = 100;
  State.isDrifting = false;
  State.isNitro = false;
  State.lap = 1;
  State.maxLaps = mode.id === 'career' ? 3 : (mode.id === 'quick' ? 2 : 1);
  State.raceTime = 0;
  State.survivalDistance = 0;
  State.shake = 0;

  hideAllScreens();
  document.getElementById('hud').classList.remove('hidden');
  updateTouchVisibility();
  showToast(`${env.name} • ${mode.name}`);
}

function updateCycleLighting(dt) {
  State.cycleClock += dt * 0.08;
  const modePref = Save.settings.cycle;
  let daylightFactor = 0.5 + 0.5 * Math.sin(State.cycleClock);
  if (modePref === 'day') daylightFactor = 1;
  else if (modePref === 'night') daylightFactor = 0.08;
  else if (modePref === 'storm') daylightFactor = 0.35;

  hemiLight.intensity = 0.45 + daylightFactor * 1.05;
  dirLight.intensity = 0.5 + daylightFactor * 2.1;
  if (playerCar && playerCar.spotLight) {
    playerCar.spotLight.intensity = daylightFactor < 0.45 ? 24 : 8;
  }
}

function stepSimulation(dt) {
  updateCycleLighting(dt);

  const carSpec = CARS.find(c => c.id === Save.selectedCar) || CARS[0];
  const engMult = 1 + (Save.upgrades.engine - 1) * 0.08;
  const nitroMult = 1 + (Save.upgrades.nitro - 1) * 0.1;
  const gripMult = 1 + (Save.upgrades.grip - 1) * 0.08;

  const maxKmh = carSpec.topSpeed * engMult;
  const accelRate = carSpec.accel * engMult;

  const wantsNitro = Keys.nitro && State.nitro > 2 && State.speed > 35;
  State.isNitro = wantsNitro;
  if (wantsNitro) {
    State.nitro = Math.max(0, State.nitro - 28 * dt / nitroMult);
  } else {
    State.nitro = Math.min(100, State.nitro + (State.isDrifting ? 18 : 7) * dt);
  }

  const boostMult = State.isNitro ? 1.32 : 1.0;
  if (Keys.up) {
    State.speed = Math.min(maxKmh * boostMult, State.speed + accelRate * boostMult * dt);
  } else if (Keys.down) {
    State.speed = Math.max(-45, State.speed - accelRate * 1.45 * dt);
  } else {
    State.speed *= Math.pow(0.45, dt);
    if (Math.abs(State.speed) < 1.5) State.speed = 0;
  }

  const steerInput = (Keys.right ? 1 : 0) - (Keys.left ? 1 : 0);
  State.isDrifting = Keys.drift && Math.abs(steerInput) > 0 && State.speed > 75 && State.yPos <= 0.05;
  const turnRate = (State.isDrifting ? 9.5 : 7.2) * gripMult;
  const targetSteer = steerInput * turnRate * (State.speed >= 0 ? 1 : -1);
  State.steerAngle += (targetSteer - State.steerAngle) * Math.min(1, dt * 11);

  const halfRoad = ROAD_WIDTH / 2 - 1.4;
  State.xPos += State.steerAngle * dt;
  if (State.xPos < -halfRoad) {
    State.xPos = -halfRoad;
    State.speed *= 0.88;
  } else if (State.xPos > halfRoad) {
    State.xPos = halfRoad;
    State.speed *= 0.88;
  }

  // Vertical / Ramp physics
  if (State.yPos > 0 || State.vy > 0) {
    State.yPos += State.vy * dt;
    State.vy -= 26 * dt;
    if (State.yPos <= 0) {
      State.yPos = 0;
      State.vy = 0;
      const landedBonus = Math.round(State.speed * 1.5);
      State.stuntScore += landedBonus;
      updateChallengeProgress('stunts', 1);
      showToast(`Stunt Landing +${landedBonus}`);
    }
  }

  // Forward motion (m/s scaled from km/h)
  const mps = (State.speed / 3.6) * 0.42;
  State.zPos += mps * dt;
  State.raceTime += dt;
  State.survivalDistance += mps * dt;

  // Drift scoring
  if (State.isDrifting) {
    State.driftCharge += dt * 360;
    const pts = Math.round(dt * 420);
    State.driftScore += pts;
    updateChallengeProgress('drift', pts);
  } else if (State.driftCharge > 180) {
    State.nitro = Math.min(100, State.nitro + 12);
    State.driftCharge = 0;
  } else {
    State.driftCharge = 0;
  }

  // Update Player 3D Mesh
  playerCar.root.position.set(State.xPos, State.yPos, State.zPos);
  playerCar.root.rotation.y = -State.steerAngle * 0.045 + (State.isDrifting ? steerInput * 0.16 : 0);
  playerCar.root.rotation.z = -State.steerAngle * 0.025;
  playerCar.flames.forEach(fl => {
    fl.visible = State.isNitro;
    if (State.isNitro) fl.scale.z = 0.8 + Math.random() * 0.6;
  });
  playerCar.wheels.forEach((w, idx) => {
    w.children[0].rotation.x += mps * dt * 1.8;
    if (idx < 2) w.rotation.y = -steerInput * 0.35;
  });

  // Ramps check
  for (const r of ramps) {
    if (State.yPos <= 0.05 && Math.abs(State.zPos - r.z) < r.l * 0.55 && Math.abs(State.xPos - r.x) < r.w * 0.6) {
      State.vy = Math.max(9.5, (State.speed / 220) * 13.5);
      State.yPos = 0.12;
      Sound.jump();
    }
  }

  // Coins check
  for (const c of coins) {
    c.mesh.rotation.y += dt * 3.2;
    if (!c.taken && Math.hypot(State.xPos - c.x, State.zPos - c.z) < 2.2 && State.yPos < 3.2) {
      c.taken = true;
      c.mesh.visible = false;
      State.coinsCollected++;
      Save.cash += 25;
      updateChallengeProgress('coins', 1);
      Sound.coin();
    }
  }

  // Obstacles check
  for (const o of obstacles) {
    if (!o.hit && Math.abs(State.zPos - o.z) < 1.8 && Math.abs(State.xPos - o.x) < 2.1 && State.yPos < 1.3) {
      o.hit = true;
      State.speed *= 0.58;
      State.shake = 0.45;
      flashDamage();
      Sound.crash();
    }
  }

  // AI Rivals update
  for (const ai of aiCars) {
    ai.z += (ai.baseSpeed / 3.6) * 0.42 * dt;
    ai.x += Math.sin(State.raceTime * 1.4 + ai.baseSpeed) * 2.2 * dt;
    if (ai.z >= TRACK_LENGTH) {
      ai.z -= TRACK_LENGTH;
      ai.lap++;
    }
    ai.model.root.position.set(ai.x, 0, ai.z);
  }

  // Lap & Track Completion
  if (State.zPos >= TRACK_LENGTH) {
    State.zPos -= TRACK_LENGTH;
    for (const c of coins) { c.taken = false; c.mesh.visible = true; }
    for (const o of obstacles) { o.hit = false; }

    if (Save.selectedMode === 'survival') {
      State.lap++;
      showToast(`Sector ${State.lap} Reached!`);
    } else if (State.lap < State.maxLaps) {
      State.lap++;
      showToast(`Lap ${State.lap} / ${State.maxLaps}`);
    } else {
      finishRace();
      return;
    }
  }

  // Camera follow
  const camMode = Save.settings.cam;
  const shakeX = State.shake > 0 ? (Math.random() - 0.5) * State.shake : 0;
  const shakeY = State.shake > 0 ? (Math.random() - 0.5) * State.shake : 0;
  State.shake = Math.max(0, State.shake - dt * 1.8);

  if (camMode === 'hood') {
    camera.position.set(State.xPos + shakeX, State.yPos + 1.15 + shakeY, State.zPos + 0.6);
    camera.lookAt(State.xPos, State.yPos + 1.0, State.zPos + 22);
  } else {
    const distBack = camMode === 'far' ? 11.5 : 8.2;
    const heightUp = camMode === 'far' ? 5.6 : 3.8;
    const targetCamX = State.xPos * 0.85 + shakeX;
    camera.position.x += (targetCamX - camera.position.x) * Math.min(1, dt * 9);
    camera.position.y = State.yPos + heightUp + shakeY;
    camera.position.z = State.zPos - distBack;
    camera.lookAt(State.xPos * 0.9, State.yPos + 1.1, State.zPos + 16);
  }

  document.getElementById('nitro-vignette').style.opacity = State.isNitro ? '1' : '0';
  Sound.updateContinuous(Math.abs(State.speed) / maxKmh, State.isDrifting, State.isNitro, true);
  updateHUD();
}

function flashDamage() {
  const el = document.getElementById('damage-flash');
  el.style.opacity = '1';
  setTimeout(() => { el.style.opacity = '0'; }, 160);
}

function updateChallengeProgress(type, amount) {
  let changed = false;
  for (const ch of Save.challenges) {
    if (ch.id === type && !ch.claimed && ch.progress < ch.target) {
      ch.progress = Math.min(ch.target, ch.progress + amount);
      changed = true;
    }
  }
  if (changed) persistSave();
}

function computePosition() {
  if (!aiCars.length) return '1/1';
  const playerTotal = State.lap * TRACK_LENGTH + State.zPos;
  let rank = 1;
  for (const ai of aiCars) {
    if (ai.lap * TRACK_LENGTH + ai.z > playerTotal) rank++;
  }
  return `${rank}/${aiCars.length + 1}`;
}

function updateHUD() {
  const mode = MODES.find(m => m.id === Save.selectedMode) || MODES[0];
  const env = ENVIRONMENTS.find(e => e.id === Save.selectedEnv) || ENVIRONMENTS[0];
  document.getElementById('hud-pos').textContent = computePosition();
  document.getElementById('hud-lap').textContent = Save.selectedMode === 'survival' ? `SEC ${State.lap}` : `LAP ${State.lap}/${State.maxLaps}`;
  document.getElementById('hud-mode-info').textContent = `${env.name.toUpperCase()} • ${mode.name.toUpperCase()}`;
  document.getElementById('hud-metric-val').textContent = formatTime(State.raceTime);
  document.getElementById('hud-score-sub').textContent = `COINS: ${State.coinsCollected} • DRIFT: ${State.driftScore} • STUNT: ${State.stuntScore}`;
  document.getElementById('hud-cash').textContent = `$${Save.cash}`;
  document.getElementById('hud-drift-badge').textContent = State.isDrifting ? 'DRIFTING +NITRO' : (State.isNitro ? 'NITRO OVERDRIVE' : 'READY');
  document.getElementById('hud-speed').textContent = Math.round(Math.abs(State.speed));
  document.getElementById('hud-nitro-pct').textContent = `${Math.round(State.nitro)}%`;
  document.getElementById('hud-nitro-bar').style.width = `${State.nitro}%`;

  const activeCh = Save.challenges.find(c => !c.claimed) || Save.challenges[0];
  document.getElementById('hud-daily-txt').textContent = `${activeCh.text} (${activeCh.progress}/${activeCh.target})`;
}

function formatTime(sec) {
  const mins = Math.floor(sec / 60);
  const rem = sec % 60;
  return `${String(mins).padStart(2, '0')}:${rem.toFixed(1).padStart(4, '0')}`;
}

function finishRace() {
  State.phase = 'finished';
  Sound.updateContinuous(0, false, false, false);
  const posNum = parseInt(computePosition().split('/')[0], 10) || 1;
  const posBonus = posNum === 1 ? 450 : (posNum === 2 ? 250 : 120);
  const earned = 150 + posBonus + State.coinsCollected * 25 + Math.round(State.driftScore * 0.1) + Math.round(State.stuntScore * 0.08);
  Save.cash += earned;
  Save.rep += posNum === 1 ? 100 : 50;

  if (Save.selectedMode === 'time') {
    const prev = Save.bestTimes[Save.selectedEnv];
    if (!prev || State.raceTime < prev) Save.bestTimes[Save.selectedEnv] = State.raceTime;
  }
  persistSave();

  showModal(
    'RACE COMPLETE',
    `Position: <strong>${computePosition()}</strong><br>Time: <strong>${formatTime(State.raceTime)}</strong><br>Drift Score: <strong>${State.driftScore}</strong> • Stunt Score: <strong>${State.stuntScore}</strong><br><br><span style="color:#fde047;font-weight:800;">Reward Earned: +$${earned}</span>`,
    [
      { label: 'Race Again', fn: () => { hideModal(); startRace(); } },
      { label: 'Garage & Upgrades', fn: () => { hideModal(); openGarage(); } },
      { label: 'Main Menu', fn: () => { hideModal(); returnToMenu(); } }
    ]
  );
}

function togglePause() {
  if (State.phase === 'racing') {
    State.phase = 'paused';
    Sound.updateContinuous(0, false, false, false);
    showModal('PAUSED', 'Race telemetry on hold.', [
      { label: 'Resume Race', fn: () => { hideModal(); State.phase = 'racing'; } },
      { label: 'Restart Race', fn: () => { hideModal(); startRace(); } },
      { label: 'Main Menu', fn: () => { hideModal(); returnToMenu(); } }
    ]);
  } else if (State.phase === 'paused') {
    hideModal();
    State.phase = 'racing';
  }
}

/* ============================================================================
   7. SCREENS, GARAGE, CHALLENGES & SETTINGS UI
   ============================================================================ */
const SCREENS = ['menu-screen', 'setup-screen', 'garage-screen', 'challenges-screen', 'settings-screen'];
function hideAllScreens() {
  SCREENS.forEach(id => document.getElementById(id).classList.add('hidden'));
}
function showScreen(id) {
  Sound.ui();
  hideAllScreens();
  document.getElementById('hud').classList.add('hidden');
  document.getElementById('touch-layer').classList.add('hidden');
  document.getElementById(id).classList.remove('hidden');
  refreshBadges();
}
function returnToMenu() {
  State.phase = 'menu';
  Sound.updateContinuous(0, false, false, false);
  buildEnvironmentAndTrack(Save.selectedEnv, Save.selectedMode);
  showScreen('menu-screen');
}
function refreshBadges() {
  document.getElementById('menu-cash-badge').textContent = `$${Save.cash}`;
}
function showModal(title, html, buttons) {
  document.getElementById('modal-title').innerHTML = title;
  document.getElementById('modal-body').innerHTML = html;
  const wrap = document.getElementById('modal-buttons');
  wrap.innerHTML = '';
  buttons.forEach(b => {
    const btn = document.createElement('button');
    btn.className = 'menu-btn';
    btn.innerHTML = `<span>${b.label}</span><span>►</span>`;
    btn.onclick = b.fn;
    wrap.appendChild(btn);
  });
  document.getElementById('modal-screen').classList.remove('hidden');
}
function hideModal() {
  document.getElementById('modal-screen').classList.add('hidden');
}
function updateTouchVisibility() {
  const mode = Save.settings.touch;
  const isTouchDevice = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
  const show = State.phase === 'racing' && (mode === 'on' || (mode === 'auto' && isTouchDevice));
  document.getElementById('touch-layer').classList.toggle('hidden', !show);
}

function openSetup() {
  showScreen('setup-screen');
  const mGrid = document.getElementById('modes-grid');
  mGrid.innerHTML = '';
  MODES.forEach(m => {
    const div = document.createElement('div');
    div.className = `card ${Save.selectedMode === m.id ? 'active' : ''}`;
    div.innerHTML = `<div><span class="pill">Mode</span><div style="font-weight:800;margin-top:6px;">${m.name}</div><div style="font-size:0.76rem;color:#94a3b8;margin-top:4px;">${m.desc}</div></div>`;
    div.onclick = () => { Save.selectedMode = m.id; persistSave(); openSetup(); };
    mGrid.appendChild(div);
  });

  const eGrid = document.getElementById('envs-grid');
  eGrid.innerHTML = '';
  ENVIRONMENTS.forEach(e => {
    const best = Save.bestTimes[e.id] ? `Best: ${formatTime(Save.bestTimes[e.id])}` : `Par: ${e.targetSec}s`;
    const div = document.createElement('div');
    div.className = `card ${Save.selectedEnv === e.id ? 'active' : ''}`;
    div.innerHTML = `<div><span class="pill gold">${best}</span><div style="font-weight:800;margin-top:6px;">${e.name}</div><div style="font-size:0.74rem;color:#94a3b8;margin-top:3px;">${e.wet ? 'Wet Asphalt Reflections' : 'High-Grip Surface'}</div></div>`;
    div.onclick = () => { Save.selectedEnv = e.id; persistSave(); buildEnvironmentAndTrack(e.id, Save.selectedMode); openSetup(); };
    eGrid.appendChild(div);
  });
}

function openGarage() {
  showScreen('garage-screen');
  document.getElementById('garage-cash').textContent = `$${Save.cash}`;
  document.getElementById('garage-rep').textContent = Save.rep;
  document.getElementById('lv-engine').textContent = Save.upgrades.engine;
  document.getElementById('lv-nitro').textContent = Save.upgrades.nitro;
  document.getElementById('lv-grip').textContent = Save.upgrades.grip;

  const swWrap = document.getElementById('paint-swatches');
  swWrap.innerHTML = '';
  PAINTS.forEach(col => {
    const sw = document.createElement('div');
    sw.className = `swatch ${Save.paint === col ? 'selected' : ''}`;
    sw.style.background = '#' + col.toString(16).padStart(6, '0');
    sw.onclick = () => {
      Save.paint = col;
      persistSave();
      buildEnvironmentAndTrack(Save.selectedEnv, Save.selectedMode);
      openGarage();
    };
    swWrap.appendChild(sw);
  });

  const cGrid = document.getElementById('cars-grid');
  cGrid.innerHTML = '';
  CARS.forEach(c => {
    const owned = Save.unlockedCars.includes(c.id);
    const selected = Save.selectedCar === c.id;
    const div = document.createElement('div');
    div.className = `card ${selected ? 'active' : ''} ${!owned ? 'locked' : ''}`;
    div.innerHTML = `
      <div>
        <div style="display:flex;justify-content:space-between;align-items:center;">
          <span class="pill">${c.cls}</span>
          <strong style="color:#fde047;font-size:0.82rem;">${owned ? (selected ? 'ACTIVE' : 'OWNED') : '$' + c.price}</strong>
        </div>
        <div style="font-weight:900;font-size:1.05rem;margin-top:8px;">${c.name}</div>
        <div class="stat-row"><label><span>Top Speed</span><span>${c.topSpeed} KM/H</span></label><div class="mini-bar"><div class="mini-fill" style="width:${Math.min(100, (c.topSpeed / 320) * 100)}%"></div></div></div>
        <div class="stat-row"><label><span>Acceleration</span><span>${c.accel}</span></label><div class="mini-bar"><div class="mini-fill" style="width:${Math.min(100, (c.accel / 200) * 100)}%;background:#f97316;"></div></div></div>
        <div class="stat-row"><label><span>Handling</span><span>${c.grip.toFixed(2)}x</span></label><div class="mini-bar"><div class="mini-fill" style="width:${Math.min(100, ((c.grip - 0.9) / 0.4) * 100)}%;background:#22c55e;"></div></div></div>
      </div>
      <div>
        ${!owned
          ? `<button class="act-btn warn" style="width:100%;" ${Save.cash < c.price ? 'disabled' : ''} data-buy="${c.id}">Unlock ($${c.price})</button>`
          : `<button class="act-btn" style="width:100%;" ${selected ? 'disabled' : ''} data-pick="${c.id}">${selected ? 'Selected' : 'Select Car'}</button>`
        }
      </div>`;
    cGrid.appendChild(div);
  });

  cGrid.querySelectorAll('[data-buy]').forEach(btn => {
    btn.onclick = () => {
      const car = CARS.find(x => x.id === btn.dataset.buy);
      if (car && Save.cash >= car.price) {
        Save.cash -= car.price;
        Save.unlockedCars.push(car.id);
        Save.selectedCar = car.id;
        persistSave();
        Sound.coin();
        buildEnvironmentAndTrack(Save.selectedEnv, Save.selectedMode);
        openGarage();
      }
    };
  });
  cGrid.querySelectorAll('[data-pick]').forEach(btn => {
    btn.onclick = () => {
      Save.selectedCar = btn.dataset.pick;
      persistSave();
      Sound.ui();
      buildEnvironmentAndTrack(Save.selectedEnv, Save.selectedMode);
      openGarage();
    };
  });
}

document.getElementById('btn-up-engine').onclick = () => buyUpgrade('engine', 350);
document.getElementById('btn-up-nitro').onclick = () => buyUpgrade('nitro', 300);
document.getElementById('btn-up-grip').onclick = () => buyUpgrade('grip', 300);
function buyUpgrade(key, cost) {
  const cur = Save.upgrades[key];
  const price = cost * cur;
  if (cur < 5 && Save.cash >= price) {
    Save.cash -= price;
    Save.upgrades[key]++;
    persistSave();
    Sound.coin();
    openGarage();
  }
}

function openChallenges() {
  showScreen('challenges-screen');
  const list = document.getElementById('challenges-list');
  list.innerHTML = '';
  Save.challenges.forEach((ch, idx) => {
    const done = ch.progress >= ch.target;
    const row = document.createElement('div');
    row.className = 'card';
    row.style.marginBottom = '10px';
    row.innerHTML = `
      <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;">
        <div>
          <div style="font-weight:800;">${ch.text}</div>
          <div style="font-size:0.78rem;color:#94a3b8;margin-top:3px;">Progress: ${ch.progress} / ${ch.target} • Reward: <span style="color:#fde047;">$${ch.reward}</span></div>
        </div>
        <button class="act-btn ${done && !ch.claimed ? 'warn' : ''}" ${(!done || ch.claimed) ? 'disabled' : ''} data-claim="${idx}">
          ${ch.claimed ? 'Claimed' : (done ? 'Claim $' + ch.reward : 'In Progress')}
        </button>
      </div>`;
    list.appendChild(row);
  });
  list.querySelectorAll('[data-claim]').forEach(btn => {
    btn.onclick = () => {
      const ch = Save.challenges[parseInt(btn.dataset.claim, 10)];
      if (ch && ch.progress >= ch.target && !ch.claimed) {
        ch.claimed = true;
        Save.cash += ch.reward;
        persistSave();
        Sound.coin();
        openChallenges();
      }
    };
  });
}

// Wire navigation buttons
document.getElementById('btn-quick-race').onclick = startRace;
document.getElementById('btn-start-configured').onclick = startRace;
document.getElementById('btn-open-race-setup').onclick = openSetup;
document.getElementById('btn-open-garage').onclick = openGarage;
document.getElementById('btn-open-challenges').onclick = openChallenges;
document.getElementById('btn-open-settings').onclick = () => showScreen('settings-screen');
document.getElementById('btn-pause').onclick = togglePause;
document.querySelectorAll('[data-back]').forEach(btn => {
  btn.onclick = () => showScreen(btn.dataset.back);
});

// Settings bindings
document.getElementById('set-sfx').value = Save.settings.sfx;
document.getElementById('set-music').value = Save.settings.music;
document.getElementById('set-cam').value = Save.settings.cam;
document.getElementById('set-cycle').value = Save.settings.cycle;
document.getElementById('set-touch').value = Save.settings.touch;
document.getElementById('set-gfx').value = Save.settings.gfx;

document.getElementById('set-sfx').oninput = e => { Save.settings.sfx = parseFloat(e.target.value); persistSave(); };
document.getElementById('set-music').oninput = e => { Save.settings.music = parseFloat(e.target.value); persistSave(); };
document.getElementById('set-cam').onchange = e => { Save.settings.cam = e.target.value; persistSave(); };
document.getElementById('set-cycle').onchange = e => { Save.settings.cycle = e.target.value; persistSave(); };
document.getElementById('set-touch').onchange = e => { Save.settings.touch = e.target.value; persistSave(); updateTouchVisibility(); };
document.getElementById('set-gfx').onchange = e => {
  Save.settings.gfx = e.target.value;
  persistSave();
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, Save.settings.gfx === 'high' ? 2 : 1.5));
  renderer.shadowMap.enabled = Save.settings.gfx === 'high';
};
document.getElementById('btn-reset-save').onclick = () => {
  Save = structuredClone(DEFAULT_SAVE);
  persistSave();
  refreshBadges();
  showToast('Save Data Reset');
};

window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});

/* ============================================================================
   8. MAIN ANIMATION LOOP
   ============================================================================ */
buildEnvironmentAndTrack(Save.selectedEnv, Save.selectedMode);
refreshBadges();

let prevTime = performance.now();
function animate(now) {
  requestAnimationFrame(animate);
  const dt = Math.min(0.05, (now - prevTime) / 1000);
  prevTime = now;

  if (State.phase === 'racing') {
    stepSimulation(dt);
  } else if (State.phase === 'menu' && playerCar) {
    // Gentle showcase camera orbit on the main menu
    const t = now * 0.0005;
    camera.position.set(Math.sin(t) * 7.5, 3.4, Math.cos(t) * 7.5);
    camera.lookAt(0, 0.8, 0);
  }

  renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>

Game Source: VELOCITY X — BEYOND LIMITS

Creator: PlasmaStar57

Libraries: three

Complexity: complex (1463 lines, 63.8 KB)

The full source code is displayed above on this page.

Remix Instructions

To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: velocity-x-beyond-limits-plasmastar57" to link back to the original. Then publish at arcadelab.ai/publish.