/**
 * Stripe Subscription Manager — Analytics Dashboard Sync Button
 *
 * Handles the "Sync with Stripe" button click, POSTs to admin-ajax.php,
 * and updates status text with localized i18n strings from strp_sub_sync_params.
 */
(function(){
    var btn       = document.getElementById('strp-sync-stripe-btn');
    var status    = document.getElementById('strp-sync-status');
    var statusTxt = document.getElementById('strp-sync-status-text');
    var nonce     = document.getElementById('strp_sub_sync_stripe_nonce');

    if ( ! btn || ! nonce ) return;

    btn.addEventListener('click', function(){
        if ( btn.disabled ) return;
        btn.disabled = true;
        status.style.display = 'inline-block';
        statusTxt.textContent = strp_sub_sync_params.i18n.syncing;

        var data = new FormData();
        data.append('action', 'strp_sub_sync_stripe');
        data.append('nonce', nonce.value);

        fetch(ajaxurl, { method: 'POST', body: data, credentials: 'same-origin' })
            .then(function(r){ return r.json(); })
            .then(function(resp){
                if ( resp.success ) {
                    statusTxt.textContent = resp.data.updated + ' / ' + resp.data.checked + ' ' + strp_sub_sync_params.i18n.updated;
                } else {
                    statusTxt.textContent = strp_sub_sync_params.i18n.error + ': ' + ( resp.data || strp_sub_sync_params.i18n.unknownError );
                }
            })
            .catch(function(){
                statusTxt.textContent = strp_sub_sync_params.i18n.requestFailed;
            })
            .finally(function(){
                btn.disabled = false;
                setTimeout(function(){ status.style.display = 'none'; }, 8000);
            });
    });
})();
