/**
 * HuSNS - 工具函数模块
 * 提供通用辅助函数
 */

var HuSNS = window.HuSNS || {};

/**
 * 格式化时间
 * @param {number|string} timestamp - 时间戳
 * @returns {string} 格式化后的时间字符串
 */
HuSNS.formatTime = function(timestamp) {
    var date = new Date(parseInt(timestamp) * 1000);
    var now = new Date();
    var diff = now.getTime() - date.getTime();
    
    var minute = 60 * 1000;
    var hour = minute * 60;
    var day = hour * 24;
    var week = day * 7;
    var month = day * 30;
    
    if (diff < minute) {
        return '刚刚';
    } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前';
    } else if (diff < week) {
        return Math.floor(diff / day) + '天前';
    } else if (diff < month) {
        return Math.floor(diff / week) + '周前';
    } else {
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
    }
};

/**
 * 压缩图片
 * @param {File} file - 图片文件
 * @returns {Promise<File>} 压缩后的图片文件
 */
HuSNS.compressImage = function(file) {
    return new Promise(function(resolve) {
        var img = new Image();
        img.onload = function() {
            try {
                var MAX_WIDTH = 800;
                var MAX_HEIGHT = 800;
                
                var width = img.width;
                var height = img.height;
                
                if (width > MAX_WIDTH) {
                    height = (height * MAX_WIDTH) / width;
                    width = MAX_WIDTH;
                }
                if (height > MAX_HEIGHT) {
                    width = (width * MAX_HEIGHT) / height;
                    height = MAX_HEIGHT;
                }
                
                var quality = 0.7;
                var originalSizeKB = file.size / 1024;
                
                if (originalSizeKB > 2048) {
                    quality = 0.45;
                } else if (originalSizeKB > 1024) {
                    quality = 0.5;
                } else if (originalSizeKB > 512) {
                    quality = 0.55;
                }
                
                var canvas = document.createElement('canvas');
                canvas.width = Math.round(width);
                canvas.height = Math.round(height);
                
                var ctx = canvas.getContext('2d');
                if (!ctx) {
                    resolve(file);
                    return;
                }
                
                ctx.imageSmoothingEnabled = true;
                ctx.imageSmoothingQuality = 'high';
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                
                canvas.toBlob(function(blob) {
                    if (blob) {
                        var compressedFile = new File([blob], file.name.replace(/\.[^.]+$/, '.jpg'), {
                            type: 'image/jpeg',
                            lastModified: Date.now()
                        });
                        resolve(compressedFile);
                    } else {
                        resolve(file);
                    }
                }, 'image/jpeg', quality);
            } catch (error) {
                resolve(file);
            }
        };
        
        img.onerror = function() {
            resolve(file);
        };
        
        img.src = URL.createObjectURL(file);
    });
};

/**
 * 压缩视频
 * @param {File} file - 视频文件
 * @returns {Promise<File>} 压缩后的视频文件
 */
HuSNS.compressVideo = function(file) {
    return new Promise(function(resolve) {
        // 如果文件小于5MB，不压缩直接返回
        if (file.size < 5 * 1024 * 1024) {
            resolve(file);
            return;
        }
        
        var video = document.createElement('video');
        video.src = URL.createObjectURL(file);
        video.autoplay = false;
        video.muted = true;
        video.playsInline = true;
        
        video.onloadedmetadata = function() {
            try {
                var width = video.videoWidth;
                var height = video.videoHeight;
                
                // 限制视频分辨率
                var MAX_WIDTH = 1280;
                var MAX_HEIGHT = 720;
                
                if (width > MAX_WIDTH) {
                    height = (height * MAX_WIDTH) / width;
                    width = MAX_WIDTH;
                }
                if (height > MAX_HEIGHT) {
                    width = (width * MAX_HEIGHT) / height;
                    height = MAX_HEIGHT;
                }
                
                width = Math.round(width / 2) * 2;
                height = Math.round(height / 2) * 2;
                
                var canvas = document.createElement('canvas');
                canvas.width = width;
                canvas.height = height;
                var ctx = canvas.getContext('2d');
                
                var stream = canvas.captureStream(30);
                var mimeType = 'video/mp4';
                
                var mediaRecorder = new MediaRecorder(stream, {
                    mimeType: mimeType,
                    videoBitsPerSecond: 1000000
                });
                
                var chunks = [];
                mediaRecorder.ondataavailable = function(e) {
                    if (e.data.size > 0) {
                        chunks.push(e.data);
                    }
                };
                
                mediaRecorder.onstop = function() {
                    var blob = new Blob(chunks, { type: mimeType });
                    var compressedFile = new File([blob], file.name.replace(/\.[^.]+$/, '.mp4'), {
                        type: mimeType,
                        lastModified: Date.now()
                    });
                    resolve(compressedFile);
                };
                
                mediaRecorder.start();
                
                var currentTime = 0;
                var duration = video.duration;
                var frameInterval = 1000 / 30;
                
                var drawFrame = function() {
                    if (currentTime >= duration || mediaRecorder.state === 'inactive') {
                        mediaRecorder.stop();
                        return;
                    }
                    
                    video.currentTime = currentTime;
                    video.onseeked = function() {
                        ctx.drawImage(video, 0, 0, width, height);
                        currentTime += frameInterval / 1000;
                        setTimeout(drawFrame, frameInterval);
                    };
                };
                
                drawFrame();
                
            } catch (error) {
                console.error('视频压缩失败:', error);
                resolve(file);
            }
        };
        
        video.onerror = function() {
            resolve(file);
        };
    });
};

/**
 * URL处理函数
 * @param {string} path - 路径
 * @returns {string} 完整URL
 */
HuSNS.url = function(path) {
    if (path.startsWith('http')) return path;
    if (path.startsWith('?')) return path;
    var cleanPath = path.replace('?', '&');
    var baseUrl = window.API_BASE_URL || '';
    return baseUrl + '/?r=' + cleanPath;
};

/**
 * HTML转义函数
 * @param {string} str - 待转义字符串
 * @returns {string} 转义后的字符串
 */
HuSNS.escape = function(str) {
    return str ? str.replace(/[<>"'&]/g, function(c) {
        return {'<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;",'&':'&amp;'}[c];
    }) : '';
};

/**
 * 字符串截断
 * @param {string} str - 原字符串
 * @param {number} start - 起始位置
 * @param {number} len - 截取长度
 * @returns {string} 截断后的字符串
 */
HuSNS.substr = function(str, start, len) {
    return str ? str.substring(start, start + len) : '';
};

/**
 * 去除HTML标签
 * @param {string} str - 含HTML的字符串
 * @returns {string} 纯文本
 */
HuSNS.strip_tags = function(str) {
    return str ? str.replace(/<[^>]*>/g, '') : '';
};

/**
 * Toast提示
 * @param {string} message - 提示内容
 * @param {number} duration - 显示时长(ms)
 */
HuSNS.showToast = function(message, duration) {
    duration = duration || 2000;
    var existingToast = document.querySelector('.husns-toast');
    if (existingToast) {
        existingToast.remove();
    }
    
    var toast = document.createElement('div');
    toast.className = 'husns-toast';
    toast.style.cssText = [
        'position:fixed',
        'top:50%',
        'left:50%',
        'transform:translate(-50%,-50%)',
        'background:rgba(0,0,0,0.75)',
        'color:#fff',
        'padding:12px 24px',
        'border-radius:8px',
        'font-size:14px',
        'z-index:10000',
        'max-width:80%',
        'text-align:center'
    ].join(';');
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s';
        setTimeout(function() { toast.remove(); }, 300);
    }, duration);
};

/**
 * 震动反馈（移动端）
 * @param {number} duration - 震动时长(ms)
 */
HuSNS.vibrate = function(duration) {
    duration = duration || 10;
    if (navigator.vibrate) {
        navigator.vibrate(duration);
    }
};

/**
 * 获取默认头像URL
 * @returns {string} 默认头像路径
 */
HuSNS.getDefaultAvatar = function() {
    var themeUrl = window.THEME_URL || '';
    return themeUrl + '/images/avatar_default.png';
};

/**
 * 生成用户头像颜色
 * @param {string} name - 用户名
 * @returns {Object} {bg, text} 颜色配置
 */
HuSNS.getAvatarColor = function(name) {
    var colors = [
        {bg: '#667eea', text: '#ffffff'},
        {bg: '#764ba2', text: '#ffffff'},
        {bg: '#f093fb', text: '#ffffff'},
        {bg: '#f5576c', text: '#ffffff'},
        {bg: '#4facfe', text: '#ffffff'},
        {bg: '#00f2fe', text: '#ffffff'},
        {bg: '#43e97b', text: '#ffffff'},
        {bg: '#38f9d7', text: '#ffffff'},
        {bg: '#fa709a', text: '#ffffff'},
        {bg: '#fee140', text: '#333333'},
        {bg: '#30cfd0', text: '#ffffff'},
        {bg: '#a8edea', text: '#333333'},
        {bg: '#ff9a9e', text: '#ffffff'},
        {bg: '#ffecd2', text: '#333333'},
        {bg: '#a1c4fd', text: '#ffffff'},
        {bg: '#c2e9fb', text: '#333333'}
    ];
    var hash = 0;
    for (var i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    return colors[Math.abs(hash) % colors.length];
};

/**
 * 检查是否登录
 * @returns {boolean}
 */
HuSNS.isLoggedIn = function() {
    return !!document.body.dataset.userId;
};

/**
 * 图片懒加载模块
 */
HuSNS.LazyLoad = (function() {
    var observer = null;
    
    /**
     * 初始化懒加载
     */
    function init() {
        if ('IntersectionObserver' in window) {
            observer = new IntersectionObserver(handleIntersection, {
                rootMargin: '50px',
                threshold: 0.01
            });
            
            observeImages();
        } else {
            // 降级方案：使用 scroll 事件
            fallbackLoad();
        }
    }
    
    /**
     * 观察所有懒加载图片
     */
    function observeImages() {
        var lazyImages = document.querySelectorAll('img[data-src]');
        lazyImages.forEach(function(img) {
            observer.observe(img);
        });
    }
    
    /**
     * 交集回调处理
     */
    function handleIntersection(entries) {
        entries.forEach(function(entry) {
            if (entry.isIntersecting) {
                var img = entry.target;
                loadImage(img);
                observer.unobserve(img);
            }
        });
    }
    
    /**
     * 加载图片
     */
    function loadImage(img) {
        var src = img.getAttribute('data-src');
        var srcset = img.getAttribute('data-srcset');
        
        if (src) {
            img.onload = function() {
                img.removeAttribute('data-src');
                img.removeAttribute('data-srcset');
                img.classList.add('lazy-loaded');
            };
            
            img.onerror = function() {
                // 加载失败时显示占位图
                img.src = HuSNS.getDefaultAvatar();
                img.removeAttribute('data-src');
                img.removeAttribute('data-srcset');
            };
            
            if (srcset) {
                img.srcset = srcset;
            }
            img.src = src;
        }
    }
    
    /**
     * 降级方案：滚动加载
     */
    function fallbackLoad() {
        var lazyImages = document.querySelectorAll('img[data-src]');
        
        function checkImages() {
            lazyImages.forEach(function(img) {
                if (isInViewport(img)) {
                    loadImage(img);
                }
            });
            // 更新未加载的图片列表
            lazyImages = document.querySelectorAll('img[data-src]');
            if (lazyImages.length === 0) {
                window.removeEventListener('scroll', checkImages);
            }
        }
        
        function isInViewport(el) {
            var rect = el.getBoundingClientRect();
            return (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
                rect.right <= (window.innerWidth || document.documentElement.clientWidth)
            );
        }
        
        window.addEventListener('scroll', checkImages, { passive: true });
        // 初始检查
        checkImages();
    }
    
    /**
     * 重新观察新增的图片
     */
    function refresh() {
        if (observer) {
            observeImages();
        } else {
            fallbackLoad();
        }
    }
    
    return {
        init: init,
        refresh: refresh
    };
})();

// 全局暴露
window.HuSNS = HuSNS;

// 全局快捷函数，兼容现有代码
window.showToast = function(message, duration) {
    HuSNS.showToast(message, duration);
};

window.formatTime = function(timestamp) {
    return HuSNS.formatTime(timestamp);
};

// DOM加载完成后初始化懒加载
document.addEventListener('DOMContentLoaded', function() {
    HuSNS.LazyLoad.init();
});