const products = [{
  id: 'PRO1',
  name: 'Part 1',
  image: '/images/device/img_03.png',
  image1: '/images/device/step_03.png',
},
{
  id: 'PRO2',
  name: 'Part 2',
  image: '/images/device/img_02.png',
  image1: '/images/device/step_02.png',
},
{
  id: 'PRO3',
  name: 'Part 3',
  image: '/images/device/img_01.png',
  image1: '/images/device/step_01.png',
},
{
  id: 'PRO4',
  name: ' Part 4',
  image: '/images/device/img_04.png',
  image1: '/images/device/step_04.png',
},
];


// options are optional ;)
MobileDragDrop.polyfill({
  forceApply: true,
  holdToDrag: 100,
  dragImageTranslateOverride: MobileDragDrop.scrollBehaviourDragImageTranslateOverride
});


///////
function dragStart(event, chosenClass) {
  event.dataTransfer.effectAllowed = 'move';
  event.dataTransfer.setData('text', event.target.id);
  event.target.classList.add("draggable--active");
}
function dragOver(event) {
  event.preventDefault();
  event.dataTransfer.effectAllowed = 'move';
  event.target.closest(".drop-zone").classList.add("drop-zone--active");
}
function dragLeave(event) {
  event.target.classList.remove("drop-zone--active");
}
function dragDrop(event) {
  event.target.closest(".drop-zone").append(document.getElementById(event.dataTransfer.getData('text')))
  document.getElementsByClassName("draggable--active")[0].classList.remove("draggable--active");

  if (document.getElementsByClassName("drop-zone--active")[0]) {
    document.getElementsByClassName("drop-zone--active")[0].classList.remove("drop-zone--active");
  }
  event.preventDefault();
}
function dragEnd(event) {
  if (document.getElementsByClassName("draggable--active")[0]) {
    document.getElementsByClassName("draggable--active")[0].classList.remove("draggable--active");
  }
}

// dragenter listener
function dragEnter(event) {
  event.preventDefault();
}

const productList = document.getElementById("productList");
const mainDropZone = document.getElementById("mainDropZone");
const hiddenSlots = document.getElementById("hiddenSlots");
const winMsg1 = document.getElementById("winMsg1");
let selectedProducts = [];
let selectedQuestions = [];
let currentQuestionIndex = 0;
let score = 0;
let scoreLevel = "";
////new timer
// let time = 0;
let interval = null;
const countdownElement = document.getElementById('countdown_text');
const clockFaceElement = document.getElementById('clock-face');
const needleElement = document.getElementById('needle');
let countdownTime = 2; //10

const stopTimer = document.getElementById('stopTimer');
const pauseOverlay = document.getElementById('pauseOverlay');
let remainingTime = countdownTime;
let pauseTime = 0;
let isStopped = false;

////
const correctOrder = ["PRO3", "PRO2", "PRO1", "PRO4"];
let currentIndex = 0;

function startCountdown(duration) {
  // Clear any existing interval
  clearInterval(interval);
  let startTime = Date.now() - (countdownTime - remainingTime) * 1000;
  interval = setInterval(() => {
    const elapsed = Math.floor((Date.now() - startTime) / 1000);
    remainingTime = duration - elapsed;

    if (remainingTime <= 0) {
      clearInterval(interval);
      remainingTime = 0;
      timeusUp();
    }

    updateDisplay(remainingTime, duration);
  }, 1000);
}

function updateDisplay(time, duration) {
  const seconds = time % 90;
  countdownElement.textContent = `${seconds < 10 ? '' : ''}${seconds}`;

  // Calculate the degree for the needle
  const degree = ((duration - time) / duration) * 360;
  needleElement.style.transform = `rotate(${degree}deg)`;

  // Calculate the percentage for the background fill
  const percentage = 100 - (time / duration) * 100;
  clockFaceElement.style.background = `conic-gradient(#0672cb ${percentage}%, #ffffff ${percentage}%)`;
}

// Pause/resume timer with toggle functionality
// stopTimer.addEventListener("click", e => {
//   e.preventDefault();

//   if (isStopped) {
//     // Resume the timer
//     console.log('resumed');
//     startCountdown(countdownTime);
//     stopTimer.querySelector('span').textContent = 'PAUSE';
//     isStopped = false;
//     document.querySelector('.pauseOverlay').style.display = 'none';

//   } else {
//     // Pause the timer
//     document.querySelector('.pauseOverlay').style.display = 'block';
//     console.log('paused');
//     clearInterval(interval);
//     stopTimer.querySelector('span').textContent = 'RESUME';
//     isStopped = true;
//   }
// });


// Pause/resume timer with toggle functionality
// pauseOverlay.addEventListener("click", e => {
//   e.preventDefault();
//   // Resume the timer
//   console.log('resumed');
//   startCountdown(countdownTime);
//   stopTimer.querySelector('span').textContent = 'PAUSE';
//   isStopped = false;
//   document.querySelector('.pauseOverlay').style.display = 'none';
// });

// Start the timer initially
startCountdown(countdownTime);
/////Start timer ends

/// Render draggable products
products.forEach(p => {

  const div = document.createElement("div");

  div.className = "product" + " " + p.id;
  div.dataset.id = p.id;

  const img = document.createElement("img");
  img.src = p.image;
  img.id = p.id;
  img.setAttribute("draggable", true);
  img.setAttribute("ondragstart", "dragStart(event)");
  img.setAttribute("ondragend", "dragEnd( event )");

  const name = document.createElement("span");
  name.textContent = p.name;
  div.appendChild(img);
  // div.appendChild(name);

  productList.appendChild(div);

  const slotDiv = document.createElement("div");
  slotDiv.className = "slot";
  slotDiv.dataset.slot = p.id;
  slotDiv.id = `slot-${p.id}`;

  hiddenSlots.appendChild(slotDiv);

  // Desktop drag
  div.addEventListener("dragstart", e => {
    e.dataTransfer.setData("text/plain", p.id);
  });
});


/////Mian Game Function
mainDropZone.addEventListener("drop", e => {
  e.preventDefault();
  const productId = e.dataTransfer.getData("text/plain");
  handleComponent(productId);
});


//// On click function
// const productItems = document.querySelectorAll(".product");
// productItems.forEach(product => {
//   product.addEventListener("click", e => {
//     e.preventDefault();
//     const productId = e.currentTarget.getAttribute("id");
//      alert(productId);
//      handleComponent(productId);
//   });
// });
//// On click function ends


function handleComponent(productId) {
  if (productId === correctOrder[currentIndex]) {
    currentIndex++;
    const slot = document.getElementById(`slot-${productId}`);
    if (slot) {
      slot.classList.add("visible");
      slot.classList.add(productId);

      const product = products.find(p => p.id === productId);
      const prodimg = document.createElement("img");
      prodimg.src = product.image1;
      prodimg.alt = product.name;

      slot.appendChild(prodimg);

      selectedProducts.push(productId);
      // if (selectedProducts.length === 1) startTimer();
      if (selectedProducts.length === 4) {
        ShowAfterWin();
      }
    }
  } else {
    //alert("Oops! That piece doesn't fit there - try another one!");
    //document.getElementById('mainDropZone').innerHTML = "";
    //return;


    // Remove the last dropped element if it was added visually
    const droppedImgs = document.querySelectorAll("#mainDropZone img");
    if (droppedImgs.length > 0) {
      const lastImg = droppedImgs[droppedImgs.length - 1];
      lastImg.parentNode.removeChild(lastImg);
    }

    // Remove the slot if it was added
    if (selectedProducts.includes(productId)) return;
    const product = products.find(p => p.id === productId);

    const img = document.createElement("img");
    img.src = product.image;
    img.id = product.id;
    img.setAttribute("draggable", true);
    img.setAttribute("ondragstart", "dragStart(event)");
    img.setAttribute("ondragend", "dragEnd( event )");

    const component = document.querySelector(`.${productId}`);
    component.appendChild(img);
    //   return false
  }
}

//// Show after win steps
function ShowAfterWin() {
  clearInterval(interval);
  const myModal = new bootstrap.Modal(document.getElementById("winModal"));
  myModal.show();
}

////End game
function endGame() {
  clearInterval(interval);
  document.getElementById("gameOverModal").style.display = "none";
  //document.getElementById("finalScore").innerText = `${score}/5`;
}

////Times us
function timeusUp() {
  document.getElementById("gameOverModal").style.display = "block";
  document.getElementById("gameOverModal").classList.add("show");
  document.getElementById("gameOverModal").setAttribute("aria-hidden", "false");

  const myModal = new bootstrap.Modal(document.getElementById("winModal"));
  myModal.show();

}
