<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Byte-Sized Brawl: Code Chaos</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <style>
        body {
            margin: 0;
            overflow: hidden;
            font-family: 'Inter', sans-serif;
            background-color: #1a1a2e; /* Dark background */
            color: #e0e0e0; /* Light text */
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start; /* Align items to the top to ensure space for description */
            min-height: 100vh;
        }

        #game-container {
            position: relative;
            width: 100vw;
            height: 80vh; /* Make game container take 80% of viewport height */
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #1f1f3f; /* Slightly different background to see container boundaries */
        }

        canvas {
            display: block;
            background-color: #2a2a4a; /* Slightly lighter dark blue for canvas */
            border-radius: 15px; /* Rounded corners for canvas */
            box-shadow: 0 0 20px rgba(0, 255, 255, 0.5); /* Glowing effect */
            width: 100%; /* Ensure canvas fills container width */
            height: 100%; /* Ensure canvas fills container height */
        }

        #ui-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none; /* Allow mouse events to pass through to canvas */
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            padding: 20px;
            box-sizing: border-box;
        }

        .player-stats {
            display: flex;
            justify-content: space-between;
            width: 100%;
        }

        .player-info {
            background-color: rgba(0, 0, 0, 0.6);
            padding: 10px 15px;
            border-radius: 10px;
            border: 1px solid #00ffff; /* Cyan border */
            box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
            pointer-events: auto; /* Allow interaction with these elements */
            font-size: 1.1em;
            display: flex;
            flex-direction: column;
            gap: 5px;
            min-width: 150px;
            text-align: center;
        }

        .health-bar-container {
            width: 100%;
            background-color: #555;
            border-radius: 5px;
            height: 10px;
            overflow: hidden;
            border: 1px solid #00ffff;
        }

        .health-bar {
            height: 100%;
            background-color: #00ff00; /* Green health */
            width: 100%; /* Will be updated by JS */
            transition: width 0.2s ease-out;
        }

        #reset-button-container {
            width: 100%;
            display: flex;
            justify-content: center;
            pointer-events: auto; /* Allow interaction with button */
        }

        #resetButton {
            background-color: #4CAF50; /* Green */
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 1.2em;
            box-shadow: 0 5px #388e3c; /* Darker green shadow */
            transition: all 0.2s ease;
            pointer-events: auto; /* Allow interaction */
        }

        #resetButton:hover {
            background-color: #45a049;
            box-shadow: 0 3px #388e3c;
            transform: translateY(2px);
        }

        #resetButton:active {
            background-color: #3e8e41;
            box-shadow: 0 0 #388e3c;
            transform: translateY(5px);
        }

        #floating-message {
            position: absolute;
            top: 20%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            padding: 15px 25px;
            border-radius: 10px;
            border: 2px solid #00ffff;
            box-shadow: 0 0 15px rgba(0, 255, 255, 0.7);
            text-align: center;
            font-size: 1.3em;
            color: #ffffff;
            z-index: 1000;
            opacity: 0; /* Hidden by default */
            transition: opacity 0.3s ease-in-out;
            pointer-events: none; /* Allow mouse events to pass through */
        }

        .game-description-container {
            width: 80%;
            max-width: 900px;
            background-color: rgba(0, 0, 0, 0.6);
            padding: 20px;
            border-radius: 15px;
            border: 1px solid #00ffff;
            box-shadow: 0 0 15px rgba(0, 255, 255, 0.4);
            margin-top: 20px;
            text-align: left;
            overflow-y: auto; /* Enable scrolling for long descriptions */
            max-height: 18vh; /* Adjust max-height to fit remaining space */
            margin-bottom: 20px; /* Add some margin at the bottom */
        }

        .game-description-container h2 {
            color: #00ffff;
            margin-top: 0;
            text-align: center;
        }

        .game-description-container h3 {
            color: #99ffff;
            margin-top: 15px;
        }

        .game-description-container ul {
            list-style-type: disc;
            margin-left: 20px;
        }

        .game-description-container li {
            margin-bottom: 5px;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .player-info {
                font-size: 0.9em;
                padding: 8px 10px;
                min-width: unset;
            }
            #resetButton {
                padding: 10px 20px;
                font-size: 1em;
            }
            .game-description-container {
                width: 95%;
                padding: 15px;
                font-size: 0.9em;
                max-height: 25vh; /* Adjust max-height for smaller screens */
            }
            #game-container {
                height: 65vh; /* Adjust game container height for smaller screens */
            }
            #floating-message {
                font-size: 1em;
                padding: 10px 15px;
            }
        }
    </style>
</head>
<body>
    <div id="game-container">
        <canvas id="gameCanvas"></canvas>
        <div id="ui-overlay">
            <div class="player-stats">
                <div class="player-info">
                    Player 1 (WASD/E)<br>
                    Life: <span id="player1Life">100</span>
                    <div class="health-bar-container"><div id="player1HealthBar" class="health-bar"></div></div>
                    KOs: <span id="player1KOs">0</span>
                </div>
                <div class="player-info">
                    Player 2 (IJKL/U)<br>
                    Life: <span id="player2Life">100</span>
                    <div class="health-bar-container"><div id="player2HealthBar" class="health-bar"></div></div>
                    KOs: <span id="player2KOs">0</span>
                </div>
            </div>
            <div id="reset-button-container">
                <button id="resetButton">Reset Game</button>
            </div>
        </div>
        <div id="floating-message"></div>
    </div>

    <div class="game-description-container">
        <h2>Byte-Sized Brawl: Code Chaos</h2>
        <p>Welcome to "Byte-Sized Brawl: Code Chaos"! Dive into a retro-futuristic 3D arena, a simulated MMO testing ground where glitches are the least of your worries. Team up or face off against a friend in this top-down action-RPG, engaging in chaotic combat, solving byte-sized puzzles, and navigating a world on the brink of a digital meltdown!</p>

        <h3>Game Parts:</h3>
        <ul>
            <li><strong>Playable Characters:</strong> Two stylized humanoid figures (Player 1 and Player 2), assembled from 3D primitives, ready for action.</li>
            <li><strong>Glitch Bots:</strong> Various enemies constructed from primitive shapes, each with unique (and sometimes buggy) attack patterns.</li>
            <li><strong>Interactive Environment:</strong> A 3D arena with obstacles, movable blocks, and pressure plates that might just lead to digital treasure... or a trap!</li>
            <li><strong>NPCs (Non-Playable Code):</strong> Simple primitive figures offering cryptic quests and dialogue that might just make sense in the matrix.</li>
            <li><strong>Skill Tree (Conceptual):</strong> While not fully implemented in this demo, imagine a branching path of digital upgrades to enhance your character's abilities.</li>
            <li><strong>Digital Loot:</strong> Primitive-assembled items and equipment to boost your stats.</li>
            <li><strong>Life/Score Display:</strong> Keep track of your vital signs and KOs with clear displays at the top of the screen.</li>
            <li><strong>"Reset" Button:</strong> Your ultimate debug tool! Heals both players to full life and resets the current area, perfect for when things get too chaotic.</li>
        </ul>

        <h3>Method Steps:</h3>
        <ul>
            <li><strong>Explore the Digital Frontier:</strong> Navigate the top-down, full-screen 3D scene.</li>
            <li><strong>Player 1 Controls (WASD):</strong> Move your character with precision.</li>
            <li><strong>Player 2 Controls (IJKL):</strong> Guide your companion through the chaos.</li>
            <li><strong>Left Player Action (E):</strong> Unleash a digital attack, activate objects, or try to understand the NPCs.</li>
            <li><strong>Right Player Action (U):</strong> Perform your own digital assault, interact with the environment, or just flail wildly.</li>
            <li><strong>Solve Byte-Sized Puzzles:</strong> Push blocks, activate pressure plates, and bypass laser grids (if they were here!).</li>
            <li><strong>Complete Quests (Theoretically):</strong> Accept challenges from NPCs and try not to break the simulation.</li>
            <li><strong>Level Up (Imagination Required):</strong> Gain experience and unlock new skills from your conceptual skill tree.</li>
            <li><strong>Hit the Reset Button:</strong> When all else fails, use the "Reset Game" button to get a fresh start.</li>
        </ul>

        <h3>Rules of Engagement:</h3>
        <ul>
            <li><strong>Combat Rewards:</strong> Defeat Glitch Bots to earn experience and digital loot.</li>
            <li><strong>Skill Gates:</strong> Certain areas or puzzles might require specific skills or items (in a full version!).</li>
            <li><strong>Narrative Glitches:</strong> Dialogue choices might impact the story (or just confuse you further).</li>
            <li><strong>Co-op or Compete:</strong> Work together to achieve common goals, or compete for the most KOs and resources.</li>
            <li><strong>Incapacitation Protocol:</strong> If your life bar depletes, you're incapacitated! Your partner can revive you by getting close and using their action button, or you can both use the "Reset" button. If both players are down, it's game over!</li>
        </ul>

        <h3>What Makes It Fun:</h3>
        <ul>
            <li><strong>Retro-Futuristic Mashup:</strong> A unique blend of nostalgic 2D action-RPG vibes with modern 3D chaos.</li>
            <li><strong>Dynamic Duo Gameplay:</strong> The cooperative/competitive modes add layers of strategy and hilarious interactions.</li>
            <li><strong>Varied Digital Mayhem:</strong> From combat to puzzles and the promise of skill progression, there's always something to do.</li>
            <li><strong>Witty Narrative:</strong> The "futuristic MMO testing ground" setting provides a fun, self-aware backdrop for your adventures.</li>
        </ul>
    </div>

    <script>
        // Global variables for Three.js
        let scene, camera, renderer;
        let player1, player2;
        let enemies = [];
        let movableBlock;
        let pressurePlate;
        let wallToOpen; // The wall that opens when pressure plate is activated
        let powerups = []; // Array to hold power-up objects
        let shieldVisual; // Visual representation of the co-op shield
        let activeExplosions = []; // To manage particle explosions
        let activeShieldParticles = []; // To manage shield healing particles

        // Game state variables
        const MAX_HEALTH = 100;
        let player1Health = MAX_HEALTH;
        let player2Health = MAX_HEALTH;
        let player1KOs = 0;
        let player2KOs = 0;
        let player1Incapacitated = false;
        let player2Incapacitated = false;
        let pressurePlateActivated = false;
        let isShieldActive = false; // New: Co-op shield state

        // Wave and Scoring
        let currentWave = 1;
        let enemiesInCurrentWave = 0;
        let enemiesDefeatedInWave = 0;
        let scorePerEnemy = 10;
        let totalScore = 0;

        // Player movement and action states
        const keys = {
            w: false, a: false, s: false, d: false, e: false, // Player 1
            i: false, j: false, k: false, l: false, u: false  // Player 2
        };
        const PLAYER_SPEED = 0.5;
        const BASE_ATTACK_RANGE = 10; // Base attack range
        const COOP_ATTACK_RANGE_BOOST = 15; // Additional range when co-op shield is active
        const ATTACK_COOLDOWN = 500; // milliseconds
        const ATTACK_DURATION = 200; // milliseconds for attack animation
        let player1LastAttackTime = 0;
        let player2LastAttackTime = 0;
        const ENEMY_SPEED = 0.1; // Slower enemy speed
        const POWERUP_DURATION = 5000; // 5 seconds for attack/magic/armor boost
        const SHIELD_RANGE = 20; // Distance for co-op shield activation
        const COOP_ATTACK_WINDOW = 300; // Time window for combined attack (milliseconds)
        const PARTICLE_LIFESPAN = 1000; // Particle system lifespan in ms

        // UI elements
        const player1LifeSpan = document.getElementById('player1Life');
        const player2LifeSpan = document.getElementById('player2Life');
        const player1KOsSpan = document.getElementById('player1KOs');
        const player2KOsSpan = document.getElementById('player2KOs');
        const player1HealthBar = document.getElementById('player1HealthBar');
        const player2HealthBar = document.getElementById('player2HealthBar');
        const resetButton = document.getElementById('resetButton');
        const floatingMessage = document.getElementById('floating-message');
        let messageTimeout; // To clear previous message timeouts

        // Function to show a custom message box (now disappearing text)
        function showMessage(message) {
            clearTimeout(messageTimeout); // Clear any existing timeout
            floatingMessage.textContent = message;
            floatingMessage.style.opacity = 1;
            messageTimeout = setTimeout(() => {
                floatingMessage.style.opacity = 0;
            }, 2000); // Disappear after 2 seconds
        }

        // --- Wave and Enemy Spawning Functions ---
        function spawnEnemiesForWave(waveNumber) {
            // Clear existing enemies
            enemies.forEach(enemy => scene.remove(enemy));
            enemies = [];

            const numEnemies = Math.min(15, 3 + waveNumber * 2); // Max 15 enemies, scaling
            scorePerEnemy = 10 * waveNumber; // Score increases per wave

            for (let i = 0; i < numEnemies; i++) {
                const x = (Math.random() - 0.5) * 100;
                const z = (Math.random() - 0.5) * 100;
                enemies.push(createEnemy(0x00ff00, x, 0, z));
            }
            enemies.forEach(enemy => scene.add(enemy));
            enemiesInCurrentWave = numEnemies;
            enemiesDefeatedInWave = 0;
            showMessage(`Wave ${waveNumber} started! Score per enemy: ${scorePerEnemy}`);
        }

        function checkWaveCompletion() {
            if (enemiesDefeatedInWave >= enemiesInCurrentWave) {
                currentWave++;
                showMessage(`Wave ${currentWave - 1} completed! Preparing Wave ${currentWave}...`);
                setTimeout(() => spawnEnemiesForWave(currentWave), 2000); // Delay for next wave
            }
        }
        // --- End Wave and Enemy Spawning Functions ---


        // Initialize the game
        window.onload = function() {
            checkCanvasDimensions();
        };

        function checkCanvasDimensions() {
            const canvas = document.getElementById('gameCanvas');
            if (canvas.clientWidth > 0 && canvas.clientHeight > 0) {
                console.log('Canvas dimensions are valid. Initializing Three.js...');
                initThreeJS();
                spawnEnemiesForWave(1); // Start the first wave
                animate();
            } else {
                console.log('Canvas dimensions not yet valid. Retrying in 100ms...');
                setTimeout(checkCanvasDimensions, 100);
            }
        }

        function initThreeJS() {
            console.log('initThreeJS called.');

            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x2a2a4a);

            const canvas = document.getElementById('gameCanvas');
            const canvasWidth = canvas.clientWidth;
            const canvasHeight = canvas.clientHeight;

            console.log('initThreeJS - Canvas Width:', canvasWidth, 'Canvas Height:', canvasHeight);

            const aspect = canvasWidth / canvasHeight;
            const frustumSize = 120;

            camera = new THREE.OrthographicCamera(
                frustumSize * aspect / -2,
                frustumSize * aspect / 2,
                frustumSize / 2,
                frustumSize / -2,
                1,
                1000
            );
            camera.position.set(0, 70, 0);
            camera.lookAt(0, 0, 0);

            renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
            renderer.setSize(canvasWidth, canvasHeight);
            renderer.setPixelRatio(window.devicePixelRatio);

            const ambientLight = new THREE.AmbientLight(0x606060);
            scene.add(ambientLight);
            const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
            directionalLight.position.set(1, 1, 1).normalize();
            scene.add(directionalLight);

            const groundGeometry = new THREE.PlaneGeometry(150, 150);
            const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x4a4a6a, side: THREE.DoubleSide });
            const ground = new THREE.Mesh(groundGeometry, groundMaterial);
            ground.rotation.x = Math.PI / 2;
            scene.add(ground);

            const gridHelper = new THREE.GridHelper(100, 10, 0x00ffff, 0x888888);
            scene.add(gridHelper);

            const axesHelper = new THREE.AxesHelper(50);
            scene.add(axesHelper);

            player1 = createPlayer(0xff0000, -20, 0, 0);
            player2 = createPlayer(0x0000ff, 20, 0, 0);
            scene.add(player1);
            scene.add(player2);

            // Create shield visual (initially hidden)
            const shieldGeometry = new THREE.CylinderGeometry(SHIELD_RANGE, SHIELD_RANGE, 1, 32);
            const shieldMaterial = new THREE.MeshBasicMaterial({ color: 0x00ffff, transparent: true, opacity: 0.2 });
            shieldVisual = new THREE.Mesh(shieldGeometry, shieldMaterial);
            shieldVisual.position.y = 5; // Place slightly above ground
            shieldVisual.visible = false; // Hide initially
            scene.add(shieldVisual);

            // Initialize puzzle elements and powerups here, so they are always defined
            movableBlock = createMovableBlock(0xffff00, -10, 0, -10);
            scene.add(movableBlock);
            pressurePlate = createPressurePlate(0x888888, 10, 0, -10);
            scene.add(pressurePlate);
            wallToOpen = createWall(0x663300, 10, 0, -20);
            scene.add(wallToOpen);

            powerups.push(createPowerup('health', -40, 0, 40));
            powerups.push(createPowerup('attack', 40, 0, 40));
            powerups.push(createPowerup('magic', -40, 0, -40));
            powerups.push(createPowerup('armor', 40, 0, -40));
            powerups.push(createPowerup('health', 0, 0, 0));
            powerups.forEach(powerup => scene.add(powerup));


            window.addEventListener('resize', onWindowResize, false);
            document.addEventListener('keydown', onKeyDown, false);
            document.addEventListener('keyup', onKeyUp, false);
            resetButton.addEventListener('click', resetGame);

            updateUI();
            onWindowResize();
        }

        // --- Object Creation Functions ---

        function createPlayer(color, x, y, z) {
            const playerGroup = new THREE.Group();

            // Body (Box)
            const bodyGeometry = new THREE.BoxGeometry(4, 8, 4);
            const bodyMaterial = new THREE.MeshLambertMaterial({ color: color });
            const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
            body.position.y = 4; // Center on ground
            playerGroup.add(body);

            // Head (Sphere)
            const headGeometry = new THREE.SphereGeometry(2, 16, 16);
            const headMaterial = new THREE.MeshLambertMaterial({ color: 0xffe0bd }); // Skin color
            const head = new THREE.Mesh(headGeometry, headMaterial);
            head.position.y = 10; // On top of body
            playerGroup.add(head);

            // Arms (Cylinders) - Now part of the player group for independent rotation
            // Right arm (for weapon)
            const armRightGroup = new THREE.Group();
            const armGeometry = new THREE.CylinderGeometry(1, 1, 6, 8);
            const armMaterial = new THREE.MeshLambertMaterial({ color: color });
            const armRightMesh = new THREE.Mesh(armGeometry, armMaterial);
            armRightMesh.position.set(0, 3, 0); // Position relative to arm group's pivot
            armRightGroup.add(armRightMesh);
            armRightGroup.position.set(3, 7, 0); // Position arm group relative to player body
            armRightGroup.rotation.z = -Math.PI / 4; // Initial rotation
            playerGroup.add(armRightGroup);
            playerGroup.userData.armRight = armRightGroup; // Store reference for animation

            // Weapon (simple box for now)
            const weaponGeometry = new THREE.BoxGeometry(1, 1, 5);
            const weaponMaterial = new THREE.MeshLambertMaterial({ color: 0x888888 });
            const weapon = new THREE.Mesh(weaponGeometry, weaponMaterial);
            weapon.position.set(0, 3, 2.5); // Position at the end of the arm
            armRightGroup.add(weapon);
            playerGroup.userData.weapon = weapon; // Store reference

            // Left arm
            const armLeft = new THREE.Mesh(armGeometry, armMaterial);
            armLeft.position.set(-3, 7, 0);
            armLeft.rotation.z = Math.PI / 4;
            playerGroup.add(armLeft);

            // Legs (Cylinders)
            const legGeometry = new THREE.CylinderGeometry(1.5, 1.5, 4, 8);
            const legMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 }); // Dark color for pants
            const legLeft = new THREE.Mesh(legGeometry, legMaterial);
            legLeft.position.set(-1.5, 2, 0);
            playerGroup.add(legLeft);

            const legRight = new THREE.Mesh(legGeometry, legMaterial);
            legRight.position.set(1.5, 2, 0);
            playerGroup.add(legRight);

            playerGroup.position.set(x, y, z);
            playerGroup.userData.health = MAX_HEALTH;
            playerGroup.userData.isPlayer = true;
            playerGroup.userData.incapacitated = false;
            playerGroup.userData.isAttacking = false;
            playerGroup.userData.attackBoost = 0; // No attack boost initially
            playerGroup.userData.magicBoost = 0; // No magic boost initially
            playerGroup.userData.armorBoost = 0; // No armor boost initially
            return playerGroup;
        }

        function createEnemy(color, x, y, z) {
            const enemyGroup = new THREE.Group();

            // Main Body (Rounded Box)
            const bodyGeometry = new THREE.BoxGeometry(6, 6, 6);
            const bodyMaterial = new THREE.MeshLambertMaterial({ color: color });
            const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
            body.position.y = 3; // Center on ground
            enemyGroup.add(body);

            // Head (Octahedron for a more robotic/glitchy look)
            const headGeometry = new THREE.OctahedronGeometry(3);
            const headMaterial = new THREE.MeshLambertMaterial({ color: 0x888888 }); // Grey
            const head = new THREE.Mesh(headGeometry, headMaterial);
            head.position.y = 8; // On top of body
            enemyGroup.add(head);

            // Eyes (Small Spheres)
            const eyeGeometry = new THREE.SphereGeometry(0.8, 8, 8);
            const eyeMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 }); // Red eyes
            const eyeLeft = new THREE.Mesh(eyeGeometry, eyeMaterial);
            eyeLeft.position.set(-1.5, 9, 2.5);
            head.add(eyeLeft);
            const eyeRight = new THREE.Mesh(eyeGeometry, eyeMaterial);
            eyeRight.position.set(1.5, 9, 2.5);
            head.add(eyeRight);

            // Legs (Thin Cylinders)
            const legGeometry = new THREE.CylinderGeometry(0.8, 0.8, 4, 8);
            const legMaterial = new THREE.MeshLambertMaterial({ color: 0x555555 });
            const legFrontLeft = new THREE.Mesh(legGeometry, legMaterial);
            legFrontLeft.position.set(-2, 0, -2);
            enemyGroup.add(legFrontLeft);
            const legFrontRight = new THREE.Mesh(legGeometry, legMaterial);
            legFrontRight.position.set(2, 0, -2);
            enemyGroup.add(legFrontRight);
            const legBackLeft = new THREE.Mesh(legGeometry, legMaterial);
            legBackLeft.position.set(-2, 0, 2);
            enemyGroup.add(legBackLeft);
            const legBackRight = new THREE.Mesh(legGeometry, legMaterial);
            legBackRight.position.set(2, 0, 2);
            enemyGroup.add(legBackRight);

            // Antennas (Thin Cylinders on head)
            const antennaGeometry = new THREE.CylinderGeometry(0.3, 0.3, 3, 8);
            const antennaMaterial = new THREE.MeshLambertMaterial({ color: 0xaaaaaa });
            const antennaLeft = new THREE.Mesh(antennaGeometry, antennaMaterial);
            antennaLeft.position.set(-1.5, 11, 0);
            antennaLeft.rotation.x = Math.PI / 4;
            enemyGroup.add(antennaLeft);
            const antennaRight = new THREE.Mesh(antennaGeometry, antennaMaterial);
            antennaRight.position.set(1.5, 11, 0);
            antennaRight.rotation.x = -Math.PI / 4;
            enemyGroup.add(antennaRight);


            enemyGroup.position.set(x, y, z);
            enemyGroup.userData.health = 50; // Enemies have less health
            enemyGroup.userData.isEnemy = true;
            return enemyGroup;
        }

        function createMovableBlock(color, x, y, z) {
            const geometry = new THREE.DodecahedronGeometry(6); // More interesting shape
            const material = new THREE.MeshLambertMaterial({ color: color });
            const block = new THREE.Mesh(geometry, material);
            block.position.set(x, y + 6, z); // Center on ground
            block.userData.isMovable = true;
            return block;
        }

        function createPressurePlate(color, x, y, z) {
            const geometry = new THREE.TorusGeometry(4, 1, 8, 32); // Flat torus shape
            const material = new THREE.MeshLambertMaterial({ color: color });
            const plate = new THREE.Mesh(geometry, material);
            plate.rotation.x = Math.PI / 2; // Lay flat
            plate.position.set(x, y + 0.5, z); // Slightly above ground
            plate.userData.isPressurePlate = true;
            return plate;
        }

        function createWall(color, x, y, z) {
            // A more stylized barrier with multiple boxes
            const wallGroup = new THREE.Group();
            const segmentGeometry = new THREE.BoxGeometry(5, 15, 5);
            const segmentMaterial = new THREE.MeshLambertMaterial({ color: color });

            for (let i = -2; i <= 2; i++) {
                const segment = new THREE.Mesh(segmentGeometry, segmentMaterial);
                segment.position.set(i * 6, 7.5, 0); // Spaced segments
                wallGroup.add(segment);
            }
            wallGroup.position.set(x, y, z);
            wallGroup.userData.isWall = true;
            return wallGroup;
        }

        function createPowerup(type, x, y, z) {
            let geometry;
            let material;
            let powerupMesh;

            switch (type) {
                case 'health':
                    geometry = new THREE.SphereGeometry(3, 16, 16);
                    material = new THREE.MeshLambertMaterial({ color: 0xff0000 }); // Red sphere for health
                    powerupMesh = new THREE.Mesh(geometry, material);
                    break;
                case 'attack':
                    geometry = new THREE.ConeGeometry(3, 6, 8);
                    material = new THREE.MeshLambertMaterial({ color: 0x00ffff }); // Cyan cone for attack boost
                    powerupMesh = new THREE.Mesh(geometry, material);
                    powerupMesh.rotation.x = Math.PI / 2; // Point it horizontally
                    break;
                case 'magic':
                    geometry = new THREE.TetrahedronGeometry(4); // Pyramid for magic
                    material = new THREE.MeshLambertMaterial({ color: 0x8A2BE2 }); // Purple for magic
                    powerupMesh = new THREE.Mesh(geometry, material);
                    break;
                case 'armor':
                    geometry = new THREE.BoxGeometry(5, 5, 5);
                    material = new THREE.MeshLambertMaterial({ color: 0x708090 }); // Slate gray for armor
                    powerupMesh = new THREE.Mesh(geometry, material);
                    break;
                default:
                    geometry = new THREE.BoxGeometry(4, 4, 4);
                    material = new THREE.MeshLambertMaterial({ color: 0xcccccc });
                    powerupMesh = new THREE.Mesh(geometry, material);
                    break;
            }

            powerupMesh.position.set(x, y + (geometry.parameters.height ? geometry.parameters.height / 2 : 2), z);
            powerupMesh.userData.isPowerup = true;
            powerupMesh.userData.type = type;
            return powerupMesh;
        }

        function createExplosionParticles(position, color) {
            const particleCount = 50;
            const positions = new Float32Array(particleCount * 3);
            const colors = new Float32Array(particleCount * 3);
            const sizes = new Float32Array(particleCount);

            const pColor = new THREE.Color(color);

            for (let i = 0; i < particleCount; i++) {
                // Random position within a small sphere
                positions[i * 3] = position.x + (Math.random() - 0.5) * 10;
                positions[i * 3 + 1] = position.y + (Math.random() - 0.5) * 10 + 5; // Slightly above ground
                positions[i * 3 + 2] = position.z + (Math.random() - 0.5) * 10;

                colors[i * 3] = pColor.r;
                colors[i * 3 + 1] = pColor.g;
                colors[i * 3 + 2] = pColor.b;

                sizes[i] = Math.random() * 2 + 1; // Random size
            }

            const geometry = new THREE.BufferGeometry();
            geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
            geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); // Custom attribute for size

            const material = new THREE.PointsMaterial({
                size: 1, // Base size, actual size controlled by 'size' attribute
                vertexColors: true,
                transparent: true,
                opacity: 1,
                blending: THREE.AdditiveBlending,
                sizeAttenuation: true // Particles closer to camera appear larger
            });

            const particles = new THREE.Points(geometry, material);
            particles.userData.spawnTime = Date.now();
            particles.userData.lifespan = PARTICLE_LIFESPAN;
            particles.userData.velocity = [];
            for (let i = 0; i < particleCount; i++) {
                particles.userData.velocity.push(
                    new THREE.Vector3((Math.random() - 0.5) * 0.5, Math.random() * 0.5 + 0.1, (Math.random() - 0.5) * 0.5)
                );
            }
            scene.add(particles);
            activeExplosions.push(particles);
        }

        function createShieldHealingParticles(position) {
            const particleCount = 5; // Fewer particles for healing
            const positions = new Float32Array(particleCount * 3);
            const colors = new Float32Array(particleCount * 3);
            const sizes = new Float32Array(particleCount);

            const pColor = new THREE.Color(0x00ff00); // Green for healing

            for (let i = 0; i < particleCount; i++) {
                positions[i * 3] = position.x + (Math.random() - 0.5) * 5;
                positions[i * 3 + 1] = position.y + (Math.random() - 0.5) * 5 + 5;
                positions[i * 3 + 2] = position.z + (Math.random() - 0.5) * 5;

                colors[i * 3] = pColor.r;
                colors[i * 3 + 1] = pColor.g;
                colors[i * 3 + 2] = pColor.b;

                sizes[i] = Math.random() * 1 + 0.5;
            }

            const geometry = new THREE.BufferGeometry();
            geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
            geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));

            const material = new THREE.PointsMaterial({
                size: 1,
                vertexColors: true,
                transparent: true,
                opacity: 0.8,
                blending: THREE.AdditiveBlending,
                sizeAttenuation: true
            });

            const particles = new THREE.Points(geometry, material);
            particles.userData.spawnTime = Date.now();
            particles.userData.lifespan = PARTICLE_LIFESPAN;
            particles.userData.velocity = [];
            for (let i = 0; i < particleCount; i++) {
                particles.userData.velocity.push(
                    new THREE.Vector3(0, Math.random() * 0.2 + 0.05, 0) // Move mostly upwards
                );
            }
            scene.add(particles);
            activeShieldParticles.push(particles);
        }


        // --- Game Logic Functions ---

        function onWindowResize() {
            const canvas = document.getElementById('gameCanvas');
            const newWidth = canvas.clientWidth;
            const newHeight = canvas.clientHeight;

            console.log('Resizing - Canvas Width:', newWidth, 'Canvas Height:', newHeight);

            if (newWidth > 0 && newHeight > 0) {
                const aspect = newWidth / newHeight;
                const frustumSize = 120;

                camera.left = frustumSize * aspect / -2;
                camera.right = frustumSize * aspect / 2;
                camera.top = frustumSize / 2;
                camera.bottom = frustumSize / -2;
                camera.updateProjectionMatrix();

                renderer.setSize(newWidth, newHeight);
            }
        }

        function onKeyDown(event) {
            switch (event.key) {
                case 'w': keys.w = true; break; case 'a': keys.a = true; break;
                case 's': keys.s = true; break; case 'd': keys.d = true; break;
                case 'e': keys.e = true; break;

                case 'i': keys.i = true; break; case 'j': keys.j = true; break;
                case 'k': keys.k = true; break; case 'l': keys.l = true; break;
                case 'u': keys.u = true; break;
            }
        }

        function onKeyUp(event) {
            switch (event.key) {
                case 'w': keys.w = false; break; case 'a': keys.a = false; break;
                case 's': keys.s = false; break; case 'd': keys.d = false; break;
                case 'e': keys.e = false; break;

                case 'i': keys.i = false; break; case 'j': keys.j = false; break;
                case 'k': keys.k = false; break; case 'l': keys.l = false; break;
                case 'u': keys.u = false; break;
            }
        }

        function updatePlayerMovement(player, deltaX, deltaZ) {
            if (player.userData.incapacitated) return;

            const newX = player.position.x + deltaX;
            const newZ = player.position.z + deltaZ;

            const boundary = 70;
            if (Math.abs(newX) < boundary && Math.abs(newZ) < boundary) {
                player.position.x = newX;
                player.position.z = newZ;
            }
        }

        function handlePlayerActions() {
            const currentTime = Date.now();

            // Player 1 Action (E)
            if (keys.e && !player1Incapacitated) {
                if (player2Incapacitated && player1.position.distanceTo(player2.position) < 10) {
                    player2Incapacitated = false;
                    player2Health = Math.min(MAX_HEALTH, player2Health + MAX_HEALTH / 2); // Revive with half health
                    updateUI();
                    showMessage("Player 1 revived Player 2!");
                } else if (!player1.userData.isAttacking && currentTime - player1LastAttackTime > ATTACK_COOLDOWN) {
                    player1.userData.isAttacking = true;
                    player1.userData.attackStartTime = currentTime;
                    player1LastAttackTime = currentTime;
                }
            }

            // Player 2 Action (U)
            if (keys.u && !player2Incapacitated) {
                if (player1Incapacitated && player2.position.distanceTo(player1.position) < 10) {
                    player1Incapacitated = false;
                    player1Health = Math.min(MAX_HEALTH, player1Health + MAX_HEALTH / 2); // Revive with half health
                    updateUI();
                    showMessage("Player 2 revived Player 1!");
                } else if (!player2.userData.isAttacking && currentTime - player2LastAttackTime > ATTACK_COOLDOWN) {
                    player2.userData.isAttacking = true;
                    player2.userData.attackStartTime = currentTime;
                    player2LastAttackTime = currentTime;
                }
            }
        }

        function animatePlayerAttack(player) {
            if (!player.userData.isAttacking) return;

            const currentTime = Date.now();
            const elapsedTime = currentTime - player.userData.attackStartTime;
            const progress = Math.min(1, elapsedTime / ATTACK_DURATION);

            const startAngle = -Math.PI / 4;
            const endAngle = Math.PI * 3 / 4;

            if (progress < 0.5) {
                player.userData.armRight.rotation.z = startAngle + (endAngle - startAngle) * (progress * 2);
            } else {
                player.userData.armRight.rotation.z = endAngle - (endAngle - startAngle) * ((progress - 0.5) * 2);
            }

            if (progress >= 0.25 && progress <= 0.75 && !player.userData.damageDealtThisSwing) {
                let currentAttackRange = BASE_ATTACK_RANGE;
                if (isShieldActive) {
                    currentAttackRange += COOP_ATTACK_RANGE_BOOST;
                }
                if (player.userData.magicBoost > currentTime) { // Magic boost increases range
                    currentAttackRange *= 1.5;
                }

                enemies.forEach(enemy => {
                    if (enemy.userData.health > 0 && player.position.distanceTo(enemy.position) < currentAttackRange) {
                        // Check for combined attack
                        const otherPlayer = (player === player1) ? player2 : player1;
                        const otherPlayerLastAttackTime = (player === player1) ? player2LastAttackTime : player1LastAttackTime;

                        if (isShieldActive && otherPlayer.userData.isAttacking && (currentTime - otherPlayerLastAttackTime < COOP_ATTACK_WINDOW)) {
                            showMessage("Combined Attack! Monster Instantly Defeated!");
                            enemy.userData.health = 0; // Instant kill
                        } else {
                            showMessage("Monster Instantly Defeated!");
                            enemy.userData.health = 0; // Instant kill
                        }

                        if (enemy.userData.health <= 0) {
                            scene.remove(enemy);
                            createExplosionParticles(enemy.position, 0xffa500); // Orange explosion
                            if (player === player1) player1KOs++;
                            else player2KOs++;
                            totalScore += scorePerEnemy; // Add score
                            enemiesDefeatedInWave++;
                            checkWaveCompletion();
                        }
                        updateUI();
                    }
                });
                player.userData.damageDealtThisSwing = true;
            }

            if (progress >= 1) {
                player.userData.isAttacking = false;
                player.userData.armRight.rotation.z = startAngle;
                player.userData.damageDealtThisSwing = false;
            }
        }

        function updateEnemyLogic() {
            enemies.forEach(enemy => {
                if (enemy.userData.health <= 0) return;

                let targetPlayer = null;
                const distToP1 = enemy.position.distanceTo(player1.position);
                const distToP2 = enemy.position.distanceTo(player2.position);

                if (!player1Incapacitated && !player2Incapacitated) {
                    targetPlayer = (distToP1 < distToP2) ? player1 : player2;
                } else if (!player1Incapacitated) {
                    targetPlayer = player1;
                } else if (!player2Incapacitated) {
                    targetPlayer = player2;
                } else {
                    return;
                }

                if (targetPlayer) {
                    const direction = new THREE.Vector3().subVectors(targetPlayer.position, enemy.position).normalize();
                    enemy.position.addScaledVector(direction, ENEMY_SPEED);

                    if (enemy.position.distanceTo(targetPlayer.position) < 8) {
                        let damage = 0.5;
                        if (isShieldActive) {
                            damage *= 0.1; // Reduce damage significantly if shield is active
                        }
                        if (targetPlayer.userData.armorBoost > Date.now()) { // Armor boost reduces damage
                            damage *= 0.5;
                        }

                        if (targetPlayer === player1 && !player1Incapacitated) {
                            player1Health -= damage;
                            if (player1Health <= 0) {
                                player1Health = 0;
                                player1Incapacitated = true;
                                showMessage("Player 1 incapacitated! Player 2, revive them or reset!");
                            }
                        } else if (targetPlayer === player2 && !player2Incapacitated) {
                            player2Health -= damage;
                            if (player2Health <= 0) {
                                player2Health = 0;
                                player2Incapacitated = true;
                                showMessage("Player 2 incapacitated! Player 1, revive them or reset!");
                            }
                        }
                        updateUI();
                    }
                }
            });
        }

        function handleMovableBlock() {
            // Simplified collision check for pushing block
            const players = [player1, player2];
            players.forEach(player => {
                if (player.userData.incapacitated) return;
                const distToBlock = player.position.distanceTo(movableBlock.position);
                if (distToBlock < 10) {
                    const direction = new THREE.Vector3().subVectors(movableBlock.position, player.position).normalize();
                    movableBlock.position.addScaledVector(direction, PLAYER_SPEED * 0.5); // Push slower than player movement
                    // Basic boundary for block
                    const blockBoundary = 60;
                    movableBlock.position.x = Math.max(-blockBoundary, Math.min(blockBoundary, movableBlock.position.x));
                    movableBlock.position.z = Math.max(-blockBoundary, Math.min(blockBoundary, movableBlock.position.z));
                }
            });

            const distanceToPlate = movableBlock.position.distanceTo(pressurePlate.position);
            if (distanceToPlate < 5 && !pressurePlateActivated) {
                pressurePlateActivated = true;
                scene.remove(wallToOpen);
                showMessage("A path has opened!");
            } else if (distanceToPlate >= 5 && pressurePlateActivated) {
                // Optional: wall reappears if block leaves plate
                // if (!scene.children.includes(wallToOpen)) {
                //     scene.add(wallToOpen);
                // }
                // pressurePlateActivated = false;
            }
        }

        function checkPowerupCollisions() {
            const currentTime = Date.now();
            const players = [player1, player2];

            for (let i = powerups.length - 1; i >= 0; i--) {
                const powerup = powerups[i];
                powerup.rotation.y += 0.02;

                players.forEach(player => {
                    if (player.position.distanceTo(powerup.position) < 5) {
                        switch (powerup.userData.type) {
                            case 'health':
                                if (player === player1) player1Health = Math.min(MAX_HEALTH, player1Health + 30);
                                else player2Health = Math.min(MAX_HEALTH, player2Health + 30);
                                showMessage(`${player === player1 ? 'Player 1' : 'Player 2'} picked up Health!`);
                                break;
                            case 'attack':
                                player.userData.attackBoost = currentTime + POWERUP_DURATION;
                                showMessage(`${player === player1 ? 'Player 1' : 'Player 2'} picked up Attack Boost!`);
                                break;
                            case 'magic':
                                player.userData.magicBoost = currentTime + POWERUP_DURATION;
                                showMessage(`${player === player1 ? 'Player 1' : 'Player 2'} picked up Magic Boost!`);
                                break;
                            case 'armor':
                                player.userData.armorBoost = currentTime + POWERUP_DURATION;
                                showMessage(`${player === player1 ? 'Player 1' : 'Player 2'} picked up Armor Boost!`);
                                break;
                        }
                        scene.remove(powerup);
                        powerups.splice(i, 1);
                        updateUI();
                    }
                });
            }

            // Decay boosts
            players.forEach(player => {
                if (player.userData.attackBoost > 0 && currentTime > player.userData.attackBoost) {
                    player.userData.attackBoost = 0;
                    showMessage(`${player === player1 ? 'Player 1' : 'Player 2'}'s Attack Boost expired!`);
                }
                if (player.userData.magicBoost > 0 && currentTime > player.userData.magicBoost) {
                    player.userData.magicBoost = 0;
                    showMessage(`${player === player1 ? 'Player 1' : 'Player 2'}'s Magic Boost expired!`);
                }
                if (player.userData.armorBoost > 0 && currentTime > player.userData.armorBoost) {
                    player.userData.armorBoost = 0;
                    showMessage(`${player === player1 ? 'Player 1' : 'Player 2'}'s Armor Boost expired!`);
                }
            });
        }

        function updateCoopShield() {
            const distanceBetweenPlayers = player1.position.distanceTo(player2.position);
            const wasShieldActive = isShieldActive;

            if (distanceBetweenPlayers < SHIELD_RANGE && !player1Incapacitated && !player2Incapacitated) {
                isShieldActive = true;
                shieldVisual.position.copy(player1.position).lerp(player2.position, 0.5);
                shieldVisual.visible = true;

                // Continuously spawn healing particles
                if (Math.random() < 0.1) { // Spawn rate
                    createShieldHealingParticles(player1.position);
                    createShieldHealingParticles(player2.position);
                }

                if (!wasShieldActive) {
                    showMessage("Co-op Shield Activated!");
                }
            } else {
                isShieldActive = false;
                shieldVisual.visible = false;
                if (wasShieldActive) {
                    showMessage("Co-op Shield Deactivated.");
                }
            }
        }

        function updateParticleSystems() {
            const currentTime = Date.now();

            // Update explosion particles
            for (let i = activeExplosions.length - 1; i >= 0; i--) {
                const particles = activeExplosions[i];
                const elapsedTime = currentTime - particles.userData.spawnTime;
                const progress = elapsedTime / particles.userData.lifespan;

                if (progress >= 1) {
                    scene.remove(particles);
                    activeExplosions.splice(i, 1);
                    continue;
                }

                // Update particle positions and opacity
                const positions = particles.geometry.attributes.position.array;
                const sizes = particles.geometry.attributes.size.array;
                const velocities = particles.userData.velocity;
                const material = particles.material;

                material.opacity = 1 - progress; // Fade out

                for (let j = 0; j < positions.length / 3; j++) {
                    positions[j * 3] += velocities[j].x;
                    positions[j * 3 + 1] += velocities[j].y;
                    positions[j * 3 + 2] += velocities[j].z;
                    // Make particles shrink
                    sizes[j] = (1 - progress) * (particles.userData.initialSizes ? particles.userData.initialSizes[j] : sizes[j]);
                }
                particles.geometry.attributes.position.needsUpdate = true;
                particles.geometry.attributes.size.needsUpdate = true;
            }

            // Update shield healing particles
            for (let i = activeShieldParticles.length - 1; i >= 0; i--) {
                const particles = activeShieldParticles[i];
                const elapsedTime = currentTime - particles.userData.spawnTime;
                const progress = elapsedTime / particles.userData.lifespan;

                if (progress >= 1) {
                    scene.remove(particles);
                    activeShieldParticles.splice(i, 1);
                    continue;
                }

                const positions = particles.geometry.attributes.position.array;
                const velocities = particles.userData.velocity;
                const material = particles.material;

                material.opacity = 1 - progress;

                for (let j = 0; j < positions.length / 3; j++) {
                    positions[j * 3] += velocities[j].x;
                    positions[j * 3 + 1] += velocities[j].y;
                    positions[j * 3 + 2] += velocities[j].z;
                }
                particles.geometry.attributes.position.needsUpdate = true;
            }
        }


        function updateUI() {
            player1LifeSpan.textContent = Math.max(0, Math.floor(player1Health));
            player2LifeSpan.textContent = Math.max(0, Math.floor(player2Health));
            // For now, let's just use player1KOs as total score
            document.getElementById('player1KOs').textContent = totalScore;
            document.getElementById('player2KOs').textContent = `Wave: ${currentWave}`;


            player1HealthBar.style.width = `${(player1Health / MAX_HEALTH) * 100}%`;
            player2HealthBar.style.width = `${(player2Health / MAX_HEALTH) * 100}%`;

            player1.visible = !player1Incapacitated;
            player2.visible = !player2Incapacitated;

            if (player1Incapacitated && player2Incapacitated) {
                showMessage("Game Over! Both players incapacitated. Press Reset to restart.");
                // Prevent further game logic until reset
                return;
            }
        }

        function resetGame() {
            player1Health = MAX_HEALTH;
            player2Health = MAX_HEALTH;
            player1KOs = 0;
            player2KOs = 0;
            totalScore = 0; // Reset total score
            currentWave = 1; // Reset wave
            player1Incapacitated = false;
            player2Incapacitated = false;
            pressurePlateActivated = false;
            isShieldActive = false;

            player1.position.set(-20, 0, 0);
            player2.position.set(20, 0, 0);
            player1.userData.isAttacking = false;
            player2.userData.isAttacking = false;
            player1.userData.attackBoost = 0;
            player2.userData.attackBoost = 0;
            player1.userData.magicBoost = 0;
            player2.userData.magicBoost = 0;
            player1.userData.armorBoost = 0;
            player2.userData.armorBoost = 0;
            player1.userData.armRight.rotation.z = -Math.PI / 4;
            player2.userData.armRight.rotation.z = -Math.PI / 4;

            enemies.forEach(enemy => scene.remove(enemy));
            enemies = [];
            powerups.forEach(powerup => scene.remove(powerup));
            powerups = [];
            activeExplosions.forEach(p => scene.remove(p));
            activeExplosions = [];
            activeShieldParticles.forEach(p => scene.remove(p));
            activeShieldParticles = [];

            // Remove old puzzle elements from scene if they exist
            if (movableBlock && movableBlock.parent) scene.remove(movableBlock);
            if (pressurePlate && pressurePlate.parent) scene.remove(pressurePlate);
            if (wallToOpen && wallToOpen.parent) scene.remove(wallToOpen);

            // Re-create and add initial puzzle elements
            movableBlock = createMovableBlock(0xffff00, -10, 0, -10);
            scene.add(movableBlock);
            pressurePlate = createPressurePlate(0x888888, 10, 0, -10);
            scene.add(pressurePlate);
            wallToOpen = createWall(0x663300, 10, 0, -20);
            scene.add(wallToOpen);
            pressurePlateActivated = false; // Ensure wall is reset to its original state

            powerups.push(createPowerup('health', -40, 0, 40));
            powerups.push(createPowerup('attack', 40, 0, 40));
            powerups.push(createPowerup('magic', -40, 0, -40));
            powerups.push(createPowerup('armor', 40, 0, -40));
            powerups.push(createPowerup('health', 0, 0, 0));
            powerups.forEach(powerup => scene.add(powerup));

            shieldVisual.visible = false;

            spawnEnemiesForWave(currentWave); // Start the first wave again
            updateUI();
        }

        // Animation loop
        function animate() {
            requestAnimationFrame(animate);

            // Only update game logic if not game over
            if (!(player1Incapacitated && player2Incapacitated)) {
                if (keys.w) updatePlayerMovement(player1, 0, -PLAYER_SPEED);
                if (keys.s) updatePlayerMovement(player1, 0, PLAYER_SPEED);
                if (keys.a) updatePlayerMovement(player1, -PLAYER_SPEED, 0);
                if (keys.d) updatePlayerMovement(player1, PLAYER_SPEED, 0);

                if (keys.i) updatePlayerMovement(player2, 0, -PLAYER_SPEED);
                if (keys.k) updatePlayerMovement(player2, 0, PLAYER_SPEED);
                if (keys.j) updatePlayerMovement(player2, -PLAYER_SPEED, 0);
                if (keys.l) updatePlayerMovement(player2, PLAYER_SPEED);

                handlePlayerActions();
                animatePlayerAttack(player1);
                animatePlayerAttack(player2);
                updateEnemyLogic();
                handleMovableBlock();
                checkPowerupCollisions();
                updateCoopShield();
            }
            updateParticleSystems(); // Always update particles, even if game over
            updateUI();

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