document.addEventListener('DOMContentLoaded', () => {
  const grid = document.querySelector('.grid')
  const flagsLeft = document.querySelector('#flags-left')
  const result = document.querySelector('#result')
  // dod mainīgos
  let width = 8
  let bombAmount = 10
  let flags = 0
  let squares = []
  let isGameOver = false
  let isGameStart = false


// timer




var mins =0;
var seconds =0;

$('#start').click(function(){
      startTimer();
});

$('#stop').click(function(){
      clearTimeout(timex);
});


function startTimer(){
  timex = setTimeout(function(){
      seconds++;
    if(seconds >59){seconds=0;mins++;
     
                       
    if(mins<10){                     
      $("#mins").text('0'+mins+':');}       
       else $("#mins").text(mins+':');
                   }    
    if(seconds <10) {
      $("#seconds").text('0'+seconds);} else {
      $("#seconds").text(seconds);
      }
     
    
      startTimer();
  },1000);
}
// }

  //generee lauku
  function createBoard() {
    flagsLeft.innerHTML = bombAmount

    //masiva pievieno bumbas pec nejausibas principa (nestrada)
    const bombsArray = Array(bombAmount).fill('bomb')
    const emptyArray = Array(width*width - bombAmount).fill('valid')
    const gameArray = emptyArray.concat(bombsArray)
    const shuffledArray = gameArray.sort(() => Math.random() -0.5)
//popule blokus
    for(let i = 0; i < width*width; i++) {
      const square = document.createElement('div')
      square.setAttribute('id', i)
      square.classList.add(shuffledArray[i])
      grid.appendChild(square)
      squares.push(square)

      // kreisais klikskis
      square.addEventListener('click', function(e) {
        if(!isGameStart){
          startTimer()
          isGameStart = true;
        }
        click(square)
      })

      // labais klikskis
      square.oncontextmenu = function(e) {
        e.preventDefault()
        addFlag(square)
      }
    }

    //generee ciparus, cik bumbas ir blakus
    for (let i = 0; i < squares.length; i++) {
      let total = 0
      const isLeftEdge = (i % width === 0)
      const isRightEdge = (i % width === width -1)

      //aizliedz sturiem skaitit bumbas no otras puses
      if (squares[i].classList.contains('valid')) {
        if (i > 0 && !isLeftEdge && squares[i -1].classList.contains('bomb')) total ++
        if (i > 7 && !isRightEdge && squares[i +1 -width].classList.contains('bomb')) total ++
        if (i > 8 && squares[i -width].classList.contains('bomb')) total ++
        if (i > 9 && !isLeftEdge && squares[i -1 -width].classList.contains('bomb')) total ++
        
        if (i < 63 && !isRightEdge && squares[i +1].classList.contains('bomb')) total ++
        
        if (i < 56 && !isLeftEdge && squares[i -1 +width].classList.contains('bomb')) total ++
        if (i < 54 && !isRightEdge && squares[i +1 +width].classList.contains('bomb')) total ++
        if (i < 55 && squares[i +width].classList.contains('bomb')) total ++
        squares[i].setAttribute('data', total)
      }
    }
  }
  createBoard()

  //pievieno karodzinu ar labo klikski
  function addFlag(square) {
    if (isGameOver) return
    if (!square.classList.contains('checked') && (flags < bombAmount)) {
      if (!square.classList.contains('flag')) {
        square.classList.add('flag')
        square.innerHTML = ' 🚩'
        flags ++
        flagsLeft.innerHTML = bombAmount- flags
        checkForWin()
       } else {
        square.classList.remove('flag')
        square.innerHTML = ''
        flags --
        flagsLeft.innerHTML = bombAmount- flags
      }
     }
  }

  //klikska iespejamas sekas
  function click(square) {
    let currentId = square.id
    if (isGameOver) return
    if (square.classList.contains('checked') || square.classList.contains('flag')) return
    if (square.classList.contains('bomb')) {
      gameOver(square)
    } else {
      let total = square.getAttribute('data')
      if (total !=0) {
        square.classList.add('checked')
        if (total == 1) square.classList.add('one')
        if (total == 2) square.classList.add('two')
        if (total == 3) square.classList.add('three')
        if (total == 4) square.classList.add('four')
        if (total == 5) square.classList.add('five')
        if (total == 6) square.classList.add('six')
        if (total == 7) square.classList.add('seven')
        if (total == 8) square.classList.add('eight')
        square.innerHTML = total
        return
      }
      checkSquare(square, currentId)
    }
    square.classList.add('checked')
  }

  //parbauda blakus blokus kad kads bloks tiek nospiests
  function checkSquare(square, currentId) {
    const isLeftEdge = (currentId % width === 0)
    const isRightEdge = (currentId % width === width -1)

    setTimeout(() => {
      if (currentId > 0 && !isLeftEdge) {
        const newId = squares[parseInt(currentId) -1].id
        //const newId = parseInt(currentId) - 1   ....refactor
        const newSquare = document.getElementById(newId)
        click(newSquare)
      }
      if (currentId > 7 && !isRightEdge) {
        const newId = squares[parseInt(currentId) +1 -width].id
        //const newId = parseInt(currentId) +1 -width   ....refactor
        const newSquare = document.getElementById(newId)
        click(newSquare)
      }
      if (currentId > 8) {
        const newId = squares[parseInt(currentId -width)].id
        //const newId = parseInt(currentId) -width   ....refactor
        const newSquare = document.getElementById(newId)
        click(newSquare)
      }
      if (currentId > 9 && !isLeftEdge) {
        const newId = squares[parseInt(currentId) -1 -width].id
        //const newId = parseInt(currentId) -1 -width   ....refactor
        const newSquare = document.getElementById(newId)
        click(newSquare)
      }


      if (currentId < 63 && !isRightEdge) {
        const newId = squares[parseInt(currentId) +1].id
        //const newId = parseInt(currentId) +1   ....refactor
        const newSquare = document.getElementById(newId)
        click(newSquare)
      }


      if (currentId < 56 && !isLeftEdge) {
        const newId = squares[parseInt(currentId) -1 +width].id
        //const newId = parseInt(currentId) -1 +width   ....refactor
        const newSquare = document.getElementById(newId)
        click(newSquare)
      }
      if (currentId < 54 && !isRightEdge) {
        const newId = squares[parseInt(currentId) +1 +width].id
        //const newId = parseInt(currentId) +1 +width   ....refactor
        const newSquare = document.getElementById(newId)
        click(newSquare)
      }
      if (currentId < 55) {
        const newId = squares[parseInt(currentId) +width].id
        //const newId = parseInt(currentId) +width   ....refactor
        const newSquare = document.getElementById(newId)
        click(newSquare)
      }
    }, 10)
  }

  //game over
  function gameOver(square) {
    result.innerHTML = 'BOOM! Game Over!'
    isGameOver = true
    clearTimeout(timex)
   

    //parada visas bumbas kad game over
    squares.forEach(square => {
      if (square.classList.contains('bomb')) {
        square.innerHTML = '💣'
        square.classList.remove('bomb')
        square.classList.add('checked')
      }
    })
  }

  //parbauda vai ir uzvarets
  function checkForWin() {
    let matches = 0;

    for (let i = 0; i < squares.length; i++) {
      if (squares[i].classList.contains('flag') && squares[i].classList.contains('bomb')) {
        matches++;
      }
    
      if (matches === bombAmount) {
        result.innerHTML = 'YOU WIN!';
        isGameOver = true;
        clearTimeout(timex);
    
 // Extract and parse the time values
 const minsText = document.getElementById('mins').textContent;
 const secondsText = document.getElementById('seconds').textContent;

 // Parse the time values into integers
 const mins = parseInt(minsText);
 const seconds = parseInt(secondsText);

 // Proceed with updating the time and performing the database update
 const newTime = mins * 60 + seconds; // Convert time to seconds for easier comparison


 $.ajax({
  url: 'update_time.php', // Replace with your server-side script or API endpoint
  method: 'POST',
  data: { time: newTime },
  success: function (response) {
    // Handle the response if needed
    console.log('Time updated successfully');
  },
  error: function (xhr, status, error) {
    // Handle the error if the update fails
    console.error('Failed to update time:', error);
  }
});


      }
    }
  }
})