<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game</title>
    <link rel="stylesheet" href="main.css">
    <!-- <script src="sandbox.js" defer></script> -->
</head>

<body>
    <nav class="gameUi">
        <div class="logo">
            <a href="/"><img id="superbased" src="/img/superbased.png" alt=""></a>
            <a href="/"><img id="devolved"src="/img/devolved.png" alt=""></a>
          </div>
    <!-- scoreboard -->
    <h1 class="scoreboard">0</h1>

    <div class="health">
        <h1 class="hp">3</h1>
        <img src="/img/heart.png" class="heart" id="heart1" alt="" srcset="">
        <h1 class="super">SUPER CHARGE</h1>
    </div>
    </nav>

    <!-- player -->
    <div class="fullScreen">
        <div class="object">
            <h1 class="text" id="coock"> <%= user.username%></h1>
        </div>
    </div>
    <!-- enemy npc -->
    <div class="enemy">
        <div class="killBox">
            <h1 class="text"> enemy</h1>
        </div>
    </div>
    
    <script>
//DOM Elements
let objImage = document.querySelector('.object'); //player
let enemy = document.querySelector(".enemy") //enemy npc
let scoreboard = document.querySelector('.scoreboard') //scoreboard
let playerName = document.querySelector("#coock").innerText
let playerHp = document.querySelector(".hp")
let charge = document.querySelector(".super")





//variabels
let leftPosition = (window.innerWidth - 100) // player start nd current position 
let topPosition = (window.innerHeight - 100) // player start nd current position 
let topEnemy = 78 // enemy current and start position
let leftEnemy = 1 // enemyt current and start position
const speed = 10// game speed
let playerSpeed = speed
let enemySpeed = speed - 9

let score = 0 //current score
let isInside = 0 // if enemy is inside player
let hp = 3
let enemywidth = 100
let enemyhieght = 100
let playerCharge = 0
let playerChargeReady = 0
let sec = 0
const startTopPostion = topPosition
const startLeftPostion = leftPosition
const enemyStartLeftPostion = topEnemy
const enemyStartTopPostion = leftEnemy
const boundsPlayer = {    
  left: 0,
  top: 78,
  right: window.innerWidth - 100,
  bottom: window.innerHeight - 100
}; 
let boundsEnemy = {    
  left: 0,
  top: 78,
  right: window.innerWidth - enemywidth,
  bottom: window.innerHeight - enemyhieght
}; 
function startRun () {
    objImage.style.left = leftPosition + "px" 
    objImage.style.top = topPosition + "px"
} //function for starting the game ( moves player to start position)
function moveLeft() {
    leftPosition -= playerSpeed;
    if (leftPosition < boundsPlayer.left) {
      leftPosition = boundsPlayer.left;// sets player position to bounds position  
    } //cheacks if player is inside bounds
    objImage.style.left = leftPosition + "px";
} // moves the player left

function moveUp() {
    topPosition -= playerSpeed;
    if (topPosition < boundsPlayer.top) {
      topPosition = boundsPlayer.top;// sets player position to bounds position  
    }//cheacks if player is inside bounds
    objImage.style.top = topPosition + "px";
}// moves the player up

function moveRight() {
    leftPosition += playerSpeed;
    if (leftPosition > boundsPlayer.right) {
      leftPosition = boundsPlayer.right;// sets player position to bounds position  
    }//cheacks if player is inside bounds
    objImage.style.left = leftPosition + "px";
}// moves the player right

function moveDown() {
    topPosition += playerSpeed;
    if (topPosition > boundsPlayer.bottom) {
      topPosition = boundsPlayer.bottom;// sets player position to bounds position  
    }//cheacks if player is inside bounds
    objImage.style.top = topPosition + "px";
}// moves the player down
startRun() // runs function to set players
document.querySelector('body').addEventListener("keydown", function (e) { //anonym functon to cheack whitch key was pressed
    let key_code = e.keyCode; //saves key press value
    switch (key_code) {
        case 37:// key pressed left
            moveLeft();
            break;
        case 38:// key pressed up
            moveUp();
            break;
        case 39://key pressed right
            moveRight();
            break;
        case 40://key pressed down
            moveDown();
            break;
            case 32://key pressed down
            if (playerChargeReady == 1) {
              superChargeOn()
            }
            break;
        default:// breakes code if up donw left right was not pressed
            break;
    }
});



function enemyMoveRight() {
    leftEnemy += enemySpeed;
    if (leftEnemy > boundsEnemy.right) {
      leftEnemy = boundsEnemy.right;// sets enemy position to bounds position  
    }//cheacks if enemy is inside bounds
    enemy.style.left = leftEnemy + "px";
}// moves the enemy down



function enemyMoveLeft() {
    leftEnemy -= enemySpeed;
    if (leftEnemy < boundsEnemy.left) {
      leftEnemy = boundsEnemy.left;// sets enemy position to bounds position  
    }//cheacks if enemy is inside bounds
    enemy.style.left = leftEnemy + "px";
}// moves the enemy down



function enemyMoveUp() {
    topEnemy -= enemySpeed;
    if (topEnemy < boundsEnemy.top) {
      topEnemy = boundsEnemy.top;// sets enemy position to bounds position  
    }//cheacks if enemy is inside bounds
    enemy.style.top = topEnemy + "px";
}// moves the enemy down
function enemyMoveDown() {
    topEnemy += enemySpeed;
    if (topEnemy > boundsEnemy.bottom) {
        topEnemy = boundsEnemy.bottom;// sets enemy position to bounds position  
      }//cheacks if enmy is inside bounds
    enemy.style.top = topEnemy + "px";
}// moves the enemy down

function followObject() {
    boundsEnemy = {    
    left: 0,
    top: 78,
    right: window.innerWidth - enemywidth,
    bottom: window.innerHeight - enemyhieght
}; 
    const objRect = objImage.getBoundingClientRect(); //get current position of player
    const enemyRect = enemy.getBoundingClientRect();//get current position of enemy
    
    // calculate distance between objImage and enemy
    const distanceX = objRect.x - enemyRect.x;
    const distanceY = objRect.y - enemyRect.y;
    
    // move enemy closer to objImage
    if (playerCharge == 1) {
      if (distanceX < 0) {
      enemyMoveRight();
    } else if (distanceX > 0) {
      enemyMoveLeft();
    }
    
    if (distanceY < 0) {
      enemyMoveDown();
    } else if (distanceY > 0) {
      enemyMoveUp();
    }
    }
    if (playerCharge == 0) {
      if (distanceX > 0) {
      enemyMoveRight();
    } else if (distanceX < 0) {
      enemyMoveLeft();
    }
    
    if (distanceY > 0) {
      enemyMoveDown();
    } else if (distanceY < 0) {
      enemyMoveUp();
    }
    
    }

    
    if (!(
        objRect.right < enemyRect.left || 
        objRect.left > enemyRect.right || 
        objRect.bottom < enemyRect.top || 
        objRect.top > enemyRect.bottom
      )) {
        isInside = 1 
        //cheacks if enemy is inside player
    }
    else {
      //else is not inside
        isInside = 0
    }
  }
function sizeEnemy() {
    enemywidth = enemywidth + 10
    enemyhieght = enemyhieght + 10
    enemy.style.height + enemyhieght
    enemy.style.width + enemywidth
    enemy.style.width = enemywidth + "px"
    enemy.style.height = enemyhieght + "px"
}
function enemySpeedUpdate() {
  enemySpeed = enemySpeed + 1
}
function updateHp() {
    playerHp.innerText = hp
}

  async function addScore () {
    if (isInside == 1) { //cheack if enemy inside player
        if (playerCharge == 0) {
          hp = hp - 1
            if (hp == 0) {
              const topScore = score
              try {
            const res = await fetch('/score', { 
            method: 'POST', 
            body: JSON.stringify({  score: topScore, username: playerName }),
            headers: {'Content-Type': 'application/json'}
                });
            const data = await res.json()
            window.location.replace("/scoreboard");
            if (data.errors) {
                console.log(data.errors);
            }


        } catch (error) {
            console.log(error);
        }
            
        
            }
            updateHp()
            topPosition = startTopPostion
            leftPosition =startLeftPostion
            topEnemy = enemyStartLeftPostion
            leftEnemy = enemyStartTopPostion
            objImage.style.top = topPosition + "px";
            objImage.style.left = leftPosition + "px";
            enemy.style.left = leftEnemy + "px";
            enemy.style.top = topEnemy + "px";
            ; //takes away score if enemy is inside player
    } else if (playerCharge == 1) {
          hp = hp +1 
          updateHp()
          topPosition = startTopPostion
            leftPosition =startLeftPostion
            topEnemy = enemyStartLeftPostion
            leftEnemy = enemyStartTopPostion
            objImage.style.top = topPosition + "px";
            objImage.style.left = leftPosition + "px";
            enemy.style.left = leftEnemy + "px";
            enemy.style.top = topEnemy + "px"

          score = score + 1
        scoreboard.innerText = score
        if (playerCharge == 1) {
          console.log(sec);
            if (sec > 4) {
              sec = 0
              superChargeOff()
            } else {
              charge.style.color="red"

            sec = sec + 1
            }
          }}}  else { // if not player gets score
        score = score + 1
        scoreboard.innerText = score
        if (playerCharge == 1) {
          console.log(sec);
            if (sec > 4) {
              sec = 0
              superChargeOff()
            } else {
              charge.style.color="red"
            sec = sec + 1
            }
          
        }
    }   
 
  }

  function superChargeReady() {
    console.log("charge is ready");
    playerChargeReady = 1
    charge.style.color="white"
  }
  function superChargeOn() {
    console.log("charge is on");
    playerCharge = 1
    playerSpeed = speed + speed
  }
  function superChargeOff() {
    console.log("charge is of");
    playerCharge = 0
    playerChargeReady = 1
    charge.style.color="black"
    playerSpeed = speed
  }
  
  
  // call followObject() function every 1000 milliseconds to move enemy
  setInterval(enemySpeedUpdate, 10000)
  setInterval(sizeEnemy, 60000)
  setTimeout(setInterval(followObject, 50), 1000)
  setInterval(superChargeReady, 60000)
  setInterval(addScore, 1000) // turns on score counter
    </script>
</body>
</html>


<script>
    
</script>