no bro with sandbox mode when I go up and tyr to go back I get blocked


        let maxGameScrollPosition = 0; // Holds furthest right camera scroll so far
        let leftBoundaryX = 0; // Moving left boundary for player position

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Adventure Game</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #222;
            color: #fff;
            font-family: Arial, sans-serif;
            overflow: hidden;
        }
 
        #game-container {
            position: relative;
            width: 800px;
            height: 400px;
            background-color: #333;
            overflow: hidden;
            border: 2px solid #444;
        }


        #upgrades-menu {
            display: none;
            background-color: rgba(0, 0, 0, 0.8);
            color: #fff;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }

        #upgrade-list {
            margin: 20px 0;
        }

        .upgrade-option {
            margin: 10px 0;
            font-size: 18px;
        }

#start-menu, #game-mode-options, #level-options {
    display: none; /* Initially hidden */
    text-align: center; /* Center text for buttons */
    position: absolute; /* Positioned relative to parent */
    top: 50%; /* Start middle of vertical view */
    left: 50%; /* Start middle of horizontal view */
    transform: translate(-50%, -50%); /* Center it */
    z-index: 10; /* Bring to the front */
}

        .button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            background-color: #555;
            color: #fff;
            border: none;
            border-radius: 5px;
        }

        .navigation-button {
            margin: 5px;
        }

.split-enemy.split {
    border-radius: 0 !important;
}

.boost-drainer-chain {
  position: absolute;
  border-top: 2px dotted cyan;
  pointer-events: none;
  z-index: 1000;
  height: 0; /* Since it's a horizontal line rotated, height is zero */
}


.boost-drainer {
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: 2px solid cyan;
  background-color: green; /* start at green */
  transition: background-color 0.5s;
  z-index: 20;
}

.boost-drainer.green { background-color: green !important; }
.boost-drainer.yellow { background-color: yellow !important; }
.boost-drainer.red { background-color: red !important; }

.boost-laser {
  position: absolute;
  width: 5px;
  height: 120px; /* height of laser, adjust */
  background-color: red;
  top: 0; /* will be positioned at bottom 0 */
  box-shadow: 0 0 10px red;
  z-index: 19;
  pointer-events: none; /* no interference with input */
}

.split-enemy:not(.split) {
    border-radius: 0 !important; /* Make mini splitters squares */
}

.split-enemy:not(.split) {
    border-radius: 0 !important;
}
 
#game-world {
    position: absolute;
    width: 10000px; /* bigger world - adjust as you wish */
    height: 100%;
    transition: transform 0.1s linear;
}
 
        #player {
            position: absolute;
            bottom: 0;
            left: 50px;
            width: 30px;
            height: 30px;
            background-color: #4CAF50;
            animation: idle 1s infinite alternate;
        }
 
        @keyframes idle {
            from { transform: translateY(0); }
            to { transform: translateY(2px); }
        }
 
@keyframes charging-prep {
    0%, 100% { box-shadow: 0 0 5px rgba(255, 0, 0, 0.6); }
    50% { box-shadow: 0 0 15px rgba(255, 0, 0, 1); }
}

#sandbox-panel {
    border: 2px solid cyan !important;
    background-color: rgba(0, 0, 0, 0.95) !important;
}
 
@keyframes boss-shake {
    0%, 100% { transform: translate(0, 0); }
    25% { transform: translate(-5px, 0); }
    50% { transform: translate(5px, 0); }
    75% { transform: translate(-5px, 0); }
}
 
 
@keyframes charge-trail {
    0% { opacity: 0.8; transform: scale(1); }
    100% { opacity: 0; transform: scale(2); }
}
 
@keyframes boss-shield-glow {
    0%, 100% { box-shadow: 0 0 10px red; }
    50% { box-shadow: 0 0 20px red; }
}
 
        .character, .boss-door, .power-up, .enemy, .virus-drone, .laser-enemy, .obstacle, .bullet, .burst, .boss, #friend, .coin, .flying-enemy, .charging-enemy, .stealth-enemy, .split-enemy, .boost-drainer, .sniper-enemy, .reflective-enemy, .explosive-enemy, .teleporter-enemy, .mourning-enemy, .velocity-enemy, .sticky-enemy, .reflective-enemy {
            position: absolute;
        }
 
        .character, .king, .stealth-enemy, .split-enemy, .sniper-enemy, .reflective-enemy, .explosive-enemy,
        .teleporter-enemy, .mourning-enemy, .velocity-enemy, .sticky-enemy, .reflective-enemy {
            border-radius: 50%;
        }


.virus-drone {
    position: absolute;
    width: 30px;
    height: 30px;
    background-color: green;
    border: 3px solid red;
    border-radius: 5px;
    z-index: 11;
}

.infected {
    background-color: #00cc00 !important; // bright green
    filter: drop-shadow(0 0 5px lime);
    transition: background-color 0.3s;
}

.infected.shielded::after {
    content: '';
    position: absolute;
    top: -5px; left: -5px;
    width: calc(100% + 10px);
    height: calc(100% + 10px);
    border: 2px solid cyan;
    border-radius: 5px;
    pointer-events: none;
    animation: shieldPulse 2s infinite;
}

@keyframes shieldPulse {
    0%, 100% { opacity: 0.3; }
    50% { opacity: 1; }
}

.energy-blast {
    position: absolute;
    width: 200px; /* Diameter of the burst */
    height: 200px; /* Diameter of the burst */
    border-radius: 50%; /* Make it circular */
    border: 2px solid rgba(0, 255, 255, 0.8); /* Color and transparency */
    opacity: 0.5; /* Semi-transparent */
    animation: pulse 0.5s ease-out; /* Animation for the burst */
}

@keyframes pulse {
    0% {
        transform: scale(1);
        opacity: 0.5;
    }
    100% {
        transform: scale(2); /* Expand the burst for the visual effect */
        opacity: 0; /* Fade out */
    }
}
 
.charging-prep {
    animation: charging-prep 1s infinite alternate;
}

.outlined {
    border: 3px solid green; /* Change as necessary */
    box-shadow: 0 0 10px green; /* Add glow effect */
}
 
.boss-shielded {
    animation: boss-shield-glow 0.8s infinite alternate;
    border: 3px solid red;
}
 
.charging-active {
    box-shadow: 0 0 15px red, 0 0 30px red;
    border: 2px solid red;
}
 
.charge-trail {
    position: absolute;
    width: 35px;
    height: 35px;
    background-color: rgba(255, 50, 50, 0.5);
    border-radius: 50%;
    opacity: 1;
    animation: charge-trail 0.4s ease-out;
}
 
.bullet-trail {
    position: absolute;
    width: 8px;
    height: 4px;
    background-color: rgba(255, 215, 0, 0.5);
    opacity: 1;
    transition: opacity 0.3s ease-out;
}

.laser-line {
    pointer-events: none; /* prevent interfering with input */
    z-index: 1000;
    border-radius: 2px;
    transition: background-color 0.2s ease;
}
 

.infected.shielded::after {
    content: '';
    position: absolute;
    top: -5px; left: -5px;
    width: calc(100% + 10px);
    height: calc(100% + 10px);
    border: 2px solid cyan;
    border-radius: 5px;
    pointer-events: none;
    animation: shieldPulse 2s infinite;
}

 
        .coin {
            width: 15px;
            height: 15px;
            background-color: #FFD700;
            border-radius: 50%;
            animation: spin 2s linear infinite;
        }
 
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
 
        .flying-enemy {
            width: 30px;
            height: 30px;
            background-color: #0099FF;
            border-radius: 50%;
            opacity: 0.9;
        }
 
        .charging-enemy {
            width: 40px;
            height: 40px;
            background-color: #FF5500;
            animation: charge 1s linear infinite alternate;
            border-radius: 50%;
        }
 
        .enemy {
            width: 25px;
            height: 25px;
            background-color: #FF5733;
        }

.laser-warning-line {
    position: absolute;
    width: 6px;
    background-color: yellow;
    opacity: 0.7;
    pointer-events: none;
    z-index: 9;
}

.laser-beam {
    position: absolute;
    width: 8px;
    background-color: red;
    opacity: 0.9;
    pointer-events: none;
    z-index: 10;
}

        .split-enemy {
            width: 35px;
            height: 35px;
            background-color: #FF5733;
        }

        .laser-enemy {
            width: 35px;
            height: 35px;
            background-color: #FF5733;
        }
 
        .obstacle {
            width: 30px;
            height: 30px;
            background-color: #f44336;
        }

.lava {
    position: absolute;
    width: 100%;
    bottom: 0;
    background-color: red;
    z-index: 5;
    height: 0;
    transition: height 0.1s linear;
}
 
        .power-up {
            width: 20px;
            height: 20px;
        }
 
        .bullet {
            width: 10px;
            height: 5px;
            background-color: #FFD700;
        }
 
        .burst {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: rgba(255, 69, 0, 0.7);
            animation: burst 0.5s ease-out;
        }
 
        @keyframes burst {
            from { transform: scale(0.5); opacity: 1; }
            to { transform: scale(1.5); opacity: 0; }
        }
 
        .boss-door {
            width: 30px;
            height: 60px;
            background-color: #FFFF00;
        }
 
        .burst {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: rgba(255, 69, 0, 0.7);
            animation: burst 0.5s ease-out;
        }   
 
        .boss {
            width: 60px;
            height: 60px;
            background-color: #FF4500;
        }


.reflective-enemy {
    width: 25px;
    height: 25px;
    background-color: #FF5733;
    border: 3px solid transparent; /* Initial border */
    box-shadow: 0 0 10px green; /* Glow effect */
}

        .mourning-enemy {
            width: 25px;
            height: 25px;
            background-color: #FF3333;
        }

        .sniper-enemy {
            width: 25px;
            height: 25px;
            background-color: #FF3333;
        }


 
        #score, #lives, #level, #timer, #shop-score {
            position: absolute;
            top: 10px;
            font-size: 16px;
        }


 
 
 
        #score { left: 10px; }
        #lives { right: 10px; }
        #level { left: 150px; }
        #timer { left: 250px; }
        #shop-score { left: 350px; }
 
        #instructions, #cutscene, #level-intro, #level-intro, #boss-fight, #boss-hallway, #game-over, #interact-message {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: rgba(0, 0, 0, 0.8);
            color: #fff;
            flex-direction: column;
            font-size: 18px;
            z-index: 10;
        }

  #sandbox-gui .btn:disabled {
    opacity: 0.4;
    cursor: default;
  }
  #sandbox-gui input[type="range"] {
    -webkit-appearance: none; width: 100%; background: #004;
  }
  #sandbox-gui input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none; height: 16px; width: 16px; background: #0ff; cursor: pointer; border-radius: 50%;
  }
 
        #instructions button, #cutscene button, #level-intro button, #level-intro2 button, #boss-fight button, #game-over button, #boss-hallway button {
            margin-top: 10px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            background-color: #555;
            color: #fff;
        }
 
        #cutscene, #level-intro, #level-intro2, #boss-fight, #boss-hallway, #game-over, #interact-message {
            display: none;
        }

#element-sample > div {
    margin: auto;
    transform-origin: center center;
}
 
        #intro {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: space-around;
            align-items: center;
            background-color: rgba(0, 0, 0, 0.8);
            color: #fff;
            flex-direction: row;
            font-size: 18px;
            z-index: 11;
        }
 
#boss-health-bar {
    display: none; /* Initially hidden */
    position: absolute;
    top: 10px; /* Adjust based on your UI */
    left: 50%; /* Center it horizontally or adjust as needed */
    transform: translateX(-50%); /* Center alignment */
    width: 150px; /* Set fixed maximum width for the health bar */
    height: 20px; /* Height of the bar */
    background-color: #666; /* Background bar color */
    border: 1px solid #333; /* Border style */
    border-radius: 5px; /* Rounded corners */
    overflow: hidden; /* Prevent overflow */
    transition: width 0.5s ease; /* Smooth transition */
}

#boss-health {
    height: 100%;
    background-color: green; /* Initial health segment color */
    border-radius: 5px; /* Rounded corners for inner health */
}
 
        #friend {
            width: 30px;
            height: 30px;
            background-color: #00FF00;
            display: none;
        }
 
        #power-up-message {
            position: absolute;
            top: 50px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 24px;
            z-index: 12;
            display: none;
        }
 
        /* New CSS for cool features */
        @keyframes flash {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
 
        .flashing {
            animation: flash 0.5s infinite;
        }
 
        .glow {
            box-shadow: 0 0 10px rgba(255,255,255,0.5);
        }
    </style>
</head>
<body>
    <div id="game-container">
        <div id="game-world">
            <div id="player"></div>
        </div>
<div id="upgrades-menu" style="display:none;">
    <h2>Upgrades</h2>
    <button onclick="previousUpgrade()" class="button">Previous</button>
    <div id="upgrade-list"></div>
    <button onclick="nextUpgrade()" class="button">Next</button>
    <button onclick="buyUpgrade()" class="button">Buy Upgrade</button>
    <button onclick="viewEquippedUpgrades()" class="button">View Equipped</button> <!-- New button -->
    <button onclick="closeUpgrades()" class="button">Close</button>
    <div id="message" style="color: red;"></div>
</div>

<div id="sandbox-gui" style="position:fixed;top:50px;right:20px;width:520px;height:600px;background:rgba(0,0,0,0.95);color:#0ff;border:2px solid cyan;box-sizing:border-box;z-index:9999;display:flex;flex-direction:column;font-family: monospace;">
  <div id="sandbox-header" style="background:#004;padding:6px;cursor:move;display:flex;justify-content:space-between;align-items:center;">
    <span>Sandbox Mode</span>
    <button id="sandbox-minimize-btn" style="background:#006;color:#0ff;border:none;padding:4px 10px;cursor:pointer;">_</button>
  </div>
  <div id="sandbox-tabs-container" style="flex-grow:1;display:flex;flex-direction:column;overflow:hidden;">
    <!-- Tab buttons -->
    <div id="sandbox-tabs" style="display:flex;gap:10px;background:#003;padding:6px;border-bottom:1px solid cyan;">
      <button class="sandbox-tab-btn active" data-tab="all-elements" style="background:none;color:#0ff;border:none;cursor:pointer;">All Elements</button>
      <button class="sandbox-tab-btn" data-tab="character-modifiers" style="background:none;color:#0ff;border:none;cursor:pointer;">Character Modifiers</button>
      <button class="sandbox-tab-btn" data-tab="fun" style="background:none;color:#0ff;border:none;cursor:pointer;">Fun</button>
      <button class="sandbox-tab-btn" data-tab="map-modifier" style="background:none;color:#0ff;border:none;cursor:pointer;">Map Modifier</button>
      <button class="sandbox-tab-btn" data-tab="settings" style="background:none;color:#0ff;border:none;cursor:pointer;">Settings</button>
    </div>
    <!-- Tab contents -->
    <div id="sandbox-tab-contents" style="flex-grow:1;overflow:auto;padding:10px;">
      <!-- All Elements Tab -->
      <div id="tab-all-elements" class="sandbox-tab-content active" style="display:block;">
        <input id="element-search" placeholder="Search elements..." type="text" style="width:100%;padding:6px;margin-bottom:8px;color:#000;" />
        <div id="element-list" style="max-height:280px;overflow-y:auto;border:1px solid #0ff;padding:6px;background:#111;"></div>
        <div style="margin-top:8px;display:flex;justify-content:center;gap:10px;">
          <button id="element-prev" class="btn" style="background:#006;color:#0ff;border:none;padding:6px 14px;cursor:pointer;">&laquo; Prev</button>
          <span id="element-page-info" style="align-self:center;"></span>
          <button id="element-next" class="btn" style="background:#006;color:#0ff;border:none;padding:6px 14px;cursor:pointer;">Next &raquo;</button>
        </div>
        <hr style="margin:8px 0;border:1px solid #0ff;" />
        <div id="element-preview-container" style="display:flex;gap:10px;">
          <div id="element-preview" style="flex:1;min-height:130px;border:1px solid #0ff;background:#112;display:flex;justify-content:center;align-items:center;position:relative;color:#0ff;">
            <em>Select element to preview</em>
          </div>
          <div style="flex-shrink:0; display:flex; flex-direction: column; gap: 6px;">
            <button id="spawn-element-btn" style="background:#00a;color:#0ff;border:none;padding:10px 18px;cursor:pointer;" disabled>Spawn</button>

            <label for="spawn-offset-slider" style="margin-top:8px; font-size:12px; color:#0ff; user-select:none;">Spawn Distance Offset: <span id="spawn-offset-value">200</span> px</label>
            <input id="spawn-offset-slider" type="range" min="0" max="2000" step="10" value="600" style="width:200px;" />

            <div style="margin-top:6px; display:flex; gap:6px;">
              <button id="undo-spawn-btn" style="flex:1; background:#660;color:#fff; border:none; padding:8px; cursor:pointer;" disabled>Undo</button>
              <button id="redo-spawn-btn" style="flex:1; background:#066;color:#0ff; border:none; padding:8px; cursor:pointer;" disabled>Redo</button>
            </div>
          </div>
        </div>
      </div>
      <!-- Character Modifiers Tab -->
      <div id="tab-character-modifiers" class="sandbox-tab-content" style="display:none; color:#0ff;">
        <div>
          <label>Player Color: </label>
          <input type="color" id="player-color-picker" value="#4CAF50" />
        </div>
        <div style="margin-top:12px;">
          <label>Gravity (normal=0.5): </label>
          <input type="range" id="gravity-slider" min="-1" max="1" step="0.05" value="0.5" style="width:100%;" />
          <div id="gravity-value" style="text-align:right;">0.50</div>
        </div>
        <div style="margin-top:12px;">
          <label>Player Speed: </label>
          <input type="range" id="player-speed-slider" min="1" max="15" step="0.1" value="5" style="width:100%;" />
          <div id="player-speed-value" style="text-align:right;">5.00</div>
        </div>
        <div style="margin-top:12px;">
          <label>Bullet Speed: </label>
          <input type="range" id="bullet-speed-slider" min="1" max="20" step="0.1" value="5" style="width:100%;" />
          <div id="bullet-speed-value" style="text-align:right;">5.00</div>
        </div>

<div style="margin-top: 20px; color: #0ff;">
  <label for="lives-input">Player Lives:</label>
  <input type="number" id="lives-input" min="0" max="99" value="3" style="width: 80px; margin-left: 8px;" />
</div>

<div style="margin-top: 10px; color: #0ff;">
  <label for="score-input">Player Score:</label>
  <input type="number" id="score-input" min="0" max="999999" value="0" style="width: 120px; margin-left: 8px;" />
</div>
      </div>

      <!-- Fun Tab -->
<div id="tab-fun" class="sandbox-tab-content" style="display:none; color:#0ff;">

  <h3>Fun Functions</h3>
  <input 
    id="fun-functions-search" 
    type="search" 
    placeholder="Search fun functions..." 
    style="width: 100%; margin-bottom: 12px; padding: 6px; font-size: 14px;"
    autocomplete="off"
  />
  <div id="fun-functions-list" style="display:flex; flex-direction: column; gap: 10px;"></div>
  <div id="fun-cooldown-message" style="margin-top:10px; font-style: italic;"></div>
</div>
      <!-- Map Modifier Tab -->
      <div id="tab-map-modifier" class="sandbox-tab-content" style="display:none; color:#0ff;">
        <div>
          <label>Background Color: </label>
          <input type="color" id="background-color-picker" value="#333333" />
        </div>
        <div style="margin-top:12px;">
          <label><input type="checkbox" id="toggle-platforms" checked /> Platforms Visible</label><br/>
          <label><input type="checkbox" id="toggle-obstacles" checked /> Obstacles Visible</label><br/>
          <label><input type="checkbox" id="toggle-enemies" checked /> Enemies Visible</label><br/>
          <label><input type="checkbox" id="toggle-powerups" checked /> Power-Ups Visible</label><br/>
          <label><input type="checkbox" id="toggle-coins" checked /> Coins Visible</label><br/>
        </div>
      </div>
      <!-- Settings Tab -->
      <div id="tab-settings" class="sandbox-tab-content" style="display:none; color:#0ff;">
<div style="margin-top: 20px; border-top: 1px solid cyan; padding-top: 10px;">
  <label>
    <input type="checkbox" id="spawn-entities-enable-checkbox" />
    Enable Entity Spawner
  </label>
  <br />
  <label for="spawn-entities-level-select" style="margin-top: 10px; display: inline-block;">
    Select Spawn Level:
  </label>
  <select id="spawn-entities-level-select" disabled>
    <option value="1">Level 1</option>
    <option value="2">Level 2</option>
    <option value="3">Level 3</option>
    <option value="4">Level 4</option>
    <option value="5">Level 5</option>
  </select>
</div>
        <div>
          <label><input type="checkbox" id="experiment-mode-checkbox" /> Enable Experiment Mode (Freeze enemies + Move)</label>
        </div>
        <div id="experiment-controls" style="margin-top:10px; display:none; border:1px solid #0ff; padding:8px;">
          <p>Experiment Mode Controls:</p>
          <div><button id="unfreeze-enemies-btn" style="background:#006;color:#0ff;border:none;padding:6px 12px;cursor:pointer;">Unfreeze All Enemies</button></div>
          <p style="margin-top:8px;">Select an enemy in Map Modifier tab to move it:</p>
          <div style="display:flex;gap:6px;flex-wrap:wrap">
            <button data-dir="up" class="enemy-move-btn" style="background:#006;color:#0ff;border:none;padding:6px 12px;cursor:pointer;">Up</button>
            <button data-dir="down" class="enemy-move-btn" style="background:#006;color:#0ff;border:none;padding:6px 12px;cursor:pointer;">Down</button>
            <button data-dir="left" class="enemy-move-btn" style="background:#006;color:#0ff;border:none;padding:6px 12px;cursor:pointer;">Left</button>
            <button data-dir="right" class="enemy-move-btn" style="background:#006;color:#0ff;border:none;padding:6px 12px;cursor:pointer;">Right</button>
          </div>
          <div style="margin-top:6px;">
            <em>Selected Enemy: <span id="selected-enemy-info">None</span></em>
          </div>
        </div>
        <hr />
        <div>
          <label><input type="checkbox" id="enable-logs-checkbox" /> Enable View Logs (Toggle draggable logs window)</label>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Logs window -->
<div id="logs-window" style="position:fixed; top:680px; right:20px; width:400px; max-height:200px; background:rgba(0,0,0,0.85); border:2px solid cyan; overflow:auto; padding:8px; font-family: monospace; font-size:12px; color:#0ff; z-index:10000; display:none; cursor:move;">
  <b>Logs</b>
  <button id="clear-logs-btn" style="float:right;background:#006; color:#0ff; border:none; cursor:pointer;">Clear</button>
  <pre id="logs-content" style="white-space:pre-wrap;"></pre>
</div>

        <div id="score">Score: 0</div>
        <div id="shop-score">Shop Score: 0</div>
        <div id="lives">Lives: 3</div>
        <div id="level">Level: 1</div>
        <div id="timer">Timer: 0</div>
        <div id="instructions">
            <p>Press Arrow Up to Jump</p>
            <p>Use Arrow Left/Right to Move</p>
            <p>Press Space to Shoot</p>
            <p>Press Z for Power-Up</p>
            <p>Press E to interact</p>
            <button onclick="showGameModeOptions()">Start Game</button> <!-- Start Game Button -->
            <button onclick="togglePause()">Pause/Resume</button>
            <button onclick="openUpgrades()">Open Upgrades</button>
        </div>
        <div id="cutscene">
            <p>Get ready for the next level!</p>
            <button onclick="continueGame()">Continue</button>
        </div>
    <div id="equipped-upgrades" style="display: none;"> <!-- Initially hidden -->
        <h3>Equipped Upgrades:</h3>
        <!-- Equipped upgrades will be displayed here -->
    </div>
<div id="game-mode-options" style="display: none;"> 
    <button onclick="startGamee()" class="button">Story Mode</button>
    <button id="endless-mode-btn" onclick="showLevelOptions()" class="button" style="display: none;">Endless Mode</button>
    <button id="sandbox-mode-btn" onclick="startSandboxMode()" class="button" style="display: none;">Sandbox Mode</button>
</div>
    <div id="level-options" style="display: none;"> 
        <button onclick="startEndlessMode(1)" class="button" >Level 1</button> <!-- Level 1 Button -->
        <button onclick="startEndlessMode(2)" class="button">Level 2</button> <!-- Level 2 Button -->
        <button onclick="startEndlessMode(3)" class="button">Level 3</button> <!-- Level 3 Button -->
        <button onclick="startEndlessMode(4)" class="button">Level 4</button> <!-- Level 4 Button -->
        <button onclick="startEndlessMode(5)" class="button">Level 5</button> <!-- Level 4 Button -->

    </div>

    </div>
        <div id="level-intro">
            <p id="level-text">Get Ready for Adventure!</p>
            <button onclick="startLevel()">Start Level</button>
        </div>
       <div id="level-intro2">
            <p id="level-text">Get Ready for Adventure!</p>
            <button onclick="restartGame()">Start Endless mode</button>
        </div>
        <div id="boss-fight">
            <p>Defeat the Boss!</p>
        </div>
        <div id="game-over">
            <p>Game Over!</p>
            <button onclick="restartGame()">Restart</button>
        </div>
        <div id="boss-hallway">
            <p>You have entered the boss hallway! Prepare yourself!</p>
            <button onclick="startBossFight()">Proceed</button>
        </div>
        <div id="boss-health-bar">
            <div id="boss-health"></div>
        </div>
        <div id="power-up-message"></div>
        <div id="interact-message"></div>
        <div id="friend"></div>
    </div>
 
    <script>
            const gameContainer = document.getElementById('game-container');
            const gameWorld = document.getElementById('game-world');
            const player = document.getElementById('player');
            const scoreDisplay = document.getElementById('score');
            const maxUpgrades = 5; // Maximum number of upgrades you can equip
            const livesDisplay = document.getElementById('lives');
            const levelDisplay = document.getElementById('level');
            const timerDisplay = document.getElementById('timer');
            const instructions = document.getElementById('instructions');
const funTabBtn = document.querySelector('.sandbox-tab-btn[data-tab="fun"]');
const funTabContent = document.getElementById('tab-fun');
let isInBossHallway = false; // globally defined flag to track hallway state
  let experimentModeEnabled = false;
  let frozenEnemyPositions = new Map();
  let selectedEnemy = null;
            const cutscene = document.getElementById('cutscene');
            const levelIntro = document.getElementById('level-intro');
            const levelText = document.getElementById('level-text2');
            const levelIntro2 = document.getElementById('level-intro2');
            const levelText2 = document.getElementById('level-text');
const spawnOffsetSlider = document.getElementById('spawn-offset-slider');
const spawnOffsetValueDisplay = document.getElementById('spawn-offset-value');
const spawnBtn = document.getElementById('spawn-element-btn');
const undoBtn = document.getElementById('undo-spawn-btn');
const redoBtn = document.getElementById('redo-spawn-btn');
const funSearchInput = document.getElementById('fun-functions-search');
const funFunctionsListDiv = document.getElementById('fun-functions-list');
            const bossFightScreen = document.getElementById('boss-fight');
            const gameOverScreen = document.getElementById('game-over');
let spawnOffset = parseInt(spawnOffsetSlider.value, 10);

// Undo/Redo stacks for spawned elements
const spawnedElementsStack = [];
const redoStack = [];
            const intro = document.getElementById('intro');
            const dialoguePara = document.querySelector('#dialogue p');
const upgradesPerPage = 1; // Number of upgrades to show per page
            const bossHallway = document.getElementById('boss-hallway');
            const bossHealthBar = document.getElementById('boss-health-bar');
            const bossHealthDisplay = document.getElementById('boss-health');
            let currentPage = 0; // Tracks current page
let currentGameMode; // Temporary variable to store the current game mode

let currentEndlessLevel = localStorage.getItem('endlessLevel') ? parseInt(localStorage.getItem('endlessLevel')) : 1; // Endless Mode Level Tracking
let storyModeLevel = localStorage.getItem('storyLevel') ? parseInt(localStorage.getItem('storyLevel')) : 1; // Story Mode Level Tracking
let isEndlessMode = false; // Track if currently in Endless Mode
            let bulletSpeed = 5; // Initialize bullet speed
// Other variables...
            let phaseStartTime = null; // Track the start time of the boss phase
            let playerScore = localStorage.getItem('playerScore') ? parseInt(localStorage.getItem('playerScore')) : 0;
            const powerUpMessage = document.getElementById('power-up-message');
            let upgradesEquipped = []; // Store equipped upgrades
            const viruses = [];

            const friend = document.getElementById('friend');
            const obstacleSpawnDistance = 500; // Distance before the right edge
            let playerPositionX = 50;
            let upgradesPurchased = [];
            let boostDrainer = null;
            let boostDrainerLaser = null;
            let boostDrainerHP = 3;
            let boostDrainerState = "moving"; // "moving", "green", "yellow", "red", "firing", "dead"
            let boostDrainerAttackTimeout = null;
            const boostDrainerAttackXOffset = 250; // how close to player it moves before attack
            const boostDrainerSpeed = 1.0; // pixels per frame
            let virusDroneHits = 0;  // tracks hits on Virus Drone
            let playerPositionY = 0;
            let playerVelocityX = 0;
            let objectSpawnDistance = 300; // Distance from the right edge to spawn new objects
            let playerVelocityY = 0;
            let removedEnemies = [];
            let phaseThreeStarted = false; // Flag to track if Phase Three has started
            let phaseThreeStarted1 = false; // Flag to track if Phase Three has started
            let phaseThreeStarted3 = false; // Flag to track if Phase Three has started
            let bossDefeatedMessageDisplayed = false; // Flag to track if the defeated message has been displayed
            let playerMaxSpeed = 5;
            const playerJumpStrength = 12;
            let jumpCount = 0;
            let maxJumps = 1;
            let isDoubleJumpEnabled = false;
            let isJumping = false;
            let isCycling = false;  // Lock to prevent concurrent calls
            let isPaused = false;
            let canShoot = true;
            let waveCooldown = false; // Track if a wave is on cooldown
            let bossAttacking = false;
            let bossAttackPhase = 0;
            let gameInterval;
            let obstacles = [];
            let enemies = [];
            const shownPreMessages = {};
            let bullets = [];
            let powerUps = [];
            let boostDrainerChain = null;
            let isTeleporting = false; // Track whether teleport is available
            let platforms = [];
            let bossDoors = [];
            let maxPlayerPositionX = 50;  // Track furthest progress
            let coins = [];
            let score = 0;
            let isInBossDoor = false;
            let lastSpawnCheck = 0;
            let lives = 3;
            let level = localStorage.getItem('playerLevel') ? parseInt(localStorage.getItem('playerLevel')) : 1;
            const gravity = 0.5;
            const maxLevels = 5;
            let movingLeft = false, movingRight = false;
            let currentDirection = 1;
            let currentPowerUp = null;
            let powerUpTimer = 0;
            let gameScrollPosition = 0;
            let maxGameScrollPosition = 0; // Holds furthest right camera scroll so far
            let leftBoundaryX = 0; // Moving left boundary for player position
            const bossScoreThreshold = 1;
            const dialogues = [
                "Player: Hey friend! What a nice day for an adventure!",
                "Friend: Indeed! Maybe we should explore the caves.",
                "Player: What's that over there? Is it the King?",
                "King: Haha, I've found you! You're coming with me!",
                "Friend: Player, help me!"
            ];
            let dialogueIndex = 0;
            let boss = null;
            let bossHealth = 100;
            let bossShielded = true;
            let bossPowerObtained = false;
            let bossFightActive = false;

  const gui = document.getElementById('sandbox-gui');
  const header = document.getElementById('sandbox-header');
  const minimizeBtn = document.getElementById('sandbox-minimize-btn');
  
  // Tabs
  const tabButtons = gui.querySelectorAll('.sandbox-tab-btn');
  const tabContents = gui.querySelectorAll('.sandbox-tab-content');
  
  // All Elements tab vars
  let allCssClasses = [];
  let filteredClasses = [];
  let currentElementPage = 0;
  const elementsPerPage = 5;
  let selectedElementClass = null;

  // References to tab elements under all elements tab
  const elementListDiv = document.getElementById('element-list');
  const searchInput = document.getElementById('element-search');
  const prevBtn = document.getElementById('element-prev');
  const nextBtn = document.getElementById('element-next');
  const pageInfoSpan = document.getElementById('element-page-info');
  const previewContainer = document.getElementById('element-preview');
  const spawnElementBtn = document.getElementById('spawn-element-btn');

  // Character Modifiers tab elements
  const playerColorInput = document.getElementById('player-color-picker');
  const gravitySlider = document.getElementById('gravity-slider');
  const gravityValue = document.getElementById('gravity-value');
  const playerSpeedSlider = document.getElementById('player-speed-slider');
  const playerSpeedValue = document.getElementById('player-speed-value');
let lastFunCallTime = 0;
const funCooldownSecs = 1;
  const bulletSpeedSlider = document.getElementById('bullet-speed-slider');
  const bulletSpeedValue = document.getElementById('bullet-speed-value');

  // Map Modifier tab
  const bgColorInput = document.getElementById('background-color-picker');
  const togglePlatforms = document.getElementById('toggle-platforms');
  const toggleObstacles = document.getElementById('toggle-obstacles');
  const toggleEnemies = document.getElementById('toggle-enemies');
  const togglePowerups = document.getElementById('toggle-powerups');
  const toggleCoins = document.getElementById('toggle-coins');

const spawnEntitiesEnableCheckbox = document.getElementById('spawn-entities-enable-checkbox');
const spawnEntitiesLevelSelect = document.getElementById('spawn-entities-level-select');
let spawnEntitiesEnabled = false;
let spawnEntitiesLevel = 1;
let spawnEntitiesIntervalId = null;
const spawnedSpecialEntities = []; // track entities spawned for cleanup

  // Settings tab
  const experimentModeCheckbox = document.getElementById('experiment-mode-checkbox');
  const experimentControls = document.getElementById('experiment-controls');
  const unfreezeEnemiesBtn = document.getElementById('unfreeze-enemies-btn');
  const enemyMoveButtons = experimentControls.querySelectorAll('.enemy-move-btn');
  const selectedEnemyInfoSpan = document.getElementById('selected-enemy-info');
  const enableLogsCheckbox = document.getElementById('enable-logs-checkbox');

  // Logs window elements
  const logsWindow = document.getElementById('logs-window');
  const logsContent = document.getElementById('logs-content');
  const clearLogsBtn = document.getElementById('clear-logs-btn');

  let isMinimized = false;

const levelSpawnEntitiesMap = {
  1: function spawnLevel1Entities() {
    if (Math.random() < 0.05) spawnEnemy();
    if (Math.random() < 0.03) spawnFlyingEnemy();
    if (Math.random() < 0.02) spawnObstacle();
  },
  2: function spawnLevel2Entities() {
    if (Math.random() < 0.05) spawnEnemy();
    if (Math.random() < 0.03) spawnChargingEnemy();
    if (Math.random() < 0.02) spawnObstacle();
    if (Math.random() < 0.01) spawnSniperEnemy();
  },
  3: function spawnLevel3Entities() {
    if (Math.random() < 0.05) spawnEnemy();
    if (Math.random() < 0.03) spawnFlyingEnemy();
    if (Math.random() < 0.01) spawnReflectiveEnemy();
    if (Math.random() < 0.02) spawnObstacle();
  },
  4: function spawnLevel4Entities() {
    if (Math.random() < 0.01) spawnLaserEnemy();
    if (Math.random() < 0.02) spawnSplitterEnemy();
  },
  5: function spawnLevel5Entities() {
    if (Math.random() < 0.05) spawnEnemy();
    if (Math.random() < 0.03) spawnVirusDrone();
    if (Math.random() < 0.01) spawnSplitterEnemy();
  }
};

// Enable dropdown only if checkbox is checked
spawnEntitiesEnableCheckbox.addEventListener('change', e => {
  spawnEntitiesEnabled = e.target.checked;
  spawnEntitiesLevelSelect.disabled = !spawnEntitiesEnabled;
  if(!spawnEntitiesEnabled) {
    spawnedSpecialEntities.forEach(e => e.remove());
    spawnedSpecialEntities.length = 0;
  }
});

spawnEntitiesLevelSelect.addEventListener('change', e => {
  spawnEntitiesLevel = parseInt(e.target.value);
  log(`Entity spawner level set to ${spawnEntitiesLevel}`);
});


  // For dragging
  let dragOffsetX = 0, dragOffsetY = 0, isDragging = false;
  header.addEventListener('mousedown', e => {
    if (e.target === minimizeBtn) return;
    isDragging = true;
    const rect = gui.getBoundingClientRect();
    dragOffsetX = e.clientX - rect.left;
    dragOffsetY = e.clientY - rect.top;
    document.body.style.userSelect = 'none';
  });
  window.addEventListener('mouseup', () => {
    isDragging = false;
    document.body.style.userSelect = '';
  });
  window.addEventListener('mousemove', e => {
    if (isDragging) {
      let posX = e.clientX - dragOffsetX;
      let posY = e.clientY - dragOffsetY;

      // Clamp inside viewport
      posX = Math.min(Math.max(0, posX), window.innerWidth - gui.offsetWidth);
      posY = Math.min(Math.max(0, posY), window.innerHeight - gui.offsetHeight);

      gui.style.left = posX + 'px';
      gui.style.top = posY + 'px';
      gui.style.right = '';
      gui.style.bottom = '';
      gui.style.position = 'fixed';
    }
  });

  // Logs window drag
  let logDragOffsetX=0, logDragOffsetY=0, logIsDragging=false;
  logsWindow.addEventListener('mousedown', e => {
    if(e.target === clearLogsBtn) return;
    logIsDragging=true;
    const r = logsWindow.getBoundingClientRect();
    logDragOffsetX = e.clientX - r.left;
    logDragOffsetY = e.clientY - r.top;
    document.body.style.userSelect = 'none';
  });
  window.addEventListener('mouseup', () => {
    logIsDragging=false;
    document.body.style.userSelect = '';
  });
  window.addEventListener('mousemove', e => {
    if(logIsDragging){
      let lnX = e.clientX - logDragOffsetX;
      let lnY = e.clientY - logDragOffsetY;
      lnX = Math.min(Math.max(0, lnX), window.innerWidth - logsWindow.offsetWidth);
      lnY = Math.min(Math.max(0, lnY), window.innerHeight - logsWindow.offsetHeight);
      logsWindow.style.left = lnX + 'px';
      logsWindow.style.top = lnY + 'px';
      logsWindow.style.position = 'fixed';
      logsWindow.style.right = '';
      logsWindow.style.bottom = '';
    }
  });

  // Minimize toggle
  minimizeBtn.onclick = () => {
    isMinimized = !isMinimized;
    if (isMinimized) {
      gui.style.height = '40px';
      gui.querySelector('#sandbox-tabs-container').style.display = 'none';
      minimizeBtn.textContent = '❐';
    } else {
      gui.style.height = '600px';
      gui.querySelector('#sandbox-tabs-container').style.display = 'flex';
      minimizeBtn.textContent = '_';
    }
  };

  // Tab switching
  tabButtons.forEach(btn => {
    btn.addEventListener('click', e => {
      tabButtons.forEach(b => b.classList.remove('active'));
      tabContents.forEach(c => (c.style.display = 'none'));
      btn.classList.add('active');
      const targetTab = btn.dataset.tab;
      document.getElementById('tab-' + targetTab).style.display = 'block';
    });
  });

function initializeSandboxElements() {
  allCssClasses = extractAllCssClasses();

  // Add your known power-ups forcibly if missing
  allPowerUpTypes.forEach(pu => {
    if (!allCssClasses.includes(pu)) {
      allCssClasses.push(pu);
    }
  });

  allCssClasses.sort();
  filteredClasses = allCssClasses;

  currentElementPage = 0;
  selectedElementClass = null;
  spawnElementBtn.disabled = true;
  searchInput.value = '';
  previewContainer.innerHTML = '<em>Select element to preview</em>';

  displayElementList();
}

function enableEnemySelection() {
  enemies.forEach(enemy => {
    if (!enemy._selectionEnabled) {
      enemy.addEventListener('click', (e) => {
        e.stopPropagation();
        if (selectedEnemy) selectedEnemy.style.outline = '';
        selectedEnemy = enemy;
        selectedEnemy.style.outline = '2px solid magenta';
        selectedEnemyInfoSpan.textContent = `Class: ${selectedEnemy.className}`;
        log(`Selected enemy: ${selectedEnemy.className}`);
      });
      enemy._selectionEnabled = true;
    }
  });
}

gameWorld.addEventListener('click', () => {
  if (selectedEnemy) {
    selectedEnemy.style.outline = '';
    selectedEnemy = null;
    selectedEnemyInfoSpan.textContent = 'None';
    log('Deselected enemy.');
  }
});

  // --- All Elements Tab functions ---

  // Extract all CSS classes from embedded stylesheets
  const allPowerUpTypes = [
    "super-speed", "invincibility", "teleportation",
    "reflective-shield", "double-shot", "extra-life",
    "score-boost", "mega-jump", "energy-blast", "light-speed",
    "blazing-trail", "sonic-wave", "armor", "telekinetic",
    "camouflage", "dimension-shift", "energy-drain", "mind-control",
    "hologram", "fire", "ice", "hypno"
  ];

  // Recursively process a list of CSSRules and add all classes found
function extractAllCssClasses() {
  const classesSet = new Set();


  function processRules(rules) {
    if (!rules) return;
    for (const rule of rules) {
      if (rule.type === CSSRule.STYLE_RULE) {
        if (rule.selectorText) {
          const selectors = rule.selectorText.split(/\s*,\s*/);
          for (const sel of selectors) {
            const classMatches = sel.match(/\.(?:[\w-]+)/g);
            if (classMatches) {
              classMatches.forEach(cls => {
                classesSet.add(cls.substring(1));
              });
            }
          }
        }
      } else if (
        rule.type === CSSRule.MEDIA_RULE ||
        rule.type === CSSRule.SUPPORTS_RULE ||
        rule.type === CSSRule.DOCUMENT_RULE
      ) {
        processRules(rule.cssRules);
      }
    }
  }

  for (const sheet of document.styleSheets) {
    try {
      if (!sheet.cssRules) continue;
      processRules(sheet.cssRules);
    } catch (e) {
      // Ignore inaccessible sheets
    }
  }
  // Add power-up types forcibly to ensure inclusion
  allPowerUpTypes.forEach(pu => classesSet.add(pu));

  return Array.from(classesSet).sort();
}

function displayElementList() {
  const start = currentElementPage * elementsPerPage;
  const end = start + elementsPerPage;
  const toShow = filteredClasses.slice(start, end);

  elementListDiv.innerHTML = '';
  if (toShow.length === 0) {
    elementListDiv.innerHTML = '<em>No elements found.</em>';
    spawnElementBtn.disabled = true;
    previewContainer.innerHTML = '<em>Select element to preview</em>';
    selectedElementClass = null;
    updatePageInfo();
    return;
  }

  toShow.forEach(cls => {
    const el = document.createElement('div');
    el.textContent = cls;
    el.style.padding = '6px';
    el.style.cursor = 'pointer';
    el.style.borderBottom = '1px solid #0ff';
    el.title = 'Click to preview and spawn';

    if (cls === selectedElementClass) {
      el.style.backgroundColor = '#066';
    }

    el.onclick = () => {
      selectedElementClass = cls;
      spawnElementBtn.disabled = false;
      displayElementList(); // refresh to highlight selection
      showElementPreview(cls);
    };

    elementListDiv.appendChild(el);
  });

  updatePageInfo();
}

funTabBtn.addEventListener('click', () => {
  // Deactivate all tabs and hide contents
  document.querySelectorAll('.sandbox-tab-btn').forEach(btn => btn.classList.remove('active'));
  document.querySelectorAll('.sandbox-tab-content').forEach(c => c.style.display = 'none');

  // Activate Fun tab and show content
  funTabBtn.classList.add('active');
  funTabContent.style.display = 'block';
});

// --- Define your fun functions here ---
const funFunctions = [
  // Your original 5 fun functions:
  {
    name: 'Grant Extra Life',
    description: 'Add one life to player.',
    func: () => {
      lives = Math.min(lives + 1, 99);
      updateDisplay();
      log('Extra life granted!');
    }
  },
  {
    name: 'Magnet Field',
    description: 'Create a 150px magnet field around player pulling coins and power-ups for 8 seconds.',
    func: () => {
      const interval = setInterval(() => {
        [...coins, ...powerUps].forEach(obj => {
          const ox = parseInt(obj.style.left);
          const oy = parseInt(obj.style.bottom);
          let dx = playerPositionX - ox;
          let dy = playerPositionY - oy;
          let dist = Math.sqrt(dx*dx + dy*dy);
          if(dist < 150 && dist > 1){
            obj.style.left = ox + dx * 0.15 + 'px';
            obj.style.bottom = oy + dy * 0.15 + 'px';
          }
        });
      }, 50);
      setTimeout(() => {
        clearInterval(interval);
        log('Magnet field expired!');
      }, 8000);
      log('Magnet field activated!');
    }
  },
  {
    name: 'Super Bounce',
    description: 'Launch player with a massive bounce (3x jump strength).',
    func: () => {
      playerVelocityY = playerJumpStrength * 3;
      isJumping = true;
      jumpCount++;
      log('Super bounce triggered!');
    }
  },
  {
    name: 'Double Score',
    description: 'Double all points earned for 15 seconds.',
    func: () => {
      let origAddScore = window.addScore;
      window.addScore = function(amount){
        origAddScore(amount*2);
      };
      log('Score doubled!');
      setTimeout(() => {
        window.addScore = origAddScore;
        log('Score double ended!');
      }, 15000);
    }
  },
  {
    name: 'Multiple Rockets',
    description: 'Fire 5 rockets in rapid succession.',
    func: () => {
      let count = 0;
      const rocketInterval = setInterval(() => {
        if (count >= 5) {
          clearInterval(rocketInterval);
          log('Rocket barrage ended!');
          return;
        }
        shootFire();
        count++;
      }, 200);
      log('Firing multiple rockets!');
    }
  },
  {
    name: 'Invisibility Cloak',
    description: 'Player turns invisible, cannot be hit for 7 seconds.',
    func: () => {
      player.style.opacity = '0.15';
      isInvincible = true;
      log('Player invisible and invincible!');
      setTimeout(() => {
        player.style.opacity = '1';
        isInvincible = false;
        log('Invisibility ended!');
      }, 7000);
    }
  },
  {
    name: 'Spin Dash',
    description: 'Player spins and dashes forward 200px damaging enemies hit.',
    func: () => {
      let distance = 0;
      let speed = 20;
      player.classList.add('glow');
      const dashInterval = setInterval(() => {
        if (distance >= 200) {
          clearInterval(dashInterval);
          player.classList.remove('glow');
          log('Spin dash ended!');
          return;
        }
        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';

        enemies.forEach((enemy, idx) => {
          if (checkCollision(player, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy hit by spin dash!');
          }
        });
        distance += speed;
      }, 40);
      log('Spin dash started!');
    }
  },
  {
    name: 'Summon Shield Drone',
    description: 'Summon a drone that protects player absorbing 3 hits for 5 seconds.',
    func: () => {
      const drone = document.createElement('div');
      drone.style.position = 'absolute';
      drone.style.width = '40px';
      drone.style.height = '40px';
      drone.style.borderRadius = '50%';
      drone.style.border = '2px solid cyan';
      drone.style.left = (playerPositionX + player.offsetWidth / 2 - 20) + 'px';
      drone.style.bottom = (playerPositionY + player.offsetHeight / 2 - 20) + 'px';
      drone.style.zIndex = 2000;
      gameWorld.appendChild(drone);
      log('Shield drone summoned!');

      let hitsLeft = 3;
      drone.dataset.hitsLeft = hitsLeft;

      const droneInterval = setInterval(() => {
        if (hitsLeft <= 0) {
          drone.remove();
          clearInterval(droneInterval);
          log('Shield drone destroyed!');
          return;
        }
        // Follow player
        drone.style.left = (playerPositionX + player.offsetWidth / 2 - 20) + 'px';
        drone.style.bottom = (playerPositionY + player.offsetHeight / 2 - 20) + 'px';

        bullets.forEach((bulletObj, idx) => {
          const bullet = bulletObj.element;
          if (checkCollision(drone, bullet)) {
            bullet.remove();
            bullets.splice(idx, 1);
            hitsLeft--;
            drone.dataset.hitsLeft = hitsLeft;
            log(`Drone absorbed a hit! Hits left: ${hitsLeft}`);
          }
        });

        enemies.forEach((enemy, idx) => {
          if (checkCollision(drone, enemy)) {
            enemy.remove();
            enemies.splice(idx, 1);
            hitsLeft--;
            drone.dataset.hitsLeft = hitsLeft;
            log(`Drone destroyed enemy! Hits left: ${hitsLeft}`);
          }
        });
      }, 100);
      setTimeout(() => {
        if (drone.parentElement) {
          drone.remove();
          clearInterval(droneInterval);
          log('Shield drone time ended!');
        }
      }, 5000);
    }
  },
  {
    name: 'Earthquake',
    description: 'Shake the screen and knock back all enemies for 4 seconds.',
    func: () => {
      shakeScreen();
      const knockbackInterval = setInterval(() => {
        enemies.forEach(enemy => {
          let enemyLeft = parseInt(enemy.style.left);
          let knockAmount = (enemyLeft < playerPositionX) ? -30 : 30;
          enemy.style.left = enemyLeft + knockAmount + 'px';
        });
      }, 200);
      setTimeout(() => {
        clearInterval(knockbackInterval);
        log('Earthquake ended!');
      }, 4000);
      log('Earthquake activated!');
    }
  },
  {
    name: 'Inferno Burst',
    description: 'Release a powerful burst of fire around the player.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      let radius = 150;
      enemies.forEach((enemy, idx) => {
        let dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist <= radius){
          applyBurn(enemy);
          log('Enemy burned by Inferno Burst!');
        }
      });
      log('Inferno Burst activated!');
    }
  },
  {
    name: 'Power Surge',
    description: 'Double player speed and damage for 10 seconds.',
    func: () => {
      playerMaxSpeed *= 2;
      window.addScore = (old => amount => old(amount * 2))(window.addScore || ((a)=>{}));
      player.classList.add('glow');
      log('Power Surge activated! Speed and damage doubled!');
      setTimeout(() => {
        playerMaxSpeed /= 2;
        // Restore original addScore
        window.addScore = (amount) => { score += amount; updateDisplay(); };
        player.classList.remove('glow');
        log('Power Surge ended!');
      }, 10000);
    }
  },
  {
    name: 'Rapid Reload',
    description: 'Shoot 20 bullets in rapid succession.',
    func: () => {
      let shots = 0;
      const interval = setInterval(() => {
        shootBullet(currentDirection);
        shots++;
        if (shots >= 20) {
          clearInterval(interval);
          log('Rapid Reload ended!');
        }
      }, 80);
      log('Rapid Reload started!');
    }
  },
  {
    name: 'Ice Storm',
    description: 'Slow and freeze enemies randomly for 8 seconds.',
    func: () => {
      enemies.forEach(enemy => {
        let speed = parseFloat(enemy.dataset.speed) || 1;
        enemy.dataset.speed = (speed * 0.4).toString();
      });
      log('Enemies slowed by Ice Storm!');
      const freezeInterval = setInterval(() => {
        if (enemies.length === 0) return;
        const enemy = enemies[Math.floor(Math.random()*enemies.length)];
        enemy.classList.add('frozen-enemy');
        enemy.style.opacity = '0.3';
        setTimeout(() => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
          log('Enemy unfrozen from Ice Storm!');
        }, 2000);
      }, 1500);
      setTimeout(() => {
        enemies.forEach(enemy => enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed) || 1).toString());
        clearInterval(freezeInterval);
        log('Ice Storm ended!');
      }, 8000);
      log('Ice Storm activated!');
    }
  },
  {
    name: 'Magnetize',
    description: 'Attract all power ups, coins, and enemies for 6 seconds.',
    func: () => {
      const allObjects = [...coins, ...powerUps, ...enemies];
      const interval = setInterval(() => {
        allObjects.forEach(obj => {
          let ox = parseFloat(obj.style.left);
          let oy = parseFloat(obj.style.bottom);
          let nx = ox + (playerPositionX - ox)*0.1;
          let ny = oy + (playerPositionY - oy)*0.1;
          obj.style.left = nx + 'px';
          obj.style.bottom = ny + 'px';
        });
      }, 50);
      setTimeout(() => {
        clearInterval(interval);
        log('Magnetize effect ended!');
      }, 6000);
      log('Magnetize started!');
    }
  },
  {
    name: 'Laser Barrage',
    description: 'Player shoots lasers in eight directions rapidly for 5 seconds.',
    func: () => {
      const angles = [0, 45, 90, 135, 180, 225, 270, 315];
      let count = 0;
      const interval = setInterval(() => {
        angles.forEach(angle => {
          const bullet = document.createElement('div');
          bullet.classList.add('bullet');
          bullet.style.position = 'absolute';
          bullet.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
          bullet.style.bottom = (playerPositionY + player.offsetHeight/2) + 'px';
          bullet.style.width = '8px';
          bullet.style.height = '4px';
          bullet.style.backgroundColor = 'red';
          bullet.style.borderRadius = '2px';
          gameWorld.appendChild(bullet);
          let rad = angle * Math.PI/180;
          let speed = 8;
          let frameId;
          function moveBullet() {
            if(!bullet.parentElement)return cancelAnimationFrame(frameId);
            let left = parseFloat(bullet.style.left);
            let bottom = parseFloat(bullet.style.bottom);
            bullet.style.left = (left + Math.cos(rad)*speed) + 'px';
            bullet.style.bottom = (bottom + Math.sin(rad)*speed) + 'px';
            if(left < 0 || left > gameWorld.offsetWidth || bottom < 0 || bottom > gameWorld.offsetHeight){
              bullet.remove();
              cancelAnimationFrame(frameId);
            }
            frameId = requestAnimationFrame(moveBullet);
          }
          moveBullet();
        });
        count++;
        if(count >= 25){
          clearInterval(interval);
          log('Laser Barrage ended!');
        }
      }, 200);
      log('Laser Barrage started!');
    }
  },
  {
    name: 'Poison Cloud',
    description: 'Spawn a moving cloud that poisons enemies over time for 8 seconds.',
    func: () => {
      const cloud = document.createElement('div');
      cloud.style.position = 'absolute';
      cloud.style.left = playerPositionX + 'px';
      cloud.style.bottom = (playerPositionY + 100) + 'px';
      cloud.style.width = '150px';
      cloud.style.height = '100px';
      cloud.style.backgroundColor = 'rgba(0,128,0,0.5)';
      cloud.style.borderRadius = '50%';
      gameWorld.appendChild(cloud);

      const poisonInterval = setInterval(() => {
        enemies.forEach(enemy => {
          if(checkCollision(cloud, enemy)){
            applyBurn(enemy);
          }
        });
        cloud.style.left = (parseInt(cloud.style.left) + 2) + 'px'; // move cloud right
      }, 300);

      setTimeout(() => {
        clearInterval(poisonInterval);
        cloud.remove();
        log('Poison Cloud disappeared!');
      }, 8000);
      log('Poison Cloud spawned!');
    }
  },
  {
    name: 'Teleport Barrage',
    description: 'Teleport randomly and shoot fire bullets rapidly for 6 seconds.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        playerPositionX = Math.max(0, Math.min(gameWorld.offsetWidth - player.offsetWidth, Math.random() * gameWorld.offsetWidth));
        player.style.left = playerPositionX + 'px';
        shootFire();
        count++;
        if(count >= 30){
          clearInterval(interval);
          log('Teleport Barrage ended!');
        }
      }, 200);
      log('Teleport Barrage started!');
    }
  },
  {
    name: 'Shield Boost',
    description: 'Add a shield that absorbs 4 hits and +2 extra lives.',
    func: () => {
      lives = Math.min(lives + 2, 99);
      player.style.border = '4px double gold';
      player.dataset.shieldHits = '4';
      log('Shield Boost activated! +2 lives and shield up.');
      setTimeout(() => {
        player.style.border = '';
        delete player.dataset.shieldHits;
        log('Shield Boost expired!');
      }, 10000);
    }
  },
  {
    name: 'Summon Minions',
    description: 'Spawn 4 minions that follow and attack enemies for 10 seconds.',
    func: () => {
      const minions = [];
      for(let i=0; i<4; i++) {
        let m = document.createElement('div');
        m.style.position = 'absolute';
        m.style.width = '20px';
        m.style.height = '20px';
        m.style.borderRadius = '50%';
        m.style.backgroundColor = 'lightblue';
        m.style.left = (playerPositionX + i * 25) + 'px';
        m.style.bottom = (playerPositionY + 20) + 'px';
        gameWorld.appendChild(m);
        minions.push(m);
      }
      const interval = setInterval(() => {
        minions.forEach((minion, idx) => {
          if (!minion.parentElement) return;
          // Follow player smoothly
          let mx = parseFloat(minion.style.left);
          let my = parseFloat(minion.style.bottom);
          let dx = playerPositionX + player.offsetWidth / 2 - mx;
          let dy = playerPositionY + player.offsetHeight / 2 - my;
          minion.style.left = mx + dx * 0.1 + 'px';
          minion.style.bottom = my + dy * 0.1 + 'px';

          enemies.forEach((enemy, eidx) => {
            if (checkCollision(minion, enemy)) {
              enemy.remove();
              enemies.splice(eidx, 1);
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              log('Minion killed an enemy!');
            }
          });
        });
      }, 50);

      setTimeout(() => {
        clearInterval(interval);
        minions.forEach(m => m.remove());
        log('Minions disappeared!');
      }, 10000);
      log('Minions summoned!');
    }
  },
  {
    name: 'Energy Wave',
    description: 'Send a wave damaging enemy obstacles across the screen.',
    func: () => {
      let x = playerPositionX;
      const wave = document.createElement('div');
      wave.style.position = 'absolute';
      wave.style.bottom = playerPositionY + 'px';
      wave.style.left = x + 'px';
      wave.style.width = '50px';
      wave.style.height = '40px';
      wave.style.backgroundColor = 'lime';
      wave.style.opacity = '0.6';
      wave.style.borderRadius = '20%';
      gameWorld.appendChild(wave);

      const interval = setInterval(() => {
        x += 10;
        wave.style.left = x + 'px';
        obstacles.forEach((obstacle, idx) => {
          if(checkCollision(wave, obstacle)){
            obstacle.remove();
            obstacles.splice(idx, 1);
            createBurst(parseInt(obstacle.style.left), parseInt(obstacle.style.bottom));
            log('Obstacle destroyed by energy wave!');
          }
        });
        enemies.forEach((enemy, idx) => {
          if (checkCollision(wave, enemy)) {
            enemy.remove();
            enemies.splice(idx, 1);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            log('Enemy destroyed by energy wave!');
          }
        });
        if (x > gameWorld.offsetWidth) {
          wave.remove();
          clearInterval(interval);
          log('Energy wave ended!');
        }
      }, 20);
      log('Energy wave unleashed!');
    }
  },
  {
    name: 'Hyper Jump',
    description: 'Jump instantly 3x normal jump height.',
    func: () => {
      if (!isJumping && jumpCount < maxJumps) {
        playerVelocityY = playerJumpStrength * 3;
        jumpCount++;
        isJumping = true;
        log('Hyper jump executed!');
      }
    }
  },
  {
    name: 'Dash Slash',
    description: 'Dash forward 150px slicing enemies on touch.',
    func: () => {
      let distance = 0;
      const dashSpeed = 15;
      player.classList.add('glow');
      const interval = setInterval(() => {
        if (distance >= 150) {
          clearInterval(interval);
          player.classList.remove('glow');
          log('Dash Slash ended!');
          return;
        }
        playerPositionX = Math.min(playerPositionX + dashSpeed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';
        enemies.forEach((enemy, idx) => {
          if(checkCollision(player, enemy)){
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy sliced by Dash Slash!');
          }
        });
        distance += dashSpeed;
      }, 30);
      log('Dash Slash started!');
    }
  },
  {
    name: 'Mirror Shield',
    description: 'Reflect enemy bullets for 6 seconds.',
    func: () => {
      let reflectInterval = setInterval(() => {
        bullets.forEach(bulletObj => {
          const bullet = bulletObj.element;
          if(checkCollision(player, bullet)){
            bulletObj.direction *= -1;
            log('Enemy bullet reflected!');
          }
        });
      }, 50);
      log('Mirror Shield activated!');

      setTimeout(() => {
        clearInterval(reflectInterval);
        log('Mirror Shield expired!');
      }, 6000);
    }
  },
  {
    name: 'Bullet Rain',
    description: 'Fire rapid bullets downwards for 10 seconds.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        let bullet = createBullet(0);
        bullet.style.position = 'absolute';
        bullet.style.left = (playerPositionX + player.offsetWidth/2 - 5 + (Math.random()*30 - 15)) + 'px';
        bullet.style.bottom = (playerPositionY + player.offsetHeight) + 'px';
        bullet.style.width = '7px';
        bullet.style.height = '12px';
        bullet.style.backgroundColor = 'yellow';
        gameWorld.appendChild(bullet);

        let bInterval = setInterval(() => {
          bullet.style.bottom = (parseInt(bullet.style.bottom) - 15) + 'px';
          if(parseInt(bullet.style.bottom) <= 0){
            bullet.remove();
            clearInterval(bInterval);
          }
          enemies.forEach((enemy, idx) => {
            if(checkCollision(bullet, enemy)){
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx,1);
              bullet.remove();
              clearInterval(bInterval);
              log('Enemy hit by bullet rain!');
            }
          });
        }, 30);

        count++;
        if(count >= 80){
          clearInterval(interval);
          log('Bullet rain ended!');
        }
      }, 80);
      log('Bullet rain started!');
    }
  },
  {
    name: 'Black Hole',
    description: 'Summon a black hole that pulls enemies inward and then explodes.',
    func: () => {
      const hole = document.createElement('div');
      hole.style.position = 'absolute';
      hole.style.width = '160px';
      hole.style.height = '160px';
      hole.style.borderRadius = '50%';
      hole.style.backgroundColor = 'black';
      hole.style.left = (playerPositionX + player.offsetWidth/2 - 80) + 'px';
      hole.style.bottom = (playerPositionY + player.offsetHeight/2 - 80) + 'px';
      hole.style.opacity = '0.7';
      gameWorld.appendChild(hole);

      let pullFactor = 0.2;

      const pullInterval = setInterval(() => {
        enemies.forEach(enemy => {
          let ex = parseInt(enemy.style.left);
          let ey = parseInt(enemy.style.bottom);
          let dx = (playerPositionX + player.offsetWidth/2) - ex;
          let dy = (playerPositionY + player.offsetHeight/2) - ey;
          enemy.style.left = (ex + dx * pullFactor) + 'px';
          enemy.style.bottom = (ey + dy * pullFactor) + 'px';
        });
      }, 50);

      setTimeout(() => {
        clearInterval(pullInterval);
        enemies.forEach((enemy, idx) => {
          if (Math.hypot(
            parseInt(enemy.style.left) - (playerPositionX + player.offsetWidth/2),
            parseInt(enemy.style.bottom) - (playerPositionY + player.offsetHeight/2)
          ) < 100) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx,1);
            log('Enemy sucked into black hole!');
          }
        });
        hole.remove();
        log('Black hole exploded!');
      }, 5000);
      log('Black hole summoned!');
    }
  },
  {
    name: 'Fire Chain',
    description: 'Ignite a chain reaction fire that jumps between nearby enemies.',
    func: () => {
      if(enemies.length === 0){
        log('No enemies to ignite!');
        return;
      }
      let ignited = new Set();
      let current = enemies[Math.floor(Math.random()*enemies.length)];

      function igniteNext(enemy, times) {
        if(!enemy || times <= 0) return;
        applyBurn(enemy);
        ignited.add(enemy);
        log('Enemy ignited by fire chain!');
        setTimeout(() => {
          // Find nearest un-ignited enemy within 120 px
          let neighbors = enemies.filter(e => !ignited.has(e));
          neighbors = neighbors.filter(e => Math.hypot(
            parseInt(e.style.left)-parseInt(enemy.style.left),
            parseInt(e.style.bottom)-parseInt(enemy.style.bottom)
          ) <= 120);
          if(neighbors.length > 0) {
            igniteNext(neighbors[0], times-1);
          }
        }, 400);
      }
      igniteNext(current, 5);
      log('Fire Chain activated!');
    }
  },
  {
    name: 'Time Warp',
    description: 'Player moves twice as fast, enemies move half speed for 5 seconds.',
    func: () => {
      playerMaxSpeed *= 2;
      enemies.forEach(enemy => {
        enemy.dataset.originalSpeed = enemy.dataset.speed || '1';
        enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed) * 0.5).toString();
      });
      log('Time Warp activated!');
      setTimeout(() => {
        playerMaxSpeed /= 2;
        enemies.forEach(enemy => {
          enemy.dataset.speed = enemy.dataset.originalSpeed;
          delete enemy.dataset.originalSpeed;
        });
        log('Time Warp ended!');
      }, 5000);
    }
  },
  {
    name: 'Exploding Mines',
    description: 'Drop 5 mines that explode after 2 seconds damaging enemies nearby.',
    func: () => {
      for(let i=0; i<5; i++) {
        let mine = document.createElement('div');
        mine.style.position = 'absolute';
        mine.style.width = '18px';
        mine.style.height = '18px';
        mine.style.backgroundColor = 'darkred';
        mine.style.borderRadius = '50%';
        mine.style.left = (playerPositionX + (Math.random()-0.5)*200) + 'px';
        mine.style.bottom = playerPositionY + 'px';
        gameWorld.appendChild(mine);
        setTimeout(() => {
          createBurst(parseInt(mine.style.left), parseInt(mine.style.bottom));
          enemies.forEach((enemy, idx) => {
            if (Math.hypot(parseInt(enemy.style.left) - parseInt(mine.style.left), parseInt(enemy.style.bottom) - parseInt(mine.style.bottom)) < 120) {
              enemy.remove();
              enemies.splice(idx,1);
              log('Enemy destroyed by mine explosion!');
            }
          });
          mine.remove();
        }, 2000 + i*300);
      }
      log('Exploding mines planted!');
    }
  },
  {
    name: 'Electric Surge',
    description: 'Shock all enemies for massive damage instantly.',
    func: () => {
      enemies.forEach((enemy, idx) => {
        createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
        enemy.remove();
        enemies.splice(idx, 1);
      });
      log('Electric Surge zapped all enemies!');
    }
  },
  {
    name: 'Sticky Web',
    description: 'Launch a sticky web that slows enemies in its path for 6 seconds.',
    func: () => {
      const web = document.createElement('div');
      web.style.position = 'absolute';
      web.style.left = playerPositionX + 'px';
      web.style.bottom = (playerPositionY + 20) + 'px';
      web.style.width = '100px';
      web.style.height = '20px';
      web.style.backgroundColor = 'rgba(150,75,0,0.7)';
      gameWorld.appendChild(web);

      enemies.forEach(enemy => {
        if (checkCollision(web, enemy)) {
          enemy.dataset.originalSpeed = enemy.dataset.speed || '1';
          enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed)*0.3).toString();
          enemy.classList.add('slowed-enemy');
        }
      });

      setTimeout(() => {
        enemies.forEach(enemy => {
          if(enemy.classList.contains('slowed-enemy')){
            enemy.dataset.speed = enemy.dataset.originalSpeed;
            enemy.classList.remove('slowed-enemy');
            delete enemy.dataset.originalSpeed;
          }
        });
        web.remove();
        log('Sticky Web ended!');
      }, 6000);
      log('Sticky Web created!');
    }
  },
  {
    name: 'Summon Fire Elemental',
    description: 'Spawn a fire elemental that patrols and burns enemies for 10 seconds.',
    func: () => {
      const elemental = document.createElement('div');
      elemental.style.position = 'absolute';
      elemental.style.width = '40px';
      elemental.style.height = '40px';
      elemental.style.borderRadius = '50%';
      elemental.style.backgroundColor = 'orange';
      elemental.style.left = (playerPositionX + 100) + 'px';
      elemental.style.bottom = (playerPositionY) + 'px';
      gameWorld.appendChild(elemental);

      let direction = 1;
      const speed = 3;

      const interval = setInterval(() => {
        let x = parseInt(elemental.style.left);
        if(x <= playerPositionX + 50) direction = 1;
        else if(x >= playerPositionX + 150) direction = -1;

        elemental.style.left = (x + direction*speed) + 'px';

        enemies.forEach((enemy, idx) => {
          if (checkCollision(elemental, enemy)) {
            applyBurn(enemy);
            log('Enemy burned by fire elemental!');
          }
        });
      }, 50);

      setTimeout(() => {
        clearInterval(interval);
        elemental.remove();
        log('Fire elemental vanished!');
      }, 10000);
      log('Fire elemental summoned!');
    }
  },
  {
    name: 'Dark Pulse',
    description: 'Emit a dark pulse that briefly stuns all enemies around player.',
    func: () => {
      enemies.forEach(enemy => {
        let dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 250) {
          enemy.classList.add('frozen-enemy');
          enemy.style.opacity = '0.3';
          setTimeout(() => {
            enemy.classList.remove('frozen-enemy');
            enemy.style.opacity = '1';
            log('Enemy recovered from dark pulse stun!');
          }, 3000);
        }
      });
      log('Dark Pulse emitted!');
    }
  },
  {
    name: 'Double Fire',
    description: 'Shoot two fire bullets simultaneously.',
    func: () => {
      shootFire();
      setTimeout(shootFire, 100);
      log('Double fire bullets shot!');
    }
  },
  {
    name: 'Multi-Dash',
    description: 'Dash 4 times rapidly forward damaging enemies on contact.',
    func: () => {
      let dashes = 0;
      const dashDist = 80;
      const dashSpeed = 20;
      const dash = () => {
        if(dashes >= 4){
          log('Multi-Dash ended!');
          return;
        }
        dashes++;
        let dist = 0;
        const interval = setInterval(() => {
          if(dist >= dashDist){
            clearInterval(interval);
            setTimeout(dash, 150);
            return;
          }
          playerPositionX = Math.min(playerPositionX + dashSpeed, gameWorld.offsetWidth - player.offsetWidth);
          player.style.left = playerPositionX + 'px';
          enemies.forEach((enemy, idx) => {
            if(checkCollision(player, enemy)){
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              log('Enemy hit by multi-dash!');
            }
          });
          dist += dashSpeed;
        }, 30);
      };
      dash();
      log('Multi-Dash started!');
    }
  },
  {
    name: 'Scatter Shot',
    description: 'Shoot 8 bullets in a wide spread.',
    func: () => {
      for(let angle = -35; angle <= 35; angle += 10){
        const bullet = createBullet(currentDirection);
        bullet.style.transform = `rotate(${angle}deg)`;
        bullet.style.backgroundColor = 'yellow';
        gameWorld.appendChild(bullet);

        let rad = (angle + (currentDirection > 0 ? 0 : 180)) * Math.PI/180;
        let speed = 7 + Math.random()*3;
        let x = playerPositionX + player.offsetWidth / 2;
        let y = playerPositionY + player.offsetHeight / 2;

        function move() {
          if(!bullet.parentElement) return;
          x += Math.cos(rad)*speed;
          y += Math.sin(rad)*speed;
          bullet.style.left = x + 'px';
          bullet.style.bottom = y + 'px';

          enemies.forEach((enemy, idx) => {
            if (checkCollision(bullet, enemy)) {
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              log('Enemy hit by scatter shot!');
              bullet.remove();
              return;
            }
          });
          if(x < 0 || x > gameWorld.offsetWidth || y < 0 || y > gameWorld.offsetHeight) {
            bullet.remove();
            return;
          }
          requestAnimationFrame(move);
        }
        move();
      }
      log('Scatter shot fired!');
    }
  },
  {
    name: 'Healing Aura',
    description: 'Player heals 1 life every 3 seconds for 15 seconds.',
    func: () => {
      let ticks = 0;
      const interval = setInterval(() => {
        if(lives < 99){
          lives++;
          updateDisplay();
          log('Healing aura restored 1 life!');
        }
        ticks++;
        if(ticks >= 5){
          clearInterval(interval);
          log('Healing aura ended!');
        }
      }, 3000);
      log('Healing aura activated!');
    }
  },
  {
    name: 'Force Push',
    description: 'Push all enemies backward 150px instantly.',
    func: () => {
      enemies.forEach(enemy => {
        const enemyLeft = parseInt(enemy.style.left);
        let newLeft = enemyLeft + 150 * (enemyLeft < playerPositionX ? -1 : 1);
        newLeft = Math.min(gameWorld.offsetWidth - enemy.offsetWidth, Math.max(0, newLeft));
        enemy.style.left = newLeft + 'px';
        log('Enemy pushed by force push!');
      });
      log('Force Push activated!');
    }
  },
  {
    name: 'Summon Turret',
    description: 'Summon a turret near player that shoots at enemies for 8 seconds.',
    func: () => {
      const turret = document.createElement('div');
      turret.style.position = 'absolute';
      turret.style.left = (playerPositionX + 60) + 'px';
      turret.style.bottom = (playerPositionY) + 'px';
      turret.style.width = '30px';
      turret.style.height = '30px';
      turret.style.backgroundColor = 'darkgray';
      turret.style.borderRadius = '50%';
      gameWorld.appendChild(turret);

      let shotsFired = 0;
      const maxShots = 30;
      const shootInterval = setInterval(() => {
        if(shotsFired >= maxShots){
          clearInterval(shootInterval);
          turret.remove();
          log('Turret vanished!');
          return;
        }
        // Shoot at nearest enemy
        if(enemies.length > 0){
          let nearestEnemy = enemies.reduce((prev, curr) => {
            const prevDist = Math.hypot(parseInt(prev.style.left) - parseInt(turret.style.left), parseInt(prev.style.bottom) - parseInt(turret.style.bottom));
            const currDist = Math.hypot(parseInt(curr.style.left) - parseInt(turret.style.left), parseInt(curr.style.bottom) - parseInt(turret.style.bottom));
            return currDist < prevDist ? curr : prev;
          });
          const bullet = document.createElement('div');
          bullet.classList.add('bullet');
          bullet.style.position = 'absolute';
          bullet.style.left = turret.style.left;
          bullet.style.bottom = turret.style.bottom;
          bullet.style.backgroundColor = 'red';
          bullet.style.width = '7px';
          bullet.style.height = '4px';
          gameWorld.appendChild(bullet);

          let bx = parseInt(bullet.style.left);
          let by = parseInt(bullet.style.bottom);
          let tx = parseInt(nearestEnemy.style.left);
          let ty = parseInt(nearestEnemy.style.bottom);
          const dist = Math.hypot(tx-bx, ty-by);
          const speed = 9;

          let frameId;
          function moveBullet(){
            if(!bullet.parentElement) return cancelAnimationFrame(frameId);
            let dx = (tx - bx)/dist * speed;
            let dy = (ty - by)/dist * speed;
            bx += dx;
            by += dy;
            bullet.style.left = bx + 'px';
            bullet.style.bottom = by + 'px';
            if(checkCollision(bullet, nearestEnemy)){
              createBurst(parseInt(nearestEnemy.style.left), parseInt(nearestEnemy.style.bottom));
              nearestEnemy.remove();
              enemies.splice(enemies.indexOf(nearestEnemy),1);
              bullet.remove();
              cancelAnimationFrame(frameId);
              log('Turret bullet hit enemy!');
              return;
            }
            if(bx < 0 || bx > gameWorld.offsetWidth || by < 0 || by > gameWorld.offsetHeight){
              bullet.remove();
              cancelAnimationFrame(frameId);
              return;
            }
            frameId = requestAnimationFrame(moveBullet);
          }
          moveBullet();
        }
        shotsFired++;
      }, 300);
      log('Turret summoned!');
    }
  },
  {
    name: 'Cannon Shot',
    description: 'Launch a cannon ball that destroys obstacles on impact.',
    func: () => {
      const cannon = document.createElement('div');
      cannon.style.position = 'absolute';
      cannon.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
      cannon.style.bottom = (playerPositionY + player.offsetHeight/2) + 'px';
      cannon.style.width = '18px';
      cannon.style.height = '18px';
      cannon.style.backgroundColor = 'black';
      cannon.style.borderRadius = '50%';
      gameWorld.appendChild(cannon);

      let x = parseInt(cannon.style.left);
      let y = parseInt(cannon.style.bottom);
      let speedX = 10 * currentDirection;
      let speedY = 6;
      let gravityEffect = 0.4;

      function move() {
        if(!cannon.parentElement) return;
        x += speedX;
        y += speedY;
        speedY -= gravityEffect;
        cannon.style.left = x + 'px';
        cannon.style.bottom = y + 'px';

        obstacles.forEach((obstacle, idx) => {
          if(checkCollision(cannon, obstacle)){
            createBurst(parseInt(obstacle.style.left), parseInt(obstacle.style.bottom));
            obstacle.remove();
            obstacles.splice(idx,1);
            cannon.remove();
            log('Obstacle destroyed by cannon shot!');
          }
        });

        if(y <= 0){
          cannon.remove();
          log('Cannon shot landed!');
          return;
        }
        requestAnimationFrame(move);
      }
      move();
      log('Cannon shot fired!');
    }
  },
  {
    name: 'Elemental Fury',
    description: 'Randomly cast fire, ice or lightning bullets for 15 seconds.',
    func: () => {
      const effects = ['fire', 'ice', 'hypno'];
      let count = 0;
      const interval = setInterval(() => {
        if(count >= 50){
          clearInterval(interval);
          log('Elemental Fury ended!');
          return;
        }
        const effect = effects[Math.floor(Math.random()*effects.length)];
        switch(effect){
          case 'fire': shootFire(); break;
          case 'ice': shootIce(); break;
          case 'hypno': shootHypno(); break;
        }
        count++;
      }, 300);
      log('Elemental Fury started!');
    }
  },
  {
    name: 'Pulse Wave',
    description: 'Emit a pulsing wave every second for 6 seconds damaging enemies.',
    func: () => {
      let pulseCount = 0;
      const interval = setInterval(() => {
        createBurst(playerPositionX, playerPositionY);
        enemies.forEach((enemy, idx) => {
          if (Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY) < 120){
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy hit by pulse wave!');
          }
        });
        pulseCount++;
        if (pulseCount >= 6) {
          clearInterval(interval);
          log('Pulse Wave ended!');
        }
      }, 1000);
      log('Pulse Wave activated!');
    }
  },
  {
    name: 'Ice Spikes',
    description: 'Create spikes from ground that freeze enemies for 3 seconds.',
    func: () => {
      let spikes = [];
      for(let i=0; i < 6; i++) {
        let spike = document.createElement('div');
        spike.style.position = 'absolute';
        let x = playerPositionX + i*40 - 80;
        spike.style.left = x + 'px';
        spike.style.bottom = '0px';
        spike.style.width = '20px';
        spike.style.height = '60px';
        spike.style.backgroundColor = 'lightblue';
        spike.style.borderRadius = '0 0 10px 10px';
        gameWorld.appendChild(spike);
        spikes.push(spike);
      }
      enemies.forEach(enemy => {
        spikes.forEach(spike => {
          if(checkCollision(enemy, spike)){
            enemy.classList.add('frozen-enemy');
            enemy.style.opacity = '0.2';
            setTimeout(() => {
              enemy.classList.remove('frozen-enemy');
              enemy.style.opacity = '1';
              log('Enemy unfrozen from ice spikes!');
            }, 3000);
          }
        });
      });
      setTimeout(() => {
        spikes.forEach(sp => sp.remove());
        log('Ice spikes disappeared!');
      }, 5000);
      log('Ice spikes spawned!');
    }
  },
  {
    name: 'Shock Chain',
    description: 'Electric shocks jump between up to 5 enemies.',
    func: () => {
      if (!enemies.length) return log('No enemies for Shock Chain!');
      let shocked = new Set();
      let startEnemy = enemies[Math.floor(Math.random()*enemies.length)];

      function shock(enemy, jumps) {
        if(!enemy || jumps <= 0) return;
        shocked.add(enemy);
        enemy.style.backgroundColor = 'yellow';
        setTimeout(() => enemy.style.backgroundColor = '', 500);
        enemy.remove();
        enemies.splice(enemies.indexOf(enemy), 1);
        log('Enemy shocked!');

        let nearby = enemies.filter(e => !shocked.has(e) && Math.hypot(parseInt(e.style.left) - parseInt(enemy.style.left), parseInt(e.style.bottom) - parseInt(enemy.style.bottom)) < 120);
        if(nearby.length) {
          setTimeout(() => shock(nearby[0], jumps-1), 400);
        }
      }
      shock(startEnemy, 5);
      log('Shock Chain activated!');
    }
  },
  {
    name: 'Rapid Heal',
    description: 'Heal player by 1 life every 0.5 sec for 5 seconds.',
    func: () => {
      let times = 0;
      const interval = setInterval(() => {
        if (lives < 99) {
          lives++;
          updateDisplay();
          log('Rapid heal boosted life!');
        }
        times++;
        if (times >= 10) {
          clearInterval(interval);
          log('Rapid heal ended!');
        }
      }, 500);
      log('Rapid heal started!');
    }
  },
  {
    name: 'Hallucination',
    description: 'Player creates illusions confusing enemies for 6 seconds.',
    func: () => {
      let copies = [];
      for(let i=0; i<3; i++){
        const copy = document.createElement('div');
        copy.style.position = 'absolute';
        copy.style.width = player.offsetWidth + 'px';
        copy.style.height = player.offsetHeight + 'px';
        copy.style.border = '2px dashed magenta';
        copy.style.left = (playerPositionX + (i-1)*50) + 'px';
        copy.style.bottom = playerPositionY + 'px';
        copy.style.opacity = '0.6';
        gameWorld.appendChild(copy);
        copies.push(copy);
      }
      enemies.forEach(enemy => enemy.classList.add('confused-enemy'));
      log('Hallucination illusions spawned!');
      setTimeout(() => {
        copies.forEach(copy => copy.remove());
        enemies.forEach(enemy => enemy.classList.remove('confused-enemy'));
        log('Hallucination ended!');
      }, 6000);
    }
  },
  {
    name: 'Fireball Barrage',
    description: 'Launch 10 fireballs straight forward rapidly.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        shootFire();
        count++;
        if(count >= 10) {
          clearInterval(interval);
          log('Fireball Barrage ended!');
        }
      }, 200);
      log('Fireball Barrage started!');
    }
  },
  {
    name: 'Freeze Grenade',
    description: 'Throw grenade freezing enemies within 100px radius after 2 seconds.',
    func: () => {
      let x = playerPositionX + player.offsetWidth/2;
      let y = playerPositionY + player.offsetHeight/2;

      const grenade = document.createElement('div');
      grenade.style.position = 'absolute';
      grenade.style.left = x + 'px';
      grenade.style.bottom = y + 'px';
      grenade.style.width = '15px';
      grenade.style.height = '15px';
      grenade.style.backgroundColor = '#00f';
      grenade.style.borderRadius = '50%';
      gameWorld.appendChild(grenade);

      setTimeout(() => {
        createBurst(x, y);
        enemies.forEach((enemy, idx) => {
          let dist = Math.hypot(parseInt(enemy.style.left) - x, parseInt(enemy.style.bottom) - y);
          if (dist < 100) {
            enemy.classList.add('frozen-enemy');
            enemy.style.opacity = '0.3';
            setTimeout(() => {
              enemy.classList.remove('frozen-enemy');
              enemy.style.opacity = '1';
              log('Enemy thawed from freeze grenade!');
            }, 4000);
          }
        });
        grenade.remove();
      }, 2000);
      log('Freeze grenade thrown!');
    }
  },
  {
    name: 'Bullet Shield',
    description: 'Create a shield that absorbs up to 10 bullets for 6 seconds.',
    func: () => {
      let shieldHits = 10;
      player.style.border = '4px outset cyan';
      log('Bullet Shield activated!');

      const interval = setInterval(() => {
        bullets.forEach((bulletObj, i) => {
          if(checkCollision(player, bulletObj.element)){
            shieldHits--;
            bulletObj.element.remove();
            bullets.splice(i,1);
            log('Bullet absorbed by shield!');
            if(shieldHits <= 0){
              clearInterval(interval);
              player.style.border = '';
              log('Bullet Shield broken!');
            }
          }
        });
      }, 50);

      setTimeout(() => {
        clearInterval(interval);
        player.style.border = '';
        log('Bullet Shield expired!');
      }, 6000);
    }
  },
  {
    name: 'Glitched Teleport',
    description: 'Teleport to random locations on screen rapidly (8 times).',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        playerPositionX = Math.random() * (gameWorld.offsetWidth - player.offsetWidth);
        playerPositionY = Math.random() * 200;
        player.style.left = playerPositionX + 'px';
        player.style.bottom = playerPositionY + 'px';
        log('Glitched teleport executed!');
        count++;
        if (count >= 8) {
          clearInterval(interval);
          log('Glitched Teleport ended!');
        }
      }, 300);
    }
  },
  {
    name: 'Tornado Spin',
    description: 'Player spins fast and pulls nearby enemies in for 6 seconds.',
    func: () => {
      player.classList.add('glow');

      const radius = 150;
      const spinInterval = setInterval(() => {
        enemies.forEach(enemy => {
          let ex = parseInt(enemy.style.left) + enemy.offsetWidth/2;
          let ey = parseInt(enemy.style.bottom) + enemy.offsetHeight/2;
          let px = playerPositionX + player.offsetWidth/2;
          let py = playerPositionY + player.offsetHeight/2;
          let dx = px - ex;
          let dy = py - ey;
          let dist = Math.sqrt(dx*dx + dy*dy);
          if(dist < radius){
            enemy.style.left = (parseInt(enemy.style.left) + dx*0.15) + 'px';
            enemy.style.bottom = (parseInt(enemy.style.bottom) + dy*0.15) + 'px';
          }
        });
      }, 50);

      setTimeout(() => {
        clearInterval(spinInterval);
        player.classList.remove('glow');
        log('Tornado Spin ended!');
      }, 6000);
      log('Tornado Spin started!');
    }
  },
  {
    name: 'Chain Fire',
    description: 'Shoot bullets that explode and ignite nearby enemies causing burn chain.',
    func: () => {
      const startX = playerPositionX + player.offsetWidth/2;
      const startY = playerPositionY + player.offsetHeight/2;
      const bullet = document.createElement('div');
      bullet.style.position = 'absolute';
      bullet.style.left = startX + 'px';
      bullet.style.bottom = startY + 'px';
      bullet.style.width = '10px';
      bullet.style.height = '5px';
      bullet.style.backgroundColor = 'red';
      bullet.style.borderRadius = '3px';
      gameWorld.appendChild(bullet);

      let x = startX;
      let speed = 10;

      function move() {
        if (!bullet.parentElement) return;
        x += currentDirection * speed;
        bullet.style.left = x + 'px';

        enemies.forEach((enemy, idx) => {
          if(checkCollision(bullet, enemy)){
            applyBurn(enemy);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));

            // Ignite nearby enemies chaining
            enemies.forEach(e => {
              let dist = Math.hypot(parseInt(e.style.left) - parseInt(enemy.style.left), parseInt(e.style.bottom) - parseInt(enemy.style.bottom));
              if (dist < 120) applyBurn(e);
            });

            bullet.remove();
            log('Chain Fire exploded!');
          }
        });

        if(x < 0 || x > gameWorld.offsetWidth){
          bullet.remove();
          log('Chain Fire bullet removed!');
          return;
        }
        requestAnimationFrame(move);
      }
      move();
      log('Chain Fire shot!');
    }
  },
  {
    name: 'Shock Trap',
    description: 'Place a shock trap that stuns enemies passing by for 5 seconds.',
    func: () => {
      const trap = document.createElement('div');
      trap.style.position = 'absolute';
      trap.style.left = playerPositionX + 'px';
      trap.style.bottom = '0px';
      trap.style.width = '60px';
      trap.style.height = '20px';
      trap.style.backgroundColor = 'cyan';
      trap.style.opacity = '0.7';
      gameWorld.appendChild(trap);

      const interval = setInterval(() => {
        enemies.forEach(enemy => {
          if(checkCollision(trap, enemy)){
            enemy.classList.add('frozen-enemy');
            enemy.style.opacity = '0.3';
            setTimeout(() => {
              enemy.classList.remove('frozen-enemy');
              enemy.style.opacity = '1';
              log('Enemy unfrozen from Shock Trap!');
            }, 2000);
          }
        });
      }, 100);

      setTimeout(() => {
        clearInterval(interval);
        trap.remove();
        log('Shock trap disappeared!');
      }, 5000);
      log('Shock Trap deployed!');
    }
  },
  {
    name: 'Lightning Strike',
    description: 'Call down a lightning strike on a targeted enemy.',
    func: () => {
      if(enemies.length === 0) {
        log('No enemies for Lightning Strike!');
        return;
      }
      const enemy = enemies[Math.floor(Math.random()*enemies.length)];
      const lightning = document.createElement('div');
      lightning.style.position = 'absolute';
      lightning.style.left = enemy.style.left;
      lightning.style.bottom = (parseInt(enemy.style.bottom)+enemy.offsetHeight) + 'px';
      lightning.style.width = '10px';
      lightning.style.height = '100px';
      lightning.style.backgroundColor = 'yellow';
      lightning.style.opacity = '0.9';
      gameWorld.appendChild(lightning);

      setTimeout(() => {
        lightning.remove();
        createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
        enemy.remove();
        enemies.splice(enemies.indexOf(enemy), 1);
        log('Lightning strike hit an enemy!');
      }, 500);
      log('Lightning Strike called!');
    }
  },
  {
    name: 'Invulnerability Burst',
    description: 'Become invulnerable and emit damaging bursts every second for 5 seconds.',
    func: () => {
      isInvincible = true;
      player.classList.add('flash');
      let count = 0;
      const interval = setInterval(() => {
        createBurst(playerPositionX, playerPositionY);
        enemies.forEach((enemy, idx) => {
          if(Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY) < 120){
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy hit by invulnerable burst!');
          }
        });
        count++;
        if(count >= 5){
          clearInterval(interval);
          isInvincible = false;
          player.classList.remove('flash');
          log('Invulnerability Burst ended!');
        }
      }, 1000);
      log('Invulnerability Burst started!');
    }
  },
  {
    name: 'Meteor Storm',
    description: 'Summon a storm of meteors that rain down for 10 seconds!',
    func: async () => {
      log('Meteor Storm summoned!');
      displayMessage('Meteor Storm Incoming!', 3);
      await sleep(3000);

      const rainCount = 30;
      for (let i = 0; i < rainCount; i++) {
        const meteor = document.createElement('div');
        meteor.style.position = 'absolute';
        meteor.style.width = '28px';
        meteor.style.height = '28px';
        meteor.style.borderRadius = '50%';
        meteor.style.backgroundColor = 'orangered';
        meteor.style.left = (gameScrollPosition + Math.random() * gameContainer.offsetWidth) + 'px';
        meteor.style.bottom = (gameContainer.offsetHeight + 50) + 'px';
        gameWorld.appendChild(meteor);

        let fallSpeed = 22 + Math.random() * 5;
        let interval = setInterval(() => {
          let bottom = parseInt(meteor.style.bottom);
          bottom -= fallSpeed;
          meteor.style.bottom = bottom + 'px';

          if (bottom <= 0) {
            createBurst(parseInt(meteor.style.left), 0);
            // Damage enemies and obstacles within 80px radius
            const centerX = parseInt(meteor.style.left) + 14;
            const centerY = 0;
            enemies.forEach((enemy, idx) => {
              const ex = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
              const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;
              if (Math.hypot(ex - centerX, ey - centerY) < 80) {
                enemy.remove();
                enemies.splice(idx, 1);
                log('Enemy pulverized by meteor!');
              }
            });
            obstacles.forEach((ob, idx) => {
              const ox = parseInt(ob.style.left) + ob.offsetWidth / 2;
              const oy = parseInt(ob.style.bottom) + ob.offsetHeight / 2;
              if (Math.hypot(ox - centerX, oy - centerY) < 80) {
                ob.remove();
                obstacles.splice(idx, 1);
                log('Obstacle shattered by meteor!');
              }
            });
            meteor.remove();
            clearInterval(interval);
          }
        }, 35);
        await sleep(300); // delay between meteors
      }
      log('Meteor Storm ended!');
    }
  },

  /** 3. Plasma Wave */
  {
    name: 'Plasma Wave',
    description: 'Create a plasma wave that expands and destroys all obstacles in its path.',
    func: () => {
      const wave = document.createElement('div');
      wave.style.position = 'absolute';
      wave.style.left = (playerPositionX - 50) + 'px';
      wave.style.bottom = (playerPositionY - 50) + 'px';
      wave.style.width = '100px';
      wave.style.height = '100px';
      wave.style.borderRadius = '50%';
      wave.style.background = 'radial-gradient(circle, #0ff, transparent)';
      wave.style.opacity = '0.7';
      wave.style.zIndex = 9999;
      gameWorld.appendChild(wave);

      let diameter = 100;
      const maxDiameter = 700;

      let interval = setInterval(() => {
        diameter += 20;
        wave.style.width = diameter + 'px';
        wave.style.height = diameter + 'px';
        wave.style.left = (playerPositionX - diameter/2 + player.offsetWidth/2) + 'px';
        wave.style.bottom = (playerPositionY - diameter/2 + player.offsetHeight/2) + 'px';

        obstacles.forEach((obstacle, idx) => {
          const ox = parseInt(obstacle.style.left) + obstacle.offsetWidth/2;
          const oy = parseInt(obstacle.style.bottom) + obstacle.offsetHeight/2;
          const centerX = playerPositionX + player.offsetWidth/2;
          const centerY = playerPositionY + player.offsetHeight/2;
          if (Math.hypot(ox - centerX, oy - centerY) < diameter/2) {
            obstacle.remove();
            obstacles.splice(idx, 1);
            log('Obstacle obliterated by plasma wave!');
          }
        });

        enemies.forEach((enemy, idx) => {
          const ex = parseInt(enemy.style.left) + enemy.offsetWidth/2;
          const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight/2;
          const centerX = playerPositionX + player.offsetWidth/2;
          const centerY = playerPositionY + player.offsetHeight/2;
          if (Math.hypot(ex - centerX, ey - centerY) < diameter/2) {
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy incinerated by plasma wave!');
          }
        });

        if (diameter > maxDiameter) {
          clearInterval(interval);
          wave.remove();
          log('Plasma wave ended!');
        }
      }, 60);

      log('Plasma wave launched!');
    }
  },

  /** 4. Shockwave Chain */
  {
    name: 'Shockwave Chain',
    description: 'Unleash sequential shockwaves knocking back enemies in waves.',
    func: async () => {
      const waves = 6;
      for(let i=0; i<waves; i++){
        createBurst(playerPositionX, playerPositionY);

        enemies.forEach(enemy => {
          const dist = Math.abs(parseInt(enemy.style.left) - playerPositionX);
          if(dist < 200 + i*50) {
            let newLeft = parseInt(enemy.style.left) + (enemy.style.left < playerPositionX ? -50 : 50);
            enemy.style.left = Math.max(0, Math.min(gameWorld.offsetWidth - enemy.offsetWidth, newLeft)) + 'px';
            log('Enemy knocked back by shockwave ' + (i+1));
          }
        });
        await sleep(800);
      }
      log('Shockwave Chain complete!');
    }
  },

  /** 5. Radial Laser Barrage */
  {
    name: 'Radial Laser Barrage',
    description: 'Fire lasers in a 360-degree spread around the player for 6 seconds.',
    func: () => {
      let count = 0;
      const lasersCount = 18;
      const laserLength = 60;

      const interval = setInterval(() => {
        for(let i=0; i < lasersCount; i++){
          const angle = (i * 20) * Math.PI/180;
          const laser = document.createElement('div');
          laser.style.position = 'absolute';
          laser.style.width = '6px';
          laser.style.height = laserLength + 'px';
          laser.style.backgroundColor = 'red';
          laser.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
          laser.style.bottom = (playerPositionY + player.offsetHeight/2) + 'px';
          laser.style.transformOrigin = 'center bottom';
          laser.style.transform = `rotate(${angle * 180/Math.PI}deg)`;
          laser.style.opacity = '0.85';
          gameWorld.appendChild(laser);

          setTimeout(() => {
            laser.remove();
          }, 400);

          enemies.forEach((enemy, idx) => {
            let dx = parseInt(enemy.style.left) + enemy.offsetWidth/2 - (playerPositionX + player.offsetWidth/2);
            let dy = parseInt(enemy.style.bottom) + enemy.offsetHeight/2 - (playerPositionY + player.offsetHeight/2);
            let dist = Math.sqrt(dx*dx + dy*dy);
            let laserX = Math.sin(angle)*laserLength;
            let laserY = Math.cos(angle)*laserLength;

            // Check if enemy is near laser path (within 20px when projected)
            let projectedDist = Math.abs(dx * Math.cos(angle) - dy * Math.sin(angle));
            if (dist < laserLength && projectedDist < 20) {
              enemy.remove();
              enemies.splice(idx, 1);
              log('Enemy vaporized by radial laser!');
            }
          });
        }

        count++;
        if(count >= 30) {
          clearInterval(interval);
          log('Radial Laser Barrage ended!');
        }
      }, 200);
      log('Firing radial laser barrage!');
    }
  },

  /** 6. Frenzy Dash */
  {
    name: 'Frenzy Dash',
    description: 'Dash forward repeatedly, damaging enemies with each pass for 8 seconds.',
    func: () => {
      const dashLength = 180;
      const dashSpeed = 20;
      let dashes = 0;
      let isDashRight = currentDirection > 0;
      const bounceBack = () => {
        isDashRight = !isDashRight;
      };
      const interval = setInterval(() => {
        if (dashes >= 20) {
          clearInterval(interval);
          log('Frenzy Dash ended!');
          return;
        }
        if (isDashRight) {
          playerPositionX = Math.min(playerPositionX + dashSpeed, gameWorld.offsetWidth - player.offsetWidth);
          if (playerPositionX >= gameWorld.offsetWidth - player.offsetWidth) bounceBack();
        } else {
          playerPositionX = Math.max(0, playerPositionX - dashSpeed);
          if (playerPositionX <= 0) bounceBack();
        }
        player.style.left = playerPositionX + 'px';
        dashes++;
        enemies.forEach((enemy, idx) => {
          if (checkCollision(player, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy smashed by frenzy dash!');
          }
        });
      }, 100);
      log('Frenzy Dash started!');
    }
  },

  /** 7. Thunder Strike */
  {
    name: 'Thunder Strike',
    description: 'Call a massive lightning bolt that damages a large radius for 3 seconds.',
    func: () => {
      const lightning = document.createElement('div');
      lightning.style.position = 'absolute';
      let x = playerPositionX + player.offsetWidth / 2 - 25;
      lightning.style.left = x + 'px';
      lightning.style.bottom = '0px';
      lightning.style.width = '50px';
      lightning.style.height = gameContainer.offsetHeight + 'px';
      lightning.style.backgroundColor = 'yellow';
      lightning.style.opacity = '0.9';
      lightning.style.filter = 'drop-shadow(0 0 10px yellow)';
      gameWorld.appendChild(lightning);

      enemies.forEach((enemy, idx) => {
        let ex = parseInt(enemy.style.left);
        if (ex + enemy.offsetWidth/2 > x && ex < x + 50) {
          enemy.remove();
          enemies.splice(idx, 1);
          createBurst(ex, parseInt(enemy.style.bottom));
          log('Enemy hit by Thunder Strike!');
        }
      });

      setTimeout(() => {
        lightning.remove();
        log('Thunder Strike ended!');
      }, 3000);

      log('Thunder Strike called!');
    }
  },

  /** 8. Gravity Vortex */
  {
    name: 'Gravity Vortex',
    description: 'Create a vortex that pulls enemies toward the player for 8 seconds.',
    func: () => {
      const pullRadius = 250;
      const interval = setInterval(() => {
        enemies.forEach(enemy => {
          let ex = parseInt(enemy.style.left);
          let ey = parseInt(enemy.style.bottom);
          const px = playerPositionX + player.offsetWidth/2;
          const py = playerPositionY + player.offsetHeight/2;
          let dx = px - ex;
          let dy = py - ey;
          let dist = Math.sqrt(dx*dx+dy*dy);
          if(dist < pullRadius && dist > 1){
            enemy.style.left = (ex + dx*0.1) + 'px';
            enemy.style.bottom = (ey + dy*0.1) + 'px';
          }
        });
      }, 40);
      setTimeout(() => {
        clearInterval(interval);
        log('Gravity Vortex ended!');
      }, 8000);
      log('Gravity Vortex activated!');
    }
  },

  /** 9. Ice Spikes Wall */
  {
    name: 'Ice Spikes Wall',
    description: 'Create a temporary wall of ice spikes damaging enemies that touch it.',
    func: () => {
      const wallLeft = playerPositionX + 100;
      const spikes = [];
      for(let i=0; i<5; i++){
        const spike = document.createElement('div');
        spike.style.position = 'absolute';
        spike.style.left = (wallLeft + i*30) + 'px';
        spike.style.bottom = '0px';
        spike.style.width = '25px';
        spike.style.height = '100px';
        spike.style.backgroundColor = 'lightblue';
        spike.style.borderRadius = '8px';
        gameWorld.appendChild(spike);
        spikes.push(spike);
      }
      const interval = setInterval(() => {
        spikes.forEach(spike => {
          enemies.forEach((enemy, idx) => {
            if (checkCollision(spike, enemy)) {
              applyBurn(enemy);
              enemy.style.backgroundColor = 'lightblue';
            }
          });
        });
      }, 200);
      setTimeout(() => {
        spikes.forEach(spike => spike.remove());
        clearInterval(interval);
        log('Ice Spikes Wall vanished!');
      }, 7000);
      log('Ice Spikes Wall deployed!');
    }
  },

  /** 10. Void Collapse (pull all enemies, then explode after 6s) */
  {
    name: 'Void Collapse',
    description: 'Pull all enemies to center and then explode.',
    func: () => {
      let centerX = gameScrollPosition + gameContainer.offsetWidth / 2;
      let centerY = gameContainer.offsetHeight / 2;

      const interval = setInterval(() => {
        enemies.forEach(enemy => {
          let ex = parseInt(enemy.style.left);
          let ey = parseInt(enemy.style.bottom);
          let dx = centerX - ex;
          let dy = centerY - ey;
          enemy.style.left = (ex + dx * 0.15) + 'px';
          enemy.style.bottom = (ey + dy * 0.15) + 'px';
        });
      }, 30);

      setTimeout(() => {
        clearInterval(interval);
        enemies.forEach((enemy, idx) => {
          if (Math.hypot(parseInt(enemy.style.left) - centerX, parseInt(enemy.style.bottom) - centerY) < 100) {
            enemy.remove();
            enemies.splice(idx, 1);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            log('Enemy consumed by void collapse!');
          }
        });
      }, 6000);

      log('Void Collapse initiated!');
    }
  },

  /** 11. Toxic Rain */
  {
    name: 'Toxic Rain',
    description: 'Rain acid damaging all enemies over 10 seconds.',
    func: async () => {
      displayMessage('Toxic Rain is falling!', 3);
      await sleep(3000);

      let count = 0;
      const maxDrops = 50;
      const drops = [];

      const spawnDrop = () => {
        let drop = document.createElement('div');
        drop.style.position = 'absolute';
        drop.style.left = (gameScrollPosition + Math.random() * gameContainer.offsetWidth) + 'px';
        drop.style.bottom = (gameContainer.offsetHeight + 30) + 'px';
        drop.style.width = '12px';
        drop.style.height = '20px';
        drop.style.backgroundColor = 'green';
        drop.style.borderRadius = '50%';
        gameWorld.appendChild(drop);
        drops.push(drop);

        let speed = 15 + Math.random()*7;
        let intId = setInterval(() => {
          if (!drop.parentElement) {
            clearInterval(intId);
            return;
          }
          let y = parseInt(drop.style.bottom) - speed;
          drop.style.bottom = y + 'px';

          if (y <= 0) {
            createBurst(parseInt(drop.style.left), 0);
            enemies.forEach((enemy, idx) => {
              if (checkCollision(drop, enemy)) {
                enemy.remove();
                enemies.splice(idx, 1);
                log('Enemy corroded by toxic rain!');
              }
            });
            drop.remove();
            clearInterval(intId);
          }
        }, 50);
      };

      let spawnInt = setInterval(() => {
        if (count >= maxDrops) {
          clearInterval(spawnInt);
          setTimeout(() => {
            drops.forEach(d => d.remove());
            log('Toxic Rain ended!');
          }, 3000);
          return;
        }
        spawnDrop();
        count++;
      }, 200);
      log('Toxic Rain started!');
    }
  },

  /** 12. Lightning Rush */
  {
    name: 'Lightning Rush',
    description: 'Dash rapidly through enemies zapping them for 8 seconds.',
    func: () => {
      let rushCount = 0;
      const rushSpeed = 30;
      player.classList.add('glow');
      const interval = setInterval(() => {
        if(rushCount >= 15){
          clearInterval(interval);
          player.classList.remove('glow');
          log('Lightning Rush ended!');
          return;
        }
        playerPositionX = Math.min(playerPositionX + rushSpeed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';
        enemies.forEach((enemy, idx) => {
          if(checkCollision(player, enemy)){
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx,1);
            log('Enemy zapped by Lightning Rush!');
          }
        });
        rushCount++;
      }, 250);
      log('Lightning Rush started!');
    }
  },

  /** 13. Energy Chain */
  {
    name: 'Energy Chain',
    description: 'Create chaining electric arcs that damage multiple enemies.',
    func: () => {
      if(enemies.length === 0){
        log('No enemies for Energy Chain!');
        return;
      }
      let chainSet = new Set();
      function chain(enemy, count){
        if(!enemy || count <= 0) return;
        chainSet.add(enemy);
        enemy.style.backgroundColor = 'cyan';
        setTimeout(() => { enemy.style.backgroundColor = ''; }, 400);
        enemy.remove();
        enemies.splice(enemies.indexOf(enemy),1);
        log('Enemy zapped by energy chain!');

        let near = enemies.filter(e => !chainSet.has(e) && Math.hypot(parseInt(e.style.left)-parseInt(enemy.style.left), parseInt(e.style.bottom)-parseInt(enemy.style.bottom)) < 130);
        if(near.length) setTimeout(() => chain(near[0], count-1), 300);
      }
      chain(enemies[Math.floor(Math.random()*enemies.length)],6);
      log('Energy Chain activated!');
    }
  },

  /** 14. Flame Whirlwind */
  {
    name: 'Flame Whirlwind',
    description: 'Player spins with flames generating burn damage to all close enemies for 5 seconds.',
    func: () => {
      player.classList.add('glow');
      let lifetime = 0;
      let interval = setInterval(() => {
        lifetime += 100;
        enemies.forEach((enemy, idx) => {
          const dx = parseInt(enemy.style.left) - playerPositionX;
          const dy = parseInt(enemy.style.bottom) - playerPositionY;
          const dist = Math.sqrt(dx*dx + dy*dy);
          if(dist < 120){
            applyBurn(enemy);
          }
        });
        if(lifetime > 5000){
          clearInterval(interval);
          player.classList.remove('glow');
          log('Flame Whirlwind ended!');
        }
      }, 100);
      log('Flame Whirlwind activated!');
    }
  },

  /** 15. Shadow Clone */
  {
    name: 'Shadow Clone',
    description: 'Spawn 3 shadow clones that attack enemies for 8 seconds.',
    func: () => {
      const clones = [];
      for(let i=0;i<3;i++){
        const c = document.createElement('div');
        c.style.position = 'absolute';
        c.style.width = player.offsetWidth + 'px';
        c.style.height = player.offsetHeight + 'px';
        c.style.backgroundColor = 'black';
        c.style.opacity = '0.6';
        c.style.borderRadius = '50%';
        c.style.left = (playerPositionX + (i-1)*40) + 'px';
        c.style.bottom = playerPositionY + 'px';
        gameWorld.appendChild(c);
        clones.push(c);
      }
      let interval = setInterval(() => {
        clones.forEach(c => {
          if(!c.parentElement) return;
          let x = parseInt(c.style.left);
          c.style.left = x + ((Math.random() > 0.5) ? 3 : -3) + 'px';
          enemies.forEach((enemy, idx) => {
            if(checkCollision(c,enemy)){
              enemy.remove();
              enemies.splice(idx,1);
              log('Enemy defeated by shadow clone!');
            }
          });
        });
      }, 50);
      setTimeout(() => {
        clearInterval(interval);
        clones.forEach(c => c.remove());
        log('Shadow Clones faded!');
      }, 8000);
      log('Shadow Clones spawned!');
    }
  },

  /** 16. Drill Charge */
  {
    name: 'Drill Charge',
    description: 'Charge forward piercing through enemies and obstacles for 5 seconds.',
    func: () => {
      player.classList.add('glow');
      let dist = 0;
      const maxDist = 500;
      const speed = 18;
      const interval = setInterval(() => {
        if(dist > maxDist){
          clearInterval(interval);
          player.classList.remove('glow');
          log('Drill Charge ended!');
          return;
        }
        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';
        obstacles.forEach((obs, idx) => {
          if(checkCollision(player, obs)){
            obs.remove();
            obstacles.splice(idx,1);
            createBurst(parseInt(obs.style.left), parseInt(obs.style.bottom));
            log('Obstacle drilled!');
          }
        });
        enemies.forEach((enemy, idx) => {
          if(checkCollision(player, enemy)){
            enemy.remove();
            enemies.splice(idx,1);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            log('Enemy pierced by drill!');
          }
        });
        dist += speed;
      }, 40);
      log('Drill Charge started!');
    }
  },

  /** 17. Chain Lightning Slash */
  {
    name: 'Chain Lightning Slash',
    description: 'Player swings chain lightning slash stunning and damaging enemies.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 220){
          enemy.classList.add('frozen-enemy');
          enemy.style.opacity = '0.3';
          setTimeout(() => {
            enemy.remove();
            enemies.splice(enemies.indexOf(enemy),1);
            log('Enemy defeated by lightning slash!');
          }, 1700);
        }
      });
      log('Chain Lightning Slash unleashed!');
    }
  },

  /** 18. Fire Lance */
  {
    name: 'Fire Lance',
    description: 'Shoot a long flame lance damaging all enemies in a line.',
    func: () => {
      const lance = document.createElement('div');
      lance.style.position = 'absolute';
      lance.style.left = playerPositionX + 'px';
      lance.style.bottom = playerPositionY + 'px';
      lance.style.width = '150px';
      lance.style.height = '12px';
      lance.style.background = 'linear-gradient(to right, red, orange, yellow)';
      gameWorld.appendChild(lance);

      enemies.forEach((enemy, idx) => {
        if(parseInt(enemy.style.left) > playerPositionX && parseInt(enemy.style.left) < playerPositionX + 150){
          enemy.remove();
          enemies.splice(idx,1);
          createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
          log('Enemy burned by Fire Lance!');
        }
      });

      setTimeout(() => {
        lance.remove();
        log('Fire Lance ended!');
      }, 1200);
      log('Fire Lance fired!');
    }
  },

  /** 19. Energy Overload */
  {
    name: 'Energy Overload',
    description: 'Player radiates energy damaging all enemies each second for 8 seconds.',
    func: () => {
      let ticks = 0;
      const interval = setInterval(() => {
        createBurst(playerPositionX, playerPositionY);
        enemies.forEach((enemy, idx) => {
          if (Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY) < 175) {
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy zapped by Energy Overload!');
          }
        });
        ticks++;
        if (ticks >= 8) {
          clearInterval(interval);
          log('Energy Overload ended!');
        }
      }, 1000);
      log('Energy Overload started!');
    }
  },

  /** 20. Poison Mist */
  {
    name: 'Poison Mist',
    description: 'Ability emits a toxic mist that damages and slows enemies for 7 seconds.',
    func: () => {
      const mist = document.createElement('div');
      mist.style.position = 'absolute';
      mist.style.left = (playerPositionX - 60) + 'px';
      mist.style.bottom = (playerPositionY - 40) + 'px';
      mist.style.width = '140px';
      mist.style.height = '120px';
      mist.style.backgroundColor = 'rgba(0, 150, 0, 0.6)';
      mist.style.borderRadius = '50%';
      gameWorld.appendChild(mist);

      enemies.forEach(enemy => {
        enemy.dataset.originalSpeed = enemy.dataset.speed || '1';
        enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed) * 0.5).toString();
      });

      const damageInterval = setInterval(() => {
        enemies.forEach(enemy => {
          if(checkCollision(mist, enemy)){
            applyBurn(enemy);
          }
        });
      }, 800);

      setTimeout(() => {
        clearInterval(damageInterval);
        enemies.forEach(enemy => {
          if(enemy.dataset.originalSpeed){
            enemy.dataset.speed = enemy.dataset.originalSpeed;
            delete enemy.dataset.originalSpeed;
          }
        });
        mist.remove();
        log('Poison Mist vanished!');
      }, 7000);
      log('Poison Mist activated!');
    }
  },

  /** 21. Raging Tornado */
  {
    name: 'Raging Tornado',
    description: 'Player summons a tornado pulling enemies and blocking shots for 7 seconds.',
    func: () => {
      const tornado = document.createElement('div');
      tornado.style.position = 'absolute';
      tornado.style.left = (playerPositionX - 70) + 'px';
      tornado.style.bottom = (playerPositionY - 40) + 'px';
      tornado.style.width = '140px';
      tornado.style.height = '140px';
      tornado.style.borderRadius = '50%';
      tornado.style.background = 'rgba(150,150,255,0.5)';
      tornado.style.border = '3px solid #8ac';
      tornado.style.zIndex = 9999;
      gameWorld.appendChild(tornado);

      const pullInterval = setInterval(() => {
        enemies.forEach(enemy => {
          let dx = playerPositionX + player.offsetWidth/2 - parseInt(enemy.style.left) - enemy.offsetWidth/2;
          let dy = playerPositionY + player.offsetHeight/2 - parseInt(enemy.style.bottom) - enemy.offsetHeight/2;
          let dist = Math.sqrt(dx*dx + dy*dy);
          if(dist < 200){
            enemy.style.left = (parseInt(enemy.style.left) + dx*0.12) + 'px';
            enemy.style.bottom = (parseInt(enemy.style.bottom) + dy*0.12) + 'px';
          }
        });
      }, 50);

      setTimeout(() => {
        clearInterval(pullInterval);
        tornado.remove();
        log('Raging Tornado disappeared!');
      }, 7000);
      log('Raging Tornado summoned!');
    }
  },

  /** 22. Thunder Roll */
  {
    name: 'Thunder Roll',
    description: 'Player rolls forward creating thunder shocks damaging enemies, 6 seconds.',
    func: () => {
      player.classList.add('glow');
      let distance = 0;
      const maxDistance = 350;
      const speed = 20;
      const interval = setInterval(() => {
        if(distance >= maxDistance){
          clearInterval(interval);
          player.classList.remove('glow');
          log('Thunder Roll ended!');
          return;
        }
        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';
        createBurst(playerPositionX, playerPositionY);
        enemies.forEach((enemy, idx) => {
          if(checkCollision(player, enemy)){
            enemy.remove();
            enemies.splice(idx,1);
            log('Enemy shocked by Thunder Roll!');
          }
        });
        distance += speed;
      }, 100);
      log('Thunder Roll started!');
    }
  },

  /** 23. Mega Shield */
  {
    name: 'Mega Shield',
    description: 'Create a giant shield for 12 seconds that blocks all damage.',
    func: () => {
      player.style.border = '6px double blue';
      isInvincible = true;
      log('Mega Shield up!');
      setTimeout(() => {
        player.style.border = '';
        isInvincible = false;
        log('Mega Shield down!');
      }, 12000);
    }
  },

  /** 24. Ice Barrier */
  {
    name: 'Ice Barrier',
    description: 'Create an ice wall blocking enemy movement for 7 seconds.',
    func: () => {
      const wall = document.createElement('div');
      wall.style.position = 'absolute';
      wall.style.left = (playerPositionX + 50) + 'px';
      wall.style.bottom = '0px';
      wall.style.width = '30px';
      wall.style.height = '150px';
      wall.style.backgroundColor = 'cyan';
      wall.style.borderRadius = '8px';
      gameWorld.appendChild(wall);

      enemies.forEach(enemy => {
        if (checkCollision(enemy, wall)) {
          enemy.dataset.speedBackup = enemy.dataset.speed;
          enemy.dataset.speed = '0';
        }
      });

      setTimeout(() => {
        enemies.forEach(enemy => {
          if (enemy.dataset.speedBackup) {
            enemy.dataset.speed = enemy.dataset.speedBackup;
            delete enemy.dataset.speedBackup;
          }
        });
        wall.remove();
        log('Ice Barrier disappeared!');
      }, 7000);
      log('Ice Barrier created!');
    }
  },

  /** 25. Lightning Orb */
  {
    name: 'Lightning Orb',
    description: 'Summon an orb that orbits player and zaps enemies for 9 seconds.',
    func: () => {
      const orb = document.createElement('div');
      orb.style.position = 'absolute';
      orb.style.width = '30px';
      orb.style.height = '30px';
      orb.style.borderRadius = '50%';
      orb.style.backgroundColor = 'skyblue';
      orb.style.left = (playerPositionX + 50) + 'px';
      orb.style.bottom = (playerPositionY + 50) + 'px';
      gameWorld.appendChild(orb);

      let angle = 0;
      let radius = 60;
      const interval = setInterval(() => {
        angle += 0.1;
        let x = playerPositionX + player.offsetWidth/2 + radius * Math.cos(angle);
        let y = playerPositionY + player.offsetHeight/2 + radius * Math.sin(angle);
        orb.style.left = x + 'px';
        orb.style.bottom = y + 'px';

        enemies.forEach((enemy, idx) => {
          if (checkCollision(orb, enemy)) {
            enemy.remove();
            enemies.splice(idx, 1);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            log('Enemy zapped by Lightning Orb!');
          }
        });
      }, 40);

      setTimeout(() => {
        clearInterval(interval);
        orb.remove();
        log('Lightning Orb disappeared!');
      }, 9000);

      log('Lightning Orb summoned!');
    }
  },

  /** 26. Toxic Explosion */
  {
    name: 'Toxic Explosion',
    description: 'Create an explosion with poison that damages over time for 8 seconds.',
    func: () => {
      const x = playerPositionX + player.offsetWidth / 2;
      const y = playerPositionY + player.offsetHeight / 2;
      createBurst(x, y);

      const poisonRadius = 200;
      let ticks = 0;

      const interval = setInterval(() => {
        enemies.forEach(enemy => {
          const ex = parseInt(enemy.style.left) + enemy.offsetWidth/2;
          const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight/2;
          const dist = Math.hypot(ex - x, ey - y);
          if(dist < poisonRadius){
            applyBurn(enemy);
          }
        });
        ticks++;
        if(ticks > 8){
          clearInterval(interval);
          log('Toxic Explosion ended!');
        }
      }, 1000);

      log('Toxic Explosion activated!');
    }
  },

  /** 27. Shadow Step */
  {
    name: 'Shadow Step',
    description: 'Become invisible and teleport randomly around enemies for 12 seconds.',
    func: async () => {
      player.style.opacity = '0.1';
      isInvincible = true;
      log('Shadow Step activated!');

      for(let i=0; i<10; i++){
        if(enemies.length == 0) break;
        const e = enemies[Math.floor(Math.random()*enemies.length)];
        playerPositionX = parseInt(e.style.left) + (Math.random() * 60 - 30);
        playerPositionY = parseInt(e.style.bottom);
        player.style.left = playerPositionX + 'px';
        player.style.bottom = playerPositionY + 'px';
        await sleep(1000);
      }

      player.style.opacity = '1';
      isInvincible = false;
      log('Shadow Step ended!');
    }
  },

  /** 28. Volcanic Eruption */
  {
    name: 'Volcanic Eruption',
    description: 'Summon lava pillars around player that explode after 4 seconds.',
    func: () => {
      for(let i= -2; i<3; i++){
        const pillar = document.createElement('div');
        pillar.style.position = 'absolute';
        pillar.style.width = '35px';
        pillar.style.height = '120px';
        pillar.style.backgroundColor = 'orangered';
        pillar.style.left = (playerPositionX + i*40) + 'px';
        pillar.style.bottom = '0px';
        gameWorld.appendChild(pillar);

        setTimeout(() => {
          createBurst(parseInt(pillar.style.left), 120);
          enemies.forEach((enemy, idx) => {
            if (Math.abs(parseInt(enemy.style.left) - parseInt(pillar.style.left)) < 50) {
              enemy.remove();
              enemies.splice(idx, 1);
              log('Enemy incinerated by volcanic eruption!');
            }
          });
          pillar.remove();
        }, 4000);
      }
      log('Volcanic Eruption started!');
    }
  },

  /** 29. Phantom Slash */
  {
    name: 'Phantom Slash',
    description: 'Dash fast forward slashing enemies with a ghostly blade.',
    func: () => {
      let dist = 0;
      const maxDist = 300;
      const speed = 25;
      player.classList.add('glow');
      const interval = setInterval(() => {
        if(dist >= maxDist){
          clearInterval(interval);
          player.classList.remove('glow');
          log('Phantom Slash ended!');
          return;
        }
        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';

        enemies.forEach((enemy, idx) => {
          if (checkCollision(player, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx,1);
            log('Enemy slashed by Phantom!');
          }
        });
        dist += speed;
      }, 30);
      log('Phantom Slash started!');
    }
  },

  /** 30. Energy Barrage */
  {
    name: 'Energy Barrage',
    description: 'Rapidly fire 50 energy bullets in random directions.',
    func: () => {
      let bulletsFired = 0;
      const maxBullets = 50;

      const barrageInterval = setInterval(() => {
        if (bulletsFired >= maxBullets) {
          clearInterval(barrageInterval);
          log('Energy Barrage ended!');
          return;
        }

        const bullet = document.createElement('div');
        bullet.classList.add('bullet');
        bullet.style.position = 'absolute';
        bullet.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
        bullet.style.bottom = (playerPositionY + player.offsetHeight/2) + 'px';
        bullet.style.backgroundColor = 'cyan';
        bullet.style.width = '6px';
        bullet.style.height = '6px';
        bullet.style.borderRadius = '50%';
        gameWorld.appendChild(bullet);

        let angle = Math.random() * 2 * Math.PI;
        let speed = 9 + Math.random() * 4;
        let x = parseFloat(bullet.style.left);
        let y = parseFloat(bullet.style.bottom);

        function move() {
          if(!bullet.parentElement) return;
          x += Math.cos(angle)*speed;
          y += Math.sin(angle)*speed;
          bullet.style.left = x + 'px';
          bullet.style.bottom = y + 'px';

          if(x < 0 || x > gameWorld.offsetWidth || y < 0 || y > gameWorld.offsetHeight){
            bullet.remove();
            return;
          }

          enemies.forEach((enemy, idx) => {
            if (checkCollision(bullet, enemy)) {
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              bullet.remove();
              return;
            }
          });

          requestAnimationFrame(move);
        }
        move();
        bulletsFired++;
      }, 120);
      log('Energy Barrage started!');
    }
  },


  // --- Player Power-Ups and Buffs (with cool effects & combos) ---
  {
    name: 'Tornado Dash',
    description: 'Dash forward surrounded by a mini tornado damaging enemies for 6 seconds.',
    func: () => {
      const tornado = document.createElement('div');
      tornado.style.position = 'absolute';
      tornado.style.width = '80px';
      tornado.style.height = '80px';
      tornado.style.borderRadius = '50%';
      tornado.style.border = '3px solid lightblue';
      tornado.style.opacity = '0.7';
      tornado.style.zIndex = 9000;
      gameWorld.appendChild(tornado);

      let distance = 0;
      const maxDistance = 400;
      const speed = 18;

      const interval = setInterval(() => {
        if(distance > maxDistance){
          tornado.remove();
          clearInterval(interval);
          log('Tornado Dash ended!');
          return;
        }
        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';
        tornado.style.left = (playerPositionX - 20) + 'px';
        tornado.style.bottom = (playerPositionY - 20) + 'px';

        enemies.forEach((enemy, idx) => {
          if(checkCollision(tornado, enemy)){
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy shredded by Tornado Dash!');
          }
        });

        distance += speed;
      }, 40);

      log('Tornado Dash started!');
    }
  },
  {
    name: 'Titan’s Roar',
    description: 'Shout, causing nearby enemies to freeze and tremble for 5 seconds.',
    func: () => {
      log('Titan’s Roar emits!');
      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 300){
          enemy.style.transition = 'transform 0.3s ease';
          enemy.style.transform = 'scale(1.15)';
          enemy.classList.add('frozen-enemy');
          enemy.style.opacity = '0.3';
        }
      });
      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.style.transform = '';
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        log('Titan’s Roar ended!');
      }, 5000);
    }
  },
  {
    name: 'Cyclone Grip',
    description: 'Create a cyclone around player trapping enemies inside for 6 seconds.',
    func: () => {
      const cyclone = document.createElement('div');
      cyclone.style.position = 'absolute';
      cyclone.style.width = '220px';
      cyclone.style.height = '220px';
      cyclone.style.borderRadius = '50%';
      cyclone.style.border = '4px double #00FFFF';
      cyclone.style.left = (playerPositionX - 90) + 'px';
      cyclone.style.bottom = (playerPositionY - 90) + 'px';
      cyclone.style.opacity = '0.8';
      gameWorld.appendChild(cyclone);

      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 110){
          enemy.dataset.speedBackup = enemy.dataset.speed || '1';
          enemy.dataset.speed = '0';
          enemy.style.opacity = '0.4';
          enemy.style.transition = 'opacity 0.3s';
        }
      });

      setTimeout(() => {
        enemies.forEach(enemy => {
          if(enemy.dataset.speedBackup){
            enemy.dataset.speed = enemy.dataset.speedBackup;
            delete enemy.dataset.speedBackup;
            enemy.style.opacity = '1';
          }
        });
        cyclone.remove();
        log('Cyclone Grip ended!');
      }, 6000);

      log('Cyclone Grip activated!');
    }
  },
  {
    name: 'Rapid Pulse Heal',
    description: 'Regain 5 lives rapidly over 5 seconds.',
    func: () => {
      let healed = 0;
      const interval = setInterval(() => {
        if (healed >= 5){
          clearInterval(interval);
          log('Rapid Pulse Heal ended!');
          return;
        }
        lives = Math.min(lives + 1, 99);
        updateDisplay();
        log('Healed 1 life rapidly!');
        healed++;
      }, 1000);
      log('Rapid Pulse Heal started!');
    }
  },
  {
    name: 'Magnetic Wave',
    description: 'Push enemies away and pull power-ups close in a large radius.',
    func: () => {
      const powerPulls = [...powerUps, ...coins];
      log('Magnetic Wave activated!');
      for (let t=0;t<70;t++) {
        setTimeout(() => {
          enemies.forEach(enemy => {
            let ex = parseInt(enemy.style.left);
            let dx = ex - playerPositionX;
            if (Math.abs(dx) < 300){
              enemy.style.left = (ex + dx * 0.2) + 'px';
            }
          });
          powerPulls.forEach(pw => {
            let px = parseInt(pw.style.left);
            let dx = playerPositionX - px;
            if (Math.abs(dx) < 300){
              pw.style.left = (px + dx * 0.15) + 'px';
            }
          });
          if(t===69) log('Magnetic Wave ended!');
        }, 50*t);
      }
    }
  },
  {
    name: 'Plasma Shield',
    description: 'Create a protective shield that damages nearby enemies for 10 seconds.',
    func: () => {
      const shield = document.createElement('div');
      shield.style.position = 'absolute';
      shield.style.width = '140px';
      shield.style.height = '140px';
      shield.style.borderRadius = '50%';
      shield.style.border = '5px solid cyan';
      shield.style.left = (playerPositionX - 55) + 'px';
      shield.style.bottom = (playerPositionY - 55) + 'px';
      gameWorld.appendChild(shield);

      const interval = setInterval(() => {
        enemies.forEach((enemy, i) => {
          if (checkCollision(shield, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(i,1);
            log('Enemy damaged by plasma shield!');
          }
        });
      }, 150);

      setTimeout(() => {
        clearInterval(interval);
        shield.remove();
        log('Plasma Shield ended!');
      }, 10000);

      log('Plasma Shield active!');
    }
  },
  {
    name: 'Fury Strike',
    description: 'Triple jump immediately after a super powerful downward strike.',
    func: async () => {
      log('Fury Strike started!');
      if(!isJumping && jumpCount < maxJumps){
        playerVelocityY = playerJumpStrength * 3;
        jumpCount++;
        isJumping = true;
        await sleep(1200);
        for(let i=0; i<3; i++){
          doubleJump();
          await sleep(400);
        }
        log('Fury Strike attack completed!');
      }
    }
  },
  {
    name: 'Chain Shockwave',
    description: 'Sequential shockwaves ripple outwards damaging everything in their path.',
    func: async () => {
      let radius = 100;
      for(let i=0; i<5; i++){
        createBurst(playerPositionX, playerPositionY);
        enemies.forEach((enemy, idx) => {
          const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
          if(dist < radius){
            enemy.remove();
            enemies.splice(idx,1);
            log('Enemy hit by chain shockwave!');
          }
        });
        obstacles.forEach((ob, idx) => {
          const dist = Math.hypot(parseInt(ob.style.left) - playerPositionX, parseInt(ob.style.bottom) - playerPositionY);
          if(dist < radius){
            ob.remove();
            obstacles.splice(idx,1);
            log('Obstacle destroyed by chain shockwave!');
          }
        });
        radius += 100;
        await sleep(1200);
      }
      log('Chain Shockwave sequence ended!');
    }
  },
  // ... 10 more large boss-like moves like these would be added similarly ...
  // Due to token limit, I present them in batches.
  
  // === Player Upgrades and Cool Powerups (20+) ===

  {
    name: 'Fire Frenzy',
    description: 'Rapidly fire 10 fire bullets in quick bursts.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        shootFire();
        count++;
        if(count>=10){
          clearInterval(interval);
          log('Fire Frenzy ended!');
        }
      }, 100);
      log('Fire Frenzy activated!');
    }
  },
  {
    name: 'Ice Shard Barrage',
    description: 'Fire 15 icy shards that freeze enemies on hit.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        shootIce();
        count++;
        if(count >= 15){
          clearInterval(interval);
          log('Ice Shard Barrage ended!');
        }
      }, 150);
      log('Ice Shard Barrage activated!');
    }
  },
  {
    name: 'Hypno Swarm',
    description: 'Shoot 20 hypnotic bullets that confuse enemies.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        shootHypno();
        count++;
        if(count >= 20){
          clearInterval(interval);
          log('Hypno Swarm ended!');
        }
      }, 100);
      log('Hypno Swarm activated!');
    }
  },
  {
    name: 'Speed Surge',
    description: 'Increase player speed by 7 for 10 seconds.',
    func: () => {
      playerMaxSpeed += 7;
      log('Speed surged!');
      setTimeout(() => {
        playerMaxSpeed -= 7;
        log('Speed surge ended!');
      }, 10000);
    }
  },
  {
    name: 'Mega Heal',
    description: 'Instantly heal 10 lives.',
    func: () => {
      lives = Math.min(lives + 10, 99);
      updateDisplay();
      log('Mega Heal activated! 10 lives restored.');
    }
  },
  {
    name: 'Bullet Rainstorm',
    description: 'Fire a barrage of 50 bullets in all directions.',
    func: () => {
      for(let i=0; i < 50; i++) {
        setTimeout(() => {
          const angle = Math.random() * 2 * Math.PI;
          const bullet = createBullet(1);
          bullet.style.position = 'absolute';
          bullet.style.left = (playerPositionX + player.offsetWidth / 2) + 'px';
          bullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
          gameWorld.appendChild(bullet);

          let x = parseFloat(bullet.style.left);
          let y = parseFloat(bullet.style.bottom);
          let speed = 10;
          let dx = Math.cos(angle) * speed;
          let dy = Math.sin(angle) * speed;
          function move() {
            if(!bullet.parentElement) return;
            x += dx;
            y += dy;
            bullet.style.left = x + 'px';
            bullet.style.bottom = y + 'px';
            if(x < 0 || x > gameWorld.offsetWidth || y < 0 || y > gameWorld.offsetHeight) {
              bullet.remove();
              return;
            }
            requestAnimationFrame(move);
          }
          move();
        }, i*60);
      }
      log('Bullet Rainstorm activated!');
    }
  },
  {
    name: 'Gravity Well',
    description: 'Pull all enemies and pickups slowly towards player for 8 seconds.',
    func: () => {
      let interval = setInterval(() => {
        [...enemies, ...coins, ...powerUps].forEach(obj => {
          const ox = parseFloat(obj.style.left);
          const oy = parseFloat(obj.style.bottom);
          obj.style.left = ox + (playerPositionX - ox) * 0.075 + 'px';
          obj.style.bottom = oy + (playerPositionY - oy) * 0.075 + 'px';
        });
      }, 40);
      setTimeout(() => {
        clearInterval(interval);
        log('Gravity Well ended!');
      }, 8000);
      log('Gravity Well activated!');
    }
  },
  {
    name: 'Energy Burst',
    description: 'Release a huge energy pulse damaging everything near player.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      const radius = 250;
      [...enemies, ...obstacles].forEach((obj, idx, arr) => {
        let ox = parseInt(obj.style.left) + obj.offsetWidth / 2;
        let oy = parseInt(obj.style.bottom) + obj.offsetHeight / 2;
        let dist = Math.hypot(ox - (playerPositionX + player.offsetWidth/2), oy - (playerPositionY + player.offsetHeight/2));
        if(dist < radius) {
          obj.remove();
          arr.splice(idx, 1);
          log('Object destroyed by energy burst!');
        }
      });
      log('Energy Burst unleashed!');
    }
  },
  {
    name: 'Repulsion Field',
    description: 'Push all enemies away instantly with great force.',
    func: () => {
      const radius = 300;
      [...enemies].forEach(enemy => {
        let ex = parseInt(enemy.style.left);
        let ey = parseInt(enemy.style.bottom);
        let dx = ex - playerPositionX;
        let dy = ey - playerPositionY;
        let dist = Math.sqrt(dx*dx + dy*dy);
        if(dist < radius){
          let force = 120 * (1 - dist/radius);
          enemy.style.left = Math.min(Math.max(0, ex + (dx / dist) * force), gameWorld.offsetWidth - enemy.offsetWidth) + 'px';
          enemy.style.bottom = Math.min(Math.max(0, ey + (dy / dist) * force), gameContainer.offsetHeight - enemy.offsetHeight) + 'px';
          log('Enemy pushed by repulsion!');
        }
      });
      log('Repulsion Field activated!');
    }
  },

  /** 31. Bullet Magnetism */
  {
    name: 'Bullet Magnetism',
    description: `Magnetically pull bullets towards the player, deflecting them and pushing them away.`,
    func: () => {
      const interval = setInterval(() => {
        bullets.forEach(b => {
          const el = b.element;
          let bx = parseFloat(el.style.left);
          let by = parseFloat(el.style.bottom);
          let dx = playerPositionX - bx;
          let dy = playerPositionY - by;
          let dist = Math.sqrt(dx*dx + dy*dy);
          if(dist < 180 && dist > 10){
            // Pull bullet towards player and flip direction partially
            b.direction = -b.direction;
            el.style.left = bx + dx*0.3 + 'px';
            el.style.bottom = by + dy*0.3 + 'px';
            log('Bullet deflected by magnetism!');
          }
        });
      }, 60);
      setTimeout(() => {
        clearInterval(interval);
        log('Bullet Magnetism expired!');
      }, 10000);
      log('Bullet Magnetism activated!');
    }
  },

  /** 32. Berserk Mode */
  {
    name: 'Berserk Mode',
    description: `Player moves and shoots twice as fast, and is fully invincible for 7 seconds.`,
    func: () => {
      playerMaxSpeed *= 2;
      isInvincible = true;
      player.classList.add('glow');
      log('Berserk Mode activated!');
      setTimeout(() => {
        playerMaxSpeed /= 2;
        isInvincible = false;
        player.classList.remove('glow');
        log('Berserk Mode ended!');
      }, 7000);
    }
  },

  /** 33. Flash Grenade */
  {
    name: 'Flash Grenade',
    description: 'Flash all enemies bright white, stunning them for 4 seconds.',
    func: () => {
      enemies.forEach(enemy => {
        enemy.style.filter = 'brightness(10)';
        enemy.classList.add('frozen-enemy');
        enemy.style.opacity = '0.2';
      });
      log('Flash Grenade exploded!');
      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.style.filter = '';
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        log('Enemies recovered from flash!');
      }, 4000);
    }
  },

  /** 34. Supernova Charge */
  {
    name: 'Supernova Charge',
    description: 'Charge for 5 seconds then release a huge explosion damaging everything nearby.',
    func: async () => {
      displayMessage('Charging Supernova...', 5);
      await sleep(5000);
      createBurst(playerPositionX, playerPositionY);
      enemies.forEach((enemy, idx) => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 350){
          enemy.remove();
          enemies.splice(idx, 1);
          log('Enemy incinerated by Supernova!');
        }
      });
      obstacles.forEach((ob, idx) => {
        const dist = Math.hypot(parseInt(ob.style.left) - playerPositionX, parseInt(ob.style.bottom) - playerPositionY);
        if(dist < 200){
          ob.remove();
          obstacles.splice(idx,1);
          log('Obstacle destroyed by Supernova!');
        }
      });
      log('Supernova released!');
    }
  },

  /** 35. Rocket Swarm */
  {
    name: 'Rocket Swarm',
    description: 'Fire 8 rocket projectiles that track and destroy enemies.',
    func: () => {
      for(let i=0; i<8; i++) {
        setTimeout(() => {
          if(enemies.length === 0) {
            log('No enemies for Rocket Swarm!');
            return;
          }
          let target = enemies[Math.floor(Math.random()*enemies.length)];
          let rocket = document.createElement('div');
          rocket.style.position = 'absolute';
          rocket.style.width = '14px';
          rocket.style.height = '8px';
          rocket.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
          rocket.style.bottom = (playerPositionY + player.offsetHeight/2) + 'px';
          rocket.style.backgroundColor = 'red';
          rocket.style.borderRadius = '4px';
          gameWorld.appendChild(rocket);

          let x = parseFloat(rocket.style.left);
          let y = parseFloat(rocket.style.bottom);

          const speed = 12;

          function move() {
            if(!rocket.parentElement || !target || !target.parentElement){
              rocket.remove();
              return;
            }
            let tx = parseInt(target.style.left);
            let ty = parseInt(target.style.bottom);
            let dx = tx - x;
            let dy = ty - y;
            let dist = Math.sqrt(dx*dx + dy*dy);
            if(dist < 15){
              createBurst(tx, ty);
              target.remove();
              enemies.splice(enemies.indexOf(target),1);
              rocket.remove();
              log('Enemy destroyed by rocket!');
              return;
            }
            x += (dx/dist)*speed;
            y += (dy/dist)*speed;
            rocket.style.left = x + 'px';
            rocket.style.bottom = y + 'px';
            requestAnimationFrame(move);
          }
          move();
        }, i*120);
      }
      log('Rocket Swarm launched!');
    }
  },

  /** 36. Time Freeze Blast */
  {
    name: 'Time Freeze Blast',
    description: 'Freeze all enemies for 6 seconds while player moves at double speed.',
    func: () => {
      enemies.forEach(enemy => {
        enemy.dataset.originalSpeed = enemy.dataset.speed || '1';
        enemy.dataset.speed = '0';
        enemy.style.opacity = '0.2';
      });
      playerMaxSpeed *= 2;
      log('Time Freeze Blast activated!');

      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.dataset.speed = enemy.dataset.originalSpeed;
          delete enemy.dataset.originalSpeed;
          enemy.style.opacity = '1';
        });
        playerMaxSpeed /= 2;
        log('Time Freeze Blast ended!');
      }, 6000);
    }
  },

  /** 37. Poison Barrage */
  {
    name: 'Poison Barrage',
    description: 'Shoot 12 poison bullets that apply damage over time on hit.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        shootPoisonBullet();
        count++;
        if(count >= 12){
          clearInterval(interval);
          log('Poison Barrage ended!');
        }
      }, 250);

      log('Poison Barrage started!');

      function shootPoisonBullet() {
        const bullet = createBullet(currentDirection);
        bullet.style.position = 'absolute';
        bullet.style.backgroundColor = 'green';
        bullet.style.width = '9px';
        bullet.style.height = '6px';
        gameWorld.appendChild(bullet);

        let x = parseFloat(bullet.style.left);
        let y = parseFloat(bullet.style.bottom);
        const speed = 10;

        function move() {
          if(!bullet.parentElement) return;
          x += speed * currentDirection;
          bullet.style.left = x + 'px';

          enemies.forEach((enemy, idx) => {
            if(checkCollision(bullet, enemy)){
              applyPoison(enemy);
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              bullet.remove();
              log('Enemy poisoned!');
              enemies.splice(idx,1);
              return;
            }
          });
          if(x < 0 || x > gameWorld.offsetWidth){
            bullet.remove();
            return;
          }
          requestAnimationFrame(move);
        }
        move();
      }

      function applyPoison(enemy){
        let ticks = 5;
        let interval = setInterval(() => {
          if(ticks <= 0){
            clearInterval(interval);
            return;
          }
          // Reduce health or remove enemy here (simplify to remove instantly)
          enemy.style.opacity = (enemy.style.opacity === '1' ? '0.6' : '1');
          ticks--;
        }, 800);
      }
    }
  },

  /** 38. Laser Scorch */
  {
    name: 'Laser Scorch',
    description: 'Shoot continuous laser for 7 seconds burning all enemies in the way.',
    func: () => {
      let laser = document.createElement('div');
      laser.style.position = 'absolute';
      laser.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
      laser.style.bottom = playerPositionY + 'px';
      laser.style.width = '12px';
      laser.style.height = gameContainer.offsetHeight + 'px';
      laser.style.backgroundColor = 'red';
      laser.style.opacity = '0.7';
      gameWorld.appendChild(laser);

      let interval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          if(checkCollision(laser, enemy)){
            applyBurn(enemy);
            log('Enemy burned by Laser Scorch!');
            enemy.remove();
            enemies.splice(idx, 1);
          }
        });
      }, 150);

      setTimeout(() => {
        clearInterval(interval);
        laser.remove();
        log('Laser Scorch ended!');
      }, 7000);

      log('Laser Scorch activated!');
    }
  },

  /** 39. Supernova Dash */
  {
    name: 'Supernova Dash',
    description: 'Dash forward and explode, damaging enemies in huge radius.',
    func: () => {
      let distance = 0;
      const maxDistance = 250;
      const speed = 30;
      player.classList.add('glow');
      const interval = setInterval(() => {
        if(distance >= maxDistance){
          clearInterval(interval);
          player.classList.remove('glow');
          createBurst(playerPositionX, playerPositionY);
          enemies.forEach((enemy, idx) => {
            const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
            if(dist <= 180){
              enemy.remove();
              enemies.splice(idx,1);
              log('Enemy destroyed by Supernova Dash!');
            }
          });
          log('Supernova Dash ended!');
          return;
        }
        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';
        enemies.forEach((enemy, idx) => {
          if (checkCollision(player, enemy)){
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx,1);
            log('Enemy hit by Supernova Dash!');
          }
        });
        distance += speed;
      }, 40);
      log('Supernova Dash started!');
    }
  },

  /** 40. Ice Spike Barrage */
  {
    name: 'Ice Spike Barrage',
    description: 'Shoot 15 spikes that freeze enemies for 3s.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        shootIce();
        count++;
        if(count >= 15){
          clearInterval(interval);
          log('Ice Spike Barrage ended!');
        }
      }, 150);
      log('Ice Spike Barrage started!');
    }
  },

  /** 41. Firestorm */
  {
    name: 'Firestorm',
    description: 'A massive flame circle expands outwards damaging enemies over 8 seconds.',
    func: () => {
      const centerX = playerPositionX + player.offsetWidth/2;
      const centerY = playerPositionY + player.offsetHeight/2;
      let radius = 60;
      const maxRadius = 320;

      const wave = document.createElement('div');
      wave.style.position = 'absolute';
      wave.style.borderRadius = '50%';
      wave.style.boxShadow = '0 0 30px 10px red';
      wave.style.border = '3px solid orange';
      wave.style.opacity = '0.5';
      gameWorld.appendChild(wave);

      const interval = setInterval(() => {
        radius += 20;
        wave.style.width = (radius * 2) + 'px';
        wave.style.height = (radius * 2) + 'px';
        wave.style.left = (centerX - radius) + 'px';
        wave.style.bottom = (centerY - radius) + 'px';
        enemies.forEach((enemy, idx) => {
          const dist = Math.hypot(parseInt(enemy.style.left) + enemy.offsetWidth/2 - centerX, parseInt(enemy.style.bottom) + enemy.offsetHeight/2 - centerY);
          if(dist < radius){
            applyBurn(enemy);
            enemy.style.backgroundColor = 'orange';
          }
        });
        if(radius >= maxRadius){
          clearInterval(interval);
          wave.remove();
          log('Firestorm ended!');
        }
      }, 250);
      log('Firestorm activated!');
    }
  },

  /** 42. Hyper Beam */
  {
    name: 'Hyper Beam',
    description: 'Charge and release a powerful beam that pierces all enemies.',
    func: async () => {
      displayMessage('Charging Hyper Beam...', 4);
      await sleep(4000);

      const beam = document.createElement('div');
      beam.style.position = 'absolute';
      beam.style.left = (playerPositionX + player.offsetWidth/2 - 8) + 'px';
      beam.style.bottom = playerPositionY + 'px';
      beam.style.width = '16px';
      beam.style.height = gameContainer.offsetHeight + 'px';
      beam.style.backgroundColor = 'purple';
      beam.style.opacity = '0.75';
      gameWorld.appendChild(beam);

      enemies.forEach((enemy, idx) => {
        if(checkCollision(beam, enemy)){
          enemy.remove();
          enemies.splice(idx,1);
          createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
          log('Enemy destroyed by Hyper Beam!');
        }
      });

      setTimeout(() => {
        beam.remove();
        log('Hyper Beam ended!');
      }, 3500);
      log('Hyper Beam fired!');
    }
  },

  /** 43. Toxic Nova */
  {
    name: 'Toxic Nova',
    description: 'Explode poisonous gas in radius, applying burn over 10 seconds.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      const radius = 180;
      let ticks = 0;
      const interval = setInterval(() => {
        enemies.forEach(enemy => {
          if (Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY) < radius) {
            applyBurn(enemy);
          }
        });
        ticks++;
        if(ticks > 10){
          clearInterval(interval);
          log('Toxic Nova ended!');
        }
      }, 1000);
      log('Toxic Nova emitted!');
    }
  }, 

  /** 44. Lightning Whip */
  {
    name: 'Lightning Whip',
    description: 'Create an electric whip that damages enemies in front of player instantly.',
    func: () => {
      const whip = document.createElement('div');
      whip.style.position = 'absolute';
      whip.style.left = (playerPositionX + (currentDirection > 0 ? player.offsetWidth : -100)) + 'px';
      whip.style.bottom = (playerPositionY + player.offsetHeight*0.5) + 'px';
      whip.style.width = '100px';
      whip.style.height = '14px';
      whip.style.backgroundColor = 'yellow';
      whip.style.opacity = '0.8';
      gameWorld.appendChild(whip);

      enemies.forEach((enemy, idx) => {
        if (checkCollision(whip, enemy)) {
          enemy.remove();
          enemies.splice(idx, 1);
          createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
          log('Enemy struck by Lightning Whip!');
        }
      });

      setTimeout(() => {
        whip.remove();
        log('Lightning Whip disappeared!');
      }, 800);
      log('Lightning Whip unleashed!');
    }
  },

  /** 45. Sonic Boom */
  {
    name: 'Sonic Boom',
    description: 'Explosive soundwave damages and pushes back enemies within 250px.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 250){
          let newLeft = parseInt(enemy.style.left) + (parseInt(enemy.style.left) < playerPositionX ? -130 : 130);
          enemy.style.left = Math.min(Math.max(0, newLeft), gameWorld.offsetWidth - enemy.offsetWidth) + 'px';
          log('Enemy pushed back by Sonic Boom!');
        }
      });
      log('Sonic Boom emitted!');
    }
  },

  /** 46. Phantom Clone Barrage */
  {
    name: 'Phantom Clone Barrage',
    description: 'Summon 5 phantom clones that randomly fire bullets at enemies.',
    func: () => {
      const clones = [];
      for(let i=0; i<5; i++){
        let clone = document.createElement('div');
        clone.style.position = 'absolute';
        clone.style.left = (playerPositionX + (i-2)*45) + 'px';
        clone.style.bottom = playerPositionY + 'px';
        clone.style.width = player.offsetWidth + 'px';
        clone.style.height = player.offsetHeight + 'px';
        clone.style.opacity = '0.5';
        clone.style.backgroundColor = 'purple';
        clone.style.borderRadius = '50%';
        gameWorld.appendChild(clone);
        clones.push(clone);
      }
      const interval = setInterval(() => {
        clones.forEach(clone => {
          if(enemies.length == 0) return;
          const enemy = enemies[Math.floor(Math.random()*enemies.length)];
          shootBulletAtPos(clone, enemy);
        });
      }, 400);
      setTimeout(() => {
        clones.forEach(c => c.remove());
        clearInterval(interval);
        log('Phantom Clone Barrage ended!');
      }, 9000);
      log('Phantom Clone Barrage started!');

      function shootBulletAtPos(fromEl, target) {
        if(!fromEl.parentElement || !target.parentElement) return;
        const bullet = document.createElement('div');
        bullet.classList.add('bullet');
        bullet.style.position = 'absolute';
        bullet.style.left = fromEl.style.left;
        bullet.style.bottom = fromEl.style.bottom;
        bullet.style.width = '8px';
        bullet.style.height = '6px';
        bullet.style.backgroundColor = 'magenta';
        gameWorld.appendChild(bullet);

        let bx = parseFloat(bullet.style.left);
        let by = parseFloat(bullet.style.bottom);
        let tx = parseInt(target.style.left);
        let ty = parseInt(target.style.bottom);

        const dist = Math.hypot(tx - bx, ty - by);
        const speed = 9;

        function move() {
          if(!bullet.parentElement) return;
          let dx = (tx - bx)/dist * speed;
          let dy = (ty - by)/dist * speed;
          bx += dx;
          by += dy;
          bullet.style.left = bx + 'px';
          bullet.style.bottom = by + 'px';
          if(checkCollision(bullet, target)){
            createBurst(tx, ty);
            target.remove();
            enemies.splice(enemies.indexOf(target),1);
            bullet.remove();
            log('Phantom clone bullet hit!');
            return;
          }
          if(bx < 0 || bx > gameWorld.offsetWidth || by < 0 || by > gameWorld.offsetHeight){
            bullet.remove();
            return;
          }
          requestAnimationFrame(move);
        }
        move();
      }
    }
  },

  /** 47. Dynamic Speed Boost */
  {
    name: 'Dynamic Speed Boost',
    description: `Gain random speed boosts cycling every 1.5 seconds for 12 seconds.`,
    func: () => {
      let ticks = 0;
      const maxTicks = 8;
      const defaultSpeed = playerMaxSpeed;
      const interval = setInterval(() => {
        playerMaxSpeed = defaultSpeed + Math.floor(Math.random()*12);
        log(`Speed set to ${playerMaxSpeed}`);
        ticks++;
        if(ticks >= maxTicks){
          clearInterval(interval);
          playerMaxSpeed = defaultSpeed;
          log('Dynamic speed boost ended!');
        }
      }, 1500);
      log('Dynamic Speed Boost started!');
    }
  },

  /** 48. Bullet Piercer */
  {
    name: 'Bullet Piercer',
    description: 'Bullets can pierce through 3 enemies each for 7 seconds.',
    func: () => {
      window.piercingBullets = true;
      log('Bullet Piercer activated!');

      setTimeout(() => {
        window.piercingBullets = false;
        log('Bullet Piercer expired!');
      }, 7000);
    }
  },

  /** 49. Cyclone Toss */
  {
    name: 'Cyclone Toss',
    description: 'Toss nearby enemies into the air and slam them down.',
    func: async () => {
      log('Cyclone Toss started!');
      createBurst(playerPositionX, playerPositionY);
      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 170){
          enemy.style.transition = 'bottom 0.7s ease-out';
          enemy.style.bottom = (parseInt(enemy.style.bottom) + 200) + 'px';
        }
      });
      await sleep(800);
      enemies.forEach(enemy => {
        enemy.style.bottom = '0px';
      });
      await sleep(700);
      log('Cyclone Toss ended!');
    }
  },

  /** 50. Electric Surge Ring */
  {
    name: 'Electric Surge Ring',
    description: 'Create a ring of electricity that slowly rotates and shocks enemies.',
    func: () => {
      const ring = document.createElement('div');
      ring.style.position = 'absolute';
      ring.style.width = '180px';
      ring.style.height = '180px';
      ring.style.border = '6px solid cyan';
      ring.style.borderRadius = '50%';
      ring.style.left = (playerPositionX - 70) + 'px';
      ring.style.bottom = (playerPositionY - 70) + 'px';
      ring.style.zIndex = '9999';
      gameWorld.appendChild(ring);

      let angle = 0;

      const interval = setInterval(() => {
        angle += 0.07;
        ring.style.transform = `rotate(${angle}rad)`;
        enemies.forEach((enemy, idx) => {
          const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
          if(dist < 100){
            enemy.remove();
            enemies.splice(idx,1);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            log('Enemy zapped by Electric Surge Ring!');
          }
        });
      }, 40);
      setTimeout(() => {
        clearInterval(interval);
        ring.remove();
        log('Electric Surge Ring ended!');
      }, 9000);
      log('Electric Surge Ring activated!');
    }
  },

  //--- Here end 30 big boss-like fun functions with cutscenes, blast waves, summons, status effects! ---

  // --- Additional cool powerups and fun moves (20+) to make total 50 more ---

  {
    name: 'Rapid Healing Wave',
    description: 'Heals player by 1 life every 0.75 seconds for 12 seconds.',
    func: () => {
      let ticks = 0;
      const interval = setInterval(() => {
        if (lives < 99) {
          lives++;
          updateDisplay();
          log('Healing wave restored 1 life!');
        }
        ticks++;
        if (ticks >= 16) {
          clearInterval(interval);
          log('Rapid Healing Wave ended!');
        }
      }, 750);
      log('Rapid Healing Wave started!');
    }
  },
  {
    name: 'Orbital Blade',
    description: 'Shoot spinning blades orbiting player for 7 seconds.',
    func: () => {
      const blades = [];
      for(let i=0; i<4; i++){
        const blade = document.createElement('div');
        blade.style.position = 'absolute';
        blade.style.width = '25px';
        blade.style.height = '8px';
        blade.style.borderRadius = '8px';
        blade.style.backgroundColor = 'silver';
        gameWorld.appendChild(blade);
        blades.push({el: blade, angle: i * (2*Math.PI/4)});
      }
      let angle = 0;
      const radius = 60;

      let intv = setInterval(() => {
        angle += 0.1;
        blades.forEach(blade => {
          blade.angle += 0.1;
          const x = playerPositionX + player.offsetWidth/2 + radius*Math.cos(blade.angle);
          const y = playerPositionY + player.offsetHeight/2 + radius*Math.sin(blade.angle);
          blade.el.style.left = x + 'px';
          blade.el.style.bottom = y + 'px';

          enemies.forEach((enemy, idx) => {
            if(checkCollision(blade.el, enemy)){
              enemy.remove();
              enemies.splice(idx,1);
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              log('Enemy cut by Orbital Blade!');
            }
          });
        });
      }, 50);
      setTimeout(() => {
        clearInterval(intv);
        blades.forEach(b => b.el.remove());
        log('Orbital Blade vanished!');
      }, 7000);
      log('Orbital Blade spawned!');
    }
  },
  {
    name: 'Blazing Trail',
    description: 'Leave a fiery trail that burns enemies for 6 seconds.',
    func: () => {
      let interval = setInterval(() => {
        const trail = document.createElement('div');
        trail.style.position = 'absolute';
        trail.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
        trail.style.bottom = (playerPositionY + player.offsetHeight/2) + 'px';
        trail.style.width = '15px';
        trail.style.height = '15px';
        trail.style.borderRadius = '50%';
        trail.style.backgroundColor = 'orange';
        trail.style.opacity = '0.7';
        gameWorld.appendChild(trail);
        setTimeout(() => trail.remove(), 500);

        enemies.forEach((enemy, idx) => {
          if (checkCollision(trail, enemy)){
            applyBurn(enemy);
          }
        });
      },100);
      setTimeout(() => {
        clearInterval(interval);
        log('Blazing Trail ended!');
      }, 6000);
      log('Blazing Trail activated!');
    }
  },
  {
    name: 'Revive Spark',
    description: 'Bring back 3 recently defeated enemies with half health as allies for 7 seconds.',
    func: () => {
      log('Revive Spark activated!');
      // Assuming removedEnemies array from your code tracks recently defeated enemies
      if(typeof removedEnemies === 'undefined' || removedEnemies.length === 0){
        log('No recently defeated enemies to revive!');
        return;
      }
      const revives = removedEnemies.splice(0, 3);
      revives.forEach(r => {
        const ally = createElement(r.className, enemies, playerPositionX + Math.random() * 40 + 20);
        ally.style.backgroundColor = 'lightgreen';
      });
      setTimeout(() => {
        enemies = enemies.filter(enemy => !revives.includes(enemy));
        revives.forEach(r => {
          const idx = enemies.indexOf(r);
          if(idx !== -1) {
            enemies[idx].remove();
            enemies.splice(idx, 1);
          }
        });
        log('Revived allies vanished!');
      }, 7000);
    }
  },
  {
    name: 'Shock Flash',
    description: 'Flash screen with a shockwave that stuns enemies for 3 seconds.',
    func: () => {
      const flash = document.createElement('div');
      Object.assign(flash.style, {
        position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh',
        backgroundColor: 'white', opacity: '0.9', zIndex: 10000,
        pointerEvents: 'none',
      });
      document.body.appendChild(flash);

      enemies.forEach(enemy => {
        enemy.classList.add('frozen-enemy');
        enemy.style.opacity = '0.2';
      });

      log('Shock Flash activated!');
      setTimeout(() => {
        flash.remove();
        enemies.forEach(enemy => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        log('Shock Flash ended!');
      }, 3000);
    }
  },
  {
    name: 'Arc Wave',
    description: 'Release an arc-shaped energy wave damaging enemies across π/2 radian sector.',
    func: () => {
      const originX = playerPositionX + player.offsetWidth / 2;
      const originY = playerPositionY + player.offsetHeight / 2;
      const maxDistance = 280;
      const arcAngle = Math.PI / 2; // 90 degrees

      enemies.forEach(enemy => {
        const ex = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
        const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;

        const dx = ex - originX;
        const dy = ey - originY;
        const distance = Math.hypot(dx, dy);
        let angle = Math.atan2(dy, dx);
        let forwardAngle = currentDirection === 1 ? 0 : Math.PI;

        // Normalize angles for easy comparison
        const diff = Math.abs(angle - forwardAngle);
        if(distance <= maxDistance && diff <= arcAngle / 2){
          createBurst(ex, ey);
          enemy.remove();
          enemies.splice(enemies.indexOf(enemy), 1);
          log('Enemy wiped by arc wave!');
        }
      });
      createBurst(playerPositionX, playerPositionY);
      log('Arc Wave unleashed!');
    }
  },
  {
    name: 'Blade Flurry',
    description: 'Launch a flurry of spinning blades forward covering wide space.',
    func: () => {
      const bladeCount = 6;
      let blades = [];

      for(let i = 0; i < bladeCount; i++){
        const blade = document.createElement('div');
        blade.style.position = 'absolute';
        blade.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
        blade.style.bottom = (playerPositionY + player.offsetHeight/2 + (i - bladeCount/2)*12) + 'px';
        blade.style.width = '30px';
        blade.style.height = '10px';
        blade.style.backgroundColor = 'gray';
        blade.style.borderRadius = '15px';
        gameWorld.appendChild(blade);
        blades.push(blade);
      }

      let dist = 0;
      const maxDist = 400;
      let interval = setInterval(() => {
        if(dist > maxDist){
          blades.forEach(b => b.remove());
          clearInterval(interval);
          log('Blade Flurry ended!');
          return;
        }
        blades.forEach(blade => {
          let left = parseInt(blade.style.left);
          blade.style.left = (left + 10 * currentDirection) + 'px';
          enemies.forEach((enemy, idx) => {
            if(checkCollision(blade,enemy)){
              enemy.remove();
              enemies.splice(idx,1);
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              log('Enemy sliced by Blade Flurry!');
            }
          });
        });
        dist += 10;
      }, 40);

      log('Blade Flurry launched!');
    }
  },


  /** 51. Iron Skin */
  {
    name: 'Iron Skin',
    description: 'Makes player take no damage from enemies for 10 seconds.',
    func: () => {
      isInvincible = true;
      player.style.border = '5px solid gray';
      log('Iron Skin activated!');
      setTimeout(() => {
        isInvincible = false;
        player.style.border = '';
        log('Iron Skin expired!');
      }, 10000);
    }
  },

  /** 52. Flame Trail */
  {
    name: 'Flame Trail',
    description: 'Player leaves fire on the ground damaging enemies passing over for 7 seconds.',
    func: () => {
      const fireInterval = setInterval(() => {
        const fire = document.createElement('div');
        fire.style.position = 'absolute';
        fire.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
        fire.style.bottom = playerPositionY + 'px';
        fire.style.width = '15px';
        fire.style.height = '30px';
        fire.style.backgroundColor = 'orange';
        fire.style.borderRadius = '10px';
        gameWorld.appendChild(fire);

        setTimeout(() => fire.remove(), 1000);

        enemies.forEach((enemy, idx) => {
          if (checkCollision(fire, enemy)) {
            applyBurn(enemy);
            enemy.style.backgroundColor = 'orange';
            log('Enemy burned by flame trail!');
          }
        });
      }, 150);

      setTimeout(() => {
        clearInterval(fireInterval);
        log('Flame Trail ended!');
      }, 7000);
      log('Flame Trail activated!');
    }
  },

  /** 53. Frost Nova */
  {
    name: 'Frost Nova',
    description: 'Freeze all enemies within 160px radius for 5 seconds.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 160){
          enemy.classList.add('frozen-enemy');
          enemy.style.opacity = '0.3';
          setTimeout(() => {
            enemy.classList.remove('frozen-enemy');
            enemy.style.opacity = '1';
            log('Enemy unfrozen from Frost Nova!');
          }, 5000);
        }
      });
      log('Frost Nova released!');
    }
  },

  /** 54. Scorching Beam */
  {
    name: 'Scorching Beam',
    description: 'Fire a scorching beam burning enemies in a straight line for 6 seconds.',
    func: () => {
      const beam = document.createElement('div');
      beam.style.position = 'absolute';
      beam.style.left = (playerPositionX + player.offsetWidth/2 - 10) + 'px';
      beam.style.bottom = playerPositionY + 'px';
      beam.style.width = '20px';
      beam.style.height = gameContainer.offsetHeight + 'px';
      beam.style.backgroundColor = 'orange';
      beam.style.opacity = '0.8';
      gameWorld.appendChild(beam);

      const interval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          if(checkCollision(beam, enemy)){
            applyBurn(enemy);
            log('Enemy burning from Scorching Beam!');
            enemy.remove();
            enemies.splice(idx,1);
          }
        });
      }, 150);

      setTimeout(() => {
        clearInterval(interval);
        beam.remove();
        log('Scorching Beam ended!');
      }, 6000);
      log('Scorching Beam fired!');
    }
  },

  /** 55. Double Dash */
  {
    name: 'Double Dash',
    description: 'Perform two fast dashes doing damage and knocking back enemies.',
    func: async () => {
      for(let count=0; count<2; count++){
        player.classList.add('glow');
        let dist = 0;
        const maxDist = 240;
        const speed = 25;
        await new Promise(resolve => {
          const interval = setInterval(() => {
            if(dist >= maxDist){
              clearInterval(interval);
              resolve();
              return;
            }
            playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
            player.style.left = playerPositionX + 'px';
            enemies.forEach((enemy, idx) => {
              if(checkCollision(player, enemy)){
                enemy.remove();
                enemies.splice(idx,1);
                createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
                log('Enemy hit by Dash!');
              }
            });
            dist += speed;
          }, 40);
        });
        player.classList.remove('glow');
        await sleep(400);
      }
      log('Double Dash complete!');
    }
  },

  /** 56. Nova Shield */
  {
    name: 'Nova Shield',
    description: 'Create a protective shield that emits damaging nova pulses every 3 seconds for 12 seconds.',
    func: () => {
      player.style.border = '6px solid cyan';
      let pulseCount = 0;
      let interval = setInterval(() => {
        createBurst(playerPositionX, playerPositionY);
        enemies.forEach((enemy, idx) => {
          if (Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY) < 140) {
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy destroyed by Nova Shield!');
          }
        });
        pulseCount++;
        if(pulseCount > 4){
          clearInterval(interval);
          player.style.border = '';
          log('Nova Shield expired!');
        }
      }, 3000);
      log('Nova Shield activated!');
    }
  },

  /** 57. Flame Kick Combo */
  {
    name: 'Flame Kick Combo',
    description: 'Perform a triple combo attack wrapping enemies in flames.',
    func: async () => {
      log('Flame Kick Combo started!');
      for(let i=0; i<3; i++){
        createBurst(playerPositionX, playerPositionY);
        enemies.forEach((enemy, idx) => {
          const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
          if(dist < 120){
            applyBurn(enemy);
            enemy.style.backgroundColor = 'orange';
          }
        });
        await sleep(600);
      }
      log('Flame Kick Combo ended!');
    }
  },

  /** 58. Magnetic Blade */
  {
    name: 'Magnetic Blade',
    description: 'Swing a magnetic blade pulling enemies close and slashing them.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      enemies.forEach(enemy => {
        const dx = playerPositionX - parseInt(enemy.style.left);
        const dy = playerPositionY - parseInt(enemy.style.bottom);
        let dist = Math.sqrt(dx*dx + dy*dy);
        if(dist < 250){
          enemy.style.left = (parseInt(enemy.style.left) + dx * 0.2) + 'px';
          enemy.style.bottom = (parseInt(enemy.style.bottom) + dy * 0.2) + 'px';
        }
      });

      setTimeout(() => {
        enemies.forEach((enemy, idx) => {
          if(checkCollision(player, enemy)){
            enemy.remove();
            enemies.splice(idx,1);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            log('Enemy slashed by Magnetic Blade!');
          }
        });
      }, 700);
      log('Magnetic Blade swung!');
    }
  },

  /** 59. Fire Lotus */
  {
    name: 'Fire Lotus',
    description: 'Spawn a lotus flower around player that shoots fire at nearest enemies for 8 seconds.',
    func: () => {
      const lotus = document.createElement('div');
      lotus.style.position = 'absolute';
      lotus.style.left = (playerPositionX + player.offsetWidth/2 - 30) + 'px';
      lotus.style.bottom = (playerPositionY + player.offsetHeight/2 - 30) + 'px';
      lotus.style.width = '60px';
      lotus.style.height = '60px';
      lotus.style.borderRadius = '50%';
      lotus.style.backgroundColor = 'red';
      lotus.style.opacity = '0.8';
      gameWorld.appendChild(lotus);

      let shots = 0;
      const maxShots = 20;

      const attackInterval = setInterval(() => {
        if(shots >= maxShots){
          clearInterval(attackInterval);
          lotus.remove();
          log('Fire Lotus disappeared!');
          return;
        }
        if(enemies.length === 0) return;

        let target = enemies.reduce((a,b) => {
          const ad = Math.hypot(parseInt(a.style.left) - parseInt(lotus.style.left), parseInt(a.style.bottom) - parseInt(lotus.style.bottom));
          const bd = Math.hypot(parseInt(b.style.left) - parseInt(lotus.style.left), parseInt(b.style.bottom) - parseInt(lotus.style.bottom));
          return ad < bd ? a : b;
        });

        let bullet = document.createElement('div');
        bullet.classList.add('bullet');
        bullet.style.position = 'absolute';
        bullet.style.left = lotus.style.left;
        bullet.style.bottom = lotus.style.bottom;
        bullet.style.backgroundColor = 'orange';
        bullet.style.width = '7px';
        bullet.style.height = '6px';
        gameWorld.appendChild(bullet);

        let bx = parseFloat(bullet.style.left), by = parseFloat(bullet.style.bottom);
        let tx = parseInt(target.style.left), ty = parseInt(target.style.bottom);
        let dist = Math.hypot(tx - bx, ty - by);
        const speed = 9;

        function move() {
          if(!bullet.parentElement) return;
          let dx = (tx - bx) / dist * speed;
          let dy = (ty - by) / dist * speed;
          bx += dx;
          by += dy;
          bullet.style.left = bx + 'px';
          bullet.style.bottom = by + 'px';

          if(checkCollision(bullet, target)){
            createBurst(tx, ty);
            target.remove();
            enemies.splice(enemies.indexOf(target),1);
            bullet.remove();
            log('Fire Lotus bullet hit!');
            return;
          }

          if(bx < 0 || bx > gameWorld.offsetWidth || by < 0 || by > gameWorld.offsetHeight){
            bullet.remove();
            return;
          }
          requestAnimationFrame(move);
        }
        move();

        shots++;
      }, 400);

      log('Fire Lotus summoned!');
    }
  },
  {
    name: 'Drone Swarm Assist',
    description: 'Summon a swarm of 6 small AI drones that orbit the player and shoot enemies for 10 seconds.',
    func: () => {
      const droneCount = 6;
      const drones = [];
      for (let i = 0; i < droneCount; i++) {
        const drone = document.createElement('div');
        drone.style.position = 'absolute';
        drone.style.width = '15px';
        drone.style.height = '15px';
        drone.style.backgroundColor = 'cyan';
        drone.style.borderRadius = '50%';
        drone.style.opacity = '0.8';
        drone.style.zIndex = 1000;
        gameWorld.appendChild(drone);
        drones.push({ el: drone, angle: (i * (2 * Math.PI)) / droneCount, cooldown: 0 });
      }
      
      let timeElapsed = 0;
      const duration = 10000; // 10 seconds
      const radius = 50;

      const intervalId = setInterval(() => {
        timeElapsed += 50;
        drones.forEach(d => {
          if (!d.el.parentElement) return;
          d.angle += 0.05;
          const newX = playerPositionX + player.offsetWidth / 2 + radius * Math.cos(d.angle);
          const newY = playerPositionY + player.offsetHeight / 2 + radius * Math.sin(d.angle);
          d.el.style.left = newX + 'px';
          d.el.style.bottom = newY + 'px';

          if (d.cooldown <= 0) {
            // Shoot bullet ahead orbit direction
            const bullet = document.createElement('div');
            bullet.classList.add('bullet');
            bullet.style.position = 'absolute';
            bullet.style.backgroundColor = 'cyan';
            bullet.style.width = '6px';
            bullet.style.height = '3px';
            bullet.style.borderRadius = '3px';
            bullet.style.left = (newX + 5) + 'px';
            bullet.style.bottom = (newY + 5) + 'px';
            gameWorld.appendChild(bullet);

            let bx = newX + 5;
            let by = newY + 5;
            const speed = 7;
            const angleRad = d.angle;

            function moveBullet() {
              if (!bullet.parentElement) return;
              bx += Math.cos(angleRad) * speed;
              by += Math.sin(angleRad) * speed;
              bullet.style.left = bx + 'px';
              bullet.style.bottom = by + 'px';

              enemies.forEach((enemy, idx) => {
                if (checkCollision(bullet, enemy)) {
                  createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
                  enemy.remove();
                  enemies.splice(idx, 1);
                  bullet.remove();
                  return;
                }
              });

              if (bx < 0 || bx > gameWorld.offsetWidth || by < 0 || by > gameWorld.offsetHeight) {
                bullet.remove();
                return;
              }

              requestAnimationFrame(moveBullet);
            }
            moveBullet();

            d.cooldown = 1000; // 1 second cooldown
          }
          d.cooldown -= 50;
        });

        if (timeElapsed >= duration) {
          drones.forEach(d => { if(d.el) d.el.remove(); });
          clearInterval(intervalId);
          log('Drone Swarm Assist ended!');
        }
      }, 50);

      log('Drone Swarm Assist summoned!');
    }
  },

  // 102: Hypno Wave
  {
    name: 'Hypno Wave',
    description: 'Emit a hypnotic pulse that instantly hypnotizes nearby enemies for 8 seconds.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      enemies.forEach(enemy => {
        let dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if (dist < 200 && !enemy.classList.contains('hypnotized')) {
          enemy.classList.add('hypnotized');
          enemy.style.backgroundColor = 'pink';
          hypnotizeEnemy(enemy);  // Use the existing hypnotize behavior function
          setTimeout(() => {
            if(enemy) {
              enemy.classList.remove('hypnotized');
              enemy.style.backgroundColor = '';
            }
          }, 8000);
        }
      });
      log('Hypno Wave released!');
    }
  },

  // 103: Instant Wall Barrage
  {
    name: 'Instant Wall Barrage',
    description: 'Erect 3 damaging wall barriers behind the player that last 7 seconds, damaging enemies on contact.',
    func: () => {
      const gap = 80;
      for (let i = 1; i <= 3; i++) {
        const wall = document.createElement('div');
        wall.style.position = 'absolute';
        wall.style.width = '30px';
        wall.style.height = '150px';
        wall.style.backgroundColor = 'magenta';
        wall.style.opacity = '0.7';
        wall.style.left = (playerPositionX - i * gap) + 'px'; // Walls behind player
        wall.style.bottom = '0px';
        gameWorld.appendChild(wall);

        const damageInterval = setInterval(() => {
          enemies.forEach((enemy, idx) => {
            if (checkCollision(wall, enemy)) {
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              log('Enemy crushed by Instant Wall Barrage!');
            }
          });
        }, 100);

        setTimeout(() => {
          clearInterval(damageInterval);
          wall.remove();
          log('Wall barrier disappeared.');
        }, 7000);
      }

      log('Instant Wall Barrage activated!');
    }
  },

  // 104: AI Friend Protector
  {
    name: 'AI Friend Protector',
    description: 'Summon a green ally that follows the player and blocks all enemy attacks for 12 seconds.',
    func: () => {
      const friendAlly = document.createElement('div');
      friendAlly.style.position = 'absolute';
      friendAlly.style.width = '30px';
      friendAlly.style.height = '30px';
      friendAlly.style.borderRadius = '50%';
      friendAlly.style.backgroundColor = 'limegreen';
      friendAlly.style.border = '2px solid white';
      friendAlly.style.left = (playerPositionX - 40) + 'px';
      friendAlly.style.bottom = playerPositionY + 'px';
      gameWorld.appendChild(friendAlly);

      const intervalId = setInterval(() => {
        if (!friendAlly.parentElement) {
          clearInterval(intervalId);
          return;
        }
        // Follow player smoothly
        const fX = parseFloat(friendAlly.style.left);
        const fY = parseFloat(friendAlly.style.bottom);
        const pX = playerPositionX;
        const pY = playerPositionY;
        const dx = pX - fX;
        const dy = pY - fY;

        friendAlly.style.left = fX + dx * 0.15 + 'px';
        friendAlly.style.bottom = fY + dy * 0.15 + 'px';

        // Block enemies (remove enemies within 40px radius)
        enemies.forEach((enemy, idx) => {
          let dist = Math.hypot(parseInt(enemy.style.left) - fX, parseInt(enemy.style.bottom) - fY);
          if (dist < 40) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy blocked by AI Friend Protector!');
          }
        });
      }, 60);

      setTimeout(() => {
        if (friendAlly.parentElement) friendAlly.remove();
        clearInterval(intervalId);
        log('AI Friend Protector vanished!');
      }, 12000);

      log('AI Friend Protector summoned!');
    }
  },

  // 105: Boss Phase - Reflective Prism
  {
    name: 'Boss Phase - Reflective Prism',
    description: 'The boss summons a prism that reflects all bullets for 8 seconds.',
    func: async () => {
      if (!boss) {
        log('No boss active for Reflective Prism!');
        return;
      }

      displayMessage('Boss activates Reflective Prism! Bullets will be reflected!', 8);
      log('Boss Reflective Prism enabled!');

      // Attach prism element in front of boss
      const prism = document.createElement('div');
      prism.style.position = 'absolute';
      prism.style.width = '50px';
      prism.style.height = '50px';
      prism.style.borderRadius = '30%';
      prism.style.backgroundColor = 'purple';
      prism.style.left = (parseInt(boss.style.left) + boss.offsetWidth + 10) + 'px';
      prism.style.bottom = (parseInt(boss.style.bottom) + 20) + 'px';
      prism.style.boxShadow = '0 0 25px violet';
      gameWorld.appendChild(prism);

      // Bullets will reflect at prism
      const reflectInterval = setInterval(() => {
        bullets.forEach(bulletObj => {
          const bullet = bulletObj.element;
          if (checkCollision(bullet, prism)) {
            bulletObj.direction *= -1; // Reverse bullet direction
            log('Bullet reflected by Boss Prism!');
          }
        });
      }, 30);

      await sleep(8000);

      clearInterval(reflectInterval);
      prism.remove();
      log('Boss Reflective Prism ended!');
      displayMessage('Boss Reflective Prism ended!');
    }
  },

  // 106: Instant Hypno-Controlled Enemy Swap
  {
    name: 'Instant Hypno-Controlled Enemy Swap',
    description: 'Swap control with an enemy instantly and move it for 10 seconds to destroy other enemies.',
    func: () => {
      if (enemies.length === 0) {
        log('No enemies to swap control with!');
        return;
      }

      const enemyToControl = enemies[Math.floor(Math.random() * enemies.length)];
      enemyToControl.style.backgroundColor = 'violet';
      enemyToControl.classList.add('hypnotized');
      log('You control an enemy for 10 seconds!');

      const duration = 10000;

      // Timer for controlled enemy movement
      let direction = Math.random() < 0.5 ? -1 : 1;
      const speed = 7;

      const interval = setInterval(() => {
        if (!enemyToControl.parentElement) {
          clearInterval(interval);
          return;
        }
        let newX = parseInt(enemyToControl.style.left) + speed * direction;
        if (newX < 0 || newX > gameWorld.offsetWidth - enemyToControl.offsetWidth) {
          direction *= -1;
          newX = Math.max(0, Math.min(gameWorld.offsetWidth - enemyToControl.offsetWidth, newX));
        }
        enemyToControl.style.left = newX + 'px';

        // Destroy enemies on collision
        enemies.forEach((enemy, idx) => {
          if (enemy !== enemyToControl && checkCollision(enemy, enemyToControl)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Controlled enemy kills an enemy!');
          }
        });
      }, 50);

      setTimeout(() => {
        clearInterval(interval);
        if (enemyToControl.parentElement) {
          enemyToControl.classList.remove('hypnotized');
          enemyToControl.style.backgroundColor = '';
        }
        log('Hypno-controlled enemy returned to normal!');
      }, duration);
    }
  },

  // 107: Lightning Drone Barrage
  {
    name: 'Lightning Drone Barrage',
    description: 'Summon 3 lightning drones that strike lightning bolts on enemies every 2 seconds for 8 seconds.',
    func: () => {
      const drones = [];
      const droneCount = 3;

      for (let i = 0; i < droneCount; i++) {
        const drone = document.createElement('div');
        drone.style.position = 'absolute';
        drone.style.width = '25px';
        drone.style.height = '25px';
        drone.style.borderRadius = '50%';
        drone.style.backgroundColor = 'cyan';
        drone.style.border = '2px solid white';
        drone.style.left = (playerPositionX + i * 40 + 60) + 'px';
        drone.style.bottom = (playerPositionY + 100) + 'px';
        gameWorld.appendChild(drone);
        drones.push(drone);
      }

      const interval = setInterval(() => {
        drones.forEach(drone => {
          if (!drone.parentElement) return;
          // Find nearest enemy within 300px
          const droneX = parseInt(drone.style.left);
          const droneY = parseInt(drone.style.bottom);
          let nearestEnemy = null;
          let nearestDistance = 9999;
          enemies.forEach(enemy => {
            const ex = parseInt(enemy.style.left);
            const ey = parseInt(enemy.style.bottom);
            const dist = Math.hypot(ex - droneX, ey - droneY);
            if (dist < nearestDistance && dist < 300) {
              nearestDistance = dist;
              nearestEnemy = enemy;
            }
          });
          if (nearestEnemy) {
            // Visual lightning bolt (simple vertical line for demo)
            const bolt = document.createElement('div');
            bolt.style.position = 'absolute';
            bolt.style.left = (nearestEnemy.offsetLeft + nearestEnemy.offsetWidth / 2) + 'px';
            bolt.style.bottom = nearestEnemy.style.bottom;
            bolt.style.width = '4px';
            bolt.style.height = '50px';
            bolt.style.backgroundColor = 'skyblue';
            bolt.style.borderRadius = '2px';
            bolt.style.zIndex = '1000';
            gameWorld.appendChild(bolt);

            setTimeout(() => {
              if (nearestEnemy.parentElement) {
                createBurst(parseInt(nearestEnemy.style.left), parseInt(nearestEnemy.style.bottom));
                nearestEnemy.remove();
                enemies = enemies.filter(e => e !== nearestEnemy);
                log('Enemy zapped by Lightning Drone!');
              }
              bolt.remove();
            }, 200);
          }
        });
      }, 2000);

      setTimeout(() => {
        drones.forEach(drone => { if (drone.parentElement) drone.remove(); });
        clearInterval(interval);
        log('Lightning Drone Barrage ended!');
      }, 8000);
      log('Lightning Drone Barrage started!');
    }
  },

  // 108: Wall of Fire Dash
  {
    name: 'Wall of Fire Dash',
    description: 'Dash forward leaving a wall of fire that damages enemies for 6 seconds.',
    func: () => {
      let distance = 0;
      const maxDistance = 400;
      const speed = 20;
      player.classList.add('glow');
      const fireWalls = [];

      const interval = setInterval(() => {
        if (distance >= maxDistance) {
          clearInterval(interval);
          fireWalls.forEach(wall => wall.remove());
          player.classList.remove('glow');
          log('Wall of Fire Dash ended!');
          return;
        }

        // Move player forward
        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';

        // Leave fire wall behind
        const wall = document.createElement('div');
        wall.style.position = 'absolute';
        wall.style.left = (playerPositionX - 20) + 'px';
        wall.style.bottom = playerPositionY + 'px';
        wall.style.width = '30px';
        wall.style.height = '60px';
        wall.style.backgroundColor = 'orange';
        wall.style.opacity = '0.7';
        wall.style.borderRadius = '8px';
        gameWorld.appendChild(wall);
        fireWalls.push(wall);

        // Damage enemies touching fire walls
        enemies.forEach((enemy, idx) => {
          fireWalls.forEach(fireWall => {
            if (checkCollision(enemy, fireWall)) {
              applyBurn(enemy);
              log('Enemy burned by Wall of Fire!');
            }
          });
        });

        // Remove walls older than 3 seconds
        if (fireWalls.length > 15) {
          const removedWall = fireWalls.shift();
          removedWall.remove();
        }

        distance += speed;
      }, 40);

      log('Wall of Fire Dash started!');
    }
  },

  // 109: Drone Repair Station
  {
    name: 'Drone Repair Station',
    description: 'Place a repair station that heals player’s AI drones gradually for 10 seconds.',
    func: () => {
      const station = document.createElement('div');
      station.style.position = 'absolute';
      station.style.left = (playerPositionX + 50) + 'px';
      station.style.bottom = playerPositionY + 'px';
      station.style.width = '40px';
      station.style.height = '40px';
      station.style.borderRadius = '50%';
      station.style.backgroundColor = 'lime';
      station.style.opacity = '0.8';
      gameWorld.appendChild(station);

      // Mock drone health - in real code, you might maintain drone health status

      let ticks = 0;
      const maxTicks = 20;

      const interval = setInterval(() => {
        // Heal + log (placeholder)
        ticks++;
        if (ticks >= maxTicks) {
          clearInterval(interval);
          station.remove();
          log('Drone Repair Station expired!');
        } else {
          log('Drones repaired a little...');
        }
      }, 500);
      log('Drone Repair Station deployed!');
    }
  },

  // 110: Instant Hypno Clap
  {
    name: 'Instant Hypno Clap',
    description: 'Players clap causing immediate stun to all nearby enemies for 4 seconds.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if (dist < 150) {
          enemy.classList.add('frozen-enemy');
          enemy.style.opacity = '0.25';
          setTimeout(() => {
            if(enemy) {
              enemy.classList.remove('frozen-enemy');
              enemy.style.opacity = '1';
              log('Enemy recovered from Hypno Clap stun!');
            }
          }, 4000);
        }
      });
      log('Hypno Clap emitted!');
    }
  },

  // 111: Boss Clone Summon
  {
    name: 'Boss Clone Summon',
    description: 'Boss creates 2 identical clones that confuse the player for 12 seconds.',
    func: () => {
      if (!boss) {
        log('No boss active!');
        return;
      }
      const clones = [];
      for (let i = 0; i < 2; i++) {
        const clone = document.createElement('div');
        clone.classList.add('boss');
        clone.style.position = 'absolute';
        clone.style.width = boss.offsetWidth + 'px';
        clone.style.height = boss.offsetHeight + 'px';
        clone.style.backgroundColor = 'rgba(255,69,0,0.6)';
        clone.style.left = (parseInt(boss.style.left) + (i === 0 ? -80 : 80)) + 'px';
        clone.style.bottom = boss.style.bottom;
        gameWorld.appendChild(clone);
        clones.push(clone);
      }
      setTimeout(() => {
        clones.forEach(clone => clone.remove());
        log('Boss clones vanished!');
      }, 12000);
      log('Boss summoned clones!');
    }
  },

  // 112: Alien Mind Control
  {
    name: 'Alien Mind Control',
    description: 'Infect all enemies to fight for you for 8 seconds (enemy minions).',
    func: () => {
      enemies.forEach(enemy => {
        enemy.style.border = '3px solid purple';
        enemy.dataset.friendly = 'true';
        // Enemy now attacks other enemies (disable damage to player temporarily)
      });
      log('Alien Mind Control activated! Enemies fight for you.');

      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.style.border = '';
          delete enemy.dataset.friendly;
        });
        log('Alien Mind Control ended! Enemies back to normal.');
      }, 8000);
    }
  },

  // 113: Hypno Drone
  {
    name: 'Hypno Drone',
    description: 'Summon a drone that hypnotizes enemies on contact for 10 seconds.',
    func: () => {
      const drone = document.createElement('div');
      drone.style.position = 'absolute';
      drone.style.width = '25px';
      drone.style.height = '25px';
      drone.style.borderRadius = '50%';
      drone.style.backgroundColor = 'purple';
      drone.style.left = (playerPositionX + 60) + 'px';
      drone.style.bottom = playerPositionY + 'px';
      gameWorld.appendChild(drone);

      let dir = 1;

      const interval = setInterval(() => {
        if (!drone.parentElement) {
          clearInterval(interval);
          return;
        }
        let newLeft = parseInt(drone.style.left) + 5 * dir;
        if (newLeft < playerPositionX || newLeft > playerPositionX + 200) {
          dir *= -1;
          newLeft = parseInt(drone.style.left) + 5 * dir;
        }
        drone.style.left = newLeft + 'px';

        enemies.forEach(enemy => {
          if (!enemy.classList.contains('hypnotized') && checkCollision(drone, enemy)) {
            enemy.classList.add('hypnotized');
            enemy.style.backgroundColor = 'pink';
            hypnotizeEnemy(enemy);
            log('Enemy hypnotized by Hypno Drone!');
          }
        });
      }, 60);

      setTimeout(() => {
        drone.remove();
        clearInterval(interval);
        enemies.forEach(enemy => {
          enemy.classList.remove('hypnotized');
          enemy.style.backgroundColor = '';
        });
        log('Hypno Drone expired!');
      }, 10000);
      log('Hypno Drone summoned!');
    }
  },

  // 114: Instant Walls - Ice Spike Columns
  {
    name: 'Instant Walls - Ice Spike Columns',
    description: 'Create 5 ice spike columns instantly damaging enemies for 9 seconds.',
    func: () => {
      const spikeCount = 5;
      const spikeWidth = 30;
      const spikeHeight = 110;
      const baseX = playerPositionX + 50;

      const spikes = [];

      for (let i = 0; i < spikeCount; i++) {
        const spike = document.createElement('div');
        spike.style.position = 'absolute';
        spike.style.left = (baseX + i * (spikeWidth + 10)) + 'px';
        spike.style.bottom = '0px';
        spike.style.width = spikeWidth + 'px';
        spike.style.height = spikeHeight + 'px';
        spike.style.backgroundColor = 'lightblue';
        spike.style.borderRadius = '8px 8px 10px 10px';
        gameWorld.appendChild(spike);
        spikes.push(spike);
      }

      const interval = setInterval(() => {
        spikes.forEach(spike => {
          enemies.forEach((enemy, idx) => {
            if (checkCollision(spike, enemy)) {
              applyBurn(enemy);
              log('Enemy burned by Ice Spike Column!');
            }
          });
        });
      }, 200);

      setTimeout(() => {
        clearInterval(interval);
        spikes.forEach(sp => sp.remove());
        log('Ice Spike Columns vanished!');
      }, 9000);
      log('Ice Spike Columns created!');
    }
  },

  // 115: Super Hypno Swarm
  {
    name: 'Super Hypno Swarm',
    description: 'Fire 30 hypnotic bullets rapidly that confuse enemies for 10 seconds.',
    func: () => {
      let count = 0;
      const interval = setInterval(() => {
        shootHypno();
        count++;
        if (count >= 30) {
          clearInterval(interval);
          log('Super Hypno Swarm ended!');
        }
      }, 100);
      log('Super Hypno Swarm unleashed!');
    }
  },

  // 116: Drone Healing Aura
  {
    name: 'Drone Healing Aura',
    description: 'Summon drones that heal player by 1 life every second for 12 seconds.',
    func: () => {
      const drone = document.createElement('div');
      drone.style.position = 'absolute';
      drone.style.width = '40px';
      drone.style.height = '40px';
      drone.style.borderRadius = '50%';
      drone.style.backgroundColor = 'lightgreen';
      drone.style.opacity = '0.6';
      drone.style.left = (playerPositionX + 50) + 'px';
      drone.style.bottom = playerPositionY + 'px';
      gameWorld.appendChild(drone);

      let ticks = 0;
      const maxTicks = 12;
      const interval = setInterval(() => {
        if (lives < 99) {
          lives++;
          updateDisplay();
          log('Drone heals player 1 life!');
        }
        ticks++;
        if (ticks >= maxTicks) {
          clearInterval(interval);
          drone.remove();
          log('Drone Healing Aura ended!');
        }
      }, 1000);
      log('Drone Healing Aura activated!');
    }
  },

  // 117: Instant Shock Pulse
  {
    name: 'Instant Shock Pulse',
    description: 'Stun all enemies for 5 seconds instantly, removing their movement.',
    func: () => {
      enemies.forEach(enemy => {
        enemy.classList.add('frozen-enemy');
        enemy.style.opacity = '0.3';
      });
      log('Shock Pulse stun all enemies!');
      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        log('Shock Pulse ended.');
      }, 5000);
    }
  },

  // 118: Instant Hypno Guard
  {
    name: 'Instant Hypno Guard',
    description: 'Create a protective hypnotic shield for 8 seconds that bombs touching enemies.',
    func: () => {
      const shield = document.createElement('div');
      shield.style.position = 'absolute';
      shield.style.width = '140px';
      shield.style.height = '140px';
      shield.style.borderRadius = '50%';
      shield.style.border = '4px dotted magenta';
      shield.style.left = (playerPositionX - 55) + 'px';
      shield.style.bottom = (playerPositionY - 55) + 'px';
      shield.style.opacity = '0.6';
      gameWorld.appendChild(shield);

      const interval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          if (checkCollision(shield, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy destroyed by Hypno Guard bomb!');
          }
        });
      }, 250);

      setTimeout(() => {
        clearInterval(interval);
        shield.remove();
        log('Hypno Guard shield expired!');
      }, 8000);
      log('Hypno Guard activated!');
    }
  },

  // 119: Instant Drone EMP
  {
    name: 'Instant Drone EMP',
    description: 'Disable all drones (friendly and enemy) on the stage instantly for 5 seconds.',
    func: () => {
      let droneElements = [...gameWorld.querySelectorAll('div')].filter(d =>
        d.style.backgroundColor === 'cyan' || d.style.backgroundColor === 'lightblue' || d.style.backgroundColor === 'purple');
      droneElements.forEach(drone => {
        drone.style.filter = 'grayscale(100%) brightness(0.5)';
        drone.dataset.disabled = 'true';
      });
      log('Drone EMP activated! Drones disabled.');

      setTimeout(() => {
        droneElements.forEach(drone => {
          drone.style.filter = '';
          delete drone.dataset.disabled;
        });
        log('Drone EMP ended! Drones restored.');
      }, 5000);
    }
  },

  // 120: Boss Phase - Gravity Storm

  {
    name: "Plasma Dome",
    description: "Create a glowing plasma dome around player that damages enemies for 10 seconds.",
    func: () => {
      const dome = document.createElement('div');
      dome.style.position = 'absolute';
      dome.style.width = '160px';
      dome.style.height = '160px';
      dome.style.borderRadius = '50%';
      dome.style.border = '4px solid #0ff';
      dome.style.left = (playerPositionX - 60) + 'px';
      dome.style.bottom = (playerPositionY - 60) + 'px';
      dome.style.boxShadow = '0 0 40px #0ff, inset 0 0 25px #0ff';
      dome.style.opacity = '0.8';
      dome.style.pointerEvents = 'none';
      dome.style.zIndex = '9999';
      gameWorld.appendChild(dome);

      const intervalId = setInterval(() => {
        enemies.forEach((enemy, i) => {
          if (checkCollision(dome, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(i, 1);
            log('Enemy struck by Plasma Dome!');
          }
        });
      }, 150);

      setTimeout(() => {
        clearInterval(intervalId);
        dome.remove();
        log('Plasma Dome disappeared!');
      }, 10000);

      // Scoped CSS effect pulse for dome glow
      const styleId = 'fun-plasma-dome-style';
      if (!document.getElementById(styleId)) {
        const s = document.createElement('style');
        s.id = styleId;
        s.textContent = `
          @keyframes plasmaPulse {
            0%, 100% { box-shadow: 0 0 40px #0ff, inset 0 0 25px #0ff; }
            50% { box-shadow: 0 0 65px #0ff, inset 0 0 50px #0ff; }
          }
          .plasma-dome-glow {
            animation: plasmaPulse 2s infinite;
          }
        `;
        document.head.appendChild(s);
      }
      dome.classList.add('plasma-dome-glow');
    }
  },

  /** 52. Thunder Dance */
  {
    name: "Thunder Dance",
    description: "Player sprays lightning arcs around randomly damaging enemies for 8 seconds.",
    func: () => {
      const lightningArcs = [];
      const numArcs = 6;

      // Create arcs around player
      for (let i = 0; i < numArcs; i++) {
        const arc = document.createElement('div');
        arc.style.position = 'absolute';
        arc.style.width = '50px';
        arc.style.height = '6px';
        arc.style.backgroundColor = 'yellow';
        arc.style.borderRadius = '10px';
        arc.style.filter = 'drop-shadow(0 0 10px yellow)';
        arc.style.opacity = '0.8';
        gameWorld.appendChild(arc);
        lightningArcs.push({ el: arc, angle: (i * (360 / numArcs)) * Math.PI / 180 });
      }

      let angleOffset = 0;

      const intervalId = setInterval(() => {
        angleOffset += 0.15;
        lightningArcs.forEach(({ el, angle }, i) => {
          const a = angle + angleOffset;
          const x = playerPositionX + player.offsetWidth / 2 + 90 * Math.cos(a);
          const y = playerPositionY + player.offsetHeight / 2 + 70 * Math.sin(a);
          el.style.left = x + 'px';
          el.style.bottom = y + 'px';

          enemies.forEach((enemy, idx) => {
            if (checkCollision(el, enemy)) {
              enemy.remove();
              enemies.splice(idx, 1);
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              log('Enemy zapped by Thunder Dance arc!');
            }
          });
        });
      }, 40);

      setTimeout(() => {
        clearInterval(intervalId);
        lightningArcs.forEach(({ el }) => el.remove());
        log('Thunder Dance ended!');
      }, 8000);
    }
  },

  /** 53. Frost Prison */
  {
    name: "Frost Prison",
    description: "Freeze all enemies solid in ice blocks for 6 seconds.",
    func: () => {
      const iceBlocks = enemies.map(enemy => {
        const block = document.createElement('div');
        block.style.position = 'absolute';
        block.style.width = enemy.offsetWidth + 'px';
        block.style.height = enemy.offsetHeight + 'px';
        block.style.left = enemy.style.left;
        block.style.bottom = enemy.style.bottom;
        block.style.backgroundColor = '#a0e0ff';
        block.style.borderRadius = '10px';
        block.style.border = '3px solid #00aaff';
        block.style.opacity = '0.9';
        block.style.zIndex = '998';
        gameWorld.appendChild(block);

        // Freeze enemy visually
        enemy.style.opacity = '0.3';
        enemy.style.pointerEvents = 'none';

        return { block, enemy };
      });

      setTimeout(() => {
        iceBlocks.forEach(({ block, enemy }) => {
          if (block.parentElement) block.remove();
          enemy.style.opacity = '1';
          enemy.style.pointerEvents = 'auto';
        });
        log('Frost Prison broken!');
      }, 6000);

      log('Frost Prison activated!');
    }
  },

  /** 54. Summon Meteor Shower */
  {
    name: "Meteor Shower",
    description: "Summon meteors raining down slowly over 8 seconds destroying enemies & obstacles.",
    func: async () => {
      log('Meteor Shower started!');
      const count = 25;

      for (let i = 0; i < count; i++) {
        const meteor = document.createElement('div');
        meteor.style.position = 'absolute';
        meteor.style.width = '28px';
        meteor.style.height = '28px';
        meteor.style.borderRadius = '50%';
        meteor.style.backgroundColor = 'orangered';
        meteor.style.left = (gameScrollPosition + Math.random() * gameContainer.offsetWidth) + 'px';
        meteor.style.bottom = (gameContainer.offsetHeight + 60) + 'px';
        gameWorld.appendChild(meteor);

        let fallSpeed = 20 + Math.random() * 10;
        let fallInterval = setInterval(() => {
          let bottom = parseInt(meteor.style.bottom);
          bottom -= fallSpeed;
          meteor.style.bottom = bottom + 'px';

          if (bottom <= 0) {
            createBurst(parseInt(meteor.style.left), 0);
            enemies.forEach((enemy, idx) => {
              if (Math.hypot(parseInt(enemy.style.left) - parseInt(meteor.style.left), parseInt(enemy.style.bottom)) < 80) {
                enemy.remove();
                enemies.splice(idx, 1);
                log('Enemy destroyed by meteor!');
              }
            });
            obstacles.forEach((ob, idx) => {
              if (Math.hypot(parseInt(ob.style.left) - parseInt(meteor.style.left), parseInt(ob.style.bottom)) < 80) {
                ob.remove();
                obstacles.splice(idx, 1);
                log('Obstacle destroyed by meteor!');
              }
            });
            clearInterval(fallInterval);
            meteor.remove();
          }
        }, 40);
        await sleep(300);
      }

      log('Meteor Shower ended!');
    }
  },

  /** 55. Shadow Realm */
  {
    name: "Shadow Realm",
    description: "Player turns semi-transparent and enemies are slower for 10 seconds.",
    func: () => {
      player.style.opacity = '0.3';

      enemies.forEach(enemy => {
        let baseSpeed = parseFloat(enemy.dataset.speed) || 1;
        enemy.dataset.speedBackup = baseSpeed;
        enemy.dataset.speed = (baseSpeed * 0.3).toString();
        enemy.style.filter = 'blur(1.5px)';
        enemy.style.opacity = '0.6';
      });

      setTimeout(() => {
        player.style.opacity = '1';
        enemies.forEach(enemy => {
          enemy.dataset.speed = enemy.dataset.speedBackup || '1';
          enemy.style.filter = '';
          enemy.style.opacity = '1';
          delete enemy.dataset.speedBackup;
        });
        log('Shadow Realm ended!');
      }, 10000);

      log('Shadow Realm activated!');
    }
  },

  /** 56. Healing Wave */
  {
    name: "Healing Wave",
    description: "Heal the player continuously by 1 life every 2 seconds for 12 seconds.",
    func: () => {
      let healCount = 0;
      const maxHeals = 6;
      const healInterval = setInterval(() => {
        if (healCount >= maxHeals) {
          clearInterval(healInterval);
          log('Healing Wave ended!');
          return;
        }
        if (lives < 99) {
          lives++;
          updateDisplay();
          log('Player healed 1 life by Healing Wave!');
        }
        healCount++;
      }, 2000);
      log('Healing Wave started!');
    }
  },

  /** 57. Fire Spirit */
  {
    name: "Fire Spirit",
    description: "Summon a fire spirit that orbits the player and shoots fireballs for 10 seconds.",
    func: () => {
      const spirit = document.createElement('div');
      spirit.style.position = 'absolute';
      spirit.style.width = '30px';
      spirit.style.height = '30px';
      spirit.style.borderRadius = '50%';
      spirit.style.backgroundColor = 'orangered';
      spirit.style.left = (playerPositionX + 60) + 'px';
      spirit.style.bottom = (playerPositionY + 60) + 'px';
      gameWorld.appendChild(spirit);

      let angle = 0;
      const radius = 70;
      let shotsFired = 0;

      const interval = setInterval(() => {
        angle += 0.08;
        let x = playerPositionX + player.offsetWidth / 2 + radius * Math.cos(angle);
        let y = playerPositionY + player.offsetHeight / 2 + radius * Math.sin(angle);
        spirit.style.left = x + 'px';
        spirit.style.bottom = y + 'px';

        // Fireball shooting every 12 frames ~every 0.2 sec at 60fps
        if (shotsFired % 12 === 0) {
          const bullet = createBullet(1);
          bullet.style.position = 'absolute';
          bullet.style.left = spirit.style.left;
          bullet.style.bottom = spirit.style.bottom;
          bullet.style.backgroundColor = 'orange';
          gameWorld.appendChild(bullet);

          const bulletInterval = setInterval(() => {
            if (!bullet.parentElement) {
              clearInterval(bulletInterval);
              return;
            }
            let xBullet = parseFloat(bullet.style.left) + 5;
            bullet.style.left = xBullet + 'px';

            enemies.forEach((enemy, idx) => {
              if (checkCollision(bullet, enemy)) {
                createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
                enemy.remove();
                enemies.splice(idx, 1);
                bullet.remove();
                clearInterval(bulletInterval);
                log('Enemy hit by Fire Spirit fireball!');
                return;
              }
            });

            if (xBullet > gameWorld.offsetWidth) {
              bullet.remove();
              clearInterval(bulletInterval);
            }
          }, 30);
        }
        shotsFired++;
      }, 16);

      setTimeout(() => {
        clearInterval(interval);
        spirit.remove();
        log('Fire Spirit disappeared!');
      }, 10000);
      log('Fire Spirit summoned!');
    }
  },

  /** 58. Ice Wall Barrage */
  {
    name: "Ice Wall Barrage",
    description: "Create 5 ice walls in front of player that slowly move right damaging enemies for 8 seconds.",
    func: () => {
      const wallCount = 5;
      const iceWalls = [];

      // Spawn 5 walls spaced 50 px apart
      for (let i = 0; i < wallCount; i++) {
        const wall = document.createElement('div');
        wall.style.position = 'absolute';
        wall.style.width = '40px';
        wall.style.height = '60px';
        wall.style.backgroundColor = 'lightblue';
        wall.style.borderRadius = '10px';
        wall.style.left = (playerPositionX + player.offsetWidth + i * 50) + 'px';
        wall.style.bottom = playerPositionY + 'px';
        gameWorld.appendChild(wall);
        iceWalls.push(wall);
      }

      const interval = setInterval(() => {
        iceWalls.forEach((wall, idx) => {
          let left = parseFloat(wall.style.left);
          wall.style.left = (left + 4) + 'px';

          enemies.forEach((enemy, eidx) => {
            if (checkCollision(wall, enemy)) {
              applyBurn(enemy);
              enemy.style.backgroundColor = 'lightblue';
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            }
          });

          if (left > gameWorld.offsetWidth) {
            wall.remove();
            iceWalls.splice(idx, 1);
          }
        });

        if (iceWalls.length === 0) {
          clearInterval(interval);
          log('Ice Wall Barrage ended!');
        }
      }, 40);

      log('Ice Wall Barrage started!');
    }
  },

  /** 59. Laser Rain */
  {
    name: "Laser Rain",
    description: "Lasers shoot randomly from the sky for 6 seconds damaging enemies & obstacles.",
    func: () => {
      const lasers = [];
      const laserWidth = 6;

      const spawnLaser = () => {
        const laser = document.createElement('div');
        laser.style.position = 'absolute';
        laser.style.width = laserWidth + 'px';
        laser.style.height = '150px';
        laser.style.backgroundColor = 'red';
        laser.style.borderRadius = '3px';
        laser.style.left = (gameScrollPosition + Math.random() * gameContainer.offsetWidth) + 'px';
        laser.style.bottom = (gameContainer.offsetHeight) + 'px';
        gameWorld.appendChild(laser);
        lasers.push(laser);

        // Descend laser over 800 ms
        let bottom = parseInt(laser.style.bottom);
        const interval = setInterval(() => {
          bottom -= 18;
          laser.style.bottom = bottom + 'px';

          if (bottom <= 0) {
            createBurst(parseInt(laser.style.left), 0);
            enemies.forEach((enemy, idx) => {
              if (checkCollision(laser, enemy)) {
                enemy.remove();
                enemies.splice(idx, 1);
                log('Enemy hit by laser rain!');
              }
            });
            obstacles.forEach((ob, idx) => {
              if (checkCollision(laser, ob)) {
                ob.remove();
                obstacles.splice(idx, 1);
                log('Obstacle destroyed by laser rain!');
              }
            });
            clearInterval(interval);
            lasers.splice(lasers.indexOf(laser), 1);
            laser.remove();
          }
        }, 40);
      };

      const spawnInterval = setInterval(() => {
        spawnLaser();
      }, 300);

      setTimeout(() => {
        clearInterval(spawnInterval);
        lasers.forEach(laser => laser.remove());
        lasers.length = 0;
        log('Laser Rain ended!');
      }, 6000);

      log('Laser Rain started!');
    }
  },

  /** 60. Sonic Dash */
  {
    name: "Sonic Dash",
    description: "Player dashes extremely fast forward leaving sonic rings damaging enemies.",
    func: () => {
      let distance = 0;
      const maxDistance = 500;
      const speed = 40;

      player.classList.add('glow');

      const interval = setInterval(() => {
        if (distance > maxDistance) {
          clearInterval(interval);
          player.classList.remove('glow');
          log('Sonic Dash ended!');
          return;
        }

        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';

        // Create sonic ring
        const ring = document.createElement('div');
        ring.style.position = 'absolute';
        ring.style.left = (playerPositionX + player.offsetWidth / 2) + 'px';
        ring.style.bottom = (playerPositionY + player.offsetHeight / 3) + 'px';
        ring.style.width = '40px';
        ring.style.height = '40px';
        ring.style.borderRadius = '50%';
        ring.style.border = '3px solid deepskyblue';
        ring.style.opacity = '0.8';
        ring.style.pointerEvents = 'none';
        gameWorld.appendChild(ring);

        ring.animate(
          [
            { transform: 'scale(0.4)', opacity: 0.8 },
            { transform: 'scale(1.6)', opacity: 0 }
          ],
          {
            duration: 600,
            easing: 'ease-out'
          }
        );

        setTimeout(() => ring.remove(), 600);

        enemies.forEach((enemy, idx) => {
          if (checkCollision(ring, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy hit by Sonic Dash ring!');
          }
        });

        distance += speed;
      }, 30);

      log('Sonic Dash started!');
    }
  },
// Extend your existing funFunctions with these 100 fun functions:
  // 61. Shadow Blink Strike
  {
    name: 'Shadow Blink Strike',
    description: `Player teleports rapidly creating shadow copies that strike nearby enemies with dark magic.`,
    func: () => {
      const copyCount = 6;
      const shadowCopies = [];
      const originalX = playerPositionX;
      const originalY = playerPositionY;
      const speed = 100;
      log('Shadow Blink Strike started!');

      for (let i = 0; i < copyCount; i++) {
        const shadow = document.createElement('div');
        shadow.style.position = 'absolute';
        shadow.style.width = player.offsetWidth + 'px';
        shadow.style.height = player.offsetHeight + 'px';
        shadow.style.background = 'radial-gradient(rgba(0,0,0,0.9), transparent)';
        shadow.style.borderRadius = '50%';
        shadow.style.left = originalX + 'px';
        shadow.style.bottom = originalY + 'px';
        shadow.style.zIndex = 1200;
        shadow.style.opacity = '0.7';
        gameWorld.appendChild(shadow);
        shadowCopies.push(shadow);
      }

      let counter = 0;
      const intervalId = setInterval(() => {
        if (counter >= copyCount) {
          shadowCopies.forEach(c => c.remove());
          log('Shadow Blink Strike ended!');
          clearInterval(intervalId);
          return;
        }
        const xOffset = (Math.random() - 0.5) * 300;
        const yOffset = (Math.random() - 0.5) * 150;

        playerPositionX = Math.min(Math.max(0, originalX + xOffset), gameWorld.offsetWidth - player.offsetWidth);
        playerPositionY = Math.min(Math.max(0, originalY + yOffset), gameContainer.offsetHeight - player.offsetHeight);
        player.style.left = playerPositionX + 'px';
        player.style.bottom = playerPositionY + 'px';

        // Strike enemies near old position
        enemies.forEach((enemy, idx) => {
          const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
          if (dist < 100) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy struck by shadow blink!');
          }
        });

        // Animate shadow copy
        const shadow = shadowCopies[counter];
        shadow.style.left = player.style.left;
        shadow.style.bottom = player.style.bottom;
        shadow.style.opacity = '1';
        shadow.animate([
          { transform: 'scale(1)', opacity: 1 },
          { transform: 'scale(1.5)', opacity: 0 }
        ], { duration: 700, fill: 'forwards' });

        counter++;
      }, 800);
    }
  },

  // 62. _Glowing Aura_ powerup
  {
    name: 'Glowing Aura',
    description: 'Player is surrounded by a glowing, slowly rotating circle that damages enemies on contact for 8 seconds.',
    func: () => {
      const aura = document.createElement('div');
      aura.style.position = 'absolute';
      aura.style.left = (playerPositionX - 40) + 'px';
      aura.style.bottom = (playerPositionY - 40) + 'px';
      aura.style.width = '110px';
      aura.style.height = '110px';
      aura.style.borderRadius = '50%';
      aura.style.border = '4px solid #0ff';
      aura.style.boxShadow = '0 0 20px #0ff, 0 0 50px #0ff inset';
      aura.style.zIndex = 9000;
      aura.style.pointerEvents = 'none';
      gameWorld.appendChild(aura);

      let angle = 0;

      const interval = setInterval(() => {
        if (!aura.parentElement) {
          clearInterval(interval);
          return;
        }
        angle += 0.04;
        aura.style.transform = `rotate(${angle}rad)`;
        // Keep aura attached to player
        aura.style.left = (playerPositionX - 40) + 'px';
        aura.style.bottom = (playerPositionY - 40) + 'px';

        enemies.forEach((enemy, idx) => {
          if (checkCollision(aura, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy damaged by glowing aura!');
          }
        });
      }, 60);

      setTimeout(() => {
        aura.remove();
        clearInterval(interval);
        log('Glowing Aura ended!');
      }, 8000);
    }
  },

  // 63. Secret Enraged Minion
  {
    name: 'Spawn Enraged Minion',
    description: 'Secret enemy: A fast red minion that homes on player relentlessly.',
    func: () => {
      // Add CSS dynamically for red minion
      if (!document.getElementById('red-minion-style')) {
        const style = document.createElement('style');
        style.id = 'red-minion-style';
        style.textContent = `
          .red-minion {
            width: 30px;
            height: 30px;
            background-color: #C00;
            border-radius: 50%;
            box-shadow: 0 0 8px red;
            position: absolute;
            pointer-events: all;
            z-index: 15;
          }
        `;
        document.head.appendChild(style);
      }

      const minion = document.createElement('div');
      minion.classList.add('red-minion');
      minion.style.left = (gameScrollPosition + gameContainer.offsetWidth + 100) + 'px';
      minion.style.bottom = (50 + Math.random() * 200) + 'px';
      gameWorld.appendChild(minion);
      enemies.push(minion);

      let speed = 6;

      const moveInterval = setInterval(() => {
        if (!minion.parentElement) {
          clearInterval(moveInterval);
          return;
        }
        const x = parseFloat(minion.style.left);
        const y = parseFloat(minion.style.bottom);

        let dx = playerPositionX - x;
        let dy = playerPositionY - y;
        const dist = Math.sqrt(dx * dx + dy * dy);

        if (dist < 10) {
          reduceLives();
          createBurst(x, y);
          minion.remove();
          enemies.splice(enemies.indexOf(minion), 1);
          clearInterval(moveInterval);
          log('Enraged Minion attacked!');
          return;
        }

        // Normalize speed vector
        const stepX = (dx / dist) * speed;
        const stepY = (dy / dist) * speed;

        minion.style.left = (x + stepX) + 'px';
        minion.style.bottom = (y + stepY) + 'px';

        // Remove if offscreen left
        if (x < gameScrollPosition - 30) {
          minion.remove();
          enemies.splice(enemies.indexOf(minion), 1);
          clearInterval(moveInterval);
          log('Enraged Minion vanished (offscreen)');
        }
      }, 40);

      log('Enraged Minion Spawned!');
    }
  },

  // 64. Boss Ultimate Flame Barrage
  {
    name: 'Boss Ultimate Flame Barrage',
    description: 'Boss shoots 20 fast flame balls in random directions in an epic barrage.',
    func: async () => {
      if (!boss) {
        log('No boss active!');
        return;
      }
      displayMessage('Boss unleashes Ultimate Flame Barrage!', 3);
      await sleep(3000);
      const bossX = parseInt(boss.style.left) + boss.offsetWidth / 2;
      const bossY = parseInt(boss.style.bottom) + boss.offsetHeight / 2;

      let shotsFired = 0;
      const maxShots = 20;

      const shootFlame = () => {
        if (shotsFired >= maxShots) {
          return;
        }
        const flame = document.createElement('div');
        flame.style.position = 'absolute';
        flame.style.width = '14px';
        flame.style.height = '14px';
        flame.style.borderRadius = '50%';
        flame.style.backgroundColor = 'orangered';
        flame.style.left = bossX + 'px';
        flame.style.bottom = bossY + 'px';
        flame.style.boxShadow = '0 0 15px 8px orange';
        gameWorld.appendChild(flame);

        let angle = Math.random() * 2 * Math.PI;
        let speed = 10 + Math.random() * 5;
        let x = bossX;
        let y = bossY;

        const move = () => {
          if (!flame.parentElement) {
            return;
          }
          x += Math.cos(angle) * speed;
          y += Math.sin(angle) * speed;
          flame.style.left = x + 'px';
          flame.style.bottom = y + 'px';

          // Check colliding with player
          if (checkCollision(flame, player)) {
            reduceLives();
            flame.remove();
            return;
          }

          // Remove if off screen
          if (x < 0 || x > gameWorld.offsetWidth || y < 0 || y > gameContainer.offsetHeight) {
            flame.remove();
            return;
          }

          requestAnimationFrame(move);
        };
        move();
        shotsFired++;
      };

      const intervalId = setInterval(() => {
        if (shotsFired >= maxShots) {
          clearInterval(intervalId);
          log('Boss Ultimate Flame Barrage ended!');
          return;
        }
        shootFlame();
      }, 220);
    }
  },

  // 65. Secret Power-Up: Ghost Cloak
  {
    name: 'Ghost Cloak',
    description: `Player becomes ghostly semi-transparent and can pass through enemies for 10 seconds.`,
    func: () => {
      player.style.opacity = '0.3';
      player.style.border = '2px solid cyan';
      player.style.filter = 'blur(2px) drop-shadow(0 0 5px cyan)';
      isInvincible = true;
      log('Ghost Cloak activated! Passing through enemies!');
      let startTime = Date.now();

      // Modify enemy collision check temporarily:
      const originalHandleCollision = handlePlayerEnemyCollision;
      window.handlePlayerEnemyCollision = () => {
        // Ignore enemy collisions while ghost cloak active
      };

      setTimeout(() => {
        player.style.opacity = '1';
        player.style.border = '';
        player.style.filter = '';
        isInvincible = false;
        if (originalHandleCollision) {
          window.handlePlayerEnemyCollision = originalHandleCollision;
        }
        log('Ghost Cloak ended!');
      }, 10000);
    }
  },

  // 66. Power Surge - Speed and Damage Multiplier with Cool Effects
  {
    name: 'Supercharged Power Surge',
    description: `Massively increase player speed + damage for 12 seconds with cinematic glow and pulse effects.`,
    func: async () => {
      playerMaxSpeed *= 3;
      if (!window.addScoreBackup) {
        window.addScoreBackup = window.addScore || ((amount) => { score += amount; updateDisplay(); });
      }
      window.addScore = ((oldFunc) => (amount) => oldFunc(amount * 3))(window.addScore);

      // Add glowing pulse around player
      const pulse = document.createElement('div');
      pulse.style.position = 'absolute';
      pulse.style.left = (playerPositionX - 30) + 'px';
      pulse.style.bottom = (playerPositionY - 30) + 'px';
      pulse.style.width = '90px';
      pulse.style.height = '90px';
      pulse.style.borderRadius = '50%';
      pulse.style.border = '5px solid gold';
      pulse.style.boxShadow = '0 0 25px 10px gold, inset 0 0 30px 10px gold';
      pulse.style.zIndex = 9001;
      gameWorld.appendChild(pulse);

      pulse.animate([
        { opacity: 1, transform: 'scale(1)' },
        { opacity: 0.3, transform: 'scale(1.3)' },
        { opacity: 1, transform: 'scale(1)' }
      ], { duration: 2000, iterations: Infinity });

      log('Supercharged Power Surge activated!');

      await sleep(12000);

      playerMaxSpeed /= 3;
      window.addScore = window.addScoreBackup;
      delete window.addScoreBackup;

      pulse.remove();

      log('Supercharged Power Surge ended!');
    }
  },

  // 67. Secret Enemy: Teleporting Mine
  {
    name: 'Teleporting Mine',
    description: 'Spawn a mine that teleports around randomly and explodes when close to player.',
    func: () => {
      // CSS for mine
      if (!document.getElementById('teleport-mine-style')) {
        const s = document.createElement('style');
        s.id = 'teleport-mine-style';
        s.textContent = `
          .teleport-mine {
            width: 28px;
            height: 28px;
            background-color: darkred;
            border-radius: 50%;
            position: absolute;
            box-shadow: 0 0 15px red;
            cursor: pointer;
            z-index: 20;
          }
          .teleport-mine-explode {
            animation: explodeFlash 0.5s ease-out forwards;
          }
          @keyframes explodeFlash {
            0% { box-shadow: 0 0 15px red; }
            50% { box-shadow: 0 0 50px red; }
            100% { box-shadow: 0 0 0 red; opacity: 0; }
          }
        `;
        document.head.appendChild(s);
      }

      const mine = document.createElement('div');
      mine.classList.add('teleport-mine');
      mine.style.left = (gameScrollPosition + gameContainer.offsetWidth + 70) + 'px';
      mine.style.bottom = (30 + Math.random() * 180) + 'px';
      gameWorld.appendChild(mine);
      enemies.push(mine);

      // Teleport position choices (random near player)
      const teleportPositions = [
        () => [playerPositionX + (Math.random() * 200 - 100), playerPositionY + (Math.random() * 100 - 50)],
        () => [playerPositionX + 150, playerPositionY],
        () => [playerPositionX - 150, playerPositionY + 30],
        () => [gameScrollPosition + gameContainer.offsetWidth + 50, 40],
      ];

      const teleportInterval = setInterval(() => {
        if (!mine.parentElement) {
          clearInterval(teleportInterval);
          return;
        }
        // Check distance to player, detonate if close
        const mineX = parseFloat(mine.style.left);
        const mineY = parseFloat(mine.style.bottom);
        const dist = Math.hypot(mineX - playerPositionX, mineY - playerPositionY);
        if (dist < 40) {
          // Explode
          mine.classList.add('teleport-mine-explode');
          reduceLives();
          setTimeout(() => {
            mine.remove();
            const idx = enemies.indexOf(mine);
            if (idx > -1) enemies.splice(idx, 1);
          }, 550);
          clearInterval(teleportInterval);
          log('Teleporting Mine exploded!');
          return;
        }

        // Teleport randomly around player
        const [newX, newY] = teleportPositions[Math.floor(Math.random() * teleportPositions.length)]();
        mine.style.left = Math.min(Math.max(gameScrollPosition, Math.min(newX, gameWorld.offsetWidth - mine.offsetWidth))) + 'px';
        mine.style.bottom = Math.min(Math.max(0, newY), gameContainer.offsetHeight - mine.offsetHeight) + 'px';
      }, 1000);

      log('Teleporting Mine spawned!');
    }
  },

  // 68. Boss Power - Energy Orbitals
  {
    name: 'Boss Energy Orbitals',
    description: 'Boss summons 5 fast energy orbs whirling and damaging player on touch.',
    func: () => {
      if (!boss) {
        log('No boss active!');
        return;
      }
      const orbs = [];
      const orbCount = 5;
      const radius = 90;
      const centerX = parseInt(boss.style.left) + boss.offsetWidth / 2;
      const centerY = parseInt(boss.style.bottom) + boss.offsetHeight / 2;

      for (let i = 0; i < orbCount; i++) {
        const orb = document.createElement('div');
        orb.style.position = 'absolute';
        orb.style.width = '20px';
        orb.style.height = '20px';
        orb.style.borderRadius = '50%';
        orb.style.backgroundColor = 'cyan';
        orb.style.boxShadow = '0 0 15px #0ff';
        orb.style.left = (centerX + radius * Math.cos((i * 2 * Math.PI) / orbCount)) + 'px';
        orb.style.bottom = (centerY + radius * Math.sin((i * 2 * Math.PI) / orbCount)) + 'px';
        gameWorld.appendChild(orb);
        orbs.push({ el: orb, angle: (i * 2 * Math.PI) / orbCount });
      }

      let angle = 0;
      const speed = 0.1;
      const interval = setInterval(() => {
        if (orbs.length === 0) {
          clearInterval(interval);
          log('Boss Energy Orbitals ended!');
          return;
        }
        angle += speed;

        orbs.forEach(({ el, angle: baseAngle }, idx) => {
          const currentAngle = baseAngle + angle;
          const x = centerX + radius * Math.cos(currentAngle);
          const y = centerY + radius * Math.sin(currentAngle);
          el.style.left = x + 'px';
          el.style.bottom = y + 'px';

          if (checkCollision(el, player)) {
            reduceLives();
            createBurst(parseInt(player.style.left), parseInt(player.style.bottom));
          }
        });
      }, 40);

      setTimeout(() => {
        orbs.forEach(o => o.el.remove());
        orbs.length = 0;
        clearInterval(interval);
      }, 10000);
    }
  },

  // 69. Cooldown Reduction Powerup
  {
    name: 'Cooldown Reduction',
    description: 'Reduce all ability cooldowns by 50% for 10 seconds, with a shiny timer overlay.',
    func: () => {
      const overlay = document.createElement('div');
      overlay.textContent = 'Cooldowns Halved!';
      Object.assign(overlay.style, {
        position: 'absolute',
        top: '10px',
        left: '50%',
        transform: 'translateX(-50%)',
        padding: '8px 16px',
        backgroundColor: 'rgba(255,255,0,0.85)',
        color: '#000',
        fontWeight: 'bold',
        borderRadius: '12px',
        zIndex: '9999',
        pointerEvents: 'none',
        fontSize: '18px',
      });
      gameWorld.appendChild(overlay);

      // Hypothetical global cooldown variable you maintain elsewhere
      if (typeof globalCooldown !== 'undefined' && globalCooldown) {
        globalCooldown = globalCooldown / 2;
      }

      log('Cooldown Reduction activated!');

      setTimeout(() => {
        if (globalCooldown) {
          globalCooldown = globalCooldown * 2; // Restore
        }
        overlay.remove();
        log('Cooldown Reduction ended!');
      }, 10000);
    }
  },

  // 70. Secret Move - Telepathy Confusion
  {
    name: 'Telepathy Confusion',
    description: 'Confuse all enemies making them attack each other for 8 seconds.',
    func: () => {
      if (enemies.length === 0) { log('No enemies to confuse!'); return; }
      enemies.forEach(enemy => {
        enemy.classList.add('confused-enemy');
        enemy.style.backgroundColor = '#ff00ffaa';

        // Move randomly across screen bumping into others
        enemy.confusionInterval = setInterval(() => {
          if (!enemy.parentElement) {
            clearInterval(enemy.confusionInterval);
            return;
          }
          let newX = parseInt(enemy.style.left) + Math.random() * 20 - 10;
          let newY = parseInt(enemy.style.bottom) + Math.random() * 20 - 10;
          newX = Math.max(0, Math.min(gameWorld.offsetWidth - enemy.offsetWidth, newX));
          newY = Math.max(0, Math.min(gameContainer.offsetHeight - enemy.offsetHeight, newY));
          enemy.style.left = newX + 'px';
          enemy.style.bottom = newY + 'px';

          // If colliding with another confused enemy, both take damage (for fun)
          enemies.forEach(other => {
            if (other !== enemy && other.classList.contains('confused-enemy')) {
              if (checkCollision(enemy, other)) {
                createBurst(parseInt(other.style.left), parseInt(other.style.bottom));
                other.remove();
                enemies.splice(enemies.indexOf(other), 1);
                log('Confused enemy hit another!');
              }
            }
          });
        }, 150);
      });

      setTimeout(() => {
        enemies.forEach(enemy => {
          if (enemy.confusionInterval) clearInterval(enemy.confusionInterval);
          enemy.classList.remove('confused-enemy');
          enemy.style.backgroundColor = '';
        });
        log('Telepathy Confusion ended!');
      }, 8000);
      log('Telepathy Confusion started!');
    }
  },

  // 71. Lightning Ground Spike
  {
    name: 'Lightning Ground Spike',
    description: 'Summon a huge lightning spike that strikes the ground and electrocutes enemies for 7 seconds.',
    func: () => {
      const spike = document.createElement('div');
      spike.style.position = 'absolute';
      spike.style.left = (playerPositionX + player.offsetWidth/2 - 20) + 'px';
      spike.style.bottom = '0px';
      spike.style.width = '40px';
      spike.style.height = '100px';
      spike.style.backgroundColor = 'cyan';
      spike.style.boxShadow = '0 0 20px 10px cyan';
      spike.style.borderRadius = '10px';
      gameWorld.appendChild(spike);

      let tickCount = 0;

      const interval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          if (checkCollision(spike, enemy)) {
            enemy.remove();
            enemies.splice(idx, 1);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            log('Enemy electrocuted by lightning spike!');
          }
        });
        tickCount++;
        if (tickCount > 7) {
          clearInterval(interval);
          spike.remove();
          log('Lightning Ground Spike ended!');
        }
      }, 1000);

      log('Lightning Ground Spike deployed!');
    }
  },

  // 72. Cosmic Starfall
  {
    name: 'Cosmic Starfall',
    description: 'Summon stars falling from the sky damaging everything on impact for 10 seconds.',
    func: async () => {
      log('Cosmic Starfall starting!');
      displayMessage('Cosmic stars are falling!', 3);
      await sleep(3000);

      const count = 40;
      for (let i = 0; i < count; i++) {
        const star = document.createElement('div');
        star.style.position = 'absolute';
        star.style.width = '20px';
        star.style.height = '20px';
        star.style.background = 'radial-gradient(circle, white, yellow)';
        star.style.borderRadius = '50%';
        star.style.left = (gameScrollPosition + Math.random() * gameContainer.offsetWidth) + 'px';
        star.style.bottom = (gameContainer.offsetHeight + 50) + 'px';
        star.style.boxShadow = '0 0 30px 10px white';
        gameWorld.appendChild(star);

        let speed = 15 + Math.random() * 6;
        let interval = setInterval(() => {
          if (!star.parentElement) {
            clearInterval(interval);
            return;
          }
          let bottom = parseInt(star.style.bottom);
          bottom -= speed;
          star.style.bottom = bottom + 'px';

          if (bottom <= 0) {
            createBurst(parseInt(star.style.left), 0);
            enemies = enemies.filter(enemy => {
              if (checkCollision(star, enemy)) {
                enemy.remove();
                log('Enemy smashed by Starfall!');
                return false;
              }
              return true;
            });
            obstacles = obstacles.filter(ob => {
              if (checkCollision(star, ob)) {
                ob.remove();
                log('Obstacle smashed by Starfall!');
                return false;
              }
              return true;
            });

            star.remove();
            clearInterval(interval);
          }
        }, 40);
        await sleep(180);
      }

      log('Cosmic Starfall ended!');
    }
  },

  // 73. Burning Spiral Barrage
  {
    name: 'Burning Spiral Barrage',
    description: 'Player spins and launches burning projectiles in a spiral for 8 seconds.',
    func: () => {
      const duration = 8000;
      const intervalMs = 150;
      let angle = 0;

      const interval = setInterval(() => {
        const bullet = document.createElement('div');
        bullet.style.position = 'absolute';
        bullet.style.width = '10px';
        bullet.style.height = '10px';
        bullet.style.borderRadius = '50%';
        bullet.style.backgroundColor = 'orange';
        bullet.style.boxShadow = '0 0 20px 8px orange';
        bullet.style.left = (playerPositionX + player.offsetWidth / 2) + 'px';
        bullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
        gameWorld.appendChild(bullet);

        let x = playerPositionX + player.offsetWidth / 2;
        let y = playerPositionY + player.offsetHeight / 2;
        const speed = 9;

        let currentAngle = angle;
        angle += Math.PI / 8;

        const move = () => {
          if (!bullet.parentElement) return;

          x += Math.cos(currentAngle) * speed;
          y += Math.sin(currentAngle) * speed;
          bullet.style.left = x + 'px';
          bullet.style.bottom = y + 'px';

          // Damage enemies
          enemies.forEach((enemy, idx) => {
            if (checkCollision(bullet, enemy)) {
              applyBurn(enemy);
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              bullet.remove();
              return;
            }
          });

          if (x < 0 || x > gameWorld.offsetWidth || y < 0 || y > gameContainer.offsetHeight) {
            bullet.remove();
            return;
          }
          requestAnimationFrame(move);
        };
        move();
      }, intervalMs);

      setTimeout(() => {
        clearInterval(interval);
        log('Burning Spiral Barrage ended!');
      }, duration);

      log('Burning Spiral Barrage started!');
    }
  },

  // 74. Invulnerability Flash
  {
    name: 'Invulnerability Flash',
    description: 'Player becomes invulnerable and flashes bright white for 6 seconds.',
    func: () => {
      isInvincible = true;
      player.style.transition = 'filter 0.3s';
      player.style.filter = 'brightness(1.5) drop-shadow(0 0 15px white)';

      log('Invulnerability Flash activated!');

      setTimeout(() => {
        isInvincible = false;
        player.style.filter = '';
        log('Invulnerability Flash ended!');
      }, 6000);
    }
  },

  // 75. Aurora Shield
  {
    name: 'Aurora Shield',
    description: 'Surround the player with a colorful rotating shield that reflects bullets for 10 seconds.',
    func: () => {
      const shield = document.createElement('div');
      Object.assign(shield.style, {
        position: 'absolute',
        width: '120px',
        height: '120px',
        borderRadius: '50%',
        border: '4px solid transparent',
        left: (playerPositionX - 35) + 'px',
        bottom: (playerPositionY - 35) + 'px',
        zIndex: 9999,
        pointerEvents: 'none',
        background:
          'conic-gradient(from 0deg at 50% 50%, red, orange, yellow, green, blue, indigo, violet, red)',
        opacity: 0.75,
      });
      gameWorld.appendChild(shield);

      let angle = 0;
      isInvincible = true;

      const interval = setInterval(() => {
        angle += 2;
        if (!shield.parentElement) {
          clearInterval(interval);
          return;
        }
        shield.style.transform = `rotate(${angle}deg)`;
      }, 30);

      // Bullet reflection within 100px of shield center
      const reflectInterval = setInterval(() => {
        bullets.forEach((bullet, idx) => {
          const el = bullet.element;
          const bX = parseInt(el.style.left) + el.offsetWidth / 2;
          const bY = parseInt(el.style.bottom) + el.offsetHeight / 2;
          const cX = playerPositionX + player.offsetWidth / 2;
          const cY = playerPositionY + player.offsetHeight / 2;
          const dist = Math.hypot(bX - cX, bY - cY);

          if (dist < 60) {
            bullet.direction *= -1;
            el.style.backgroundColor = 'cyan';
            log('Bullet reflected by Aurora Shield!');
          }
        });
      }, 40);

      setTimeout(() => {
        isInvincible = false;
        shield.remove();
        clearInterval(interval);
        clearInterval(reflectInterval);
        log('Aurora Shield ended!');
      }, 10000);
    }
  },

  // 76. Lava Burst
  {
    name: 'Lava Burst',
    description: 'Erupt a circle of lava under the player damaging all enemies on ground for 5 seconds.',
    func: () => {
      const radius = 180;
      const lava = document.createElement('div');
      Object.assign(lava.style, {
        position: 'absolute',
        left: (playerPositionX + player.offsetWidth / 2 - radius) + 'px',
        bottom: (playerPositionY - radius) + 'px',
        width: radius * 2 + 'px',
        height: radius * 2 + 'px',
        borderRadius: '50%',
        background: 'radial-gradient(circle, orange, darkred)',
        zIndex: 9000,
        opacity: 0.75,
      });
      gameWorld.appendChild(lava);

      const interval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          const ex = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
          const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;
          const px = playerPositionX + player.offsetWidth / 2;
          const py = playerPositionY + player.offsetHeight / 2;
          const dist = Math.hypot(ex - px, ey - py);
          if (dist < radius) {
            enemy.remove();
            enemies.splice(idx, 1);
            createBurst(ex, ey);
            log('Enemy incinerated by Lava Burst!');
          }
        });
      }, 1000);

      setTimeout(() => {
        clearInterval(interval);
        lava.remove();
        log('Lava Burst ended!');
      }, 5000);
    }
  },

  // 77. Holographic Decoy
  {
    name: 'Holographic Decoy',
    description: 'Spawn a hologram copy of player that draws enemy fire for 8 seconds.',
    func: () => {
      const decoy = document.createElement('div');
      decoy.style.position = 'absolute';
      decoy.style.width = player.offsetWidth + 'px';
      decoy.style.height = player.offsetHeight + 'px';
      decoy.style.left = playerPositionX + 100 + 'px';
      decoy.style.bottom = playerPositionY + 'px';
      decoy.style.borderRadius = '50%';
      decoy.style.backgroundColor = 'rgba(0,0,255,0.5)';
      decoy.style.border = '2px dotted blue';
      decoy.style.zIndex = 9500;
      gameWorld.appendChild(decoy);

      let dir = 1;
      let speed = 4;

      const moveInterval = setInterval(() => {
        if (!decoy.parentElement) {
          clearInterval(moveInterval);
          return;
        }
        let newLeft = parseInt(decoy.style.left) + speed * dir;
        if (newLeft < playerPositionX + 50 || newLeft > playerPositionX + 150) dir *= -1;
        else decoy.style.left = newLeft + 'px';

        // Absorb enemy hits
        enemies.forEach((enemy, idx) => {
          if (checkCollision(enemy, decoy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy hit by decoy!');
          }
        });
      }, 50);

      setTimeout(() => {
        clearInterval(moveInterval);
        decoy.remove();
        log('Holographic Decoy disappeared!');
      }, 8000);

      log('Holographic Decoy created!');
    }
  },
  {
    name: "Cosmic Blast",
    description: "Create a huge expanding cosmic explosion that disintegrates all enemies around you.",
    func: () => {
      const radius = 300;
      const centerX = playerPositionX + player.offsetWidth / 2;
      const centerY = playerPositionY + player.offsetHeight / 2;

      const blast = document.createElement('div');
      Object.assign(blast.style, {
        position: 'absolute',
        left: (centerX - 50) + 'px',
        bottom: (centerY - 50) + 'px',
        width: '100px',
        height: '100px',
        borderRadius: '50%',
        background: 'radial-gradient(circle at center, #fff 0%, transparent 70%)',
        boxShadow: '0 0 40px 30px white',
        opacity: '0.7',
        pointerEvents: 'none',
        zIndex: 11000,
        transform: 'scale(0)',
        transition: 'transform 0.7s ease-out, opacity 0.7s ease-out'
      });
      gameWorld.appendChild(blast);

      // Trigger scale expanding + fading
      setTimeout(() => {
        blast.style.transform = 'scale(6)';
        blast.style.opacity = '0';
      }, 50);

      // Damage enemies in radius instantly
      enemies.forEach((enemy, idx) => {
        let ex = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
        let ey = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;
        if (Math.hypot(ex - centerX, ey - centerY) <= radius) {
          createBurst(ex, ey);
          enemy.remove();
          enemies.splice(idx, 1);
          log("Enemy disintegrated by Cosmic Blast!");
        }
      });

      setTimeout(() => {
        blast.remove();
        log("Cosmic Blast ended!");
      }, 750);

      log("Cosmic Blast activated!");
    }
  },

  /** 102. Gravity Slam */
  {
    name: "Gravity Slam",
    description: "Player slams the ground causing a gravity wave that pulls enemies and obstacles toward you.",
    func: () => {
      const waveRadius = 220;
      const centerX = playerPositionX + player.offsetWidth / 2;
      const centerY = 0;

      const wave = document.createElement('div');
      Object.assign(wave.style, {
        position: 'absolute',
        left: (centerX - waveRadius) + 'px',
        bottom: '0px',
        width: (waveRadius * 2) + 'px',
        height: (waveRadius * 2) + 'px',
        borderRadius: '50%',
        border: '3px solid aqua',
        boxShadow: '0 0 35px aqua, inset 0 0 60px cyan',
        opacity: '0.85',
        pointerEvents: 'none',
        zIndex: 10000,
        animation: 'gravityPull 3s ease-out forwards'
      });
      gameWorld.appendChild(wave);

      if (!document.getElementById('gravityPullKeyframes')) {
        const style = document.createElement('style');
        style.id = 'gravityPullKeyframes';
        style.textContent = `
          @keyframes gravityPull {
            0% { transform: scale(0.3); opacity: 1; }
            100% { transform: scale(1); opacity: 0; }
          }
        `;
        document.head.appendChild(style);
      }

      const interval = setInterval(() => {
        [...enemies, ...obstacles].forEach(obj => {
          const ox = parseFloat(obj.style.left) + obj.offsetWidth / 2;
          const oy = parseFloat(obj.style.bottom) + obj.offsetHeight / 2;
          const dx = centerX - ox;
          const dy = centerY - oy;
          const dist = Math.hypot(dx, dy);
          if (dist < waveRadius && dist > 1) {
            obj.style.left = (parseFloat(obj.style.left) + dx * 0.1) + 'px';
            obj.style.bottom = (parseFloat(obj.style.bottom) + dy * 0.1) + 'px';
          }
        });
      }, 50);

      setTimeout(() => {
        clearInterval(interval);
        wave.remove();
        log("Gravity Slam ended!");
      }, 3000);

      log("Gravity Slam activated!");
    }
  },

  /** 103. Ultimate Flame Vortex */
  {
    name: "Ultimate Flame Vortex",
    description: "Player emits a spinning fiery vortex which continuously burns nearby enemies.",
    func: () => {
      const vortex = document.createElement('div');
      Object.assign(vortex.style, {
        position: 'absolute',
        left: (playerPositionX + player.offsetWidth/2 - 60) + 'px',
        bottom: (playerPositionY + player.offsetHeight/2 - 60) + 'px',
        width: '120px',
        height: '120px',
        borderRadius: '50%',
        border: '4px solid orangered',
        boxShadow: '0 0 40px 25px orange, inset 0 0 60px 35px red',
        opacity: '0.75',
        pointerEvents: 'none',
        zIndex: 9000,
        animation: 'vortexSpin 1s linear infinite'
      });
      gameWorld.appendChild(vortex);

      if (!document.getElementById('vortexSpinKeyframes')) {
        const style = document.createElement('style');
        style.id = 'vortexSpinKeyframes';
        style.textContent = `
          @keyframes vortexSpin {
            from {transform: rotate(0deg);}
            to {transform: rotate(360deg);}
          }
        `;
        document.head.appendChild(style);
      }

      const duration = 8000;
      const damageInterval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          const enemyCenterX = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
          const enemyCenterY = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;
          const vortexCenterX = playerPositionX + player.offsetWidth / 2;
          const vortexCenterY = playerPositionY + player.offsetHeight / 2;

          const dist = Math.hypot(enemyCenterX - vortexCenterX, enemyCenterY - vortexCenterY);
          if (dist < 90) {
            applyBurn(enemy);
            log("Enemy burned by Flame Vortex!");
          }
        });
      }, 200);

      setTimeout(() => {
        clearInterval(damageInterval);
        vortex.remove();
        log("Ultimate Flame Vortex ended!");
      }, duration);

      log("Ultimate Flame Vortex activated!");
    }
  },

  /** 104. Boss Roar - Stun Wave */
  {
    name: "Boss Roar - Stun Wave",
    description: "Boss emits a powerful roar stunning the player and enemies near for 4 seconds.",
    func: async () => {
      displayMessage("Boss is roaring! Brace yourself!", 2);
      await sleep(2000);

      // Flash screen red
      const screenFlash = document.createElement('div');
      Object.assign(screenFlash.style, {
        position: 'fixed',
        width: '100vw',
        height: '100vh',
        top: '0',
        left: '0',
        backgroundColor: 'rgba(255,0,0,0.7)',
        zIndex: 20000,
        pointerEvents: 'none',
        opacity: '0',
        transition: 'opacity 0.1s ease-in-out',
      });
      document.body.appendChild(screenFlash);

      // Animate flash
      let fadeIn = true;
      const fadeCount = 6;
      let count = 0;

      const fadeInterval = setInterval(() => {
        screenFlash.style.opacity = fadeIn ? '0.7' : '0';
        fadeIn = !fadeIn;
        count++;
        if(count >= fadeCount) {
          clearInterval(fadeInterval);
          screenFlash.remove();
        }
      }, 200);

      // Stun player & enemies within 220px
      const stunDuration = 4000;
      let stunned = [];

      function stunEntity(el) {
        if(stunned.includes(el)) return;
        stunned.push(el);
        el.style.filter = 'grayscale(1) brightness(0.6)';
        el.style.pointerEvents = 'none';
      }

      stunEntity(player);
      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if(dist < 220) {
          stunEntity(enemy);
        }
      });

      await sleep(stunDuration);

      // Remove stun effects
      stunned.forEach(el => {
        el.style.filter = '';
        el.style.pointerEvents = '';
      });

      log("Boss Roar stun ended!");
    }
  },

  /** 105. Secret: Time Splitter Enemy */
  {
    name: "Spawn Time Splitter Enemy",
    description: "Secret enemy: teleports randomly and delays its movement causing time glitches.",
    func: () => {
      // Add CSS only once
      if(!document.getElementById('time-splitter-style')) {
        const style = document.createElement('style');
        style.id = 'time-splitter-style';
        style.textContent = `
          .time-splitter {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: linear-gradient(45deg, #8800ff, #440077);
            box-shadow: 0 0 10px purple, inset 0 0 5px indigo;
            position: absolute;
            cursor: pointer;
            z-index: 20;
          }
          .time-splitter.glitch {
            animation: glitchEffect 0.4s infinite;
          }
          @keyframes glitchEffect {
            0%, 100% { filter: drop-shadow(0 0 5px violet); }
            50% { filter: drop-shadow(10px 0 10px violet); }
          }
        `;
        document.head.appendChild(style);
      }

      const enemy = document.createElement('div');
      enemy.classList.add('time-splitter');
      enemy.style.left = (gameScrollPosition + gameContainer.offsetWidth + 60) + 'px';
      enemy.style.bottom = (100 + Math.random() * 200) + 'px';
      gameWorld.appendChild(enemy);
      enemies.push(enemy);

      let glitchState = false;
      let teleportCooldown = 0;

      const interval = setInterval(() => {
        if(!enemy.parentElement) {
          clearInterval(interval);
          return;
        }

        const currentX = parseFloat(enemy.style.left);
        if(teleportCooldown <= 0) {
          // Teleport randomly in a radius
          const offsetX = (Math.random() - 0.5) * 400;
          const offsetY = (Math.random() - 0.5) * 200;
          enemy.style.left = Math.min(Math.max(0, currentX + offsetX), gameWorld.offsetWidth - enemy.offsetWidth) + 'px';
          enemy.style.bottom = Math.min(gameContainer.offsetHeight - enemy.offsetHeight, Math.max(0, parseFloat(enemy.style.bottom) + offsetY)) + 'px';

          teleportCooldown = 120 + Math.random() * 100;
          glitchState = !glitchState;
          if(glitchState) enemy.classList.add('glitch'); else enemy.classList.remove('glitch');
        } else {
          // Slowly float left while glitch visible
          enemy.style.left = (currentX - 1) + 'px';
          teleportCooldown--;
        }

        // Destroy if goes off-screen left
        if(currentX < gameScrollPosition - enemy.offsetWidth) {
          enemy.remove();
          enemies.splice(enemies.indexOf(enemy), 1);
          clearInterval(interval);
          log('Time Splitter enemy vanished offscreen.');
        }

        // Collision with player
        if (checkCollision(player, enemy)) {
          reduceLives();
          createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
          enemy.remove();
          enemies.splice(enemies.indexOf(enemy), 1);
          clearInterval(interval);
          log('Time Splitter enemy hurt player!');
        }
      }, 30);

      log('Time Splitter enemy spawned - beware of time glitches!');
    }
  },

  /** 106. Infinite Lightning Chain */
  {
    name: "Infinite Lightning Chain",
    description: "A chain lightning that jumps through enemies infinitely (until no targets).",
    func: () => {
      if(enemies.length === 0) {
        log("No enemies for Infinite Lightning Chain");
        return;
      }

      let hitEnemies = new Set();

      function chain(currentEnemy) {
        if (!currentEnemy || hitEnemies.has(currentEnemy)) return;
        hitEnemies.add(currentEnemy);

        // Visual strike
        const flash = document.createElement('div');
        flash.style.position = 'absolute';
        flash.style.left = currentEnemy.style.left;
        flash.style.bottom = currentEnemy.style.bottom;
        flash.style.width = '35px';
        flash.style.height = '35px';
        flash.style.borderRadius = '50%';
        flash.style.boxShadow = '0 0 40px 20px cyan inset';
        flash.style.pointerEvents = 'none';
        flash.style.zIndex = 11000;
        gameWorld.appendChild(flash);

        setTimeout(() => flash.remove(), 400);

        // Remove enemy
        createBurst(parseInt(currentEnemy.style.left), parseInt(currentEnemy.style.bottom));
        currentEnemy.remove();
        enemies = enemies.filter(e => e !== currentEnemy);

        // Find next closest enemies within 150px
        const nextEnemies = enemies.filter(e => {
          const dx = parseInt(e.style.left) - parseInt(currentEnemy.style.left);
          const dy = parseInt(e.style.bottom) - parseInt(currentEnemy.style.bottom);
          return Math.hypot(dx, dy) <= 150 && !hitEnemies.has(e);
        });

        if(nextEnemies.length > 0) {
          setTimeout(() => {
            chain(nextEnemies[0]);
          }, 300); // Chain delay
        }
      }

      chain(enemies[Math.floor(Math.random() * enemies.length)]);
      log("Infinite Lightning Chain started!");
    }
  },

  /** 107. Rocket Rain */
  {
    name: "Rocket Rain",
    description: "Fire a heavy rain of rocketry missiles that track and destroy enemies rapidly.",
    func: () => {
      let missileCount = 20;

      function fireRocket() {
        if(!missileCount) {
          log("Rocket Rain complete!");
          return;
        }
        missileCount--;

        const missile = document.createElement('div');
        Object.assign(missile.style, {
          position: 'absolute',
          width: '14px',
          height: '6px',
          background: 'red',
          borderRadius: '6px',
          left: (playerPositionX + player.offsetWidth / 2) + 'px',
          bottom: (playerPositionY + player.offsetHeight / 2) + 'px',
          zIndex: 9500
        });
        gameWorld.appendChild(missile);

        let target = enemies.length ? enemies[Math.floor(Math.random() * enemies.length)] : null;
        let x = parseFloat(missile.style.left);
        let y = parseFloat(missile.style.bottom);
        let speed = 10;

        function move() {
          if (!missile.parentElement) return;
          if(!target || !target.parentElement) {
            missile.remove();
            return;
          }
          let tx = parseInt(target.style.left) + target.offsetWidth / 2;
          let ty = parseInt(target.style.bottom) + target.offsetHeight / 2;

          let dx = tx - x;
          let dy = ty - y;
          let dist = Math.hypot(dx, dy);
          let vx = (dx / dist) * speed;
          let vy = (dy / dist) * speed;

          x += vx;
          y += vy;
          missile.style.left = x + 'px';
          missile.style.bottom = y + 'px';

          if(dist < 12) {
            createBurst(tx, ty);
            target.remove();
            enemies = enemies.filter(en => en !== target);
            missile.remove();
            log("Enemy destroyed by rocket!");
            return;
          }

          if(x < 0 || x > gameWorld.offsetWidth || y < 0 || y > gameContainer.offsetHeight) {
            missile.remove();
            return;
          }
          requestAnimationFrame(move);
        }
        move();
      }

      let fireInterval = setInterval(() => {
        if(missileCount <= 0) {
          clearInterval(fireInterval);
          return;
        }
        fireRocket();
      }, 200);

      log("Rocket Rain activated!");
    }
  },

  /** 108. Time Distortion Field */
  {
    name: "Time Distortion Field",
    description: "Create a field slowly freezing all enemies and slowing player movement for 7 seconds.",
    func: () => {
      const fieldRadius = 250;
      const centerX = playerPositionX + player.offsetWidth / 2;
      const centerY = playerPositionY + player.offsetHeight / 2;

      const field = document.createElement('div');
      Object.assign(field.style, {
        position: 'absolute',
        left: (centerX - fieldRadius) + 'px',
        bottom: (centerY - fieldRadius) + 'px',
        width: (fieldRadius * 2) + 'px',
        height: (fieldRadius * 2) + 'px',
        borderRadius: '50%',
        backgroundColor: 'rgba(100,160,255,0.2)',
        border: '3px solid #44aaff',
        boxShadow: '0 0 40px 25px #44aaff inset',
        pointerEvents: 'none',
        opacity: '0.75',
        zIndex: 9000
      });
      gameWorld.appendChild(field);

      let originalSpeed = playerMaxSpeed;
      playerMaxSpeed *= 0.6; // Slow player

      const freezeInterval = setInterval(() => {
        enemies.forEach(enemy => {
          const ex = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
          const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;
          const dist = Math.hypot(ex - centerX, ey - centerY);
          if (dist <= fieldRadius) {
            enemy.classList.add('frozen-enemy');
            enemy.style.opacity = '0.3';
          }
        });
      }, 100);

      setTimeout(() => {
        clearInterval(freezeInterval);
        enemies.forEach(enemy => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        playerMaxSpeed = originalSpeed;

        field.remove();
        log("Time Distortion Field ended!");
      }, 7000);

      log("Time Distortion Field activated!");
    }
  },

  /** 109. Acid Rain */
  {
    name: "Acid Rain",
    description: "Spawn acid drops from the sky that damage and slow enemies on hit for 8 seconds.",
    func: async () => {
      displayMessage("Acid Rain descending!", 3);
      await sleep(3000);

      let drops = [];
      let count = 0;
      const maxDrops = 40;

      function spawnDrop() {
        const drop = document.createElement('div');
        Object.assign(drop.style, {
          position: 'absolute',
          width: '12px',
          height: '20px',
          borderRadius: '50%',
          backgroundColor: 'darkgreen',
          opacity: '0.7',
          left: (gameScrollPosition + Math.random() * gameContainer.offsetWidth) + 'px',
          bottom: (gameContainer.offsetHeight + 20) + 'px',
          pointerEvents: 'none',
          zIndex: 9000
        });
        gameWorld.appendChild(drop);
        drops.push(drop);

        let speed = 10 + Math.random() * 5;
        let interval = setInterval(() => {
          if (!drop.parentElement) {
            clearInterval(interval);
            return;
          }
          drop.style.bottom = (parseFloat(drop.style.bottom) - speed) + 'px';

          // Collision damage
          enemies.forEach(enemy => {
            if (checkCollision(drop, enemy)) {
              applyBurn(enemy);
              enemy.dataset.speed = (parseFloat(enemy.dataset.speed || 1) * 0.5).toString();
              log("Enemy hit by acid drop!");
            }
          });

          if (parseFloat(drop.style.bottom) <= 0) {
            drop.remove();
            clearInterval(interval);
          }
        }, 40);
      }

      const spawnInterval = setInterval(() => {
        if (count >= maxDrops) {
          clearInterval(spawnInterval);
          setTimeout(() => {
            drops.forEach(drop => drop.remove());
            log("Acid Rain ended!");
          }, 3000);
          return;
        }
        spawnDrop();
        count++;
      }, 150);

      log("Acid Rain started!");
    }
  },

  /** 110. Electric Overload Blast */
  {
    name: "Electric Overload Blast",
    description: "Player emits a high-voltage shock around, damaging and paralyzing enemies for 5 seconds.",
    func: () => {
      const overload = document.createElement('div');
      Object.assign(overload.style, {
        position: 'absolute',
        left: (playerPositionX + player.offsetWidth / 2 - 150) + 'px',
        bottom: (playerPositionY + player.offsetHeight / 2 - 150) + 'px',
        width: '300px',
        height: '300px',
        borderRadius: '50%',
        boxShadow: '0 0 60px 30px yellow, inset 0 0 80px 40px #ffd',
        backgroundColor: 'rgba(255,255,150,0.15)',
        pointerEvents: 'none',
        zIndex: 12000,
        animation: 'electricPulse 1.5s ease-in-out infinite alternate'
      });

      gameWorld.appendChild(overload);

      if (!document.getElementById('electricPulseKeyframes')) {
        const style = document.createElement('style');
        style.id = 'electricPulseKeyframes';
        style.textContent = `
          @keyframes electricPulse {
            0% { box-shadow: 0 0 40px 20px yellow, inset 0 0 60px 30px #ffd; }
            100% { box-shadow: 0 0 90px 45px yellow, inset 0 0 120px 60px #ffd; }
          }
        `;
        document.head.appendChild(style);
      }

      const paralysisDuration = 5000;

      const interval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          const ecx = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
          const ecy = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;
          const pcx = playerPositionX + player.offsetWidth / 2;
          const pcy = playerPositionY + player.offsetHeight / 2;
          const dist = Math.hypot(ecx - pcx, ecy - pcy);
          if(dist < 150) {
            enemy.classList.add('frozen-enemy');
            enemy.style.opacity = '0.3';
          }
        });
      }, 100);

      setTimeout(() => {
        clearInterval(interval);
        enemies.forEach(enemy => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        overload.remove();
        log("Electric Overload Blast ended!");
      }, paralysisDuration);

      log("Electric Overload Blast activated!");
    }
  },

  /** 111. Secret Enemy: Crystal Beetle */
  {
    name: "Spawn Crystal Beetle",
    description: "Secret enemy: Slow-moving beetle covered by reflective crystal armor.",
    func: () => {
      if(!document.getElementById('crystalBeetleStyle')) {
        const style = document.createElement('style');
        style.id = 'crystalBeetleStyle';
        style.textContent = `
          .crystal-beetle {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: linear-gradient(135deg, #88eef3, #44aacc);
            box-shadow: 0 0 8px #22ccff;
            border: 3px solid #55eeff;
            position: absolute;
            cursor: pointer;
            z-index: 25;
          }
          .crystal-beetle.shielded {
            border-color: white;
            box-shadow: 0 0 30px 5px white;
          }
        `;
        document.head.appendChild(style);
      }

      const beetle = document.createElement('div');
      beetle.classList.add('crystal-beetle', 'shielded');
      beetle.style.left = (gameScrollPosition + gameContainer.offsetWidth + 60) + 'px';
      beetle.style.bottom = (30 + Math.random() * 50) + 'px';

      beetle.dataset.shieldHits = '4';
      beetle.dataset.speed = '1.5';

      gameWorld.appendChild(beetle);
      enemies.push(beetle);

      // Move left slowly, remove after shield hits depleted
      let moveInterval = setInterval(() => {
        if(!beetle.parentElement) {
          clearInterval(moveInterval);
          return;
        }

        const currentX = parseFloat(beetle.style.left);
        beetle.style.left = (currentX - 1.5) + 'px';

        if(currentX < gameScrollPosition - beetle.offsetWidth) {
          beetle.remove();
          enemies.splice(enemies.indexOf(beetle), 1);
          clearInterval(moveInterval);
          log("Crystal Beetle went idle offscreen.");
          return;
        }

        // Remove shield when hit count reaches zero - listen on bullet collision separately!
        if(beetle.dataset.shieldHits === '0') {
          beetle.classList.remove('shielded');
          beetle.style.border = '3px solid #005566';
          log("Crystal Beetle's crystal armor destroyed!");
        }
      }, 40);

      log("Crystal Beetle spawned, it has a tough crystal shield!");
    }
  },

  /** 112. Power-Up: Nano Repair Bots */
  {
    name: "Nano Repair Bots",
    description: "Summon nano bots that slowly repair player's armor and heal 1 life every 2 seconds for 12 seconds.",
    func: () => {
      const botCount = 4;
      const bots = [];

      for(let i = 0; i < botCount; i++) {
        const bot = document.createElement('div');
        Object.assign(bot.style, {
          position: 'absolute',
          width: '18px',
          height: '18px',
          borderRadius: '50%',
          backgroundColor: 'lightgreen',
          border: '2px solid green',
          opacity: '0.8',
          pointerEvents: 'none',
          zIndex: 12000,
          left: (playerPositionX + (i - (botCount/2)) * 25) + 'px',
          bottom: (playerPositionY + player.offsetHeight / 2) + 'px',
          animation: 'botFloat 2s ease-in-out infinite alternate',
        });
        gameWorld.appendChild(bot);
        bots.push(bot);
      }

      if(!document.getElementById('botFloatAnimation')) {
        const style = document.createElement('style');
        style.id = 'botFloatAnimation';
        style.textContent = `
          @keyframes botFloat {
            from { transform: translateY(0); }
            to { transform: translateY(14px); }
          }
        `;
        document.head.appendChild(style);
      }

      let healsDone = 0;
      const maxHeals = 6;

      const healInterval = setInterval(() => {
        if(healsDone >= maxHeals) {
          clearInterval(healInterval);
          bots.forEach(bot => bot.remove());
          log("Nano Repair Bots finished healing!");
          return;
        }
        if(lives < 7) {
          lives++;
          updateDisplay();
          log("Nano Repair Bots healed 1 life!");
        }
        healsDone++;
      }, 2000);

      log("Nano Repair Bots deployed!");
    }
  },

  /** 113. Power-Up: Shadow Cloak Escape */
  {
    name: "Shadow Cloak Escape",
    description: "Player becomes semi-invisible and cannot be hit for 7 seconds while moving 30% faster.",
    func: () => {
      player.style.opacity = '0.3';
      player.style.border = '2px solid violet';
      const originalSpeed = playerMaxSpeed;
      playerMaxSpeed *= 1.3;

      isInvincible = true;

      log("Shadow Cloak Escape activated!");

      setTimeout(() => {
        player.style.opacity = '1';
        player.style.border = '';
        playerMaxSpeed = originalSpeed;
        isInvincible = false;
        log("Shadow Cloak Escape ended!");
      }, 7000);
    }
  },

  /** 114. Boss Summon: Shadow Minions */
  {
    name: "Boss Summon - Shadow Minions",
    description: "Boss summons 4 shadow minions that follow and attack the player.",
    func: () => {
      if(!boss) {
        log("No active boss to summon minions.");
        return;
      }

      const minions = [];
      for(let i=0; i<4; i++) {
        const minion = document.createElement('div');
        minion.classList.add('enemy');
        minion.style.position = 'absolute';
        minion.style.backgroundColor = 'rgba(20, 20, 20, 0.8)';
        minion.style.left = (parseInt(boss.style.left) + i * 45) + 'px';
        minion.style.bottom = (parseInt(boss.style.bottom) + 10) + 'px';
        minion.style.width = '30px';
        minion.style.height = '30px';
        minion.style.borderRadius = '50%';
        gameWorld.appendChild(minion);
        enemies.push(minion);
        minions.push(minion);
      }

      // Minion follow and attack
      const interval = setInterval(() => {
        minions.forEach((minion, idx) => {
          if(!minion.parentElement) {
            minions.splice(idx, 1);
            if(minions.length === 0) clearInterval(interval);
            return;
          }
          let mx = parseFloat(minion.style.left);
          let my = parseFloat(minion.style.bottom);
          let px = playerPositionX;
          let py = playerPositionY;

          const dx = px - mx;
          const dy = py - my;
          const dist = Math.hypot(dx, dy);

          if(dist > 5) {
            minion.style.left = (mx + (dx / dist) * 3) + 'px';
            minion.style.bottom = (my + (dy / dist) * 3) + 'px';
          }

          if(checkCollision(minion, player)) {
            reduceLives();
            createBurst(mx, my);
            minion.remove();
            enemies.splice(enemies.indexOf(minion), 1);
            minions.splice(idx, 1);
          }
        });
      }, 50);

      log("Boss summoned Shadow Minions!");
    }
  },

  /** 115. Power-Up: Frost Grip */
  {
    name: "Frost Grip",
    description: "Freeze player in place but freeze all enemies for 5 seconds.",
    func: async () => {
      displayMessage("Frost Grip activated! You are frozen but so are enemies!", 1);
      let frozenPosX = playerPositionX;
      let frozenPosY = playerPositionY;
      player.style.opacity = '0.4';
      isFrozenInPlace = true;

      enemies.forEach(enemy => {
        enemy.classList.add('frozen-enemy');
        enemy.style.opacity = '0.2';
      });

      await sleep(5000);

      isFrozenInPlace = false;
      player.style.opacity = '1';
      enemies.forEach(enemy => {
        enemy.classList.remove('frozen-enemy');
        enemy.style.opacity = '1';
      });

      log("Frost Grip ended!");
    }
  },

  /** 116. Secret Power-Up: Mirror Barrier */
  {
    name: "Mirror Barrier",
    description: "Create a temporary barrier that reflects all bullets for 10 seconds.",
    func: () => {
      const barrier = document.createElement('div');
      Object.assign(barrier.style, {
        position: 'absolute',
        width: '140px',
        height: '140px',
        borderRadius: '50%',
        border: '4px double cyan',
        left: (playerPositionX - 60) + 'px',
        bottom: (playerPositionY - 60) + 'px',
        boxShadow: '0 0 35px 15px cyan',
        opacity: '0.6',
        pointerEvents: 'none',
        zIndex: 10000
      });
      gameWorld.appendChild(barrier);

      const reflectInterval = setInterval(() => {
        bullets.forEach(bullet => {
          const bRect = bullet.element.getBoundingClientRect();
          const barrierRect = barrier.getBoundingClientRect();

          if(!(bRect.right < barrierRect.left || bRect.left > barrierRect.right ||
              bRect.bottom < barrierRect.top || bRect.top > barrierRect.bottom)) {
            bullet.direction *= -1;
            bullet.element.style.backgroundColor = 'cyan';
            log("Bullet reflected by Mirror Barrier!");
          }
        });
      }, 40);

      setTimeout(() => {
        clearInterval(reflectInterval);
        barrier.remove();
        log("Mirror Barrier expired!");
      }, 10000);

      log("Mirror Barrier activated!");
    }
  },

  /** 117. Power-Up: Warp Dash */
  {
    name: "Warp Dash",
    description: "Dash forward instantly 400px, passing through all enemies and destroying them.",
    func: () => {
      const distance = 400;
      let startX = playerPositionX;
      const targetX = Math.min(gameWorld.offsetWidth - player.offsetWidth, startX + distance);
      const step = 35;

      const dashInterval = setInterval(() => {
        if (playerPositionX >= targetX) {
          clearInterval(dashInterval);
          log("Warp Dash ended!");
          return;
        }
        playerPositionX += step;
        player.style.left = playerPositionX + 'px';

        enemies.forEach((enemy, idx) => {
          if (checkCollision(player, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log("Enemy destroyed by Warp Dash!");
          }
        });
      }, 50);

      log("Warp Dash started!");
    }
  },

  /** 118. Boss Power: Shadow Tornado */
  {
    name: "Boss Power - Shadow Tornado",
    description: "Boss summons a shadow tornado pulling player and enemies causing continuous damage.",
    func: () => {
      if (!boss) {
        log("No active boss for Shadow Tornado.");
        return;
      }
      const tornado = document.createElement('div');
      Object.assign(tornado.style, {
        position: 'absolute',
        width: '220px',
        height: '220px',
        borderRadius: '50%',
        border: '5px solid rgba(30,30,30,0.7)',
        background: 'radial-gradient(circle at center, rgba(50,50,50,0.7), rgba(10,10,10,0.1))',
        left: (parseInt(boss.style.left) + boss.offsetWidth / 2 - 110) + 'px',
        bottom: (parseInt(boss.style.bottom) + boss.offsetHeight / 2 - 110) + 'px',
        opacity: '0.85',
        pointerEvents: 'none',
        zIndex: 15000,
        animation: 'spinTornado 2s linear infinite',
      });
      gameWorld.appendChild(tornado);

      if(!document.getElementById('spinTornadoKeyframes')) {
        const style = document.createElement('style');
        style.id = 'spinTornadoKeyframes';
        style.textContent = `
          @keyframes spinTornado {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
        `;
        document.head.appendChild(style);
      }

      let duration = 12000; // 12 seconds
      const pullStrength = 0.12;
      const damageInterval = 150;

      const interval = setInterval(() => {
        if(!tornado.parentElement) {
          clearInterval(interval);
          return;
        }

        // Pull enemies & player toward center of tornado
        const centerX = parseInt(tornado.style.left) + 110;
        const centerY = parseInt(tornado.style.bottom) + 110;

        function pullObj(el) {
          const x = parseInt(el.style.left) + (el.offsetWidth / 2);
          const y = parseInt(el.style.bottom) + (el.offsetHeight / 2);
          const dx = centerX - x;
          const dy = centerY - y;
          const dist = Math.hypot(dx, dy);
          if(dist > 1) {
            el.style.left = (parseInt(el.style.left) + dx * pullStrength) + 'px';
            el.style.bottom = (parseInt(el.style.bottom) + dy * pullStrength) + 'px';
          }
        }

        [player, ...enemies].forEach(pullObj);

        // Damage any enemies or player very close
        enemies.forEach((enemy, idx) => {
          const ex = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
          const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;
          if (Math.hypot(ex - centerX, ey - centerY) < 70) {
            createBurst(ex, ey);
            enemy.remove();
            enemies.splice(idx, 1);
            log("Enemy destroyed by Shadow Tornado!");
          }
        });

        // Damage player if close and not invincible
        const playerX = playerPositionX + player.offsetWidth / 2;
        const playerY = playerPositionY + player.offsetHeight / 2;
        if (Math.hypot(playerX - centerX, playerY - centerY) < 70) {
          reduceLives();
          log("Player hit by Shadow Tornado!");
        }

      }, damageInterval);

      setTimeout(() => {
        clearInterval(interval);
        tornado.remove();
        log("Shadow Tornado ended!");
      }, duration);

      log("Boss cast Shadow Tornado!");
    }
  },

  /** 119. Quickstep Frenzy */
  {
    name: "Quickstep Frenzy",
    description: "Player rapidly dashes back and forth for 8 seconds damaging all enemies touched.",
    func: () => {
      player.classList.add('glow');
      let distance = 0;
      let direction = 1;
      const maxDistance = 350;
      const step = 22;

      const interval = setInterval(() => {
        if(distance > maxDistance) {
          distance = 0;
          direction = -direction;
        }
        playerPositionX = Math.min(Math.max(0, playerPositionX + direction * step), gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';

        enemies.forEach((enemy, idx) => {
          if(checkCollision(player, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log("Enemy smashed by Quickstep Frenzy!");
          }
        });

        distance += step;
      }, 100);

      setTimeout(() => {
        clearInterval(interval);
        player.classList.remove('glow');
        log("Quickstep Frenzy ended!");
      }, 8000);

      log("Quickstep Frenzy activated!");
    }
  },

  /** 120. Power-Up: Plasma Shield Explosion */
  {
    name: "Plasma Shield Explosion",
    description: "Create a plasma shield that explodes damaging all enemies within 160px after 7 seconds.",
    func: () => {
      const shield = document.createElement('div');
      Object.assign(shield.style, {
        position: 'absolute',
        width: '140px',
        height: '140px',
        borderRadius: '50%',
        border: '5px solid cyan',
        left: (playerPositionX - 55) + 'px',
        bottom: (playerPositionY - 55) + 'px',
        boxShadow: '0 0 35px 15px cyan inset',
        opacity: '0.75',
        pointerEvents: 'none',
        zIndex: 9000
      });
      gameWorld.appendChild(shield);

      setTimeout(() => {
        createBurst(playerPositionX + player.offsetWidth / 2, playerPositionY + player.offsetHeight / 2);
        enemies.forEach((enemy, idx) => {
          const ex = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
          const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;
          const px = playerPositionX + player.offsetWidth / 2;
          const py = playerPositionY + player.offsetHeight / 2;
          const dist = Math.hypot(ex - px, ey - py);
          if(dist < 160) {
            enemy.remove();
            enemies.splice(idx, 1);
            log("Enemy obliterated by Plasma Shield Explosion!");
          }
        });
        shield.remove();
        log("Plasma Shield Explosion triggered!");
      }, 7000);

      log("Plasma Shield created!");
    }
  },

  {
    name: 'Celestial Comet Strike',
    description: 'Call down a massive comet from the sky that slams forward destroying everything in a 150px line.',
    func: async () => {
      const comet = document.createElement('div');
      comet.style.position = 'absolute';
      comet.style.width = '180px';
      comet.style.height = '60px';
      comet.style.background = 'radial-gradient(circle at center, white, #ff9800)';
      comet.style.borderRadius = '30% / 50%';
      comet.style.boxShadow = '0 0 40px 10px orange, inset 0 0 30px 15px white';
      comet.style.left = (playerPositionX + gameContainer.offsetWidth) + 'px';
      comet.style.bottom = (playerPositionY + 300) + 'px';
      comet.style.transform = 'rotate(-25deg)';
      comet.style.zIndex = '16000';
      gameWorld.appendChild(comet);

      // Animate comet falling and slam forward
      comet.animate([
        { transform: 'rotate(-25deg) translateX(0) translateY(0)', opacity: 1 },
        { transform: 'rotate(-25deg) translateX(-850px) translateY(200px)', opacity: 1 },
      ], { duration: 2800, easing: 'ease-in' });

      // Remove comet after animation and cause impact
      setTimeout(() => {
        createBurst(parseInt(comet.style.left), parseInt(comet.style.bottom));
        // Destroy enemies in approximate line
        enemies = enemies.filter((enemy) => {
          const ex = parseInt(enemy.style.left);
          const ey = parseInt(enemy.style.bottom);
          const px = playerPositionX;
          const py = playerPositionY;
          const distX = ex - px;
          const distY = ey - py;
          if (distY < 250 && distY > 100 && distX < 850 && distX > 0) {
            log('Enemy smashed by Celestial Comet!');
            enemy.remove();
            return false; // remove enemy
          }
          return true;
        });
        comet.remove();
      }, 2800);

      log('Celestial Comet called!');
    }
  },

  {
    name: 'Phantom Flicker',
    description: 'Become untouchable by briefly flickering in and out for 8 seconds.',
    func: () => {
      let flickerCount = 0;
      const maxFlickers = 16;
      const interval = setInterval(() => {
        if (flickerCount >= maxFlickers) {
          player.style.opacity = '1';
          clearInterval(interval);
          log('Phantom Flicker ended!');
          return;
        }
        player.style.opacity = player.style.opacity === '1' ? '0' : '1';
        flickerCount++;
      }, 250);
      log('Phantom Flicker activated!');
    }
  },

  {
    name: 'Nova Burst',
    description: 'Emit an explosive Nova blast that destroys all enemies within 200px radius instantly.',
    func: () => {
      createBurst(playerPositionX, playerPositionY);
      enemies = enemies.filter(enemy => {
        const ex = parseInt(enemy.style.left);
        const ey = parseInt(enemy.style.bottom);
        const dist = Math.hypot(ex - playerPositionX, ey - playerPositionY);
        if (dist < 200) {
          log('Enemy obliterated by Nova Burst!');
          enemy.remove();
          return false;
        }
        return true;
      });

      // Visual flash effect
      const flash = document.createElement('div');
      Object.assign(flash.style, {
        position: 'fixed',
        top: '0', left: '0',
        width: '100vw',
        height: '100vh',
        backgroundColor: 'white',
        opacity: '0.8',
        pointerEvents: 'none',
        zIndex: '20000',
        transition: 'opacity 0.5s ease-out'
      });
      document.body.appendChild(flash);
      setTimeout(() => {
        flash.style.opacity = '0';
        setTimeout(() => flash.remove(), 500);
      }, 100);

      log('Nova Burst unleashed!');
    }
  },

  {
    name: 'Graviton Pull',
    description: 'Activate a strong gravity well that pulls all enemies to player for 7 seconds.',
    func: () => {
      const gravityWell = document.createElement('div');
      gravityWell.style.position = 'absolute';
      gravityWell.style.width = '280px';
      gravityWell.style.height = '280px';
      gravityWell.style.borderRadius = '50%';
      gravityWell.style.border = '5px solid #fff';
      gravityWell.style.boxShadow = '0 0 40px 25px aqua';
      gravityWell.style.left = (playerPositionX - 100) + 'px';
      gravityWell.style.bottom = (playerPositionY - 100) + 'px';
      gravityWell.style.zIndex = '10500';
      gameWorld.appendChild(gravityWell);

      const pullInterval = setInterval(() => {
        enemies.forEach(enemy => {
          const ex = parseInt(enemy.style.left);
          const ey = parseInt(enemy.style.bottom);
          const dx = playerPositionX - ex;
          const dy = playerPositionY - ey;
          const dist = Math.hypot(dx, dy);
          if (dist < 250 && dist > 0) {
            enemy.style.left = (ex + dx * 0.25) + 'px';
            enemy.style.bottom = (ey + dy * 0.25) + 'px';
          }
        });
      }, 33);

      setTimeout(() => {
        clearInterval(pullInterval);
        gravityWell.remove();
        log('Graviton Pull ended!');
      }, 7000);

      log('Graviton Pull activated!');
    }
  },

  {
    name: 'Shard Storm',
    description: 'Summon a storm of sharp crystal shards raining that pierce enemies for 6 seconds.',
    func: () => {
      const shards = [];
      const totalShards = 30;

      for (let i = 0; i < totalShards; i++) {
        const shard = document.createElement('div');
        shard.style.position = 'absolute';
        shard.style.width = '10px';
        shard.style.height = '30px';
        shard.style.background = 'linear-gradient(to bottom, #0ff, #005)';
        shard.style.borderRadius = '4px';
        shard.style.left = (gameScrollPosition + Math.random() * gameContainer.offsetWidth) + 'px';
        shard.style.bottom = (gameContainer.offsetHeight + 50 + Math.random() * 100) + 'px';
        shard.style.transform = `rotate(${Math.random() * 360}deg)`;
        shard.style.opacity = '0.9';
        gameWorld.appendChild(shard);
        shards.push(shard);

        let fallSpeed = 15 + Math.random() * 5;

        const move = setInterval(() => {
          if (!shard.parentElement) {
            clearInterval(move);
            return;
          }
          let bottom = parseFloat(shard.style.bottom);
          bottom -= fallSpeed;
          shard.style.bottom = bottom + 'px';

          if (bottom <= 0) {
            createBurst(parseInt(shard.style.left), 0);
            enemies.forEach((enemy, idx) => {
              if (checkCollision(shard, enemy)) {
                enemy.remove();
                enemies.splice(idx, 1);
                log('Enemy pierced by Shard Storm!');
              }
            });
            shard.remove();
            clearInterval(move);
          }
        }, 33);
      }

      setTimeout(() => {
        shards.forEach(s => s.remove());
        log('Shard Storm ended!');
      }, 6000);

      log('Shard Storm summoned!');
    }
  },

  {
    name: 'Energy Shockfield',
    description: 'Create a field of electric shocks around player that stuns enemies for 5 seconds.',
    func: () => {
      const field = document.createElement('div');
      field.style.position = 'absolute';
      field.style.width = '180px';
      field.style.height = '180px';
      field.style.borderRadius = '50%';
      field.style.border = '3px solid cyan';
      field.style.boxShadow = '0 0 65px 30px cyan inset';
      field.style.left = (playerPositionX - 60) + 'px';
      field.style.bottom = (playerPositionY - 60) + 'px';
      gameWorld.appendChild(field);

      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if (dist < 90) {
          enemy.classList.add('frozen-enemy');
          enemy.style.opacity = '0.3';
        }
      });

      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        field.remove();
        log('Energy Shockfield expired!');
      }, 5000);

      log('Energy Shockfield created!');
    }
  },

  {
    name: 'Spike Trap',
    description: 'Place a spike trap that damages all enemies passing over it for 6 seconds.',
    func: () => {
      const trap = document.createElement('div');
      trap.style.position = 'absolute';
      trap.style.width = '120px';
      trap.style.height = '20px';
      trap.style.left = (playerPositionX + 50) + 'px';
      trap.style.bottom = '0px';
      trap.style.backgroundColor = 'darkred';
      trap.style.borderRadius = '8px';
      trap.style.boxShadow = '0 0 12px 3px crimson inset';
      gameWorld.appendChild(trap);

      const interval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          if (checkCollision(trap, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy destroyed by Spike Trap!');
          }
        });
      }, 100);

      setTimeout(() => {
        clearInterval(interval);
        trap.remove();
        log('Spike Trap expired!');
      }, 6000);

      log('Spike Trap placed!');
    }
  },

  {
    name: 'Healing Pulse',
    description: 'Heal player for 3 lives instantly and emit a pulse healing nearby allies.',
    func: () => {
      lives = Math.min(lives + 3, 99);
      updateDisplay();
      createBurst(playerPositionX, playerPositionY);

      // Also heal friendly allies for 6 seconds if you have any (here no allies, but show pulse)
      const pulse = document.createElement('div');
      pulse.style.position = 'absolute';
      pulse.style.width = '200px';
      pulse.style.height = '200px';
      pulse.style.borderRadius = '50%';
      pulse.style.border = '4px solid lightgreen';
      pulse.style.left = (playerPositionX - 75) + 'px';
      pulse.style.bottom = (playerPositionY - 75) + 'px';
      pulse.style.opacity = '0.5';
      pulse.style.zIndex = '9999';
      gameWorld.appendChild(pulse);

      pulse.animate([
        { opacity: 0.5, transform: 'scale(0.6)' },
        { opacity: 0, transform: 'scale(2.5)' },
      ], { duration: 1200 });

      setTimeout(() => {
        pulse.remove();
      }, 1200);

      log('Healing Pulse emitted!');
    }
  },

  {
    name: 'Blizzard Wind',
    description: 'Summon a chilling wind that slows all enemies by 80% for 7 seconds.',
    func: () => {
      const blizzard = document.createElement('div');
      blizzard.style.position = 'absolute';
      blizzard.style.width = '280px';
      blizzard.style.height = '280px';
      blizzard.style.borderRadius = '50%';
      blizzard.style.background = 'rgba(200,240,255,0.5)';
      blizzard.style.border = '4px solid #00aaff';
      blizzard.style.left = (playerPositionX - 80) + 'px';
      blizzard.style.bottom = (playerPositionY - 80) + 'px';
      gameWorld.appendChild(blizzard);

      enemies.forEach(enemy => {
        enemy.dataset.originalSpeed = enemy.dataset.speed || '1';
        enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed) * 0.2).toString();
        enemy.style.filter = 'blur(1.6px) drop-shadow(0 0 10px #0af)';
        enemy.style.opacity = '0.5';
      });

      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.dataset.speed = enemy.dataset.originalSpeed || '1';
          delete enemy.dataset.originalSpeed;
          enemy.style.filter = '';
          enemy.style.opacity = '1';
        });
        blizzard.remove();
        log('Blizzard Wind ended!');
      }, 7000);

      log('Blizzard Wind activated!');
    }
  },

  {
    name: 'Spectral Blade',
    description: 'Player swings a spectral blade dealing massive damage in a wide arc.',
    func: () => {
      const blade = document.createElement('div');
      blade.style.position = 'absolute';
      blade.style.left = (playerPositionX - 70) + 'px';
      blade.style.bottom = (playerPositionY + player.offsetHeight / 2 - 25) + 'px';
      blade.style.width = '120px';
      blade.style.height = '60px';
      blade.style.background = 'linear-gradient(90deg, transparent 0%, violet 20%, violet 80%, transparent 100%)';
      blade.style.borderRadius = '40%';
      blade.style.opacity = '0.7';
      blade.style.zIndex = '17000';
      blade.style.pointerEvents = 'none';
      gameWorld.appendChild(blade);

      // Arc swing animation
      blade.animate([
        { transform: 'rotate(0deg)', opacity: 0.7 },
        { transform: 'rotate(60deg)', opacity: 0 },
      ], { duration: 800, easing: 'ease-out' });

      // Remove after animation
      setTimeout(() => blade.remove(), 800);

      enemies.forEach((enemy, idx) => {
        const ex = parseInt(enemy.style.left);
        const ey = parseInt(enemy.style.bottom);
        const distX = ex - playerPositionX;
        const distY = ey - playerPositionY;
        if (distX > 0 && distX < 130 && Math.abs(distY) < 60) {
          enemy.remove();
          enemies.splice(idx, 1);
          createBurst(ex, ey);
          log('Enemy sliced by Spectral Blade!');
        }
      });
      log('Spectral Blade swung!');
    }
  },

  {
    name: 'Flash Step',
    description: 'Quickly teleport forward 250px damaging enemies at start and end positions.',
    func: () => {
      const startX = playerPositionX;
      const endX = Math.min(playerPositionX + 250, gameWorld.offsetWidth - player.offsetWidth);

      // Damage enemies at starting position
      enemies = enemies.filter(enemy => {
        const ex = parseInt(enemy.style.left);
        const ey = parseInt(enemy.style.bottom);
        if (Math.abs(ex - startX) < 60 && Math.abs(ey - playerPositionY) < 100) {
          createBurst(ex, ey);
          enemy.remove();
          log('Enemy hit by Flash Step start!');
          return false;
        }
        return true;
      });

      // Teleport player visually
      playerPositionX = endX;
      player.style.left = playerPositionX + 'px';

      // Damage enemies at new position
      enemies = enemies.filter(enemy => {
        const ex = parseInt(enemy.style.left);
        const ey = parseInt(enemy.style.bottom);
        if (Math.abs(ex - endX) < 60 && Math.abs(ey - playerPositionY) < 100) {
          createBurst(ex, ey);
          enemy.remove();
          log('Enemy hit by Flash Step end!');
          return false;
        }
        return true;
      });

      // Add brief white flash
      const flash = document.createElement('div');
      Object.assign(flash.style, {
        position: 'fixed',
        left: '0',
        top: '0',
        width: '100vw',
        height: '100vh',
        backgroundColor: 'white',
        opacity: '0.6',
        pointerEvents: 'none',
        zIndex: 20000,
        transition: 'opacity 0.2s ease-out'
      });
      document.body.appendChild(flash);
      setTimeout(() => {
        flash.style.opacity = '0';
        setTimeout(() => flash.remove(), 200);
      }, 50);

      log('Flash Step executed!');
    }
  },

  {
    name: 'Chain Firestorm',
    description: 'Launch a sequence of expanding fireballs in multiple directions finishing in a big explosion.',
    func: async () => {
      const directions = [0, 45, 90, 135, 180, 225, 270, 315].map(d => d * Math.PI / 180);
      const explosions = [];

      for (let i = 0; i < 8; i++) {
        const fireball = document.createElement('div');
        fireball.style.position = 'absolute';
        fireball.style.width = '25px';
        fireball.style.height = '25px';
        fireball.style.backgroundColor = 'orangered';
        fireball.style.borderRadius = '50%';
        fireball.style.left = (playerPositionX + player.offsetWidth / 2) + 'px';
        fireball.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
        fireball.style.boxShadow = '0 0 20px 8px orange';
        fireball.style.zIndex = '16000';
        gameWorld.appendChild(fireball);

        let x = playerPositionX + player.offsetWidth / 2;
        let y = playerPositionY + player.offsetHeight / 2;
        let angle = directions[i];
        let speed = 6;

        const anim = setInterval(() => {
          if (!fireball.parentElement) {
            clearInterval(anim);
            return;
          }
          x += Math.cos(angle) * speed;
          y += Math.sin(angle) * speed;
          fireball.style.left = x + 'px';
          fireball.style.bottom = y + 'px';

          // Remove at screen bounds
          if (x < 0 || x > gameWorld.offsetWidth || y < 0 || y > gameContainer.offsetHeight) {
            fireball.remove();
            clearInterval(anim);
            return;
          }

          // Check collision with enemies
          enemies.forEach((enemy, idx) => {
            if (checkCollision(fireball, enemy)) {
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              fireball.remove();
              clearInterval(anim);
              log('Enemy caught in Chain Firestorm!');
              return;
            }
          });
        }, 33);

        explosions.push({ fireball, anim });
        await sleep(250);
      }

      // After all fireballs fired, trigger big explosion at player
      createBurst(playerPositionX, playerPositionY);
      log('Chain Firestorm ends with a big blast!');
    }
  },

  {
    name: 'Iron Fortress',
    description: 'Encase yourself in an iron shell absorbing damage for 10 seconds with shield animation.',
    func: () => {
      const shield = document.createElement('div');
      shield.style.position = 'absolute';
      shield.style.width = '140px';
      shield.style.height = '140px';
      shield.style.borderRadius = '50%';
      shield.style.border = '6px solid grey';
      shield.style.boxShadow = '0 0 25px 15px silver inset';
      shield.style.left = (playerPositionX - 50) + 'px';
      shield.style.bottom = (playerPositionY - 50) + 'px';
      shield.style.zIndex = '10000';
      gameWorld.appendChild(shield);

      isInvincible = true;
      log('Iron Fortress activated!');

      shield.animate([
        { boxShadow: '0 0 25px 10px silver inset' },
        { boxShadow: '0 0 40px 20px silver, inset 0 0 30px 18px white' },
        { boxShadow: '0 0 25px 10px silver inset' }
      ], { duration: 1500, iterations: Infinity });

      setTimeout(() => {
        isInvincible = false;
        shield.remove();
        log('Iron Fortress expired!');
      }, 10000);
    }
  },

  {
    name: 'Rapid Fire Turret',
    description: 'Summon a small turret near player that fires rapid bullets for 10 seconds.',
    func: () => {
      const turret = document.createElement('div');
      turret.style.position = 'absolute';
      turret.style.width = '40px';
      turret.style.height = '40px';
      turret.style.borderRadius = '10%';
      turret.style.backgroundColor = 'gray';
      turret.style.left = (playerPositionX + 50) + 'px';
      turret.style.bottom = playerPositionY + 'px';
      gameWorld.appendChild(turret);

      let shotsFired = 0;
      const maxShots = 50;
      const interval = setInterval(() => {
        if (!turret.parentElement || shotsFired >= maxShots) {
          turret.remove();
          clearInterval(interval);
          log('Rapid Fire Turret ended!');
          return;
        }
        
        const bullet = document.createElement('div');
        bullet.classList.add('bullet');
        bullet.style.position = 'absolute';
        bullet.style.left = turret.style.left;
        bullet.style.bottom = turret.style.bottom;
        bullet.style.width = '8px';
        bullet.style.height = '5px';
        bullet.style.backgroundColor = 'red';
        gameWorld.appendChild(bullet);

        let x = parseFloat(bullet.style.left);
        let y = parseFloat(bullet.style.bottom);
        const speed = 12;

        const move = () => {
          if (!bullet.parentElement) return;
          
          x += speed;
          bullet.style.left = x + 'px';
          
          enemies.forEach((enemy, idx) => {
            if (checkCollision(bullet, enemy)) {
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              bullet.remove();
              return;
            }
          });

          if (x > gameWorld.offsetWidth) {
            bullet.remove();
            return;
          }
          requestAnimationFrame(move);
        };

        move();
        shotsFired++;
      }, 150);

      log('Rapid Fire Turret summoned!');
    }
  },

  {
    name: 'Gravity Grenade',
    description: 'Throw a grenade that pulls enemies toward explosion and then damages after 3 seconds.',
    func: () => {
      const x = playerPositionX + player.offsetWidth / 2;
      const y = playerPositionY + player.offsetHeight / 2;

      const grenade = document.createElement('div');
      grenade.style.position = 'absolute';
      grenade.style.width = '20px';
      grenade.style.height = '20px';
      grenade.style.borderRadius = '50%';
      grenade.style.backgroundColor = 'purple';
      grenade.style.left = x + 'px';
      grenade.style.bottom = y + 'px';
      gameWorld.appendChild(grenade);

      let time = 0;

      const interval = setInterval(() => {
        time += 100;

        // Pull enemies toward grenade
        enemies.forEach(enemy => {
          const ex = parseInt(enemy.style.left);
          const ey = parseInt(enemy.style.bottom);
          const dx = x - ex;
          const dy = y - ey;
          const dist = Math.hypot(dx, dy);
          if (dist > 10 && dist < 250) {
            enemy.style.left = (ex + dx * 0.25) + 'px';
            enemy.style.bottom = (ey + dy * 0.25) + 'px';
          }
        });

        if (time >= 3000) {
          clearInterval(interval);
          createBurst(x, y);
          enemies = enemies.filter((enemy, idx) => {
            const ex = parseInt(enemy.style.left);
            const ey = parseInt(enemy.style.bottom);
            const dist = Math.hypot(ex - x, ey - y);
            if (dist < 100) {
              enemy.remove();
              log('Enemy destroyed by Gravity Grenade!');
              return false;
            }
            return true;
          });
          grenade.remove();
        }
      }, 100);

      log('Gravity Grenade thrown!');
    }
  },

  {
    name: 'Rainbow Trail',
    description: 'Player leaves a vibrant rainbow trail that damages and confuses enemies for 8 seconds.',
    func: () => {
      const colors = ['red','orange','yellow','green','blue','indigo','violet'];
      const trails = [];

      const interval = setInterval(() => {
        const trail = document.createElement('div');
        trail.style.position = 'absolute';
        trail.style.left = (playerPositionX + player.offsetWidth / 2) + 'px';
        trail.style.bottom = (playerPositionY + player.offsetHeight / 3) + 'px';
        trail.style.width = '25px';
        trail.style.height = '15px';
        trail.style.borderRadius = '15px';
        trail.style.backgroundColor = colors[Math.floor(Math.random()*colors.length)];
        trail.style.opacity = '0.8';
        gameWorld.appendChild(trail);
        trails.push(trail);

        enemies.forEach((enemy, idx) => {
          if (checkCollision(trail, enemy)) {
            enemy.classList.add('confused-enemy');
            enemy.style.backgroundColor = 'magenta';
            setTimeout(() => {
              enemy.classList.remove('confused-enemy');
              enemy.style.backgroundColor = '';
            }, 4000);
          }
        });

        setTimeout(() => {
          trail.remove();
          trails.splice(trails.indexOf(trail), 1);
        }, 1200);
      }, 150);

      setTimeout(() => {
        clearInterval(interval);
        trails.forEach(t => t.remove());
        log('Rainbow Trail ended!');
      }, 8000);

      log('Rainbow Trail activated!');
    }
  },

  {
    name: 'Orbital Spike',
    description: 'Spawn 4 spiky orbs orbiting around player that shred enemies on contact for 9 seconds.',
    func: () => {
      const orbs = [];
      const totalOrbs = 4;
      const radius = 75;
      for (let i = 0; i < totalOrbs; i++) {
        const orb = document.createElement('div');
        orb.style.position = 'absolute';
        orb.style.width = '30px';
        orb.style.height = '30px';
        orb.style.borderRadius = '50%';
        orb.style.backgroundColor = 'coral';
        orb.style.border = '3px solid darkred';
        gameWorld.appendChild(orb);
        orbs.push({el: orb, angle: (i * (2 * Math.PI)) / totalOrbs});
      }

      let angle = 0;
      const interval = setInterval(() => {
        angle += 0.07;
        orbs.forEach(({el, angle: baseAngle}) => {
          const a = baseAngle + angle;
          const x = playerPositionX + player.offsetWidth / 2 + radius * Math.cos(a);
          const y = playerPositionY + player.offsetHeight / 2 + radius * Math.sin(a);
          el.style.left = x + 'px';
          el.style.bottom = y + 'px';

          enemies.forEach((enemy, idx) => {
            if (checkCollision(el, enemy)) {
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              log('Enemy shredded by Orbital Spike!');
            }
          });
        });
      }, 40);

      setTimeout(() => {
        clearInterval(interval);
        orbs.forEach(o => o.el.remove());
        log('Orbital Spike ended!');
      }, 9000);

      log('Orbital Spike summoned!');
    }
  },

  {
    name: 'Corrosive Mist',
    description: 'Envelop player in a mist that slowly damages enemies and reduces their speed for 8 seconds.',
    func: () => {
      const mist = document.createElement('div');
      mist.style.position = 'absolute';
      mist.style.left = (playerPositionX - 70) + 'px';
      mist.style.bottom = (playerPositionY - 70) + 'px';
      mist.style.width = '200px';
      mist.style.height = '200px';
      mist.style.borderRadius = '50%';
      mist.style.background = 'rgba(50,200,50,0.25)';
      mist.style.zIndex = '998';
      gameWorld.appendChild(mist);

      const interval = setInterval(() => {
        enemies.forEach(enemy => {
          const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
          if (dist < 120) {
            enemy.dataset.originalSpeed = enemy.dataset.speed || '1';
            enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed) * 0.4).toString();
            enemy.style.opacity = '0.5';

            // Slowly apply damage over time
            applyBurn(enemy);
          }
        });
      }, 1000);

      setTimeout(() => {
        clearInterval(interval);
        enemies.forEach(enemy => {
          enemy.dataset.speed = enemy.dataset.originalSpeed || '1';
          enemy.style.opacity = '1';
        });
        mist.remove();
        log('Corrosive Mist dissipated!');
      }, 8000);

      log('Corrosive Mist activated!');
    }
  },

  {
    name: 'Spectral Barrage',
    description: 'Shoot spectral ghost bullets that pass through enemies causing confusion for 10 seconds.',
    func: () => {
      let count = 0;
      const maxShots = 30;

      const shootGhostBullet = () => {
        const bullet = document.createElement('div');
        bullet.style.position = 'absolute';
        bullet.style.left = (playerPositionX + player.offsetWidth / 2) + 'px';
        bullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
        bullet.style.width = '12px';
        bullet.style.height = '12px';
        bullet.style.borderRadius = '50%';
        bullet.style.backgroundColor = 'rgba(200, 200, 255, 0.5)';
        bullet.style.boxShadow = '0 0 15px 5px #aad';
        bullet.style.zIndex = '10800';
        gameWorld.appendChild(bullet);

        let x = playerPositionX + player.offsetWidth / 2;

        const interval = setInterval(() => {
          if (!bullet.parentElement) {
            clearInterval(interval);
            return;
          }
          x += 15;
          bullet.style.left = x + 'px';

          enemies.forEach(enemy => {
            if (checkCollision(bullet, enemy) && !enemy.classList.contains('confused-enemy')) {
              enemy.classList.add('confused-enemy');
              enemy.style.backgroundColor = 'purple';
              setTimeout(() => {
                enemy.classList.remove('confused-enemy');
                enemy.style.backgroundColor = '';
              }, 5000);
            }
          });

          if (x > gameWorld.offsetWidth) {
            bullet.remove();
            clearInterval(interval);
          }
        }, 33);
      };

      const interval = setInterval(() => {
        if (count >= maxShots) {
          clearInterval(interval);
          log('Spectral Barrage ended!');
          return;
        }
        shootGhostBullet();
        count++;
      }, 200);

      log('Spectral Barrage started!');
    }
  },

  {
    name: 'Static Field',
    description: 'Generate static electricity around player that dissipates, damaging enemies over 15 seconds.',
    func: () => {
      const field = document.createElement('div');
      field.style.position = 'absolute';
      field.style.width = '220px';
      field.style.height = '220px';
      field.style.borderRadius = '50%';
      field.style.border = '6px dotted white';
      field.style.boxShadow = '0 0 30px 15px white, inset 0 0 40px 20px #ccc';
      field.style.left = (playerPositionX - 75) + 'px';
      field.style.bottom = (playerPositionY - 75) + 'px';
      field.style.zIndex = '10300';
      gameWorld.appendChild(field);

      let ticks = 0;

      const interval = setInterval(() => {
        ticks++;
        enemies.forEach((enemy, idx) => {
          if (checkCollision(field, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy zapped by Static Field!');
          }
        });
        if (ticks > 15) {
          clearInterval(interval);
          field.remove();
          log('Static Field decayed!');
        }
      }, 1000);

      log('Static Field activated!');
    }
  },

  {
    name: 'Orbital Fire Spikes',
    description: 'Spawn fiery spikes rotating around the player that damage enemies on contact for 9 seconds.',
    func: () => {
      const spikes = [];
      const count = 5;
      const radius = 80;

      for (let i = 0; i < count; i++) {
        const spike = document.createElement('div');
        spike.style.position = 'absolute';
        spike.style.width = '14px';
        spike.style.height = '40px';
        spike.style.background = 'orange';
        spike.style.borderRadius = '5px';
        spike.style.boxShadow = '0 0 10px 5px orange';
        gameWorld.appendChild(spike);
        spikes.push({ el: spike, angle: (i * (2 * Math.PI)) / count });
      }

      let angle = 0;
      const interval = setInterval(() => {
        angle += 0.07;
        spikes.forEach(({ el, angle: baseAngle }) => {
          const a = baseAngle + angle;
          const x = playerPositionX + player.offsetWidth / 2 + radius * Math.cos(a);
          const y = playerPositionY + player.offsetHeight / 2 + radius * Math.sin(a);
          el.style.left = x + 'px';
          el.style.bottom = y + 'px';

          enemies.forEach((enemy, idx) => {
            if (checkCollision(el, enemy)) {
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(idx, 1);
              log('Enemy impaled by Orbital Fire Spike!');
            }
          });
        });
      }, 40);

      setTimeout(() => {
        clearInterval(interval);
        spikes.forEach(s => s.el.remove());
        log('Orbital Fire Spikes ended!');
      }, 9000);

      log('Orbital Fire Spikes summoned!');
    }
  },

  {
    name: 'Telekinetic Push',
    description: 'Push all enemies away from the player’s position with great force, knocking them back 400px.',
    func: () => {
      enemies.forEach(enemy => {
        const ex = parseInt(enemy.style.left);
        const dx = ex - playerPositionX;
        if (dx === 0) return; // exactly under player—no movement

        const newLeft = ex + (dx > 0 ? 400 : -400);
        enemy.style.left = Math.max(0, Math.min(gameWorld.offsetWidth - enemy.offsetWidth, newLeft)) + 'px';
        createBurst(ex, parseInt(enemy.style.bottom));
        log('Enemy knocked back by Telekinetic Push!');
      });
      log('Telekinetic Push activated!');
    }
  },

  {
    name: 'Laser Garden',
    description: 'Place multiple static laser beams in a circle around the player that last 8 seconds.',
    func: () => {
      const lasers = [];
      const laserCount = 12;
      const radius = 120;

      for (let i = 0; i < laserCount; i++) {
        const laser = document.createElement('div');
        laser.style.position = 'absolute';
        laser.style.width = '6px';
        laser.style.height = '80px';
        laser.style.backgroundColor = 'red';
        laser.style.borderRadius = '3px';
        laser.style.zIndex = '11000';
        laser.style.opacity = '0.85';
        const angle = (i * 360 / laserCount) * Math.PI / 180;
        const x = playerPositionX + player.offsetWidth / 2 + radius * Math.cos(angle);
        const y = playerPositionY + player.offsetHeight / 2 + radius * Math.sin(angle);
        laser.style.left = x + 'px';
        laser.style.bottom = y + 'px';
        laser.style.transformOrigin = 'center bottom';
        laser.style.transform = `rotate(${angle * 180 / Math.PI}deg)`;
        gameWorld.appendChild(laser);
        lasers.push(laser);
      }

      const interval = setInterval(() => {
        lasers.forEach((laser, idx) => {
          enemies.forEach((enemy, eidx) => {
            if (checkCollision(laser, enemy)) {
              createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
              enemy.remove();
              enemies.splice(eidx, 1);
              log('Enemy vaporized by Laser Garden!');
            }
          });
        });
      }, 100);

      setTimeout(() => {
        clearInterval(interval);
        lasers.forEach(laser => laser.remove());
        log('Laser Garden expired!');
      }, 8000);

      log('Laser Garden deployed!');
    }
  },

  {
    name: 'Phantom Leap',
    description: 'Teleport in a big leap 400px forward leaving a damaging shockwave.',
    func: () => {
      const shockwave = document.createElement('div');
      shockwave.style.position = 'absolute';
      shockwave.style.width = '180px';
      shockwave.style.height = '180px';
      shockwave.style.borderRadius = '50%';
      shockwave.style.border = '3px solid purple';
      shockwave.style.boxShadow = '0 0 40px 30px violet inset';
      shockwave.style.left = (playerPositionX - 20) + 'px';
      shockwave.style.bottom = (playerPositionY - 20) + 'px';
      shockwave.style.zIndex = '11500';
      shockwave.style.opacity = '0.9';
      gameWorld.appendChild(shockwave);

      playerPositionX = Math.min(playerPositionX + 400, gameWorld.offsetWidth - player.offsetWidth);
      player.style.left = playerPositionX + 'px';

      enemies = enemies.filter(enemy => {
        const ex = parseInt(enemy.style.left);
        const ey = parseInt(enemy.style.bottom);
        const dist = Math.hypot(ex - playerPositionX, ey - playerPositionY);
        if (dist < 150) {
          createBurst(ex, ey);
          enemy.remove();
          log('Enemy hit by Phantom Leap shockwave!');
          return false;
        }
        return true;
      });

      shockwave.animate([
        {opacity: 0.9, transform: 'scale(1)'},
        {opacity: 0, transform: 'scale(2.5)'}
      ], {duration: 700, easing: 'ease-out'});

      setTimeout(() => shockwave.remove(), 700);

      log('Phantom Leap completed!');
    }
  },

  {
    name: 'Arc Lightning Chain',
    description: 'Unleash an arc of lightning reaching 180 degrees that chains between enemies.',
    func: () => {
      const originX = playerPositionX + player.offsetWidth / 2;
      const originY = playerPositionY + player.offsetHeight / 2;
      const arcRadians = Math.PI; // 180 degrees
      const maxDistance = 200;

      // Find all enemies within arc
      enemies = enemies.filter(enemy => {
        const ex = parseInt(enemy.style.left) + enemy.offsetWidth / 2;
        const ey = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2;

        const dx = ex - originX;
        const dy = ey - originY;
        const dist = Math.hypot(dx, dy);

        if (dist > maxDistance) return true;

        let angle = Math.atan2(dy, dx);
        if (currentDirection === -1) {
          angle = Math.PI - angle;
        }
        // Normalize within arc
        if (angle < 0) angle = -angle;

        if (angle <= arcRadians / 2) {
          createBurst(ex, ey);
          log('Enemy zapped by Arc Lightning Chain!');
          return false;
        }
        return true;
      });
      createBurst(playerPositionX, playerPositionY);
      log('Arc Lightning Chain executed!');
    }
  },

  {
    name: 'Vortex Throw',
    description: 'Grab nearest enemies and throw them away with force causing ragdoll effect.',
    func: () => {
      let thrownCount = 0;
      const maxThrow = 5;

      const grabRadius = 120;
      const enemiesToThrow = enemies.filter(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        return dist < grabRadius;
      });

      enemiesToThrow.forEach(enemy => {
        if (thrownCount >= maxThrow) return;

        // Calculate throw direction (randomized outward)
        const angle = Math.random() * 2 * Math.PI;
        const force = 50 + Math.random() * 60;

        let left = parseInt(enemy.style.left);
        let bottom = parseInt(enemy.style.bottom);

        enemy.style.transition = 'left 1s ease-out, bottom 1s ease-out';
        enemy.style.left = (left + Math.cos(angle) * force) + 'px';
        enemy.style.bottom = (bottom + Math.sin(angle) * force + 80) + 'px';

        // After animation, enemy is damaged
        setTimeout(() => {
          createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
          enemy.remove();
          enemies = enemies.filter(e => e !== enemy);
          log('Enemy thrown away and destroyed by Vortex Throw!');
        }, 1000);

        thrownCount++;
      });

      log('Vortex Throw released!');
    }
  },

  {
    name: 'Burning Wheel',
    description: 'Create a spinning fiery wheel around player that burns all enemies on contact for 7 seconds.',
    func: () => {
      const wheel = document.createElement('div');
      wheel.style.position = 'absolute';
      wheel.style.width = '170px';
      wheel.style.height = '170px';
      wheel.style.borderRadius = '50%';
      wheel.style.border = '6px solid orange';
      wheel.style.boxShadow = '0 0 25px 20px orange, inset 0 0 40px 30px red';
      wheel.style.left = (playerPositionX - 60) + 'px';
      wheel.style.bottom = (playerPositionY - 60) + 'px';
      wheel.style.zIndex = '12000';
      gameWorld.appendChild(wheel);

      let angle = 0;
      const interval = setInterval(() => {
        angle += 0.1;
        wheel.style.transform = `rotate(${angle}rad)`;
        enemies.forEach((enemy, idx) => {
          const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
          if (dist < 90) {
            applyBurn(enemy);
            log('Enemy burned by Burning Wheel!');
          }
        });
      }, 33);

      setTimeout(() => {
        clearInterval(interval);
        wheel.remove();
        log('Burning Wheel expired!');
      }, 7000);

      log('Burning Wheel activated!');
    }
  },

  {
    name: 'Shock Leap',
    description: 'Player leaps forward electrifying ground and stunning enemies for 5 seconds.',
    func: async () => {
      playerPositionX = Math.min(playerPositionX + 200, gameWorld.offsetWidth - player.offsetWidth);
      player.style.left = playerPositionX + 'px';
      createBurst(playerPositionX, playerPositionY);

      const groundShock = document.createElement('div');
      groundShock.style.position = 'absolute';
      groundShock.style.width = '250px';
      groundShock.style.height = '50px';
      groundShock.style.borderRadius = '15px';
      groundShock.style.backgroundColor = 'cyan';
      groundShock.style.boxShadow = '0 0 30px 15px skyblue inset';
      groundShock.style.left = (playerPositionX - 80) + 'px';
      groundShock.style.bottom = (playerPositionY) + 'px';
      groundShock.style.zIndex = '9000';
      gameWorld.appendChild(groundShock);

      enemies.forEach(enemy => {
        const dist = Math.hypot(parseInt(enemy.style.left) - playerPositionX, parseInt(enemy.style.bottom) - playerPositionY);
        if (dist < 110) {
          enemy.classList.add('frozen-enemy');
          enemy.style.opacity = '0.3';
        }
      });

      await sleep(5000);

      enemies.forEach(enemy => {
        enemy.classList.remove('frozen-enemy');
        enemy.style.opacity = '1';
      });
      groundShock.remove();
      log('Shock Leap ended!');
    }
  },

  {
    name: 'Toxic Bomb',
    description: 'Throw a bomb that explodes in toxic gas dealing damage and poisoning for 6 seconds.',
    func: () => {
      const x = playerPositionX + player.offsetWidth / 2 + 30;
      const y = playerPositionY + player.offsetHeight / 2;

      const bomb = document.createElement('div');
      bomb.style.position = 'absolute';
      bomb.style.width = '25px';
      bomb.style.height = '25px';
      bomb.style.borderRadius = '50%';
      bomb.style.backgroundColor = 'green';
      bomb.style.left = x + 'px';
      bomb.style.bottom = y + 'px';
      gameWorld.appendChild(bomb);

      setTimeout(() => {
        createBurst(x, y);
        enemies.forEach((enemy, idx) => {
          if (Math.hypot(parseInt(enemy.style.left) - x, parseInt(enemy.style.bottom) - y) < 100) {
            applyBurn(enemy);

            // Poison effect (reduce opacity flicker to show damage)
            let ticks = 5;
            const poisonInterval = setInterval(() => {
              if (ticks <= 0) {
                clearInterval(poisonInterval);
                return;
              }
              enemy.style.opacity = enemy.style.opacity === '0.6' ? '1' : '0.6';
              ticks--;
            }, 700);
          }
        });
        bomb.remove();
        log('Toxic Bomb exploded!');
      }, 1800);

      log('Toxic Bomb thrown!');
    }
  },

  {
    name: 'Momentum Charge',
    description: 'Charge up and dash forward 300px piercing through enemies for 3 seconds.',
    func: async () => {
      player.classList.add('glow');

      const dashDistance = 300;
      const dashSpeed = 25;
      let traveled = 0;

      while (traveled < dashDistance) {
        playerPositionX = Math.min(playerPositionX + dashSpeed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';

        enemies.forEach((enemy, idx) => {
          if (checkCollision(player, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy pierced by Momentum Charge!');
          }
        });

        traveled += dashSpeed;
        await sleep(40);
      }

      player.classList.remove('glow');
      log('Momentum Charge ended!');
    }
  },

  {
    name: 'Sonic Wave Burst',
    description: 'Emit a forward-directed sonic wave that disorients and pushes back enemies.',
    func: () => {
      const wave = document.createElement('div');
      wave.style.position = 'absolute';
      wave.style.width = '250px';
      wave.style.height = '60px';
      wave.style.left = playerPositionX + 'px';
      wave.style.bottom = (playerPositionY + player.offsetHeight / 3) + 'px';
      wave.style.borderRadius = '25%';
      wave.style.backgroundColor = 'deepskyblue';
      wave.style.opacity = '0.6';
      wave.style.boxShadow = '0 0 40px 30px deepskyblue';
      gameWorld.appendChild(wave);

      let waveExpansion = 0;
      const maxExpansion = 350;

      const interval = setInterval(() => {
        waveExpansion += 8;
        wave.style.width = waveExpansion + 'px';

        enemies.forEach(enemy => {
          const dx = parseInt(enemy.style.left) - playerPositionX;
          const dy = parseInt(enemy.style.bottom) - playerPositionY;
          const dist = Math.sqrt(dx * dx + dy * dy);

          if (dist < waveExpansion) {
            // Knock back by 50 px
            enemy.style.left = Math.min(gameWorld.offsetWidth - enemy.offsetWidth, enemy.offsetLeft + 50) + 'px';
            // Disorient (random small movement)
            enemy.style.bottom = Math.min(gameContainer.offsetHeight - enemy.offsetHeight, parseInt(enemy.style.bottom) + (Math.random() * 12 - 6)) + 'px';
            log('Enemy disoriented by Sonic Wave!');
          }
        });

        if (waveExpansion >= maxExpansion) {
          clearInterval(interval);
          wave.remove();
          log('Sonic Wave Burst ended!');
        }
      }, 40);

      log('Sonic Wave Burst released!');
    }
  },

  {
    name: 'Carnival Confetti',
    description: 'Shoot colorful confetti bullets that confuse and distract enemies.',
    func: () => {
      const colors = ['#e91e63','#ffeb3b','#2196f3','#4caf50','#ff9800'];
      let count = 0;

      const interval = setInterval(() => {
        if (count >= 30) {
          clearInterval(interval);
          log('Carnival Confetti ended!');
          return;
        }
        const bullet = document.createElement('div');
        bullet.style.position = 'absolute';
        bullet.style.width = '8px';
        bullet.style.height = '8px';
        bullet.style.borderRadius = '50%';
        bullet.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        bullet.style.left = (playerPositionX + player.offsetWidth/2) + 'px';
        bullet.style.bottom = (playerPositionY + player.offsetHeight/2) + 'px';
        gameWorld.appendChild(bullet);

        let x = playerPositionX + player.offsetWidth / 2;
        const speed = 12;

        const moveInterval = setInterval(() => {
          if (!bullet.parentElement) {
            clearInterval(moveInterval);
            return;
          }
          x += speed;
          bullet.style.left = x + 'px';

          enemies.forEach(enemy => {
            if (!enemy.classList.contains('confused-enemy') && checkCollision(bullet, enemy)) {
              enemy.classList.add('confused-enemy');
              enemy.style.backgroundColor = 'pink';

              setTimeout(() => {
                enemy.classList.remove('confused-enemy');
                enemy.style.backgroundColor = '';
              }, 6000);

              bullet.remove();
              clearInterval(moveInterval);
              log('Enemy confused by Carnival Confetti!');
            }
          });

          if (x > gameWorld.offsetWidth) {
            bullet.remove();
            clearInterval(moveInterval);
          }
        }, 33);

        count++;
      }, 120);

      log('Carnival Confetti fired!');
    }
  },

  {
    name: 'Magnetic Surge',
    description: 'Creates a surge that magnetically pulls all pickups and repels enemies for 8 seconds.',
    func: () => {
      const radius = 200;
      const duration = 8000;
      const powerUpPulls = [...powerUps, ...coins];

      const interval = setInterval(() => {
        enemies.forEach(enemy => {
          const ex = parseInt(enemy.style.left);
          const dx = ex - playerPositionX;
          if (Math.abs(dx) < radius) {
            enemy.style.left = Math.min(gameWorld.offsetWidth - enemy.offsetWidth, ex + dx*0.25) + 'px';
          }
        });
        powerUpPulls.forEach(pickup => {
          const px = parseInt(pickup.style.left);
          const dx = playerPositionX - px;
          if (Math.abs(dx) < radius) {
            pickup.style.left = px + dx * 0.5 + 'px';
          }
        });
      }, 50);

      setTimeout(() => {
        clearInterval(interval);
        log('Magnetic Surge ended!');
      }, duration);

      log('Magnetic Surge activated!');
    }
  },

  {
    name: 'Tidal Wave',
    description: 'Generates a large water wave moving forward damaging enemies over 7 seconds.',
    func: () => {
      const wave = document.createElement('div');
      wave.style.position = 'absolute';
      wave.style.width = '250px';
      wave.style.height = '100px';
      wave.style.background = 'linear-gradient(90deg, #00bfff, #1469d3)';
      wave.style.borderRadius = '40% / 100%';
      wave.style.left = playerPositionX + 'px';
      wave.style.bottom = playerPositionY + 'px';
      wave.style.opacity = '0.75';
      wave.style.zIndex = '10700';
      gameWorld.appendChild(wave);

      let distance = 0;
      const speed = 15;
      const maxDistance = 900;

      const interval = setInterval(() => {
        distance += speed;
        wave.style.left = (playerPositionX + distance) + 'px';

        // Check collision with enemies
        enemies.forEach((enemy, idx) => {
          if (checkCollision(wave, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy swept by Tidal Wave!');
          }
        });

        if (distance >= maxDistance) {
          clearInterval(interval);
          wave.remove();
          log('Tidal Wave ended!');
        }
      }, 33);

      log('Tidal Wave released!');
    }
  },

  {
    name: 'Flash Freeze',
    description: 'Instantly freeze all enemies on screen for 5 seconds stalling movement and attacks.',
    func: () => {
      enemies.forEach(enemy => {
        enemy.classList.add('frozen-enemy');
        enemy.style.opacity = '0.25';
      });

      const freezeFlash = document.createElement('div');
      Object.assign(freezeFlash.style, {
        position: 'fixed',
        top: '0',
        left: '0',
        width: '100vw',
        height: '100vh',
        backgroundColor: 'lightblue',
        opacity: '0.4',
        pointerEvents: 'none',
        zIndex: '20000',
        transition: 'opacity 0.8s ease-out'
      });
      document.body.appendChild(freezeFlash);

      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        freezeFlash.style.opacity = '0';
        setTimeout(() => freezeFlash.remove(), 800);
        log('Flash Freeze ended!');
      }, 5000);

      log('Flash Freeze activated!');
    }
  },

  {
    name: 'Toxic Tendrils',
    description: 'Summon toxic vine tendrils that grab and damage enemies for 7 seconds.',
    func: () => {
      const tendrils = [];
      for (let i = 0; i < 3; i++) {
        const tendril = document.createElement('div');
        tendril.style.position = 'absolute';
        tendril.style.width = '20px';
        tendril.style.height = '120px';
        tendril.style.left = (playerPositionX + i * 60 - 40) + 'px';
        tendril.style.bottom = '0px';
        tendril.style.backgroundColor = 'darkgreen';
        tendril.style.borderRadius = '12px';
        tendril.style.opacity = '0.8';
        tendril.style.zIndex = '9500';
        gameWorld.appendChild(tendril);
        tendrils.push(tendril);
      }

      const interval = setInterval(() => {
        tendrils.forEach(tendril => {
          enemies.forEach((enemy, idx) => {
            if (checkCollision(tendril, enemy)) {
              applyBurn(enemy);
              log('Enemy caught in Toxic Tendrils!');
            }
          });
        });
      }, 200);

      setTimeout(() => {
        clearInterval(interval);
        tendrils.forEach(t => t.remove());
        log('Toxic Tendrils withered!');
      }, 7000);
      log('Toxic Tendrils summoned!');
    }
  },
  {
    name: 'Boss Phase - Shadow Realm',
    description: 'Boss expands a dark realm reducing player visibility and slowing all movements for 10 seconds.',
    func: async () => {
      displayMessage('Boss: Enter my Shadow Realm!', 4);

      const domain = document.createElement('div');
      Object.assign(domain.style, {
        position: 'absolute',
        left: '0px',
        bottom: '0px',
        width: `${gameWorld.offsetWidth}px`,
        height: `${gameContainer.offsetHeight}px`,
        backgroundColor: 'rgba(10, 10, 10, 0.9)',
        zIndex: '20000',
        pointerEvents: 'none',
        transition: 'opacity 3s ease-in',
        opacity: '0'
      });
      gameWorld.appendChild(domain);

      // Fade in domain
      requestAnimationFrame(() => {
        domain.style.opacity = '1';
      });

      // Reduce player speed and enemies speed
      const originalSpeed = playerMaxSpeed;
      playerMaxSpeed *= 0.4;

      enemies.forEach(enemy => {
        enemy.dataset.originalSpeed = enemy.dataset.speed || '1';
        enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed) * 0.3).toString();
        enemy.style.opacity = '0.5';
      });

      // Hide player partially
      player.style.filter = 'blur(2px) brightness(0.3)';

      await new Promise(r => setTimeout(r, 10000));

      // Restore speed & remove effects
      playerMaxSpeed = originalSpeed;
      enemies.forEach(enemy => {
        enemy.dataset.speed = enemy.dataset.originalSpeed || '1';
        enemy.style.opacity = '1';
        delete enemy.dataset.originalSpeed;
      });
      player.style.filter = '';

      domain.style.opacity = '0';
      setTimeout(() => {
        domain.remove();
        log('Boss Phase: Shadow Realm ended!');
      }, 3000);

      log('Boss cast Domain Expansion: Shadow Realm!');
    }
  },

  /** 122. Boss Phase - Gravity Crush */
  {
    name: 'Boss Phase - Gravity Crush',
    description: 'Boss causes gravity to increase - all jumps are halved and fall speed doubled for 8 seconds.',
    func: async () => {
      displayMessage('Boss: Feel the weight of the world!', 3);

      let originalJumpStrength = playerJumpStrength;
      let originalGravity = gravity;

      // Halve jump and double gravity
      playerJumpStrength *= 0.5;
      gravity *= 2;

      await sleep(8000);

      // Restore normal jump and gravity
      playerJumpStrength = originalJumpStrength;
      gravity = originalGravity;

      displayMessage('Gravity returns to normal!', 3);
      log('Boss Phase: Gravity Crush ended!');
    }
  },

  /** 123. Boss Phase - Fire Domain */
  {
    name: 'Boss Phase - Fire Domain',
    description: 'Boss ignites a fiery domain setting the floor ablaze. Player must jump carefully for 12 seconds.',
    func: () => {
      displayMessage('Boss: The floor is lava!', 4);

      const lavaFloor = document.createElement('div');
      Object.assign(lavaFloor.style, {
        position: 'absolute',
        left: '0px',
        bottom: '0px',
        width: `${gameWorld.offsetWidth}px`,
        height: '40px',
        background: 'linear-gradient(45deg, #ff3300, #aa0000)',
        filter: 'blur(4px)',
        boxShadow: '0 0 30px 12px red inset',
        zIndex: 11000,
        pointerEvents: 'none',
      });
      gameWorld.appendChild(lavaFloor);

      // Damage when touching floor (approximate with player Y)
      const interval = setInterval(() => {
        if (playerPositionY < 40) {
          reduceLives();
          displayMessage('Burned by the lava! Watch your steps!', 1);
        }
      }, 700);

      setTimeout(() => {
        clearInterval(interval);
        lavaFloor.remove();
        displayMessage('The ground cools down...', 3);
        log('Boss Phase: Fire Domain ended!');
      }, 12000);

      log('Boss unleashed Fire Domain!');
    }
  },

  /** 124. Boss Phase - Wind Blast */
  {
    name: 'Boss Phase - Wind Blast',
    description: 'A powerful wind blast pushes player backward and disorients movement for 7 seconds.',
    func: () => {
      displayMessage('Boss: Feel the raging wind!', 3);

      const blast = document.createElement('div');
      Object.assign(blast.style, {
        position: 'absolute',
        left: (playerPositionX - 50) + 'px',
        bottom: (playerPositionY + player.offsetHeight / 2 - 25) + 'px',
        width: '150px',
        height: '50px',
        background: 'radial-gradient(circle, rgba(200,200,255,0.6), transparent)',
        borderRadius: '50%',
        boxShadow: '0 0 20px 10px lightblue',
        zIndex: 14000,
        pointerEvents: 'none',
      });
      gameWorld.appendChild(blast);

      let originalMaxSpeed = playerMaxSpeed;
      let disoriented = true;
      playerMaxSpeed *= 0.6;

      let pushDistanceLeft = 250;
      let pushStep = 15;

      const pushInterval = setInterval(() => {
        if (pushDistanceLeft <= 0) {
          clearInterval(pushInterval);
          disoriented = false;
          playerMaxSpeed = originalMaxSpeed;
          displayMessage('Wind settles down...', 2);
          blast.remove();
          log('Boss Phase: Wind Blast ended!');
          return;
        }
        playerPositionX = Math.max(0, playerPositionX - pushStep);
        player.style.left = playerPositionX + 'px';
        pushDistanceLeft -= pushStep;
      }, 50);

      log('Boss cast Wind Blast!');
    }
  },

  /** 125. Boss Phase - Ice Floor */
  {
    name: 'Boss Phase - Ice Floor',
    description: 'The ground becomes slippery causing player movement to lose traction for 10 seconds.',
    func: () => {
      displayMessage('Boss: The ice makes your footsteps betray you!', 4);

      let normalSpeed = playerMaxSpeed;
      playerMaxSpeed *= 0.8; // Slightly slower

      let originalHandleJump = handleJump;
      // Override horizontal movement to simulate slide (simplified)
      window.handleJump = () => {
        // Less jump control => simulate slipping by random side drift after jump
        if(playerPositionY === 0 || isJumping){ // allow jump like normal
          playerVelocityY = playerJumpStrength;
          jumpCount++;
          isJumping = true;
        }
        // Add slight left/right offset randomly
        playerPositionX += (Math.random() - 0.5) * 20;
        player.style.left = Math.max(0, Math.min(gameWorld.offsetWidth - player.offsetWidth, playerPositionX)) + 'px';
      };

      setTimeout(() => {
        playerMaxSpeed = normalSpeed;
        window.handleJump = originalHandleJump;
        displayMessage('The ice has melted...', 3);
        log('Boss Phase: Ice Floor ended!');
      }, 10000);

      log('Boss activates Ice Floor!');
    }
  },

  /** 126. Boss Phase - Crystal Spikes */
  {
    name: 'Boss Phase - Crystal Spikes',
    description: 'Crystals erupt from the ground dealing damage when touched, lasts 10 seconds.',
    func: () => {
      displayMessage('Boss summons deadly crystal spikes!', 4);

      const spikes = [];
      for(let i = 0; i < 8; i++) {
        const spike = document.createElement('div');
        Object.assign(spike.style, {
          position: 'absolute',
          width: '20px',
          height: '70px',
          background: 'linear-gradient(to top, #aad4ff, #577bbd)',
          borderRadius: '0 0 10px 10px',
          boxShadow: '0 0 10px 3px #7eb4ff inset',
          left: (i * 120) + 'px',
          bottom: '0px',
          zIndex: 11000,
          opacity: '0.8',
        });
        gameWorld.appendChild(spike);
        spikes.push(spike);
      }

      const damageInterval = setInterval(() => {
        spikes.forEach(spike => {
          if (checkCollision(player, spike)) {
            reduceLives();
            flashScreen('rgba(170, 200, 255, 0.7)');
          }
        });
      }, 250);

      setTimeout(() => {
        clearInterval(damageInterval);
        spikes.forEach(s => s.remove());
        displayMessage('Crystal Spikes disappear...', 3);
        log('Boss Phase: Crystal Spikes ended!');
      }, 10000);

      log('Boss uses Crystal Spikes!');
    }
  },

  /** 127. Boss Phase - Time Distortion */
  {
    name: 'Boss Phase - Time Distortion',
    description: 'Time slows down for player and speed up for enemies for 8 seconds.',
    func: () => {
      displayMessage("Boss distorts your perception of time!", 3);

      let originalPlayerSpeed = playerMaxSpeed;
      playerMaxSpeed *= 0.4;
      enemies.forEach(enemy => {
        enemy.dataset.originalSpeed = enemy.dataset.speed || '1';
        enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed) * 1.8).toString();
      });

      setTimeout(() => {
        playerMaxSpeed = originalPlayerSpeed;
        enemies.forEach(enemy => {
          enemy.dataset.speed = enemy.dataset.originalSpeed || '1';
          delete enemy.dataset.originalSpeed;
        });
        displayMessage("Time flow returns to normal!", 3);
        log('Boss Phase: Time Distortion ended!');
      }, 8000);

      log('Boss has cast Time Distortion!');
    }
  },

  /** 128. Boss Phase - Lightning Storm */
  {
    name: 'Boss Phase - Lightning Storm',
    description: 'Summon lightning bolts hitting random ground points every 1.5s for 12 seconds.',
    func: async () => {
      displayMessage('Boss calls down a lightning storm! Avoid the strikes!', 4);

      const maxStrikes = 10;
      for(let i=0; i<maxStrikes; i++) {
        const strikeX = Math.random() * (gameWorld.offsetWidth - 60) + gameScrollPosition;
        const lightning = document.createElement('div');
        Object.assign(lightning.style, {
          position: 'absolute',
          width: '12px',
          height: '120px',
          backgroundColor: 'yellow',
          left: `${strikeX}px`,
          bottom: '0',
          zIndex: 12000,
          filter: 'drop-shadow(0 0 20px yellow)',
        });
        gameWorld.appendChild(lightning);

        if(checkCollision(player, lightning)) {
          reduceLives();
          flashScreen('rgba(255, 255, 100, 0.9)');
        }

        enemies.forEach((enemy, idx) => {
          if (checkCollision(enemy, lightning)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy struck by lightning!');
          }
        });

        await sleep(1500);
        lightning.remove();
      }

      displayMessage('Lightning Storm ended!', 3);
      log('Boss Phase: Lightning Storm ended!');
    }
  },

  /** 129. Boss Phase - Void Rift */
  {
    name: 'Boss Phase - Void Rift',
    description: 'A rift opens and pulls nearby enemies inward until they vanish for 10 seconds.',
    func: () => {
      displayMessage('Boss opens a Void Rift drawing beings within!', 3);

      const rift = document.createElement('div');
      Object.assign(rift.style, {
        position: 'absolute',
        width: '200px',
        height: '200px',
        borderRadius: '50%',
        left: (playerPositionX + player.offsetWidth / 2 - 100) + 'px',
        bottom: (playerPositionY + player.offsetHeight / 2 - 100) + 'px',
        background: 'radial-gradient(circle, black, transparent 75%)',
        boxShadow: '0 0 50px 30px black inset',
        zIndex: 11000,
        pointerEvents: 'none'
      });
      gameWorld.appendChild(rift);

      const interval = setInterval(() => {
        enemies.forEach(enemy => {
          const ex = parseInt(enemy.style.left);
          const ey = parseInt(enemy.style.bottom);
          const dx = (playerPositionX + player.offsetWidth / 2) - ex;
          const dy = (playerPositionY + player.offsetHeight / 2) - ey;
          const dist = Math.hypot(dx, dy);
          if (dist < 200) {
            enemy.style.left = ex + dx * 0.2 + 'px';
            enemy.style.bottom = ey + dy * 0.2 + 'px';
            if (dist < 50) {
              createBurst(ex, ey);
              enemy.remove();
              enemies = enemies.filter(e => e !== enemy);
              log('Enemy swallowed by Void Rift!');
            }
          }
        });
      }, 40);

      setTimeout(() => {
        clearInterval(interval);
        rift.remove();
        displayMessage('Void Rift closes...', 3);
        log('Boss Phase: Void Rift ended!');
      }, 10000);

      log('Boss opens Void Rift!');
    }
  },

  /** 130. Boss Phase - Sonic Barrage */
  {
    name: 'Boss Phase - Sonic Barrage',
    description: 'Boss fires waves of sonic blasts in quick succession for 10 seconds.',
    func: async () => {
      displayMessage('Boss releases a barrage of sonic blasts!', 4);

      const blastCount = 12;
      for(let i=0; i<blastCount; i++) {
        const blast = document.createElement('div');
        Object.assign(blast.style, {
          position: 'absolute',
          width: '80px',
          height: '80px',
          borderRadius: '50%',
          backgroundColor: 'deepskyblue',
          opacity: '0.5',
          left: (playerPositionX + 100) + 'px',
          bottom: (playerPositionY) + 'px',
          zIndex: 15000,
          pointerEvents: 'none',
          transform: 'scale(0.5)',
          boxShadow: '0 0 25px 15px #00aaff'
        });
        gameWorld.appendChild(blast);

        blast.animate([
          {opacity: 0.5, transform: 'scale(0.5)'},
          {opacity: 0, transform: 'scale(2.2)'}
        ], {duration: 900, easing: 'ease-out'});

        enemies.forEach((enemy, idx) => {
          const dist = Math.hypot(parseInt(enemy.style.left) - (playerPositionX + 100), parseInt(enemy.style.bottom) - playerPositionY);
          if (dist < 130) {
            enemy.remove();
            enemies.splice(idx, 1);
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            log('Enemy hit by Sonic Barrage!');
          }
        });

        setTimeout(() => blast.remove(), 900);
        await sleep(800);
      }

      displayMessage('Sonic Barrage ended!', 3);
      log('Boss finished Sonic Barrage!');
    }
  },  

  {
    name: 'Quantum Blink',
    description: 'Instantly swap player position with a random enemy on screen.',
    func: () => {
      if (enemies.length === 0) {
        log('No enemies to swap with!');
        return;
      }
      const randEnemy = enemies[Math.floor(Math.random() * enemies.length)];
      const playerX = playerPositionX;
      const playerY = playerPositionY;

      playerPositionX = parseInt(randEnemy.style.left);
      playerPositionY = parseInt(randEnemy.style.bottom);
      player.style.left = playerPositionX + 'px';
      player.style.bottom = playerPositionY + 'px';

      randEnemy.style.left = playerX + 'px';
      randEnemy.style.bottom = playerY + 'px';

      log('Quantum Blink performed!');
    }
  },

  {
    name: 'Mirror Image',
    description: 'Create 3 illusory clones of player to confuse enemies for 8 seconds.',
    func: () => {
      const clones = [];
      for (let i = -1; i <= 1; i++) {
        if (i === 0) continue; // skip actual player
        const clone = document.createElement('div');
        clone.style.position = 'absolute';
        clone.style.width = player.offsetWidth + 'px';
        clone.style.height = player.offsetHeight + 'px';
        clone.style.left = (playerPositionX + i*60) + 'px';
        clone.style.bottom = playerPositionY + 'px';
        clone.style.backgroundColor = 'rgba(255,255,255,0.3)';
        clone.style.borderRadius = '50%';
        clone.style.pointerEvents = 'none';
        clone.style.zIndex = '14000';
        gameWorld.appendChild(clone);
        clones.push(clone);
      }
      log('Mirror Images created!');

      setTimeout(() => {
        clones.forEach(c => c.remove());
        log('Mirror Images fade away!');
      }, 8000);
    }
  },

  {
    name: 'Volcanic Shield',
    description: 'Encase player in lava that flames enemies on touch for 7 seconds.',
    func: () => {
      const shield = document.createElement('div');
      Object.assign(shield.style, {
        position: 'absolute',
        width: '140px',
        height: '140px',
        borderRadius: '50%',
        background: 'radial-gradient(circle, darkorange, orangered)',
        filter: 'blur(8px)',
        opacity: '0.7',
        left: (playerPositionX - 55) + 'px',
        bottom: (playerPositionY - 55) + 'px',
        zIndex: '10200',
        pointerEvents: 'none'
      });
      gameWorld.appendChild(shield);

      const interval = setInterval(() => {
        enemies.forEach((enemy, idx) => {
          if (checkCollision(shield, enemy)) {
            applyBurn(enemy);
          }
        });
      }, 150);

      setTimeout(() => {
        clearInterval(interval);
        shield.remove();
        log('Volcanic Shield expired!');
      }, 7000);

      log('Volcanic Shield activated!');
    }
  },

  {
    name: 'Energy Entangle',
    description: 'Trap all enemies in energy bonds freezing them for 6 seconds.',
    func: () => {
      enemies.forEach(enemy => {
        enemy.style.border = '4px solid cyan';
        enemy.classList.add('frozen-enemy');
        enemy.style.filter = 'drop-shadow(0 0 10px cyan)';
        enemy.style.opacity = '0.4';
      });

      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.border = '';
          enemy.style.filter = '';
          enemy.style.opacity = '1';
        });
        log('Energy Entangle released!');
      }, 6000);

      log('Energy Entangle activated!');
    }
  },

  {
    name: 'Spectral Arrow',
    description: 'Fire a spectral arrow that passes through enemies damaging all in straight line.',
    func: () => {
      const arrow = document.createElement('div');
      arrow.style.position = 'absolute';
      arrow.style.left = (playerPositionX + player.offsetWidth / 2) + 'px';
      arrow.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
      arrow.style.width = '20px';
      arrow.style.height = '6px';
      arrow.style.backgroundColor = 'lightblue';
      arrow.style.borderRadius = '3px';
      arrow.style.boxShadow = '0 0 12px 6px lightblue';
      arrow.style.zIndex = '16999';
      gameWorld.appendChild(arrow);

      let x = playerPositionX + player.offsetWidth / 2;
      const speed = 18;

      const interval = setInterval(() => {
        if(!arrow.parentElement) {
          clearInterval(interval);
          return;
        }
        x += speed;
        arrow.style.left = x + 'px';

        enemies.forEach((enemy, idx) => {
          if (checkCollision(arrow, enemy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log('Enemy hit by Spectral Arrow!');
            // Arrow continues through, no removal
          }
        });

        if(x > gameWorld.offsetWidth) {
          clearInterval(interval);
          arrow.remove();
          log('Spectral Arrow ended!');
        }
      }, 20);

      log('Spectral Arrow fired!');
    }
  },

  {
    name: 'Shadow Bind',
    description: 'Bind one random enemy in place for 6 seconds with a dark tether.',
    func: () => {
      if (enemies.length === 0) {
        log('No enemy to bind!');
        return;
      }
      const enemy = enemies[Math.floor(Math.random() * enemies.length)];

      const tether = document.createElement('div');
      tether.style.position = 'absolute';
      tether.style.width = '6px';
      tether.style.height = enemy.offsetHeight + 'px';
      tether.style.left = (parseInt(enemy.style.left) + enemy.offsetWidth / 2 - 3) + 'px';
      tether.style.bottom = enemy.style.bottom;
      tether.style.background = 'linear-gradient(180deg, black, purple)';
      tether.style.boxShadow = '0 0 15px 5px purple';
      tether.style.zIndex = '12000';
      gameWorld.appendChild(tether);

      enemy.style.pointerEvents = 'none'; // Stops movement or interactions

      setTimeout(() => {
        enemy.style.pointerEvents = '';
        tether.remove();
        log('Shadow Bind expired!');
      }, 6000);

      log('Enemy bound by Shadow Bind!');
    }
  },

  // 65 more such creative, unique functions with new ideas follow ...

  // Example:

  {
    name: 'Solar Flare Burst',
    description: 'Release a blinding flare that damages all enemies and blinds them for 4 seconds.',
    func: () => {
      const flare = document.createElement('div');
      Object.assign(flare.style, {
        position: 'fixed',
        top: '0', left: '0',
        width: '100vw', height: '100vh',
        backgroundColor: 'white',
        opacity: '0.9',
        zIndex: '200000',
        pointerEvents: 'none'
      });
      document.body.appendChild(flare);

      enemies.forEach(enemy => {
        enemy.style.filter = 'brightness(0.2)';
        enemy.style.opacity = '0.35';
      });

      setTimeout(() => {
        flare.style.opacity = '0';
        setTimeout(() => flare.remove(), 600);
        enemies.forEach(enemy => {
          enemy.style.filter = '';
          enemy.style.opacity = '1';
        });
      }, 4000);

      log('Solar Flare Burst activated!');
    }
  },

{
  name: "Boss Phase - Domain Expansion: Shadow Realm",
  description: "Boss darkens the arena reducing visibility & slowing all movement for 10 seconds.",
  func: async () => {
    displayMessage("Boss: Step into my Shadow Realm!", 4);

    const domain = document.createElement('div');
    Object.assign(domain.style, {
      position: 'absolute',
      left: '0',
      bottom: '0',
      width: `${gameWorld.offsetWidth}px`,
      height: `${gameContainer.offsetHeight}px`,
      backgroundColor: 'rgba(8, 8, 15, 0.9)',
      zIndex: '50000',
      pointerEvents: 'none',
      opacity: '0',
      transition: 'opacity 3s ease-in'
    });
    gameWorld.appendChild(domain);

    requestAnimationFrame(() => domain.style.opacity = '1');

    const oldPlayerSpeed = playerMaxSpeed;
    playerMaxSpeed *= 0.4;
    enemies.forEach(e => {
      e.dataset.originalSpeed = e.dataset.speed || "1";
      e.dataset.speed = (parseFloat(e.dataset.originalSpeed) * 0.4).toString();
      e.style.opacity = '0.5';
      e.style.filter = 'blur(1.4px) drop-shadow(0 0 5px black)';
    });

    player.style.filter = 'blur(2px) brightness(0.4)';

    await sleep(10000);

    playerMaxSpeed = oldPlayerSpeed;
    enemies.forEach(e => {
      e.dataset.speed = e.dataset.originalSpeed || "1";
      delete e.dataset.originalSpeed;
      e.style.filter = '';
      e.style.opacity = '1';
    });
    player.style.filter = '';

    domain.style.opacity = '0';
    setTimeout(() => {
      domain.remove();
      log("Boss Shadow Realm ended!");
    }, 3000);
  }
},

/** 2. Boss Phase - Gravity Crush */
{
  name: "Boss Phase - Gravity Crush",
  description: "Boss increases gravity; player jumps low and falls fast for 8 seconds.",
  func: async () => {
    displayMessage("Boss: Crush under my gravity!", 3);

    let oldGravity = gravity;
    let oldJump = playerJumpStrength;

    gravity *= 2;
    playerJumpStrength *= 0.5;

    await sleep(8000);

    gravity = oldGravity;
    playerJumpStrength = oldJump;

    displayMessage("Gravity restored!", 3);
    log("Boss Gravity Crush ended!");
  }
},

/** 3. Boss Phase - Fire Domain */
{
  name: "Boss Phase - Fire Domain",
  description: "Boss sets the floor ablaze for 12 seconds! Avoid the burning ground.",
  func: () => {
    displayMessage("Boss: The floor is lava!!!", 4);

    const floorLava = document.createElement('div');
    Object.assign(floorLava.style, {
      position: 'absolute',
      bottom: '0',
      left: '0',
      width: `${gameWorld.offsetWidth}px`,
      height: '40px',
      background: 'linear-gradient(45deg, #f00, #a00)',
      boxShadow: '0 0 25px 15px orange, inset 0 0 30px 25px #ff3300',
      filter: 'blur(4px)',
      opacity: '0.75',
      zIndex: '10000',
      pointerEvents: 'none'
    });
    gameWorld.appendChild(floorLava);

    const damageInterval = setInterval(() => {
      if (playerPositionY < 40) {
        reduceLives();
        displayMessage("Burned! Jump fast!", 1);
      }
    }, 700);

    setTimeout(() => {
      clearInterval(damageInterval);
      floorLava.remove();
      displayMessage("The lava cools...", 3);
      log("Boss Fire Domain ended!");
    }, 12000);
  }
},

/** 4. Boss Phase - Wind Blast */
{
  name: "Boss Phase - Wind Blast",
  description: "Powerful wind pushes player backward & slows movement for 7 seconds.",
  func: () => {
    displayMessage("Boss: Feel the mighty wind!", 3);

    const blast = document.createElement('div');
    Object.assign(blast.style, {
      position: 'absolute',
      width: '160px',
      height: '60px',
      borderRadius: '30%',
      background: 'radial-gradient(circle, #bbf, transparent)',
      boxShadow: '0 0 30px 15px #99ccff',
      opacity: '0.85',
      left: (playerPositionX - 70) + 'px',
      bottom: (playerPositionY + player.offsetHeight / 3) + 'px',
      pointerEvents: 'none',
      zIndex: '16000'
    });
    gameWorld.appendChild(blast);

    let oldSpeed = playerMaxSpeed;
    playerMaxSpeed *= 0.6;

    let distanceLeft = 250;
    const pushSpeed = 15;

    const pushInterval = setInterval(() => {
      if (distanceLeft <= 0) {
        clearInterval(pushInterval);
        playerMaxSpeed = oldSpeed;
        blast.remove();
        displayMessage("The wind settles.", 2);
        log("Boss Wind Blast ended!");
        return;
      }
      playerPositionX = Math.max(0, playerPositionX - pushSpeed);
      player.style.left = playerPositionX + 'px';
      distanceLeft -= pushSpeed;
    }, 50);
  }
},

/** 5. Boss Phase - Ice Floor */
{
  name: "Boss Phase - Ice Floor",
  description: "The floor is frozen and slippery, movement loses control for 10 seconds.",
  func: () => {
    displayMessage("Boss: Glaciate your path!", 4);

    let normalSpeed = playerMaxSpeed;
    playerMaxSpeed *= 0.75;

    // Save original jump handler and override for slippery effect
    let origHandleJump = window.handleJump;
    window.handleJump = () => {
      if (playerPositionY === 0 || isJumping) {
        playerVelocityY = playerJumpStrength;
        jumpCount++;
        isJumping = true;
      }
      playerPositionX += (Math.random() - 0.5) * 18;
      playerPositionX = Math.max(0, Math.min(gameWorld.offsetWidth - player.offsetWidth, playerPositionX));
      player.style.left = playerPositionX + 'px';
    };

    setTimeout(() => {
      playerMaxSpeed = normalSpeed;
      window.handleJump = origHandleJump;
      displayMessage("The ice melts!", 3);
      log("Boss Ice Floor ended!");
    }, 10000);
  }
},

/** 6. Boss Phase - Crystal Spikes */
{
  name: "Boss Phase - Crystal Spikes",
  description: "Crystals burst from ground damaging player on contact for 10 seconds.",
  func: () => {
    displayMessage("Boss: Crystals pierce the earth!", 4);

    const spikes = [];
    for(let i=0; i<7; i++) {
      const spike = document.createElement('div');
      Object.assign(spike.style, {
        position: 'absolute',
        width: '22px',
        height: '80px',
        background: 'linear-gradient(to top, #aaccee, #446688)',
        borderRadius: '0 0 12px 12px',
        boxShadow: '0 0 10px 5px #99bbff inset',
        left: (i * 120) + 'px',
        bottom: '0',
        opacity: '0.8',
        zIndex: '11000'
      });
      gameWorld.appendChild(spike);
      spikes.push(spike);
    }

    const damageLoop = setInterval(() => {
      spikes.forEach(spike => {
        if (checkCollision(player, spike)) reduceLives();
      });
    }, 250);

    setTimeout(() => {
      clearInterval(damageLoop);
      spikes.forEach(sp => sp.remove());
      displayMessage('Crystals retract...', 2);
      log('Boss Crystal Spikes ended!');
    }, 10000);
  }
},

/** 7. Boss Phase - Time Distortion */
{
  name: "Boss Phase - Time Distortion",
  description: "Time slows for player, enemies speed up for 8 seconds.",
  func: async () => {
    displayMessage("Boss slows your time!", 3);

    let oldSpeed = playerMaxSpeed;
    playerMaxSpeed *= 0.35;

    enemies.forEach(enemy => {
      enemy.dataset.originalSpeed = enemy.dataset.speed || "1";
      enemy.dataset.speed = (parseFloat(enemy.dataset.originalSpeed) * 2).toString();
    });

    await sleep(8000);

    playerMaxSpeed = oldSpeed;
    enemies.forEach(enemy => {
      enemy.dataset.speed = enemy.dataset.originalSpeed || "1";
      delete enemy.dataset.originalSpeed;
    });

    displayMessage("Time returns to normal.", 3);
    log("Boss Time Distortion ended!");
  }
},

/** 8. Boss Phase - Lightning Storm */
{
  name: "Boss Phase - Lightning Storm",
  description: "Lightning bolts strike random ground points every 1.5s for 12 seconds.",
  func: async () => {
    displayMessage("Boss calls down a storm of lightning!", 4);

    for (let i=0; i<10; i++) {
      let strikeX = Math.random() * (gameWorld.offsetWidth - 60) + gameScrollPosition;

      const lightning = document.createElement('div');
      Object.assign(lightning.style, {
        position: 'absolute',
        width: '10px',
        height: '120px',
        backgroundColor: 'yellow',
        left: `${strikeX}px`,
        bottom: '0px',
        zIndex: 20000,
        filter: 'drop-shadow(0 0 22px yellow)'
      });
      gameWorld.appendChild(lightning);

      if (checkCollision(player, lightning)) reduceLives();

      enemies.forEach((enemy, idx) => {
        if(checkCollision(enemy, lightning)){
          createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
          enemy.remove();
          enemies.splice(idx, 1);
          log("Enemy zapped by lightning");
        }
      });

      await sleep(1500);
      lightning.remove();
    }

    displayMessage("Lightning Storm ends!", 3);
    log("Boss Lightning Storm ended!");
  }
},

/** 9. Boss Phase - Void Rift */
{
  name: "Boss Phase - Void Rift",
  description: "A void pulls enemies in until they vanish for 10 seconds.",
  func: () => {
    displayMessage("Boss opens a Void Rift!", 3);

    const rift = document.createElement('div');
    Object.assign(rift.style, {
      position: 'absolute',
      width: '200px',
      height: '200px',
      borderRadius: '50%',
      left: (playerPositionX + player.offsetWidth / 2 - 100) + 'px',
      bottom: (playerPositionY + player.offsetHeight / 2 - 100) + 'px',
      background: 'radial-gradient(circle, black, transparent 75%)',
      boxShadow: '0 0 50px 30px black inset',
      zIndex: 21000,
      pointerEvents: 'none'
    });
    gameWorld.appendChild(rift);

    const pull = setInterval(() => {
      enemies.forEach(enemy => {
        const ex = parseInt(enemy.style.left);
        const ey = parseInt(enemy.style.bottom);
        const dx = playerPositionX + player.offsetWidth/2 - ex;
        const dy = playerPositionY + player.offsetHeight/2 - ey;
        const dist = Math.hypot(dx, dy);
        if(dist < 200){
          enemy.style.left = `${ex + dx * 0.22}px`;
          enemy.style.bottom = `${ey + dy *0.22}px`;
          if(dist < 50) {
            createBurst(ex, ey);
            enemy.remove();
            enemies = enemies.filter(e => e !== enemy);
            log("Enemy swallowed by Void Rift!");
          }
        }
      });
    }, 40);

    setTimeout(() => {
      clearInterval(pull);
      rift.remove();
      displayMessage("The Void Rift closes!", 3);
      log("Boss Void Rift ended!");
    }, 10000);
  }
},

  {
    name: "Rainbow Slash",
    description: "Player does a wide rainbow slash clearing enemies in a big arc.",
    func: () => {
      const arc = document.createElement('div');
      Object.assign(arc.style, {
        position: 'absolute',
        width: '180px',
        height: '80px',
        borderRadius: '80% / 100%',
        left: (playerPositionX - 80) + 'px',
        bottom: (playerPositionY + player.offsetHeight / 2 - 30) + 'px',
        background: "conic-gradient(red, orange, yellow, green, blue, indigo, violet, red)",
        opacity: 0.75,
        pointerEvents: 'none',
        zIndex: 16000,
      });
      gameWorld.appendChild(arc);

      arc.animate([
        { transform: 'scale(1)', opacity: 0.75 },
        { transform: 'scale(1.5)', opacity: 0 }
      ], { duration: 900, easing: 'ease-out' });

      enemies.forEach((enemy, idx) => {
        if (checkCollision(arc, enemy)) {
          createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
          enemy.remove();
          enemies.splice(idx, 1);
          log("Enemy obliterated by Rainbow Slash!");
        }
      });

      setTimeout(() => arc.remove(), 900);
      log("Rainbow Slash activated!");
    }
  },

  /** 132. Magnetic Grasp */
  {
    name: "Magnetic Grasp",
    description: "Pulls all picks and enemies close to player for 7 seconds.",
    func: () => {
      const range = 220;
      const duration = 7000;
      const interval = setInterval(() => {
        [...coins, ...powerUps, ...enemies].forEach(obj => {
          const ox = parseFloat(obj.style.left);
          const oy = parseFloat(obj.style.bottom);
          obj.style.left = ox + (playerPositionX - ox) * 0.15 + 'px';
          obj.style.bottom = oy + (playerPositionY - oy) * 0.15 + 'px';
        });
      }, 33);

      setTimeout(() => {
        clearInterval(interval);
        log("Magnetic Grasp ended!");
      }, duration);
      log("Magnetic Grasp started!");
    }
  },

  /** 133. Jet Propulsion Dash */
  {
    name: "Jet Propulsion Dash",
    description: "Player dashes 350px while leaving fire behind damaging enemies.",
    func: async () => {
      player.classList.add('glow');
      const trail = [];

      const dashDistance = 350;
      let moved = 0;
      const speed = 27;

      const dash = setInterval(() => {
        if(moved > dashDistance){
          clearInterval(dash);
          player.classList.remove('glow');
          trail.forEach(t => t.remove());
          log("Jet Propulsion Dash ended!");
          return;
        }

        playerPositionX = Math.min(playerPositionX + speed, gameWorld.offsetWidth - player.offsetWidth);
        player.style.left = playerPositionX + 'px';

        const flame = document.createElement('div');
        Object.assign(flame.style, {
          position: 'absolute',
          width: '15px',
          height: '40px',
          borderRadius: '10px',
          background: 'linear-gradient(180deg, #ff6600, #330000)',
          opacity: '0.75',
          left: (playerPositionX - 20) + 'px',
          bottom: playerPositionY + 'px',
          zIndex: 14000,
          pointerEvents: 'none',
          filter: 'blur(3px)'
        });
        gameWorld.appendChild(flame);
        trail.push(flame);
        setTimeout(() => {
          flame.remove();
          trail.splice(trail.indexOf(flame), 1);
        }, 500);

        enemies.forEach((enemy, idx) => {
          if (checkCollision(enemy, flame)) {
            applyBurn(enemy);
          }
        });

        moved += speed;
      }, 35);
      log("Jet Propulsion Dash started!");
    }
  },

  /** 134. Electric Net Trap */
  {
    name: "Electric Net Trap",
    description: "Spawns an electric net that traps and stuns enemies for 6 seconds.",
    func: () => {
      const net = document.createElement('div');
      Object.assign(net.style, {
        position: 'absolute',
        width: '180px',
        height: '180px',
        borderRadius: '20px',
        background: 'radial-gradient(circle, rgba(0,255,255,0.3), transparent 90%)',
        border: '4px solid cyan',
        boxShadow: '0 0 25px 12px cyan inset',
        left: (playerPositionX - 75) + 'px',
        bottom: (playerPositionY - 75) + 'px',
        zIndex: 10500,
        pointerEvents: 'none'
      });
      gameWorld.appendChild(net);

      enemies.forEach(enemy => {
        if (checkCollision(net, enemy)) {
          enemy.classList.add('frozen-enemy');
          enemy.style.opacity = '0.3';
        }
      });

      setTimeout(() => {
        enemies.forEach(enemy => {
          enemy.classList.remove('frozen-enemy');
          enemy.style.opacity = '1';
        });
        net.remove();
        log("Electric Net Trap expired!");
      }, 6000);

      log("Electric Net Trap deployed!");
    }
  },

  /** 135. Plasma Chain Lightning */
  {
    name: "Plasma Chain Lightning",
    description: "Chains electric bolts among multiple enemies damaging and stunning.",
    func: () => {
      if (enemies.length === 0) {
        log('No enemies to chain lightning!');
        return;
      }

      const hitEnemies = new Set();

      function chain(toEnemy, remainingChains) {
        if (!toEnemy || hitEnemies.has(toEnemy) || remainingChains <= 0) return;

        hitEnemies.add(toEnemy);
        const flash = document.createElement('div');
        Object.assign(flash.style, {
          position: 'absolute',
          left: toEnemy.style.left,
          bottom: toEnemy.style.bottom,
          width: '30px',
          height: '30px',
          borderRadius: '50%',
          boxShadow: '0 0 40px 18px cyan inset',
          pointerEvents: 'none',
          zIndex: 15000
        });
        gameWorld.appendChild(flash);
        setTimeout(() => flash.remove(), 350);

        createBurst(parseInt(toEnemy.style.left), parseInt(toEnemy.style.bottom));
        toEnemy.remove();
        enemies = enemies.filter(e => e !== toEnemy);
        log("Enemy zapped by Plasma Chain!");

        // Find nearest unhit enemy within 160 px
        const near = enemies
          .filter(e => !hitEnemies.has(e))
          .sort((a, b) => {
            const dxA = parseInt(a.style.left) - parseInt(toEnemy.style.left);
            const dyA = parseInt(a.style.bottom) - parseInt(toEnemy.style.bottom);
            const dxB = parseInt(b.style.left) - parseInt(toEnemy.style.left);
            const dyB = parseInt(b.style.bottom) - parseInt(toEnemy.style.bottom);
            return Math.sqrt(dxA*dxA + dyA*dyA) - Math.sqrt(dxB*dxB + dyB*dyB);
          })[0];

        setTimeout(() => chain(near, remainingChains - 1), 350);
      }

      chain(enemies[Math.floor(Math.random() * enemies.length)], 6);
      log("Plasma Chain Lightning initiated!");
    }
  },

  /** 136. Holo Decoy */
  {
    name: "Holo Decoy",
    description: "Player creates a holographic decoy that distracts enemies for 9 seconds.",
    func: () => {
      const decoy = document.createElement('div');
      const startLeft = playerPositionX + 100;
      const startBottom = playerPositionY;
      Object.assign(decoy.style, {
        position: 'absolute',
        left: startLeft + 'px',
        bottom: startBottom + 'px',
        width: player.offsetWidth + 'px',
        height: player.offsetHeight + 'px',
        borderRadius: '50%',
        backgroundColor: 'rgba(100,100,255,0.4)',
        border: '2px dashed blue',
        filter: 'blur(1.8px)',
        zIndex: 12200,
      });
      gameWorld.appendChild(decoy);

      let direction = 1;
      const interval = setInterval(() => {
        if(!decoy.parentElement) {
          clearInterval(interval);
          return;
        }
        let x = parseFloat(decoy.style.left);
        x += direction * 3;
        if(x < startLeft - 60 || x > startLeft + 60) direction = -direction;
        decoy.style.left = x + 'px';

        enemies.forEach((enemy, idx) => {
          if(checkCollision(enemy, decoy)) {
            createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            enemy.remove();
            enemies.splice(idx, 1);
            log("Enemy distracted by Holo Decoy!");
          }
        });
      }, 40);

      setTimeout(() => {
        clearInterval(interval);
        decoy.remove();
        log("Holo Decoy expired!");
      }, 9000);

      log("Holo Decoy deployed!");
    }
  },

  /** 137. Fireball Volley */
  {
    name: "Fireball Volley",
    description: "Launch 20 fireballs in rapid succession forward.",
    func: () => {
      let fired = 0;
      const total = 20;

      const fireballInterval = setInterval(() => {
        shootFire();
        fired++;
        if(fired >= total) {
          clearInterval(fireballInterval);
          log("Fireball Volley ended!");
        }
      }, 150);

      log("Fireball Volley started!");
    }
  },


];





// Usage:


// Add the new fun functions to the existing list


function updatePageInfo() {
  const totalPages = Math.ceil(filteredClasses.length / elementsPerPage);
  pageInfoSpan.textContent = `Page ${currentElementPage + 1} / ${totalPages || 1}`;
  prevBtn.disabled = currentElementPage === 0;
  nextBtn.disabled = currentElementPage >= totalPages - 1;
}

// Handlers for prev/next buttons in element list pagination

nextBtn.onclick = () => {
  const totalPages = Math.ceil(filteredClasses.length / elementsPerPage);
  if (currentElementPage < totalPages - 1) {
    currentElementPage++;
    displayElementList();
  }
};

spawnOffsetSlider.addEventListener('input', () => {
  spawnOffset = parseInt(spawnOffsetSlider.value, 10);
  spawnOffsetValueDisplay.textContent = spawnOffset;
});

// Filter elements on search input change
searchInput.oninput = () => {
  const searchTerm = searchInput.value.trim().toLowerCase();
  if (searchTerm) {
    filteredClasses = allCssClasses.filter(c => c.toLowerCase().includes(searchTerm));
  } else {
    filteredClasses = allCssClasses;
  }
  currentElementPage = 0;
  selectedElementClass = null;
  spawnElementBtn.disabled = true;
  previewContainer.innerHTML = '<em>Select element to preview</em>';
  displayElementList();
};


  const powerUpClasses = [
    "super-speed", "invincibility", "teleportation",
    "reflective-shield", "double-shot", "extra-life",
    "score-boost", "mega-jump", "energy-blast", "light-speed",
    "blazing-trail", "sonic-wave", "armor", "telekinetic",
    "camouflage", "dimension-shift", "energy-drain", "mind-control",
    "hologram", "fire", "ice", "hypno"
  ];


function updateFunCooldownUI() {
  const now = Date.now();
  const cooldownDiv = document.getElementById('fun-cooldown-message');
  const buttons = document.querySelectorAll('#fun-functions-list button');

  // Use 1000 (milliseconds) for 1-second cooldown check instead of 100
  const timeSinceLastCall = (now - lastFunCallTime) / 1000; // Corrected to divide by 1000 for seconds

  if (timeSinceLastCall < funCooldownSecs) {
    const secondsLeft = Math.ceil(funCooldownSecs - timeSinceLastCall);
    cooldownDiv.textContent = `Cooldown: Please wait ${secondsLeft} second${secondsLeft !== 1 ? 's' : ''} before next function call.`;
    buttons.forEach(btn => btn.disabled = true);
  } else {
    cooldownDiv.textContent = 'You can call a fun function!';
    buttons.forEach(btn => btn.disabled = false);
  }
}

function renderFilteredFunFunctions(filterText = '') {
  const filter = filterText.trim().toLowerCase();
  funFunctionsListDiv.innerHTML = '';
  const filtered = funFunctions.filter(f => f.name.toLowerCase().includes(filter) || (f.description && f.description.toLowerCase().includes(filter)));
  if (filtered.length === 0) {
    funFunctionsListDiv.innerHTML = '<em>No fun functions match your search.</em>';
    return;
  }
  filtered.forEach((f, idx) => {
    const btn = document.createElement('button');
    btn.textContent = f.name;
    btn.title = f.description || '';
    btn.style.padding = '8px 12px';
    btn.style.cursor = 'pointer';
    btn.style.width = '100%';
    btn.style.textAlign = 'left';

    btn.onclick = () => {
      f.func();
    };

    funFunctionsListDiv.appendChild(btn);
  });
}

// Initially render full list
renderFilteredFunFunctions();

// Search input event
funSearchInput.addEventListener('input', e => {
  renderFilteredFunFunctions(e.target.value);
});

// Build and render function buttons list
function renderFunFunctions() {
  const container = document.getElementById('fun-functions-list');

  // Create search input if it doesn't exist yet
  let searchInput = document.getElementById('fun-functions-search');
  if (!searchInput) {
    searchInput = document.createElement('input');
    searchInput.id = 'fun-functions-search';
    searchInput.type = 'search';
    searchInput.placeholder = 'Search fun functions...';
    searchInput.style.width = '100%';
    searchInput.style.marginBottom = '12px';
    searchInput.style.padding = '6px';
    searchInput.style.fontSize = '14px';
    container.parentNode.insertBefore(searchInput, container);

    // Re-render buttons as user types
    searchInput.addEventListener('input', () => {
      renderFunFunctions();
    });
  }

  const filterText = searchInput.value.trim().toLowerCase();

  container.innerHTML = ''; // Clear previous buttons

  // Filter functions by search term in name or description
  const filteredFun = filterText === '' 
    ? funFunctions 
    : funFunctions.filter(f => 
        f.name.toLowerCase().includes(filterText) || (f.description && f.description.toLowerCase().includes(filterText))
      );

  if (filteredFun.length === 0) {
    container.innerHTML = '<em>No fun functions match your search.</em>';
    return;
  }

  filteredFun.forEach(f => {
    const btn = document.createElement('button');
    btn.textContent = f.name;
    btn.title = f.description;
    btn.style.padding = '8px 12px';
    btn.style.cursor = 'pointer';

    btn.onclick = () => {
      const now = Date.now();
      if (now - lastFunCallTime < funCooldownSecs * 1000) {
        // Still cooling down - ignore click
        return;
      }
      try {
        f.func();
      } catch (err) {
        log(`Error running function ${f.name}: ${err}`);
      }
      lastFunCallTime = now;
      updateFunCooldownUI();
    };

    container.appendChild(btn);
  });

  // Initial cooldown UI update
  updateFunCooldownUI();

  // Run cooldown UI updates every second, only once
  if (!renderFunFunctions._cooldownIntervalId) {
    renderFunFunctions._cooldownIntervalId = setInterval(updateFunCooldownUI, 1000);
  }
}


  // Create preview element for selected class
function showElementPreview(cssClass) {
  previewContainer.innerHTML = '';
  if (!cssClass) {
    previewContainer.innerHTML = '<em>Select element to preview</em>';
    return;
  }
  const previewEl = document.createElement('div');
  previewEl.className = cssClass;
  previewEl.textContent = cssClass;
  previewEl.style.margin = 'auto';
  previewEl.style.width = '100px';
  previewEl.style.height = '100px';
  previewEl.style.position = 'relative';
  previewEl.style.display = 'flex';
  previewEl.style.justifyContent = 'center';
  previewEl.style.alignItems = 'center';
  previewEl.style.backgroundColor = 'rgba(0,255,255,0.1)';
  previewContainer.appendChild(previewEl);

  // Try to detect any CSS animation and run it (optional)
  const computed = window.getComputedStyle(previewEl);
  const animationName = computed.animationName || computed.webkitAnimationName;
  if (animationName && animationName !== 'none') {
    previewEl.style.animationPlayState = 'running';
  }
}

// Spawn one element with the selected class near player position on clicking spawn button
spawnElementBtn.onclick = () => {
  if (!selectedElementClass) return;

  let el;
  const spawnX = playerPositionX + spawnOffset;

  if (allPowerUpTypes.includes(selectedElementClass)) {
    el = spawnPowerUpOfType(selectedElementClass, spawnOffset);
    log(`Spawned power-up: ${selectedElementClass} at +${spawnOffset}px`);
  } else {
    el = document.createElement('div');
    el.className = selectedElementClass;
    el.style.position = 'absolute';
    el.style.left = spawnX + 'px';
    el.style.bottom = '0px';
    gameWorld.appendChild(el);

    const enemyClasses = [
      "enemy", "flying-enemy", "charging-enemy", "split-enemy", "laser-enemy",
      "sniper-enemy", "reflective-enemy", "velocity-enemy", "sticky-enemy",
      "teleporter-enemy", "mourning-enemy", "virus-drone"
    ];

    if (enemyClasses.includes(selectedElementClass)) {
      enemies.push(el);
    } else if (selectedElementClass === 'boss') {
      boss = el; // Assign global boss reference
      boss.style.bottom = '100px'; // Adjust position
    } else if (selectedElementClass === 'obstacle') {
      obstacles.push(el);
    } else if (selectedElementClass === 'platform') {
      platforms.push(el);
    } else if (selectedElementClass === 'power-up') {
      powerUps.push(el);
    } else if (selectedElementClass === 'coin') {
      coins.push(el);
    }

    log(`Spawned element: ${selectedElementClass} at x=${spawnX}`);
  }

  el.style.outline = '2px solid cyan';
  setTimeout(() => {
    if (el) el.style.outline = '';
  }, 1500);

  // Undo/Redo stack
  if (typeof spawnedElementsStack !== 'undefined') {
    spawnedElementsStack.push(el);
    if (typeof redoStack !== 'undefined') redoStack.length = 0;
    if (typeof updateUndoRedoButtons === 'function') updateUndoRedoButtons();
  }
};

  // --- Character Modifiers Tab functions ---

  function updatePlayerColor(color) {
    player.style.backgroundColor = color;
  }
  playerColorInput.oninput = (e) => {
    updatePlayerColor(e.target.value);
  };

gravitySlider.oninput = e => {
  gravity = parseFloat(e.target.value);
  gravityValue.textContent = gravity.toFixed(2);
};

playerSpeedSlider.oninput = e => {
  playerMaxSpeed = parseFloat(e.target.value);
  playerSpeedValue.textContent = playerMaxSpeed.toFixed(2);
};

bulletSpeedSlider.oninput = e => {
  bulletSpeed = parseFloat(e.target.value);
  bulletSpeedValue.textContent = bulletSpeed.toFixed(2);
};

  // Initialize values from existing variables (if set)
  playerColorInput.value = window.getComputedStyle(player).backgroundColor || '#4CAF50';
  if (window.gravity !== undefined) gravitySlider.value = window.gravity;
  else gravitySlider.value = 0.5;
  gravityValue.textContent = gravitySlider.value;

  if (window.playerMaxSpeed !== undefined) playerSpeedSlider.value = window.playerMaxSpeed;
  else playerSpeedSlider.value = 5;
  playerSpeedValue.textContent = playerSpeedSlider.value;

  if (window.bulletSpeed !== undefined) bulletSpeedSlider.value = window.bulletSpeed;
  else bulletSpeedSlider.value = 5;
  bulletSpeedValue.textContent = bulletSpeedSlider.value;

  // --- Map Modifier Tab functions ---

  bgColorInput.oninput = e => {
    gameContainer.style.backgroundColor = e.target.value;
  };

  function toggleVisibility(collection, visible) {
    collection.forEach(el => {
      el.style.display = visible ? '' : 'none';
    });
  }

  togglePlatforms.onchange = e => {
    toggleVisibility(platforms, e.target.checked);
  };
  toggleObstacles.onchange = e => {
    toggleVisibility(obstacles, e.target.checked);
  };
  toggleEnemies.onchange = e => {
    toggleVisibility(enemies, e.target.checked);
  };
  togglePowerups.onchange = e => {
    toggleVisibility(powerUps, e.target.checked);
  };
  toggleCoins.onchange = e => {
    toggleVisibility(coins, e.target.checked);
  };

  // --- Experiment Mode and Settings tab ---

  // Experiment Mode: freezes enemies (pauses their movement / removes from move list)
  // Stores original functions and disables updates for enemies

// Undo button removes last spawned element
undoBtn.addEventListener('click', () => {
  if (spawnedElementsStack.length === 0) return;

  const lastEl = spawnedElementsStack.pop();
  if (lastEl) {
    lastEl.remove();
    redoStack.push(lastEl);
    log(`Undo spawn`);
  }
  updateUndoRedoButtons();
});

// Redo button restores last undone spawn
redoBtn.addEventListener('click', () => {
  if (redoStack.length === 0) return;

  const el = redoStack.pop();
  if (el) {
    gameWorld.appendChild(el);
    spawnedElementsStack.push(el);
    log(`Redo spawn`);
  }
  updateUndoRedoButtons();
});

// Enable/disable Undo/Redo buttons based on stacks
function updateUndoRedoButtons() {
  undoBtn.disabled = spawnedElementsStack.length === 0;
  redoBtn.disabled = redoStack.length === 0;
}


function spawnPowerUpOfType(type, offset = 200) {
  const powerUp = document.createElement('div');
  powerUp.classList.add('power-up');
  powerUp.setAttribute('data-type', type);
  powerUp.style.backgroundColor = getPowerUpColor(type);
  powerUp.style.position = 'absolute';
  powerUp.style.left = (playerPositionX + offset) + 'px';
  powerUp.style.bottom = (Math.floor(Math.random() * 100) + 50) + 'px';
  gameWorld.appendChild(powerUp);
  powerUps.push(powerUp);
  return powerUp;
}

  function freezeEnemies() {
    enemies.forEach(enemy => {
      if (!enemy.classList.contains('sandbox-frozen')) {
        enemy.classList.add('sandbox-frozen');
        frozenEnemyPositions.set(enemy, {left: enemy.style.left, bottom: enemy.style.bottom});
        enemy.style.transition = 'none';
        // Freeze by flag; we do not call movement on frozen enemies (modify your game loop to respect if you add that)
      }
    });
  }
  function unfreezeEnemies() {
    enemies.forEach(enemy => {
      enemy.classList.remove('sandbox-frozen');
    });
    frozenEnemyPositions.clear();
  }

  experimentModeCheckbox.onchange = e => {
    experimentModeEnabled = e.target.checked;
    if (experimentModeEnabled) {
      freezeEnemies();
      experimentControls.style.display = 'block';
      log("Experiment Mode Enabled: Enemies frozen.");
    } else {
      unfreezeEnemies();
      experimentControls.style.display = 'none';
      selectedEnemy = null;
      selectedEnemyInfoSpan.textContent = 'None';
      log("Experiment Mode Disabled: Enemies unfrozen.");
    }
  };

  unfreezeEnemiesBtn.onclick = () => {
    unfreezeEnemies();
    experimentModeCheckbox.checked = false;
    experimentControls.style.display = 'none';
    selectedEnemy = null;
    selectedEnemyInfoSpan.textContent = 'None';
    log("Unfroze all enemies through Experiment Control.");
  };

  // Map Modifier tab enhancement: select enemy by click for movement in experiment mode
  toggleEnemies.parentElement.addEventListener('click', (ev) => {
    if(!experimentModeEnabled) return;
    if(ev.target.tagName.toLowerCase() === 'input') return; // ignore checkbox clicks

    // Reset any existing highlights
    enemies.forEach(en => {
      en.style.outline = '';
    });

    if (enemies.length === 0) {
      selectedEnemy = null;
      selectedEnemyInfoSpan.textContent = 'None';
      return;
    }

    // Select the first enemy visible, or improve this by popup list if you want
    // For demo: select random visible enemy
    const visibleEnemies = enemies.filter(en => en.style.display !== 'none');
    if (visibleEnemies.length === 0) return;
    selectedEnemy = visibleEnemies[0];
    selectedEnemy.style.outline = '2px solid magenta';
    selectedEnemyInfoSpan.textContent = `Class: ${selectedEnemy.className}`;
  });

  // Movement buttons for selected enemy
  enemyMoveButtons.forEach(btn => {
    btn.onclick = () => {
      if (!selectedEnemy) return;
      let leftPx = parseInt(selectedEnemy.style.left) || 0;
      let bottomPx = parseInt(selectedEnemy.style.bottom) || 0;

      switch(btn.dataset.dir) {
        case 'up': bottomPx += 10; break;
        case 'down': bottomPx = Math.max(0, bottomPx - 10); break;
        case 'left': leftPx = Math.max(0, leftPx - 10); break;
        case 'right': leftPx += 10; break;
      }
      selectedEnemy.style.left = leftPx + 'px';
      selectedEnemy.style.bottom = bottomPx + 'px';
      log(`Moved selected enemy ${btn.dataset.dir} to (left:${leftPx}px, bottom:${bottomPx}px)`);
    };
  });

  // --- Logs window ---

  function log(msg) {
    // Time stamp + message
    const time = new Date().toLocaleTimeString();
    logsContent.textContent += `[${time}] ${msg}\n`;
    logsContent.scrollTop = logsContent.scrollHeight;
  }
  clearLogsBtn.onclick = () => {
    logsContent.textContent = '';
  };

  enableLogsCheckbox.onchange = e => {
    if (e.target.checked) {
      logsWindow.style.display = 'block';
      log('Logs window enabled');
    } else {
      logsWindow.style.display = 'none';
    }
  };


  // --- Initialize data WHEN sandbox mode is started ---

  function startSandboxMode() {
    // Show sandbox GUI
    gui.style.display = 'flex';
    localStorage.setItem('gameMode', 'sandbox');
    // Reset inputs to current values (optional)
    playerColorInput.value = rgbToHex(
      window.getComputedStyle(player).backgroundColor || '#4CAF50'
    );
    gravitySlider.value = window.gravity !== undefined ? window.gravity : 0.5;
    gravityValue.textContent = gravitySlider.value;
    playerSpeedSlider.value = window.playerMaxSpeed !== undefined ? window.playerMaxSpeed : 5;
    playerSpeedValue.textContent = playerSpeedSlider.value;
    bulletSpeedSlider.value = window.bulletSpeed !== undefined ? window.bulletSpeed : 5;
    bulletSpeedValue.textContent = bulletSpeedSlider.value;
    bgColorInput.value = rgbToHex(window.getComputedStyle(gameContainer).backgroundColor || '#333333');

    togglePlatforms.checked = platforms.every(el => el.style.display !== 'none');
    toggleObstacles.checked = obstacles.every(el => el.style.display !== 'none');
    toggleEnemies.checked = enemies.every(el => el.style.display !== 'none');
    togglePowerups.checked = powerUps.every(el => el.style.display !== 'none');
    toggleCoins.checked = coins.every(el => el.style.display !== 'none');

// Only run this in sandbox mode (optional guard)
if (localStorage.getItem('gameMode') === 'sandbox') {
  const livesInput = document.getElementById('lives-input');
  const scoreInput = document.getElementById('score-input');

  // Initialize inputs with current values
  livesInput.value = lives;
  scoreInput.value = score;

  // Update display function for consistency
  function updateSandboxDisplay() {
    livesDisplay.textContent = `Lives: ${lives}`;
    scoreDisplay.textContent = `Score: ${score}`;    
  }

  // On input change, update lives variable and update display
  livesInput.addEventListener('input', () => {
    let newLives = parseInt(livesInput.value, 10);
    if (isNaN(newLives) || newLives < 0) newLives = 0;
    if (newLives > 99) newLives = 99;
    lives = newLives;
    updateSandboxDisplay();
  });

  // On input change, update score variable and display
  scoreInput.addEventListener('input', () => {
    let newScore = parseInt(scoreInput.value, 10);
    if (isNaN(newScore) || newScore < 0) newScore = 0;
    score = newScore;
    updateSandboxDisplay();
  });

  // Make sure display at start correct
  updateSandboxDisplay();
}

    // Extract & show all CSS classes initially
    allCssClasses = extractAllCssClasses();
    filteredClasses = allCssClasses;
    currentElementPage = 0;
    selectedElementClass = null;
    spawnElementBtn.disabled = true;
    searchInput.value = '';
    displayElementList();
    renderFunFunctions();
    clearAllElements();
    playerPositionX = 50;
    playerPositionY = 0;
    player.style.left = playerPositionX + 'px';
    player.style.bottom = playerPositionY + 'px';

    score = 0;
    lives = 3;
    level = 1;
    updateDisplay();
    startGame();
    gui.style.left = '';
    gui.style.top = '';
    gui.style.right = '20px';
    gui.style.bottom = '';

    if (gameInterval) clearInterval(gameInterval);
    gameInterval = setInterval(gameLoop, 1000 / 60);

    log('Sandbox Mode activated');

    // Ensure sandbox doesn't auto-close when starting for testing
  }

  // Utility: convert rgb/rgba string to hex color for input[type=color]
  function rgbToHex(rgb) {
    const m = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
    if (!m) return '#000000';
    return "#" + ((1 << 24) + (parseInt(m[1]) << 16) + (parseInt(m[2]) << 8) + parseInt(m[3])).toString(16).slice(1);
  }

  // Hide sandbox GUI initially (until mode started)
  gui.style.display = 'none';

  // Expose startSandboxMode globally for your "Sandbox Mode" button
  window.startSandboxMode = startSandboxMode;

  // Optional: you can auto-enable sandbox for testing now:
  //startSandboxMode();

  // --- DONE SETUP ---
 

            window.addEventListener('keydown', handleKeydown);
            window.addEventListener('keyup', handleKeyup);


const upgrades = [
    { name: 'Super Speed', price: 4500, effect: 'Increase speed by 10%', id: 'speedBoost' },
    { name: 'Super bullet', price: 1200, effect: 'Faster bullet speed', id: 'doubleDamage' },
    { name: 'Double jump', price: 7500, effect: 'Double jump', id: 'doubleJump' },
    { name: 'Extra Lives', price: 2500, effect: 'Gain 3 extra lives', id: 'ExtraLives' }, // Add this line for Extra Lives
    // Add more upgrades as needed
];

function getCssClasses() {
    const classes = new Set();
    for (const sheet of document.styleSheets) {
        try {
            if (!sheet.cssRules) continue; // skip if no rules available
            for (const rule of sheet.cssRules) {
                if (rule.selectorText) {
                    const selectors = rule.selectorText.split(/\s*,\s*/);
                    selectors.forEach(selector => {
                        // Match class names in selectors (e.g. ".enemy", ".split-enemy", ".boss-door")
                        const matches = selector.match(/\.(\w[\w-]*)/g);
                        if (matches) {
                            matches.forEach(cls => classes.add(cls.substring(1)));
                        }
                    });
                }
            }
        } catch (e) {
            // Ignore CORS protected stylesheets
        }
    }
    return Array.from(classes).sort();
}

// Render elements with search and preview support


function showEndlessModeButton() {
    const endlessBtn = document.getElementById('endless-mode-btn');
    if (endlessBtn) {
        endlessBtn.style.display = 'inline-block';
        endlessBtn.disabled = false;
    }
}

function showSandboxModeButton() {
    const sandboxBtn = document.getElementById('sandbox-mode-btn');
    if (sandboxBtn) {
        sandboxBtn.style.display = 'inline-block';
        sandboxBtn.disabled = false;
    }
}

// Function to select an upgrade
// Function to select the current upgrade
function selectUpgrade(index) {
    selectedUpgrade = upgrades[index]; // Select the upgrade at the given index
}

function updateShopScoreDisplay() {
    const shopScoreDisplay = document.getElementById('shop-score');
    shopScoreDisplay.textContent = `Shop Score: ${playerScore}`; // Display the total amount
}

// Function to display current selected upgrade details
function displaySelectedUpgrade() {
    const upgradeInfo = document.getElementById("upgrade-list");
    upgradeInfo.innerHTML += `<br><strong>Selected Upgrade:</strong><br>
        ${selectedUpgrade.name}<br>
        Price: ${selectedUpgrade.price}<br>
        Effect: ${selectedUpgrade.effect}<br>`;
}

// Declare the selectedUpgrade at the top
let selectedUpgrade = null;
let currentUpgradeIndex = 0; // Keep track of the currently selected upgrade

// Function to open upgrades
function openUpgrades() {
    document.getElementById("instructions").style.display = "none"; // Hide main menu
    document.getElementById("upgrades-menu").style.display = "block"; // Show upgrades menu
    displayUpgradeOptions(); // Display available upgrades
    selectUpgrade(currentUpgradeIndex); // Start with first upgrade selected
}

function closeUpgrades() {
    document.getElementById("upgrades-menu").style.display = "none"; // Hide upgrades menu
    document.getElementById("instructions").style.display = "flex"; // Show main menu again
}

// Function to buy the selected upgrade
// Function to buy the selected upgrade
// Function to buy the selected upgrade

        function showGameModeOptions() {
            document.getElementById('instructions').style.display = 'none'; // Hide start button
            document.getElementById('game-mode-options').style.display = 'block'; // Show game mode options
        }

        // Function to show level options for Endless Mode
        function showLevelOptions() {
            document.getElementById('game-mode-options').style.display = 'none'; // Hide game mode options
            document.getElementById('level-options').style.display = 'block'; // Show level buttons
        }




function startEndlessMode(chosenLevel) {
    console.log('Endless Mode Selected for Level:', chosenLevel); // Debug log
        document.getElementById('level-options').style.display = 'none'; // Hide level options
    // Set the game mode to Endless
    localStorage.setItem('gameMode', 'endless'); // This sets the gameMode in local storage
    isEndlessMode = true; // Indicate that we are now in endless mode
    currentEndlessLevel = chosenLevel; // Set the chosen level for this session
    
    localStorage.setItem('endlessLevel', currentEndlessLevel); // Save the selected level to local storage

    resetGame(); // Reset your game state

    switchLevelBackground(); // Set the correct background according to currentEndlessLevel

    spawnEndlessEntities(); // Spawn enemies based on the current endless level

checkCollisionWithPlatformsAndObstacles();

    gameInterval = setInterval(gameLoop, 1000 / 60); // Start the game loop    
}

// Ensure the currentEndlessLevel is used in your functions where needed, 
// for instance in the game loop or resetGame function if appropriate
window.addEventListener('load', () => {
    loadEquippedUpgrades();

    const endlessUnlocked = localStorage.getItem('endlessModeUnlocked') === 'true';

    const sandboxBtn = document.getElementById('sandbox-mode-btn');

    const sandboxUnlocked = localStorage.getItem('sandboxModeUnlocked') === 'true';

    const endlessBtn = document.getElementById('endless-mode-btn');


    if (endlessUnlocked) {
        // Show endless mode button properly
        if (endlessBtn) {
            endlessBtn.style.display = 'inline-block';  // Show
            endlessBtn.disabled = false;
            endlessBtn.style.visibility = 'visible';
            endlessBtn.removeAttribute('hidden');
        }
    } else {
        // Hide endless mode button initially
        if (endlessBtn) {
            endlessBtn.style.display = 'none';
        }
    }

    if (sandboxUnlocked) {
        // Show endless mode button properly
        if (sandboxBtn) {
            sandboxBtn.style.display = 'inline-block';  // Show
            sandboxBtn.disabled = false;
            sandboxBtn.style.visibility = 'visible';
            sandboxBtn.removeAttribute('hidden');
        }
    } else {
        // Hide endless mode button initially
        if (sandboxBtn) {
            sandboxBtn.style.display = 'none';
        }
    }

    // Reset temp variables - only if you really intend to reset them on load
    currentGameMode = null;
    currentEndlessLevel = null;
});

// Store purchased upgrades separately

// Function to buy and equip/unequip upgrades
function buyUpgrade() {
    const upgrade = upgrades[currentPage]; // Get the currently displayed upgrade
    if (!upgrade) {
        return displayMessage("Please select an upgrade.");
    }

    const score = parseInt(localStorage.getItem('playerScore')) || 0;
    const upgradeIndex = upgradesEquipped.indexOf(upgrade.id);
    const purchasedIndex = upgradesPurchased.indexOf(upgrade.id);

    // If the upgrade is already equipped
    if (upgradeIndex > -1) {
        // Unequip logic
        upgradesEquipped.splice(upgradeIndex, 1);
        removeUpgradeEffects(upgrade); // Remove effects of the unequipped upgrade
        displayMessage(`${upgrade.name} has been unequipped!`);
    } else {
        // If the upgrade is already purchased but not equipped
        if (purchasedIndex > -1) {
            // Just equip the upgrade
            upgradesEquipped.push(upgrade.id);
            applyUpgrade(upgrade); // Apply effects of the newly equipped upgrade
            displayMessage(`${upgrade.name} has been equipped!`);
        } else {
            // Check if the player has enough score to buy the upgrade
            if (score < upgrade.price) {
                return displayMessage("You need more score to buy this upgrade.");
            }

            // Deduct the cost and "purchase" the upgrade
            localStorage.setItem('playerScore', score - upgrade.price);
            upgradesPurchased.push(upgrade.id); // Mark the upgrade as purchased
            upgradesEquipped.push(upgrade.id); // Equip it
            applyUpgrade(upgrade); // Apply effects of the newly equipped upgrade
            displayMessage(`${upgrade.name} has been equipped!`);
        }
    }

    // Save the equipped upgrades and purchased upgrades to local storage
    saveUpgrades();
    
    // Refresh equipped display if needed
    updateEquippedDisplay(); 

    // Update the button text or state accordingly
    updateButtonText(upgrade.id);
}

function loadEquippedUpgrades() {
    const savedUpgradesEquipped = localStorage.getItem('upgradesEquipped');
    if (savedUpgradesEquipped) {
        upgradesEquipped = JSON.parse(savedUpgradesEquipped); // Update contents instead of reassigning with const
        upgradesEquipped.forEach(upgradeId => {
            const upgrade = upgrades.find(up => up.id === upgradeId);
            if (upgrade) {
                applyUpgrade(upgrade); // Apply effects of loaded upgrades
            }
        });
    }

    const savedUpgradesPurchased = localStorage.getItem('upgradesPurchased');
    if (savedUpgradesPurchased) {
        upgradesPurchased = JSON.parse(savedUpgradesPurchased); // Update contents
    }
}

// Function to save the upgrades to local storage
function saveUpgrades() {
    localStorage.setItem('upgradesEquipped', JSON.stringify(upgradesEquipped));
    localStorage.setItem('upgradesPurchased', JSON.stringify(upgradesPurchased));
}

// Function to update the button text based on the equipped state
function updateButtonText(upgradeId) {
    const upgrade = upgrades.find(up => up.id === upgradeId);
    if (upgrade) {
        const button = document.getElementById('upgrade-list'); // Assume the button has this ID
        const isEquipped = upgradesEquipped.indexOf(upgradeId) > -1;
        button.textContent = isEquipped ? "Unequip" : "Buy Upgrade"; 
    }
}

// Function to remove effects when unequipping an upgrade
function removeUpgradeEffects(upgrade) {
    switch (upgrade.id) {
        case 'speedBoost':
            playerMaxSpeed -= 1.5; // Revert speed increase
            break;
        case 'doubleDamage':
            bulletSpeed -= 7;
            break;
        case 'doubleJump':
            maxJumps = 1
            isDoubleJumpEnabled = false; // Enable double jump
            console.log('Double Jump Activated!');
            break;
        case 'ExtraLives': // New case for Extra Lives upgrade
            removeLife();
            console.log('Extra lives granted! Total lives:', lives); // Log the new lives total
            break;
        // Add additional cases for removing effects of new upgrades here
    }
}

function startGamee() {
                localStorage.setItem('gameMode', 'story'); // Set game mode to endless
                startGame();
}

// Function to apply effects of an upgrade
function applyUpgrade(upgrade) {
    switch (upgrade.id) {
        case 'speedBoost':
            playerMaxSpeed += 2; // Increase speed
            break;
        case 'doubleDamage':
            bulletSpeed += 7;
            break;
        case 'doubleJump':
            maxJumps = 2; // Allow an additional jump
            isDoubleJumpEnabled = true; // Enable double jump
            console.log('Double Jump Activated! You can now jump again mid-air.');
            break;
        case 'ExtraLives': // New case for Extra Lives upgrade
            gainExtraLife2();
            console.log('Extra lives granted! Total lives:', lives); // Log the new lives total
            break;
        // Add additional cases for new upgrades here
    }
}

// Function to view equipped upgrades
function viewEquippedUpgrades() {
    const equippedList = document.getElementById("equipped-upgrades");
    
    // Toggle display of the equipped upgrades
    if (equippedList.style.display === "none") {
        equippedList.style.display = "block"; // Show the equipped upgrades
        updateEquippedDisplay(); // Update the display with currently equipped upgrades
    } else {
        equippedList.style.display = "none"; // Hide the equipped upgrades
    }
}

// Function to update the equipped display
function viewEquippedUpgrades() {
    // Open a new blank tab
    const equippedWindow = window.open("", "_blank");
    
    // Create the HTML content for the equipped upgrades
    let equippedContent = '<html><head><title>Equipped Upgrades</title></head><body>';
    equippedContent += '<h3>Equipped Upgrades:</h3>'; // Add header

    if (upgradesEquipped.length === 0) {
        equippedContent += "<p>No upgrades equipped.</p>"; // Message when no upgrades are equipped
    } else {
        upgradesEquipped.forEach(id => {
            const upgrade = upgrades.find(upg => upg.id === id);
            if (upgrade) {
                equippedContent += `
                    <div>
                        <strong>${upgrade.name}</strong><br>
                        Price: ${upgrade.price}<br>
                        Effect: ${upgrade.effect}<br>
                    </div>
                    <hr>
                `;
            }
        });
    }

    equippedContent += '</body></html>'; // Close HTML tags
    
    // Write the content to the new window
    equippedWindow.document.write(equippedContent);
    equippedWindow.document.close(); // Close the document for rendering
}

function updateEquippedDisplay() {
    const equippedList = document.getElementById("equipped-upgrades");
    equippedList.innerHTML = ""; // Clear the current display

    if (upgradesEquipped.length === 0) {
        equippedList.innerHTML = "<p>No upgrades equipped.</p>"; // Handle the case where no upgrades are equipped
    } else {
        upgradesEquipped.forEach(id => {
            const upgrade = upgrades.find(upg => upg.id === id);
            if (upgrade) {
                equippedList.innerHTML += `
                    <div>
                        <strong>${upgrade.name}</strong><br>
                        Price: ${upgrade.price}<br>
                        Effect: ${upgrade.effect}<br>
                    </div>
                    <hr>
                `;
            }
        });
    }
}

if (upgradesEquipped.includes(selectedUpgrade.id)) {
    // Unequip logic
    const index = upgradesEquipped.indexOf(selectedUpgrade.id);
    if (index > -1) upgradesEquipped.splice(index, 1);
    displayMessage(`${selectedUpgrade.name} is now unequipped!`);
} else {
    // Equip logic
    localStorage.setItem('playerScore', score - selectedUpgrade.price);
    upgradesEquipped.push(selectedUpgrade.id);
    displayMessage(`${selectedUpgrade.name} has been equipped!`);
}

// Refresh equipped display
updateEquippedDisplay(); // Call it here to update the UI

function updateNavigationButtons(totalUpgrades) {
    const prevBtn = document.querySelector('#upgrades-menu button[onclick="previousUpgrade()"]');
    const nextBtn = document.querySelector('#upgrades-menu button[onclick="nextUpgrade()"]');
    
    prevBtn.disabled = currentPage === 0; // Disable if on the first page
    nextBtn.disabled = (currentPage + 1) * upgradesPerPage >= totalUpgrades; // Disable if on the last page
}



// Function to display messages to the player
function displayMessage(text, seconds = 3) {
    bossMessageElement.textContent = text; // example
    bossMessageElement.style.display = "block";
    setTimeout(() => {
        bossMessageElement.style.display = "none";
    }, seconds * 1000);
}

function nextUpgrade() {
    if (currentPage < upgrades.length - 1) {
        currentPage++;
        displayUpgradeOptions();
    }
}

function previousUpgrade() {
    if (currentPage > 0) {
        currentPage--;
        displayUpgradeOptions();
    }
}

function displayUpgradeOptions() {
    const upgradeList = document.getElementById("upgrade-list");
    const upgrade = upgrades[currentPage];


    const equipped = upgradesEquipped.includes(upgrade.id) ? " (Equipped)" : ""; // Check if equipped
    upgradeList.innerHTML = `
        <strong>${upgrade.name}</strong>${equipped}<br>
        Price: ${upgrade.price}<br>
        Effect: ${upgrade.effect}<br>
    `;

    // Update navigation buttons
    updateNavigationButtons();
}

 
function handleKeydown(e) {
    switch (e.key) {
        case 'ArrowLeft':
            movingLeft = true;
            currentDirection = -1;
            break;
        case 'ArrowRight':
            movingRight = true;
            currentDirection = 1;
            break;
        case 'ArrowUp':
            handleJump();
            break;
        case ' ': // Space bar for shooting
            if (canShoot) {
                shootBullet(currentDirection);
                canShoot = false;
                setTimeout(() => canShoot = true, 300);
            }
            break;
        case 'z':
        case 'Z': // Power-Up activation
            if (currentPowerUp) { // Check if there is a power-up to use
                usePowerUp();
            } else if (bossPowerObtained) { // Charge if the boss power is obtained and no power-up is active
                isCharging = true;
                chargeTime = 0;
            }
            break;
        case 'e':
        case 'E':
            interact(); // Trigger the interact function when 'E' is pressed
            break;
    }
}
 
function handleKeyup(e) {
    switch (e.key) {
        case 'ArrowLeft':
            movingLeft = false;
            break;
        case 'ArrowRight':
            movingRight = false;
            break;
        case 'z':
        case 'Z':
            if (bossPowerObtained && isCharging) {
                isCharging = false;
                shootLaserBlast(chargeTime);
            }
            break;
    }
}
 
 
function handleJump() {
    if (playerPositionY === 0) { // If the player is on the ground, perform a regular jump
        playerVelocityY = playerJumpStrength; // Apply jump force
        jumpCount = 1; // Set jump count to indicate first jump
        isJumping = true; // Set jumping status to true
    } else if (jumpCount < maxJumps) { // Allow double jump if jump count allows
        doubleJump(); // Call double jump function
    }
}
 
            function nextDialogue() {
                if (dialogueIndex < dialogues.length - 1) {
                    dialogueIndex++;
                    dialoguePara.textContent = dialogues[dialogueIndex];
                } else {
                    intro.style.display = 'none';
                    startGame();
                }
            }





function doubleJump() {
    if (jumpCount < maxJumps) { // Check if the player can still jump
        playerVelocityY = playerJumpStrength; // Apply jump force
        jumpCount++; // Increment the jump count
        isJumping = true; // Set jumping status to true
    }
}
 
            function shootBullet(direction) {
                const bullet = createBullet(direction);
                bullets.push({ element: bullet, direction });
                gameWorld.appendChild(bullet);
 
                if (currentPowerUp === 'double-shot') {
                    const altBullet = createBullet(direction + 1);
                    bullets.push({ element: altBullet, direction });
                    gameWorld.appendChild(altBullet);
                }
 
                if (currentPowerUp === 'speed-bullet') {
                    const sideBullet1 = createBullet(direction + 6);
                    const sideBullet2 = createBullet(direction - 6);
                    bullets.push({ element: sideBullet1, direction });
                    bullets.push({ element: sideBullet2, direction });
                    gameWorld.appendChild(sideBullet1);
                    gameWorld.appendChild(sideBullet2);
                }
            }
 
            function createBurst(x, y) {
                const burst = document.createElement('div');
                burst.classList.add('burst');
                burst.style.left = x + 'px';
                burst.style.bottom = y + 'px';
                gameWorld.appendChild(burst);
                setTimeout(() => burst.remove(), 500);
            }
function moveCamera() {
    const gameMode = localStorage.getItem('gameMode');

    if (gameMode === 'sandbox') {
        // Free camera movement: center on player, clamp to world edges
        let proposedScroll = playerPositionX - (gameContainer.offsetWidth / 2);
        let maxScroll = gameWorld.offsetWidth - gameContainer.offsetWidth;
        if (maxScroll < 0) maxScroll = 0; // Should not happen usually

        // Clamp between 0 and maxScroll for smooth bounds check
        gameScrollPosition = Math.min(Math.max(0, proposedScroll), maxScroll);
    } else {
        // OLD Logic: force camera forward only beyond last max scroll, except in boss door  
        if (!isInBossDoor) {
            let proposedScroll = Math.max(0, playerPositionX - (gameContainer.offsetWidth / 2));

            if (proposedScroll > maxGameScrollPosition) {
                maxGameScrollPosition = proposedScroll;
            }
            gameScrollPosition = maxGameScrollPosition;
        } else {
            // In boss door follows player freely, no restrictions
            gameScrollPosition = Math.max(0, playerPositionX - (gameContainer.offsetWidth / 2));
        }
    }

    // Apply camera transform once
    gameWorld.style.transform = `translateX(${-gameScrollPosition}px)`;
}

// Function to reset player and possibly generate more obstacles
function resetPlayerPosition() {
    playerPositionX = 50; // Reset to starting position
    player.style.left = playerPositionX + 'px'; // Ensure the player is positioned correctly

    // Optionally, regenerate obstacles or enemies here
    regenerateEntities(); // Call a function that generates new obstacles and/or enemies
}

// Function to regenerate entities
function regenerateEntities() {
    // Logic to create and append new obstacles/enemies depending on your game mechanics
    for (let i = 0; i < 5; i++) { // Change the number to spawn desired quantity
        spawnObstacle(); // or spawnEnemy(); as needed
    }
}
 
let summonCooldown = 0;
 
function summonAllies() {
    for (let i = 0; i < 3; i++) {
        let ally = createElement('ally', [], parseInt(player.style.left) + (i * 30));
        ally.style.bottom = player.style.bottom;
        gameWorld.appendChild(ally);
 
        let destroyCount = 0;
        let moveInterval = setInterval(() => {
            ally.style.left = (parseInt(ally.style.left) + 5) + 'px';
 
            enemies.forEach((enemy, index) => {
                if (checkCollision(ally, enemy) && destroyCount < 3) {
                    enemy.remove();
                    enemies.splice(index, 1);
                    destroyCount++;
                }
            });
 
            if (destroyCount >= 3) {
                ally.remove();
                clearInterval(moveInterval);
            }
        }, 50);
 
        setTimeout(() => {
            ally.remove();
            clearInterval(moveInterval);
        }, 5000);
    }
}
 
 
 
function createBulletTrail(x, y) {
    const trail = document.createElement('div');
    trail.classList.add('bullet-trail');
    trail.style.left = x + 'px';
    trail.style.bottom = y + 'px';
    gameWorld.appendChild(trail);
 
    setTimeout(() => {
        trail.style.opacity = '0';
        setTimeout(() => trail.remove(), 300);
    }, 50);
}
 
function moveBullets() {
    bullets.forEach((bulletObj, index) => {
        const bullet = bulletObj.element;
        const bulletDirection = bulletObj.direction;

        // Calculate new position
        const newX = parseInt(bullet.style.left) + (bulletDirection * bulletSpeed);
        bullet.style.left = newX + 'px';

        createBulletTrail(newX, parseInt(bullet.style.bottom));

        // Remove if out of bounds
        if (newX > gameScrollPosition + gameContainer.offsetWidth || newX < 0) {
            bullet.remove();
            bullets.splice(index, 1);
        } else {
            // Check collisions with enemies
            for (let enemyIndex = 0; enemyIndex < enemies.length; enemyIndex++) {
                const enemy = enemies[enemyIndex];
                if (checkCollision(bullet, enemy)) {
                    if (enemy.classList.contains('reflective-enemy')) {
                        // Handle reflective enemy bullet collision
                        handleBulletCollisionWithReflectiveEnemy(enemy, bullet);
                        bullet.remove();
                        bullets.splice(index, 1);
                        break;
                    } else if (enemy.classList.contains('boost-drainer')) {
                        // Handle boost drainer bullet collision
                        if (handleBoostDrainerHit(bulletObj, index)) {
                            // Bullet handled and removed inside handler
                            break;
                        }
                    } else {
                        // Handle other enemy hits
                        handleEnemyHit(enemy, enemyIndex);
                        createBurst(newX, parseInt(bullet.style.bottom));
                        bullet.remove();
                        bullets.splice(index, 1);
                        break;
                    }
                }
            }
            checkBossHit();
        }
    });
}
 
function handleEnemyHit(enemy, enemyIndex) {
    if (enemy.classList.contains('split-enemy')) {
        handleSplitterEnemyHit(enemy, enemyIndex);
    } else if (enemy.classList.contains('infected')) {
        // Existing infected enemy logic...
        let shieldHitsLeft = parseInt(enemy.dataset.shieldHitsLeft) || 0;

        if (shieldHitsLeft > 0) {
            shieldHitsLeft--;
            enemy.dataset.shieldHitsLeft = shieldHitsLeft.toString();

            if (shieldHitsLeft === 0) enemy.classList.remove('shielded');

            enemy.style.opacity = '0.5';
            setTimeout(() => {
                if (enemy) enemy.style.opacity = '0.8';
            }, 150);
            return;
        }

        let health = parseInt(enemy.dataset.health) || 1;
        health--;

        if (health <= 0) {
            enemy.remove();
            enemies.splice(enemyIndex, 1);
        } else {
            enemy.dataset.health = health.toString();
            enemy.style.opacity = '0.5';
            setTimeout(() => {
                if (enemy) enemy.style.opacity = '0.8';
            }, 150);
        }
    } else {
        // Normal enemy - destroy immediately
        enemy.remove();
        enemies.splice(enemyIndex, 1);
    }

    score += 10;
    playerScore += 50;
    localStorage.setItem('playerScore', playerScore);
    updateDisplay();
}
 
function startGame() {
    // Hide game mode options and other screens
    document.getElementById("game-mode-options").style.display = "none";
    gameOverScreen.style.display = 'none';
    instructions.style.display = 'none';

    // Retrieve the game mode from local storage
    const gameMode = localStorage.getItem('gameMode');

    if (gameMode === 'story') {
        // Logic for starting Story Mode
        resetGame(false); // Continue from current Story Mode level
        levelIntro.style.display = 'flex'; // Show level intro for Story Mode
    } else if (gameMode === 'endless') {
        // Logic for starting Endless Mode
        if (!localStorage.getItem('endlessLevel')) {
            localStorage.setItem('endlessLevel', '1'); // Start Endless level at 1 if not set
        }
        resetGame(false); // Continue from last saved Endless level
        levelIntro.style.display = 'flex'; // Show level intro for Endless Mode
    } else if (gameMode === 'sandbox') {
        // Logic for starting Sandbox Mode
        // You can skip level intro or show some sandbox intro if you want
        resetGame(false); // Reset game for fresh sandbox session, or false to continue?
        levelIntro.style.display = 'none'; // Hide level intro; sandbox doesn't need level intro
        clearInterval(gameInterval); // Stop any existing intervals if any
    } else {
        // Default to Story Mode if no mode is set
        localStorage.setItem('gameMode', 'story'); // Default to Story Mode
        localStorage.setItem('storyLevel', '2'); // Set initial level for Story Mode
        resetGame(true); // Start a new game
        levelIntro.style.display = 'flex'; // Show level intro screen
    }
}
 
            function startLevel() {
                levelIntro.style.display = 'none';
                gameInterval = setInterval(gameLoop, 1000 / 60);
            }
 
function resetGame(isNewGame = false) {
    lives = upgradesEquipped.includes('ExtraLives') ? 6 : 3; // Set lives based on the Extra Lives upgrade

    // Reset player state variables
    playerPositionX = 50; 
    playerPositionY = 0; 
    playerVelocityX = 0; 
    playerVelocityY = 0; 
    isJumping = false;
    jumpCount = 0;
    isDoubleJumpEnabled = false; 
    gameScrollPosition = 0; 
    
    clearAllElements(); // Clear all game entities

    // Reset the level based on the game mode.
    const gameMode = localStorage.getItem('gameMode');
    if (gameMode === 'endless') {
        level = localStorage.getItem('endlessLevel') 
                ? parseInt(localStorage.getItem('endlessLevel')) // Retrieve endless level
                : 1; // Start at Level 1 if none found
    } else {
        level = localStorage.getItem('storyLevel') 
                ? parseInt(localStorage.getItem('storyLevel')) 
                : 1; // Default for story mode
    }

    switchLevelBackground(); // Set the background according to the current level

    updateDisplay(); // Reflect updates on the UI
}


 
function updateDisplay() {
    if (isEndlessMode) {
        // For Endless Mode
        levelDisplay.textContent = `Level: ${currentEndlessLevel}`;
    } else {
        // For Story Mode
        levelDisplay.textContent = `Level: ${storyModeLevel}`;
    }
    scoreDisplay.textContent = `Score: ${score}`;
    livesDisplay.textContent = `Lives: ${lives}`;
    timerDisplay.textContent = `Timer: ${powerUpTimer}`;
}
 



function updatePlayerPosition() {
    // Calculate velocity based on input
    if (movingRight) {
        playerVelocityX = playerMaxSpeed;
    } else if (movingLeft) {
        playerVelocityX = -playerMaxSpeed;
    } else {
        playerVelocityX = 0;
    }

    // Tentative new position
  let newPlayerX = playerPositionX + playerVelocityX;

  if (bossFightActive) {
    // Boss room horizontal boundaries (adjust these to fit your boss room)
    const BOSS_ROOM_LEFT = 0;
    const BOSS_ROOM_RIGHT = 1600;  

    // Clamp newPlayerX so player can't go outside boss walls
    newPlayerX = Math.min(Math.max(newPlayerX, BOSS_ROOM_LEFT), BOSS_ROOM_RIGHT);
    
  } else if (!isInBossDoor) {
    // Moving border and player left clamp applied only outside boss door/fight
    let proposedScroll = Math.max(0, newPlayerX - (gameContainer.offsetWidth / 2));

    if (proposedScroll > leftBoundaryX) {
      leftBoundaryX = proposedScroll;
    }

    if (newPlayerX < leftBoundaryX) {
      // Clamp player so they cannot move backward beyond moving border
      newPlayerX = leftBoundaryX;
    }
  }
  
  // Apply the final clamped position
  playerPositionX = newPlayerX;
  player.style.left = playerPositionX + 'px';

    // Jump/gravity logic stays the same...

    let onPlatform = checkCollisionWithPlatformsAndObstacles();

    platforms.forEach(platform => {
        if (checkCollision(player, platform) && playerVelocityY < 0) {
            playerPositionY = parseInt(platform.style.bottom) + platform.offsetHeight;
            playerVelocityY = 0;
            isJumping = false;
            jumpCount = 0;
            onPlatform = true;
        }
    });

    if (!onPlatform || isJumping) {
        playerVelocityY -= gravity;
        playerPositionY += playerVelocityY;

        if (playerPositionY <= 0) {
            playerPositionY = 0;
            playerVelocityY = 0;
            isJumping = false;
            jumpCount = 0;
        }
    } else {
        playerVelocityY = 0;
    }
    player.style.bottom = playerPositionY + 'px';

    // Move camera (handles boss door differently)
    moveCamera();
}


 
function spawnEntities() {
    if (!isPaused && !bossFightActive) {
        if (Math.random() < 0.003) spawnObstacle();
        
        // Spawn enemies based on the current level
        if (level === 1) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.003) spawnFlyingEnemy();
            if (Math.random() < 0.002) spawnObstacle();
        } else if (level === 2) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.002) spawnObstacle();
            if (Math.random() < 0.003) spawnChargingEnemy(); // Charging enemy option for Level 2
            if (Math.random() < 0.001) spawnSniperEnemy(); // Sniper enemy option for Level 2
        } else if (level === 3) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.002) spawnObstacle();
            if (Math.random() < 0.003) spawnFlyingEnemy(); // Flying enemy option for Level 3
            if (Math.random() < 0.001) spawnReflectiveEnemy(); // Reflective enemy option for Level 3
        } else if (level === 4) {
            if (Math.random() < 0.001) spawnLaserEnemy();
            if (Math.random() < 0.002) spawnSplitterEnemy();
        } else if (level === 5) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.002) spawnVirusDrone();
            if (Math.random() < 0.001) spawnSplitterEnemy();
        }

        if (Math.random() < 0.002 && !currentPowerUp) spawnPowerUp();
        if (Math.random() < 0.001) spawnPlatform();
        if (Math.random() < 0.003) spawnCoin();



        // Manage boss door spawning only if in Story Mode
        if (localStorage.getItem('gameMode') === 'story') {
            if (bossDoors.length === 0 && score >= level * bossScoreThreshold && enemies.length === 0) {
                spawnBossDoor();
            }
        }
    }
}
 

function cleanUpObjects() {
    // Remove obstacles that are too far to the left
    obstacles = obstacles.filter(obstacle => {
        const position = parseInt(obstacle.style.left);
        if (position < -obstacle.offsetWidth) {
            obstacle.remove(); // Remove from the DOM
            return false; // Do not keep this object in the active array
        }
        return true; // Keep this object in the active array
    });

    // Similarly for enemies
    enemies = enemies.filter(enemy => {
        const position = parseInt(enemy.style.left);
        if (position < -enemy.offsetWidth) {
            enemy.remove(); // Remove from the DOM
            return false; // Do not keep this object in the active array
        }
        return true; // Keep this object in the active array
    });
}

            function moveElements() {
                moveArray(obstacles, 2, 15);
                moveArray(enemies, 1, 30);
                moveArray(coins, 2, 0);
                moveArray(powerUps, 2, 0, true);
                moveArray(platforms, 1, 0);
                moveFlyingEnemies();
                moveSniperEnemies();
                moveLaserEnemies();
                moveReflectiveEnemies();
                moveSplitterEnemies();
                moveChargingEnemies();
                moveStealthEnemies();
                moveVirusDrones();
                moveBullets();
                moveNewEnemies();
                moveBoostDrainer()
            }

// Spawn a Laser Enemy (like a sniper — fixed x, y)
function spawnLaserEnemy() {
    const leftPos = gameScrollPosition + gameContainer.offsetWidth;
    const laserEnemy = createElement('laser-enemy', enemies, leftPos);
    laserEnemy.style.bottom = '300px';
    laserEnemy.style.width = '30px';
    laserEnemy.style.height = '30px';
    laserEnemy.style.backgroundColor = 'purple';
    laserEnemy.dataset.laserState = 'warning';
    laserEnemy.dataset.lastDamageTime = '0';
    laserEnemy._warningLine = null;
    laserEnemy._laserBeam = null;
    // createElement already does append and enemies.push
}

// Call every frame in moveEnemies or gameLoop
function moveLaserEnemies() {
    enemies.forEach(enemy => {
        if (!enemy.classList.contains('laser-enemy')) return;

        if (enemy.dataset.laserState === 'warning') {
            if (!enemy._warningLine) {
                createWarningLine(enemy);
                setTimeout(() => {
                    enemy.dataset.laserState = 'active';
                    if (enemy._warningLine) {
                        enemy._warningLine.remove();
                        enemy._warningLine = null;
                    }
                    if (enemy._warningLineUpdateInterval) {
                        clearInterval(enemy._warningLineUpdateInterval);
                        enemy._warningLineUpdateInterval = null;
                    }
                    activateLaserBeam(enemy);
                }, 1000);
            }
            // ⚠️ WARNING LINE DOES NOT DAMAGE PLAYER - NO COLLISION CHECK!
        } else if (enemy.dataset.laserState === 'active') {
            const lastDamageTime = parseInt(enemy.dataset.lastDamageTime) || 0;
            const now = Date.now();

            if (enemy._laserBeam && checkCollision(enemy._laserBeam, player)) {
                if (now - lastDamageTime > 1000) { // damage cooldown 1s
                    reduceLives();
                    enemy.dataset.lastDamageTime = now.toString();
                }
            }
        }
    });
}

 
            function spawnObstacle() {
                const obstacle = createElement('obstacle', obstacles, gameScrollPosition + gameContainer.offsetWidth);
                obstacle.style.bottom = '0px';
            }
 
            function spawnEnemy() {
                const baseEnemy = createElement('enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                baseEnemy.style.bottom = '0px';
 
                const chance = Math.random();
                if (chance < 0.3) {
                    spawnTeleporterEnemy();
                } else if (chance < 0.7) {
                    spawnVelocityEnemy();
                } else if (chance < 0.9) {
                    spawnStickyEnemy();
                }
            }

function moveVirusDrones() {
    viruses.forEach((virus, vIndex) => {
        if (!virus.infectedCount) virus.infectedCount = 0; // init counter

        // Pick target enemy for infection
        if (!virus.targetEnemy || !enemies.includes(virus.targetEnemy)) {
            virus.targetEnemy = null;
            if (enemies.length > 0) {
                virus.targetEnemy = enemies[Math.floor(Math.random() * enemies.length)];
            } else {
                // No target, fly left and clean up if off-screen
                virus.style.left = (parseInt(virus.style.left) - parseInt(virus.dataset.speed)) + 'px';
                if(parseInt(virus.style.left) < gameScrollPosition - virus.offsetWidth) {
                    virus.remove();
                    viruses.splice(vIndex, 1);
                    virusDroneHits = 0;
                }
                return;
            }
        }

        const target = virus.targetEnemy;

        const virusPosX = parseFloat(virus.style.left) + virus.offsetWidth / 2;
        const virusPosY = parseFloat(virus.style.bottom);
        const enemyPosX = parseFloat(target.style.left) + target.offsetWidth / 2;
        const enemyPosY = parseFloat(target.style.bottom);

        const speedH = parseFloat(virus.dataset.speed) || 5;
        const speedV = 10;

        // Horizontal move gently towards target
        if (Math.abs(virusPosX - enemyPosX) > 5) {
            if (virusPosX < enemyPosX) {
                virus.style.left = (parseFloat(virus.style.left) + speedH) + 'px';
            } else {
                virus.style.left = (parseFloat(virus.style.left) - speedH) + 'px';
            }

            // Use smooth vertical cruising instead of forced fixed height (optional)
            const cruisingHeight = 350;
            let virusPosYCurrent = parseFloat(virus.style.bottom) || cruisingHeight;
            if (virusPosYCurrent < cruisingHeight) {
                virus.style.bottom = (virusPosYCurrent + speedV) + 'px';
            } else if (virusPosYCurrent > cruisingHeight) {
                virus.style.bottom = (virusPosYCurrent - speedV) + 'px';
            } else {
                virus.style.bottom = cruisingHeight + 'px';
            }
        } else {
            // Move vertically down inside enemy for infection smoothly
            const targetInsideY = enemyPosY + target.offsetHeight / 2;
            if (virusPosY > targetInsideY + 2) {
                // Smooth downward movement clamped to not go below targetInsideY + 2 
                let newBottom = virusPosY - speedV;
                if (newBottom < targetInsideY + 2) {
                    newBottom = targetInsideY + 2;
                }
                virus.style.bottom = newBottom + 'px';
            } else {
                infectEnemy(target);

                virus.infectedCount++; // Increment infection count
                virus.targetEnemy = null; // Reset target

                if (virus.infectedCount >= 3) {
                    // Destroy virus drone after infecting 3 enemies
                    virus.remove();
                    viruses.splice(vIndex, 1);
                    virusDroneHits = 0;
                }
            }
        }

        // Check bullets hitting virus drone - keep your existing logic here as needed
        bullets.forEach((bulletObj, bIndex) => {
            const bullet = bulletObj.element;
            if (checkCollision(virus, bullet)) {
                bullet.remove();
                bullets.splice(bIndex, 1);

                virusDroneHits++;
                if (virusDroneHits >= 3) {
                    virus.remove();
                    viruses.splice(vIndex, 1);
                    virusDroneHits = 0;
                    enemies.forEach(e => {
                        if (e.classList.contains('infected')) {
                            cureEnemy(e);
                        }
                    });
                }
            }
        });

        // Remove virus drone if off screen left
        if (parseFloat(virus.style.left) < gameScrollPosition - virus.offsetWidth) {
            virus.remove();
            viruses.splice(vIndex, 1);
            virusDroneHits = 0;
        }
    });
}

function createWarningLine(enemy) {
    if (enemy._warningLine) {
        enemy._warningLine.remove();
        enemy._warningLine = null;
    }

    const warning = document.createElement('div');
    warning.classList.add('laser-warning-line');

    const width = 6;

    const enemyLeft = parseInt(enemy.style.left);
    const enemyBottom = parseInt(enemy.style.bottom);
    const enemyHeight = enemy.offsetHeight;
    const left = enemyLeft + enemy.offsetWidth / 2 - width / 2;

    warning.style.position = 'absolute';
    warning.style.left = left + 'px';
    warning.style.bottom = '0px';
    warning.style.width = width + 'px';
    warning.style.height = (enemyBottom + enemyHeight) + 'px';
    warning.style.backgroundColor = 'yellow';
    warning.style.opacity = '0.7';
    warning.style.zIndex = '9';

    gameWorld.appendChild(warning);
    enemy._warningLine = warning;

    if (enemy._warningLineUpdateInterval) clearInterval(enemy._warningLineUpdateInterval);
    enemy._warningLineUpdateInterval = setInterval(() => {
        if (!enemy._warningLine) {
            clearInterval(enemy._warningLineUpdateInterval);
            enemy._warningLineUpdateInterval = null;
            return;
        }
        const curLeft = parseInt(enemy.style.left);
        const curBottom = parseInt(enemy.style.bottom);
        const leftPos = curLeft + enemy.offsetWidth / 2 - width / 2;
        enemy._warningLine.style.left = leftPos + 'px';
        enemy._warningLine.style.height = (curBottom + enemy.offsetHeight) + 'px';
    }, 16);
}

function activateLaserBeam(enemy) {
    if (enemy._warningLine) {
        enemy._warningLine.remove();
        enemy._warningLine = null;
    }
    if (enemy._warningLineUpdateInterval) {
        clearInterval(enemy._warningLineUpdateInterval);
        enemy._warningLineUpdateInterval = null;
    }
    if (enemy._laserBeam) {
        enemy._laserBeam.remove();
        enemy._laserBeam = null;
    }

    const laser = document.createElement('div');
    laser.classList.add('laser-beam');

    const laserWidth = 8;
    const enemyLeft = parseInt(enemy.style.left);
    const enemyBottom = parseInt(enemy.style.bottom);
    const enemyHeight = enemy.offsetHeight;
    const left = enemyLeft + enemy.offsetWidth / 2 - laserWidth / 2;

    laser.style.position = 'absolute';
    laser.style.left = left + 'px';
    laser.style.bottom = '0px';
    laser.style.width = laserWidth + 'px';
    laser.style.height = (enemyBottom + enemyHeight) + 'px';
    laser.style.backgroundColor = 'red';
    laser.style.opacity = '0.9';
    laser.style.zIndex = '10';

    gameWorld.appendChild(laser);
    enemy._laserBeam = laser;

    enemy._laserBeamUpdateInterval = setInterval(() => {
        if (!enemy._laserBeam) {
            clearInterval(enemy._laserBeamUpdateInterval);
            enemy._laserBeamUpdateInterval = null;
            return;
        }
        const curLeft = parseInt(enemy.style.left);
        const curBottom = parseInt(enemy.style.bottom);
        const leftPos = curLeft + enemy.offsetWidth / 2 - laserWidth / 2;

        enemy._laserBeam.style.left = leftPos + 'px';
        enemy._laserBeam.style.height = (curBottom + enemy.offsetHeight) + 'px';
    }, 16);

    setTimeout(() => {
        if (enemy._laserBeam) {
            enemy._laserBeam.remove();
            enemy._laserBeam = null;
        }
        clearInterval(enemy._laserBeamUpdateInterval);
        enemy._laserBeamUpdateInterval = null;

        enemy.dataset.laserState = 'cooldown';

        setTimeout(() => {
            enemy.dataset.laserState = 'warning';
        }, 3000);
    }, 2000);
}

// Infect Enemy function
// Infect Enemy function - updated for multiple shield hits and faster speed
function infectEnemy(enemy) {
    if (enemy.classList.contains('infected')) return; // Already infected
    enemy.classList.add('infected', 'shielded');

    enemy.dataset.health = '1';          // 1 health after shield
    enemy.dataset.shieldHitsLeft = '2';  // 2 shield hits before health

    // Store or retrieve base speed
    let baseSpeed = parseInt(enemy.dataset.baseSpeed) || 1;
    if (!enemy.dataset.baseSpeed) {
        baseSpeed = parseInt(enemy.dataset.speed) || 1;
        enemy.dataset.baseSpeed = baseSpeed.toString();
    }
    enemy.dataset.speed = (baseSpeed * 3).toString(); // Speed is tripled

    enemy.dataset.powerful = 'true';

    // Visual effects
    enemy.style.opacity = '0.8';
    enemy.style.filter = 'drop-shadow(0 0 5px lime)';
}

// Handle bullet collision with shielded enemy - place this inside your bullet collision code
function handleBulletCollisionWithInfectedEnemy(enemy, bulletIndex) {
    if (enemy.classList.contains('infected') && enemy.classList.contains('shielded')) {
        let shieldHitsLeft = parseInt(enemy.dataset.shieldHitsLeft) || 0;
        shieldHitsLeft--;

        // Shield hit logic to decrement shield hits
        if (shieldHitsLeft <= 0) {
            // Shield broken, now damage health
            enemy.dataset.shieldHitsLeft = '0';
            // Decrement health by 1 on each bullet after shield is down
            let health = parseInt(enemy.dataset.health) || 2; // default infected health 2
            health--;

            if (health <= 0) {
                // Enemy dies
                enemy.remove();
                enemies = enemies.filter(e => e !== enemy);
            } else {
                enemy.dataset.health = health.toString();
                // Maybe flash enemy to indicate hit
                enemy.style.opacity = '0.5';
                setTimeout(() => {
                    if (enemy) enemy.style.opacity = '0.8';
                }, 150);
            }
        } else {
            // Shield still active
            enemy.dataset.shieldHitsLeft = shieldHitsLeft.toString();
            // Flash on shield hit
            enemy.style.opacity = '0.5';
            setTimeout(() => {
                if (enemy) enemy.style.opacity = '0.8';
            }, 150);
        }

        // Remove the bullet after hit
        bullets[bulletIndex].element.remove();
        bullets.splice(bulletIndex, 1);

        return true;
    }
    return false;
}

// Cure enemy restores normal speed and removes shield
function cureEnemy(enemy) {
    enemy.classList.remove('infected', 'shielded');
    enemy.style.pointerEvents = 'auto';
    enemy.style.opacity = '1';
    enemy.style.filter = 'none';

    // Reset speed to baseSpeed or default 1
    enemy.dataset.speed = enemy.dataset.baseSpeed || '1';
    enemy.dataset.shieldHitsLeft = '0';
    enemy.dataset.health = '1'; // normal enemies 1 HP
    enemy.dataset.powerful = 'false';

    // You may reset other enemy attributes here if applied.
}


// Enhance Enemy stats (called on infection)
function enhanceEnemy(enemy) {
    // Example: double speed and fire rate if enemy shoots
    const speed = parseInt(enemy.dataset.speed) || 1;
    enemy.dataset.speed = speed * 2;

    // If enemy shoots bullets (like sniper), reduce cooldown or increase damage
    if(enemy.dataset.lastShotTime) {
        enemy.dataset.shootCooldown = (parseInt(enemy.dataset.shootCooldown) || 3000) / 2; 
    }

    // You can add more attribute enhancements here, e.g. health, damage, size
}

// Normalize Enemy back to default (called on cure)
function normalizeEnemy(enemy) {
    const speed = parseInt(enemy.dataset.speed) || 2;
    enemy.dataset.speed = speed / 2;

    if(enemy.dataset.lastShotTime) {
        enemy.dataset.shootCooldown = (parseInt(enemy.dataset.shootCooldown) || 1500) * 2;
    }

    // Reset any other attributes to normal here
}
 
            function spawnPowerUp() {
                const powerUpTypes = allPowerUpTypes;
                const type = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)];
                const powerUp = createElement('power-up', powerUps, gameScrollPosition + gameContainer.offsetWidth);
                powerUp.setAttribute('data-type', type);
                powerUp.style.backgroundColor = getPowerUpColor(type);
                powerUp.style.bottom = Math.floor(Math.random() * 100) + 'px';
            }
 
            function spawnCoin() {
                const coin = createElement('coin', coins, gameScrollPosition + gameContainer.offsetWidth);
                coin.style.bottom = Math.floor(Math.random() * 50 + 50) + 'px';
            }
 
function getPowerUpColor(type) {
    switch (type) {
        case 'super-speed': return 'lime';
        case 'invincibility': return 'gold';
        case 'teleportation': return 'violet';
        case 'reflective-shield': return 'aqua';
        case 'double-shot': return 'red';
        case 'extra-life': return 'lightgreen';
        case 'score-boost': return 'coral';
        case 'mega-jump': return 'fuchsia';
        case 'energy-blast': return 'limegreen'; // Specify colors for valid powers
        case 'light-speed': return 'white'; // Define colors for light-speed
        case 'blazing-trail': return 'gold'; // Specify for blazing-trail
        case 'sonic-wave': return 'blueviolet'; // Specify for sonic-wave
        case 'armor': return 'lightgrey'; // Define color for armor
        case 'telekinetic': return 'silver'; // Define color for telekinetic
        case 'camouflage': return 'darkgreen'; // Define color for camouflage
        case 'dimension-shift': return 'black'; // Define color for dimension-shift
        case 'energy-drain': return 'red'; // Define color for energy-drain
        case 'mind-control': return 'purple'; // Define color for mind-control
        case 'hologram': return 'pink'; // Define color for hologram
        case 'fire': return 'red'; // Define color for energy-drain
        case 'ice': return 'darkblue'; // Define color for energy-drain
        case 'hypno': return 'pink'; // Define color for energy-drain
        default: return 'white'; // Fallback for any unknown type
    }
}
 
            function spawnPlatform() {
                const platform = createElement('platform', platforms, gameScrollPosition + gameContainer.offsetWidth);
                platform.style.bottom = Math.floor(Math.random() * 200 + 100) + 'px';
            }
 
            function spawnBossDoor() {
                const bossDoor = createElement('boss-door', bossDoors, gameScrollPosition + gameContainer.offsetWidth + 200);
                bossDoor.style.bottom = '0px';
            }
 
function createElement(className, array, leftPosition, type = '') {
    const element = document.createElement('div');
    element.classList.add(className);
    if (type) element.setAttribute('data-type', type);
    element.style.left = leftPosition + 'px';
    gameWorld.appendChild(element);
    array.push(element);
    return element;
}
 
function moveArray(array, speed, scoreValue, isPowerUp = false) {
    array.forEach((el, index) => {
        el.style.left = (parseInt(el.style.left) - speed) + 'px';
        if (parseInt(el.style.left) < gameScrollPosition - el.offsetWidth) {
            removeElement(el, array, index, 0);
        } else if (checkCollision(player, el)) {
            handleCollision(el, array, index, scoreValue, isPowerUp);
        }
    });
}
 
            function removeElement(el, array, index, scoreValue) {
                el.remove();
                array.splice(index, 1);
                if (scoreValue) {
                    score += scoreValue;
                    updateDisplay();
                }
            }

spawnEntitiesLevelSelect.addEventListener('change', () => {
  spawnEntitiesLevel = parseInt(spawnEntitiesLevelSelect.value);
  if (spawnEntitiesEnabled) {
    // Restart loop with new level
    stopSpawnEntitiesLoop();
    startSpawnEntitiesLoop();
  }
});

// Start spawning entities periodically
function startSpawnEntitiesLoop() {
  if (spawnEntitiesIntervalId) return; // already running

  spawnEntitiesIntervalId = setInterval(() => {
    if (localStorage.getItem('gameMode') !== 'sandbox') return; // Only in sandbox mode
    if (!spawnEntitiesEnabled) return;

    // Spawn entities according to selected level
    const spawnFunc = levelSpawnEntitiesMap[spawnEntitiesLevel];
    if (spawnFunc) {
      spawnFunc();
    }
  }, 1); // Every 2 seconds (adjust as needed)
}

// Stop spawning and clear spawned entities related to this feature
function stopSpawnEntitiesLoop() {
  if (spawnEntitiesIntervalId) {
    clearInterval(spawnEntitiesIntervalId);
    spawnEntitiesIntervalId = null;
  }

  // Optional: Remove spawned special entities to keep clean
  spawnedSpecialEntities.forEach(ent => {
    if (ent.parentElement) ent.remove();
  });
  spawnedSpecialEntities.length = 0;
}
 
function handleCollision(el, array, index, scoreValue, isPowerUp = false) {
    if (el.classList.contains('coin')) {
        score += 5; // Increase score for collecting a coin
        updateDisplay(); // Update the display if needed
    } 
    
    // Handle power-ups
    else if (isPowerUp) {
        applyPowerUp(el); // Apply power-up effects
    }
    
    // Handle boss door interactions
    else if (el.classList.contains('boss-door')) {
        if (score >= level * bossScoreThreshold) {
            interactMessage.textContent = "Press 'E' to enter boss door."; // Prompt for interaction
            interactMessage.style.display = checkCollision(player, el) ? 'block' : 'none'; // Show message if player is near
            if (checkCollision(player, el) && playerPositionX >= parseInt(el.style.left)) {
                openBossHallway(); // Proceed to boss hallway
            }
        }
    }

    // Handle enemy and obstacle collisions
    else if (el.classList.contains('enemy') || el.classList.contains('obstacle')) {
        reduceLives(); // Reduce player's lives on collision with enemies or obstacles
    }

    // Remove the collided element from the game world
    removeElement(el, array, index, scoreValue);
}
 
            function applyPowerUp(el) {
                if (currentPowerUp || currentPowerUp === 'boss-power-up') return;
 
                const type = el.getAttribute('data-type');
                if (type === 'boss-power-up') {
                    grantBossPowerUp();
                } else {
                    currentPowerUp = type;
                    let duration = 10;
                    activatePowerUp(type);
                    powerUpTimer = duration;
 
                    const powerUpInterval = setInterval(() => {
                        powerUpTimer--;
                        if (powerUpTimer <= 0) {
                            clearInterval(powerUpInterval);
                            resetPowerUp();
                        }
                        updateDisplay();
                    }, 1000);
                }
 
                displayPowerUpMessage(type);
            }

function activatePowerUp(type) {
    switch (type) {
        case 'super-speed':
            player.style.backgroundColor = 'lime';
            playerMaxSpeed += 8; // Increase speed
            break;
        case 'invincibility':
            player.style.backgroundColor = 'gold';
            PlayerInvincibility(); // Implement this function for invincibility
            break;
        case 'teleportation':
            teleportPlayer(); // Implement this function for teleportation
            break;
        case 'reflective-shield':
            activateReflectiveShield(); // Implement the reflective shield functionality
            break;
        case 'double-shot':
            enableDoubleShot(); // Implement functionality for double shot
            break;
        case 'extra-life':
            gainExtraLife(); // Implement functionality for gaining an extra life
            break;
        case 'score-boost':
            boostScore(); // Implement functionality for score boost
            break;
        case 'mega-jump':
            activateMegaJump(); // Implement functionality for mega jump
            break;
        case 'energy-blast':
            activateEnergyBlast(); // Implement functionality for energy blast
            break;
        case 'light-speed':
            player.style.backgroundColor = 'lime';
            playerMaxSpeed += 10; // Increase speed
            break;
        case 'blazing-trail':
            activateBlazingTrail(); // Implement functionality for blazing trail
            break;
        case 'sonic-wave':
            activateSonicWave(); // Implement functionality for sonic wave
            break;
        case 'armor':
            activateArmor(); // Implement functionality for armor
            break;
        case 'telekinetic':
            activateTelekinetic(); // Implement functionality for telekinetic
            break;
        case 'camouflage':
            activateCamouflage(); // Implement functionality for camouflage
            break;
        case 'dimension-shift':
            activateDimensionShift(); // Implement functionality for dimension shift
            break;
        case 'energy-drain':
            activateEnergyDrain(); // Implement functionality for energy drain
            break;
        case 'mind-control':
            activateMindControl(); // Implement functionality for mind control
            break;
        case 'hologram':
            activateHologram(); // Implement functionality for hologram
            break;
        case 'fire':
            shootFire();
            break;
        case 'ice':
            shootIce();
            break;
        case 'hypno':
            shootHypno();
            break;
        default:
            // Consider logging or managing invalid power-up requests
            console.log(`Unknown power-up type: ${type}`);
            break;
    }
}

function handlePlayerEnemyCollision() {
    enemies.forEach((enemy, index) => {
        // Check collision with the player
        if (checkCollision(player, enemy)) {
            if (enemy.classList.contains('frozen')) {
                // If frozen, destroy the enemy
                enemy.remove(); // Remove frozen enemy
                enemies.splice(index, 1); // Remove from the enemies array
                updateDisplay(); // Update any relevant game display elements if needed
            } else {
                // Normal behavior for non-frozen enemies
                reduceLives(); // This would reduce lives for non-frozen collisions
            }
        }
    });
}
 


function allowPlayerMovement(e) {
    switch (e.key) {
        case 'ArrowLeft':
            playerPositionX -= playerMaxSpeed; // Move left
            player.style.left = playerPositionX + 'px';
            break;
        case 'ArrowRight':
            playerPositionX += playerMaxSpeed; // Move right
            player.style.left = playerPositionX + 'px';
            break;
        case ' ': // Space to shoot
            shootBullet(currentDirection); // Allow shooting during freeze
            break;
    }
}
 
function resetPowerUp() {
    currentPowerUp = null; // Also can now be re-assigned
    player.style.backgroundColor = '#4CAF50';
    if (upgradesEquipped.includes('speedBoost')) {
        playerMaxSpeed = 7; // Set the boosted speed or any other value you want
    } else {
        playerMaxSpeed = 5; // Default speed if the upgrade is not equipped
    }
    player.style.opacity = '1';
    if (upgradesEquipped.includes('doubleJump')) {
        isDoubleJumpEnabled = true; // Enable double jump if upgrade is equipped
    } else {
        isDoubleJumpEnabled = false; // Disable double jump otherwise
    }
    clearTimeout(timeSlowTimeout);
    resetGravity();
}
 
            function displayPowerUpMessage(type) {
                powerUpMessage.textContent = `You obtained ${type.replace(/-/g, ' ')}!`;
                powerUpMessage.style.display = 'block';
                setTimeout(() => powerUpMessage.style.display = 'none', 2000);
            }
 
            function grantBossPowerUp() {
                bossPowerObtained = true;
                powerUpMessage.textContent = "Boss Power-Up Obtained!";
                powerUpMessage.style.display = 'block';
                setTimeout(() => powerUpMessage.style.display = 'none', 2000);
            }

function PlayerInvincibility() {
    // Check for collision with enemies
    enemies.forEach((enemy) => {
        if (checkCollision(player, enemy)) {
            if (!isInvincible) { // Only reduce lives if not invincible
                if (lives > 1) {
                    lives--; // Deduct a life when colliding with an enemy
                    updateDisplay(); // Update the displayed lives
                }
            }
        }
    });

    // Immediately reset lives to 3 if they drop below that
    if (lives < 3) {
        lives = 3; // Reset lives to 3 instantly
        updateDisplay(); // Update display to show 3 lives
    }
}
 
            function usePowerUp() {
                if (!currentPowerUp) return;
                switch (currentPowerUp) {
                    case 'ice':
                        shootIce();
                        break;
                    case 'sonic-wave':
                        activateSonicWave();
                        break;
                    case 'fire':
                        shootFire();
                        break;
                    case 'teleportation':
                        teleportPlayer();
                        break;
                    case 'levitate':
                        useLevitate();
                        break;
                    case 'hypno':
                        shootHypno();
                        break;
                    case 'double-shot':
                        shootDouble();
                        break;
                    default:
                        break;
                }
            }
 
function shootIce() {
    const iceBullet = createBullet(currentDirection); // Create the ice bullet
    iceBullet.style.backgroundColor = 'blue'; // Set bullet color to blue
    gameWorld.appendChild(iceBullet);

    const iceBulletObj = { element: iceBullet, direction: currentDirection };
    
    animateBullet(iceBulletObj, 5, (target) => {
        // Check for collision with enemies
        if (target.classList.contains('obstacles')) {
            target.classList.add('frozen'); // Mark the enemy as frozen
            target.style.backgroundColor = '#00f'; // Change color to blue
            target.style.opacity = '0.5'; // Reduce visibility
            target.dataset.isFrozen = 'true'; // Mark enemy as frozen

            // Set a timer to unfreeze
            setTimeout(() => {
                if (target.dataset.isFrozen === 'true') {
                    target.classList.remove('frozen'); // Remove frozen status
                    target.style.backgroundColor = ''; // Reset color
                    target.style.opacity = '1'; // Reset visibility
                    delete target.dataset.isFrozen; // Clear the frozen marker
                }
            }, 5000); // 5 seconds to unfreeze
        }
    });
}
 
function shootFire() {
  const fireBullet = createBullet(currentDirection);
  fireBullet.style.backgroundColor = 'red';
  fireBullet.classList.add('fire-bullet');   // << Add this class
  gameWorld.appendChild(fireBullet);

  const fireBulletObj = { element: fireBullet, direction: currentDirection };
  animateBullet(fireBulletObj);
}
 
            function useLevitate() {
                player.style.transform = 'translateY(-20px)';
                const levitateUp = setTimeout(() => {
                    player.style.transform = 'translateY(0)';
                    clearTimeout(levitateUp);
                }, 1000);
            }
 
            function enableDoubleShot() {
            }
 
            function createBullet(direction = 1) {
                const bullet = document.createElement('div');
                bullet.classList.add('bullet');
                bullet.style.backgroundColor = '#FFD700';
                bullet.style.left = (playerPositionX + player.offsetWidth / 2 - 5) + 'px';
                bullet.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px';
                return bullet;
            }
 
function shootHypno() {
  const hypnoBullet = createBullet(currentDirection);
  hypnoBullet.style.backgroundColor = 'pink';
  hypnoBullet.classList.add('hypno-bullet'); // << Add this class
  gameWorld.appendChild(hypnoBullet);

  const hypnoBulletObj = { element: hypnoBullet, direction: currentDirection };
  animateBullet(hypnoBulletObj);
}
 
            function shootDouble() {
                const bullet1 = createBullet(currentDirection);
                const bullet2 = createBullet(currentDirection);
                bullets.push({ element: bullet1, direction: currentDirection });
                bullets.push({ element: bullet2, direction: currentDirection });
                gameWorld.appendChild(bullet1);
                gameWorld.appendChild(bullet2);
            }
 
function hypnotizeEnemy(enemy) {
    let destroyCount = 0; // Count how many enemies are destroyed by this hypnotized enemy
    const moveInterval = setInterval(() => {
        let nearestEnemy = findNearestEnemyTo(enemy);
        if (!nearestEnemy) {
            enemy.remove(); // If no nearest enemy, remove this one
            clearInterval(moveInterval); // Stop interval
            return;
        }

        let ex = parseInt(enemy.style.left);
        let ey = parseInt(enemy.style.bottom);
        let nex = parseInt(nearestEnemy.style.left);
        let ney = parseInt(nearestEnemy.style.bottom);

        let dx = nex - ex;
        let dy = ney - ey;
        let distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < 5) {
            destroyCount++;
            createBurst(nex, ney); // Create an effect when destroying enemies
            nearestEnemy.remove();
            enemies = enemies.filter(e => e !== nearestEnemy); // Clean up enemies

            if (destroyCount >= 3) { // Define a limit for multiple enemies hypnotized
                enemy.remove(); // Remove this hypnotized enemy after doing its effects
                clearInterval(moveInterval); // Stop interval
            }
        } else {
            let angle = Math.atan2(dy, dx); // Calculate angle to move towards the nearest enemy
            enemy.style.left = (ex + Math.cos(angle) * 2) + 'px'; // Move slightly towards
            enemy.style.bottom = (ey + Math.sin(angle) * 2) + 'px';
        }
    }, 1000 / 60); // Run update at 60 FPS
}
 
            function findNearestEnemyTo(sourceEnemy) {
                let minDistance = Infinity;
                let closestEnemy = null;
 
                enemies.forEach(enemy => {
                    if (enemy !== sourceEnemy) {
                        let distance = calculateDistance(sourceEnemy, enemy);
                        if (distance < minDistance) {
                            minDistance = distance;
                            closestEnemy = enemy;
                        }
                    }
                });
 
                return closestEnemy;
            }
 
            function calculateDistance(el1, el2) {
                let el1Rect = el1.getBoundingClientRect();
                let el2Rect = el2.getBoundingClientRect();
                let dx = (el1Rect.left + el1Rect.width / 2) - (el2Rect.left + el2Rect.width / 2);
                let dy = (el1Rect.top + el1Rect.height / 2) - (el2Rect.top + el2Rect.height / 2);
                return Math.sqrt(dx * dx + dy * dy);
            }
 
            function enableDoubleJump(enable = true) {
                isDoubleJumpEnabled = enable;
            }

function moveBoostDrainer() {
    if (!boostDrainer) return;

    // Move left slowly
    let currentX = parseInt(boostDrainer.style.left);
    boostDrainer.style.left = (currentX - 0.5) + 'px'; // Adjust speed here

    // Remove if off-screen left
    if (currentX < gameScrollPosition - boostDrainer.offsetWidth) {
        removeBoostDrainer();
        return;
    }

    // Update chain line connecting player and boost drainer
    if (boostDrainerChain) {
        updateChainLine(boostDrainer, boostDrainerChain, player);
    }
}
 
function teleportPlayer() {
    if (isTeleporting) return; // Prevent multiple teleports in quick succession

    // Set cooldown
    isTeleporting = true; // Set to true to indicate teleport in progress

    // Calculate teleportation distance
    const teleportDistance = 145; // Increase this to a larger value for more noticeable teleport

    // Determine player current direction
    let teleportOffset = teleportDistance * currentDirection; // Use currentDirection to allow for left (-1) and right (1) teleporting

    // Update player position
    playerPositionX += teleportOffset; // Move the player in the direction they are facing
    playerPositionX = Math.max(0, Math.min(gameWorld.offsetWidth - player.offsetWidth, playerPositionX)); // Ensure player stays in bounds

    // Log positions for debugging
    console.log('Teleporting to position:', playerPositionX);

    player.style.left = playerPositionX + 'px'; // Update player's position on screen

    // Set a timeout for the cooldown
    setTimeout(() => {
        isTeleporting = false; // Reset teleport ability after cooldown
    }, 1000); // 1000 milliseconds = 1 second cooldown
}
 
            function toggleGravity() {
                const originalGravity = gravity;
                gravity = -gravity;
                setTimeout(() => {
                    gravity = originalGravity;
                }, 5000);
            }
 
function resetGravity() {
    gravity = Math.abs(gravity); // Needs to ensure gravity is declared with let or var
}
 
            function freezeEnemies() {
                enemies.forEach(enemy => {
                    enemy.style.transition = 'opacity 1s';
                    enemy.style.opacity = '0.2';
                    enemy.classList.add('frozen-enemy');
                });
                setTimeout(() => {
                    enemies.forEach(enemy => {
                        enemy.style.opacity = '1';
                        enemy.classList.remove('frozen-enemy');
                    });
                }, 5000);
            }
 
            function createClone() {
                const clone = createElement('player', [], playerPositionX + 50);
                clone.style.bottom = playerPositionY + 'px';
                clone.style.backgroundColor = '#00F';
                clone.style.border = '2px dashed #FFF';
                gameWorld.appendChild(clone);
                setTimeout(() => clone.remove(), 5000);
            }
 
            function triggerShockwave() {
                const shockwaveRadius = 10000;
                enemies.forEach(enemy => {
                    const dist = calculateDistance(player, enemy);
                    if (dist < shockwaveRadius) {
                        createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
                        enemy.remove();
                    }
                });
            }
 
            function absorbEnergy() {
                score += 50;
                updateDisplay();
            }
 
            function shrinkPlayer() {
                player.style.transform = 'scale(0.5)';
                setTimeout(() => player.style.transform = 'scale(1)', 5000);
            }
 
            function growPlayer() {
                player.style.transform = 'scale(1.5)';
                setTimeout(() => player.style.transform = 'scale(1)', 5000);
            }
 
            function healPlayer() {
                if (lives < 5) {
                    lives++;
                    updateDisplay();
                }
            }
 
            function activateShield() {
                player.style.border = '3px solid purple';
                player.style.opacity = '0.6';
                lives = Math.min(lives + 1, 7);
                updateDisplay();
            }
 
            function gainExtraLife() {
                lives = Math.min(lives + 1, 7);
                updateDisplay();
            }

function gainExtraLife2() {
    lives = Math.min(lives + 3, 6); // Increase lives by 3, ensuring it doesn't exceed 5
    updateDisplay(); // Update the display to reflect the new number of lives
}

function removeLife() {
    lives = Math.max(lives - 3, 3); // Decrease lives by 3, ensuring it doesn't fall below 3
    updateDisplay(); // Update the display to reflect the new number of lives
}
 
            function boostScore() {
                score += 100;
                updateDisplay();
            }
 
let consecutiveJumps = 0; // Initialize a variable to track consecutive jumps
const maxJumpCount = 3; // Maximum number of normal jumps before triggering a mega jump
const megaJumpMultiplier = 1.5; // Multiplier for the mega jump

function activateMegaJump() {
    if (consecutiveJumps < maxJumpCount) {
        // Perform a normal jump if within the max jump limit
        playerVelocityY = playerJumpStrength; // Regular jump value
        consecutiveJumps++; // Increment consecutive jumps
    } else {
        // Trigger a mega jump if max jump limit has been reached
        playerVelocityY = playerJumpStrength * megaJumpMultiplier; // Apply mega jump
        consecutiveJumps = 0; // Reset consecutive jumps to 0 after a mega jump
    }
    isJumping = true; // Set the jumping status to true
}

// Call this function whenever the player lands to reset the consecutive jumps count
function checkLanding() {
    if (playerPositionY <= 0) { // Assuming ground level is at y = 0
        consecutiveJumps = 0; // Reset consecutive jumps when landing
    }
}
 
            function activateReflectiveShield() {
                player.style.border = '3px dashed cyan';
                const reflectInterval = setInterval(() => {
                    bullets.forEach((bullet, index) => {
                        if (checkCollision(player, bullet.element)) {
                            bullet.direction *= -1;
                        }
                    });
                }, 1000 / 60);
 
                setTimeout(() => {
                    player.style.border = '';
                    clearInterval(reflectInterval);
                }, 5000);
            }
 
            function activateRegeneration() {
                const regenerationInterval = setInterval(() => {
                    if (lives < 5) lives++;
                    updateDisplay();
                    if (!currentPowerUp || currentPowerUp !== 'regeneration') {
                        clearInterval(regenerationInterval);
                    }
                }, 2000);
            }
 
            function activateMagnet() {
                const magnetInterval = setInterval(() => {
                    coins.forEach(coin => {
                        const coinX = parseInt(coin.style.left);
                        const coinY = parseInt(coin.style.bottom);
                        const dx = playerPositionX - coinX;
                        const dy = playerPositionY - coinY;
                        if (Math.sqrt(dx * dx + dy * dy) < 100) {
                            coin.style.left = (coinX + dx * 0.1) + 'px';
                            coin.style.bottom = (coinY + dy * 0.1) + 'px';
                        }
                    });
 
                    if (!currentPowerUp || currentPowerUp !== 'magnet') {
                        clearInterval(magnetInterval);
                    }
                }, 1000/ 60);
            }
 
            let timeSlowTimeout;
 
            function slowDownTime() {
                const originalTiming = 1000 / 60;
                clearInterval(gameInterval);
                gameInterval = setInterval(gameLoop, originalTiming * 2);
                timeSlowTimeout = setTimeout(() => {
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, originalTiming);
                }, 5000);
            }
 
function activateEnergyBlast() {
    const blastRadius = 100; // Define the radius of the blast
    const burst = document.createElement('div'); // Create a burst element
    burst.classList.add('energy-blast'); // Assign a class for styles
    burst.style.left = (playerPositionX - blastRadius) + 'px'; // Position the burst to the player's location
    burst.style.bottom = (playerPositionY - blastRadius) + 'px'; // Center the burst around the player
    gameWorld.appendChild(burst); // Add the burst to the game world

    // Set a timeout to remove the burst effect after a duration
    setTimeout(() => {
        burst.remove(); // Remove the burst after showing it
    }, 500); // Keep the burst visible for half a second

    // Identify and destroy nearby enemies
    let enemiesToRemove = enemies.filter(enemy => calculateDistance(player, enemy) < blastRadius);
    enemiesToRemove.forEach(enemy => {
        createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom)); // Create an explosion effect at enemy's location
        enemy.remove(); // Remove the enemy from the game
        enemies = enemies.filter(e => e !== enemy); // Ensure the enemy is removed from the enemies array
    });

    updateDisplay(); // Update the display to reflect any changes (like score)
}

function initializeBossHealth() {
    bossHealth = level === 3 ? 250 : 100; // Example health values based on level
    updateDisplay();
}
 
function activateBlazingTrail() {
    let trailInterval = setInterval(() => {
        const trail = document.createElement('div');
        trail.className = 'bullet'; // Using the same class for stylistic purposes
        trail.style.left = (playerPositionX + player.offsetWidth / 2) + 'px'; // Position trail based on player's location
        trail.style.bottom = (playerPositionY + player.offsetHeight / 2) + 'px'; // Center the trail on the player
        trail.style.backgroundColor = 'orange'; // Trail color
        gameWorld.appendChild(trail); // Add the trail to the game

        // Check collision with enemies
        enemies.forEach((enemy, enemyIndex) => {
            if (checkCollision(trail, enemy)) {
                // Create burst effect for visual feedback
                const burst = document.createElement('div');
                burst.className = 'burst'; // The CSS class for the burst effect
                burst.style.left = enemy.style.left; // Position it at the enemy's position
                burst.style.bottom = enemy.style.bottom; // Position it at the enemy's position
                gameWorld.appendChild(burst);
                
                // Clean up burst after a short duration
                setTimeout(() => burst.remove(), 500); // Remove burst after 0.5 seconds
                
                // Remove enemy
                enemy.remove(); // Remove the enemy from game
                enemies.splice(enemyIndex, 1); // Remove from enemies array to prevent future collisions
            }
        });

        // Remove the trail after a short duration
        setTimeout(() => trail.remove(), 500); // Remove trail after 0.5 seconds
    }, 100); // The interval for creating the trails

    // Automatically clear the interval after a certain time, e.g., 5 seconds
    setTimeout(() => {
        clearInterval(trailInterval); // Clear the interval for the trail creation
    }, 5000);
}


 
function activateSonicWave() {
    if (waveCooldown) return; // Prevent activation if already on cooldown
    waveCooldown = true; // Set cooldown to prevent further activation

    const wave = document.createElement('div');
    wave.className = 'wave'; // Class for wave styling
    wave.style.left = (playerPositionX - 50) + 'px'; // Center the wave below the player
    wave.style.bottom = (playerPositionY - 50) + 'px'; // Position just below player
    wave.style.backgroundColor = 'cyan'; // Wave color
    wave.style.width = '100px'; // Width of the wave
    wave.style.height = '100px'; // Height of the wave
    wave.style.position = 'absolute'; // Ensure proper positioning
    gameWorld.appendChild(wave); // Add the wave to the game world

    let destroyedBlocks = 0; // Track how many blocks have been destroyed

    // Move the wave forward quickly
    let waveInterval = setInterval(() => {
        wave.style.left = (parseInt(wave.style.left) + 10) + 'px'; // Move wave to the right

        // Check for collision with obstacles
        obstacles.forEach((block, index) => {
            if (checkCollision(wave, block) && destroyedBlocks < 3) { // Destroy only until 3 blocks
                // Create burst effect
                const burst = document.createElement('div'); 
                burst.className = 'burst';
                burst.style.left = block.style.left; 
                burst.style.bottom = block.style.bottom; 
                gameWorld.appendChild(burst);
                
                setTimeout(() => burst.remove(), 500); // Remove burst after half a second
                
                block.remove(); // Remove the obstacle
                obstacles.splice(index, 1); // Remove from the array
                destroyedBlocks++; // Increment the destroyed block count
            }
        });

        // Cleanup if wave goes off screen
        if (parseInt(wave.style.left) > gameWorld.offsetWidth) {
            clearInterval(waveInterval); // Stop moving the wave if it goes off screen
            wave.remove(); // Remove the wave
            resetWave(); // Reset block destruction count
            return; // Exit the function
        }
    }, 50); // Adjust speed of the wave as needed

    // Automatically remove the wave after a brief time
    setTimeout(() => {
        clearInterval(waveInterval); // Ensure the interval is cleared after time is up
        wave.remove(); // Remove the wave
        resetWave(); // Reset properties after the effect finishes
    }, 2000); // Duration of the wave effect (2 seconds)
}

// Reset wave properties for future use
function resetWave() {
    destroyedBlocks = 0; // Reset the number of destroyed blocks for future waves
    waveCooldown = false; // Reset cooldown state
}
 
            function activateArmor() {
                player.style.border = '3px solid steelblue';
                lives = Math.min(lives + 3, 5);
                updateDisplay();
            }
 
function activateTelekinetic() {
    const forceInterval = setInterval(() => {
        enemies.forEach((enemy, index) => {
            const enemyX = parseInt(enemy.style.left) + enemy.offsetWidth / 2; // Get center position
            const enemyY = parseInt(enemy.style.bottom) + enemy.offsetHeight / 2; // Get center position
            const dx = playerPositionX - enemyX;
            const dy = playerPositionY - enemyY;

            // Check if the player is within a certain distance (e.g., 100 pixels)
            if (Math.sqrt(dx * dx + dy * dy) < 100) {
                // Move the enemy upwards slightly
                enemy.style.bottom = (enemyY + 2) + 'px'; // Adjust height as necessary for feel
            } else if (enemyY > 0) { // Only lower it if above 0
                // Bring the enemy back down to ground level smoothly
                enemy.style.bottom = (enemyY - 2) + 'px'; // Adjust to bring back down
                // Stop exactly at the ground level if necessary
                if (parseInt(enemy.style.bottom) < 0) {
                    enemy.style.bottom = '0px'; // Prevent going below 0
                }
            }
        });
    }, 1000 / 60); // Update at 60 FPS

    // Optional: Set a timeout for how long telekinesis lasts
    setTimeout(() => clearInterval(forceInterval), 5000); // Lasts for 5 seconds
}
 
            function activateCamouflage() {
                player.style.opacity = '0.2';
                setTimeout(() => player.style.opacity = '1', 5000);
            }
 
// Array to temporarily hold removed enemies

function activateDimensionShift() {
    // Change the background color to indicate the shift
    gameWorld.style.backgroundColor = 'black';

    // Hide and remove all enemies in the game world
    enemies.forEach((enemy, index) => {
        enemy.style.transition = 'opacity 1s'; // Set transition for fading effect
        enemy.style.opacity = '0'; // Start fading the enemy
        setTimeout(() => {
            enemy.remove(); // Remove from the DOM after fading
            enemies.splice(index, 1); // Remove from the enemies array
        }, 1000); // Match the timeout to the fade-out duration (1 second)
    });

    // Hide and remove all obstacles in the game world
    obstacles.forEach((obstacle, index) => {
        obstacle.style.transition = 'opacity 1s'; // Set transition for fading effect
        obstacle.style.opacity = '0'; // Start fading the obstacle
        setTimeout(() => {
            obstacle.remove(); // Remove from the DOM after fading
            obstacles.splice(index, 1); // Remove from the obstacles array
        }, 1000); // Match the timeout to the fade-out duration (1 second)
    });

    // Reset background color after a period
    setTimeout(() => {
        gameWorld.style.backgroundColor = ''; // Reset the background color after 5 seconds

        // Restore removed enemies
        removedEnemies.forEach(removedEnemy => {
            // Re-create the enemy in the game world
            const newEnemy = createElement(removedEnemy.className, enemies, gameScrollPosition + gameContainer.offsetWidth);
            newEnemy.style.bottom = '0px'; // Reset position
            gameWorld.appendChild(newEnemy); // Append back to game world
        });

        // Clear out the removedEnemies array for future use
        removedEnemies = [];

        // If you have obstacles that should be restored, handle that here as well
        // You may need to keep track of removed obstacles in a similar way if needed
    }, 5000); // Keep the black background for 5 seconds
}
 
            function activateEnergyDrain() {
                const drainInterval = setInterval(() => {
                    if (score > 0) {
                        score -= 1;
                        updateDisplay();
                    }
                }, 100);
 
                setTimeout(() => clearInterval(drainInterval), 5000);
            }

function applyBurn(enemy) {
    // Prevent stacking multiple burns on same enemy
    if (enemy.classList.contains('burning')) return;

    enemy.classList.add('burning');
    enemy.style.backgroundColor = 'orange';  // Visual indicator for burn

    // Initialize or read enemy health (default to 3 if not set)
    let health = parseInt(enemy.dataset.health) || 3;
    enemy.dataset.health = health.toString();

    let burnTicks = 3;   // Number of damage ticks (seconds)
    const burnDamage = 1; // Damage per tick

    const burnInterval = setInterval(() => {
        if(burnTicks <= 0) {
            // Burn finished: cleanup visuals & interval
            clearInterval(burnInterval);
            enemy.classList.remove('burning');
            enemy.style.backgroundColor = '';  // Reset to original or default

            // Remove dataset health if enemy survived for neatness
            if (enemy.parentElement && health > 0) {
                enemy.dataset.health = health.toString();
            } else if (health <= 0) {
                enemy.remove();
                enemies = enemies.filter(e => e !== enemy);
            }

            return;
        }

        // Apply burn damage
        health -= burnDamage;

        // Update health dataset
        enemy.dataset.health = health.toString();

        // Optional: flash to indicate hit
        enemy.style.opacity = '0.5';
        setTimeout(() => {
            if(enemy) enemy.style.opacity = '1';
        }, 150);

        // Remove enemy if health depleted
        if (health <= 0) {
            clearInterval(burnInterval);
            if (enemy.parentElement) {
                enemy.remove();
                enemies = enemies.filter(e => e !== enemy);
            }
            return;
        }

        burnTicks--;
    }, 1000); // Tick every 1 second
}
 
function activateMindControl() {
    const hypnotizeRange = 1000; // Set hypnotize range in pixels (you can adjust this)

    // Loop through all enemies
    enemies.forEach(enemy => {
        const enemyX = parseInt(enemy.style.left) + (enemy.offsetWidth / 2); // Get the center of the enemy
        const enemyY = parseInt(enemy.style.bottom) + (enemy.offsetHeight / 2); // Get the center of the enemy
        const dx = playerPositionX - enemyX; // Calculate horizontal distance
        const dy = playerPositionY - enemyY; // Calculate vertical distance

        // Check if within the hypnotize range
        const distance = Math.sqrt(dx * dx + dy * dy); // Calculate distance to the player
        if (distance < hypnotizeRange) {
            if (!enemy.classList.contains('hypnotized')) {
                enemy.classList.add('hypnotized'); // Mark enemy as hypnotized
                enemy.style.backgroundColor = 'violet'; // Change color to indicate hypnotization
                
                // Call the function to handle hypnosis effects
                hypnotizeEnemy(enemy);
            }
        }
    });
}
 
function activateHologram() {
    const hologram = document.createElement('div');
    hologram.className = 'hologram'; // Use a hologram class for styling
    hologram.style.position = 'absolute';
    hologram.style.left = `${playerPositionX - 25}px`; // Position the hologram centered relative to player
    hologram.style.bottom = `${playerPositionY}px`; // Vertical alignment with player
    hologram.style.width = '50px'; // Fixed width for better visibility
    hologram.style.height = '50px'; // Fixed height for better visibility
    hologram.style.backgroundColor = 'rgba(0, 0, 255, 0.5)'; // Semi-transparent blue color
    hologram.style.borderRadius = '50%'; // Round shape
    hologram.style.zIndex = '100'; // Ensure the hologram is above other elements
    gameWorld.appendChild(hologram); // Add the hologram to the game world

    // Pulsate effect
    let scale = 5;
    const pulseSpeed = 0.05; // Adjust pulsate speed
    const maxScale = 1.2; // Maximum scale for pulsate
    const minScale = 1; // Minimum scale for pulsate
    
    const pulseInterval = setInterval(() => {
        scale += pulseSpeed * Math.sin(Date.now() / 500); // Use sine for smooth pulsating effect
        scale = Math.max(minScale, Math.min(scale, maxScale)); // Clamp scale
        hologram.style.transform = `scale(${scale})`;
    }, 100); // Make it appear smooth

    // Behavior to distract nearby enemies
    enemies.forEach(enemy => {
        const enemyX = parseInt(enemy.style.left) + (enemy.offsetWidth / 2);
        const enemyY = parseInt(enemy.style.bottom) + (enemy.offsetHeight / 2);
        const dx = playerPositionX - enemyX;
        const dy = playerPositionY - enemyY;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < 100) { // If enemy is within distraction range
            // Smoothly move the enemy away from the hologram
            const moveAmount = 50; // The distance to move away
            const newLeft = enemyX + (dx > 0 ? moveAmount : -moveAmount); // Move away from hologram
            enemy.style.transition = 'left 0.5s'; // Smooth movement transition
            enemy.style.left = `${newLeft}px`;
        }
    });

    // Remove the hologram after 5 seconds
    setTimeout(() => {
        clearInterval(pulseInterval); // Stop the pulsating effect
        hologram.remove(); // Remove hologram from the game world
    }, 7500);
}
 
function animateBullet(bulletObj, speed, impactCallback = () => {}) {
    const bulletInterval = setInterval(() => {
        const bullet = bulletObj.element;
        const newLeft = parseInt(bullet.style.left) + (bulletObj.direction * speed);
        bullet.style.left = newLeft + 'px';

        if (newLeft > gameScrollPosition + gameContainer.offsetWidth || newLeft < 0) {
            bullet.remove();
            clearInterval(bulletInterval);
            return;
        }

        for (const target of [...obstacles, ...enemies]) {
            if (checkCollision(bullet, target)) {
                // Handle infected + shielded enemy
                if (target.classList.contains('infected') && target.classList.contains('shielded')) {
                    let shieldHitsLeft = parseInt(target.dataset.shieldHitsLeft) || 2;
                    shieldHitsLeft--;

                    if (shieldHitsLeft <= 0) {
                        // Shield broken
                        target.dataset.shieldHitsLeft = '0';
                        target.classList.remove('shielded');

                        let health = parseInt(target.dataset.health) || 1;
                        health--;

                        if (health <= 0) {
                            target.remove();
                            enemies = enemies.filter(e => e !== target);
                        } else {
                            target.dataset.health = health.toString();
                            target.style.opacity = '0.5';
                            setTimeout(() => {
                                if (target) target.style.opacity = '0.8';
                            }, 150);
                        }
                    } else {
                        // Shield still active, just decrement and flash
                        target.dataset.shieldHitsLeft = shieldHitsLeft.toString();
                        target.style.opacity = '0.5';
                        setTimeout(() => {
                            if (target) target.style.opacity = '0.8';
                        }, 150);
                    }

                    createBurst(newLeft, parseInt(bullet.style.bottom));
                    bullet.remove();
                    clearInterval(bulletInterval);
                    return;
                }

                // Hypno bullet effect (no instant death)
                if (bullet.classList.contains('hypno-bullet') && target.classList.contains('enemy') && !target.classList.contains('hypnotized')) {
                    target.classList.add('hypnotized');
                    target.style.backgroundColor = 'pink';
                    hypnotizeEnemy(target);

                    createBurst(newLeft, parseInt(bullet.style.bottom));
                    bullet.remove();
                    clearInterval(bulletInterval);
                    return;
                }

                // Fire bullet effect (fade and remove obstacle)
if (bullet.classList.contains('fire-bullet') && target.classList.contains('enemy')) {
    applyBurn(target);
    bullet.remove();
    clearInterval(bulletMoveInterval);
    return;
}

                // Ice bullet effect (freeze, no instant death)
                if (bullet.classList.contains('ice-bullet')) {
                    if (target.classList.contains('obstacle') || target.classList.contains('enemy')) {
                        target.classList.add('frozen');
                        target.style.backgroundColor = '#00f';
                        target.style.opacity = '0.5';
                        target.dataset.isFrozen = 'true';

                        setTimeout(() => {
                            if (target.dataset.isFrozen === 'true') {
                                target.classList.remove('frozen');
                                target.style.backgroundColor = '';
                                target.style.opacity = '1';
                                delete target.dataset.isFrozen;
                            }
                        }, 5000);

                        createBurst(newLeft, parseInt(bullet.style.bottom));
                        bullet.remove();
                        clearInterval(bulletInterval);
                        return;
                    }
                }

                // Normal enemies and obstacles: remove on hit
                if (target.classList.contains('enemy') || target.classList.contains('obstacle')) {
                    target.remove();
                    enemies = enemies.filter(e => e !== target);
                    createBurst(newLeft, parseInt(bullet.style.bottom));
                    bullet.remove();
                    clearInterval(bulletInterval);
                    return;
                }

                // Apply other impact effects, if any
                impactCallback(target);

                bullet.remove();
                clearInterval(bulletInterval);
                return;
            }
        }
    }, 1000 / 60);
}
 
function reduceLives() {
    if (player.style.border) {
        player.style.border = '';
        player.style.opacity = '1';
    } else {
        lives--;
        if (lives <= 0) {
            endGame(false); // Call endGame if lives are 0
        } else {
        }
    }
    updateDisplay();
}

function resetBoss() {
    if (boss) {
        if (level === 3) {
            bossHealth = 150; // Restore boss health to 150 for level 3
        } else {
            bossHealth = 100; // Restore boss health for other levels
        }
        updateBossHealth(); // Update the UI to reflect the new health value
    }
}
 
            function checkCollision(rect1, rect2) {
                const rect1Bounds = rect1.getBoundingClientRect();
                const rect2Bounds = rect2.getBoundingClientRect();
                return !(rect1Bounds.top > rect2Bounds.bottom || rect1Bounds.bottom < rect2Bounds.top ||
                        rect1Bounds.left > rect2Bounds.right || rect1Bounds.right < rect2Bounds.left);
            }
 
            function togglePause() {
                if (isPaused) {
                    gameInterval = setInterval(gameLoop, 1000 / 60);
                    isPaused = false;
                } else {
                    clearInterval(gameInterval);
                    isPaused = true;
                }
            }
 
            function clearAllElements() {
                [obstacles, enemies, bullets.map(b => b.element), powerUps, platforms, bossDoors, coins]
                    .forEach(arr => {
                        arr.forEach(el => el.remove());
                        arr.length = 0;
                    });
            }
 


function interact() {
  if (checkCollision(player, friend)) {
    activateFriendDialogue();
  }

  bossDoors.forEach(door => {
    if (checkCollision(player, door)) {
      if (isInBossHallway) {
        log("Already in boss hallway. Cannot enter again.");
        return; // Ignore interaction if already inside
      }

      if (score >= level * bossScoreThreshold) {
        openBossHallway();
        isInBossHallway = true; // Mark player as now inside the boss hallway
        teleportPlayerToBossAndStartFight();
      } else {
        openBossHallway();
      }
    }
  });
}

async function teleportPlayerToBossAndStartFight() {
  if (!boss) {
    log("Boss not present to teleport to.");
    return;
  }

  const teleportDuration = 600; // ms

  // Optional: fade player out
  player.style.transition = `opacity ${teleportDuration / 2}ms ease`;
  player.style.opacity = '0';

  // Wait for fade out
  await new Promise(resolve => setTimeout(resolve, teleportDuration / 2));

  // Compute teleport position near boss - e.g., 60px left of boss center
  const bossLeft = parseInt(boss.style.left);
  const bossBottom = parseInt(boss.style.bottom);

  const teleportX = bossLeft - player.offsetWidth - 20; // 20px gap left of boss
  const teleportY = bossBottom; // Same vertical position (ground level)

  // Apply teleport position
  playerPositionX = teleportX;
  playerPositionY = teleportY;
  player.style.left = playerPositionX + 'px';
  player.style.bottom = playerPositionY + 'px';

  // Optional: fade back in
  player.style.opacity = '1';

  // Wait for fade in
  await new Promise(resolve => setTimeout(resolve, teleportDuration / 2));

  log("Player teleported near boss, starting boss fight...");

  // Hide boss hallway UI if visible (adapt to your IDs)
  if (bossHallway) {
    bossHallway.style.display = 'none';
  }

  // Start boss fight function (your existing)
  startBossFight();
}
 
            function openBossHallway() {
                bossHallway.style.display = 'flex';
                clearAllElements();
                clearInterval(gameInterval);

                isInBossDoor = true;
            }
 
function startBossFight() {
    bossHallway.style.display = 'none';
    isInBossDoor = true; // enable movement restrictions again if desired
    triggerBossFight();
    gameInterval = setInterval(gameLoop, 1000 / 60); // Ensure the game loop is running for updates
}
 
function incrementLevel() {
    level++; // Increment level

    // Check if the level exceeds 3; if so, reset to 1
    if (level > 3) {
        level = 1; // Reset to Level 1
    }

    playerMaxSpeed = 5; // Reset speed back to normal
    localStorage.setItem('playerLevel', level); // Save updated level in local storage
    updateDisplay(); // Update the game display
    resetGame(); // Reset game state


}
 
            function switchLevelBackground() {
                const backgrounds = ['#333', '#1E90FF', '#228B22', '#a3a3a3','#7208c1'];
                gameContainer.style.backgroundColor = backgrounds[(level - 1) % backgrounds.length];
            }
 
            function continueGame() {
                levelIntro.style.display = 'none';
                gameInterval = setInterval(gameLoop, 1000 / 60);
            }

function spawnEndlessEntities() {
    if (!isPaused && !bossFightActive) {
        if (Math.random() < 0.003) spawnObstacle();
        
        // Spawn enemies based on the current level
        if (level === 1) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.003) spawnFlyingEnemy();
            if (Math.random() < 0.002) spawnObstacle();
        } else if (level === 2) {
            if (Math.random() < 0.002) spawnObstacle();
            if (Math.random() < 0.003) spawnChargingEnemy(); // Charging enemy option for Level 2
            if (Math.random() < 0.001) spawnSniperEnemy(); // Sniper enemy option for Level 2
        } else if (level === 3) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.003) spawnFlyingEnemy(); // Flying enemy option for Level 3
            if (Math.random() < 0.001) spawnReflectiveEnemy(); // Reflective enemy option for Level 3
        } else if (level === 4) {
            if (Math.random() < 0.001) spawnLaserEnemy(); // Charging enemy option for Level 2
            if (Math.random() < 0.002) spawnSplitterEnemy();
        } else if (level === 5) {
            if (Math.random() < 0.005) spawnEnemy();
            if (Math.random() < 0.003) spawnVirusDrone(); // Charging enemy option for Level 2
            if (Math.random() < 0.001) spawnSniperEnemy(); // Sniper enemy option for Level 2
        }

        if (Math.random() < 0.002 && !currentPowerUp) spawnPowerUp();
        if (Math.random() < 0.001) spawnPlatform();
        if (Math.random() < 0.003) spawnCoin();



        // Manage boss door spawning only if in Story Mode
        if (localStorage.getItem('gameMode') === 'endless') {
            if (bossDoors.length === 0 && score >= level * bossScoreThreshold && enemies.length === 0) {
                spawnBossDoor();
            }
        }
    }
}


 
function gameLoop() {
  if (!isPaused) {
    updatePlayerPosition();

    const gameMode = localStorage.getItem('gameMode');

    if (gameMode === 'endless') {
      spawnEndlessEntities();
      switchLevelBackground();
    } else if (gameMode === 'story') {
      spawnEntities();
    } else if (gameMode === 'sandbox') {
      level = 1;

      if (spawnEntitiesEnabled) {
        const now = Date.now();
        if (!lastSpawnCheck || (now - lastSpawnCheck) > 200) {  // Check every 200ms
          const spawnFunc = levelSpawnEntitiesMap[spawnEntitiesLevel];
          if (spawnFunc) spawnFunc();
          lastSpawnCheck = now;
        }
      }
    }

    moveElements();
    handlePlayerEnemyCollision();
    updateShopScoreDisplay();
    checkScoreForLevelTransition();
    updateBoostDrainer();
    updateDisplay();
  }
}
 
function endGame(isWin = false) {
    clearInterval(gameInterval);
    
    if (!isWin) {
        // Reset boss health if the game is lost
        resetBoss();
    }
    

    // Display the game over screen with the final score
    gameOverScreen.style.display = 'flex';
    if (localStorage.getItem('gameMode') === 'story') {
        gameOverScreen.innerHTML = `
            <p>${isWin ? 'Congratulations! You won!' : 'Game Over!'}</p>
            <p>Your current score: ${score}</p>
            <button onclick="restartGame2()">Restart</button>
        `;
    } else if (localStorage.getItem('gameMode') === 'endless') {
        gameOverScreen.innerHTML = `
            <p>Endless Mode Over!</p>
            <p>Your score: ${score}</p>
            <button onclick="restartGame()">Restart</button>
        `;
    }
}
 
            function restartGame() {
                gameOverScreen.style.display = 'none';
                resetGame();
                startLevel();
            }

            function restartGame2() {
                gameOverScreen.style.display = 'none';
                resetGame();
                startLevel();
            }
 
            function triggerBossFight() {
                bossFightScreen.style.display = 'flex';
                setTimeout(() => {
                    bossFightScreen.style.display = 'none';
                    startBossLogic();
                }, 2000);
            }
 
            function startBossLogic() {
                bossFightActive = true;
                boss = createElement('boss', [], 600);
                boss.style.bottom = '100px';
                gameWorld.appendChild(boss);
                displayBossHealth();
 
                cycleBossAttacks(); // Start the attack pattern cycle
            }
 
 
 



// Helper function for delay(ms)
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// Example placeholder for displayMessage function
// You need to implement or adjust this to your UI


// New asynchronous cycleBossAttacks function


// Helper to sleep (wait) for milliseconds

// Display a message for specified seconds
async function displayMessageTimed(text, seconds) {
    displayMessage(text, seconds);
    await sleep(seconds * 1000);
}

// Displays all pre-attack messages in sequence, then calls and awaits attackFunc
async function preAttackWithMessage(messages, attackFunc) {
    for (const msg of messages) {
        await displayMessageTimed(msg.text, msg.durationSeconds);
    }
    await attackFunc();
}

async function cycleBossAttacks() {
    if (bossHealth <= 0) {
        if (!bossDefeatedMessageDisplayed) {
            bossDefeatedMessageDisplayed = true;
            await displayMessageTimed("Boss Defeated!", 5);
        }
        return;
    }

    if (!phaseStartTime) {
        phaseStartTime = Date.now();
        bossAttackPhase = 0;
    }

    bossAttacking = true;
    bossShielded = true;
    boss.classList.add('boss-shielded');

    const maxBossMoves = (level === 1) ? 4 : (level === 2) ? 4 : 6;

    switch (level) {
        case 1:
            switch (bossAttackPhase) {
                case 0: await bossEnemyBarrage(); break;
                case 1: await bossTargetSlam(); break;
                case 2: await bossNewPower(); break;
                case 3: await bossExplosionRain(); break;
            }
            break;

        case 2:
            switch (bossAttackPhase) {
                case 0: await bossPhaseTwoBarrage(); break;
                case 1: await bossPhaseTwoTargetSlam(); break;
                case 2: await bossPhaseTwoNewPower(); break;
                case 3: await bossPhaseTwoExplosionRain(); break;
            }
            break;

        case 3:
            if (bossAttackPhase === 0 && (Date.now() - phaseStartTime) < 13000) {
                await startPhaseThree();
                return;
            }
            switch (bossAttackPhase) {
                case 0: await bossPhaseThree(); break;
                case 1: await bossPhaseTwoExplosionRain2(); break;
                case 2: await bossPhaseTwoTargetSlam3(); break;
                case 3: await bossPhaseTwoNewPower2(); break;
                case 4: await bossPhaseTwoTargetSlam2(); break;
                case 5: await bossPhase5(); break;
            }
            break;

        case 4:
            if (bossAttackPhase === 0 && (Date.now() - phaseStartTime) < 13000) {
                await startPhaseFour();
                return;
            }
            switch (bossAttackPhase) {
                case 0:
                    await preAttackWithMessage(
                        [{ text: "Lets start with something simple!", durationSeconds: 4 }],
                        EnemyBarrage
                    );
                    break;
                case 1:
                    await preAttackWithMessage(
                        [{ text: "Incredible, a nice worthy foe.", durationSeconds: 3 }],
                        bossPhaseTwoTargetSlam3
                    );
                    break;
                case 2:
                    await preAttackWithMessage(
                        [{ text: "Well nobody has got this far before, your doing somehow great...", durationSeconds: 4 }],
                        bossPhase5
                    );
                    break;
                case 3:
                    await preAttackWithMessage(
                        [{ text: "How are you NOT DEAD YET?", durationSeconds: 3 }],
                        bossPhaseTwoExplosionRain2
                    );
                    break;
                case 4:
                    await preAttackWithMessage(
                        [{ text: "Your actully getting annoying now...", durationSeconds: 3 }],
                        bossPhaseThree
                    );
                    break;
                case 5:
                    await preAttackWithMessage(
                        [{ text: "Alright let me stop talking now its game on.", durationSeconds: 4 }],
                        slidingLaserPhase
                    );
                    break;
            }
            break;

        case 5:
            switch (bossAttackPhase) {
                case 0: await bossPhaseFiveAttackA(); break;
                case 1: await bossPhaseFiveAttackB(); break;
                case 2: await bossPhaseFiveAttackC(); break;
                case 3: await bossPhaseFiveAttackE(); break;
                case 4: await bossPhaseFiveAttackF(); break;
                case 5: await bossPhaseFiveAttackF(); break;
            }
            break;

        default:
            // You might want to handle unexpected level values here as well
            break;
    }

    // Increment phase for next attack
    bossAttackPhase = (bossAttackPhase + 1) % maxBossMoves;

    // Remove shield after 10s and notify player (fire-and-forget, no await needed)
    setTimeout(() => {
        bossShielded = false;
        boss.classList.remove('boss-shielded');
        displayMessage("Boss shield is OFF! Attack now!");
    }, 10000);
}



async function slidingLaserPhase() {
    displayMessage("Sliding laser phase! Jump over the lasers!", 3);
    await sleep(3000);

    const gameWorld = document.getElementById('game-world');
    const gameBounds = gameWorld.getBoundingClientRect();

    // Laser parameters
    const laserWidth = 150;
    const laserHeight = 20;
    const initialSpeed = 3;
    const maxBounces = 4;

    // Create laser elements
    function createLaserElement(y, direction) {
        const el = document.createElement('div');
        el.style.position = 'absolute';
        el.style.width = laserWidth + 'px';
        el.style.height = laserHeight + 'px';
        el.style.backgroundColor = 'red';
        el.style.bottom = y + 'px';
        el.style.left = (gameBounds.width / 2 - laserWidth / 2) + 'px'; // center horizontally
        el.style.borderRadius = '5px';
        el.style.zIndex = '100';
        gameWorld.appendChild(el);

        return {
            element: el,
            y: y,
            speed: initialSpeed,
            direction: direction,
            bounces: 0,
            destroyed: false,
            get left() {
                return this.element.offsetLeft;
            },
            set left(val) {
                this.element.style.left = val + 'px';
            },
            get right() {
                return this.left + laserWidth;
            },
            remove() {
                if (this.element.parentElement) {
                    this.element.parentElement.removeChild(this.element);
                }
                this.destroyed = true;
            }
        };
    }

    // Instantiate two lasers
    const lasers = [
        createLaserElement(gameBounds.height * 0.3, 1),
        createLaserElement(gameBounds.height * 0.5, -1)
    ];

    // Check collision between laser and player
    function laserCollidesWithPlayer(laser) {
        const laserRect = laser.element.getBoundingClientRect();
        const playerRect = player.getBoundingClientRect();

        return !(
            playerRect.right < laserRect.left ||
            playerRect.left > laserRect.right ||
            playerRect.bottom < laserRect.top ||
            playerRect.top > laserRect.bottom
        );
    }

    return new Promise(resolve => {
        function animate() {
            // If both destroyed, end phase
            if (lasers.every(l => l.destroyed)) {
                displayMessage("Sliding laser phase complete!", 3);
                setTimeout(() => {
                    resolve();
                    cycleBossAttacks();
                }, 3000);
                return;
            }

            lasers.forEach(laser => {
                if (laser.destroyed) return;

                let newLeft = laser.left + laser.speed * laser.direction;

                // Bounce left wall
                if (newLeft <= 0) {
                    newLeft = 0;
                    laser.direction *= -1;
                    laser.bounces++;
                    laser.speed *= 1.3; // speed up

                    if (laser.bounces >= maxBounces) {
                        laser.remove();
                        return;
                    }
                }

                // Bounce right wall
                if (newLeft + laserWidth >= gameBounds.width) {
                    newLeft = gameBounds.width - laserWidth;
                    laser.direction *= -1;
                    laser.bounces++;
                    laser.speed *= 1.3;

                    if (laser.bounces >= maxBounces) {
                        laser.remove();
                        return;
                    }
                }

                laser.left = newLeft;

                // Damage player if colliding
                if (laserCollidesWithPlayer(laser)) {
                    lives = Math.max(0, lives - 1);
                    displayMessage(`Ouch! Lives left: ${lives}`, 1);

                    // Optional knockback or player jump boost can be added here
                }
            });

            requestAnimationFrame(animate);
        }

        animate();
    });
}

function bossPhase5() {
    const blockWidth = 80;
    const blockHeight = 20;

    const lavaRiseSpeed = 4;           // pixels per tick
    const lavaRiseInterval = 100;      // ms
    const warningDuration = 1000;      // 1 second warning before lava rises
    const totalPhases = 3;
    const obstacleWidth = 30;   // Add this line
    const obstacleHeight = 30;  // Add this line
    const platformHeights = [100, 200, 300];
    const laserWarningDuration = 1000; // 1 second yellow warning before laser fires
    const laserPhaseDuration = 6000;   // total laser active time per phase (6 seconds)
    const laserBaseInterval = 1000;    // starting laser shoot interval

    const obstacles = [];
    const warningLines = [];
    const lasers = [];

    const gameWorld = document.getElementById('game-world');

    let currentPhase = 0;
    let lavaHeight = 0;
    let lavaInterval;
    let lastDamageTime = 0;

    // Save original jump settings
    let originalMaxJumps = maxJumps;
    let originalDoubleJumpEnabled = isDoubleJumpEnabled;

    let laserIntervalId = null;
    let laserTimeoutId = null;

    // Create or get lava element
    let lavaElement = gameWorld.querySelector('.lava');
    if (!lavaElement) {
        lavaElement = document.createElement('div');
        lavaElement.className = 'lava';
        Object.assign(lavaElement.style, {
            position: 'absolute',
            width: '100%',
            bottom: '0',
            backgroundColor: 'red',
            height: '0px',
            zIndex: '5',
            transition: 'height 0.1s linear',
        });
        gameWorld.appendChild(lavaElement);
    }

    // Clear existing platforms and obstacles
    function clearPlatformsAndObstacles() {
        obstacles.forEach(o => o.remove());
        obstacles.length = 0;

        const blocks = [...gameWorld.querySelectorAll('div')].filter(el =>
            el.style.backgroundColor === 'blue' &&
            el.offsetWidth === blockWidth &&
            el.offsetHeight === blockHeight
        );
        blocks.forEach(b => b.remove());
    }



    // Create a block platform
    function spawnBlock(x, y) {
        const block = document.createElement('div');
        Object.assign(block.style, {
            position: 'absolute',
            width: blockWidth + 'px',
            height: blockHeight + 'px',
            backgroundColor: 'blue',
            left: x + 'px',
            bottom: y + 'px',
            zIndex: '10',
        });
        gameWorld.appendChild(block);
        return block;
    }

    // Create obstacle near block to jump on
    function spawnObstacle(x, y) {
        const obstacle = document.createElement('div');
        obstacle.className = 'obstacle';
        Object.assign(obstacle.style, {
            position: 'absolute',
            width: obstacleWidth + 'px',
            height: obstacleHeight + 'px',
            backgroundColor: 'orange',
            left: x + 'px',
            bottom: y + 'px',
            zIndex: '10',
        });
        gameWorld.appendChild(obstacle);
        obstacles.push(obstacle);
        return obstacle;
    }

    function spawnPhasePlatforms(phase) {
        clearPlatformsAndObstacles();
        const yPos = platformHeights[phase];
        const xs = [100, 300, 500];

        xs.forEach(x => spawnBlock(x, yPos));
        xs.forEach(x => spawnObstacle(x + 70, yPos));
    }

    // Get player’s distance from bottom of gameWorld
    function getPlayerBottomOffset() {
        const playerRect = player.getBoundingClientRect();
        const worldRect = gameWorld.getBoundingClientRect();
        return worldRect.bottom - playerRect.bottom;
    }

    function setTripleJump() {
        maxJumps = 3;
        isDoubleJumpEnabled = true;
        jumpCount = 0;
    }

    function restoreJumpSettings() {
        maxJumps = originalMaxJumps;
        isDoubleJumpEnabled = originalDoubleJumpEnabled;
        jumpCount = 0;
    }

    function startLavaPhase() {
        displayMessage("Lava is rising soon! Prepare yourself!");
        setTimeout(() => {
            lavaHeight = 0;
            lavaElement.style.height = '0px';
            setTripleJump();
            lavaInterval = setInterval(riseLava, lavaRiseInterval);
        }, warningDuration);
    }

    // Lava rising step
    function riseLava() {
        const maxLavaHeight = platformHeights[currentPhase];

        if (lavaHeight < maxLavaHeight) {
            lavaHeight += lavaRiseSpeed;
            if (lavaHeight > maxLavaHeight) lavaHeight = maxLavaHeight;
            lavaElement.style.height = lavaHeight + 'px';

            const playerBottomPx = parseFloat(player.style.bottom) || 0;
            const playerVelocityDown = playerVelocityY <= 0;

// Remove or comment out this block inside riseLava:


            const now = Date.now();
            if (checkCollision(player, lavaElement)) {
                const playerBottom = getPlayerBottomOffset();
                if (playerBottom < lavaHeight && (now - lastDamageTime) > 1000) {
                    reduceLives();
                    lastDamageTime = now;
                }
            }
        } else {
            clearInterval(lavaInterval);
            startLaserPhase();
        }
    }

    // Create a warning line (yellow) above a block
    function createWarningLine(block) {
        const warning = document.createElement('div');
        warning.style.position = 'absolute';
        warning.style.width = blockWidth + 'px';
        warning.style.height = '5px';
        warning.style.backgroundColor = 'yellow';
        warning.style.left = block.style.left;
        warning.style.bottom = (parseInt(block.style.bottom) + blockHeight) + 'px';
        warning.style.zIndex = '20';
        gameWorld.appendChild(warning);
        warningLines.push(warning);
        return warning;
    }

    // Create a laser beam (red) that shoots upwards from a block
    function createLaser(block) {
        const laser = document.createElement('div');
        laser.style.position = 'absolute';
        laser.style.width = '50px';
        laser.style.height = '200px'; // laser beam height
        laser.style.backgroundColor = 'red';
        laser.style.left = (parseInt(block.style.left) + blockWidth / 2 - 3) + 'px'; // centered on block
        laser.style.bottom = (parseInt(block.style.bottom) + blockHeight) + 'px';
        laser.style.zIndex = '15';
        gameWorld.appendChild(laser);
        lasers.push(laser);

        // Remove laser after 0.5s
        setTimeout(() => {
            laser.remove();
            lasers.splice(lasers.indexOf(laser), 1);
        }, 500);
        return laser;
    }

    // Remove warning lines
    function clearWarningLines() {
        warningLines.forEach(w => w.remove());
        warningLines.length = 0;
    }

    // Remove all active lasers
    function clearLasers() {
        lasers.forEach(l => l.remove());
        lasers.length = 0;
    }

    // Laser phase variables
    let laserPhaseTimer = 0;
    let currentLaserInterval = laserBaseInterval;

    // Laser damage cooldown for player (similar to lava damage)
    let laserLastDamageTime = 0;

    // Laser Phase logic:
    // Every currentLaserInterval ms: choose a random block platform and:
    // - Draw a yellow warning line 1 second before laser fires
    // - After 1s, fire laser & damage player if in laser zone (once per laser)
    function laserTick() {
        if (laserPhaseTimer >= laserPhaseDuration) {
            // Laser phase ended
            clearInterval(laserIntervalId);
            clearWarningLines();
            clearLasers();
            lavaInterval = setInterval(lowerLava, lavaRiseInterval);
            return;
        }

        laserPhaseTimer += currentLaserInterval;

        // Get all current blocks (platforms player can jump on)
        const blocks = [...gameWorld.querySelectorAll('div')].filter(el =>
            el.style.backgroundColor === 'blue' &&
            el.offsetWidth === blockWidth &&
            el.offsetHeight === blockHeight
        );
        if (blocks.length === 0) return;

        // Pick a random block different from last one if possible
        let chosenBlock = blocks[Math.floor(Math.random() * blocks.length)];

        // WARNING LINE
        const warning = createWarningLine(chosenBlock);

        // After 1s fire laser & damage
        setTimeout(() => {
            warning.remove();
            warningLines.splice(warningLines.indexOf(warning), 1);

            const laser = createLaser(chosenBlock);

            // Check if player is in laser zone vertically and horizontally approx.
            const now = Date.now();
            const playerLeftPx = parseFloat(player.style.left) || 0;
            const playerRightPx = playerLeftPx + player.offsetWidth;

            const blockLeft = parseInt(chosenBlock.style.left);
            const blockRight = blockLeft + blockWidth;

            const laserTop = parseInt(laser.style.bottom) + parseInt(laser.style.height);
            const playerBottom = parseFloat(player.style.bottom) || 0;
            const playerTop = playerBottom + player.offsetHeight;

            // Check horizontal overlap
            const horizontalOverlap = playerRightPx > blockLeft && playerLeftPx < blockRight;
            // Check vertical overlap with laser beam
            const verticalOverlap = playerBottom < laserTop && playerTop > parseInt(laser.style.bottom);

            if (horizontalOverlap && verticalOverlap && (now - laserLastDamageTime) > 1000) {
                reduceLives();
                laserLastDamageTime = now;
            }
        }, laserWarningDuration);
    }

    // Lower lava smoothly after laser phase ends
    function lowerLava() {
        if (lavaHeight > 0) {
            lavaHeight -= lavaRiseSpeed;
            if (lavaHeight < 0) lavaHeight = 0;
            lavaElement.style.height = lavaHeight + 'px';

            // Adjust player standing on lava during lowering
            const playerBottomPx = parseFloat(player.style.bottom) || 0;
            const playerVelocityDown = playerVelocityY <= 0;
            if (playerBottomPx < lavaHeight && playerVelocityDown) {
                playerPositionY = lavaHeight;
                playerVelocityY = 0;
                isJumping = false;
                jumpCount = 0;
                player.style.bottom = playerPositionY + 'px';
            }
        } else {
            clearInterval(lavaInterval);
            // Next phase
            currentPhase++;
            if (currentPhase < totalPhases) {
                currentLaserInterval = Math.max(laserBaseInterval - currentPhase * 150, 400); // speeds up laser shooting each phase
                laserPhaseTimer = 0;
                spawnPhasePlatforms(currentPhase);
                startLavaPhase();
            } else {
                displayMessage("Lava and laser phases complete! Prepare for next boss attack.");
                setTimeout(() => {
                    clearPlatformsAndObstacles();
                    lavaElement.style.height = '0px';
                    restoreJumpSettings();
                    cycleBossAttacks();
                }, 2000);
            }
        }
    }

    // Start lava rising phases as before
    currentPhase = 0;
    spawnPhasePlatforms(currentPhase);
    displayMessage("Prepare! Lava will start rising soon!");

    setTimeout(() => {
        startLavaPhase();
    }, 1500);

    // Overwrite startLavaPhase so that after lava rises fully, laser phase starts
    function startLavaPhase() {
        displayMessage("Lava is rising soon! Prepare yourself!");
        setTimeout(() => {
            lavaHeight = 0;
            lavaElement.style.height = '0px';
            setTripleJump();
            lavaInterval = setInterval(riseLava, lavaRiseInterval);
        }, warningDuration);
    }

    // Modify riseLava to start laser phase after rising fully
    function riseLava() {
        const maxLavaHeight = platformHeights[currentPhase];

        if (lavaHeight < maxLavaHeight) {
            lavaHeight += lavaRiseSpeed;
            if (lavaHeight > maxLavaHeight) lavaHeight = maxLavaHeight;
            lavaElement.style.height = lavaHeight + 'px';

            const playerBottomPx = parseFloat(player.style.bottom) || 0;
            const playerVelocityDown = playerVelocityY <= 0;

            if (playerBottomPx < lavaHeight && playerVelocityDown) {
                playerPositionY = lavaHeight;
                playerVelocityY = 0;
                isJumping = false;
                jumpCount = 0;
                player.style.bottom = playerPositionY + 'px';
            }

const now = Date.now();
if (checkCollision(player, lavaElement)) {
    const playerBottom = getPlayerBottomOffset();
    console.log(`Collision! playerBottom=${playerBottom}, lavaHeight=${lavaHeight}`);
    if (playerBottom < lavaHeight && (now - lastDamageTime) > 1000) {
        console.log("Reducing lives from lava collision");
        reduceLives();
        lastDamageTime = now;
    }
}
        } else {
            clearInterval(lavaInterval);
            displayMessage("Warning! Lasers incoming!");
            startLaserPhase();
        }
    }

    // Laser phase start
    function startLaserPhase() {
        laserPhaseTimer = 0;
        laserLastDamageTime = 0;
        laserIntervalId = setInterval(laserTick, currentLaserInterval);

        // Laser phase ends after fixed duration
        laserTimeoutId = setTimeout(() => {
            clearInterval(laserIntervalId);
            clearWarningLines();
            clearLasers();
            displayMessage("Lava retreating... Prepare for next rise!");
            lavaInterval = setInterval(lowerLava, lavaRiseInterval);
        }, laserPhaseDuration);
    }
}

function checkCollisionWithPlatformsAndObstacles() {
    const playerLeft = playerPositionX;
    let playerBottom = playerPositionY;
    const playerWidth = player.offsetWidth;
    const playerHeight = player.offsetHeight;

    let onPlatform = false;

    // Check platforms
    const blocks = [...gameWorld.querySelectorAll('div')].filter(el =>
        el.style.backgroundColor === 'blue' &&
        el.offsetWidth === 80 &&
        el.offsetHeight === 20
    );

    for (const block of blocks) {
        const blockLeft = parseInt(block.style.left);
        const blockBottom = parseInt(block.style.bottom);
        const blockRight = blockLeft + block.offsetWidth;
        const blockTop = blockBottom + block.offsetHeight;

        const horizontalOverlap = playerLeft + playerWidth > blockLeft && playerLeft < blockRight;
        const nextPlayerBottom = playerBottom + playerVelocityY;

        if (
            horizontalOverlap &&
            playerBottom >= blockTop &&
            nextPlayerBottom <= blockTop &&
            playerVelocityY <= 0
        ) {
            playerPositionY = blockTop;
            playerVelocityY = 0;
            isJumping = false;
            jumpCount = 0;
            onPlatform = true;
            break;
        } else if (
            horizontalOverlap &&
            playerBottom >= blockTop - 1 &&
            playerBottom <= blockTop + 1 &&
            playerVelocityY === 0
        ) {
            playerPositionY = blockTop;
            isJumping = false;
            jumpCount = 0;
            onPlatform = true;
            break;
        }
    }

    // Check obstacles with same logic
    for (const obstacle of obstacles) {
        const obLeft = parseInt(obstacle.style.left);
        const obBottom = parseInt(obstacle.style.bottom);
        const obRight = obLeft + obstacle.offsetWidth;
        const obTop = obBottom + obstacle.offsetHeight;

        const horizontalOverlap = playerLeft + playerWidth > obLeft && playerLeft < obRight;
        const nextPlayerBottom = playerBottom + playerVelocityY;

        if (
            horizontalOverlap &&
            playerBottom >= obTop &&
            nextPlayerBottom <= obTop &&
            playerVelocityY <= 0
        ) {
            playerPositionY = obTop;
            playerVelocityY = 0;
            isJumping = false;
            jumpCount = 0;
            onPlatform = true;
            break;
        } else if (
            horizontalOverlap &&
            playerBottom >= obTop - 1 &&
            playerBottom <= obTop + 1 &&
            playerVelocityY === 0
        ) {
            playerPositionY = obTop;
            isJumping = false;
            jumpCount = 0;
            onPlatform = true;
            break;
        }
    }

    return onPlatform;
}

function bossPhaseTwoTargetSlam2() {
    const warningLineHeight = 5; // Height of the warning line
    const rodWidth = 80; // Width of the laser rod
    const rodHeight = 300; // Height of the rod
    const rodColor = 'red'; // Color of the rod
    const laserSpawnTime = 500; // Time between spawn of lasers
    const totalWarnings = 12; // Total number of laser warnings
    let warningCount = 0; // Counter for warnings
    const warningPositions = []; // Store positions for warnings

    function spawnWarningLine() {
        // Create a warning line
        const warningLine = document.createElement('div');
        warningLine.classList.add('warning-line');
        warningLine.style.width = '80px'; // Width of the warning line
        warningLine.style.height = `${warningLineHeight}px`;
        warningLine.style.backgroundColor = 'yellow'; // Set color
        warningLine.style.position = 'absolute';
        const warningLinePosition = Math.random() * (gameContainer.offsetWidth - 80); // Random horizontal position
        warningLine.style.left = `${warningLinePosition}px`; // Set position
        warningLine.style.bottom = '50px'; // Slightly above player position
        gameWorld.appendChild(warningLine);

        // Wait for 0.5 seconds, then spawn the laser rod above
        setTimeout(() => {
            // Create a rod above the warning line
            const rod = document.createElement('div');
            rod.classList.add('rod'); // Add a class for styling
            rod.style.width = `${rodWidth}px`;
            rod.style.height = `${rodHeight}px`;
            rod.style.backgroundColor = rodColor;
            rod.style.position = 'absolute';
            rod.style.left = `${warningLinePosition + 25}px`; // Center the rod above the warning line
            rod.style.bottom = '0px'; // Start at ground level

            gameWorld.appendChild(rod); // Add rod to the game world

            // Damage player if they are still there
            if (checkCollision(player, rod)) {
                reduceLives(); // Damage the player
            }

            // Remove the rod after a brief duration
            setTimeout(() => {
                rod.remove(); // Clean up after the rod
            }, 200); // Keep the rod visible for 200 ms

            // Remove the warning line
            warningLine.remove();
        }, 500); // Spawn the rod after 500 milliseconds
    }

    // Spawn warning lines and lasers at intervals
    const spawnWarningsInterval = setInterval(() => {
        if (warningCount >= totalWarnings) {
            clearInterval(spawnWarningsInterval); // Stop after total warnings
            cycleBossAttacks(); // Proceed to the next boss cycle
            return; // Exit the function
        }

        spawnWarningLine(); // Spawn a warning line
        warningCount++; // Increase warning count
    }, laserSpawnTime); // Spawn a warning every 500 ms
}

function bossPhaseTwoNewPower2() {
    const laserCount = 3;               // Number of lasers per burst
    const laserRadius = 80;             // Distance lasers start from boss center (for initial pos)
    const laserWidth = 20;
    const laserHeight = 20;
    const laserColor = 'red';
    const healColor = 'green';
    const healChance = 0.2;
    const maxBursts = 8;
    const laserInterval = 2000;         // Time between bursts

    let burstCount = 0;

    const bounceLimit = 1; // Number of bounces before laser is destroyed

    // Assume these globals (define globally)
    // const boss = document.getElementById('boss');
    // const player = document.getElementById('player');
    // const gameWorld = document.getElementById('gameWorld');

    // Get game world boundaries once
    const worldRect = gameWorld.getBoundingClientRect();

    function createLasers() {
        const bossRect = boss.getBoundingClientRect();

        for (let i = 0; i < laserCount; i++) {
            const angle = (i * 2 * Math.PI) / laserCount; // spread lasers evenly around circle

            // Create laser element
            const laser = document.createElement('div');
            laser.classList.add('laser');
            laser.style.position = 'absolute';
            laser.style.width = `${laserWidth}px`;
            laser.style.height = `${laserHeight}px`;
            laser.style.backgroundColor = laserColor;
            laser.style.borderRadius = '2px';

            // Initial position roughly at boss position + offset by radius along angle
            // Calculate relative to gameWorld top-left (absolute positioning)
            const startX = bossRect.left + bossRect.width/2 + Math.cos(angle)*laserRadius - laserWidth/2;
            const startY = bossRect.top + bossRect.height/2 + Math.sin(angle)*laserRadius - laserHeight/2;

            laser.style.left = `${startX}px`;
            laser.style.top = `${startY}px`;

            gameWorld.appendChild(laser);

            // Velocity vector (pixels per frame)
            // Let's say speed = 4px per frame (~60fps, adjust as needed)
            const speed = 4;
            let vx = Math.cos(angle)*speed;
            let vy = Math.sin(angle)*speed;

            let bounces = 0;

            // Use requestAnimationFrame for smooth animation
            function animate() {
                if (!laser.parentElement) return; // Laser removed/destroyed

                // Current position
                let x = parseFloat(laser.style.left);
                let y = parseFloat(laser.style.top);

                // Move laser
                x += vx;
                y += vy;

                // Check boundaries (bounce off gameWorld edges)
                if (x <= 0) { 
                    x = 0;
                    vx = -vx;
                    bounces++;
                }
                if (y <= 0) { 
                    y = 0;
                    vy = -vy;
                    bounces++;
                }
                if (x + laserWidth >= worldRect.width) {
                    x = worldRect.width - laserWidth;
                    vx = -vx;
                    bounces++;
                }
                if (y + laserHeight >= worldRect.height) {
                    y = worldRect.height - laserHeight;
                    vy = -vy;
                    bounces++;
                }

                laser.style.left = `${x}px`;
                laser.style.top = `${y}px`;

                // Collision with player
                // Here you can improve detection, currently simple AABB
                const playerRect = player.getBoundingClientRect();
                const laserRect = laser.getBoundingClientRect();

                if (!(playerRect.right < laserRect.left ||
                    playerRect.left > laserRect.right ||
                    playerRect.bottom < laserRect.top ||
                    playerRect.top > laserRect.bottom)) {

                    // On collision, heal or damage once:
                    if (Math.random() < healChance) {
                        gainExtraLife && gainExtraLife();
                    } else {
                        reduceLives();
                    }

                    // Remove laser immediately on hit
                    laser.remove();
                    return;
                }

                // Remove laser after 2 bounces
                if (bounces > bounceLimit) {
                    laser.remove();
                    return;
                }

                requestAnimationFrame(animate);
            }

            requestAnimationFrame(animate);
        }
    }

    // Interval that runs burstCount times, then stops
    const laserBurstInterval = setInterval(() => {
        if (burstCount >= maxBursts) {
            clearInterval(laserBurstInterval);
            cycleBossAttacks && cycleBossAttacks();
            return;
        }

        createLasers();
        burstCount++;
    }, laserInterval);
}



// Call function to test
// bossPhaseTwoNewPower2();


function startPhaseThree() {
    if (phaseThreeStarted) return; // Prevent running it multiple times
    phaseThreeStarted = true; // Set flag to true once started

    initializeBossHealth(); // Sets the boss health based on the current level

    const messages = [
        "Player: Oh god what is this",
        "Boss: All the moves and powers i had...",
        "Boss: But this time your not going to get pass this.",
        "Boss: This is your final game",
        "Player: alright lets take a bet on that!",
    ];

    let phase3MessageIndex = 0; // Track which message is currently displayed

    function displayMessages() {
        if (phase3MessageIndex < messages.length) {
            displayMessage(messages[phase3MessageIndex]);
            phase3MessageIndex++;
            setTimeout(displayMessages, 3000); // Display the next message after 3 seconds
        } else {
            // Once messages are done, start the boss attack cycle
            cycleBossAttacks(); // Start boss attacks
        }
    }

    displayMessages(); // Start displaying messages
}



// Wait until boss exists, then change color
function changeBossColorBlue() {
  if (!boss) {
    console.warn("Boss element not ready!");
    return;
  }
  boss.style.backgroundColor = 'blue';
}

function changeBossColorBlue2() {
  if (!boss) {
    console.warn("Boss element not ready!");
    return;
  }
  boss.style.backgroundColor = 'yellow';
}

// Call it when appropriate, no await needed
function startPhaseFour() {
    console.log("startPhaseFour called");

    if (typeof phaseThreeStarted === "undefined") {
        console.error("phaseThreeStarted is not defined!");
    }
    if (phaseThreeStarted) {
        console.log("Phase 3 already started.");
        return;
    }
    phaseThreeStarted = true;
    console.log("Starting Phase Four logic.");

    if (typeof initializeBossHealth !== "function") {
        console.error("initializeBossHealth is not defined!");
    }
    initializeBossHealth();

    // Set up level-specific behaviors
    let messages;
    let preMessageFunction = function() {};
    let endMessageFunction = function() {};

    console.log("Level:", level);

    if (level === 4) {
        messages = [
            "Boss: Well well well...",
            "Boss: THIS? is what my brother was talking about!",
            "Boss: You look so weak haha..",
            "Boss: Well i should introduce myself",
            "Boss: Im the strongest cube ever!",
            "Player: Well he just told me that already so a big flex ig...",
            "Boss: Intersting... you seem somewhat smart.",
            "Player: Well knowing this is the last boss fight i will end you!...",
            "Boss: Alright lets get started then!",
        ];
        preMessageFunction = changeBossColorBlue;
        endMessageFunction = cycleBossAttacks;
    } else if (level === 5) {
        messages = [
            "System: Welcome to your final test.",
            "Player: What do you mean?",
            "System: To unlock life you must win..",
            "Player: Alright lets do it!",
        ];
        preMessageFunction = changeBossColorBlue2;
        endMessageFunction = cycleBossAttacks;
    } else {
        messages = [
            "Boss: Well well well...",
            "Boss: THIS? is what my brother was talking about!",
            "Boss: You look so weak haha..",
            "Boss: Well i should introduce myself",
            "Boss: Im the strongest cube ever!",
            "Player: Well he just told me that already so a big flex ig...",
            "Boss: Intersting... you seem somewhat smart.",
            "Player: Well knowing this is the last boss fight i will end you!...",
            "Boss: Alright lets get started then!",
        ];
        preMessageFunction = changeBossColorBlue;
        endMessageFunction = cycleBossAttacks;
    }
    if (typeof preMessageFunction !== "function") {
        console.error("preMessageFunction is not a function!");
    }
    preMessageFunction();

    let phase3MessageIndex = 0;

    function displayMessages() {
        if (phase3MessageIndex < messages.length) {
            if (typeof displayMessage !== "function") {
                console.error("displayMessage is not defined!");
            }
            displayMessage(messages[phase3MessageIndex]);
            phase3MessageIndex++;
            setTimeout(displayMessages, 3000);
        } else {
            if (typeof endMessageFunction !== "function") {
                console.error("endMessageFunction is not a function!");
            }
            cycleBossAttacks();
        }
    }

    displayMessages();
}



function startPhaseFive() {
    if (phaseThreeStarted) return;
    phaseThreeStarted = true;

    initializeBossHealth();
    changeBossColorBlue2();

    const messages = [
        "System: Welcome to your final test.",
        "Player: What do you mean?",
        "System: To unlock life you must win..",
        "Player: Alright lets do it!",
    ];

    let phase3MessageIndex = 0;

    function displayMessages() {
        if (phase3MessageIndex < messages.length) {
            console.log("Displaying message:", messages[phase3MessageIndex]);
            displayMessage(messages[phase3MessageIndex]);
            phase3MessageIndex++;
            setTimeout(displayMessages, 3000);
        } else {
            console.log("Messages done. Starting boss attacks...");
            cycleBossAttacks();
        }
    }

    displayMessages();
}


function bossPhaseTwoTargetSlam() {
  const maxSlams = 4;
  const groundLevel = 0;
  const hoverHeight = 100;
  const slamDurationDown = 400;    // Faster slam down
  const slamHoldDuration = 1200;   // Hold slam a bit shorter
  const slamDurationUp = 600;      // Faster slam up
  const slamCooldown = 700;        // Faster cooldown between slams

  // Reduce lives should be defined globally / externally
  // This function just calls it
  function reduceLives() {
    if (lives > 0) {
      lives--;
      console.log("Player hit by boss slam! Lives Remaining:", lives);
      // Trigger additional feedback if needed
    }
  }

  function createBurst(x, y) {
    // Your burst effect implementation here
    console.log(`Burst at (${x}, ${y})`);
  }

  // Animate CSS bottom property with transition and Promise-based resolution
  function animateBottomPosition(targetBottom, duration) {
    return new Promise((resolve) => {
      let resolved = false;

      function onTransitionEnd(e) {
        if (e.propertyName === 'bottom' && !resolved) {
          resolved = true;
          boss.removeEventListener('transitionend', onTransitionEnd);
          resolve();
        }
      }

      boss.addEventListener('transitionend', onTransitionEnd);
      boss.style.transition = `bottom ${duration}ms ease-in-out`;
      boss.style.bottom = `${targetBottom}px`;

      // Safety fallback if transitionend does not fire
      setTimeout(() => {
        if (!resolved) {
          resolved = true;
          boss.removeEventListener('transitionend', onTransitionEnd);
          resolve();
        }
      }, duration + 50);
    });
  }

  // Get bounding rects for player, boss, and boss parent
  function getRects() {
    return {
      playerRect: player.getBoundingClientRect(),
      bossRect: boss.getBoundingClientRect(),
      parentRect: boss.parentElement.getBoundingClientRect()
    };
  }

  // Axis-aligned bounding box collision detection
  function isCollision(rect1, rect2) {
    return !(
      rect1.right < rect2.left ||
      rect1.left > rect2.right ||
      rect1.bottom < rect2.top ||
      rect1.top > rect2.bottom
    );
  }

  // Monitor collision during slam hold, damage max once per second
  function monitorCollisionDuringSlam(duration) {
    return new Promise((resolve) => {
      const hitCooldown = 1000; // ms between allowed hits
      let lastHitTimestamp = 0;
      const startTime = performance.now();

      function check(time) {
        if (time - startTime >= duration) {
          resolve();
          return;
        }

        const { playerRect, bossRect } = getRects();

        if (isCollision(playerRect, bossRect)) {
          if (time - lastHitTimestamp > hitCooldown && lives > 0) {
            reduceLives();
            lastHitTimestamp = time;
            shakeScreen(); // Assuming you defined shakeScreen globally
          }
        }

        if (lives <= 0) {
          resolve(); // Stop if no lives left
          return;
        }

        requestAnimationFrame(check);
      }

      requestAnimationFrame(check);
    });
  }

  async function performSlam() {
    let slamCount = 0;

    while (slamCount < maxSlams) {
      // Position boss instantly above player horizontally
      const { playerRect, parentRect } = getRects();
      const playerCenterX = playerRect.left - parentRect.left + playerRect.width / 2;

      boss.style.transition = 'none';
      boss.style.left = `${playerCenterX - boss.offsetWidth / 2}px`;
      boss.style.bottom = `${hoverHeight}px`;

      // Wait for next frame so changes apply
      await new Promise(resolve => requestAnimationFrame(resolve));

      // Shorter hover pause for snappier feel
      await new Promise(resolve => setTimeout(resolve, 300));

      shakeScreen();

      // Slam down
      await animateBottomPosition(groundLevel, slamDurationDown);

      createBurst(playerCenterX, groundLevel);

      // Hold slam while monitoring collision damage
      await monitorCollisionDuringSlam(slamHoldDuration);

      // Slam back up
      await animateBottomPosition(hoverHeight, slamDurationUp);

      slamCount++;

      // Cooldown before next slam
      await new Promise(resolve => setTimeout(resolve, slamCooldown));
    }

    console.log("Slam attack finished");

    if (typeof resetBossPosition === 'function') {
      resetBossPosition();
    }

    if (typeof cycleBossAttacks === 'function') {
      setTimeout(cycleBossAttacks, 5000); // Faster cycle after slam attack
    }
  }

  performSlam();
}

function bossPhaseTwoTargetSlam3() {
    let slamCount = 0;
    const maxSlams = 6;
    const groundLevel = 0;   
    const hoverHeight = 100; 
    const slamDurationDown = 200;
    const slamHoldDuration = 1000;
    const slamDurationUp = 700;
    const slamCooldown = 450;
    let slamActive = false;

    // assuming boss and player are defined globally or in the outer scope
    // e.g. const boss = document.getElementById('boss');
    // const player = document.getElementById('player');

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function monitorCollisionDuringSlam(duration) {
        const startTime = Date.now();
        let lastHitTime = 0;   // added to throttle reduceLives

        return new Promise((resolve) => {
            const interval = setInterval(() => {
                const now = Date.now();
                if (now - startTime >= duration) {
                    clearInterval(interval);
                    resolve();
                    return;
                }

                if (checkCollision(player, boss)) {
                    // Only reduce lives if at least 1000ms (1 second) passed since last hit
                    if (now - lastHitTime >= 1000) {
                        reduceLives();
                        console.log("Player hit by the boss slam! Lives Remaining: " + lives);
                        lastHitTime = now;
                    }
                }
            }, 50);
        });
    }

    function animateBottomPosition(targetBottom, duration) {
        return new Promise(resolve => {
            function onTransitionEnd(event) {
                if (event.propertyName === 'bottom') {
                    boss.removeEventListener('transitionend', onTransitionEnd);
                    resolve();
                }
            }
            boss.addEventListener('transitionend', onTransitionEnd);
            void boss.offsetWidth;
            boss.style.transition = `bottom ${duration}ms ease-in-out`;
            boss.style.bottom = `${targetBottom}px`;
        });
    }

    async function performSlam() {
        while (slamCount < maxSlams) {
            slamActive = true;

            const playerRect = player.getBoundingClientRect();
            const parentRect = boss.parentElement.getBoundingClientRect();

            const playerX = playerRect.left - parentRect.left + playerRect.width / 2;

            boss.style.transition = 'none';
            boss.style.left = `${playerX - boss.offsetWidth / 2}px`;
            boss.style.bottom = `${hoverHeight}px`;

            await sleep(250);

            shakeScreen();

            await animateBottomPosition(groundLevel, slamDurationDown);

            createBurst(playerX, groundLevel);

            await monitorCollisionDuringSlam(slamHoldDuration);

            await animateBottomPosition(hoverHeight, slamDurationUp);

            slamCount++;
            slamActive = false;

            await sleep(slamCooldown);
        }

        console.log('Slam attack finished');
        resetBossPosition();
        setTimeout(cycleBossAttacks, 10000);
    }

    performSlam();
}

function bossTargetSlam() {
    let slamCount = 0;
    const maxSlams = 4;
    const groundLevel = 0;   
    const hoverHeight = 100; 
    const slamDurationDown = 500;   
    const slamHoldDuration = 1500;  
    const slamDurationUp = 700;     
    const slamCooldown = 1000;      

    // Track if a slam is currently active
    let slamActive = false;

    // Promise-based sleep
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // Collision check: AABB rectangle intersection
    function checkCollision(elem1, elem2) {
        const r1 = elem1.getBoundingClientRect();
        const r2 = elem2.getBoundingClientRect();
        return !(
            r1.right < r2.left ||
            r1.left > r2.right ||
            r1.bottom < r2.top ||
            r1.top > r2.bottom
        );
    }

    // Placeholder for player's lives remaining, define accordingly
    let lives = 3;

    // Reduces player's lives safely
reduceLives();

    // Shake screen effect placeholder — implement your own or remove

shakeScreen();

    // Create burst effect placeholder — implement as needed
    function createBurst(x, y) {
        console.log(`Burst at (${x}, ${y})`);
    }

    // Animate bottom position with transition and Promise
    function animateBottomPosition(targetBottom, duration) {
        return new Promise(resolve => {
            function onTransitionEnd(event) {
                if (event.propertyName === 'bottom') {
                    boss.removeEventListener('transitionend', onTransitionEnd);
                    resolve();
                }
            }
            boss.addEventListener('transitionend', onTransitionEnd);

            // Force reflow to apply transition properly
            void boss.offsetWidth;

            boss.style.transition = `bottom ${duration}ms ease-in-out`;
            boss.style.bottom = `${targetBottom}px`;
        });
    }

    // Monitor collision during slamHoldDuration, but only reduce lives once per second max
    async function monitorCollisionDuringSlam(duration) {
        return new Promise((resolve) => {
            let lastHitTime = 0;

            const interval = setInterval(() => {
                const now = Date.now();

                if (now - lastHitTime >= 1000 && checkCollision(player, boss)) {
                    reduceLives();
                    lastHitTime = now;
                }

                if (now >= startTime + duration) {
                    clearInterval(interval);
                    resolve();
                }
            }, 50);

            const startTime = Date.now();
        });
    }

    async function performSlam() {
        while (slamCount < maxSlams) {
            slamActive = true;

            // Calculate player and boss parent positions to align boss over player horizontally
            const playerRect = player.getBoundingClientRect();
            const parentRect = boss.parentElement.getBoundingClientRect();

            // Player center X inside boss parent container
            const playerX = playerRect.left - parentRect.left + playerRect.width / 2;

            // Position boss instantly above player at hover height
            boss.style.transition = 'none';
            boss.style.left = `${playerX - boss.offsetWidth / 2}px`;
            boss.style.bottom = `${hoverHeight}px`;

            await sleep(500); // hover delay

            shakeScreen();

            // Slam down
            await animateBottomPosition(groundLevel, slamDurationDown);

            createBurst(playerX, groundLevel);

            // Check collision during slam hold, max once per 1000ms
            await monitorCollisionDuringSlam(slamHoldDuration);

            // Slam back up
            await animateBottomPosition(hoverHeight, slamDurationUp);

            slamCount++;
            slamActive = false;

            await sleep(slamCooldown);
        }

        console.log("Slam attack finished");
        if (typeof resetBossPosition === 'function') {
            resetBossPosition();
        }
        if (typeof cycleBossAttacks === 'function') {
            setTimeout(cycleBossAttacks, 10000);
        }
    }

    performSlam();
}







function bossPhaseTwoNewPower() {
    let bossSlideCount = 0; // Count how many times the boss has slid side to side
    const bossMaxSlides = 5; // Maximum number of slides
    let direction = 1; // 1 for right, -1 for left
    let canDamagePlayer = true; // Flag to control damage timing
    
    // Set the boss to ground level and an initial position
    boss.style.bottom = '0px'; // Set boss to ground level
    boss.style.left = '50px'; // Starting position; adjust as needed

    // Get the width of the game world for boundary checks
    const gameWorldWidth = gameWorld.offsetWidth;

    // Interval to move the boss
    const slideInterval = setInterval(() => {
        // Move the boss
        const currentLeft = parseInt(boss.style.left);
        const nextLeft = currentLeft + (4 * direction); // Move by 4 pixels

        // Check for wall collision
        if (nextLeft < 0 || nextLeft + boss.offsetWidth > gameWorldWidth) {
            direction *= -1; // Reverse direction upon hitting the wall
            bossSlideCount++; // Increment the slide count
            
            // Bounce back the boss a little to ensure it doesn't stay stuck
            boss.style.left = (currentLeft + (4 * direction)) + 'px'; // Adjust position slightly after collision
        } else {
            boss.style.left = nextLeft + 'px'; // Move the boss
        }

        // Check collision with the player
        if (checkCollision(boss, player)) {
            // Reduce lives every second when colliding
            if (canDamagePlayer) {
                reduceLives(); // Damage the player if they collide with the boss
                canDamagePlayer = false; // Prevent further damage until the cooldown
                setTimeout(() => {
                    canDamagePlayer = true; // Reset after 1 second
                }, 1000);
            }
        }

        // Stop sliding after the specified number of slides and trigger the next boss cycle
        if (bossSlideCount >= bossMaxSlides) {
            clearInterval(slideInterval); // Stop the sliding movement
            resetBossPosition();
            cycleBossAttacks(); // Call this function to start the next boss cycle
        }
    }, 3); // Faster interval for rapid movement
}


function bossPhaseTwoExplosionRain2() {
    const blockWidth = 30; // Width of the falling blocks
    const blockHeight = 10; // Height of the falling blocks
    const blockSpeed = 5; // Speed of block movement (pixels per frame)
    const blocks = []; // Array to hold active blocks
    const spawnInterval = 500; // Time between block spawns (in milliseconds)
    const duration = 15000; // Total duration of the attack (in milliseconds)
    const leftRightDuration = 5500; // Move blocks left/right for 3 seconds
    const upDownDuration = duration - leftRightDuration; // Then move blocks up/down for 7 seconds

    // Keep track of current phase
    let phase = 'leftRight'; // 'leftRight' or 'upDown'
    let phaseStartTime = performance.now();

    // Function to spawn a block for the left/right phase
    function spawnBlockLeftRight() {
        const block = document.createElement('div');
        block.classList.add('explosive-block');
        block.style.width = `${blockWidth}px`;
        block.style.height = `${blockHeight}px`;
        block.style.position = 'absolute';
        block.style.backgroundColor = 'red';

        // Spawn from left or right side randomly
        const fromLeft = Math.random() < 0.5;
        block.dataset.fromLeft = fromLeft; // Store direction in dataset

        // Set initial horizontal position (off screen)
        block.style.left = fromLeft ? `${-blockWidth}px` : `${window.innerWidth}px`;
        // Random vertical position on screen
        block.style.bottom = `${Math.random() * (window.innerHeight - blockHeight)}px`;
        document.body.appendChild(block);

        blocks.push(block);
    }

    // Function to spawn a block for the up/down phase
    function spawnBlockUpDown() {
        const block = document.createElement('div');
        block.classList.add('explosive-block');
        block.style.width = `${blockWidth}px`;
        block.style.height = `${blockHeight}px`;
        block.style.position = 'absolute';
        block.style.backgroundColor = 'red';

        // Spawn from bottom or top randomly
        const fromBottom = Math.random() < 0.5;
        block.dataset.fromBottom = fromBottom;

        // Random horizontal position on the screen
        block.style.left = `${Math.random() * (window.innerWidth - blockWidth)}px`;
        // Initial vertical position (off screen)
        block.style.bottom = fromBottom ? `${-blockHeight}px` : `${window.innerHeight}px`;
        document.body.appendChild(block);

        blocks.push(block);
    }

    // Function to update/move the blocks based on current phase
    function updateBlocks() {
        for (let i = blocks.length - 1; i >= 0; i--) {
            const block = blocks[i];
            if (!document.body.contains(block)) { 
                // Remove any blocks that were removed from DOM
                blocks.splice(i, 1);
                continue;
            }

            if (phase === 'leftRight') {
                // Move horizontally toward center of screen
                let currentLeft = parseFloat(block.style.left);
                const moveDir = block.dataset.fromLeft === 'true' ? 1 : -1; // left->right is +1, right->left is -1
                const newLeft = currentLeft + (blockSpeed * moveDir);
                block.style.left = `${newLeft}px`;

                // If block moved completely off screen past opposite side, remove it
                if (moveDir === 1 && newLeft > window.innerWidth) {
                    block.remove();
                    blocks.splice(i, 1);
                    continue;
                }
                if (moveDir === -1 && newLeft < -blockWidth) {
                    block.remove();
                    blocks.splice(i, 1);
                    continue;
                }
            } else if (phase === 'upDown') {
                // Move blocks vertically up or down
                let currentBottom = parseFloat(block.style.bottom);
                const moveDir = block.dataset.fromBottom === 'true' ? 1 : -1; // bottom->top = +1, top->bottom = -1
                const newBottom = currentBottom + (blockSpeed * moveDir);
                block.style.bottom = `${newBottom}px`;

                // Remove if off screen vertically
                if (moveDir === 1 && newBottom > window.innerHeight) {
                    block.remove();
                    blocks.splice(i, 1);
                    continue;
                }
                if (moveDir === -1 && newBottom < -blockHeight) {
                    block.remove();
                    blocks.splice(i, 1);
                    continue;
                }
            }

            // Check collision with player (assuming player is accessible globally)
            if (checkCollision(player, block)) {
                reduceLives();
                block.remove();
                blocks.splice(i, 1);
            }
        }
    }

    // Interval to spawn blocks depending on the phase
    let spawnBlocksInterval = setInterval(() => {
        if (phase === 'leftRight') {
            spawnBlockLeftRight();
        } else if (phase === 'upDown') {
            spawnBlockUpDown();
        }
    }, spawnInterval);

    // Animation frame loop to move blocks
    function animationLoop() {
        const now = performance.now();

        // Switch phase after respective time
        if (phase === 'leftRight' && now - phaseStartTime >= leftRightDuration) {
            phase = 'upDown';
            phaseStartTime = now;

            // Remove all existing blocks from leftRight phase immediately
            blocks.forEach(block => block.remove());
            blocks.length = 0;
        } else if (phase === 'upDown' && now - phaseStartTime >= upDownDuration) {
            // End attack and clean up
            clearInterval(spawnBlocksInterval);
            blocks.forEach(block => block.remove());
            blocks.length = 0;
            cycleBossAttacks();
            return; // Stop the animation loop
        }

        updateBlocks();
        requestAnimationFrame(animationLoop);
    }

    requestAnimationFrame(animationLoop);
}



function spawnBoostDrainer() {
    if (boostDrainer) return;

    const spawnX = gameScrollPosition + gameContainer.offsetWidth + 50;
    const spawnY = Math.random() * 200 + 50;

    boostDrainer = document.createElement('div');
    boostDrainer.classList.add('boost-drainer');
    boostDrainer.style.left = spawnX + 'px';
    boostDrainer.style.bottom = spawnY + 'px';
    gameWorld.appendChild(boostDrainer);

    // Create chain element
    boostDrainerChain = document.createElement('div');
    boostDrainerChain.classList.add('boost-drainer-chain');
    gameWorld.appendChild(boostDrainerChain);

    boostDrainerHP = 3;
    boostDrainerState = "moving"; // Start moving state
}

// Call this inside your main game loop or movement update function
function updateBoostDrainer() {
    if (!boostDrainer) return;

    const playerX = playerPositionX;
    let enemyX = parseInt(boostDrainer.style.left);

    switch (boostDrainerState) {
        case 'moving':
            const targetX = playerX + boostDrainerAttackXOffset;

            if (enemyX > targetX) {
                enemyX -= boostDrainerSpeed;
                boostDrainer.style.left = enemyX + 'px';
            } else {
                // Reached attack position, start attack cycle
                boostDrainerState = 'green';
                boostDrainer.style.backgroundColor = 'green'; // Visual green state
                boostDrainer.classList.remove('yellow', 'red');

                boostDrainerAttackTimeout = setTimeout(() => {
                    boostDrainerState = 'yellow';
                    boostDrainer.style.backgroundColor = 'yellow';
                    boostDrainer.classList.add('yellow');
                    
                    boostDrainerAttackTimeout = setTimeout(() => {
                        boostDrainerState = 'red';
                        boostDrainer.style.backgroundColor = 'red';
                        boostDrainer.classList.remove('yellow');
                        boostDrainer.classList.add('red');

                        fireBoostDrainerLaser(3); // Repeat laser fire 3 times
                    }, 1000);
                }, 1000);
            }
            break;
        // other states can be no movement
        default:
            break;
    }

    // Update the chain line only when moving or in states where player and drainer exist
    if (boostDrainerChain) {
        updateChainLine(boostDrainer, boostDrainerChain, player);
    }
}

function fireBoostDrainerLaser(timesLeft) {
    if (!boostDrainer || timesLeft <= 0) {
        removeBoostDrainer();
        return;
    }

    boostDrainerState = 'firing';

    // Create laser div or reuse existing laser if you want smooth transition
    if (boostDrainerLaser) {
        boostDrainerLaser.remove();
        boostDrainerLaser = null;
    }

    boostDrainerLaser = document.createElement('div');
    boostDrainerLaser.classList.add('boost-laser');

    const left = parseInt(boostDrainer.style.left) + boostDrainer.offsetWidth / 2 - 2; 
    boostDrainerLaser.style.left = left + 'px';
    boostDrainerLaser.style.bottom = '0px';
    
    // Laser height can be fixed or adjusted dynamically
    boostDrainerLaser.style.height = '120px';

    gameWorld.appendChild(boostDrainerLaser);

    // Laser stays visible for 0.75s, then disappear, and wait 0.5s before next fire
    setTimeout(() => {
        if(boostDrainerLaser) {
            boostDrainerLaser.remove();
            boostDrainerLaser = null;
        }
        boostDrainerState = 'red'; // Can reset state or handle as needed
        
        setTimeout(() => {
            fireBoostDrainerLaser(timesLeft -1);
        }, 500);
    }, 750);
}

// Update the dotted chain line between two elements
function updateChainLine(fromEl, lineEl, toEl) {
    if (!fromEl || !lineEl || !toEl) return;

    // Get bounding rectangles
    const fromRect = fromEl.getBoundingClientRect();
    const toRect = toEl.getBoundingClientRect();
    const containerRect = gameWorld.getBoundingClientRect();

    // Calculate center point within gameWorld coordinates
    // relative to gameWorld's top-left corner BUT we position absolute with bottom coordinate,
    // so invert Y relative to container
    function centerX(rect) {
        return rect.left - containerRect.left + rect.width / 2;
    }
    function centerYBottom(rect) {
        // bottom coordinate = container height - (rect.top - container top + half height)
        return gameContainer.offsetHeight - (rect.top - containerRect.top + rect.height / 2);
    }

    const x1 = centerX(fromRect);
    const y1 = centerYBottom(fromRect);
    const x2 = centerX(toRect);
    const y2 = centerYBottom(toRect);

    const dx = x2 - x1;
    const dy = y2 - y1;

    const length = Math.sqrt(dx * dx + dy * dy);
    const angle = Math.atan2(dy, dx) * 180 / Math.PI;

    // Adjust the dotted line style here for better positioning
    lineEl.style.width = length + 'px';
    lineEl.style.left = x1 + 'px';
    lineEl.style.bottom = y1 + 'px';
    lineEl.style.transformOrigin = 'left center';
    lineEl.style.transform = `rotate(${angle}deg)`;
}

// Handle when bullet hits the boost drainer
function handleBoostDrainerHit(bulletObj, bulletIndex) {
    if (!boostDrainer) return false;
    if (!checkCollision(bulletObj.element, boostDrainer)) return false;

    // Remove bullet
    bulletObj.element.remove();
    bullets.splice(bulletIndex, 1);

    // Reduce HP
    boostDrainerHP--;
    // Flash
    boostDrainer.style.opacity = '0.5';
    setTimeout(() => {
        if (boostDrainer) boostDrainer.style.opacity = '1';
    }, 150);

    // If dead, remove
    if (boostDrainerHP <= 0) {
        removeBoostDrainer();
    }

    return true; // bullet handled
}

// Remove drainer and chain line cleanup
function removeBoostDrainer() {
    if (boostDrainer) {
        boostDrainer.remove();
        boostDrainer = null;
    }
    if (boostDrainerChain) {
        boostDrainerChain.remove();
        boostDrainerChain = null;
    }
    if (boostDrainerLaser) {
        boostDrainerLaser.remove();
        boostDrainerLaser = null;
    }
    if (boostDrainerAttackTimeout) {
        clearTimeout(boostDrainerAttackTimeout);
        boostDrainerAttackTimeout = null;
    }
    boostDrainerHP = 0;
    boostDrainerState = "dead";
}

function checkBoostDrainerLaserCollision() {
    if (!boostDrainerLaser) return;

    if (checkCollision(player, boostDrainerLaser)) {
        // Hit by laser — destroy enemy & reduce lives
        removeBoostDrainer();
        reduceLives();
    }
}


function bossPhaseTwoExplosionRain() {
    const blockWidth = 30; // Width of the falling blocks
    const blockHeight = 10; // Height of the falling blocks
    const blockSpeed = 5; // Speed of block movement
    const blocks = []; // Array to hold active blocks
    const spawnInterval = 500; // Time between block spawns (in milliseconds)
    const duration = 10000; // Duration of the attack (in milliseconds)

    // Function to create and spawn blocks
    function spawnBlock() {
        const block = document.createElement('div');
        block.classList.add('explosive-block'); // Add a class for styling
        block.style.width = `${blockWidth}px`;
        block.style.height = `${blockHeight}px`;
        block.style.position = 'absolute';
        block.style.backgroundColor = 'red';

        // Determine random left or right spawn position (off screen)
        const side = Math.random() < 0.5 ? -blockWidth : window.innerWidth; 
        block.style.left = side < 0 ? `${side}px` : `${side - blockWidth}px`;
        block.style.bottom = `${Math.random() * window.innerHeight}px`; // Random vertical position
        document.body.appendChild(block);

        // Move block across the screen
        const moveInterval = setInterval(() => {
            const currentLeft = parseInt(block.style.left);
            block.style.left = `${currentLeft + (side < 0 ? blockSpeed : -blockSpeed)}px`; // Move toward center

            // Check if the block is out of bounds
            if (currentLeft < -blockWidth || currentLeft > window.innerWidth) {
                clearInterval(moveInterval); // Stop moving if out of bounds
                block.remove(); // Remove block from DOM
            }

            // Check collision with player
            if (checkCollision(player, block)) {
                reduceLives(); // Reduce player's lives
                block.remove(); // Remove block on collision
                clearInterval(moveInterval); // Stop moving
            }
        }, 1000 / 60); // Move at 60 FPS
        blocks.push(block); // Add the block to the list of active blocks
    }

    // Start spawning blocks
    const spawnBlocksInterval = setInterval(spawnBlock, spawnInterval);

    // Stop spawning after the specified duration and clean up
    setTimeout(() => {
        clearInterval(spawnBlocksInterval);
        blocks.forEach(block => block.remove()); // Remove remaining blocks
        cycleBossAttacks(); // Move to next boss attack cycle
    }, duration);
}

function eded() {
  // === Config ===
  const CONFIG = {
    blockWidth: 80,
    blockHeight: 20,
    obstacleWidth: 40,
    obstacleHeight: 20,
    lavaRiseSpeed: 1,          // pixels per tick
    lavaRiseInterval: 100,     // ms
    phaseLavaHeight: 100,      // lava height per phase
    totalPhases: 3,
    damageCooldown: 1000       // ms cooldown between damage ticks
  };

  // === State ===
  let currentPhase = 0;
  let lavaHeight = 0;
  let lavaIntervalId = null;
  let lastDamageTime = 0;

  // Spawned elements tracking (for cleanup)
  const blocks = [];
  const obstacles = [];

  // Assumes global DOM references:
  // - gameWorld: container element for gameplay (should be position: relative or absolute)
  // - player: player character element
  // - reduceLives(): function that reduces player lives
  // - cycleBossAttacks(): function that triggers after phase completes

  // === Helper: checkCollision ===
  // Simple AABB collision between two elements using getBoundingClientRect

  // === Helper: getPlayerBottomOffset ===
  // Distance in pixels from player's bottom edge to bottom of the game world container.
  function getPlayerBottomOffset() {
    const playerRect = player.getBoundingClientRect();
    const worldRect = gameWorld.getBoundingClientRect();
    return worldRect.bottom - playerRect.bottom; // positive means above bottom
  }

  // === Spawn functions ===
  function createBlock(x) {
    const block = document.createElement('div');
    block.className = 'block';
    Object.assign(block.style, {
      position: 'absolute',
      width: CONFIG.blockWidth + 'px',
      height: CONFIG.blockHeight + 'px',
      backgroundColor: 'blue',
      left: x + 'px',
      bottom: '0',
      zIndex: '10',
    });
    gameWorld.appendChild(block);
    blocks.push(block);
    return block;
  }

  function createObstacle(x) {
    const obstacle = document.createElement('div');
    obstacle.className = 'obstacle';
    Object.assign(obstacle.style, {
      position: 'absolute',
      width: CONFIG.obstacleWidth + 'px',
      height: CONFIG.obstacleHeight + 'px',
      backgroundColor: 'orange',
      left: x + 'px',
      bottom: '0',
      zIndex: '10',
    });
    gameWorld.appendChild(obstacle);
    obstacles.push(obstacle);
    return obstacle;
  }

  // === Spawning initial fixed blocks ===
  function spawnInitialBlocks() {
    [100, 300, 500].forEach(xPos => createBlock(xPos));
  }

  // === Spawning obstacles per phase ===
  function spawnPhaseObstacles() {
    // Could vary per phase dynamically, for now fixed positions
    [150, 350, 550].forEach(xPos => createObstacle(xPos));
  }

  // === Cleanup elements ===
  function cleanupElements() {
    blocks.forEach(b => b.remove());
    obstacles.forEach(o => o.remove());
    blocks.length = 0;
    obstacles.length = 0;

    // Remove lava if any
    const existingLava = gameWorld.querySelector('.lava');
    if (existingLava) existingLava.remove();
  }

  // === Create lava element ===
  function createLava() {
    const lava = document.createElement('div');
    lava.className = 'lava';
    Object.assign(lava.style, {
      position: 'absolute',
      width: '100%',
      height: '0',
      bottom: '0',
      backgroundColor: 'red',
      zIndex: '5',
      transition: 'height 0.1s linear', // smooth growth per interval
    });
    gameWorld.appendChild(lava);
    return lava;
  }

  // === Damage player if touching lava with cooldown ===
  function tryDamagePlayer() {
    const now = Date.now();
    if (now - lastDamageTime < CONFIG.damageCooldown) return; // cooldown active

    if (checkCollision(player, lavaElement)) {
      const playerBottomDist = getPlayerBottomOffset();
      if (playerBottomDist < lavaHeight) {
        reduceLives();
        lastDamageTime = now;
      }
    }
  }

  // === Lava rise tick ===
  function onLavaRise() {
    lavaHeight += CONFIG.lavaRiseSpeed;
    lavaElement.style.height = lavaHeight + 'px';

    tryDamagePlayer();

    // Check if current phase lava fully raised
    if (lavaHeight >= (currentPhase + 1) * CONFIG.phaseLavaHeight) {
      clearInterval(lavaIntervalId);
      lavaIntervalId = null;
      currentPhase++;

      if (currentPhase < CONFIG.totalPhases) {
        // Spawn obstacles for next phase
        spawnPhaseObstacles();

        // Reset lava after short delay for player repositioning
        setTimeout(() => {
          lavaHeight = 0;
          lavaElement.style.height = '0px';
          lavaIntervalId = setInterval(onLavaRise, CONFIG.lavaRiseInterval);
        }, 1000);

      } else {
        // Final phase complete, proceed to next boss phase or attacks
        cycleBossAttacks();
      }
    }
  }

  // === Start phase 5 ===
  function startPhase() {
    cleanupElements();

    // Spawn blocks and initial obstacles
    spawnInitialBlocks();
    spawnPhaseObstacles();

    // Create lava element fresh
    lavaElement = createLava();

    // Reset state
    lavaHeight = 0;
    currentPhase = 0;
    lastDamageTime = 0;

    // Start lava rising loop
    lavaIntervalId = setInterval(onLavaRise, CONFIG.lavaRiseInterval);
  }

  // Launch phase 5
  let lavaElement; // define lavaElement here to be accessible in nested functions
  startPhase();
}


function bossPhaseTwoTargetSlam() {
    let slamCount = 0;
    const maxSlams = 4;
    const groundLevel = 0;   
    const hoverHeight = 100; 
    const slamDurationDown = 500;   
    const slamHoldDuration = 1500;  
    const slamDurationUp = 700;     
    const slamCooldown = 1000;      

    // Track if a slam is currently active
    let slamActive = false;

    // Promise-based sleep
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // Collision check: AABB rectangle intersection
    function checkCollision(elem1, elem2) {
        const r1 = elem1.getBoundingClientRect();
        const r2 = elem2.getBoundingClientRect();
        return !(
            r1.right < r2.left ||
            r1.left > r2.right ||
            r1.bottom < r2.top ||
            r1.top > r2.bottom
        );
    }

    // Placeholder for player's lives remaining, define accordingly
    let lives = 3;

    // Reduces player's lives safely
    function reduceLives() {
        if (lives > 0) {
            lives--;
            console.log("Player hit by boss slam! Lives Remaining:", lives);
        }
    }

    // Shake screen effect placeholder — implement your own or remove
    function shakeScreen() {
        // Example simple console log
        console.log("Screen shakes!");
    }

    // Create burst effect placeholder — implement as needed
    function createBurst(x, y) {
        console.log(`Burst at (${x}, ${y})`);
    }

    // Animate bottom position with transition and Promise
    function animateBottomPosition(targetBottom, duration) {
        return new Promise(resolve => {
            function onTransitionEnd(event) {
                if (event.propertyName === 'bottom') {
                    boss.removeEventListener('transitionend', onTransitionEnd);
                    resolve();
                }
            }
            boss.addEventListener('transitionend', onTransitionEnd);

            // Force reflow to apply transition properly
            void boss.offsetWidth;

            boss.style.transition = `bottom ${duration}ms ease-in-out`;
            boss.style.bottom = `${targetBottom}px`;
        });
    }

    // Monitor collision during slamHoldDuration, but only reduce lives once per second max
    async function monitorCollisionDuringSlam(duration) {
        return new Promise((resolve) => {
            let lastHitTime = 0;

            const interval = setInterval(() => {
                const now = Date.now();

                if (now - lastHitTime >= 1000 && checkCollision(player, boss)) {
                    reduceLives();
                    lastHitTime = now;
                }

                if (now >= startTime + duration) {
                    clearInterval(interval);
                    resolve();
                }
            }, 50);

            const startTime = Date.now();
        });
    }

    async function performSlam() {
        while (slamCount < maxSlams) {
            slamActive = true;

            // Calculate player and boss parent positions to align boss over player horizontally
            const playerRect = player.getBoundingClientRect();
            const parentRect = boss.parentElement.getBoundingClientRect();

            // Player center X inside boss parent container
            const playerX = playerRect.left - parentRect.left + playerRect.width / 2;

            // Position boss instantly above player at hover height
            boss.style.transition = 'none';
            boss.style.left = `${playerX - boss.offsetWidth / 2}px`;
            boss.style.bottom = `${hoverHeight}px`;

            await sleep(500); // hover delay

            shakeScreen();

            // Slam down
            await animateBottomPosition(groundLevel, slamDurationDown);

            createBurst(playerX, groundLevel);

            // Check collision during slam hold, max once per 1000ms
            await monitorCollisionDuringSlam(slamHoldDuration);

            // Slam back up
            await animateBottomPosition(hoverHeight, slamDurationUp);

            slamCount++;
            slamActive = false;

            await sleep(slamCooldown);
        }

        console.log("Slam attack finished");
        if (typeof resetBossPosition === 'function') {
            resetBossPosition();
        }
        if (typeof cycleBossAttacks === 'function') {
            setTimeout(cycleBossAttacks, 10000);
        }
    }

    performSlam();
}

// Function to shake the screen
function shakeScreen() {
    let shakeEffect = document.createElement('div');
    shakeEffect.style.position = "fixed";
    shakeEffect.style.top = "0";
    shakeEffect.style.left = "0";
    shakeEffect.style.width = "100%";
    shakeEffect.style.height = "100%";
    shakeEffect.style.backgroundColor = "rgba(255, 0, 0, 0.5)"; // Flashing effect
    shakeEffect.style.transition = 'transform 0.1s';
    document.body.appendChild(shakeEffect);

    // Shake effect
    const shakeTimes = 15; // Number of shakes
    const shakeDistance = 40; // Distance to shake
    const shakeInterval = 50; // Time between shakes

    for(let i = 0; i < shakeTimes; i++) {
        setTimeout(() => {
            shakeEffect.style.transform = (i % 2 === 0) ? `translateX(-${shakeDistance}px)` : `translateX(${shakeDistance}px)`;
        }, i * shakeInterval);
    }

    // Reset the screen after shaking
    setTimeout(() => {
        shakeEffect.style.transform = 'translateX(0)';
    }, shakeTimes * shakeInterval);

    setTimeout(() => {
        shakeEffect.remove(); // Clean up the shake effect
    }, shakeTimes * shakeInterval + 100); // Ensure it removes after the reset
}

// Function to reset the boss position to the center of the screen
function resetBossPosition() {
    boss.style.left = (gameContainer.offsetWidth / 2 - boss.offsetWidth / 2) + 'px'; // Center the boss
    boss.style.bottom = "100px"; // Reset position
}
 
 


function bossPhaseTwoBarrage() {
    boss.style.animation = "boss-shake 1s infinite alternate"; // Boss shakes

    let spawnCount = 0;
    let spawnInterval = setInterval(() => {
        if (spawnCount >= 15) { // Stops after 10 spawns
            clearInterval(spawnInterval);
            boss.style.animation = ""; // Stop shaking
            setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
            return;
        }

        let enemy = createElement('enemy', enemies, Math.random() * gameContainer.offsetWidth);
        enemy.style.bottom = "400px"; // Start from top

        let fallSpeed = 12;
        let fallInterval = setInterval(() => {
            enemy.style.bottom = (parseInt(enemy.style.bottom) - fallSpeed) + "px";

            if (parseInt(enemy.style.bottom) <= 0) {
                enemy.style.bottom = "0px"; // Stop at ground level
                clearInterval(fallInterval);
            }

            // Check for collision with player
            if (checkCollision(player, enemy)) {
                reduceLives();
                enemy.remove();
                clearInterval(fallInterval);
            }
        }, 50);

        spawnCount++;
    }, 500); // Spawn every half second
}
 
function bossEnemyBarrage() {
    boss.style.animation = "boss-shake 1s infinite alternate"; // Boss shakes

    let spawnCount = 0;
    let spawnInterval = setInterval(() => {
        if (spawnCount >= 10) { // Stops after 10 spawns
            clearInterval(spawnInterval);
            boss.style.animation = ""; // Stop shaking
            setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
            return;
        }

        let enemy = createElement('enemy', enemies, Math.random() * gameContainer.offsetWidth);
        enemy.style.bottom = "400px"; // Start from top

        let fallSpeed = 8;
        let fallInterval = setInterval(() => {
            enemy.style.bottom = (parseInt(enemy.style.bottom) - fallSpeed) + "px";

            if (parseInt(enemy.style.bottom) <= 0) {
                enemy.style.bottom = "0px"; // Stop at ground level
                clearInterval(fallInterval);
            }

            // Check for collision with player
            if (checkCollision(player, enemy)) {
                reduceLives();
                enemy.remove();
                clearInterval(fallInterval);
            }
        }, 50);

        spawnCount++;
    }, 500); // Spawn every half second
}
 
 
 
function bossPhaseTwoTargetSlam() {
  const maxSlams = 4;
  const groundLevel = 0;
  const hoverHeight = 100;
  const slamDurationDown = 400;    // Faster slam down
  const slamHoldDuration = 1200;   // Hold slam a bit shorter
  const slamDurationUp = 600;      // Faster slam up
  const slamCooldown = 700;        // Faster cooldown between slams

  // Track if slam is active to avoid overlapping slams
  let slamCount = 0;

  // Player lives placeholder (should come from your global game state)
  // Consider passing lives as param or referencing global store instead

  function reduceLives() {
    if (lives > 0) {
      lives--;
      console.log("Player hit by boss slam! Lives Remaining:", lives);
      // TODO: Trigger player hit animation / feedback here
    }
  }


  // Use Promises to handle CSS transitions cleanly
  function animateBottomPosition(targetBottom, duration) {
    return new Promise((resolve) => {
      let resolved = false;
      
      function onTransitionEnd(e) {
        if (e.propertyName === 'bottom' && !resolved) {
          resolved = true;
          boss.removeEventListener('transitionend', onTransitionEnd);
          resolve();
        }
      }
      
      boss.addEventListener('transitionend', onTransitionEnd);

      // Apply CSS transition
      boss.style.transition = `bottom ${duration}ms ease-in-out`;
      boss.style.bottom = `${targetBottom}px`;

      // Safety fallback in case transitionend doesn't fire:
      setTimeout(() => {
        if (!resolved) {
          resolved = true;
          boss.removeEventListener('transitionend', onTransitionEnd);
          resolve();
        }
      }, duration + 50);
    });
  }

  // Helper to get player and boss rectangles
  function getRects() {
    return {
      playerRect: player.getBoundingClientRect(),
      bossRect: boss.getBoundingClientRect(),
      parentRect: boss.parentElement.getBoundingClientRect()
    };
  }

  // Check AABB collision between two DOMRect objects
  function isCollision(rect1, rect2) {
    return !(
      rect1.right < rect2.left ||
      rect1.left > rect2.right ||
      rect1.bottom < rect2.top ||
      rect1.top > rect2.bottom
    );
  }

  // Smoothly monitor collision during hold using requestAnimationFrame for fast, real-time checks
 function monitorCollisionDuringSlam(duration) {
  return new Promise((resolve) => {
    const hitCooldown = 1000; // ms between allowed hits
    let lastHitTimestamp = 0;
    const startTime = performance.now();

    function check(time) {
      if (time - startTime >= duration) {
        resolve();
        return;
      }

      const { playerRect, bossRect } = getRects();

      if (isCollision(playerRect, bossRect)) {
        if (time - lastHitTimestamp > hitCooldown && lives > 0) {
          reduceLives();
          lastHitTimestamp = time;
          shakeScreen();
        }
      }

      if (lives <= 0) {
        resolve(); // Stop checking if player dead or no lives left
        return;
      }

      requestAnimationFrame(check);
    }

    requestAnimationFrame(check);
  });
}

  async function performSlam() {
    slamCount = 0;

    while (slamCount < maxSlams) {
      // Position boss above player horizontally, instantly (no transition)
      const { playerRect, parentRect } = getRects();
      const playerCenterX = playerRect.left - parentRect.left + playerRect.width / 2;
      boss.style.transition = 'none';  // Remove transition for instant move
      boss.style.left = `${playerCenterX - boss.offsetWidth / 2}px`;
      boss.style.bottom = `${hoverHeight}px`;

      // Let rendering catch up (a frame or short delay)
      await new Promise(resolve => requestAnimationFrame(resolve));

      await new Promise(resolve => setTimeout(resolve, 300)); // small hover pause, quicker than before

      shakeScreen();

      // Slam down animation
      await animateBottomPosition(groundLevel, slamDurationDown);

      createBurst(playerCenterX, groundLevel);

      // Hold slammed position while checking collision multiple times a second, respond quick but not too spammy
      await monitorCollisionDuringSlam(slamHoldDuration);

      // Slam back up
      await animateBottomPosition(hoverHeight, slamDurationUp);

      slamCount++;

      // Cooldown between slams
      await new Promise(resolve => setTimeout(resolve, slamCooldown));
    }

    console.log("Slam attack finished");

    // Reset boss position or continue attack cycles
    if (typeof resetBossPosition === 'function') {
      resetBossPosition();
    }
    if (typeof cycleBossAttacks === 'function') {
      // Reduced delay to chain attacks faster
      setTimeout(cycleBossAttacks, 5000);
    }
  }

  performSlam();
}
 
function bossExplosionRain() {
    boss.style.animation = "boss-shake 1s infinite alternate";

    let dropCount = 0;
    let dropInterval = setInterval(() => {
        if (dropCount >= 10) {
            clearInterval(dropInterval);
            boss.style.animation = "";
            setTimeout(cycleBossAttacks, 3000); // Cooldown before next attack
            return;
        }

        // Randomize the X position based on the player's position
        let playerPositionX = parseInt(player.style.left);
        let explosionBlock = document.createElement('div'); // Corrected to use document.createElement
        explosionBlock.classList.add('explosive-block'); // Add a class if you want to style it later
        explosionBlock.style.position = "absolute"; // Important for positioning
        explosionBlock.style.left = (playerPositionX + Math.random() * 30 - 15) + "px"; // Randomize the horizontal position
        explosionBlock.style.bottom = "400px"; // Start high
        explosionBlock.style.width = "30px"; // Width of the falling block
        explosionBlock.style.height = "10px"; // Height of the falling block
        explosionBlock.style.backgroundColor = "red"; // Color of the falling block
        gameWorld.appendChild(explosionBlock);

        let fallSpeed = 5; // Speed of fall
        let fallInterval = setInterval(() => {
            explosionBlock.style.bottom = (parseInt(explosionBlock.style.bottom) - fallSpeed) + "px";

            if (parseInt(explosionBlock.style.bottom) <= 0) {
                createBurst(parseInt(explosionBlock.style.left), 0); // Create burst effect
                if (checkCollision(explosionBlock, player)) {
                    reduceLives(); // Reduce lives if hit
                }
                explosionBlock.remove(); // Remove block once it hits ground
                clearInterval(fallInterval);
            }
        }, 50); // Update every 50ms

        dropCount++;
    }, 1000); // Drop every second
}


class Laser {
    constructor(x, y, direction, length) {
        this.x = x;
        this.y = y;
        this.direction = direction;  // 'vertical' or 'horizontal'
        this.length = length;
        this.element = null;
    }

    createElement() {
        this.element = document.createElement('div');
        this.element.style.position = 'absolute';
        this.element.style.backgroundColor = 'yellow';
        if (this.direction === 'vertical') {
            this.element.style.width = '4px';
            this.element.style.height = this.length + 'px';
            this.element.style.left = this.x + 'px';
            this.element.style.bottom = this.y + 'px';
        } else {
            this.element.style.height = '4px';
            this.element.style.width = this.length + 'px';
            this.element.style.left = this.x + 'px';
            this.element.style.bottom = this.y + 'px';
        }
        this.element.style.opacity = '0.8';
        this.element.style.zIndex = '1000';
        this.element.classList.add('laser-beam');
        document.getElementById('game-world').appendChild(this.element);
    }

    activate() {
        // Make laser red and fully opaque when activated
        if (!this.element) return;
        this.element.style.backgroundColor = 'red';
        this.element.style.opacity = '1';
    }

    remove() {
        if (this.element && this.element.parentElement) {
            this.element.parentElement.removeChild(this.element);
            this.element = null;
        }
    }

    getBoundingRect() {
        return this.element.getBoundingClientRect();
    }
}

function isPlayerOnLaser(laser) {
    if (!laser.element) return false;
    const playerRect = player.getBoundingClientRect();
    const laserRect = laser.getBoundingRect();

    return !(
        playerRect.right < laserRect.left ||
        playerRect.left > laserRect.right ||
        playerRect.bottom < laserRect.top ||
        playerRect.top > laserRect.bottom
    );
}

// Main laser phase boss move function - call it with await in your attack cycle
async function laserPhaseMove() {
    displayMessage("Dodge the lasers!", 2);
    await sleep(2000); // Wait for player to read the message

    const repeats = 4;
    const gameWorld = document.getElementById('game-world');
    const gameBounds = gameWorld.getBoundingClientRect();

    for (let round = 0; round < repeats; round++) {
        // Spawn lasers
        const lasers = [];

        // Number of lasers per round (can tweak for difficulty)
        const lasersCount = 5;

        for (let i = 0; i < lasersCount; i++) {
            const vertical = Math.random() < 0.5;

            if (vertical) {
                // Random X inside game world boundaries
                const xPos = Math.random() * gameBounds.width;
                // Y set to bottom of game world container - zero
                lasers.push(new Laser(xPos, 0, 'vertical', gameBounds.height));
            } else {
                // Random Y inside game world height
                const yPos = Math.random() * gameBounds.height;
                // X at left edge = 0
                lasers.push(new Laser(0, yPos, 'horizontal', gameBounds.width));
            }
        }

        // Create laser elements in DOM with warning color (yellow)
        lasers.forEach(laser => laser.createElement());

        // Warn lasers blinking: toggle opacity several times for 1 second
        const warningDurationMs = 1000;
        const blinkIntervalMs = 200;
        const blinkCount = warningDurationMs / blinkIntervalMs;
        for (let b = 0; b < blinkCount; b++) {
            lasers.forEach(laser => {
                if (!laser.element) return;
                laser.element.style.opacity = (b % 2 === 0) ? '0.3' : '0.8';
            });
            await sleep(blinkIntervalMs);
        }

        // Set lasers fully visible and red (active)
        lasers.forEach(laser => laser.activate());

        // Damage phase: 2 seconds, check collisions every 100ms
        const damageDurationMs = 2000;
        const damageCheckIntervalMs = 100;
        let elapsed = 0;

        while (elapsed < damageDurationMs) {
            lasers.forEach(laser => {
                if (isPlayerOnLaser(laser)) {
                    lives = Math.max(0, lives - 1);
                    displayMessage(`Hit! Lives: ${lives}`, 1);

                    // TODO: Add your death/game over logic here if lives <= 0
                }
            });
            await sleep(damageCheckIntervalMs);
            elapsed += damageCheckIntervalMs;
        }

        // Remove all lasers from DOM and clear array
        lasers.forEach(laser => laser.remove());
        lasers.length = 0;

        // Short delay before next round
        await sleep(500);
    }

    displayMessage("Laser phase complete!", 2);
    await sleep(2000);

    cycleBossAttacks();
}

// Helper sleep function (if not defined)

function getRandomSpawnCount(min = 1, max = 2) {
    // Reduced spawn per interval for better control
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

async function bossPhaseFiveAttackA() {
    displayMessage("Trial 1", 3);
    await sleep(3000);

    const spawnInterval = 1000;  // Spawn every 1s
    const maxTotalEnemies = 12;
    let totalSpawned = 0;

    await new Promise(resolve => {
        const intervalId = setInterval(() => {
            if (totalSpawned >= maxTotalEnemies) {
                clearInterval(intervalId);
                resolve();
                return;
            }

            let count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnEnemy();
                totalSpawned++;
            }

            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnFlyingEnemy();
                totalSpawned++;
            }

            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnObstacle();
                totalSpawned++;
            }
        }, spawnInterval);
    });

    await cycleBossAttacks();
}

async function bossPhaseFiveAttackB() {
    displayMessage("Trial 2", 3);
    await sleep(3000);

    const spawnInterval = 1200;
    const maxTotalEnemies = 12;
    let totalSpawned = 0;

    await new Promise(resolve => {
        const intervalId = setInterval(() => {
            if (totalSpawned >= maxTotalEnemies) {
                clearInterval(intervalId);
                resolve();
                return;
            }
            let count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnChargingEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i = 0; i < count && totalSpawned < maxTotalEnemies; i++) {
                spawnSniperEnemy();
                totalSpawned++;
            }
        }, spawnInterval);
    });

    await cycleBossAttacks();
}

async function bossPhaseFiveAttackC() {
    displayMessage("Trial 3", 3);
    await sleep(3000);

    const spawnInterval = 1100;
    const maxTotalEnemies = 12;
    let totalSpawned = 0;

    await new Promise(resolve => {
        const intervalId = setInterval(() => {
            if (totalSpawned >= maxTotalEnemies) {
                clearInterval(intervalId);
                resolve();
                return;
            }
            let count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnFlyingEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnReflectiveEnemy();
                totalSpawned++;
            }
        }, spawnInterval);
    });

    await cycleBossAttacks();
}

async function bossPhaseFiveAttackD() {
    displayMessage("Trial 4", 3);
    await sleep(3000);

    const spawnInterval = 1200;
    const maxTotalEnemies = 12;
    let totalSpawned = 0;

    await new Promise(resolve => {
        const intervalId = setInterval(() => {
            if (totalSpawned >= maxTotalEnemies) {
                clearInterval(intervalId);
                resolve();
                return;
            }
            let count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnLaserEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnSplitterEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnObstacle();
                totalSpawned++;
            }
        }, spawnInterval);
    });

    await cycleBossAttacks();
}

async function bossPhaseFiveAttackE() {
    displayMessage("Trial 5", 3);
    await sleep(3000);

    const spawnInterval = 1400;
    const maxTotalEnemies = 12;
    let totalSpawned = 0;

    await new Promise(resolve => {
        const intervalId = setInterval(() => {
            if (totalSpawned >= maxTotalEnemies) {
                clearInterval(intervalId);
                resolve();
                return;
            }
            let count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnFlyingEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnSniperEnemy();
                totalSpawned++;
            }
        }, spawnInterval);
    });

    await cycleBossAttacks();
}

async function bossPhaseFiveAttackF() {
    displayMessage("Trial 6", 3);
    await sleep(3000);

    const spawnInterval = 1300;
    const maxTotalEnemies = 12;
    let totalSpawned = 0;

    await new Promise(resolve => {
        const intervalId = setInterval(() => {
            if (totalSpawned >= maxTotalEnemies) {
                clearInterval(intervalId);
                resolve();
                return;
            }
            let count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnEnemy();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnVirusDrone();
                totalSpawned++;
            }
            count = getRandomSpawnCount(1,1);
            for(let i=0; i<count && totalSpawned < maxTotalEnemies; i++) {
                spawnSplitterEnemy();
                totalSpawned++;
            }
        }, spawnInterval);
    });

    await cycleBossAttacks();
}

function EnemyBarrage() {
    const numberOfFlyingEnemies = 3; // Total number of flying enemies to summon
    const numberOfChargingEnemies = 5; // Number of charging enemies to spawn
    const flyingSpawnDelay = 3000; // Delay between each flying enemy spawn (in milliseconds)
    const chargingSpawnDelay = 4000; // Delay between each charging enemy spawn (in milliseconds)
    const totalDuration = 15000; // Total time for the flying enemy spawning process (in milliseconds)

    // Function to spawn multiple flying enemies
    const flyingEnemiesInterval = setInterval(() => {
        if (numberOfFlyingEnemies > 0) {
            SpawnSplitterEnemy(); // Call to spawn a single flying enemy
            numberOfFlyingEnemies--; // Decrement the count
        } else {
            clearInterval(flyingEnemiesInterval); // Stop spawning when done
        }
    }, flyingSpawnDelay); // Spawn every 2 seconds

    // Function to spawn charging enemies
    const chargingEnemiesInterval = setInterval(() => {
        if (numberOfChargingEnemies > 0) {
            spawnChargingEnemy(); // Call to spawn a charging enemy
            numberOfChargingEnemies--; // Decrement the count
        } else {
            clearInterval(chargingEnemiesInterval); // Stop spawning when done
        }
    }, chargingSpawnDelay); // Spawn every 3 seconds

    // Wait before proceeding to the next boss cycle
    setTimeout(() => {
        clearInterval(flyingEnemiesInterval); // Clear the spawn loops
        clearInterval(chargingEnemiesInterval);
        cycleBossAttacks(); // Proceed to the next boss attack
    }, totalDuration); // 10 seconds before moving to next attack
}

function bossPhaseThree() {
    const numberOfFlyingEnemies = 6; // Total number of flying enemies to summon
    const numberOfChargingEnemies = 10; // Number of charging enemies to spawn
    const flyingSpawnDelay = 3000; // Delay between each flying enemy spawn (in milliseconds)
    const chargingSpawnDelay = 4000; // Delay between each charging enemy spawn (in milliseconds)
    const totalDuration = 20000; // Total time for the flying enemy spawning process (in milliseconds)

    // Function to spawn multiple flying enemies
    const flyingEnemiesInterval = setInterval(() => {
        if (numberOfFlyingEnemies > 0) {
            spawnFlyingEnemy(); // Call to spawn a single flying enemy
            numberOfFlyingEnemies--; // Decrement the count
        } else {
            clearInterval(flyingEnemiesInterval); // Stop spawning when done
        }
    }, flyingSpawnDelay); // Spawn every 2 seconds

    // Function to spawn charging enemies
    const chargingEnemiesInterval = setInterval(() => {
        if (numberOfChargingEnemies > 0) {
            spawnChargingEnemy(); // Call to spawn a charging enemy
            numberOfChargingEnemies--; // Decrement the count
        } else {
            clearInterval(chargingEnemiesInterval); // Stop spawning when done
        }
    }, chargingSpawnDelay); // Spawn every 3 seconds

    // Wait before proceeding to the next boss cycle
    setTimeout(() => {
        clearInterval(flyingEnemiesInterval); // Clear the spawn loops
        clearInterval(chargingEnemiesInterval);
        cycleBossAttacks(); // Proceed to the next boss attack
    }, totalDuration); // 10 seconds before moving to next attack
}

function bossNewPower() {
    let shotsFired = 0;
    const maxShots = 15;
    const shotCooldown = 800; // 0.8 seconds between shots

    const shootInterval = setInterval(() => {
        if (shotsFired >= maxShots) {
            clearInterval(shootInterval);

            // Introduce a delay before invoking the next attack or phase
            setTimeout(() => {
                cycleBossAttacks(); // Call back the attack cycle function
            }, 2000); // 2 seconds for any cooling down or animation effect
            return; // Stop firing after maximum shots
        }

        // Calculate the boss's and player's positions
        const bossX = parseInt(boss.style.left) + boss.offsetWidth / 2; // Middle of the boss
        const bossY = parseInt(boss.style.bottom) + 30; // Just above the boss
        const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Middle of the player
        const playerY = parseInt(player.style.bottom); // Bottom of the player
        
        // Calculate the direction vector
        const dx = playerX - bossX;
        const dy = playerY - bossY;
        const distance = Math.sqrt(dx * dx + dy * dy);
        const velocity = 10; // Speed of the projectile

        // Create a projectile
        const projectile = document.createElement('div');
        projectile.classList.add('boss-projectile');
        projectile.style.width = '10px';
        projectile.style.height = '10px';
        projectile.style.backgroundColor = 'orange';
        projectile.style.position = 'absolute';
        projectile.style.left = `${bossX - 5}px`; // Center it
        projectile.style.bottom = `${bossY}px`; // Start just above the boss
        gameWorld.appendChild(projectile);

        let projectileInterval = setInterval(() => {
            // Move projectile towards the player
            const moveX = (dx / distance) * velocity; // Calculate x movement
            const moveY = (dy / distance) * velocity; // Calculate y movement
            projectile.style.left = (parseInt(projectile.style.left) + moveX) + 'px';
            projectile.style.bottom = (parseInt(projectile.style.bottom) + moveY) + 'px';

            // Check collision
            if (checkCollision(player, projectile)) {
                reduceLives(); // Reduce player lives on hit
                projectile.remove(); // Remove projectile on hit
                clearInterval(projectileInterval);
            }

            // Remove projectile if it goes off-screen
            if (parseInt(projectile.style.bottom) > gameContainer.offsetHeight || 
                parseInt(projectile.style.left) < 0 || 
                parseInt(projectile.style.left) > gameContainer.offsetWidth) {
                projectile.remove(); // Remove off-screen
                clearInterval(projectileInterval);
            }
        }, 50); // Update every 50ms

        shotsFired++;
    }, shotCooldown); // Fire every 0.8 seconds
}
 
 
 
 
            function displayBossHealth() {
                bossHealthBar.style.display = 'block';
                updateBossHealth();
            }
 
function updateBossHealth() {
    // Ensure the health bar width updates according to boss health
    const maxHealth = 150; // Define the maximum health for level 3
    const currentHealth = Math.max(0, Math.min(bossHealth, maxHealth)); // Ensure health stays within bounds

    // Calculate the percentage of current health relative to the maximum health
    const healthPercentage = (currentHealth / maxHealth) * 100;

    // Update the CSS width of the health bar to reflect the current health
    bossHealthBar.style.width = `${healthPercentage}%`;

    // Optional: Set a different color based on health status (for visual feedback)
    if (currentHealth > maxHealth * 0.5) {
        bossHealthBar.style.backgroundColor = 'green'; // Healthy
    } else if (currentHealth > maxHealth * 0.2) {
        bossHealthBar.style.backgroundColor = 'yellow'; // Caution
    } else {
        bossHealthBar.style.backgroundColor = 'red'; // Critical health
    }
}
 
            function spawnBossEnemies() {
                if (bossShielded) {
                    for (let i = 0; i < 2; i++) {
                        const enemy = createElement('enemy', enemies, parseInt(boss.style.left) + (i * 50));
                        enemy.style.bottom = `${Math.random() * 250}px`;
                    }
                }
            }
 
            function spawnBossBullets() {
                const bullet = createBullet();
                bullet.style.left = parseInt(boss.style.left) + 'px';
                bullet.style.bottom = parseInt(boss.style.bottom) + 30 + 'px';
                bullet.style.backgroundColor = 'orange';
                gameWorld.appendChild(bullet);
                bullets.push({ element: bullet, direction: -1 });
            }
 
function checkBossHit() {
    if (!boss || bossShielded) return; // Stop damaging if boss is shielded

    bullets.forEach((bullet, bulletIndex) => {
        if (checkCollision(bullet.element, boss)) {
            bossHealth -= 2; // Decrement boss health
            updateBossHealth();
            bullet.element.remove();
            bullets.splice(bulletIndex, 1);
            
            // Check if the boss is defeated
            if (bossHealth <= 0) {
                displayMessage("Boss defeated!");
                onBossDefeated(); // Trigger boss defeat logic
            }
        }
    });
}
 
 
 
function onBossDefeated() {
    bossHealthBar.style.display = 'none'; // Hide health bar upon defeat

    const gameMode = localStorage.getItem('gameMode');
    let messages = []; // Array to hold messages

    // Create messages based on the level
    if (level === 1) {
        messages = [
            "Player: Take THAT!.",
            "Boss: Noooo! You may have won, but I'll see you in the next level!",
            "Boss: Until next time.",
            "Boss: Prepare yourself for what's to come!"
        ];
    } else if (level === 2) {
        messages = [
            "Player: Heh to ez!.",
            "Boss: You think this is the end? I’ll return!",
            "Boss: With my new enemies, you will never win!",
            "Boss: Prepare for an even greater challenge in Level 3!",
            "Boss: You will need to be stronger to defeat me next time!",
        ];
} else if (level === 3) {
    messages = [
        "Boss: How could this happen?!",
        "Boss: Well... That was all the attacks I had... and you beated them.",
        "Boss: Well now worries because my brother knows about this now.",
        "Boss: He will make sure your dead.",
        "Player: What do you mean your brother is coming to get me?.",
        "Boss: The strongest one in our family known for wiping all advanturers.",
        "Player: How come he is the strongest.",
        "Boss: he is known for his annoying attacks and summoning things.",
        "Boss: He plays around to much with his players.",
        "Boss: Good luck because this might be your actual last fight...",
        "Player: Ok?...",
    ];
    } else if (level === 4) {
        messages = [
            "Boss: I wish not to speak with you, get out.",
        ];
    } else if (level === 5) {
        messages = [
            "Trials ended",
            "Thank you for playing.",
            "That is the end of the game.",
        ];
}

// Function to display messages sequentially
function displaySequentialMessages(messages, index) {
    if (index < messages.length) {
        displayMessage(messages[index]); // Display current message
        
        // Set timeout for the next message
        setTimeout(() => {
            displaySequentialMessages(messages, index + 1); // Move to next message
        }, 4500); // 4.5 seconds delay
    } else {
        // After all messages in level 3, unlock Endless Mode
        if (level === 6) {
            localStorage.setItem('endlessModeUnlocked', 'true');
            localStorage.setItem('sandboxModeUnlocked', 'true');
            displayMessage("Endless Mode And sandbox Unlocked!"); // Optional inform player
            showEndlessModeButton();
            setTimeout(() => {
                setupNextLevel(); // Proceed to the next level setup
            }, 3000);
        } else {
            setupNextLevel(); // Proceed to the next level setup
        }
    }
}



    // Start the message display
    displaySequentialMessages(messages, 0);
}

function setupNextLevel() {
    // Check if in Endless Mode or Story Mode to manage levels separately
    if (isEndlessMode) {
        // Increment level for Endless mode
        currentEndlessLevel++; 
        localStorage.setItem('endlessLevel', currentEndlessLevel); // Save updated level
        
        displayMessage(`You've advanced to Endless Level ${currentEndlessLevel}!`);
        
    } else {
        // Logic for Story Mode - increment story level
        storyModeLevel++;
        if (storyModeLevel > 5) {
            storyModeLevel = 1; // Reset back to Level 1 if beyond max
        }
        localStorage.setItem('storyLevel', storyModeLevel); // Save updated level
        
        displayMessage(`You've advanced to Story Level ${storyModeLevel}!`);
    }

    // Set up the boss door to advance to the next level
    const bossDoor = document.createElement('div'); // Create a new div for the boss door
    bossDoor.classList.add('boss-door'); // Add class for styling
    bossDoor.style.position = 'absolute'; // Positioning for the door
    bossDoor.style.left = '600px'; // Specify door's X position
    bossDoor.style.bottom = '0px'; // Specify door's Y position (ground level)
    bossDoor.style.width = '50px'; // Set width
    bossDoor.style.height = '100px'; // Set height
    bossDoor.style.backgroundColor = 'gold'; // Set background color (for visibility)
    bossDoor.style.border = '2px solid black'; // Optional: add a border
    bossDoor.style.boxShadow = '0 0 15px rgba(255, 215, 0, 1)'; // Glow effect

    // Append the boss door to the game world
    gameWorld.appendChild(bossDoor);

    // Inform the player they can interact with the door
    displayMessage("Press 'E' to proceed to the next level!");
    
    // Allow player to transition to the next level upon interacting
    document.addEventListener('keydown', function handleKeyDown(event) {
        if (event.key === 'E' || event.key === 'e') {
            displayMessage("Refreshing to Level " + level + "...");
            location.reload(); // Refresh the page to start the new level
            console.log("Page refreshed for Level " + level + ".");
            document.removeEventListener('keydown', handleKeyDown); // Remove the event listener to prevent repeated triggering
        }
    });
}

function clearAllElements() {
    // Clear all elements in the game (elements grouped into arrays for easier management)
    [obstacles, enemies, bullets.map(b => b.element), powerUps, platforms, bossDoors, coins].forEach(arr => {
        arr.forEach(el => el.remove());
        arr.length = 0; // Clear the array
    });
}

function SendBackToDoor() {
    setTimeout(() => {
        player.style.left = "50px";
        player.style.bottom = "0px";

        setTimeout(() => {
            activateBossPower();
            level = 2; // Reset to Level 1
            resetGame();
            startLevel(); // Restart the game
        }, 2000);
    }, 3000);
}
 
 
            function activateFriendDialogue() {
                interactMessage.style.display = 'none';
                displayMessage("Thank you for saving me!");
                setTimeout(() => {
                    displayMessage("I got a secret power for you.");
                    setTimeout(() => {
                        grantBossPowerUp();
                        sendbacktodoor();
                        friend.style.display = 'none';
                    }, 3000);
                }, 2000);
            }
 
let isCharging = false;
let chargeTime = 0;
 
function shootLaserBlast(chargeTime) {
    let laser = document.createElement('div');
    laser.classList.add('laser');
    laser.style.left = player.style.left;
    laser.style.bottom = player.style.bottom;
    laser.style.width = `${chargeTime * 10}px`;
    laser.style.height = "10px";
    laser.style.backgroundColor = "cyan";
    gameWorld.appendChild(laser);
 
    setTimeout(() => {
        laser.remove();
        enemies.forEach(enemy => {
            if (checkCollision(laser, enemy)) {
                enemy.remove();
            }
        });
    }, 100);
}
 
 
            function displayMessage(message) {
                powerUpMessage.textContent = message;
                powerUpMessage.style.display = 'block';
                setTimeout(() => {
                    powerUpMessage.style.display = 'none';
                }, 2000);
            }
 
            function checkScoreForLevelTransition() {
                   localStorage.setItem('playerLevel', level); // Save updated level in local stora
            }
 
            function spawnFlyingEnemy() {
                const flyingEnemy = createElement('flying-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                flyingEnemy.style.bottom = Math.random() * 150 + 50 + 'px';
            }
 
function moveFlyingEnemies() {
    enemies.forEach((enemy, index) => {
        if (enemy.classList.contains('flying-enemy')) {
            // Move the enemy up and down
            let enemyYPosition = parseInt(enemy.style.bottom) || 0; // Get current Y position or default to 0
            let direction = enemy.dataset.direction ? parseInt(enemy.dataset.direction) : 1; // Up or down direction

            // Update vertical position of the flying enemy
            enemyYPosition += direction * 1; // Move 1 pixel per frame 
            enemy.style.bottom = enemyYPosition + 'px';

            // Reverse direction if the flying enemy reaches a certain height
            if (enemyYPosition >= 150) { // Maximum height
                direction = -1; // Change to downward movement
            } else if (enemyYPosition <= 0) { // Minimum height (ground)
                direction = 1; // Change to upward movement
            }
            enemy.dataset.direction = direction; // Store the current direction for the next update

            // Move the enemy left
            enemy.style.left = (parseInt(enemy.style.left) - 2) + 'px';

            // Check shooting
            if (enemy.dataset.lastShotTime === undefined || Date.now() - enemy.dataset.lastShotTime > 10000) { // Every 10 seconds
                shootBulletAtPlayer(enemy); // Shoot at the player
                enemy.dataset.lastShotTime = Date.now(); // Update the last shot time
            }

            // Boundary checking and collision with the player
            if (parseInt(enemy.style.left) < 0) {
                removeElement(enemy, enemies, index, 30);
            } else if (checkCollision(player, enemy)) {
                reduceLives();
                removeElement(enemy, enemies, index, 0);
            }
        }
    });
}

// Function to shoot a bullet aimed at the player
function shootBulletAtPlayer(enemy) {
    const bullet = document.createElement('div');
    bullet.classList.add('bullet'); // Add your bullet class
    bullet.style.width = '10px';
    bullet.style.height = '5px';
    bullet.style.backgroundColor = 'orange'; // Bullet color
    bullet.style.position = 'absolute';
    
    // Position the bullet at the enemy's current position
    bullet.style.left = (parseInt(enemy.style.left) + 20) + 'px'; // Position it slightly in front of the enemy
    bullet.style.bottom = (parseInt(enemy.style.bottom) + 15) + 'px'; // Start just below the enemy
    gameWorld.appendChild(bullet); // Add bullet to the game world
    
    // Calculate angle towards the player
    const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Center of player
    const playerY = parseInt(player.style.bottom); // Bottom of player

    const dx = playerX - (parseInt(bullet.style.left) + bullet.offsetWidth / 2);
    const dy = playerY - (parseInt(bullet.style.bottom));
    const distance = Math.sqrt(dx * dx + dy * dy); 
    const velocity = 5; // Speed of the bullet

    // Bullet movement
    const moveBullet = setInterval(() => {
        const moveX = (dx / distance) * velocity; 
        const moveY = (dy / distance) * velocity;

        bullet.style.left = (parseInt(bullet.style.left) + moveX) + 'px';
        bullet.style.bottom = (parseInt(bullet.style.bottom) + moveY) + 'px';

        // Check if the bullet hits the player or goes off screen
        if (checkCollision(bullet, player)) {
            reduceLives(); // Damages the player
            bullet.remove(); // Remove bullet
            clearInterval(moveBullet); // Stop moving the bullet
        }

        if (parseInt(bullet.style.left) < 0 || parseInt(bullet.style.left) > gameWorld.offsetWidth || parseInt(bullet.style.bottom) < 0) {
            bullet.remove(); // Remove bullet if it goes off screen
            clearInterval(moveBullet); // Stop moving the bullet
        }
    }, 1000 / 60); // 60 FPS
}
 
            function spawnChargingEnemy() {
                const chargingEnemy = createElement('charging-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                chargingEnemy.style.bottom = '0px';
                chargingEnemy.setAttribute('data-charge', '0');
                chargingEnemy.classList.add('charging-prep'); // Fading in/out red glow effect
            }
 
 
            function createChargeTrail(x, y) {
                const trail = document.createElement('div');
                trail.classList.add('charge-trail');
                trail.style.left = x + 'px';
                trail.style.bottom = y + 'px';
                gameWorld.appendChild(trail);
 
                setTimeout(() => trail.remove(), 400); // Shorter effect for smoothness
            }
 
 
 
 
function moveChargingEnemies() {
    enemies.forEach((enemy, index) => {
        if (enemy.classList.contains('charging-enemy')) {
            let chargeTime = parseInt(enemy.getAttribute('data-charge'));
 
            if (chargeTime < 60) {
                // Charging phase (fading in/out glow)
                enemy.setAttribute('data-charge', chargeTime + 1);
            } else {
                // Fully Charged (Solid Red Outline + Charging Forward)
                enemy.classList.remove('charging-prep');
                enemy.classList.add('charging-active');
                enemy.style.left = (parseInt(enemy.style.left) - 6) + 'px';
 
                // Create a bright red trail
                createChargeTrail(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
            }
 
            // Check collision with player
            if (checkCollision(player, enemy)) {
                createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom)); // Impact explosion
                reduceLives();
                removeElement(enemy, enemies, index, 0);
            }
 
            // Remove if out of bounds
            if (parseInt(enemy.style.left) < gameScrollPosition - enemy.offsetWidth) {
                removeElement(enemy, enemies, index, 30);
            }
        }
    });
}
 
 
 
            function spawnStealthEnemy() {
                const stealthEnemy = createElement('stealth-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                stealthEnemy.setAttribute('data-stealth', '0');
                stealthEnemy.style.backgroundColor = '#555';
                stealthEnemy.style.opacity = '1';
            }
 
            function moveStealthEnemies() {
                enemies.forEach(en => {
                    if (en.classList.contains('stealth-enemy')) {
                        const stealth = parseInt(en.getAttribute('data-stealth'));
                        if (stealth > 50) {
                            en.style.opacity = en.style.opacity == '0' ? '1' : '0';
                            en.setAttribute('data-stealth', '0');
                        } else {
                            en.setAttribute('data-stealth', stealth + 1);
                        }
                    }
                });
            }

function moveSniperEnemies() {
    enemies.forEach((enemy, index) => {
        if (enemy.classList.contains('sniper-enemy')) {
            const enemyX = parseInt(enemy.style.left) + enemy.offsetWidth / 2; // Center position
            const enemyY = parseInt(enemy.style.bottom) + enemy.offsetHeight; // Height

            // Shooting mechanism
            if (!enemy.dataset.lastShotTime || Date.now() - enemy.dataset.lastShotTime > 3000) { // Every 3 seconds
                shootAtPlayer(enemy);
                enemy.dataset.lastShotTime = Date.now(); // Update for next shot
            }

            // Check distance to player
            const distanceToPlayer = Math.sqrt(Math.pow(enemyX - (parseInt(player.style.left) + player.offsetWidth / 2), 2) + 
                Math.pow(enemyY - parseInt(player.style.bottom), 2));
            
            if (distanceToPlayer < 300) { // Within 300 pixels visibility range
                enemy.style.opacity = '1'; // Fully visible
            } else {
                enemy.style.opacity = '0.5'; // Reduced opacity
            }
        }
    });
}

// Function for the sniper to shoot at the player
function shootAtPlayer(enemy) {
    const bullet = document.createElement('div');
    bullet.classList.add('bullet'); // Add your class for the bullet
    bullet.style.width = '10px';
    bullet.style.height = '5px';
    bullet.style.backgroundColor = 'red'; // Bullet color
    bullet.style.position = 'absolute';
    
    // Position the bullet at the sniper's location
    bullet.style.left = (parseInt(enemy.style.left) + 20) + 'px'; // Set slight offset
    bullet.style.bottom = (parseInt(enemy.style.bottom) + 15) + 'px'; // Set above the sniper
    gameWorld.appendChild(bullet); // Add bullet to the game world

    // Calculate angle towards the player
    const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Center of player
    const playerY = parseInt(player.style.bottom); // Bottom of player

    const dx = playerX - (parseInt(bullet.style.left) + bullet.offsetWidth / 2);
    const dy = playerY - (parseInt(bullet.style.bottom));
    const distance = Math.sqrt(dx * dx + dy * dy); 
    const velocity = 5; // Speed of the bullet

    // Bullet movement logic
    const moveBullet = setInterval(() => {
        const moveX = (dx / distance) * velocity; // Calculate x movement direction
        const moveY = (dy / distance) * velocity; // Calculate y movement direction

        bullet.style.left = (parseInt(bullet.style.left) + moveX) + 'px';
        bullet.style.bottom = (parseInt(bullet.style.bottom) + moveY) + 'px';

        // Check for bullet collision with player
        if (checkCollision(bullet, player)) {
            reduceLives(); // Damage player
            bullet.remove(); // Remove bullet
            clearInterval(moveBullet); // Stop bullet movement
        }

        // Remove bullet if it goes off screen
        if (parseInt(bullet.style.left) < 0 || parseInt(bullet.style.left) > gameWorld.offsetWidth || parseInt(bullet.style.bottom) < 0) {
            bullet.remove(); // Remove bullet if it goes off screen
            clearInterval(moveBullet); // Stop bullet movement
        }
    }, 1000 / 60); // 60 FPS
}
 
function spawnSplitterEnemy() {
    const leftPos = gameScrollPosition + gameContainer.offsetWidth;
    const splitter = createElement('split-enemy', enemies, leftPos);
    splitter.style.left = leftPos + 'px';
    splitter.style.bottom = '0px';
    splitter.classList.add('split');  // Important!
    splitter.style.width = '50px';    
    splitter.style.height = '50px';
}

function moveSplitterEnemies() {
    enemies.forEach((enemy, index) => {
        if (enemy.classList.contains('split-enemy')) {
            const speed = enemy.classList.contains('split') ? 1 : 3; // mini splitters move faster
            enemy.style.left = (parseInt(enemy.style.left) - speed) + 'px';

            if (parseInt(enemy.style.left) < gameScrollPosition - enemy.offsetWidth) {
                removeElement(enemy, enemies, index, 30);  // Give some score for killing
            } else if (checkCollision(player, enemy)) {
                reduceLives();
                removeElement(enemy, enemies, index, 0);
            }
        }
    });
}
 
function handleSplitterEnemyHit(enemy, enemyIndex) {
    console.log('Splitter hit triggered for enemy:', enemy);
    if (enemy.classList.contains('split')) {  // just to be sure
        const baseLeft = parseInt(enemy.style.left);
        const baseBottom = enemy.style.bottom;
        const miniSize = 20;          // Increased size from 15 to 20 px
        const gap = 10;               // Gap between minis (pixels)

        for (let i = 0; i < 2; i++) { // Spawn only 2 mini enemies
            // Calculate left position for each mini enemy to have gap between them
            const miniLeft = baseLeft + i * (miniSize + gap);
            const miniEnemy = createElement('split-enemy', enemies, miniLeft);
            miniEnemy.style.width = miniSize + 'px';
            miniEnemy.style.height = miniSize + 'px';
            miniEnemy.classList.remove('split');
            miniEnemy.style.bottom = baseBottom; // Appear at the same vertical pos
        }
    }
    removeElement(enemy, enemies, enemyIndex, 0);
}
 
            function handleExplosiveEnemyHit(enemy, enemyIndex) {
                removeElement(enemy, enemies, enemyIndex, 0);
                enemies.forEach((otherEnemy, index) => {
                    if (calculateDistance(enemy, otherEnemy) < 50) {
                        removeElement(otherEnemy, enemies, index, 0);
                    }
                });
                createBurst(parseInt(enemy.style.left), parseInt(enemy.style.bottom));
                reduceLives();
            }
 
            function spawnSniperEnemy() {
                const sniper = createElement('sniper-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                sniper.style.bottom = '200px';
                const sniperInterval = setInterval(() => {
                    if (Math.random() < 0.05 && calculateDistance(player, sniper) < 300) {
                        const bullet = createBullet();
                        bullet.style.left = parseInt(sniper.style.left) + 'px';
                        bullet.style.bottom = parseInt(sniper.style.bottom) + 'px';
                        bullet.style.backgroundColor = 'red';
                        gameWorld.appendChild(bullet);
                        bullets.push({ element: bullet, direction: -1 });
                    }
                }, 1000);
 
                sniper.setAttribute('data-interval', sniperInterval);
            }
 

// Function to spawn the reflective enemy at the bottom
function spawnReflectiveEnemy() {
    // Create the reflective enemy element
    var reflectiveEnemy = createElement('reflective-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);

    // Set initial attributes
    reflectiveEnemy.setAttribute('data-health', '10'); // Set initial health or reflection strength
    reflectiveEnemy.classList.add('outlined'); // Add CSS class for glowing outline
    reflectiveEnemy.dataset.reflectiveHits = 0; // Initialize reflection hits tracking

    // Position the reflective enemy at the bottom of the game world
    reflectiveEnemy.style.bottom = '0px'; // Set to 0 for the bottom position

    // Set up shooting capability
    reflectiveEnemy.dataset.lastShotTime = Date.now(); // Track when the last shot was fired

    // Append the reflective enemy to the game world
    gameWorld.appendChild(reflectiveEnemy);
}

// Function to handle shooting bullets at the player
function shootAtPlayer2(reflectiveEnemy) {
    const bullet = document.createElement('div');
    bullet.classList.add('enemy-bullet'); // Style class for the bullet
    bullet.style.width = '10px';
    bullet.style.height = '5px';
    bullet.style.backgroundColor = 'red'; // Enemy bullet color
    bullet.style.position = 'absolute';

    // Position the bullet at the enemy's location
    bullet.style.left = `${parseInt(reflectiveEnemy.style.left) + 20}px`; // Center the bullet
    bullet.style.bottom = `${parseInt(reflectiveEnemy.style.bottom) + 15}px`; // Above the enemy
    gameWorld.appendChild(bullet); // Add bullet to the game world

    // Calculate the player’s position
    const playerX = parseInt(player.style.left) + player.offsetWidth / 2; // Center of player
    const playerY = parseInt(player.style.bottom); // Bottom of player

    // Calculate direction towards the player
    const dx = playerX - (parseInt(bullet.style.left) + bullet.offsetWidth / 2);
    const dy = playerY - parseInt(bullet.style.bottom);
    const distance = Math.sqrt(dx * dx + dy * dy);
    const velocity = 5; // Speed of the bullet

    // Move the bullet towards the player
    const moveBulletInterval = setInterval(() => {
        const moveX = (dx / distance) * velocity; // Calculate x movement
        const moveY = (dy / distance) * velocity; // Calculate y movement

        bullet.style.left = (parseInt(bullet.style.left) + moveX) + 'px';
        bullet.style.bottom = (parseInt(bullet.style.bottom) + moveY) + 'px';

        // Check for collision with player
        if (checkCollision(player, bullet)) {
            reduceLives(); // Damage player
            bullet.remove(); // Remove bullet
            clearInterval(moveBulletInterval); // Stop movement
        }

        // Remove bullet if it goes off screen
        if (parseInt(bullet.style.left) < 0 || parseInt(bullet.style.left) > gameWorld.offsetWidth || parseInt(bullet.style.bottom) < 0) {
            bullet.remove(); // Remove bullet if it goes off screen
            clearInterval(moveBulletInterval); // Stop movement
        }
    }, 1000 / 60); // Move at 60 FPS
}

// Update reflective enemy behavior to shoot at player on hit
function handleBulletCollisionWithReflectiveEnemy(reflectiveEnemy, bullet) {
    // Check if the bullet collides with the reflective enemy
    if (checkCollision(reflectiveEnemy, bullet)) {
        bullet.remove(); // Remove bullet on collision
        reflectiveEnemy.dataset.reflectiveHits++; // Track the number of hits

        // Call the shoot function after a certain interval
        if (Date.now() - reflectiveEnemy.dataset.lastShotTime >= 1) { // Cooldown for 2 seconds between shots
            shootAtPlayer2(reflectiveEnemy);
            reflectiveEnemy.dataset.lastShotTime = Date.now(); // Reset the shot time
        }
    }
}
 
            function spawnNewInteractiveEnemies() {
                const randomFeature = Math.random();
                if (randomFeature < 0.2) {
                    spawnTeleporterEnemy();
                } else if (randomFeature < 0.6) {
                    spawnVelocityEnemy();
                } else if (randomFeature < 0.8) {
                    spawnStickyEnemy();
                } else {
                    spawnReflectiveEnemy();
                }
            }
 
            function moveNewEnemies() {
                moveTeleporterEnemies();
                moveVelocityEnemies();
                moveStickyEnemies();
            }
 
            // New enemies with creative features
            function spawnTeleporterEnemy() {
                const teleporterEnemy = createElement('teleporter-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                teleporterEnemy.style.backgroundColor = '#8A2BE2'; 
                teleporterEnemy.style.bottom = '0px';
                teleporterEnemy.setAttribute('data-teleport', '0');
            }
 
            function moveTeleporterEnemies() {
                enemies.forEach(en => {
                    if (en.classList.contains('teleporter-enemy')) {
                        const teleport = parseInt(en.getAttribute('data-teleport'));
                        if (teleport > 100) {
                            en.style.left = Math.random() * (gameWorld.offsetWidth - en.offsetWidth) + 'px';
                            en.setAttribute('data-teleport', '0');
                        } else {
                            en.setAttribute('data-teleport', teleport + 1);
                        }
                    }
                });
            }

function moveReflectiveEnemies() {
    var enemiesToRemove = []; // Array to track enemies to be removed

    enemies.forEach(function(en, index) {
        if (en.classList.contains('reflective-enemy')) {
            // Move the reflective enemy to the left
            en.style.left = (parseInt(en.style.left) - 1) + 'px';

            // Check for collision with bullets
            bullets.forEach(function(bullet, bulletIndex) {
                // If the bullet collides with the reflective enemy
                if (checkCollision(en, bullet.element)) {
                    // Reflect the bullet's direction
                    bullet.direction *= -1; 

                    // Adjust bullet position slightly to avoid getting stuck
                    bullet.element.style.left = (parseInt(bullet.element.style.left) + (bullet.direction * 5)) + 'px';

                    // Increment the reflective hits count
                    en.dataset.reflectiveHits++;

                    // Optional: handle when you want to remove the enemy after a number of hits, if desired
                    if (parseInt(en.dataset.reflectiveHits) >= 10) {
                        enemiesToRemove.push(index); // Mark for removal
                    }

                    // Remove the bullet
                    bullet.element.remove();
                    bullets.splice(bulletIndex, 1); // Remove bullet from the bullets array
                }
            });

            // Check for collision with the player
            if (checkCollision(player, en)) {
                reduceLives(); // Reduce lives if player hits the reflective enemy
                enemiesToRemove.push(index); // Mark enemy for removal
            }

            // Remove if off-screen
            if (parseInt(en.style.left) < -en.offsetWidth) {
                enemiesToRemove.push(index); // Mark for removal
            }
        }
    });

    // Remove enemies marked for removal
    enemiesToRemove.reverse().forEach(function(index) {
        removeElement(enemies[index], enemies, index, 0);
    });
}
 
            function spawnVelocityEnemy() {
                const velocityEnemy = createElement('velocity-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                velocityEnemy.style.backgroundColor = '#FF4500'; 
                velocityEnemy.style.bottom = Math.random() * 150 + 'px';
                velocityEnemy.setAttribute('data-speed', '2');
            }
 
            function moveVelocityEnemies() {
                enemies.forEach(en => {
                    if (en.classList.contains('velocity-enemy')) {
                        const speed = parseInt(en.getAttribute('data-speed'));
                        en.style.left = (parseInt(en.style.left) - speed) + 'px';
                        en.style.bottom = (parseInt(en.style.bottom) + (Math.random() - 0.5) * 10) + 'px';
                        if (parseInt(en.style.left) < gameScrollPosition - en.offsetWidth) {
                            removeElement(en, enemies, 0, 30);
                        } else if (checkCollision(player, en)) {
                            reduceLives();
                            removeElement(en, enemies, 0, 0);
                        }
                    }
                });
            }

function spawnVirusDrone() {
    const leftPos = gameScrollPosition + gameContainer.offsetWidth;
    const virus = document.createElement('div');
    virus.classList.add('virus-drone');
    virus.style.bottom = '380px'; // top of screen (400px height container minus 20 px)
    virus.style.left = leftPos + 'px';
    virus.dataset.speed = 8;
    virus.dataset.activeEnemy = ''; // enemy it’s currently infecting

    gameWorld.appendChild(virus);
    viruses.push(virus); // store in separate array to manage separately
}
 
            function spawnStickyEnemy() {
                const stickyEnemy = createElement('sticky-enemy', enemies, gameScrollPosition + gameContainer.offsetWidth);
                stickyEnemy.style.backgroundColor = '#FFD700'; 
                stickyEnemy.style.bottom = '0px';
            }
 
            function moveStickyEnemies() {
                enemies.forEach(en => {
                    if (en.classList.contains('sticky-enemy')) {
                        en.style.left = (parseInt(en.style.left) - 1) + 'px';
                        if (checkCollision(player, en)) {
                            player.style.backgroundColor = '#FFD700';
                            setTimeout(() => player.style.backgroundColor = '#4CAF50', 2000);
                            removeElement(en, enemies, 0, 0);
                        }
                    }
                });
            }
 
 
    </script>
</body>
</html>