var HuSNS = window.HuSNS || {};
HuSNS.Logger = {
    _isProduction: window.NODE_ENV === 'production',
    _logLevel: window.LOG_LEVEL || 'info',
    
    _levels: {
        debug: 0,
        info: 1,
        warn: 2,
        error: 3
    },
    
    debug: function() {
        if (this._shouldLog('debug')) {
            console.debug.apply(console, arguments);
        }
    },
    
    info: function() {
        if (this._shouldLog('info')) {
            console.info.apply(console, arguments);
        }
    },
    
    warn: function() {
        if (this._shouldLog('warn')) {
            console.warn.apply(console, arguments);
        }
    },
    
    error: function(msg, err) {
        if (this._shouldLog('error')) {
            console.error(msg, err);
        }
        this._report(msg, err);
    },
    
    _shouldLog: function(level) {
        if (this._isProduction && level === 'debug') {
            return false;
        }
        return this._levels[level] >= this._levels[this._logLevel];
    },
    
    _report: function(msg, err) {
        if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
            try {
                var data = {
                    message: msg,
                    error: err ? err.stack || err.message : null,
                    url: window.location.href,
                    timestamp: Date.now()
                };
                navigator.sendBeacon('/api/log/report', JSON.stringify(data));
            } catch (e) {
                // 上报失败不影响主流程
            }
        }
    }
};

if (typeof module !== 'undefined' && module.exports) {
    module.exports = HuSNS.Logger;
}