function toggleSelect(id) {
  const element = document.getElementById(id);
  if (element) {
    element.classList.toggle("hidden");
  }
}

function selectItem(targetId, value, dropdownId) {
  const target = document.getElementById(targetId);
  if (target) {
    target.innerText = value;
    target.classList.replace("text-[#626262]", "text-[#BDBDBD]");
  }
  const dropdown = document.getElementById(dropdownId);
  if (dropdown) {
    dropdown.classList.add("hidden");
  }
}

function selectAndNavigate(name, icon) {
  localStorage.setItem("selectedCardName", name);
  localStorage.setItem("selectedCardIcon", icon);
  localStorage.setItem("paymentStatus", "success");
  window.location.href = "./card.html";
}

document.addEventListener("DOMContentLoaded", function () {
  const payBtn = document.getElementById("payBtn");
  const paymentForm = document.getElementById("paymentForm");
  const selectedText = document.getElementById("selectedPayment");
  const selectedIcon = selectedText ? selectedText.previousElementSibling : null;

  const nameInput = document.getElementById("name");
  const phoneInput = document.getElementById("phone");

  const savedName = localStorage.getItem("selectedCardName");
  const savedIcon = localStorage.getItem("selectedCardIcon");

  if (savedName && selectedText && selectedIcon) {
    selectedText.innerText = savedName;
    selectedText.classList.replace("text-[#BDBDBD]", "text-white");
    selectedIcon.src = savedIcon;
  }

  function updateButtonState() {
    if (!payBtn || !nameInput || !phoneInput) return;

    if (nameInput.value.trim() !== "" && phoneInput.value.trim() !== "") {
      payBtn.innerText = "Confirm & Pay";
      payBtn.style.backgroundColor = "#B092FF"; 
    } else {
      payBtn.innerText = "Pay";
      payBtn.style.backgroundColor = "";
    }
  }

  if (nameInput) nameInput.addEventListener("input", updateButtonState);
  if (phoneInput) phoneInput.addEventListener("input", updateButtonState);

  if (paymentForm) {
    paymentForm.addEventListener("submit", function (e) {
      e.preventDefault();

      let isValid = true;
      const fields = ["name", "phone"];

      fields.forEach((id) => {
        const input = document.getElementById(id);
        const error = input ? input.nextElementSibling : null;

        if (input && input.value.trim() === "") {
          input.style.borderColor = "#ef4444";
          if (error) error.classList.remove("hidden");
          isValid = false;
        } else if (input) {
          input.style.borderColor = "transparent";
          if (error) error.classList.add("hidden");
        }
      });

      if (isValid) {
        localStorage.removeItem("paymentStatus");
        localStorage.removeItem("selectedCardName");
        localStorage.removeItem("selectedCardIcon");
        window.location.href = "./passcode.html";
      }
    });
  }
  
  updateButtonState();
});