let timer;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');

function startTimer(seconds){

    clearInterval(timer); // clears the current timer function

    const now = Date.now();
    const then = now + seconds * 1000; // calculates the time when the timer should stop

    displayTimeLeft(seconds); // displays the time left
    displayEndTime(then); // displays the time when the timer should stop

    timer = setInterval(() => {
        const secondsLeft = Math.round((then - Date.now()) / 1000); // calculates the time left in seconds
        if(secondsLeft < 0) { // if the time left is less than 0 stop the timer
          clearInterval(timer);
          return;
        }
        displayTimeLeft(secondsLeft); // displays the time left
      }, 1000); // repeats the function every second
}

function displayTimeLeft(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainderSeconds = seconds % 60;
    const display = `${minutes}:${remainderSeconds < 10 ? '0' : '' }${remainderSeconds}`;
    document.title = display;
    timerDisplay.textContent = display;
  }
  
  function displayEndTime(timestamp) {
    const end = new Date(timestamp);
    const hour = end.getHours();
    const adjustedHour = hour > 12 ? hour - 12 : hour;
    const minutes = end.getMinutes();
    endTime.textContent = `Be Back At ${adjustedHour}:${minutes < 10 ? '0' : ''}${minutes}`;
  }


function Timer() {
    const seconds = parseInt(this.dataset.time);
    startTimer(seconds);
}
  
buttons.forEach(button => button.addEventListener('click', Timer));

document.customForm.addEventListener('submit', function(e) {
    e.preventDefault();
    const mins = this.minutes.value;
    console.log(mins);
    startTimer(mins * 60);
    this.reset();
  });