/**
 * HuSNS - 媒体查看器模块
 * 统一处理图片和视频的查看功能
 */

var HuSNS = window.HuSNS || {};

/**
 * 生成视频缩略图
 */
HuSNS.generateVideoThumbnails = function() {
    var videoThumbnails = document.querySelectorAll('.moment-video-thumbnail');
    videoThumbnails.forEach(function(container) {
        var videoUrl = container.getAttribute('data-video');
        var posterImg = container.querySelector('.moment-video-poster');
        
        if (!videoUrl || !posterImg) return;
        
        var video = document.createElement('video');
        video.src = videoUrl;
        video.crossOrigin = 'anonymous';
        video.preload = 'metadata';
        
        video.addEventListener('loadedmetadata', function() {
            video.currentTime = 0.5;
        });
        
        video.addEventListener('seeked', function() {
            var canvas = document.createElement('canvas');
            canvas.width = video.videoWidth || 320;
            canvas.height = video.videoHeight || 180;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            
            posterImg.src = canvas.toDataURL('image/png');
            posterImg.style.background = 'transparent';
        });
        
        video.addEventListener('error', function() {
            posterImg.src = '';
            posterImg.style.background = '#1a1a1a';
        });
    });
};

// 查看器状态
HuSNS.MediaViewer = {
    currentIndex: 0,
    items: [],
    scale: 1,
    translateX: 0,
    translateY: 0,
    isDragging: false,
    isZoomed: false,
    touchStartX: 0,
    touchStartY: 0,
    lastTouchX: 0,
    lastTouchY: 0,
    initialDistance: 0,
    initialScale: 1,
    lastClickTime: 0,
    overlay: null
};

/**
 * 打开媒体查看器
 * @param {Array} items - 媒体项数组，每项包含 type (image/video), src, title 等
 * @param {number} startIndex - 开始索引
 */
HuSNS.openMediaViewer = function(items, startIndex = 0) {
    const viewer = HuSNS.MediaViewer;
    viewer.items = items;
    viewer.currentIndex = Math.max(0, Math.min(startIndex, items.length - 1));
    viewer.scale = 1;
    viewer.translateX = 0;
    viewer.translateY = 0;
    viewer.isDragging = false;
    viewer.isZoomed = false;

    // 创建查看器
    const overlay = document.createElement('div');
    overlay.className = 'media-viewer-overlay';
    overlay.innerHTML = getViewerHTML(items, viewer.currentIndex);
    viewer.overlay = overlay;

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

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

    // 绑定事件
    bindViewerEvents(overlay, items);
};

/**
 * 生成查看器HTML
 */
function getViewerHTML(items, startIndex) {
    const hasMultiple = items.length > 1;
    let slidesHtml = items.map((item, i) => {
        if (item.type === 'video') {
            return `
                <div class="media-viewer-slide" data-type="video">
                    <div class="video-container">
                        <video class="media-viewer-video" src="${item.src}" poster="${item.poster || ''}" playsinline controls>
                            <source src="${item.src}" type="video/mp4">
                        </video>
                        <div class="video-overlay">
                            <div class="play-icon" id="playIcon_${i}">▶</div>
                        </div>
                        <div class="video-duration">${formatDuration(item.duration)}</div>
                    </div>
                </div>
            `;
        } else {
            return `
                <div class="media-viewer-slide" data-type="image">
                    <img class="media-viewer-image" 
                         src="${item.src}" 
                         alt="${item.title || ''}" 
                         data-index="${i}"
                         draggable="false" />
                </div>
            `;
        }
    }).join('');

    return `
        <div class="media-viewer-container">
            <button class="media-viewer-close">
                <svg viewBox="0 0 24 24" fill="#333"><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="media-viewer-swiper" style="transform: translateX(${-startIndex * 100}%)">
                ${slidesHtml}
            </div>
            
            ${hasMultiple ? `
            <button class="media-viewer-nav media-viewer-prev">
                <svg viewBox="0 0 24 24" fill="white"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>
            </button>
            <button class="media-viewer-nav media-viewer-next">
                <svg viewBox="0 0 24 24" fill="white"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>
            </button>
            <div class="media-viewer-indicator">${startIndex + 1}/${items.length}</div>
            ` : ''}
            
            <div class="media-viewer-actions">
                <button class="action-btn" title="下载">
                    <svg viewBox="0 0 24 24" fill="white"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg>
                </button>
                <button class="action-btn" title="分享">
                    <svg viewBox="0 0 24 24" fill="white"><path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.39 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.39 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/></svg>
                </button>
            </div>
            
            <div class="media-viewer-zoom-controls">
                <button class="zoom-btn">
                    <svg viewBox="0 0 24 24" fill="white"><path d="M19 13H5v-2h14v2z"/></svg>
                </button>
                <button class="zoom-btn">
                    <svg viewBox="0 0 24 24" fill="white"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>
                </button>
            </div>
            
            <div class="media-viewer-loading" id="loadingIndicator" style="display: none;">
                <div class="loading-spinner"></div>
            </div>
        </div>
    `;
}

/**
 * 绑定查看器事件
 */
function bindViewerEvents(overlay, items) {
    const viewer = HuSNS.MediaViewer;
    const swiper = overlay.querySelector('.media-viewer-swiper');
    const slides = overlay.querySelectorAll('.media-viewer-slide');
    const indicator = overlay.querySelector('.media-viewer-indicator');
    const prevBtn = overlay.querySelector('.media-viewer-prev');
    const nextBtn = overlay.querySelector('.media-viewer-next');
    const zoomInBtn = overlay.querySelector('.zoom-btn:last-child');
    const zoomOutBtn = overlay.querySelector('.zoom-btn:first-child');
    const downloadBtn = overlay.querySelector('.action-btn:first-child');
    const shareBtn = overlay.querySelector('.action-btn:nth-child(2)');

    // 点击关闭按钮
    const closeBtn = overlay.querySelector('.media-viewer-close');
    closeBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        HuSNS.closeMediaViewer();
    });

    // 导航按钮
    if (prevBtn) {
        prevBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            viewer.prev();
        });
    }
    if (nextBtn) {
        nextBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            viewer.next();
        });
    }

    // 缩放按钮
    if (zoomInBtn) {
        zoomInBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            viewer.zoomIn();
        });
    }
    if (zoomOutBtn) {
        zoomOutBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            viewer.zoomOut();
        });
    }

    // 下载和分享按钮
    if (downloadBtn) {
        downloadBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            viewer.download();
        });
    }
    if (shareBtn) {
        shareBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            viewer.share();
        });
    }

    // 视频播放按钮
    const videoOverlay = overlay.querySelector('.video-overlay');
    if (videoOverlay) {
        videoOverlay.addEventListener('click', function(e) {
            e.stopPropagation();
            viewer.togglePlay();
        });
    }

    // 统一处理点击事件（避免多次触发）
    let clickTimeout = null;
    overlay.addEventListener('click', function(e) {
        // 如果有未完成的timeout，说明刚处理完一次点击
        if (clickTimeout) {
            return;
        }

        const img = e.target.closest('.media-viewer-image');
        const isBackground = e.target === overlay || e.target === overlay.querySelector('.media-viewer-container');

        // 点击背景关闭
        if (isBackground) {
            clickTimeout = setTimeout(() => {
                clickTimeout = null;
            }, 100);
            HuSNS.closeMediaViewer();
            return;
        }

        // 点击图片
        if (img) {
            const now = Date.now();
            const isDoubleClick = (now - viewer.lastClickTime) < 300;
            viewer.lastClickTime = now;

            if (isDoubleClick && !viewer.isDragging) {
                // 双击缩放
                clickTimeout = setTimeout(() => {
                    clickTimeout = null;
                }, 100);

                if (viewer.scale > 1) {
                    viewer.scale = 1;
                    viewer.translateX = 0;
                    viewer.translateY = 0;
                    viewer.isZoomed = false;
                } else {
                    viewer.scale = 2;
                    viewer.isZoomed = true;
                }
                updateImageTransform();
            } else if (!viewer.isDragging && !isDoubleClick) {
                // 单击关闭（延迟处理以区分双击）
                clickTimeout = setTimeout(() => {
                    clickTimeout = null;
                    if (!viewer.isDragging) {
                        HuSNS.closeMediaViewer();
                    }
                }, 200);
            }
        }
    });

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

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

    // 触摸移动
    overlay.addEventListener('touchmove', (e) => {
        const currentItem = items[viewer.currentIndex];
        
        if (e.touches.length === 2) {
            // 双指缩放（仅图片）
            if (currentItem.type === 'image') {
                e.preventDefault();
                const distance = getDistance(e.touches[0], e.touches[1]);
                const delta = distance / viewer.initialDistance;
                viewer.scale = Math.max(1, Math.min(5, viewer.initialScale * delta));
                viewer.isZoomed = viewer.scale > 1;
                updateImageTransform();
            }
        } else if (e.touches.length === 1 && viewer.scale > 1 && currentItem.type === 'image') {
            // 单指拖动（只有放大后且是图片才能拖动）
            e.preventDefault();
            viewer.isDragging = true;
            
            const currentX = e.touches[0].clientX;
            const currentY = e.touches[0].clientY;
            
            const deltaX = currentX - viewer.lastTouchX;
            const deltaY = currentY - viewer.lastTouchY;
            
            viewer.translateX += deltaX;
            viewer.translateY += deltaY;
            
            // 限制拖动范围
            const img = slides[viewer.currentIndex].querySelector('.media-viewer-image');
            if (img) {
                const imgRect = img.getBoundingClientRect();
                const maxTranslateX = Math.max(0, (imgRect.width * viewer.scale - window.innerWidth) / 2);
                const maxTranslateY = Math.max(0, (imgRect.height * viewer.scale - window.innerHeight) / 2);
                
                viewer.translateX = Math.max(-maxTranslateX, Math.min(maxTranslateX, viewer.translateX));
                viewer.translateY = Math.max(-maxTranslateY, Math.min(maxTranslateY, viewer.translateY));
            }
            
            updateImageTransform();
            
            viewer.lastTouchX = currentX;
            viewer.lastTouchY = currentY;
        } else if (e.touches.length === 1 && viewer.scale <= 1) {
            // 单指滑动切换媒体（未放大时）
            viewer.lastTouchX = e.touches[0].clientX;
            viewer.lastTouchY = e.touches[0].clientY;
        }
    }, { passive: false });

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

                // 只在水平滑动距离大于垂直滑动距离时切换
                if (Math.abs(deltaX) > threshold && Math.abs(deltaX) > Math.abs(deltaY)) {
                    if (deltaX > 0 && viewer.currentIndex < items.length - 1) {
                        viewer.next();
                    } else if (deltaX < 0 && viewer.currentIndex > 0) {
                        viewer.prev();
                    }
                }
            }

            viewer.touchStartX = viewer.touchStartY = 0;
            viewer.isDragging = false;
        }
    }, { passive: true });

    // 更新显示
    function updateImageTransform() {
        const currentSlide = slides[viewer.currentIndex];
        if (!currentSlide) return;
        
        const img = currentSlide.querySelector('.media-viewer-image');
        if (img) {
            if (viewer.scale > 1) {
                img.style.transform = `scale(${viewer.scale}) translate(${viewer.translateX / viewer.scale}px, ${viewer.translateY / viewer.scale}px)`;
            } else {
                img.style.transform = 'scale(1)';
                viewer.translateX = 0;
                viewer.translateY = 0;
            }
        }
    }

    function updateNavigation() {
        if (prevBtn) {
            prevBtn.disabled = viewer.currentIndex === 0;
            prevBtn.style.opacity = viewer.currentIndex === 0 ? '0.3' : '1';
        }
        if (nextBtn) {
            nextBtn.disabled = viewer.currentIndex === items.length - 1;
            nextBtn.style.opacity = viewer.currentIndex === items.length - 1 ? '0.3' : '1';
        }
        if (indicator) {
            indicator.textContent = (viewer.currentIndex + 1) + '/' + items.length;
        }
        // 更新滑动位置（带动画）
        if (swiper) {
            swiper.style.transition = 'transform 0.3s ease-out';
            swiper.style.transform = `translateX(${-viewer.currentIndex * 100}%)`;
        }
    }

    // 暴露方法到 viewer 对象
    viewer.prev = function() {
        if (viewer.currentIndex > 0) {
            pauseCurrentVideo();
            viewer.currentIndex--;
            viewer.scale = 1;
            viewer.translateX = 0;
            viewer.translateY = 0;
            viewer.isZoomed = false;
            updateNavigation();
            playCurrentVideo();
        }
    };

    viewer.next = function() {
        if (viewer.currentIndex < items.length - 1) {
            pauseCurrentVideo();
            viewer.currentIndex++;
            viewer.scale = 1;
            viewer.translateX = 0;
            viewer.translateY = 0;
            viewer.isZoomed = false;
            updateNavigation();
            playCurrentVideo();
        }
    };

    viewer.zoomIn = function() {
        const currentItem = items[viewer.currentIndex];
        if (currentItem.type !== 'image') return;
        
        viewer.scale = Math.min(5, viewer.scale + 0.5);
        viewer.isZoomed = viewer.scale > 1;
        updateImageTransform();
    };

    viewer.zoomOut = function() {
        const currentItem = items[viewer.currentIndex];
        if (currentItem.type !== 'image') return;
        
        viewer.scale = Math.max(1, viewer.scale - 0.5);
        if (viewer.scale <= 1) {
            viewer.translateX = 0;
            viewer.translateY = 0;
            viewer.isZoomed = false;
        }
        updateImageTransform();
    };

    viewer.togglePlay = function() {
        const currentSlide = slides[viewer.currentIndex];
        const video = currentSlide?.querySelector('.media-viewer-video');
        const playIcon = currentSlide?.querySelector('.play-icon');
        
        if (video) {
            if (video.paused) {
                video.play();
                playIcon?.classList.add('hidden');
            } else {
                video.pause();
                playIcon?.classList.remove('hidden');
            }
        }
    };

    viewer.download = function() {
        const currentItem = items[viewer.currentIndex];
        const link = document.createElement('a');
        link.href = currentItem.src;
        link.download = currentItem.title || 'media';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    viewer.share = function() {
        const currentItem = items[viewer.currentIndex];
        
        if (navigator.share) {
            navigator.share({
                title: currentItem.title || '分享内容',
                text: currentItem.title || '',
                url: currentItem.src
            }).catch(() => {});
        } else {
            // 复制链接到剪贴板
            navigator.clipboard.writeText(currentItem.src).then(() => {
                showToast('链接已复制到剪贴板');
            }).catch(() => {
                showToast('分享功能暂不可用');
            });
        }
    };

    // 暂停当前视频
    function pauseCurrentVideo() {
        const currentSlide = slides[viewer.currentIndex];
        const video = currentSlide?.querySelector('.media-viewer-video');
        if (video) {
            video.pause();
            const playIcon = currentSlide.querySelector('.play-icon');
            playIcon?.classList.remove('hidden');
        }
    }

    // 播放当前视频
    function playCurrentVideo() {
        setTimeout(() => {
            const currentSlide = slides[viewer.currentIndex];
            const video = currentSlide?.querySelector('.media-viewer-video');
            if (video && currentSlide.dataset.type === 'video') {
                video.play().catch(() => {});
            }
        }, 300);
    }

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

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

/**
 * 格式化时长
 */
function formatDuration(seconds) {
    if (!seconds) return '00:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

/**
 * 关闭媒体查看器
 */
HuSNS.closeMediaViewer = function() {
    const viewer = HuSNS.MediaViewer;
    if (!viewer.overlay) return;

    // 暂停所有视频
    const videos = viewer.overlay.querySelectorAll('.media-viewer-video');
    videos.forEach(v => v.pause());

    viewer.overlay.classList.remove('show');
    setTimeout(() => {
        if (viewer.overlay) {
            viewer.overlay.remove();
            viewer.overlay = null;
            document.body.style.overflow = '';
        }
    }, 300);

    document.removeEventListener('keydown', handleViewerKeydown);
}

/**
 * 键盘事件处理
 */
function handleViewerKeydown(e) {
    const viewer = HuSNS.MediaViewer;
    
    if (e.key === 'Escape') {
        HuSNS.closeMediaViewer();
    } else if (e.key === 'ArrowLeft') {
        viewer.prev && viewer.prev();
    } else if (e.key === 'ArrowRight') {
        viewer.next && viewer.next();
    } else if (e.key === '+' || e.key === '=') {
        viewer.zoomIn && viewer.zoomIn();
    } else if (e.key === '-' || e.key === '_') {
        viewer.zoomOut && viewer.zoomOut();
    }
}

/**
 * Toast提示
 */
function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'media-viewer-toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 2000);
}

/**
 * 从元素打开媒体查看器（兼容 detail.php）
 * @param {HTMLElement} element - 包含 data-images 和 data-index 属性的图片元素
 */
HuSNS.openMediaViewerFromElement = function(element) {
    if (!element) return;
    
    const imagesJson = element.getAttribute('data-images');
    const index = parseInt(element.getAttribute('data-index')) || 0;
    
    if (!imagesJson) return;
    
    try {
        const images = JSON.parse(imagesJson);
        const items = images.map(function(src) {
            return {
                type: 'image',
                src: src,
                title: ''
            };
        });
        
        HuSNS.openMediaViewer(items, index);
    } catch (e) {
        console.error('Failed to parse images:', e);
    }
};

/**
 * 为动态列表的媒体添加点击事件
 */
document.addEventListener('DOMContentLoaded', function() {
    // 生成视频缩略图
    HuSNS.generateVideoThumbnails();

    // 使用事件委托处理图片点击
    document.addEventListener('click', function(e) {
        // 处理图片点击（跳过已有onclick的图片和图片查看器中的元素）
        const img = e.target.closest('.moment-img, .detail-image');
        if (img && !e.target.closest('.media-viewer-overlay') && !img.hasAttribute('onclick')) {
            e.preventDefault();
            e.stopPropagation();

            // 详情页图片使用 data-images 属性
            if (img.classList.contains('detail-image') && img.hasAttribute('data-images')) {
                HuSNS.openMediaViewerFromElement(img);
                return;
            }

            // 列表页图片使用 grid 结构
            const grid = img.closest('.moment-image-grid');
            if (!grid) return;

            const allImgs = grid.querySelectorAll('.moment-img');
            const items = Array.from(allImgs).map(function(i) {
                return {
                    type: 'image',
                    src: i.src || i.dataset.src || i.getAttribute('data-src') || '',
                    title: i.alt || ''
                };
            }).filter(function(item) { return item.src; });

            const index = Array.from(allImgs).indexOf(img);
            HuSNS.openMediaViewer(items, index >= 0 ? index : 0);
        }

        // 处理视频点击（跳过已有onclick的视频缩略图）
        const videoThumbnail = e.target.closest('.moment-video-thumbnail');
        if (videoThumbnail && !e.target.closest('.media-viewer-overlay') && !videoThumbnail.hasAttribute('onclick')) {
            e.preventDefault();
            e.stopPropagation();

            const videoUrl = videoThumbnail.getAttribute('data-video');
            const posterUrl = videoThumbnail.querySelector('.moment-video-poster')?.src;
            const duration = parseFloat(videoThumbnail.getAttribute('data-duration') || '0');
            
            if (videoUrl) {
                HuSNS.openMediaViewer([{
                    type: 'video',
                    src: videoUrl,
                    poster: posterUrl,
                    duration: duration,
                    title: ''
                }], 0);
            }
        }
    });
});

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