const rollButton = document.getElementById("rollButton");
const demoCompleteButton = document.getElementById("demoCompleteButton");
const dieOne = document.getElementById("dieOne");
const dieTwo = document.getElementById("dieTwo");
const resultText = document.getElementById("resultText");
const completionOverlay = document.getElementById("completionOverlay");
const closeModal = document.getElementById("closeModal");
const liveChatButton = document.getElementById("liveChatButton");
const modalResult = document.getElementById("modalResult");

const prizeMap = {
  12: "FREE RM10",
  10: "FREE RM9",
  7: "FREE RM8",
};

function randomDie() {
  return Math.floor(Math.random() * 6) + 1;
}

function getPrize(total) {
  return prizeMap[total] || "Thank You Reward";
}

function showCompletion(resultLabel = "Lucky Reward") {
  modalResult.textContent = resultLabel;
  completionOverlay.classList.add("is-visible");
  completionOverlay.setAttribute("aria-hidden", "false");
  document.body.classList.add("modal-open");
  closeModal.focus();
}

function hideCompletion() {
  completionOverlay.classList.remove("is-visible");
  completionOverlay.setAttribute("aria-hidden", "true");
  document.body.classList.remove("modal-open");
  rollButton.focus();
}

async function rollDice() {
  rollButton.disabled = true;
  resultText.textContent = "Rolling...";
  dieOne.classList.add("is-rolling");
  dieTwo.classList.add("is-rolling");

  const animationTimer = window.setInterval(() => {
    dieOne.textContent = randomDie();
    dieTwo.textContent = randomDie();
  }, 90);

  await new Promise((resolve) => window.setTimeout(resolve, 1200));
  window.clearInterval(animationTimer);

  const first = randomDie();
  const second = randomDie();
  const total = first + second;
  const prize = getPrize(total);

  dieOne.textContent = first;
  dieTwo.textContent = second;
  dieOne.classList.remove("is-rolling");
  dieTwo.classList.remove("is-rolling");
  resultText.textContent = `${first} + ${second} = ${total} — ${prize}`;
  rollButton.disabled = false;

  window.setTimeout(() => showCompletion(prize), 550);
}

rollButton.addEventListener("click", rollDice);
demoCompleteButton.addEventListener("click", () => showCompletion("FREE RM10"));
closeModal.addEventListener("click", hideCompletion);
liveChatButton.addEventListener("click", () => window.livechat());

completionOverlay.addEventListener("click", (event) => {
  if (event.target === completionOverlay) hideCompletion();
});

document.addEventListener("keydown", (event) => {
  if (event.key === "Escape" && completionOverlay.classList.contains("is-visible")) {
    hideCompletion();
  }
});
