This is good mama if even better: <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no,viewport-fit=cover" />
  <title>ULTRA CYBER-NEON SNAKE 2.0 - HYPER EDITION</title>
  <link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@700&display=swap" rel="stylesheet">
  <style>
    /* --- Reset & Base --- */
    *, *::before, *::after {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      touch-action: manipulation;
    }
    html, body {
      height: 100%;
      overflow: hidden;
      user-select: none;
      background: linear-gradient(135deg, #0f2027, #0c1a20, #0d1520);
      background-size: 600% 600%;
      animation: bgShift 20s ease infinite;
      font-family: 'Rajdhani', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #0f9;
      -webkit-tap-highlight-color: transparent;
    }
    @keyframes bgShift {
      0%, 100% { background-position: 0% 50%; }
      50% { background-position: 100% 50%; }
    }

    /* --- Neon Title --- */
    .title {
      font-size: 4.2rem;
      text-transform: uppercase;
      letter-spacing: 12px;
      margin: 15px 0 10px;
      text-align: center;
      text-shadow: 
        0 0 8px #0f9,
        0 0 16px #0f9,
        0 0 32px #0f9,
        0 0 64px #0ff,
        0 0 128px #0ff;
      animation: neonFlicker 3s infinite alternate;
      position: relative;
      font-weight: 900;
      z-index: 10;
      transform: skewY(-3deg);
    }
    .title span {
      color: #f0f;
      animation: neonFlickerPink 3s infinite alternate;
      text-shadow: 
        0 0 8px #f0f,
        0 0 16px #f0f,
        0 0 32px #f0f,
        0 0 64px #ff00ff,
        0 0 128px #ff00ff;
    }
    .subtitle {
      font-size: 2.2rem;
      color: #0ff;
      text-shadow: 0 0 15px #0ff, 0 0 30px #0ff;
      margin-bottom: 25px;
      text-align: center;
      animation: pulse 1.5s infinite;
      font-weight: 700;
      letter-spacing: 4px;
    }
    @keyframes pulse {
      0%, 100% { opacity: 0.7; transform: scale(0.95); }
      50% { opacity: 1; transform: scale(1.05); }
    }

    /* --- Game Container --- */
    main.game-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;
      max-width: 130vmin;
      position: relative;
      padding: 15px;
      user-select: none;
    }

    /* --- Game Frame --- */
    #game {
      position: relative;
      width: 110vmin;
      height: 110vmin;
      background: #111;
      border: 6px solid #0f9;
      border-radius: 30px;
      box-shadow: 
        inset 0 0 40px #0f9a,
        0 0 50px rgba(0, 255, 200, 0.75);
      touch-action: none;
      overflow: hidden;
      user-select: none;
    }
    canvas {
      width: 100%;
      height: 100%;
      display: block;
      background: transparent;
      border-radius: 30px;
      position: relative;
      z-index: 2;
      outline-offset: -5px;
      outline: none;
    }

    /* --- Neon Glow --- */
    .neon-glow {
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: radial-gradient(circle at center, rgba(0, 255, 200, 0.25), transparent 70%);
      z-index: 1;
      pointer-events: none;
      animation: rotateGlow 40s linear infinite;
      filter: blur(70px);
    }
    @keyframes rotateGlow {
      100% { transform: rotate(360deg); }
    }

    /* --- Neon Flicker Animations --- */
    @keyframes neonFlicker {
      0%, 18%, 22%, 25%, 53%, 57%, 100% {
        text-shadow:
          0 0 8px #0f9,
          0 0 16px #0f9,
          0 0 32px #0f9,
          0 0 64px #0ff,
          0 0 128px #0ff;
      }
      20%, 24%, 55% {
        text-shadow: none;
      }
    }
    @keyframes neonFlickerPink {
      0%, 18%, 22%, 25%, 53%, 57%, 100% {
        text-shadow:
          0 0 8px #f0f,
          0 0 16px #f0f,
          0 0 32px #f0f,
          0 0 64px #f0f,
          0 0 128px #f0f;
      }
      20%, 24%, 55% {
        text-shadow: none;
      }
    }

    /* --- Scoreboard --- */
    #scoreboard {
      margin-top: 20px;
      text-align: center;
      font-size: 2.2rem;
      font-weight: 800;
      animation: neonFlicker 3s infinite;
      padding: 20px 35px;
      border-radius: 25px;
      background: rgba(0, 20, 30, 0.85);
      box-shadow: 0 0 30px rgba(0, 255, 200, 0.75);
      display: flex;
      gap: 35px;
      letter-spacing: 2px;
      user-select: none;
      align-items: center;
      justify-content: center;
      min-width: 500px;
      position: relative;
      z-index: 20;
    }
    #scoreboard.flash {
      color: #fff;
      text-shadow:
        0 0 35px #0ff,
        0 0 70px #0ff,
        0 0 105px #0ff;
      background: rgba(0, 40, 60, 0.95);
      transform: scale(1.08);
      transition: all 0.3s ease;
    }
    #scoreboard.combo {
      animation: comboFlash 0.5s infinite alternate;
    }
    @keyframes comboFlash {
      0% { background: rgba(200, 0, 100, 0.8); }
      100% { background: rgba(255, 0, 150, 0.95); }
    }

    /* --- Controls --- */
    #controls {
      margin-top: 30px;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 22px;
      width: 110vmin;
      max-width: 500px;
      position: relative;
      z-index: 10;
      user-select: none;
    }
    .btn {
      background: linear-gradient(145deg, #0f9, #0c7);
      border: none;
      border-radius: 25px;
      padding: 24px 0;
      font-size: 1.9rem;
      font-weight: 900;
      box-shadow:
        0 0 30px #0f9,
        inset 0 0 12px rgba(255, 255, 255, 0.7);
      cursor: pointer;
      transition: all 0.25s ease;
      user-select: none;
      color: #000;
      outline: none;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    /* Focus visible outline for accessibility */
    .btn:focus-visible {
      outline: 4px solid #0cffaa;
      outline-offset: 3px;
    }
    .btn::before {
      content: '';
      position: absolute;
      top: -60%;
      left: -60%;
      width: 220%;
      height: 220%;
      background: rgba(255, 255, 255, 0.25);
      transform: rotate(45deg);
      transition: transform 0.5s ease;
      pointer-events: none;
    }
    .btn:hover,
    .btn:focus-visible {
      background: linear-gradient(145deg, #0cffaa, #0cffaa);
      box-shadow:
        0 0 60px #0cffaa,
        inset 0 0 22px rgba(255, 255, 255, 0.9);
      transform: scale(1.12);
      z-index: 20;
    }
    .btn:hover::before {
      transform: rotate(45deg) translate(140px, 140px);
    }
    .btn:active {
      background: linear-gradient(145deg, #0c7, #0a5);
      box-shadow:
        inset 0 0 50px #0c7,
        inset 0 0 25px rgba(0, 0, 0, 0.7);
      transform: scale(0.95);
      transition: none;
      z-index: 15;
    }
    @media (max-width: 700px) {
      .btn {
        font-size: 1.6rem;
        padding: 18px 0;
        border-radius: 20px;
      }
      #scoreboard {
        min-width: 350px;
        font-size: 1.8rem;
        padding: 15px 25px;
        gap: 20px;
      }
      #controls {
        max-width: 380px;
      }
      #game {
        width: 95vmin;
        height: 95vmin;
      }
      .title {
        font-size: 3.2rem;
        letter-spacing: 8px;
      }
      .subtitle {
        font-size: 1.8rem;
      }
    }

    /* --- Restart Button --- */
    #restartBtn, #soundToggleBtn, #pauseBtn {
      margin-top: 25px;
      background: linear-gradient(145deg, #0ff, #0cc);
      color: #000;
      border-radius: 25px;
      padding: 22px 0;
      font-size: 1.8rem;
      font-weight: 800;
      box-shadow:
        0 0 45px #0ff,
        inset 0 0 12px rgba(255, 255, 255, 0.8);
      cursor: pointer;
      user-select: none;
      width: 110vmin;
      max-width: 500px;
      display: none;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;
      border: none;
      text-transform: uppercase;
      letter-spacing: 2px;
    }
    #restartBtn:focus-visible, #soundToggleBtn:focus-visible, #pauseBtn:focus-visible {
      outline: 4px solid #0cc;
      outline-offset: 3px;
    }
    #restartBtn::before, #soundToggleBtn::before, #pauseBtn::before {
      content: '';
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: rgba(255, 255, 255, 0.25);
      transform: rotate(45deg);
      transition: transform 0.5s ease;
      pointer-events: none;
    }
    #restartBtn:hover, #restartBtn:focus-visible,
    #soundToggleBtn:hover, #soundToggleBtn:focus-visible,
    #pauseBtn:hover, #pauseBtn:focus-visible {
      background: linear-gradient(145deg, #0cc, #0aa);
      box-shadow:
        0 0 65px #0cc,
        inset 0 0 22px rgba(255, 255, 255, 0.85);
      transform: scale(1.08);
    }
    #restartBtn:hover::before, #soundToggleBtn:hover::before, #pauseBtn:hover::before {
      transform: rotate(45deg) translate(150px, 150px);
    }
    #restartBtn:active, #soundToggleBtn:active, #pauseBtn:active {
      background: linear-gradient(145deg, #099, #077);
      box-shadow:
        inset 0 0 50px #099,
        inset 0 0 25px rgba(0, 0, 0, 0.75);
      transform: scale(0.95);
      transition: none;
    }

    /* --- Combo Meter --- */
    #comboMeter {
      width: 110vmin;
      max-width: 500px;
      height: 20px;
      background: rgba(0, 20, 30, 0.85);
      border-radius: 15px;
      margin-top: 25px;
      overflow: hidden;
      position: relative;
      box-shadow: 0 0 22px rgba(0, 255, 200, 0.65);
      user-select: none;
      z-index: 20;
    }
    #comboBar {
      height: 100%;
      width: 0%;
      background: linear-gradient(90deg, #0f9, #f0f);
      border-radius: 15px;
      transition: width 0.3s ease;
      box-shadow: 0 0 15px rgba(0, 255, 200, 0.95);
    }

    /* --- Power-ups --- */
    .power-up {
      position: absolute;
      z-index: 5;
      animation: float 3s infinite ease-in-out;
      filter: drop-shadow(0 0 15px rgba(255, 255, 255, 0.97));
      user-select: none;
    }
    @keyframes float {
      0%, 100% { transform: translateY(0); }
      50% { transform: translateY(-20px); }
    }

    /* --- Game Over Screen --- */
    .game-over {
      position: absolute;
      top: 0; left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.97);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      z-index: 300;
      opacity: 0;
      pointer-events: none;
      transition: opacity 0.5s ease;
      user-select: none;
    }
    .game-over.show {
      opacity: 1;
      pointer-events: all;
    }
    .game-over h2 {
      font-size: 5.5rem;
      color: #f0f;
      text-shadow: 0 0 25px #f0f, 0 0 50px #f0f;
      margin-bottom: 45px;
      animation: neonFlickerPink 1.5s infinite alternate;
      letter-spacing: 8px;
      font-weight: 900;
      transform: skewY(-5deg);
    }
    .game-over p {
      font-size: 2.8rem;
      margin-bottom: 50px;
      color: #0ff;
      text-shadow: 0 0 18px #0ff;
      letter-spacing: 3px;
      user-select: all;
    }
    .game-over button.btn {
      max-width: 380px;
      width: 300px;
    }

    /* --- Snake Type Indicator --- */
    #snakeType {
      position: absolute;
      top: 20px;
      right: 20px;
      font-size: 1.3rem;
      background: rgba(0, 20, 30, 0.9);
      padding: 12px 25px;
      border-radius: 35px;
      color: #0ff;
      text-shadow: 0 0 12px #0ff;
      z-index: 15;
      box-shadow: 0 0 25px rgba(0, 255, 200, 0.65);
      font-weight: 900;
      letter-spacing: 2px;
      user-select: none;
      font-family: 'Rajdhani', sans-serif;
      text-transform: uppercase;
      pointer-events: none;
      border: 2px solid #0ff;
    }

    /* --- Level Indicator --- */
    #levelIndicator {
      position: absolute;
      top: 20px;
      left: 20px;
      font-size: 1.3rem;
      background: rgba(0, 20, 30, 0.9);
      padding: 12px 25px;
      border-radius: 35px;
      color: #0ff;
      text-shadow: 0 0 12px #0ff;
      z-index: 15;
      box-shadow: 0 0 25px rgba(0, 255, 200, 0.65);
      font-weight: 900;
      letter-spacing: 2px;
      user-select: none;
      font-family: 'Rajdhani', sans-serif;
      pointer-events: none;
      border: 2px solid #0ff;
    }

    /* --- Cyber Grid --- */
    .cyber-grid {
      position: absolute;
      top: 0; left: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
      pointer-events: none;
      opacity: 0.25;
      background:
        repeating-linear-gradient(
          0deg,
          transparent,
          transparent 15px,
          rgba(0, 255, 200, 0.15) 15px,
          rgba(0, 255, 200, 0.15) 30px
        ),
        repeating-linear-gradient(
          90deg,
          transparent,
          transparent 15px,
          rgba(0, 255, 200, 0.15) 15px,
          rgba(0, 255, 200, 0.15) 30px
        );
    }

    /* --- Power-up Timer --- */
    .power-timer {
      position: absolute;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      width: 75%;
      height: 16px;
      background: rgba(0, 20, 30, 0.85);
      border-radius: 10px;
      overflow: hidden;
      z-index: 15;
      box-shadow: 0 0 20px rgba(0, 255, 200, 0.45);
      display: none;
      user-select: none;
    }
    .power-timer-bar {
      height: 100%;
      width: 100%;
      background: linear-gradient(90deg, #0f9, #f0f);
      transition: width 0.1s linear;
      border-radius: 10px;
    }

    /* --- Shield Effect --- */
    .shield-effect {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 115%;
      height: 115%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
      border: 5px solid rgba(0, 200, 255, 0.6);
      box-shadow: 0 0 50px rgba(0, 200, 255, 0.95);
      animation: shieldPulse 2s infinite;
      pointer-events: none;
      z-index: 8;
      filter: drop-shadow(0 0 18px #0ff);
    }
    @keyframes shieldPulse {
      0%, 100% { transform: translate(-50%, -50%) scale(0.9); opacity: 0.5; }
      50% { transform: translate(-50%, -50%) scale(1.1); opacity: 0.8; }
    }

    /* --- Laser Effect --- */
    .laser-beam {
      position: absolute;
      background: linear-gradient(90deg, rgba(255,85,0,0.7), rgba(255,200,0,0.9), rgba(255,85,0,0.7));
      border-radius: 8px;
      z-index: 7;
      box-shadow: 0 0 30px rgba(255,85,0,0.95);
      pointer-events: none;
      opacity: 0.95;
      animation: laserPulse 0.3s infinite alternate;
    }
    @keyframes laserPulse {
      from { opacity: 0.8; }
      to { opacity: 1; }
    }

    /* --- Time Warp Effect --- */
    .time-warp-effect {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: radial-gradient(circle, rgba(150, 0, 255, 0.3), transparent 70%);
      z-index: 9;
      pointer-events: none;
      opacity: 0;
      transition: opacity 0.5s ease;
    }
    .time-warp-effect.active {
      opacity: 0.7;
    }

    /* --- Portal Effect --- */
    .portal {
      position: absolute;
      z-index: 6;
      animation: portalSpin 10s infinite linear;
      filter: drop-shadow(0 0 20px rgba(255, 255, 255, 0.9));
      pointer-events: none;
    }
    @keyframes portalSpin {
      100% { transform: rotate(360deg); }
    }

    /* --- Hyper Mode Effect --- */
    .hyper-mode {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: radial-gradient(circle, rgba(255, 0, 150, 0.25), transparent 60%);
      z-index: 10;
      pointer-events: none;
      opacity: 0;
      animation: hyperPulse 0.8s infinite alternate;
    }
    @keyframes hyperPulse {
      from { opacity: 0.2; }
      to { opacity: 0.5; }
    }
    .hyper-mode.active {
      opacity: 0.3;
    }

    /* --- Mobile Controls Notice --- */
    .mobile-notice {
      margin-top: 15px;
      color: #0f9;
      text-align: center;
      font-size: 1.3rem;
      text-shadow: 0 0 8px #0f9;
      display: none;
      max-width: 110vmin;
      user-select: none;
      padding: 10px 20px;
      background: rgba(0, 20, 30, 0.7);
      border-radius: 15px;
      box-shadow: 0 0 15px rgba(0, 255, 200, 0.5);
    }
  </style>
</head>
<body>
  <div class="neon-glow"></div>
  <div class="cyber-grid"></div>
  <div class="time-warp-effect" id="timeWarpEffect"></div>
  <div class="hyper-mode" id="hyperMode"></div>

  <h1 class="title" aria-label="Game title: Ultra Cyber Snake 2.0">
    ULTRA <span>CYBER</span> SNAKE 2.0
  </h1>
  <div class="subtitle" id="subtitle">HYPER EDITION - NEXT LEVEL GAMEPLAY!</div>

  <main class="game-container" role="main">
    <section id="game" role="region" aria-label="Snake game area" tabindex="-1">
      <canvas id="canvas" tabindex="0" aria-live="polite" aria-label="Game canvas"></canvas>

      <div id="snakeType" aria-live="polite" aria-atomic="true">NORMAL</div>
      <div id="levelIndicator">LEVEL: <span id="currentLevel">1</span></div>

      <div class="power-timer" id="powerTimer" aria-hidden="true" title="Power-up time left">
        <div class="power-timer-bar" id="powerTimerBar"></div>
      </div>

      <div class="game-over" id="gameOverScreen" role="dialog" aria-modal="true" aria-labelledby="gameOverTitle" tabindex="-1">
        <h2 id="gameOverTitle">GAME OVER</h2>
        <p>SCORE: <span id="finalScore">0</span></p>
        <button id="restartBtn2" class="btn" type="button" aria-label="Restart game">PLAY AGAIN</button>
      </div>
    </section>

    <div id="scoreboard" aria-live="polite" aria-atomic="true" role="status" aria-label="Scoreboard">
      <div>SCORE: <span id="currentScore">0</span></div>
      <div>HIGH: <span id="highScore">0</span></div>
    </div>

    <div id="comboMeter" aria-hidden="true" title="Combo meter">
      <div id="comboBar"></div>
    </div>

    <nav id="controls" aria-label="Directional controls">
      <button class="btn" data-dir="left" aria-label="Move left" type="button">←</button>
      <button class="btn" data-dir="up" aria-label="Move up" type="button">↑</button>
      <button class="btn" data-dir="down" aria-label="Move down" type="button">↓</button>
      <button class="btn" data-dir="right" aria-label="Move right" type="button">→</button>
    </nav>

    <button id="pauseBtn" type="button" aria-label="Pause or resume game">PAUSE GAME</button>
    <button id="restartBtn" type="button" aria-label="Restart game">RESTART GAME</button>
    <button id="soundToggleBtn" type="button" aria-label="Toggle sound effects">SOUND: ON</button>

    <div class="mobile-notice" id="mobileNotice" aria-hidden="true">Swipe or tap buttons to control the snake</div>
  </main>

  <!-- Audio elements aria-hidden -->
  <audio id="eatSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
  <audio id="powerSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
  <audio id="gameOverSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
  <audio id="levelUpSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
  <audio id="laserSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
  <audio id="portalSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>
  <audio id="hyperSfx" preload="auto" aria-hidden="true" tabindex="-1"></audio>

  <script>
  (() => {
    const AudioCtx = window.AudioContext || window.webkitAudioContext;
    let audioContext;
    let soundAllowed = true;

    // Prepare audio context on user gesture
    function initAudioContext() {
      if(!audioContext) {
        audioContext = new AudioCtx();
      }
    }

    // Sound generation functions
    function playOscillator({type='sine', frequencyStart, frequencyEnd, duration, gain=0.3}) {
      if (!soundAllowed) return;
      try {
        if (!audioContext) initAudioContext();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();

        oscillator.type = type;
        oscillator.frequency.setValueAtTime(frequencyStart, audioContext.currentTime);
        if (frequencyEnd) {
          oscillator.frequency.exponentialRampToValueAtTime(frequencyEnd, audioContext.currentTime + duration);
        }

        gainNode.gain.setValueAtTime(gain, audioContext.currentTime);
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.start();
        gainNode.gain.exponentialRampToValueAtTime(0.00001, audioContext.currentTime + duration);
        oscillator.stop(audioContext.currentTime + duration + 0.05);

        oscillator.onended = () => {
          oscillator.disconnect();
          gainNode.disconnect();
        };
      } catch (e) {
        // Fail silently
      }
    }

    function generateEatSound() {
      playOscillator({frequencyStart: 523.25, duration: 0.3});
    }

    function generatePowerSound() {
      playOscillator({frequencyStart: 220, frequencyEnd: 880, duration: 0.5});
    }

    function generateGameOverSound() {
      playOscillator({frequencyStart: 349.23, frequencyEnd: 130.81, duration: 0.7, gain: 0.4});
    }

    function generateLevelUpSound() {
      playOscillator({frequencyStart: 523.25, frequencyEnd: 1046.5, duration: 0.5});
    }

    function generateLaserSound() {
      playOscillator({type: 'square', frequencyStart: 880, frequencyEnd: 220, duration: 0.1});
    }

    function generatePortalSound() {
      playOscillator({type: 'sawtooth', frequencyStart: 220, frequencyEnd: 880, duration: 0.8, gain: 0.3});
    }

    function generateHyperSound() {
      playOscillator({type: 'sine', frequencyStart: 220, frequencyEnd: 1760, duration: 0.7, gain: 0.4});
    }

    // DOM references
    const game = document.getElementById('game');
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const scoreEl = document.getElementById('currentScore');
    const highEl = document.getElementById('highScore');
    const scoreboard = document.getElementById('scoreboard');
    const comboBar = document.getElementById('comboBar');
    const snakeType = document.getElementById('snakeType');
    const levelIndicator = document.getElementById('currentLevel');
    const btns = document.querySelectorAll('.btn[data-dir]');
    const restartBtn = document.getElementById('restartBtn');
    const restartBtn2 = document.getElementById('restartBtn2');
    const gameOverScreen = document.getElementById('gameOverScreen');
    const finalScore = document.getElementById('finalScore');
    const powerTimer = document.getElementById('powerTimer');
    const powerTimerBar = document.getElementById('powerTimerBar');
    const mobileNotice = document.getElementById('mobileNotice');
    const pauseBtn = document.getElementById('pauseBtn');
    const soundToggleBtn = document.getElementById('soundToggleBtn');
    const subtitle = document.getElementById('subtitle');
    const timeWarpEffect = document.getElementById('timeWarpEffect');
    const hyperMode = document.getElementById('hyperMode');

    // Enhanced game configuration
    const tileCount = 40;           // Bigger board
    let gridSize;
    const baseFps = 12;             // Balanced speed
    let currentFps = baseFps;
    const maxApples = 8;            // More apples for bigger board

    // Game state
    let snake, velocity, nextVel, apples, score, gameOver;
    let comboCounter, lastAppleTime, hue;
    let effects;
    let highScore = parseInt(localStorage.getItem('snakeHighScore'), 10) || 0;
    let powerUps = [];
    let snakeMode = 'normal';
    let powerUpActive = false;
    let powerUpEndTime = 0;
    let level = 1;
    let trailParticles = [];
    let shieldHits = 0;
    let laserShotsLeft = 0;
    let laserCooldown = false;
    let paused = false;
    let portals = [];
    let hyperModeActive = false;
    let hyperModeEndTime = 0;

    highEl.textContent = highScore;
    levelIndicator.textContent = level;

    // Show mobile notice if touch device
    if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
      mobileNotice.style.display = 'block';
      mobileNotice.setAttribute('aria-hidden', 'false');
    }

    // Resize canvas and grid dynamically
    function resizeCanvas() {
      const size = Math.min(game.clientWidth, game.clientHeight);
      canvas.width = size;
      canvas.height = size;
      gridSize = size / tileCount;
    }
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    /* HELPERS */
    function colorGradient(isSnake) {
      hue = (hue + 4) % 360;
      if (isSnake) {
        const c1 = `hsl(${hue},100%,65%)`;
        const c2 = `hsl(${(hue + 45) % 360},100%,75%)`;
        const grad = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        grad.addColorStop(0, c1);
        grad.addColorStop(1, c2);
        return grad;
      } else {
        const grad = ctx.createRadialGradient(0, 0, 5, 0, 0, gridSize * 0.6);
        grad.addColorStop(0, `hsl(${hue},100%,85%)`);
        grad.addColorStop(1, `hsl(${(hue + 70) % 360},80%,55%)`);
        return grad;
      }
    }
    function roundedRect(x, y, w, h, r) {
      ctx.beginPath();
      ctx.moveTo(x + r, y);
      ctx.lineTo(x + w - r, y);
      ctx.quadraticCurveTo(x + w, y, x + w, y + r);
      ctx.lineTo(x + w, y + h - r);
      ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
      ctx.lineTo(x + r, y + h);
      ctx.quadraticCurveTo(x, y + h, x, y + h - r);
      ctx.lineTo(x, y + r);
      ctx.quadraticCurveTo(x, y, x + r, y);
      ctx.closePath();
      ctx.fill();
    }
    function isEmpty(x, y) {
      return !snake.some(s => s.x === x && s.y === y) &&
        !apples.some(a => a.x === x && a.y === y) &&
        !powerUps.some(p => p.x === x && p.y === y) &&
        !portals.some(p => p.x === x && p.y === y);
    }

    // Spawn apples and power-ups
    function spawnApples() {
      while (apples.length < maxApples) {
        const p = {
          x: Math.floor(Math.random() * tileCount),
          y: Math.floor(Math.random() * tileCount),
        };
        if (isEmpty(p.x, p.y)) apples.push(p);
      }

      // Spawn power-ups more frequently
      if (Math.random() < 0.18 && !powerUpActive && powerUps.length === 0) {
        const types = ['speed', 'ghost', 'shield', 'laser', 'portal', 'hyper'];
        const candidate = {
          x: Math.floor(Math.random() * tileCount),
          y: Math.floor(Math.random() * tileCount),
          type: types[Math.floor(Math.random() * types.length)],
        };
        if (isEmpty(candidate.x, candidate.y)) powerUps.push(candidate);
      }
    }

    // Spawn portals (appear at level 5+)
    function spawnPortals() {
      if (level < 5 || portals.length > 0) return;
      
      // Find two empty positions
      let pos1 = null, pos2 = null;
      let attempts = 0;
      
      while ((!pos1 || !pos2) && attempts < 50) {
        const p = {
          x: Math.floor(Math.random() * tileCount),
          y: Math.floor(Math.random() * tileCount)
        };
        
        if (isEmpty(p.x, p.y)) {
          if (!pos1) {
            pos1 = p;
          } else if (!pos2 && 
                    (Math.abs(pos1.x - p.x) > 10 || Math.abs(pos1.y - p.y) > 10)) {
            pos2 = p;
          }
        }
        attempts++;
      }
      
      if (pos1 && pos2) {
        portals.push({...pos1, id: 1});
        portals.push({...pos2, id: 2});
        generatePortalSound();
      }
    }

    // Effects
    function addScoreFx(x, y, amt) {
      effects.score.push({
        x: x * gridSize + gridSize / 2,
        y: y * gridSize + gridSize / 2,
        alpha: 1,
        text: '+' + amt,
        size: 32,
      });
    }
    function addParticles(x, y, color) {
      for (let i = 0; i < 45; i++) {
        effects.particles.push({
          x: x * gridSize + gridSize / 2,
          y: y * gridSize + gridSize / 2,
          dx: (Math.random() - 0.5) * 15,
          dy: (Math.random() - 0.5) * 15,
          alpha: 1,
          size: Math.random() * 8 + 4,
          color: color || `hsla(${(hue + i * 15) % 360}, 100%, 75%, 1)`,
        });
      }
    }
    function updateEffects() {
      for (let i = effects.score.length - 1; i >= 0; i--) {
        const e = effects.score[i];
        e.y -= 2.5;
        e.alpha -= 0.03;
        e.size += 0.4;
        if (e.alpha <= 0) effects.score.splice(i, 1);
      }
      for (let i = effects.particles.length - 1; i >= 0; i--) {
        const p = effects.particles[i];
        p.x += p.dx;
        p.y += p.dy;
        p.alpha -= 0.04;
        if (p.alpha <= 0) effects.particles.splice(i, 1);
      }
    }
    function flashScore() {
      scoreboard.classList.add('flash');
      setTimeout(() => scoreboard.classList.remove('flash'), 300);
      generateEatSound();
    }
    function flashCombo() {
      scoreboard.classList.add('combo');
      setTimeout(() => scoreboard.classList.remove('combo'), 800);
    }

    // Trail particles for snake movement effect
    function addTrailParticle(x, y) {
      trailParticles.push({
        x: x * gridSize + gridSize / 2,
        y: y * gridSize + gridSize / 2,
        size: gridSize * (0.8 + Math.random() * 0.4),
        alpha: 0.75,
        hue: (hue + Math.random() * 60) % 360,
        life: 25,
      });
    }
    function updateTrailParticles() {
      for (let i = trailParticles.length - 1; i >= 0; i--) {
        const p = trailParticles[i];
        p.alpha -= 0.03;
        p.size -= 0.25;
        p.life--;
        if (p.life <= 0 || p.alpha <= 0) trailParticles.splice(i, 1);
      }
    }
    function drawTrailParticles() {
      for (let p of trailParticles) {
        ctx.globalAlpha = p.alpha;
        ctx.fillStyle = `hsla(${p.hue}, 100%, 70%, ${p.alpha})`;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.size / 2, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.globalAlpha = 1;
    }

    // Laser shot effect and logic
    function shootLaser() {
      if (laserShotsLeft <= 0 || laserCooldown) return;
      laserShotsLeft--;
      laserCooldown = true;
      setTimeout(() => laserCooldown = false, 150); // Prevent super spam

      const head = snake[0];
      const targetX = (head.x + velocity.x + tileCount) % tileCount;
      const targetY = (head.y + velocity.y + tileCount) % tileCount;

      // Visual laser line for short duration
      laserVisuals.push({
        fromX: head.x * gridSize + gridSize / 2,
        fromY: head.y * gridSize + gridSize / 2,
        toX: targetX * gridSize + gridSize / 2,
        toY: targetY * gridSize + gridSize / 2,
        alpha: 1,
        life: 12,
      });

      try {
        generateLaserSound();
      } catch {}
    }

    let laserVisuals = [];

    // Time Warp power-up effect
    function activateTimeWarp() {
      timeWarpEffect.classList.add('active');
      const originalFps = currentFps;
      currentFps = baseFps * 0.5; // Slow down time
      interval = 1000 / currentFps;
      
      setTimeout(() => {
        timeWarpEffect.classList.remove('active');
        currentFps = originalFps;
        interval = 1000 / currentFps;
      }, 8000);
    }

    // Hyper Mode power-up effect
    function activateHyperMode() {
      hyperMode.classList.add('active');
      hyperModeActive = true;
      hyperModeEndTime = Date.now() + 12000;
      
      // Make snake faster and invincible
      const originalFps = currentFps;
      currentFps = baseFps * 2.5;
      interval = 1000 / currentFps;
      
      setTimeout(() => {
        hyperMode.classList.remove('active');
        hyperModeActive = false;
        currentFps = originalFps;
        interval = 1000 / currentFps;
      }, 12000);
    }

    // Main game update loop
    function update() {
      if (gameOver || paused) return;

      // Power-up timer
      if (powerUpActive) {
        const timeLeft = powerUpEndTime - Date.now();
        if (timeLeft > 0) {
          powerTimerBar.style.width = (timeLeft / 10000 * 100) + '%';
        } else {
          powerUpActive = false;
          if (snakeMode === 'shield') shieldHits = 0;
          if (snakeMode === 'laser') laserShotsLeft = 0;
          snakeMode = 'normal';
          snakeType.textContent = 'NORMAL';
          snakeType.style.color = '#0ff';
          powerTimer.style.display = 'none';
          currentFps = baseFps;
          subtitle.textContent = 'HYPER EDITION - NEXT LEVEL GAMEPLAY!';
        }
      }

      // Apply nextVel only if not reversing
      if (nextVel.x !== -velocity.x || nextVel.y !== -velocity.y) {
        velocity = nextVel;
      }

      const head = {
        x: (snake[0].x + velocity.x + tileCount) % tileCount,
        y: (snake[0].y + velocity.y + tileCount) % tileCount,
      };

      // Handle collisions
      if (!['ghost', 'shield', 'laser'].includes(snakeMode) &&
        snake.some((p, i) => i > 0 && p.x === head.x && p.y === head.y) &&
        !hyperModeActive) {
        gameOver = true;
        showGameOver();
        return;
      } else if (snakeMode === 'shield' && snake.some((p, i) => i > 0 && p.x === head.x && p.y === head.y) &&
                !hyperModeActive) {
        // Shield absorbs one collision
        shieldHits++;
        if (shieldHits >= 2) {
          // Shield broken for rest of power-up period
          powerUpActive = false;
          snakeMode = 'normal';
          snakeType.textContent = 'NORMAL';
          snakeType.style.color = '#0ff';
          powerTimer.style.display = 'none';
          currentFps = baseFps;
        }
        // Remove last snake segment instead of game over
        snake.pop();
      }

      // Check portal collision
      for (let i = 0; i < portals.length; i++) {
        if (portals[i].x === head.x && portals[i].y === head.y) {
          // Find the connected portal
          const connectedPortal = portals.find(p => p.id !== portals[i].id);
          if (connectedPortal) {
            // Teleport snake head to connected portal
            head.x = connectedPortal.x;
            head.y = connectedPortal.y;
            generatePortalSound();
            break;
          }
        }
      }

      addTrailParticle(snake[0].x, snake[0].y);
      snake.unshift(head);

      let ateApple = false;
      let collectedPower = false;

      // Eat apples
      for (let i = 0; i < apples.length; i++) {
        if (apples[i].x === head.x && apples[i].y === head.y) {
          const now = Date.now();
          const timeBonus = (now - lastAppleTime < 2500) ? 8 : 0;
          const comboBonus = comboCounter * 5;
          const gain = 15 + timeBonus + comboBonus;
          score += gain;
          comboCounter++;
          lastAppleTime = now;
          comboBar.style.width = Math.min(100, comboCounter * 12) + '%';
          if (comboCounter >= 3) flashCombo();
          scoreEl.textContent = score;

          // Level up every 80 points
          const newLevel = Math.floor(score / 80) + 1;
          if (newLevel > level) {
            level = newLevel;
            levelIndicator.textContent = level;
            generateLevelUpSound();
            // Increase speed by 10% per level
            currentFps = baseFps * Math.min(3.5, 1 + (level - 1) * 0.1);
            if (!powerUpActive) interval = 1000 / currentFps; // sync fps interval
            subtitle.textContent = `LEVEL ${level} - ULTRA CYBER CHALLENGE!`;
            spawnPortals();
          }

          if (score > highScore) {
            highScore = score;
            localStorage.setItem('snakeHighScore', highScore);
            highEl.textContent = highScore;
          }

          addScoreFx(head.x, head.y, gain);
          addParticles(head.x, head.y);
          flashScore();
          apples.splice(i, 1);
          spawnApples();
          ateApple = true;
          break;
        }
      }

      // Collect power-ups
      for (let i = 0; i < powerUps.length; i++) {
        if (powerUps[i].x === head.x && powerUps[i].y === head.y) {
          snakeMode = powerUps[i].type;
          powerUpActive = true;
          powerUpEndTime = Date.now() + 10000;
          snakeType.textContent = snakeMode.toUpperCase();

          const typeColors = {
            speed: '#0f9',
            ghost: '#f0f',
            shield: '#0ff',
            laser: '#ff5500',
            portal: '#ff00ff',
            hyper: '#ff5500'
          };
          snakeType.style.color = typeColors[snakeMode] || '#0ff';
          powerTimer.style.display = 'block';
          powerTimerBar.style.width = '100%';

          // Reset shield & laser states
          shieldHits = 0;
          laserShotsLeft = 5;

          subtitle.textContent = `POWER-UP: ${snakeMode.toUpperCase()} - ACTIVE!`;

          if (snakeMode === 'speed') {
            currentFps = baseFps * 2.5;
          } else if (snakeMode === 'hyper') {
            activateHyperMode();
          } else if (snakeMode === 'portal') {
            spawnPortals();
          } else {
            currentFps = baseFps * 1.2;
          }

          // Particles color based on power-up
          let particleColor;
          switch (snakeMode) {
            case 'speed': particleColor = 'rgba(0,255,150,1)'; break;
            case 'ghost': particleColor = 'rgba(255,0,200,1)'; break;
            case 'shield': particleColor = 'rgba(0,200,255,1)'; break;
            case 'laser': particleColor = 'rgba(255,85,0,1)'; break;
            case 'portal': particleColor = 'rgba(255,0,255,1)'; break;
            case 'hyper': particleColor = 'rgba(255,150,0,1)'; break;
            default: particleColor = null;
          }

          addParticles(head.x, head.y, particleColor);
          generatePowerSound();
          powerUps.splice(i, 1);
          collectedPower = true;
          break;
        }
      }

      if (!ateApple && !collectedPower) {
        comboCounter = 0;
        comboBar.style.width = '0%';
        snake.pop();
      }

      // Update trail 
      updateTrailParticles();

      // Update laser visuals alpha and cleanup
      laserVisuals.forEach(l => {
        l.alpha -= 0.08;
        l.life--;
      });
      laserVisuals = laserVisuals.filter(l => l.alpha > 0 && l.life > 0);
    }

    // Drawing function
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      drawTrailParticles();

      // Draw grid background
      ctx.strokeStyle = 'rgba(0, 200, 180, 0.15)';
      ctx.lineWidth = 1;
      for (let i = 0; i <= tileCount; i++) {
        const pos = i * gridSize;
        ctx.beginPath();
        ctx.moveTo(pos, 0);
        ctx.lineTo(pos, canvas.height);
        ctx.moveTo(0, pos);
        ctx.lineTo(canvas.width, pos);
        ctx.stroke();
      }

      // Draw portals
      portals.forEach(p => {
        const cx = p.x * gridSize + gridSize / 2;
        const cy = p.y * gridSize + gridSize / 2;
        ctx.save();
        ctx.translate(cx, cy);
        ctx.rotate(Date.now() * 0.001 * (p.id === 1 ? 1 : -1));
        
        ctx.shadowColor = '#ff00ff';
        ctx.shadowBlur = 30;
        
        // Outer ring
        ctx.strokeStyle = '#f0f';
        ctx.lineWidth = 6;
        ctx.beginPath();
        ctx.arc(0, 0, gridSize * 0.8, 0, Math.PI * 2);
        ctx.stroke();
        
        // Inner ring
        ctx.strokeStyle = '#0ff';
        ctx.lineWidth = 4;
        ctx.beginPath();
        ctx.arc(0, 0, gridSize * 0.6, 0, Math.PI * 2);
        ctx.stroke();
        
        // Portal center
        ctx.fillStyle = '#ff00ff';
        ctx.beginPath();
        ctx.arc(0, 0, gridSize * 0.4, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.restore();
      });

      // Draw power-ups
      powerUps.forEach(p => {
        const cx = p.x * gridSize + gridSize / 2;
        const cy = p.y * gridSize + gridSize / 2;
        ctx.save();
        ctx.translate(cx, cy);
        ctx.rotate(Date.now() * 0.002);

        ctx.shadowColor = p.type === 'speed' ? '#0f9' : 
                          p.type === 'ghost'  ? '#f0f' : 
                          p.type === 'laser'  ? '#ff5500' : 
                          p.type === 'portal' ? '#ff00ff' :
                          p.type === 'hyper'  ? '#ff5500' : '#0ff';
        ctx.shadowBlur = 28;

        if (p.type === 'speed') {
          // Lightning bolt shape
          ctx.fillStyle = '#0ff';
          ctx.beginPath();
          ctx.moveTo(0, -gridSize*0.35);
          ctx.lineTo(gridSize*0.3, 0);
          ctx.lineTo(0, gridSize*0.35);
          ctx.lineTo(-gridSize*0.3, 0);
          ctx.closePath();
          ctx.fill();
        } else if (p.type === 'ghost') {
          // Ghost shape
          ctx.fillStyle = '#f0f';
          ctx.beginPath();
          ctx.arc(0, 0, gridSize*0.35, 0, Math.PI);
          ctx.lineTo(gridSize*0.35, gridSize*0.35);
          ctx.quadraticCurveTo(gridSize*0.15, gridSize*0.55, 0, gridSize*0.35);
          ctx.quadraticCurveTo(-gridSize*0.15, gridSize*0.55, -gridSize*0.35, gridSize*0.35);
          ctx.closePath();
          ctx.fill();

          // Eyes
          ctx.fillStyle = '#000';
          ctx.beginPath();
          ctx.arc(-gridSize*0.15, -gridSize*0.12, gridSize*0.09, 0, Math.PI*2);
          ctx.arc(gridSize*0.15, -gridSize*0.12, gridSize*0.09, 0, Math.PI*2);
          ctx.fill();
        } else if (p.type === 'laser') {
          // Laser power-up
          ctx.fillStyle = '#ff5500';
          ctx.beginPath();
          ctx.arc(0, 0, gridSize*0.35, 0, Math.PI*2);
          ctx.fill();

          ctx.strokeStyle = '#ff9900';
          ctx.lineWidth = 5;
          ctx.beginPath();
          ctx.moveTo(-gridSize*0.3, 0);
          ctx.lineTo(gridSize*0.3, 0);
          ctx.moveTo(0, -gridSize*0.3);
          ctx.lineTo(0, gridSize*0.3);
          ctx.stroke();
        } else if (p.type === 'portal') {
          // Portal power-up
          ctx.fillStyle = '#ff00ff';
          ctx.beginPath();
          ctx.arc(0, 0, gridSize*0.4, 0, Math.PI*2);
          ctx.fill();
          
          ctx.strokeStyle = '#0ff';
          ctx.lineWidth = 4;
          ctx.beginPath();
          ctx.arc(0, 0, gridSize*0.5, 0, Math.PI*2);
          ctx.stroke();
        } else if (p.type === 'hyper') {
          // Hyper power-up
          ctx.fillStyle = '#ff5500';
          ctx.beginPath();
          ctx.arc(0, 0, gridSize*0.4, 0, Math.PI*2);
          ctx.fill();
          
          ctx.strokeStyle = '#ffcc00';
          ctx.lineWidth = 5;
          ctx.beginPath();
          ctx.moveTo(-gridSize*0.3, -gridSize*0.3);
          ctx.lineTo(gridSize*0.3, gridSize*0.3);
          ctx.moveTo(gridSize*0.3, -gridSize*0.3);
          ctx.lineTo(-gridSize*0.3, gridSize*0.3);
          ctx.stroke();
        } else {
          // Shield shape
          ctx.fillStyle = '#0ff';
          ctx.beginPath();
          ctx.arc(0, 0, gridSize*0.4, 0, Math.PI*2);
          ctx.fill();

          ctx.fillStyle = '#111';
          ctx.beginPath();
          ctx.arc(0, 0, gridSize*0.3, 0, Math.PI*2);
          ctx.fill();

          ctx.strokeStyle = '#0ff';
          ctx.lineWidth = 5;
          ctx.beginPath();
          ctx.arc(0, 0, gridSize*0.35, 0, Math.PI*2);
          ctx.stroke();
        }

        ctx.restore();
      });

      // Draw apples
      apples.forEach(a => {
        const cx = a.x * gridSize + gridSize / 2;
        const cy = a.y * gridSize + gridSize / 2;
        ctx.save();
        ctx.translate(cx, cy);
        const scale = 0.95 + 0.15 * Math.sin(Date.now() / 120);
        ctx.scale(scale, scale);
        ctx.shadowColor = '#f33';
        ctx.shadowBlur = 25;
        ctx.fillStyle = colorGradient(false);
        ctx.beginPath();
        ctx.ellipse(0, 0, gridSize*0.5, gridSize*0.65, Math.PI/6, 0, 2*Math.PI);
        ctx.fill();
        ctx.fillStyle = '#282';
        ctx.beginPath();
        ctx.ellipse(0, -gridSize*0.35, gridSize*0.2, gridSize*0.4, Math.PI/4, 0, 2*Math.PI);
        ctx.fill();
        ctx.restore();
      });

      // Draw snake
      snake.forEach((s, i) => {
        const px = s.x * gridSize, py = s.y * gridSize;
        ctx.save();

        // Opacity gradient from head to tail
        let alpha = 1 - (i / snake.length) * 0.8;
        alpha = Math.min(1, Math.max(0.2, alpha));

        ctx.globalAlpha = alpha;

        // Snake color per mode
        if (snakeMode === 'speed') {
          ctx.fillStyle = `hsl(${(hue + i * 15) % 360}, 100%, 65%)`;
        } else if (snakeMode === 'ghost') {
          ctx.fillStyle = `hsla(${(hue + 240 + i * 15) % 360}, 100%, 75%, ${alpha})`;
        } else if (snakeMode === 'shield') {
          ctx.fillStyle = `hsla(${(hue + 180 + i * 15) % 360}, 100%, 62%, ${alpha})`;
        } else if (snakeMode === 'laser') {
          ctx.fillStyle = `hsla(${(hue + 30 + i * 15) % 360}, 100%, 62%, ${alpha})`;
        } else if (snakeMode === 'portal') {
          ctx.fillStyle = `hsla(${(hue + 300 + i * 15) % 360}, 100%, 65%, ${alpha})`;
        } else if (hyperModeActive) {
          ctx.fillStyle = `hsla(${(hue + 45 + i * 15) % 360}, 100%, 70%, ${alpha})`;
        } else {
          ctx.fillStyle = colorGradient(true);
        }

        ctx.shadowColor = snakeMode === 'ghost' ? '#f0f' :
                          snakeMode === 'laser' ? '#ff5500' : 
                          snakeMode === 'portal' ? '#ff00ff' :
                          hyperModeActive ? '#ff5500' : '#0ff';
        ctx.shadowBlur = (i === 0 ? 35 : 25);

        roundedRect(px + 4, py + 4, gridSize - 8, gridSize - 8, 12);

        // Draw snake eyes on head
        if (i === 0) {
          const eyeSize = gridSize * 0.2;
          ctx.fillStyle = '#000';
          ctx.globalAlpha = 1;

          // Eyes
          ctx.beginPath();
          ctx.arc(px + gridSize * 0.35, py + gridSize * 0.45, eyeSize, 0, Math.PI * 2);
          ctx.arc(px + gridSize * 0.72, py + gridSize * 0.45, eyeSize, 0, Math.PI * 2);
          ctx.fill();

          // Pupils follow velocity direction
          ctx.fillStyle = snakeMode === 'laser' || hyperModeActive ? '#ff5500' : '#fff';
          const pupilOffsetX = velocity.x * eyeSize * 0.7;
          const pupilOffsetY = velocity.y * eyeSize * 0.7;

          ctx.beginPath();
          ctx.arc(px + gridSize * 0.35 + pupilOffsetX, py + gridSize * 0.45 + pupilOffsetY, eyeSize * 0.6, 0, Math.PI * 2);
          ctx.arc(px + gridSize * 0.72 + pupilOffsetX, py + gridSize * 0.45 + pupilOffsetY, eyeSize * 0.6, 0, Math.PI * 2);
          ctx.fill();

          // Laser eyes effect
          if (snakeMode === 'laser' || hyperModeActive) {
            ctx.strokeStyle = '#ff5500';
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.moveTo(px + gridSize * 0.35 + pupilOffsetX * 5, py + gridSize * 0.45 + pupilOffsetY * 5);
            ctx.lineTo(px + gridSize * 0.35 + pupilOffsetX * 12, py + gridSize * 0.45 + pupilOffsetY * 12);
            ctx.moveTo(px + gridSize * 0.72 + pupilOffsetX * 5, py + gridSize * 0.45 + pupilOffsetY * 5);
            ctx.lineTo(px + gridSize * 0.72 + pupilOffsetX * 12, py + gridSize * 0.45 + pupilOffsetY * 12);
            ctx.stroke();
          }
        }

        ctx.restore();
      });

      // Draw score particles & texts
      effects.particles.forEach(p => {
        ctx.fillStyle = p.color;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.size, 0, 2 * Math.PI);
        ctx.fill();
      });
      effects.score.forEach(e => {
        ctx.fillStyle = `rgba(0,255,150,${e.alpha})`;
        ctx.font = `bold ${e.size}px 'Rajdhani', 'Segoe UI', sans-serif`;
        ctx.textAlign = 'center';
        ctx.shadowColor = '#0f9';
        ctx.shadowBlur = 16;
        ctx.fillText(e.text, e.x, e.y);
      });

      // Shield halo on head
      if (snakeMode === 'shield') {
        const head = snake[0];
        const cx = head.x * gridSize + gridSize / 2;
        const cy = head.y * gridSize + gridSize / 2;

        ctx.save();
        ctx.beginPath();
        ctx.arc(cx, cy, gridSize * 1.1, 0, Math.PI * 2);
        ctx.strokeStyle = 'rgba(0, 200, 255, 0.7)';
        ctx.lineWidth = 6;
        ctx.shadowColor = '#0ff';
        ctx.shadowBlur = 40;
        ctx.stroke();
        ctx.restore();
      }

      // Laser visual beams
      laserVisuals.forEach(l => {
        ctx.save();
        ctx.lineCap = 'round';
        ctx.lineWidth = 8;
        ctx.strokeStyle = `rgba(255,85,0,${l.alpha})`;
        ctx.shadowColor = `rgba(255,180,50,${l.alpha})`;
        ctx.shadowBlur = 35;
        ctx.beginPath();
        ctx.moveTo(l.fromX, l.fromY);
        ctx.lineTo(l.toX, l.toY);
        ctx.stroke();
        ctx.restore();
      });
    }

    // Input handling (touch & buttons & keyboard)
    let touchStart = null;
    const minSwipe = 30;

    canvas.addEventListener('touchstart', e => {
      if (e.touches.length === 1) {
        touchStart = { x: e.touches[0].clientX, y: e.touches[0].clientY };
      }
    }, { passive: true });
    canvas.addEventListener('touchmove', e => {
      if (!touchStart) return;
      const dx = e.touches[0].clientX - touchStart.x;
      const dy = e.touches[0].clientY - touchStart.y;
      if (Math.abs(dx) > minSwipe || Math.abs(dy) > minSwipe) {
        let dir;
        if (Math.abs(dx) > Math.abs(dy)) {
          dir = dx > 0 ? 'right' : 'left';
        } else {
          dir = dy > 0 ? 'down' : 'up';
        }
        changeDir(dir);
        touchStart = null;
      }
    }, { passive: true });
    canvas.addEventListener('touchend', () => { touchStart = null; });

    btns.forEach(button => button.addEventListener('click', () => {
      changeDir(button.dataset.dir);
      canvas.focus();
    }));

    window.addEventListener('keydown', e => {
      if(gameOver) return;

      // Accept input only if canvas or controls in focus for arrow keys
      const isInputFocused = (document.activeElement === canvas || game.contains(document.activeElement));
      if(!isInputFocused && !gameOverScreen.classList.contains('show')) return;

      const keyMap = {
        ArrowUp: 'up', ArrowDown: 'down',
        ArrowLeft: 'left', ArrowRight: 'right',
        w: 'up', W: 'up',
        s: 'down', S: 'down',
        a: 'left', A: 'left',
        d: 'right', D: 'right',
      };

      if(e.key === 'p' || e.key === 'P') {
        e.preventDefault();
        togglePause();
        return;
      }

      if(e.key === ' ' && snakeMode === 'laser' && !paused) {
        e.preventDefault();
        shootLaser();
        return;
      }

      const dir = keyMap[e.key];
      if (dir) {
        e.preventDefault();
        changeDir(dir);
      }
    });

    function changeDir(dir) {
      const mapping = { up: { x: 0, y: -1 }, down: { x: 0, y: 1 }, left: { x: -1, y: 0 }, right: { x: 1, y: 0 } };
      const newVel = mapping[dir];
      if (newVel && (newVel.x !== -velocity.x || newVel.y !== -velocity.y)) {
        nextVel = newVel;
      }
    }

    // Show Game Over UI with focus trap and announce
    function showGameOver() {
      generateGameOverSound();
      setTimeout(() => {
        finalScore.textContent = score;
        gameOverScreen.classList.add('show');
        restartBtn.style.display = 'block';
        pauseBtn.style.display = 'none';
        soundToggleBtn.style.display = 'block';
        restartBtn.focus();
        canvas.setAttribute('aria-hidden', 'true');
        subtitle.textContent = "GAME OVER - PRESS PLAY AGAIN";
      }, 120);
    }

    // Hide Game Over UI
    function hideGameOver() {
      gameOverScreen.classList.remove('show');
      restartBtn.style.display = 'none';
      pauseBtn.style.display = 'block';
      canvas.removeAttribute('aria-hidden');
      subtitle.textContent = "HYPER EDITION - NEXT LEVEL GAMEPLAY!";
    }

    // Init or reset game state
    function initGame() {
      snake = [];
      for(let i = 0; i < 6; i++) {
         snake.push({ x: Math.floor(tileCount/2) - i, y: Math.floor(tileCount/2) });
      }
      velocity = { x: 1, y: 0 };
      nextVel = { x: 1, y: 0 };
      apples = [];
      powerUps = [];
      portals = [];
      score = 0;
      comboCounter = 0;
      lastAppleTime = 0;
      hue = 0;
      effects = { score: [], particles: [] };
      gameOver = false;
      snakeMode = 'normal';
      powerUpActive = false;
      powerUpEndTime = 0;
      level = 1;
      trailParticles = [];
      shieldHits = 0;
      laserShotsLeft = 0;
      laserVisuals = [];
      paused = false;
      hyperModeActive = false;
      currentFps = baseFps;
      interval = 1000 / currentFps;
      comboBar.style.width = '0%';
      snakeType.textContent = 'NORMAL';
      snakeType.style.color = '#0ff';
      scoreEl.textContent = score;
      levelIndicator.textContent = level;
      restartBtn.style.display = 'none';
      powerTimer.style.display = 'none';
      pauseBtn.style.display = 'block';
      soundToggleBtn.style.display = 'block';
      timeWarpEffect.classList.remove('active');
      hyperMode.classList.remove('active');
      hideGameOver();
      spawnApples();
      canvas.focus();
    }

    // Pause toggle
    function togglePause() {
      paused = !paused;
      if(paused) {
        pauseBtn.textContent = "RESUME GAME";
        subtitle.textContent = "PAUSED";
        canvas.setAttribute('aria-busy', 'true');
      } else {
        pauseBtn.textContent = "PAUSE GAME";
        subtitle.textContent = `LEVEL ${level} - ULTRA CYBER CHALLENGE!`;
        canvas.removeAttribute('aria-busy');
      }
    }

    // Restart buttons
    restartBtn.addEventListener('click', () => {
      initGame();
    });
    restartBtn2.addEventListener('click', () => {
      initGame();
    });

    // Sound toggle button
    soundToggleBtn.addEventListener('click', () => {
      soundAllowed = !soundAllowed;
      if (!audioContext && soundAllowed) {
        initAudioContext();
      }
      soundToggleBtn.textContent = soundAllowed ? "SOUND: ON" : "SOUND: OFF";
    });

    // Main loop params
    let lastTime = 0;
    let delta = 0;
    let interval = 1000 / currentFps;

    // Main loop
    function loop(ts = 0) {
      if (!lastTime) lastTime = ts;
      delta += ts - lastTime;
      lastTime = ts;

      interval = 1000 / currentFps;

      while (delta >= interval) {
        update();
        updateEffects();
        delta -= interval;
      }
      draw();
      requestAnimationFrame(loop);
    }

    /* Initialize */
    initGame();
    requestAnimationFrame(loop);

  })();
  </script>
</body>
</html>