
(function ($) {
    'use strict';
    document.addEventListener('DOMContentLoaded', function () {
        $('.hide_cart_widget_if_empty').closest('.widget_shopping_cart').hide();
        let timesCalled = 0;
        let finalize    = 0;
        const form       = document.getElementById('tdsMmethodForm');
        const acsElement = document.getElementById("showAcs");
        const loaders = document.getElementsByClassName('primer-loading-banner');
        const loader  = loaders && loaders.length > 0 ? loaders[0] : null;
        if (!form && acsElement && acsElement.src !== null) {
            acsElement.style.display = "flex";
            acsElement.addEventListener('load', function () {
                if (acsElement.contentDocument) {
                    console.log("start looking for cres pers from start");
                    console.log(acsElement.contentDocument);
                    acsElement.style.display = "none";
                    makeAjaxRequestForFinal();
                    loader.style.display = "block";
                }
            });
        }
        function extractOrderIdFromURL() {
            const url     = window.location.href;
            const matches = url.match(/\/order-pay\/(\d+)\//);
            if (matches && matches.length > 1) {
                return matches[1];
            }
            return null;
        }
        if (form) {
            function makeAjaxRequest() {
                const order_id = extractOrderIdFromURL();
                if (order_id) {
                    jQuery.ajax({
                        type   : "post",
                        url    : primer_3ds_ajax_obj.ajaxurl,
                        data   : {action: "continue_3ds_method", order_id: order_id, timesCalled: timesCalled},
                        success: function (response) {
                            console.log(response)
                            if (response.type === "success") {
                                console.log("Success! Stopping the loop.");
                                if (response.action === "do_transaction") {
                                    console.log("Success! Proceed Transaction.");
                                    jQuery.ajax({
                                        type   : "post",
                                        url    : primer_3ds_ajax_obj.ajaxurl,
                                        data   : {
                                            action               : "process_payment_with_token_3ds",
                                            order_id             : order_id,
                                            transaction_form_data: response.data
                                        },
                                        success: function (response_second) {
                                            console.log(response_second)
                                            if (response_second.type === "redirect") {
                                                console.log("redirecting")
                                                window.location.href = response_second.redirect;
                                            } else {
                                                window.history.back();
                                            }
                                        },
                                        error  : function (error) {
                                            console.log(error);
                                        },
                                    });
                                }
                            } else if (response.type === "showAcs") {
                                if (modal) {
                                    const acsElement         = document.getElementById("showAcs");
                                    acsElement.src           = 'data:text/html;charset=utf-8,' + encodeURIComponent(response.acsData);
                                    acsElement.style.display = "flex";
                                    acsElement.addEventListener('load', function () {
                                        if (acsElement.contentDocument) {
                                            console.log("start looking for cres pers");
                                            console.log(acsElement.contentDocument);
                                            acsElement.style.display = "none";
                                            makeAjaxRequestForFinal();
                                        }
                                    });
                                } else {
                                    window.history.back();
                                }
                            } else if (response.type === "redirect") {
                                console.log("redirecting")
                                window.location.href = response.redirect;
                            } else {
                                console.log("relooping")
                                timesCalled++;
                                setTimeout(makeAjaxRequest, 700);
                            }
                        },
                        error  : function (error) {
                            setTimeout(makeAjaxRequest, 700);
                        },
                    });
                } else {
                    console.log("no order");
                }
            }
            const startTime = Date.now();
            const duration  = 10 * 1000;
            function startAjaxLoop() {
                const currentTime = Date.now();
                if (currentTime - startTime < duration) {
                    makeAjaxRequest();
                } else {
                    console.log("Loop completed after 10 seconds.");
                }
            }
            startAjaxLoop();
        }

        function makeAjaxRequestForFinal() {
            const order_id = extractOrderIdFromURL();
            if (order_id && finalize === 0) {
                finalize = 1;
                jQuery.ajax({
                    type   : "post",
                    url    : primer_3ds_ajax_obj.ajaxurl,
                    data   : {action: "finalize_3ds_method", order_id: order_id},
                    success: function (response) {
                        console.log(response)
                        if (response.type === "success") {
                            console.log("Success! Stopping the loop.");
                            if (response.action === "do_transaction") {
                                console.log("Success! Proceed Transaction.");
                                jQuery.ajax({
                                    type   : "post",
                                    url    : primer_3ds_ajax_obj.ajaxurl,
                                    data   : {
                                        action               : "process_payment_with_token_3ds",
                                        order_id             : order_id,
                                        transaction_form_data: response.data
                                    },
                                    success: function (response_second) {
                                        console.log(response_second)
                                        if (response_second.type === "redirect") {
                                            console.log("redirecting")
                                            window.location.href = response_second.redirect;
                                        } else {
                                            window.history.back();
                                        }
                                    },
                                    error  : function (error) {
                                        console.log(error);
                                    },
                                });
                            }
                        } else if (response.type === "redirect") {
                            console.log("redirecting final")
                            window.location.href = response.redirect;
                        } else {
                            console.log("relooping final")
                            finalize = 0;
                            setTimeout(makeAjaxRequestForFinal, 700);
                        }
                    },
                    error  : function (error) {
                        finalize = 0;
                        setTimeout(makeAjaxRequestForFinal, 700);
                    },
                });
            } else {
                console.log("no order");
            }
        }

        // Installments
        const targetId    = 'wc-piraeusbank_gateway-payment-token-new';
        let preservedNode = $('#' + targetId).closest('li');
        if (!preservedNode.length) {
            return;
        }
        const observer = new MutationObserver(function (mutations) {
            if (document.getElementById(targetId)) {
                return;
            }
            let wasRemoved = false;
            mutations.forEach(function (mutation) {
                if (mutation.removedNodes) {
                    for (let i = 0; i < mutation.removedNodes.length; i++) {
                        const node = mutation.removedNodes[i];
                        if (node.nodeType === 1) {
                            if (
                                node.id === targetId ||
                                node.contains(preservedNode[0]) ||
                                $(node).find('#' + targetId).length > 0
                            ) {
                                wasRemoved = true;
                            }
                        }
                    }
                }
            });
            if (wasRemoved) {
                const container = $('ul.wc-saved-payment-methods');
                if (container.length && !document.getElementById(targetId)) {
                    container.prepend(preservedNode);
                    console.log('Restored Piraeus payment method.');
                }
            }
        });
        observer.observe(document.body, {
            childList: true,
            subtree  : true
        });

        const newPaymentRadio = $('#wc-piraeusbank_gateway-payment-token-new');
        if (newPaymentRadio.length) {
            newPaymentRadio.prop('checked', true).trigger('change');
        }

        $(document).on('change', 'input[name="wc-piraeusbank_gateway-payment-token"]', function() {
            if ($(this).val() === 'installments' && $(this).is(':checked')) {
                $('.installments-bin-field').slideDown();
                $('p#primer-bin-field').not('.installments-bin-field p').hide();
            } else {
                $('.installments-bin-field').slideUp();
            }
        });

        function checkInitialState() {
            if ($('input[name="wc-piraeusbank_gateway-payment-token"]:checked').val() === 'installments') {
                $('.installments-bin-field').show();
            } else {
                $('.installments-bin-field').hide();
            }
        }
        checkInitialState();

        $(document).on('updated_checkout', function() {
            checkInitialState();
        });
        $(document).on('click', '#primer-validate-bin', function (e) {
            e.preventDefault();
            var button   = $(this);
            var binInput = button.siblings('input[name="primer_bin"]');
            validateBin(binInput, button);
        });
        $(document).on('keypress', 'input[name="primer_bin"]', function (e) {
            if (e.which === 13) {
                e.preventDefault();
                var button = $(this).siblings('#primer-validate-bin');
                validateBin(this, button);
            }
        });

        function validateBin(binInput, button) {
            var message    = binInput.closest('.installments-bin-field').find('.primer-bin-message');
            var validInput = binInput.siblings('input[name="primer_bin_valid"]');
            var bin        = binInput.val().trim();
            if (bin.length !== 8 || !/^\d+$/.test(bin)) {
                message.removeClass('success').addClass('error').text(primer_vars.i18n.invalid_bin);
                validInput.val('0');
                removeInstallmentsDropdown();
                return;
            }
            var orderTotal = $('input[name="payment_method"]:checked').closest('.payment_box').find('input[name="order_total"]').val() ||
                $('input[name="order_total"]').val() ||
                $('.order-total .amount').text().replace(/[^0-9.,]/g, '').replace(',', '.');
            orderTotal     = parseFloat(orderTotal);
            if (isNaN(orderTotal) || orderTotal <= 0) {
                message.removeClass('success').addClass('error').text(primer_vars.i18n.invalid_amount);
                validInput.val('0');
                removeInstallmentsDropdown();
                return;
            }
            button.prop('disabled', true).addClass('loading');
            message.removeClass('error success').text(primer_vars.i18n.validating);
            $.ajax({
                url     : primer_vars.ajax_url,
                type    : 'POST',
                data    : {
                    action     : 'primer_validate_bin',
                    ajax_nonce : primer_vars.nonce,
                    bin        : bin,
                    order_total: orderTotal
                },
                dataType: 'json',
                success : function (response) {
                    if (response.success) {
                        message.removeClass('error').addClass('success').text(response.data.message);
                        validInput.val('1');
                        if (response.data.installments > 1) {
                            updateInstallmentsDropdown(response.data.installments);
                        }
                    } else {
                        message.removeClass('success').addClass('error').text(response.data.message);
                        validInput.val('0');
                        removeInstallmentsDropdown();
                    }
                },
                error   : function (xhr, status, error) {
                    console.error('BIN validation error:', error);
                    message.removeClass('success').addClass('error').text(primer_vars.i18n.validation_error);
                    validInput.val('0');
                    removeInstallmentsDropdown();
                },
                complete: function () {
                    button.prop('disabled', false).removeClass('loading');
                }
            });
        }

        function removeInstallmentsDropdown() {
            var installmentsSelect = $('select[name="primer_installments"]');
            if (installmentsSelect.length > 0) {
                installmentsSelect.closest('p').remove();
            }
        }

        function updateInstallmentsDropdown(maxInstallments) {
            var installmentsSelect = $('select[name="primer_installments"]');
            if (installmentsSelect.length === 0) {
                installmentsSelect = $('<select id="primer_max_installments" name="primer_installments" class="input-select"></select>');
                $('.installments-bin-field').append('<p class="form-row installment-wrapper"><label>' + primer_vars.i18n.installments + '</label></p>');
                $('.installments-bin-field').find('p:last').append(installmentsSelect);
            } else {
                installmentsSelect.empty();
                installmentsSelect.show();
                installmentsSelect.closest('p').show();
            }
            for (var i = 1; i <= maxInstallments; i++) {
                var optionText = i === 1
                    ? primer_vars.i18n.single_payment
                    : i + ' ' + primer_vars.i18n.installments_suffix;
                installmentsSelect.append($('<option>', {
                    value: i,
                    text: optionText,
                    selected: (i === maxInstallments)
                }));
            }
            installmentsSelect.trigger('change');
        }

        if ($('input[name="primer_bin_nonce"]').length === 0) {
            $('form.checkout, form#order_review').append('<input type="hidden" name="primer_bin_nonce" value="' + primer_vars.nonce + '">');
        }
    });
})(jQuery);