jQuery(document).ready(function () {
    if (!window.AdyenCheckout) {
        console.warn("AdyenCheckout ещё не загружен");
        return;
    }

    const calculateButtonState = (payment_method, show = false) => {
        const mainBtn = jQuery('.wfacp-order-place-btn-wrap');
        const orderPayBtn = jQuery('button#place_order');

        const mainGooglePayBtn = jQuery('.woosa_adyen_google_pay_button');
        const orderPayGooglePayBtn = jQuery('#woosa_adyen_google_pay_button');

        if (payment_method === 'woosa_adyen_google_pay' && !show) {
            mainBtn && mainBtn.hide()
            orderPayBtn && orderPayBtn.hide()
        } else {
            mainBtn && mainBtn.show()
            orderPayBtn && orderPayBtn.show()

            show && mainGooglePayBtn.hide()
            show && orderPayGooglePayBtn.hide()
        }
    }

    jQuery( 'form.checkout' ).on( 'change', 'input[name="payment_method"]', function() {
        const current_payment_method = jQuery( this ).val();

        calculateButtonState(current_payment_method)
    });

    jQuery( 'form#order_review' ).on( 'change', 'input[name="payment_method"]', function() {
        const current_payment_method = jQuery( this ).val();

        calculateButtonState(current_payment_method)
    });

    jQuery('body')
        .on('updated_checkout', function () {
            const current_payment_method = jQuery('input[name="payment_method"]:checked').val()

            calculateButtonState(current_payment_method)
        });

    const origAdyenCheckout = window.AdyenCheckout;

    window.AdyenCheckout = function (config) {
        const orig = config.onChange;

        config.onChange = (data, component) => {
            orig(data, component);

            const current_payment_method = jQuery('input[name="payment_method"]:checked').val()

            console.log('current_payment_method onChange', current_payment_method, data.isValid);

            if (current_payment_method !== 'woosa_adyen_google_pay') return;

            if (data.isValid) {
                calculateButtonState(current_payment_method, data.isValid)
                jQuery('.woosa_adyen_google_pay_button').hide()

                setTimeout(() => {
                    jQuery('button[name="woocommerce_checkout_place_order"]').trigger('click');
                })
            }
        }

        return origAdyenCheckout(config);
    };
});