jQuery(function($){
    $('#wawp-save-prefs').on('click',function(){
        const btn  = $(this);
        const msg  = $('#wawp-prefs-msg').removeClass('wawp-ok wawp-err');
        btn.prop('disabled',true);   msg.text(wawpPrefs.i18n.saving);

        if (wawpPrefs.rest_url) {
            fetch(wawpPrefs.rest_url + '/toggle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': wawpPrefs.nonce
                },
                body: JSON.stringify({
                    login: $('#wawp-login-pref').is(':checked'),
                    wc: $('#wawp-wc-pref').is(':checked')
                })
            })
            .then(res => res.json())
            .then(res => {
                msg.addClass(res.success ? 'wawp-ok' : 'wawp-err')
                   .text(res.success ? wawpPrefs.i18n.saved : (res.message || wawpPrefs.i18n.error));
            })
            .catch(() => {
                msg.addClass('wawp-err').text(wawpPrefs.i18n.error);
            })
            .finally(() => btn.prop('disabled', false));
        } else {
            // Fallback to AJAX if rest_url is not defined yet
            $.post(wawpPrefs.ajax,{
                action : 'wawp_toggle_prefs',
                nonce  : wawpPrefs.nonce,
                login  : $('#wawp-login-pref').is(':checked'),
                wc     : $('#wawp-wc-pref').is(':checked')
            }).done(res=>{
                msg.addClass(res.success ? 'wawp-ok':'wawp-err')
                   .text( res.success ? wawpPrefs.i18n.saved : wawpPrefs.i18n.error );
            }).fail(()=>{
                msg.addClass('wawp-err').text(wawpPrefs.i18n.error);
            }).always(()=>btn.prop('disabled',false));
        }
    });
});
