const SWEET_ALERT_CDN = "https://cdn.jsdelivr.net/npm/sweetalert2@11";

const state = {
  viewState: "selection",
  selectedCard: "visa1",
  loading: false
};

let selectionStateEl;
let scanStateEl;
let confirmBtnEl;
let addCardBtnEl;
let cancelBtnEl;
let manualEntryBtnEl;

let swalLoaderPromise = null;

function loadSweetAlertIfNeeded() {
  if (window.Swal) return Promise.resolve(true);
  if (swalLoaderPromise) return swalLoaderPromise;

  swalLoaderPromise = new Promise((resolve) => {
    const script = document.createElement("script");
    script.src = SWEET_ALERT_CDN;
    script.async = true;
    script.onload = () => resolve(true);
    script.onerror = () => resolve(false);
    document.head.appendChild(script);
  });

  return swalLoaderPromise;
}

async function showModal({ icon, title, text, width = "335px" }) {
  const hasSwal = await loadSweetAlertIfNeeded();
  if (hasSwal && window.Swal) {
    return window.Swal.fire({
      icon,
      title,
      text,
      width,
      confirmButtonText: "OK",
      confirmButtonColor: "#7B48FF",
      background: "#121212",
      color: "#EEF2F6"
    });
  }

  alert(`${title}: ${text}`);
  return Promise.resolve();
}

function setViewState(nextState) {
  state.viewState = nextState;

  if (nextState === "scan") {
    selectionStateEl.classList.add("hidden-state");
    scanStateEl.classList.remove("hidden-state");
  } else {
    scanStateEl.classList.add("hidden-state");
    selectionStateEl.classList.remove("hidden-state");
  }
}

function syncSelectedCard() {
  const checkedInput = document.querySelector('input[name="payment_method"]:checked');
  state.selectedCard = checkedInput?.value || "visa1";
}

function setLoading(isLoading) {
  state.loading = isLoading;
  if (!confirmBtnEl) return;

  confirmBtnEl.disabled = isLoading;
  confirmBtnEl.textContent = isLoading ? "Processing..." : "Confirm";
  if (isLoading) {
    confirmBtnEl.classList.add("opacity-70", "cursor-not-allowed");
  } else {
    confirmBtnEl.classList.remove("opacity-70", "cursor-not-allowed");
  }
}

async function handleConfirmAddCard() {
  try {
    setLoading(true);

    const cardData = {
      cardType: state.selectedCard === "visa1" ? "Visa" : "MasterCard",
      isDefault: true
    };

    console.log("Card payload:", cardData);

    await new Promise((resolve) => setTimeout(resolve, 2000));

    await showModal({
      icon: "success",
      title: "Card Added",
      text: `${cardData.cardType} card has been added successfully.`,
      width: "400px"
    });

    window.location.href = "./profile.html";
  } catch (error) {
    console.error("API Error:", error);
    await showModal({
      icon: "error",
      title: "Error",
      text: "Something went wrong!",
      width: "335px"
    });
  } finally {
    setLoading(false);
  }
}

function handleBack() {
  if (state.viewState === "scan") {
    setViewState("selection");
  } else {
    history.back();
  }
}

function initAddNewCardPage() {
  selectionStateEl = document.getElementById("selection-state");
  scanStateEl = document.getElementById("scan-state");
  confirmBtnEl = document.getElementById("confirmBtn");
  addCardBtnEl = document.getElementById("addCardBtn");
  cancelBtnEl = document.getElementById("cancelBtn");
  manualEntryBtnEl = document.getElementById("manualEntryBtn");

  const cardInputs = document.querySelectorAll('input[name="payment_method"]');
  cardInputs.forEach((input) => {
    input.addEventListener("change", syncSelectedCard);
  });

  addCardBtnEl?.addEventListener("click", () => setViewState("scan"));
  cancelBtnEl?.addEventListener("click", () => setViewState("selection"));
  confirmBtnEl?.addEventListener("click", handleConfirmAddCard);
  manualEntryBtnEl?.addEventListener("click", async () => {
    await showModal({
      icon: "info",
      title: "Manual Entry",
      text: "Manual card entry will be available soon.",
      width: "400px"
    });
  });

  syncSelectedCard();
  setViewState("selection");
}

window.handleBack = handleBack;

document.addEventListener("DOMContentLoaded", initAddNewCardPage);
