/**
 * 图片查看器 - 支持左右滑动、放大缩小、拖动、点击关闭
 */

(function() {
    'use strict';

    let imageViewerImages = [];
    let imageViewerCurrentIndex = 0;
    let imageViewerScale = 1;
    let imageViewerTranslateX = 0;
    let imageViewerTranslateY = 0;
    let touchStartX = 0;
    let touchStartY = 0;
    let lastTouchX = 0;
    let lastTouchY = 0;
    let initialDistance = 0;
    let initialScale = 1;
    let isDragging = false;
    let isZoomed = false;

    // 打开图片查看器
    function openImageViewer(images, startIndex = 0) {
        imageViewerImages = images;
        imageViewerCurrentIndex = startIndex;
        imageViewerScale = 1;
        imageViewerTranslateX = 0;
        imageViewerTranslateY = 0;
        isDragging = false;
        isZoomed = false;

        const overlay = document.createElement('div');
        overlay.className = 'image-viewer-overlay';
        overlay.innerHTML = getViewerHTML(images, startIndex);

        document.body.appendChild(overlay);
        document.body.style.overflow = 'hidden';

        // 动画显示
        requestAnimationFrame(() => {
            overlay.classList.add('show');
        });

        // 绑定事件
        bindViewerEvents(overlay, images);

        // ESC键关闭
        document.addEventListener('keydown', handleViewerKeydown);
    }

    // 生成查看器HTML
    function getViewerHTML(images, startIndex) {
        const hasMultiple = images.length > 1;
        let slidesHtml = images.map((src, i) => `
            <div class="image-viewer-slide">
                <img class="image-viewer-image" 
                     src="${src}" 
                     alt="" 
                     data-index="${i}"
                     draggable="false" />
            </div>
        `).join('');

        return `
            <div class="image-viewer-container">
                <button class="image-viewer-close" onclick="window.closeImageViewer()">
                    <svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
                </button>
                
                <div class="image-viewer-swiper" style="transform: translateX(${-startIndex * 100}%)">
                    ${slidesHtml}
                </div>
                
                ${hasMultiple ? `
                <button class="image-viewer-nav image-viewer-prev" onclick="window.prevImage()">
                    <svg viewBox="0 0 24 24"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
                </button>
                <button class="image-viewer-nav image-viewer-next" onclick="window.nextImage()">
                    <svg viewBox="0 0 24 24"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>
                </button>
                <div class="image-viewer-indicator">${startIndex + 1}/${images.length}</div>
                ` : ''}
                
                <div class="image-viewer-zoom-controls">
                    <button class="zoom-btn" onclick="window.zoomOut()">
                        <svg viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/></svg>
                    </button>
                    <button class="zoom-btn" onclick="window.zoomIn()">
                        <svg viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>
                    </button>
                </div>
            </div>
        `;
    }

    // 绑定事件
    function bindViewerEvents(overlay, images) {
        const swiper = overlay.querySelector('.image-viewer-swiper');
        const slides = overlay.querySelectorAll('.image-viewer-slide');
        const indicator = overlay.querySelector('.image-viewer-indicator');
        const prevBtn = overlay.querySelector('.image-viewer-prev');
        const nextBtn = overlay.querySelector('.image-viewer-next');

        // 点击关闭按钮
        const closeBtn = overlay.querySelector('.image-viewer-close');
        closeBtn.addEventListener('click', closeImageViewer);

        // 点击背景关闭
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) {
                closeImageViewer();
            }
        });

        // 点击图片关闭（所有情况）
        overlay.addEventListener('click', function(e) {
            const img = e.target.closest('.image-viewer-image');
            if (img && !isDragging && !isZoomed) {
                e.stopPropagation();
                closeImageViewer();
            }
        });

        // 双击缩放
        let lastClickTime = 0;
        overlay.addEventListener('click', function(e) {
            const img = e.target.closest('.image-viewer-image');
            if (img) {
                e.stopPropagation();
                const now = Date.now();
                if (now - lastClickTime < 300) {
                    // 双击
                    if (imageViewerScale > 1) {
                        imageViewerScale = 1;
                        imageViewerTranslateX = 0;
                        imageViewerTranslateY = 0;
                        isZoomed = false;
                    } else {
                        imageViewerScale = 2;
                        isZoomed = true;
                    }
                    updateImageTransform();
                }
                lastClickTime = now;
            }
        });

        // 触摸开始
        overlay.addEventListener('touchstart', (e) => {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
            lastTouchX = touchStartX;
            lastTouchY = touchStartY;
            isDragging = false;

            // 双指缩放
            if (e.touches.length === 2) {
                initialDistance = getDistance(e.touches[0], e.touches[1]);
                initialScale = imageViewerScale;
            }
        }, { passive: true });

        // 触摸移动
        overlay.addEventListener('touchmove', (e) => {
            if (e.touches.length === 2) {
                // 双指缩放
                e.preventDefault();
                const distance = getDistance(e.touches[0], e.touches[1]);
                const delta = distance / initialDistance;
                imageViewerScale = Math.max(1, Math.min(5, initialScale * delta));
                isZoomed = imageViewerScale > 1;
                updateImageTransform();
            } else if (e.touches.length === 1 && imageViewerScale > 1) {
                // 单指拖动（只有放大后才能拖动）
                e.preventDefault();
                isDragging = true;
                
                const currentX = e.touches[0].clientX;
                const currentY = e.touches[0].clientY;
                
                const deltaX = currentX - lastTouchX;
                const deltaY = currentY - lastTouchY;
                
                imageViewerTranslateX += deltaX;
                imageViewerTranslateY += deltaY;
                
                // 限制拖动范围
                const img = slides[imageViewerCurrentIndex].querySelector('.image-viewer-image');
                if (img) {
                    const imgRect = img.getBoundingClientRect();
                    const maxTranslateX = Math.max(0, (imgRect.width * imageViewerScale - window.innerWidth) / 2);
                    const maxTranslateY = Math.max(0, (imgRect.height * imageViewerScale - window.innerHeight) / 2);
                    
                    imageViewerTranslateX = Math.max(-maxTranslateX, Math.min(maxTranslateX, imageViewerTranslateX));
                    imageViewerTranslateY = Math.max(-maxTranslateY, Math.min(maxTranslateY, imageViewerTranslateY));
                }
                
                updateImageTransform();
                
                lastTouchX = currentX;
                lastTouchY = currentY;
            } else if (e.touches.length === 1 && imageViewerScale <= 1) {
                // 单指滑动切换图片（未放大时）
                const currentX = e.touches[0].clientX;
                const currentY = e.touches[0].clientY;
                
                // 更新最后触摸位置用于计算滑动距离
                lastTouchX = currentX;
                lastTouchY = currentY;
            }
        }, { passive: false });

        // 触摸结束
        overlay.addEventListener('touchend', (e) => {
            if (e.touches.length === 0) {
                if (!isDragging && imageViewerScale <= 1) {
                    // 单指滑动切换图片（没有拖动且没有放大）
                    const deltaX = touchStartX - lastTouchX;
                    const threshold = 50;

                    if (Math.abs(deltaX) > threshold) {
                        if (deltaX > 0 && imageViewerCurrentIndex < images.length - 1) {
                            nextImage();
                        } else if (deltaX < 0 && imageViewerCurrentIndex > 0) {
                            prevImage();
                        }
                    }
                }

                // 重置位置
                touchStartX = touchStartY = 0;
                isDragging = false;
            }
        }, { passive: true });

        // 更新显示
        function updateImageTransform() {
            const currentSlide = slides[imageViewerCurrentIndex];
            if (currentSlide) {
                const img = currentSlide.querySelector('.image-viewer-image');
                if (imageViewerScale > 1) {
                    img.style.transform = `scale(${imageViewerScale}) translate(${imageViewerTranslateX / imageViewerScale}px, ${imageViewerTranslateY / imageViewerScale}px)`;
                } else {
                    img.style.transform = 'scale(1)';
                    imageViewerTranslateX = 0;
                    imageViewerTranslateY = 0;
                }
            }
        }

        function updateNavigation() {
            if (prevBtn) {
                prevBtn.disabled = imageViewerCurrentIndex === 0;
            }
            if (nextBtn) {
                nextBtn.disabled = imageViewerCurrentIndex === images.length - 1;
            }
            if (indicator) {
                indicator.textContent = (imageViewerCurrentIndex + 1) + '/' + images.length;
            }
            // 更新滑动位置
            swiper.style.transform = `translateX(${-imageViewerCurrentIndex * 100}%)`;
        }

        // 暴露给全局
        window.closeImageViewer = closeImageViewer;
        window.prevImage = function() {
            if (imageViewerCurrentIndex > 0) {
                imageViewerCurrentIndex--;
                imageViewerScale = 1;
                imageViewerTranslateX = 0;
                imageViewerTranslateY = 0;
                isZoomed = false;
                updateNavigation();
            }
        };
        window.nextImage = function() {
            if (imageViewerCurrentIndex < images.length - 1) {
                imageViewerCurrentIndex++;
                imageViewerScale = 1;
                imageViewerTranslateX = 0;
                imageViewerTranslateY = 0;
                isZoomed = false;
                updateNavigation();
            }
        };
        window.zoomIn = function() {
            imageViewerScale = Math.min(5, imageViewerScale + 0.5);
            isZoomed = imageViewerScale > 1;
            updateImageTransform();
        };
        window.zoomOut = function() {
            imageViewerScale = Math.max(1, imageViewerScale - 0.5);
            if (imageViewerScale <= 1) {
                imageViewerTranslateX = 0;
                imageViewerTranslateY = 0;
                isZoomed = false;
            }
            updateImageTransform();
        };
    }

    // 计算两点距离
    function getDistance(touch1, touch2) {
        const dx = touch2.clientX - touch1.clientX;
        const dy = touch2.clientY - touch1.clientY;
        return Math.sqrt(dx * dx + dy * dy);
    }

    // 关闭图片查看器
    function closeImageViewer() {
        const overlay = document.querySelector('.image-viewer-overlay');
        if (overlay) {
            overlay.classList.remove('show');
            setTimeout(() => {
                overlay.remove();
                document.body.style.overflow = '';
            }, 300);
        }
        document.removeEventListener('keydown', handleViewerKeydown);

        // 清理全局函数
        delete window.closeImageViewer;
        delete window.prevImage;
        delete window.nextImage;
        delete window.zoomIn;
        delete window.zoomOut;
    }

    // 键盘事件
    function handleViewerKeydown(e) {
        if (e.key === 'Escape') {
            closeImageViewer();
        } else if (e.key === 'ArrowLeft') {
            window.prevImage && window.prevImage();
        } else if (e.key === 'ArrowRight') {
            window.nextImage && window.nextImage();
        } else if (e.key === '+' || e.key === '=') {
            window.zoomIn && window.zoomIn();
        } else if (e.key === '-' || e.key === '_') {
            window.zoomOut && window.zoomOut();
        }
    }

    // 为动态图片添加点击事件
    document.addEventListener('DOMContentLoaded', function() {
        // 使用事件委托处理图片点击
        document.addEventListener('click', function(e) {
            const img = e.target.closest('.moment-img');
            if (img) {
                e.preventDefault();
                e.stopPropagation();

                const grid = img.closest('.moment-image-grid');
                if (!grid) return;

                const allImgs = grid.querySelectorAll('.moment-img');
                const images = Array.from(allImgs).map(function(i) {
                    return i.src || i.dataset.src || i.getAttribute('data-src') || '';
                }).filter(function(src) { return src; });

                const index = Array.from(allImgs).indexOf(img);
                openImageViewer(images, index >= 0 ? index : 0);
            }
        });
    });

    // 暴露打开函数
    window.openImageViewer = openImageViewer;
})();