(function ($){
    $(document).ready(() => {
        $( 'body' ).on( 'updated_checkout', () => {
            let $checked = $('form[name="checkout"] input[name="payment_method"]:checked');
            if($checked.length > 0) {
                displayNotification($checked.val());
            }
        });
    });

    function displayNotification(paymentMethod) {
        if(paymentMethod === 'acceptblue-cc'){
            appendNotification('card', 'form[name="checkout"] div.acceptblue-card-wrap');
        }
        if(paymentMethod === 'acceptblue-ach'){
            appendNotification('check', 'form[name="checkout"] div.acceptblue-ach-wrap');
        }
        if(paymentMethod === 'acceptblue-google-pay'){
            appendNotification('google_pay', 'form[name="checkout"] div.acceptblue-google-pay-wrap');
        }
    }

    let n = false;
    function appendNotification(type, wrapperSelector) {
        let wrap =  $(wrapperSelector);
        if(wrap) {
            if(n !== false) {
                n.remove();
                n = false;
            }
            n = notification(type);
            wrap.append(n.get());
        }
    }

    function notification(type){
        let notification = '<div></div>';
        let $n = false;
        if(pgabfwSurcharge.success === '1') {
            let val = pgabfwSurcharge[type] ?? '';
            notification = `<div style="margin-top: 5px;" ><b>${val}</b></div>`;
        }
        $n = $($.trim(notification));
        return {
            get(){
                return $n;
            },
            remove(){
                if($n) {
                    $n.remove();
                    $n = false;
                }
            }
        }
    }

    function addGutenbergNotificationToSavedPaymentMethod(selected){
        let value = selected.value;
        if(typeof pgabfwSurcharge.tokens === "object" && pgabfwSurcharge.tokens.hasOwnProperty(value)) {
            let label = selected
                .closest('.wc-block-components-radio-control__option')
                .querySelector('.wc-block-components-radio-control__label');

            appendNotification(pgabfwSurcharge.tokens[value], label);
        }
    }

    window.addEventListener('DOMContentLoaded', () => {
        setTimeout(() => {
            let selected = document.querySelector('div[data-block-name="woocommerce/checkout"] #payment-method .wc-block-components-radio-control__input:checked');

            if(selected) {
                addGutenbergNotificationToSavedPaymentMethod(selected)
            }

            $('div[data-block-name="woocommerce/checkout"] #payment-method .wc-block-components-radio-control').on('change', '.wc-block-components-radio-control__input', function(e) {
                if(n !== false) {  n.remove(); n = false; }
                addGutenbergNotificationToSavedPaymentMethod(this);
            });
        }, 200);
    });
})(jQuery);
