/* ===== RANDOM ANSWER ===== */
const answer = Array.from({ length: 5 }, () => Math.floor(Math.random() * 10));
const hidden = answer.join("");
let attempts = 6;

console.log("Answer:", hidden);

/* ===== ROW INPUTS ===== */
const rows = [];

for (let r = 1; r <= 6; r++) {
  const row = [];
  for (let c = 1; c <= 5; c++) {
    row.push(document.getElementById(`input${r}_${c}`));
  }
  rows.push(row);
}

/* ===== ENABLE FIRST ROW ===== */
rows[0].forEach(input => input.disabled = false);

/* ===== AUTO MOVE & BACKSPACE ===== */
rows.forEach(row => {
  row.forEach((input, idx) => {

    input.addEventListener("input", function () {
      this.value = this.value.replace(/[^0-9]/g, "").slice(0, 1);

      if (this.value !== "" && idx < row.length - 1) {
        row[idx + 1].focus();
      }
    });

    input.addEventListener("keydown", function (e) {
      if (e.key === "Backspace" && this.value === "" && idx > 0) {
        row[idx - 1].focus();
      }
    });

  });
});

/* ===== ENABLE / DISABLE ROW ===== */
function enableRow(rowNum) {
  rows[rowNum - 1].forEach(x => x.disabled = false);
}

function disableRow(rowNum) {
  rows[rowNum - 1].forEach(x => x.disabled = true);
}

/* ===== SUBMIT FUNCTION (FIXED) ===== */
document.getElementById("submit").addEventListener("click", function () {

  const currentRow = rows.length - attempts; // ✅ correct row tracking
  const row = rows[currentRow];

  // 🚫 Prevent empty submission
  const guessVals = row.map(i => i.value);
  if (guessVals.some(v => v === "")) {
    alert("Fill in all boxes before submitting.");
    return;
  }

  const guess = guessVals.map(Number);

  // 🎨 COLOR LOGIC
  guess.forEach((val, idx) => {
    if (val === answer[idx]) {
      row[idx].style.backgroundColor = "green";
    } else if (val > answer[idx]) {
      row[idx].style.backgroundColor = "red";
    } else {
      row[idx].style.backgroundColor = "blue";
    }
  });

  disableRow(currentRow + 1); // convert to 1-based

  // ✅ WIN CHECK
  if (guess.every((v, i) => v === answer[i])) {
    alert("You Win!");
    return;
  }

  attempts--; // ✅ move BEFORE enabling next row

  // ✅ ENABLE NEXT ROW PROPERLY
  if (attempts > 0) {
    const nextRow = currentRow + 1;
    enableRow(nextRow + 1); // 1-based function
    rows[nextRow][0].focus();
  } else {
    alert("Game Over!\nAnswer was: " + hidden);
  }
});

/* ===== TUTORIAL MENU ===== */
const tutorialLink = document.querySelector(".nav-links a");
const tutorialMenu = document.getElementById("tutorialMenu");
const closeTutorial = document.getElementById("closeTutorial");

// Show aside when ? clicked
tutorialLink.addEventListener("click", e => {
  e.preventDefault();
  tutorialMenu.classList.add("active");
});

// Hide aside
closeTutorial.addEventListener("click", () => {
  tutorialMenu.classList.remove("active");
});