🎮ArcadeLab

SHADOW PROTOCOL

by PlasmaStar57
1329 lines67.6 KB
▶ 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="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="SHADOW PROTOCOL">
<meta name="mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<meta name="theme-color" content="#080b10">
<title>SHADOW PROTOCOL</title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; }
  html, body { position: fixed; inset: 0; width: 100%; height: 100%; overflow: hidden; background: #070a0f; color: #e2e8f0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; touch-action: none; overscroll-behavior: none; }
  canvas { display: block; width: 100%; height: 100%; touch-action: none; }
  #ui-layer { position: absolute; inset: 0; pointer-events: none; display: flex; flex-direction: column; justify-content: space-between; padding-top: env(safe-area-inset-top); padding-bottom: env(safe-area-inset-bottom); padding-left: env(safe-area-inset-left); padding-right: env(safe-area-inset-right); }
  .interactive { pointer-events: auto; }
  .screen { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; background: radial-gradient(circle at 50% 35%, rgba(18, 28, 45, 0.92), rgba(5, 8, 13, 0.98)); z-index: 20; padding: calc(20px + env(safe-area-inset-top)) calc(20px + env(safe-area-inset-right)) calc(20px + env(safe-area-inset-bottom)) calc(20px + env(safe-area-inset-left)); touch-action: pan-y; }
  .hidden { display: none !important; }
  h1.title { font-size: clamp(2.1rem, 5vw, 4.2rem); letter-spacing: 0.22em; font-weight: 900; text-transform: uppercase; color: #f8fafc; text-shadow: 0 0 25px rgba(239, 68, 68, 0.7), 0 4px 12px rgba(0,0,0,0.9); margin-bottom: 6px; text-align: center; }
  .subtitle { font-size: 0.9rem; letter-spacing: 0.32em; color: #ef4444; text-transform: uppercase; margin-bottom: 28px; font-weight: 700; text-align: center; }
  .btn-group { display: flex; flex-direction: column; gap: 11px; width: min(320px, 85vw); }
  .btn { background: linear-gradient(90deg, rgba(30,41,59,0.9), rgba(15,23,42,0.95)); border: 1px solid rgba(148,163,184,0.3); border-left: 4px solid #ef4444; color: #f1f5f9; padding: 13px 20px; font-size: 0.98rem; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; cursor: pointer; transition: all 0.15s ease; text-align: left; display: flex; justify-content: space-between; align-items: center; touch-action: manipulation; }
  .btn:hover:not(:disabled), .btn:active:not(:disabled) { background: linear-gradient(90deg, rgba(239,68,68,0.28), rgba(30,41,59,0.95)); border-color: #ef4444; transform: translateX(4px); }
  .btn:disabled { opacity: 0.4; cursor: not-allowed; border-left-color: #475569; }
  .panel { background: rgba(11, 16, 26, 0.96); border: 1px solid rgba(148, 163, 184, 0.25); border-top: 3px solid #ef4444; width: min(920px, 94vw); max-height: 84vh; display: flex; flex-direction: column; padding: 20px; box-shadow: 0 20px 50px rgba(0,0,0,0.85); }
  .panel-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(148,163,184,0.2); padding-bottom: 12px; margin-bottom: 16px; }
  .panel-title { font-size: 1.35rem; font-weight: 800; letter-spacing: 0.15em; text-transform: uppercase; color: #f8fafc; }
  .close-btn { background: rgba(239,68,68,0.2); border: 1px solid #ef4444; color: #fca5a5; padding: 7px 14px; font-weight: 700; cursor: pointer; text-transform: uppercase; letter-spacing: 0.1em; touch-action: manipulation; }
  .close-btn:hover, .close-btn:active { background: #ef4444; color: #fff; }
  .scroll-area { overflow-y: auto; -webkit-overflow-scrolling: touch; flex: 1; padding-right: 6px; touch-action: pan-y; }
  .grid-missions { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
  .mission-card { background: rgba(20, 29, 46, 0.85); border: 1px solid rgba(148,163,184,0.22); padding: 14px; cursor: pointer; transition: 0.15s; display: flex; flex-direction: column; justify-content: space-between; touch-action: manipulation; }
  .mission-card:hover:not(.locked), .mission-card:active:not(.locked) { border-color: #ef4444; background: rgba(35, 45, 68, 0.95); }
  .mission-card.locked { opacity: 0.45; cursor: not-allowed; }
  .tag { font-size: 0.72rem; padding: 2px 7px; background: rgba(239,68,68,0.2); color: #fca5a5; border: 1px solid rgba(239,68,68,0.4); font-weight: 700; letter-spacing: 0.08em; display: inline-block; }
  .stars { color: #facc15; letter-spacing: 2px; font-size: 0.95rem; }
  .armory-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 12px; }
  .weapon-card { background: rgba(20, 29, 46, 0.85); border: 1px solid rgba(148,163,184,0.25); padding: 14px; display: flex; flex-direction: column; gap: 8px; }
  .stat-bar { height: 6px; background: #1e293b; width: 100%; overflow: hidden; }
  .stat-fill { height: 100%; background: #38bdf8; }
  .action-sm { background: #dc2626; color: white; border: none; padding: 8px 12px; font-weight: 700; font-size: 0.78rem; letter-spacing: 0.08em; cursor: pointer; text-transform: uppercase; touch-action: manipulation; }
  .action-sm:disabled { background: #334155; color: #94a3b8; cursor: not-allowed; }
  .action-sm.equip { background: #0284c7; }
  /* HUD */
  #hud { padding: 12px 16px; display: flex; justify-content: space-between; align-items: flex-start; width: 100%; gap: 8px; }
  .hud-box { background: rgba(9, 13, 22, 0.8); border: 1px solid rgba(148,163,184,0.25); padding: 9px 12px; backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); }
  .bar-wrap { width: min(170px, 28vw); height: 9px; background: #1e293b; margin-top: 4px; position: relative; }
  .hp-fill { height: 100%; background: linear-gradient(90deg, #dc2626, #ef4444); transition: width 0.15s; }
  .arm-fill { height: 100%; background: linear-gradient(90deg, #0284c7, #38bdf8); transition: width 0.15s; }
  #boss-hud { position: absolute; top: calc(12px + env(safe-area-inset-top)); left: 50%; transform: translateX(-50%); width: min(440px, 65vw); background: rgba(15, 10, 15, 0.88); border: 1px solid #ef4444; padding: 8px 14px; text-align: center; }
  #boss-bar { width: 100%; height: 11px; background: #27151a; margin-top: 5px; }
  #boss-fill { height: 100%; background: linear-gradient(90deg, #991b1b, #f43f5e); width: 100%; transition: width 0.1s; }
  /* Cutscene */
  #cutscene-box { position: absolute; inset: 0; background: rgba(4, 6, 11, 0.92); z-index: 30; display: flex; flex-direction: column; justify-content: flex-end; padding: calc(18px + env(safe-area-inset-top)) calc(18px + env(safe-area-inset-right) + 18px) calc(18px + env(safe-area-inset-bottom)) calc(18px + env(safe-area-inset-left) + 18px); touch-action: manipulation; }
  .dialogue-frame { background: rgba(15, 23, 42, 0.95); border: 1px solid rgba(148,163,184,0.35); border-left: 5px solid #ef4444; padding: 18px; max-width: 860px; width: 100%; margin: 0 auto; display: flex; gap: 16px; align-items: center; }
  .portrait { width: 70px; height: 70px; flex-shrink: 0; border: 2px solid #475569; background: #0f172a; display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: 1.4rem; }
  /* Mobile & iOS Controls */
  #mobile-controls { position: absolute; inset: 0; pointer-events: none; z-index: 15; }
  .touch-zone { position: absolute; bottom: calc(18px + env(safe-area-inset-bottom)); pointer-events: auto; touch-action: none; }
  #joystick-base { left: calc(20px + env(safe-area-inset-left)); width: 124px; height: 124px; border-radius: 50%; background: rgba(255,255,255,0.09); border: 2px solid rgba(255,255,255,0.24); }
  #joystick-knob { position: absolute; left: 40px; top: 40px; width: 44px; height: 44px; border-radius: 50%; background: rgba(239,68,68,0.72); border: 2px solid #fca5a5; }
  .touch-btns { right: calc(18px + env(safe-area-inset-right)); bottom: calc(18px + env(safe-area-inset-bottom)); display: grid; grid-template-columns: repeat(3, 58px); gap: 10px; pointer-events: auto; }
  .t-btn { width: 58px; height: 58px; border-radius: 50%; background: rgba(15,23,42,0.76); border: 2px solid rgba(148,163,184,0.42); color: #f8fafc; font-weight: 800; font-size: 0.7rem; display: flex; align-items: center; justify-content: center; touch-action: none; }
  .t-btn:active, .t-btn.active { background: rgba(239,68,68,0.65); border-color: #fca5a5; }
  .t-btn.fire { width: 66px; height: 66px; background: rgba(220,38,38,0.5); border-color: #ef4444; }
  .setting-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid rgba(148,163,184,0.15); gap: 12px; }
  input[type=range] { accent-color: #ef4444; width: 150px; touch-action: pan-x; }
  select { background: #1e293b; color: #f8fafc; border: 1px solid #475569; padding: 7px 10px; font-size: 16px; touch-action: manipulation; }
  #ios-tip { font-size: 0.72rem; color: #64748b; text-align: center; margin-top: 8px; }
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>

<div id="ui-layer">
  <!-- HUD -->
  <div id="hud" class="hidden">
    <div class="hud-box">
      <div style="display:flex;justify-content:space-between;font-size:0.72rem;font-weight:700;letter-spacing:0.1em;gap:8px;">
        <span id="hud-name">ALEX CARTER</span><span id="hud-hp-txt">100/100</span>
      </div>
      <div class="bar-wrap"><div id="hud-hp" class="hp-fill" style="width:100%"></div></div>
      <div style="display:flex;justify-content:space-between;font-size:0.7rem;font-weight:700;letter-spacing:0.1em;margin-top:5px;color:#7dd3fc;gap:8px;">
        <span>ARMOR</span><span id="hud-arm-txt">50/50</span>
      </div>
      <div class="bar-wrap"><div id="hud-arm" class="arm-fill" style="width:100%"></div></div>
    </div>

    <div class="hud-box" style="text-align:center;max-width:320px;">
      <div id="hud-lvl" style="font-size:0.7rem;color:#ef4444;font-weight:800;letter-spacing:0.15em;">MISSION 01</div>
      <div id="hud-obj" style="font-size:0.82rem;font-weight:600;margin-top:2px;">Eliminate Black Veil forces</div>
    </div>

    <div style="display:flex;gap:8px;align-items:flex-start;">
      <div class="hud-box" style="text-align:right;">
        <div id="hud-wpn" style="font-size:0.78rem;font-weight:800;color:#38bdf8;letter-spacing:0.08em;">M9 TACTICAL</div>
        <div id="hud-ammo" style="font-size:1.15rem;font-weight:900;letter-spacing:0.05em;">15 / ∞</div>
        <div style="font-size:0.68rem;color:#94a3b8;">XP: <span id="hud-xp" style="color:#facc15;font-weight:700;">0</span></div>
      </div>
      <button id="btn-pause" class="hud-box interactive" style="cursor:pointer;font-weight:900;color:#f8fafc;padding:10px 14px;touch-action:manipulation;">II</button>
    </div>
  </div>

  <div id="boss-hud" class="hidden">
    <div id="boss-name" style="font-size:0.82rem;font-weight:900;letter-spacing:0.18em;color:#fca5a5;">BOSS</div>
    <div id="boss-bar"><div id="boss-fill"></div></div>
  </div>

  <!-- Mobile & iOS Touch Controls -->
  <div id="mobile-controls" class="hidden">
    <div id="joystick-base" class="touch-zone"><div id="joystick-knob"></div></div>
    <div class="touch-btns touch-zone">
      <div class="t-btn" data-act="weapon">WPN</div>
      <div class="t-btn" data-act="reload">RLD</div>
      <div class="t-btn" data-act="jump">JUMP</div>
      <div class="t-btn" data-act="crouch">DUCK</div>
      <div class="t-btn" data-act="melee">KNIFE</div>
      <div class="t-btn fire" data-act="shoot">FIRE</div>
    </div>
  </div>
</div>

<!-- MAIN MENU -->
<div id="menu-screen" class="screen">
  <div style="font-size:0.72rem;letter-spacing:0.28em;color:#94a3b8;margin-bottom:6px;">YEAR 2042 // CLASSIFIED OPERATIONS</div>
  <h1 class="title">SHADOW PROTOCOL</h1>
  <div class="subtitle">BLACK VEIL INSURGENCY</div>
  <div class="btn-group">
    <button class="btn" id="btn-new"><span>New Game</span><span>►</span></button>
    <button class="btn" id="btn-cont"><span>Continue</span><span id="cont-lvl-tag">LVL 1</span></button>
    <button class="btn" id="btn-missions"><span>Mission Select</span><span>12</span></button>
    <button class="btn" id="btn-armory"><span>Armory & Upgrades</span><span id="menu-xp-tag" style="color:#facc15;">0 XP</span></button>
    <button class="btn" id="btn-settings"><span>Settings</span><span>⚙</span></button>
    <button class="btn" id="btn-credits"><span>Credits</span><span>★</span></button>
  </div>
  <div style="margin-top:20px;font-size:0.74rem;color:#64748b;text-align:center;">
    PC: A/D or Arrows Move • W/Space Jump • S Crouch • Mouse Aim & Shoot • R Reload • Q/1-7 Switch • E Melee
  </div>
  <div id="ios-tip" class="hidden">iPhone / iPad: Open in Safari → Share (↑) → Add to Home Screen for full-screen app mode.</div>
</div>

<!-- MISSION SELECT -->
<div id="missions-screen" class="screen hidden">
  <div class="panel">
    <div class="panel-header">
      <div class="panel-title">Mission Select</div>
      <button class="close-btn" onclick="UI.showScreen('menu-screen')">Back</button>
    </div>
    <div class="scroll-area grid-missions" id="missions-grid"></div>
  </div>
</div>

<!-- ARMORY -->
<div id="armory-screen" class="screen hidden">
  <div class="panel">
    <div class="panel-header">
      <div>
        <div class="panel-title">Shadow Armory</div>
        <div style="font-size:0.8rem;color:#facc15;font-weight:700;">AVAILABLE XP: <span id="armory-xp">0</span></div>
      </div>
      <button class="close-btn" onclick="UI.showScreen('menu-screen')">Back</button>
    </div>
    <div class="scroll-area">
      <div style="background:rgba(14,116,144,0.2);border:1px solid #0284c7;padding:12px;margin-bottom:14px;display:flex;justify-content:space-between;align-items:center;gap:10px;">
        <div>
          <div style="font-weight:800;color:#38bdf8;">EXOSUIT TACTICAL PLATING (TIER <span id="armor-tier">1</span>/5)</div>
          <div style="font-size:0.8rem;color:#cbd5e1;">Increases Max Armor & Damage Mitigation</div>
        </div>
        <button class="action-sm equip" id="btn-up-armor">Upgrade (250 XP)</button>
      </div>
      <div class="armory-grid" id="armory-grid"></div>
    </div>
  </div>
</div>

<!-- SETTINGS -->
<div id="settings-screen" class="screen hidden">
  <div class="panel" style="max-width:540px;">
    <div class="panel-header">
      <div class="panel-title">System Settings</div>
      <button class="close-btn" onclick="UI.showScreen('menu-screen')">Back</button>
    </div>
    <div class="scroll-area">
      <div class="setting-row"><span>Music Volume</span><input type="range" id="set-music" min="0" max="1" step="0.05" value="0.4"></div>
      <div class="setting-row"><span>SFX Volume</span><input type="range" id="set-sfx" min="0" max="1" step="0.05" value="0.6"></div>
      <div class="setting-row"><span>Graphics Quality</span>
        <select id="set-gfx"><option value="high">Ultra HD (Weather + Glow)</option><option value="med">Medium</option><option value="low">Performance</option></select>
      </div>
      <div class="setting-row"><span>Touch Controls</span>
        <select id="set-touch"><option value="auto">Auto Detect</option><option value="on">Always Show</option><option value="off">Hidden</option></select>
      </div>
      <div class="setting-row"><span>Language</span>
        <select id="set-lang"><option value="en">English</option><option value="es">Español</option></select>
      </div>
      <div class="setting-row"><span>Display</span><button class="action-sm equip" onclick="toggleFullscreen()">Toggle Fullscreen</button></div>
      <div class="setting-row"><span>Save Data</span><button class="action-sm" onclick="resetProgress()">Reset Campaign</button></div>
    </div>
  </div>
</div>

<!-- CREDITS -->
<div id="credits-screen" class="screen hidden">
  <div class="panel" style="max-width:560px;text-align:center;">
    <div class="panel-header">
      <div class="panel-title">Credits</div>
      <button class="close-btn" onclick="UI.showScreen('menu-screen')">Back</button>
    </div>
    <div class="scroll-area" style="padding:16px 0;line-height:1.8;">
      <h2 style="color:#ef4444;letter-spacing:0.2em;">SHADOW PROTOCOL</h2>
      <p style="color:#94a3b8;font-size:0.85rem;margin-bottom:16px;">2042 TACTICAL ACTION ENGINE</p>
      <p><strong>Lead Design & Architecture:</strong> Shadow Interactive</p>
      <p><strong>Character & Weapons Systems:</strong> Project Shadow Division</p>
      <p><strong>Synthesized Audio & Dynamic Score:</strong> WebAudio Combat DSP</p>
      <p style="margin-top:16px;color:#64748b;font-size:0.8rem;">Built as a self-contained HD 2D HTML5 Engine for iOS, Android & PC.</p>
    </div>
  </div>
</div>

<!-- PAUSE / MISSION COMPLETE / ENDING OVERLAY -->
<div id="modal-screen" class="screen hidden" style="background:rgba(4,7,12,0.88);z-index:25;">
  <div class="panel" style="max-width:520px;text-align:center;">
    <div id="modal-title" class="panel-title" style="margin-bottom:10px;color:#ef4444;">PAUSED</div>
    <div id="modal-body" style="color:#cbd5e1;font-size:0.95rem;line-height:1.6;margin-bottom:20px;"></div>
    <div id="modal-actions" class="btn-group" style="margin:0 auto;"></div>
  </div>
</div>

<!-- CUTSCENE OVERLAY -->
<div id="cutscene-box" class="hidden interactive">
  <div id="cutscene-art" style="flex:1;display:flex;align-items:center;justify-content:center;text-align:center;padding:16px;"></div>
  <div class="dialogue-frame">
    <div id="cs-portrait" class="portrait">AC</div>
    <div style="flex:1;">
      <div id="cs-speaker" style="font-weight:900;color:#ef4444;letter-spacing:0.15em;font-size:0.85rem;margin-bottom:4px;">ALEX CARTER</div>
      <div id="cs-text" style="font-size:1rem;line-height:1.5;color:#f1f5f9;"></div>
      <div style="margin-top:12px;display:flex;justify-content:space-between;align-items:center;">
        <span style="font-size:0.75rem;color:#64748b;">TAP OR PRESS SPACE TO CONTINUE</span>
        <button class="action-sm" id="cs-skip">Skip Scene »</button>
      </div>
    </div>
  </div>
</div>

<script>
/* ==========================================================================
   0. PLATFORM & iOS SAFARI / WEB AUDIO UNLOCK HELPERS
   ========================================================================== */
const Platform = (() => {
  const ua = navigator.userAgent || '';
  const isIOS = /iPad|iPhone|iPod/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
  const isStandalone = window.navigator.standalone === true || window.matchMedia('(display-mode: standalone)').matches;
  return { isIOS, isStandalone };
})();

if (Platform.isIOS && !Platform.isStandalone) {
  document.getElementById('ios-tip').classList.remove('hidden');
}

/* ==========================================================================
   1. AUDIO SYNTHESIZER (iOS-safe WebAudio unlock + Procedural SFX & Music)
   ========================================================================== */
const AudioSys = (() => {
  let ctx = null, musicTimer = null, step = 0, isBossMusic = false, unlocked = false;
  function init() {
    const AudioCtx = window.AudioContext || window.webkitAudioContext;
    if (!AudioCtx) return;
    if (!ctx) ctx = new AudioCtx();
    if (ctx.state === 'suspended' || ctx.state === 'interrupted') {
      ctx.resume().catch(() => {});
    }
    if (!unlocked && ctx) {
      unlocked = true;
      try {
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        gain.gain.value = 0.0001;
        osc.connect(gain); gain.connect(ctx.destination);
        osc.start(); osc.stop(ctx.currentTime + 0.02);
      } catch (_) {}
    }
  }
  function playTone(freq, type, dur, vol, slide = 0) {
    if (!ctx || SaveData.settings.sfx <= 0) return;
    if (ctx.state !== 'running') ctx.resume().catch(() => {});
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    osc.type = type;
    osc.frequency.setValueAtTime(freq, ctx.currentTime);
    if (slide) osc.frequency.exponentialRampToValueAtTime(Math.max(20, freq + slide), ctx.currentTime + dur);
    gain.gain.setValueAtTime(vol * SaveData.settings.sfx, ctx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + dur);
    osc.connect(gain); gain.connect(ctx.destination);
    osc.start(); osc.stop(ctx.currentTime + dur);
  }
  function playNoise(dur, vol, filterFreq = 1000) {
    if (!ctx || SaveData.settings.sfx <= 0) return;
    if (ctx.state !== 'running') ctx.resume().catch(() => {});
    const bufSize = Math.max(1, Math.floor(ctx.sampleRate * dur));
    const buf = ctx.createBuffer(1, bufSize, ctx.sampleRate);
    const data = buf.getChannelData(0);
    for (let i = 0; i < bufSize; i++) data[i] = Math.random() * 2 - 1;
    const noise = ctx.createBufferSource();
    noise.buffer = buf;
    const filter = ctx.createBiquadFilter();
    filter.type = 'lowpass'; filter.frequency.value = filterFreq;
    const gain = ctx.createGain();
    gain.gain.setValueAtTime(vol * SaveData.settings.sfx, ctx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + dur);
    noise.connect(filter); filter.connect(gain); gain.connect(ctx.destination);
    noise.start();
  }
  function shoot(wpnType) {
    init();
    if (wpnType === 'energy') { playTone(880, 'sawtooth', 0.18, 0.3, -650); playTone(440, 'sine', 0.15, 0.25, -200); }
    else if (wpnType === 'sniper') { playNoise(0.35, 0.55, 2400); playTone(160, 'triangle', 0.25, 0.4, -110); }
    else if (wpnType === 'shotgun') { playNoise(0.28, 0.6, 1400); playTone(110, 'sawtooth', 0.2, 0.45, -70); }
    else { playNoise(0.11, 0.35, 3200); playTone(220, 'square', 0.08, 0.2, -140); }
  }
  function explosion() { init(); playNoise(0.55, 0.65, 650); playTone(75, 'sawtooth', 0.45, 0.5, -55); }
  function reload() { init(); playTone(520, 'triangle', 0.07, 0.2); setTimeout(() => playTone(780, 'triangle', 0.09, 0.25), 140); }
  function hit() { init(); playTone(140, 'sawtooth', 0.08, 0.25, -60); }
  function pickup() { init(); playTone(660, 'sine', 0.1, 0.25); setTimeout(() => playTone(990, 'sine', 0.15, 0.25), 80); }
  function startMusic(boss = false) {
    init(); isBossMusic = boss;
    if (musicTimer) clearInterval(musicTimer);
    const scale = boss ? [110, 116.5, 130.8, 146.8, 164.8, 174.6] : [82.4, 98, 110, 123.5, 146.8, 164.8];
    musicTimer = setInterval(() => {
      if (!ctx || SaveData.settings.music <= 0) return;
      if (ctx.state === 'suspended' || ctx.state === 'interrupted') ctx.resume().catch(() => {});
      const f = scale[step % scale.length] * (step % 8 === 0 ? 0.5 : 1);
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();
      osc.type = isBossMusic ? 'sawtooth' : 'triangle';
      osc.frequency.setValueAtTime(f, ctx.currentTime);
      gain.gain.setValueAtTime(0.08 * SaveData.settings.music, ctx.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.22);
      osc.connect(gain); gain.connect(ctx.destination);
      osc.start(); osc.stop(ctx.currentTime + 0.24);
      step++;
    }, boss ? 180 : 280);
  }
  return { init, shoot, explosion, reload, hit, pickup, startMusic };
})();

window.addEventListener('touchstart', () => AudioSys.init(), { passive: true });
window.addEventListener('pointerdown', () => AudioSys.init(), { passive: true });
document.addEventListener('visibilitychange', () => {
  if (!document.hidden) AudioSys.init();
});

/* ==========================================================================
   2. GAME DATA: WEAPONS, LEVELS, STORY CUTSCENES & SAVE SYSTEM
   ========================================================================== */
const WEAPONS = [
  { id: 0, name: 'M9 Tactical Pistol', type: 'pistol', dmg: 22, rate: 0.24, mag: 15, reload: 1.0, speed: 950, spread: 0.02, pellets: 1, unlockCost: 0, color: '#94a3b8' },
  { id: 1, name: 'M4A1 Shadow Carbine', type: 'ar', dmg: 26, rate: 0.12, mag: 30, reload: 1.4, speed: 1100, spread: 0.04, pellets: 1, unlockCost: 150, color: '#38bdf8' },
  { id: 2, name: 'MP5-SD Submachine', type: 'smg', dmg: 18, rate: 0.075, mag: 40, reload: 1.2, speed: 1000, spread: 0.07, pellets: 1, unlockCost: 300, color: '#34d399' },
  { id: 3, name: 'M870 Breach Shotgun', type: 'shotgun', dmg: 19, rate: 0.65, mag: 8, reload: 1.6, speed: 880, spread: 0.18, pellets: 6, unlockCost: 450, color: '#f97316' },
  { id: 4, name: 'M24 Recon Sniper', type: 'sniper', dmg: 115, rate: 0.85, mag: 6, reload: 1.8, speed: 1650, spread: 0.005, pellets: 1, unlockCost: 650, color: '#a855f7' },
  { id: 5, name: 'M249 Heavy LMG', type: 'lmg', dmg: 28, rate: 0.09, mag: 80, reload: 2.3, speed: 1080, spread: 0.06, pellets: 1, unlockCost: 900, color: '#eab308' },
  { id: 6, name: 'X-01 Plasma Railgun', type: 'energy', dmg: 145, rate: 0.45, mag: 12, reload: 1.5, speed: 1800, spread: 0.01, pellets: 1, unlockCost: 1300, color: '#f43f5e' }
];

const LEVELS = [
  { id: 1, title: 'THE FALL', env: 'city', diff: 'Easy', obj: 'Escape the burning city & eliminate hostiles', length: 3400, weather: 'ash', boss: null, waves: ['basic','basic','drone'] },
  { id: 2, title: 'LOST SIGNAL', env: 'outpost', diff: 'Easy', obj: 'Reach the relay tower & rescue survivors', length: 3800, weather: 'rain', boss: null, waves: ['basic','sniper','drone'] },
  { id: 3, title: 'DEAD FOREST', env: 'forest', diff: 'Medium', obj: 'Infiltrate Black Veil supply camp', length: 4200, weather: 'fog', boss: null, waves: ['basic','heavy','sniper'] },
  { id: 4, title: 'OPERATION NIGHTFALL', env: 'base', diff: 'Medium', obj: 'Breach perimeter & defeat Armored Commander', length: 4400, weather: 'rain', boss: { name: 'COMMANDER KANE (EXO-MECH)', hp: 850, phase: 1 }, waves: ['basic','heavy','drone'] },
  { id: 5, title: 'THE EXPERIMENT', env: 'lab', diff: 'Medium', obj: 'Uncover Project Shadow files in Sub-Lab 4', length: 4500, weather: 'sparks', boss: null, waves: ['mutant','drone','elite'] },
  { id: 6, title: 'DESERT STORM', env: 'desert', diff: 'Med-Hard', obj: 'Cross the canyon during sandstorm ambush', length: 4800, weather: 'sand', boss: null, waves: ['sniper','heavy','drone','elite'] },
  { id: 7, title: 'FROZEN TRUTH', env: 'arctic', diff: 'Hard', obj: 'Secure original AI viral genome in Arctic Vault', length: 5000, weather: 'snow', boss: { name: 'SPECIMEN X-09 (ALPHA MUTANT)', hp: 1200, phase: 1 }, waves: ['elite','mutant','sniper'] },
  { id: 8, title: 'BETRAYAL', env: 'bunker', diff: 'Hard', obj: 'Survive Handler Mercer’s ambush & escape bunker', length: 5200, weather: 'sparks', boss: null, waves: ['elite','heavy','drone'] },
  { id: 9, title: 'LAST SURVIVORS', env: 'city', diff: 'Hard', obj: 'Clear industrial sector for civilian evac', length: 5400, weather: 'ash', boss: null, waves: ['heavy','elite','mutant','drone'] },
  { id: 10, title: 'THE DARK NETWORK', env: 'lab', diff: 'Very Hard', obj: 'Destroy the ORACLE-9 Central AI Mainframe', length: 5500, weather: 'sparks', boss: { name: 'ORACLE-9 CENTRAL AI CORE', hp: 1650, phase: 1 }, waves: ['drone','elite','mutant'] },
  { id: 11, title: 'FINAL DESCENT', env: 'hq', diff: 'Very Hard', obj: 'Assault Black Veil Citadel defenses', length: 5800, weather: 'rain', boss: null, waves: ['elite','heavy','sniper','drone'] },
  { id: 12, title: 'SHADOW PROTOCOL', env: 'hq', diff: 'Extreme', obj: 'Confront General Vargas & end Project Shadow', length: 4600, weather: 'ash', boss: { name: 'GENERAL VARGAS (OMEGA SUIT)', hp: 2400, phase: 1, final: true }, waves: ['elite','heavy'] }
];

const CUTSCENES = {
  1: [
    { spk: 'NARRATOR // 2042', code: '2042', col: '#ef4444', txt: 'October 2042. Within 72 hours, the Chimera-V pathogen severed global satellites and collapsed every major government.' },
    { spk: 'ALEX CARTER', code: 'AC', col: '#38bdf8', txt: 'Black Veil didn’t contain the outbreak—they engineered it. I’m done running. Time to hunt them down.' }
  ],
  4: [
    { spk: 'COMMANDER KANE', code: 'BV', col: '#f97316', txt: 'You’re a ghost from Project Shadow, Carter! General Vargas already owns the ashes of this world!' },
    { spk: 'ALEX CARTER', code: 'AC', col: '#38bdf8', txt: 'Tell Vargas his empire ends tonight.' }
  ],
  5: [
    { spk: 'PROJECT SHADOW ARCHIVE', code: 'AI', col: '#a855f7', txt: '[CLASSIFIED LOG]: Subject Alex Carter was the first successful neural host for the Shadow Combat Protocol...' },
    { spk: 'ALEX CARTER', code: 'AC', col: '#38bdf8', txt: 'My memories... the enhancements... I wasn’t just a soldier. I was their prototype.' }
  ],
  8: [
    { spk: 'HANDLER MERCER (COMMS)', code: 'HM', col: '#eab308', txt: 'Forgive me, Alex. Vargas promised sanctuary for my family if I led you into the sub-bunker.' },
    { spk: 'ALEX CARTER', code: 'AC', col: '#38bdf8', txt: 'Lockdown triggered. Laser grids active. I’ll blast my way through every last one of them!' }
  ],
  12: [
    { spk: 'GENERAL VARGAS', code: 'GV', col: '#ef4444', txt: 'Look at what humanity built, Carter—weakness! With ORACLE-9 and Project Shadow, only the strong survive!' },
    { spk: 'ALEX CARTER', code: 'AC', col: '#38bdf8', txt: 'You slaughtered millions for a lie, Vargas. Shadow Protocol is terminated—starting with you!' }
  ]
};

const DefaultSave = {
  unlockedLevel: 1,
  stars: {},
  xp: 200,
  unlockedWeapons: [0],
  weaponLevels: { 0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1 },
  equippedWeapon: 0,
  armorTier: 1,
  settings: { music: 0.4, sfx: 0.6, gfx: 'high', touch: 'auto', lang: 'en' }
};
let SaveData = JSON.parse(localStorage.getItem('shadow_protocol_save') || 'null') || JSON.parse(JSON.stringify(DefaultSave));
function saveGame() {
  try { localStorage.setItem('shadow_protocol_save', JSON.stringify(SaveData)); } catch (_) {}
}

/* ==========================================================================
   3. INPUT & MULTI-TOUCH / iOS GESTURE HANDLER
   ========================================================================== */
const Input = { left: false, right: false, jump: false, crouch: false, shoot: false, reload: false, melee: false, mouseX: 600, mouseY: 300, useMouse: true };
window.addEventListener('gesturestart', e => e.preventDefault(), { passive: false });
window.addEventListener('gesturechange', e => e.preventDefault(), { passive: false });

window.addEventListener('keydown', e => {
  const k = e.key.toLowerCase();
  if (k === 'a' || k === 'arrowleft') Input.left = true;
  if (k === 'd' || k === 'arrowright') Input.right = true;
  if (k === 'w' || k === 'arrowup' || k === ' ') Input.jump = true;
  if (k === 's' || k === 'arrowdown') Input.crouch = true;
  if (k === 'r') Game.reloadWeapon();
  if (k === 'e') Game.meleeAttack();
  if (k === 'q') Game.cycleWeapon();
  if (k >= '1' && k <= '7') Game.selectWeapon(parseInt(k) - 1);
  if (k === 'escape' && Game.state === 'playing') Game.togglePause();
  if ((k === ' ' || k === 'enter') && Game.state === 'cutscene') CutsceneMgr.next();
});
window.addEventListener('keyup', e => {
  const k = e.key.toLowerCase();
  if (k === 'a' || k === 'arrowleft') Input.left = false;
  if (k === 'd' || k === 'arrowright') Input.right = false;
  if (k === 'w' || k === 'arrowup' || k === ' ') Input.jump = false;
  if (k === 's' || k === 'arrowdown') Input.crouch = false;
});
window.addEventListener('mousemove', e => { Input.mouseX = e.clientX; Input.mouseY = e.clientY; Input.useMouse = true; });
window.addEventListener('mousedown', e => { if (e.button === 0 && Game.state === 'playing') Input.shoot = true; });
window.addEventListener('mouseup', () => Input.shoot = false);

// Virtual Joystick & Multi-Touch Buttons (iOS & Android)
const joyBase = document.getElementById('joystick-base'), joyKnob = document.getElementById('joystick-knob');
let joyId = null;
joyBase.addEventListener('touchstart', e => {
  e.preventDefault(); AudioSys.init();
  const t = e.changedTouches[0];
  joyId = t.identifier; handleJoy(t);
}, { passive: false });
joyBase.addEventListener('touchmove', e => {
  e.preventDefault();
  for (let i = 0; i < e.changedTouches.length; i++) {
    const t = e.changedTouches[i];
    if (t.identifier === joyId) handleJoy(t);
  }
}, { passive: false });
function releaseJoy(e) {
  for (let i = 0; i < e.changedTouches.length; i++) {
    if (e.changedTouches[i].identifier === joyId) {
      joyId = null; joyKnob.style.transform = 'translate(0px,0px)';
      Input.left = Input.right = Input.crouch = false;
    }
  }
}
joyBase.addEventListener('touchend', releaseJoy, { passive: false });
joyBase.addEventListener('touchcancel', releaseJoy, { passive: false });

function handleJoy(t) {
  const rect = joyBase.getBoundingClientRect();
  const dx = t.clientX - (rect.left + rect.width / 2);
  const dy = t.clientY - (rect.top + rect.height / 2);
  const dist = Math.min(38, Math.hypot(dx, dy));
  const ang = Math.atan2(dy, dx);
  joyKnob.style.transform = `translate(${Math.cos(ang)*dist}px, ${Math.sin(ang)*dist}px)`;
  Input.useMouse = false;
  Input.left = dx < -14;
  Input.right = dx > 14;
  Input.crouch = dy > 24;
}
document.querySelectorAll('.t-btn').forEach(btn => {
  const act = btn.dataset.act;
  btn.addEventListener('touchstart', e => {
    e.preventDefault(); AudioSys.init(); btn.classList.add('active'); Input.useMouse = false;
    if (act === 'shoot') Input.shoot = true;
    if (act === 'jump') Input.jump = true;
    if (act === 'crouch') Input.crouch = true;
    if (act === 'reload') Game.reloadWeapon();
    if (act === 'weapon') Game.cycleWeapon();
    if (act === 'melee') Game.meleeAttack();
  }, { passive: false });
  const endBtn = e => {
    e.preventDefault(); btn.classList.remove('active');
    if (act === 'shoot') Input.shoot = false;
    if (act === 'jump') Input.jump = false;
    if (act === 'crouch') Input.crouch = false;
  };
  btn.addEventListener('touchend', endBtn, { passive: false });
  btn.addEventListener('touchcancel', endBtn, { passive: false });
});

/* ==========================================================================
   4. CUTSCENE MANAGER
   ========================================================================== */
const CutsceneMgr = {
  queue: [], idx: 0, onDone: null,
  play(lines, cb) {
    if (!lines || !lines.length) return cb();
    this.queue = lines; this.idx = 0; this.onDone = cb;
    Game.state = 'cutscene';
    document.getElementById('cutscene-box').classList.remove('hidden');
    this.render();
  },
  render() {
    const item = this.queue[this.idx];
    document.getElementById('cs-speaker').textContent = item.spk;
    document.getElementById('cs-speaker').style.color = item.col;
    const port = document.getElementById('cs-portrait');
    port.textContent = item.code; port.style.borderColor = item.col; port.style.color = item.col;
    document.getElementById('cs-text').textContent = item.txt;
    document.getElementById('cutscene-art').innerHTML = `<div style="max-width:600px;">
      <div style="font-size:0.75rem;letter-spacing:0.3em;color:${item.col};margin-bottom:8px;">TACTICAL TRANSMISSION // ${this.idx+1}/${this.queue.length}</div>
      <div style="font-size:clamp(1.15rem, 3.2vw, 1.5rem);font-weight:800;color:#f8fafc;text-shadow:0 2px 15px rgba(0,0,0,0.9);">"${item.txt}"</div>
    </div>`;
  },
  next() {
    this.idx++;
    if (this.idx >= this.queue.length) this.finish();
    else this.render();
  },
  finish() {
    document.getElementById('cutscene-box').classList.add('hidden');
    if (this.onDone) this.onDone();
  }
};
document.getElementById('cutscene-box').addEventListener('click', e => { if (e.target.id !== 'cs-skip') CutsceneMgr.next(); });
document.getElementById('cs-skip').addEventListener('click', () => CutsceneMgr.finish());

/* ==========================================================================
   5. CORE 2D ENGINE, ENVIRONMENTS, ENTITIES & BOSS AI
   ========================================================================== */
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let W = 0, H = 0, DPR = 1;
function resizeCanvas() {
  DPR = Math.min(window.devicePixelRatio || 1, 2);
  W = window.innerWidth;
  H = window.innerHeight;
  canvas.width = Math.floor(W * DPR);
  canvas.height = Math.floor(H * DPR);
  ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
window.addEventListener('orientationchange', () => setTimeout(resizeCanvas, 150));

const ENV_THEMES = {
  city:    { sky1: '#0b0f19', sky2: '#27171c', fog: 'rgba(239,68,68,0.08)', ground: '#1e2430', accent: '#ef4444' },
  outpost: { sky1: '#0c1622', sky2: '#1b2e3c', fog: 'rgba(56,189,248,0.07)', ground: '#1a2634', accent: '#38bdf8' },
  forest:  { sky1: '#071410', sky2: '#132a21', fog: 'rgba(52,211,153,0.09)', ground: '#11221b', accent: '#10b981' },
  base:    { sky1: '#0f172a', sky2: '#1e293b', fog: 'rgba(148,163,184,0.08)', ground: '#1e293b', accent: '#f59e0b' },
  lab:     { sky1: '#090d16', sky2: '#17153b', fog: 'rgba(168,85,247,0.1)', ground: '#181828', accent: '#a855f7' },
  desert:  { sky1: '#23170c', sky2: '#452711', fog: 'rgba(245,158,11,0.14)', ground: '#3b2414', accent: '#f97316' },
  arctic:  { sky1: '#0c1e2e', sky2: '#1e3a52', fog: 'rgba(186,230,253,0.14)', ground: '#cbd5e1', accent: '#38bdf8' },
  bunker:  { sky1: '#09090b', sky2: '#18181b', fog: 'rgba(239,68,68,0.1)', ground: '#18181b', accent: '#dc2626' },
  hq:      { sky1: '#09050d', sky2: '#230c18', fog: 'rgba(244,63,94,0.12)', ground: '#161320', accent: '#f43f5e' }
};

const Game = {
  state: 'menu',
  levelIdx: 0,
  camX: 0,
  shake: 0,
  groundY: 0,
  player: null,
  enemies: [],
  bullets: [],
  particles: [],
  pickups: [],
  platforms: [],
  weatherParticles: [],
  boss: null,
  kills: 0,
  startTime: 0,

  startLevel(idx) {
    AudioSys.init();
    this.levelIdx = idx;
    const lvl = LEVELS[idx];
    UI.hideAllScreens();
    CutsceneMgr.play(CUTSCENES[lvl.id], () => {
      this.initLevelEntities(lvl);
      this.state = 'playing';
      document.getElementById('hud').classList.remove('hidden');
      UI.updateTouchVisibility();
      AudioSys.startMusic(!!lvl.boss);
    });
  },

  initLevelEntities(lvl) {
    this.groundY = H - 90;
    this.camX = 0;
    this.shake = 0;
    this.kills = 0;
    this.startTime = performance.now();
    const maxArm = 40 + SaveData.armorTier * 20;
    const wpn = WEAPONS[SaveData.equippedWeapon];
    this.player = {
      x: 140, y: this.groundY - 68, vx: 0, vy: 0, w: 30, h: 68,
      hp: 100, maxHp: 100, armor: maxArm, maxArmor: maxArm,
      facing: 1, aimAngle: 0, grounded: true, crouch: false,
      ammo: wpn.mag, reloading: 0, fireTimer: 0, meleeTimer: 0, hurtTimer: 0, animTime: 0
    };
    this.enemies = []; this.bullets = []; this.particles = []; this.pickups = []; this.platforms = []; this.boss = null;
    document.getElementById('boss-hud').classList.add('hidden');

    for (let px = 480; px < lvl.length - 500; px += 460) {
      this.platforms.push({ x: px, y: this.groundY - 115, w: 170, h: 16, type: 'plat' });
      if (Math.random() > 0.35) this.platforms.push({ x: px + 210, y: this.groundY - 38, w: 46, h: 38, type: 'cover' });
    }

    const diffMult = 1 + idxScaling(lvl.id);
    for (let ex = 620; ex < lvl.length - 450; ex += Math.max(250, 420 - lvl.id * 12)) {
      const type = lvl.waves[Math.floor(Math.random() * lvl.waves.length)];
      this.spawnEnemy(type, ex, diffMult);
    }

    if (lvl.boss) {
      this.boss = {
        ...lvl.boss, maxHp: lvl.boss.hp, x: lvl.length - 320, y: this.groundY - 110,
        w: 64, h: 110, vx: 0, vy: 0, timer: 0, attackCd: 1.5, facing: -1, active: false
      };
    }

    this.weatherParticles = Array.from({ length: SaveData.settings.gfx === 'low' ? 20 : 75 }, () => ({
      x: Math.random() * W, y: Math.random() * H,
      vx: lvl.weather === 'sand' ? -9 : (lvl.weather === 'snow' ? -1.5 : -2.5),
      vy: lvl.weather === 'rain' ? 14 : (lvl.weather === 'ash' ? 1.5 : 3),
      size: Math.random() * 3 + 1.5
    }));

    document.getElementById('hud-lvl').textContent = `MISSION ${String(lvl.id).padStart(2, '0')}: ${lvl.title}`;
    document.getElementById('hud-obj').textContent = lvl.obj;
    this.updateHUD();
  },

  spawnEnemy(type, x, mult) {
    const specs = {
      basic:  { hp: 55,  spd: 110, range: 440, rate: 1.3, dmg: 9,  w: 28, h: 64, col: '#ef4444', flying: false },
      heavy:  { hp: 135, spd: 65,  range: 390, rate: 1.6, dmg: 15, w: 36, h: 72, col: '#f97316', flying: false },
      sniper: { hp: 50,  spd: 40,  range: 720, rate: 2.3, dmg: 26, w: 28, h: 64, col: '#a855f7', flying: false },
      elite:  { hp: 105, spd: 145, range: 480, rate: 0.9, dmg: 13, w: 30, h: 66, col: '#eab308', flying: false },
      drone:  { hp: 45,  spd: 165, range: 420, rate: 1.1, dmg: 10, w: 34, h: 24, col: '#38bdf8', flying: true },
      mutant: { hp: 95,  spd: 215, range: 70,  rate: 0.8, dmg: 20, w: 34, h: 62, col: '#10b981', flying: false }
    };
    const s = specs[type];
    this.enemies.push({
      type, x, y: s.flying ? this.groundY - 165 - Math.random() * 60 : this.groundY - s.h,
      vx: 0, vy: 0, w: s.w, h: s.h, hp: Math.round(s.hp * mult), maxHp: Math.round(s.hp * mult),
      spd: s.spd, range: s.range, rate: s.rate, dmg: Math.round(s.dmg * mult),
      col: s.col, flying: s.flying, cd: Math.random() * 1.2, facing: -1, anim: Math.random() * 6
    });
  },

  selectWeapon(idx) {
    if (!SaveData.unlockedWeapons.includes(idx)) return;
    SaveData.equippedWeapon = idx;
    const wpn = WEAPONS[idx];
    this.player.ammo = wpn.mag;
    this.player.reloading = 0;
    AudioSys.reload();
    this.updateHUD();
  },

  cycleWeapon() {
    const list = SaveData.unlockedWeapons;
    const next = list[(list.indexOf(SaveData.equippedWeapon) + 1) % list.length];
    this.selectWeapon(next);
  },

  reloadWeapon() {
    const wpn = WEAPONS[SaveData.equippedWeapon];
    if (this.player.reloading > 0 || this.player.ammo === wpn.mag) return;
    this.player.reloading = wpn.reload;
    AudioSys.reload();
  },

  meleeAttack() {
    if (this.player.meleeTimer > 0) return;
    this.player.meleeTimer = 0.45;
    AudioSys.hit();
    const reach = 65;
    this.enemies.forEach(e => {
      if (Math.abs((e.x + e.w/2) - (this.player.x + this.player.w/2)) < reach && Math.abs(e.y - this.player.y) < 70) {
        e.hp -= 65;
        this.spawnParticles(e.x + e.w/2, e.y + e.h/2, '#ef4444', 10);
      }
    });
  },

  firePlayerWeapon() {
    const p = this.player;
    const wpn = WEAPONS[SaveData.equippedWeapon];
    const lvlBonus = 1 + (SaveData.weaponLevels[wpn.id] - 1) * 0.18;
    if (p.fireTimer > 0 || p.reloading > 0) return;
    if (p.ammo <= 0) { this.reloadWeapon(); return; }

    p.ammo--;
    p.fireTimer = wpn.rate;
    this.shake = Math.max(this.shake, wpn.type === 'sniper' || wpn.type === 'shotgun' ? 6 : 2.5);
    AudioSys.shoot(wpn.type);

    const gunX = p.x + p.w / 2 + p.facing * 22;
    const gunY = p.y + (p.crouch ? 24 : 20);
    this.spawnParticles(gunX, gunY, '#fde047', 4);

    for (let i = 0; i < wpn.pellets; i++) {
      const ang = p.aimAngle + (Math.random() - 0.5) * wpn.spread;
      this.bullets.push({
        fromPlayer: true, x: gunX, y: gunY,
        vx: Math.cos(ang) * wpn.speed, vy: Math.sin(ang) * wpn.speed,
        dmg: wpn.dmg * lvlBonus, color: wpn.color, life: 1.4, pierce: wpn.type === 'sniper' || wpn.type === 'energy'
      });
    }
    if (p.ammo === 0) this.reloadWeapon();
    this.updateHUD();
  },

  damagePlayer(dmg) {
    const p = this.player;
    if (p.hurtTimer > 0) return;
    p.hurtTimer = 0.25;
    this.shake = 7;
    AudioSys.hit();
    if (p.armor > 0) {
      const absorbed = Math.min(p.armor, dmg * 0.75);
      p.armor -= absorbed;
      dmg -= absorbed;
    }
    p.hp = Math.max(0, p.hp - dmg);
    this.spawnParticles(p.x + p.w/2, p.y + 30, '#ef4444', 8);
    this.updateHUD();
    if (p.hp <= 0) this.gameOver();
  },

  spawnParticles(x, y, color, count) {
    const mult = SaveData.settings.gfx === 'low' ? 0.4 : 1;
    for (let i = 0; i < count * mult; i++) {
      const a = Math.random() * Math.PI * 2;
      const spd = Math.random() * 220 + 40;
      this.particles.push({ x, y, vx: Math.cos(a) * spd, vy: Math.sin(a) * spd - 60, life: 0.35 + Math.random() * 0.25, color, size: Math.random() * 3.5 + 1.5 });
    }
  },

  update(dt) {
    if (this.state !== 'playing') return;
    const lvl = LEVELS[this.levelIdx];
    const p = this.player;
    this.groundY = H - 90;

    if (p.fireTimer > 0) p.fireTimer -= dt;
    if (p.meleeTimer > 0) p.meleeTimer -= dt;
    if (p.hurtTimer > 0) p.hurtTimer -= dt;
    if (this.shake > 0) this.shake = Math.max(0, this.shake - dt * 28);
    if (p.reloading > 0) {
      p.reloading -= dt;
      if (p.reloading <= 0) { p.ammo = WEAPONS[SaveData.equippedWeapon].mag; this.updateHUD(); }
    }

    p.crouch = Input.crouch && p.grounded;
    p.h = p.crouch ? 44 : 68;
    const moveSpd = p.crouch ? 145 : 290;
    p.vx = 0;
    if (Input.left) { p.vx = -moveSpd; p.facing = -1; }
    if (Input.right) { p.vx = moveSpd; p.facing = 1; }
    if (Input.jump && p.grounded) { p.vy = -560; p.grounded = false; }

    p.vy += 1380 * dt;
    p.x = Math.max(20, Math.min(lvl.length - 60, p.x + p.vx * dt));
    p.y += p.vy * dt;
    if (p.vx !== 0) p.animTime += dt * 10;

    p.grounded = false;
    if (p.y + p.h >= this.groundY) { p.y = this.groundY - p.h; p.vy = 0; p.grounded = true; }
    for (let plat of this.platforms) {
      if (plat.type === 'plat' && p.vy >= 0 && p.x + p.w > plat.x && p.x < plat.x + plat.w &&
          p.y + p.h >= plat.y && p.y + p.h <= plat.y + 22) {
        p.y = plat.y - p.h; p.vy = 0; p.grounded = true;
      }
    }

    if (Input.useMouse) {
      const screenX = p.x + p.w/2 - this.camX;
      const screenY = p.y + 20;
      p.aimAngle = Math.atan2(Input.mouseY - screenY, Input.mouseX - screenX);
      p.facing = Math.cos(p.aimAngle) >= 0 ? 1 : -1;
    } else {
      p.aimAngle = p.facing === 1 ? 0 : Math.PI;
    }

    if (Input.shoot) this.firePlayerWeapon();

    const targetCam = Math.max(0, Math.min(lvl.length - W, p.x - W * 0.32));
    this.camX += (targetCam - this.camX) * Math.min(1, dt * 8);

    for (let i = this.bullets.length - 1; i >= 0; i--) {
      const b = this.bullets[i];
      b.x += b.vx * dt; b.y += b.vy * dt; b.life -= dt;
      let hit = b.life <= 0 || b.y >= this.groundY;

      for (let plat of this.platforms) {
        if (plat.type === 'cover' && b.x > plat.x && b.x < plat.x + plat.w && b.y > plat.y && b.y < plat.y + plat.h) {
          hit = true; this.spawnParticles(b.x, b.y, '#94a3b8', 3);
        }
      }

      if (!hit && b.fromPlayer) {
        for (let e of this.enemies) {
          if (b.x > e.x && b.x < e.x + e.w && b.y > e.y && b.y < e.y + e.h) {
            e.hp -= b.dmg;
            this.spawnParticles(b.x, b.y, '#ef4444', 6);
            if (!b.pierce) hit = true;
            break;
          }
        }
        if (!hit && this.boss && this.boss.active && b.x > this.boss.x && b.x < this.boss.x + this.boss.w && b.y > this.boss.y && b.y < this.boss.y + this.boss.h) {
          this.boss.hp -= b.dmg;
          this.spawnParticles(b.x, b.y, '#f43f5e', 7);
          if (!b.pierce) hit = true;
        }
      } else if (!hit && !b.fromPlayer) {
        if (b.x > p.x && b.x < p.x + p.w && b.y > p.y && b.y < p.y + p.h) {
          this.damagePlayer(b.dmg);
          hit = true;
        }
      }
      if (hit) this.bullets.splice(i, 1);
    }

    for (let i = this.enemies.length - 1; i >= 0; i--) {
      const e = this.enemies[i];
      e.anim += dt * 7;
      const dx = (p.x + p.w/2) - (e.x + e.w/2);
      const dist = Math.abs(dx);
      if (dist < 820) {
        e.facing = dx >= 0 ? 1 : -1;
        if (dist > e.range * 0.72) e.x += e.facing * e.spd * dt;
        if (e.flying) e.y += Math.sin(e.anim * 0.6) * 35 * dt;
        e.cd -= dt;
        if (e.cd <= 0 && dist <= e.range) {
          e.cd = e.rate;
          if (e.type === 'mutant') {
            if (dist < 75) this.damagePlayer(e.dmg);
          } else {
            const ang = Math.atan2((p.y + 24) - (e.y + e.h * 0.35), dx);
            this.bullets.push({ fromPlayer: false, x: e.x + e.w/2, y: e.y + e.h * 0.35, vx: Math.cos(ang)*540, vy: Math.sin(ang)*540, dmg: e.dmg, color: '#f87171', life: 1.8 });
            AudioSys.shoot('ar');
          }
        }
      }
      if (e.hp <= 0) {
        this.kills++;
        SaveData.xp += 25;
        AudioSys.explosion();
        this.spawnParticles(e.x + e.w/2, e.y + e.h/2, e.col, 16);
        if (Math.random() < 0.32) this.pickups.push({ x: e.x, y: this.groundY - 22, type: Math.random() < 0.55 ? 'hp' : 'armor' });
        this.enemies.splice(i, 1);
        this.updateHUD();
      }
    }

    if (this.boss) {
      const b = this.boss;
      const dist = Math.abs((p.x + p.w/2) - (b.x + b.w/2));
      if (dist < 760 && !b.active) {
        b.active = true;
        document.getElementById('boss-hud').classList.remove('hidden');
        document.getElementById('boss-name').textContent = b.name;
      }
      if (b.active) {
        b.timer += dt;
        b.facing = p.x < b.x ? -1 : 1;
        if (b.hp < b.maxHp * 0.65 && b.phase === 1) { b.phase = 2; this.spawnParticles(b.x+32, b.y+50, '#facc15', 25); }
        if (b.hp < b.maxHp * 0.32 && b.phase === 2) { b.phase = 3; this.spawnParticles(b.x+32, b.y+50, '#f43f5e', 35); }

        b.x += Math.sin(b.timer * (1.2 + b.phase * 0.4)) * (130 + b.phase * 45) * dt;
        b.x = Math.max(lvl.length - 850, Math.min(lvl.length - 120, b.x));

        b.attackCd -= dt;
        if (b.attackCd <= 0) {
          b.attackCd = Math.max(0.55, 1.5 - b.phase * 0.3);
          const baseAng = Math.atan2((p.y + 25) - (b.y + 40), (p.x + 15) - (b.x + 32));
          const spreadCount = b.phase === 1 ? 1 : (b.phase === 2 ? 3 : 5);
          for (let s = 0; s < spreadCount; s++) {
            const a = baseAng + (s - (spreadCount - 1)/2) * 0.16;
            this.bullets.push({ fromPlayer: false, x: b.x + 32, y: b.y + 40, vx: Math.cos(a)*620, vy: Math.sin(a)*620, dmg: 16 + b.phase * 3, color: '#fb7185', life: 2.0 });
          }
          AudioSys.shoot('shotgun');
        }
        document.getElementById('boss-fill').style.width = `${Math.max(0, (b.hp / b.maxHp) * 100)}%`;
        if (b.hp <= 0) {
          AudioSys.explosion();
          this.spawnParticles(b.x + 32, b.y + 55, '#f43f5e', 45);
          SaveData.xp += 250;
          this.boss = null;
          document.getElementById('boss-hud').classList.add('hidden');
          this.completeLevel();
          return;
        }
      }
    }

    for (let i = this.pickups.length - 1; i >= 0; i--) {
      const pk = this.pickups[i];
      if (Math.abs(pk.x - p.x) < 38 && Math.abs(pk.y - p.y) < 65) {
        AudioSys.pickup();
        if (pk.type === 'hp') p.hp = Math.min(p.maxHp, p.hp + 30);
        else p.armor = Math.min(p.maxArmor, p.armor + 25);
        this.pickups.splice(i, 1);
        this.updateHUD();
      }
    }

    for (let i = this.particles.length - 1; i >= 0; i--) {
      const pt = this.particles[i];
      pt.x += pt.vx * dt; pt.y += pt.vy * dt; pt.vy += 320 * dt; pt.life -= dt;
      if (pt.life <= 0) this.particles.splice(i, 1);
    }
    for (let wp of this.weatherParticles) {
      wp.x += wp.vx; wp.y += wp.vy;
      if (wp.x < 0) wp.x = W; if (wp.y > H) { wp.y = 0; wp.x = Math.random() * W; }
    }

    if (!this.boss && p.x >= lvl.length - 160) {
      this.completeLevel();
    }
  },

  updateHUD() {
    const p = this.player;
    const wpn = WEAPONS[SaveData.equippedWeapon];
    document.getElementById('hud-hp').style.width = `${(p.hp / p.maxHp) * 100}%`;
    document.getElementById('hud-hp-txt').textContent = `${Math.ceil(p.hp)}/${p.maxHp}`;
    document.getElementById('hud-arm').style.width = `${(p.armor / p.maxArmor) * 100}%`;
    document.getElementById('hud-arm-txt').textContent = `${Math.ceil(p.armor)}/${p.maxArmor}`;
    document.getElementById('hud-wpn').textContent = wpn.name;
    document.getElementById('hud-ammo').textContent = p.reloading > 0 ? 'RELOADING...' : `${p.ammo} / ∞`;
    document.getElementById('hud-xp').textContent = SaveData.xp;
  },

  togglePause() {
    if (this.state === 'playing') {
      this.state = 'paused';
      UI.showModal('MISSION PAUSED', 'Tactical systems on standby.', [
        { label: 'Resume Mission', fn: () => { UI.hideModal(); this.state = 'playing'; } },
        { label: 'Restart Mission', fn: () => { UI.hideModal(); this.startLevel(this.levelIdx); } },
        { label: 'Abort to Main Menu', fn: () => { UI.hideModal(); UI.returnToMenu(); } }
      ]);
    } else if (this.state === 'paused') {
      UI.hideModal(); this.state = 'playing';
    }
  },

  gameOver() {
    this.state = 'gameover';
    UI.showModal('OPERATIVE KIA', 'Alex Carter was neutralized in action. Black Veil continues its global lockdown.', [
      { label: 'Retry Mission', fn: () => { UI.hideModal(); this.startLevel(this.levelIdx); } },
      { label: 'Return to Base', fn: () => { UI.hideModal(); UI.returnToMenu(); } }
    ]);
  },

  completeLevel() {
    this.state = 'victory';
    const lvl = LEVELS[this.levelIdx];
    const stars = this.player.hp > 70 ? 3 : (this.player.hp > 35 ? 2 : 1);
    SaveData.stars[lvl.id] = Math.max(SaveData.stars[lvl.id] || 0, stars);
    const bonusXp = 120 + stars * 50;
    SaveData.xp += bonusXp;
    if (lvl.id < 12) SaveData.unlockedLevel = Math.max(SaveData.unlockedLevel, lvl.id + 1);
    saveGame();

    if (lvl.id === 12) {
      UI.showModal('FINAL PROTOCOL CHOICE',
        `General Vargas has fallen and the ORACLE-9 core lies exposed.<br><br><strong>Choose the fate of Project Shadow:</strong>`, [
        { label: 'ENDING A: Destroy ORACLE-9 (Free Humanity)', fn: () => this.showEnding('A') },
        { label: 'ENDING B: Merge with ORACLE-9 (Become Shadow)', fn: () => this.showEnding('B') }
      ]);
      return;
    }

    UI.showModal(`MISSION ${lvl.id} COMPLETE`,
      `Rating: <span style="color:#facc15;font-size:1.3rem;">${'★'.repeat(stars)}${'☆'.repeat(3-stars)}</span><br>Hostiles Neutralized: ${this.kills}<br>XP Earned: +${bonusXp} XP`, [
      { label: 'Next Mission »', fn: () => { UI.hideModal(); this.startLevel(this.levelIdx + 1); } },
      { label: 'Armory & Upgrades', fn: () => { UI.hideModal(); UI.returnToMenu(); UI.openArmory(); } },
      { label: 'Main Menu', fn: () => { UI.hideModal(); UI.returnToMenu(); } }
    ]);
  },

  showEnding(type) {
    const text = type === 'A'
      ? 'Alex detonates the reactor core, erasing ORACLE-9 and Project Shadow forever. Across the globe, satellites flicker back to life as humanity begins to rebuild.'
      : 'Alex interfaces his neural implant directly into ORACLE-9, seizing command of Black Veil’s global network to enforce an eternal, silent peace from the shadows.';
    UI.showModal(`ENDING ${type}: ${type === 'A' ? 'DAWN OF LIBERTY' : 'ETERNAL SHADOW'}`, text, [
      { label: 'View Credits', fn: () => { UI.hideModal(); UI.returnToMenu(); UI.showScreen('credits-screen'); } },
      { label: 'Main Menu', fn: () => { UI.hideModal(); UI.returnToMenu(); } }
    ]);
  },

  /* ========================================================================
     6. HD 2D PROCEDURAL RENDERER (Parallax, Lighting, Skeletal Sprites)
     ======================================================================== */
  render() {
    const lvl = LEVELS[this.levelIdx] || LEVELS[0];
    const theme = ENV_THEMES[lvl.env];
    ctx.save();
    if (this.shake > 0) ctx.translate((Math.random()-0.5)*this.shake, (Math.random()-0.5)*this.shake);

    const skyGrad = ctx.createLinearGradient(0, 0, 0, H);
    skyGrad.addColorStop(0, theme.sky1);
    skyGrad.addColorStop(1, theme.sky2);
    ctx.fillStyle = skyGrad;
    ctx.fillRect(0, 0, W, H);

    ctx.fillStyle = 'rgba(10, 14, 23, 0.65)';
    for (let i = -1; i < Math.ceil(W / 180) + 2; i++) {
      const bx = i * 180 - ((this.camX * 0.2) % 180);
      const bh = 140 + ((Math.abs(i * 73) % 130));
      ctx.fillRect(bx, this.groundY - bh, 155, bh);
      if (lvl.env === 'city' || lvl.env === 'hq' || lvl.env === 'base') {
        ctx.fillStyle = theme.accent;
        ctx.globalAlpha = 0.25;
        ctx.fillRect(bx + 20, this.groundY - bh + 25, 12, 6);
        ctx.fillRect(bx + 80, this.groundY - bh + 55, 12, 6);
        ctx.globalAlpha = 1;
        ctx.fillStyle = 'rgba(10, 14, 23, 0.65)';
      }
    }

    ctx.fillStyle = 'rgba(15, 22, 34, 0.85)';
    for (let i = -1; i < Math.ceil(W / 260) + 2; i++) {
      const mx = i * 260 - ((this.camX * 0.48) % 260);
      const mh = 90 + ((Math.abs(i * 41) % 95));
      ctx.fillRect(mx, this.groundY - mh, 190, mh);
    }

    ctx.save();
    ctx.translate(-this.camX, 0);

    ctx.fillStyle = theme.ground;
    ctx.fillRect(0, this.groundY, lvl.length + 400, H - this.groundY);
    ctx.fillStyle = theme.accent;
    ctx.fillRect(0, this.groundY, lvl.length + 400, 3);

    const exX = lvl.length - 160;
    const beaconGrad = ctx.createLinearGradient(exX, this.groundY - 220, exX, this.groundY);
    beaconGrad.addColorStop(0, 'rgba(56, 189, 248, 0)');
    beaconGrad.addColorStop(1, 'rgba(56, 189, 248, 0.35)');
    ctx.fillStyle = beaconGrad;
    ctx.fillRect(exX, this.groundY - 220, 110, 220);
    ctx.fillStyle = '#38bdf8';
    ctx.font = 'bold 12px sans-serif';
    ctx.fillText('EXTRACTION ZONE', exX + 4, this.groundY - 12);

    for (let plat of this.platforms) {
      ctx.fillStyle = plat.type === 'plat' ? '#334155' : '#475569';
      ctx.fillRect(plat.x, plat.y, plat.w, plat.h);
      ctx.fillStyle = theme.accent;
      ctx.fillRect(plat.x, plat.y, plat.w, 3);
    }

    for (let pk of this.pickups) {
      ctx.fillStyle = pk.type === 'hp' ? '#ef4444' : '#38bdf8';
      ctx.fillRect(pk.x, pk.y, 20, 20);
      ctx.fillStyle = '#fff';
      ctx.fillRect(pk.x + 8, pk.y + 4, 4, 12);
      ctx.fillRect(pk.x + 4, pk.y + 8, 12, 4);
    }

    for (let e of this.enemies) {
      this.drawSoldier(e.x, e.y, e.w, e.h, e.facing, e.col, e.anim, e.flying, false);
      ctx.fillStyle = '#0f172a'; ctx.fillRect(e.x, e.y - 10, e.w, 4);
      ctx.fillStyle = e.col; ctx.fillRect(e.x, e.y - 10, e.w * (e.hp / e.maxHp), 4);
    }

    if (this.boss) {
      const b = this.boss;
      this.drawSoldier(b.x, b.y, b.w, b.h, b.facing, b.phase === 3 ? '#f43f5e' : '#f97316', b.timer * 6, false, true);
    }

    if (this.player) {
      const p = this.player;
      this.drawSoldier(p.x, p.y, p.w, p.h, p.facing, '#38bdf8', p.animTime, false, false, p);
    }

    for (let b of this.bullets) {
      ctx.fillStyle = b.color;
      ctx.beginPath();
      ctx.arc(b.x, b.y, b.fromPlayer ? 3.5 : 4.2, 0, Math.PI * 2);
      ctx.fill();
    }

    for (let pt of this.particles) {
      ctx.globalAlpha = Math.max(0, pt.life * 2);
      ctx.fillStyle = pt.color;
      ctx.fillRect(pt.x, pt.y, pt.size, pt.size);
    }
    ctx.globalAlpha = 1;
    ctx.restore();

    ctx.fillStyle = theme.fog;
    ctx.fillRect(0, 0, W, H);
    ctx.fillStyle = lvl.weather === 'sand' ? 'rgba(251,191,36,0.45)' : 'rgba(226,232,240,0.45)';
    for (let wp of this.weatherParticles) {
      if (lvl.weather === 'rain') ctx.fillRect(wp.x, wp.y, 1.5, 11);
      else { ctx.beginPath(); ctx.arc(wp.x, wp.y, wp.size, 0, Math.PI * 2); ctx.fill(); }
    }

    ctx.restore();
  },

  drawSoldier(x, y, w, h, facing, visorCol, anim, flying, isBoss, playerRef = null) {
    ctx.save();
    ctx.translate(x + w / 2, y);
    if (flying) {
      ctx.fillStyle = '#1e293b'; ctx.fillRect(-w/2, 4, w, h - 8);
      ctx.fillStyle = visorCol; ctx.fillRect(-6, 9, 12, 5);
      ctx.restore(); return;
    }
    const stride = Math.sin(anim) * (isBoss ? 10 : 7);
    ctx.fillStyle = '#0f172a';
    ctx.fillRect(-9 + stride * 0.5, h - 24, 7, 24);
    ctx.fillRect(2 - stride * 0.5, h - 24, 7, 24);
    ctx.fillStyle = playerRef ? '#1e293b' : '#27272a';
    ctx.fillRect(-w/2 + 2, 16, w - 4, h - 38);
    ctx.fillStyle = playerRef ? '#334155' : '#3f3f46';
    ctx.fillRect(-w/2 + 4, 20, w - 8, h - 46);
    ctx.fillStyle = '#18181b';
    ctx.fillRect(-9, 0, 18, 16);
    ctx.fillStyle = visorCol;
    ctx.fillRect(facing === 1 ? 1 : -9, 5, 8, 4);

    ctx.save();
    ctx.translate(0, 24);
    if (playerRef) ctx.rotate(playerRef.aimAngle);
    else if (facing === -1) ctx.scale(-1, 1);
    ctx.fillStyle = '#090d16';
    ctx.fillRect(0, -3, isBoss ? 36 : 24, 6);
    ctx.fillStyle = visorCol;
    ctx.fillRect(10, -2, 8, 2);
    if (playerRef && playerRef.meleeTimer > 0.25) {
      ctx.strokeStyle = '#38bdf8'; ctx.lineWidth = 3;
      ctx.beginPath(); ctx.arc(12, 0, 32, -0.8, 0.8); ctx.stroke();
    }
    ctx.restore();
    ctx.restore();
  }
};

function idxScaling(id) { return (id - 1) * 0.14; }

/* ==========================================================================
   7. UI CONTROLLER & MENU BUILDERS
   ========================================================================== */
const UI = {
  screens: ['menu-screen', 'missions-screen', 'armory-screen', 'settings-screen', 'credits-screen'],
  showScreen(id) {
    this.hideAllScreens();
    document.getElementById('hud').classList.add('hidden');
    document.getElementById('mobile-controls').classList.add('hidden');
    document.getElementById('boss-hud').classList.add('hidden');
    document.getElementById(id).classList.remove('hidden');
    this.refreshMenuTags();
  },
  hideAllScreens() { this.screens.forEach(s => document.getElementById(s).classList.add('hidden')); },
  returnToMenu() { Game.state = 'menu'; this.showScreen('menu-screen'); },
  refreshMenuTags() {
    document.getElementById('cont-lvl-tag').textContent = `LVL ${SaveData.unlockedLevel}`;
    document.getElementById('menu-xp-tag').textContent = `${SaveData.xp} XP`;
  },
  openMissions() {
    this.showScreen('missions-screen');
    const grid = document.getElementById('missions-grid');
    grid.innerHTML = '';
    LEVELS.forEach((lvl, idx) => {
      const locked = lvl.id > SaveData.unlockedLevel;
      const st = SaveData.stars[lvl.id] || 0;
      const card = document.createElement('div');
      card.className = `mission-card ${locked ? 'locked' : ''}`;
      card.innerHTML = `
        <div>
          <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;">
            <span class="tag">LVL ${lvl.id} • ${lvl.diff}</span>
            <span class="stars">${'★'.repeat(st)}${'☆'.repeat(3-st)}</span>
          </div>
          <div style="font-weight:800;font-size:1.05rem;color:#f8fafc;">${lvl.title}</div>
          <div style="font-size:0.78rem;color:#94a3b8;margin-top:4px;">${lvl.obj}</div>
        </div>
        <div style="margin-top:12px;font-size:0.72rem;color:#38bdf8;font-weight:700;text-transform:uppercase;">
          ${locked ? 'LOCKED' : 'DEPLOY MISSION ►'}
        </div>`;
      if (!locked) card.onclick = () => Game.startLevel(idx);
      grid.appendChild(card);
    });
  },
  openArmory() {
    this.showScreen('armory-screen');
    document.getElementById('armory-xp').textContent = SaveData.xp;
    document.getElementById('armor-tier').textContent = SaveData.armorTier;
    const armBtn = document.getElementById('btn-up-armor');
    const armCost = SaveData.armorTier * 250;
    armBtn.textContent = SaveData.armorTier >= 5 ? 'MAXED' : `Upgrade (${armCost} XP)`;
    armBtn.disabled = SaveData.armorTier >= 5 || SaveData.xp < armCost;
    armBtn.onclick = () => {
      if (SaveData.xp >= armCost && SaveData.armorTier < 5) {
        SaveData.xp -= armCost; SaveData.armorTier++; saveGame(); this.openArmory(); AudioSys.pickup();
      }
    };

    const grid = document.getElementById('armory-grid');
    grid.innerHTML = '';
    WEAPONS.forEach(w => {
      const unlocked = SaveData.unlockedWeapons.includes(w.id);
      const equipped = SaveData.equippedWeapon === w.id;
      const wLvl = SaveData.weaponLevels[w.id] || 1;
      const upCost = wLvl * 180;
      const card = document.createElement('div');
      card.className = 'weapon-card';
      card.innerHTML = `
        <div style="display:flex;justify-content:space-between;align-items:center;">
          <strong style="color:${w.color};">${w.name}</strong>
          <span class="tag">${unlocked ? 'MK-' + wLvl : 'LOCKED'}</span>
        </div>
        <div style="font-size:0.75rem;color:#94a3b8;">Damage: ${Math.round(w.dmg * (1 + (wLvl-1)*0.18))} • Mag: ${w.mag}</div>
        <div class="stat-bar"><div class="stat-fill" style="width:${Math.min(100, w.dmg * 0.7)}%;background:${w.color};"></div></div>
        <div style="display:flex;gap:8px;margin-top:6px;">
          ${!unlocked
            ? `<button class="action-sm" ${SaveData.xp < w.unlockCost ? 'disabled' : ''} onclick="unlockWpn(${w.id})">Unlock (${w.unlockCost} XP)</button>`
            : `<button class="action-sm equip" ${equipped ? 'disabled' : ''} onclick="equipWpn(${w.id})">${equipped ? 'Equipped' : 'Equip'}</button>
               <button class="action-sm" ${wLvl >= 5 || SaveData.xp < upCost ? 'disabled' : ''} onclick="upgradeWpn(${w.id})">${wLvl >= 5 ? 'MAX' : 'Upgrade ('+upCost+' XP)'}</button>`
          }
        </div>`;
      grid.appendChild(card);
    });
  },
  showModal(title, bodyHtml, buttons) {
    document.getElementById('modal-title').innerHTML = title;
    document.getElementById('modal-body').innerHTML = bodyHtml;
    const actBox = document.getElementById('modal-actions');
    actBox.innerHTML = '';
    buttons.forEach(b => {
      const btn = document.createElement('button');
      btn.className = 'btn';
      btn.innerHTML = `<span>${b.label}</span><span>►</span>`;
      btn.onclick = b.fn;
      actBox.appendChild(btn);
    });
    document.getElementById('modal-screen').classList.remove('hidden');
  },
  hideModal() { document.getElementById('modal-screen').classList.add('hidden'); },
  updateTouchVisibility() {
    const mode = SaveData.settings.touch;
    const isTouch = Platform.isIOS || ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
    const show = mode === 'on' || (mode === 'auto' && isTouch);
    document.getElementById('mobile-controls').classList.toggle('hidden', !show);
  }
};

window.unlockWpn = id => {
  const w = WEAPONS[id];
  if (SaveData.xp >= w.unlockCost) {
    SaveData.xp -= w.unlockCost; SaveData.unlockedWeapons.push(id); SaveData.equippedWeapon = id;
    saveGame(); UI.openArmory(); AudioSys.pickup();
  }
};
window.equipWpn = id => { SaveData.equippedWeapon = id; saveGame(); UI.openArmory(); AudioSys.reload(); };
window.upgradeWpn = id => {
  const cost = (SaveData.weaponLevels[id] || 1) * 180;
  if (SaveData.xp >= cost) { SaveData.xp -= cost; SaveData.weaponLevels[id]++; saveGame(); UI.openArmory(); AudioSys.pickup(); }
};
window.toggleFullscreen = () => {
  if (Platform.isIOS) {
    alert('On iPhone/iPad: Tap the Share button (↑) in Safari and select "Add to Home Screen" for full-screen app mode.');
    return;
  }
  if (!document.fullscreenElement) document.documentElement.requestFullscreen().catch(()=>{});
  else document.exitFullscreen();
};
window.resetProgress = () => {
  SaveData = JSON.parse(JSON.stringify(DefaultSave)); saveGame(); UI.refreshMenuTags(); alert('Campaign progress reset.');
};

document.getElementById('btn-new').onclick = () => Game.startLevel(0);
document.getElementById('btn-cont').onclick = () => Game.startLevel(SaveData.unlockedLevel - 1);
document.getElementById('btn-missions').onclick = () => UI.openMissions();
document.getElementById('btn-armory').onclick = () => UI.openArmory();
document.getElementById('btn-settings').onclick = () => UI.showScreen('settings-screen');
document.getElementById('btn-credits').onclick = () => UI.showScreen('credits-screen');
document.getElementById('btn-pause').onclick = () => Game.togglePause();

document.getElementById('set-music').value = SaveData.settings.music;
document.getElementById('set-sfx').value = SaveData.settings.sfx;
document.getElementById('set-gfx').value = SaveData.settings.gfx;
document.getElementById('set-touch').value = SaveData.settings.touch;
document.getElementById('set-music').oninput = e => { SaveData.settings.music = parseFloat(e.target.value); saveGame(); };
document.getElementById('set-sfx').oninput = e => { SaveData.settings.sfx = parseFloat(e.target.value); saveGame(); };
document.getElementById('set-gfx').onchange = e => { SaveData.settings.gfx = e.target.value; saveGame(); };
document.getElementById('set-touch').onchange = e => { SaveData.settings.touch = e.target.value; saveGame(); };

let lastTime = performance.now();
function loop(now) {
  const dt = Math.min(0.05, (now - lastTime) / 1000);
  lastTime = now;
  Game.update(dt);
  Game.render();
  requestAnimationFrame(loop);
}
UI.refreshMenuTags();
requestAnimationFrame(loop);
</script>
</body>
</html>

Game Source: SHADOW PROTOCOL

Creator: PlasmaStar57

Libraries: none

Complexity: complex (1329 lines, 67.6 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: shadow-protocol-plasmastar57" to link back to the original. Then publish at arcadelab.ai/publish.