document.addEventListener('DOMContentLoaded', function() {
    const canvas = document.getElementById('game-canvas');
    const ctx = canvas.getContext('2d');
    const playerSize = 40;
    const playerImage = new Image();
    playerImage.src = 'player.png';
    const layerWidth = 80;  
    const ladderXOffset = 200;  
    const ladderWidth = layerWidth / 2;  
    const ladderHeight = 80;  
    const playerSpeed = 10;  
    let playerX = 0;  
    let playerY = canvas.height - playerSize - 50;  
    let isJumping = false;
    let canMove = false;  
    let jumpsLeft = 2;  
    let currentLayer = 0;  
    const ladderPositions = [];  
    let isOnLadder = false;  
    let greenRectangles = [];  
    let lives = 3;  
    let level = 1;  
    let previousPlayerY = playerY;  
    let countdown = -15;  
    let purpleSquareX = 333;  
    let purpleSquareY = 333;  
    let purpleSquareSize = 40;  
    let blueSquareX = 100;  
    let blueSquareY = 100;  
    let blueSquareSize = 40;  
    let pinkSquare = {
        x: 0,  
        y: canvas.height - playerSize - 50,  
        size: playerSize,  
        isInvincible: false,  
        invincibilityTimer: 0,  
         
    };
    let isInvincible = false;  
    let invincibilityTimer = 0;  
    let score = 0;  
 
let isPinkSquareVisible = true;
let isDonkeyKongVisible = true;
 
let lastConsoleLogMessage = "";
const dkImage = new Image();
dkImage.src = 'dk.png';
 

function logAndStore(message) {
    console.log(message);
    lastConsoleLogMessage = message;
}

function drawDonkeyKong() {
    if (isDonkeyKongVisible) {
         
        ctx.drawImage(dkImage, playerX + playerSize - 60, playerY - 60, 60, 60);
    }
}




 
setTimeout(() => {
    isPinkSquareVisible = false;
}, 10000);  
     
    for (let i = 0; i < 5; i++) {
        let x;
        if (i % 2 === 0) {  
            x = canvas.width - ladderXOffset - ladderWidth;
        } else {  
            x = ladderXOffset;
        }
        const y = canvas.height - 50 - (i + 1) * 100 + 10;  
        ladderPositions.push({ x, y });
    }

    function drawScore() {
        ctx.font = "16px Arial";
        ctx.fillStyle = "#0095DD";
         
        ctx.fillText(`Score: ${score}`, canvas.width - 60 - 100, 20);  
    }

 
function drawHammerTime() {
    if (isPinkSquareVisible) {
        ctx.font = "30px Arial";
        ctx.fillStyle = "red";
         
        ctx.fillText("HAMMERTIME", canvas.width - 500, 595);  
    }
}

    function drawPlayer() {
        if (isInvincible) {
             
            ctx.fillStyle = 'pink';
            ctx.fillRect(pinkSquare.x, pinkSquare.y, pinkSquare.size, pinkSquare.size);
        } else {
             
            ctx.fillStyle = '#fff';
            ctx.fillRect(playerX, playerY, playerSize, playerSize);
        }
        
    }
    

    function drawSolidObjects() {
        ctx.fillStyle = '#8B4513';  
        let yPos = canvas.height - 50;
        let openingSide = 'right';
    
        for (let i = 0; i < canvas.height; i += 100) {
            if (i === playerY) {  
                ctx.fillRect(0, yPos, canvas.width, 20);  
            } else {
                 
                if (openingSide === 'left') {
                    ctx.fillRect(0, yPos, canvas.width - layerWidth, 20);  
                    openingSide = 'right';
                } else {
                    ctx.fillRect(layerWidth, yPos, canvas.width - layerWidth, 20);  
                    openingSide = 'left';
                }
            }
            yPos -= 100;
        }
    
         
        ctx.fillStyle = '#008000';  
        ladderPositions.forEach(ladder => {
            let adjustedX = ladder.x;  
    
             
            if (level === 2 || level === 3) {
                 
                adjustedX = canvas.width - ladder.x - ladderWidth;
            }
    
            ctx.fillRect(adjustedX, ladder.y, ladderWidth, ladderHeight);  
        });
    }

     
    function drawDonkeyKong() {
        greenRectangles.forEach(rectangle => {
            const image = new Image();
            image.src = 'wp.png';  
            ctx.drawImage(image, rectangle.x, rectangle.y, 40, 40);
        });


         
        if (level === 2 || level === 3) {
             
            ctx.fillRect(canvas.width - 100 - 60, 90, 60, 60);  
        } else {
            ctx.fillRect(canvas.width - 100 - 60, 90, 60, 60);  
        }
    }

     
    function drawLevel() {
        ctx.font = '20px Arial';
        ctx.fillStyle = 'white';
        ctx.fillText(`Level: ${level}`, 10, canvas.height - 10);
    }

     
    function drawCountdown() {
        ctx.font = '20px Arial';
        ctx.fillStyle = 'white';
        ctx.fillText(`Countdown: ${countdown}`, canvas.width / 2 - 50, 30);
    }

     
    function drawLives() {
        ctx.font = '20px Arial';
        ctx.fillStyle = 'white';
        ctx.fillText(`Lives: ${lives}`, 10, 30);
    }

 
function movePlayer(direction) {
    if (direction === 'left') {
         
        playerX -= playerSpeed;
        pinkSquare.x = playerX - pinkSquare.size;  
    } else if (direction === 'right') {
         
        playerX += playerSpeed;
        pinkSquare.x = playerX + playerSize;  
    }
    draw();
}

 
document.addEventListener('keydown', function(event) {
    if (!canMove) return;  
    if (!isJumping) {
        if (event.key === 'ArrowLeft' && playerX > 0) {
            movePlayer('left');  
        } else if (event.key === 'ArrowRight' && playerX + playerSize < canvas.width) {
            movePlayer('right');  
        } else if (event.key === 'ArrowUp') {
            climbUp();
        } else if (event.key === 'ArrowDown') {
            climbDown();
        }
    }
    if (event.key === ' ') {
        jump();
    }
    checkCollisions();
    checkLevelTransition();  
    draw();
});

     
function drawPurpleSquare() {
    ctx.fillStyle = 'purple';
    purpleSquareY = 10;  
    ctx.fillRect(purpleSquareX, purpleSquareY, purpleSquareSize, purpleSquareSize);
}

    function drawBlueSquare() {
        ctx.fillStyle = 'blue';  
        ctx.fillRect(blueSquareX, blueSquareY, blueSquareSize, blueSquareSize);  
    }
     
    function clearCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

    function draw() {
        clearCanvas();
        drawDonkeyKong();
        drawPlayer();  
        
        drawSolidObjects();
        drawLives();
        drawLevel();
        drawCountdown();
        drawPurpleSquare();
        drawHammerTime();
        
    
     
    if (level === 2) {
        blueSquareX = 200;  
        blueSquareY = 200;  
    } else if (level === 3) {
        blueSquareX = 300;  
        blueSquareY = 300;  
    } else if (level === 4) {
        blueSquareX = 400;  
        blueSquareY = 400;  
    }
    
    drawBlueSquare();  
    drawScore();
}
    
function drawPinkSquare() {
    ctx.fillStyle = 'pink';  
    ctx.fillRect(pinkSquare.x, pinkSquare.y, pinkSquare.size, pinkSquare.size);
}
     
    function jump() {
        if (!isJumping && jumpsLeft > 0 && !isOnLadder) {
            isJumping = true;
            previousPlayerY = playerY;  
            playerY -= 50;  
            jumpsLeft--;
            setTimeout(() => {
                isJumping = false;
                applyGravity();
                checkJumpCompletion();  
            }, 700);  
        }
    }

     
    function applyGravity() {
        const groundLevel = canvas.height - playerSize - 50 - (currentLayer * 100);
        if (playerY < groundLevel) {
            playerY += 10;
            draw();
            requestAnimationFrame(applyGravity);
        } else {
            playerY = groundLevel;
            jumpsLeft = 2;
            draw();
        }
    }

 
function climbUp() {
    for (const ladder of ladderPositions) {
        let adjustedX = ladder.x;  

         
        if (level === 2 || level === 3) {
             
            adjustedX = canvas.width - ladder.x - ladderWidth;
        }

         
        if (
            playerX + playerSize >= adjustedX &&
            playerX <= adjustedX + ladderWidth &&
            playerY + playerSize >= ladder.y &&
            playerY <= ladder.y + ladderHeight
        ) {
            playerY -= 100;
            currentLayer++;
            draw();
            return;
        }

      
        
    }
}

     
    function climbDown() {
        for (const ladder of ladderPositions) {
            if (
                playerX + playerSize >= ladder.x &&
                playerX <= ladder.x + ladderWidth &&
                playerY + playerSize >= ladder.y &&
                playerY <= ladder.y + ladderHeight
            ) {
                if (!isOnLadder) {
                    playerY += 50;
                    currentLayer--;
                }
                isOnLadder = true;
                draw();
                return;
            }
        }
    }

    function moveGreenRectangle(rectangle) {
         
        if (rectangle.direction === 'left' && level === 1 || rectangle.direction === 'right' && level === 2) {
            rectangle.x -= rectangle.speed;
        } else {
            rectangle.x += rectangle.speed;
        }
         
        const solidObjectsY = canvas.height - 90;
        if (rectangle.y + 40 >= solidObjectsY) {
            if (rectangle.x < canvas.width - layerWidth && rectangle.x + 40 > layerWidth) {
                rectangle.speed *= -1;
                rectangle.y = solidObjectsY - 40;
            }
        }
        if (rectangle.x <= 39 || rectangle.x >= canvas.width - 79) {
            rectangle.y += 100;
            rectangle.speed *= -1;
        }
        if (currentLayer === 0 && rectangle.y >= canvas.height - 90 - 20) {
            rectangle.speed = -5;
            rectangle.y = canvas.height - 90 - 20;
        }
        if (rectangle.y >= canvas.height - 90 - 50) {
            rectangle.speed = 5;
        }
    }

     
    function generateGreenRectangle() {
         
        let initialX = level === 1 ? canvas.width - 160 : canvas.width - 60 - 40;  
        const randomY = 110;
        let speed = 5;  

          
    if (level === 2) {
        speed += 0.1;
    } else if (level === 3) {
        speed += 0.3;
    } else if (level === 4) {
        speed += 0.6;
    }

        const direction = level === 1 ? 'left' : 'right';  
        greenRectangles.push({ x: initialX, y: randomY, speed, direction });
    }

     
    function checkJumpCompletion() {
         
        if (playerY < previousPlayerY) {
            for (let i = 0; i < greenRectangles.length; i++) {
                const rectangle = greenRectangles[i];
                 
                if (
                    playerX < rectangle.x + 40 &&
                    playerX + playerSize > rectangle.x &&
                    previousPlayerY + playerSize <= rectangle.y &&  
                    playerY + playerSize >= rectangle.y - 15  
                ) {
                     
                     
                    const proximityScore = Math.max(0, 100 - Math.abs(playerX + playerSize / 2 - (rectangle.x + 20)));
                    score += proximityScore;
                    console.log(`Score: ${score}`);
                }
            }
        }
        previousPlayerY = playerY;  
    }

    function checkCollisions() {
        
        if (
            playerX < blueSquareX + blueSquareSize &&
            playerX + playerSize > blueSquareX &&
            playerY < blueSquareY + blueSquareSize &&
            playerY + playerSize > blueSquareY
        ) {
             
            pinkSquare.x = playerX;  
            pinkSquare.y = playerY;  
            pinkSquare.isInvincible = true;
            pinkSquare.invincibilityTimer = 10;  
             
            blueSquareX = -100;  
            blueSquareY = -100;  
        
             
            playerX = pinkSquare.x;
            playerY = pinkSquare.y;
            isInvincible = true;  
        
            draw();  
        }
        const donkeyKongX = canvas.width - 100 - 60;  
        const donkeyKongY = 90;
        if (
            pinkSquare.x < donkeyKongX + 60 &&
            pinkSquare.x + pinkSquare.size > donkeyKongX &&
            pinkSquare.y < donkeyKongY + 60 &&
            pinkSquare.y + pinkSquare.size > donkeyKongY
        ) {
             
            if (level === 1) {
                 
                isDonkeyKongVisible = false;  
                console.log("Donkey Kong has been defeated!");
            } else if (level >= 2) {
                 
                isDonkeyKongVisible = true;  
                console.log("Donkey Kong has reappeared!");
            }
        }
    
    
         
    
 
for (let i = 0; i < greenRectangles.length; i++) {
    const rectangle = greenRectangles[i];
    if (
        playerX < rectangle.x + 40 &&
        playerX + playerSize > rectangle.x &&
        playerY < rectangle.y + 40 &&
        playerY + playerSize > rectangle.y
    ) {
         
        if (isInvincible) {
             
            score += 100;  
            greenRectangles.splice(i, 1);  
            i--;  
        } else {
             
            lives--;
            if (lives <= 0) {
                 
                resetGame();
            } else {
                resetPlayerPosition();
            }
        }
        break;  
    }
}
    }

     
    function resetPlayerPosition() {
        playerX = 0;
        playerY = canvas.height - playerSize - 50;
        currentLayer = 0;
        isOnLadder = false;
        jumpsLeft = 2;
        if (level === 2 || level === 3 || level === 4) {
             
            playerX = canvas.width - playerSize - 80;  
            playerY = canvas.height - playerSize - 50;  
        }
    }

     
    function resetGame() {
         
        resetPlayerPosition();
        lives = 3;
        level = 1;
         
    }

     
    function startCountdown() {
        const countdownInterval = setInterval(() => {
            countdown++;
            draw();
            if (gameOver) {
                clearInterval(countdownInterval);
                            }
        }, 1000);  
    }

    startCountdown();  

     
    setTimeout(() => {
        document.addEventListener('keydown', function(event) {
            if (!isJumping) {
                if (event.key === 'ArrowLeft' && playerX > 0) {
                    movePlayer('left');  
                } else if (event.key === 'ArrowRight' && playerX + playerSize < canvas.width) {
                    movePlayer('right');  
                } else if (event.key === 'ArrowUp') {
                    climbUp();  
                } else if (event.key === 'ArrowDown') {
                    climbDown();  
                }
            }
            if (event.key === ' ') {
                jump();
            }
            checkCollisions();
            checkLevelTransition();  
            draw();
        });
    }, 15);  

     
    function randomSpawnTime(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

     
    function spawnGreenRectangle() {
         
        let minInterval, maxInterval;
        if (level === 1) {
            minInterval = 1500;  
            maxInterval = 4500;  
        } else if (level === 2 || level === 3 || level === 4) {
            minInterval = 999;  
            maxInterval = 1999;  
        }

         
        const randomInterval = randomSpawnTime(minInterval, maxInterval);

         
        generateGreenRectangle();
        draw();

         
        setTimeout(spawnGreenRectangle, randomInterval);
    }

    spawnGreenRectangle();  

 
setInterval(() => {
    greenRectangles.forEach(moveGreenRectangle);
    checkCollisions();  
    draw();

     
    if (isInvincible && invincibilityTimer > 0) {
        invincibilityTimer--;
         
        if (invincibilityTimer === 0) {
             
            isInvincible = false;
             
            playerX = 0;
            playerY = canvas.height - playerSize - 50;
             
            isOnLadder = false;
            jumpsLeft = 2;
            currentLayer = 0;
             
            draw();
        }
    }
    function hidePinkSquareAfterDelay() {
        setTimeout(() => {
            isPinkSquareVisible = false;
        }, 10000);  
    }
     
    if (level === 1 && score >= 300) {
         
        isPinkSquareVisible = false;

         
        isInvincible = false;

         
        score = 300;
    }
}, 30);  

     
    if (score >= 300) {
         
        isPinkSquareVisible = false;

         
        isInvincible = false;
    }
    
     
    function checkLevelTransition() {
         
        if (
            (playerX < purpleSquareX + purpleSquareSize &&
            playerX + playerSize > purpleSquareX &&
            playerY < purpleSquareY + purpleSquareSize &&
            playerY + playerSize > purpleSquareY) ||
            (pinkSquare.x < purpleSquareX + purpleSquareSize &&
            pinkSquare.x + pinkSquare.size > purpleSquareX &&
            pinkSquare.y < purpleSquareY + purpleSquareSize &&
            pinkSquare.y + pinkSquare.size > purpleSquareY)
        ) {
             
             
            level++;
    
             
            resetGameStatesForNextLevel();
    
             
            logAndStore(`After level ${level - 1}`);
        }
 
const maxScores = [300, 600, 800, 1200];  

function checkLevelTransition() {
     
    if (
        (playerX < purpleSquareX + purpleSquareSize &&
        playerX + playerSize > purpleSquareX &&
        playerY < purpleSquareY + purpleSquareSize &&
        playerY + playerSize > purpleSquareY) ||
        (pinkSquare.x < purpleSquareX + purpleSquareSize &&
        pinkSquare.x + pinkSquare.size > purpleSquareX &&
        pinkSquare.y < purpleSquareY + purpleSquareSize &&
        pinkSquare.y + pinkSquare.size > purpleSquareY)
    ) {
         
         
        level++;

         
        resetGameStatesForNextLevel();

         
        logAndStore(`Transitioned to level ${level} after reaching the purple square.`);
    }

     
    if (level === 1 && score >= 300) {
         
        isPinkSquareVisible = false;

         
        isInvincible = false;

         
        score = 300;
    } else if (level === 2 && score >= 600) {
         
        isPinkSquareVisible = false;

         
        isInvincible = false;

         
        score = 600;
    } else if (level === 3 && score >= 900) {
         
        isPinkSquareVisible = false;

         
        isInvincible = false;

         
        score = 900;
    } else if (level === 4 && score >= 1200) {
         
        isPinkSquareVisible = false;

         
        isInvincible = false;

         
        score = 1200;
    }
}

 
setInterval(checkLevelTransition, 1000 / 60);  
    }
    
    function resetGameStatesForNextLevel() {
         
        resetPlayerPosition();
        isPinkSquareVisible = true;  
        isInvincible = false;  
         
    }
    
    function resetPlayerPosition() {
         
        if (level === 1) {
            playerX = 0;  
            playerY = canvas.height - playerSize - 50;  
        } else if (level === 2) {
             
            playerX = canvas.width - playerSize - 80;  
            playerY = canvas.height - playerSize - 50;  
        } else if (level === 3 || level === 4) {
             
             
            playerX = canvas.width - playerSize - 80;  
            playerY = canvas.height - playerSize - 50;  
        }
         
        currentLayer = 0;
        isOnLadder = false;
        jumpsLeft = 2;
    }
 
}); ineed help with my games, its like donkey kong, i need the player "whitesquare" to be player.png image instead