
// 图片懒加载模块
class LazyLoadManager {
    constructor() {
        this.observer = null;
        this.init();
    }

    init() {
        // 检查浏览器是否支持IntersectionObserver
        if ('IntersectionObserver' in window) {
            this.observer = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        this.loadImage(img);
                        observer.unobserve(img);
                    }
                });
            }, {
                rootMargin: '50px 0px', // 提前50px开始加载
                threshold: 0.1
            });
            console.log('懒加载管理器初始化成功');
        } else {
            console.warn('浏览器不支持IntersectionObserver，将使用传统懒加载方式');
            this.initFallback();
        }
    }

    // 加载图片
    loadImage(img) {
        const src = img.dataset.src;
        if (!src) return;

        // 创建临时图片对象预加载
        const tempImg = new Image();
        tempImg.onload = () => {
            img.src = src;
            img.classList.add('loaded');
            img.classList.remove('loading');
            console.log('图片加载成功:', src);
        };
        tempImg.onerror = () => {
            img.classList.add('error');
            img.classList.remove('loading');
            console.error('图片加载失败:', src);
        };
        tempImg.src = src;
    }

    // 观察需要懒加载的图片
    observe(img) {
        if (this.observer) {
            this.observer.observe(img);
        }
    }

    // 传统懒加载方式（不支持IntersectionObserver的浏览器）
    initFallback() {
        let lazyloadThrottleTimeout;

        const lazyload = () => {
            if (lazyloadThrottleTimeout) {
                clearTimeout(lazyloadThrottleTimeout);
            }

            lazyloadThrottleTimeout = setTimeout(() => {
                const lazyImages = document.querySelectorAll('img.lazy-load');
                lazyImages.forEach(img => {
                    if (this.isInViewport(img)) {
                        this.loadImage(img);
                        img.classList.remove('lazy-load');
                    }
                });

                if (lazyImages.length === 0) { 
                    document.removeEventListener('scroll', lazyload);
                    window.removeEventListener('resize', lazyload);
                    window.removeEventListener('orientationChange', lazyload);
                }
            }, 20);
        };

        document.addEventListener('scroll', lazyload);
        window.addEventListener('resize', lazyload);
        window.addEventListener('orientationchange', lazyload);
    }

    // 检查元素是否在视口中
    isInViewport(element) {
        const rect = element.getBoundingClientRect();
        return (
            rect.bottom >= 0 &&
            rect.right >= 0 &&
            rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.left <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }
}

// 创建全局懒加载管理器实例
const lazyLoadManager = new LazyLoadManager();

// 导出懒加载管理器
if (typeof module !== 'undefined' && module.exports) {
    module.exports = LazyLoadManager;
}
