;(function ($) {
    'use strict';

    // Function to handle AJAX request
    function handleStoreCreditAction(action, nonce) {
        $.ajax({
            type: 'POST',
            url: unlockafe_ajax.ajax_url,
            data: {
                action: action,
                nonce: nonce
            },
            success: function (response) {
                if (response.success) {
                    // Refresh the cart or checkout page to show the changes
                    $(document.body).trigger('update_checkout');
                    $(document.body).trigger('wc_update_cart');
                } else {
                    // You might want to show an error message here
                    console.error('Store credit action failed:', response.data.message);
                }
            },
            error: function (error) {
                console.error('AJAX error:', error);
            }
        });
    }

    // Apply Store Credit
    $(document).on('click', '.unlockafe-apply-store-credit', function (e) {
        e.preventDefault();
        var nonce = $(this).data('nonce');
        handleStoreCreditAction('unlockafe_apply_store_credit', nonce);
    });

    // Remove Store Credit
    $(document).on('click', '.unlockafe-remove-store-credit', function (e) {
        e.preventDefault();
        var nonce = $(this).data('nonce');
        if (nonce) {
            handleStoreCreditAction('unlockafe_remove_store_credit', nonce);
        } else {
            console.error('Could not find nonce for remove action.');
        }
    });
});
