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

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

        if (current_payment_method === 'woosa_adyen_apple_pay') {
            jQuery('.wfacp-order-place-btn-wrap').hide()
        }
    });

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

        if (current_payment_method === 'woosa_adyen_apple_pay') {
            jQuery('.wfacp-order-place-btn-wrap').hide()
        }
    });

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

            if (current_payment_method === 'woosa_adyen_apple_pay') {
                jQuery('.wfacp-order-place-btn-wrap').hide()
            }
        });

    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="checked"]').val()

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

            if (data.isValid) {
                jQuery('.wfacp-order-place-btn-wrap').show()
                jQuery('.woosa_adyen_google_pay_button').hide()

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

        return origAdyenCheckout(config);
    };
});