const dino = document.querySelector('.dino');
const contador = document.querySelector('.contador');
const background = document.querySelector('.background');

let score = 0;
let position = 0;
let isJumping = false;
let isGameOver = false;

function handleKeyUp(event) {
  if (event.keyCode === 32) {
    if (!isJumping) {
      jump();
    }

    if (isGameOver) {
      document.location.reload(true);
    }
  }
}

function jump() {
  isJumping = true;

  let upInterval = setInterval(() => {
    if (position >= 150) {
      // DESCENDO
      clearInterval(upInterval);

      let downInterval = setInterval(() => {
        if (position <= 0) {
          clearInterval(downInterval);
          isJumping = false;
        } else {
          position -= 30;
          dino.style.bottom = position + 'px';
        }
      }, 20);
    } else {
      // SUBINDO
      position += 30;
      dino.style.bottom = position + 'px';
    }
  }, 20);
}

function createCactus() {
  const cactus = document.createElement('div');
  let cactusPosition = 2000;
  let randomTime = Math.random() * 6000;

  if (isGameOver) return;

  cactus.classList.add('cactus');
  background.appendChild(cactus);
  cactus.style.left = cactusPosition + 'px';

  let leftTimer = setInterval(() => {
    if (cactusPosition < -60) {
      // SAIU DA TELA
      clearInterval(leftTimer);
      background.removeChild(cactus);
      score += 50;
      contador.innerHTML = 'Score: ' + score;
    } else if (cactusPosition > 0 && cactusPosition < 60 && position < 60) {
      // GAME OVER
      clearInterval(leftTimer);
      isGameOver = true;
      document.body.innerHTML = '<h1 class="game-over">Game Over...<br /><br />Tecle espaco para continuar...</h1>';
    } else {
      cactusPosition -= 15;
      cactus.style.left = cactusPosition + 'px';
    }
  }, 20);

  setTimeout(createCactus, randomTime);
}

if(isGameOver == false) createCactus();
document.addEventListener('keyup', handleKeyUp);
