(function($){
    // SAFETY: Check if vmo_ajax is defined
    if (typeof vmo_ajax === 'undefined') {
        console.warn('vmo_ajax not defined - balance functions will not work');
        return;
    }
    
    // Balance logic
    window.updateTokenBalance = function(callback) {
        $.post(vmo_ajax.ajaxurl, {
            action: 'vmo_get_token_balance',
            security: vmo_ajax.nonce
        }, function (res) {
            if (res.success && typeof res.data.balance !== 'undefined') {
                // Use new display format if available (percentage + days remaining)
                const $el = $('#vmo-token-balance');
                if ($el.length) {
                    if (res.data.display) {
                        $el.text(res.data.display);
                    } else {
                        $el.text(res.data.balance);
                    }
                }
                if (typeof callback === 'function') callback(res.data.balance);
            } else {
                if (typeof callback === 'function') callback(0);
            }
        });
    };

    window.checkTokenBalanceAndNotify = function(requiredTokens = 1200, callback) {
        window.updateTokenBalance(function (balance) {
            if (balance < requiredTokens) {
                window.showToast("Not enough balance. Please upgrade or add an add-on.", 'error');
                $('#vmo-send-btn').prop('disabled', true);
                callback(false);
            } else {
                $('#vmo-send-btn').prop('disabled', false);
                callback(true);
            }
        });
    };
})(jQuery);