

export class Installments {
    constructor() {
        if (!document.querySelector(".wc_payment_method .payment_method_wc-koin-credit"))
            return;

        this.setEvents();
        this.handleCardTypeChange();
    }

    setEvents() {
        jQuery(document.body).on('updated_checkout', () => {
            const selectedPaymentMethod = document.querySelector('input[name="payment_method"]:checked');
            if (selectedPaymentMethod && selectedPaymentMethod.value === 'wc-koin-credit') {
                this.handleCardTypeChange();
                this.getCardInstallments();
            }
        });
        document.addEventListener('wk-koin-brand-changed', () => {
            this.getCardInstallments();
        });

        const cardTypeSelect = document.querySelector("#wko-card-type");
        if (cardTypeSelect) {
            cardTypeSelect.addEventListener('change', () => {
                this.handleCardTypeChange();
            });
        }
    }

    handleCardTypeChange() {
        const cardType = document.querySelector("#wko-card-type");
        const installmentsContainer = document.querySelector(".wko-card-installments");

        if (!cardType || !installmentsContainer) return;

        const installmentsSelect = document.querySelector("#wko-card-installments");

        if (cardType.value === 'debit') {
            installmentsContainer.classList.add('wko-hidden');

            if (installmentsSelect) {
                installmentsSelect.innerHTML = "";

                const option1 = document.createElement('option');
                option1.value = '1';
                option1.text = '1x';
                option1.selected = true;
                installmentsSelect.appendChild(option1);
            }
        } else {
            installmentsContainer.classList.remove('wko-hidden');

            this.getCardInstallments().then(() => {
                if (installmentsSelect && installmentsSelect.options.length > 0) {
                    installmentsSelect.selectedIndex = 0;
                }
            });
        }
    }


    getCardInstallments() {
        const brand = document.querySelector("#wko-card-brand");
        const number = document.querySelector("#wko-card-number")
        const nonce = document.querySelector("#wko-card-nonce");
        const total = document.querySelector("#wko-cart-total");

        this.resetInstallmentsError();

        this.setRequestLoader();

        return fetch(
            koinParams.installmentsUrl,
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    'X-WP-Nonce': nonce.value
                },
                body: JSON.stringify({
                    brand: brand.value,
                    number: number.value.replace(/\s/g, '').substring(0, 8), // Send only the first 8 numbers without spaces
                    total: total.value,
                    _wpnonce: nonce.value,
                }),
            },
        )
            .then((response) => response.json())
            .then((data) => {
                if (data.success === true) {
                    const installments = data.data;
                    const select = document.querySelector("#wko-card-installments");
                    select.innerHTML = "";

                    for (const key in installments) {
                        const option = document.createElement("option");
                        option.value = key;
                        option.innerText = installments[key];

                        select.appendChild(option);
                    }

                    return;
                }

                throw Error(data.message);
            })
            .catch((error) => {
                const errorList = document.querySelector("#wko-installments-error");
                if (errorList && errorList.innerHTML === "") {
                    const span = document.createElement("span");

                    span.innerText = error.message;
                    errorList.appendChild(span);
                    errorList.classList.add("active");
                }
            })
            .finally(() => {
                jQuery(".koin-checkout-fields").removeClass("processing").unblock();
            });
    }

    setRequestLoader() {
        jQuery(".koin-checkout-fields")
            .addClass("processing")
            .block({
                message: null,
                overlayCSS: {
                    background: "#fff",
                    opacity: 0.6,
                },
            });
    }

    resetInstallmentsError() {
        const errorList = document.querySelector("#wko-installments-error");
        errorList.innerText = "";
        errorList.classList.remove("active");
    }

}
