document.addEventListener("DOMContentLoaded", function () {
  const paymentForm = document.getElementById("paymentForm");
  const cardNum = document.getElementById("cardNum");
  const cardName = document.getElementById("cardName");
  const cvv = document.getElementById("cvv");
  const expiryInput = document.getElementById("expiry");
  const expiryError = document.getElementById("expiryError");
  const cardError = document.getElementById("cardError");

  // Expiry Date Auto-slash (MM/YY)
  expiryInput.addEventListener("input", function (e) {
    let value = e.target.value.replace(/\D/g, "");
    if (value.length > 2) {
      value = value.slice(0, 2) + "/" + value.slice(2, 4);
    }
    e.target.value = value;
  });

  function validateExpiry(expiryStr) {
    if (expiryStr.length !== 5) return false;
    const parts = expiryStr.split("/");
    const month = parseInt(parts[0], 10);
    const year = parseInt(parts[1], 10);

    if (isNaN(month) || isNaN(year) || month < 1 || month > 12) return false;

    const now = new Date();
    const currentYear = parseInt(now.getFullYear().toString().slice(-2), 10);
    const currentMonth = now.getMonth() + 1;

    if (year < currentYear || (year === currentYear && month < currentMonth)) {
      return false;
    }
    return true;
  }

  // বাটন ক্লিকের বদলে ফর্ম সাবমিট হ্যান্ডেল করা সবচেয়ে ভালো
  paymentForm.addEventListener("submit", function (e) {
    e.preventDefault(); // পেজ রিফ্রেশ বন্ধ করবে

    let isValid = true;

    // Card Number Validation
    if (cardNum.value.length !== 16 || isNaN(cardNum.value)) {
      cardNum.classList.add("!ring-1", "!ring-red-500");
      cardError.classList.remove("hidden");
      isValid = false;
    } else {
      cardNum.classList.remove("!ring-1", "!ring-red-500");
      cardError.classList.add("hidden");
    }

    // Name Validation
    if (cardName.value.trim().length < 3) {
      cardName.classList.add("!ring-1", "!ring-red-500");
      isValid = false;
    } else {
      cardName.classList.remove("!ring-1", "!ring-red-500");
    }

    // CVV Validation
    if (cvv.value.length !== 3 || isNaN(cvv.value)) {
      cvv.classList.add("!ring-1", "!ring-red-500");
      isValid = false;
    } else {
      cvv.classList.remove("!ring-1", "!ring-red-500");
    }

    // Expiry Validation
    if (!validateExpiry(expiryInput.value)) {
      expiryInput.classList.add("!ring-1", "!ring-red-500");
      expiryError.classList.remove("hidden");
      isValid = false;
    } else {
      expiryInput.classList.remove("!ring-1", "!ring-red-500");
      expiryError.classList.add("hidden");
    }

    if (isValid) {
      localStorage.setItem("paymentStatus", "success");
      // সাকসেস হলে রিডাইরেক্ট
      window.location.href = "./secure-payment.html";
    }
  });
});
